summaryrefslogtreecommitdiff
path: root/src/mscorlib/src
diff options
context:
space:
mode:
Diffstat (limited to 'src/mscorlib/src')
-rw-r--r--src/mscorlib/src/CleanupToDoList.cs27
-rw-r--r--src/mscorlib/src/Internal/Runtime/Augments/RuntimeThread.cs7
-rw-r--r--src/mscorlib/src/Microsoft/Win32/Registry.cs21
-rw-r--r--src/mscorlib/src/Microsoft/Win32/RegistryKey.cs758
-rw-r--r--src/mscorlib/src/Microsoft/Win32/RegistryOptions.cs25
-rw-r--r--src/mscorlib/src/Microsoft/Win32/RegistryValueKind.cs4
-rw-r--r--src/mscorlib/src/Microsoft/Win32/RegistryView.cs2
-rw-r--r--src/mscorlib/src/Microsoft/Win32/SafeHandles/SafeFileMappingHandle.cs39
-rw-r--r--src/mscorlib/src/Microsoft/Win32/SafeHandles/SafeFindHandle.cs1
-rw-r--r--src/mscorlib/src/Microsoft/Win32/SafeHandles/SafeLibraryHandle.cs1
-rw-r--r--src/mscorlib/src/Microsoft/Win32/SafeHandles/SafeLocalAllocHandle.cs29
-rw-r--r--src/mscorlib/src/Microsoft/Win32/SafeHandles/SafeRegistryHandle.cs4
-rw-r--r--src/mscorlib/src/Microsoft/Win32/SafeHandles/SafeViewOfFileHandle.cs46
-rw-r--r--src/mscorlib/src/Microsoft/Win32/SafeHandles/SafeWaitHandle.cs2
-rw-r--r--src/mscorlib/src/Microsoft/Win32/SafeHandles/Win32SafeHandles.cs5
-rw-r--r--src/mscorlib/src/Microsoft/Win32/UnsafeNativeMethods.cs15
-rw-r--r--src/mscorlib/src/Microsoft/Win32/Win32Native.cs1389
-rw-r--r--src/mscorlib/src/System.Private.CoreLib.txt67
-rw-r--r--src/mscorlib/src/System/AccessViolationException.cs39
-rw-r--r--src/mscorlib/src/System/Action.cs6
-rw-r--r--src/mscorlib/src/System/Activator.cs192
-rw-r--r--src/mscorlib/src/System/AppContext/AppContext.cs41
-rw-r--r--src/mscorlib/src/System/AppDomain.cs1307
-rw-r--r--src/mscorlib/src/System/AppDomainAttributes.cs21
-rw-r--r--src/mscorlib/src/System/AppDomainManager.cs3
-rw-r--r--src/mscorlib/src/System/AppDomainSetup.cs383
-rw-r--r--src/mscorlib/src/System/AppDomainUnloadedException.cs13
-rw-r--r--src/mscorlib/src/System/ApplicationException.cs40
-rw-r--r--src/mscorlib/src/System/ApplicationId.cs141
-rw-r--r--src/mscorlib/src/System/ArgIterator.cs69
-rw-r--r--src/mscorlib/src/System/ArgumentException.cs105
-rw-r--r--src/mscorlib/src/System/ArgumentNullException.cs47
-rw-r--r--src/mscorlib/src/System/ArgumentOutOfRangeException.cs2
-rw-r--r--src/mscorlib/src/System/ArithmeticException.cs39
-rw-r--r--src/mscorlib/src/System/Array.cs93
-rw-r--r--src/mscorlib/src/System/ArraySegment.cs14
-rw-r--r--src/mscorlib/src/System/ArrayTypeMismatchException.cs41
-rw-r--r--src/mscorlib/src/System/AsyncCallback.cs6
-rw-r--r--src/mscorlib/src/System/Attribute.cs6
-rw-r--r--src/mscorlib/src/System/AttributeTargets.cs48
-rw-r--r--src/mscorlib/src/System/AttributeUsageAttribute.cs1
-rw-r--r--src/mscorlib/src/System/BCLDebug.cs67
-rw-r--r--src/mscorlib/src/System/BadImageFormatException.cs2
-rw-r--r--src/mscorlib/src/System/BitConverter.cs6
-rw-r--r--src/mscorlib/src/System/Boolean.cs1
-rw-r--r--src/mscorlib/src/System/Buffer.cs7
-rw-r--r--src/mscorlib/src/System/ByReference.cs12
-rw-r--r--src/mscorlib/src/System/Byte.cs1
-rw-r--r--src/mscorlib/src/System/CLRConfig.cs20
-rw-r--r--src/mscorlib/src/System/CLSCompliantAttribute.cs22
-rw-r--r--src/mscorlib/src/System/CannotUnloadAppDomainException.cs49
-rw-r--r--src/mscorlib/src/System/CfgParser.cs564
-rw-r--r--src/mscorlib/src/System/Char.cs1
-rw-r--r--src/mscorlib/src/System/CharEnumerator.cs84
-rw-r--r--src/mscorlib/src/System/Collections/ArrayList.cs2085
-rw-r--r--src/mscorlib/src/System/Collections/CollectionBase.cs20
-rw-r--r--src/mscorlib/src/System/Collections/Comparer.cs4
-rw-r--r--src/mscorlib/src/System/Collections/Concurrent/ConcurrentDictionary.cs375
-rw-r--r--src/mscorlib/src/System/Collections/Concurrent/ConcurrentQueue.cs1486
-rw-r--r--src/mscorlib/src/System/Collections/Concurrent/ConcurrentStack.cs323
-rw-r--r--src/mscorlib/src/System/Collections/Concurrent/IProducerConsumerCollection.cs49
-rw-r--r--src/mscorlib/src/System/Collections/Concurrent/OrderablePartitioner.cs280
-rw-r--r--src/mscorlib/src/System/Collections/Concurrent/Partitioner.cs101
-rw-r--r--src/mscorlib/src/System/Collections/Concurrent/PartitionerStatic.cs1715
-rw-r--r--src/mscorlib/src/System/Collections/DictionaryEntry.cs4
-rw-r--r--src/mscorlib/src/System/Collections/Generic/Comparer.cs3
-rw-r--r--src/mscorlib/src/System/Collections/Generic/DebugView.cs1
-rw-r--r--src/mscorlib/src/System/Collections/Generic/Dictionary.cs2
-rw-r--r--src/mscorlib/src/System/Collections/Generic/EqualityComparer.cs153
-rw-r--r--src/mscorlib/src/System/Collections/Generic/KeyNotFoundException.cs1
-rw-r--r--src/mscorlib/src/System/Collections/Generic/KeyValuePair.cs3
-rw-r--r--src/mscorlib/src/System/Collections/Generic/List.cs12
-rw-r--r--src/mscorlib/src/System/Collections/Hashtable.cs323
-rw-r--r--src/mscorlib/src/System/Collections/ICollection.cs1
-rw-r--r--src/mscorlib/src/System/Collections/IComparer.cs1
-rw-r--r--src/mscorlib/src/System/Collections/IDictionary.cs1
-rw-r--r--src/mscorlib/src/System/Collections/IDictionaryEnumerator.cs1
-rw-r--r--src/mscorlib/src/System/Collections/IEnumerable.cs1
-rw-r--r--src/mscorlib/src/System/Collections/IEnumerator.cs1
-rw-r--r--src/mscorlib/src/System/Collections/IEqualityComparer.cs1
-rw-r--r--src/mscorlib/src/System/Collections/IHashCodeProvider.cs3
-rw-r--r--src/mscorlib/src/System/Collections/IList.cs1
-rw-r--r--src/mscorlib/src/System/Collections/KeyValuePairs.cs40
-rw-r--r--src/mscorlib/src/System/Collections/ListDictionaryInternal.cs14
-rw-r--r--src/mscorlib/src/System/Collections/ObjectModel/Collection.cs1
-rw-r--r--src/mscorlib/src/System/Collections/ObjectModel/KeyedCollection.cs1
-rw-r--r--src/mscorlib/src/System/Collections/ObjectModel/ReadOnlyCollection.cs1
-rw-r--r--src/mscorlib/src/System/Collections/SortedList.cs1008
-rw-r--r--src/mscorlib/src/System/Collections/Stack.cs379
-rw-r--r--src/mscorlib/src/System/CompatibilitySwitches.cs31
-rw-r--r--src/mscorlib/src/System/ComponentModel/EditorBrowsableAttribute.cs48
-rw-r--r--src/mscorlib/src/System/Configuration/Assemblies/AssemblyHash.cs74
-rw-r--r--src/mscorlib/src/System/Configuration/Assemblies/AssemblyHashAlgorithm.cs4
-rw-r--r--src/mscorlib/src/System/Configuration/Assemblies/AssemblyVersionCompatibility.cs1
-rw-r--r--src/mscorlib/src/System/ContextMarshalException.cs45
-rw-r--r--src/mscorlib/src/System/Convert.cs9
-rw-r--r--src/mscorlib/src/System/DBNull.cs2
-rw-r--r--src/mscorlib/src/System/DataMisalignedException.cs34
-rw-r--r--src/mscorlib/src/System/DateTime.cs15
-rw-r--r--src/mscorlib/src/System/DateTimeKind.cs6
-rw-r--r--src/mscorlib/src/System/DateTimeOffset.cs1
-rw-r--r--src/mscorlib/src/System/DayOfWeek.cs7
-rw-r--r--src/mscorlib/src/System/Decimal.cs14
-rw-r--r--src/mscorlib/src/System/Delegate.cs1
-rw-r--r--src/mscorlib/src/System/DelegateSerializationHolder.cs9
-rw-r--r--src/mscorlib/src/System/Diagnostics/Assert.cs9
-rw-r--r--src/mscorlib/src/System/Diagnostics/ConditionalAttribute.cs1
-rw-r--r--src/mscorlib/src/System/Diagnostics/Contracts/Contracts.cs128
-rw-r--r--src/mscorlib/src/System/Diagnostics/Contracts/ContractsBCL.cs16
-rw-r--r--src/mscorlib/src/System/Diagnostics/Debugger.cs52
-rw-r--r--src/mscorlib/src/System/Diagnostics/DebuggerAttributes.cs116
-rw-r--r--src/mscorlib/src/System/Diagnostics/Eventing/EventDescriptor.cs2
-rw-r--r--src/mscorlib/src/System/Diagnostics/Eventing/EventProvider.cs21
-rw-r--r--src/mscorlib/src/System/Diagnostics/Eventing/EventSource.cs23
-rw-r--r--src/mscorlib/src/System/Diagnostics/Eventing/FrameworkEventSource.cs70
-rw-r--r--src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/TraceLoggingTypeInfo.cs2
-rw-r--r--src/mscorlib/src/System/Diagnostics/Eventing/XplatEventLogger.cs2
-rw-r--r--src/mscorlib/src/System/Diagnostics/LogSwitch.cs13
-rw-r--r--src/mscorlib/src/System/Diagnostics/Stackframe.cs37
-rw-r--r--src/mscorlib/src/System/Diagnostics/Stacktrace.cs14
-rw-r--r--src/mscorlib/src/System/Diagnostics/SymbolStore/ISymBinder.cs42
-rw-r--r--src/mscorlib/src/System/Diagnostics/SymbolStore/ISymDocument.cs48
-rw-r--r--src/mscorlib/src/System/Diagnostics/SymbolStore/ISymDocumentWriter.cs1
-rw-r--r--src/mscorlib/src/System/Diagnostics/SymbolStore/ISymMethod.cs86
-rw-r--r--src/mscorlib/src/System/Diagnostics/SymbolStore/ISymNamespace.cs30
-rw-r--r--src/mscorlib/src/System/Diagnostics/SymbolStore/ISymReader.cs68
-rw-r--r--src/mscorlib/src/System/Diagnostics/SymbolStore/ISymScope.cs47
-rw-r--r--src/mscorlib/src/System/Diagnostics/SymbolStore/ISymVariable.cs41
-rw-r--r--src/mscorlib/src/System/Diagnostics/SymbolStore/ISymWriter.cs78
-rw-r--r--src/mscorlib/src/System/Diagnostics/SymbolStore/SymAddressKind.cs3
-rw-r--r--src/mscorlib/src/System/Diagnostics/SymbolStore/SymDocumentType.cs24
-rw-r--r--src/mscorlib/src/System/Diagnostics/SymbolStore/SymLanguageType.cs42
-rw-r--r--src/mscorlib/src/System/Diagnostics/SymbolStore/SymLanguageVendor.cs23
-rw-r--r--src/mscorlib/src/System/Diagnostics/SymbolStore/Token.cs13
-rw-r--r--src/mscorlib/src/System/Diagnostics/log.cs116
-rw-r--r--src/mscorlib/src/System/DivideByZeroException.cs40
-rw-r--r--src/mscorlib/src/System/DllNotFoundException.cs1
-rw-r--r--src/mscorlib/src/System/Double.cs2
-rw-r--r--src/mscorlib/src/System/DuplicateWaitObjectException.cs58
-rw-r--r--src/mscorlib/src/System/EntryPointNotFoundException.cs44
-rw-r--r--src/mscorlib/src/System/Enum.cs132
-rw-r--r--src/mscorlib/src/System/Environment.cs616
-rw-r--r--src/mscorlib/src/System/EventArgs.cs15
-rw-r--r--src/mscorlib/src/System/EventHandler.cs7
-rw-r--r--src/mscorlib/src/System/Exception.cs98
-rw-r--r--src/mscorlib/src/System/ExecutionEngineException.cs39
-rw-r--r--src/mscorlib/src/System/FieldAccessException.cs40
-rw-r--r--src/mscorlib/src/System/FlagsAttribute.cs7
-rw-r--r--src/mscorlib/src/System/FormatException.cs40
-rw-r--r--src/mscorlib/src/System/FormattableString.cs2
-rw-r--r--src/mscorlib/src/System/GC.cs18
-rw-r--r--src/mscorlib/src/System/Globalization/Calendar.cs9
-rw-r--r--src/mscorlib/src/System/Globalization/CalendarAlgorithmType.cs1
-rw-r--r--src/mscorlib/src/System/Globalization/CalendarData.cs35
-rw-r--r--src/mscorlib/src/System/Globalization/CalendarWeekRule.cs1
-rw-r--r--src/mscorlib/src/System/Globalization/ChineseLunisolarCalendar.cs4
-rw-r--r--src/mscorlib/src/System/Globalization/CompareInfo.cs6
-rw-r--r--src/mscorlib/src/System/Globalization/CultureData.cs110
-rw-r--r--src/mscorlib/src/System/Globalization/CultureInfo.cs98
-rw-r--r--src/mscorlib/src/System/Globalization/CultureNotFoundException.cs1
-rw-r--r--src/mscorlib/src/System/Globalization/CultureTypes.cs1
-rw-r--r--src/mscorlib/src/System/Globalization/DateTimeFormat.cs8
-rw-r--r--src/mscorlib/src/System/Globalization/DateTimeFormatInfo.cs24
-rw-r--r--src/mscorlib/src/System/Globalization/DateTimeStyles.cs1
-rw-r--r--src/mscorlib/src/System/Globalization/DaylightTime.cs1
-rw-r--r--src/mscorlib/src/System/Globalization/DigitShapes.cs1
-rw-r--r--src/mscorlib/src/System/Globalization/EastAsianLunisolarCalendar.cs1
-rw-r--r--src/mscorlib/src/System/Globalization/EncodingTable.cs4
-rw-r--r--src/mscorlib/src/System/Globalization/GlobalizationAssembly.cs1
-rw-r--r--src/mscorlib/src/System/Globalization/GregorianCalendar.cs5
-rw-r--r--src/mscorlib/src/System/Globalization/GregorianCalendarTypes.cs1
-rw-r--r--src/mscorlib/src/System/Globalization/HebrewCalendar.cs1
-rw-r--r--src/mscorlib/src/System/Globalization/HijriCalendar.cs5
-rw-r--r--src/mscorlib/src/System/Globalization/JapaneseCalendar.cs14
-rw-r--r--src/mscorlib/src/System/Globalization/JulianCalendar.cs5
-rw-r--r--src/mscorlib/src/System/Globalization/KoreanCalendar.cs6
-rw-r--r--src/mscorlib/src/System/Globalization/NumberFormatInfo.cs26
-rw-r--r--src/mscorlib/src/System/Globalization/NumberStyles.cs1
-rw-r--r--src/mscorlib/src/System/Globalization/RegionInfo.cs5
-rw-r--r--src/mscorlib/src/System/Globalization/SortKey.cs1
-rw-r--r--src/mscorlib/src/System/Globalization/StringInfo.cs4
-rw-r--r--src/mscorlib/src/System/Globalization/TaiwanCalendar.cs6
-rw-r--r--src/mscorlib/src/System/Globalization/TextElementEnumerator.cs1
-rw-r--r--src/mscorlib/src/System/Globalization/TextInfo.cs9
-rw-r--r--src/mscorlib/src/System/Globalization/ThaiBuddhistCalendar.cs6
-rw-r--r--src/mscorlib/src/System/Globalization/UnicodeCategory.cs1
-rw-r--r--src/mscorlib/src/System/Guid.cs9
-rw-r--r--src/mscorlib/src/System/IAppDomain.cs28
-rw-r--r--src/mscorlib/src/System/IAppDomainPauseManager.cs40
-rw-r--r--src/mscorlib/src/System/IAppDomainSetup.cs84
-rw-r--r--src/mscorlib/src/System/IAsyncResult.cs18
-rw-r--r--src/mscorlib/src/System/ICloneable.cs1
-rw-r--r--src/mscorlib/src/System/IComparable.cs8
-rw-r--r--src/mscorlib/src/System/IConvertible.cs10
-rw-r--r--src/mscorlib/src/System/ICustomFormatter.cs11
-rw-r--r--src/mscorlib/src/System/IDisposable.cs8
-rw-r--r--src/mscorlib/src/System/IEquatable.cs8
-rw-r--r--src/mscorlib/src/System/IFormatProvider.cs8
-rw-r--r--src/mscorlib/src/System/IFormattable.cs9
-rw-r--r--src/mscorlib/src/System/IO/BinaryReader.cs1
-rw-r--r--src/mscorlib/src/System/IO/BinaryWriter.cs5
-rw-r--r--src/mscorlib/src/System/IO/Directory.cs806
-rw-r--r--src/mscorlib/src/System/IO/DirectoryInfo.cs511
-rw-r--r--src/mscorlib/src/System/IO/DirectoryNotFoundException.cs1
-rw-r--r--src/mscorlib/src/System/IO/DriveNotFoundException.cs8
-rw-r--r--src/mscorlib/src/System/IO/EndOfStreamException.cs1
-rw-r--r--src/mscorlib/src/System/IO/File.cs601
-rw-r--r--src/mscorlib/src/System/IO/FileAccess.cs1
-rw-r--r--src/mscorlib/src/System/IO/FileAttributes.cs39
-rw-r--r--src/mscorlib/src/System/IO/FileInfo.cs270
-rw-r--r--src/mscorlib/src/System/IO/FileLoadException.cs2
-rw-r--r--src/mscorlib/src/System/IO/FileMode.cs1
-rw-r--r--src/mscorlib/src/System/IO/FileNotFoundException.cs2
-rw-r--r--src/mscorlib/src/System/IO/FileOptions.cs1
-rw-r--r--src/mscorlib/src/System/IO/FileShare.cs1
-rw-r--r--src/mscorlib/src/System/IO/FileSystemEnumerable.cs107
-rw-r--r--src/mscorlib/src/System/IO/FileSystemInfo.cs240
-rw-r--r--src/mscorlib/src/System/IO/IOException.cs1
-rw-r--r--src/mscorlib/src/System/IO/MemoryStream.cs5
-rw-r--r--src/mscorlib/src/System/IO/PathTooLongException.cs1
-rw-r--r--src/mscorlib/src/System/IO/PinnedBufferMemoryStream.cs4
-rw-r--r--src/mscorlib/src/System/IO/ReadLinesIterator.cs102
-rw-r--r--src/mscorlib/src/System/IO/SearchOption.cs1
-rw-r--r--src/mscorlib/src/System/IO/SeekOrigin.cs1
-rw-r--r--src/mscorlib/src/System/IO/Stream.cs28
-rw-r--r--src/mscorlib/src/System/IO/StreamReader.cs10
-rw-r--r--src/mscorlib/src/System/IO/StreamWriter.cs765
-rw-r--r--src/mscorlib/src/System/IO/TextReader.cs12
-rw-r--r--src/mscorlib/src/System/IO/TextWriter.cs886
-rw-r--r--src/mscorlib/src/System/IO/UnmanagedMemoryAccessor.cs1
-rw-r--r--src/mscorlib/src/System/IO/UnmanagedMemoryStream.cs47
-rw-r--r--src/mscorlib/src/System/IO/UnmanagedMemoryStreamWrapper.cs1
-rw-r--r--src/mscorlib/src/System/IO/__Error.cs28
-rw-r--r--src/mscorlib/src/System/IObservable.cs13
-rw-r--r--src/mscorlib/src/System/IObserver.cs14
-rw-r--r--src/mscorlib/src/System/IProgress.cs11
-rw-r--r--src/mscorlib/src/System/IndexOutOfRangeException.cs39
-rw-r--r--src/mscorlib/src/System/InsufficientExecutionStackException.cs45
-rw-r--r--src/mscorlib/src/System/Int16.cs1
-rw-r--r--src/mscorlib/src/System/Int32.cs1
-rw-r--r--src/mscorlib/src/System/Int64.cs1
-rw-r--r--src/mscorlib/src/System/IntPtr.cs17
-rw-r--r--src/mscorlib/src/System/Internal.cs8
-rw-r--r--src/mscorlib/src/System/InvalidCastException.cs49
-rw-r--r--src/mscorlib/src/System/InvalidOperationException.cs37
-rw-r--r--src/mscorlib/src/System/InvalidProgramException.cs38
-rw-r--r--src/mscorlib/src/System/InvalidTimeZoneException.cs28
-rw-r--r--src/mscorlib/src/System/Lazy.cs2
-rw-r--r--src/mscorlib/src/System/LowLevelConsole.cs36
-rw-r--r--src/mscorlib/src/System/MarshalByRefObject.cs21
-rw-r--r--src/mscorlib/src/System/Math.cs23
-rw-r--r--src/mscorlib/src/System/MathF.cs3
-rw-r--r--src/mscorlib/src/System/MemberAccessException.cs40
-rw-r--r--src/mscorlib/src/System/MethodAccessException.cs40
-rw-r--r--src/mscorlib/src/System/MidpointRounding.cs9
-rw-r--r--src/mscorlib/src/System/MissingFieldException.cs9
-rw-r--r--src/mscorlib/src/System/MissingMemberException.cs12
-rw-r--r--src/mscorlib/src/System/MissingMethodException.cs9
-rw-r--r--src/mscorlib/src/System/MulticastDelegate.cs5
-rw-r--r--src/mscorlib/src/System/MulticastNotSupportedException.cs40
-rw-r--r--src/mscorlib/src/System/NonSerializedAttribute.cs1
-rw-r--r--src/mscorlib/src/System/NotFiniteNumberException.cs62
-rw-r--r--src/mscorlib/src/System/NotImplementedException.cs32
-rw-r--r--src/mscorlib/src/System/NotSupportedException.cs36
-rw-r--r--src/mscorlib/src/System/NullReferenceException.cs41
-rw-r--r--src/mscorlib/src/System/Nullable.cs3
-rw-r--r--src/mscorlib/src/System/Number.cs4
-rw-r--r--src/mscorlib/src/System/Numerics/Hashing/HashHelpers.cs8
-rw-r--r--src/mscorlib/src/System/Object.cs3
-rw-r--r--src/mscorlib/src/System/ObjectDisposedException.cs79
-rw-r--r--src/mscorlib/src/System/ObsoleteAttribute.cs43
-rw-r--r--src/mscorlib/src/System/OperatingSystem.cs21
-rw-r--r--src/mscorlib/src/System/OperationCanceledException.cs1
-rw-r--r--src/mscorlib/src/System/OutOfMemoryException.cs1
-rw-r--r--src/mscorlib/src/System/OverflowException.cs41
-rw-r--r--src/mscorlib/src/System/ParamArrayAttribute.cs13
-rw-r--r--src/mscorlib/src/System/PlatformID.cs3
-rw-r--r--src/mscorlib/src/System/PlatformNotSupportedException.cs35
-rw-r--r--src/mscorlib/src/System/Progress.cs36
-rw-r--r--src/mscorlib/src/System/Random.cs1
-rw-r--r--src/mscorlib/src/System/RankException.cs36
-rw-r--r--src/mscorlib/src/System/ReadOnlySpan.cs293
-rw-r--r--src/mscorlib/src/System/Reflection/AmbiguousMatchException.cs1
-rw-r--r--src/mscorlib/src/System/Reflection/Assembly.cs507
-rw-r--r--src/mscorlib/src/System/Reflection/AssemblyAttributes.cs19
-rw-r--r--src/mscorlib/src/System/Reflection/AssemblyName.cs8
-rw-r--r--src/mscorlib/src/System/Reflection/AssemblyNameFlags.cs3
-rw-r--r--src/mscorlib/src/System/Reflection/AssemblyNameProxy.cs28
-rw-r--r--src/mscorlib/src/System/Reflection/Binder.cs2
-rw-r--r--src/mscorlib/src/System/Reflection/BindingFlags.cs1
-rw-r--r--src/mscorlib/src/System/Reflection/CallingConventions.cs1
-rw-r--r--src/mscorlib/src/System/Reflection/ComInterfaces.cs115
-rw-r--r--src/mscorlib/src/System/Reflection/ConstructorInfo.cs42
-rw-r--r--src/mscorlib/src/System/Reflection/CustomAttribute.cs44
-rw-r--r--src/mscorlib/src/System/Reflection/CustomAttributeFormatException.cs1
-rw-r--r--src/mscorlib/src/System/Reflection/DefaultMemberAttribute.cs1
-rw-r--r--src/mscorlib/src/System/Reflection/Emit/AssemblyBuilder.cs280
-rw-r--r--src/mscorlib/src/System/Reflection/Emit/AssemblyBuilderAccess.cs3
-rw-r--r--src/mscorlib/src/System/Reflection/Emit/AssemblyBuilderData.cs346
-rw-r--r--src/mscorlib/src/System/Reflection/Emit/ComInterfaces.cs143
-rw-r--r--src/mscorlib/src/System/Reflection/Emit/ConstructorBuilder.cs34
-rw-r--r--src/mscorlib/src/System/Reflection/Emit/CustomAttributeBuilder.cs18
-rw-r--r--src/mscorlib/src/System/Reflection/Emit/DynamicILGenerator.cs243
-rw-r--r--src/mscorlib/src/System/Reflection/Emit/DynamicMethod.cs36
-rw-r--r--src/mscorlib/src/System/Reflection/Emit/EnumBuilder.cs13
-rw-r--r--src/mscorlib/src/System/Reflection/Emit/EventBuilder.cs7
-rw-r--r--src/mscorlib/src/System/Reflection/Emit/EventToken.cs2
-rw-r--r--src/mscorlib/src/System/Reflection/Emit/FieldBuilder.cs23
-rw-r--r--src/mscorlib/src/System/Reflection/Emit/FieldToken.cs2
-rw-r--r--src/mscorlib/src/System/Reflection/Emit/FlowControl.cs1
-rw-r--r--src/mscorlib/src/System/Reflection/Emit/GenericTypeParameterBuilder.cs5
-rw-r--r--src/mscorlib/src/System/Reflection/Emit/ILGenerator.cs67
-rw-r--r--src/mscorlib/src/System/Reflection/Emit/ISymWrapperCore.cs143
-rw-r--r--src/mscorlib/src/System/Reflection/Emit/Label.cs2
-rw-r--r--src/mscorlib/src/System/Reflection/Emit/LocalBuilder.cs6
-rw-r--r--src/mscorlib/src/System/Reflection/Emit/MethodBuilder.cs319
-rw-r--r--src/mscorlib/src/System/Reflection/Emit/MethodBuilderInstantiation.cs1
-rw-r--r--src/mscorlib/src/System/Reflection/Emit/MethodToken.cs2
-rw-r--r--src/mscorlib/src/System/Reflection/Emit/ModuleBuilder.cs263
-rw-r--r--src/mscorlib/src/System/Reflection/Emit/ModuleBuilderData.cs32
-rw-r--r--src/mscorlib/src/System/Reflection/Emit/OpCodes.cs3
-rw-r--r--src/mscorlib/src/System/Reflection/Emit/Opcode.cs2
-rw-r--r--src/mscorlib/src/System/Reflection/Emit/OpcodeType.cs1
-rw-r--r--src/mscorlib/src/System/Reflection/Emit/OperandType.cs1
-rw-r--r--src/mscorlib/src/System/Reflection/Emit/PEFileKinds.cs1
-rw-r--r--src/mscorlib/src/System/Reflection/Emit/ParameterBuilder.cs26
-rw-r--r--src/mscorlib/src/System/Reflection/Emit/ParameterToken.cs7
-rw-r--r--src/mscorlib/src/System/Reflection/Emit/PropertyBuilder.cs15
-rw-r--r--src/mscorlib/src/System/Reflection/Emit/PropertyToken.cs2
-rw-r--r--src/mscorlib/src/System/Reflection/Emit/SignatureHelper.cs44
-rw-r--r--src/mscorlib/src/System/Reflection/Emit/SignatureToken.cs2
-rw-r--r--src/mscorlib/src/System/Reflection/Emit/StackBehaviour.cs1
-rw-r--r--src/mscorlib/src/System/Reflection/Emit/StringToken.cs2
-rw-r--r--src/mscorlib/src/System/Reflection/Emit/SymbolType.cs2
-rw-r--r--src/mscorlib/src/System/Reflection/Emit/TypeBuilder.cs215
-rw-r--r--src/mscorlib/src/System/Reflection/Emit/TypeBuilderInstantiation.cs3
-rw-r--r--src/mscorlib/src/System/Reflection/Emit/TypeToken.cs7
-rw-r--r--src/mscorlib/src/System/Reflection/Emit/UnmanagedMarshal.cs183
-rw-r--r--src/mscorlib/src/System/Reflection/Emit/XXXOnTypeBuilderInstantiation.cs18
-rw-r--r--src/mscorlib/src/System/Reflection/EventAttributes.cs1
-rw-r--r--src/mscorlib/src/System/Reflection/EventInfo.cs7
-rw-r--r--src/mscorlib/src/System/Reflection/FieldAttributes.cs1
-rw-r--r--src/mscorlib/src/System/Reflection/FieldInfo.cs9
-rw-r--r--src/mscorlib/src/System/Reflection/ICustomAttributeProvider.cs1
-rw-r--r--src/mscorlib/src/System/Reflection/IReflect.cs1
-rw-r--r--src/mscorlib/src/System/Reflection/InterfaceMapping.cs5
-rw-r--r--src/mscorlib/src/System/Reflection/InvalidFilterCriteriaException.cs1
-rw-r--r--src/mscorlib/src/System/Reflection/ManifestResourceInfo.cs2
-rw-r--r--src/mscorlib/src/System/Reflection/MdImport.cs3
-rw-r--r--src/mscorlib/src/System/Reflection/MemberFilter.cs1
-rw-r--r--src/mscorlib/src/System/Reflection/MemberInfo.cs6
-rw-r--r--src/mscorlib/src/System/Reflection/MemberTypes.cs1
-rw-r--r--src/mscorlib/src/System/Reflection/MethodAttributes.cs1
-rw-r--r--src/mscorlib/src/System/Reflection/MethodBase.cs28
-rw-r--r--src/mscorlib/src/System/Reflection/MethodBody.cs4
-rw-r--r--src/mscorlib/src/System/Reflection/MethodImplAttributes.cs2
-rw-r--r--src/mscorlib/src/System/Reflection/MethodInfo.cs31
-rw-r--r--src/mscorlib/src/System/Reflection/Missing.cs2
-rw-r--r--src/mscorlib/src/System/Reflection/Module.cs30
-rw-r--r--src/mscorlib/src/System/Reflection/ObfuscateAssemblyAttribute.cs1
-rw-r--r--src/mscorlib/src/System/Reflection/ObfuscationAttribute.cs1
-rw-r--r--src/mscorlib/src/System/Reflection/ParameterAttributes.cs1
-rw-r--r--src/mscorlib/src/System/Reflection/ParameterInfo.cs6
-rw-r--r--src/mscorlib/src/System/Reflection/ParameterModifier.cs1
-rw-r--r--src/mscorlib/src/System/Reflection/Pointer.cs1
-rw-r--r--src/mscorlib/src/System/Reflection/PropertyAttributes.cs1
-rw-r--r--src/mscorlib/src/System/Reflection/PropertyInfo.cs7
-rw-r--r--src/mscorlib/src/System/Reflection/ReflectionTypeLoadException.cs7
-rw-r--r--src/mscorlib/src/System/Reflection/ResourceAttributes.cs1
-rw-r--r--src/mscorlib/src/System/Reflection/RuntimeReflectionExtensions.cs12
-rw-r--r--src/mscorlib/src/System/Reflection/StrongNameKeyPair.cs2
-rw-r--r--src/mscorlib/src/System/Reflection/TargetException.cs1
-rw-r--r--src/mscorlib/src/System/Reflection/TargetInvocationException.cs1
-rw-r--r--src/mscorlib/src/System/Reflection/TargetParameterCountException.cs1
-rw-r--r--src/mscorlib/src/System/Reflection/TypeAttributes.cs2
-rw-r--r--src/mscorlib/src/System/Reflection/TypeDelegator.cs3
-rw-r--r--src/mscorlib/src/System/Reflection/TypeFilter.cs1
-rw-r--r--src/mscorlib/src/System/Reflection/TypeInfo.cs1
-rw-r--r--src/mscorlib/src/System/Resources/FileBasedResourceGroveler.cs36
-rw-r--r--src/mscorlib/src/System/Resources/IResourceReader.cs1
-rw-r--r--src/mscorlib/src/System/Resources/IResourceWriter.cs45
-rw-r--r--src/mscorlib/src/System/Resources/LooselyLinkedResourceReference.cs1
-rw-r--r--src/mscorlib/src/System/Resources/MissingManifestResourceException.cs1
-rw-r--r--src/mscorlib/src/System/Resources/MissingSatelliteAssemblyException.cs1
-rw-r--r--src/mscorlib/src/System/Resources/NeutralResourcesLanguageAttribute.cs1
-rw-r--r--src/mscorlib/src/System/Resources/ResourceManager.cs47
-rw-r--r--src/mscorlib/src/System/Resources/ResourceReader.cs251
-rw-r--r--src/mscorlib/src/System/Resources/ResourceSet.cs4
-rw-r--r--src/mscorlib/src/System/Resources/SatelliteContractVersionAttribute.cs1
-rw-r--r--src/mscorlib/src/System/Resources/UltimateResourceFallbackLocation.cs1
-rw-r--r--src/mscorlib/src/System/RtType.cs80
-rw-r--r--src/mscorlib/src/System/Runtime/CompilerServices/AccessedThroughPropertyAttribute.cs1
-rw-r--r--src/mscorlib/src/System/Runtime/CompilerServices/AssemblyAttributesGoHere.cs43
-rw-r--r--src/mscorlib/src/System/Runtime/CompilerServices/AsyncMethodBuilder.cs60
-rw-r--r--src/mscorlib/src/System/Runtime/CompilerServices/CompilationRelaxations.cs2
-rw-r--r--src/mscorlib/src/System/Runtime/CompilerServices/CompilerGlobalScopeAttribute.cs1
-rw-r--r--src/mscorlib/src/System/Runtime/CompilerServices/ConditionalWeakTable.cs366
-rw-r--r--src/mscorlib/src/System/Runtime/CompilerServices/CustomConstantAttribute.cs1
-rw-r--r--src/mscorlib/src/System/Runtime/CompilerServices/DateTimeConstantAttribute.cs1
-rw-r--r--src/mscorlib/src/System/Runtime/CompilerServices/DecimalConstantAttribute.cs1
-rw-r--r--src/mscorlib/src/System/Runtime/CompilerServices/DecoratedNameAttribute.cs18
-rw-r--r--src/mscorlib/src/System/Runtime/CompilerServices/DiscardableAttribute.cs1
-rw-r--r--src/mscorlib/src/System/Runtime/CompilerServices/ITuple.cs22
-rw-r--r--src/mscorlib/src/System/Runtime/CompilerServices/IndexerNameAttribute.cs1
-rw-r--r--src/mscorlib/src/System/Runtime/CompilerServices/IsVolatile.cs1
-rw-r--r--src/mscorlib/src/System/Runtime/CompilerServices/MethodImplAttribute.cs4
-rw-r--r--src/mscorlib/src/System/Runtime/CompilerServices/RuntimeHelpers.cs6
-rw-r--r--src/mscorlib/src/System/Runtime/CompilerServices/RuntimeWrappedException.cs1
-rw-r--r--src/mscorlib/src/System/Runtime/CompilerServices/TaskAwaiter.cs9
-rw-r--r--src/mscorlib/src/System/Runtime/CompilerServices/TupleElementNamesAttribute.cs57
-rw-r--r--src/mscorlib/src/System/Runtime/CompilerServices/TypeForwardedToAttribute.cs12
-rw-r--r--src/mscorlib/src/System/Runtime/CompilerServices/Unsafe.cs13
-rw-r--r--src/mscorlib/src/System/Runtime/CompilerServices/YieldAwaitable.cs1
-rw-r--r--src/mscorlib/src/System/Runtime/CompilerServices/jithelpers.cs2
-rw-r--r--src/mscorlib/src/System/Runtime/ExceptionServices/CorruptingExceptionCommon.cs2
-rw-r--r--src/mscorlib/src/System/Runtime/ExceptionServices/ExceptionNotification.cs3
-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.cs1
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/Attributes.cs353
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/BStrWrapper.cs2
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/COMException.cs13
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/CallingConvention.cs1
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/CharSet.cs1
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/ComEventsMethod.cs72
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/ComEventsSink.cs118
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/ComMemberType.cs1
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/ComTypes/IEnumerable.cs28
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/ComTypes/IEnumerator.cs34
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/ComTypes/IExpando.cs31
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/ComTypes/IReflect.cs79
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/CriticalHandle.cs13
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/CurrencyWrapper.cs1
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/DispatchWrapper.cs2
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/ErrorWrapper.cs2
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/Expando/IExpando.cs12
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/ExtensibleClassFactory.cs40
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/ExternalException.cs1
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/GcHandle.cs146
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/HandleRef.cs1
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/ICustomAdapter.cs1
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/ICustomFactory.cs1
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/ICustomMarshaler.cs1
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/ICustomQueryInterface.cs2
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/IException.cs4
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/IRegistrationServices.cs50
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/ITypeLibConverter.cs122
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/InvalidComObjectException.cs1
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/InvalidOleVariantTypeException.cs1
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/LayoutKind.cs1
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/Marshal.cs538
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/MarshalDirectiveException.cs1
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/NativeMethods.cs31
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/NonPortable.cs33
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/ObjectCreationDelegate.cs24
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/RegistrationServices.cs1059
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/RuntimeEnvironment.cs81
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/SEHException.cs1
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/SafeArrayRankMismatchException.cs1
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/SafeArrayTypeMismatchException.cs1
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/SafeBuffer.cs15
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/SafeHandle.cs15
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/TCEAdapterGen/EventItfInfo.cs53
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/TCEAdapterGen/EventProviderWriter.cs774
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/TCEAdapterGen/EventSinkHelperWriter.cs298
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/TCEAdapterGen/NameSpaceExtractor.cs21
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/TCEAdapterGen/TCEAdapterGenerator.cs141
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/UCOMIBindCtx.cs46
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/UCOMIConnectionPoint.cs30
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/UCOMIConnectionPointContainer.cs27
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/UCOMIEnumConnectionPoints.cs32
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/UCOMIEnumConnections.cs42
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/UCOMIEnumMoniker.cs33
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/UCOMIEnumString.cs32
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/UCOMIEnumVARIANT.cs35
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/UCOMIEnumerable.cs30
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/UCOMIEnumerator.cs32
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/UCOMIExpando.cs33
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/UCOMIMoniker.cs60
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/UCOMIPersistFile.cs36
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/UCOMIReflect.cs79
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/UCOMIRunningObjectTable.cs32
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/UCOMIStream.cs57
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/UCOMITypeComp.cs52
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/UCOMITypeInfo.cs330
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/UCOMITypeLib.cs71
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/UnknownWrapper.cs1
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/Variant.cs658
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/Attributes.cs2
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/CLRIPropertyValueImpl.cs9
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/ConstantSplittableMap.cs62
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/CustomPropertyImpl.cs1
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/IVector.cs3
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/NativeMethods.cs2
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/WindowsRuntimeBufferHelper.cs2
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/WindowsRuntimeMarshal.cs42
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/WindowsRuntimeMetadata.cs100
-rw-r--r--src/mscorlib/src/System/Runtime/Loader/AssemblyLoadContext.cs41
-rw-r--r--src/mscorlib/src/System/Runtime/MemoryFailPoint.cs6
-rw-r--r--src/mscorlib/src/System/Runtime/ProfileOptimization.cs50
-rw-r--r--src/mscorlib/src/System/Runtime/Reliability/CriticalFinalizerObject.cs4
-rw-r--r--src/mscorlib/src/System/Runtime/Reliability/PrePrepareMethodAttribute.cs2
-rw-r--r--src/mscorlib/src/System/Runtime/Remoting/ObjectHandle.cs9
-rw-r--r--src/mscorlib/src/System/Runtime/Serialization/FormatterConverter.cs3
-rw-r--r--src/mscorlib/src/System/Runtime/Serialization/FormatterServices.cs480
-rw-r--r--src/mscorlib/src/System/Runtime/Serialization/IDeserializationCallback.cs1
-rw-r--r--src/mscorlib/src/System/Runtime/Serialization/IFormatter.cs41
-rw-r--r--src/mscorlib/src/System/Runtime/Serialization/IFormatterConverter.cs1
-rw-r--r--src/mscorlib/src/System/Runtime/Serialization/IObjectReference.cs2
-rw-r--r--src/mscorlib/src/System/Runtime/Serialization/ISerializable.cs2
-rw-r--r--src/mscorlib/src/System/Runtime/Serialization/ISerializationSurrogate.cs34
-rw-r--r--src/mscorlib/src/System/Runtime/Serialization/ISurrogateSelector.cs34
-rw-r--r--src/mscorlib/src/System/Runtime/Serialization/MemberHolder.cs51
-rw-r--r--src/mscorlib/src/System/Runtime/Serialization/SafeSerializationManager.cs210
-rw-r--r--src/mscorlib/src/System/Runtime/Serialization/SerializationAttributes.cs5
-rw-r--r--src/mscorlib/src/System/Runtime/Serialization/SerializationBinder.cs29
-rw-r--r--src/mscorlib/src/System/Runtime/Serialization/SerializationException.cs1
-rw-r--r--src/mscorlib/src/System/Runtime/Serialization/SerializationFieldInfo.cs136
-rw-r--r--src/mscorlib/src/System/Runtime/Serialization/SerializationInfo.cs59
-rw-r--r--src/mscorlib/src/System/Runtime/Serialization/SerializationInfoEnumerator.cs2
-rw-r--r--src/mscorlib/src/System/Runtime/Serialization/StreamingContext.cs2
-rw-r--r--src/mscorlib/src/System/Runtime/Versioning/CompatibilitySwitch.cs28
-rw-r--r--src/mscorlib/src/System/Runtime/Versioning/TargetFrameworkId.cs28
-rw-r--r--src/mscorlib/src/System/RuntimeArgumentHandle.cs1
-rw-r--r--src/mscorlib/src/System/RuntimeHandles.cs150
-rw-r--r--src/mscorlib/src/System/SByte.cs1
-rw-r--r--src/mscorlib/src/System/Security/AccessControl/Enums.cs75
-rw-r--r--src/mscorlib/src/System/Security/Attributes.cs3
-rw-r--r--src/mscorlib/src/System/Security/BuiltInPermissionSets.cs255
-rw-r--r--src/mscorlib/src/System/Security/CodeAccessPermission.cs229
-rw-r--r--src/mscorlib/src/System/Security/CodeAccessSecurityEngine.cs400
-rw-r--r--src/mscorlib/src/System/Security/FrameSecurityDescriptor.cs537
-rw-r--r--src/mscorlib/src/System/Security/HostProtectionException.cs135
-rw-r--r--src/mscorlib/src/System/Security/HostSecurityManager.cs90
-rw-r--r--src/mscorlib/src/System/Security/IEvidenceFactory.cs11
-rw-r--r--src/mscorlib/src/System/Security/IPermission.cs84
-rw-r--r--src/mscorlib/src/System/Security/ISecurityEncodable.cs17
-rw-r--r--src/mscorlib/src/System/Security/ISecurityPolicyEncodable.cs17
-rw-r--r--src/mscorlib/src/System/Security/IStackWalk.cs23
-rw-r--r--src/mscorlib/src/System/Security/NamedPermissionSet.cs75
-rw-r--r--src/mscorlib/src/System/Security/PermissionListSet.cs535
-rw-r--r--src/mscorlib/src/System/Security/PermissionSet.cs1605
-rw-r--r--src/mscorlib/src/System/Security/PermissionSetEnumerator.cs89
-rw-r--r--src/mscorlib/src/System/Security/PermissionSetTriple.cs270
-rw-r--r--src/mscorlib/src/System/Security/PermissionToken.cs383
-rw-r--r--src/mscorlib/src/System/Security/Permissions/EnvironmentPermission.cs347
-rw-r--r--src/mscorlib/src/System/Security/Permissions/FileDialogPermission.cs158
-rw-r--r--src/mscorlib/src/System/Security/Permissions/FileIOPermission.cs1216
-rw-r--r--src/mscorlib/src/System/Security/Permissions/GACIdentityPermission.cs103
-rw-r--r--src/mscorlib/src/System/Security/Permissions/HostProtectionPermission.cs265
-rw-r--r--src/mscorlib/src/System/Security/Permissions/IBuiltInPermission.cs63
-rw-r--r--src/mscorlib/src/System/Security/Permissions/IUnrestrictedPermission.cs13
-rw-r--r--src/mscorlib/src/System/Security/Permissions/IsolatedStorageFilePermission.cs163
-rw-r--r--src/mscorlib/src/System/Security/Permissions/IsolatedStoragePermission.cs183
-rw-r--r--src/mscorlib/src/System/Security/Permissions/PermissionAttributes.cs880
-rw-r--r--src/mscorlib/src/System/Security/Permissions/PermissionState.cs21
-rw-r--r--src/mscorlib/src/System/Security/Permissions/ReflectionPermission.cs274
-rw-r--r--src/mscorlib/src/System/Security/Permissions/RegistryPermission.cs363
-rw-r--r--src/mscorlib/src/System/Security/Permissions/SecurityPermission.cs270
-rw-r--r--src/mscorlib/src/System/Security/Permissions/SiteIdentityPermission.cs251
-rw-r--r--src/mscorlib/src/System/Security/Permissions/StrongNameIdentityPermission.cs401
-rw-r--r--src/mscorlib/src/System/Security/Permissions/StrongNamePublicKeyBlob.cs94
-rw-r--r--src/mscorlib/src/System/Security/Permissions/UIPermission.cs327
-rw-r--r--src/mscorlib/src/System/Security/Permissions/URLIdentityPermission.cs284
-rw-r--r--src/mscorlib/src/System/Security/Permissions/ZoneIdentityPermission.cs208
-rw-r--r--src/mscorlib/src/System/Security/Permissions/keycontainerpermission.cs634
-rw-r--r--src/mscorlib/src/System/Security/Policy/ApplicationTrust.cs126
-rw-r--r--src/mscorlib/src/System/Security/Policy/Evidence.cs38
-rw-r--r--src/mscorlib/src/System/Security/Policy/EvidenceBase.cs178
-rw-r--r--src/mscorlib/src/System/Security/Policy/EvidenceTypeDescriptor.cs160
-rw-r--r--src/mscorlib/src/System/Security/Policy/IDelayEvaluatedEvidence.cs34
-rw-r--r--src/mscorlib/src/System/Security/Policy/IIdentityPermissionFactory.cs20
-rw-r--r--src/mscorlib/src/System/Security/Policy/IRuntimeEvidenceFactory.cs36
-rw-r--r--src/mscorlib/src/System/Security/Policy/PolicyException.cs50
-rw-r--r--src/mscorlib/src/System/Security/Policy/PolicyStatement.cs246
-rw-r--r--src/mscorlib/src/System/Security/Policy/Site.cs105
-rw-r--r--src/mscorlib/src/System/Security/Policy/StrongName.cs171
-rw-r--r--src/mscorlib/src/System/Security/Policy/URL.cs98
-rw-r--r--src/mscorlib/src/System/Security/Policy/Zone.cs93
-rw-r--r--src/mscorlib/src/System/Security/Principal/IIdentity.cs29
-rw-r--r--src/mscorlib/src/System/Security/Principal/IPrincipal.cs26
-rw-r--r--src/mscorlib/src/System/Security/Principal/TokenImpersonationLevel.cs15
-rw-r--r--src/mscorlib/src/System/Security/SafeSecurityHandles.cs148
-rw-r--r--src/mscorlib/src/System/Security/SecurityContext.cs486
-rw-r--r--src/mscorlib/src/System/Security/SecurityElement.cs875
-rw-r--r--src/mscorlib/src/System/Security/SecurityException.cs35
-rw-r--r--src/mscorlib/src/System/Security/SecurityManager.cs157
-rw-r--r--src/mscorlib/src/System/Security/SecurityRuntime.cs159
-rw-r--r--src/mscorlib/src/System/Security/SecurityState.cs1
-rw-r--r--src/mscorlib/src/System/Security/SecurityZone.cs29
-rw-r--r--src/mscorlib/src/System/Security/Util/Config.cs83
-rw-r--r--src/mscorlib/src/System/Security/Util/Hex.cs126
-rw-r--r--src/mscorlib/src/System/Security/Util/StringExpressionSet.cs752
-rw-r--r--src/mscorlib/src/System/Security/Util/TokenBasedSet.cs443
-rw-r--r--src/mscorlib/src/System/Security/Util/TokenBasedSetEnumerator.cs36
-rw-r--r--src/mscorlib/src/System/Security/Util/URLString.cs1237
-rw-r--r--src/mscorlib/src/System/Security/Util/XMLUtil.cs435
-rw-r--r--src/mscorlib/src/System/Security/Util/sitestring.cs289
-rw-r--r--src/mscorlib/src/System/Security/VerificationException.cs1
-rw-r--r--src/mscorlib/src/System/Security/securestring.cs751
-rw-r--r--src/mscorlib/src/System/SerializableAttribute.cs1
-rw-r--r--src/mscorlib/src/System/SharedStatics.cs33
-rw-r--r--src/mscorlib/src/System/Single.cs2
-rw-r--r--src/mscorlib/src/System/Span.cs226
-rw-r--r--src/mscorlib/src/System/StackOverflowException.cs41
-rw-r--r--src/mscorlib/src/System/String.Comparison.cs9
-rw-r--r--src/mscorlib/src/System/String.Manipulation.cs247
-rw-r--r--src/mscorlib/src/System/String.cs19
-rw-r--r--src/mscorlib/src/System/StringComparer.cs161
-rw-r--r--src/mscorlib/src/System/StringComparison.cs9
-rw-r--r--src/mscorlib/src/System/StringSplitOptions.cs5
-rw-r--r--src/mscorlib/src/System/StubHelpers.cs34
-rw-r--r--src/mscorlib/src/System/SystemException.cs37
-rw-r--r--src/mscorlib/src/System/Text/ASCIIEncoding.cs9
-rw-r--r--src/mscorlib/src/System/Text/BaseCodePageEncoding.cs332
-rw-r--r--src/mscorlib/src/System/Text/CodePageEncoding.cs136
-rw-r--r--src/mscorlib/src/System/Text/DBCSCodePageEncoding.cs1194
-rw-r--r--src/mscorlib/src/System/Text/Decoder.cs9
-rw-r--r--src/mscorlib/src/System/Text/DecoderFallback.cs8
-rw-r--r--src/mscorlib/src/System/Text/DecoderNLS.cs11
-rw-r--r--src/mscorlib/src/System/Text/EUCJPEncoding.cs183
-rw-r--r--src/mscorlib/src/System/Text/Encoder.cs8
-rw-r--r--src/mscorlib/src/System/Text/EncoderBestFitFallback.cs2
-rw-r--r--src/mscorlib/src/System/Text/EncoderExceptionFallback.cs2
-rw-r--r--src/mscorlib/src/System/Text/EncoderNLS.cs11
-rw-r--r--src/mscorlib/src/System/Text/EncoderReplacementFallback.cs2
-rw-r--r--src/mscorlib/src/System/Text/Encoding.cs232
-rw-r--r--src/mscorlib/src/System/Text/EncodingForwarder.cs6
-rw-r--r--src/mscorlib/src/System/Text/EncodingNLS.cs1
-rw-r--r--src/mscorlib/src/System/Text/EncodingProvider.cs1
-rw-r--r--src/mscorlib/src/System/Text/GB18030Encoding.cs1365
-rw-r--r--src/mscorlib/src/System/Text/ISCIIEncoding.cs2621
-rw-r--r--src/mscorlib/src/System/Text/ISO2022Encoding.cs1983
-rw-r--r--src/mscorlib/src/System/Text/Latin1Encoding.cs3
-rw-r--r--src/mscorlib/src/System/Text/MLangCodePageEncoding.cs172
-rw-r--r--src/mscorlib/src/System/Text/Normalization.Windows.cs8
-rw-r--r--src/mscorlib/src/System/Text/Normalization.cs7
-rw-r--r--src/mscorlib/src/System/Text/SBCSCodePageEncoding.cs1009
-rw-r--r--src/mscorlib/src/System/Text/StringBuilder.cs12
-rw-r--r--src/mscorlib/src/System/Text/SurrogateEncoder.cs57
-rw-r--r--src/mscorlib/src/System/Text/UTF7Encoding.cs11
-rw-r--r--src/mscorlib/src/System/Text/UTF8Encoding.cs7
-rw-r--r--src/mscorlib/src/System/Text/UnicodeEncoding.cs8
-rw-r--r--src/mscorlib/src/System/ThreadAttributes.cs12
-rw-r--r--src/mscorlib/src/System/ThreadStaticAttribute.cs12
-rw-r--r--src/mscorlib/src/System/Threading/ApartmentState.cs1
-rw-r--r--src/mscorlib/src/System/Threading/AsyncLocal.cs2
-rw-r--r--src/mscorlib/src/System/Threading/AutoResetEvent.cs2
-rw-r--r--src/mscorlib/src/System/Threading/CancellationToken.cs8
-rw-r--r--src/mscorlib/src/System/Threading/CancellationTokenRegistration.cs1
-rw-r--r--src/mscorlib/src/System/Threading/CancellationTokenSource.cs102
-rw-r--r--src/mscorlib/src/System/Threading/CountdownEvent.cs2
-rw-r--r--src/mscorlib/src/System/Threading/EventWaitHandle.cs14
-rw-r--r--src/mscorlib/src/System/Threading/ExecutionContext.cs62
-rw-r--r--src/mscorlib/src/System/Threading/IObjectHandle.cs31
-rw-r--r--src/mscorlib/src/System/Threading/Interlocked.cs20
-rw-r--r--src/mscorlib/src/System/Threading/LazyInitializer.cs1
-rw-r--r--src/mscorlib/src/System/Threading/LockCookie.cs57
-rw-r--r--src/mscorlib/src/System/Threading/LockRecursionException.cs1
-rw-r--r--src/mscorlib/src/System/Threading/ManualResetEvent.cs2
-rw-r--r--src/mscorlib/src/System/Threading/ManualResetEventSlim.cs2
-rw-r--r--src/mscorlib/src/System/Threading/Monitor.cs3
-rw-r--r--src/mscorlib/src/System/Threading/Mutex.cs52
-rw-r--r--src/mscorlib/src/System/Threading/Overlapped.cs54
-rw-r--r--src/mscorlib/src/System/Threading/ParameterizedThreadStart.cs1
-rw-r--r--src/mscorlib/src/System/Threading/ReaderWriterLock.cs276
-rw-r--r--src/mscorlib/src/System/Threading/SemaphoreSlim.cs6
-rw-r--r--src/mscorlib/src/System/Threading/SpinLock.cs82
-rw-r--r--src/mscorlib/src/System/Threading/SpinWait.cs1
-rw-r--r--src/mscorlib/src/System/Threading/SynchronizationContext.cs23
-rw-r--r--src/mscorlib/src/System/Threading/SynchronizationLockException.cs1
-rw-r--r--src/mscorlib/src/System/Threading/Tasks/BeginEndAwaitableAdapter.cs157
-rw-r--r--src/mscorlib/src/System/Threading/Tasks/ConcurrentExclusiveSchedulerPair.cs1
-rw-r--r--src/mscorlib/src/System/Threading/Tasks/FutureFactory.cs145
-rw-r--r--src/mscorlib/src/System/Threading/Tasks/IAsyncCausalityTracerStatics.cs14
-rw-r--r--src/mscorlib/src/System/Threading/Tasks/Parallel.cs3593
-rw-r--r--src/mscorlib/src/System/Threading/Tasks/ParallelLoopState.cs641
-rw-r--r--src/mscorlib/src/System/Threading/Tasks/ParallelRangeManager.cs279
-rw-r--r--src/mscorlib/src/System/Threading/Tasks/ProducerConsumerQueues.cs171
-rw-r--r--src/mscorlib/src/System/Threading/Tasks/TPLETWProvider.cs214
-rw-r--r--src/mscorlib/src/System/Threading/Tasks/Task.cs716
-rw-r--r--src/mscorlib/src/System/Threading/Tasks/TaskCompletionSource.cs17
-rw-r--r--src/mscorlib/src/System/Threading/Tasks/TaskContinuation.cs54
-rw-r--r--src/mscorlib/src/System/Threading/Tasks/TaskExceptionHolder.cs17
-rw-r--r--src/mscorlib/src/System/Threading/Tasks/TaskFactory.cs259
-rw-r--r--src/mscorlib/src/System/Threading/Tasks/TaskScheduler.cs1
-rw-r--r--src/mscorlib/src/System/Threading/Tasks/future.cs171
-rw-r--r--src/mscorlib/src/System/Threading/Thread.cs542
-rw-r--r--src/mscorlib/src/System/Threading/ThreadAbortException.cs6
-rw-r--r--src/mscorlib/src/System/Threading/ThreadInterruptedException.cs1
-rw-r--r--src/mscorlib/src/System/Threading/ThreadLocal.cs1
-rw-r--r--src/mscorlib/src/System/Threading/ThreadPool.cs960
-rw-r--r--src/mscorlib/src/System/Threading/ThreadPriority.cs1
-rw-r--r--src/mscorlib/src/System/Threading/ThreadStart.cs2
-rw-r--r--src/mscorlib/src/System/Threading/ThreadState.cs1
-rw-r--r--src/mscorlib/src/System/Threading/ThreadStateException.cs1
-rw-r--r--src/mscorlib/src/System/Threading/Timeout.cs2
-rw-r--r--src/mscorlib/src/System/Threading/Timer.cs147
-rw-r--r--src/mscorlib/src/System/Threading/Volatile.cs32
-rw-r--r--src/mscorlib/src/System/Threading/WaitHandle.cs13
-rw-r--r--src/mscorlib/src/System/ThrowHelper.cs36
-rw-r--r--src/mscorlib/src/System/TimeSpan.cs1
-rw-r--r--src/mscorlib/src/System/TimeZone.cs1
-rw-r--r--src/mscorlib/src/System/TimeZoneInfo.AdjustmentRule.cs251
-rw-r--r--src/mscorlib/src/System/TimeZoneInfo.StringSerializer.cs625
-rw-r--r--src/mscorlib/src/System/TimeZoneInfo.TransitionTime.cs159
-rw-r--r--src/mscorlib/src/System/TimeZoneInfo.Unix.cs1463
-rw-r--r--src/mscorlib/src/System/TimeZoneInfo.Win32.cs1023
-rw-r--r--src/mscorlib/src/System/TimeZoneInfo.cs5535
-rw-r--r--src/mscorlib/src/System/TimeZoneNotFoundException.cs33
-rw-r--r--src/mscorlib/src/System/TimeoutException.cs44
-rw-r--r--src/mscorlib/src/System/Tuple.cs729
-rw-r--r--src/mscorlib/src/System/TupleExtensions.cs930
-rw-r--r--src/mscorlib/src/System/Type.cs45
-rw-r--r--src/mscorlib/src/System/TypeAccessException.cs24
-rw-r--r--src/mscorlib/src/System/TypeCode.cs10
-rw-r--r--src/mscorlib/src/System/TypeInitializationException.cs58
-rw-r--r--src/mscorlib/src/System/TypeLoadException.cs2
-rw-r--r--src/mscorlib/src/System/TypeUnloadedException.cs1
-rw-r--r--src/mscorlib/src/System/TypedReference.cs2
-rw-r--r--src/mscorlib/src/System/UInt16.cs1
-rw-r--r--src/mscorlib/src/System/UInt32.cs1
-rw-r--r--src/mscorlib/src/System/UInt64.cs1
-rw-r--r--src/mscorlib/src/System/UIntPtr.cs1
-rw-r--r--src/mscorlib/src/System/UnauthorizedAccessException.cs36
-rw-r--r--src/mscorlib/src/System/UnhandledExceptionEventArgs.cs36
-rw-r--r--src/mscorlib/src/System/UnhandledExceptionEventHandler.cs6
-rw-r--r--src/mscorlib/src/System/ValueTuple.cs2324
-rw-r--r--src/mscorlib/src/System/ValueType.cs1
-rw-r--r--src/mscorlib/src/System/Variant.cs15
-rw-r--r--src/mscorlib/src/System/Version.cs4
-rw-r--r--src/mscorlib/src/System/Void.cs9
-rw-r--r--src/mscorlib/src/System/WeakReference.cs2
-rw-r--r--src/mscorlib/src/System/_LocalDataStore.cs244
-rw-r--r--src/mscorlib/src/System/_LocalDataStoreMgr.cs332
-rw-r--r--src/mscorlib/src/System/__ComObject.cs7
-rw-r--r--src/mscorlib/src/System/cominterfaces.cs40
-rw-r--r--src/mscorlib/src/mscorlib.Friends.cs12
738 files changed, 12560 insertions, 75168 deletions
diff --git a/src/mscorlib/src/CleanupToDoList.cs b/src/mscorlib/src/CleanupToDoList.cs
new file mode 100644
index 0000000000..f07d23f8ae
--- /dev/null
+++ b/src/mscorlib/src/CleanupToDoList.cs
@@ -0,0 +1,27 @@
+// 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.
+
+//
+// Stubbed out types to be cleanup from CoreLib
+//
+
+namespace System.Security
+{
+ internal enum SecurityContextSource
+ {
+ CurrentAppDomain = 0,
+ CurrentAssembly
+ }
+}
+
+namespace System.Security.Policy
+{
+ internal sealed class Evidence
+ {
+ }
+
+ internal sealed class ApplicationTrust
+ {
+ }
+}
diff --git a/src/mscorlib/src/Internal/Runtime/Augments/RuntimeThread.cs b/src/mscorlib/src/Internal/Runtime/Augments/RuntimeThread.cs
index 3aafe01a2c..58eff98dec 100644
--- a/src/mscorlib/src/Internal/Runtime/Augments/RuntimeThread.cs
+++ b/src/mscorlib/src/Internal/Runtime/Augments/RuntimeThread.cs
@@ -9,13 +9,14 @@ 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
{
+ internal RuntimeThread() {}
+
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);
@@ -147,11 +148,9 @@ namespace Internal.Runtime.Augments
#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
@@ -163,8 +162,6 @@ namespace Internal.Runtime.Augments
** 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
diff --git a/src/mscorlib/src/Microsoft/Win32/Registry.cs b/src/mscorlib/src/Microsoft/Win32/Registry.cs
index 3ee5f4648b..bf4f73949a 100644
--- a/src/mscorlib/src/Microsoft/Win32/Registry.cs
+++ b/src/mscorlib/src/Microsoft/Win32/Registry.cs
@@ -15,8 +15,7 @@ namespace Microsoft.Win32 {
* @security(checkClassLinking=on)
*/
//This class contains only static members and does not need to be serializable.
- [ComVisible(true)]
- public static class Registry {
+ internal static class Registry {
static Registry()
{
}
@@ -130,24 +129,6 @@ namespace Microsoft.Win32 {
key.Close();
}
}
-
- public static void SetValue(string keyName, string valueName, object value ) {
- SetValue(keyName, valueName, value, RegistryValueKind.Unknown);
- }
-
- public static void SetValue(string keyName, string valueName, object value, RegistryValueKind valueKind ) {
- string subKeyName;
- RegistryKey basekey = GetBaseKeyFromKeyName(keyName, out subKeyName);
- BCLDebug.Assert(basekey != null, "basekey can't be null!");
- RegistryKey key = basekey.CreateSubKey(subKeyName);
- BCLDebug.Assert(key != null, "An exception should be thrown if failed!");
- try {
- key.SetValue(valueName, value, valueKind);
- }
- finally {
- key.Close();
- }
- }
}
}
diff --git a/src/mscorlib/src/Microsoft/Win32/RegistryKey.cs b/src/mscorlib/src/Microsoft/Win32/RegistryKey.cs
index ff678f132c..f82b276059 100644
--- a/src/mscorlib/src/Microsoft/Win32/RegistryKey.cs
+++ b/src/mscorlib/src/Microsoft/Win32/RegistryKey.cs
@@ -55,7 +55,6 @@ namespace Microsoft.Win32
using System.Collections;
using System.Collections.Generic;
using System.Security;
- using System.Security.Permissions;
using System.Text;
using System.Threading;
using System.IO;
@@ -68,21 +67,6 @@ namespace Microsoft.Win32
using System.Diagnostics.CodeAnalysis;
/**
- * Registry hive values. Useful only for GetRemoteBaseKey
- */
- [Serializable]
- [System.Runtime.InteropServices.ComVisible(true)]
- public enum RegistryHive
- {
- ClassesRoot = unchecked((int)0x80000000),
- CurrentUser = unchecked((int)0x80000001),
- LocalMachine = unchecked((int)0x80000002),
- Users = unchecked((int)0x80000003),
- PerformanceData = unchecked((int)0x80000004),
- CurrentConfig = unchecked((int)0x80000005),
- }
-
- /**
* Registry encapsulation. To get an instance of a RegistryKey use the
* Registry class's static members then call OpenSubKey.
*
@@ -90,8 +74,7 @@ namespace Microsoft.Win32
* @security(checkDllCalls=off)
* @security(checkClassLinking=on)
*/
- [ComVisible(true)]
- public sealed class RegistryKey : MarshalByRefObject, IDisposable
+ internal sealed class RegistryKey : MarshalByRefObject, IDisposable
{
// We could use const here, if C# supported ELEMENT_TYPE_I fully.
@@ -168,17 +151,6 @@ namespace Microsoft.Win32
* Creates a RegistryKey.
*
* This key is bound to hkey, if writable is <b>false</b> then no write operations
- * will be allowed.
- */
- private RegistryKey(SafeRegistryHandle hkey, bool writable, RegistryView view)
- : this(hkey, writable, false, false, false, view) {
- }
-
-
- /**
- * Creates a RegistryKey.
- *
- * This key is bound to hkey, if writable is <b>false</b> then no write operations
* will be allowed. If systemkey is set then the hkey won't be released
* when the object is GC'ed.
* The remoteKey flag when set to true indicates that we are dealing with registry entries
@@ -239,262 +211,11 @@ namespace Microsoft.Win32
}
}
- public void Flush() {
- if (hkey != null) {
- if (IsDirty()) {
- Win32Native.RegFlushKey(hkey);
- }
- }
- }
-
void IDisposable.Dispose()
{
Dispose(true);
}
- /**
- * Creates a new subkey, or opens an existing one.
- *
- * @param subkey Name or path to subkey to create or open.
- *
- * @return the subkey, or <b>null</b> if the operation failed.
- */
- [SuppressMessage("Microsoft.Concurrency", "CA8001", Justification = "Reviewed for thread safety")]
- public RegistryKey CreateSubKey(String subkey) {
- return CreateSubKey(subkey, checkMode);
- }
-
- [ComVisible(false)]
- public RegistryKey CreateSubKey(String subkey, RegistryKeyPermissionCheck permissionCheck)
- {
- return CreateSubKeyInternal(subkey, permissionCheck, null, RegistryOptions.None);
- }
-
- [ComVisible(false)]
- public RegistryKey CreateSubKey(String subkey, RegistryKeyPermissionCheck permissionCheck, RegistryOptions options)
- {
- return CreateSubKeyInternal(subkey, permissionCheck, null, options);
- }
-
- [ComVisible(false)]
- public RegistryKey CreateSubKey(String subkey, bool writable)
- {
- return CreateSubKeyInternal(subkey, writable ? RegistryKeyPermissionCheck.ReadWriteSubTree : RegistryKeyPermissionCheck.ReadSubTree, null, RegistryOptions.None);
- }
-
- [ComVisible(false)]
- public RegistryKey CreateSubKey(String subkey, bool writable, RegistryOptions options)
- {
- return CreateSubKeyInternal(subkey, writable ? RegistryKeyPermissionCheck.ReadWriteSubTree : RegistryKeyPermissionCheck.ReadSubTree, null, options);
- }
-
- [ComVisible(false)]
- private unsafe RegistryKey CreateSubKeyInternal(String subkey, RegistryKeyPermissionCheck permissionCheck, object registrySecurityObj, RegistryOptions registryOptions)
- {
- ValidateKeyOptions(registryOptions);
- ValidateKeyName(subkey);
- ValidateKeyMode(permissionCheck);
- EnsureWriteable();
- subkey = FixupName(subkey); // Fixup multiple slashes to a single slash
-
- // only keys opened under read mode is not writable
- if (!remoteKey) {
- RegistryKey key = InternalOpenSubKey(subkey, (permissionCheck != RegistryKeyPermissionCheck.ReadSubTree));
- if (key != null) { // Key already exits
- CheckPermission(RegistryInternalCheck.CheckSubKeyWritePermission, subkey, false, RegistryKeyPermissionCheck.Default);
- CheckPermission(RegistryInternalCheck.CheckSubTreePermission, subkey, false, permissionCheck);
- key.checkMode = permissionCheck;
- return key;
- }
- }
-
- CheckPermission(RegistryInternalCheck.CheckSubKeyCreatePermission, subkey, false, RegistryKeyPermissionCheck.Default);
-
- Win32Native.SECURITY_ATTRIBUTES secAttrs = null;
-
- int disposition = 0;
-
- // By default, the new key will be writable.
- SafeRegistryHandle result = null;
- int ret = Win32Native.RegCreateKeyEx(hkey,
- subkey,
- 0,
- null,
- (int)registryOptions /* specifies if the key is volatile */,
- GetRegistryKeyAccess(permissionCheck != RegistryKeyPermissionCheck.ReadSubTree) | (int)regView,
- secAttrs,
- out result,
- out disposition);
-
- if (ret == 0 && !result.IsInvalid) {
- RegistryKey key = new RegistryKey(result, (permissionCheck != RegistryKeyPermissionCheck.ReadSubTree), false, remoteKey, false, regView);
- CheckPermission(RegistryInternalCheck.CheckSubTreePermission, subkey, false, permissionCheck);
- key.checkMode = permissionCheck;
-
- if (subkey.Length == 0)
- key.keyName = keyName;
- else
- key.keyName = keyName + "\\" + subkey;
- return key;
- }
- else if (ret != 0) // syscall failed, ret is an error code.
- Win32Error(ret, keyName + "\\" + subkey); // Access denied?
-
- BCLDebug.Assert(false, "Unexpected code path in RegistryKey::CreateSubKey");
- return null;
- }
-
- /**
- * Deletes the specified subkey. Will throw an exception if the subkey has
- * subkeys. To delete a tree of subkeys use, DeleteSubKeyTree.
- *
- * @param subkey SubKey to delete.
- *
- * @exception InvalidOperationException thrown if the subkey has child subkeys.
- */
- public void DeleteSubKey(String subkey) {
- DeleteSubKey(subkey, true);
- }
-
- public void DeleteSubKey(String subkey, bool throwOnMissingSubKey) {
- ValidateKeyName(subkey);
- EnsureWriteable();
- subkey = FixupName(subkey); // Fixup multiple slashes to a single slash
- CheckPermission(RegistryInternalCheck.CheckSubKeyWritePermission, subkey, false, RegistryKeyPermissionCheck.Default);
-
- // Open the key we are deleting and check for children. Be sure to
- // explicitly call close to avoid keeping an extra HKEY open.
- //
- RegistryKey key = InternalOpenSubKey(subkey,false);
- if (key != null) {
- try {
- if (key.InternalSubKeyCount() > 0) {
- ThrowHelper.ThrowInvalidOperationException(ExceptionResource.InvalidOperation_RegRemoveSubKey);
- }
- }
- finally {
- key.Close();
- }
-
- int ret;
-
- try {
- ret = Win32Native.RegDeleteKeyEx(hkey, subkey, (int)regView, 0);
- }
- catch (EntryPointNotFoundException) {
- ret = Win32Native.RegDeleteKey(hkey, subkey);
- }
-
- if (ret!=0) {
- if (ret == Win32Native.ERROR_FILE_NOT_FOUND) {
- if (throwOnMissingSubKey)
- ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_RegSubKeyAbsent);
- }
- else
- Win32Error(ret, null);
- }
- }
- else { // there is no key which also means there is no subkey
- if (throwOnMissingSubKey)
- ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_RegSubKeyAbsent);
- }
- }
-
- /**
- * Recursively deletes a subkey and any child subkeys.
- *
- * @param subkey SubKey to delete.
- */
- public void DeleteSubKeyTree(String subkey) {
- DeleteSubKeyTree(subkey, true /*throwOnMissingSubKey*/);
- }
-
- [ComVisible(false)]
- public void DeleteSubKeyTree(String subkey, Boolean throwOnMissingSubKey) {
- ValidateKeyName(subkey);
-
- // Security concern: Deleting a hive's "" subkey would delete all
- // of that hive's contents. Don't allow "".
- if (subkey.Length==0 && IsSystemKey()) {
- ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_RegKeyDelHive);
- }
-
- EnsureWriteable();
-
- subkey = FixupName(subkey); // Fixup multiple slashes to a single slash
- CheckPermission(RegistryInternalCheck.CheckSubTreeWritePermission, subkey, false, RegistryKeyPermissionCheck.Default);
-
- RegistryKey key = InternalOpenSubKey(subkey, true);
- if (key != null) {
- try {
- if (key.InternalSubKeyCount() > 0) {
- String[] keys = key.InternalGetSubKeyNames();
-
- for (int i=0; i<keys.Length; i++) {
- key.DeleteSubKeyTreeInternal(keys[i]);
- }
- }
- }
- finally {
- key.Close();
- }
-
- int ret;
- try {
- ret = Win32Native.RegDeleteKeyEx(hkey, subkey, (int)regView, 0);
- }
- catch (EntryPointNotFoundException) {
- ret = Win32Native.RegDeleteKey(hkey, subkey);
- }
-
- if (ret!=0) Win32Error(ret, null);
- }
- else if(throwOnMissingSubKey) {
- ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_RegSubKeyAbsent);
- }
- }
-
- // 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.
- private void DeleteSubKeyTreeInternal(string subkey) {
- RegistryKey key = InternalOpenSubKey(subkey, true);
- if (key != null) {
- try {
- if (key.InternalSubKeyCount() > 0) {
- String[] keys = key.InternalGetSubKeyNames();
-
- for (int i=0; i<keys.Length; i++) {
- key.DeleteSubKeyTreeInternal(keys[i]);
- }
- }
- }
- finally {
- key.Close();
- }
-
- int ret;
- try {
- ret = Win32Native.RegDeleteKeyEx(hkey, subkey, (int)regView, 0);
- }
- catch (EntryPointNotFoundException) {
- ret = Win32Native.RegDeleteKey(hkey, subkey);
- }
- if (ret!=0) Win32Error(ret, null);
- }
- else {
- ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_RegSubKeyAbsent);
- }
- }
-
- /**
- * Deletes the specified value from this key.
- *
- * @param name Name of value to delete.
- */
- public void DeleteValue(String name) {
- DeleteValue(name, true);
- }
-
public void DeleteValue(String name, bool throwOnMissingValue) {
EnsureWriteable();
CheckPermission(RegistryInternalCheck.CheckValueWritePermission, name, false, RegistryKeyPermissionCheck.Default);
@@ -552,68 +273,6 @@ namespace Microsoft.Win32
return key;
}
-
- [ComVisible(false)]
- public static RegistryKey OpenBaseKey(RegistryHive hKey, RegistryView view) {
- ValidateKeyView(view);
- CheckUnmanagedCodePermission();
- return GetBaseKey((IntPtr)((int)hKey), view);
- }
-
- /**
- * Retrieves a new RegistryKey that represents the requested key on a foreign
- * machine. Valid values for hKey are members of the RegistryHive enum, or
- * Win32 integers such as:
- *
- * HKEY_CLASSES_ROOT,
- * HKEY_CURRENT_USER,
- * HKEY_LOCAL_MACHINE,
- * HKEY_USERS,
- * HKEY_PERFORMANCE_DATA,
- * HKEY_CURRENT_CONFIG,
- * HKEY_DYN_DATA.
- *
- * @param hKey HKEY_* to open.
- * @param machineName the machine to connect to
- *
- * @return the RegistryKey requested.
- */
- public static RegistryKey OpenRemoteBaseKey(RegistryHive hKey, String machineName) {
- return OpenRemoteBaseKey(hKey, machineName, RegistryView.Default);
- }
-
- [ComVisible(false)]
- public static RegistryKey OpenRemoteBaseKey(RegistryHive hKey, String machineName, RegistryView view) {
- if (machineName==null)
- 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"));
- }
- ValidateKeyView(view);
-
- CheckUnmanagedCodePermission();
- // connect to the specified remote registry
- SafeRegistryHandle foreignHKey = null;
- int ret = Win32Native.RegConnectRegistry(machineName, new SafeRegistryHandle(new IntPtr((int)hKey), false), out foreignHKey);
-
- if (ret == Win32Native.ERROR_DLL_INIT_FAILED)
- // return value indicates an error occurred
- throw new ArgumentException(Environment.GetResourceString("Arg_DllInitFailure"));
-
- if (ret != 0)
- Win32ErrorStatic(ret, null);
-
- if (foreignHKey.IsInvalid)
- // return value indicates an error occurred
- throw new ArgumentException(Environment.GetResourceString("Arg_RegKeyNoRemoteConnect", machineName));
-
- RegistryKey key = new RegistryKey(foreignHKey, true, false, true, ((IntPtr) hKey) == HKEY_PERFORMANCE_DATA, view);
- key.checkMode = RegistryKeyPermissionCheck.Default;
- key.keyName = hkeyNames[index];
- return key;
- }
-
/**
* Retrieves a subkey. If readonly is <b>true</b>, then the subkey is opened with
* read-only access.
@@ -685,26 +344,6 @@ namespace Microsoft.Win32
return OpenSubKey(name, false);
}
- /**
- * Retrieves the count of subkeys.
- *
- * @return a count of subkeys.
- */
- public int SubKeyCount {
- get {
- CheckPermission(RegistryInternalCheck.CheckKeyReadPermission, null, false, RegistryKeyPermissionCheck.Default);
- return InternalSubKeyCount();
- }
- }
-
- [ComVisible(false)]
- public RegistryView View {
- get {
- EnsureNotDisposed();
- return regView;
- }
- }
-
internal int InternalSubKeyCount() {
EnsureNotDisposed();
@@ -770,18 +409,6 @@ namespace Microsoft.Win32
return names;
}
- /**
- * Retrieves the count of values.
- *
- * @return a count of values.
- */
- public int ValueCount {
- get {
- CheckPermission(RegistryInternalCheck.CheckKeyReadPermission, null, false, RegistryKeyPermissionCheck.Default);
- return InternalValueCount();
- }
- }
-
internal int InternalValueCount() {
EnsureNotDisposed();
int values = 0;
@@ -883,7 +510,6 @@ namespace Microsoft.Win32
return InternalGetValue(name, defaultValue, false, true);
}
- [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), nameof(options));
@@ -1110,37 +736,6 @@ namespace Microsoft.Win32
return data;
}
-
- [ComVisible(false)]
- public RegistryValueKind GetValueKind(string name) {
- CheckPermission(RegistryInternalCheck.CheckValueReadPermission, name, false, RegistryKeyPermissionCheck.Default);
- EnsureNotDisposed();
-
- int type = 0;
- int datasize = 0;
- int ret = Win32Native.RegQueryValueEx(hkey, name, null, ref type, (byte[])null, ref datasize);
- if (ret != 0)
- Win32Error(ret, null);
- if (type == Win32Native.REG_NONE)
- return RegistryValueKind.None;
- else if (!Enum.IsDefined(typeof(RegistryValueKind), type))
- return RegistryValueKind.Unknown;
- else
- return (RegistryValueKind) type;
- }
-
- /**
- * Retrieves the current state of the dirty property.
- *
- * A key is marked as dirty if any operation has occurred that modifies the
- * contents of the key.
- *
- * @return <b>true</b> if the key has been modified.
- */
- private bool IsDirty() {
- return (this.state & STATE_DIRTY) != 0;
- }
-
private bool IsSystemKey() {
return (this.state & STATE_SYSTEMKEY) != 0;
}
@@ -1153,13 +748,6 @@ namespace Microsoft.Win32
return (this.state & STATE_PERF_DATA) != 0;
}
- public String Name {
- get {
- EnsureNotDisposed();
- return keyName;
- }
- }
-
private void SetDirty() {
this.state |= STATE_DIRTY;
}
@@ -1174,7 +762,6 @@ namespace Microsoft.Win32
SetValue(name, value, RegistryValueKind.Unknown);
}
- [ComVisible(false)]
public unsafe void SetValue(String name, Object value, RegistryValueKind valueKind) {
if (value==null)
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.value);
@@ -1392,19 +979,6 @@ namespace Microsoft.Win32
}
}
- internal static void Win32ErrorStatic(int errorCode, String str) {
- switch (errorCode) {
- case Win32Native.ERROR_ACCESS_DENIED:
- if (str != null)
- throw new UnauthorizedAccessException(Environment.GetResourceString("UnauthorizedAccess_RegistryKeyGeneric_Key", str));
- else
- throw new UnauthorizedAccessException();
-
- default:
- throw new IOException(Win32Native.GetMessage(errorCode), errorCode);
- }
- }
-
internal static String FixupName(String name)
{
BCLDebug.Assert(name!=null,"[FixupName]name!=null");
@@ -1469,301 +1043,9 @@ namespace Microsoft.Win32
}
- //
- // Read/Write/Create SubKey Permission
- //
- private void GetSubKeyReadPermission(string subkeyName, out RegistryPermissionAccess access, out string path) {
- access = RegistryPermissionAccess.Read;
- path = keyName + "\\" + subkeyName + "\\.";
- }
- private void GetSubKeyWritePermission(string subkeyName, out RegistryPermissionAccess access, out string path) {
- // If we want to open a subkey of a read-only key as writeable, we need to do the check.
- access = RegistryPermissionAccess.Write;
- path = keyName + "\\" + subkeyName + "\\.";
- }
- private void GetSubKeyCreatePermission(string subkeyName, out RegistryPermissionAccess access, out string path) {
- access = RegistryPermissionAccess.Create;
- path = keyName + "\\" + subkeyName + "\\.";
- }
-
- //
- // Read/Write/ReadWrite SubTree Permission
- //
- private void GetSubTreeReadPermission(string subkeyName, out RegistryPermissionAccess access, out string path) {
- access = RegistryPermissionAccess.Read;
- path = keyName + "\\" + subkeyName + "\\";
- }
- private void GetSubTreeWritePermission(string subkeyName, out RegistryPermissionAccess access, out string path) {
- access = RegistryPermissionAccess.Write;
- path = keyName + "\\" + subkeyName + "\\";
- }
- private void GetSubTreeReadWritePermission(string subkeyName, out RegistryPermissionAccess access, out string path) {
- access = RegistryPermissionAccess.Write | RegistryPermissionAccess.Read;
- path = keyName + "\\" + subkeyName;
- }
-
- //
- // Read/Write/Create Value Permission
- //
- private void GetValueReadPermission(string valueName, out RegistryPermissionAccess access, out string path) {
- access = RegistryPermissionAccess.Read;
- path = keyName+"\\"+valueName;
- }
- private void GetValueWritePermission(string valueName, out RegistryPermissionAccess access, out string path) {
- access = RegistryPermissionAccess.Write;
- path = keyName+"\\"+valueName;
- }
- private void GetValueCreatePermission(string valueName, out RegistryPermissionAccess access, out string path) {
- access = RegistryPermissionAccess.Create;
- path = keyName+"\\"+valueName;
- }
-
- // Read Key Permission
- private void GetKeyReadPermission(out RegistryPermissionAccess access, out string path) {
- access = RegistryPermissionAccess.Read;
- path = keyName + "\\.";
- }
-
private void CheckPermission(RegistryInternalCheck check, string item, bool subKeyWritable, RegistryKeyPermissionCheck subKeyCheck)
{
- bool demand = false;
- RegistryPermissionAccess access = RegistryPermissionAccess.NoAccess;
- string path = null;
-
- switch (check) {
- //
- // Read/Write/Create SubKey Permission
- //
- case RegistryInternalCheck.CheckSubKeyReadPermission:
- if (remoteKey) {
- CheckUnmanagedCodePermission();
- }
- else {
- BCLDebug.Assert(checkMode == RegistryKeyPermissionCheck.Default, "Should be called from a key opened under default mode only!");
- BCLDebug.Assert(subKeyWritable == false, "subKeyWritable should be false (unused)");
- BCLDebug.Assert(subKeyCheck == RegistryKeyPermissionCheck.Default, "subKeyCheck should be Default (unused)");
- demand = true;
- GetSubKeyReadPermission(item, out access, out path);
- }
- break;
- case RegistryInternalCheck.CheckSubKeyWritePermission:
- if (remoteKey) {
- CheckUnmanagedCodePermission();
- }
- else {
- BCLDebug.Assert(checkMode != RegistryKeyPermissionCheck.ReadSubTree, "We shouldn't allow creating sub key under read-only key!");
- BCLDebug.Assert(subKeyWritable == false, "subKeyWritable should be false (unused)");
- BCLDebug.Assert(subKeyCheck == RegistryKeyPermissionCheck.Default, "subKeyCheck should be Default (unused)");
- if( checkMode == RegistryKeyPermissionCheck.Default) {
- demand = true;
- GetSubKeyWritePermission(item, out access, out path);
- }
- }
- break;
- case RegistryInternalCheck.CheckSubKeyCreatePermission:
- if (remoteKey) {
- CheckUnmanagedCodePermission();
- }
- else {
- BCLDebug.Assert(checkMode != RegistryKeyPermissionCheck.ReadSubTree, "We shouldn't allow creating sub key under read-only key!");
- BCLDebug.Assert(subKeyWritable == false, "subKeyWritable should be false (unused)");
- BCLDebug.Assert(subKeyCheck == RegistryKeyPermissionCheck.Default, "subKeyCheck should be Default (unused)");
- if( checkMode == RegistryKeyPermissionCheck.Default) {
- demand = true;
- GetSubKeyCreatePermission(item, out access, out path);
- }
- }
- break;
- //
- // Read/Write/ReadWrite SubTree Permission
- //
- case RegistryInternalCheck.CheckSubTreeReadPermission:
- if (remoteKey) {
- CheckUnmanagedCodePermission();
- }
- else {
- BCLDebug.Assert(subKeyWritable == false, "subKeyWritable should be false (unused)");
- BCLDebug.Assert(subKeyCheck == RegistryKeyPermissionCheck.Default, "subKeyCheck should be Default (unused)");
- if( checkMode == RegistryKeyPermissionCheck.Default) {
- demand = true;
- GetSubTreeReadPermission(item, out access, out path);
- }
- }
- break;
- case RegistryInternalCheck.CheckSubTreeWritePermission:
- if (remoteKey) {
- CheckUnmanagedCodePermission();
- }
- else {
- BCLDebug.Assert(checkMode != RegistryKeyPermissionCheck.ReadSubTree, "We shouldn't allow writing value to read-only key!");
- BCLDebug.Assert(subKeyWritable == false, "subKeyWritable should be false (unused)");
- BCLDebug.Assert(subKeyCheck == RegistryKeyPermissionCheck.Default, "subKeyCheck should be Default (unused)");
- if( checkMode == RegistryKeyPermissionCheck.Default) {
- demand = true;
- GetSubTreeWritePermission(item, out access, out path);
- }
- }
- break;
- case RegistryInternalCheck.CheckSubTreeReadWritePermission:
- if (remoteKey) {
- CheckUnmanagedCodePermission();
- }
- else {
- BCLDebug.Assert(subKeyWritable == false, "subKeyWritable should be false (unused)");
- BCLDebug.Assert(subKeyCheck == RegistryKeyPermissionCheck.Default, "subKeyCheck should be Default (unused)");
- // If we want to open a subkey of a read-only key as writeable, we need to do the check.
- demand = true;
- GetSubTreeReadWritePermission(item, out access, out path);
- }
- break;
- //
- // Read/Write/Create Value Permission
- //
- case RegistryInternalCheck.CheckValueReadPermission:
- ///*** no remoteKey check ***///
- BCLDebug.Assert(subKeyWritable == false, "subKeyWritable should be false (unused)");
- BCLDebug.Assert(subKeyCheck == RegistryKeyPermissionCheck.Default, "subKeyCheck should be Default (unused)");
- if( checkMode == RegistryKeyPermissionCheck.Default) {
- // only need to check for default mode (dynamice check)
- demand = true;
- GetValueReadPermission(item, out access, out path);
- }
- break;
- case RegistryInternalCheck.CheckValueWritePermission:
- if (remoteKey) {
- CheckUnmanagedCodePermission();
- }
- else {
- BCLDebug.Assert(checkMode != RegistryKeyPermissionCheck.ReadSubTree, "We shouldn't allow writing value to read-only key!");
- BCLDebug.Assert(subKeyWritable == false, "subKeyWritable should be false (unused)");
- BCLDebug.Assert(subKeyCheck == RegistryKeyPermissionCheck.Default, "subKeyCheck should be Default (unused)");
- // skip the security check if the key is opened under write mode
- if( checkMode == RegistryKeyPermissionCheck.Default) {
- demand = true;
- GetValueWritePermission(item, out access, out path);
- }
- }
- break;
- case RegistryInternalCheck.CheckValueCreatePermission:
- if (remoteKey) {
- CheckUnmanagedCodePermission();
- }
- else {
- BCLDebug.Assert(checkMode != RegistryKeyPermissionCheck.ReadSubTree, "We shouldn't allow creating value under read-only key!");
- BCLDebug.Assert(subKeyWritable == false, "subKeyWritable should be false (unused)");
- BCLDebug.Assert(subKeyCheck == RegistryKeyPermissionCheck.Default, "subKeyCheck should be Default (unused)");
- // skip the security check if the key is opened under write mode
- if( checkMode == RegistryKeyPermissionCheck.Default) {
- demand = true;
- GetValueCreatePermission(item, out access, out path);
- }
- }
- break;
- //
- // CheckKeyReadPermission
- //
- case RegistryInternalCheck.CheckKeyReadPermission:
- ///*** no remoteKey check ***///
- if( checkMode == RegistryKeyPermissionCheck.Default) {
- BCLDebug.Assert(item == null, "CheckKeyReadPermission should never have a non-null item parameter!");
- BCLDebug.Assert(subKeyWritable == false, "subKeyWritable should be false (unused)");
- BCLDebug.Assert(subKeyCheck == RegistryKeyPermissionCheck.Default, "subKeyCheck should be Default (unused)");
-
- // only need to check for default mode (dynamice check)
- demand = true;
- GetKeyReadPermission(out access, out path);
- }
- break;
- //
- // CheckSubTreePermission
- //
- case RegistryInternalCheck.CheckSubTreePermission:
- BCLDebug.Assert(subKeyWritable == false, "subKeyWritable should be false (unused)");
- if( subKeyCheck == RegistryKeyPermissionCheck.ReadSubTree) {
- if( checkMode == RegistryKeyPermissionCheck.Default) {
- if( remoteKey) {
- CheckUnmanagedCodePermission();
- }
- else {
- demand = true;
- GetSubTreeReadPermission(item, out access, out path);
- }
- }
- }
- else if(subKeyCheck == RegistryKeyPermissionCheck.ReadWriteSubTree) {
- if( checkMode != RegistryKeyPermissionCheck.ReadWriteSubTree) {
- if( remoteKey) {
- CheckUnmanagedCodePermission();
- }
- else {
- demand = true;
- GetSubTreeReadWritePermission(item, out access, out path);
- }
- }
- }
- break;
-
- //
- // CheckOpenSubKeyWithWritablePermission uses the 'subKeyWritable' parameter
- //
- case RegistryInternalCheck.CheckOpenSubKeyWithWritablePermission:
- BCLDebug.Assert(subKeyCheck == RegistryKeyPermissionCheck.Default, "subKeyCheck should be Default (unused)");
- // If the parent key is not opened under default mode, we have access already.
- // If the parent key is opened under default mode, we need to check for permission.
- if(checkMode == RegistryKeyPermissionCheck.Default) {
- if( remoteKey) {
- CheckUnmanagedCodePermission();
- }
- else {
- demand = true;
- GetSubKeyReadPermission(item, out access, out path);
- }
- break;
- }
- if( subKeyWritable && (checkMode == RegistryKeyPermissionCheck.ReadSubTree)) {
- if( remoteKey) {
- CheckUnmanagedCodePermission();
- }
- else {
- demand = true;
- GetSubTreeReadWritePermission(item, out access, out path);
- }
- break;
- }
- break;
-
- //
- // CheckOpenSubKeyPermission uses the 'subKeyCheck' parameter
- //
- case RegistryInternalCheck.CheckOpenSubKeyPermission:
- BCLDebug.Assert(subKeyWritable == false, "subKeyWritable should be false (unused)");
- if(subKeyCheck == RegistryKeyPermissionCheck.Default) {
- if( checkMode == RegistryKeyPermissionCheck.Default) {
- if(remoteKey) {
- CheckUnmanagedCodePermission();
- }
- else {
- demand = true;
- GetSubKeyReadPermission(item, out access, out path);
- }
- }
- }
- break;
-
- default:
- BCLDebug.Assert(false, "CheckPermission default switch case should never be hit!");
- break;
- }
-
- if (demand) {
- new RegistryPermission(access, path).Demand();
- }
- }
-
- static private void CheckUnmanagedCodePermission() {
-#pragma warning disable 618
- new SecurityPermission(SecurityPermissionFlag.UnmanagedCode).Demand();
-#pragma warning restore 618
+ // TODO: Cleanup
}
private bool ContainsRegistryValue(string name) {
@@ -1798,26 +1080,6 @@ namespace Microsoft.Win32
return winAccess;
}
- static int GetRegistryKeyAccess(RegistryKeyPermissionCheck mode) {
- int winAccess = 0;
- switch(mode) {
- case RegistryKeyPermissionCheck.ReadSubTree:
- case RegistryKeyPermissionCheck.Default:
- winAccess = Win32Native.KEY_READ;
- break;
-
- case RegistryKeyPermissionCheck.ReadWriteSubTree:
- winAccess = Win32Native.KEY_READ| Win32Native.KEY_WRITE;
- break;
-
- default:
- BCLDebug.Assert(false, "unexpected code path");
- break;
- }
-
- return winAccess;
- }
-
private RegistryKeyPermissionCheck GetSubKeyPermissonCheck(bool subkeyWritable) {
if( checkMode == RegistryKeyPermissionCheck.Default) {
return checkMode;
@@ -1851,18 +1113,6 @@ namespace Microsoft.Win32
ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_RegKeyStrLenBug);
}
-
- static private void ValidateKeyMode(RegistryKeyPermissionCheck mode) {
- if( mode < RegistryKeyPermissionCheck.Default || mode > RegistryKeyPermissionCheck.ReadWriteSubTree) {
- ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_InvalidRegistryKeyPermissionCheck, ExceptionArgument.mode);
- }
- }
-
- static private void ValidateKeyOptions(RegistryOptions options) {
- if (options < RegistryOptions.None || options > RegistryOptions.Volatile) {
- ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_InvalidRegistryOptionsCheck, ExceptionArgument.options);
- }
- }
static private void ValidateKeyView(RegistryView view) {
if (view != RegistryView.Default && view != RegistryView.Registry32 && view != RegistryView.Registry64) {
@@ -1877,14 +1127,14 @@ namespace Microsoft.Win32
}
[Flags]
- public enum RegistryValueOptions {
+ internal enum RegistryValueOptions {
None = 0,
DoNotExpandEnvironmentNames = 1
}
// the name for this API is meant to mimic FileMode, which has similar values
- public enum RegistryKeyPermissionCheck {
+ internal enum RegistryKeyPermissionCheck {
Default = 0,
ReadSubTree = 1,
ReadWriteSubTree = 2
diff --git a/src/mscorlib/src/Microsoft/Win32/RegistryOptions.cs b/src/mscorlib/src/Microsoft/Win32/RegistryOptions.cs
deleted file mode 100644
index 4d5e3aaab1..0000000000
--- a/src/mscorlib/src/Microsoft/Win32/RegistryOptions.cs
+++ /dev/null
@@ -1,25 +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.
-
-//
-//
-//
-// Implements Microsoft.Win32.RegistryOptions
-//
-// ======================================================================================
-namespace Microsoft.Win32 {
- using System;
-
- [Flags]
- public enum RegistryOptions {
- None = Win32Native.REG_OPTION_NON_VOLATILE, // 0x0000
- Volatile = Win32Native.REG_OPTION_VOLATILE, // 0x0001
-///
-/// Consider exposing more options in a future release. Users can access this
-/// functionality by calling [RegistryKey].Handle and pinvoking
-///
-/// CreateLink = Win32Native.REG_OPTION_CREATE_LINK, // 0x0002
-/// BackupRestore = Win32Native.REG_OPTION_BACKUP_RESTORE,// 0x0004
- };
-}
diff --git a/src/mscorlib/src/Microsoft/Win32/RegistryValueKind.cs b/src/mscorlib/src/Microsoft/Win32/RegistryValueKind.cs
index c88d5f920a..5e22275332 100644
--- a/src/mscorlib/src/Microsoft/Win32/RegistryValueKind.cs
+++ b/src/mscorlib/src/Microsoft/Win32/RegistryValueKind.cs
@@ -4,8 +4,7 @@
namespace Microsoft.Win32 {
-[System.Runtime.InteropServices.ComVisible(true)]
- public enum RegistryValueKind {
+ internal enum RegistryValueKind {
String = Win32Native.REG_SZ,
ExpandString = Win32Native.REG_EXPAND_SZ,
Binary = Win32Native.REG_BINARY,
@@ -13,7 +12,6 @@ namespace Microsoft.Win32 {
MultiString = Win32Native.REG_MULTI_SZ,
QWord = Win32Native.REG_QWORD,
Unknown = 0, // REG_NONE is defined as zero but BCL
- [System.Runtime.InteropServices.ComVisible(false)]
None = unchecked((int)0xFFFFFFFF), // mistakingly overrode this value.
} // Now instead of using Win32Native.REG_NONE we use "-1" and play games internally.
}
diff --git a/src/mscorlib/src/Microsoft/Win32/RegistryView.cs b/src/mscorlib/src/Microsoft/Win32/RegistryView.cs
index 7fbc2b3391..302a603e0c 100644
--- a/src/mscorlib/src/Microsoft/Win32/RegistryView.cs
+++ b/src/mscorlib/src/Microsoft/Win32/RegistryView.cs
@@ -11,7 +11,7 @@
namespace Microsoft.Win32 {
using System;
- public enum RegistryView {
+ internal enum RegistryView {
Default = 0, // 0x0000 operate on the default registry view
Registry64 = Win32Native.KEY_WOW64_64KEY, // 0x0100 operate on the 64-bit registry view
Registry32 = Win32Native.KEY_WOW64_32KEY, // 0x0200 operate on the 32-bit registry view
diff --git a/src/mscorlib/src/Microsoft/Win32/SafeHandles/SafeFileMappingHandle.cs b/src/mscorlib/src/Microsoft/Win32/SafeHandles/SafeFileMappingHandle.cs
deleted file mode 100644
index cb915fe7c3..0000000000
--- a/src/mscorlib/src/Microsoft/Win32/SafeHandles/SafeFileMappingHandle.cs
+++ /dev/null
@@ -1,39 +0,0 @@
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-// See the LICENSE file in the project root for more information.
-
-/*============================================================
-**
-**
-**
-** 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;
-
-namespace Microsoft.Win32.SafeHandles
-{
- internal sealed class SafeFileMappingHandle : SafeHandleZeroOrMinusOneIsInvalid
- {
- internal SafeFileMappingHandle() : base(true) {}
-
- // 0 is an Invalid Handle
- internal SafeFileMappingHandle(IntPtr handle, bool ownsHandle) : base (ownsHandle)
- {
- SetHandle(handle);
- }
-
- 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 219fb77001..89ea22b855 100644
--- a/src/mscorlib/src/Microsoft/Win32/SafeHandles/SafeFindHandle.cs
+++ b/src/mscorlib/src/Microsoft/Win32/SafeHandles/SafeFindHandle.cs
@@ -13,7 +13,6 @@
using System;
using System.Security;
-using System.Security.Permissions;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
using System.Runtime.ConstrainedExecution;
diff --git a/src/mscorlib/src/Microsoft/Win32/SafeHandles/SafeLibraryHandle.cs b/src/mscorlib/src/Microsoft/Win32/SafeHandles/SafeLibraryHandle.cs
index 23631987a5..603558c51a 100644
--- a/src/mscorlib/src/Microsoft/Win32/SafeHandles/SafeLibraryHandle.cs
+++ b/src/mscorlib/src/Microsoft/Win32/SafeHandles/SafeLibraryHandle.cs
@@ -4,7 +4,6 @@
namespace Microsoft.Win32 {
using Microsoft.Win32.SafeHandles;
- using System.Security.Permissions;
sealed internal class SafeLibraryHandle : SafeHandleZeroOrMinusOneIsInvalid {
internal SafeLibraryHandle() : base(true) {}
diff --git a/src/mscorlib/src/Microsoft/Win32/SafeHandles/SafeLocalAllocHandle.cs b/src/mscorlib/src/Microsoft/Win32/SafeHandles/SafeLocalAllocHandle.cs
deleted file mode 100644
index d6c1577eeb..0000000000
--- a/src/mscorlib/src/Microsoft/Win32/SafeHandles/SafeLocalAllocHandle.cs
+++ /dev/null
@@ -1,29 +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 Microsoft.Win32.SafeHandles
-{
- using System;
- using System.Runtime.CompilerServices;
- using System.Runtime.InteropServices;
- using System.Runtime.ConstrainedExecution;
-
- internal sealed class SafeLocalAllocHandle : SafeBuffer {
- private SafeLocalAllocHandle () : base(true) {}
-
- // 0 is an Invalid Handle
- internal SafeLocalAllocHandle (IntPtr handle) : base (true) {
- SetHandle(handle);
- }
-
- internal static SafeLocalAllocHandle InvalidHandle {
- get { return new SafeLocalAllocHandle(IntPtr.Zero); }
- }
-
- 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 4f96b81e72..a1e5bc4263 100644
--- a/src/mscorlib/src/Microsoft/Win32/SafeHandles/SafeRegistryHandle.cs
+++ b/src/mscorlib/src/Microsoft/Win32/SafeHandles/SafeRegistryHandle.cs
@@ -11,13 +11,12 @@
namespace Microsoft.Win32.SafeHandles {
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;
- public sealed class SafeRegistryHandle : SafeHandleZeroOrMinusOneIsInvalid {
+ internal sealed class SafeRegistryHandle : SafeHandleZeroOrMinusOneIsInvalid {
internal SafeRegistryHandle() : base(true) {}
public SafeRegistryHandle(IntPtr preexistingHandle, bool ownsHandle) : base(ownsHandle) {
@@ -30,7 +29,6 @@ namespace Microsoft.Win32.SafeHandles {
[DllImport(Win32Native.ADVAPI32)]
[SuppressUnmanagedCodeSecurity]
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
internal static extern int RegCloseKey(IntPtr hKey);
}
}
diff --git a/src/mscorlib/src/Microsoft/Win32/SafeHandles/SafeViewOfFileHandle.cs b/src/mscorlib/src/Microsoft/Win32/SafeHandles/SafeViewOfFileHandle.cs
deleted file mode 100644
index 38a9323c0b..0000000000
--- a/src/mscorlib/src/Microsoft/Win32/SafeHandles/SafeViewOfFileHandle.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.
-
-/*============================================================
-**
-**
-**
-** 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;
-using Microsoft.Win32.SafeHandles;
-
-namespace Microsoft.Win32.SafeHandles
-{
- internal sealed class SafeViewOfFileHandle : SafeHandleZeroOrMinusOneIsInvalid
- {
- internal SafeViewOfFileHandle() : base(true) {}
-
- // 0 is an Invalid Handle
- internal SafeViewOfFileHandle(IntPtr handle, bool ownsHandle) : base (ownsHandle) {
- SetHandle(handle);
- }
-
- override protected bool ReleaseHandle()
- {
- if (Win32Native.UnmapViewOfFile(handle))
- {
- handle = IntPtr.Zero;
- return true;
- }
-
- return false;
- }
- }
-}
-
diff --git a/src/mscorlib/src/Microsoft/Win32/SafeHandles/SafeWaitHandle.cs b/src/mscorlib/src/Microsoft/Win32/SafeHandles/SafeWaitHandle.cs
index 0e57136952..0ebcd5c09e 100644
--- a/src/mscorlib/src/Microsoft/Win32/SafeHandles/SafeWaitHandle.cs
+++ b/src/mscorlib/src/Microsoft/Win32/SafeHandles/SafeWaitHandle.cs
@@ -14,7 +14,6 @@
using System;
using System.Security;
-using System.Security.Permissions;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
using System.Runtime.ConstrainedExecution;
@@ -31,7 +30,6 @@ namespace Microsoft.Win32.SafeHandles {
{
}
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
public SafeWaitHandle(IntPtr existingHandle, bool ownsHandle) : base(ownsHandle)
{
SetHandle(existingHandle);
diff --git a/src/mscorlib/src/Microsoft/Win32/SafeHandles/Win32SafeHandles.cs b/src/mscorlib/src/Microsoft/Win32/SafeHandles/Win32SafeHandles.cs
index 08ae0955a8..62418131f3 100644
--- a/src/mscorlib/src/Microsoft/Win32/SafeHandles/Win32SafeHandles.cs
+++ b/src/mscorlib/src/Microsoft/Win32/SafeHandles/Win32SafeHandles.cs
@@ -18,13 +18,11 @@ namespace Microsoft.Win32.SafeHandles
using System;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
- using System.Security.Permissions;
using System.Runtime.ConstrainedExecution;
// Class of safe handle which uses 0 or -1 as an invalid handle.
public abstract class SafeHandleZeroOrMinusOneIsInvalid : SafeHandle
{
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
protected SafeHandleZeroOrMinusOneIsInvalid(bool ownsHandle) : base(IntPtr.Zero, ownsHandle)
{
}
@@ -43,7 +41,6 @@ namespace Microsoft.Win32.SafeHandles
// Class of safe handle which uses only -1 as an invalid handle.
public abstract class SafeHandleMinusOneIsInvalid : SafeHandle
{
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
protected SafeHandleMinusOneIsInvalid(bool ownsHandle) : base(new IntPtr(-1), ownsHandle)
{
}
@@ -62,7 +59,6 @@ namespace Microsoft.Win32.SafeHandles
// Class of critical handle which uses 0 or -1 as an invalid handle.
public abstract class CriticalHandleZeroOrMinusOneIsInvalid : CriticalHandle
{
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
protected CriticalHandleZeroOrMinusOneIsInvalid() : base(IntPtr.Zero)
{
}
@@ -75,7 +71,6 @@ namespace Microsoft.Win32.SafeHandles
// Class of critical handle which uses only -1 as an invalid handle.
public abstract class CriticalHandleMinusOneIsInvalid : CriticalHandle
{
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
protected CriticalHandleMinusOneIsInvalid() : base(new IntPtr(-1))
{
}
diff --git a/src/mscorlib/src/Microsoft/Win32/UnsafeNativeMethods.cs b/src/mscorlib/src/Microsoft/Win32/UnsafeNativeMethods.cs
index 19d638d61a..6e37b9c878 100644
--- a/src/mscorlib/src/Microsoft/Win32/UnsafeNativeMethods.cs
+++ b/src/mscorlib/src/Microsoft/Win32/UnsafeNativeMethods.cs
@@ -12,7 +12,6 @@ namespace Microsoft.Win32 {
using System.Runtime.Serialization;
using System.Runtime.Versioning;
using System.Security;
- using System.Security.Permissions;
using System.Text;
using System.Diagnostics.Tracing;
@@ -59,7 +58,6 @@ namespace Microsoft.Win32 {
[DllImport(Win32Native.KERNEL32, CharSet=System.Runtime.InteropServices.CharSet.Unicode)]
[return: MarshalAs(UnmanagedType.Bool)]
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
internal static extern bool FreeLibrary(IntPtr hModule);
@@ -120,19 +118,6 @@ namespace Microsoft.Win32 {
[DllImport(Win32Native.ADVAPI32, ExactSpelling = true, EntryPoint = "EventUnregister", CharSet = System.Runtime.InteropServices.CharSet.Unicode)]
internal static extern uint EventUnregister([In] long registrationHandle);
- //
- // Writing (Publishing/Logging) APIs
- //
- //
- [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(
- [In] long registrationHandle,
- [In] ref EventDescriptor eventDescriptor,
- [In] int userDataCount,
- [In] EventProvider.EventData* userData
- );
-
[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(
diff --git a/src/mscorlib/src/Microsoft/Win32/Win32Native.cs b/src/mscorlib/src/Microsoft/Win32/Win32Native.cs
index b5b808b424..b081b16ca1 100644
--- a/src/mscorlib/src/Microsoft/Win32/Win32Native.cs
+++ b/src/mscorlib/src/Microsoft/Win32/Win32Native.cs
@@ -155,42 +155,6 @@ namespace Microsoft.Win32 {
internal const int HWND_BROADCAST = 0xffff;
internal const int WM_SETTINGCHANGE = 0x001A;
- // CryptProtectMemory and CryptUnprotectMemory.
- internal const uint CRYPTPROTECTMEMORY_BLOCK_SIZE = 16;
- internal const uint CRYPTPROTECTMEMORY_SAME_PROCESS = 0x00;
- internal const uint CRYPTPROTECTMEMORY_CROSS_PROCESS = 0x01;
- internal const uint CRYPTPROTECTMEMORY_SAME_LOGON = 0x02;
-
- // Security Quality of Service flags
- internal const int SECURITY_ANONYMOUS = ((int)SECURITY_IMPERSONATION_LEVEL.Anonymous << 16);
- internal const int SECURITY_SQOS_PRESENT = 0x00100000;
-
- // Access Control library.
- internal const string MICROSOFT_KERBEROS_NAME = "Kerberos";
- internal const uint ANONYMOUS_LOGON_LUID = 0x3e6;
-
- internal const int SECURITY_ANONYMOUS_LOGON_RID = 0x00000007;
- internal const int SECURITY_AUTHENTICATED_USER_RID = 0x0000000B;
- internal const int SECURITY_LOCAL_SYSTEM_RID = 0x00000012;
- internal const int SECURITY_BUILTIN_DOMAIN_RID = 0x00000020;
-
- internal const uint SE_PRIVILEGE_DISABLED = 0x00000000;
- internal const uint SE_PRIVILEGE_ENABLED_BY_DEFAULT = 0x00000001;
- internal const uint SE_PRIVILEGE_ENABLED = 0x00000002;
- internal const uint SE_PRIVILEGE_USED_FOR_ACCESS = 0x80000000;
-
- internal const uint SE_GROUP_MANDATORY = 0x00000001;
- internal const uint SE_GROUP_ENABLED_BY_DEFAULT = 0x00000002;
- internal const uint SE_GROUP_ENABLED = 0x00000004;
- internal const uint SE_GROUP_OWNER = 0x00000008;
- internal const uint SE_GROUP_USE_FOR_DENY_ONLY = 0x00000010;
- internal const uint SE_GROUP_LOGON_ID = 0xC0000000;
- internal const uint SE_GROUP_RESOURCE = 0x20000000;
-
- internal const uint DUPLICATE_CLOSE_SOURCE = 0x00000001;
- internal const uint DUPLICATE_SAME_ACCESS = 0x00000002;
- internal const uint DUPLICATE_SAME_ATTRIBUTES = 0x00000004;
-
// TimeZone
internal const int TIME_ZONE_ID_INVALID = -1;
internal const int TIME_ZONE_ID_UNKNOWN = 0;
@@ -416,20 +380,6 @@ namespace Microsoft.Win32 {
}
[StructLayout(LayoutKind.Sequential)]
- internal struct SYSTEM_INFO {
- internal int dwOemId; // This is a union of a DWORD and a struct containing 2 WORDs.
- internal int dwPageSize;
- internal IntPtr lpMinimumApplicationAddress;
- internal IntPtr lpMaximumApplicationAddress;
- internal IntPtr dwActiveProcessorMask;
- internal int dwNumberOfProcessors;
- internal int dwProcessorType;
- internal int dwAllocationGranularity;
- internal short wProcessorLevel;
- internal short wProcessorRevision;
- }
-
- [StructLayout(LayoutKind.Sequential)]
internal class SECURITY_ATTRIBUTES {
internal int nLength = 0;
// don't remove null, or this field will disappear in bcl.small
@@ -465,206 +415,6 @@ namespace Microsoft.Win32 {
}
[StructLayout(LayoutKind.Sequential)]
- internal struct FILE_TIME {
- public FILE_TIME(long fileTime) {
- ftTimeLow = (uint) fileTime;
- ftTimeHigh = (uint) (fileTime >> 32);
- }
-
- public long ToTicks() {
- return ((long) ftTimeHigh << 32) + ftTimeLow;
- }
-
- internal uint ftTimeLow;
- internal uint ftTimeHigh;
- }
-
- [StructLayout(LayoutKind.Sequential, CharSet=CharSet.Unicode)]
- internal struct KERB_S4U_LOGON {
- internal uint MessageType;
- internal uint Flags;
- internal UNICODE_INTPTR_STRING ClientUpn; // REQUIRED: UPN for client
- internal UNICODE_INTPTR_STRING ClientRealm; // Optional: Client Realm, if known
- }
-
- [StructLayoutAttribute(LayoutKind.Sequential)]
- internal struct LSA_OBJECT_ATTRIBUTES {
- internal int Length;
- internal IntPtr RootDirectory;
- internal IntPtr ObjectName;
- internal int Attributes;
- internal IntPtr SecurityDescriptor;
- internal IntPtr SecurityQualityOfService;
- }
-
- [StructLayout(LayoutKind.Sequential, CharSet=CharSet.Unicode)]
- internal struct UNICODE_STRING {
- internal ushort Length;
- internal ushort MaximumLength;
- [MarshalAs(UnmanagedType.LPWStr)] internal string Buffer;
- }
-
- [StructLayout(LayoutKind.Sequential, CharSet=CharSet.Unicode)]
- internal struct UNICODE_INTPTR_STRING {
- /// <remarks>
- /// Note - this constructor extracts the raw pointer from the safe handle, so any
- /// strings created with this version of the constructor will be unsafe to use after the buffer
- /// has been freed.
- /// </remarks>
- 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)");
-
- this.Length = (ushort) stringBytes;
- this.MaxLength = (ushort) buffer.ByteLength;
-
- // Marshaling with a SafePointer does not work correctly, so unfortunately we need to extract
- // the raw handle here.
- this.Buffer = buffer.DangerousGetHandle();
- }
-
- /// <remarks>
- /// This constructor should be used for constructing UNICODE_STRING structures with pointers
- /// into a block of memory managed by a SafeHandle or the GC. It shouldn't be used to own
- /// any memory on its own.
- /// </remarks>
- internal UNICODE_INTPTR_STRING(int stringBytes, IntPtr buffer) {
- BCLDebug.Assert((stringBytes == 0 && buffer == IntPtr.Zero) || (stringBytes > 0 && stringBytes <= UInt16.MaxValue && buffer != IntPtr.Zero),
- "(stringBytes == 0 && buffer == IntPtr.Zero) || (stringBytes > 0 && stringBytes <= UInt16.MaxValue && buffer != IntPtr.Zero)");
-
- this.Length = (ushort)stringBytes;
- this.MaxLength = (ushort)stringBytes;
- this.Buffer = buffer;
- }
-
- internal ushort Length;
- internal ushort MaxLength;
- internal IntPtr Buffer;
- }
-
- [StructLayout(LayoutKind.Sequential)]
- internal struct LSA_TRANSLATED_NAME {
- internal int Use;
- internal UNICODE_INTPTR_STRING Name;
- internal int DomainIndex;
- }
-
- [StructLayoutAttribute(LayoutKind.Sequential)]
- internal struct LSA_TRANSLATED_SID {
- internal int Use;
- internal uint Rid;
- internal int DomainIndex;
- }
-
- [StructLayoutAttribute(LayoutKind.Sequential)]
- internal struct LSA_TRANSLATED_SID2 {
- internal int Use;
- internal IntPtr Sid;
- internal int DomainIndex;
- uint Flags;
- }
-
- [StructLayout(LayoutKind.Sequential)]
- internal struct LSA_TRUST_INFORMATION {
- internal UNICODE_INTPTR_STRING Name;
- internal IntPtr Sid;
- }
-
- [StructLayout(LayoutKind.Sequential)]
- internal struct LSA_REFERENCED_DOMAIN_LIST {
- internal int Entries;
- internal IntPtr Domains;
- }
-
- [StructLayout(LayoutKind.Sequential, CharSet=CharSet.Unicode)]
- internal struct LUID {
- internal uint LowPart;
- internal uint HighPart;
- }
-
- [StructLayout(LayoutKind.Sequential, CharSet=CharSet.Unicode)]
- internal struct LUID_AND_ATTRIBUTES {
- internal LUID Luid;
- internal uint Attributes;
- }
-
- [StructLayout(LayoutKind.Sequential, CharSet=CharSet.Unicode)]
- internal struct QUOTA_LIMITS {
- internal IntPtr PagedPoolLimit;
- internal IntPtr NonPagedPoolLimit;
- internal IntPtr MinimumWorkingSetSize;
- internal IntPtr MaximumWorkingSetSize;
- internal IntPtr PagefileLimit;
- internal IntPtr TimeLimit;
- }
-
- [StructLayout(LayoutKind.Sequential, CharSet=CharSet.Unicode)]
- internal struct SECURITY_LOGON_SESSION_DATA {
- internal uint Size;
- internal LUID LogonId;
- internal UNICODE_INTPTR_STRING UserName;
- internal UNICODE_INTPTR_STRING LogonDomain;
- internal UNICODE_INTPTR_STRING AuthenticationPackage;
- internal uint LogonType;
- internal uint Session;
- internal IntPtr Sid;
- internal long LogonTime;
- }
-
- [StructLayout(LayoutKind.Sequential, CharSet=CharSet.Unicode)]
- internal struct SID_AND_ATTRIBUTES {
- internal IntPtr Sid;
- internal uint Attributes;
- internal static readonly long SizeOf = (long)Marshal.SizeOf(typeof(SID_AND_ATTRIBUTES));
- }
-
- [StructLayout(LayoutKind.Sequential, CharSet=CharSet.Unicode)]
- internal struct TOKEN_GROUPS {
- internal uint GroupCount;
- internal SID_AND_ATTRIBUTES Groups; // SID_AND_ATTRIBUTES Groups[ANYSIZE_ARRAY];
- }
-
- [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
- internal struct TOKEN_PRIMARY_GROUP
- {
- internal IntPtr PrimaryGroup;
- }
-
- [StructLayout(LayoutKind.Sequential, CharSet=CharSet.Unicode)]
- internal struct TOKEN_PRIVILEGE {
- internal uint PrivilegeCount;
- internal LUID_AND_ATTRIBUTES Privilege;
- }
-
- [StructLayout(LayoutKind.Sequential, CharSet=CharSet.Unicode)]
- internal struct TOKEN_SOURCE {
- private const int TOKEN_SOURCE_LENGTH = 8;
-
- [MarshalAs(UnmanagedType.ByValArray, SizeConst=TOKEN_SOURCE_LENGTH)]
- internal char[] Name;
- internal LUID SourceIdentifier;
- }
-
- [StructLayout(LayoutKind.Sequential, CharSet=CharSet.Unicode)]
- internal struct TOKEN_STATISTICS {
- internal LUID TokenId;
- internal LUID AuthenticationId;
- internal long ExpirationTime;
- internal uint TokenType;
- internal uint ImpersonationLevel;
- internal uint DynamicCharged;
- internal uint DynamicAvailable;
- internal uint GroupCount;
- internal uint PrivilegeCount;
- internal LUID ModifiedId;
- }
-
- [StructLayout(LayoutKind.Sequential, CharSet=CharSet.Unicode)]
- internal struct TOKEN_USER {
- internal SID_AND_ATTRIBUTES User;
- }
-
- [StructLayout(LayoutKind.Sequential)]
internal struct MEMORYSTATUSEX {
// The length field must be set to the size of this data structure.
internal int length;
@@ -707,18 +457,11 @@ namespace Microsoft.Win32 {
internal const String SHIM = "mscoree.dll";
internal const String CRYPT32 = "crypt32.dll";
internal const String SECUR32 = "secur32.dll";
-#if FEATURE_MAIN_CLR_MODULE_USES_CORE_NAME
internal const String MSCORWKS = "coreclr.dll";
-#else //FEATURE_MAIN_CLR_MODULE_USES_CORE_NAME
- internal const String MSCORWKS = "clr.dll";
-#endif //FEATURE_MAIN_CLR_MODULE_USES_CORE_NAME
// From WinBase.h
internal const int SEM_FAILCRITICALERRORS = 1;
- [DllImport(KERNEL32, SetLastError=true)]
- internal static extern void GetSystemInfo(ref SYSTEM_INFO lpSystemInfo);
-
[DllImport(KERNEL32, CharSet=CharSet.Auto, BestFitMapping=true)]
internal static extern int FormatMessage(int dwFlags, IntPtr lpSource,
int dwMessageId, int dwLanguageId, [Out]StringBuilder lpBuffer,
@@ -741,22 +484,13 @@ namespace Microsoft.Win32 {
}
[DllImport(KERNEL32, EntryPoint="LocalAlloc")]
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
internal static extern IntPtr LocalAlloc_NoSafeHandle(int uFlags, UIntPtr sizetdwBytes);
- [DllImport(KERNEL32, CharSet=CharSet.Auto, SetLastError=true)]
- internal static extern
- SafeLocalAllocHandle LocalAlloc(
- [In] int uFlags,
- [In] UIntPtr sizetdwBytes);
-
[DllImport(KERNEL32, SetLastError=true)]
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
internal static extern IntPtr LocalFree(IntPtr handle);
// MSDN says the length is a SIZE_T.
[DllImport(NTDLL, EntryPoint = "RtlZeroMemory")]
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
internal static extern void ZeroMemory(IntPtr address, UIntPtr length);
internal static bool GlobalMemoryStatusEx(ref MEMORYSTATUSEX buffer)
@@ -775,52 +509,11 @@ namespace Microsoft.Win32 {
// the MemoryFailPoint implementation (within a CER) to increase the
// size of the page file, ignoring any host memory allocators.
[DllImport(KERNEL32, SetLastError=true)]
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
unsafe internal static extern void * VirtualAlloc(void* address, UIntPtr numBytes, int commitOrReserve, int pageProtectionMode);
[DllImport(KERNEL32, SetLastError=true)]
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
unsafe internal static extern bool VirtualFree(void* address, UIntPtr numBytes, int pageFreeMode);
-
-
- // Note - do NOT use this to call methods. Use P/Invoke, which will
- // do much better things w.r.t. marshaling, pinning memory, security
- // stuff, better interactions with thread aborts, etc. This is used
- // solely by DoesWin32MethodExist for avoiding try/catch EntryPointNotFoundException
- // in scenarios where an OS Version check is insufficient
- [DllImport(KERNEL32, CharSet=CharSet.Ansi, BestFitMapping=false, SetLastError=true, ExactSpelling=true)]
- private static extern IntPtr GetProcAddress(IntPtr hModule, String methodName);
-
- [DllImport(KERNEL32, CharSet=CharSet.Auto, BestFitMapping=false, SetLastError=true)]
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
- private static extern IntPtr GetModuleHandle(String moduleName);
-
- 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.
- IntPtr hModule = Win32Native.GetModuleHandle(moduleName);
- if (hModule == IntPtr.Zero) {
- BCLDebug.Assert(hModule != IntPtr.Zero, "GetModuleHandle failed. Dll isn't loaded?");
- return false;
- }
- IntPtr functionPointer = Win32Native.GetProcAddress(hModule, methodName);
- return (functionPointer != IntPtr.Zero);
- }
-
- // There is no need to call CloseProcess or to use a SafeHandle if you get the handle
- // using GetCurrentProcess as it returns a pseudohandle
- [DllImport(KERNEL32, SetLastError = true, CallingConvention = CallingConvention.Winapi)]
- [return: MarshalAs(UnmanagedType.Bool)]
- internal static extern bool IsWow64Process(
- [In]
- IntPtr hSourceProcessHandle,
- [Out, MarshalAs(UnmanagedType.Bool)]
- out bool isWow64);
-
- [DllImport(KERNEL32, CharSet=CharSet.Auto, BestFitMapping=false)]
- internal static extern uint GetTempPath(int bufferLen, [Out]StringBuilder buffer);
-
[DllImport(KERNEL32, CharSet=CharSet.Ansi, ExactSpelling=true, EntryPoint="lstrlenA")]
internal static extern int lstrlenA(IntPtr ptr);
@@ -828,37 +521,23 @@ namespace Microsoft.Win32 {
internal static extern int lstrlenW(IntPtr ptr);
[DllImport(Win32Native.OLEAUT32, CharSet = CharSet.Unicode)]
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
internal static extern IntPtr SysAllocStringLen(String src, int len); // BSTR
[DllImport(Win32Native.OLEAUT32)]
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
internal static extern uint SysStringLen(IntPtr bstr);
[DllImport(Win32Native.OLEAUT32)]
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
internal static extern void SysFreeString(IntPtr bstr);
#if FEATURE_COMINTEROP
[DllImport(Win32Native.OLEAUT32)]
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
internal static extern IntPtr SysAllocStringByteLen(byte[] str, uint len); // BSTR
[DllImport(Win32Native.OLEAUT32)]
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
internal static extern uint SysStringByteLen(IntPtr bstr);
-#if FEATURE_LEGACYSURFACE
- [DllImport(Win32Native.OLEAUT32)]
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
- internal static extern uint SysStringLen(SafeBSTRHandle bstr);
#endif
-#endif
-
- [DllImport(KERNEL32)]
- internal static extern int GetACP();
-
[DllImport(KERNEL32, SetLastError=true)]
internal static extern bool SetEvent(SafeWaitHandle handle);
@@ -872,134 +551,24 @@ namespace Microsoft.Win32 {
internal static extern SafeWaitHandle OpenEvent(/* DWORD */ int desiredAccess, bool inheritHandle, String name);
[DllImport(KERNEL32, SetLastError=true, CharSet=CharSet.Auto, BestFitMapping=false)]
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
internal static extern SafeWaitHandle CreateMutex(SECURITY_ATTRIBUTES lpSecurityAttributes, bool initialOwner, String name);
[DllImport(KERNEL32, SetLastError=true, CharSet=CharSet.Auto, BestFitMapping=false)]
internal static extern SafeWaitHandle OpenMutex(/* DWORD */ int desiredAccess, bool inheritHandle, String name);
[DllImport(KERNEL32, SetLastError=true)]
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
internal static extern bool ReleaseMutex(SafeWaitHandle handle);
- [DllImport(KERNEL32, SetLastError = true, CharSet = CharSet.Auto, BestFitMapping = false)]
- internal unsafe static extern int GetFullPathName(char* path, int numBufferChars, char* buffer, IntPtr mustBeZero);
-
- [DllImport(KERNEL32, SetLastError=true, CharSet=CharSet.Auto, BestFitMapping=false)]
- internal unsafe static extern int GetFullPathName(String path, int numBufferChars, [Out]StringBuilder buffer, IntPtr mustBeZero);
-
- [DllImport(KERNEL32, SetLastError = true, CharSet = CharSet.Auto, BestFitMapping = false)]
- internal unsafe static extern int GetLongPathName(char* path, char* longPathBuffer, int bufferLength);
-
- [DllImport(KERNEL32, SetLastError = true, ExactSpelling = true)]
- internal unsafe static extern uint GetFullPathNameW(char* path, uint numBufferChars, SafeHandle buffer, IntPtr mustBeZero);
-
- [DllImport(KERNEL32, SetLastError = true, CharSet = CharSet.Auto, BestFitMapping = false)]
- internal static extern int GetLongPathName(String path, [Out]StringBuilder longPathBuffer, int bufferLength);
-
- [DllImport(KERNEL32, SetLastError = true, ExactSpelling = true)]
- internal static extern uint GetLongPathNameW(SafeHandle lpszShortPath, SafeHandle lpszLongPath, uint cchBuffer);
-
- [DllImport(KERNEL32, SetLastError = true, CharSet = CharSet.Unicode, ExactSpelling = true)]
- internal static extern uint GetLongPathNameW(string lpszShortPath, SafeHandle lpszLongPath, uint cchBuffer);
-
- [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);
-
- [DllImport(KERNEL32, SetLastError=true, ExactSpelling=true)]
- internal static extern IntPtr MapViewOfFile(
- SafeFileMappingHandle handle, uint dwDesiredAccess, uint dwFileOffsetHigh, uint dwFileOffsetLow, UIntPtr dwNumerOfBytesToMap);
-
- [DllImport(KERNEL32, ExactSpelling=true)]
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
- internal static extern bool UnmapViewOfFile(IntPtr lpBaseAddress );
-
[DllImport(KERNEL32, SetLastError=true)]
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
internal static extern bool CloseHandle(IntPtr handle);
- [DllImport(KERNEL32)]
- internal static extern int GetFileType(SafeFileHandle handle);
-
- [DllImport(KERNEL32, SetLastError=true)]
- internal static extern bool SetEndOfFile(SafeFileHandle hFile);
-
- [DllImport(KERNEL32, SetLastError = true)]
- [return: MarshalAs(UnmanagedType.Bool)]
- internal static extern bool FlushFileBuffers(SafeFileHandle hFile);
-
- [DllImport(KERNEL32, SetLastError=true, EntryPoint="SetFilePointer")]
- private unsafe static extern int SetFilePointerWin32(SafeFileHandle handle, int lo, int * hi, int origin);
-
- internal unsafe static long SetFilePointer(SafeFileHandle handle, long offset, System.IO.SeekOrigin origin, out int hr) {
- hr = 0;
- int lo = (int) offset;
- int hi = (int) (offset >> 32);
- lo = SetFilePointerWin32(handle, lo, &hi, (int) origin);
-
- if (lo == -1 && ((hr = Marshal.GetLastWin32Error()) != 0))
- return -1;
- return (long) (((ulong) ((uint) hi)) << 32) | ((uint) lo);
- }
-
- // Note there are two different ReadFile prototypes - this is to use
- // the type system to force you to not trip across a "feature" in
- // Win32's async IO support. You can't do the following three things
- // simultaneously: overlapped IO, free the memory for the overlapped
- // struct in a callback (or an EndRead method called by that callback),
- // and pass in an address for the numBytesRead parameter.
-
- [DllImport(KERNEL32, SetLastError=true)]
- unsafe internal static extern int ReadFile(SafeFileHandle handle, byte* bytes, int numBytesToRead, IntPtr numBytesRead_mustBeZero, NativeOverlapped* overlapped);
-
- [DllImport(KERNEL32, SetLastError=true)]
- unsafe internal static extern int ReadFile(SafeFileHandle handle, byte* bytes, int numBytesToRead, out int numBytesRead, IntPtr mustBeZero);
-
- // Note there are two different WriteFile prototypes - this is to use
- // the type system to force you to not trip across a "feature" in
- // Win32's async IO support. You can't do the following three things
- // simultaneously: overlapped IO, free the memory for the overlapped
- // struct in a callback (or an EndWrite method called by that callback),
- // and pass in an address for the numBytesRead parameter.
-
- [DllImport(KERNEL32, SetLastError=true)]
- internal static unsafe extern int WriteFile(SafeFileHandle handle, byte* bytes, int numBytesToWrite, IntPtr numBytesWritten_mustBeZero, NativeOverlapped* lpOverlapped);
-
[DllImport(KERNEL32, SetLastError=true)]
internal static unsafe extern int WriteFile(SafeFileHandle handle, byte* bytes, int numBytesToWrite, out int numBytesWritten, IntPtr mustBeZero);
- // This is only available on Vista or higher
- [DllImport(KERNEL32, SetLastError=true)]
- internal static unsafe extern bool CancelIoEx(SafeFileHandle handle, NativeOverlapped* lpOverlapped);
-
- // NOTE: The out parameters are PULARGE_INTEGERs and may require
- // some byte munging magic.
- [DllImport(KERNEL32, CharSet=CharSet.Auto, SetLastError=true, BestFitMapping=false)]
- internal static extern bool GetDiskFreeSpaceEx(String drive, out long freeBytesForUser, out long totalBytes, out long freeBytes);
-
- [DllImport(KERNEL32, CharSet=CharSet.Auto, SetLastError=true, BestFitMapping=false)]
- internal static extern int GetDriveType(String drive);
-
- [DllImport(KERNEL32, CharSet=CharSet.Auto, SetLastError=true, BestFitMapping=false)]
- internal static extern bool GetVolumeInformation(String drive, [Out]StringBuilder volumeName, int volumeNameBufLen, out int volSerialNumber, out int maxFileNameLen, out int fileSystemFlags, [Out]StringBuilder fileSystemName, int fileSystemNameBufLen);
-
- [DllImport(KERNEL32, CharSet=CharSet.Auto, SetLastError=true, BestFitMapping=false)]
- internal static extern bool SetVolumeLabel(String driveLetter, String volumeName);
-
- // The following 4 methods are used by Microsoft.WlcProfile
- [DllImport(KERNEL32)]
- [return: MarshalAs(UnmanagedType.Bool)]
- internal static extern bool QueryPerformanceCounter(out long value);
-
- [DllImport(KERNEL32)]
- [return: MarshalAs(UnmanagedType.Bool)]
- internal static extern bool QueryPerformanceFrequency(out long value);
-
[DllImport(KERNEL32, SetLastError = true, CharSet = CharSet.Auto, BestFitMapping = false)]
internal static extern SafeWaitHandle CreateSemaphore(SECURITY_ATTRIBUTES lpSecurityAttributes, int initialCount, int maximumCount, String name);
[DllImport(KERNEL32, SetLastError = true)]
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool ReleaseSemaphore(SafeWaitHandle handle, int releaseCount, out int previousCount);
@@ -1023,24 +592,8 @@ namespace Microsoft.Win32 {
}
[DllImport(KERNEL32, CharSet=CharSet.Auto, SetLastError=true, BestFitMapping=false)]
- internal static extern int GetWindowsDirectory([Out]StringBuilder sb, int length);
-
- [DllImport(KERNEL32, CharSet=CharSet.Auto, SetLastError=true, BestFitMapping=false)]
internal static extern int GetSystemDirectory([Out]StringBuilder sb, int length);
- [DllImport(KERNEL32, SetLastError=true)]
- internal unsafe static extern bool SetFileTime(SafeFileHandle hFile, FILE_TIME* creationTime,
- FILE_TIME* lastAccessTime, FILE_TIME* lastWriteTime);
-
- [DllImport(KERNEL32, SetLastError=true)]
- internal static extern int GetFileSize(SafeFileHandle hFile, out int highSize);
-
- [DllImport(KERNEL32, SetLastError=true)]
- internal static extern bool LockFile(SafeFileHandle handle, int offsetLow, int offsetHigh, int countLow, int countHigh);
-
- [DllImport(KERNEL32, SetLastError=true)]
- internal static extern bool UnlockFile(SafeFileHandle handle, int offsetLow, int offsetHigh, int countLow, int countHigh);
-
internal static readonly IntPtr INVALID_HANDLE_VALUE = new IntPtr(-1); // WinBase.h
// Note, these are #defines used to extract handles, and are NOT handles.
@@ -1188,42 +741,6 @@ namespace Microsoft.Win32 {
internal String cAlternateFileName = null;
}
-#if FEATURE_CORESYSTEM
- [DllImport(KERNEL32, SetLastError=true, CharSet=CharSet.Auto, BestFitMapping=false)]
- private static extern bool CopyFileEx(String src,
- String dst,
- IntPtr progressRoutine,
- IntPtr progressData,
- ref uint cancel,
- uint flags);
-
- internal static bool CopyFile(String src, String dst, bool failIfExists)
- {
- uint cancel = 0;
- return CopyFileEx(src, dst, IntPtr.Zero, IntPtr.Zero, ref cancel, failIfExists ? 1U : 0U);
- }
-#else // FEATURE_CORESYSTEM
- [DllImport(KERNEL32, SetLastError=true, CharSet=CharSet.Auto, BestFitMapping=false)]
- internal static extern bool CopyFile(
- String src, String dst, bool failIfExists);
-#endif // FEATURE_CORESYSTEM
-
- [DllImport(KERNEL32, SetLastError=true, CharSet=CharSet.Auto, BestFitMapping=false)]
- internal static extern bool CreateDirectory(
- String path, SECURITY_ATTRIBUTES lpSecurityAttributes);
-
- [DllImport(KERNEL32, SetLastError=true, CharSet=CharSet.Auto, BestFitMapping=false)]
- internal static extern bool DeleteFile(String path);
-
- [DllImport(KERNEL32, SetLastError=true, CharSet=CharSet.Auto, BestFitMapping=false)]
- internal static extern bool ReplaceFile(String replacedFileName, String replacementFileName, String backupFileName, int dwReplaceFlags, IntPtr lpExclude, IntPtr lpReserved);
-
- [DllImport(ADVAPI32, SetLastError=true, CharSet=CharSet.Auto, BestFitMapping=false)]
- internal static extern bool DecryptFile(String path, int reservedMustBeZero);
-
- [DllImport(ADVAPI32, SetLastError=true, CharSet=CharSet.Auto, BestFitMapping=false)]
- internal static extern bool EncryptFile(String path);
-
[DllImport(KERNEL32, SetLastError=true, CharSet=CharSet.Auto, BestFitMapping=false)]
internal static extern SafeFindHandle FindFirstFile(String fileName, [In, Out] Win32Native.WIN32_FIND_DATA data);
@@ -1234,71 +751,26 @@ namespace Microsoft.Win32 {
WIN32_FIND_DATA lpFindFileData);
[DllImport(KERNEL32)]
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
internal static extern bool FindClose(IntPtr handle);
- [DllImport(KERNEL32, SetLastError=true, CharSet=CharSet.Auto, BestFitMapping=false)]
- internal static extern int GetCurrentDirectory(
- int nBufferLength,
- [Out]StringBuilder lpBuffer);
-
[DllImport(KERNEL32, SetLastError = true, ExactSpelling = true)]
- internal static extern uint GetCurrentDirectoryW(uint nBufferLength, SafeHandle lpBuffer);
+ internal static extern uint GetCurrentDirectoryW(uint nBufferLength, char[] lpBuffer);
[DllImport(KERNEL32, SetLastError=true, CharSet=CharSet.Auto, BestFitMapping=false)]
internal static extern bool GetFileAttributesEx(String name, int fileInfoLevel, ref WIN32_FILE_ATTRIBUTE_DATA lpFileInformation);
[DllImport(KERNEL32, SetLastError=true, CharSet=CharSet.Auto, BestFitMapping=false)]
- internal static extern bool SetFileAttributes(String name, int attr);
-
- [DllImport(KERNEL32, SetLastError=true)]
- internal static extern int GetLogicalDrives();
-
- [DllImport(KERNEL32, CharSet=CharSet.Auto, SetLastError=true, BestFitMapping=false)]
- internal static extern uint GetTempFileName(String tmpPath, String prefix, uint uniqueIdOrZero, [Out]StringBuilder tmpFileName);
-
-#if FEATURE_CORESYSTEM
- [DllImport(KERNEL32, SetLastError=true, CharSet=CharSet.Auto, BestFitMapping=false)]
- private static extern bool MoveFileEx(String src, String dst, uint flags);
-
- internal static bool MoveFile(String src, String dst)
- {
- return MoveFileEx(src, dst, 2 /* MOVEFILE_COPY_ALLOWED */);
- }
-#else // FEATURE_CORESYSTEM
- [DllImport(KERNEL32, SetLastError=true, CharSet=CharSet.Auto, BestFitMapping=false)]
- internal static extern bool MoveFile(String src, String dst);
-#endif // FEATURE_CORESYSTEM
-
- [DllImport(KERNEL32, SetLastError=true, CharSet=CharSet.Auto, BestFitMapping=false)]
- internal static extern bool DeleteVolumeMountPoint(String mountPoint);
-
- [DllImport(KERNEL32, SetLastError=true, CharSet=CharSet.Auto, BestFitMapping=false)]
- internal static extern bool RemoveDirectory(String path);
-
- [DllImport(KERNEL32, SetLastError=true, CharSet=CharSet.Auto, BestFitMapping=false)]
internal static extern bool SetCurrentDirectory(String path);
[DllImport(KERNEL32, SetLastError=false, EntryPoint="SetErrorMode", ExactSpelling=true)]
private static extern int SetErrorMode_VistaAndOlder(int newMode);
- [DllImport(KERNEL32, SetLastError=true, EntryPoint="SetThreadErrorMode")]
- private static extern bool SetErrorMode_Win7AndNewer(int newMode, out int oldMode);
-
// RTM versions of Win7 and Windows Server 2008 R2
private static readonly Version ThreadErrorModeMinOsVersion = new Version(6, 1, 7600);
// this method uses the thread-safe version of SetErrorMode on Windows 7 / Windows Server 2008 R2 operating systems.
internal static int SetErrorMode(int newMode)
{
-#if !FEATURE_CORESYSTEM // ARMSTUB
- if (Environment.OSVersion.Version >= ThreadErrorModeMinOsVersion)
- {
- int oldMode;
- SetErrorMode_Win7AndNewer(newMode, out oldMode);
- return oldMode;
- }
-#endif
return SetErrorMode_VistaAndOlder(newMode);
}
@@ -1307,13 +779,6 @@ namespace Microsoft.Win32 {
[DllImport(KERNEL32)]
internal static extern unsafe int WideCharToMultiByte(uint cp, uint flags, char* pwzSource, int cchSource, byte* pbDestBuffer, int cbDestBuffer, IntPtr null1, IntPtr null2);
- // A Win32 HandlerRoutine
- internal delegate bool ConsoleCtrlHandlerRoutine(int controlType);
-
- [DllImport(KERNEL32, SetLastError=true)]
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
- internal static extern bool SetConsoleCtrlHandler(ConsoleCtrlHandlerRoutine handler, bool addOrRemove);
-
[DllImport(KERNEL32, CharSet=CharSet.Auto, SetLastError=true, BestFitMapping=false)]
internal static extern bool SetEnvironmentVariable(string lpName, string lpValue);
@@ -1329,9 +794,6 @@ namespace Microsoft.Win32 {
[DllImport(KERNEL32, CharSet=CharSet.Auto, SetLastError=true)]
internal static extern uint GetCurrentProcessId();
- [DllImport(ADVAPI32, CharSet=CharSet.Auto)]
- internal static extern bool GetUserName([Out]StringBuilder lpBuffer, ref int nSize);
-
[DllImport(KERNEL32, CharSet=CharSet.Auto, BestFitMapping=false)]
internal extern static int GetComputerName([Out]StringBuilder nameBuffer, ref int bufferSize);
@@ -1347,195 +809,7 @@ namespace Microsoft.Win32 {
[DllImport(OLE32)]
internal static extern IntPtr CoTaskMemRealloc(IntPtr pv, UIntPtr cb);
- [StructLayoutAttribute(LayoutKind.Sequential)]
- internal struct COORD
- {
- internal short X;
- internal short Y;
- }
-
- [StructLayoutAttribute(LayoutKind.Sequential)]
- internal struct SMALL_RECT
- {
- internal short Left;
- internal short Top;
- internal short Right;
- internal short Bottom;
- }
-
- [StructLayoutAttribute(LayoutKind.Sequential)]
- internal struct CONSOLE_SCREEN_BUFFER_INFO
- {
- internal COORD dwSize;
- internal COORD dwCursorPosition;
- internal short wAttributes;
- internal SMALL_RECT srWindow;
- internal COORD dwMaximumWindowSize;
- }
-
- [StructLayoutAttribute(LayoutKind.Sequential)]
- internal struct CONSOLE_CURSOR_INFO
- {
- internal int dwSize;
- internal bool bVisible;
- }
-
- // Win32's KEY_EVENT_RECORD
- [StructLayout(LayoutKind.Sequential, CharSet=CharSet.Auto)]
- internal struct KeyEventRecord
- {
- internal bool keyDown;
- internal short repeatCount;
- internal short virtualKeyCode;
- internal short virtualScanCode;
- internal char uChar; // Union between WCHAR and ASCII char
- internal int controlKeyState;
- }
-
- // Really, this is a union of KeyEventRecords and other types.
- [StructLayout(LayoutKind.Sequential, CharSet=CharSet.Auto)]
- internal struct InputRecord
- {
- internal short eventType;
- internal KeyEventRecord keyEvent;
- // This struct is a union! Word alighment should take care of padding!
- }
-
-[Serializable]
- [Flags]
- internal enum Color : short
- {
- Black = 0,
- ForegroundBlue = 0x1,
- ForegroundGreen = 0x2,
- ForegroundRed = 0x4,
- ForegroundYellow = 0x6,
- ForegroundIntensity = 0x8,
- BackgroundBlue = 0x10,
- BackgroundGreen = 0x20,
- BackgroundRed = 0x40,
- BackgroundYellow = 0x60,
- BackgroundIntensity = 0x80,
-
- ForegroundMask = 0xf,
- BackgroundMask = 0xf0,
- ColorMask = 0xff
- }
-
- [StructLayout(LayoutKind.Sequential)]
- internal struct CHAR_INFO
- {
- ushort charData; // Union between WCHAR and ASCII char
- short attributes;
- }
-
- internal const int ENABLE_PROCESSED_INPUT = 0x0001;
- internal const int ENABLE_LINE_INPUT = 0x0002;
- internal const int ENABLE_ECHO_INPUT = 0x0004;
-
- [DllImport(KERNEL32, SetLastError=true)]
- internal static extern bool SetConsoleMode(IntPtr hConsoleHandle, int mode);
-
- [DllImport(KERNEL32, SetLastError=true)]
- internal static extern bool GetConsoleMode(IntPtr hConsoleHandle, out int mode);
-
- [DllImport(KERNEL32, SetLastError=true)]
- internal static extern bool Beep(int frequency, int duration);
-
- [DllImport(KERNEL32, SetLastError=true)]
- internal static extern bool GetConsoleScreenBufferInfo(IntPtr hConsoleOutput,
- out CONSOLE_SCREEN_BUFFER_INFO lpConsoleScreenBufferInfo);
-
- [DllImport(KERNEL32, SetLastError=true)]
- internal static extern bool SetConsoleScreenBufferSize(IntPtr hConsoleOutput, COORD size);
-
- [DllImport(KERNEL32, SetLastError=true)]
- internal static extern COORD GetLargestConsoleWindowSize(IntPtr hConsoleOutput);
-
- [DllImport(KERNEL32, CharSet=CharSet.Auto, SetLastError=true)]
- internal static extern bool FillConsoleOutputCharacter(IntPtr hConsoleOutput,
- char character, int nLength, COORD dwWriteCoord, out int pNumCharsWritten);
-
- [DllImport(KERNEL32, SetLastError=true)]
- internal static extern bool FillConsoleOutputAttribute(IntPtr hConsoleOutput,
- short wColorAttribute, int numCells, COORD startCoord, out int pNumBytesWritten);
-
- [DllImport(KERNEL32, SetLastError=true)]
- internal static unsafe extern bool SetConsoleWindowInfo(IntPtr hConsoleOutput,
- bool absolute, SMALL_RECT* consoleWindow);
-
- [DllImport(KERNEL32, SetLastError=true)]
- internal static extern bool SetConsoleTextAttribute(IntPtr hConsoleOutput, short attributes);
-
- [DllImport(KERNEL32, SetLastError=true)]
- internal static extern bool SetConsoleCursorPosition(IntPtr hConsoleOutput,
- COORD cursorPosition);
-
- [DllImport(KERNEL32, SetLastError=true)]
- internal static extern bool GetConsoleCursorInfo(IntPtr hConsoleOutput,
- out CONSOLE_CURSOR_INFO cci);
-
- [DllImport(KERNEL32, SetLastError=true)]
- internal static extern bool SetConsoleCursorInfo(IntPtr hConsoleOutput,
- ref CONSOLE_CURSOR_INFO cci);
-
- [DllImport(KERNEL32, CharSet=CharSet.Auto, SetLastError=true, BestFitMapping=true)]
- internal static extern bool SetConsoleTitle(String title);
-
- [DllImport(KERNEL32, CharSet=CharSet.Auto, SetLastError=true)]
- internal static extern bool ReadConsoleInput(IntPtr hConsoleInput, out InputRecord buffer, int numInputRecords_UseOne, out int numEventsRead);
-
- [DllImport(KERNEL32, CharSet=CharSet.Auto, SetLastError=true)]
- internal static extern bool PeekConsoleInput(IntPtr hConsoleInput, out InputRecord buffer, int numInputRecords_UseOne, out int numEventsRead);
-
- [DllImport(KERNEL32, SetLastError=true)]
- internal static unsafe extern bool ReadConsoleOutput(IntPtr hConsoleOutput, CHAR_INFO* pBuffer, COORD bufferSize, COORD bufferCoord, ref SMALL_RECT readRegion);
-
- [DllImport(KERNEL32, CharSet=CharSet.Unicode, SetLastError=true)]
- [return: MarshalAs(UnmanagedType.Bool)]
- internal static unsafe extern bool ReadConsoleW(SafeFileHandle hConsoleInput, Byte* lpBuffer, Int32 nNumberOfCharsToRead, out Int32 lpNumberOfCharsRead, IntPtr pInputControl);
-
- [DllImport(KERNEL32, SetLastError=true)]
- internal static unsafe extern bool WriteConsoleOutput(IntPtr hConsoleOutput, CHAR_INFO* buffer, COORD bufferSize, COORD bufferCoord, ref SMALL_RECT writeRegion);
-
- [DllImport(KERNEL32, CharSet=CharSet.Unicode, SetLastError=true)]
- [return: MarshalAs(UnmanagedType.Bool)]
- internal static unsafe extern bool WriteConsoleW(SafeFileHandle hConsoleOutput, Byte* lpBuffer, Int32 nNumberOfCharsToWrite, out Int32 lpNumberOfCharsWritten, IntPtr lpReservedMustBeNull);
-
- [DllImport(USER32)] // Appears to always succeed
- internal static extern short GetKeyState(int virtualKeyCode);
-
- [DllImport(KERNEL32, SetLastError=false)]
- internal static extern uint GetConsoleCP();
-
- [DllImport(KERNEL32, SetLastError=true)]
- internal static extern bool SetConsoleCP(uint codePage);
-
- [DllImport(KERNEL32, SetLastError=false)]
- internal static extern uint GetConsoleOutputCP();
-
- [DllImport(KERNEL32, SetLastError=true)]
- internal static extern bool SetConsoleOutputCP(uint codePage);
-
#if FEATURE_WIN32_REGISTRY
- [DllImport(ADVAPI32, CharSet=CharSet.Auto, BestFitMapping=false)]
- internal static extern int RegConnectRegistry(String machineName,
- SafeRegistryHandle key, out SafeRegistryHandle result);
-
- // Note: RegCreateKeyEx won't set the last error on failure - it returns
- // an error code if it fails.
- [DllImport(ADVAPI32, CharSet=CharSet.Auto, BestFitMapping=false)]
- internal static extern int RegCreateKeyEx(SafeRegistryHandle hKey, String lpSubKey,
- int Reserved, String lpClass, int dwOptions,
- int samDesired, SECURITY_ATTRIBUTES lpSecurityAttributes,
- out SafeRegistryHandle hkResult, out int lpdwDisposition);
-
- [DllImport(ADVAPI32, CharSet=CharSet.Auto, BestFitMapping=false)]
- internal static extern int RegDeleteKey(SafeRegistryHandle hKey, String lpSubKey);
-
- [DllImport(ADVAPI32, CharSet=CharSet.Auto, BestFitMapping=false)]
- internal static extern int RegDeleteKeyEx(SafeRegistryHandle hKey, String lpSubKey,
- int samDesired, int Reserved);
[DllImport(ADVAPI32, CharSet=CharSet.Auto, BestFitMapping=false)]
internal static extern int RegDeleteValue(SafeRegistryHandle hKey, String lpValueName);
@@ -1552,17 +826,9 @@ namespace Microsoft.Win32 {
IntPtr lpReserved_MustBeZero, int[] lpType, byte[] lpData,
int[] lpcbData);
-
- [DllImport(ADVAPI32)]
- internal static extern int RegFlushKey(SafeRegistryHandle hKey);
-
[DllImport(ADVAPI32, CharSet=CharSet.Auto, BestFitMapping=false)]
internal static extern int RegOpenKeyEx(SafeRegistryHandle hKey, String lpSubKey,
int ulOptions, int samDesired, out SafeRegistryHandle hkResult);
-
- [DllImport(ADVAPI32, CharSet=CharSet.Auto, BestFitMapping=false)]
- internal static extern int RegOpenKeyEx(IntPtr hKey, String lpSubKey,
- int ulOptions, int samDesired, out SafeRegistryHandle hkResult);
[DllImport(ADVAPI32, CharSet=CharSet.Auto, BestFitMapping=false)]
internal static extern int RegQueryInfoKey(SafeRegistryHandle hKey, [Out]StringBuilder lpClass,
@@ -1593,11 +859,6 @@ namespace Microsoft.Win32 {
ref int lpcbData);
[DllImport(ADVAPI32, CharSet=CharSet.Auto, BestFitMapping=false)]
- internal static extern int RegQueryValueEx(SafeRegistryHandle hKey, String lpValueName,
- int[] lpReserved, ref int lpType, [Out]StringBuilder lpData,
- ref int lpcbData);
-
- [DllImport(ADVAPI32, CharSet=CharSet.Auto, BestFitMapping=false)]
internal static extern int RegSetValueEx(SafeRegistryHandle hKey, String lpValueName,
int Reserved, RegistryValueKind dwType, byte[] lpData, int cbData);
@@ -1676,640 +937,11 @@ namespace Microsoft.Win32 {
internal const int CSIDL_MYMUSIC = 0x000d;
internal const int CSIDL_MYPICTURES = 0x0027;
- [DllImport(SHELL32, CharSet=CharSet.Auto, BestFitMapping=false)]
- internal static extern int SHGetFolderPath(IntPtr hwndOwner, int nFolder, IntPtr hToken, int dwFlags, [Out]StringBuilder lpszPath);
-
internal const int NameSamCompatible = 2;
-
- [DllImport(SECUR32, CharSet=CharSet.Unicode, SetLastError=true)]
- // Win32 return type is BOOLEAN (which is 1 byte and not BOOL which is 4bytes)
- internal static extern byte GetUserNameEx(int format, [Out]StringBuilder domainName, ref uint domainNameLen);
-
- [DllImport(ADVAPI32, CharSet=CharSet.Auto, SetLastError=true, BestFitMapping=false)]
- internal static extern bool LookupAccountName(string machineName, string accountName, byte[] sid,
- ref int sidLen, [Out]StringBuilder domainName, ref uint domainNameLen, out int peUse);
-
- // Note: This returns a handle, but it shouldn't be closed. The Avalon
- // team says CloseWindowStation would ignore this handle. So there
- // isn't a lot of value to switching to SafeHandle here.
- [DllImport(USER32, ExactSpelling=true)]
- internal static extern IntPtr GetProcessWindowStation();
-
- [DllImport(USER32, SetLastError=true)]
- internal static extern bool GetUserObjectInformation(IntPtr hObj, int nIndex,
- [MarshalAs(UnmanagedType.LPStruct)] USEROBJECTFLAGS pvBuffer, int nLength, ref int lpnLengthNeeded);
[DllImport(USER32, SetLastError=true, BestFitMapping=false)]
internal static extern IntPtr SendMessageTimeout(IntPtr hWnd, int Msg, IntPtr wParam, String lParam, uint fuFlags, uint uTimeout, IntPtr lpdwResult);
- [StructLayout(LayoutKind.Sequential)]
- internal class USEROBJECTFLAGS {
- internal int fInherit = 0;
- internal int fReserved = 0;
- internal int dwFlags = 0;
- }
-
- //
- // DPAPI
- //
-
-#if FEATURE_LEGACYSURFACE
- //
- // RtlEncryptMemory and RtlDecryptMemory are declared in the internal header file crypt.h.
- // They were also recently declared in the public header file ntsecapi.h (in the Platform SDK as well as the current build of Server 2003).
- // We use them instead of CryptProtectMemory and CryptUnprotectMemory because
- // they are available in both WinXP and in Windows Server 2003.
- //
-
- [DllImport(Win32Native.ADVAPI32, CharSet=CharSet.Unicode, SetLastError=true)]
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
- internal static extern
- int SystemFunction040 (
- [In,Out] SafeBSTRHandle pDataIn,
- [In] uint cbDataIn, // multiple of RTL_ENCRYPT_MEMORY_SIZE
- [In] uint dwFlags);
-
- [DllImport(Win32Native.ADVAPI32, CharSet=CharSet.Unicode, SetLastError=true)]
- internal static extern
- int SystemFunction041 (
- [In,Out] SafeBSTRHandle pDataIn,
- [In] uint cbDataIn, // multiple of RTL_ENCRYPT_MEMORY_SIZE
- [In] uint dwFlags);
-#endif // FEATURE_LEGACYSURFACE
-
- [DllImport(NTDLL, CharSet=CharSet.Unicode, SetLastError=true)]
- internal static extern
- int RtlNtStatusToDosError (
- [In] int status);
-
- // Get the current FIPS policy setting on Vista and above
- [DllImport("bcrypt.dll")]
- internal static extern uint BCryptGetFipsAlgorithmMode(
- [MarshalAs(UnmanagedType.U1), Out]out bool pfEnabled);
-
- //
- // Managed ACLs
- //
-
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
- [DllImport(ADVAPI32, CharSet=CharSet.Unicode, SetLastError=true)]
- internal static extern
- bool AdjustTokenPrivileges (
- [In] SafeAccessTokenHandle TokenHandle,
- [In] bool DisableAllPrivileges,
- [In] ref TOKEN_PRIVILEGE NewState,
- [In] uint BufferLength,
- [In,Out] ref TOKEN_PRIVILEGE PreviousState,
- [In,Out] ref uint ReturnLength);
-
- [DllImport(ADVAPI32, CharSet=CharSet.Unicode, SetLastError=true)]
- internal static extern
- bool AllocateLocallyUniqueId(
- [In,Out] ref LUID Luid);
-
- [DllImport(ADVAPI32, CharSet=CharSet.Unicode, SetLastError=true)]
- internal static extern
- bool CheckTokenMembership(
- [In] SafeAccessTokenHandle TokenHandle,
- [In] byte[] SidToCheck,
- [In,Out] ref bool IsMember);
-
- [DllImport(
- ADVAPI32,
- EntryPoint="ConvertSecurityDescriptorToStringSecurityDescriptorW",
- CallingConvention=CallingConvention.Winapi,
- SetLastError=true,
- ExactSpelling=true,
- CharSet=CharSet.Unicode)]
- internal static extern BOOL ConvertSdToStringSd(
- byte[] securityDescriptor,
- /* DWORD */ uint requestedRevision,
- ULONG securityInformation,
- out IntPtr resultString,
- ref ULONG resultStringLength );
-
- [DllImport(
- ADVAPI32,
- EntryPoint="ConvertStringSecurityDescriptorToSecurityDescriptorW",
- CallingConvention=CallingConvention.Winapi,
- SetLastError=true,
- ExactSpelling=true,
- CharSet=CharSet.Unicode)]
- internal static extern BOOL ConvertStringSdToSd(
- string stringSd,
- /* DWORD */ uint stringSdRevision,
- out IntPtr resultSd,
- ref ULONG resultSdLength );
-
- [DllImport(
- ADVAPI32,
- EntryPoint="ConvertStringSidToSidW",
- CallingConvention=CallingConvention.Winapi,
- SetLastError=true,
- ExactSpelling=true,
- CharSet=CharSet.Unicode)]
- internal static extern BOOL ConvertStringSidToSid(
- string stringSid,
- out IntPtr ByteArray
- );
-
- [DllImport(
- ADVAPI32,
- EntryPoint = "ConvertSidToStringSidW",
- CallingConvention = CallingConvention.Winapi,
- SetLastError = true,
- ExactSpelling = true,
- CharSet = CharSet.Unicode)]
- [return: MarshalAs(UnmanagedType.Bool)]
- internal static extern bool ConvertSidToStringSid(
- IntPtr Sid,
- ref IntPtr StringSid
- );
-
-
- [DllImport(
- ADVAPI32,
- EntryPoint="CreateWellKnownSid",
- CallingConvention=CallingConvention.Winapi,
- SetLastError=true,
- ExactSpelling=true,
- CharSet=CharSet.Unicode)]
- internal static extern BOOL CreateWellKnownSid(
- int sidType,
- byte[] domainSid,
- [Out] byte[] resultSid,
- ref /*DWORD*/ uint resultSidLength );
-
- [DllImport(KERNEL32, CharSet=CharSet.Auto, SetLastError=true)]
- internal static extern
- bool DuplicateHandle (
- [In] IntPtr hSourceProcessHandle,
- [In] IntPtr hSourceHandle,
- [In] IntPtr hTargetProcessHandle,
- [In,Out] ref SafeAccessTokenHandle lpTargetHandle,
- [In] uint dwDesiredAccess,
- [In] bool bInheritHandle,
- [In] uint dwOptions);
-
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
- [DllImport(KERNEL32, CharSet=CharSet.Auto, SetLastError=true)]
- internal static extern
- bool DuplicateHandle (
- [In] IntPtr hSourceProcessHandle,
- [In] SafeAccessTokenHandle hSourceHandle,
- [In] IntPtr hTargetProcessHandle,
- [In,Out] ref SafeAccessTokenHandle lpTargetHandle,
- [In] uint dwDesiredAccess,
- [In] bool bInheritHandle,
- [In] uint dwOptions);
-
- [DllImport(
- ADVAPI32,
- EntryPoint="EqualDomainSid",
- CallingConvention=CallingConvention.Winapi,
- SetLastError=true,
- ExactSpelling=true,
- CharSet=CharSet.Unicode)]
- internal static extern BOOL IsEqualDomainSid(
- byte[] sid1,
- byte[] sid2,
- out bool result);
-
- [DllImport(KERNEL32, CharSet=CharSet.Auto, SetLastError=true)]
- internal static extern IntPtr GetCurrentProcess();
-
- [DllImport(KERNEL32, CharSet = CharSet.Auto, SetLastError = true)]
- internal static extern IntPtr GetCurrentThread();
-
- [DllImport(
- ADVAPI32,
- EntryPoint="GetSecurityDescriptorLength",
- CallingConvention=CallingConvention.Winapi,
- SetLastError=true,
- ExactSpelling=true,
- CharSet=CharSet.Unicode)]
- internal static extern /*DWORD*/ uint GetSecurityDescriptorLength(
- IntPtr byteArray );
-
- [DllImport(
- ADVAPI32,
- EntryPoint="GetSecurityInfo",
- CallingConvention=CallingConvention.Winapi,
- SetLastError=true,
- ExactSpelling=true,
- CharSet=CharSet.Unicode)]
- internal static extern /*DWORD*/ uint GetSecurityInfoByHandle(
- SafeHandle handle,
- /*DWORD*/ uint objectType,
- /*DWORD*/ uint securityInformation,
- out IntPtr sidOwner,
- out IntPtr sidGroup,
- out IntPtr dacl,
- out IntPtr sacl,
- out IntPtr securityDescriptor );
-
- [DllImport(
- ADVAPI32,
- EntryPoint="GetNamedSecurityInfoW",
- CallingConvention=CallingConvention.Winapi,
- SetLastError=true,
- ExactSpelling=true,
- CharSet=CharSet.Unicode)]
- internal static extern /*DWORD*/ uint GetSecurityInfoByName(
- string name,
- /*DWORD*/ uint objectType,
- /*DWORD*/ uint securityInformation,
- out IntPtr sidOwner,
- out IntPtr sidGroup,
- out IntPtr dacl,
- out IntPtr sacl,
- out IntPtr securityDescriptor );
-
- [DllImport(ADVAPI32, CharSet=CharSet.Auto, SetLastError=true)]
- internal static extern
- bool GetTokenInformation (
- [In] IntPtr TokenHandle,
- [In] uint TokenInformationClass,
- [In] SafeLocalAllocHandle TokenInformation,
- [In] uint TokenInformationLength,
- [Out] out uint ReturnLength);
-
- [DllImport(ADVAPI32, CharSet=CharSet.Auto, SetLastError=true)]
- internal static extern
- bool GetTokenInformation (
- [In] SafeAccessTokenHandle TokenHandle,
- [In] uint TokenInformationClass,
- [In] SafeLocalAllocHandle TokenInformation,
- [In] uint TokenInformationLength,
- [Out] out uint ReturnLength);
-
- [DllImport(
- ADVAPI32,
- EntryPoint="GetWindowsAccountDomainSid",
- CallingConvention=CallingConvention.Winapi,
- SetLastError=true,
- ExactSpelling=true,
- CharSet=CharSet.Unicode)]
- internal static extern BOOL GetWindowsAccountDomainSid(
- byte[] sid,
- [Out] byte[] resultSid,
- ref /*DWORD*/ uint resultSidLength );
-
- internal enum SECURITY_IMPERSONATION_LEVEL
- {
- Anonymous = 0,
- Identification = 1,
- Impersonation = 2,
- Delegation = 3,
- }
-
- // Structures and definitions for Claims that are being introduced in Win8
- // inside the NTTOken - see winnt.h. They will be surfaced through WindowsIdentity.Claims
-
- // CLAIM_SECURITY_ATTRIBUTE_TYPE_INVALID -> 0x00
- internal const int CLAIM_SECURITY_ATTRIBUTE_TYPE_INVALID = 0;
-
- // CLAIM_SECURITY_ATTRIBUTE_TYPE_INT64 -> 0x01
- internal const int CLAIM_SECURITY_ATTRIBUTE_TYPE_INT64 = 1;
-
- // CLAIM_SECURITY_ATTRIBUTE_TYPE_UINT64 -> 0x02
- internal const int CLAIM_SECURITY_ATTRIBUTE_TYPE_UINT64 = 2;
-
- // CLAIM_SECURITY_ATTRIBUTE_TYPE_STRING -> 0x03
- internal const int CLAIM_SECURITY_ATTRIBUTE_TYPE_STRING = 3;
-
- // CLAIM_SECURITY_ATTRIBUTE_TYPE_FQBN -> 0x04
- internal const int CLAIM_SECURITY_ATTRIBUTE_TYPE_FQBN = 4;
-
- // CLAIM_SECURITY_ATTRIBUTE_TYPE_SID -> 0x05
- internal const int CLAIM_SECURITY_ATTRIBUTE_TYPE_SID = 5;
-
- // CLAIM_SECURITY_ATTRIBUTE_TYPE_BOOLEAN -> 0x06
- internal const int CLAIM_SECURITY_ATTRIBUTE_TYPE_BOOLEAN = 6;
-
- // CLAIM_SECURITY_ATTRIBUTE_TYPE_OCTET_STRING -> 0x10
- internal const int CLAIM_SECURITY_ATTRIBUTE_TYPE_OCTET_STRING = 16;
-
- // CLAIM_SECURITY_ATTRIBUTE_NON_INHERITABLE -> 0x0001
- internal const int CLAIM_SECURITY_ATTRIBUTE_NON_INHERITABLE = 1;
-
- // CLAIM_SECURITY_ATTRIBUTE_VALUE_CASE_SENSITIVE -> 0x0002
- internal const int CLAIM_SECURITY_ATTRIBUTE_VALUE_CASE_SENSITIVE = 2;
-
- // CLAIM_SECURITY_ATTRIBUTE_USE_FOR_DENY_ONLY -> 0x0004
- internal const int CLAIM_SECURITY_ATTRIBUTE_USE_FOR_DENY_ONLY = 4;
-
- // CLAIM_SECURITY_ATTRIBUTE_DISABLED_BY_DEFAULT -> 0x0008
- internal const int CLAIM_SECURITY_ATTRIBUTE_DISABLED_BY_DEFAULT = 8;
-
- // CLAIM_SECURITY_ATTRIBUTE_DISABLED -> 0x0010
- internal const int CLAIM_SECURITY_ATTRIBUTE_DISABLED = 16;
-
- // CLAIM_SECURITY_ATTRIBUTE_MANDATORY -> 0x0020
- internal const int CLAIM_SECURITY_ATTRIBUTE_MANDATORY = 32;
-
- internal const int CLAIM_SECURITY_ATTRIBUTE_VALID_FLAGS =
- CLAIM_SECURITY_ATTRIBUTE_NON_INHERITABLE
- | CLAIM_SECURITY_ATTRIBUTE_VALUE_CASE_SENSITIVE
- | CLAIM_SECURITY_ATTRIBUTE_USE_FOR_DENY_ONLY
- | CLAIM_SECURITY_ATTRIBUTE_DISABLED_BY_DEFAULT
- | CLAIM_SECURITY_ATTRIBUTE_DISABLED
- | CLAIM_SECURITY_ATTRIBUTE_MANDATORY;
-
-
- [StructLayoutAttribute( LayoutKind.Explicit )]
- internal struct CLAIM_SECURITY_ATTRIBUTE_INFORMATION_V1
- {
- // defined as union in CLAIM_SECURITY_ATTRIBUTES_INFORMATION
- [FieldOffsetAttribute( 0 )]
- public IntPtr pAttributeV1;
- }
-
- [StructLayoutAttribute( LayoutKind.Sequential )]
- internal struct CLAIM_SECURITY_ATTRIBUTES_INFORMATION
- {
- /// WORD->unsigned short
- public ushort Version;
-
- /// WORD->unsigned short
- public ushort Reserved;
-
- /// DWORD->unsigned int
- public uint AttributeCount;
-
- /// CLAIM_SECURITY_ATTRIBUTE_V1
- public CLAIM_SECURITY_ATTRIBUTE_INFORMATION_V1 Attribute;
- }
-
- //
- // Fully-qualified binary name.
- //
- [StructLayoutAttribute( LayoutKind.Sequential, CharSet = CharSet.Unicode )]
- internal struct CLAIM_SECURITY_ATTRIBUTE_FQBN_VALUE
- {
- // DWORD64->unsigned __int64
- public ulong Version;
-
- // PWSTR->WCHAR*
- [MarshalAsAttribute( UnmanagedType.LPWStr )]
- public string Name;
- }
-
- [StructLayoutAttribute( LayoutKind.Sequential, CharSet = CharSet.Unicode )]
- internal struct CLAIM_SECURITY_ATTRIBUTE_OCTET_STRING_VALUE
- {
- /// PVOID->void*
- public IntPtr pValue;
-
- /// DWORD->unsigned int
- public uint ValueLength;
- }
-
- [StructLayoutAttribute( LayoutKind.Explicit, CharSet = CharSet.Unicode )]
- internal struct CLAIM_VALUES_ATTRIBUTE_V1
- {
- // PLONG64->__int64*
- [FieldOffsetAttribute( 0 )]
- public IntPtr pInt64;
-
- // PDWORD64->unsigned __int64*
- [FieldOffsetAttribute( 0 )]
- public IntPtr pUint64;
-
- // PWSTR*
- [FieldOffsetAttribute( 0 )]
- public IntPtr ppString;
-
- // PCLAIM_SECURITY_ATTRIBUTE_FQBN_VALUE->_CLAIM_SECURITY_ATTRIBUTE_FQBN_VALUE*
- [FieldOffsetAttribute( 0 )]
- public IntPtr pFqbn;
-
- // PCLAIM_SECURITY_ATTRIBUTE_OCTET_STRING_VALUE->_CLAIM_SECURITY_ATTRIBUTE_OCTET_STRING_VALUE*
- [FieldOffsetAttribute( 0 )]
- public IntPtr pOctetString;
- }
-
- [StructLayoutAttribute( LayoutKind.Sequential, CharSet = CharSet.Unicode )]
- internal struct CLAIM_SECURITY_ATTRIBUTE_V1
- {
- // PWSTR->WCHAR*
- [MarshalAsAttribute( UnmanagedType.LPWStr )]
- public string Name;
-
- // WORD->unsigned short
- public ushort ValueType;
-
- // WORD->unsigned short
- public ushort Reserved;
-
- // DWORD->unsigned int
- public uint Flags;
-
- // DWORD->unsigned int
- public uint ValueCount;
-
- // struct CLAIM_VALUES - a union of 4 possible values
- public CLAIM_VALUES_ATTRIBUTE_V1 Values;
- }
-
- [DllImport(
- ADVAPI32,
- EntryPoint="IsWellKnownSid",
- CallingConvention=CallingConvention.Winapi,
- SetLastError=true,
- ExactSpelling=true,
- CharSet=CharSet.Unicode)]
- internal static extern BOOL IsWellKnownSid(
- byte[] sid,
- int type );
-
- [DllImport(
- ADVAPI32,
- EntryPoint="LsaOpenPolicy",
- CallingConvention=CallingConvention.Winapi,
- SetLastError=true,
- ExactSpelling=true,
- CharSet=CharSet.Unicode)]
- internal static extern /*DWORD*/ uint LsaOpenPolicy(
- string systemName,
- ref LSA_OBJECT_ATTRIBUTES attributes,
- int accessMask,
- out SafeLsaPolicyHandle handle
- );
-
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
- [DllImport(
- ADVAPI32,
- EntryPoint="LookupPrivilegeValueW",
- CharSet=CharSet.Auto,
- SetLastError=true,
- ExactSpelling=true,
- BestFitMapping=false)]
- internal static extern
- bool LookupPrivilegeValue (
- [In] string lpSystemName,
- [In] string lpName,
- [In,Out] ref LUID Luid);
-
- [DllImport(
- ADVAPI32,
- EntryPoint="LsaLookupSids",
- CallingConvention=CallingConvention.Winapi,
- SetLastError=true,
- ExactSpelling=true,
- CharSet=CharSet.Unicode)]
- internal static extern /*DWORD*/ uint LsaLookupSids(
- SafeLsaPolicyHandle handle,
- int count,
- IntPtr[] sids,
- ref SafeLsaMemoryHandle referencedDomains,
- ref SafeLsaMemoryHandle names
- );
-
- [DllImport(ADVAPI32, SetLastError=true)]
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
- internal static extern int LsaFreeMemory( IntPtr handle );
-
- [DllImport(
- ADVAPI32,
- EntryPoint="LsaLookupNames",
- CallingConvention=CallingConvention.Winapi,
- SetLastError=true,
- ExactSpelling=true,
- CharSet=CharSet.Unicode)]
- internal static extern /*DWORD*/ uint LsaLookupNames(
- SafeLsaPolicyHandle handle,
- int count,
- UNICODE_STRING[] names,
- ref SafeLsaMemoryHandle referencedDomains,
- ref SafeLsaMemoryHandle sids
- );
-
- [DllImport(
- ADVAPI32,
- EntryPoint="LsaLookupNames2",
- CallingConvention=CallingConvention.Winapi,
- SetLastError=true,
- ExactSpelling=true,
- CharSet=CharSet.Unicode)]
- internal static extern /*DWORD*/ uint LsaLookupNames2(
- SafeLsaPolicyHandle handle,
- int flags,
- int count,
- UNICODE_STRING[] names,
- ref SafeLsaMemoryHandle referencedDomains,
- ref SafeLsaMemoryHandle sids
- );
-
- [DllImport(SECUR32, CharSet=CharSet.Auto, SetLastError=true)]
- internal static extern
- int LsaConnectUntrusted (
- [In,Out] ref SafeLsaLogonProcessHandle LsaHandle);
-
- [DllImport(SECUR32, CharSet=CharSet.Auto, SetLastError=true)]
- internal static extern
- int LsaGetLogonSessionData (
- [In] ref LUID LogonId,
- [In,Out] ref SafeLsaReturnBufferHandle ppLogonSessionData);
-
- [DllImport(SECUR32, CharSet=CharSet.Auto, SetLastError=true)]
- internal static extern
- int LsaLogonUser (
- [In] SafeLsaLogonProcessHandle LsaHandle,
- [In] ref UNICODE_INTPTR_STRING OriginName,
- [In] uint LogonType,
- [In] uint AuthenticationPackage,
- [In] IntPtr AuthenticationInformation,
- [In] uint AuthenticationInformationLength,
- [In] IntPtr LocalGroups,
- [In] ref TOKEN_SOURCE SourceContext,
- [In,Out] ref SafeLsaReturnBufferHandle ProfileBuffer,
- [In,Out] ref uint ProfileBufferLength,
- [In,Out] ref LUID LogonId,
- [In,Out] ref SafeAccessTokenHandle Token,
- [In,Out] ref QUOTA_LIMITS Quotas,
- [In,Out] ref int SubStatus);
-
- [DllImport(SECUR32, CharSet=CharSet.Auto, SetLastError=true)]
- internal static extern
- int LsaLookupAuthenticationPackage (
- [In] SafeLsaLogonProcessHandle LsaHandle,
- [In] ref UNICODE_INTPTR_STRING PackageName,
- [In,Out] ref uint AuthenticationPackage);
-
- [DllImport(SECUR32, CharSet=CharSet.Auto, SetLastError=true)]
- internal static extern
- int LsaRegisterLogonProcess (
- [In] ref UNICODE_INTPTR_STRING LogonProcessName,
- [In,Out] ref SafeLsaLogonProcessHandle LsaHandle,
- [In,Out] ref IntPtr SecurityMode);
-
- [DllImport(SECUR32, SetLastError=true)]
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
- internal static extern int LsaDeregisterLogonProcess(IntPtr handle);
-
- [DllImport(ADVAPI32, SetLastError=true)]
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
- internal static extern int LsaClose( IntPtr handle );
-
- [DllImport(SECUR32, SetLastError=true)]
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
- internal static extern int LsaFreeReturnBuffer(IntPtr handle);
-
- [DllImport(
- ADVAPI32,
- EntryPoint="SetNamedSecurityInfoW",
- CallingConvention=CallingConvention.Winapi,
- SetLastError=true,
- ExactSpelling=true,
- CharSet=CharSet.Unicode)]
- internal static extern /*DWORD*/ uint SetSecurityInfoByName(
- string name,
- /*DWORD*/ uint objectType,
- /*DWORD*/ uint securityInformation,
- byte[] owner,
- byte[] group,
- byte[] dacl,
- byte[] sacl );
-
- [DllImport(
- ADVAPI32,
- EntryPoint="SetSecurityInfo",
- CallingConvention=CallingConvention.Winapi,
- SetLastError=true,
- ExactSpelling=true,
- CharSet=CharSet.Unicode)]
- internal static extern /*DWORD*/ uint SetSecurityInfoByHandle(
- SafeHandle handle,
- /*DWORD*/ uint objectType,
- /*DWORD*/ uint securityInformation,
- byte[] owner,
- byte[] group,
- byte[] dacl,
- byte[] sacl );
-
- [DllImport(KERNEL32, CharSet=CharSet.Unicode)]
- [SuppressUnmanagedCodeSecurityAttribute()]
- internal unsafe static extern int WideCharToMultiByte(
- int CodePage,
- UInt32 dwFlags,
- char* lpWideCharStr,
- int cchWideChar,
- byte* lpMultiByteStr,
- int cchMultiByte,
- char* lpDefaultChar,
- bool* lpUsedDefaultChar);
-
- [DllImport(KERNEL32, CharSet=CharSet.Unicode)]
- [SuppressUnmanagedCodeSecurityAttribute()]
- internal unsafe static extern int MultiByteToWideChar(
- int CodePage,
- UInt32 dwFlags,
- byte* lpMultiByteStr,
- int cchMultiByte,
- char* lpWideCharStr,
- int cchWideChar);
-
[DllImport(KERNEL32, SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
internal extern static bool QueryUnbiasedInterruptTime(out ulong UnbiasedTime);
@@ -2320,25 +952,6 @@ namespace Microsoft.Win32 {
[Out, MarshalAs(UnmanagedType.LPArray)] byte[] buffer, int length);
#else
private const int BCRYPT_USE_SYSTEM_PREFERRED_RNG = 0x00000002;
-
- [DllImport("BCrypt.dll", CharSet = CharSet.Unicode)]
- private static extern uint BCryptGenRandom(IntPtr hAlgorithm, [In, Out] byte[] pbBuffer, int cbBuffer, int dwFlags);
-
- internal static void Random(bool bStrong, byte[] buffer, int length)
- {
- uint status = BCryptGenRandom(IntPtr.Zero, buffer, length, BCRYPT_USE_SYSTEM_PREFERRED_RNG);
- if (status != STATUS_SUCCESS)
- {
- if (status == STATUS_NO_MEMORY)
- {
- throw new OutOfMemoryException();
- }
- else
- {
- throw new InvalidOperationException();
- }
- }
- }
#endif
}
}
diff --git a/src/mscorlib/src/System.Private.CoreLib.txt b/src/mscorlib/src/System.Private.CoreLib.txt
index cf17dae96f..b4e9e297d9 100644
--- a/src/mscorlib/src/System.Private.CoreLib.txt
+++ b/src/mscorlib/src/System.Private.CoreLib.txt
@@ -330,8 +330,8 @@ Arg_MemberInfoNullModule = The Module object containing the member cannot be nul
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_LongerThanSrcArray = Source array was not long enough. Check the source index, length, and the array's lower bounds.
+Arg_LongerThanDestArray = Destination array was not long enough. Check the destination index, 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.
@@ -590,10 +590,8 @@ 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
;
; =====================================================
@@ -895,44 +893,6 @@ Cryptography_PasswordDerivedBytes_FewBytesSalt = Salt is not at least eight byte
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.
@@ -1092,7 +1052,6 @@ InvalidOperation_CantCancelCtrlBreak = Applications may not prevent control-brea
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.
@@ -1410,10 +1369,9 @@ NotSupported_NativeCallableTarget = Methods with NativeCallableAttribute cannot
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_APPX
NotSupported_AppX = {0} is not supported in AppX.
LoadOfFxAssemblyNotSupported_AppX = {0} of .NET Framework assemblies is not supported in AppX.
@@ -1426,16 +1384,12 @@ ReflectionTypeLoad_LoadFailed = Unable to load one or more of the requested type
#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.
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
+NotSupported_ReflectionOnlyLoad = Assembly.ReflectionOnlyLoad is not supported.
+NotSupported_ReflectionOnlyGetType = Type.ReflectionOnlyGetType is not supported.
; TypeLoadException
TypeLoad_ResolveType = Could not resolve type '{0}'.
@@ -1991,10 +1945,6 @@ WeakReference_NoLongerValid = The weak reference is no longer valid.
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
;
@@ -2007,11 +1957,9 @@ 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.
@@ -2282,3 +2230,6 @@ Globalization.cp_57011 = ISCII Punjabi
;------------------
+; ValueTuple
+ArgumentException_ValueTupleIncorrectType=Argument must be of type {0}.
+ArgumentException_ValueTupleLastArgumentNotAValueTuple=The last element of an eight element ValueTuple must be a ValueTuple.
diff --git a/src/mscorlib/src/System/AccessViolationException.cs b/src/mscorlib/src/System/AccessViolationException.cs
index 308d52e9ed..12911c1b17 100644
--- a/src/mscorlib/src/System/AccessViolationException.cs
+++ b/src/mscorlib/src/System/AccessViolationException.cs
@@ -11,41 +11,38 @@
**
=============================================================================*/
-namespace System
-{
-
- using System;
- using System.Runtime.Serialization;
- [System.Runtime.InteropServices.ComVisible(true)]
+using System;
+using System.Runtime.Serialization;
+
+namespace System
+{
[Serializable]
- public class AccessViolationException : SystemException
+ public class AccessViolationException : SystemException
{
- public AccessViolationException()
- : base(Environment.GetResourceString("Arg_AccessViolationException"))
+ public AccessViolationException()
+ : base(SR.Arg_AccessViolationException)
{
- SetErrorCode(__HResults.E_POINTER);
+ HResult = __HResults.E_POINTER;
}
-
- public AccessViolationException(String message)
- : base(message)
+
+ public AccessViolationException(String message)
+ : base(message)
{
- SetErrorCode(__HResults.E_POINTER);
+ HResult = __HResults.E_POINTER;
}
-
- public AccessViolationException(String message, Exception innerException)
- : base(message, innerException)
+
+ public AccessViolationException(String message, Exception innerException)
+ : base(message, innerException)
{
- SetErrorCode(__HResults.E_POINTER);
+ HResult = __HResults.E_POINTER;
}
- protected AccessViolationException(SerializationInfo info, StreamingContext context) : base(info, context) {}
+ protected AccessViolationException(SerializationInfo info, StreamingContext context) : base(info, context) { }
#pragma warning disable 169 // Field is not used from managed.
private IntPtr _ip; // Address of faulting instruction.
private IntPtr _target; // Address that could not be accessed.
private int _accessType; // 0:read, 1:write
#pragma warning restore 169
-
}
-
}
diff --git a/src/mscorlib/src/System/Action.cs b/src/mscorlib/src/System/Action.cs
index 27f7fafe5c..23c7e93194 100644
--- a/src/mscorlib/src/System/Action.cs
+++ b/src/mscorlib/src/System/Action.cs
@@ -6,8 +6,6 @@ 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
public delegate void Action();
public delegate void Action<in T1,in T2>(T1 arg1, T2 arg2);
public delegate void Action<in T1,in T2,in T3>(T1 arg1, T2 arg2, T3 arg3);
@@ -32,8 +30,6 @@ namespace System
public delegate int Comparison<in T>(T x, T y);
public delegate TOutput Converter<in TInput, out TOutput>(TInput input);
-
- public delegate bool Predicate<in T>(T obj);
+ public delegate bool Predicate<in T>(T obj);
}
-
diff --git a/src/mscorlib/src/System/Activator.cs b/src/mscorlib/src/System/Activator.cs
index 6fad8f3173..323fbba9cc 100644
--- a/src/mscorlib/src/System/Activator.cs
+++ b/src/mscorlib/src/System/Activator.cs
@@ -22,16 +22,12 @@ namespace System {
using StackCrawlMark = System.Threading.StackCrawlMark;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
- using System.Security.Permissions;
using AssemblyHashAlgorithm = System.Configuration.Assemblies.AssemblyHashAlgorithm;
using System.Runtime.Versioning;
using System.Diagnostics.Contracts;
// Only statics, does not need to be marked with the serializable attribute
- [ClassInterface(ClassInterfaceType.None)]
- [ComDefaultInterface(typeof(_Activator))]
- [System.Runtime.InteropServices.ComVisible(true)]
- public sealed class Activator : _Activator
+ public sealed class Activator
{
internal const int LookupMask = 0x000000FF;
internal const BindingFlags ConLookup = (BindingFlags) (BindingFlags.Instance | BindingFlags.Public);
@@ -209,31 +205,6 @@ namespace System {
null,
activationAttributes);
}
-
- [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,
- String typeName,
- bool ignoreCase,
- BindingFlags bindingAttr,
- Binder binder,
- Object[] args,
- CultureInfo culture,
- Object[] activationAttributes,
- Evidence securityInfo)
- {
- StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
- return CreateInstance(assemblyName,
- typeName,
- ignoreCase,
- bindingAttr,
- binder,
- args,
- culture,
- activationAttributes,
- securityInfo,
- ref stackMark);
- }
[MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
public static ObjectHandle CreateInstance(string assemblyName,
@@ -286,7 +257,7 @@ namespace System {
// Classic managed type
assembly = RuntimeAssembly.InternalLoadAssemblyName(
assemblyName, securityInfo, null, ref stackMark,
- true /*thrownOnFileNotFound*/, false /*forIntrospection*/, false /*suppressSecurityChecks*/);
+ true /*thrownOnFileNotFound*/, false /*forIntrospection*/);
}
}
@@ -314,29 +285,6 @@ namespace System {
}
}
- [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.")]
- static public ObjectHandle CreateInstanceFrom(String assemblyFile,
- String typeName,
- bool ignoreCase,
- BindingFlags bindingAttr,
- Binder binder,
- Object[] args,
- CultureInfo culture,
- Object[] activationAttributes,
- Evidence securityInfo)
-
- {
- return CreateInstanceFromInternal(assemblyFile,
- typeName,
- ignoreCase,
- bindingAttr,
- binder,
- args,
- culture,
- activationAttributes,
- securityInfo);
- }
-
public static ObjectHandle CreateInstanceFrom(string assemblyFile,
string typeName,
bool ignoreCase,
@@ -388,120 +336,6 @@ namespace System {
}
}
- //
- // This API is designed to be used when a host needs to execute code in an AppDomain
- // with restricted security permissions. In that case, we demand in the client domain
- // and assert in the server domain because the server domain might not be trusted enough
- // to pass the security checks when activating the type.
- //
-
- public static ObjectHandle CreateInstance (AppDomain domain, string assemblyName, string typeName) {
- if (domain == null)
- throw new ArgumentNullException(nameof(domain));
- Contract.EndContractBlock();
- return domain.InternalCreateInstanceWithNoSecurity(assemblyName, typeName);
- }
-
- [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,
- string typeName,
- bool ignoreCase,
- BindingFlags bindingAttr,
- Binder binder,
- Object[] args,
- CultureInfo culture,
- Object[] activationAttributes,
- Evidence securityAttributes) {
- if (domain == null)
- throw new ArgumentNullException(nameof(domain));
- Contract.EndContractBlock();
-
- return domain.InternalCreateInstanceWithNoSecurity(assemblyName, typeName, ignoreCase, bindingAttr, binder, args, culture, activationAttributes, securityAttributes);
- }
-
- public static ObjectHandle CreateInstance(AppDomain domain,
- string assemblyName,
- string typeName,
- bool ignoreCase,
- BindingFlags bindingAttr,
- Binder binder,
- object[] args,
- CultureInfo culture,
- object[] activationAttributes)
- {
- if (domain == null)
- throw new ArgumentNullException(nameof(domain));
- Contract.EndContractBlock();
-
- return domain.InternalCreateInstanceWithNoSecurity(assemblyName,
- typeName,
- ignoreCase,
- bindingAttr,
- binder,
- args,
- culture,
- activationAttributes,
- null);
- }
-
- //
- // This API is designed to be used when a host needs to execute code in an AppDomain
- // with restricted security permissions. In that case, we demand in the client domain
- // and assert in the server domain because the server domain might not be trusted enough
- // to pass the security checks when activating the type.
- //
-
- public static ObjectHandle CreateInstanceFrom (AppDomain domain, string assemblyFile, string typeName) {
- if (domain == null)
- throw new ArgumentNullException(nameof(domain));
- Contract.EndContractBlock();
- return domain.InternalCreateInstanceFromWithNoSecurity(assemblyFile, typeName);
- }
-
- [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,
- string typeName,
- bool ignoreCase,
- BindingFlags bindingAttr,
- Binder binder,
- Object[] args,
- CultureInfo culture,
- Object[] activationAttributes,
- Evidence securityAttributes) {
- if (domain == null)
- throw new ArgumentNullException(nameof(domain));
- Contract.EndContractBlock();
-
- return domain.InternalCreateInstanceFromWithNoSecurity(assemblyFile, typeName, ignoreCase, bindingAttr, binder, args, culture, activationAttributes, securityAttributes);
- }
-
- public static ObjectHandle CreateInstanceFrom(AppDomain domain,
- string assemblyFile,
- string typeName,
- bool ignoreCase,
- BindingFlags bindingAttr,
- Binder binder,
- object[] args,
- CultureInfo culture,
- object[] activationAttributes)
- {
- if (domain == null)
- throw new ArgumentNullException(nameof(domain));
- Contract.EndContractBlock();
-
- return domain.InternalCreateInstanceFromWithNoSecurity(assemblyFile,
- typeName,
- ignoreCase,
- bindingAttr,
- binder,
- args,
- culture,
- activationAttributes,
- null);
- }
-
public static ObjectHandle CreateComInstanceFrom(String assemblyName,
String typeName)
{
@@ -553,28 +387,6 @@ namespace System {
private static void Log(bool test, string title, string success, string failure)
{
}
-
- void _Activator.GetTypeInfoCount(out uint pcTInfo)
- {
- throw new NotImplementedException();
- }
-
- void _Activator.GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo)
- {
- throw new NotImplementedException();
- }
-
- void _Activator.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 _Activator.Invoke in VM\DangerousAPIs.h and
- // include _Activator in SystemDomain::IsReflectionInvocationMethod in AppDomain.cpp.
- void _Activator.Invoke(uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr)
- {
- throw new NotImplementedException();
- }
}
}
diff --git a/src/mscorlib/src/System/AppContext/AppContext.cs b/src/mscorlib/src/System/AppContext/AppContext.cs
index 41e44508f0..5a3b732fa8 100644
--- a/src/mscorlib/src/System/AppContext/AppContext.cs
+++ b/src/mscorlib/src/System/AppContext/AppContext.cs
@@ -19,6 +19,16 @@ namespace System
}
private static readonly Dictionary<string, SwitchValueState> s_switchMap = new Dictionary<string, SwitchValueState>();
+ static AppContext()
+ {
+ // Unloading event must happen before ProcessExit event
+ AppDomain.CurrentDomain.ProcessExit += OnUnloading;
+ AppDomain.CurrentDomain.ProcessExit += OnProcessExit;
+
+ // populate the AppContext with the default set of values
+ AppContextDefaultValues.PopulateDefaultValues();
+ }
+
public static string BaseDirectory
{
get
@@ -73,25 +83,28 @@ namespace System
}
}
- public static event System.EventHandler ProcessExit
- {
- add
- {
- AppDomain.CurrentDomain.ProcessExit += value;
- }
- remove
- {
- AppDomain.CurrentDomain.ProcessExit -= value;
- }
+ public static event System.EventHandler ProcessExit;
+ internal static event System.EventHandler Unloading;
+
+ private static void OnProcessExit(object sender, EventArgs e)
+ {
+ var processExit = ProcessExit;
+ if (processExit != null)
+ {
+ processExit(null, EventArgs.Empty);
+ }
}
- #region Switch APIs
- static AppContext()
+ private static void OnUnloading(object sender, EventArgs e)
{
- // populate the AppContext with the default set of values
- AppContextDefaultValues.PopulateDefaultValues();
+ var unloading = Unloading;
+ if (unloading != null)
+ {
+ unloading(null, EventArgs.Empty);
+ }
}
+ #region Switch APIs
/// <summary>
/// Try to get the value of the switch.
/// </summary>
diff --git a/src/mscorlib/src/System/AppDomain.cs b/src/mscorlib/src/System/AppDomain.cs
index fe524c4dc5..c6987392d5 100644
--- a/src/mscorlib/src/System/AppDomain.cs
+++ b/src/mscorlib/src/System/AppDomain.cs
@@ -20,9 +20,7 @@ namespace System
using System.Runtime;
using System.Runtime.CompilerServices;
using System.Security;
- using System.Security.Permissions;
using System.Security.Policy;
- using System.Security.Util;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
@@ -37,11 +35,8 @@ namespace System
using System.Runtime.Versioning;
using System.Diagnostics;
using System.Diagnostics.Contracts;
-#if FEATURE_EXCEPTION_NOTIFICATIONS
using System.Runtime.ExceptionServices;
-#endif // FEATURE_EXCEPTION_NOTIFICATIONS
- [ComVisible(true)]
public class ResolveEventArgs : EventArgs
{
private String _Name;
@@ -73,7 +68,6 @@ namespace System
}
}
- [ComVisible(true)]
public class AssemblyLoadEventArgs : EventArgs
{
private Assembly _LoadedAssembly;
@@ -91,16 +85,13 @@ namespace System
}
[Serializable]
- [ComVisible(true)]
public delegate Assembly ResolveEventHandler(Object sender, ResolveEventArgs args);
[Serializable]
- [ComVisible(true)]
public delegate void AssemblyLoadEventHandler(Object sender, AssemblyLoadEventArgs args);
[Serializable]
- [ComVisible(true)]
- public delegate void AppDomainInitializer(string[] args);
+ internal delegate void AppDomainInitializer(string[] args);
internal class AppDomainInitializerInfo
{
@@ -161,7 +152,6 @@ namespace System
if (Info==null)
return null;
AppDomainInitializer retVal=null;
- new ReflectionPermission(ReflectionPermissionFlag.MemberAccess).Assert();
for (int i=0;i<Info.Length;i++)
{
Assembly assembly=Assembly.Load(Info[i].TargetTypeAssembly);
@@ -177,12 +167,7 @@ namespace System
}
}
-
- [ClassInterface(ClassInterfaceType.None)]
- [ComDefaultInterface(typeof(System._AppDomain))]
- [ComVisible(true)]
- public sealed class AppDomain :
- _AppDomain, IEvidenceFactory
+ internal sealed class AppDomain
{
// Domain security information
// These fields initialized from the other side only. (NOTE: order
@@ -190,13 +175,12 @@ namespace System
// the EE- AppDomainBaseObject in this case)
private AppDomainManager _domainManager;
- private Dictionary<String, Object[]> _LocalStore;
+ private Dictionary<String, Object> _LocalStore;
private AppDomainSetup _FusionStore;
private Evidence _SecurityIdentity;
#pragma warning disable 169
private Object[] _Policies; // Called from the VM.
#pragma warning restore 169
- [method: System.Security.SecurityCritical]
public event AssemblyLoadEventHandler AssemblyLoad;
private ResolveEventHandler _TypeResolve;
@@ -263,7 +247,6 @@ namespace System
}
#if FEATURE_REFLECTION_ONLY_LOAD
- [method: System.Security.SecurityCritical]
public event ResolveEventHandler ReflectionOnlyAssemblyResolve;
#endif // FEATURE_REFLECTION_ONLY
@@ -279,10 +262,8 @@ namespace System
// keys, the vhe values are ignored.
private Dictionary<String, object> _compatFlags;
-#if FEATURE_EXCEPTION_NOTIFICATIONS
// Delegate that will hold references to FirstChance exception notifications
private EventHandler<FirstChanceExceptionEventArgs> _firstChanceException;
-#endif // FEATURE_EXCEPTION_NOTIFICATIONS
private IntPtr _pDomain; // this is an unmanaged pointer (AppDomain * m_pDomain)` used from the VM.
@@ -366,9 +347,6 @@ namespace System
string assembly,
string type);
- [MethodImplAttribute(MethodImplOptions.InternalCall)]
- private static extern void nSetHostSecurityManagerFlags (HostSecurityManagerOptions flags);
-
[SuppressUnmanagedCodeSecurity]
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
private static extern void SetSecurityHomogeneousFlag(AppDomainHandle domain,
@@ -398,7 +376,6 @@ namespace System
Debug.Assert(_domainManager == null, "_domainManager == null");
AppDomainSetup adSetup = FusionStore;
-#if FEATURE_VERSIONING
String trustedPlatformAssemblies = (String)(GetData("TRUSTED_PLATFORM_ASSEMBLIES"));
if (trustedPlatformAssemblies != null)
{
@@ -427,7 +404,6 @@ namespace System
}
SetupBindingPaths(trustedPlatformAssemblies, platformResourceRoots, appPaths, appNiPaths, appLocalWinMD);
}
-#endif // FEATURE_VERSIONING
string domainManagerAssembly;
string domainManagerType;
@@ -437,9 +413,7 @@ namespace System
{
try
{
- new PermissionSet(PermissionState.Unrestricted).Assert();
_domainManager = CreateInstanceAndUnwrap(domainManagerAssembly, domainManagerType) as AppDomainManager;
- CodeAccessPermission.RevertAssert();
}
catch (FileNotFoundException e)
{
@@ -505,35 +479,6 @@ namespace System
CompatibilitySwitches.InitializeSwitches();
}
- // Retrieves a possibly-cached target framework name for this appdomain. This could be set
- // 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).
- internal String GetTargetFrameworkName()
- {
- String targetFrameworkName = _FusionStore.TargetFrameworkName;
-
- if (targetFrameworkName == null && IsDefaultAppDomain() && !_FusionStore.CheckedForTargetFrameworkName)
- {
- // This should only be run in the default appdomain. All other appdomains should have
- // values copied from the default appdomain and/or specified by the host.
- Assembly assembly = Assembly.GetEntryAssembly();
- if (assembly != null)
- {
- TargetFrameworkAttribute[] attrs = (TargetFrameworkAttribute[])assembly.GetCustomAttributes(typeof(TargetFrameworkAttribute));
- if (attrs != null && attrs.Length > 0)
- {
- Debug.Assert(attrs.Length == 1);
- targetFrameworkName = attrs[0].FrameworkName;
- _FusionStore.TargetFrameworkName = targetFrameworkName;
- }
- }
- _FusionStore.CheckedForTargetFrameworkName = true;
- }
-
- return targetFrameworkName;
- }
-
/// <summary>
/// Returns the setting of the corresponding compatibility config switch (see CreateAppDomainManager for the impact).
/// </summary>
@@ -605,38 +550,6 @@ namespace System
}
/// <summary>
- /// Checks (and throws on failure) if the domain supports Assembly.LoadWithPartialName.
- /// </summary>
- [Pure]
- internal static void CheckLoadWithPartialNameSupported(StackCrawlMark stackMark)
- {
-#if FEATURE_APPX
- if (IsAppXModel())
- {
- RuntimeAssembly callingAssembly = RuntimeAssembly.GetExecutingAssembly(ref stackMark);
- bool callerIsFxAssembly = callingAssembly != null && callingAssembly.IsFrameworkAssembly();
- if (!callerIsFxAssembly)
- {
- throw new NotSupportedException(Environment.GetResourceString("NotSupported_AppX", "Assembly.LoadWithPartialName"));
- }
- }
-#endif
- }
-
- /// <summary>
- /// Checks (and throws on failure) if the domain supports DefinePInvokeMethod.
- /// </summary>
- [Pure]
- internal static void CheckDefinePInvokeSupported()
- {
- // We don't want users to use DefinePInvokeMethod in RefEmit to bypass app store validation on allowed native libraries.
-#if FEATURE_APPX
- if (IsAppXModel())
- throw new NotSupportedException(Environment.GetResourceString("NotSupported_AppX", "DefinePInvokeMethod"));
-#endif
- }
-
- /// <summary>
/// Checks (and throws on failure) if the domain supports Assembly.Load(byte[] ...).
/// </summary>
[Pure]
@@ -649,26 +562,6 @@ namespace System
}
/// <summary>
- /// Checks (and throws on failure) if the domain supports AppDomain.CreateDomain.
- /// </summary>
- [Pure]
- internal static void CheckCreateDomainSupported()
- {
-#if FEATURE_APPX
- // Can create a new domain in an AppX process only when DevMode is enabled and
- // AssemblyLoadingCompat is not enabled (since there is no multi-domain support
- // for LoadFrom and LoadFile in AppX.
- if(IsAppXModel())
- {
- if (!IsAppXDesignMode())
- {
- throw new NotSupportedException(Environment.GetResourceString("NotSupported_AppX", "AppDomain.CreateDomain"));
- }
- }
-#endif
- }
-
- /// <summary>
/// Get the name of the assembly and type that act as the AppDomainManager for this domain
/// </summary>
internal void GetAppDomainManagerType(out string assembly, out string type)
@@ -811,319 +704,6 @@ namespace System
}
#endif // FEATURE_REFLECTION_ONLY_LOAD
-
- /**********************************************
- * If an AssemblyName has a public key specified, the assembly is assumed
- * to have a strong name and a hash will be computed when the assembly
- * is saved.
- **********************************************/
- [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
- public AssemblyBuilder DefineDynamicAssembly(
- AssemblyName name,
- AssemblyBuilderAccess access)
- {
- Contract.Ensures(Contract.Result<AssemblyBuilder>() != null);
-
- StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
- return InternalDefineDynamicAssembly(name, access, null,
- null, null, null, null, ref stackMark, null, SecurityContextSource.CurrentAssembly);
- }
-
- [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
- public AssemblyBuilder DefineDynamicAssembly(
- AssemblyName name,
- AssemblyBuilderAccess access,
- IEnumerable<CustomAttributeBuilder> assemblyAttributes)
- {
- Contract.Ensures(Contract.Result<AssemblyBuilder>() != null);
-
- StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
- return InternalDefineDynamicAssembly(name,
- access,
- null, null, null, null, null,
- ref stackMark,
- assemblyAttributes, SecurityContextSource.CurrentAssembly);
- }
-
- [MethodImplAttribute(MethodImplOptions.NoInlining)] // Due to the stack crawl mark
- public AssemblyBuilder DefineDynamicAssembly(AssemblyName name,
- AssemblyBuilderAccess access,
- IEnumerable<CustomAttributeBuilder> assemblyAttributes,
- SecurityContextSource securityContextSource)
- {
- Contract.Ensures(Contract.Result<AssemblyBuilder>() != null);
-
- StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
- return InternalDefineDynamicAssembly(name,
- access,
- null, null, null, null, null,
- ref stackMark,
- assemblyAttributes,
- securityContextSource);
- }
-
- [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
- public AssemblyBuilder DefineDynamicAssembly(
- AssemblyName name,
- AssemblyBuilderAccess access,
- String dir)
- {
- Contract.Ensures(Contract.Result<AssemblyBuilder>() != null);
-
- StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
- return InternalDefineDynamicAssembly(name, access, dir,
- null, null, null, null,
- ref stackMark,
- null,
- SecurityContextSource.CurrentAssembly);
- }
-
- [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(
- AssemblyName name,
- AssemblyBuilderAccess access,
- Evidence evidence)
- {
- Contract.Ensures(Contract.Result<AssemblyBuilder>() != null);
-
- StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
- return InternalDefineDynamicAssembly(name, access, null,
- evidence, null, null, null,
- ref stackMark,
- null,
- SecurityContextSource.CurrentAssembly);
- }
-
- [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(
- AssemblyName name,
- AssemblyBuilderAccess access,
- PermissionSet requiredPermissions,
- PermissionSet optionalPermissions,
- PermissionSet refusedPermissions)
- {
- Contract.Ensures(Contract.Result<AssemblyBuilder>() != null);
-
- StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
- return InternalDefineDynamicAssembly(name, access, null, null,
- requiredPermissions,
- optionalPermissions,
- refusedPermissions,
- ref stackMark,
- null,
- SecurityContextSource.CurrentAssembly);
- }
-
- [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(
- AssemblyName name,
- AssemblyBuilderAccess access,
- String dir,
- Evidence evidence)
- {
- Contract.Ensures(Contract.Result<AssemblyBuilder>() != null);
-
- StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
- return InternalDefineDynamicAssembly(name, access, dir, evidence,
- null, null, null, ref stackMark, null, SecurityContextSource.CurrentAssembly);
- }
-
- [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(
- AssemblyName name,
- AssemblyBuilderAccess access,
- String dir,
- PermissionSet requiredPermissions,
- PermissionSet optionalPermissions,
- PermissionSet refusedPermissions)
- {
- Contract.Ensures(Contract.Result<AssemblyBuilder>() != null);
-
- StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
- return InternalDefineDynamicAssembly(name, access, dir, null,
- requiredPermissions,
- optionalPermissions,
- refusedPermissions,
- ref stackMark,
- null,
- SecurityContextSource.CurrentAssembly);
- }
-
- [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(
- AssemblyName name,
- AssemblyBuilderAccess access,
- Evidence evidence,
- PermissionSet requiredPermissions,
- PermissionSet optionalPermissions,
- PermissionSet refusedPermissions)
- {
- Contract.Ensures(Contract.Result<AssemblyBuilder>() != null);
-
- StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
- return InternalDefineDynamicAssembly(name, access, null,
- evidence,
- requiredPermissions,
- optionalPermissions,
- refusedPermissions,
- ref stackMark,
- null,
- SecurityContextSource.CurrentAssembly);
- }
-
- [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(
- AssemblyName name,
- AssemblyBuilderAccess access,
- String dir,
- Evidence evidence,
- PermissionSet requiredPermissions,
- PermissionSet optionalPermissions,
- PermissionSet refusedPermissions)
- {
- Contract.Ensures(Contract.Result<AssemblyBuilder>() != null);
-
- StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
- return InternalDefineDynamicAssembly(name, access, dir,
- evidence,
- requiredPermissions,
- optionalPermissions,
- refusedPermissions,
- ref stackMark,
- null,
- SecurityContextSource.CurrentAssembly);
- }
-
- [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(
- AssemblyName name,
- AssemblyBuilderAccess access,
- String dir,
- Evidence evidence,
- PermissionSet requiredPermissions,
- PermissionSet optionalPermissions,
- PermissionSet refusedPermissions,
- bool isSynchronized)
- {
- Contract.Ensures(Contract.Result<AssemblyBuilder>() != null);
-
- StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
- return InternalDefineDynamicAssembly(name,
- access,
- dir,
- evidence,
- requiredPermissions,
- optionalPermissions,
- refusedPermissions,
- ref stackMark,
- null,
- SecurityContextSource.CurrentAssembly);
- }
-
- [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(
- AssemblyName name,
- AssemblyBuilderAccess access,
- String dir,
- Evidence evidence,
- PermissionSet requiredPermissions,
- PermissionSet optionalPermissions,
- PermissionSet refusedPermissions,
- bool isSynchronized,
- IEnumerable<CustomAttributeBuilder> assemblyAttributes)
- {
- Contract.Ensures(Contract.Result<AssemblyBuilder>() != null);
-
- StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
- return InternalDefineDynamicAssembly(name,
- access,
- dir,
- evidence,
- requiredPermissions,
- optionalPermissions,
- refusedPermissions,
- ref stackMark,
- assemblyAttributes,
- SecurityContextSource.CurrentAssembly);
- }
-
- [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
- public AssemblyBuilder DefineDynamicAssembly(
- AssemblyName name,
- AssemblyBuilderAccess access,
- String dir,
- bool isSynchronized,
- IEnumerable<CustomAttributeBuilder> assemblyAttributes)
- {
- Contract.Ensures(Contract.Result<AssemblyBuilder>() != null);
-
- StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
- return InternalDefineDynamicAssembly(name,
- access,
- dir,
- null,
- null,
- null,
- null,
- ref stackMark,
- assemblyAttributes,
- SecurityContextSource.CurrentAssembly);
- }
-
- [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
- private AssemblyBuilder InternalDefineDynamicAssembly(
- AssemblyName name,
- AssemblyBuilderAccess access,
- String dir,
- Evidence evidence,
- PermissionSet requiredPermissions,
- PermissionSet optionalPermissions,
- PermissionSet refusedPermissions,
- ref StackCrawlMark stackMark,
- IEnumerable<CustomAttributeBuilder> assemblyAttributes,
- SecurityContextSource securityContextSource)
- {
- return AssemblyBuilder.InternalDefineDynamicAssembly(name,
- access,
- dir,
- evidence,
- requiredPermissions,
- optionalPermissions,
- refusedPermissions,
- ref stackMark,
- assemblyAttributes,
- securityContextSource);
- }
-
- [MethodImplAttribute(MethodImplOptions.InternalCall)]
- private extern String nApplyPolicy(AssemblyName an);
-
- // Return the assembly name that results from applying policy.
- [ComVisible(false)]
- public String ApplyPolicy(String assemblyName)
- {
- AssemblyName asmName = new AssemblyName(assemblyName);
-
- byte[] pk = asmName.GetPublicKeyToken();
- if (pk == null)
- pk = asmName.GetPublicKey();
-
- // Simply-named assemblies cannot have policy, so for those,
- // we simply return the passed-in assembly name.
- if ((pk == null) || (pk.Length == 0))
- return assemblyName;
- else
- return nApplyPolicy(asmName);
- }
-
public ObjectHandle CreateInstance(String assemblyName,
String typeName)
@@ -1140,437 +720,6 @@ namespace System
typeName);
}
- internal ObjectHandle InternalCreateInstanceWithNoSecurity (string assemblyName, string typeName) {
- PermissionSet.s_fullTrust.Assert();
- return CreateInstance(assemblyName, typeName);
- }
-
- public ObjectHandle CreateInstanceFrom(String assemblyFile,
- String typeName)
-
- {
- // jit does not check for that, so we should do it ...
- if (this == null)
- throw new NullReferenceException();
- Contract.EndContractBlock();
-
- return Activator.CreateInstanceFrom(assemblyFile,
- typeName);
- }
-
- internal ObjectHandle InternalCreateInstanceFromWithNoSecurity (string assemblyName, string typeName) {
- PermissionSet.s_fullTrust.Assert();
- return CreateInstanceFrom(assemblyName, typeName);
- }
-
-#if FEATURE_COMINTEROP
- // The first parameter should be named assemblyFile, but it was incorrectly named in a previous
- // release, and the compatibility police won't let us change the name now.
- public ObjectHandle CreateComInstanceFrom(String assemblyName,
- String typeName)
-
- {
- if (this == null)
- throw new NullReferenceException();
- Contract.EndContractBlock();
-
- return Activator.CreateComInstanceFrom(assemblyName,
- typeName);
- }
-
- public ObjectHandle CreateComInstanceFrom(String assemblyFile,
- String typeName,
- byte[] hashValue,
- AssemblyHashAlgorithm hashAlgorithm)
-
- {
- if (this == null)
- throw new NullReferenceException();
- Contract.EndContractBlock();
-
- return Activator.CreateComInstanceFrom(assemblyFile,
- typeName,
- hashValue,
- hashAlgorithm);
- }
-
-#endif // FEATURE_COMINTEROP
-
- public ObjectHandle CreateInstance(String assemblyName,
- String typeName,
- Object[] activationAttributes)
-
- {
- // jit does not check for that, so we should do it ...
- if (this == null)
- throw new NullReferenceException();
-
- if (assemblyName == null)
- throw new ArgumentNullException(nameof(assemblyName));
- Contract.EndContractBlock();
-
- return Activator.CreateInstance(assemblyName,
- typeName,
- activationAttributes);
- }
-
- public ObjectHandle CreateInstanceFrom(String assemblyFile,
- String typeName,
- Object[] activationAttributes)
-
- {
- // jit does not check for that, so we should do it ...
- if (this == null)
- throw new NullReferenceException();
- Contract.EndContractBlock();
-
- return Activator.CreateInstanceFrom(assemblyFile,
- typeName,
- activationAttributes);
- }
-
- [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 ObjectHandle CreateInstance(String assemblyName,
- String typeName,
- bool ignoreCase,
- BindingFlags bindingAttr,
- Binder binder,
- Object[] args,
- CultureInfo culture,
- Object[] activationAttributes,
- Evidence securityAttributes)
- {
- // jit does not check for that, so we should do it ...
- if (this == null)
- throw new NullReferenceException();
-
- if (assemblyName == null)
- throw new ArgumentNullException(nameof(assemblyName));
- Contract.EndContractBlock();
-
-#pragma warning disable 618
- return Activator.CreateInstance(assemblyName,
- typeName,
- ignoreCase,
- bindingAttr,
- binder,
- args,
- culture,
- activationAttributes,
- securityAttributes);
-#pragma warning restore 618
- }
-
- public ObjectHandle CreateInstance(string assemblyName,
- string typeName,
- bool ignoreCase,
- BindingFlags bindingAttr,
- Binder binder,
- object[] args,
- CultureInfo culture,
- object[] activationAttributes)
- {
- // jit does not check for that, so we should do it ...
- if (this == null)
- throw new NullReferenceException();
-
- if (assemblyName == null)
- throw new ArgumentNullException(nameof(assemblyName));
- Contract.EndContractBlock();
-
- return Activator.CreateInstance(assemblyName,
- typeName,
- ignoreCase,
- bindingAttr,
- binder,
- args,
- culture,
- activationAttributes);
- }
-
- internal ObjectHandle InternalCreateInstanceWithNoSecurity (string assemblyName,
- string typeName,
- bool ignoreCase,
- BindingFlags bindingAttr,
- Binder binder,
- Object[] args,
- CultureInfo culture,
- Object[] activationAttributes,
- Evidence securityAttributes)
- {
- PermissionSet.s_fullTrust.Assert();
-#pragma warning disable 618
- return CreateInstance(assemblyName, typeName, ignoreCase, bindingAttr, binder, args, culture, activationAttributes, securityAttributes);
-#pragma warning restore 618
- }
-
- [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 ObjectHandle CreateInstanceFrom(String assemblyFile,
- String typeName,
- bool ignoreCase,
- BindingFlags bindingAttr,
- Binder binder,
- Object[] args,
- CultureInfo culture,
- Object[] activationAttributes,
- Evidence securityAttributes)
-
- {
- // jit does not check for that, so we should do it ...
- if (this == null)
- throw new NullReferenceException();
- Contract.EndContractBlock();
-
- return Activator.CreateInstanceFrom(assemblyFile,
- typeName,
- ignoreCase,
- bindingAttr,
- binder,
- args,
- culture,
- activationAttributes,
- securityAttributes);
- }
-
- public ObjectHandle CreateInstanceFrom(string assemblyFile,
- string typeName,
- bool ignoreCase,
- BindingFlags bindingAttr,
- Binder binder,
- object[] args,
- CultureInfo culture,
- object[] activationAttributes)
- {
- // jit does not check for that, so we should do it ...
- if (this == null)
- throw new NullReferenceException();
- Contract.EndContractBlock();
-
- return Activator.CreateInstanceFrom(assemblyFile,
- typeName,
- ignoreCase,
- bindingAttr,
- binder,
- args,
- culture,
- activationAttributes);
- }
-
- internal ObjectHandle InternalCreateInstanceFromWithNoSecurity (string assemblyName,
- string typeName,
- bool ignoreCase,
- BindingFlags bindingAttr,
- Binder binder,
- Object[] args,
- CultureInfo culture,
- Object[] activationAttributes,
- Evidence securityAttributes)
- {
- PermissionSet.s_fullTrust.Assert();
-#pragma warning disable 618
- return CreateInstanceFrom(assemblyName, typeName, ignoreCase, bindingAttr, binder, args, culture, activationAttributes, securityAttributes);
-#pragma warning restore 618
- }
-
- [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
- public Assembly Load(AssemblyName assemblyRef)
- {
- StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
- return RuntimeAssembly.InternalLoadAssemblyName(assemblyRef, null, null, ref stackMark, true /*thrownOnFileNotFound*/, false, false);
- }
-
- [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
- public Assembly Load(String assemblyString)
- {
- StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
- return RuntimeAssembly.InternalLoad(assemblyString, null, ref stackMark, false);
- }
-
- [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
- public Assembly Load(byte[] rawAssembly)
- {
- StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
- return RuntimeAssembly.nLoadImage(rawAssembly,
- null, // symbol store
- null, // evidence
- ref stackMark,
- false,
- SecurityContextSource.CurrentAssembly);
-
- }
-
- [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
- public Assembly Load(byte[] rawAssembly,
- byte[] rawSymbolStore)
- {
- StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
- return RuntimeAssembly.nLoadImage(rawAssembly,
- rawSymbolStore,
- null, // evidence
- ref stackMark,
- false, // fIntrospection
- SecurityContextSource.CurrentAssembly);
- }
-
- [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)
- {
- StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
- return RuntimeAssembly.nLoadImage(rawAssembly,
- rawSymbolStore,
- securityEvidence,
- ref stackMark,
- false, // fIntrospection
- SecurityContextSource.CurrentAssembly);
- }
-
- [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,
- Evidence assemblySecurity)
- {
- StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
- return RuntimeAssembly.InternalLoadAssemblyName(assemblyRef, assemblySecurity, null, ref stackMark, true /*thrownOnFileNotFound*/, false, false);
- }
-
- [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,
- Evidence assemblySecurity)
- {
- StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
- return RuntimeAssembly.InternalLoad(assemblyString, assemblySecurity, ref stackMark, false);
- }
-
- public int ExecuteAssembly(String assemblyFile)
- {
- return ExecuteAssembly(assemblyFile, (string[])null);
- }
-
- [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 ExecuteAssembly which does not take an Evidence parameter. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.")]
- public int ExecuteAssembly(String assemblyFile,
- Evidence assemblySecurity)
- {
- return ExecuteAssembly(assemblyFile, assemblySecurity, null);
- }
-
- [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 ExecuteAssembly which does not take an Evidence parameter. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.")]
- public int ExecuteAssembly(String assemblyFile,
- Evidence assemblySecurity,
- String[] args)
- {
- RuntimeAssembly assembly = (RuntimeAssembly)Assembly.LoadFrom(assemblyFile, assemblySecurity);
-
- if (args == null)
- args = new String[0];
-
- return nExecuteAssembly(assembly, args);
- }
-
- public int ExecuteAssembly(string assemblyFile, string[] args)
- {
- RuntimeAssembly assembly = (RuntimeAssembly)Assembly.LoadFrom(assemblyFile);
-
- if (args == null)
- args = new String[0];
-
- return nExecuteAssembly(assembly, args);
- }
-
- [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 ExecuteAssembly which does not take an Evidence parameter. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.")]
- public int ExecuteAssembly(String assemblyFile,
- Evidence assemblySecurity,
- String[] args,
- byte[] hashValue,
- AssemblyHashAlgorithm hashAlgorithm)
- {
- RuntimeAssembly assembly = (RuntimeAssembly)Assembly.LoadFrom(assemblyFile,
- assemblySecurity,
- hashValue,
- hashAlgorithm);
- if (args == null)
- args = new String[0];
-
- return nExecuteAssembly(assembly, args);
- }
-
- public int ExecuteAssembly(string assemblyFile,
- string[] args,
- byte[] hashValue,
- AssemblyHashAlgorithm hashAlgorithm)
- {
- RuntimeAssembly assembly = (RuntimeAssembly)Assembly.LoadFrom(assemblyFile,
- hashValue,
- hashAlgorithm);
- if (args == null)
- args = new String[0];
-
- return nExecuteAssembly(assembly, args);
- }
-
- public int ExecuteAssemblyByName(String assemblyName)
- {
- return ExecuteAssemblyByName(assemblyName, (string[])null);
- }
-
- [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 ExecuteAssemblyByName which does not take an Evidence parameter. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.")]
- public int ExecuteAssemblyByName(String assemblyName,
- Evidence assemblySecurity)
- {
-#pragma warning disable 618
- return ExecuteAssemblyByName(assemblyName, assemblySecurity, null);
-#pragma warning restore 618
- }
-
- [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 ExecuteAssemblyByName which does not take an Evidence parameter. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.")]
- public int ExecuteAssemblyByName(String assemblyName,
- Evidence assemblySecurity,
- params String[] args)
- {
- RuntimeAssembly assembly = (RuntimeAssembly)Assembly.Load(assemblyName, assemblySecurity);
-
- if (args == null)
- args = new String[0];
-
- return nExecuteAssembly(assembly, args);
- }
-
- public int ExecuteAssemblyByName(string assemblyName, params string[] args)
- {
- RuntimeAssembly assembly = (RuntimeAssembly)Assembly.Load(assemblyName);
-
- if (args == null)
- args = new String[0];
-
- return nExecuteAssembly(assembly, args);
- }
-
- [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 ExecuteAssemblyByName which does not take an Evidence parameter. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.")]
- public int ExecuteAssemblyByName(AssemblyName assemblyName,
- Evidence assemblySecurity,
- params String[] args)
- {
- RuntimeAssembly assembly = (RuntimeAssembly)Assembly.Load(assemblyName, assemblySecurity);
-
- if (args == null)
- args = new String[0];
-
- return nExecuteAssembly(assembly, args);
- }
-
- public int ExecuteAssemblyByName(AssemblyName assemblyName, params string[] args)
- {
- RuntimeAssembly assembly = (RuntimeAssembly)Assembly.Load(assemblyName);
-
- if (args == null)
- args = new String[0];
-
- return nExecuteAssembly(assembly, args);
- }
-
public static AppDomain CurrentDomain
{
get {
@@ -1579,11 +728,6 @@ namespace System
}
}
- public String FriendlyName
- {
- get { return nGetFriendlyName(); }
- }
-
public String BaseDirectory
{
get {
@@ -1616,19 +760,6 @@ namespace System
return StringBuilderCache.GetStringAndRelease(sb);
}
- public Assembly[] GetAssemblies()
- {
- return nGetAssemblies(false /* forIntrospection */);
- }
-
- public Assembly[] ReflectionOnlyGetAssemblies()
- {
- return nGetAssemblies(true /* forIntrospection */);
- }
-
- [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
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern bool IsUnloadingForcedFinalize();
@@ -1642,38 +773,22 @@ namespace System
internal static extern void PublishAnonymouslyHostedDynamicMethodsAssembly(RuntimeAssembly assemblyHandle);
public void SetData (string name, object data) {
- SetDataHelper(name, data, null);
- }
-
- 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));
- }
-
- SetDataHelper(name, data, permission);
- }
-
- private void SetDataHelper (string name, object data, IPermission permission)
- {
if (name == null)
throw new ArgumentNullException(nameof(name));
Contract.EndContractBlock();
// SetData should only be used to set values that don't already exist.
- object[] currentVal;
+ object currentVal;
lock (((ICollection)LocalStore).SyncRoot) {
LocalStore.TryGetValue(name, out currentVal);
}
- if (currentVal != null && currentVal[0] != null)
+ if (currentVal != null)
{
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_SetData_OnlyOnce"));
}
lock (((ICollection)LocalStore).SyncRoot) {
- LocalStore[name] = new object[] {data, permission};
+ LocalStore[name] = data;
}
}
@@ -1687,23 +802,17 @@ namespace System
int key = AppDomainSetup.Locate(name);
if(key == -1)
{
-#if FEATURE_LOADER_OPTIMIZATION
if(name.Equals(AppDomainSetup.LoaderOptimizationKey))
return FusionStore.LoaderOptimization;
else
-#endif // FEATURE_LOADER_OPTIMIZATION
{
- object[] data;
+ object data;
lock (((ICollection)LocalStore).SyncRoot) {
LocalStore.TryGetValue(name, out data);
}
if (data == null)
return null;
- if (data[1] != null) {
- IPermission permission = (IPermission) data[1];
- permission.Demand();
- }
- return data[0];
+ return data;
}
}
else {
@@ -1720,71 +829,16 @@ namespace System
}
}
}
-
- // The compat flags are set at domain creation time to indicate that the given breaking
- // change should not be used in this domain.
- //
- // After the domain has been created, this Nullable boolean returned by this method should
- // always have a value. Code in the runtime uses this to know if it is safe to cache values
- // that might change if the compatibility switches have not been set yet.
- public Nullable<bool> IsCompatibilitySwitchSet(String value)
- {
- Nullable<bool> fReturn;
-
- if (_compatFlagsInitialized == false)
- {
- fReturn = new Nullable<bool>();
- }
- else
- {
- fReturn = new Nullable<bool>(_compatFlags != null && _compatFlags.ContainsKey(value));
- }
-
- return fReturn;
- }
[Obsolete("AppDomain.GetCurrentThreadId has been deprecated because it does not provide a stable Id when managed threads are running on fibers (aka lightweight threads). To get a stable identifier for a managed thread, use the ManagedThreadId property on Thread. http://go.microsoft.com/fwlink/?linkid=14202", false)]
[DllImport(Microsoft.Win32.Win32Native.KERNEL32)]
public static extern int GetCurrentThreadId();
- internal ApplicationTrust ApplicationTrust
- {
- get {
- if (_applicationTrust == null && _IsFastFullTrustDomain) {
- _applicationTrust = new ApplicationTrust(new PermissionSet(PermissionState.Unrestricted));
- }
-
- return _applicationTrust;
- }
- }
-
- public String DynamicDirectory
- {
- get {
- String dyndir = GetDynamicDir();
- if (dyndir != null)
- new FileIOPermission( FileIOPermissionAccess.PathDiscovery, dyndir ).Demand();
-
- return dyndir;
- }
- }
-
- [MethodImplAttribute(MethodImplOptions.InternalCall)]
- extern private String GetDynamicDir();
-
private AppDomain() {
throw new NotSupportedException(Environment.GetResourceString(ResId.NotSupported_Constructor));
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
- private extern int _nExecuteAssembly(RuntimeAssembly assembly, String[] args);
- internal int nExecuteAssembly(RuntimeAssembly assembly, String[] args)
- {
- return _nExecuteAssembly(assembly, args);
- }
-
-#if FEATURE_VERSIONING
- [MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern void nCreateContext();
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
@@ -1795,12 +849,9 @@ namespace System
{
nSetupBindingPaths(trustedPlatformAssemblies, platformResourceRoots, appPath, appNiPaths, appLocalWinMD);
}
-#endif // FEATURE_VERSIONING
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private extern String nGetFriendlyName();
- [MethodImplAttribute(MethodImplOptions.InternalCall)]
- private extern bool nIsDefaultAppDomainForEvidence();
// support reliability for certain event handlers, if the target
// methods also participate in this discipline. If caller passes
@@ -1864,7 +915,6 @@ namespace System
}
}
-#if FEATURE_EXCEPTION_NOTIFICATIONS
// This is the event managed code can wireup against to be notified
// about first chance exceptions.
//
@@ -1886,7 +936,6 @@ namespace System
_firstChanceException -= value;
}
}
-#endif // FEATURE_EXCEPTION_NOTIFICATIONS
private void OnAssemblyLoadEvent(RuntimeAssembly LoadedAssembly)
{
@@ -1990,24 +1039,18 @@ namespace System
return null;
}
- private Dictionary<String, Object[]> LocalStore
+ private Dictionary<String, Object> LocalStore
{
get {
if (_LocalStore != null)
return _LocalStore;
else {
- _LocalStore = new Dictionary<String, Object[]>();
+ _LocalStore = new Dictionary<String, Object>();
return _LocalStore;
}
}
}
- // Used to determine if server object context is valid in
- // x-domain remoting scenarios.
- [MethodImplAttribute(MethodImplOptions.InternalCall)]
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
- internal static extern bool IsDomainIdValid(Int32 id);
-
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private static extern void nSetNativeDllSearchDirectories(string paths);
@@ -2021,27 +1064,14 @@ namespace System
info.SetupDefaults(RuntimeEnvironment.GetModuleFileName(), imageLocationAlreadyNormalized : true);
}
-#if FEATURE_VERSIONING
nCreateContext();
-#endif // FEATURE_VERSIONING
-#if FEATURE_LOADER_OPTIMIZATION
if (info.LoaderOptimization != LoaderOptimization.NotSpecified || (oldInfo != null && info.LoaderOptimization != oldInfo.LoaderOptimization))
UpdateLoaderOptimization(info.LoaderOptimization);
-#endif
// This must be the last action taken
_FusionStore = info;
}
- // used to package up evidence, so it can be serialized
- // for the call to InternalRemotelySetupRemoteDomain
- [Serializable]
- private class EvidenceCollection
- {
- public Evidence ProvidedSecurityInfo;
- public Evidence CreatorsSecurityInfo;
- }
-
private static void RunInitializer(AppDomainSetup setup)
{
if (setup.AppDomainInitializer!=null)
@@ -2172,7 +1202,6 @@ namespace System
newSetup.ApplicationBase = NormalizePath(propertyValues[i], fullCheck: true);
}
-#if FEATURE_LOADER_OPTIMIZATION
else if(propertyNames[i]=="LOADER_OPTIMIZATION")
{
if(propertyValues[i]==null)
@@ -2187,7 +1216,6 @@ namespace System
default: throw new ArgumentException(Environment.GetResourceString("Argument_UnrecognizedLoaderOptimization"), "LOADER_OPTIMIZATION");
}
}
-#endif // FEATURE_LOADER_OPTIMIZATION
else if(propertyNames[i]=="TRUSTED_PLATFORM_ASSEMBLIES" ||
propertyNames[i]=="PLATFORM_RESOURCE_ROOTS" ||
propertyNames[i]=="APP_PATHS" ||
@@ -2197,11 +1225,11 @@ namespace System
if(values == null)
throw new ArgumentNullException(propertyNames[i]);
- ad.SetDataHelper(propertyNames[i], NormalizeAppPaths(values), null);
+ ad.SetData(propertyNames[i], NormalizeAppPaths(values));
}
else if(propertyNames[i]!= null)
{
- ad.SetDataHelper(propertyNames[i],propertyValues[i],null); // just propagate
+ ad.SetData(propertyNames[i],propertyValues[i]); // just propagate
}
}
}
@@ -2312,22 +1340,6 @@ namespace System
}
}
-#if FEATURE_LOADER_OPTIMIZATION
- private void SetupLoaderOptimization(LoaderOptimization policy)
- {
- if(policy != LoaderOptimization.NotSpecified) {
- Debug.Assert(FusionStore.LoaderOptimization == LoaderOptimization.NotSpecified,
- "It is illegal to change the Loader optimization on a domain");
-
- FusionStore.LoaderOptimization = policy;
- UpdateLoaderOptimization(FusionStore.LoaderOptimization);
- }
- }
-#endif
-
- [MethodImplAttribute(MethodImplOptions.InternalCall)]
- internal extern IntPtr GetSecurityDescriptor();
-
private void SetupDomainSecurity(Evidence appDomainEvidence,
IntPtr creatorsSecurityDescriptor,
bool publishAppDomain)
@@ -2355,10 +1367,8 @@ namespace System
private extern void nSetDisableInterfaceCache();
#endif // FEATURE_COMINTEROP
-#if FEATURE_LOADER_OPTIMIZATION
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern void UpdateLoaderOptimization(LoaderOptimization optimization);
-#endif
public AppDomainSetup SetupInformation
{
@@ -2377,52 +1387,14 @@ namespace System
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
private static extern void GetGrantSet(AppDomainHandle domain, ObjectHandleOnStack retGrantSet);
- public PermissionSet PermissionSet
- {
- // SecurityCritical because permissions can contain sensitive information such as paths
- get
- {
- PermissionSet grantSet = null;
- GetGrantSet(GetNativeHandle(), JitHelpers.GetObjectHandleOnStack(ref grantSet));
-
- if (grantSet != null)
- {
- return grantSet.Copy();
- }
- else
- {
- return new PermissionSet(PermissionState.Unrestricted);
- }
- }
- }
-
public bool IsFullyTrusted
{
get
{
- PermissionSet grantSet = null;
- GetGrantSet(GetNativeHandle(), JitHelpers.GetObjectHandleOnStack(ref grantSet));
-
- return grantSet == null || grantSet.IsUnrestricted();
- }
- }
-
- public bool IsHomogenous
- {
- get
- {
- // Homogenous AppDomains always have an ApplicationTrust associated with them
- return _IsFastFullTrustDomain || _applicationTrust != null;
+ return true;
}
}
- [MethodImplAttribute(MethodImplOptions.InternalCall)]
- private extern void nChangeSecurityPolicy();
-
- [MethodImplAttribute(MethodImplOptions.InternalCall)]
- [ReliabilityContract(Consistency.MayCorruptAppDomain, Cer.MayFail)]
- internal static extern void nUnload(Int32 domainInternal);
-
public Object CreateInstanceAndUnwrap(String assemblyName,
String typeName)
{
@@ -2433,269 +1405,16 @@ namespace System
return oh.Unwrap();
} // CreateInstanceAndUnwrap
- public Object CreateInstanceAndUnwrap(String assemblyName,
- String typeName,
- Object[] activationAttributes)
- {
- ObjectHandle oh = CreateInstance(assemblyName, typeName, activationAttributes);
- if (oh == null)
- return null;
-
- return oh.Unwrap();
- } // CreateInstanceAndUnwrap
-
-
- [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 CreateInstanceAndUnwrap which does not take an Evidence parameter. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.")]
- public Object CreateInstanceAndUnwrap(String assemblyName,
- String typeName,
- bool ignoreCase,
- BindingFlags bindingAttr,
- Binder binder,
- Object[] args,
- CultureInfo culture,
- Object[] activationAttributes,
- Evidence securityAttributes)
- {
-#pragma warning disable 618
- ObjectHandle oh = CreateInstance(assemblyName, typeName, ignoreCase, bindingAttr,
- binder, args, culture, activationAttributes, securityAttributes);
-#pragma warning restore 618
-
- if (oh == null)
- return null;
-
- return oh.Unwrap();
- } // CreateInstanceAndUnwrap
-
- public object CreateInstanceAndUnwrap(string assemblyName,
- string typeName,
- bool ignoreCase,
- BindingFlags bindingAttr,
- Binder binder,
- object[] args,
- CultureInfo culture,
- object[] activationAttributes)
- {
- ObjectHandle oh = CreateInstance(assemblyName,
- typeName,
- ignoreCase,
- bindingAttr,
- binder,
- args,
- culture,
- activationAttributes);
-
- if (oh == null)
- {
- return null;
- }
-
- return oh.Unwrap();
- }
-
- // The first parameter should be named assemblyFile, but it was incorrectly named in a previous
- // release, and the compatibility police won't let us change the name now.
- public Object CreateInstanceFromAndUnwrap(String assemblyName,
- String typeName)
- {
- ObjectHandle oh = CreateInstanceFrom(assemblyName, typeName);
- if (oh == null)
- return null;
-
- return oh.Unwrap();
- } // CreateInstanceAndUnwrap
-
-
- // The first parameter should be named assemblyFile, but it was incorrectly named in a previous
- // release, and the compatibility police won't let us change the name now.
- public Object CreateInstanceFromAndUnwrap(String assemblyName,
- String typeName,
- Object[] activationAttributes)
- {
- ObjectHandle oh = CreateInstanceFrom(assemblyName, typeName, activationAttributes);
- if (oh == null)
- return null;
-
- return oh.Unwrap();
- } // CreateInstanceAndUnwrap
-
-
- // The first parameter should be named assemblyFile, but it was incorrectly named in a previous
- // release, and the compatibility police won't let us change the name now.
- [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 CreateInstanceFromAndUnwrap which does not take an Evidence parameter. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.")]
- public Object CreateInstanceFromAndUnwrap(String assemblyName,
- String typeName,
- bool ignoreCase,
- BindingFlags bindingAttr,
- Binder binder,
- Object[] args,
- CultureInfo culture,
- Object[] activationAttributes,
- Evidence securityAttributes)
- {
-#pragma warning disable 618
- ObjectHandle oh = CreateInstanceFrom(assemblyName, typeName, ignoreCase, bindingAttr,
- binder, args, culture, activationAttributes, securityAttributes);
-#pragma warning restore 618
-
- if (oh == null)
- return null;
-
- return oh.Unwrap();
- } // CreateInstanceAndUnwrap
-
- public object CreateInstanceFromAndUnwrap(string assemblyFile,
- string typeName,
- bool ignoreCase,
- BindingFlags bindingAttr,
- Binder binder,
- object[] args,
- CultureInfo culture,
- object[] activationAttributes)
- {
- ObjectHandle oh = CreateInstanceFrom(assemblyFile,
- typeName,
- ignoreCase,
- bindingAttr,
- binder,
- args,
- culture,
- activationAttributes);
- if (oh == null)
- {
- return null;
- }
-
- return oh.Unwrap();
- }
-
public Int32 Id
{
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
get {
return GetId();
}
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
internal extern Int32 GetId();
-
- internal const Int32 DefaultADID = 1;
-
- public bool IsDefaultAppDomain()
- {
- if (GetId()==DefaultADID)
- return true;
- return false;
- }
-
-#if FEATURE_APPDOMAIN_RESOURCE_MONITORING
- [MethodImplAttribute(MethodImplOptions.InternalCall)]
- private static extern void nEnableMonitoring();
-
- [MethodImplAttribute(MethodImplOptions.InternalCall)]
- private static extern bool nMonitoringIsEnabled();
-
- // return -1 if ARM is not supported.
- [MethodImplAttribute(MethodImplOptions.InternalCall)]
- private extern Int64 nGetTotalProcessorTime();
-
- // return -1 if ARM is not supported.
- [MethodImplAttribute(MethodImplOptions.InternalCall)]
- private extern Int64 nGetTotalAllocatedMemorySize();
-
- // return -1 if ARM is not supported.
- [MethodImplAttribute(MethodImplOptions.InternalCall)]
- private extern Int64 nGetLastSurvivedMemorySize();
-
- // return -1 if ARM is not supported.
- [MethodImplAttribute(MethodImplOptions.InternalCall)]
- private static extern Int64 nGetLastSurvivedProcessMemorySize();
-
- public static bool MonitoringIsEnabled
- {
- get {
- return nMonitoringIsEnabled();
- }
-
- set {
- if (value == false)
- {
- throw new ArgumentException(Environment.GetResourceString("Arg_MustBeTrue"));
- }
- else
- {
- nEnableMonitoring();
- }
- }
- }
- // Gets the total processor time for this AppDomain.
- // Throws NotSupportedException if ARM is not enabled.
- public TimeSpan MonitoringTotalProcessorTime
- {
- get {
- Int64 i64ProcessorTime = nGetTotalProcessorTime();
- if (i64ProcessorTime == -1)
- {
- throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_WithoutARM"));
- }
- return new TimeSpan(i64ProcessorTime);
- }
- }
-
- // Gets the number of bytes allocated in this AppDomain since
- // the AppDomain was created.
- // Throws NotSupportedException if ARM is not enabled.
- public Int64 MonitoringTotalAllocatedMemorySize
- {
- get {
- Int64 i64AllocatedMemory = nGetTotalAllocatedMemorySize();
- if (i64AllocatedMemory == -1)
- {
- throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_WithoutARM"));
- }
- return i64AllocatedMemory;
- }
- }
-
- // Gets the number of bytes survived after the last collection
- // that are known to be held by this AppDomain. After a full
- // collection this number is accurate and complete. After an
- // ephemeral collection this number is potentially incomplete.
- // Throws NotSupportedException if ARM is not enabled.
- public Int64 MonitoringSurvivedMemorySize
- {
- get {
- Int64 i64LastSurvivedMemory = nGetLastSurvivedMemorySize();
- if (i64LastSurvivedMemory == -1)
- {
- throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_WithoutARM"));
- }
- return i64LastSurvivedMemory;
- }
- }
-
- // Gets the total bytes survived from the last collection. After
- // a full collection this number represents the number of the bytes
- // being held live in managed heaps. (This number should be close
- // to the number obtained from GC.GetTotalMemory for a full collection.)
- // After an ephemeral collection this number represents the number
- // of bytes being held live in ephemeral generations.
- // Throws NotSupportedException if ARM is not enabled.
- public static Int64 MonitoringSurvivedProcessMemorySize
- {
- get {
- Int64 i64LastSurvivedProcessMemory = nGetLastSurvivedProcessMemorySize();
- if (i64LastSurvivedProcessMemory == -1)
- {
- throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_WithoutARM"));
- }
- return i64LastSurvivedProcessMemory;
- }
- }
-#endif
}
/// <summary>
diff --git a/src/mscorlib/src/System/AppDomainAttributes.cs b/src/mscorlib/src/System/AppDomainAttributes.cs
index 0980b5fe90..960f9c1cac 100644
--- a/src/mscorlib/src/System/AppDomainAttributes.cs
+++ b/src/mscorlib/src/System/AppDomainAttributes.cs
@@ -14,8 +14,7 @@
namespace System {
[Serializable]
- [System.Runtime.InteropServices.ComVisible(true)]
- public enum LoaderOptimization
+ internal enum LoaderOptimization
{
NotSpecified = 0,
SingleDomain = 1,
@@ -26,23 +25,5 @@ namespace System {
[Obsolete("This method has been deprecated. Please use Assembly.Load() instead. http://go.microsoft.com/fwlink/?linkid=14202")]
DisallowBindings = 4
}
-
- [AttributeUsage (AttributeTargets.Method)]
- [System.Runtime.InteropServices.ComVisible(true)]
- public sealed class LoaderOptimizationAttribute : Attribute
- {
- internal byte _val;
-
- public LoaderOptimizationAttribute(byte value)
- {
- _val = value;
- }
- public LoaderOptimizationAttribute(LoaderOptimization value)
- {
- _val = (byte) value;
- }
- public LoaderOptimization Value
- { get {return (LoaderOptimization) _val;} }
- }
}
diff --git a/src/mscorlib/src/System/AppDomainManager.cs b/src/mscorlib/src/System/AppDomainManager.cs
index 71bc088d1d..bd2faa0110 100644
--- a/src/mscorlib/src/System/AppDomainManager.cs
+++ b/src/mscorlib/src/System/AppDomainManager.cs
@@ -15,8 +15,7 @@ namespace System
using System.Security;
using System.Runtime.InteropServices;
- [System.Runtime.InteropServices.ComVisible(true)]
- public class AppDomainManager : MarshalByRefObject
+ internal class AppDomainManager : MarshalByRefObject
{
public AppDomainManager () {}
diff --git a/src/mscorlib/src/System/AppDomainSetup.cs b/src/mscorlib/src/System/AppDomainSetup.cs
index fc8a64c192..0d19ad237f 100644
--- a/src/mscorlib/src/System/AppDomainSetup.cs
+++ b/src/mscorlib/src/System/AppDomainSetup.cs
@@ -26,10 +26,7 @@ namespace System
using System.Collections.Generic;
[Serializable]
- [ClassInterface(ClassInterfaceType.None)]
- [System.Runtime.InteropServices.ComVisible(true)]
- public sealed class AppDomainSetup :
- IAppDomainSetup
+ internal sealed class AppDomainSetup
{
[Serializable]
internal enum LoaderInformation
@@ -55,7 +52,7 @@ namespace System
ConfigurationBytesValue = 15, // LOADER_CONFIGURATION_BYTES
LoaderMaximum = 18 // LOADER_MAXIMUM
}
-
+
// Constants from fusionsetup.h.
private const string LOADER_OPTIMIZATION = "LOADER_OPTIMIZATION";
private const string CONFIGURATION_EXTENSION = ".config";
@@ -439,22 +436,6 @@ namespace System
return path;
}
- private bool IsFilePath(String path)
- {
-#if !PLATFORM_UNIX
- return (path[1] == ':') || ( (path[0] == '\\') && (path[1] == '\\') );
-#else
- return (path[0] == '/');
-#endif // !PLATFORM_UNIX
- }
-
- internal static String ApplicationBaseKey
- {
- get {
- return ACTAG_APP_BASE_URL;
- }
- }
-
public String ConfigurationFile
{
get {
@@ -466,22 +447,6 @@ namespace System
}
}
- // Used by the ResourceManager internally. This must not do any
- // security checks to avoid infinite loops.
- internal String ConfigurationFileInternal
- {
- get {
- return NormalizePath(Value[(int) LoaderInformation.ConfigurationFileValue], true);
- }
- }
-
- internal static String ConfigurationFileKey
- {
- get {
- return ACTAG_APP_CONFIG_FILE;
- }
- }
-
public byte[] GetConfigurationBytes()
{
if (_ConfigurationBytes == null)
@@ -490,18 +455,6 @@ namespace System
return (byte[]) _ConfigurationBytes.Clone();
}
- public void SetConfigurationBytes(byte[] value)
- {
- _ConfigurationBytes = value;
- }
-
- private static String ConfigurationBytesKey
- {
- get {
- return ACTAG_APP_CONFIG_BLOB;
- }
- }
-
// only needed by AppDomain.Setup(). Not really needed by users.
internal Dictionary<string, object> GetCompatibilityFlags()
{
@@ -543,105 +496,6 @@ namespace System
}
}
- internal bool CheckedForTargetFrameworkName
- {
- get { return _CheckedForTargetFrameworkName; }
- set { _CheckedForTargetFrameworkName = value; }
- }
-
- public String DynamicBase
- {
- get {
- return VerifyDir(Value[(int) LoaderInformation.DynamicBaseValue], true);
- }
-
- set {
- if (value == null)
- Value[(int) LoaderInformation.DynamicBaseValue] = null;
- else {
- if(ApplicationName == null)
- throw new MemberAccessException(Environment.GetResourceString("AppDomain_RequireApplicationName"));
-
- StringBuilder s = new StringBuilder( NormalizePath(value, false) );
- s.Append('\\');
- string h = ParseNumbers.IntToString(ApplicationName.GetLegacyNonRandomizedHashCode(),
- 16, 8, '0', ParseNumbers.PrintAsI4);
- s.Append(h);
-
- Value[(int) LoaderInformation.DynamicBaseValue] = s.ToString();
- }
- }
- }
-
- internal static String DynamicBaseKey
- {
- get {
- return ACTAG_APP_DYNAMIC_BASE;
- }
- }
-
- public bool DisallowPublisherPolicy
- {
- get
- {
- return (Value[(int) LoaderInformation.DisallowPublisherPolicyValue] != null);
- }
- set
- {
- if (value)
- Value[(int) LoaderInformation.DisallowPublisherPolicyValue]="true";
- else
- Value[(int) LoaderInformation.DisallowPublisherPolicyValue]=null;
- }
- }
-
-
- public bool DisallowBindingRedirects
- {
- get
- {
- return (Value[(int) LoaderInformation.DisallowBindingRedirectsValue] != null);
- }
- set
- {
- if (value)
- Value[(int) LoaderInformation.DisallowBindingRedirectsValue] = "true";
- else
- Value[(int) LoaderInformation.DisallowBindingRedirectsValue] = null;
- }
- }
-
- public bool DisallowCodeDownload
- {
- get
- {
- return (Value[(int) LoaderInformation.DisallowCodeDownloadValue] != null);
- }
- set
- {
- if (value)
- Value[(int) LoaderInformation.DisallowCodeDownloadValue] = "true";
- else
- Value[(int) LoaderInformation.DisallowCodeDownloadValue] = null;
- }
- }
-
-
- public bool DisallowApplicationBaseProbing
- {
- get
- {
- return (Value[(int) LoaderInformation.DisallowAppBaseProbingValue] != null);
- }
- set
- {
- if (value)
- Value[(int) LoaderInformation.DisallowAppBaseProbingValue] = "true";
- else
- Value[(int) LoaderInformation.DisallowAppBaseProbingValue] = null;
- }
- }
-
private String VerifyDir(String dir, bool normalize)
{
if (dir != null) {
@@ -656,93 +510,6 @@ namespace System
return dir;
}
- private void VerifyDirList(String dirs)
- {
- if (dirs != null) {
- String[] dirArray = dirs.Split(';');
- int len = dirArray.Length;
-
- for (int i = 0; i < len; i++)
- VerifyDir(dirArray[i], true);
- }
- }
-
- internal String DeveloperPath
- {
- get {
- String dirs = Value[(int) LoaderInformation.DevPathValue];
- VerifyDirList(dirs);
- return dirs;
- }
-
- set {
- if(value == null)
- Value[(int) LoaderInformation.DevPathValue] = null;
- else {
- String[] directories = value.Split(';');
- int size = directories.Length;
- StringBuilder newPath = StringBuilderCache.Acquire();
- bool fDelimiter = false;
-
- for(int i = 0; i < size; i++) {
- if(directories[i].Length != 0) {
- if(fDelimiter)
- newPath.Append(";");
- else
- fDelimiter = true;
-
- newPath.Append(Path.GetFullPath(directories[i]));
- }
- }
-
- String newString = StringBuilderCache.GetStringAndRelease(newPath);
- if (newString.Length == 0)
- Value[(int) LoaderInformation.DevPathValue] = null;
- else
- Value[(int) LoaderInformation.DevPathValue] = newString;
- }
- }
- }
-
- internal static String DisallowPublisherPolicyKey
- {
- get
- {
- return ACTAG_DISALLOW_APPLYPUBLISHERPOLICY;
- }
- }
-
- internal static String DisallowCodeDownloadKey
- {
- get
- {
- return ACTAG_CODE_DOWNLOAD_DISABLED;
- }
- }
-
- internal static String DisallowBindingRedirectsKey
- {
- get
- {
- return ACTAG_DISALLOW_APP_BINDING_REDIRECTS;
- }
- }
-
- internal static String DeveloperPathKey
- {
- get {
- return ACTAG_DEV_PATH;
- }
- }
-
- internal static String DisallowAppBaseProbingKey
- {
- get
- {
- return ACTAG_DISALLOW_APP_BASE_PROBING;
- }
- }
-
public String ApplicationName
{
get {
@@ -754,13 +521,6 @@ namespace System
}
}
- internal static String ApplicationNameKey
- {
- get {
- return ACTAG_APP_NAME;
- }
- }
-
[XmlIgnoreMember]
public AppDomainInitializer AppDomainInitializer
{
@@ -786,7 +546,7 @@ namespace System
internal ApplicationTrust InternalGetApplicationTrust()
{
if (_ApplicationTrust == null) return null;
- ApplicationTrust grantSet = new ApplicationTrust(NamedPermissionSet.GetBuiltInSet(_ApplicationTrust));
+ ApplicationTrust grantSet = new ApplicationTrust();
return grantSet;
}
@@ -804,115 +564,6 @@ namespace System
}
}
- public String PrivateBinPath
- {
- get {
- String dirs = Value[(int) LoaderInformation.PrivateBinPathValue];
- VerifyDirList(dirs);
- return dirs;
- }
-
- set {
- Value[(int) LoaderInformation.PrivateBinPathValue] = value;
- }
- }
-
- internal static String PrivateBinPathKey
- {
- get {
- return ACTAG_APP_PRIVATE_BINPATH;
- }
- }
-
- public String PrivateBinPathProbe
- {
- get {
- return Value[(int) LoaderInformation.PrivateBinPathProbeValue];
- }
-
- set {
- Value[(int) LoaderInformation.PrivateBinPathProbeValue] = value;
- }
- }
-
- internal static String PrivateBinPathProbeKey
- {
- get {
- return ACTAG_BINPATH_PROBE_ONLY;
- }
- }
-
- public String ShadowCopyDirectories
- {
- get {
- String dirs = Value[(int) LoaderInformation.ShadowCopyDirectoriesValue];
- VerifyDirList(dirs);
- return dirs;
- }
-
- set {
- Value[(int) LoaderInformation.ShadowCopyDirectoriesValue] = value;
- }
- }
-
- internal static String ShadowCopyDirectoriesKey
- {
- get {
- return ACTAG_APP_SHADOW_COPY_DIRS;
- }
- }
-
- public String ShadowCopyFiles
- {
- get {
- return Value[(int) LoaderInformation.ShadowCopyFilesValue];
- }
-
- set {
- if((value != null) &&
- (String.Compare(value, "true", StringComparison.OrdinalIgnoreCase) == 0))
- Value[(int) LoaderInformation.ShadowCopyFilesValue] = value;
- else
- Value[(int) LoaderInformation.ShadowCopyFilesValue] = null;
- }
- }
-
- internal static String ShadowCopyFilesKey
- {
- get {
- return ACTAG_FORCE_CACHE_INSTALL;
- }
- }
-
- public String CachePath
- {
- get {
- return VerifyDir(Value[(int) LoaderInformation.CachePathValue], false);
- }
-
- set {
- Value[(int) LoaderInformation.CachePathValue] = NormalizePath(value, false);
- }
- }
-
- internal static String CachePathKey
- {
- get {
- return ACTAG_APP_CACHE_BASE;
- }
- }
-
- public String LicenseFile
- {
- get {
- return VerifyDir(Value[(int) LoaderInformation.LicenseFileValue], true);
- }
-
- set {
- Value[(int) LoaderInformation.LicenseFileValue] = value;
- }
- }
-
public LoaderOptimization LoaderOptimization
{
get {
@@ -938,34 +589,6 @@ namespace System
}
}
- internal static String PrivateBinPathEnvironmentVariable
- {
- get {
- return APPENV_RELATIVEPATH;
- }
- }
-
- internal static string RuntimeConfigurationFile
- {
- get {
- return MACHINE_CONFIGURATION_FILE;
- }
- }
-
- internal static string MachineConfigKey
- {
- get {
- return ACTAG_MACHINE_CONFIG;
- }
- }
-
- internal static string HostBindingKey
- {
- get {
- return ACTAG_HOST_CONFIG_FILE;
- }
- }
-
static internal int Locate(String s)
{
if(String.IsNullOrEmpty(s))
diff --git a/src/mscorlib/src/System/AppDomainUnloadedException.cs b/src/mscorlib/src/System/AppDomainUnloadedException.cs
index 8ba37dc4c5..30bee7c7de 100644
--- a/src/mscorlib/src/System/AppDomainUnloadedException.cs
+++ b/src/mscorlib/src/System/AppDomainUnloadedException.cs
@@ -15,23 +15,12 @@ namespace System {
using System.Runtime.Serialization;
- [System.Runtime.InteropServices.ComVisible(true)]
[Serializable]
- public class AppDomainUnloadedException : SystemException {
+ internal class AppDomainUnloadedException : SystemException {
public AppDomainUnloadedException()
: base(Environment.GetResourceString("Arg_AppDomainUnloadedException")) {
SetErrorCode(__HResults.COR_E_APPDOMAINUNLOADED);
}
-
- public AppDomainUnloadedException(String message)
- : base(message) {
- SetErrorCode(__HResults.COR_E_APPDOMAINUNLOADED);
- }
-
- public AppDomainUnloadedException(String message, Exception innerException)
- : base(message, innerException) {
- SetErrorCode(__HResults.COR_E_APPDOMAINUNLOADED);
- }
//
//This constructor is required for serialization.
diff --git a/src/mscorlib/src/System/ApplicationException.cs b/src/mscorlib/src/System/ApplicationException.cs
index c56746fae0..900feb57f9 100644
--- a/src/mscorlib/src/System/ApplicationException.cs
+++ b/src/mscorlib/src/System/ApplicationException.cs
@@ -12,9 +12,10 @@
**
=============================================================================*/
-namespace System {
-
- using System.Runtime.Serialization;
+using System.Runtime.Serialization;
+
+namespace System
+{
// The ApplicationException is the base class for nonfatal,
// application errors that occur. These exceptions are generated
// (i.e., thrown) by an application, not the Runtime. Applications that need
@@ -22,35 +23,34 @@ namespace System {
// ApplicationException extends but adds no new functionality to
// RecoverableException.
//
- [System.Runtime.InteropServices.ComVisible(true)]
[Serializable]
- public class ApplicationException : Exception {
-
+ public class ApplicationException : Exception
+ {
// Creates a new ApplicationException with its message string set to
// the empty string, its HRESULT set to COR_E_APPLICATION,
// and its ExceptionInfo reference set to null.
- public ApplicationException()
- : base(Environment.GetResourceString("Arg_ApplicationException")) {
- SetErrorCode(__HResults.COR_E_APPLICATION);
+ public ApplicationException()
+ : base(SR.Arg_ApplicationException)
+ {
+ HResult = __HResults.COR_E_APPLICATION;
}
-
+
// Creates a new ApplicationException with its message string set to
// message, its HRESULT set to COR_E_APPLICATION,
// and its ExceptionInfo reference set to null.
//
- public ApplicationException(String message)
- : base(message) {
- SetErrorCode(__HResults.COR_E_APPLICATION);
- }
-
- public ApplicationException(String message, Exception innerException)
- : base(message, innerException) {
- SetErrorCode(__HResults.COR_E_APPLICATION);
+ public ApplicationException(String message)
+ : base(message)
+ {
+ HResult = __HResults.COR_E_APPLICATION;
}
- protected ApplicationException(SerializationInfo info, StreamingContext context) : base(info, context) {
+ public ApplicationException(String message, Exception innerException)
+ : base(message, innerException)
+ {
+ HResult = __HResults.COR_E_APPLICATION;
}
+ protected ApplicationException(SerializationInfo info, StreamingContext context) : base(info, context) { }
}
-
}
diff --git a/src/mscorlib/src/System/ApplicationId.cs b/src/mscorlib/src/System/ApplicationId.cs
deleted file mode 100644
index 93fc37dd99..0000000000
--- a/src/mscorlib/src/System/ApplicationId.cs
+++ /dev/null
@@ -1,141 +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.
-
-
-//
-//
-// This class identifies a deployment or manifest identity.
-//
-
-namespace System {
- using System.Reflection;
- using System.Security;
- using System.Security.Policy;
- using System.Security.Util;
- using System.Text;
- using System.Diagnostics.Contracts;
-
- [Serializable]
- [System.Runtime.InteropServices.ComVisible(true)]
- public sealed class ApplicationId {
- private string m_name;
- private Version m_version;
- private string m_processorArchitecture;
- private string m_culture;
- internal byte[] m_publicKeyToken;
-
- internal ApplicationId () {}
-
- //
- // Public.
- //
-
- public ApplicationId (byte[] publicKeyToken, string name, Version version, string processorArchitecture, string culture) {
- if (name == null)
- throw new ArgumentNullException(nameof(name));
- if (name.Length == 0)
- throw new ArgumentException(Environment.GetResourceString("Argument_EmptyApplicationName"));
- if (version == null)
- throw new ArgumentNullException(nameof(version));
- if (publicKeyToken == null)
- throw new ArgumentNullException(nameof(publicKeyToken));
- Contract.EndContractBlock();
-
- m_publicKeyToken = new byte[publicKeyToken.Length];
- Array.Copy(publicKeyToken, 0, m_publicKeyToken, 0, publicKeyToken.Length);
- m_name = name;
- m_version = version;
- m_processorArchitecture = processorArchitecture;
- m_culture = culture;
- }
-
- public byte[] PublicKeyToken {
- get {
- byte[] publicKeyToken = new byte[m_publicKeyToken.Length];
- Array.Copy(m_publicKeyToken, 0, publicKeyToken, 0, m_publicKeyToken.Length);
- return publicKeyToken;
- }
- }
-
- public string Name {
- get {
- return m_name;
- }
- }
-
- public Version Version {
- get {
- return m_version;
- }
- }
-
- public string ProcessorArchitecture {
- get {
- return m_processorArchitecture;
- }
- }
-
- public string Culture {
- get {
- return m_culture;
- }
- }
-
- public ApplicationId Copy () {
- return new ApplicationId(m_publicKeyToken, m_name, m_version, m_processorArchitecture, m_culture);
- }
-
- public override string ToString () {
- StringBuilder sb = StringBuilderCache.Acquire();
- sb.Append(this.m_name);
- if (m_culture != null) {
- sb.Append(", culture=\"");
- sb.Append(m_culture);
- sb.Append("\"");
- }
- sb.Append(", version=\"");
- sb.Append(m_version.ToString());
- sb.Append("\"");
- if (m_publicKeyToken != null) {
- sb.Append(", publicKeyToken=\"");
- sb.Append(Hex.EncodeHexString(m_publicKeyToken));
- sb.Append("\"");
- }
- if (m_processorArchitecture != null) {
- sb.Append(", processorArchitecture =\"");
- sb.Append(this.m_processorArchitecture);
- sb.Append("\"");
- }
- return StringBuilderCache.GetStringAndRelease(sb);
- }
-
- public override bool Equals (Object o) {
- ApplicationId other = (o as ApplicationId);
- if (other == null)
- return false;
-
- if (!(Equals(this.m_name, other.m_name) &&
- Equals(this.m_version, other.m_version) &&
- Equals(this.m_processorArchitecture, other.m_processorArchitecture) &&
- Equals(this.m_culture, other.m_culture)))
- return false;
-
- if (this.m_publicKeyToken.Length != other.m_publicKeyToken.Length)
- return false;
-
- for (int i = 0; i < this.m_publicKeyToken.Length; ++i) {
- if (this.m_publicKeyToken[i] != other.m_publicKeyToken[i])
- return false;
- }
-
- return true;
- }
-
- public override int GetHashCode() {
- // Note: purposely skipping publicKeyToken, processor architecture and culture as they
- // are less likely to make things not equal than name and version.
- return m_name.GetHashCode() ^ m_version.GetHashCode();
- }
- }
-}
diff --git a/src/mscorlib/src/System/ArgIterator.cs b/src/mscorlib/src/System/ArgIterator.cs
index c5bc379505..83a60b95e1 100644
--- a/src/mscorlib/src/System/ArgIterator.cs
+++ b/src/mscorlib/src/System/ArgIterator.cs
@@ -16,6 +16,19 @@ namespace System {
[StructLayout(LayoutKind.Sequential)]
public struct ArgIterator
{
+ private IntPtr ArgCookie; // Cookie from the EE.
+
+ // The SigPointer structure consists of the following members. (Note: this is an inline native SigPointer data type)
+ private IntPtr sigPtr; // Pointer to remaining signature.
+ private IntPtr sigPtrLen; // Remaining length of the pointer
+
+ // Note, sigPtrLen is actually a DWORD, but on 64bit systems this structure becomes
+ // 8-byte aligned, which requires us to pad it.
+
+ private IntPtr ArgPtr; // Pointer to remaining args.
+ private int RemainingArgs; // # of remaining args.
+
+#if VARARGS_ENABLED //The JIT doesn't support Varargs calling convention.
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private extern ArgIterator(IntPtr arglist);
@@ -34,7 +47,6 @@ namespace System {
// This is much like the C va_start macro
[CLSCompliant(false)]
-
public unsafe ArgIterator(RuntimeArgumentHandle arglist, void* ptr) : this(arglist.Value, ptr)
{
}
@@ -121,17 +133,54 @@ namespace System {
{
throw new NotSupportedException(Environment.GetResourceString("NotSupported_NYI"));
}
+#else
+ public ArgIterator(RuntimeArgumentHandle arglist)
+ {
+ throw new PlatformNotSupportedException(); //The JIT requires work to enable ArgIterator see: https://github.com/dotnet/coreclr/issues/9204.
+ }
- private IntPtr ArgCookie; // Cookie from the EE.
+ [CLSCompliant(false)]
+ public unsafe ArgIterator(RuntimeArgumentHandle arglist, void* ptr)
+ {
+ throw new PlatformNotSupportedException(); //The JIT requires work to enable ArgIterator see: https://github.com/dotnet/coreclr/issues/9204.
+ }
- // The SigPointer structure consists of the following members. (Note: this is an inline native SigPointer data type)
- private IntPtr sigPtr; // Pointer to remaining signature.
- private IntPtr sigPtrLen; // Remaining length of the pointer
+ public void End()
+ {
+ throw new PlatformNotSupportedException(); //The JIT requires work to enable ArgIterator see: https://github.com/dotnet/coreclr/issues/9204.
+ }
- // Note, sigPtrLen is actually a DWORD, but on 64bit systems this structure becomes
- // 8-byte aligned, which requires us to pad it.
-
- private IntPtr ArgPtr; // Pointer to remaining args.
- private int RemainingArgs; // # of remaining args.
+ public override bool Equals(Object o)
+ {
+ throw new PlatformNotSupportedException(); //The JIT requires work to enable ArgIterator see: https://github.com/dotnet/coreclr/issues/9204.
+ }
+
+ public override int GetHashCode()
+ {
+ throw new PlatformNotSupportedException(); //The JIT requires work to enable ArgIterator see: https://github.com/dotnet/coreclr/issues/9204.
+ }
+
+ [System.CLSCompliantAttribute(false)]
+ public System.TypedReference GetNextArg()
+ {
+ throw new PlatformNotSupportedException(); //The JIT requires work to enable ArgIterator see: https://github.com/dotnet/coreclr/issues/9204.
+ }
+
+ [System.CLSCompliantAttribute(false)]
+ public System.TypedReference GetNextArg(System.RuntimeTypeHandle rth)
+ {
+ throw new PlatformNotSupportedException(); //The JIT requires work to enable ArgIterator see: https://github.com/dotnet/coreclr/issues/9204.
+ }
+
+ public unsafe System.RuntimeTypeHandle GetNextArgType()
+ {
+ throw new PlatformNotSupportedException(); //The JIT requires work to enable ArgIterator see: https://github.com/dotnet/coreclr/issues/9204.
+ }
+
+ public int GetRemainingCount()
+ {
+ throw new PlatformNotSupportedException(); //The JIT requires work to enable ArgIterator see: https://github.com/dotnet/coreclr/issues/9204.
+ }
+#endif //VARARGS_ENABLED
}
}
diff --git a/src/mscorlib/src/System/ArgumentException.cs b/src/mscorlib/src/System/ArgumentException.cs
index f37b7690a8..fe054a9aa0 100644
--- a/src/mscorlib/src/System/ArgumentException.cs
+++ b/src/mscorlib/src/System/ArgumentException.cs
@@ -11,84 +11,87 @@
**
=============================================================================*/
-namespace System {
-
- using System;
- using System.Runtime.Remoting;
- using System.Runtime.Serialization;
- using System.Globalization;
- using System.Security.Permissions;
- using System.Diagnostics.Contracts;
+using System.Globalization;
+using System.Runtime.Serialization;
+
+namespace System
+{
// The ArgumentException is thrown when an argument does not meet
// the contract of the method. Ideally it should give a meaningful error
// message describing what was wrong and which parameter is incorrect.
//
- [System.Runtime.InteropServices.ComVisible(true)]
[Serializable]
- public class ArgumentException : SystemException, ISerializable {
- private String m_paramName;
-
+ public class ArgumentException : SystemException, ISerializable
+ {
+ private String _paramName;
+
// Creates a new ArgumentException with its message
// string set to the empty string.
- public ArgumentException()
- : base(Environment.GetResourceString("Arg_ArgumentException")) {
- SetErrorCode(__HResults.COR_E_ARGUMENT);
+ public ArgumentException()
+ : base(SR.Arg_ArgumentException)
+ {
+ HResult = __HResults.COR_E_ARGUMENT;
}
-
+
// Creates a new ArgumentException with its message
// string set to message.
//
- public ArgumentException(String message)
- : base(message) {
- SetErrorCode(__HResults.COR_E_ARGUMENT);
+ public ArgumentException(String message)
+ : base(message)
+ {
+ HResult = __HResults.COR_E_ARGUMENT;
}
-
- public ArgumentException(String message, Exception innerException)
- : base(message, innerException) {
- SetErrorCode(__HResults.COR_E_ARGUMENT);
+
+ public ArgumentException(String message, Exception innerException)
+ : base(message, innerException)
+ {
+ HResult = __HResults.COR_E_ARGUMENT;
}
- public ArgumentException(String message, String paramName, Exception innerException)
- : base(message, innerException) {
- m_paramName = paramName;
- SetErrorCode(__HResults.COR_E_ARGUMENT);
+ public ArgumentException(String message, String paramName, Exception innerException)
+ : base(message, innerException)
+ {
+ _paramName = paramName;
+ HResult = __HResults.COR_E_ARGUMENT;
}
-
- public ArgumentException (String message, String paramName)
-
- : base (message) {
- m_paramName = paramName;
- SetErrorCode(__HResults.COR_E_ARGUMENT);
+
+ public ArgumentException(String message, String paramName)
+ : base(message)
+ {
+ _paramName = paramName;
+ HResult = __HResults.COR_E_ARGUMENT;
}
- protected ArgumentException(SerializationInfo info, StreamingContext context) : base(info, context) {
- m_paramName = info.GetString("ParamName");
+ protected ArgumentException(SerializationInfo info, StreamingContext context)
+ : base(info, context)
+ {
+ _paramName = info.GetString("ParamName");
}
-
+
+ public override void GetObjectData(SerializationInfo info, StreamingContext context)
+ {
+ base.GetObjectData(info, context);
+ info.AddValue("ParamName", _paramName, typeof(String));
+ }
+
public override String Message
{
- get {
+ get
+ {
String s = base.Message;
- if (!String.IsNullOrEmpty(m_paramName)) {
- String resourceString = Environment.GetResourceString("Arg_ParamName_Name", m_paramName);
+ if (!String.IsNullOrEmpty(_paramName))
+ {
+ String resourceString = SR.Format(SR.Arg_ParamName_Name, _paramName);
return s + Environment.NewLine + resourceString;
}
else
return s;
}
}
-
- public virtual String ParamName {
- get { return m_paramName; }
- }
-
- public override void GetObjectData(SerializationInfo info, StreamingContext context) {
- if (info==null) {
- throw new ArgumentNullException(nameof(info));
- }
- Contract.EndContractBlock();
- base.GetObjectData(info, context);
- info.AddValue("ParamName", m_paramName, typeof(String));
+
+ public virtual String ParamName
+ {
+ get { return _paramName; }
}
}
}
diff --git a/src/mscorlib/src/System/ArgumentNullException.cs b/src/mscorlib/src/System/ArgumentNullException.cs
index 661ebd29af..3a86223ccf 100644
--- a/src/mscorlib/src/System/ArgumentNullException.cs
+++ b/src/mscorlib/src/System/ArgumentNullException.cs
@@ -11,44 +11,43 @@
**
=============================================================================*/
-namespace System {
-
- using System;
- using System.Runtime.Serialization;
- using System.Runtime.Remoting;
- using System.Security.Permissions;
-
+using System.Runtime.Serialization;
+
+namespace System
+{
// The ArgumentException is thrown when an argument
// is null when it shouldn't be.
//
- [System.Runtime.InteropServices.ComVisible(true)]
[Serializable]
public class ArgumentNullException : ArgumentException
{
// Creates a new ArgumentNullException with its message
// string set to a default message explaining an argument was null.
- public ArgumentNullException()
- : base(Environment.GetResourceString("ArgumentNull_Generic")) {
- // Use E_POINTER - COM used that for null pointers. Description is "invalid pointer"
- SetErrorCode(__HResults.E_POINTER);
+ public ArgumentNullException()
+ : base(SR.ArgumentNull_Generic)
+ {
+ // Use E_POINTER - COM used that for null pointers. Description is "invalid pointer"
+ HResult = __HResults.E_POINTER;
}
- public ArgumentNullException(String paramName)
- : base(Environment.GetResourceString("ArgumentNull_Generic"), paramName) {
- SetErrorCode(__HResults.E_POINTER);
+ public ArgumentNullException(String paramName)
+ : base(SR.ArgumentNull_Generic, paramName)
+ {
+ HResult = __HResults.E_POINTER;
}
- public ArgumentNullException(String message, Exception innerException)
- : base(message, innerException) {
- SetErrorCode(__HResults.E_POINTER);
- }
-
- public ArgumentNullException(String paramName, String message)
- : base(message, paramName) {
- SetErrorCode(__HResults.E_POINTER);
+ public ArgumentNullException(String message, Exception innerException)
+ : base(message, innerException)
+ {
+ HResult = __HResults.E_POINTER;
}
- protected ArgumentNullException(SerializationInfo info, StreamingContext context) : base(info, context) {
+ public ArgumentNullException(String paramName, String message)
+ : base(message, paramName)
+ {
+ HResult = __HResults.E_POINTER;
}
+
+ 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 78a90db34e..59a8434089 100644
--- a/src/mscorlib/src/System/ArgumentOutOfRangeException.cs
+++ b/src/mscorlib/src/System/ArgumentOutOfRangeException.cs
@@ -17,12 +17,10 @@ namespace System {
using System.Runtime.Remoting;
using System.Runtime.Serialization;
using System.Globalization;
- using System.Security.Permissions;
using System.Diagnostics.Contracts;
// The ArgumentOutOfRangeException is thrown when an argument
// is outside the legal range for that argument.
- [System.Runtime.InteropServices.ComVisible(true)]
[Serializable]
public class ArgumentOutOfRangeException : ArgumentException, ISerializable {
diff --git a/src/mscorlib/src/System/ArithmeticException.cs b/src/mscorlib/src/System/ArithmeticException.cs
index f5360939cc..081ba454f5 100644
--- a/src/mscorlib/src/System/ArithmeticException.cs
+++ b/src/mscorlib/src/System/ArithmeticException.cs
@@ -11,42 +11,41 @@
**
=============================================================================*/
-namespace System {
-
- using System;
- using System.Runtime.Serialization;
+using System.Runtime.Serialization;
+
+namespace System
+{
// The ArithmeticException is thrown when overflow or underflow
// occurs.
//
- [System.Runtime.InteropServices.ComVisible(true)]
[Serializable]
public class ArithmeticException : SystemException
- {
+ {
// Creates a new ArithmeticException with its message string set to
// the empty string, its HRESULT set to COR_E_ARITHMETIC,
// and its ExceptionInfo reference set to null.
- public ArithmeticException()
- : base(Environment.GetResourceString("Arg_ArithmeticException")) {
- SetErrorCode(__HResults.COR_E_ARITHMETIC);
+ public ArithmeticException()
+ : base(SR.Arg_ArithmeticException)
+ {
+ HResult = __HResults.COR_E_ARITHMETIC;
}
-
+
// Creates a new ArithmeticException with its message string set to
// message, its HRESULT set to COR_E_ARITHMETIC,
// and its ExceptionInfo reference set to null.
//
- public ArithmeticException(String message)
- : base(message) {
- SetErrorCode(__HResults.COR_E_ARITHMETIC);
- }
-
- public ArithmeticException(String message, Exception innerException)
- : base(message, innerException) {
- SetErrorCode(__HResults.COR_E_ARITHMETIC);
+ public ArithmeticException(String message)
+ : base(message)
+ {
+ HResult = __HResults.COR_E_ARITHMETIC;
}
- protected ArithmeticException(SerializationInfo info, StreamingContext context) : base(info, context) {
+ public ArithmeticException(String message, Exception innerException)
+ : base(message, innerException)
+ {
+ HResult = __HResults.COR_E_ARITHMETIC;
}
+ protected ArithmeticException(SerializationInfo info, StreamingContext context) : base(info, context) { }
}
-
}
diff --git a/src/mscorlib/src/System/Array.cs b/src/mscorlib/src/System/Array.cs
index 7bb6ebbdd3..23989f30fb 100644
--- a/src/mscorlib/src/System/Array.cs
+++ b/src/mscorlib/src/System/Array.cs
@@ -20,13 +20,11 @@ namespace System {
using System.Runtime.Versioning;
using System.Security;
using System.Diagnostics;
- using System.Security.Permissions;
using System.Diagnostics.Contracts;
// Note that we make a T[] (single-dimensional w/ zero as the lower bound) implement both
// IList<U> and IReadOnlyList<U>, where T : U dynamically. See the SZArrayHelper class for details.
[Serializable]
- [ComVisible(true)]
public abstract class Array : ICloneable, IList, IStructuralComparable, IStructuralEquatable
{
// This ctor exists solely to prevent C# from generating a protected .ctor that violates the surface area. I really want this to be a
@@ -43,7 +41,6 @@ namespace System {
return new ReadOnlyCollection<T>(array);
}
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
public static void Resize<T>(ref T[] array, int newSize) {
if (newSize < 0)
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.newSize, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum);
@@ -154,7 +151,7 @@ namespace System {
if (lengths[i] < 0)
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.lengths, i, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum);
- fixed (int* pLengths = lengths)
+ fixed (int* pLengths = &lengths[0])
return InternalCreate((void*)t.TypeHandle.Value,lengths.Length,pLengths,null);
}
@@ -211,8 +208,8 @@ namespace System {
if (lengths[i] < 0)
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.lengths, i, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum);
- fixed (int* pLengths = lengths)
- fixed(int* pLowerBounds = lowerBounds)
+ fixed (int* pLengths = &lengths[0])
+ fixed(int* pLowerBounds = &lowerBounds[0])
return InternalCreate((void*)t.TypeHandle.Value,lengths.Length,pLengths,pLowerBounds);
}
@@ -224,25 +221,9 @@ namespace System {
return CreateInstance(elementType, length);
}
- internal static Array UnsafeCreateInstance(Type elementType, int length1, int length2)
- {
- return CreateInstance(elementType, length1, length2);
- }
-
- internal static Array UnsafeCreateInstance(Type elementType, params int[] lengths)
- {
- return CreateInstance(elementType, lengths);
- }
-
- internal static Array UnsafeCreateInstance(Type elementType, int[] lengths, int[] lowerBounds)
- {
- return CreateInstance(elementType, lengths, lowerBounds);
- }
-
// Copies length elements from sourceArray, starting at index 0, to
// destinationArray, starting at index 0.
//
- [ReliabilityContract(Consistency.MayCorruptInstance, Cer.MayFail)]
public static void Copy(Array sourceArray, Array destinationArray, int length)
{
if (sourceArray == null)
@@ -263,7 +244,6 @@ namespace System {
// Copies length elements from sourceArray, starting at sourceIndex, to
// destinationArray, starting at destinationIndex.
//
- [ReliabilityContract(Consistency.MayCorruptInstance, Cer.MayFail)]
public static void Copy(Array sourceArray, int sourceIndex, Array destinationArray, int destinationIndex, int length)
{
Copy(sourceArray, sourceIndex, destinationArray, destinationIndex, length, false);
@@ -273,7 +253,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.
- [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);
@@ -282,13 +261,11 @@ 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.
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
public static void ConstrainedCopy(Array sourceArray, int sourceIndex, Array destinationArray, int destinationIndex, int length)
{
Copy(sourceArray, sourceIndex, destinationArray, destinationIndex, length, true);
}
- [ReliabilityContract(Consistency.MayCorruptInstance, Cer.MayFail)]
public static void Copy(Array sourceArray, Array destinationArray, long length)
{
if (length > Int32.MaxValue || length < Int32.MinValue)
@@ -297,7 +274,6 @@ namespace System {
Array.Copy(sourceArray, destinationArray, (int) length);
}
- [ReliabilityContract(Consistency.MayCorruptInstance, Cer.MayFail)]
public static void Copy(Array sourceArray, long sourceIndex, Array destinationArray, long destinationIndex, long length)
{
if (sourceIndex > Int32.MaxValue || sourceIndex < Int32.MinValue)
@@ -315,7 +291,6 @@ namespace System {
// at index.
//
[MethodImplAttribute(MethodImplOptions.InternalCall)]
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
public static extern void Clear(Array array, int index, int length);
// The various Get values...
@@ -328,7 +303,7 @@ namespace System {
Contract.EndContractBlock();
TypedReference elemref = new TypedReference();
- fixed(int* pIndices = indices)
+ fixed(int* pIndices = &indices[0])
InternalGetReference(&elemref, indices.Length, pIndices);
return TypedReference.InternalToObject(&elemref);
}
@@ -375,7 +350,6 @@ namespace System {
return TypedReference.InternalToObject(&elemref);
}
- [ComVisible(false)]
public Object GetValue(long index)
{
if (index > Int32.MaxValue || index < Int32.MinValue)
@@ -385,7 +359,6 @@ namespace System {
return this.GetValue((int) index);
}
- [ComVisible(false)]
public Object GetValue(long index1, long index2)
{
if (index1 > Int32.MaxValue || index1 < Int32.MinValue)
@@ -397,7 +370,6 @@ namespace System {
return this.GetValue((int) index1, (int) index2);
}
- [ComVisible(false)]
public Object GetValue(long index1, long index2, long index3)
{
if (index1 > Int32.MaxValue || index1 < Int32.MinValue)
@@ -411,7 +383,6 @@ namespace System {
return this.GetValue((int) index1, (int) index2, (int) index3);
}
- [ComVisible(false)]
public Object GetValue(params long[] indices)
{
if (indices == null)
@@ -485,12 +456,11 @@ namespace System {
Contract.EndContractBlock();
TypedReference elemref = new TypedReference();
- fixed(int* pIndices = indices)
+ fixed(int* pIndices = &indices[0])
InternalGetReference(&elemref, indices.Length, pIndices);
InternalSetValue(&elemref,value);
}
- [ComVisible(false)]
public void SetValue(Object value, long index)
{
if (index > Int32.MaxValue || index < Int32.MinValue)
@@ -500,7 +470,6 @@ namespace System {
this.SetValue(value, (int) index);
}
- [ComVisible(false)]
public void SetValue(Object value, long index1, long index2)
{
if (index1 > Int32.MaxValue || index1 < Int32.MinValue)
@@ -512,7 +481,6 @@ namespace System {
this.SetValue(value, (int) index1, (int) index2);
}
- [ComVisible(false)]
public void SetValue(Object value, long index1, long index2, long index3)
{
if (index1 > Int32.MaxValue || index1 < Int32.MinValue)
@@ -526,7 +494,6 @@ namespace System {
this.SetValue(value, (int) index1, (int) index2, (int) index3);
}
- [ComVisible(false)]
public void SetValue(Object value, params long[] indices)
{
if (indices == null)
@@ -559,12 +526,10 @@ namespace System {
public extern int Length {
[Pure]
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
[MethodImpl(MethodImplOptions.InternalCall)]
get;
}
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
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);
@@ -580,10 +545,8 @@ namespace System {
internal const int MaxArrayLength = 0X7FEFFFFF;
internal const int MaxByteArrayLength = 0x7FFFFFC7;
- [ComVisible(false)]
public extern long LongLength {
[Pure]
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
[MethodImpl(MethodImplOptions.InternalCall)]
get;
}
@@ -593,7 +556,6 @@ namespace System {
public extern int GetLength(int dimension);
[Pure]
- [ComVisible(false)]
public long GetLongLength(int dimension) {
//This method should throw an IndexOufOfRangeException for compat if dimension < 0 or >= Rank
return GetLength(dimension);
@@ -601,22 +563,18 @@ namespace System {
public extern int Rank {
[Pure]
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
get;
}
[Pure]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
public extern int GetUpperBound(int dimension);
[Pure]
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public extern int GetLowerBound(int dimension);
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern int GetDataPtrOffsetInternal();
@@ -783,7 +741,6 @@ namespace System {
// is larger than the given search value.
//
[Pure]
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
public static int BinarySearch(Array array, Object value) {
if (array==null)
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
@@ -807,7 +764,6 @@ namespace System {
// is larger than the given search value.
//
[Pure]
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
public static int BinarySearch(Array array, int index, int length, Object value) {
return BinarySearch(array, index, length, value, null);
}
@@ -827,7 +783,6 @@ namespace System {
// is larger than the given search value.
//
[Pure]
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
public static int BinarySearch(Array array, Object value, IComparer comparer) {
if (array==null)
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
@@ -852,7 +807,6 @@ namespace System {
// is larger than the given search value.
//
[Pure]
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
public static int BinarySearch(Array array, int index, int length, Object value, IComparer comparer) {
if (array==null)
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
@@ -923,11 +877,9 @@ namespace System {
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
private static extern bool TrySZBinarySearch(Array sourceArray, int sourceIndex, int count, Object value, out int retVal);
[Pure]
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
public static int BinarySearch<T>(T[] array, T value) {
if (array==null)
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
@@ -936,7 +888,6 @@ namespace System {
}
[Pure]
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
public static int BinarySearch<T>(T[] array, T value, System.Collections.Generic.IComparer<T> comparer) {
if (array==null)
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
@@ -945,13 +896,11 @@ namespace System {
}
[Pure]
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
public static int BinarySearch<T>(T[] array, int index, int length, T value) {
return BinarySearch<T>(array, index, length, value, null);
}
[Pure]
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
public static int BinarySearch<T>(T[] array, int index, int length, T value, System.Collections.Generic.IComparer<T> comparer) {
if (array==null)
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
@@ -1004,7 +953,6 @@ namespace System {
}
[Pure]
- [ComVisible(false)]
public void CopyTo(Array array, long index)
{
if (index > Int32.MaxValue || index < Int32.MinValue)
@@ -1015,7 +963,6 @@ namespace System {
}
[Pure]
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
public static T[] Empty<T>()
{
Contract.Ensures(Contract.Result<T[]>() != null);
@@ -1253,7 +1200,6 @@ namespace System {
// The array is searched forwards, and the elements of the array are
// compared to the given value using the Object.Equals method.
//
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
public static int IndexOf(Array array, Object value) {
if (array==null)
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
@@ -1269,7 +1215,6 @@ namespace System {
// elements of the array are compared to the given value using the
// Object.Equals method.
//
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
public static int IndexOf(Array array, Object value, int startIndex) {
if (array==null)
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
@@ -1285,7 +1230,6 @@ namespace System {
// elements of the array are compared to the given value using the
// Object.Equals method.
//
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
public static int IndexOf(Array array, Object value, int startIndex, int count) {
if (array==null)
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
@@ -1380,7 +1324,6 @@ namespace System {
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
private static extern bool TrySZIndexOf(Array sourceArray, int sourceIndex, int count, Object value, out int retVal);
@@ -1388,7 +1331,6 @@ namespace System {
// The array is searched backwards, and the elements of the array are
// compared to the given value using the Object.Equals method.
//
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
public static int LastIndexOf(Array array, Object value) {
if (array==null)
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
@@ -1403,7 +1345,6 @@ namespace System {
// startIndex and ending at index 0. The elements of the array are
// compared to the given value using the Object.Equals method.
//
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
public static int LastIndexOf(Array array, Object value, int startIndex) {
if (array == null)
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
@@ -1419,7 +1360,6 @@ namespace System {
// the array are compared to the given value using the Object.Equals
// method.
//
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
public static int LastIndexOf(Array array, Object value, int startIndex, int count) {
if (array==null)
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
@@ -1531,7 +1471,6 @@ namespace System {
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
private static extern bool TrySZLastIndexOf(Array sourceArray, int sourceIndex, int count, Object value, out int retVal);
@@ -1540,7 +1479,6 @@ namespace System {
// located at index length - i - 1, where length is the
// length of the array.
//
- [ReliabilityContract(Consistency.MayCorruptInstance, Cer.MayFail)]
public static void Reverse(Array array) {
if (array==null)
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
@@ -1554,7 +1492,6 @@ namespace System {
// index index + (index + count - i - 1).
// Reliability note: This may fail because it may have to box objects.
//
- [ReliabilityContract(Consistency.MayCorruptInstance, Cer.MayFail)]
public static void Reverse(Array array, int index, int length) {
if (array==null)
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
@@ -1598,10 +1535,8 @@ namespace System {
}
[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)
@@ -1610,7 +1545,6 @@ namespace System {
Reverse(array, 0, array.Length);
}
- [ReliabilityContract(Consistency.MayCorruptInstance, Cer.MayFail)]
public static void Reverse<T>(T[] array, int index, int length)
{
if (array == null)
@@ -1639,7 +1573,6 @@ namespace System {
// other using the IComparable interface, which must be implemented
// by all elements of the array.
//
- [ReliabilityContract(Consistency.MayCorruptInstance, Cer.MayFail)]
public static void Sort(Array array) {
if (array==null)
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
@@ -1653,7 +1586,6 @@ namespace System {
// keys to each other using the IComparable interface, which must be
// implemented by all elements of the keys array.
//
- [ReliabilityContract(Consistency.MayCorruptInstance, Cer.MayFail)]
public static void Sort(Array keys, Array items) {
if (keys==null)
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.keys);
@@ -1665,7 +1597,6 @@ namespace System {
// elements to each other using the IComparable interface, which
// must be implemented by all elements in the given section of the array.
//
- [ReliabilityContract(Consistency.MayCorruptInstance, Cer.MayFail)]
public static void Sort(Array array, int index, int length) {
Sort(array, null, index, length, null);
}
@@ -1676,7 +1607,6 @@ namespace System {
// keys to each other using the IComparable interface, which must be
// implemented by all elements of the keys array.
//
- [ReliabilityContract(Consistency.MayCorruptInstance, Cer.MayFail)]
public static void Sort(Array keys, Array items, int index, int length) {
Sort(keys, items, index, length, null);
}
@@ -1687,7 +1617,6 @@ namespace System {
// IComparable interface, which in that case must be implemented by
// all elements of the array.
//
- [ReliabilityContract(Consistency.MayCorruptInstance, Cer.MayFail)]
public static void Sort(Array array, IComparer comparer) {
if (array==null)
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
@@ -1703,7 +1632,6 @@ namespace System {
// the IComparable interface, which in that case must be implemented
// by all elements of the keys array.
//
- [ReliabilityContract(Consistency.MayCorruptInstance, Cer.MayFail)]
public static void Sort(Array keys, Array items, IComparer comparer) {
if (keys==null)
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.keys);
@@ -1717,7 +1645,6 @@ namespace System {
// the IComparable interface, which in that case must be implemented
// by all elements in the given section of the array.
//
- [ReliabilityContract(Consistency.MayCorruptInstance, Cer.MayFail)]
public static void Sort(Array array, int index, int length, IComparer comparer) {
Sort(array, null, index, length, comparer);
}
@@ -1730,7 +1657,6 @@ namespace System {
// the IComparable interface, which in that case must be implemented
// by all elements of the given section of the keys array.
//
- [ReliabilityContract(Consistency.MayCorruptInstance, Cer.MayFail)]
public static void Sort(Array keys, Array items, int index, int length, IComparer comparer) {
if (keys==null)
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.keys);
@@ -1772,10 +1698,8 @@ namespace System {
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
- [ReliabilityContract(Consistency.MayCorruptInstance, Cer.MayFail)]
private static extern bool TrySZSort(Array keys, Array items, int left, int right);
- [ReliabilityContract(Consistency.MayCorruptInstance, Cer.MayFail)]
public static void Sort<T>(T[] array) {
if (array==null)
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
@@ -1783,7 +1707,6 @@ namespace System {
Sort<T>(array, 0, array.Length, null);
}
- [ReliabilityContract(Consistency.MayCorruptInstance, Cer.MayFail)]
public static void Sort<TKey, TValue>(TKey[] keys, TValue[] items) {
if (keys==null)
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.keys);
@@ -1791,17 +1714,14 @@ namespace System {
Sort<TKey, TValue>(keys, items, 0, keys.Length, null);
}
- [ReliabilityContract(Consistency.MayCorruptInstance, Cer.MayFail)]
public static void Sort<T>(T[] array, int index, int length) {
Sort<T>(array, index, length, null);
}
- [ReliabilityContract(Consistency.MayCorruptInstance, Cer.MayFail)]
public static void Sort<TKey, TValue>(TKey[] keys, TValue[] items, int index, int length) {
Sort<TKey, TValue>(keys, items, index, length, null);
}
- [ReliabilityContract(Consistency.MayCorruptInstance, Cer.MayFail)]
public static void Sort<T>(T[] array, System.Collections.Generic.IComparer<T> comparer) {
if (array == null)
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
@@ -1809,7 +1729,6 @@ namespace System {
Sort<T>(array, 0, array.Length, comparer);
}
- [ReliabilityContract(Consistency.MayCorruptInstance, Cer.MayFail)]
public static void Sort<TKey, TValue>(TKey[] keys, TValue[] items, System.Collections.Generic.IComparer<TKey> comparer) {
if (keys==null)
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.keys);
@@ -1817,7 +1736,6 @@ namespace System {
Sort<TKey, TValue>(keys, items, 0, keys.Length, comparer);
}
- [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)
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
@@ -1840,7 +1758,6 @@ namespace System {
}
}
- [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)
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.keys);
diff --git a/src/mscorlib/src/System/ArraySegment.cs b/src/mscorlib/src/System/ArraySegment.cs
index b767e7bd77..03556e492a 100644
--- a/src/mscorlib/src/System/ArraySegment.cs
+++ b/src/mscorlib/src/System/ArraySegment.cs
@@ -15,8 +15,6 @@
using System.Collections;
using System.Collections.Generic;
-using System.Runtime.InteropServices;
-using System.Diagnostics;
using System.Diagnostics.Contracts;
namespace System
@@ -46,14 +44,10 @@ namespace System
public ArraySegment(T[] array, int offset, int count)
{
- if (array == null)
- ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
- if (offset < 0)
- ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.offset, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum);
- if (count < 0)
- ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.count, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum);
- if (array.Length - offset < count)
- ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_InvalidOffLen);
+ // Validate arguments, check is minimal instructions with reduced branching for inlinable fast-path
+ // Failure should be rare and location determination and message is delegated to failure functions
+ if (array == null || (offset | count) < 0 || (array.Length - offset < count))
+ ThrowHelper.ThrowArraySegmentCtorValidationFailedExceptions(array, offset, count);
Contract.EndContractBlock();
_array = array;
diff --git a/src/mscorlib/src/System/ArrayTypeMismatchException.cs b/src/mscorlib/src/System/ArrayTypeMismatchException.cs
index 4f24b9d3c7..3e941fdf8e 100644
--- a/src/mscorlib/src/System/ArrayTypeMismatchException.cs
+++ b/src/mscorlib/src/System/ArrayTypeMismatchException.cs
@@ -11,42 +11,41 @@
**
=============================================================================*/
-namespace System {
-
- using System;
- using System.Runtime.Serialization;
+using System.Runtime.Serialization;
+
+namespace System
+{
// The ArrayMismatchException is thrown when an attempt to store
// an object of the wrong type within an array occurs.
//
- [System.Runtime.InteropServices.ComVisible(true)]
[Serializable]
- public class ArrayTypeMismatchException : SystemException {
-
+ public class ArrayTypeMismatchException : SystemException
+ {
// Creates a new ArrayMismatchException with its message string set to
// the empty string, its HRESULT set to COR_E_ARRAYTYPEMISMATCH,
// and its ExceptionInfo reference set to null.
- public ArrayTypeMismatchException()
- : base(Environment.GetResourceString("Arg_ArrayTypeMismatchException")) {
- SetErrorCode(__HResults.COR_E_ARRAYTYPEMISMATCH);
+ public ArrayTypeMismatchException()
+ : base(SR.Arg_ArrayTypeMismatchException)
+ {
+ HResult = __HResults.COR_E_ARRAYTYPEMISMATCH;
}
-
+
// Creates a new ArrayMismatchException with its message string set to
// message, its HRESULT set to COR_E_ARRAYTYPEMISMATCH,
// and its ExceptionInfo reference set to null.
//
- public ArrayTypeMismatchException(String message)
- : base(message) {
- SetErrorCode(__HResults.COR_E_ARRAYTYPEMISMATCH);
- }
-
- public ArrayTypeMismatchException(String message, Exception innerException)
- : base(message, innerException) {
- SetErrorCode(__HResults.COR_E_ARRAYTYPEMISMATCH);
+ public ArrayTypeMismatchException(String message)
+ : base(message)
+ {
+ HResult = __HResults.COR_E_ARRAYTYPEMISMATCH;
}
- protected ArrayTypeMismatchException(SerializationInfo info, StreamingContext context) : base(info, context) {
+ public ArrayTypeMismatchException(String message, Exception innerException)
+ : base(message, innerException)
+ {
+ HResult = __HResults.COR_E_ARRAYTYPEMISMATCH;
}
+ protected ArrayTypeMismatchException(SerializationInfo info, StreamingContext context) : base(info, context) { }
}
-
}
diff --git a/src/mscorlib/src/System/AsyncCallback.cs b/src/mscorlib/src/System/AsyncCallback.cs
index 69a03812e1..5c49535cff 100644
--- a/src/mscorlib/src/System/AsyncCallback.cs
+++ b/src/mscorlib/src/System/AsyncCallback.cs
@@ -9,9 +9,9 @@
** Purpose: Type of callback for async operations
**
===========================================================*/
-namespace System {
+
+namespace System
+{
[Serializable]
- [System.Runtime.InteropServices.ComVisible(true)]
public delegate void AsyncCallback(IAsyncResult ar);
-
}
diff --git a/src/mscorlib/src/System/Attribute.cs b/src/mscorlib/src/System/Attribute.cs
index e77450e972..b44e13f959 100644
--- a/src/mscorlib/src/System/Attribute.cs
+++ b/src/mscorlib/src/System/Attribute.cs
@@ -13,14 +13,10 @@ namespace System {
using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Security;
- using System.Security.Permissions;
[Serializable]
[AttributeUsageAttribute(AttributeTargets.All, Inherited = true, AllowMultiple=false)]
- [ClassInterface(ClassInterfaceType.None)]
- [ComDefaultInterface(typeof(_Attribute))]
- [System.Runtime.InteropServices.ComVisible(true)]
- public abstract class Attribute : _Attribute
+ public abstract class Attribute
{
#region Private Statics
diff --git a/src/mscorlib/src/System/AttributeTargets.cs b/src/mscorlib/src/System/AttributeTargets.cs
index 33617e9623..fdfa4ab730 100644
--- a/src/mscorlib/src/System/AttributeTargets.cs
+++ b/src/mscorlib/src/System/AttributeTargets.cs
@@ -4,37 +4,33 @@
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
-namespace System {
-
- using System;
-
+
+namespace System
+{
// Enum used to indicate all the elements of the
// VOS it is valid to attach this element to.
-[Serializable]
[Flags]
-[System.Runtime.InteropServices.ComVisible(true)]
+ [Serializable]
public enum AttributeTargets
{
- Assembly = 0x0001,
- Module = 0x0002,
- Class = 0x0004,
- Struct = 0x0008,
- Enum = 0x0010,
- Constructor = 0x0020,
- Method = 0x0040,
- Property = 0x0080,
- Field = 0x0100,
- Event = 0x0200,
- Interface = 0x0400,
- Parameter = 0x0800,
- Delegate = 0x1000,
- ReturnValue = 0x2000,
- //@todo GENERICS: document GenericParameter
+ Assembly = 0x0001,
+ Module = 0x0002,
+ Class = 0x0004,
+ Struct = 0x0008,
+ Enum = 0x0010,
+ Constructor = 0x0020,
+ Method = 0x0040,
+ Property = 0x0080,
+ Field = 0x0100,
+ Event = 0x0200,
+ Interface = 0x0400,
+ Parameter = 0x0800,
+ Delegate = 0x1000,
+ ReturnValue = 0x2000,
GenericParameter = 0x4000,
-
-
- All = Assembly | Module | Class | Struct | Enum | Constructor |
- Method | Property | Field | Event | Interface | Parameter |
- Delegate | ReturnValue | GenericParameter,
+
+ All = Assembly | Module | Class | Struct | Enum | Constructor |
+ Method | Property | Field | Event | Interface | Parameter |
+ Delegate | ReturnValue | GenericParameter
}
}
diff --git a/src/mscorlib/src/System/AttributeUsageAttribute.cs b/src/mscorlib/src/System/AttributeUsageAttribute.cs
index 0c2e11caff..33f7fd805e 100644
--- a/src/mscorlib/src/System/AttributeUsageAttribute.cs
+++ b/src/mscorlib/src/System/AttributeUsageAttribute.cs
@@ -16,7 +16,6 @@ namespace System {
/* By default, attributes are inherited and multiple attributes are not allowed */
[Serializable]
[AttributeUsage(AttributeTargets.Class, Inherited = true)]
-[System.Runtime.InteropServices.ComVisible(true)]
public sealed class AttributeUsageAttribute : Attribute
{
internal AttributeTargets m_attributeTarget = AttributeTargets.All; // Defaults to all
diff --git a/src/mscorlib/src/System/BCLDebug.cs b/src/mscorlib/src/System/BCLDebug.cs
index 0ca6e616f2..7556b85789 100644
--- a/src/mscorlib/src/System/BCLDebug.cs
+++ b/src/mscorlib/src/System/BCLDebug.cs
@@ -20,7 +20,6 @@ namespace System {
using Microsoft.Win32;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
- using System.Security.Permissions;
using System.Security;
using System.Diagnostics.Contracts;
@@ -54,7 +53,6 @@ namespace System {
#if _DEBUG
internal static volatile bool m_domainUnloadAdded;
#endif
- internal static volatile PermissionSet m_MakeConsoleErrorLoggingWork;
static readonly SwitchStructure[] switches = {
new SwitchStructure("NLS", 0x00000001),
@@ -263,40 +261,6 @@ namespace System {
System.Diagnostics.Log.LogMessage((LoggingLevels)((int)level), logSwitch, StringBuilderCache.GetStringAndRelease(sb));
}
- // Note this overload doesn't take a format string. You probably don't
- // want this one.
- [Pure]
- [Conditional("_LOGGING")]
- public static void Trace(String switchName, params Object[]messages) {
- if (m_loggingNotEnabled) {
- return;
- }
-
- LogSwitch logSwitch;
- if (!CheckEnabled(switchName, LogLevel.Trace, out logSwitch)) {
- return;
- }
-
- StringBuilder sb = StringBuilderCache.Acquire();
-
- for (int i=0; i<messages.Length; i++) {
- String s;
- try {
- if (messages[i]==null) {
- s = "<null>";
- } else {
- s = messages[i].ToString();
- }
- } catch {
- s = "<unable to convert>";
- }
- sb.Append(s);
- }
-
- sb.Append(Environment.NewLine);
- System.Diagnostics.Log.LogMessage(LoggingLevels.TraceLevel0, logSwitch, StringBuilderCache.GetStringAndRelease(sb));
- }
-
[Pure]
[Conditional("_LOGGING")]
public static void Trace(String switchName, String format, params Object[] messages) {
@@ -316,22 +280,6 @@ namespace System {
System.Diagnostics.Log.LogMessage(LoggingLevels.TraceLevel0, logSwitch, StringBuilderCache.GetStringAndRelease(sb));
}
- [Conditional("_LOGGING")]
- public static void DumpStack(String switchName) {
- LogSwitch logSwitch;
-
- if (!m_registryChecked) {
- CheckRegistry();
- }
-
- if (!CheckEnabled(switchName, LogLevel.Trace, out logSwitch)) {
- return;
- }
-
- StackTrace trace = new StackTrace();
- System.Diagnostics.Log.LogMessage(LoggingLevels.TraceLevel0, logSwitch, trace.ToString());
- }
-
// For perf-related asserts. On a debug build, set the registry key
// BCLPerfWarnings to non-zero.
[Conditional("_DEBUG")]
@@ -377,21 +325,6 @@ namespace System {
#endif
}
-#if !BIT64 // 32
-#endif
- internal static bool CorrectnessEnabled()
- {
-#if BIT64
- return false;
-#else // 32
- if (AppDomain.CurrentDomain.IsUnloadingForcedFinalize())
- return false;
- if (!m_registryChecked)
- CheckRegistry();
- return m_correctnessWarnings;
-#endif // BIT64
- }
-
// Whether SafeHandles include a stack trace showing where they
// were allocated. Only useful in checked & debug builds.
internal static bool SafeHandleStackTracesEnabled {
diff --git a/src/mscorlib/src/System/BadImageFormatException.cs b/src/mscorlib/src/System/BadImageFormatException.cs
index 3f3f4a5b6e..51a6c40771 100644
--- a/src/mscorlib/src/System/BadImageFormatException.cs
+++ b/src/mscorlib/src/System/BadImageFormatException.cs
@@ -16,11 +16,9 @@ namespace System {
using System;
using System.Runtime.Serialization;
using FileLoadException = System.IO.FileLoadException;
- using System.Security.Permissions;
using SecurityException = System.Security.SecurityException;
using System.Globalization;
- [System.Runtime.InteropServices.ComVisible(true)]
[Serializable]
public class BadImageFormatException : SystemException {
diff --git a/src/mscorlib/src/System/BitConverter.cs b/src/mscorlib/src/System/BitConverter.cs
index 3a6d1c03b0..07af5a8178 100644
--- a/src/mscorlib/src/System/BitConverter.cs
+++ b/src/mscorlib/src/System/BitConverter.cs
@@ -63,7 +63,7 @@ namespace System {
Contract.Ensures(Contract.Result<byte[]>().Length == 2);
byte[] bytes = new byte[2];
- fixed(byte* b = bytes)
+ fixed(byte* b = &bytes[0])
*((short*)b) = value;
return bytes;
}
@@ -76,7 +76,7 @@ namespace System {
Contract.Ensures(Contract.Result<byte[]>().Length == 4);
byte[] bytes = new byte[4];
- fixed(byte* b = bytes)
+ fixed(byte* b = &bytes[0])
*((int*)b) = value;
return bytes;
}
@@ -89,7 +89,7 @@ namespace System {
Contract.Ensures(Contract.Result<byte[]>().Length == 8);
byte[] bytes = new byte[8];
- fixed(byte* b = bytes)
+ fixed(byte* b = &bytes[0])
*((long*)b) = value;
return bytes;
}
diff --git a/src/mscorlib/src/System/Boolean.cs b/src/mscorlib/src/System/Boolean.cs
index 9aaec9a345..c085b0a020 100644
--- a/src/mscorlib/src/System/Boolean.cs
+++ b/src/mscorlib/src/System/Boolean.cs
@@ -19,7 +19,6 @@ namespace System {
// The Boolean class provides the
// object representation of the boolean primitive type.
[Serializable]
-[System.Runtime.InteropServices.ComVisible(true)]
public struct Boolean : IComparable, IConvertible, IComparable<Boolean>, IEquatable<Boolean>
{
diff --git a/src/mscorlib/src/System/Buffer.cs b/src/mscorlib/src/System/Buffer.cs
index eee2a81b51..662b240b34 100644
--- a/src/mscorlib/src/System/Buffer.cs
+++ b/src/mscorlib/src/System/Buffer.cs
@@ -22,7 +22,6 @@ namespace System {
using nuint = System.UInt32;
#endif // BIT64
-[System.Runtime.InteropServices.ComVisible(true)]
public static class Buffer
{
// Copies from one primitive array to another primitive array without
@@ -205,7 +204,6 @@ namespace System {
*(src + len) = 0;
}
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
internal unsafe static void Memcpy(byte[] dest, int destIndex, byte* src, int srcIndex, int len) {
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");
@@ -218,7 +216,6 @@ namespace System {
}
}
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
internal unsafe static void Memcpy(byte* pDest, int destIndex, byte[] src, int srcIndex, int len)
{
Debug.Assert( (srcIndex >= 0) && (destIndex >= 0) && (len >= 0), "Index and length must be non-negative!");
@@ -242,7 +239,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]
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
#if ARM
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal unsafe static extern void Memcpy(byte* dest, byte* src, int len);
@@ -255,7 +251,6 @@ namespace System {
#endif // ARM
// This method has different signature for x64 and other platforms and is done for performance reasons.
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
internal unsafe static void Memmove(byte* dest, byte* src, nuint len)
{
// P/Invoke into the native version when the buffers are overlapping and the copy needs to be performed backwards
@@ -581,7 +576,6 @@ namespace System {
// Non-inlinable wrapper around the QCall that avoids poluting the fast path
// with P/Invoke prolog/epilog.
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
[MethodImplAttribute(MethodImplOptions.NoInlining)]
private unsafe static void _Memmove(byte* dest, byte* src, nuint len)
{
@@ -590,7 +584,6 @@ namespace System {
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
- [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.
diff --git a/src/mscorlib/src/System/ByReference.cs b/src/mscorlib/src/System/ByReference.cs
index 6f8bb2281e..833dab0d55 100644
--- a/src/mscorlib/src/System/ByReference.cs
+++ b/src/mscorlib/src/System/ByReference.cs
@@ -15,16 +15,20 @@ namespace System
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); }
+ // Implemented as a JIT intrinsic - This default implementation is for
+ // completeness and to provide a concrete error if called via reflection
+ // or if intrinsic is missed.
+ throw new System.PlatformNotSupportedException();
}
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); }
+ // Implemented as a JIT intrinsic - This default implementation is for
+ // completeness and to provide a concrete error if called via reflection
+ // or if the intrinsic is missed.
+ throw new System.PlatformNotSupportedException();
}
}
}
diff --git a/src/mscorlib/src/System/Byte.cs b/src/mscorlib/src/System/Byte.cs
index 980412b69e..666fdda75b 100644
--- a/src/mscorlib/src/System/Byte.cs
+++ b/src/mscorlib/src/System/Byte.cs
@@ -22,7 +22,6 @@ namespace System {
// The Byte class extends the Value class and
// provides object representation of the byte primitive type.
//
-[System.Runtime.InteropServices.ComVisible(true)]
[Serializable]
[System.Runtime.InteropServices.StructLayout(LayoutKind.Sequential)]
public struct Byte : IComparable, IFormattable, IConvertible
diff --git a/src/mscorlib/src/System/CLRConfig.cs b/src/mscorlib/src/System/CLRConfig.cs
index 01ad7c31ab..16c610b82b 100644
--- a/src/mscorlib/src/System/CLRConfig.cs
+++ b/src/mscorlib/src/System/CLRConfig.cs
@@ -9,26 +9,6 @@ using System.Security;
namespace System {
-/// <summary>
-/// For now, this class should be the central point to collect all managed declarations
-/// of native functions designed to expose config switches.
-/// In Dev11 M2.2 we will redesign this class to expose CLRConfig from within the CLR
-/// and refactor managed Fx code to access all compat switches through here.
-/// </summary>
-[FriendAccessAllowed]
-internal class CLRConfig {
-
- [FriendAccessAllowed]
- [MethodImplAttribute(MethodImplOptions.InternalCall)]
- [SuppressUnmanagedCodeSecurity]
- internal static extern bool CheckLegacyManagedDeflateStream();
-
- [MethodImplAttribute(MethodImplOptions.InternalCall)]
- [SuppressUnmanagedCodeSecurity]
- internal static extern bool CheckThrowUnobservedTaskExceptions();
-
-} // internal class CLRConfig
-
} // namespace System
// file CLRConfig
diff --git a/src/mscorlib/src/System/CLSCompliantAttribute.cs b/src/mscorlib/src/System/CLSCompliantAttribute.cs
index e902049558..e03600d132 100644
--- a/src/mscorlib/src/System/CLSCompliantAttribute.cs
+++ b/src/mscorlib/src/System/CLSCompliantAttribute.cs
@@ -11,23 +11,23 @@
**
=============================================================================*/
-namespace System {
-[Serializable]
- [AttributeUsage (AttributeTargets.All, Inherited=true, AllowMultiple=false)]
-[System.Runtime.InteropServices.ComVisible(true)]
- public sealed class CLSCompliantAttribute : Attribute
+namespace System
+{
+ [Serializable]
+ [AttributeUsage(AttributeTargets.All, Inherited = true, AllowMultiple = false)]
+ public sealed class CLSCompliantAttribute : Attribute
{
- private bool m_compliant;
+ private bool _compliant;
- public CLSCompliantAttribute (bool isCompliant)
+ public CLSCompliantAttribute(bool isCompliant)
{
- m_compliant = isCompliant;
+ _compliant = isCompliant;
}
- public bool IsCompliant
+ public bool IsCompliant
{
- get
+ get
{
- return m_compliant;
+ return _compliant;
}
}
}
diff --git a/src/mscorlib/src/System/CannotUnloadAppDomainException.cs b/src/mscorlib/src/System/CannotUnloadAppDomainException.cs
deleted file mode 100644
index 6b07eae5e2..0000000000
--- a/src/mscorlib/src/System/CannotUnloadAppDomainException.cs
+++ /dev/null
@@ -1,49 +0,0 @@
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-// See the LICENSE file in the project root for more information.
-
-/*=============================================================================
-**
-**
-**
-** Purpose: Exception class for failed attempt to unload an AppDomain.
-**
-**
-=============================================================================*/
-
-namespace System {
-
- using System.Runtime.Serialization;
-
- [System.Runtime.InteropServices.ComVisible(true)]
- [Serializable]
- public class CannotUnloadAppDomainException : SystemException {
- public CannotUnloadAppDomainException()
- : base(Environment.GetResourceString("Arg_CannotUnloadAppDomainException")) {
- SetErrorCode(__HResults.COR_E_CANNOTUNLOADAPPDOMAIN);
- }
-
- public CannotUnloadAppDomainException(String message)
- : base(message) {
- SetErrorCode(__HResults.COR_E_CANNOTUNLOADAPPDOMAIN);
- }
-
- public CannotUnloadAppDomainException(String message, Exception innerException)
- : base(message, innerException) {
- SetErrorCode(__HResults.COR_E_CANNOTUNLOADAPPDOMAIN);
- }
-
- //
- //This constructor is required for serialization.
- //
- protected CannotUnloadAppDomainException(SerializationInfo info, StreamingContext context) : base(info, context) {
- }
- }
-}
-
-
-
-
-
-
-
diff --git a/src/mscorlib/src/System/CfgParser.cs b/src/mscorlib/src/System/CfgParser.cs
deleted file mode 100644
index b21da7fe94..0000000000
--- a/src/mscorlib/src/System/CfgParser.cs
+++ /dev/null
@@ -1,564 +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: XMLParser and Tree builder internal to BCL
- **
- **
- ===========================================================*/
-
-namespace System
-{
- using System.Runtime.InteropServices;
- using System.Collections;
- using System.Collections.Generic;
- using System.Runtime.CompilerServices;
- using System.Security.Permissions;
- using System.Security;
- using System.Globalization;
- using System.IO;
- using System.Runtime.Versioning;
- using System.Diagnostics.Contracts;
-
- [Serializable]
- internal enum ConfigEvents
- {
- StartDocument = 0,
- StartDTD = StartDocument + 1,
- EndDTD = StartDTD + 1,
- StartDTDSubset = EndDTD + 1,
- EndDTDSubset = StartDTDSubset + 1,
- EndProlog = EndDTDSubset + 1,
- StartEntity = EndProlog + 1,
- EndEntity = StartEntity + 1,
- EndDocument = EndEntity + 1,
- DataAvailable = EndDocument + 1,
- LastEvent = DataAvailable
- }
-
- [Serializable]
- internal enum ConfigNodeType
- {
- Element = 1,
- Attribute = Element + 1,
- Pi = Attribute + 1,
- XmlDecl = Pi + 1,
- DocType = XmlDecl + 1,
- DTDAttribute = DocType + 1,
- EntityDecl = DTDAttribute + 1,
- ElementDecl = EntityDecl + 1,
- AttlistDecl = ElementDecl + 1,
- Notation = AttlistDecl + 1,
- Group = Notation + 1,
- IncludeSect = Group + 1,
- PCData = IncludeSect + 1,
- CData = PCData + 1,
- IgnoreSect = CData + 1,
- Comment = IgnoreSect + 1,
- EntityRef = Comment + 1,
- Whitespace = EntityRef + 1,
- Name = Whitespace + 1,
- NMToken = Name + 1,
- String = NMToken + 1,
- Peref = String + 1,
- Model = Peref + 1,
- ATTDef = Model + 1,
- ATTType = ATTDef + 1,
- ATTPresence = ATTType + 1,
- DTDSubset = ATTPresence + 1,
- LastNodeType = DTDSubset + 1
- }
-
- [Serializable]
- internal enum ConfigNodeSubType
- {
- Version = (int)ConfigNodeType.LastNodeType,
- Encoding = Version + 1,
- Standalone = Encoding + 1,
- NS = Standalone + 1,
- XMLSpace = NS + 1,
- XMLLang = XMLSpace + 1,
- System = XMLLang + 1,
- Public = System + 1,
- NData = Public + 1,
- AtCData = NData + 1,
- AtId = AtCData + 1,
- AtIdref = AtId + 1,
- AtIdrefs = AtIdref + 1,
- AtEntity = AtIdrefs + 1,
- AtEntities = AtEntity + 1,
- AtNmToken = AtEntities + 1,
- AtNmTokens = AtNmToken + 1,
- AtNotation = AtNmTokens + 1,
- AtRequired = AtNotation + 1,
- AtImplied = AtRequired + 1,
- AtFixed = AtImplied + 1,
- PentityDecl = AtFixed + 1,
- Empty = PentityDecl + 1,
- Any = Empty + 1,
- Mixed = Any + 1,
- Sequence = Mixed + 1,
- Choice = Sequence + 1,
- Star = Choice + 1,
- Plus = Star + 1,
- Questionmark = Plus + 1,
- LastSubNodeType = Questionmark + 1
- }
-
- internal abstract class BaseConfigHandler
- {
- // These delegates must be at the very start of the object
- // This is necessary because unmanaged code takes a dependency on this layout
- // Any changes made to this must be reflected in ConfigHelper.h in ConfigFactory class
- protected Delegate[] eventCallbacks;
- public BaseConfigHandler()
- {
- InitializeCallbacks();
- }
- private void InitializeCallbacks()
- {
- if (eventCallbacks == null)
- {
- eventCallbacks = new Delegate[6];
- eventCallbacks[0] = new NotifyEventCallback(this.NotifyEvent);
- eventCallbacks[1] = new BeginChildrenCallback(this.BeginChildren);
- eventCallbacks[2] = new EndChildrenCallback(this.EndChildren);
- eventCallbacks[3] = new ErrorCallback(this.Error);
- eventCallbacks[4] = new CreateNodeCallback(this.CreateNode);
- eventCallbacks[5] = new CreateAttributeCallback(this.CreateAttribute);
- }
- }
-
- private delegate void NotifyEventCallback(ConfigEvents nEvent);
- public abstract void NotifyEvent(ConfigEvents nEvent);
-
- private delegate void BeginChildrenCallback(int size,
- ConfigNodeSubType subType,
- ConfigNodeType nType,
- int terminal,
- [MarshalAs(UnmanagedType.LPWStr)] String text,
- int textLength,
- int prefixLength);
- public abstract void BeginChildren(int size,
- ConfigNodeSubType subType,
- ConfigNodeType nType,
- int terminal,
- [MarshalAs(UnmanagedType.LPWStr)] String text,
- int textLength,
- int prefixLength);
-
- private delegate void EndChildrenCallback(int fEmpty,
- int size,
- ConfigNodeSubType subType,
- ConfigNodeType nType,
- int terminal,
- [MarshalAs(UnmanagedType.LPWStr)] String text,
- int textLength,
- int prefixLength);
- public abstract void EndChildren(int fEmpty,
- int size,
- ConfigNodeSubType subType,
- ConfigNodeType nType,
- int terminal,
- [MarshalAs(UnmanagedType.LPWStr)] String text,
- int textLength,
- int prefixLength);
-
- private delegate void ErrorCallback(int size,
- ConfigNodeSubType subType,
- ConfigNodeType nType,
- int terminal,
- [MarshalAs(UnmanagedType.LPWStr)]String text,
- int textLength,
- int prefixLength);
- public abstract void Error(int size,
- ConfigNodeSubType subType,
- ConfigNodeType nType,
- int terminal,
- [MarshalAs(UnmanagedType.LPWStr)]String text,
- int textLength,
- int prefixLength);
-
- private delegate void CreateNodeCallback(int size,
- ConfigNodeSubType subType,
- ConfigNodeType nType,
- int terminal,
- [MarshalAs(UnmanagedType.LPWStr)]String text,
- int textLength,
- int prefixLength);
- public abstract void CreateNode(int size,
- ConfigNodeSubType subType,
- ConfigNodeType nType,
- int terminal,
- [MarshalAs(UnmanagedType.LPWStr)]String text,
- int textLength,
- int prefixLength);
-
- private delegate void CreateAttributeCallback(int size,
- ConfigNodeSubType subType,
- ConfigNodeType nType,
- int terminal,
- [MarshalAs(UnmanagedType.LPWStr)]String text,
- int textLength,
- int prefixLength);
- public abstract void CreateAttribute(int size,
- ConfigNodeSubType subType,
- ConfigNodeType nType,
- int terminal,
- [MarshalAs(UnmanagedType.LPWStr)]String text,
- int textLength,
- int prefixLength);
-
- [MethodImplAttribute(MethodImplOptions.InternalCall)]
- internal extern void RunParser(String fileName);
- }
-
- // Class used to build a DOM like tree of parsed XML
- internal class ConfigTreeParser : BaseConfigHandler
- {
- ConfigNode rootNode = null;
- ConfigNode currentNode = null;
- String fileName = null;
- int attributeEntry;
- String key = null;
- String [] treeRootPath = null; // element to start tree
- bool parsing = false;
- int depth = 0;
- int pathDepth = 0;
- int searchDepth = 0;
- bool bNoSearchPath = false;
-
- // Track state for error message formatting
- String lastProcessed = null;
- bool lastProcessedEndElement;
-
-
- // NOTE: This parser takes a path eg. /configuration/system.runtime.remoting
- // and will return a node which matches this.
- internal ConfigNode Parse(String fileName, String configPath)
- {
- return Parse(fileName, configPath, false);
- }
-
- internal ConfigNode Parse(String fileName, String configPath, bool skipSecurityStuff)
- {
- if (fileName == null)
- throw new ArgumentNullException(nameof(fileName));
- Contract.EndContractBlock();
- this.fileName = fileName;
- if (configPath[0] == '/'){
- treeRootPath = configPath.Substring(1).Split('/');
- pathDepth = treeRootPath.Length - 1;
- bNoSearchPath = false;
- }
- else{
- treeRootPath = new String[1];
- treeRootPath[0] = configPath;
- bNoSearchPath = true;
- }
-
- if (!skipSecurityStuff) {
- (new FileIOPermission(FileIOPermissionAccess.Read, Path.GetFullPath(fileName))).Demand();
- }
-#pragma warning disable 618
- (new SecurityPermission(SecurityPermissionFlag.UnmanagedCode)).Assert();
-#pragma warning restore 618
-
- try
- {
- RunParser(fileName);
- }
- catch(FileNotFoundException) {
- throw; // Pass these through unadulterated.
- }
- catch(DirectoryNotFoundException) {
- throw; // Pass these through unadulterated.
- }
- catch(UnauthorizedAccessException) {
- throw;
- }
- catch(FileLoadException) {
- throw;
- }
- catch(Exception inner) {
- String message = GetInvalidSyntaxMessage();
- // 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.
- throw new Exception(message, inner);
- }
- return rootNode;
- }
-
- public override void NotifyEvent(ConfigEvents nEvent)
- {
- BCLDebug.Trace("REMOTE", "NotifyEvent "+((Enum)nEvent).ToString()+"\n");
- }
-
- public override void BeginChildren(int size,
- ConfigNodeSubType subType,
- ConfigNodeType nType,
- int terminal,
- [MarshalAs(UnmanagedType.LPWStr)] String text,
- int textLength,
- int prefixLength)
- {
- //Trace("BeginChildren",size,subType,nType,terminal,text,textLength,prefixLength,0);
- if (!parsing &&
- (!bNoSearchPath
- && depth == (searchDepth + 1)
- && String.Compare(text, treeRootPath[searchDepth], StringComparison.Ordinal) == 0))
- {
- searchDepth++;
- }
- }
-
- public override void EndChildren(int fEmpty,
- int size,
- ConfigNodeSubType subType,
- ConfigNodeType nType,
- int terminal,
- [MarshalAs(UnmanagedType.LPWStr)] String text,
- int textLength,
- int prefixLength)
- {
- lastProcessed = text;
- lastProcessedEndElement = true;
- if (parsing)
- {
- //Trace("EndChildren",size,subType,nType,terminal,text,textLength,prefixLength,fEmpty);
-
- if (currentNode == rootNode)
- {
- // End of section of tree which is parsed
- parsing = false;
- }
-
- currentNode = currentNode.Parent;
- }
- else if (nType == ConfigNodeType.Element){
- if(depth == searchDepth && String.Compare(text, treeRootPath[searchDepth - 1], StringComparison.Ordinal) == 0)
- {
- searchDepth--;
- depth--;
- }
- else
- depth--;
- }
- }
-
- public override void Error(int size,
- ConfigNodeSubType subType,
- ConfigNodeType nType,
- int terminal,
- [MarshalAs(UnmanagedType.LPWStr)]String text,
- int textLength,
- int prefixLength)
- {
- //Trace("Error",size,subType,nType,terminal,text,textLength,prefixLength,0);
- }
-
- public override void CreateNode(int size,
- ConfigNodeSubType subType,
- ConfigNodeType nType,
- int terminal,
- [MarshalAs(UnmanagedType.LPWStr)]String text,
- int textLength,
- int prefixLength)
- {
- //Trace("CreateNode",size,subType,nType,terminal,text,textLength,prefixLength,0);
-
- if (nType == ConfigNodeType.Element)
- {
- // New Node
- lastProcessed = text;
- lastProcessedEndElement = false;
-
- if (parsing
- || (bNoSearchPath &&
- String.Compare(text, treeRootPath[0], StringComparison.OrdinalIgnoreCase) == 0)
- || (depth == searchDepth && searchDepth == pathDepth &&
- String.Compare(text, treeRootPath[pathDepth], StringComparison.OrdinalIgnoreCase) == 0 ))
- {
- parsing = true;
-
- ConfigNode parentNode = currentNode;
- currentNode = new ConfigNode(text, parentNode);
- if (rootNode == null)
- rootNode = currentNode;
- else
- parentNode.AddChild(currentNode);
- }
- else
- depth++;
- }
- else if (nType == ConfigNodeType.PCData)
- {
- // Data node
- if (currentNode != null)
- {
- currentNode.Value = text;
- }
- }
- }
-
- public override void CreateAttribute(int size,
- ConfigNodeSubType subType,
- ConfigNodeType nType,
- int terminal,
- [MarshalAs(UnmanagedType.LPWStr)]String text,
- int textLength,
- int prefixLength)
- {
- //Trace("CreateAttribute",size,subType,nType,terminal,text,textLength,prefixLength,0);
- if (parsing)
- {
- // if the value of the attribute is null, the parser doesn't come back, so need to store the attribute when the
- // attribute name is encountered
- if (nType == ConfigNodeType.Attribute)
- {
- attributeEntry = currentNode.AddAttribute(text, "");
- key = text;
- }
- else if (nType == ConfigNodeType.PCData)
- {
- currentNode.ReplaceAttribute(attributeEntry, key, text);
- }
- else
- {
- String message = GetInvalidSyntaxMessage();
- // 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.
- throw new Exception(message);
- }
- }
- }
-
-#if _DEBUG
- [System.Diagnostics.Conditional("_LOGGING")]
- private void Trace(String name,
- int size,
- ConfigNodeSubType subType,
- ConfigNodeType nType,
- int terminal,
- [MarshalAs(UnmanagedType.LPWStr)]String text,
- int textLength,
- int prefixLength, int fEmpty)
- {
-
- BCLDebug.Trace("REMOTE","Node "+name);
- BCLDebug.Trace("REMOTE","text "+text);
- BCLDebug.Trace("REMOTE","textLength "+textLength);
- BCLDebug.Trace("REMOTE","size "+size);
- BCLDebug.Trace("REMOTE","subType "+((Enum)subType).ToString());
- BCLDebug.Trace("REMOTE","nType "+((Enum)nType).ToString());
- BCLDebug.Trace("REMOTE","terminal "+terminal);
- BCLDebug.Trace("REMOTE","prefixLength "+prefixLength);
- BCLDebug.Trace("REMOTE","fEmpty "+fEmpty+"\n");
- }
-#endif
-
- private String GetInvalidSyntaxMessage()
- {
- String lastProcessedTag = null;
-
- if (lastProcessed != null)
- lastProcessedTag = (lastProcessedEndElement ? "</" : "<") + lastProcessed + ">";
-
- return Environment.GetResourceString("XML_Syntax_InvalidSyntaxInFile", fileName, lastProcessedTag);
- }
- }
-
- // Node in Tree produced by ConfigTreeParser
- internal class ConfigNode
- {
- String m_name = null;
- String m_value = null;
- ConfigNode m_parent = null;
- List<ConfigNode> m_children = new List<ConfigNode>(5);
- List<DictionaryEntry> m_attributes = new List<DictionaryEntry>(5);
-
- internal ConfigNode(String name, ConfigNode parent)
- {
- m_name = name;
- m_parent = parent;
- }
-
- internal String Name
- {
- get {return m_name;}
- }
-
- internal String Value
- {
- get {return m_value;}
- set {m_value = value;}
- }
-
- internal ConfigNode Parent
- {
- get {return m_parent;}
- }
-
- internal List<ConfigNode> Children
- {
- get {return m_children;}
- }
-
- internal List<DictionaryEntry> Attributes
- {
- get {return m_attributes;}
- }
-
- internal void AddChild(ConfigNode child)
- {
- child.m_parent = this;
- m_children.Add(child);
- }
-
- internal int AddAttribute(String key, String value)
- {
- m_attributes.Add(new DictionaryEntry(key, value));
- return m_attributes.Count-1;
- }
-
- internal void ReplaceAttribute(int index, String key, String value)
- {
- m_attributes[index] = new DictionaryEntry(key, value);
- }
-
-#if _DEBUG
- [System.Diagnostics.Conditional("_LOGGING")]
- internal void Trace()
- {
- BCLDebug.Trace("REMOTE","************ConfigNode************");
- BCLDebug.Trace("REMOTE","Name = "+m_name);
- if (m_value != null)
- BCLDebug.Trace("REMOTE","Value = "+m_value);
- if (m_parent != null)
- BCLDebug.Trace("REMOTE","Parent = "+m_parent.Name);
- for (int i=0; i<m_attributes.Count; i++)
- {
- DictionaryEntry de = (DictionaryEntry)m_attributes[i];
- BCLDebug.Trace("REMOTE","Key = "+de.Key+" Value = "+de.Value);
- }
-
- for (int i=0; i<m_children.Count; i++)
- {
- ((ConfigNode)m_children[i]).Trace();
- }
- }
-#endif
- }
-}
-
-
-
-
-
-
diff --git a/src/mscorlib/src/System/Char.cs b/src/mscorlib/src/System/Char.cs
index b9c9305932..7fe1c08715 100644
--- a/src/mscorlib/src/System/Char.cs
+++ b/src/mscorlib/src/System/Char.cs
@@ -21,7 +21,6 @@ namespace System {
using System.Diagnostics;
using System.Diagnostics.Contracts;
-[System.Runtime.InteropServices.ComVisible(true)]
[Serializable]
[System.Runtime.InteropServices.StructLayout(LayoutKind.Sequential)] public struct Char : IComparable, IConvertible
, IComparable<Char>, IEquatable<Char>
diff --git a/src/mscorlib/src/System/CharEnumerator.cs b/src/mscorlib/src/System/CharEnumerator.cs
index d25294c7e2..689ed7e488 100644
--- a/src/mscorlib/src/System/CharEnumerator.cs
+++ b/src/mscorlib/src/System/CharEnumerator.cs
@@ -11,65 +11,71 @@
**
**
============================================================*/
-namespace System {
- using System.Collections;
- using System.Collections.Generic;
- using System.Diagnostics.Contracts;
+using System.Collections;
+using System.Collections.Generic;
-[System.Runtime.InteropServices.ComVisible(true)]
- [Serializable]
- public sealed class CharEnumerator : IEnumerator, ICloneable, IEnumerator<char>, IDisposable {
- private String str;
- private int index;
- private char currentElement;
+namespace System
+{
+ public sealed class CharEnumerator : IEnumerator, IEnumerator<char>, IDisposable, ICloneable
+ {
+ private String _str;
+ private int _index;
+ private char _currentElement;
- internal CharEnumerator(String str) {
- Contract.Requires(str != null);
- this.str = str;
- this.index = -1;
+ internal CharEnumerator(String str)
+ {
+ _str = str;
+ _index = -1;
}
- public Object Clone() {
+ public object Clone()
+ {
return MemberwiseClone();
}
-
- public bool MoveNext() {
- if (index < (str.Length-1)) {
- index++;
- currentElement = str[index];
+
+ public bool MoveNext()
+ {
+ if (_index < (_str.Length - 1))
+ {
+ _index++;
+ _currentElement = _str[_index];
return true;
}
else
- index = str.Length;
+ _index = _str.Length;
return false;
-
}
- public void Dispose() {
- if (str != null)
- index = str.Length;
- str = null;
+ public void Dispose()
+ {
+ if (_str != null)
+ _index = _str.Length;
+ _str = null;
}
-
+
/// <internalonly/>
- Object IEnumerator.Current {
+ Object IEnumerator.Current
+ {
get { return Current; }
}
-
- public char Current {
- get {
- if (index == -1)
- throw new InvalidOperationException(Environment.GetResourceString(ResId.InvalidOperation_EnumNotStarted));
- if (index >= str.Length)
- throw new InvalidOperationException(Environment.GetResourceString(ResId.InvalidOperation_EnumEnded));
- return currentElement;
+
+ public char Current
+ {
+ get
+ {
+ if (_index == -1)
+ throw new InvalidOperationException(SR.InvalidOperation_EnumNotStarted);
+ if (_index >= _str.Length)
+ throw new InvalidOperationException(SR.InvalidOperation_EnumEnded);
+ return _currentElement;
}
}
- public void Reset() {
- currentElement = (char)0;
- index = -1;
+ public void Reset()
+ {
+ _currentElement = (char)0;
+ _index = -1;
}
}
}
diff --git a/src/mscorlib/src/System/Collections/ArrayList.cs b/src/mscorlib/src/System/Collections/ArrayList.cs
index e7f121370b..53746e224e 100644
--- a/src/mscorlib/src/System/Collections/ArrayList.cs
+++ b/src/mscorlib/src/System/Collections/ArrayList.cs
@@ -18,7 +18,6 @@ namespace System.Collections {
using System;
using System.Runtime;
using System.Security;
- using System.Security.Permissions;
using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Runtime.Serialization;
@@ -35,8 +34,7 @@ namespace System.Collections {
[DebuggerTypeProxy(typeof(System.Collections.ArrayList.ArrayListDebugView))]
[DebuggerDisplay("Count = {Count}")]
[Serializable]
- [System.Runtime.InteropServices.ComVisible(true)]
- public class ArrayList : IList, ICloneable
+ internal class ArrayList : IList, ICloneable
{
private Object[] _items;
[ContractPublicPropertyName("Count")]
@@ -47,12 +45,6 @@ namespace System.Collections {
private const int _defaultCapacity = 4;
private static readonly Object[] emptyArray = EmptyArray<Object>.Value;
-
- // Note: this constructor is a bogus constructor that does nothing
- // and is for use only with SyncArrayList.
- internal ArrayList( bool trash )
- {
- }
// Constructs a ArrayList. The list is initially empty and has a capacity
// of zero. Upon adding the first element to the list the capacity is
@@ -175,22 +167,6 @@ namespace System.Collections {
_version++;
}
}
-
- // Creates a ArrayList wrapper for a particular IList. This does not
- // copy the contents of the IList, but only wraps the ILIst. So any
- // changes to the underlying list will affect the ArrayList. This would
- // be useful if you want to Reverse a subrange of an IList, or want to
- // use a generic BinarySearch or Sort method without implementing one yourself.
- // However, since these methods are generic, the performance may not be
- // nearly as good for some operations as they would be on the IList itself.
- //
- public static ArrayList Adapter(IList list) {
- if (list==null)
- throw new ArgumentNullException(nameof(list));
- Contract.Ensures(Contract.Result<ArrayList>() != null);
- Contract.EndContractBlock();
- return new IListWrapper(list);
- }
// Adds the given object to the end of this list. The size of the list is
// increased by one. If required, the capacity of the list is doubled
@@ -211,52 +187,6 @@ namespace System.Collections {
public virtual void AddRange(ICollection c) {
InsertRange(_size, c);
}
-
- // Searches a section of the list for a given element using a binary search
- // algorithm. Elements of the list are compared to the search value using
- // the given IComparer interface. If comparer is null, elements of
- // the list are compared to the search value using the IComparable
- // interface, which in that case must be implemented by all elements of the
- // list and the given search value. This method assumes that the given
- // section of the list is already sorted; if this is not the case, the
- // result will be incorrect.
- //
- // The method returns the index of the given value in the list. If the
- // list does not contain the given value, the method returns a negative
- // integer. The bitwise complement operator (~) can be applied to a
- // negative result to produce the index of the first element (if any) that
- // is larger than the given search value. This is also the index at which
- // the search value should be inserted into the list in order for the list
- // to remain sorted.
- //
- // The method uses the Array.BinarySearch method to perform the
- // search.
- //
- public virtual int BinarySearch(int index, int count, Object value, IComparer comparer) {
- 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 (_size - index < count)
- throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen"));
- Contract.Ensures(Contract.Result<int>() < Count);
- Contract.Ensures(Contract.Result<int>() < index + count);
- Contract.EndContractBlock();
-
- return Array.BinarySearch((Array)_items, index, count, value, comparer);
- }
-
- public virtual int BinarySearch(Object value)
- {
- Contract.Ensures(Contract.Result<int>() < Count);
- return BinarySearch(0, Count, value, null);
- }
-
- public virtual int BinarySearch(Object value, IComparer comparer)
- {
- Contract.Ensures(Contract.Result<int>() < Count);
- return BinarySearch(0, Count, value, comparer);
- }
// Clears the contents of ArrayList.
@@ -301,13 +231,6 @@ namespace System.Collections {
return false;
}
}
-
- // Copies this ArrayList into array, which must be of a
- // compatible array type.
- //
- public virtual void CopyTo(Array array) {
- CopyTo(array, 0);
- }
// Copies this ArrayList into array, which must be of a
// compatible array type.
@@ -319,20 +242,6 @@ namespace System.Collections {
// Delegate rest of error checking to Array.Copy.
Array.Copy(_items, 0, array, arrayIndex, _size);
}
-
- // Copies a section of this list to the given array at the given index.
- //
- // The method uses the Array.Copy method to copy the elements.
- //
- public virtual void CopyTo(int index, Array array, int arrayIndex, int count) {
- if (_size - index < count)
- throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen"));
- if ((array != null) && (array.Rank != 1))
- throw new ArgumentException(Environment.GetResourceString("Arg_RankMultiDimNotSupported"));
- Contract.EndContractBlock();
- // Delegate rest of error checking to Array.Copy.
- Array.Copy(_items, index, array, arrayIndex, count);
- }
// 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
@@ -349,28 +258,6 @@ namespace System.Collections {
}
}
- // Returns a list wrapper that is fixed at the current size. Operations
- // that add or remove items will fail, however, replacing items is allowed.
- //
- public static IList FixedSize(IList list) {
- if (list==null)
- throw new ArgumentNullException(nameof(list));
- Contract.Ensures(Contract.Result<IList>() != null);
- Contract.EndContractBlock();
- return new FixedSizeList(list);
- }
-
- // Returns a list wrapper that is fixed at the current size. Operations
- // that add or remove items will fail, however, replacing items is allowed.
- //
- public static ArrayList FixedSize(ArrayList list) {
- if (list==null)
- throw new ArgumentNullException(nameof(list));
- Contract.Ensures(Contract.Result<ArrayList>() != null);
- Contract.EndContractBlock();
- return new FixedSizeArrayList(list);
- }
-
// Returns an enumerator for this list with the given
// permission for removal of elements. If modifications made to the list
// while an enumeration is in progress, the MoveNext and
@@ -381,24 +268,6 @@ namespace System.Collections {
return new ArrayListEnumeratorSimple(this);
}
- // Returns an enumerator for a section of this list with the given
- // permission for removal of elements. If modifications made to the list
- // while an enumeration is in progress, the MoveNext and
- // GetObject methods of the enumerator will throw an exception.
- //
- public virtual IEnumerator GetEnumerator(int index, int count) {
- 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 (_size - index < count)
- throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen"));
- Contract.Ensures(Contract.Result<IEnumerator>() != null);
- Contract.EndContractBlock();
-
- return new ArrayListEnumerator(this, index, count);
- }
-
// Returns the index of the first occurrence of a given value in a range of
// this list. The list is searched forwards from beginning to end.
// The elements of the list are compared to the given value using the
@@ -412,41 +281,6 @@ namespace System.Collections {
return Array.IndexOf((Array)_items, value, 0, _size);
}
- // Returns the index of the first occurrence of a given value in a range of
- // this list. The list is searched forwards, starting at index
- // startIndex and ending at count number of elements. The
- // elements of the list are compared to the given value using the
- // Object.Equals method.
- //
- // This method uses the Array.IndexOf method to perform the
- // search.
- //
- public virtual int IndexOf(Object value, int startIndex) {
- if (startIndex > _size)
- 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);
- }
-
- // Returns the index of the first occurrence of a given value in a range of
- // this list. The list is searched forwards, starting at index
- // startIndex and upto count number of elements. The
- // elements of the list are compared to the given value using the
- // Object.Equals method.
- //
- // This method uses the Array.IndexOf method to perform the
- // search.
- //
- public virtual int IndexOf(Object value, int startIndex, int count) {
- if (startIndex > _size)
- 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);
- }
-
// Inserts an element into this list at a given index. The size of the list
// is increased by one. If required, the capacity of the list is doubled
// before inserting the new element.
@@ -494,62 +328,6 @@ namespace System.Collections {
}
}
- // Returns the index of the last occurrence of a given value in a range of
- // this list. The list is searched backwards, starting at the end
- // and ending at the first element in the list. The elements of the list
- // are compared to the given value using the Object.Equals method.
- //
- // This method uses the Array.LastIndexOf method to perform the
- // search.
- //
- public virtual int LastIndexOf(Object value)
- {
- Contract.Ensures(Contract.Result<int>() < _size);
- return LastIndexOf(value, _size - 1, _size);
- }
-
- // Returns the index of the last occurrence of a given value in a range of
- // this list. The list is searched backwards, starting at index
- // startIndex and ending at the first element in the list. The
- // elements of the list are compared to the given value using the
- // Object.Equals method.
- //
- // This method uses the Array.LastIndexOf method to perform the
- // search.
- //
- public virtual int LastIndexOf(Object value, int startIndex)
- {
- if (startIndex >= _size)
- throw new ArgumentOutOfRangeException(nameof(startIndex), Environment.GetResourceString("ArgumentOutOfRange_Index"));
- Contract.Ensures(Contract.Result<int>() < Count);
- Contract.EndContractBlock();
- return LastIndexOf(value, startIndex, startIndex + 1);
- }
-
- // Returns the index of the last occurrence of a given value in a range of
- // this list. The list is searched backwards, starting at index
- // startIndex and upto count elements. The elements of
- // the list are compared to the given value using the Object.Equals
- // method.
- //
- // This method uses the Array.LastIndexOf method to perform the
- // search.
- //
- public virtual int LastIndexOf(Object value, int startIndex, int count) {
- if (Count != 0 && (startIndex < 0 || count < 0))
- throw new ArgumentOutOfRangeException((startIndex<0 ? nameof(startIndex) : nameof(count)), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
- Contract.Ensures(Contract.Result<int>() < Count);
- Contract.EndContractBlock();
-
- if (_size == 0) // Special case for an empty list
- return -1;
-
- if (startIndex >= _size || count > startIndex + 1)
- 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.
//
[FriendAccessAllowed]
@@ -560,16 +338,6 @@ namespace System.Collections {
Contract.EndContractBlock();
return new ReadOnlyList(list);
}
-
- // Returns a read-only ArrayList wrapper for the given ArrayList.
- //
- public static ArrayList ReadOnly(ArrayList list) {
- if (list==null)
- throw new ArgumentNullException(nameof(list));
- Contract.Ensures(Contract.Result<ArrayList>() != null);
- Contract.EndContractBlock();
- return new ReadOnlyArrayList(list);
- }
// Removes the element at the given index. The size of the list is
// decreased by one.
@@ -600,159 +368,6 @@ namespace System.Collections {
_version++;
}
- // Removes a range of elements from this list.
- //
- public virtual void RemoveRange(int index, int count) {
- 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 (_size - index < count)
- throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen"));
- Contract.Ensures(Count >= 0);
- //Contract.Ensures(Count == Contract.OldValue(Count) - count);
- Contract.EndContractBlock();
-
- if (count > 0) {
- int i = _size;
- _size -= count;
- if (index < _size) {
- Array.Copy(_items, index + count, _items, index, _size - index);
- }
- while (i > _size) _items[--i] = null;
- _version++;
- }
- }
-
- // Returns an IList that contains count copies of value.
- //
- public static ArrayList Repeat(Object value, int count) {
- if (count < 0)
- throw new ArgumentOutOfRangeException(nameof(count),Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
- Contract.Ensures(Contract.Result<ArrayList>() != null);
- Contract.EndContractBlock();
-
- ArrayList list = new ArrayList((count>_defaultCapacity)?count:_defaultCapacity);
- for(int i=0; i<count; i++)
- list.Add(value);
- return list;
- }
-
- // Reverses the elements in this list.
- public virtual void Reverse() {
- Reverse(0, Count);
- }
-
- // Reverses the elements in a range of this list. Following a call to this
- // method, an element in the range given by index and count
- // which was previously located at index i will now be located at
- // index index + (index + count - i - 1).
- //
- // This method uses the Array.Reverse method to reverse the
- // elements.
- //
- public virtual void Reverse(int index, int count) {
- 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 (_size - index < count)
- throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen"));
- Contract.EndContractBlock();
- Array.Reverse(_items, index, count);
- _version++;
- }
-
- // Sets the elements starting at the given index to the elements of the
- // given collection.
- //
- public virtual void SetRange(int index, ICollection c) {
- 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(nameof(index), Environment.GetResourceString("ArgumentOutOfRange_Index"));
-
- if (count > 0) {
- c.CopyTo(_items, index);
- _version++;
- }
- }
-
- public virtual ArrayList GetRange(int index, int count) {
- if (index < 0 || count < 0)
- 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);
- Contract.EndContractBlock();
- return new Range(this,index, count);
- }
-
- // Sorts the elements in this list. Uses the default comparer and
- // Array.Sort.
- public virtual void Sort()
- {
- Sort(0, Count, Comparer.Default);
- }
-
- // Sorts the elements in this list. Uses Array.Sort with the
- // provided comparer.
- public virtual void Sort(IComparer comparer)
- {
- Sort(0, Count, comparer);
- }
-
- // Sorts the elements in a section of this list. The sort compares the
- // elements to each other using the given IComparer interface. If
- // comparer is null, the elements are compared to each other using
- // the IComparable interface, which in that case must be implemented by all
- // elements of the list.
- //
- // This method uses the Array.Sort method to sort the elements.
- //
- public virtual void Sort(int index, int count, IComparer comparer) {
- 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 (_size - index < count)
- throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen"));
- Contract.EndContractBlock();
-
- Array.Sort(_items, index, count, comparer);
- _version++;
- }
-
- // Returns a thread-safe wrapper around an IList.
- //
- public static IList Synchronized(IList list) {
- if (list==null)
- throw new ArgumentNullException(nameof(list));
- Contract.Ensures(Contract.Result<IList>() != null);
- Contract.EndContractBlock();
- return new SyncIList(list);
- }
-
- // Returns a thread-safe wrapper around a ArrayList.
- //
- public static ArrayList Synchronized(ArrayList list) {
- if (list==null)
- throw new ArgumentNullException(nameof(list));
- Contract.Ensures(Contract.Result<ArrayList>() != null);
- Contract.EndContractBlock();
- return new SyncArrayList(list);
- }
-
- // ToArray returns a new Object array containing the contents of the ArrayList.
- // This requires copying the ArrayList, which is an O(n) operation.
- public virtual Object[] ToArray() {
- Contract.Ensures(Contract.Result<Object[]>() != null);
-
- Object[] array = new Object[_size];
- Array.Copy(_items, 0, array, 0, _size);
- return array;
- }
-
// ToArray returns a new array of a particular type containing the contents
// of the ArrayList. This requires copying the ArrayList and potentially
// downcasting all elements. This copy may fail and is an O(n) operation.
@@ -768,1070 +383,6 @@ namespace System.Collections {
return array;
}
- // Sets the capacity of this list to the size of the list. This method can
- // be used to minimize a list's memory overhead once it is known that no
- // new elements will be added to the list. To completely clear a list and
- // release all memory referenced by the list, execute the following
- // statements:
- //
- // list.Clear();
- // list.TrimToSize();
- //
- public virtual void TrimToSize() {
- Capacity = _size;
- }
-
-
- // This class wraps an IList, exposing it as a ArrayList
- // Note this requires reimplementing half of ArrayList...
- [Serializable]
- private class IListWrapper : ArrayList
- {
- private IList _list;
-
- internal IListWrapper(IList list) {
- _list = list;
- _version = 0; // list doesn't not contain a version number
- }
-
- public override int Capacity {
- get { return _list.Count; }
- set {
- if (value < Count) throw new ArgumentOutOfRangeException(nameof(value), Environment.GetResourceString("ArgumentOutOfRange_SmallCapacity"));
- Contract.EndContractBlock();
- }
- }
-
- public override int Count {
- get { return _list.Count; }
- }
-
- public override bool IsReadOnly {
- get { return _list.IsReadOnly; }
- }
-
- public override bool IsFixedSize {
- get { return _list.IsFixedSize; }
- }
-
-
- public override bool IsSynchronized {
- get { return _list.IsSynchronized; }
- }
-
- public override Object this[int index] {
- get {
- return _list[index];
- }
- set {
- _list[index] = value;
- _version++;
- }
- }
-
- public override Object SyncRoot {
- get { return _list.SyncRoot; }
- }
-
- public override int Add(Object obj) {
- int i = _list.Add(obj);
- _version++;
- return i;
- }
-
- public override void AddRange(ICollection c) {
- InsertRange(Count, c);
- }
-
- // 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 ? nameof(index) : nameof(count)), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
- if (this.Count - index < count)
- throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen"));
- Contract.EndContractBlock();
- if (comparer == null)
- comparer = Comparer.Default;
-
- int lo = index;
- int hi = index + count - 1;
- int mid;
- while (lo <= hi) {
- mid = (lo+hi)/2;
- int r = comparer.Compare(value, _list[mid]);
- if (r == 0)
- return mid;
- if (r < 0)
- hi = mid-1;
- else
- lo = mid+1;
- }
- // return bitwise complement of the first element greater than value.
- // Since hi is less than lo now, ~lo is the correct item.
- return ~lo;
- }
-
- public override void Clear() {
- // If _list is an array, it will support Clear method.
- // We shouldn't allow clear operation on a FixedSized ArrayList
- if(_list.IsFixedSize) {
- throw new NotSupportedException(Environment.GetResourceString("NotSupported_FixedSizeCollection"));
- }
-
- _list.Clear();
- _version++;
- }
-
- public override Object Clone() {
- // This does not do a shallow copy of _list into a ArrayList!
- // This clones the IListWrapper, creating another wrapper class!
- return new IListWrapper(_list);
- }
-
- public override bool Contains(Object obj) {
- return _list.Contains(obj);
- }
-
- public override void CopyTo(Array array, int index) {
- _list.CopyTo(array, index);
- }
-
- public override void CopyTo(int index, Array array, int arrayIndex, int count) {
- if (array==null)
- throw new ArgumentNullException(nameof(array));
- if (index < 0 || arrayIndex < 0)
- throw new ArgumentOutOfRangeException((index < 0) ? nameof(index) : nameof(arrayIndex), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
- if( count < 0)
- 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)
- throw new ArgumentException(Environment.GetResourceString("Arg_RankMultiDimNotSupported"));
- Contract.EndContractBlock();
-
- if (_list.Count - index < count)
- throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen"));
-
- for(int i=index; i<index+count; i++)
- array.SetValue(_list[i], arrayIndex++);
- }
-
- public override IEnumerator GetEnumerator() {
- return _list.GetEnumerator();
- }
-
- public override IEnumerator GetEnumerator(int index, int count) {
- if (index < 0 || count < 0)
- 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"));
-
- return new IListWrapperEnumWrapper(this, index, count);
- }
-
- public override int IndexOf(Object value) {
- return _list.IndexOf(value);
- }
-
- [SuppressMessage("Microsoft.Contracts", "CC1055")] // Skip extra error checking to avoid *potential* AppCompat problems.
- public override int IndexOf(Object value, int startIndex) {
- return IndexOf(value, startIndex, _list.Count - startIndex);
- }
-
- public override int IndexOf(Object value, int startIndex, int 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;
- if (value == null) {
- for(int i=startIndex; i<endIndex; i++)
- if (_list[i] == null)
- return i;
- return -1;
- } else {
- for(int i=startIndex; i<endIndex; i++)
- if (_list[i] != null && _list[i].Equals(value))
- return i;
- return -1;
- }
- }
-
- public override void Insert(int index, Object obj) {
- _list.Insert(index, obj);
- _version++;
- }
-
- public override void InsertRange(int index, ICollection c) {
- if (c==null)
- 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) {
- ArrayList al = _list as ArrayList;
- if( al != null) {
- // We need to special case ArrayList.
- // When c is a range of _list, we need to handle this in a special way.
- // See ArrayList.InsertRange for details.
- al.InsertRange(index, c);
- }
- else {
- IEnumerator en = c.GetEnumerator();
- while(en.MoveNext()) {
- _list.Insert(index++, en.Current);
- }
- }
- _version++;
- }
- }
-
- public override int LastIndexOf(Object value) {
- return LastIndexOf(value,_list.Count - 1, _list.Count);
- }
-
- [SuppressMessage("Microsoft.Contracts", "CC1055")] // Skip extra error checking to avoid *potential* AppCompat problems.
- public override int LastIndexOf(Object value, int startIndex) {
- return LastIndexOf(value, startIndex, startIndex + 1);
- }
-
- [SuppressMessage("Microsoft.Contracts", "CC1055")] // Skip extra error checking to avoid *potential* AppCompat problems.
- public override int LastIndexOf(Object value, int startIndex, int count) {
- if (_list.Count == 0)
- return -1;
-
- 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) {
- for(int i=startIndex; i >= endIndex; i--)
- if (_list[i] == null)
- return i;
- return -1;
- } else {
- for(int i=startIndex; i >= endIndex; i--)
- if (_list[i] != null && _list[i].Equals(value))
- return i;
- return -1;
- }
- }
-
- public override void Remove(Object value) {
- int index = IndexOf(value);
- if (index >=0)
- RemoveAt(index);
- }
-
- public override void RemoveAt(int index) {
- _list.RemoveAt(index);
- _version++;
- }
-
- public override void RemoveRange(int index, int count) {
- if (index < 0 || count < 0)
- 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"));
-
- if( count > 0) // be consistent with ArrayList
- _version++;
-
- while(count > 0) {
- _list.RemoveAt(index);
- count--;
- }
- }
-
- public override void Reverse(int index, int count) {
- if (index < 0 || count < 0)
- 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"));
-
- int i = index;
- int j = index + count - 1;
- while (i < j)
- {
- Object tmp = _list[i];
- _list[i++] = _list[j];
- _list[j--] = tmp;
- }
- _version++;
- }
-
- public override void SetRange(int index, ICollection c) {
- if (c==null) {
- throw new ArgumentNullException(nameof(c), Environment.GetResourceString("ArgumentNull_Collection"));
- }
- Contract.EndContractBlock();
-
- if (index < 0 || index > _list.Count - c.Count) {
- throw new ArgumentOutOfRangeException(nameof(index), Environment.GetResourceString("ArgumentOutOfRange_Index"));
- }
-
- if( c.Count > 0) {
- IEnumerator en = c.GetEnumerator();
- while(en.MoveNext()) {
- _list[index++] = en.Current;
- }
- _version++;
- }
- }
-
- public override ArrayList GetRange(int index, int count) {
- if (index < 0 || count < 0)
- 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"));
- return new Range(this,index, count);
- }
-
- public override void Sort(int index, int count, IComparer comparer) {
- if (index < 0 || count < 0)
- 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"));
-
- Object [] array = new Object[count];
- CopyTo(index, array, 0, count);
- Array.Sort(array, 0, count, comparer);
- for(int i=0; i<count; i++)
- _list[i+index] = array[i];
-
- _version++;
- }
-
-
- public override Object[] ToArray() {
- Object[] array = new Object[Count];
- _list.CopyTo(array, 0);
- return array;
- }
-
- public override Array ToArray(Type type)
- {
- if (type==null)
- throw new ArgumentNullException(nameof(type));
- Contract.EndContractBlock();
- Array array = Array.UnsafeCreateInstance(type, _list.Count);
- _list.CopyTo(array, 0);
- return array;
- }
-
- public override void TrimToSize()
- {
- // Can't really do much here...
- }
-
- // This is the enumerator for an IList that's been wrapped in another
- // class that implements all of ArrayList's methods.
- [Serializable]
- private sealed class IListWrapperEnumWrapper : IEnumerator, ICloneable
- {
- private IEnumerator _en;
- private int _remaining;
- private int _initialStartIndex; // for reset
- private int _initialCount; // for reset
- private bool _firstCall; // firstCall to MoveNext
-
- private IListWrapperEnumWrapper()
- {
- }
-
- internal IListWrapperEnumWrapper(IListWrapper listWrapper, int startIndex, int count)
- {
- _en = listWrapper.GetEnumerator();
- _initialStartIndex = startIndex;
- _initialCount = count;
- while(startIndex-- > 0 && _en.MoveNext());
- _remaining = count;
- _firstCall = true;
- }
-
- public Object Clone() {
- // We must clone the underlying enumerator, I think.
- IListWrapperEnumWrapper clone = new IListWrapperEnumWrapper();
- clone._en = (IEnumerator) ((ICloneable)_en).Clone();
- clone._initialStartIndex = _initialStartIndex;
- clone._initialCount = _initialCount;
- clone._remaining = _remaining;
- clone._firstCall = _firstCall;
- return clone;
- }
-
- public bool MoveNext() {
- if (_firstCall) {
- _firstCall = false;
- return _remaining-- > 0 && _en.MoveNext();
- }
- if (_remaining < 0)
- return false;
- bool r = _en.MoveNext();
- return r && _remaining-- > 0;
- }
-
- public Object Current {
- get {
- if (_firstCall)
- throw new InvalidOperationException(Environment.GetResourceString(ResId.InvalidOperation_EnumNotStarted));
- if (_remaining < 0)
- throw new InvalidOperationException(Environment.GetResourceString(ResId.InvalidOperation_EnumEnded));
- return _en.Current;
- }
- }
-
- public void Reset() {
- _en.Reset();
- int startIndex = _initialStartIndex;
- while(startIndex-- > 0 && _en.MoveNext());
- _remaining = _initialCount;
- _firstCall = true;
- }
- }
- }
-
-
- [Serializable]
- private class SyncArrayList : ArrayList
- {
- private ArrayList _list;
- private Object _root;
-
- internal SyncArrayList(ArrayList list)
- : base( false )
- {
- _list = list;
- _root = list.SyncRoot;
- }
-
- public override int Capacity {
- get {
- lock(_root) {
- return _list.Capacity;
- }
- }
- [SuppressMessage("Microsoft.Contracts", "CC1055")] // Skip extra error checking to avoid *potential* AppCompat problems.
- set {
- lock(_root) {
- _list.Capacity = value;
- }
- }
- }
-
- public override int Count {
- get { lock(_root) { return _list.Count; } }
- }
-
- public override bool IsReadOnly {
- get { return _list.IsReadOnly; }
- }
-
- public override bool IsFixedSize {
- get { return _list.IsFixedSize; }
- }
-
-
- public override bool IsSynchronized {
- get { return true; }
- }
-
- public override Object this[int index] {
- get {
- lock(_root) {
- return _list[index];
- }
- }
- set {
- lock(_root) {
- _list[index] = value;
- }
- }
- }
-
- public override Object SyncRoot {
- get { return _root; }
- }
-
- public override int Add(Object value) {
- lock(_root) {
- return _list.Add(value);
- }
- }
-
- public override void AddRange(ICollection c) {
- lock(_root) {
- _list.AddRange(c);
- }
- }
-
- public override int BinarySearch(Object value) {
- lock(_root) {
- return _list.BinarySearch(value);
- }
- }
-
- public override int BinarySearch(Object value, IComparer comparer) {
- lock(_root) {
- return _list.BinarySearch(value, comparer);
- }
- }
-
- [SuppressMessage("Microsoft.Contracts", "CC1055")] // Skip extra error checking to avoid *potential* AppCompat problems.
- public override int BinarySearch(int index, int count, Object value, IComparer comparer) {
- lock(_root) {
- return _list.BinarySearch(index, count, value, comparer);
- }
- }
-
- public override void Clear() {
- lock(_root) {
- _list.Clear();
- }
- }
-
- public override Object Clone() {
- lock(_root) {
- return new SyncArrayList((ArrayList)_list.Clone());
- }
- }
-
- public override bool Contains(Object item) {
- lock(_root) {
- return _list.Contains(item);
- }
- }
-
- public override void CopyTo(Array array) {
- lock(_root) {
- _list.CopyTo(array);
- }
- }
-
- public override void CopyTo(Array array, int index) {
- lock(_root) {
- _list.CopyTo(array, index);
- }
- }
-
- [SuppressMessage("Microsoft.Contracts", "CC1055")] // Skip extra error checking to avoid *potential* AppCompat problems.
- public override void CopyTo(int index, Array array, int arrayIndex, int count) {
- lock(_root) {
- _list.CopyTo(index, array, arrayIndex, count);
- }
- }
-
- public override IEnumerator GetEnumerator() {
- lock(_root) {
- return _list.GetEnumerator();
- }
- }
-
- [SuppressMessage("Microsoft.Contracts", "CC1055")] // Skip extra error checking to avoid *potential* AppCompat problems.
- public override IEnumerator GetEnumerator(int index, int count) {
- lock(_root) {
- return _list.GetEnumerator(index, count);
- }
- }
-
- public override int IndexOf(Object value) {
- lock(_root) {
- return _list.IndexOf(value);
- }
- }
-
- [SuppressMessage("Microsoft.Contracts", "CC1055")] // Skip extra error checking to avoid *potential* AppCompat problems.
- public override int IndexOf(Object value, int startIndex) {
- lock(_root) {
- return _list.IndexOf(value, startIndex);
- }
- }
-
- [SuppressMessage("Microsoft.Contracts", "CC1055")] // Skip extra error checking to avoid *potential* AppCompat problems.
- public override int IndexOf(Object value, int startIndex, int count) {
- lock(_root) {
- return _list.IndexOf(value, startIndex, count);
- }
- }
-
- public override void Insert(int index, Object value) {
- lock(_root) {
- _list.Insert(index, value);
- }
- }
-
- [SuppressMessage("Microsoft.Contracts", "CC1055")] // Skip extra error checking to avoid *potential* AppCompat problems.
- public override void InsertRange(int index, ICollection c) {
- lock(_root) {
- _list.InsertRange(index, c);
- }
- }
-
- public override int LastIndexOf(Object value) {
- lock(_root) {
- return _list.LastIndexOf(value);
- }
- }
-
- [SuppressMessage("Microsoft.Contracts", "CC1055")] // Skip extra error checking to avoid *potential* AppCompat problems.
- public override int LastIndexOf(Object value, int startIndex) {
- lock(_root) {
- return _list.LastIndexOf(value, startIndex);
- }
- }
-
- [SuppressMessage("Microsoft.Contracts", "CC1055")] // Skip extra error checking to avoid *potential* AppCompat problems.
- public override int LastIndexOf(Object value, int startIndex, int count) {
- lock(_root) {
- return _list.LastIndexOf(value, startIndex, count);
- }
- }
-
- public override void Remove(Object value) {
- lock(_root) {
- _list.Remove(value);
- }
- }
-
- public override void RemoveAt(int index) {
- lock(_root) {
- _list.RemoveAt(index);
- }
- }
-
- [SuppressMessage("Microsoft.Contracts", "CC1055")] // Skip extra error checking to avoid *potential* AppCompat problems.
- public override void RemoveRange(int index, int count) {
- lock(_root) {
- _list.RemoveRange(index, count);
- }
- }
-
- [SuppressMessage("Microsoft.Contracts", "CC1055")] // Skip extra error checking to avoid *potential* AppCompat problems.
- public override void Reverse(int index, int count) {
- lock(_root) {
- _list.Reverse(index, count);
- }
- }
-
- [SuppressMessage("Microsoft.Contracts", "CC1055")] // Skip extra error checking to avoid *potential* AppCompat problems.
- public override void SetRange(int index, ICollection c) {
- lock(_root) {
- _list.SetRange(index, c);
- }
- }
-
- [SuppressMessage("Microsoft.Contracts", "CC1055")] // Skip extra error checking to avoid *potential* AppCompat problems.
- public override ArrayList GetRange(int index, int count) {
- lock(_root) {
- return _list.GetRange(index, count);
- }
- }
-
- public override void Sort() {
- lock(_root) {
- _list.Sort();
- }
- }
-
- public override void Sort(IComparer comparer) {
- lock(_root) {
- _list.Sort(comparer);
- }
- }
-
- [SuppressMessage("Microsoft.Contracts", "CC1055")] // Skip extra error checking to avoid *potential* AppCompat problems.
- public override void Sort(int index, int count, IComparer comparer) {
- lock(_root) {
- _list.Sort(index, count, comparer);
- }
- }
-
- public override Object[] ToArray() {
- lock(_root) {
- return _list.ToArray();
- }
- }
-
- [SuppressMessage("Microsoft.Contracts", "CC1055")] // Skip extra error checking to avoid *potential* AppCompat problems.
- public override Array ToArray(Type type) {
- lock(_root) {
- return _list.ToArray(type);
- }
- }
-
- public override void TrimToSize() {
- lock(_root) {
- _list.TrimToSize();
- }
- }
- }
-
-
- [Serializable]
- private class SyncIList : IList
- {
- private IList _list;
- private Object _root;
-
- internal SyncIList(IList list) {
- _list = list;
- _root = list.SyncRoot;
- }
-
- public virtual int Count {
- get { lock(_root) { return _list.Count; } }
- }
-
- public virtual bool IsReadOnly {
- get { return _list.IsReadOnly; }
- }
-
- public virtual bool IsFixedSize {
- get { return _list.IsFixedSize; }
- }
-
-
- public virtual bool IsSynchronized {
- get { return true; }
- }
-
- public virtual Object this[int index] {
- get {
- lock(_root) {
- return _list[index];
- }
- }
- set {
- lock(_root) {
- _list[index] = value;
- }
- }
- }
-
- public virtual Object SyncRoot {
- get { return _root; }
- }
-
- public virtual int Add(Object value) {
- lock(_root) {
- return _list.Add(value);
- }
- }
-
-
- public virtual void Clear() {
- lock(_root) {
- _list.Clear();
- }
- }
-
- public virtual bool Contains(Object item) {
- lock(_root) {
- return _list.Contains(item);
- }
- }
-
- public virtual void CopyTo(Array array, int index) {
- lock(_root) {
- _list.CopyTo(array, index);
- }
- }
-
- public virtual IEnumerator GetEnumerator() {
- lock(_root) {
- return _list.GetEnumerator();
- }
- }
-
- public virtual int IndexOf(Object value) {
- lock(_root) {
- return _list.IndexOf(value);
- }
- }
-
- public virtual void Insert(int index, Object value) {
- lock(_root) {
- _list.Insert(index, value);
- }
- }
-
- public virtual void Remove(Object value) {
- lock(_root) {
- _list.Remove(value);
- }
- }
-
- public virtual void RemoveAt(int index) {
- lock(_root) {
- _list.RemoveAt(index);
- }
- }
- }
-
- [Serializable]
- private class FixedSizeList : IList
- {
- private IList _list;
-
- internal FixedSizeList(IList l) {
- _list = l;
- }
-
- public virtual int Count {
- get { return _list.Count; }
- }
-
- public virtual bool IsReadOnly {
- get { return _list.IsReadOnly; }
- }
-
- public virtual bool IsFixedSize {
- get { return true; }
- }
-
- public virtual bool IsSynchronized {
- get { return _list.IsSynchronized; }
- }
-
- public virtual Object this[int index] {
- get {
- return _list[index];
- }
- set {
- _list[index] = value;
- }
- }
-
- public virtual Object SyncRoot {
- get { return _list.SyncRoot; }
- }
-
- public virtual int Add(Object obj) {
- throw new NotSupportedException(Environment.GetResourceString("NotSupported_FixedSizeCollection"));
- }
-
- public virtual void Clear() {
- throw new NotSupportedException(Environment.GetResourceString("NotSupported_FixedSizeCollection"));
- }
-
- public virtual bool Contains(Object obj) {
- return _list.Contains(obj);
- }
-
- public virtual void CopyTo(Array array, int index) {
- _list.CopyTo(array, index);
- }
-
- public virtual IEnumerator GetEnumerator() {
- return _list.GetEnumerator();
- }
-
- public virtual int IndexOf(Object value) {
- return _list.IndexOf(value);
- }
-
- public virtual void Insert(int index, Object obj) {
- throw new NotSupportedException(Environment.GetResourceString("NotSupported_FixedSizeCollection"));
- }
-
- public virtual void Remove(Object value) {
- throw new NotSupportedException(Environment.GetResourceString("NotSupported_FixedSizeCollection"));
- }
-
- public virtual void RemoveAt(int index) {
- throw new NotSupportedException(Environment.GetResourceString("NotSupported_FixedSizeCollection"));
- }
- }
-
- [Serializable]
- private class FixedSizeArrayList : ArrayList
- {
- private ArrayList _list;
-
- internal FixedSizeArrayList(ArrayList l) {
- _list = l;
- _version = _list._version;
- }
-
- public override int Count {
- get { return _list.Count; }
- }
-
- public override bool IsReadOnly {
- get { return _list.IsReadOnly; }
- }
-
- public override bool IsFixedSize {
- get { return true; }
- }
-
- public override bool IsSynchronized {
- get { return _list.IsSynchronized; }
- }
-
- public override Object this[int index] {
- get {
- return _list[index];
- }
- set {
- _list[index] = value;
- _version = _list._version;
- }
- }
-
- public override Object SyncRoot {
- get { return _list.SyncRoot; }
- }
-
- public override int Add(Object obj) {
- throw new NotSupportedException(Environment.GetResourceString("NotSupported_FixedSizeCollection"));
- }
-
- public override void AddRange(ICollection c) {
- throw new NotSupportedException(Environment.GetResourceString("NotSupported_FixedSizeCollection"));
- }
-
- [SuppressMessage("Microsoft.Contracts", "CC1055")] // Skip extra error checking to avoid *potential* AppCompat problems.
- public override int BinarySearch(int index, int count, Object value, IComparer comparer) {
- return _list.BinarySearch(index, count, value, comparer);
- }
-
- public override int Capacity {
- get { return _list.Capacity; }
- [SuppressMessage("Microsoft.Contracts", "CC1055")] // Skip extra error checking to avoid *potential* AppCompat problems.
- set { throw new NotSupportedException(Environment.GetResourceString("NotSupported_FixedSizeCollection")); }
- }
-
- public override void Clear() {
- throw new NotSupportedException(Environment.GetResourceString("NotSupported_FixedSizeCollection"));
- }
-
- public override Object Clone() {
- FixedSizeArrayList arrayList = new FixedSizeArrayList(_list);
- arrayList._list = (ArrayList)_list.Clone();
- return arrayList;
- }
-
- public override bool Contains(Object obj) {
- return _list.Contains(obj);
- }
-
- public override void CopyTo(Array array, int index) {
- _list.CopyTo(array, index);
- }
-
- [SuppressMessage("Microsoft.Contracts", "CC1055")] // Skip extra error checking to avoid *potential* AppCompat problems.
- public override void CopyTo(int index, Array array, int arrayIndex, int count) {
- _list.CopyTo(index, array, arrayIndex, count);
- }
-
- public override IEnumerator GetEnumerator() {
- return _list.GetEnumerator();
- }
-
- [SuppressMessage("Microsoft.Contracts", "CC1055")] // Skip extra error checking to avoid *potential* AppCompat problems.
- public override IEnumerator GetEnumerator(int index, int count) {
- return _list.GetEnumerator(index, count);
- }
-
- public override int IndexOf(Object value) {
- return _list.IndexOf(value);
- }
-
- [SuppressMessage("Microsoft.Contracts", "CC1055")] // Skip extra error checking to avoid *potential* AppCompat problems.
- public override int IndexOf(Object value, int startIndex) {
- return _list.IndexOf(value, startIndex);
- }
-
- [SuppressMessage("Microsoft.Contracts", "CC1055")] // Skip extra error checking to avoid *potential* AppCompat problems.
- public override int IndexOf(Object value, int startIndex, int count) {
- return _list.IndexOf(value, startIndex, count);
- }
-
- public override void Insert(int index, Object obj) {
- throw new NotSupportedException(Environment.GetResourceString("NotSupported_FixedSizeCollection"));
- }
-
- [SuppressMessage("Microsoft.Contracts", "CC1055")] // Skip extra error checking to avoid *potential* AppCompat problems.
- public override void InsertRange(int index, ICollection c) {
- throw new NotSupportedException(Environment.GetResourceString("NotSupported_FixedSizeCollection"));
- }
-
- public override int LastIndexOf(Object value) {
- return _list.LastIndexOf(value);
- }
-
- [SuppressMessage("Microsoft.Contracts", "CC1055")] // Skip extra error checking to avoid *potential* AppCompat problems.
- public override int LastIndexOf(Object value, int startIndex) {
- return _list.LastIndexOf(value, startIndex);
- }
-
- [SuppressMessage("Microsoft.Contracts", "CC1055")] // Skip extra error checking to avoid *potential* AppCompat problems.
- public override int LastIndexOf(Object value, int startIndex, int count) {
- return _list.LastIndexOf(value, startIndex, count);
- }
-
- public override void Remove(Object value) {
- throw new NotSupportedException(Environment.GetResourceString("NotSupported_FixedSizeCollection"));
- }
-
- public override void RemoveAt(int index) {
- throw new NotSupportedException(Environment.GetResourceString("NotSupported_FixedSizeCollection"));
- }
-
- [SuppressMessage("Microsoft.Contracts", "CC1055")] // Skip extra error checking to avoid *potential* AppCompat problems.
- public override void RemoveRange(int index, int count) {
- throw new NotSupportedException(Environment.GetResourceString("NotSupported_FixedSizeCollection"));
- }
-
- [SuppressMessage("Microsoft.Contracts", "CC1055")] // Skip extra error checking to avoid *potential* AppCompat problems.
- public override void SetRange(int index, ICollection c) {
- _list.SetRange(index, c);
- _version = _list._version;
- }
-
- public override ArrayList GetRange(int index, int count) {
- if (index < 0 || count < 0)
- 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();
-
- return new Range(this,index, count);
- }
-
- [SuppressMessage("Microsoft.Contracts", "CC1055")] // Skip extra error checking to avoid *potential* AppCompat problems.
- public override void Reverse(int index, int count) {
- _list.Reverse(index, count);
- _version = _list._version;
- }
-
- [SuppressMessage("Microsoft.Contracts", "CC1055")] // Skip extra error checking to avoid *potential* AppCompat problems.
- public override void Sort(int index, int count, IComparer comparer) {
- _list.Sort(index, count, comparer);
- _version = _list._version;
- }
-
- public override Object[] ToArray() {
- return _list.ToArray();
- }
-
- [SuppressMessage("Microsoft.Contracts", "CC1055")] // Skip extra error checking to avoid *potential* AppCompat problems.
- public override Array ToArray(Type type) {
- return _list.ToArray(type);
- }
-
- public override void TrimToSize() {
- throw new NotSupportedException(Environment.GetResourceString("NotSupported_FixedSizeCollection"));
- }
- }
-
[Serializable]
private class ReadOnlyList : IList
{
@@ -1908,626 +459,6 @@ namespace System.Collections {
}
[Serializable]
- private class ReadOnlyArrayList : ArrayList
- {
- private ArrayList _list;
-
- internal ReadOnlyArrayList(ArrayList l) {
- _list = l;
- }
-
- public override int Count {
- get { return _list.Count; }
- }
-
- public override bool IsReadOnly {
- get { return true; }
- }
-
- public override bool IsFixedSize {
- get { return true; }
- }
-
- public override bool IsSynchronized {
- get { return _list.IsSynchronized; }
- }
-
- public override Object this[int index] {
- get {
- return _list[index];
- }
- set {
- throw new NotSupportedException(Environment.GetResourceString("NotSupported_ReadOnlyCollection"));
- }
- }
-
- public override Object SyncRoot {
- get { return _list.SyncRoot; }
- }
-
- public override int Add(Object obj) {
- throw new NotSupportedException(Environment.GetResourceString("NotSupported_ReadOnlyCollection"));
- }
-
- public override void AddRange(ICollection c) {
- throw new NotSupportedException(Environment.GetResourceString("NotSupported_ReadOnlyCollection"));
- }
-
- [SuppressMessage("Microsoft.Contracts", "CC1055")] // Skip extra error checking to avoid *potential* AppCompat problems.
- public override int BinarySearch(int index, int count, Object value, IComparer comparer) {
- return _list.BinarySearch(index, count, value, comparer);
- }
-
-
- public override int Capacity {
- get { return _list.Capacity; }
- [SuppressMessage("Microsoft.Contracts", "CC1055")] // Skip extra error checking to avoid *potential* AppCompat problems.
- set { throw new NotSupportedException(Environment.GetResourceString("NotSupported_ReadOnlyCollection")); }
- }
-
- public override void Clear() {
- throw new NotSupportedException(Environment.GetResourceString("NotSupported_ReadOnlyCollection"));
- }
-
- public override Object Clone() {
- ReadOnlyArrayList arrayList = new ReadOnlyArrayList(_list);
- arrayList._list = (ArrayList)_list.Clone();
- return arrayList;
- }
-
- public override bool Contains(Object obj) {
- return _list.Contains(obj);
- }
-
- public override void CopyTo(Array array, int index) {
- _list.CopyTo(array, index);
- }
-
- [SuppressMessage("Microsoft.Contracts", "CC1055")] // Skip extra error checking to avoid *potential* AppCompat problems.
- public override void CopyTo(int index, Array array, int arrayIndex, int count) {
- _list.CopyTo(index, array, arrayIndex, count);
- }
-
- public override IEnumerator GetEnumerator() {
- return _list.GetEnumerator();
- }
-
- [SuppressMessage("Microsoft.Contracts", "CC1055")] // Skip extra error checking to avoid *potential* AppCompat problems.
- public override IEnumerator GetEnumerator(int index, int count) {
- return _list.GetEnumerator(index, count);
- }
-
- public override int IndexOf(Object value) {
- return _list.IndexOf(value);
- }
-
- [SuppressMessage("Microsoft.Contracts", "CC1055")] // Skip extra error checking to avoid *potential* AppCompat problems.
- public override int IndexOf(Object value, int startIndex) {
- return _list.IndexOf(value, startIndex);
- }
-
- [SuppressMessage("Microsoft.Contracts", "CC1055")] // Skip extra error checking to avoid *potential* AppCompat problems.
- public override int IndexOf(Object value, int startIndex, int count) {
- return _list.IndexOf(value, startIndex, count);
- }
-
- public override void Insert(int index, Object obj) {
- throw new NotSupportedException(Environment.GetResourceString("NotSupported_ReadOnlyCollection"));
- }
-
- [SuppressMessage("Microsoft.Contracts", "CC1055")] // Skip extra error checking to avoid *potential* AppCompat problems.
- public override void InsertRange(int index, ICollection c) {
- throw new NotSupportedException(Environment.GetResourceString("NotSupported_ReadOnlyCollection"));
- }
-
- public override int LastIndexOf(Object value) {
- return _list.LastIndexOf(value);
- }
-
- [SuppressMessage("Microsoft.Contracts", "CC1055")] // Skip extra error checking to avoid *potential* AppCompat problems.
- public override int LastIndexOf(Object value, int startIndex) {
- return _list.LastIndexOf(value, startIndex);
- }
-
- [SuppressMessage("Microsoft.Contracts", "CC1055")] // Skip extra error checking to avoid *potential* AppCompat problems.
- public override int LastIndexOf(Object value, int startIndex, int count) {
- return _list.LastIndexOf(value, startIndex, count);
- }
-
- public override void Remove(Object value) {
- throw new NotSupportedException(Environment.GetResourceString("NotSupported_ReadOnlyCollection"));
- }
-
- public override void RemoveAt(int index) {
- throw new NotSupportedException(Environment.GetResourceString("NotSupported_ReadOnlyCollection"));
- }
-
- [SuppressMessage("Microsoft.Contracts", "CC1055")] // Skip extra error checking to avoid *potential* AppCompat problems.
- public override void RemoveRange(int index, int count) {
- throw new NotSupportedException(Environment.GetResourceString("NotSupported_ReadOnlyCollection"));
- }
-
- [SuppressMessage("Microsoft.Contracts", "CC1055")] // Skip extra error checking to avoid *potential* AppCompat problems.
- public override void SetRange(int index, ICollection c) {
- throw new NotSupportedException(Environment.GetResourceString("NotSupported_ReadOnlyCollection"));
- }
-
- public override ArrayList GetRange(int index, int count) {
- if (index < 0 || count < 0)
- 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();
-
- return new Range(this,index, count);
- }
-
- [SuppressMessage("Microsoft.Contracts", "CC1055")] // Skip extra error checking to avoid *potential* AppCompat problems.
- public override void Reverse(int index, int count) {
- throw new NotSupportedException(Environment.GetResourceString("NotSupported_ReadOnlyCollection"));
- }
-
- [SuppressMessage("Microsoft.Contracts", "CC1055")] // Skip extra error checking to avoid *potential* AppCompat problems.
- public override void Sort(int index, int count, IComparer comparer) {
- throw new NotSupportedException(Environment.GetResourceString("NotSupported_ReadOnlyCollection"));
- }
-
- public override Object[] ToArray() {
- return _list.ToArray();
- }
-
- [SuppressMessage("Microsoft.Contracts", "CC1055")] // Skip extra error checking to avoid *potential* AppCompat problems.
- public override Array ToArray(Type type) {
- return _list.ToArray(type);
- }
-
- public override void TrimToSize() {
- throw new NotSupportedException(Environment.GetResourceString("NotSupported_ReadOnlyCollection"));
- }
- }
-
-
- // Implements an enumerator for a ArrayList. The enumerator uses the
- // internal version number of the list to ensure that no modifications are
- // made to the list while an enumeration is in progress.
- [Serializable]
- private sealed class ArrayListEnumerator : IEnumerator, ICloneable
- {
- private ArrayList list;
- private int index;
- private int endIndex; // Where to stop.
- private int version;
- private Object currentElement;
- private int startIndex; // Save this for Reset.
-
- internal ArrayListEnumerator(ArrayList list, int index, int count) {
- this.list = list;
- startIndex = index;
- this.index = index - 1;
- endIndex = this.index + count; // last valid index
- version = list._version;
- currentElement = null;
- }
-
- public Object Clone() {
- return MemberwiseClone();
- }
-
- public bool MoveNext() {
- if (version != list._version) throw new InvalidOperationException(Environment.GetResourceString(ResId.InvalidOperation_EnumFailedVersion));
- if (index < endIndex) {
- currentElement = list[++index];
- return true;
- }
- else {
- index = endIndex + 1;
- }
-
- return false;
- }
-
- public Object Current {
- get {
- if (index < startIndex)
- throw new InvalidOperationException(Environment.GetResourceString(ResId.InvalidOperation_EnumNotStarted));
- else if (index > endIndex) {
- throw new InvalidOperationException(Environment.GetResourceString(ResId.InvalidOperation_EnumEnded));
- }
- return currentElement;
- }
- }
-
- public void Reset() {
- if (version != list._version) throw new InvalidOperationException(Environment.GetResourceString(ResId.InvalidOperation_EnumFailedVersion));
- index = startIndex - 1;
- }
- }
-
- // Implementation of a generic list subrange. An instance of this class
- // is returned by the default implementation of List.GetRange.
- [Serializable]
- private class Range: ArrayList
- {
- private ArrayList _baseList;
- private int _baseIndex;
- [ContractPublicPropertyName("Count")]
- private int _baseSize;
- private int _baseVersion;
-
- internal Range(ArrayList list, int index, int count) : base(false) {
- _baseList = list;
- _baseIndex = index;
- _baseSize = count;
- _baseVersion = list._version;
- // we also need to update _version field to make Range of Range work
- _version = list._version;
- }
-
- private void InternalUpdateRange()
- {
- if (_baseVersion != _baseList._version)
- throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_UnderlyingArrayListChanged"));
- }
-
- private void InternalUpdateVersion() {
- _baseVersion++;
- _version++;
- }
-
- public override int Add(Object value) {
- InternalUpdateRange();
- _baseList.Insert(_baseIndex + _baseSize, value);
- InternalUpdateVersion();
- return _baseSize++;
- }
-
- public override void AddRange(ICollection c) {
- if( c == null ) {
- throw new ArgumentNullException(nameof(c));
- }
- Contract.EndContractBlock();
-
- InternalUpdateRange();
- int count = c.Count;
- if( count > 0) {
- _baseList.InsertRange(_baseIndex + _baseSize, c);
- InternalUpdateVersion();
- _baseSize += count;
- }
- }
-
- // 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 ? nameof(index) : nameof(count)), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
- if (_baseSize - index < count)
- throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen"));
- Contract.EndContractBlock();
- InternalUpdateRange();
-
- int i = _baseList.BinarySearch(_baseIndex + index, count, value, comparer);
- if (i >= 0) return i - _baseIndex;
- return i + _baseIndex;
- }
-
- public override int Capacity {
- get {
- return _baseList.Capacity;
- }
-
- set {
- if (value < Count) throw new ArgumentOutOfRangeException(nameof(value), Environment.GetResourceString("ArgumentOutOfRange_SmallCapacity"));
- Contract.EndContractBlock();
- }
- }
-
-
- public override void Clear() {
- InternalUpdateRange();
- if (_baseSize != 0)
- {
- _baseList.RemoveRange(_baseIndex, _baseSize);
- InternalUpdateVersion();
- _baseSize = 0;
- }
- }
-
- public override Object Clone() {
- InternalUpdateRange();
- Range arrayList = new Range(_baseList,_baseIndex,_baseSize);
- arrayList._baseList = (ArrayList)_baseList.Clone();
- return arrayList;
- }
-
- public override bool Contains(Object item) {
- InternalUpdateRange();
- if (item==null) {
- for(int i=0; i<_baseSize; i++)
- if (_baseList[_baseIndex + i]==null)
- return true;
- return false;
- }
- else {
- for(int i=0; i<_baseSize; i++)
- if (_baseList[_baseIndex + i] != null && _baseList[_baseIndex + i].Equals(item))
- return true;
- return false;
- }
- }
-
- public override void CopyTo(Array array, int index) {
- if (array==null)
- throw new ArgumentNullException(nameof(array));
- if (array.Rank != 1)
- throw new ArgumentException(Environment.GetResourceString("Arg_RankMultiDimNotSupported"));
- if (index < 0)
- throw new ArgumentOutOfRangeException(nameof(index), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
- if (array.Length - index < _baseSize)
- throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen"));
- Contract.EndContractBlock();
-
- InternalUpdateRange();
- _baseList.CopyTo(_baseIndex, array, index, _baseSize);
- }
-
- public override void CopyTo(int index, Array array, int arrayIndex, int count) {
- if (array==null)
- 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 ? nameof(index) : nameof(count)), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
- if (array.Length - arrayIndex < count)
- throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen"));
- if (_baseSize - index < count)
- throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen"));
- Contract.EndContractBlock();
-
- InternalUpdateRange();
- _baseList.CopyTo(_baseIndex + index, array, arrayIndex, count);
- }
-
- public override int Count {
- get {
- InternalUpdateRange();
- return _baseSize;
- }
- }
-
- public override bool IsReadOnly {
- get { return _baseList.IsReadOnly; }
- }
-
- public override bool IsFixedSize {
- get { return _baseList.IsFixedSize; }
- }
-
- public override bool IsSynchronized {
- get { return _baseList.IsSynchronized; }
- }
-
- public override IEnumerator GetEnumerator() {
- return GetEnumerator(0,_baseSize);
- }
-
- public override IEnumerator GetEnumerator(int index, int count) {
- if (index < 0 || count < 0)
- 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();
-
- InternalUpdateRange();
- return _baseList.GetEnumerator(_baseIndex + index, count);
- }
-
- public override ArrayList GetRange(int index, int count) {
- if (index < 0 || count < 0)
- 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();
-
- InternalUpdateRange();
- return new Range(this, index, count);
- }
-
- public override Object SyncRoot {
- get {
- return _baseList.SyncRoot;
- }
- }
-
-
- public override int IndexOf(Object value) {
- InternalUpdateRange();
- int i = _baseList.IndexOf(value, _baseIndex, _baseSize);
- if (i >= 0) return i - _baseIndex;
- return -1;
- }
-
- public override int IndexOf(Object value, int startIndex) {
- if (startIndex < 0)
- throw new ArgumentOutOfRangeException(nameof(startIndex), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
- if (startIndex > _baseSize)
- throw new ArgumentOutOfRangeException(nameof(startIndex), Environment.GetResourceString("ArgumentOutOfRange_Index"));
- Contract.EndContractBlock();
-
- InternalUpdateRange();
- int i = _baseList.IndexOf(value, _baseIndex + startIndex, _baseSize - startIndex);
- if (i >= 0) return i - _baseIndex;
- return -1;
- }
-
- public override int IndexOf(Object value, int startIndex, int count) {
- if (startIndex < 0 || startIndex > _baseSize)
- throw new ArgumentOutOfRangeException(nameof(startIndex), Environment.GetResourceString("ArgumentOutOfRange_Index"));
-
- if (count < 0 || (startIndex > _baseSize - count))
- throw new ArgumentOutOfRangeException(nameof(count), Environment.GetResourceString("ArgumentOutOfRange_Count"));
- Contract.EndContractBlock();
-
- InternalUpdateRange();
- int i = _baseList.IndexOf(value, _baseIndex + startIndex, count);
- if (i >= 0) return i - _baseIndex;
- return -1;
- }
-
- public override void Insert(int index, Object value) {
- if (index < 0 || index > _baseSize) throw new ArgumentOutOfRangeException(nameof(index), Environment.GetResourceString("ArgumentOutOfRange_Index"));
- Contract.EndContractBlock();
-
- InternalUpdateRange();
- _baseList.Insert(_baseIndex + index, value);
- InternalUpdateVersion();
- _baseSize++;
- }
-
- public override void InsertRange(int index, ICollection c) {
- if (index < 0 || index > _baseSize) throw new ArgumentOutOfRangeException(nameof(index), Environment.GetResourceString("ArgumentOutOfRange_Index"));
- if( c == null) {
- throw new ArgumentNullException(nameof(c));
- }
- Contract.EndContractBlock();
-
- InternalUpdateRange();
- int count = c.Count;
- if( count > 0) {
- _baseList.InsertRange(_baseIndex + index, c);
- _baseSize += count;
- InternalUpdateVersion();
- }
- }
-
- public override int LastIndexOf(Object value) {
- InternalUpdateRange();
- int i = _baseList.LastIndexOf(value, _baseIndex + _baseSize - 1, _baseSize);
- if (i >= 0) return i - _baseIndex;
- return -1;
- }
-
- [SuppressMessage("Microsoft.Contracts", "CC1055")] // Skip extra error checking to avoid *potential* AppCompat problems.
- public override int LastIndexOf(Object value, int startIndex) {
- return LastIndexOf(value, startIndex, startIndex + 1);
- }
-
- [SuppressMessage("Microsoft.Contracts", "CC1055")] // Skip extra error checking to avoid *potential* AppCompat problems.
- public override int LastIndexOf(Object value, int startIndex, int count) {
- InternalUpdateRange();
- if (_baseSize == 0)
- return -1;
-
- if (startIndex >= _baseSize)
- throw new ArgumentOutOfRangeException(nameof(startIndex), Environment.GetResourceString("ArgumentOutOfRange_Index"));
- if (startIndex < 0)
- throw new ArgumentOutOfRangeException(nameof(startIndex), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
-
- int i = _baseList.LastIndexOf(value, _baseIndex + startIndex, count);
- if (i >= 0) return i - _baseIndex;
- return -1;
- }
-
- // Don't need to override Remove
-
- public override void RemoveAt(int index) {
- if (index < 0 || index >= _baseSize) throw new ArgumentOutOfRangeException(nameof(index), Environment.GetResourceString("ArgumentOutOfRange_Index"));
- Contract.EndContractBlock();
-
- InternalUpdateRange();
- _baseList.RemoveAt(_baseIndex + index);
- InternalUpdateVersion();
- _baseSize--;
- }
-
- public override void RemoveRange(int index, int count) {
- if (index < 0 || count < 0)
- 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();
-
- InternalUpdateRange();
- // No need to call _bastList.RemoveRange if count is 0.
- // In addition, _baseList won't change the vresion number if count is 0.
- if( count > 0) {
- _baseList.RemoveRange(_baseIndex + index, count);
- InternalUpdateVersion();
- _baseSize -= count;
- }
- }
-
- public override void Reverse(int index, int count) {
- if (index < 0 || count < 0)
- 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();
-
- InternalUpdateRange();
- _baseList.Reverse(_baseIndex + index, count);
- InternalUpdateVersion();
- }
-
- [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(nameof(index), Environment.GetResourceString("ArgumentOutOfRange_Index"));
- _baseList.SetRange(_baseIndex + index, c);
- if( c.Count > 0) {
- InternalUpdateVersion();
- }
- }
-
- public override void Sort(int index, int count, IComparer comparer) {
- if (index < 0 || count < 0)
- 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();
-
- InternalUpdateRange();
- _baseList.Sort(_baseIndex + index, count, comparer);
- InternalUpdateVersion();
- }
-
- public override Object this[int index] {
- get {
- InternalUpdateRange();
- 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(nameof(index), Environment.GetResourceString("ArgumentOutOfRange_Index"));
- _baseList[_baseIndex + index] = value;
- InternalUpdateVersion();
- }
- }
-
- public override Object[] ToArray() {
- InternalUpdateRange();
- Object[] array = new Object[_baseSize];
- Array.Copy(_baseList._items, _baseIndex, array, 0, _baseSize);
- return array;
- }
-
- public override Array ToArray(Type type) {
- if (type==null)
- throw new ArgumentNullException(nameof(type));
- Contract.EndContractBlock();
-
- InternalUpdateRange();
- Array array = Array.UnsafeCreateInstance(type, _baseSize);
- _baseList.CopyTo(_baseIndex, array, 0, _baseSize);
- return array;
- }
-
- public override void TrimToSize() {
- throw new NotSupportedException(Environment.GetResourceString("NotSupported_RangeCollection"));
- }
- }
-
- [Serializable]
private sealed class ArrayListEnumeratorSimple : IEnumerator, ICloneable {
private ArrayList list;
private int index;
@@ -2607,20 +538,6 @@ namespace System.Collections {
internal class ArrayListDebugView {
private ArrayList arrayList;
-
- public ArrayListDebugView( ArrayList arrayList) {
- if( arrayList == null)
- throw new ArgumentNullException(nameof(arrayList));
-
- this.arrayList = arrayList;
- }
-
- [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)]
- public Object[] Items {
- get {
- return arrayList.ToArray();
- }
- }
}
}
}
diff --git a/src/mscorlib/src/System/Collections/CollectionBase.cs b/src/mscorlib/src/System/Collections/CollectionBase.cs
index ae0c0d302d..a3dd88a7b3 100644
--- a/src/mscorlib/src/System/Collections/CollectionBase.cs
+++ b/src/mscorlib/src/System/Collections/CollectionBase.cs
@@ -12,20 +12,14 @@ namespace System.Collections {
// Useful base class for typed read/write collections where items derive from object
[Serializable]
-[System.Runtime.InteropServices.ComVisible(true)]
public abstract class CollectionBase : IList {
- ArrayList list;
+ private ArrayList list;
protected CollectionBase() {
list = new ArrayList();
}
-
- protected CollectionBase(int capacity) {
- list = new ArrayList(capacity);
- }
-
- protected ArrayList InnerList {
+ internal ArrayList InnerList {
get {
if (list == null)
list = new ArrayList();
@@ -37,16 +31,6 @@ namespace System.Collections {
get { return (IList)this; }
}
- [System.Runtime.InteropServices.ComVisible(false)]
- public int Capacity {
- get {
- return InnerList.Capacity;
- }
- set {
- InnerList.Capacity = value;
- }
- }
-
public int Count {
get {
diff --git a/src/mscorlib/src/System/Collections/Comparer.cs b/src/mscorlib/src/System/Collections/Comparer.cs
index 0e3c78b529..928b0f9f9a 100644
--- a/src/mscorlib/src/System/Collections/Comparer.cs
+++ b/src/mscorlib/src/System/Collections/Comparer.cs
@@ -17,12 +17,10 @@ namespace System.Collections {
using System;
using System.Globalization;
using System.Runtime.Serialization;
- using System.Security.Permissions;
using System.Diagnostics.Contracts;
[Serializable]
- [System.Runtime.InteropServices.ComVisible(true)]
- public sealed class Comparer : IComparer , ISerializable
+ internal sealed class Comparer : IComparer , ISerializable
{
private CompareInfo m_compareInfo;
public static readonly Comparer Default = new Comparer(CultureInfo.CurrentCulture);
diff --git a/src/mscorlib/src/System/Collections/Concurrent/ConcurrentDictionary.cs b/src/mscorlib/src/System/Collections/Concurrent/ConcurrentDictionary.cs
index c1a6f7564c..8b9014a103 100644
--- a/src/mscorlib/src/System/Collections/Concurrent/ConcurrentDictionary.cs
+++ b/src/mscorlib/src/System/Collections/Concurrent/ConcurrentDictionary.cs
@@ -24,7 +24,6 @@ using System.Runtime.Serialization;
using System.Text;
using System.Threading;
using System.Security;
-using System.Security.Permissions;
namespace System.Collections.Concurrent
{
@@ -37,10 +36,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>
- [ComVisible(false)]
[DebuggerTypeProxy(typeof(Mscorlib_DictionaryDebugView<,>))]
[DebuggerDisplay("Count = {Count}")]
- public class ConcurrentDictionary<TKey, TValue> : IDictionary<TKey, TValue>, IDictionary, IReadOnlyDictionary<TKey, TValue>
+ internal class ConcurrentDictionary<TKey, TValue> : IDictionary<TKey, TValue>, IDictionary, IReadOnlyDictionary<TKey, TValue>
{
/// <summary>
/// Tables that hold the internal state of the ConcurrentDictionary
@@ -139,149 +137,6 @@ namespace System.Collections.Concurrent
/// </summary>
public ConcurrentDictionary() : this(DefaultConcurrencyLevel, DEFAULT_CAPACITY, true, EqualityComparer<TKey>.Default) { }
- /// <summary>
- /// Initializes a new instance of the <see
- /// cref="ConcurrentDictionary{TKey,TValue}"/>
- /// class that is empty, has the specified concurrency level and capacity, and uses the default
- /// comparer for the key type.
- /// </summary>
- /// <param name="concurrencyLevel">The estimated number of threads that will update the
- /// <see cref="ConcurrentDictionary{TKey,TValue}"/> concurrently.</param>
- /// <param name="capacity">The initial number of elements that the <see
- /// cref="ConcurrentDictionary{TKey,TValue}"/>
- /// can contain.</param>
- /// <exception cref="T:System.ArgumentOutOfRangeException"><paramref name="concurrencyLevel"/> is
- /// less than 1.</exception>
- /// <exception cref="T:System.ArgumentOutOfRangeException"> <paramref name="capacity"/> is less than
- /// 0.</exception>
- public ConcurrentDictionary(int concurrencyLevel, int capacity) : this(concurrencyLevel, capacity, false, EqualityComparer<TKey>.Default) { }
-
- /// <summary>
- /// Initializes a new instance of the <see cref="ConcurrentDictionary{TKey,TValue}"/>
- /// class that contains elements copied from the specified <see
- /// cref="T:System.Collections.IEnumerable{KeyValuePair{TKey,TValue}}"/>, has the default concurrency
- /// level, has the default initial capacity, and uses the default comparer for the key type.
- /// </summary>
- /// <param name="collection">The <see
- /// cref="T:System.Collections.IEnumerable{KeyValuePair{TKey,TValue}}"/> whose elements are copied to
- /// the new
- /// <see cref="ConcurrentDictionary{TKey,TValue}"/>.</param>
- /// <exception cref="T:System.ArgumentNullException"><paramref name="collection"/> is a null reference
- /// (Nothing in Visual Basic).</exception>
- /// <exception cref="T:System.ArgumentException"><paramref name="collection"/> contains one or more
- /// duplicate keys.</exception>
- public ConcurrentDictionary(IEnumerable<KeyValuePair<TKey, TValue>> collection) : this(collection, EqualityComparer<TKey>.Default) { }
-
- /// <summary>
- /// Initializes a new instance of the <see cref="ConcurrentDictionary{TKey,TValue}"/>
- /// class that is empty, has the specified concurrency level and capacity, and uses the specified
- /// <see cref="T:System.Collections.Generic.IEqualityComparer{TKey}"/>.
- /// </summary>
- /// <param name="comparer">The <see cref="T:System.Collections.Generic.IEqualityComparer{TKey}"/>
- /// implementation to use when comparing keys.</param>
- /// <exception cref="T:System.ArgumentNullException"><paramref name="comparer"/> is a null reference
- /// (Nothing in Visual Basic).</exception>
- public ConcurrentDictionary(IEqualityComparer<TKey> comparer) : this(DefaultConcurrencyLevel, DEFAULT_CAPACITY, true, comparer) { }
-
- /// <summary>
- /// Initializes a new instance of the <see cref="ConcurrentDictionary{TKey,TValue}"/>
- /// class that contains elements copied from the specified <see
- /// cref="T:System.Collections.IEnumerable"/>, has the default concurrency level, has the default
- /// initial capacity, and uses the specified
- /// <see cref="T:System.Collections.Generic.IEqualityComparer{TKey}"/>.
- /// </summary>
- /// <param name="collection">The <see
- /// cref="T:System.Collections.IEnumerable{KeyValuePair{TKey,TValue}}"/> whose elements are copied to
- /// the new
- /// <see cref="ConcurrentDictionary{TKey,TValue}"/>.</param>
- /// <param name="comparer">The <see cref="T:System.Collections.Generic.IEqualityComparer{TKey}"/>
- /// implementation to use when comparing keys.</param>
- /// <exception cref="T:System.ArgumentNullException"><paramref name="collection"/> is a null reference
- /// (Nothing in Visual Basic). -or-
- /// <paramref name="comparer"/> is a null reference (Nothing in Visual Basic).
- /// </exception>
- public ConcurrentDictionary(IEnumerable<KeyValuePair<TKey, TValue>> collection, IEqualityComparer<TKey> comparer)
- : this(comparer)
- {
- if (collection == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.collection);
-
- InitializeFromCollection(collection);
- }
-
- /// <summary>
- /// Initializes a new instance of the <see cref="ConcurrentDictionary{TKey,TValue}"/>
- /// class that contains elements copied from the specified <see cref="T:System.Collections.IEnumerable"/>,
- /// has the specified concurrency level, has the specified initial capacity, and uses the specified
- /// <see cref="T:System.Collections.Generic.IEqualityComparer{TKey}"/>.
- /// </summary>
- /// <param name="concurrencyLevel">The estimated number of threads that will update the
- /// <see cref="ConcurrentDictionary{TKey,TValue}"/> concurrently.</param>
- /// <param name="collection">The <see cref="T:System.Collections.IEnumerable{KeyValuePair{TKey,TValue}}"/> whose elements are copied to the new
- /// <see cref="ConcurrentDictionary{TKey,TValue}"/>.</param>
- /// <param name="comparer">The <see cref="T:System.Collections.Generic.IEqualityComparer{TKey}"/> implementation to use
- /// when comparing keys.</param>
- /// <exception cref="T:System.ArgumentNullException">
- /// <paramref name="collection"/> is a null reference (Nothing in Visual Basic).
- /// -or-
- /// <paramref name="comparer"/> is a null reference (Nothing in Visual Basic).
- /// </exception>
- /// <exception cref="T:System.ArgumentOutOfRangeException">
- /// <paramref name="concurrencyLevel"/> is less than 1.
- /// </exception>
- /// <exception cref="T:System.ArgumentException"><paramref name="collection"/> contains one or more duplicate keys.</exception>
- public ConcurrentDictionary(
- int concurrencyLevel, IEnumerable<KeyValuePair<TKey, TValue>> collection, IEqualityComparer<TKey> comparer)
- : this(concurrencyLevel, DEFAULT_CAPACITY, false, comparer)
- {
- if (collection == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.collection);
- if (comparer == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.comparer);
-
- InitializeFromCollection(collection);
- }
-
- private void InitializeFromCollection(IEnumerable<KeyValuePair<TKey, TValue>> collection)
- {
- TValue dummy;
- foreach (KeyValuePair<TKey, TValue> pair in collection)
- {
- if (pair.Key == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key);
-
- if (!TryAddInternal(pair.Key, pair.Value, false, false, out dummy))
- {
- ThrowHelper.ThrowArgumentException(ExceptionResource.ConcurrentDictionary_SourceContainsDuplicateKeys);
- }
- }
-
- if (m_budget == 0)
- {
- m_budget = m_tables.m_buckets.Length / m_tables.m_locks.Length;
- }
-
- }
-
- /// <summary>
- /// Initializes a new instance of the <see cref="ConcurrentDictionary{TKey,TValue}"/>
- /// class that is empty, has the specified concurrency level, has the specified initial capacity, and
- /// uses the specified <see cref="T:System.Collections.Generic.IEqualityComparer{TKey}"/>.
- /// </summary>
- /// <param name="concurrencyLevel">The estimated number of threads that will update the
- /// <see cref="ConcurrentDictionary{TKey,TValue}"/> concurrently.</param>
- /// <param name="capacity">The initial number of elements that the <see
- /// cref="ConcurrentDictionary{TKey,TValue}"/>
- /// can contain.</param>
- /// <param name="comparer">The <see cref="T:System.Collections.Generic.IEqualityComparer{TKey}"/>
- /// implementation to use when comparing keys.</param>
- /// <exception cref="T:System.ArgumentOutOfRangeException">
- /// <paramref name="concurrencyLevel"/> is less than 1. -or-
- /// <paramref name="capacity"/> is less than 0.
- /// </exception>
- /// <exception cref="T:System.ArgumentNullException"><paramref name="comparer"/> is a null reference
- /// (Nothing in Visual Basic).</exception>
- public ConcurrentDictionary(int concurrencyLevel, int capacity, IEqualityComparer<TKey> comparer)
- : this(concurrencyLevel, capacity, false, comparer)
- {
- }
-
internal ConcurrentDictionary(int concurrencyLevel, int capacity, bool growLockArray, IEqualityComparer<TKey> comparer)
{
if (concurrencyLevel < 1)
@@ -488,91 +343,6 @@ namespace System.Collections.Concurrent
}
/// <summary>
- /// Compares the existing value for the specified key with a specified value, and if they're equal,
- /// updates the key with a third value.
- /// </summary>
- /// <param name="key">The key whose value is compared with <paramref name="comparisonValue"/> and
- /// possibly replaced.</param>
- /// <param name="newValue">The value that replaces the value of the element with <paramref
- /// name="key"/> if the comparison results in equality.</param>
- /// <param name="comparisonValue">The value that is compared to the value of the element with
- /// <paramref name="key"/>.</param>
- /// <returns>true if the value with <paramref name="key"/> was equal to <paramref
- /// name="comparisonValue"/> and replaced with <paramref name="newValue"/>; otherwise,
- /// false.</returns>
- /// <exception cref="T:System.ArgumentNullException"><paramref name="key"/> is a null
- /// reference.</exception>
- [SuppressMessage("Microsoft.Concurrency", "CA8001", Justification = "Reviewed for thread safety")]
- public bool TryUpdate(TKey key, TValue newValue, TValue comparisonValue)
- {
- if (key == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key);
-
- IEqualityComparer<TValue> valueComparer = EqualityComparer<TValue>.Default;
-
- while (true)
- {
- int bucketNo;
- int lockNo;
- int hashcode;
-
- Tables tables = m_tables;
- IEqualityComparer<TKey> comparer = tables.m_comparer;
-
- hashcode = comparer.GetHashCode(key);
- GetBucketAndLockNo(hashcode, out bucketNo, out lockNo, tables.m_buckets.Length, tables.m_locks.Length);
-
- lock (tables.m_locks[lockNo])
- {
- // If the table just got resized, we may not be holding the right lock, and must retry.
- // This should be a rare occurence.
- if (tables != m_tables)
- {
- continue;
- }
-
- // Try to find this key in the bucket
- Node prev = null;
- for (Node node = tables.m_buckets[bucketNo]; node != null; node = node.m_next)
- {
- Assert((prev == null && node == tables.m_buckets[bucketNo]) || prev.m_next == node);
- if (comparer.Equals(node.m_key, key))
- {
- if (valueComparer.Equals(node.m_value, comparisonValue))
- {
- if (s_isValueWriteAtomic)
- {
- node.m_value = newValue;
- }
- else
- {
- Node newNode = new Node(node.m_key, newValue, hashcode, node.m_next);
-
- if (prev == null)
- {
- tables.m_buckets[bucketNo] = newNode;
- }
- else
- {
- prev.m_next = newNode;
- }
- }
-
- return true;
- }
-
- return false;
- }
-
- prev = node;
- }
-
- //didn't find the key
- return false;
- }
- }
- }
-
- /// <summary>
/// Removes all keys and values from the <see cref="ConcurrentDictionary{TKey,TValue}"/>.
/// </summary>
public void Clear()
@@ -947,149 +717,6 @@ namespace System.Collections.Concurrent
}
}
- /// <summary>
- /// Adds a key/value pair to the <see cref="ConcurrentDictionary{TKey,TValue}"/>
- /// if the key does not already exist.
- /// </summary>
- /// <param name="key">The key of the element to add.</param>
- /// <param name="valueFactory">The function used to generate a value for the key</param>
- /// <exception cref="T:System.ArgumentNullException"><paramref name="key"/> is a null reference
- /// (Nothing in Visual Basic).</exception>
- /// <exception cref="T:System.ArgumentNullException"><paramref name="valueFactory"/> is a null reference
- /// (Nothing in Visual Basic).</exception>
- /// <exception cref="T:System.OverflowException">The dictionary contains too many
- /// elements.</exception>
- /// <returns>The value for the key. This will be either the existing value for the key if the
- /// key is already in the dictionary, or the new value for the key as returned by valueFactory
- /// if the key was not in the dictionary.</returns>
- public TValue GetOrAdd(TKey key, Func<TKey, TValue> valueFactory)
- {
- if (key == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key);
- if (valueFactory == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.valueFactory);
-
- TValue resultingValue;
- if (TryGetValue(key, out resultingValue))
- {
- return resultingValue;
- }
- TryAddInternal(key, valueFactory(key), false, true, out resultingValue);
- return resultingValue;
- }
-
- /// <summary>
- /// Adds a key/value pair to the <see cref="ConcurrentDictionary{TKey,TValue}"/>
- /// if the key does not already exist.
- /// </summary>
- /// <param name="key">The key of the element to add.</param>
- /// <param name="value">the value to be added, if the key does not already exist</param>
- /// <exception cref="T:System.ArgumentNullException"><paramref name="key"/> is a null reference
- /// (Nothing in Visual Basic).</exception>
- /// <exception cref="T:System.OverflowException">The dictionary contains too many
- /// elements.</exception>
- /// <returns>The value for the key. This will be either the existing value for the key if the
- /// 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) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key);
-
- TValue resultingValue;
- TryAddInternal(key, value, false, true, out resultingValue);
- return resultingValue;
- }
-
- /// <summary>
- /// Adds a key/value pair to the <see cref="ConcurrentDictionary{TKey,TValue}"/> if the key does not already
- /// exist, or updates a key/value pair in the <see cref="ConcurrentDictionary{TKey,TValue}"/> if the key
- /// already exists.
- /// </summary>
- /// <param name="key">The key to be added or whose value should be updated</param>
- /// <param name="addValueFactory">The function used to generate a value for an absent key</param>
- /// <param name="updateValueFactory">The function used to generate a new value for an existing key
- /// based on the key's existing value</param>
- /// <exception cref="T:System.ArgumentNullException"><paramref name="key"/> is a null reference
- /// (Nothing in Visual Basic).</exception>
- /// <exception cref="T:System.ArgumentNullException"><paramref name="addValueFactory"/> is a null reference
- /// (Nothing in Visual Basic).</exception>
- /// <exception cref="T:System.ArgumentNullException"><paramref name="updateValueFactory"/> is a null reference
- /// (Nothing in Visual Basic).</exception>
- /// <exception cref="T:System.OverflowException">The dictionary contains too many
- /// elements.</exception>
- /// <returns>The new value for the key. This will be either be the result of addValueFactory (if the key was
- /// 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) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key);
- if (addValueFactory == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.addValueFactory);
- if (updateValueFactory == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.updateValueFactory);
-
- TValue newValue, resultingValue;
- while (true)
- {
- TValue oldValue;
- if (TryGetValue(key, out oldValue))
- //key exists, try to update
- {
- newValue = updateValueFactory(key, oldValue);
- if (TryUpdate(key, newValue, oldValue))
- {
- return newValue;
- }
- }
- else //try add
- {
- newValue = addValueFactory(key);
- if (TryAddInternal(key, newValue, false, true, out resultingValue))
- {
- return resultingValue;
- }
- }
- }
- }
-
- /// <summary>
- /// Adds a key/value pair to the <see cref="ConcurrentDictionary{TKey,TValue}"/> if the key does not already
- /// exist, or updates a key/value pair in the <see cref="ConcurrentDictionary{TKey,TValue}"/> if the key
- /// already exists.
- /// </summary>
- /// <param name="key">The key to be added or whose value should be updated</param>
- /// <param name="addValue">The value to be added for an absent key</param>
- /// <param name="updateValueFactory">The function used to generate a new value for an existing key based on
- /// the key's existing value</param>
- /// <exception cref="T:System.ArgumentNullException"><paramref name="key"/> is a null reference
- /// (Nothing in Visual Basic).</exception>
- /// <exception cref="T:System.ArgumentNullException"><paramref name="updateValueFactory"/> is a null reference
- /// (Nothing in Visual Basic).</exception>
- /// <exception cref="T:System.OverflowException">The dictionary contains too many
- /// elements.</exception>
- /// <returns>The new value for the key. This will be either be the result of addValueFactory (if the key was
- /// 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) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key);
- if (updateValueFactory == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.updateValueFactory);
- TValue newValue, resultingValue;
- while (true)
- {
- TValue oldValue;
- if (TryGetValue(key, out oldValue))
- //key exists, try to update
- {
- newValue = updateValueFactory(key, oldValue);
- if (TryUpdate(key, newValue, oldValue))
- {
- return newValue;
- }
- }
- else //try add
- {
- if (TryAddInternal(key, addValue, false, true, out resultingValue))
- {
- return resultingValue;
- }
- }
- }
- }
-
/// <summary>
diff --git a/src/mscorlib/src/System/Collections/Concurrent/ConcurrentQueue.cs b/src/mscorlib/src/System/Collections/Concurrent/ConcurrentQueue.cs
index 7aa5971690..90ada007dd 100644
--- a/src/mscorlib/src/System/Collections/Concurrent/ConcurrentQueue.cs
+++ b/src/mscorlib/src/System/Collections/Concurrent/ConcurrentQueue.cs
@@ -1,67 +1,100 @@
// 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.
-#pragma warning disable 0420
-
-// =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+
-//
-//
-//
-// A lock-free, concurrent queue primitive, and its associated debugger view type.
-//
-// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
-
-using System;
-using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
-using System.Diagnostics.Contracts;
-using System.Runtime.ConstrainedExecution;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
-using System.Security;
-using System.Security.Permissions;
using System.Threading;
namespace System.Collections.Concurrent
{
-
/// <summary>
/// Represents a thread-safe first-in, first-out collection of objects.
/// </summary>
/// <typeparam name="T">Specifies the type of elements in the queue.</typeparam>
/// <remarks>
- /// All public and protected members of <see cref="ConcurrentQueue{T}"/> are thread-safe and may be used
+ /// All public and protected members of <see cref="ConcurrentQueue{T}"/> are thread-safe and may be used
/// concurrently from multiple threads.
/// </remarks>
- [ComVisible(false)]
[DebuggerDisplay("Count = {Count}")]
[DebuggerTypeProxy(typeof(SystemCollectionsConcurrent_ProducerConsumerCollectionDebugView<>))]
[Serializable]
- public class ConcurrentQueue<T> : IProducerConsumerCollection<T>, IReadOnlyCollection<T>
+ internal class ConcurrentQueue<T> : IProducerConsumerCollection<T>, IReadOnlyCollection<T>
{
- //fields of ConcurrentQueue
- [NonSerialized]
- private volatile Segment m_head;
+ // This implementation provides an unbounded, multi-producer multi-consumer queue
+ // that supports the standard Enqueue/TryDequeue operations, as well as support for
+ // snapshot enumeration (GetEnumerator, ToArray, CopyTo), peeking, and Count/IsEmpty.
+ // It is composed of a linked list of bounded ring buffers, each of which has a head
+ // and a tail index, isolated from each other to minimize false sharing. As long as
+ // the number of elements in the queue remains less than the size of the current
+ // buffer (Segment), no additional allocations are required for enqueued items. When
+ // the number of items exceeds the size of the current segment, the current segment is
+ // "frozen" to prevent further enqueues, and a new segment is linked from it and set
+ // as the new tail segment for subsequent enqueues. As old segments are consumed by
+ // dequeues, the head reference is updated to point to the segment that dequeuers should
+ // try next. To support snapshot enumeration, segments also support the notion of
+ // preserving for observation, whereby they avoid overwriting state as part of dequeues.
+ // Any operation that requires a snapshot results in all current segments being
+ // both frozen for enqueues and preserved for observation: any new enqueues will go
+ // to new segments, and dequeuers will consume from the existing segments but without
+ // overwriting the existing data.
+
+ /// <summary>Initial length of the segments used in the queue.</summary>
+ private const int InitialSegmentLength = 32;
+ /// <summary>
+ /// Maximum length of the segments used in the queue. This is a somewhat arbitrary limit:
+ /// larger means that as long as we don't exceed the size, we avoid allocating more segments,
+ /// but if we do exceed it, then the segment becomes garbage.
+ /// </summary>
+ private const int MaxSegmentLength = 1024 * 1024;
+ /// <summary>
+ /// Lock used to protect cross-segment operations, including any updates to <see cref="_tail"/> or <see cref="_head"/>
+ /// and any operations that need to get a consistent view of them.
+ /// </summary>
[NonSerialized]
- private volatile Segment m_tail;
-
- private T[] m_serializationArray; // Used for custom serialization.
-
- private const int SEGMENT_SIZE = 32;
-
- //number of snapshot takers, GetEnumerator(), ToList() and ToArray() operations take snapshot.
+ private object _crossSegmentLock;
+ /// <summary>The current tail segment.</summary>
[NonSerialized]
- internal volatile int m_numSnapshotTakers = 0;
+ private volatile Segment _tail;
+ /// <summary>The current head segment.</summary>
+ [NonSerialized]
+ private volatile Segment _head;
+ /// <summary>Field used to temporarily store the contents of the queue for serialization.</summary>
+ private T[] _serializationArray;
/// <summary>
/// Initializes a new instance of the <see cref="ConcurrentQueue{T}"/> class.
/// </summary>
public ConcurrentQueue()
{
- m_head = m_tail = new Segment(0, this);
+ _crossSegmentLock = new object();
+ _tail = _head = new Segment(InitialSegmentLength);
+ }
+
+ /// <summary>Set the data array to be serialized.</summary>
+ [OnSerializing]
+ private void OnSerializing(StreamingContext context)
+ {
+ _serializationArray = ToArray();
+ }
+
+ /// <summary>Clear the data array that was serialized.</summary>
+ [OnSerialized]
+ private void OnSerialized(StreamingContext context)
+ {
+ _serializationArray = null;
+ }
+
+ /// <summary>Construct the queue from the deserialized <see cref="_serializationArray"/>.</summary>
+ [OnDeserialized]
+ private void OnDeserialized(StreamingContext context)
+ {
+ Debug.Assert(_serializationArray != null);
+ InitializeFromCollection(_serializationArray);
+ _serializationArray = null;
}
/// <summary>
@@ -70,34 +103,39 @@ namespace System.Collections.Concurrent
/// <param name="collection">A collection from which to copy elements.</param>
private void InitializeFromCollection(IEnumerable<T> collection)
{
- Segment localTail = new Segment(0, this);//use this local variable to avoid the extra volatile read/write. this is safe because it is only called from ctor
- m_head = localTail;
-
- int index = 0;
- foreach (T element in collection)
+ _crossSegmentLock = new object();
+
+ // Determine the initial segment size. We'll use the default,
+ // unless the collection is known to be larger than than, in which
+ // case we round its length up to a power of 2, as all segments must
+ // be a power of 2 in length.
+ int length = InitialSegmentLength;
+ var c = collection as ICollection<T>;
+ if (c != null)
{
- Debug.Assert(index >= 0 && index < SEGMENT_SIZE);
- localTail.UnsafeAdd(element);
- index++;
-
- if (index >= SEGMENT_SIZE)
+ int count = c.Count;
+ if (count > length)
{
- localTail = localTail.UnsafeGrow();
- index = 0;
+ length = RoundUpToPowerOf2(count);
}
}
- m_tail = localTail;
+ // Initialize the segment and add all of the data to it.
+ _tail = _head = new Segment(length);
+ foreach (T item in collection)
+ {
+ Enqueue(item);
+ }
}
/// <summary>
- /// Initializes a new instance of the <see cref="ConcurrentQueue{T}"/>
- /// class that contains elements copied from the specified collection
+ /// Initializes a new instance of the <see cref="ConcurrentQueue{T}"/> class that contains elements copied
+ /// from the specified collection.
/// </summary>
- /// <param name="collection">The collection whose elements are copied to the new <see
- /// cref="ConcurrentQueue{T}"/>.</param>
- /// <exception cref="T:System.ArgumentNullException">The <paramref name="collection"/> argument is
- /// null.</exception>
+ /// <param name="collection">
+ /// The collection whose elements are copied to the new <see cref="ConcurrentQueue{T}"/>.
+ /// </param>
+ /// <exception cref="System.ArgumentNullException">The <paramref name="collection"/> argument is null.</exception>
public ConcurrentQueue(IEnumerable<T> collection)
{
if (collection == null)
@@ -109,37 +147,15 @@ namespace System.Collections.Concurrent
}
/// <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 queue from a previously seiralized one
- /// </summary>
- [OnDeserialized]
- private void OnDeserialized(StreamingContext context)
- {
- Debug.Assert(m_serializationArray != null);
- InitializeFromCollection(m_serializationArray);
- m_serializationArray = null;
- }
-
- /// <summary>
- /// Copies the elements of the <see cref="T:System.Collections.ICollection"/> to an <see
- /// cref="T:System.Array"/>, starting at a particular
- /// <see cref="T:System.Array"/> index.
+ /// Copies the elements of the <see cref="ICollection"/> to an <see
+ /// cref="Array"/>, starting at a particular <see cref="Array"/> index.
/// </summary>
- /// <param name="array">The one-dimensional <see cref="T:System.Array">Array</see> that is the
- /// destination of the elements copied from the
- /// <see cref="T:System.Collections.Concurrent.ConcurrentBag"/>. The <see
- /// cref="T:System.Array">Array</see> must have zero-based indexing.</param>
- /// <param name="index">The zero-based index in <paramref name="array"/> at which copying
- /// begins.</param>
+ /// <param name="array">
+ /// The one-dimensional <see cref="Array">Array</see> that is the destination of the
+ /// elements copied from the <see cref="ConcurrentQueue{T}"/>. <paramref name="array"/> must have
+ /// zero-based indexing.
+ /// </param>
+ /// <param name="index">The zero-based index in <paramref name="array"/> at which copying begins.</param>
/// <exception cref="ArgumentNullException"><paramref name="array"/> is a null reference (Nothing in
/// Visual Basic).</exception>
/// <exception cref="ArgumentOutOfRangeException"><paramref name="index"/> is less than
@@ -148,100 +164,52 @@ namespace System.Collections.Concurrent
/// <paramref name="array"/> is multidimensional. -or-
/// <paramref name="array"/> does not have zero-based indexing. -or-
/// <paramref name="index"/> is equal to or greater than the length of the <paramref name="array"/>
- /// -or- The number of elements in the source <see cref="T:System.Collections.ICollection"/> is
+ /// -or- The number of elements in the source <see cref="ICollection"/> is
/// greater than the available space from <paramref name="index"/> to the end of the destination
/// <paramref name="array"/>. -or- The type of the source <see
- /// cref="T:System.Collections.ICollection"/> cannot be cast automatically to the type of the
+ /// cref="ICollection"/> cannot be cast automatically to the type of the
/// destination <paramref name="array"/>.
/// </exception>
void ICollection.CopyTo(Array array, int index)
{
+ // Special-case when the Array is actually a T[], taking a faster path
+ T[] szArray = array as T[];
+ if (szArray != null)
+ {
+ CopyTo(szArray, index);
+ return;
+ }
+
// Validate arguments.
if (array == null)
{
throw new ArgumentNullException(nameof(array));
}
- // We must be careful not to corrupt the array, so we will first accumulate an
- // internal list of elements that we will then copy to the array. This requires
- // some extra allocation, but is necessary since we don't know up front whether
- // the array is sufficiently large to hold the stack's contents.
- ((ICollection)ToList()).CopyTo(array, index);
+ // Otherwise, fall back to the slower path that first copies the contents
+ // to an array, and then uses that array's non-generic CopyTo to do the copy.
+ ToArray().CopyTo(array, index);
}
/// <summary>
- /// Gets a value indicating whether access to the <see cref="T:System.Collections.ICollection"/> is
+ /// Gets a value indicating whether access to the <see cref="ICollection"/> is
/// synchronized with the SyncRoot.
/// </summary>
- /// <value>true if access to the <see cref="T:System.Collections.ICollection"/> is synchronized
+ /// <value>true if access to the <see cref="ICollection"/> is synchronized
/// with the SyncRoot; otherwise, false. For <see cref="ConcurrentQueue{T}"/>, this property always
/// returns false.</value>
- bool ICollection.IsSynchronized
- {
- // Gets a value indicating whether access to this collection is synchronized. Always returns
- // false. The reason is subtle. While access is in face thread safe, it's not the case that
- // locking on the SyncRoot would have prevented concurrent pushes and pops, as this property
- // would typically indicate; that's because we internally use CAS operations vs. true locks.
- get { return false; }
- }
-
+ bool ICollection.IsSynchronized => false; // always false, as true implies synchronization via SyncRoot
/// <summary>
/// Gets an object that can be used to synchronize access to the <see
- /// cref="T:System.Collections.ICollection"/>. This property is not supported.
- /// </summary>
- /// <exception cref="T:System.NotSupportedException">The SyncRoot property is not supported.</exception>
- object ICollection.SyncRoot
- {
- get
- {
- throw new NotSupportedException(Environment.GetResourceString("ConcurrentCollection_SyncRoot_NotSupported"));
- }
- }
-
- /// <summary>
- /// Returns an enumerator that iterates through a collection.
- /// </summary>
- /// <returns>An <see cref="T:System.Collections.IEnumerator"/> that can be used to iterate through the collection.</returns>
- IEnumerator IEnumerable.GetEnumerator()
- {
- return ((IEnumerable<T>)this).GetEnumerator();
- }
-
- /// <summary>
- /// Attempts to add an object to the <see
- /// cref="T:System.Collections.Concurrent.IProducerConsumerCollection{T}"/>.
+ /// cref="ICollection"/>. This property is not supported.
/// </summary>
- /// <param name="item">The object to add to the <see
- /// cref="T:System.Collections.Concurrent.IProducerConsumerCollection{T}"/>. The value can be a null
- /// reference (Nothing in Visual Basic) for reference types.
- /// </param>
- /// <returns>true if the object was added successfully; otherwise, false.</returns>
- /// <remarks>For <see cref="ConcurrentQueue{T}"/>, this operation will always add the object to the
- /// end of the <see cref="ConcurrentQueue{T}"/>
- /// and return true.</remarks>
- bool IProducerConsumerCollection<T>.TryAdd(T item)
- {
- Enqueue(item);
- return true;
- }
+ /// <exception cref="NotSupportedException">The SyncRoot property is not supported.</exception>
+ object ICollection.SyncRoot { get { throw new NotSupportedException(Environment.GetResourceString("ConcurrentCollection_SyncRoot_NotSupported")); } }
- /// <summary>
- /// Attempts to remove and return an object from the <see
- /// cref="T:System.Collections.Concurrent.IProducerConsumerCollection{T}"/>.
- /// </summary>
- /// <param name="item">
- /// When this method returns, if the operation was successful, <paramref name="item"/> contains the
- /// object removed. If no object was available to be removed, the value is unspecified.
- /// </param>
- /// <returns>true if an element was removed and returned succesfully; otherwise, false.</returns>
- /// <remarks>For <see cref="ConcurrentQueue{T}"/>, this operation will attempt to remove the object
- /// from the beginning of the <see cref="ConcurrentQueue{T}"/>.
- /// </remarks>
- bool IProducerConsumerCollection<T>.TryTake(out T item)
- {
- return TryDequeue(out item);
- }
+ /// <summary>Returns an enumerator that iterates through a collection.</summary>
+ /// <returns>An <see cref="IEnumerator"/> that can be used to iterate through the collection.</returns>
+ IEnumerator IEnumerable.GetEnumerator() => ((IEnumerable<T>)this).GetEnumerator();
/// <summary>
/// Gets a value that indicates whether the <see cref="ConcurrentQueue{T}"/> is empty.
@@ -258,126 +226,43 @@ namespace System.Collections.Concurrent
{
get
{
- Segment head = m_head;
- if (!head.IsEmpty)
- //fast route 1:
- //if current head is not empty, then queue is not empty
- return false;
- else if (head.Next == null)
- //fast route 2:
- //if current head is empty and it's the last segment
- //then queue is empty
- return true;
- else
- //slow route:
- //current head is empty and it is NOT the last segment,
- //it means another thread is growing new segment
- {
- SpinWait spin = new SpinWait();
- while (head.IsEmpty)
- {
- if (head.Next == null)
- return true;
-
- spin.SpinOnce();
- head = m_head;
- }
- return false;
- }
+ // IsEmpty == !TryPeek. We use a "resultUsed:false" peek in order to avoid marking
+ // segments as preserved for observation, making IsEmpty a cheaper way than either
+ // TryPeek(out T) or Count == 0 to check whether any elements are in the queue.
+ T ignoredResult;
+ return !TryPeek(out ignoredResult, resultUsed: false);
}
}
- /// <summary>
- /// Copies the elements stored in the <see cref="ConcurrentQueue{T}"/> to a new array.
- /// </summary>
- /// <returns>A new array containing a snapshot of elements copied from the <see
- /// cref="ConcurrentQueue{T}"/>.</returns>
+ /// <summary>Copies the elements stored in the <see cref="ConcurrentQueue{T}"/> to a new array.</summary>
+ /// <returns>A new array containing a snapshot of elements copied from the <see cref="ConcurrentQueue{T}"/>.</returns>
public T[] ToArray()
{
- return ToList().ToArray();
- }
+ // Snap the current contents for enumeration.
+ Segment head, tail;
+ int headHead, tailTail;
+ SnapForObservation(out head, out headHead, out tail, out tailTail);
- /// <summary>
- /// Copies the <see cref="ConcurrentQueue{T}"/> elements to a new <see
- /// cref="T:System.Collections.Generic.List{T}"/>.
- /// </summary>
- /// <returns>A new <see cref="T:System.Collections.Generic.List{T}"/> containing a snapshot of
- /// elements copied from the <see cref="ConcurrentQueue{T}"/>.</returns>
- private List<T> ToList()
- {
- // Increments the number of active snapshot takers. This increment must happen before the snapshot is
- // taken. At the same time, Decrement must happen after list copying is over. Only in this way, can it
- // eliminate race condition when Segment.TryRemove() checks whether m_numSnapshotTakers == 0.
- Interlocked.Increment(ref m_numSnapshotTakers);
+ // Count the number of items in that snapped set, and use it to allocate an
+ // array of the right size.
+ long count = GetCount(head, headHead, tail, tailTail);
+ T[] arr = new T[count];
- List<T> list = new List<T>();
- try
+ // Now enumerate the contents, copying each element into the array.
+ using (IEnumerator<T> e = Enumerate(head, headHead, tail, tailTail))
{
- //store head and tail positions in buffer,
- Segment head, tail;
- int headLow, tailHigh;
- GetHeadTailPositions(out head, out tail, out headLow, out tailHigh);
-
- if (head == tail)
- {
- head.AddToList(list, headLow, tailHigh);
- }
- else
+ int i = 0;
+ while (e.MoveNext())
{
- head.AddToList(list, headLow, SEGMENT_SIZE - 1);
- Segment curr = head.Next;
- while (curr != tail)
- {
- curr.AddToList(list, 0, SEGMENT_SIZE - 1);
- curr = curr.Next;
- }
- //Add tail segment
- tail.AddToList(list, 0, tailHigh);
+ arr[i++] = e.Current;
}
+ Debug.Assert(count == i);
}
- finally
- {
- // This Decrement must happen after copying is over.
- Interlocked.Decrement(ref m_numSnapshotTakers);
- }
- return list;
- }
- /// <summary>
- /// Store the position of the current head and tail positions.
- /// </summary>
- /// <param name="head">return the head segment</param>
- /// <param name="tail">return the tail segment</param>
- /// <param name="headLow">return the head offset, value range [0, SEGMENT_SIZE]</param>
- /// <param name="tailHigh">return the tail offset, value range [-1, SEGMENT_SIZE-1]</param>
- private void GetHeadTailPositions(out Segment head, out Segment tail,
- out int headLow, out int tailHigh)
- {
- head = m_head;
- tail = m_tail;
- headLow = head.Low;
- tailHigh = tail.High;
- SpinWait spin = new SpinWait();
-
- //we loop until the observed values are stable and sensible.
- //This ensures that any update order by other methods can be tolerated.
- while (
- //if head and tail changed, retry
- head != m_head || tail != m_tail
- //if low and high pointers, retry
- || headLow != head.Low || tailHigh != tail.High
- //if head jumps ahead of tail because of concurrent grow and dequeue, retry
- || head.m_index > tail.m_index)
- {
- spin.SpinOnce();
- head = m_head;
- tail = m_tail;
- headLow = head.Low;
- tailHigh = tail.High;
- }
+ // And return it.
+ return arr;
}
-
/// <summary>
/// Gets the number of elements contained in the <see cref="ConcurrentQueue{T}"/>.
/// </summary>
@@ -391,38 +276,140 @@ namespace System.Collections.Concurrent
{
get
{
- //store head and tail positions in buffer,
Segment head, tail;
- int headLow, tailHigh;
- GetHeadTailPositions(out head, out tail, out headLow, out tailHigh);
-
- if (head == tail)
+ int headHead, headTail, tailHead, tailTail;
+ var spinner = new SpinWait();
+ while (true)
{
- return tailHigh - headLow + 1;
+ // Capture the head and tail, as well as the head's head and tail.
+ head = _head;
+ tail = _tail;
+ headHead = Volatile.Read(ref head._headAndTail.Head);
+ headTail = Volatile.Read(ref head._headAndTail.Tail);
+
+ if (head == tail)
+ {
+ // There was a single segment in the queue. If the captured
+ // values still (or again) represent reality, return the segment's
+ // count. A single segment should be the most common case once the
+ // queue's size has stabilized after segments have grown to
+ // the point where growing is no longer needed.
+ if (head == _head &&
+ head == _tail &&
+ headHead == Volatile.Read(ref head._headAndTail.Head) &&
+ headTail == Volatile.Read(ref head._headAndTail.Tail))
+ {
+ return GetCount(head, headHead, headTail);
+ }
+ }
+ else if (head._nextSegment == tail)
+ {
+ // There were two segments in the queue. Get the positions
+ // from the tail, and if the captured values still (or again) match
+ // reality, return the sum of the counts from both segments.
+ tailHead = Volatile.Read(ref tail._headAndTail.Head);
+ tailTail = Volatile.Read(ref tail._headAndTail.Tail);
+ if (head == _head &&
+ tail == _tail &&
+ headHead == Volatile.Read(ref head._headAndTail.Head) &&
+ headTail == Volatile.Read(ref head._headAndTail.Tail) &&
+ tailHead == Volatile.Read(ref tail._headAndTail.Head) &&
+ tailTail == Volatile.Read(ref tail._headAndTail.Tail))
+ {
+ // We got stable values, so we can just compute the sizes based on those
+ // values and return the sum of the counts of the segments.
+ return GetCount(head, headHead, headTail) + GetCount(tail, tailHead, tailTail);
+ }
+ }
+ else
+ {
+ // There were more than two segments. Take the slower path, where we freeze the
+ // queue and then count the now stable segments.
+ SnapForObservation(out head, out headHead, out tail, out tailTail);
+ return unchecked((int)GetCount(head, headHead, tail, tailTail));
+ }
+
+ // We raced with enqueues/dequeues and captured an inconsistent picture of the queue.
+ // Spin and try again.
+ spinner.SpinOnce();
}
+ }
+ }
- //head segment
- int count = SEGMENT_SIZE - headLow;
+ /// <summary>Computes the number of items in a segment based on a fixed head and tail in that segment.</summary>
+ private static int GetCount(Segment s, int head, int tail)
+ {
+ if (head != tail && head != tail - s.FreezeOffset)
+ {
+ head &= s._slotsMask;
+ tail &= s._slotsMask;
+ return head < tail ? tail - head : s._slots.Length - head + tail;
+ }
+ return 0;
+ }
- //middle segment(s), if any, are full.
- //We don't deal with overflow to be consistent with the behavior of generic types in CLR.
- count += SEGMENT_SIZE * ((int)(tail.m_index - head.m_index - 1));
+ /// <summary>Gets the number of items in snapped region.</summary>
+ private static long GetCount(Segment head, int headHead, Segment tail, int tailTail)
+ {
+ // All of the segments should have been both frozen for enqueues and preserved for observation.
+ // Validate that here for head and tail; we'll validate it for intermediate segments later.
+ Debug.Assert(head._preservedForObservation);
+ Debug.Assert(head._frozenForEnqueues);
+ Debug.Assert(tail._preservedForObservation);
+ Debug.Assert(tail._frozenForEnqueues);
+
+ long count = 0;
+
+ // Head segment. We've already marked it as frozen for enqueues, so its tail position is fixed,
+ // and we've already marked it as preserved for observation (before we grabbed the head), so we
+ // can safely enumerate from its head to its tail and access its elements.
+ int headTail = (head == tail ? tailTail : Volatile.Read(ref head._headAndTail.Tail)) - head.FreezeOffset;
+ if (headHead < headTail)
+ {
+ // Mask the head and tail for the head segment
+ headHead &= head._slotsMask;
+ headTail &= head._slotsMask;
+
+ // Increase the count by either the one or two regions, based on whether tail
+ // has wrapped to be less than head.
+ count += headHead < headTail ?
+ headTail - headHead :
+ head._slots.Length - headHead + headTail;
+ }
- //tail segment
- count += tailHigh + 1;
+ // We've enumerated the head. If the tail is different from the head, we need to
+ // enumerate the remaining segments.
+ if (head != tail)
+ {
+ // Count the contents of each segment between head and tail, not including head and tail.
+ // Since there were segments before these, for our purposes we consider them to start at
+ // the 0th element, and since there is at least one segment after each, each was frozen
+ // by the time we snapped it, so we can iterate until each's frozen tail.
+ for (Segment s = head._nextSegment; s != tail; s = s._nextSegment)
+ {
+ Debug.Assert(s._preservedForObservation);
+ Debug.Assert(s._frozenForEnqueues);
+ count += s._headAndTail.Tail - s.FreezeOffset;
+ }
- return count;
+ // Finally, enumerate the tail. As with the intermediate segments, there were segments
+ // before this in the snapped region, so we can start counting from the beginning. Unlike
+ // the intermediate segments, we can't just go until the Tail, as that could still be changing;
+ // instead we need to go until the tail we snapped for observation.
+ count += tailTail - tail.FreezeOffset;
}
- }
+ // Return the computed count.
+ return count;
+ }
/// <summary>
/// Copies the <see cref="ConcurrentQueue{T}"/> elements to an existing one-dimensional <see
- /// cref="T:System.Array">Array</see>, starting at the specified array index.
+ /// cref="Array">Array</see>, starting at the specified array index.
/// </summary>
- /// <param name="array">The one-dimensional <see cref="T:System.Array">Array</see> that is the
+ /// <param name="array">The one-dimensional <see cref="Array">Array</see> that is the
/// destination of the elements copied from the
- /// <see cref="ConcurrentQueue{T}"/>. The <see cref="T:System.Array">Array</see> must have zero-based
+ /// <see cref="ConcurrentQueue{T}"/>. The <see cref="Array">Array</see> must have zero-based
/// indexing.</param>
/// <param name="index">The zero-based index in <paramref name="array"/> at which copying
/// begins.</param>
@@ -442,19 +429,36 @@ namespace System.Collections.Concurrent
{
throw new ArgumentNullException(nameof(array));
}
+ if (index < 0)
+ {
+ throw new ArgumentOutOfRangeException(nameof(index));
+ }
- // We must be careful not to corrupt the array, so we will first accumulate an
- // internal list of elements that we will then copy to the array. This requires
- // some extra allocation, but is necessary since we don't know up front whether
- // the array is sufficiently large to hold the stack's contents.
- ToList().CopyTo(array, index);
- }
+ // Snap for enumeration
+ Segment head, tail;
+ int headHead, tailTail;
+ SnapForObservation(out head, out headHead, out tail, out tailTail);
+ // Get the number of items to be enumerated
+ long count = GetCount(head, headHead, tail, tailTail);
+ if (index > array.Length - count)
+ {
+ throw new ArgumentException(Environment.GetResourceString("Arg_ArrayPlusOffTooSmall"));
+ }
- /// <summary>
- /// Returns an enumerator that iterates through the <see
- /// cref="ConcurrentQueue{T}"/>.
- /// </summary>
+ // Copy the items to the target array
+ int i = index;
+ using (IEnumerator<T> e = Enumerate(head, headHead, tail, tailTail))
+ {
+ while (e.MoveNext())
+ {
+ array[i++] = e.Current;
+ }
+ }
+ Debug.Assert(count == i - index);
+ }
+
+ /// <summary>Returns an enumerator that iterates through the <see cref="ConcurrentQueue{T}"/>.</summary>
/// <returns>An enumerator for the contents of the <see
/// cref="ConcurrentQueue{T}"/>.</returns>
/// <remarks>
@@ -465,124 +469,195 @@ namespace System.Collections.Concurrent
/// </remarks>
public IEnumerator<T> GetEnumerator()
{
- // Increments the number of active snapshot takers. This increment must happen before the snapshot is
- // taken. At the same time, Decrement must happen after the enumeration is over. Only in this way, can it
- // eliminate race condition when Segment.TryRemove() checks whether m_numSnapshotTakers == 0.
- Interlocked.Increment(ref m_numSnapshotTakers);
-
- // Takes a snapshot of the queue.
- // A design flaw here: if a Thread.Abort() happens, we cannot decrement m_numSnapshotTakers. But we cannot
- // wrap the following with a try/finally block, otherwise the decrement will happen before the yield return
- // statements in the GetEnumerator (head, tail, headLow, tailHigh) method.
Segment head, tail;
- int headLow, tailHigh;
- GetHeadTailPositions(out head, out tail, out headLow, out tailHigh);
-
- //If we put yield-return here, the iterator will be lazily evaluated. As a result a snapshot of
- // the queue is not taken when GetEnumerator is initialized but when MoveNext() is first called.
- // This is inconsistent with existing generic collections. In order to prevent it, we capture the
- // value of m_head in a buffer and call out to a helper method.
- //The old way of doing this was to return the ToList().GetEnumerator(), but ToList() was an
- // unnecessary perfomance hit.
- return GetEnumerator(head, tail, headLow, tailHigh);
+ int headHead, tailTail;
+ SnapForObservation(out head, out headHead, out tail, out tailTail);
+ return Enumerate(head, headHead, tail, tailTail);
}
/// <summary>
- /// Helper method of GetEnumerator to seperate out yield return statement, and prevent lazy evaluation.
+ /// Gets the head and tail information of the current contents of the queue.
+ /// After this call returns, the specified region can be enumerated any number
+ /// of times and will not change.
/// </summary>
- private IEnumerator<T> GetEnumerator(Segment head, Segment tail, int headLow, int tailHigh)
+ private void SnapForObservation(out Segment head, out int headHead, out Segment tail, out int tailTail)
{
- try
+ lock (_crossSegmentLock) // _head and _tail may only change while the lock is held.
{
- SpinWait spin = new SpinWait();
+ // Snap the head and tail
+ head = _head;
+ tail = _tail;
+ Debug.Assert(head != null);
+ Debug.Assert(tail != null);
+ Debug.Assert(tail._nextSegment == null);
+
+ // Mark them and all segments in between as preserving, and ensure no additional items
+ // can be added to the tail.
+ for (Segment s = head; ; s = s._nextSegment)
+ {
+ s._preservedForObservation = true;
+ if (s == tail) break;
+ Debug.Assert(s._frozenForEnqueues); // any non-tail should already be marked
+ }
+ tail.EnsureFrozenForEnqueues(); // we want to prevent the tailTail from moving
- if (head == tail)
+ // At this point, any dequeues from any segment won't overwrite the value, and
+ // none of the existing segments can have new items enqueued.
+
+ headHead = Volatile.Read(ref head._headAndTail.Head);
+ tailTail = Volatile.Read(ref tail._headAndTail.Tail);
+ }
+ }
+
+ /// <summary>Gets the item stored in the <paramref name="i"/>th entry in <paramref name="segment"/>.</summary>
+ private T GetItemWhenAvailable(Segment segment, int i)
+ {
+ Debug.Assert(segment._preservedForObservation);
+
+ // Get the expected value for the sequence number
+ int expectedSequenceNumberAndMask = (i + 1) & segment._slotsMask;
+
+ // If the expected sequence number is not yet written, we're still waiting for
+ // an enqueuer to finish storing it. Spin until it's there.
+ if ((segment._slots[i].SequenceNumber & segment._slotsMask) != expectedSequenceNumberAndMask)
+ {
+ var spinner = new SpinWait();
+ while ((Volatile.Read(ref segment._slots[i].SequenceNumber) & segment._slotsMask) != expectedSequenceNumberAndMask)
{
- for (int i = headLow; i <= tailHigh; i++)
- {
- // If the position is reserved by an Enqueue operation, but the value is not written into,
- // spin until the value is available.
- spin.Reset();
- while (!head.m_state[i].m_value)
- {
- spin.SpinOnce();
- }
- yield return head.m_array[i];
- }
+ spinner.SpinOnce();
+ }
+ }
+
+ // Return the value from the slot.
+ return segment._slots[i].Item;
+ }
+
+ private IEnumerator<T> Enumerate(Segment head, int headHead, Segment tail, int tailTail)
+ {
+ Debug.Assert(head._preservedForObservation);
+ Debug.Assert(head._frozenForEnqueues);
+ Debug.Assert(tail._preservedForObservation);
+ Debug.Assert(tail._frozenForEnqueues);
+
+ // Head segment. We've already marked it as not accepting any more enqueues,
+ // so its tail position is fixed, and we've already marked it as preserved for
+ // enumeration (before we grabbed its head), so we can safely enumerate from
+ // its head to its tail.
+ int headTail = (head == tail ? tailTail : Volatile.Read(ref head._headAndTail.Tail)) - head.FreezeOffset;
+ if (headHead < headTail)
+ {
+ headHead &= head._slotsMask;
+ headTail &= head._slotsMask;
+
+ if (headHead < headTail)
+ {
+ for (int i = headHead; i < headTail; i++) yield return GetItemWhenAvailable(head, i);
}
else
{
- //iterate on head segment
- for (int i = headLow; i < SEGMENT_SIZE; i++)
- {
- // If the position is reserved by an Enqueue operation, but the value is not written into,
- // spin until the value is available.
- spin.Reset();
- while (!head.m_state[i].m_value)
- {
- spin.SpinOnce();
- }
- yield return head.m_array[i];
- }
- //iterate on middle segments
- Segment curr = head.Next;
- while (curr != tail)
- {
- for (int i = 0; i < SEGMENT_SIZE; i++)
- {
- // If the position is reserved by an Enqueue operation, but the value is not written into,
- // spin until the value is available.
- spin.Reset();
- while (!curr.m_state[i].m_value)
- {
- spin.SpinOnce();
- }
- yield return curr.m_array[i];
- }
- curr = curr.Next;
- }
+ for (int i = headHead; i < head._slots.Length; i++) yield return GetItemWhenAvailable(head, i);
+ for (int i = 0; i < headTail; i++) yield return GetItemWhenAvailable(head, i);
+ }
+ }
- //iterate on tail segment
- for (int i = 0; i <= tailHigh; i++)
+ // We've enumerated the head. If the tail is the same, we're done.
+ if (head != tail)
+ {
+ // Each segment between head and tail, not including head and tail. Since there were
+ // segments before these, for our purposes we consider it to start at the 0th element.
+ for (Segment s = head._nextSegment; s != tail; s = s._nextSegment)
+ {
+ Debug.Assert(s._preservedForObservation, "Would have had to been preserved as a segment part of enumeration");
+ Debug.Assert(s._frozenForEnqueues, "Would have had to be frozen for enqueues as it's intermediate");
+
+ int sTail = s._headAndTail.Tail - s.FreezeOffset;
+ for (int i = 0; i < sTail; i++)
{
- // If the position is reserved by an Enqueue operation, but the value is not written into,
- // spin until the value is available.
- spin.Reset();
- while (!tail.m_state[i].m_value)
- {
- spin.SpinOnce();
- }
- yield return tail.m_array[i];
+ yield return GetItemWhenAvailable(s, i);
}
}
- }
- finally
- {
- // This Decrement must happen after the enumeration is over.
- Interlocked.Decrement(ref m_numSnapshotTakers);
+
+ // Enumerate the tail. Since there were segments before this, we can just start at
+ // its beginning, and iterate until the tail we already grabbed.
+ tailTail -= tail.FreezeOffset;
+ for (int i = 0; i < tailTail; i++)
+ {
+ yield return GetItemWhenAvailable(tail, i);
+ }
}
}
- /// <summary>
- /// Adds an object to the end of the <see cref="ConcurrentQueue{T}"/>.
- /// </summary>
- /// <param name="item">The object to add to the end of the <see
- /// cref="ConcurrentQueue{T}"/>. The value can be a null reference
- /// (Nothing in Visual Basic) for reference types.
+ /// <summary>Round the specified value up to the next power of 2, if it isn't one already.</summary>
+ private static int RoundUpToPowerOf2(int i)
+ {
+ --i;
+ i |= i >> 1;
+ i |= i >> 2;
+ i |= i >> 4;
+ i |= i >> 8;
+ i |= i >> 16;
+ return i + 1;
+ }
+
+ /// <summary>Adds an object to the end of the <see cref="ConcurrentQueue{T}"/>.</summary>
+ /// <param name="item">
+ /// The object to add to the end of the <see cref="ConcurrentQueue{T}"/>.
+ /// The value can be a null reference (Nothing in Visual Basic) for reference types.
/// </param>
public void Enqueue(T item)
{
- SpinWait spin = new SpinWait();
+ // Try to enqueue to the current tail.
+ if (!_tail.TryEnqueue(item))
+ {
+ // If we're unable to, we need to take a slow path that will
+ // try to add a new tail segment.
+ EnqueueSlow(item);
+ }
+ }
+
+ /// <summary>Adds to the end of the queue, adding a new segment if necessary.</summary>
+ private void EnqueueSlow(T item)
+ {
while (true)
{
- Segment tail = m_tail;
- if (tail.TryAppend(item))
+ Segment tail = _tail;
+
+ // Try to append to the existing tail.
+ if (tail.TryEnqueue(item))
+ {
return;
- spin.SpinOnce();
+ }
+
+ // If we were unsuccessful, take the lock so that we can compare and manipulate
+ // the tail. Assuming another enqueuer hasn't already added a new segment,
+ // do so, then loop around to try enqueueing again.
+ lock (_crossSegmentLock)
+ {
+ if (tail == _tail)
+ {
+ // Make sure no one else can enqueue to this segment.
+ tail.EnsureFrozenForEnqueues();
+
+ // We determine the new segment's length based on the old length.
+ // In general, we double the size of the segment, to make it less likely
+ // that we'll need to grow again. However, if the tail segment is marked
+ // as preserved for observation, something caused us to avoid reusing this
+ // segment, and if that happens a lot and we grow, we'll end up allocating
+ // lots of wasted space. As such, in such situations we reset back to the
+ // initial segment length; if these observations are happening frequently,
+ // this will help to avoid wasted memory, and if they're not, we'll
+ // relatively quickly grow again to a larger size.
+ int nextSize = tail._preservedForObservation ? InitialSegmentLength : tail.Capacity * 2;
+ var newTail = new Segment(nextSize);
+
+ // Hook up the new tail.
+ tail._nextSegment = newTail;
+ _tail = newTail;
+ }
+ }
}
}
-
/// <summary>
/// Attempts to remove and return the object at the beginning of the <see
/// cref="ConcurrentQueue{T}"/>.
@@ -591,369 +666,456 @@ namespace System.Collections.Concurrent
/// When this method returns, if the operation was successful, <paramref name="result"/> contains the
/// object removed. If no object was available to be removed, the value is unspecified.
/// </param>
- /// <returns>true if an element was removed and returned from the beggining of the <see
- /// cref="ConcurrentQueue{T}"/>
- /// succesfully; otherwise, false.</returns>
- public bool TryDequeue(out T result)
+ /// <returns>
+ /// true if an element was removed and returned from the beginning of the
+ /// <see cref="ConcurrentQueue{T}"/> successfully; otherwise, false.
+ /// </returns>
+ public bool TryDequeue(out T result) =>
+ _head.TryDequeue(out result) || // fast-path that operates just on the head segment
+ TryDequeueSlow(out result); // slow path that needs to fix up segments
+
+ /// <summary>Tries to dequeue an item, removing empty segments as needed.</summary>
+ private bool TryDequeueSlow(out T item)
{
- while (!IsEmpty)
+ while (true)
{
- Segment head = m_head;
- if (head.TryRemove(out result))
+ // Get the current head
+ Segment head = _head;
+
+ // Try to take. If we're successful, we're done.
+ if (head.TryDequeue(out item))
+ {
+ return true;
+ }
+
+ // Check to see whether this segment is the last. If it is, we can consider
+ // this to be a moment-in-time empty condition (even though between the TryDequeue
+ // check and this check, another item could have arrived).
+ if (head._nextSegment == null)
+ {
+ item = default(T);
+ return false;
+ }
+
+ // At this point we know that head.Next != null, which means
+ // this segment has been frozen for additional enqueues. But between
+ // the time that we ran TryDequeue and checked for a next segment,
+ // another item could have been added. Try to dequeue one more time
+ // to confirm that the segment is indeed empty.
+ Debug.Assert(head._frozenForEnqueues);
+ if (head.TryDequeue(out item))
+ {
return true;
- //since method IsEmpty spins, we don't need to spin in the while loop
+ }
+
+ // This segment is frozen (nothing more can be added) and empty (nothing is in it).
+ // Update head to point to the next segment in the list, assuming no one's beat us to it.
+ lock (_crossSegmentLock)
+ {
+ if (head == _head)
+ {
+ _head = head._nextSegment;
+ }
+ }
}
- result = default(T);
- return false;
}
/// <summary>
/// Attempts to return an object from the beginning of the <see cref="ConcurrentQueue{T}"/>
/// without removing it.
/// </summary>
- /// <param name="result">When this method returns, <paramref name="result"/> contains an object from
- /// the beginning of the <see cref="T:System.Collections.Concurrent.ConccurrentQueue{T}"/> or an
- /// unspecified value if the operation failed.</param>
+ /// <param name="result">
+ /// When this method returns, <paramref name="result"/> contains an object from
+ /// the beginning of the <see cref="Concurrent.ConcurrentQueue{T}"/> or default(T)
+ /// if the operation failed.
+ /// </param>
/// <returns>true if and object was returned successfully; otherwise, false.</returns>
- public bool TryPeek(out T result)
- {
- Interlocked.Increment(ref m_numSnapshotTakers);
+ /// <remarks>
+ /// For determining whether the collection contains any items, use of the <see cref="IsEmpty"/>
+ /// property is recommended rather than peeking.
+ /// </remarks>
+ public bool TryPeek(out T result) => TryPeek(out result, resultUsed: true);
- while (!IsEmpty)
+ /// <summary>Attempts to retrieve the value for the first element in the queue.</summary>
+ /// <param name="result">The value of the first element, if found.</param>
+ /// <param name="resultUsed">true if the result is neede; otherwise false if only the true/false outcome is needed.</param>
+ /// <returns>true if an element was found; otherwise, false.</returns>
+ private bool TryPeek(out T result, bool resultUsed)
+ {
+ // Starting with the head segment, look through all of the segments
+ // for the first one we can find that's not empty.
+ Segment s = _head;
+ while (true)
{
- Segment head = m_head;
- if (head.TryPeek(out result))
+ // Grab the next segment from this one, before we peek.
+ // This is to be able to see whether the value has changed
+ // during the peek operation.
+ Segment next = Volatile.Read(ref s._nextSegment);
+
+ // Peek at the segment. If we find an element, we're done.
+ if (s.TryPeek(out result, resultUsed))
{
- Interlocked.Decrement(ref m_numSnapshotTakers);
return true;
}
- //since method IsEmpty spins, we don't need to spin in the while loop
+
+ // The current segment was empty at the moment we checked.
+
+ if (next != null)
+ {
+ // If prior to the peek there was already a next segment, then
+ // during the peek no additional items could have been enqueued
+ // to it and we can just move on to check the next segment.
+ Debug.Assert(next == s._nextSegment);
+ s = next;
+ }
+ else if (Volatile.Read(ref s._nextSegment) == null)
+ {
+ // The next segment is null. Nothing more to peek at.
+ break;
+ }
+
+ // The next segment was null before we peeked but non-null after.
+ // That means either when we peeked the first segment had
+ // already been frozen but the new segment not yet added,
+ // or that the first segment was empty and between the time
+ // that we peeked and then checked _nextSegment, so many items
+ // were enqueued that we filled the first segment and went
+ // into the next. Since we need to peek in order, we simply
+ // loop around again to peek on the same segment. The next
+ // time around on this segment we'll then either successfully
+ // peek or we'll find that next was non-null before peeking,
+ // and we'll traverse to that segment.
}
+
result = default(T);
- Interlocked.Decrement(ref m_numSnapshotTakers);
return false;
}
-
/// <summary>
- /// private class for ConcurrentQueue.
- /// a queue is a linked list of small arrays, each node is called a segment.
- /// A segment contains an array, a pointer to the next segment, and m_low, m_high indices recording
- /// the first and last valid elements of the array.
+ /// Removes all objects from the <see cref="ConcurrentQueue{T}"/>.
/// </summary>
- private class Segment
+ public void Clear()
{
- //we define two volatile arrays: m_array and m_state. Note that the accesses to the array items
- //do not get volatile treatment. But we don't need to worry about loading adjacent elements or
- //store/load on adjacent elements would suffer reordering.
- // - Two stores: these are at risk, but CLRv2 memory model guarantees store-release hence we are safe.
- // - Two loads: because one item from two volatile arrays are accessed, the loads of the array references
- // are sufficient to prevent reordering of the loads of the elements.
- internal volatile T[] m_array;
-
- // For each entry in m_array, the corresponding entry in m_state indicates whether this position contains
- // a valid value. m_state is initially all false.
- internal volatile VolatileBool[] m_state;
-
- //pointer to the next segment. null if the current segment is the last segment
- private volatile Segment m_next;
-
- //We use this zero based index to track how many segments have been created for the queue, and
- //to compute how many active segments are there currently.
- // * The number of currently active segments is : m_tail.m_index - m_head.m_index + 1;
- // * m_index is incremented with every Segment.Grow operation. We use Int64 type, and we can safely
- // assume that it never overflows. To overflow, we need to do 2^63 increments, even at a rate of 4
- // billion (2^32) increments per second, it takes 2^31 seconds, which is about 64 years.
- internal readonly long m_index;
-
- //indices of where the first and last valid values
- // - m_low points to the position of the next element to pop from this segment, range [0, infinity)
- // m_low >= SEGMENT_SIZE implies the segment is disposable
- // - m_high points to the position of the latest pushed element, range [-1, infinity)
- // m_high == -1 implies the segment is new and empty
- // m_high >= SEGMENT_SIZE-1 means this segment is ready to grow.
- // and the thread who sets m_high to SEGMENT_SIZE-1 is responsible to grow the segment
- // - Math.Min(m_low, SEGMENT_SIZE) > Math.Min(m_high, SEGMENT_SIZE-1) implies segment is empty
- // - initially m_low =0 and m_high=-1;
- private volatile int m_low;
- private volatile int m_high;
-
- private volatile ConcurrentQueue<T> m_source;
-
- /// <summary>
- /// Create and initialize a segment with the specified index.
- /// </summary>
- internal Segment(long index, ConcurrentQueue<T> source)
+ lock (_crossSegmentLock)
{
- m_array = new T[SEGMENT_SIZE];
- m_state = new VolatileBool[SEGMENT_SIZE]; //all initialized to false
- m_high = -1;
- Debug.Assert(index >= 0);
- m_index = index;
- m_source = source;
- }
-
- /// <summary>
- /// return the next segment
- /// </summary>
- internal Segment Next
- {
- get { return m_next; }
- }
-
-
- /// <summary>
- /// return true if the current segment is empty (doesn't have any element available to dequeue,
- /// false otherwise
- /// </summary>
- internal bool IsEmpty
- {
- get { return (Low > High); }
- }
-
- /// <summary>
- /// Add an element to the tail of the current segment
- /// exclusively called by ConcurrentQueue.InitializedFromCollection
- /// InitializeFromCollection is responsible to guaratee that there is no index overflow,
- /// and there is no contention
- /// </summary>
- /// <param name="value"></param>
- internal void UnsafeAdd(T value)
- {
- Debug.Assert(m_high < SEGMENT_SIZE - 1);
- m_high++;
- m_array[m_high] = value;
- m_state[m_high].m_value = true;
+ // Simply substitute a new segment for the existing head/tail,
+ // as is done in the constructor. Operations currently in flight
+ // may still read from or write to an existing segment that's
+ // getting dropped, meaning that in flight operations may not be
+ // linear with regards to this clear operation. To help mitigate
+ // in-flight operations enqueuing onto the tail that's about to
+ // be dropped, we first freeze it; that'll force enqueuers to take
+ // this lock to synchronize and see the new tail.
+ _tail.EnsureFrozenForEnqueues();
+ _tail = _head = new Segment(InitialSegmentLength);
}
+ }
- /// <summary>
- /// Create a new segment and append to the current one
- /// Does not update the m_tail pointer
- /// exclusively called by ConcurrentQueue.InitializedFromCollection
- /// InitializeFromCollection is responsible to guaratee that there is no index overflow,
- /// and there is no contention
- /// </summary>
- /// <returns>the reference to the new Segment</returns>
- internal Segment UnsafeGrow()
+ /// <summary>
+ /// Provides a multi-producer, multi-consumer thread-safe bounded segment. When the queue is full,
+ /// enqueues fail and return false. When the queue is empty, dequeues fail and return null.
+ /// These segments are linked together to form the unbounded <see cref="ConcurrentQueue{T}"/>.
+ /// </summary>
+ [DebuggerDisplay("Capacity = {Capacity}")]
+ private sealed class Segment
+ {
+ // Segment design is inspired by the algorithm outlined at:
+ // http://www.1024cores.net/home/lock-free-algorithms/queues/bounded-mpmc-queue
+
+ /// <summary>The array of items in this queue. Each slot contains the item in that slot and its "sequence number".</summary>
+ internal readonly Slot[] _slots;
+ /// <summary>Mask for quickly accessing a position within the queue's array.</summary>
+ internal readonly int _slotsMask;
+ /// <summary>The head and tail positions, with padding to help avoid false sharing contention.</summary>
+ /// <remarks>Dequeueing happens from the head, enqueueing happens at the tail.</remarks>
+ internal PaddedHeadAndTail _headAndTail; // mutable struct: do not make this readonly
+
+ /// <summary>Indicates whether the segment has been marked such that dequeues don't overwrite the removed data.</summary>
+ internal bool _preservedForObservation;
+ /// <summary>Indicates whether the segment has been marked such that no additional items may be enqueued.</summary>
+ internal bool _frozenForEnqueues;
+ /// <summary>The segment following this one in the queue, or null if this segment is the last in the queue.</summary>
+ internal Segment _nextSegment;
+
+ /// <summary>Creates the segment.</summary>
+ /// <param name="boundedLength">
+ /// The maximum number of elements the segment can contain. Must be a power of 2.
+ /// </param>
+ public Segment(int boundedLength)
{
- 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;
+ // Validate the length
+ Debug.Assert(boundedLength >= 2, $"Must be >= 2, got {boundedLength}");
+ Debug.Assert((boundedLength & (boundedLength - 1)) == 0, $"Must be a power of 2, got {boundedLength}");
+
+ // Initialize the slots and the mask. The mask is used as a way of quickly doing "% _slots.Length",
+ // instead letting us do "& _slotsMask".
+ _slots = new Slot[boundedLength];
+ _slotsMask = boundedLength - 1;
+
+ // Initialize the sequence number for each slot. The sequence number provides a ticket that
+ // allows dequeuers to know whether they can dequeue and enqueuers to know whether they can
+ // enqueue. An enqueuer at position N can enqueue when the sequence number is N, and a dequeuer
+ // for position N can dequeue when the sequence number is N + 1. When an enqueuer is done writing
+ // at position N, it sets the sequence number to N so that a dequeuer will be able to dequeue,
+ // and when a dequeuer is done dequeueing at position N, it sets the sequence number to N + _slots.Length,
+ // so that when an enqueuer loops around the slots, it'll find that the sequence number at
+ // position N is N. This also means that when an enqueuer finds that at position N the sequence
+ // number is < N, there is still a value in that slot, i.e. the segment is full, and when a
+ // dequeuer finds that the value in a slot is < N + 1, there is nothing currently available to
+ // dequeue. (It is possible for multiple enqueuers to enqueue concurrently, writing into
+ // subsequent slots, and to have the first enqueuer take longer, so that the slots for 1, 2, 3, etc.
+ // may have values, but the 0th slot may still be being filled... in that case, TryDequeue will
+ // return false.)
+ for (int i = 0; i < _slots.Length; i++)
+ {
+ _slots[i].SequenceNumber = i;
+ }
}
- /// <summary>
- /// Create a new segment and append to the current one
- /// Update the m_tail pointer
- /// This method is called when there is no contention
- /// </summary>
- internal void Grow()
- {
- //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;
- Debug.Assert(m_source.m_tail == this);
- m_source.m_tail = m_next;
- }
+ /// <summary>Gets the number of elements this segment can store.</summary>
+ internal int Capacity => _slots.Length;
+ /// <summary>Gets the "freeze offset" for this segment.</summary>
+ internal int FreezeOffset => _slots.Length * 2;
/// <summary>
- /// Try to append an element at the end of this segment.
+ /// Ensures that the segment will not accept any subsequent enqueues that aren't already underway.
/// </summary>
- /// <param name="value">the element to append</param>
- /// <param name="tail">The tail.</param>
- /// <returns>true if the element is appended, false if the current segment is full</returns>
- /// <remarks>if appending the specified element succeeds, and after which the segment is full,
- /// then grow the segment</remarks>
- internal bool TryAppend(T value)
+ /// <remarks>
+ /// When we mark a segment as being frozen for additional enqueues,
+ /// we set the <see cref="_frozenForEnqueues"/> bool, but that's mostly
+ /// as a small helper to avoid marking it twice. The real marking comes
+ /// by modifying the Tail for the segment, increasing it by this
+ /// <see cref="FreezeOffset"/>. This effectively knocks it off the
+ /// sequence expected by future enqueuers, such that any additional enqueuer
+ /// will be unable to enqueue due to it not lining up with the expected
+ /// sequence numbers. This value is chosen specially so that Tail will grow
+ /// to a value that maps to the same slot but that won't be confused with
+ /// any other enqueue/dequeue sequence number.
+ /// </remarks>
+ internal void EnsureFrozenForEnqueues() // must only be called while queue's segment lock is held
{
- //quickly check if m_high is already over the boundary, if so, bail out
- if (m_high >= SEGMENT_SIZE - 1)
+ if (!_frozenForEnqueues) // flag used to ensure we don't increase the Tail more than once if frozen more than once
{
- return false;
- }
+ _frozenForEnqueues = true;
- //Now we will use a CAS to increment m_high, and store the result in newhigh.
- //Depending on how many free spots left in this segment and how many threads are doing this Increment
- //at this time, the returning "newhigh" can be
- // 1) < SEGMENT_SIZE - 1 : we took a spot in this segment, and not the last one, just insert the value
- // 2) == SEGMENT_SIZE - 1 : we took the last spot, insert the value AND grow the segment
- // 3) > SEGMENT_SIZE - 1 : we failed to reserve a spot in this segment, we return false to
- // Queue.Enqueue method, telling it to try again in the next segment.
-
- int newhigh = SEGMENT_SIZE; //initial value set to be over the boundary
-
- //We need do Interlocked.Increment and value/state update in a finally block to ensure that they run
- //without interuption. This is to prevent anything from happening between them, and another dequeue
- //thread maybe spinning forever to wait for m_state[] to be true;
- try
- { }
- finally
- {
- newhigh = Interlocked.Increment(ref m_high);
- if (newhigh <= SEGMENT_SIZE - 1)
+ // Increase the tail by FreezeOffset, spinning until we're successful in doing so.
+ var spinner = new SpinWait();
+ while (true)
{
- m_array[newhigh] = value;
- m_state[newhigh].m_value = true;
- }
-
- //if this thread takes up the last slot in the segment, then this thread is responsible
- //to grow a new segment. Calling Grow must be in the finally block too for reliability reason:
- //if thread abort during Grow, other threads will be left busy spinning forever.
- if (newhigh == SEGMENT_SIZE - 1)
- {
- Grow();
+ int tail = Volatile.Read(ref _headAndTail.Tail);
+ if (Interlocked.CompareExchange(ref _headAndTail.Tail, tail + FreezeOffset, tail) == tail)
+ {
+ break;
+ }
+ spinner.SpinOnce();
}
}
-
- //if newhigh <= SEGMENT_SIZE-1, it means the current thread successfully takes up a spot
- return newhigh <= SEGMENT_SIZE - 1;
}
-
- /// <summary>
- /// try to remove an element from the head of current segment
- /// </summary>
- /// <param name="result">The result.</param>
- /// <param name="head">The head.</param>
- /// <returns>return false only if the current segment is empty</returns>
- internal bool TryRemove(out T result)
+ /// <summary>Tries to dequeue an element from the queue.</summary>
+ public bool TryDequeue(out T item)
{
- SpinWait spin = new SpinWait();
- int lowLocal = Low, highLocal = High;
- while (lowLocal <= highLocal)
+ // Loop in case of contention...
+ var spinner = new SpinWait();
+ while (true)
{
- //try to update m_low
- if (Interlocked.CompareExchange(ref m_low, lowLocal + 1, lowLocal) == lowLocal)
- {
- //if the specified value is not available (this spot is taken by a push operation,
- // but the value is not written into yet), then spin
- SpinWait spinLocal = new SpinWait();
- while (!m_state[lowLocal].m_value)
- {
- spinLocal.SpinOnce();
- }
- result = m_array[lowLocal];
+ // Get the head at which to try to dequeue.
+ int currentHead = Volatile.Read(ref _headAndTail.Head);
+ int slotsIndex = currentHead & _slotsMask;
- // If there is no other thread taking snapshot (GetEnumerator(), ToList(), etc), reset the deleted entry to null.
- // It is ok if after this conditional check m_numSnapshotTakers becomes > 0, because new snapshots won't include
- // the deleted entry at m_array[lowLocal].
- if (m_source.m_numSnapshotTakers <= 0)
- {
- m_array[lowLocal] = default(T); //release the reference to the object.
- }
+ // Read the sequence number for the head position.
+ int sequenceNumber = Volatile.Read(ref _slots[slotsIndex].SequenceNumber);
- //if the current thread sets m_low to SEGMENT_SIZE, which means the current segment becomes
- //disposable, then this thread is responsible to dispose this segment, and reset m_head
- if (lowLocal + 1 >= SEGMENT_SIZE)
+ // We can dequeue from this slot if it's been filled by an enqueuer, which
+ // would have left the sequence number at pos+1.
+ int diff = sequenceNumber - (currentHead + 1);
+ if (diff == 0)
+ {
+ // We may be racing with other dequeuers. Try to reserve the slot by incrementing
+ // the head. Once we've done that, no one else will be able to read from this slot,
+ // and no enqueuer will be able to read from this slot until we've written the new
+ // sequence number. WARNING: The next few lines are not reliable on a runtime that
+ // supports thread aborts. If a thread abort were to sneak in after the CompareExchange
+ // but before the Volatile.Write, enqueuers trying to enqueue into this slot would
+ // spin indefinitely. If this implementation is ever used on such a platform, this
+ // if block should be wrapped in a finally / prepared region.
+ if (Interlocked.CompareExchange(ref _headAndTail.Head, currentHead + 1, currentHead) == currentHead)
{
- // Invariant: we only dispose the current m_head, not any other segment
- // In usual situation, disposing a segment is simply seting m_head to m_head.m_next
- // But there is one special case, where m_head and m_tail points to the same and ONLY
- //segment of the queue: Another thread A is doing Enqueue and finds that it needs to grow,
- //while the *current* thread is doing *this* Dequeue operation, and finds that it needs to
- //dispose the current (and ONLY) segment. Then we need to wait till thread A finishes its
- //Grow operation, this is the reason of having the following while loop
- spinLocal = new SpinWait();
- while (m_next == null)
+ // Successfully reserved the slot. Note that after the above CompareExchange, other threads
+ // trying to dequeue from this slot will end up spinning until we do the subsequent Write.
+ item = _slots[slotsIndex].Item;
+ if (!Volatile.Read(ref _preservedForObservation))
{
- spinLocal.SpinOnce();
+ // If we're preserving, though, we don't zero out the slot, as we need it for
+ // enumerations, peeking, ToArray, etc. And we don't update the sequence number,
+ // so that an enqueuer will see it as full and be forced to move to a new segment.
+ _slots[slotsIndex].Item = default(T);
+ Volatile.Write(ref _slots[slotsIndex].SequenceNumber, currentHead + _slots.Length);
}
- Debug.Assert(m_source.m_head == this);
- m_source.m_head = m_next;
+ return true;
}
- return true;
}
- else
+ else if (diff < 0)
{
- //CAS failed due to contention: spin briefly and retry
- spin.SpinOnce();
- lowLocal = Low; highLocal = High;
+ // The sequence number was less than what we needed, which means this slot doesn't
+ // yet contain a value we can dequeue, i.e. the segment is empty. Technically it's
+ // possible that multiple enqueuers could have written concurrently, with those
+ // getting later slots actually finishing first, so there could be elements after
+ // this one that are available, but we need to dequeue in order. So before declaring
+ // failure and that the segment is empty, we check the tail to see if we're actually
+ // empty or if we're just waiting for items in flight or after this one to become available.
+ bool frozen = _frozenForEnqueues;
+ int currentTail = Volatile.Read(ref _headAndTail.Tail);
+ if (currentTail - currentHead <= 0 || (frozen && (currentTail - FreezeOffset - currentHead <= 0)))
+ {
+ item = default(T);
+ return false;
+ }
+
+ // It's possible it could have become frozen after we checked _frozenForEnqueues
+ // and before reading the tail. That's ok: in that rare race condition, we just
+ // loop around again.
}
- }//end of while
- result = default(T);
- return false;
+
+ // Lost a race. Spin a bit, then try again.
+ spinner.SpinOnce();
+ }
}
- /// <summary>
- /// try to peek the current segment
- /// </summary>
- /// <param name="result">holds the return value of the element at the head position,
- /// value set to default(T) if there is no such an element</param>
- /// <returns>true if there are elements in the current segment, false otherwise</returns>
- internal bool TryPeek(out T result)
+ /// <summary>Tries to peek at an element from the queue, without removing it.</summary>
+ public bool TryPeek(out T result, bool resultUsed)
{
- result = default(T);
- int lowLocal = Low;
- if (lowLocal > High)
- return false;
- SpinWait spin = new SpinWait();
- while (!m_state[lowLocal].m_value)
+ if (resultUsed)
{
- spin.SpinOnce();
+ // In order to ensure we don't get a torn read on the value, we mark the segment
+ // as preserving for observation. Additional items can still be enqueued to this
+ // segment, but no space will be freed during dequeues, such that the segment will
+ // no longer be reusable.
+ _preservedForObservation = true;
+ Interlocked.MemoryBarrier();
}
- result = m_array[lowLocal];
- return true;
- }
- /// <summary>
- /// Adds part or all of the current segment into a List.
- /// </summary>
- /// <param name="list">the list to which to add</param>
- /// <param name="start">the start position</param>
- /// <param name="end">the end position</param>
- internal void AddToList(List<T> list, int start, int end)
- {
- for (int i = start; i <= end; i++)
+ // Loop in case of contention...
+ var spinner = new SpinWait();
+ while (true)
{
- SpinWait spin = new SpinWait();
- while (!m_state[i].m_value)
+ // Get the head at which to try to peek.
+ int currentHead = Volatile.Read(ref _headAndTail.Head);
+ int slotsIndex = currentHead & _slotsMask;
+
+ // Read the sequence number for the head position.
+ int sequenceNumber = Volatile.Read(ref _slots[slotsIndex].SequenceNumber);
+
+ // We can peek from this slot if it's been filled by an enqueuer, which
+ // would have left the sequence number at pos+1.
+ int diff = sequenceNumber - (currentHead + 1);
+ if (diff == 0)
{
- spin.SpinOnce();
+ result = resultUsed ? _slots[slotsIndex].Item : default(T);
+ return true;
+ }
+ else if (diff < 0)
+ {
+ // The sequence number was less than what we needed, which means this slot doesn't
+ // yet contain a value we can peek, i.e. the segment is empty. Technically it's
+ // possible that multiple enqueuers could have written concurrently, with those
+ // getting later slots actually finishing first, so there could be elements after
+ // this one that are available, but we need to peek in order. So before declaring
+ // failure and that the segment is empty, we check the tail to see if we're actually
+ // empty or if we're just waiting for items in flight or after this one to become available.
+ bool frozen = _frozenForEnqueues;
+ int currentTail = Volatile.Read(ref _headAndTail.Tail);
+ if (currentTail - currentHead <= 0 || (frozen && (currentTail - FreezeOffset - currentHead <= 0)))
+ {
+ result = default(T);
+ return false;
+ }
+
+ // It's possible it could have become frozen after we checked _frozenForEnqueues
+ // and before reading the tail. That's ok: in that rare race condition, we just
+ // loop around again.
}
- list.Add(m_array[i]);
+
+ // Lost a race. Spin a bit, then try again.
+ spinner.SpinOnce();
}
}
/// <summary>
- /// return the position of the head of the current segment
- /// Value range [0, SEGMENT_SIZE], if it's SEGMENT_SIZE, it means this segment is exhausted and thus empty
+ /// Attempts to enqueue the item. If successful, the item will be stored
+ /// in the queue and true will be returned; otherwise, the item won't be stored, and false
+ /// will be returned.
/// </summary>
- internal int Low
+ public bool TryEnqueue(T item)
{
- get
+ // Loop in case of contention...
+ var spinner = new SpinWait();
+ while (true)
{
- return Math.Min(m_low, SEGMENT_SIZE);
+ // Get the tail at which to try to return.
+ int currentTail = Volatile.Read(ref _headAndTail.Tail);
+ int slotsIndex = currentTail & _slotsMask;
+
+ // Read the sequence number for the tail position.
+ int sequenceNumber = Volatile.Read(ref _slots[slotsIndex].SequenceNumber);
+
+ // The slot is empty and ready for us to enqueue into it if its sequence
+ // number matches the slot.
+ int diff = sequenceNumber - currentTail;
+ if (diff == 0)
+ {
+ // We may be racing with other enqueuers. Try to reserve the slot by incrementing
+ // the tail. Once we've done that, no one else will be able to write to this slot,
+ // and no dequeuer will be able to read from this slot until we've written the new
+ // sequence number. WARNING: The next few lines are not reliable on a runtime that
+ // supports thread aborts. If a thread abort were to sneak in after the CompareExchange
+ // but before the Volatile.Write, other threads will spin trying to access this slot.
+ // If this implementation is ever used on such a platform, this if block should be
+ // wrapped in a finally / prepared region.
+ if (Interlocked.CompareExchange(ref _headAndTail.Tail, currentTail + 1, currentTail) == currentTail)
+ {
+ // Successfully reserved the slot. Note that after the above CompareExchange, other threads
+ // trying to return will end up spinning until we do the subsequent Write.
+ _slots[slotsIndex].Item = item;
+ Volatile.Write(ref _slots[slotsIndex].SequenceNumber, currentTail + 1);
+ return true;
+ }
+ }
+ else if (diff < 0)
+ {
+ // The sequence number was less than what we needed, which means this slot still
+ // contains a value, i.e. the segment is full. Technically it's possible that multiple
+ // dequeuers could have read concurrently, with those getting later slots actually
+ // finishing first, so there could be spaces after this one that are available, but
+ // we need to enqueue in order.
+ return false;
+ }
+
+ // Lost a race. Spin a bit, then try again.
+ spinner.SpinOnce();
}
}
- /// <summary>
- /// return the logical position of the tail of the current segment
- /// Value range [-1, SEGMENT_SIZE-1]. When it's -1, it means this is a new segment and has no elemnet yet
- /// </summary>
- internal int High
+ /// <summary>Represents a slot in the queue.</summary>
+ [StructLayout(LayoutKind.Auto)]
+ [DebuggerDisplay("Item = {Item}, SequenceNumber = {SequenceNumber}")]
+ internal struct Slot
{
- get
- {
- //if m_high > SEGMENT_SIZE, it means it's out of range, we should return
- //SEGMENT_SIZE-1 as the logical position
- return Math.Min(m_high, SEGMENT_SIZE - 1);
- }
+ /// <summary>The item.</summary>
+ public T Item;
+ /// <summary>The sequence number for this slot, used to synchronize between enqueuers and dequeuers.</summary>
+ public int SequenceNumber;
}
-
}
- }//end of class Segment
+ }
- /// <summary>
- /// A wrapper struct for volatile bool, please note the copy of the struct it self will not be volatile
- /// for example this statement will not include in volatilness operation volatileBool1 = volatileBool2 the jit will copy the struct and will ignore the volatile
- /// </summary>
- struct VolatileBool
+ /// <summary>Padded head and tail indices, to avoid false sharing between producers and consumers.</summary>
+ [DebuggerDisplay("Head = {Head}, Tail = {Tail}")]
+ [StructLayout(LayoutKind.Explicit, Size = 192)] // padding before/between/after fields based on typical cache line size of 64
+ internal struct PaddedHeadAndTail
{
- public VolatileBool(bool value)
- {
- m_value = value;
- }
- public volatile bool m_value;
+ [FieldOffset(64)] public int Head;
+ [FieldOffset(128)] public int Tail;
}
}
diff --git a/src/mscorlib/src/System/Collections/Concurrent/ConcurrentStack.cs b/src/mscorlib/src/System/Collections/Concurrent/ConcurrentStack.cs
index c36d96c26c..10a5201f6c 100644
--- a/src/mscorlib/src/System/Collections/Concurrent/ConcurrentStack.cs
+++ b/src/mscorlib/src/System/Collections/Concurrent/ConcurrentStack.cs
@@ -20,7 +20,6 @@ using System.Diagnostics.Contracts;
using System.Runtime.ConstrainedExecution;
using System.Runtime.Serialization;
using System.Security;
-using System.Security.Permissions;
using System.Threading;
namespace System.Collections.Concurrent
@@ -45,7 +44,7 @@ namespace System.Collections.Concurrent
/// </remarks>
[DebuggerDisplay("Count = {Count}")]
[DebuggerTypeProxy(typeof(SystemCollectionsConcurrent_ProducerConsumerCollectionDebugView<>))]
- public class ConcurrentStack<T> : IProducerConsumerCollection<T>, IReadOnlyCollection<T>
+ internal class ConcurrentStack<T> : IProducerConsumerCollection<T>, IReadOnlyCollection<T>
{
/// <summary>
/// A simple (internal) node type used to store elements of concurrent stacks and queues.
@@ -79,61 +78,6 @@ namespace System.Collections.Concurrent
}
/// <summary>
- /// Initializes a new instance of the <see cref="ConcurrentStack{T}"/>
- /// class that contains elements copied from the specified collection
- /// </summary>
- /// <param name="collection">The collection whose elements are copied to the new <see
- /// cref="ConcurrentStack{T}"/>.</param>
- /// <exception cref="T:System.ArgumentNullException">The <paramref name="collection"/> argument is
- /// null.</exception>
- public ConcurrentStack(IEnumerable<T> collection)
- {
- if (collection == null)
- {
- throw new ArgumentNullException(nameof(collection));
- }
- InitializeFromCollection(collection);
- }
-
- /// <summary>
- /// Initializes the contents of the stack from an existing collection.
- /// </summary>
- /// <param name="collection">A collection from which to copy elements.</param>
- private void InitializeFromCollection(IEnumerable<T> collection)
- {
- // We just copy the contents of the collection to our stack.
- Node lastNode = null;
- foreach (T element in collection)
- {
- Node newNode = new Node(element);
- newNode.m_next = lastNode;
- lastNode = newNode;
- }
-
- m_head = lastNode;
- }
-
- /// <summary>
- /// Gets a value that indicates whether the <see cref="ConcurrentStack{T}"/> is empty.
- /// </summary>
- /// <value>true if the <see cref="ConcurrentStack{T}"/> is empty; otherwise, false.</value>
- /// <remarks>
- /// For determining whether the collection contains any items, use of this property is recommended
- /// rather than retrieving the number of items from the <see cref="Count"/> property and comparing it
- /// to 0. However, as this collection is intended to be accessed concurrently, it may be the case
- /// that another thread will modify the collection after <see cref="IsEmpty"/> returns, thus invalidating
- /// the result.
- /// </remarks>
- public bool IsEmpty
- {
- // Checks whether the stack is empty. Clearly the answer may be out of date even prior to
- // the function returning (i.e. if another thread concurrently adds to the stack). It does
- // guarantee, however, that, if another thread does not mutate the stack, a subsequent call
- // to TryPop will return true -- i.e. it will also read the stack as non-empty.
- get { return m_head == null; }
- }
-
- /// <summary>
/// Gets the number of elements contained in the <see cref="ConcurrentStack{T}"/>.
/// </summary>
/// <value>The number of elements contained in the <see cref="ConcurrentStack{T}"/>.</value>
@@ -196,18 +140,6 @@ namespace System.Collections.Concurrent
}
/// <summary>
- /// Removes all objects from the <see cref="ConcurrentStack{T}"/>.
- /// </summary>
- public void Clear()
- {
- // Clear the list by setting the head to null. We don't need to use an atomic
- // operation for this: anybody who is mutating the head by pushing or popping
- // will need to use an atomic operation to guarantee they serialize and don't
- // overwrite our setting of the head to null.
- m_head = null;
- }
-
- /// <summary>
/// Copies the elements of the <see cref="T:System.Collections.ICollection"/> to an <see
/// cref="T:System.Array"/>, starting at a particular
/// <see cref="T:System.Array"/> index.
@@ -306,79 +238,6 @@ namespace System.Collections.Concurrent
PushCore(newNode, newNode);
}
- /// <summary>
- /// Inserts multiple objects at the top of the <see cref="ConcurrentStack{T}"/> atomically.
- /// </summary>
- /// <param name="items">The objects to push onto the <see cref="ConcurrentStack{T}"/>.</param>
- /// <exception cref="ArgumentNullException"><paramref name="items"/> is a null reference
- /// (Nothing in Visual Basic).</exception>
- /// <remarks>
- /// When adding multiple items to the stack, using PushRange is a more efficient
- /// mechanism than using <see cref="Push"/> one item at a time. Additionally, PushRange
- /// guarantees that all of the elements will be added atomically, meaning that no other threads will
- /// be able to inject elements between the elements being pushed. Items at lower indices in
- /// the <paramref name="items"/> array will be pushed before items at higher indices.
- /// </remarks>
- public void PushRange(T[] items)
- {
- if (items == null)
- {
- throw new ArgumentNullException(nameof(items));
- }
- PushRange(items, 0, items.Length);
- }
-
- /// <summary>
- /// Inserts multiple objects at the top of the <see cref="ConcurrentStack{T}"/> atomically.
- /// </summary>
- /// <param name="items">The objects to push onto the <see cref="ConcurrentStack{T}"/>.</param>
- /// <param name="startIndex">The zero-based offset in <paramref name="items"/> at which to begin
- /// inserting elements onto the top of the <see cref="ConcurrentStack{T}"/>.</param>
- /// <param name="count">The number of elements to be inserted onto the top of the <see
- /// cref="ConcurrentStack{T}"/>.</param>
- /// <exception cref="ArgumentNullException"><paramref name="items"/> is a null reference
- /// (Nothing in Visual Basic).</exception>
- /// <exception cref="ArgumentOutOfRangeException"><paramref name="startIndex"/> or <paramref
- /// name="count"/> is negative. Or <paramref name="startIndex"/> is greater than or equal to the length
- /// of <paramref name="items"/>.</exception>
- /// <exception cref="ArgumentException"><paramref name="startIndex"/> + <paramref name="count"/> is
- /// greater than the length of <paramref name="items"/>.</exception>
- /// <remarks>
- /// When adding multiple items to the stack, using PushRange is a more efficient
- /// mechanism than using <see cref="Push"/> one item at a time. Additionally, PushRange
- /// guarantees that all of the elements will be added atomically, meaning that no other threads will
- /// be able to inject elements between the elements being pushed. Items at lower indices in the
- /// <paramref name="items"/> array will be pushed before items at higher indices.
- /// </remarks>
- public void PushRange(T[] items, int startIndex, int count)
- {
- ValidatePushPopRangeInput(items, startIndex, count);
-
- // No op if the count is zero
- if (count == 0)
- return;
-
-
- Node head, tail;
- head = tail = new Node(items[startIndex]);
- for (int i = startIndex + 1; i < startIndex + count; i++)
- {
- Node node = new Node(items[i]);
- node.m_next = head;
- head = node;
- }
-
- tail.m_next = m_head;
- if (Interlocked.CompareExchange(ref m_head, head, tail.m_next) == tail.m_next)
- {
- return;
- }
-
- // If we failed, go to the slow path and loop around until we succeed.
- PushCore(head, tail);
-
- }
-
/// <summary>
/// Push one or many nodes into the stack, if head and tails are equal then push one node to the stack other wise push the list between head
@@ -402,73 +261,6 @@ namespace System.Collections.Concurrent
}
/// <summary>
- /// Local helper function to validate the Pop Push range methods input
- /// </summary>
- private void ValidatePushPopRangeInput(T[] items, int startIndex, int count)
- {
- if (items == null)
- {
- throw new ArgumentNullException(nameof(items));
- }
- if (count < 0)
- {
- throw new ArgumentOutOfRangeException(nameof(count), Environment.GetResourceString("ConcurrentStack_PushPopRange_CountOutOfRange"));
- }
- int length = items.Length;
- if (startIndex >= length || startIndex < 0)
- {
- throw new ArgumentOutOfRangeException(nameof(startIndex), Environment.GetResourceString("ConcurrentStack_PushPopRange_StartOutOfRange"));
- }
- if (length - count < startIndex) //instead of (startIndex + count > items.Length) to prevent overflow
- {
- throw new ArgumentException(Environment.GetResourceString("ConcurrentStack_PushPopRange_InvalidCount"));
- }
- }
-
- /// <summary>
- /// Attempts to add an object to the <see
- /// cref="T:System.Collections.Concurrent.IProducerConsumerCollection{T}"/>.
- /// </summary>
- /// <param name="item">The object to add to the <see
- /// cref="T:System.Collections.Concurrent.IProducerConsumerCollection{T}"/>. The value can be a null
- /// reference (Nothing in Visual Basic) for reference types.
- /// </param>
- /// <returns>true if the object was added successfully; otherwise, false.</returns>
- /// <remarks>For <see cref="ConcurrentStack{T}"/>, this operation
- /// will always insert the object onto the top of the <see cref="ConcurrentStack{T}"/>
- /// and return true.</remarks>
- bool IProducerConsumerCollection<T>.TryAdd(T item)
- {
- Push(item);
- return true;
- }
-
- /// <summary>
- /// Attempts to return an object from the top of the <see cref="ConcurrentStack{T}"/>
- /// without removing it.
- /// </summary>
- /// <param name="result">When this method returns, <paramref name="result"/> contains an object from
- /// the top of the <see cref="T:System.Collections.Concurrent.ConccurrentStack{T}"/> or an
- /// unspecified value if the operation failed.</param>
- /// <returns>true if and object was returned successfully; otherwise, false.</returns>
- public bool TryPeek(out T result)
- {
- Node head = m_head;
-
- // If the stack is empty, return false; else return the element and true.
- if (head == null)
- {
- result = default(T);
- return false;
- }
- else
- {
- result = head.m_value;
- return true;
- }
- }
-
- /// <summary>
/// Attempts to pop and return the object at the top of the <see cref="ConcurrentStack{T}"/>.
/// </summary>
/// <param name="result">
@@ -498,83 +290,6 @@ namespace System.Collections.Concurrent
}
/// <summary>
- /// Attempts to pop and return multiple objects from the top of the <see cref="ConcurrentStack{T}"/>
- /// atomically.
- /// </summary>
- /// <param name="items">
- /// The <see cref="T:System.Array"/> to which objects popped from the top of the <see
- /// cref="ConcurrentStack{T}"/> will be added.
- /// </param>
- /// <returns>The number of objects successfully popped from the top of the <see
- /// cref="ConcurrentStack{T}"/> and inserted in
- /// <paramref name="items"/>.</returns>
- /// <exception cref="ArgumentNullException"><paramref name="items"/> is a null argument (Nothing
- /// in Visual Basic).</exception>
- /// <remarks>
- /// When popping multiple items, if there is little contention on the stack, using
- /// TryPopRange can be more efficient than using <see cref="TryPop"/>
- /// once per item to be removed. Nodes fill the <paramref name="items"/>
- /// with the first node to be popped at the startIndex, the second node to be popped
- /// at startIndex + 1, and so on.
- /// </remarks>
- public int TryPopRange(T[] items)
- {
- if (items == null)
- {
- throw new ArgumentNullException(nameof(items));
- }
-
- return TryPopRange(items, 0, items.Length);
- }
-
- /// <summary>
- /// Attempts to pop and return multiple objects from the top of the <see cref="ConcurrentStack{T}"/>
- /// atomically.
- /// </summary>
- /// <param name="items">
- /// The <see cref="T:System.Array"/> to which objects popped from the top of the <see
- /// cref="ConcurrentStack{T}"/> will be added.
- /// </param>
- /// <param name="startIndex">The zero-based offset in <paramref name="items"/> at which to begin
- /// inserting elements from the top of the <see cref="ConcurrentStack{T}"/>.</param>
- /// <param name="count">The number of elements to be popped from top of the <see
- /// cref="ConcurrentStack{T}"/> and inserted into <paramref name="items"/>.</param>
- /// <returns>The number of objects successfully popped from the top of
- /// the <see cref="ConcurrentStack{T}"/> and inserted in <paramref name="items"/>.</returns>
- /// <exception cref="ArgumentNullException"><paramref name="items"/> is a null reference
- /// (Nothing in Visual Basic).</exception>
- /// <exception cref="ArgumentOutOfRangeException"><paramref name="startIndex"/> or <paramref
- /// name="count"/> is negative. Or <paramref name="startIndex"/> is greater than or equal to the length
- /// of <paramref name="items"/>.</exception>
- /// <exception cref="ArgumentException"><paramref name="startIndex"/> + <paramref name="count"/> is
- /// greater than the length of <paramref name="items"/>.</exception>
- /// <remarks>
- /// When popping multiple items, if there is little contention on the stack, using
- /// TryPopRange can be more efficient than using <see cref="TryPop"/>
- /// once per item to be removed. Nodes fill the <paramref name="items"/>
- /// with the first node to be popped at the startIndex, the second node to be popped
- /// at startIndex + 1, and so on.
- /// </remarks>
- public int TryPopRange(T[] items, int startIndex, int count)
- {
- ValidatePushPopRangeInput(items, startIndex, count);
-
- // No op if the count is zero
- if (count == 0)
- return 0;
-
- Node poppedHead;
- int nodesCount = TryPopCore(count, out poppedHead);
- if (nodesCount > 0)
- {
- CopyRemovedItems(poppedHead, items, startIndex, nodesCount);
-
- }
- return nodesCount;
-
- }
-
- /// <summary>
/// Local helper function to Pop an item from the stack, slow path
/// </summary>
/// <param name="result">The popped item</param>
@@ -648,42 +363,6 @@ namespace System.Collections.Concurrent
}
}
-
- /// <summary>
- /// Local helper function to copy the poped elements into a given collection
- /// </summary>
- /// <param name="head">The head of the list to be copied</param>
- /// <param name="collection">The collection to place the popped items in</param>
- /// <param name="startIndex">the beginning of index of where to place the popped items</param>
- /// <param name="nodesCount">The number of nodes.</param>
- private void CopyRemovedItems(Node head, T[] collection, int startIndex, int nodesCount)
- {
- Node current = head;
- for (int i = startIndex; i < startIndex + nodesCount; i++)
- {
- collection[i] = current.m_value;
- current = current.m_next;
- }
-
- }
-
- /// <summary>
- /// Attempts to remove and return an object from the <see
- /// cref="T:System.Collections.Concurrent.IProducerConsumerCollection{T}"/>.
- /// </summary>
- /// <param name="item">
- /// When this method returns, if the operation was successful, <paramref name="item"/> contains the
- /// object removed. If no object was available to be removed, the value is unspecified.
- /// </param>
- /// <returns>true if an element was removed and returned succesfully; otherwise, false.</returns>
- /// <remarks>For <see cref="ConcurrentStack{T}"/>, this operation will attempt to pope the object at
- /// the top of the <see cref="ConcurrentStack{T}"/>.
- /// </remarks>
- bool IProducerConsumerCollection<T>.TryTake(out T item)
- {
- return TryPop(out item);
- }
-
/// <summary>
/// Copies the items stored in the <see cref="ConcurrentStack{T}"/> to a new array.
/// </summary>
diff --git a/src/mscorlib/src/System/Collections/Concurrent/IProducerConsumerCollection.cs b/src/mscorlib/src/System/Collections/Concurrent/IProducerConsumerCollection.cs
index 56be7759c9..0347ece0ec 100644
--- a/src/mscorlib/src/System/Collections/Concurrent/IProducerConsumerCollection.cs
+++ b/src/mscorlib/src/System/Collections/Concurrent/IProducerConsumerCollection.cs
@@ -25,9 +25,8 @@ namespace System.Collections.Concurrent
/// All implementations of this interface must enable all members of this interface
/// to be used concurrently from multiple threads.
/// </remarks>
- public interface IProducerConsumerCollection<T> : IEnumerable<T>, ICollection
+ internal interface IProducerConsumerCollection<T> : IEnumerable<T>, ICollection
{
-
/// <summary>
/// Copies the elements of the <see cref="IProducerConsumerCollection{T}"/> to
/// an
@@ -51,35 +50,12 @@ namespace System.Collections.Concurrent
void CopyTo(T[] array, int index);
/// <summary>
- /// Attempts to add an object to the <see
- /// cref="IProducerConsumerCollection{T}"/>.
- /// </summary>
- /// <param name="item">The object to add to the <see
- /// cref="IProducerConsumerCollection{T}"/>.</param>
- /// <returns>true if the object was added successfully; otherwise, false.</returns>
- /// <exception cref="T:System.ArgumentException">The <paramref name="item"/> was invalid for this collection.</exception>
- bool TryAdd(T item);
-
- /// <summary>
- /// Attempts to remove and return an object from the <see cref="IProducerConsumerCollection{T}"/>.
- /// </summary>
- /// <param name="item">
- /// When this method returns, if the object was removed and returned successfully, <paramref
- /// name="item"/> contains the removed object. If no object was available to be removed, the value is
- /// unspecified.
- /// </param>
- /// <returns>true if an object was removed and returned successfully; otherwise, false.</returns>
- bool TryTake(out T item);
-
- /// <summary>
/// Copies the elements contained in the <see cref="IProducerConsumerCollection{T}"/> to a new array.
/// </summary>
/// <returns>A new array containing the elements copied from the <see cref="IProducerConsumerCollection{T}"/>.</returns>
T[] ToArray();
-
}
-
/// <summary>
/// A debugger view of the IProducerConsumerCollection that makes it simple to browse the
/// collection's contents at a point in time.
@@ -89,28 +65,5 @@ namespace System.Collections.Concurrent
{
private IProducerConsumerCollection<T> m_collection; // The collection being viewed.
- /// <summary>
- /// Constructs a new debugger view object for the provided collection object.
- /// </summary>
- /// <param name="collection">A collection to browse in the debugger.</param>
- public SystemCollectionsConcurrent_ProducerConsumerCollectionDebugView(IProducerConsumerCollection<T> collection)
- {
- if (collection == null)
- {
- throw new ArgumentNullException(nameof(collection));
- }
-
- m_collection = collection;
- }
-
- /// <summary>
- /// Returns a snapshot of the underlying collection's elements.
- /// </summary>
- [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)]
- public T[] Items
- {
- get { return m_collection.ToArray(); }
- }
-
}
}
diff --git a/src/mscorlib/src/System/Collections/Concurrent/OrderablePartitioner.cs b/src/mscorlib/src/System/Collections/Concurrent/OrderablePartitioner.cs
deleted file mode 100644
index 33e3c88e9a..0000000000
--- a/src/mscorlib/src/System/Collections/Concurrent/OrderablePartitioner.cs
+++ /dev/null
@@ -1,280 +0,0 @@
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-// See the LICENSE file in the project root for more information.
-
-// =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+
-//
-//
-//
-//
-//
-// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
-
-using System;
-using System.Collections.Generic;
-using System.Security.Permissions;
-using System.Threading;
-
-namespace System.Collections.Concurrent
-{
-
- /// <summary>
- /// Represents a particular manner of splitting an orderable data source into multiple partitions.
- /// </summary>
- /// <typeparam name="TSource">Type of the elements in the collection.</typeparam>
- /// <remarks>
- /// <para>
- /// Each element in each partition has an integer index associated with it, which determines the relative
- /// order of that element against elements in other partitions.
- /// </para>
- /// <para>
- /// Inheritors of <see cref="OrderablePartitioner{TSource}"/> must adhere to the following rules:
- /// <ol>
- /// <li>All indices must be unique, such that there may not be duplicate indices. If all indices are not
- /// unique, the output ordering may be scrambled.</li>
- /// <li>All indices must be non-negative. If any indices are negative, consumers of the implementation
- /// may throw exceptions.</li>
- /// <li><see cref="GetPartitions"/> and <see cref="GetOrderablePartitions"/> should throw a
- /// <see cref="T:System.ArgumentOutOfRangeException"/> if the requested partition count is less than or
- /// equal to zero.</li>
- /// <li><see cref="GetPartitions"/> and <see cref="GetOrderablePartitions"/> should always return a number
- /// of enumerables equal to the requested partition count. If the partitioner runs out of data and cannot
- /// create as many partitions as requested, an empty enumerator should be returned for each of the
- /// remaining partitions. If this rule is not followed, consumers of the implementation may throw a <see
- /// cref="T:System.InvalidOperationException"/>.</li>
- /// <li><see cref="GetPartitions"/>, <see cref="GetOrderablePartitions"/>,
- /// <see cref="GetDynamicPartitions"/>, and <see cref="GetOrderableDynamicPartitions"/>
- /// should never return null. If null is returned, a consumer of the implementation may throw a
- /// <see cref="T:System.InvalidOperationException"/>.</li>
- /// <li><see cref="GetPartitions"/>, <see cref="GetOrderablePartitions"/>,
- /// <see cref="GetDynamicPartitions"/>, and <see cref="GetOrderableDynamicPartitions"/>
- /// should always return partitions that can fully and uniquely enumerate the input data source. All of
- /// the data and only the data contained in the input source should be enumerated, with no duplication
- /// that was not already in the input, unless specifically required by the particular partitioner's
- /// design. If this is not followed, the output ordering may be scrambled.</li>
- /// <li>If <see cref="KeysOrderedInEachPartition"/> returns true, each partition must return elements
- /// with increasing key indices.</li>
- /// <li>If <see cref="KeysOrderedAcrossPartitions"/> returns true, all the keys in partition numbered N
- /// must be larger than all the keys in partition numbered N-1.</li>
- /// <li>If <see cref="KeysNormalized"/> returns true, all indices must be monotonically increasing from
- /// 0, though not necessarily within a single partition.</li>
- /// </ol>
- /// </para>
- /// </remarks>
- public abstract class OrderablePartitioner<TSource> : Partitioner<TSource>
- {
- /// <summary>
- /// Initializes a new instance of the <see cref="OrderablePartitioner{TSource}"/> class with the
- /// specified constraints on the index keys.
- /// </summary>
- /// <param name="keysOrderedInEachPartition">
- /// Indicates whether the elements in each partition are yielded in the order of
- /// increasing keys.
- /// </param>
- /// <param name="keysOrderedAcrossPartitions">
- /// Indicates whether elements in an earlier partition always come before
- /// elements in a later partition. If true, each element in partition 0 has a smaller order key than
- /// any element in partition 1, each element in partition 1 has a smaller order key than any element
- /// in partition 2, and so on.
- /// </param>
- /// <param name="keysNormalized">
- /// Indicates whether keys are normalized. If true, all order keys are distinct
- /// integers in the range [0 .. numberOfElements-1]. If false, order keys must still be dictinct, but
- /// only their relative order is considered, not their absolute values.
- /// </param>
- protected OrderablePartitioner(bool keysOrderedInEachPartition, bool keysOrderedAcrossPartitions, bool keysNormalized)
- {
- KeysOrderedInEachPartition = keysOrderedInEachPartition;
- KeysOrderedAcrossPartitions = keysOrderedAcrossPartitions;
- KeysNormalized = keysNormalized;
- }
-
- /// <summary>
- /// Partitions the underlying collection into the specified number of orderable partitions.
- /// </summary>
- /// <remarks>
- /// Each partition is represented as an enumerator over key-value pairs.
- /// The value of the pair is the element itself, and the key is an integer which determines
- /// the relative ordering of this element against other elements in the data source.
- /// </remarks>
- /// <param name="partitionCount">The number of partitions to create.</param>
- /// <returns>A list containing <paramref name="partitionCount"/> enumerators.</returns>
- public abstract IList<IEnumerator<KeyValuePair<long, TSource>>> GetOrderablePartitions(int partitionCount);
-
- /// <summary>
- /// Creates an object that can partition the underlying collection into a variable number of
- /// partitions.
- /// </summary>
- /// <remarks>
- /// <para>
- /// The returned object implements the <see
- /// cref="T:System.Collections.Generic.IEnumerable{TSource}"/> interface. Calling <see
- /// cref="System.Collections.Generic.IEnumerable{TSource}.GetEnumerator">GetEnumerator</see> on the
- /// object creates another partition over the sequence.
- /// </para>
- /// <para>
- /// Each partition is represented as an enumerator over key-value pairs. The value in the pair is the element
- /// itself, and the key is an integer which determines the relative ordering of this element against
- /// other elements.
- /// </para>
- /// <para>
- /// The <see cref="GetOrderableDynamicPartitions"/> method is only supported if the <see
- /// cref="System.Collections.Concurrent.Partitioner{TSource}.SupportsDynamicPartitions">SupportsDynamicPartitions</see>
- /// property returns true.
- /// </para>
- /// </remarks>
- /// <returns>An object that can create partitions over the underlying data source.</returns>
- /// <exception cref="NotSupportedException">Dynamic partitioning is not supported by this
- /// partitioner.</exception>
- public virtual IEnumerable<KeyValuePair<long, TSource>> GetOrderableDynamicPartitions()
- {
- throw new NotSupportedException(Environment.GetResourceString("Partitioner_DynamicPartitionsNotSupported"));
- }
-
- /// <summary>
- /// Gets whether elements in each partition are yielded in the order of increasing keys.
- /// </summary>
- public bool KeysOrderedInEachPartition { get; private set; }
-
- /// <summary>
- /// Gets whether elements in an earlier partition always come before elements in a later partition.
- /// </summary>
- /// <remarks>
- /// If <see cref="KeysOrderedAcrossPartitions"/> returns true, each element in partition 0 has a
- /// smaller order key than any element in partition 1, each element in partition 1 has a smaller
- /// order key than any element in partition 2, and so on.
- /// </remarks>
- public bool KeysOrderedAcrossPartitions { get; private set; }
-
- /// <summary>
- /// Gets whether order keys are normalized.
- /// </summary>
- /// <remarks>
- /// If <see cref="KeysNormalized"/> returns true, all order keys are distinct integers in the range
- /// [0 .. numberOfElements-1]. If the property returns false, order keys must still be dictinct, but
- /// only their relative order is considered, not their absolute values.
- /// </remarks>
- public bool KeysNormalized { get; private set; }
-
- /// <summary>
- /// Partitions the underlying collection into the given number of ordered partitions.
- /// </summary>
- /// <remarks>
- /// The default implementation provides the same behavior as <see cref="GetOrderablePartitions"/> except
- /// that the returned set of partitions does not provide the keys for the elements.
- /// </remarks>
- /// <param name="partitionCount">The number of partitions to create.</param>
- /// <returns>A list containing <paramref name="partitionCount"/> enumerators.</returns>
- public override IList<IEnumerator<TSource>> GetPartitions(int partitionCount)
- {
- IList<IEnumerator<KeyValuePair<long, TSource>>> orderablePartitions = GetOrderablePartitions(partitionCount);
-
- if (orderablePartitions.Count != partitionCount)
- {
- throw new InvalidOperationException("OrderablePartitioner_GetPartitions_WrongNumberOfPartitions");
- }
-
- IEnumerator<TSource>[] partitions = new IEnumerator<TSource>[partitionCount];
- for (int i = 0; i < partitionCount; i++)
- {
- partitions[i] = new EnumeratorDropIndices(orderablePartitions[i]);
- }
- return partitions;
- }
-
- /// <summary>
- /// Creates an object that can partition the underlying collection into a variable number of
- /// partitions.
- /// </summary>
- /// <remarks>
- /// <para>
- /// The returned object implements the <see
- /// cref="T:System.Collections.Generic.IEnumerable{TSource}"/> interface. Calling <see
- /// cref="System.Collections.Generic.IEnumerable{TSource}.GetEnumerator">GetEnumerator</see> on the
- /// object creates another partition over the sequence.
- /// </para>
- /// <para>
- /// The default implementation provides the same behavior as <see cref="GetOrderableDynamicPartitions"/> except
- /// that the returned set of partitions does not provide the keys for the elements.
- /// </para>
- /// <para>
- /// The <see cref="GetDynamicPartitions"/> method is only supported if the <see
- /// cref="System.Collections.Concurrent.Partitioner{TSource}.SupportsDynamicPartitions"/>
- /// property returns true.
- /// </para>
- /// </remarks>
- /// <returns>An object that can create partitions over the underlying data source.</returns>
- /// <exception cref="NotSupportedException">Dynamic partitioning is not supported by this
- /// partitioner.</exception>
- public override IEnumerable<TSource> GetDynamicPartitions()
- {
- IEnumerable<KeyValuePair<long, TSource>> orderablePartitions = GetOrderableDynamicPartitions();
- return new EnumerableDropIndices(orderablePartitions);
- }
-
- /// <summary>
- /// Converts an enumerable over key-value pairs to an enumerable over values.
- /// </summary>
- private class EnumerableDropIndices : IEnumerable<TSource>, IDisposable
- {
- private readonly IEnumerable<KeyValuePair<long, TSource>> m_source;
- public EnumerableDropIndices(IEnumerable<KeyValuePair<long, TSource>> source)
- {
- m_source = source;
- }
- public IEnumerator<TSource> GetEnumerator()
- {
- return new EnumeratorDropIndices(m_source.GetEnumerator());
- }
- IEnumerator IEnumerable.GetEnumerator()
- {
- return ((EnumerableDropIndices)this).GetEnumerator();
- }
- public void Dispose()
- {
- IDisposable d = m_source as IDisposable;
- if (d != null)
- {
- d.Dispose();
- }
- }
- }
-
- private class EnumeratorDropIndices : IEnumerator<TSource>
- {
- private readonly IEnumerator<KeyValuePair<long, TSource>> m_source;
- public EnumeratorDropIndices(IEnumerator<KeyValuePair<long, TSource>> source)
- {
- m_source = source;
- }
- public bool MoveNext()
- {
- return m_source.MoveNext();
- }
- public TSource Current
- {
- get
- {
- return m_source.Current.Value;
- }
- }
- Object IEnumerator.Current
- {
- get
- {
- return ((EnumeratorDropIndices)this).Current;
- }
- }
- public void Dispose()
- {
- m_source.Dispose();
- }
- public void Reset()
- {
- m_source.Reset();
- }
- }
-
- }
-
-}
diff --git a/src/mscorlib/src/System/Collections/Concurrent/Partitioner.cs b/src/mscorlib/src/System/Collections/Concurrent/Partitioner.cs
deleted file mode 100644
index 0192b1942c..0000000000
--- a/src/mscorlib/src/System/Collections/Concurrent/Partitioner.cs
+++ /dev/null
@@ -1,101 +0,0 @@
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-// See the LICENSE file in the project root for more information.
-
-// =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+
-//
-//
-//
-// Represents a particular way of splitting a collection into multiple partitions.
-//
-// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
-
-using System;
-using System.Collections.Generic;
-using System.Security.Permissions;
-using System.Threading;
-
-namespace System.Collections.Concurrent
-{
- /// <summary>
- /// Represents a particular manner of splitting a data source into multiple partitions.
- /// </summary>
- /// <typeparam name="TSource">Type of the elements in the collection.</typeparam>
- /// <remarks>
- /// <para>
- /// Inheritors of <see cref="Partitioner{TSource}"/> must adhere to the following rules:
- /// <ol>
- /// <li><see cref="GetPartitions"/> should throw a
- /// <see cref="T:System.ArgumentOutOfRangeException"/> if the requested partition count is less than or
- /// equal to zero.</li>
- /// <li><see cref="GetPartitions"/> should always return a number of enumerables equal to the requested
- /// partition count. If the partitioner runs out of data and cannot create as many partitions as
- /// requested, an empty enumerator should be returned for each of the remaining partitions. If this rule
- /// is not followed, consumers of the implementation may throw a <see
- /// cref="T:System.InvalidOperationException"/>.</li>
- /// <li><see cref="GetPartitions"/> and <see cref="GetDynamicPartitions"/>
- /// should never return null. If null is returned, a consumer of the implementation may throw a
- /// <see cref="T:System.InvalidOperationException"/>.</li>
- /// <li><see cref="GetPartitions"/> and <see cref="GetDynamicPartitions"/> should always return
- /// partitions that can fully and uniquely enumerate the input data source. All of the data and only the
- /// data contained in the input source should be enumerated, with no duplication that was not already in
- /// the input, unless specifically required by the particular partitioner's design. If this is not
- /// followed, the output ordering may be scrambled.</li>
- /// </ol>
- /// </para>
- /// </remarks>
- public abstract class Partitioner<TSource>
- {
- /// <summary>
- /// Partitions the underlying collection into the given number of partitions.
- /// </summary>
- /// <param name="partitionCount">The number of partitions to create.</param>
- /// <returns>A list containing <paramref name="partitionCount"/> enumerators.</returns>
- public abstract IList<IEnumerator<TSource>> GetPartitions(int partitionCount);
-
- /// <summary>
- /// Gets whether additional partitions can be created dynamically.
- /// </summary>
- /// <returns>
- /// true if the <see cref="Partitioner{TSource}"/> can create partitions dynamically as they are
- /// requested; false if the <see cref="Partitioner{TSource}"/> can only allocate
- /// partitions statically.
- /// </returns>
- /// <remarks>
- /// <para>
- /// If a derived class does not override and implement <see cref="GetDynamicPartitions"/>,
- /// <see cref="SupportsDynamicPartitions"/> should return false. The value of <see
- /// cref="SupportsDynamicPartitions"/> should not vary over the lifetime of this instance.
- /// </para>
- /// </remarks>
- public virtual bool SupportsDynamicPartitions
- {
- get { return false; }
- }
-
- /// <summary>
- /// Creates an object that can partition the underlying collection into a variable number of
- /// partitions.
- /// </summary>
- /// <remarks>
- /// <para>
- /// The returned object implements the <see
- /// cref="T:System.Collections.Generic.IEnumerable{TSource}"/> interface. Calling <see
- /// cref="System.Collections.Generic.IEnumerable{TSource}.GetEnumerator">GetEnumerator</see> on the
- /// object creates another partition over the sequence.
- /// </para>
- /// <para>
- /// The <see cref="GetDynamicPartitions"/> method is only supported if the <see
- /// cref="SupportsDynamicPartitions"/>
- /// property returns true.
- /// </para>
- /// </remarks>
- /// <returns>An object that can create partitions over the underlying data source.</returns>
- /// <exception cref="NotSupportedException">Dynamic partitioning is not supported by this
- /// partitioner.</exception>
- public virtual IEnumerable<TSource> GetDynamicPartitions()
- {
- throw new NotSupportedException(Environment.GetResourceString("Partitioner_DynamicPartitionsNotSupported"));
- }
- }
-}
diff --git a/src/mscorlib/src/System/Collections/Concurrent/PartitionerStatic.cs b/src/mscorlib/src/System/Collections/Concurrent/PartitionerStatic.cs
deleted file mode 100644
index 9b36c053ad..0000000000
--- a/src/mscorlib/src/System/Collections/Concurrent/PartitionerStatic.cs
+++ /dev/null
@@ -1,1715 +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.
-#pragma warning disable 0420
-
-// =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+
-//
-//
-//
-// A class of default partitioners for Partitioner<TSource>
-//
-// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
-
-using System.Collections.Generic;
-using System.Security.Permissions;
-using System.Threading;
-using System.Diagnostics;
-using System.Diagnostics.Contracts;
-using System.Runtime.InteropServices;
-
-namespace System.Collections.Concurrent
-{
- /// <summary>
- /// Out-of-the-box partitioners are created with a set of default behaviors.
- /// For example, by default, some form of buffering and chunking will be employed to achieve
- /// optimal performance in the common scenario where an IEnumerable<> implementation is fast and
- /// non-blocking. These behaviors can be overridden via this enumeration.
- /// </summary>
- [Flags]
- public enum EnumerablePartitionerOptions
- {
- /// <summary>
- /// Use the default behavior (i.e., use buffering to achieve optimal performance)
- /// </summary>
- None = 0x0,
-
- /// <summary>
- /// Creates a partitioner that will take items from the source enumerable one at a time
- /// and will not use intermediate storage that can be accessed more efficiently by multiple threads.
- /// This option provides support for low latency (items will be processed as soon as they are available from
- /// the source) and partial support for dependencies between items (a thread cannot deadlock waiting for an item
- /// that it, itself, is responsible for processing).
- /// </summary>
- NoBuffering = 0x1
- }
-
- // The static class Partitioners implements 3 default partitioning strategies:
- // 1. dynamic load balance partitioning for indexable data source (IList and arrays)
- // 2. static partitioning for indexable data source (IList and arrays)
- // 3. dynamic load balance partitioning for enumerables. Enumerables have indexes, which are the natural order
- // of elements, but enuemrators are not indexable
- // - data source of type IList/arrays have both dynamic and static partitioning, as 1 and 3.
- // We assume that the source data of IList/Array is not changing concurrently.
- // - data source of type IEnumerable can only be partitioned dynamically (load-balance)
- // - Dynamic partitioning methods 1 and 3 are same, both being dynamic and load-balance. But the
- // implementation is different for data source of IList/Array vs. IEnumerable:
- // * When the source collection is IList/Arrays, we use Interlocked on the shared index;
- // * When the source collection is IEnumerable, we use Monitor to wrap around the access to the source
- // enumerator.
-
- /// <summary>
- /// Provides common partitioning strategies for arrays, lists, and enumerables.
- /// </summary>
- /// <remarks>
- /// <para>
- /// The static methods on <see cref="Partitioner"/> are all thread-safe and may be used concurrently
- /// from multiple threads. However, while a created partitioner is in use, the underlying data source
- /// should not be modified, whether from the same thread that's using a partitioner or from a separate
- /// thread.
- /// </para>
- /// </remarks>
- public static class Partitioner
- {
- /// <summary>
- /// Creates an orderable partitioner from an <see cref="System.Collections.Generic.IList{T}"/>
- /// instance.
- /// </summary>
- /// <typeparam name="TSource">Type of the elements in source list.</typeparam>
- /// <param name="list">The list to be partitioned.</param>
- /// <param name="loadBalance">
- /// A Boolean value that indicates whether the created partitioner should dynamically
- /// load balance between partitions rather than statically partition.
- /// </param>
- /// <returns>
- /// An orderable partitioner based on the input list.
- /// </returns>
- public static OrderablePartitioner<TSource> Create<TSource>(IList<TSource> list, bool loadBalance)
- {
- if (list == null)
- {
- throw new ArgumentNullException(nameof(list));
- }
- if (loadBalance)
- {
- return (new DynamicPartitionerForIList<TSource>(list));
- }
- else
- {
- return (new StaticIndexRangePartitionerForIList<TSource>(list));
- }
- }
-
- /// <summary>
- /// Creates an orderable partitioner from a <see cref="System.Array"/> instance.
- /// </summary>
- /// <typeparam name="TSource">Type of the elements in source array.</typeparam>
- /// <param name="array">The array to be partitioned.</param>
- /// <param name="loadBalance">
- /// A Boolean value that indicates whether the created partitioner should dynamically load balance
- /// between partitions rather than statically partition.
- /// </param>
- /// <returns>
- /// An orderable partitioner based on the input array.
- /// </returns>
- public static OrderablePartitioner<TSource> Create<TSource>(TSource[] array, bool loadBalance)
- {
- // This implementation uses 'ldelem' instructions for element retrieval, rather than using a
- // method call.
-
- if (array == null)
- {
- throw new ArgumentNullException(nameof(array));
- }
- if (loadBalance)
- {
- return (new DynamicPartitionerForArray<TSource>(array));
- }
- else
- {
- return (new StaticIndexRangePartitionerForArray<TSource>(array));
- }
- }
-
- /// <summary>
- /// Creates an orderable partitioner from a <see cref="System.Collections.Generic.IEnumerable{TSource}"/> instance.
- /// </summary>
- /// <typeparam name="TSource">Type of the elements in source enumerable.</typeparam>
- /// <param name="source">The enumerable to be partitioned.</param>
- /// <returns>
- /// An orderable partitioner based on the input array.
- /// </returns>
- /// <remarks>
- /// The ordering used in the created partitioner is determined by the natural order of the elements
- /// as retrieved from the source enumerable.
- /// </remarks>
- public static OrderablePartitioner<TSource> Create<TSource>(IEnumerable<TSource> source)
- {
- return Create<TSource>(source, EnumerablePartitionerOptions.None);
- }
-
- /// <summary>
- /// Creates an orderable partitioner from a <see cref="System.Collections.Generic.IEnumerable{TSource}"/> instance.
- /// </summary>
- /// <typeparam name="TSource">Type of the elements in source enumerable.</typeparam>
- /// <param name="source">The enumerable to be partitioned.</param>
- /// <param name="partitionerOptions">Options to control the buffering behavior of the partitioner.</param>
- /// <exception cref="T:System.ArgumentOutOfRangeException">
- /// The <paramref name="partitionerOptions"/> argument specifies an invalid value for <see
- /// cref="T:System.Collections.Concurrent.EnumerablePartitionerOptions"/>.
- /// </exception>
- /// <returns>
- /// An orderable partitioner based on the input array.
- /// </returns>
- /// <remarks>
- /// The ordering used in the created partitioner is determined by the natural order of the elements
- /// as retrieved from the source enumerable.
- /// </remarks>
- public static OrderablePartitioner<TSource> Create<TSource>(IEnumerable<TSource> source, EnumerablePartitionerOptions partitionerOptions)
- {
- if (source == null)
- {
- throw new ArgumentNullException(nameof(source));
- }
-
- if ((partitionerOptions & (~EnumerablePartitionerOptions.NoBuffering)) != 0)
- throw new ArgumentOutOfRangeException(nameof(partitionerOptions));
-
- return (new DynamicPartitionerForIEnumerable<TSource>(source, partitionerOptions));
- }
-
- /// <summary>Creates a partitioner that chunks the user-specified range.</summary>
- /// <param name="fromInclusive">The lower, inclusive bound of the range.</param>
- /// <param name="toExclusive">The upper, exclusive bound of the range.</param>
- /// <returns>A partitioner.</returns>
- /// <exception cref="T:System.ArgumentOutOfRangeException"> The <paramref name="toExclusive"/> argument is
- /// less than or equal to the <paramref name="fromInclusive"/> argument.</exception>
- public static OrderablePartitioner<Tuple<long, long>> Create(long fromInclusive, long toExclusive)
- {
- // How many chunks do we want to divide the range into? If this is 1, then the
- // answer is "one chunk per core". Generally, though, you'll achieve better
- // load balancing on a busy system if you make it higher than 1.
- int coreOversubscriptionRate = 3;
-
- if (toExclusive <= fromInclusive) throw new ArgumentOutOfRangeException(nameof(toExclusive));
- long rangeSize = (toExclusive - fromInclusive) /
- (PlatformHelper.ProcessorCount * coreOversubscriptionRate);
- if (rangeSize == 0) rangeSize = 1;
- return Partitioner.Create(CreateRanges(fromInclusive, toExclusive, rangeSize), EnumerablePartitionerOptions.NoBuffering); // chunk one range at a time
- }
-
- /// <summary>Creates a partitioner that chunks the user-specified range.</summary>
- /// <param name="fromInclusive">The lower, inclusive bound of the range.</param>
- /// <param name="toExclusive">The upper, exclusive bound of the range.</param>
- /// <param name="rangeSize">The size of each subrange.</param>
- /// <returns>A partitioner.</returns>
- /// <exception cref="T:System.ArgumentOutOfRangeException"> The <paramref name="toExclusive"/> argument is
- /// less than or equal to the <paramref name="fromInclusive"/> argument.</exception>
- /// <exception cref="T:System.ArgumentOutOfRangeException"> The <paramref name="rangeSize"/> argument is
- /// 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(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
- }
-
- // Private method to parcel out range tuples.
- private static IEnumerable<Tuple<long, long>> CreateRanges(long fromInclusive, long toExclusive, long rangeSize)
- {
- // Enumerate all of the ranges
- long from, to;
- bool shouldQuit = false;
-
- for (long i = fromInclusive; (i < toExclusive) && !shouldQuit; i += rangeSize)
- {
- from = i;
- try { checked { to = i + rangeSize; } }
- catch (OverflowException)
- {
- to = toExclusive;
- shouldQuit = true;
- }
- if (to > toExclusive) to = toExclusive;
- yield return new Tuple<long, long>(from, to);
- }
- }
-
- /// <summary>Creates a partitioner that chunks the user-specified range.</summary>
- /// <param name="fromInclusive">The lower, inclusive bound of the range.</param>
- /// <param name="toExclusive">The upper, exclusive bound of the range.</param>
- /// <returns>A partitioner.</returns>
- /// <exception cref="T:System.ArgumentOutOfRangeException"> The <paramref name="toExclusive"/> argument is
- /// less than or equal to the <paramref name="fromInclusive"/> argument.</exception>
- public static OrderablePartitioner<Tuple<int, int>> Create(int fromInclusive, int toExclusive)
- {
- // How many chunks do we want to divide the range into? If this is 1, then the
- // answer is "one chunk per core". Generally, though, you'll achieve better
- // load balancing on a busy system if you make it higher than 1.
- int coreOversubscriptionRate = 3;
-
- if (toExclusive <= fromInclusive) throw new ArgumentOutOfRangeException(nameof(toExclusive));
- int rangeSize = (toExclusive - fromInclusive) /
- (PlatformHelper.ProcessorCount * coreOversubscriptionRate);
- if (rangeSize == 0) rangeSize = 1;
- return Partitioner.Create(CreateRanges(fromInclusive, toExclusive, rangeSize), EnumerablePartitionerOptions.NoBuffering); // chunk one range at a time
- }
-
- /// <summary>Creates a partitioner that chunks the user-specified range.</summary>
- /// <param name="fromInclusive">The lower, inclusive bound of the range.</param>
- /// <param name="toExclusive">The upper, exclusive bound of the range.</param>
- /// <param name="rangeSize">The size of each subrange.</param>
- /// <returns>A partitioner.</returns>
- /// <exception cref="T:System.ArgumentOutOfRangeException"> The <paramref name="toExclusive"/> argument is
- /// less than or equal to the <paramref name="fromInclusive"/> argument.</exception>
- /// <exception cref="T:System.ArgumentOutOfRangeException"> The <paramref name="rangeSize"/> argument is
- /// 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(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
- }
-
- // Private method to parcel out range tuples.
- private static IEnumerable<Tuple<int, int>> CreateRanges(int fromInclusive, int toExclusive, int rangeSize)
- {
- // Enumerate all of the ranges
- int from, to;
- bool shouldQuit = false;
-
- for (int i = fromInclusive; (i < toExclusive) && !shouldQuit; i += rangeSize)
- {
- from = i;
- try { checked { to = i + rangeSize; } }
- catch (OverflowException)
- {
- to = toExclusive;
- shouldQuit = true;
- }
- if (to > toExclusive) to = toExclusive;
- yield return new Tuple<int, int>(from, to);
- }
- }
-
- #region DynamicPartitionEnumerator_Abstract class
- /// <summary>
- /// DynamicPartitionEnumerator_Abstract defines the enumerator for each partition for the dynamic load-balance
- /// partitioning algorithm.
- /// - Partition is an enumerator of KeyValuePairs, each corresponding to an item in the data source:
- /// the key is the index in the source collection; the value is the item itself.
- /// - a set of such partitions share a reader over data source. The type of the reader is specified by
- /// TSourceReader.
- /// - each partition requests a contiguous chunk of elements at a time from the source data. The chunk
- /// size is initially 1, and doubles every time until it reaches the maximum chunk size.
- /// The implementation for GrabNextChunk() method has two versions: one for data source of IndexRange
- /// types (IList and the array), one for data source of IEnumerable.
- /// - The method "Reset" is not supported for any partitioning algorithm.
- /// - The implementation for MoveNext() method is same for all dynanmic partitioners, so we provide it
- /// in this abstract class.
- /// </summary>
- /// <typeparam name="TSource">Type of the elements in the data source</typeparam>
- /// <typeparam name="TSourceReader">Type of the reader on the data source</typeparam>
- //TSourceReader is
- // - IList<TSource>, when source data is IList<TSource>, the shared reader is source data itself
- // - TSource[], when source data is TSource[], the shared reader is source data itself
- // - IEnumerator<TSource>, when source data is IEnumerable<TSource>, and the shared reader is an
- // enumerator of the source data
- private abstract class DynamicPartitionEnumerator_Abstract<TSource, TSourceReader> : IEnumerator<KeyValuePair<long, TSource>>
- {
- //----------------- common fields and constructor for all dynamic partitioners -----------------
- //--- shared by all dervied class with souce data type: IList, Array, and IEnumerator
- protected readonly TSourceReader m_sharedReader;
-
- protected static int s_defaultMaxChunkSize = GetDefaultChunkSize<TSource>();
-
- //deferred allocating in MoveNext() with initial value 0, to avoid false sharing
- //we also use the fact that: (m_currentChunkSize==null) means MoveNext is never called on this enumerator
- protected SharedInt m_currentChunkSize;
-
- //deferring allocation in MoveNext() with initial value -1, to avoid false sharing
- protected SharedInt m_localOffset;
-
- private const int CHUNK_DOUBLING_RATE = 3; // Double the chunk size every this many grabs
- private int m_doublingCountdown; // Number of grabs remaining until chunk size doubles
- protected readonly int m_maxChunkSize; // s_defaultMaxChunkSize unless single-chunking is requested by the caller
-
- // m_sharedIndex shared by this set of partitions, and particularly when m_sharedReader is IEnuerable
- // it serves as tracking of the natual order of elements in m_sharedReader
- // the value of this field is passed in from outside (already initialized) by the constructor,
- protected readonly SharedLong m_sharedIndex;
-
- protected DynamicPartitionEnumerator_Abstract(TSourceReader sharedReader, SharedLong sharedIndex)
- : this(sharedReader, sharedIndex, false)
- {
- }
-
- protected DynamicPartitionEnumerator_Abstract(TSourceReader sharedReader, SharedLong sharedIndex, bool useSingleChunking)
- {
- m_sharedReader = sharedReader;
- m_sharedIndex = sharedIndex;
- m_maxChunkSize = useSingleChunking ? 1 : s_defaultMaxChunkSize;
- }
-
- // ---------------- abstract method declarations --------------
-
- /// <summary>
- /// Abstract method to request a contiguous chunk of elements from the source collection
- /// </summary>
- /// <param name="requestedChunkSize">specified number of elements requested</param>
- /// <returns>
- /// true if we successfully reserved at least one element (up to #=requestedChunkSize)
- /// false if all elements in the source collection have been reserved.
- /// </returns>
- //GrabNextChunk does the following:
- // - grab # of requestedChunkSize elements from source data through shared reader,
- // - at the time of function returns, m_currentChunkSize is updated with the number of
- // elements actually got assigned (<=requestedChunkSize).
- // - GrabNextChunk returns true if at least one element is assigned to this partition;
- // false if the shared reader already hits the last element of the source data before
- // we call GrabNextChunk
- protected abstract bool GrabNextChunk(int requestedChunkSize);
-
- /// <summary>
- /// Abstract property, returns whether or not the shared reader has already read the last
- /// element of the source data
- /// </summary>
- protected abstract bool HasNoElementsLeft { get; set; }
-
- /// <summary>
- /// Get the current element in the current partition. Property required by IEnumerator interface
- /// This property is abstract because the implementation is different depending on the type
- /// of the source data: IList, Array or IEnumerable
- /// </summary>
- public abstract KeyValuePair<long, TSource> Current { get; }
-
- /// <summary>
- /// Dispose is abstract, and depends on the type of the source data:
- /// - For source data type IList and Array, the type of the shared reader is just the dataitself.
- /// We don't do anything in Dispose method for IList and Array.
- /// - For source data type IEnumerable, the type of the shared reader is an enumerator we created.
- /// Thus we need to dispose this shared reader enumerator, when there is no more active partitions
- /// left.
- /// </summary>
- public abstract void Dispose();
-
- /// <summary>
- /// Reset on partitions is not supported
- /// </summary>
- public void Reset()
- {
- throw new NotSupportedException();
- }
-
-
- /// <summary>
- /// Get the current element in the current partition. Property required by IEnumerator interface
- /// </summary>
- Object IEnumerator.Current
- {
- get
- {
- return ((DynamicPartitionEnumerator_Abstract<TSource, TSourceReader>)this).Current;
- }
- }
-
- /// <summary>
- /// Moves to the next element if any.
- /// Try current chunk first, if the current chunk do not have any elements left, then we
- /// attempt to grab a chunk from the source collection.
- /// </summary>
- /// <returns>
- /// true if successfully moving to the next position;
- /// false otherwise, if and only if there is no more elements left in the current chunk
- /// AND the source collection is exhausted.
- /// </returns>
- public bool MoveNext()
- {
- //perform deferred allocating of the local variables.
- if (m_localOffset == null)
- {
- Debug.Assert(m_currentChunkSize == null);
- m_localOffset = new SharedInt(-1);
- m_currentChunkSize = new SharedInt(0);
- m_doublingCountdown = CHUNK_DOUBLING_RATE;
- }
-
- if (m_localOffset.Value < m_currentChunkSize.Value - 1)
- //attempt to grab the next element from the local chunk
- {
- m_localOffset.Value++;
- return true;
- }
- else
- //otherwise it means we exhausted the local chunk
- //grab a new chunk from the source enumerator
- {
- // The second part of the || condition is necessary to handle the case when MoveNext() is called
- // after a previous MoveNext call returned false.
- Debug.Assert(m_localOffset.Value == m_currentChunkSize.Value - 1 || m_currentChunkSize.Value == 0);
-
- //set the requested chunk size to a proper value
- int requestedChunkSize;
- if (m_currentChunkSize.Value == 0) //first time grabbing from source enumerator
- {
- requestedChunkSize = 1;
- }
- else if (m_doublingCountdown > 0)
- {
- requestedChunkSize = m_currentChunkSize.Value;
- }
- else
- {
- requestedChunkSize = Math.Min(m_currentChunkSize.Value * 2, m_maxChunkSize);
- m_doublingCountdown = CHUNK_DOUBLING_RATE; // reset
- }
-
- // Decrement your doubling countdown
- m_doublingCountdown--;
-
- Debug.Assert(requestedChunkSize > 0 && requestedChunkSize <= m_maxChunkSize);
- //GrabNextChunk will update the value of m_currentChunkSize
- if (GrabNextChunk(requestedChunkSize))
- {
- Debug.Assert(m_currentChunkSize.Value <= requestedChunkSize && m_currentChunkSize.Value > 0);
- m_localOffset.Value = 0;
- return true;
- }
- else
- {
- return false;
- }
- }
- }
- }
- #endregion
-
- #region Dynamic Partitioner for source data of IEnuemrable<> type
- /// <summary>
- /// Inherits from DynamicPartitioners
- /// Provides customized implementation of GetOrderableDynamicPartitions_Factory method, to return an instance
- /// of EnumerableOfPartitionsForIEnumerator defined internally
- /// </summary>
- /// <typeparam name="TSource">Type of elements in the source data</typeparam>
- private class DynamicPartitionerForIEnumerable<TSource> : OrderablePartitioner<TSource>
- {
- IEnumerable<TSource> m_source;
- readonly bool m_useSingleChunking;
-
- //constructor
- internal DynamicPartitionerForIEnumerable(IEnumerable<TSource> source, EnumerablePartitionerOptions partitionerOptions)
- : base(true, false, true)
- {
- m_source = source;
- m_useSingleChunking = ((partitionerOptions & EnumerablePartitionerOptions.NoBuffering) != 0);
- }
-
- /// <summary>
- /// Overrides OrderablePartitioner.GetOrderablePartitions.
- /// Partitions the underlying collection into the given number of orderable partitions.
- /// </summary>
- /// <param name="partitionCount">number of partitions requested</param>
- /// <returns>A list containing <paramref name="partitionCount"/> enumerators.</returns>
- override public IList<IEnumerator<KeyValuePair<long, TSource>>> GetOrderablePartitions(int partitionCount)
- {
- if (partitionCount <= 0)
- {
- throw new ArgumentOutOfRangeException(nameof(partitionCount));
- }
- IEnumerator<KeyValuePair<long, TSource>>[] partitions
- = new IEnumerator<KeyValuePair<long, TSource>>[partitionCount];
-
- IEnumerable<KeyValuePair<long, TSource>> partitionEnumerable = new InternalPartitionEnumerable(m_source.GetEnumerator(), m_useSingleChunking, true);
- for (int i = 0; i < partitionCount; i++)
- {
- partitions[i] = partitionEnumerable.GetEnumerator();
- }
- return partitions;
- }
-
- /// <summary>
- /// Overrides OrderablePartitioner.GetOrderableDyanmicPartitions
- /// </summary>
- /// <returns>a enumerable collection of orderable partitions</returns>
- override public IEnumerable<KeyValuePair<long, TSource>> GetOrderableDynamicPartitions()
- {
- return new InternalPartitionEnumerable(m_source.GetEnumerator(), m_useSingleChunking, false);
- }
-
- /// <summary>
- /// Whether additional partitions can be created dynamically.
- /// </summary>
- override public bool SupportsDynamicPartitions
- {
- get { return true; }
- }
-
- #region Internal classes: InternalPartitionEnumerable, InternalPartitionEnumerator
- /// <summary>
- /// Provides customized implementation for source data of IEnumerable
- /// Different from the counterpart for IList/Array, this enumerable maintains several additional fields
- /// shared by the partitions it owns, including a boolean "m_hasNoElementsLef", a shared lock, and a
- /// shared count "m_activePartitionCount" used to track active partitions when they were created statically
- /// </summary>
- private class InternalPartitionEnumerable : IEnumerable<KeyValuePair<long, TSource>>, IDisposable
- {
- //reader through which we access the source data
- private readonly IEnumerator<TSource> m_sharedReader;
- private SharedLong m_sharedIndex;//initial value -1
-
- private volatile KeyValuePair<long, TSource>[] m_FillBuffer; // intermediate buffer to reduce locking
- private volatile int m_FillBufferSize; // actual number of elements in m_FillBuffer. Will start
- // at m_FillBuffer.Length, and might be reduced during the last refill
- private volatile int m_FillBufferCurrentPosition; //shared value to be accessed by Interlock.Increment only
- private volatile int m_activeCopiers; //number of active copiers
-
- //fields shared by all partitions that this Enumerable owns, their allocation is deferred
- private SharedBool m_hasNoElementsLeft; // no elements left at all.
- private SharedBool m_sourceDepleted; // no elements left in the enumerator, but there may be elements in the Fill Buffer
-
- //shared synchronization lock, created by this Enumerable
- private object m_sharedLock;//deferring allocation by enumerator
-
- private bool m_disposed;
-
- // If dynamic partitioning, then m_activePartitionCount == null
- // If static partitioning, then it keeps track of active partition count
- private SharedInt m_activePartitionCount;
-
- // records whether or not the user has requested single-chunking behavior
- private readonly bool m_useSingleChunking;
-
- internal InternalPartitionEnumerable(IEnumerator<TSource> sharedReader, bool useSingleChunking, bool isStaticPartitioning)
- {
- m_sharedReader = sharedReader;
- m_sharedIndex = new SharedLong(-1);
- m_hasNoElementsLeft = new SharedBool(false);
- m_sourceDepleted = new SharedBool(false);
- m_sharedLock = new object();
- m_useSingleChunking = useSingleChunking;
-
- // Only allocate the fill-buffer if single-chunking is not in effect
- if (!m_useSingleChunking)
- {
- // Time to allocate the fill buffer which is used to reduce the contention on the shared lock.
- // First pick the buffer size multiplier. We use 4 for when there are more than 4 cores, and just 1 for below. This is based on empirical evidence.
- int fillBufferMultiplier = (PlatformHelper.ProcessorCount > 4) ? 4 : 1;
-
- // and allocate the fill buffer using these two numbers
- m_FillBuffer = new KeyValuePair<long, TSource>[fillBufferMultiplier * Partitioner.GetDefaultChunkSize<TSource>()];
- }
-
- if (isStaticPartitioning)
- {
- // If this object is created for static partitioning (ie. via GetPartitions(int partitionCount),
- // GetOrderablePartitions(int partitionCount)), we track the active partitions, in order to dispose
- // this object when all the partitions have been disposed.
- m_activePartitionCount = new SharedInt(0);
- }
- else
- {
- // Otherwise this object is created for dynamic partitioning (ie, via GetDynamicPartitions(),
- // GetOrderableDynamicPartitions()), we do not need tracking. This object must be disposed
- // explicitly
- m_activePartitionCount = null;
- }
- }
-
- public IEnumerator<KeyValuePair<long, TSource>> GetEnumerator()
- {
- if (m_disposed)
- {
- throw new ObjectDisposedException(Environment.GetResourceString("PartitionerStatic_CanNotCallGetEnumeratorAfterSourceHasBeenDisposed"));
- }
- else
- {
- return new InternalPartitionEnumerator(m_sharedReader, m_sharedIndex,
- m_hasNoElementsLeft, m_sharedLock, m_activePartitionCount, this, m_useSingleChunking);
- }
- }
-
-
- IEnumerator IEnumerable.GetEnumerator()
- {
- return ((InternalPartitionEnumerable)this).GetEnumerator();
- }
-
-
- ///////////////////
- //
- // Used by GrabChunk_Buffered()
- private void TryCopyFromFillBuffer(KeyValuePair<long, TSource>[] destArray,
- int requestedChunkSize,
- ref int actualNumElementsGrabbed)
- {
- actualNumElementsGrabbed = 0;
-
-
- // making a local defensive copy of the fill buffer reference, just in case it gets nulled out
- KeyValuePair<long, TSource>[] fillBufferLocalRef = m_FillBuffer;
- if (fillBufferLocalRef == null) return;
-
- // first do a quick check, and give up if the current position is at the end
- // so that we don't do an unncessary pair of Interlocked.Increment / Decrement calls
- if (m_FillBufferCurrentPosition >= m_FillBufferSize)
- {
- return; // no elements in the buffer to copy from
- }
-
- // We might have a chance to grab elements from the buffer. We will know for sure
- // when we do the Interlocked.Add below.
- // But first we must register as a potential copier in order to make sure
- // the elements we're copying from don't get overwritten by another thread
- // that starts refilling the buffer right after our Interlocked.Add.
- Interlocked.Increment(ref m_activeCopiers);
-
- int endPos = Interlocked.Add(ref m_FillBufferCurrentPosition, requestedChunkSize);
- int beginPos = endPos - requestedChunkSize;
-
- if (beginPos < m_FillBufferSize)
- {
- // adjust index and do the actual copy
- actualNumElementsGrabbed = (endPos < m_FillBufferSize) ? endPos : m_FillBufferSize - beginPos;
- Array.Copy(fillBufferLocalRef, beginPos, destArray, 0, actualNumElementsGrabbed);
- }
-
- // let the record show we are no longer accessing the buffer
- Interlocked.Decrement(ref m_activeCopiers);
- }
-
- /// <summary>
- /// This is the common entry point for consuming items from the source enumerable
- /// </summary>
- /// <returns>
- /// true if we successfully reserved at least one element
- /// false if all elements in the source collection have been reserved.
- /// </returns>
- internal bool GrabChunk(KeyValuePair<long, TSource>[] destArray, int requestedChunkSize, ref int actualNumElementsGrabbed)
- {
- actualNumElementsGrabbed = 0;
-
- if (m_hasNoElementsLeft.Value)
- {
- return false;
- }
-
- if (m_useSingleChunking)
- {
- return GrabChunk_Single(destArray, requestedChunkSize, ref actualNumElementsGrabbed);
- }
- else
- {
- return GrabChunk_Buffered(destArray, requestedChunkSize, ref actualNumElementsGrabbed);
- }
- }
-
- /// <summary>
- /// Version of GrabChunk that grabs a single element at a time from the source enumerable
- /// </summary>
- /// <returns>
- /// true if we successfully reserved an element
- /// false if all elements in the source collection have been reserved.
- /// </returns>
- internal bool GrabChunk_Single(KeyValuePair<long,TSource>[] destArray, int requestedChunkSize, ref int actualNumElementsGrabbed)
- {
- 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)
- {
- if (m_hasNoElementsLeft.Value) return false;
-
- try
- {
- if (m_sharedReader.MoveNext())
- {
- m_sharedIndex.Value = checked(m_sharedIndex.Value + 1);
- destArray[0]
- = new KeyValuePair<long, TSource>(m_sharedIndex.Value,
- m_sharedReader.Current);
- actualNumElementsGrabbed = 1;
- return true;
- }
- else
- {
- //if MoveNext() return false, we set the flag to inform other partitions
- m_sourceDepleted.Value = true;
- m_hasNoElementsLeft.Value = true;
- return false;
- }
- }
- catch
- {
- // On an exception, make sure that no additional items are hereafter enumerated
- m_sourceDepleted.Value = true;
- m_hasNoElementsLeft.Value = true;
- throw;
- }
- }
- }
-
-
-
- /// <summary>
- /// Version of GrabChunk that uses buffering scheme to grab items out of source enumerable
- /// </summary>
- /// <returns>
- /// true if we successfully reserved at least one element (up to #=requestedChunkSize)
- /// false if all elements in the source collection have been reserved.
- /// </returns>
- internal bool GrabChunk_Buffered(KeyValuePair<long,TSource>[] destArray, int requestedChunkSize, ref int actualNumElementsGrabbed)
- {
- Debug.Assert(requestedChunkSize > 0);
- Debug.Assert(!m_useSingleChunking, "Did not expect to be in single-chunking mode");
-
- TryCopyFromFillBuffer(destArray, requestedChunkSize, ref actualNumElementsGrabbed);
-
- if (actualNumElementsGrabbed == requestedChunkSize)
- {
- // that was easy.
- return true;
- }
- else if (m_sourceDepleted.Value)
- {
- // looks like we both reached the end of the fill buffer, and the source was depleted previously
- // this means no more work to do for any other worker
- m_hasNoElementsLeft.Value = true;
- m_FillBuffer = null;
- return (actualNumElementsGrabbed > 0);
- }
-
-
- //
- // now's the time to take the shared lock and enumerate
- //
- lock (m_sharedLock)
- {
- if (m_sourceDepleted.Value)
- {
- return (actualNumElementsGrabbed > 0);
- }
-
- try
- {
- // we need to make sure all array copiers are finished
- if (m_activeCopiers > 0)
- {
- SpinWait sw = new SpinWait();
- while( m_activeCopiers > 0) sw.SpinOnce();
- }
-
- Debug.Assert(m_sharedIndex != null); //already been allocated in MoveNext() before calling GrabNextChunk
-
- // Now's the time to actually enumerate the source
-
- // We first fill up the requested # of elements in the caller's array
- // continue from the where TryCopyFromFillBuffer() left off
- for (; actualNumElementsGrabbed < requestedChunkSize; actualNumElementsGrabbed++)
- {
- if (m_sharedReader.MoveNext())
- {
- m_sharedIndex.Value = checked(m_sharedIndex.Value + 1);
- destArray[actualNumElementsGrabbed]
- = new KeyValuePair<long, TSource>(m_sharedIndex.Value,
- m_sharedReader.Current);
- }
- else
- {
- //if MoveNext() return false, we set the flag to inform other partitions
- m_sourceDepleted.Value = true;
- break;
- }
- }
-
- // taking a local snapshot of m_FillBuffer in case some other thread decides to null out m_FillBuffer
- // in the entry of this method after observing m_sourceCompleted = true
- var localFillBufferRef = m_FillBuffer;
-
- // If the big buffer seems to be depleted, we will also fill that up while we are under the lock
- // Note that this is the only place that m_FillBufferCurrentPosition can be reset
- if (m_sourceDepleted.Value == false && localFillBufferRef != null &&
- m_FillBufferCurrentPosition >= localFillBufferRef.Length)
- {
- for (int i = 0; i < localFillBufferRef.Length; i++)
- {
- if( m_sharedReader.MoveNext())
- {
- m_sharedIndex.Value = checked(m_sharedIndex.Value + 1);
- localFillBufferRef[i]
- = new KeyValuePair<long, TSource>(m_sharedIndex.Value,
- m_sharedReader.Current);
- }
- else
- {
- // No more elements left in the enumerator.
- // Record this, so that the next request can skip the lock
- m_sourceDepleted.Value = true;
-
- // also record the current count in m_FillBufferSize
- m_FillBufferSize = i;
-
- // and exit the for loop so that we don't keep incrementing m_FillBufferSize
- break;
- }
-
- }
-
- m_FillBufferCurrentPosition = 0;
- }
-
-
- }
- catch
- {
- // If an exception occurs, don't let the other enumerators try to enumerate.
- // NOTE: this could instead throw an InvalidOperationException, but that would be unexpected
- // and not helpful to the end user. We know the root cause is being communicated already.)
- m_sourceDepleted.Value = true;
- m_hasNoElementsLeft.Value = true;
- throw;
- }
- }
-
- return (actualNumElementsGrabbed > 0);
- }
-
- public void Dispose()
- {
- if (!m_disposed)
- {
- m_disposed = true;
- m_sharedReader.Dispose();
- }
- }
- }
-
- /// <summary>
- /// Inherits from DynamicPartitionEnumerator_Abstract directly
- /// Provides customized implementation for: GrabNextChunk, HasNoElementsLeft, Current, Dispose
- /// </summary>
- private class InternalPartitionEnumerator : DynamicPartitionEnumerator_Abstract<TSource, IEnumerator<TSource>>
- {
- //---- fields ----
- //cached local copy of the current chunk
- private KeyValuePair<long, TSource>[] m_localList; //defer allocating to avoid false sharing
-
- // the values of the following two fields are passed in from
- // outside(already initialized) by the constructor,
- private readonly SharedBool m_hasNoElementsLeft;
- private readonly object m_sharedLock;
- private readonly SharedInt m_activePartitionCount;
- private InternalPartitionEnumerable m_enumerable;
-
- //constructor
- internal InternalPartitionEnumerator(
- IEnumerator<TSource> sharedReader,
- SharedLong sharedIndex,
- SharedBool hasNoElementsLeft,
- object sharedLock,
- SharedInt activePartitionCount,
- InternalPartitionEnumerable enumerable,
- bool useSingleChunking)
- : base(sharedReader, sharedIndex, useSingleChunking)
- {
- m_hasNoElementsLeft = hasNoElementsLeft;
- m_sharedLock = sharedLock;
- m_enumerable = enumerable;
- m_activePartitionCount = activePartitionCount;
-
- if (m_activePartitionCount != null)
- {
- // If static partitioning, we need to increase the active partition count.
- Interlocked.Increment(ref m_activePartitionCount.Value);
- }
- }
-
- //overriding methods
-
- /// <summary>
- /// Reserves a contiguous range of elements from source data
- /// </summary>
- /// <param name="requestedChunkSize">specified number of elements requested</param>
- /// <returns>
- /// true if we successfully reserved at least one element (up to #=requestedChunkSize)
- /// false if all elements in the source collection have been reserved.
- /// </returns>
- override protected bool GrabNextChunk(int requestedChunkSize)
- {
- Debug.Assert(requestedChunkSize > 0);
-
- if (HasNoElementsLeft)
- {
- return false;
- }
-
- // defer allocation to avoid false sharing
- if (m_localList == null)
- {
- m_localList = new KeyValuePair<long, TSource>[m_maxChunkSize];
- }
-
- // make the actual call to the enumerable that grabs a chunk
- return m_enumerable.GrabChunk(m_localList, requestedChunkSize, ref m_currentChunkSize.Value);
- }
-
- /// <summary>
- /// Returns whether or not the shared reader has already read the last
- /// element of the source data
- /// </summary>
- /// <remarks>
- /// We cannot call m_sharedReader.MoveNext(), to see if it hits the last element
- /// or not, because we can't undo MoveNext(). Thus we need to maintain a shared
- /// boolean value m_hasNoElementsLeft across all partitions
- /// </remarks>
- override protected bool HasNoElementsLeft
- {
- get { return m_hasNoElementsLeft.Value; }
- set
- {
- //we only set it from false to true once
- //we should never set it back in any circumstances
- Debug.Assert(value);
- Debug.Assert(!m_hasNoElementsLeft.Value);
- m_hasNoElementsLeft.Value = true;
- }
- }
-
- override public KeyValuePair<long, TSource> Current
- {
- get
- {
- //verify that MoveNext is at least called once before Current is called
- if (m_currentChunkSize == null)
- {
- throw new InvalidOperationException(Environment.GetResourceString("PartitionerStatic_CurrentCalledBeforeMoveNext"));
- }
- Debug.Assert(m_localList != null);
- Debug.Assert(m_localOffset.Value >= 0 && m_localOffset.Value < m_currentChunkSize.Value);
- return (m_localList[m_localOffset.Value]);
- }
- }
-
- override public void Dispose()
- {
- // If this is static partitioning, ie. m_activePartitionCount != null, since the current partition
- // is disposed, we decrement the number of active partitions for the shared reader.
- if (m_activePartitionCount != null && Interlocked.Decrement(ref m_activePartitionCount.Value) == 0)
- {
- // If the number of active partitions becomes 0, we need to dispose the shared
- // reader we created in the m_enumerable object.
- m_enumerable.Dispose();
- }
- // If this is dynamic partitioning, ie. m_activePartitionCount != null, then m_enumerable needs to
- // be disposed explicitly by the user, and we do not need to anything here
- }
- }
- #endregion
-
- }
- #endregion
-
- #region Dynamic Partitioner for source data of IndexRange types (IList<> and Array<>)
- /// <summary>
- /// Dynamic load-balance partitioner. This class is abstract and to be derived from by
- /// the customized partitioner classes for IList, Array, and IEnumerable
- /// </summary>
- /// <typeparam name="TSource">Type of the elements in the source data</typeparam>
- /// <typeparam name="TCollection"> Type of the source data collection</typeparam>
- private abstract class DynamicPartitionerForIndexRange_Abstract<TSource, TCollection> : OrderablePartitioner<TSource>
- {
- // TCollection can be: IList<TSource>, TSource[] and IEnumerable<TSource>
- // Derived classes specify TCollection, and implement the abstract method GetOrderableDynamicPartitions_Factory accordingly
- TCollection m_data;
-
- /// <summary>
- /// Constructs a new orderable partitioner
- /// </summary>
- /// <param name="data">source data collection</param>
- protected DynamicPartitionerForIndexRange_Abstract(TCollection data)
- : base(true, false, true)
- {
- m_data = data;
- }
-
- /// <summary>
- /// Partition the source data and create an enumerable over the resulting partitions.
- /// </summary>
- /// <param name="data">the source data collection</param>
- /// <returns>an enumerable of partitions of </returns>
- protected abstract IEnumerable<KeyValuePair<long, TSource>> GetOrderableDynamicPartitions_Factory(TCollection data);
-
- /// <summary>
- /// Overrides OrderablePartitioner.GetOrderablePartitions.
- /// Partitions the underlying collection into the given number of orderable partitions.
- /// </summary>
- /// <param name="partitionCount">number of partitions requested</param>
- /// <returns>A list containing <paramref name="partitionCount"/> enumerators.</returns>
- override public IList<IEnumerator<KeyValuePair<long, TSource>>> GetOrderablePartitions(int partitionCount)
- {
- if (partitionCount <= 0)
- {
- throw new ArgumentOutOfRangeException(nameof(partitionCount));
- }
- IEnumerator<KeyValuePair<long, TSource>>[] partitions
- = new IEnumerator<KeyValuePair<long, TSource>>[partitionCount];
- IEnumerable<KeyValuePair<long, TSource>> partitionEnumerable = GetOrderableDynamicPartitions_Factory(m_data);
- for (int i = 0; i < partitionCount; i++)
- {
- partitions[i] = partitionEnumerable.GetEnumerator();
- }
- return partitions;
- }
-
- /// <summary>
- /// Overrides OrderablePartitioner.GetOrderableDyanmicPartitions
- /// </summary>
- /// <returns>a enumerable collection of orderable partitions</returns>
- override public IEnumerable<KeyValuePair<long, TSource>> GetOrderableDynamicPartitions()
- {
- return GetOrderableDynamicPartitions_Factory(m_data);
- }
-
- /// <summary>
- /// Whether additional partitions can be created dynamically.
- /// </summary>
- override public bool SupportsDynamicPartitions
- {
- get { return true; }
- }
-
- }
-
- /// <summary>
- /// Defines dynamic partition for source data of IList and Array.
- /// This class inherits DynamicPartitionEnumerator_Abstract
- /// - implements GrabNextChunk, HasNoElementsLeft, and Dispose methods for IList and Array
- /// - Current property still remains abstract, implementation is different for IList and Array
- /// - introduces another abstract method SourceCount, which returns the number of elements in
- /// the source data. Implementation differs for IList and Array
- /// </summary>
- /// <typeparam name="TSource">Type of the elements in the data source</typeparam>
- /// <typeparam name="TSourceReader">Type of the reader on the source data</typeparam>
- private abstract class DynamicPartitionEnumeratorForIndexRange_Abstract<TSource, TSourceReader> : DynamicPartitionEnumerator_Abstract<TSource, TSourceReader>
- {
- //fields
- protected int m_startIndex; //initially zero
-
- //constructor
- protected DynamicPartitionEnumeratorForIndexRange_Abstract(TSourceReader sharedReader, SharedLong sharedIndex)
- : base(sharedReader, sharedIndex)
- {
- }
-
- //abstract methods
- //the Current property is still abstract, and will be implemented by derived classes
- //we add another abstract method SourceCount to get the number of elements from the source reader
-
- /// <summary>
- /// Get the number of elements from the source reader.
- /// It calls IList.Count or Array.Length
- /// </summary>
- protected abstract int SourceCount { get; }
-
- //overriding methods
-
- /// <summary>
- /// Reserves a contiguous range of elements from source data
- /// </summary>
- /// <param name="requestedChunkSize">specified number of elements requested</param>
- /// <returns>
- /// true if we successfully reserved at least one element (up to #=requestedChunkSize)
- /// false if all elements in the source collection have been reserved.
- /// </returns>
- override protected bool GrabNextChunk(int requestedChunkSize)
- {
- Debug.Assert(requestedChunkSize > 0);
-
- while (!HasNoElementsLeft)
- {
- 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);
-
- if (HasNoElementsLeft)
- {
- //HasNoElementsLeft situation changed from false to true immediately
- //and oldSharedIndex becomes stale
- return false;
- }
-
- //there won't be overflow, because the index of IList/array is int, and we
- //have casted it to long.
- long newSharedIndex = Math.Min(SourceCount - 1, oldSharedIndex + requestedChunkSize);
-
-
- //the following CAS, if successful, reserves a chunk of elements [oldSharedIndex+1, newSharedIndex]
- //inclusive in the source collection
- if (Interlocked.CompareExchange(ref m_sharedIndex.Value, newSharedIndex, oldSharedIndex)
- == oldSharedIndex)
- {
- //set up local indexes.
- //m_currentChunkSize is always set to requestedChunkSize when source data had
- //enough elements of what we requested
- m_currentChunkSize.Value = (int)(newSharedIndex - oldSharedIndex);
- m_localOffset.Value = -1;
- m_startIndex = (int)(oldSharedIndex + 1);
- return true;
- }
- }
- //didn't get any element, return false;
- return false;
- }
-
- /// <summary>
- /// Returns whether or not the shared reader has already read the last
- /// element of the source data
- /// </summary>
- override protected bool HasNoElementsLeft
- {
- get
- {
- 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
- {
- Debug.Assert(false);
- }
- }
-
- /// <summary>
- /// For source data type IList and Array, the type of the shared reader is just the data itself.
- /// We don't do anything in Dispose method for IList and Array.
- /// </summary>
- override public void Dispose()
- { }
- }
-
-
- /// <summary>
- /// Inherits from DynamicPartitioners
- /// Provides customized implementation of GetOrderableDynamicPartitions_Factory method, to return an instance
- /// of EnumerableOfPartitionsForIList defined internally
- /// </summary>
- /// <typeparam name="TSource">Type of elements in the source data</typeparam>
- private class DynamicPartitionerForIList<TSource> : DynamicPartitionerForIndexRange_Abstract<TSource, IList<TSource>>
- {
- //constructor
- internal DynamicPartitionerForIList(IList<TSource> source)
- : base(source)
- { }
-
- //override methods
- override protected IEnumerable<KeyValuePair<long, TSource>> GetOrderableDynamicPartitions_Factory(IList<TSource> m_data)
- {
- //m_data itself serves as shared reader
- return new InternalPartitionEnumerable(m_data);
- }
-
- /// <summary>
- /// Inherits from PartitionList_Abstract
- /// Provides customized implementation for source data of IList
- /// </summary>
- private class InternalPartitionEnumerable : IEnumerable<KeyValuePair<long, TSource>>
- {
- //reader through which we access the source data
- private readonly IList<TSource> m_sharedReader;
- private SharedLong m_sharedIndex;
-
- internal InternalPartitionEnumerable(IList<TSource> sharedReader)
- {
- m_sharedReader = sharedReader;
- m_sharedIndex = new SharedLong(-1);
- }
-
- public IEnumerator<KeyValuePair<long, TSource>> GetEnumerator()
- {
- return new InternalPartitionEnumerator(m_sharedReader, m_sharedIndex);
- }
-
- IEnumerator IEnumerable.GetEnumerator()
- {
- return ((InternalPartitionEnumerable)this).GetEnumerator();
- }
- }
-
- /// <summary>
- /// Inherits from DynamicPartitionEnumeratorForIndexRange_Abstract
- /// Provides customized implementation of SourceCount property and Current property for IList
- /// </summary>
- private class InternalPartitionEnumerator : DynamicPartitionEnumeratorForIndexRange_Abstract<TSource, IList<TSource>>
- {
- //constructor
- internal InternalPartitionEnumerator(IList<TSource> sharedReader, SharedLong sharedIndex)
- : base(sharedReader, sharedIndex)
- { }
-
- //overriding methods
- override protected int SourceCount
- {
- get { return m_sharedReader.Count; }
- }
- /// <summary>
- /// return a KeyValuePair of the current element and its key
- /// </summary>
- override public KeyValuePair<long, TSource> Current
- {
- get
- {
- //verify that MoveNext is at least called once before Current is called
- if (m_currentChunkSize == null)
- {
- throw new InvalidOperationException(Environment.GetResourceString("PartitionerStatic_CurrentCalledBeforeMoveNext"));
- }
-
- 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]);
- }
- }
- }
- }
-
-
-
- /// <summary>
- /// Inherits from DynamicPartitioners
- /// Provides customized implementation of GetOrderableDynamicPartitions_Factory method, to return an instance
- /// of EnumerableOfPartitionsForArray defined internally
- /// </summary>
- /// <typeparam name="TSource">Type of elements in the source data</typeparam>
- private class DynamicPartitionerForArray<TSource> : DynamicPartitionerForIndexRange_Abstract<TSource, TSource[]>
- {
- //constructor
- internal DynamicPartitionerForArray(TSource[] source)
- : base(source)
- { }
-
- //override methods
- override protected IEnumerable<KeyValuePair<long, TSource>> GetOrderableDynamicPartitions_Factory(TSource[] m_data)
- {
- return new InternalPartitionEnumerable(m_data);
- }
-
- /// <summary>
- /// Inherits from PartitionList_Abstract
- /// Provides customized implementation for source data of Array
- /// </summary>
- private class InternalPartitionEnumerable : IEnumerable<KeyValuePair<long, TSource>>
- {
- //reader through which we access the source data
- private readonly TSource[] m_sharedReader;
- private SharedLong m_sharedIndex;
-
- internal InternalPartitionEnumerable(TSource[] sharedReader)
- {
- m_sharedReader = sharedReader;
- m_sharedIndex = new SharedLong(-1);
- }
-
- IEnumerator IEnumerable.GetEnumerator()
- {
- return ((InternalPartitionEnumerable)this).GetEnumerator();
- }
-
-
- public IEnumerator<KeyValuePair<long, TSource>> GetEnumerator()
- {
- return new InternalPartitionEnumerator(m_sharedReader, m_sharedIndex);
- }
- }
-
- /// <summary>
- /// Inherits from DynamicPartitionEnumeratorForIndexRange_Abstract
- /// Provides customized implementation of SourceCount property and Current property for Array
- /// </summary>
- private class InternalPartitionEnumerator : DynamicPartitionEnumeratorForIndexRange_Abstract<TSource, TSource[]>
- {
- //constructor
- internal InternalPartitionEnumerator(TSource[] sharedReader, SharedLong sharedIndex)
- : base(sharedReader, sharedIndex)
- { }
-
- //overriding methods
- override protected int SourceCount
- {
- get { return m_sharedReader.Length; }
- }
-
- override public KeyValuePair<long, TSource> Current
- {
- get
- {
- //verify that MoveNext is at least called once before Current is called
- if (m_currentChunkSize == null)
- {
- throw new InvalidOperationException(Environment.GetResourceString("PartitionerStatic_CurrentCalledBeforeMoveNext"));
- }
-
- 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]);
- }
- }
- }
- }
- #endregion
-
-
- #region Static partitioning for IList and Array, abstract classes
- /// <summary>
- /// Static partitioning over IList.
- /// - dynamic and load-balance
- /// - Keys are ordered within each partition
- /// - Keys are ordered across partitions
- /// - Keys are normalized
- /// - Number of partitions is fixed once specified, and the elements of the source data are
- /// distributed to each partition as evenly as possible.
- /// </summary>
- /// <typeparam name="TSource">type of the elements</typeparam>
- /// <typeparam name="TCollection">Type of the source data collection</typeparam>
- private abstract class StaticIndexRangePartitioner<TSource, TCollection> : OrderablePartitioner<TSource>
- {
- protected StaticIndexRangePartitioner()
- : base(true, true, true)
- { }
-
- /// <summary>
- /// Abstract method to return the number of elements in the source data
- /// </summary>
- protected abstract int SourceCount { get; }
-
- /// <summary>
- /// Abstract method to create a partition that covers a range over source data,
- /// starting from "startIndex", ending at "endIndex"
- /// </summary>
- /// <param name="startIndex">start index of the current partition on the source data</param>
- /// <param name="endIndex">end index of the current partition on the source data</param>
- /// <returns>a partition enumerator over the specified range</returns>
- // The partitioning algorithm is implemented in GetOrderablePartitions method
- // This method delegates according to source data type IList/Array
- protected abstract IEnumerator<KeyValuePair<long, TSource>> CreatePartition(int startIndex, int endIndex);
-
- /// <summary>
- /// Overrides OrderablePartitioner.GetOrderablePartitions
- /// Return a list of partitions, each of which enumerate a fixed part of the source data
- /// The elements of the source data are distributed to each partition as evenly as possible.
- /// Specifically, if the total number of elements is N, and number of partitions is x, and N = a*x +b,
- /// where a is the quotient, and b is the remainder. Then the first b partitions each has a + 1 elements,
- /// and the last x-b partitions each has a elements.
- /// For example, if N=10, x =3, then
- /// partition 0 ranges [0,3],
- /// partition 1 ranges [4,6],
- /// partition 2 ranges [7,9].
- /// This also takes care of the situation of (x&gt;N), the last x-N partitions are empty enumerators.
- /// An empty enumerator is indicated by
- /// (m_startIndex == list.Count &amp;&amp; m_endIndex == list.Count -1)
- /// </summary>
- /// <param name="partitionCount">specified number of partitions</param>
- /// <returns>a list of partitions</returns>
- override public IList<IEnumerator<KeyValuePair<long, TSource>>> GetOrderablePartitions(int partitionCount)
- {
- if (partitionCount <= 0)
- {
- throw new ArgumentOutOfRangeException(nameof(partitionCount));
- }
-
- int quotient, remainder;
- quotient = Math.DivRem(SourceCount, partitionCount, out remainder);
-
- IEnumerator<KeyValuePair<long, TSource>>[] partitions = new IEnumerator<KeyValuePair<long, TSource>>[partitionCount];
- int lastEndIndex = -1;
- for (int i = 0; i < partitionCount; i++)
- {
- int startIndex = lastEndIndex + 1;
-
- if (i < remainder)
- {
- lastEndIndex = startIndex + quotient;
- }
- else
- {
- lastEndIndex = startIndex + quotient - 1;
- }
- partitions[i] = CreatePartition(startIndex, lastEndIndex);
- }
- return partitions;
- }
- }
-
- /// <summary>
- /// Static Partition for IList/Array.
- /// This class implements all methods required by IEnumerator interface, except for the Current property.
- /// Current Property is different for IList and Array. Arrays calls 'ldelem' instructions for faster element
- /// retrieval.
- /// </summary>
- //We assume the source collection is not being updated concurrently. Otherwise it will break the
- //static partitioning, since each partition operates on the source collection directly, it does
- //not have a local cache of the elements assigned to them.
- private abstract class StaticIndexRangePartition<TSource> : IEnumerator<KeyValuePair<long, TSource>>
- {
- //the start and end position in the source collection for the current partition
- //the partition is empty if and only if
- // (m_startIndex == m_data.Count && m_endIndex == m_data.Count-1)
- protected readonly int m_startIndex;
- protected readonly int m_endIndex;
-
- //the current index of the current partition while enumerating on the source collection
- protected volatile int m_offset;
-
- /// <summary>
- /// Constructs an instance of StaticIndexRangePartition
- /// </summary>
- /// <param name="startIndex">the start index in the source collection for the current partition </param>
- /// <param name="endIndex">the end index in the source collection for the current partition</param>
- protected StaticIndexRangePartition(int startIndex, int endIndex)
- {
- m_startIndex = startIndex;
- m_endIndex = endIndex;
- m_offset = startIndex - 1;
- }
-
- /// <summary>
- /// Current Property is different for IList and Array. Arrays calls 'ldelem' instructions for faster
- /// element retrieval.
- /// </summary>
- public abstract KeyValuePair<long, TSource> Current { get; }
-
- /// <summary>
- /// We don't dispose the source for IList and array
- /// </summary>
- public void Dispose()
- { }
-
- public void Reset()
- {
- throw new NotSupportedException();
- }
-
- /// <summary>
- /// Moves to the next item
- /// Before the first MoveNext is called: m_offset == m_startIndex-1;
- /// </summary>
- /// <returns>true if successful, false if there is no item left</returns>
- public bool MoveNext()
- {
- if (m_offset < m_endIndex)
- {
- m_offset++;
- return true;
- }
- else
- {
- //After we have enumerated over all elements, we set m_offset to m_endIndex +1.
- //The reason we do this is, for an empty enumerator, we need to tell the Current
- //property whether MoveNext has been called or not.
- //For an empty enumerator, it starts with (m_offset == m_startIndex-1 == m_endIndex),
- //and we don't set a new value to m_offset, then the above condition will always be
- //true, and the Current property will mistakenly assume MoveNext is never called.
- m_offset = m_endIndex + 1;
- return false;
- }
- }
-
- Object IEnumerator.Current
- {
- get
- {
- return ((StaticIndexRangePartition<TSource>)this).Current;
- }
- }
- }
- #endregion
-
- #region Static partitioning for IList
- /// <summary>
- /// Inherits from StaticIndexRangePartitioner
- /// Provides customized implementation of SourceCount and CreatePartition
- /// </summary>
- /// <typeparam name="TSource"></typeparam>
- private class StaticIndexRangePartitionerForIList<TSource> : StaticIndexRangePartitioner<TSource, IList<TSource>>
- {
- IList<TSource> m_list;
- internal StaticIndexRangePartitionerForIList(IList<TSource> list)
- : base()
- {
- Debug.Assert(list != null);
- m_list = list;
- }
- override protected int SourceCount
- {
- get { return m_list.Count; }
- }
- override protected IEnumerator<KeyValuePair<long, TSource>> CreatePartition(int startIndex, int endIndex)
- {
- return new StaticIndexRangePartitionForIList<TSource>(m_list, startIndex, endIndex);
- }
- }
-
- /// <summary>
- /// Inherits from StaticIndexRangePartition
- /// Provides customized implementation of Current property
- /// </summary>
- /// <typeparam name="TSource"></typeparam>
- private class StaticIndexRangePartitionForIList<TSource> : StaticIndexRangePartition<TSource>
- {
- //the source collection shared by all partitions
- private volatile IList<TSource> m_list;
-
- internal StaticIndexRangePartitionForIList(IList<TSource> list, int startIndex, int endIndex)
- : base(startIndex, endIndex)
- {
- Debug.Assert(startIndex >= 0 && endIndex <= list.Count - 1);
- m_list = list;
- }
-
- override public KeyValuePair<long, TSource> Current
- {
- get
- {
- //verify that MoveNext is at least called once before Current is called
- if (m_offset < m_startIndex)
- {
- throw new InvalidOperationException(Environment.GetResourceString("PartitionerStatic_CurrentCalledBeforeMoveNext"));
- }
-
- Debug.Assert(m_offset >= m_startIndex && m_offset <= m_endIndex);
- return (new KeyValuePair<long, TSource>(m_offset, m_list[m_offset]));
- }
- }
- }
- #endregion
-
- #region static partitioning for Arrays
- /// <summary>
- /// Inherits from StaticIndexRangePartitioner
- /// Provides customized implementation of SourceCount and CreatePartition for Array
- /// </summary>
- private class StaticIndexRangePartitionerForArray<TSource> : StaticIndexRangePartitioner<TSource, TSource[]>
- {
- TSource[] m_array;
- internal StaticIndexRangePartitionerForArray(TSource[] array)
- : base()
- {
- Debug.Assert(array != null);
- m_array = array;
- }
- override protected int SourceCount
- {
- get { return m_array.Length; }
- }
- override protected IEnumerator<KeyValuePair<long, TSource>> CreatePartition(int startIndex, int endIndex)
- {
- return new StaticIndexRangePartitionForArray<TSource>(m_array, startIndex, endIndex);
- }
- }
-
- /// <summary>
- /// Inherits from StaticIndexRangePartitioner
- /// Provides customized implementation of SourceCount and CreatePartition
- /// </summary>
- private class StaticIndexRangePartitionForArray<TSource> : StaticIndexRangePartition<TSource>
- {
- //the source collection shared by all partitions
- private volatile TSource[] m_array;
-
- internal StaticIndexRangePartitionForArray(TSource[] array, int startIndex, int endIndex)
- : base(startIndex, endIndex)
- {
- Debug.Assert(startIndex >= 0 && endIndex <= array.Length - 1);
- m_array = array;
- }
-
- override public KeyValuePair<long, TSource> Current
- {
- get
- {
- //verify that MoveNext is at least called once before Current is called
- if (m_offset < m_startIndex)
- {
- throw new InvalidOperationException(Environment.GetResourceString("PartitionerStatic_CurrentCalledBeforeMoveNext"));
- }
-
- Debug.Assert(m_offset >= m_startIndex && m_offset <= m_endIndex);
- return (new KeyValuePair<long, TSource>(m_offset, m_array[m_offset]));
- }
- }
- }
- #endregion
-
-
- #region Utility functions
- /// <summary>
- /// A very simple primitive that allows us to share a value across multiple threads.
- /// </summary>
- /// <typeparam name="TSource"></typeparam>
- private class SharedInt
- {
- internal volatile int Value;
-
- internal SharedInt(int value)
- {
- this.Value = value;
- }
-
- }
-
- /// <summary>
- /// A very simple primitive that allows us to share a value across multiple threads.
- /// </summary>
- private class SharedBool
- {
- internal volatile bool Value;
-
- internal SharedBool(bool value)
- {
- this.Value = value;
- }
-
- }
-
- /// <summary>
- /// A very simple primitive that allows us to share a value across multiple threads.
- /// </summary>
- private class SharedLong
- {
- internal long Value;
- internal SharedLong(long value)
- {
- this.Value = value;
- }
-
- }
-
- //--------------------
- // The following part calculates the default chunk size. It is copied from System.Linq.Parallel.Scheduling,
- // because mscorlib.dll cannot access System.Linq.Parallel.Scheduling
- //--------------------
-
- // The number of bytes we want "chunks" to be, when partitioning, etc. We choose 4 cache
- // lines worth, assuming 128b cache line. Most (popular) architectures use 64b cache lines,
- // but choosing 128b works for 64b too whereas a multiple of 64b isn't necessarily sufficient
- // for 128b cache systems. So 128b it is.
- private const int DEFAULT_BYTES_PER_CHUNK = 128 * 4;
-
- private static int GetDefaultChunkSize<TSource>()
- {
- int chunkSize;
-
- if (typeof(TSource).IsValueType)
- {
- chunkSize = 128;
- }
- else
- {
- 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 3ee392bb0d..0c5d8b2387 100644
--- a/src/mscorlib/src/System/Collections/DictionaryEntry.cs
+++ b/src/mscorlib/src/System/Collections/DictionaryEntry.cs
@@ -16,9 +16,9 @@
namespace System.Collections {
using System;
+ using System.ComponentModel;
// A DictionaryEntry holds a key and a value from a dictionary.
// It is returned by IDictionaryEnumerator::GetEntry().
-[System.Runtime.InteropServices.ComVisible(true)]
[Serializable]
public struct DictionaryEntry
{
@@ -52,7 +52,7 @@ namespace System.Collections {
}
}
- // BLOCKED (do not add now): [EditorBrowsable(EditorBrowsableState.Never)]
+ [EditorBrowsable(EditorBrowsableState.Never)]
public void Deconstruct(out object key, out object value)
{
key = Key;
diff --git a/src/mscorlib/src/System/Collections/Generic/Comparer.cs b/src/mscorlib/src/System/Collections/Generic/Comparer.cs
index 4f06b0af69..056843a606 100644
--- a/src/mscorlib/src/System/Collections/Generic/Comparer.cs
+++ b/src/mscorlib/src/System/Collections/Generic/Comparer.cs
@@ -265,9 +265,6 @@ namespace System.Collections.Generic
Debug.Assert(typeof(T).IsEnum, "This type is only intended to be used to compare enums!");
}
- // Used by the serialization engine.
- private Int64EnumComparer(SerializationInfo info, StreamingContext context) { }
-
public override int Compare(T x, T y)
{
long lx = JitHelpers.UnsafeEnumCastLong(x);
diff --git a/src/mscorlib/src/System/Collections/Generic/DebugView.cs b/src/mscorlib/src/System/Collections/Generic/DebugView.cs
index d0711e551e..27c5011147 100644
--- a/src/mscorlib/src/System/Collections/Generic/DebugView.cs
+++ b/src/mscorlib/src/System/Collections/Generic/DebugView.cs
@@ -16,7 +16,6 @@
namespace System.Collections.Generic {
using System;
using System.Collections.ObjectModel;
- using System.Security.Permissions;
using System.Diagnostics;
using System.Diagnostics.Contracts;
diff --git a/src/mscorlib/src/System/Collections/Generic/Dictionary.cs b/src/mscorlib/src/System/Collections/Generic/Dictionary.cs
index c2b2da9ad2..7b60e31031 100644
--- a/src/mscorlib/src/System/Collections/Generic/Dictionary.cs
+++ b/src/mscorlib/src/System/Collections/Generic/Dictionary.cs
@@ -48,12 +48,10 @@ namespace System.Collections.Generic {
using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Runtime.Serialization;
- using System.Security.Permissions;
[DebuggerTypeProxy(typeof(Mscorlib_DictionaryDebugView<,>))]
[DebuggerDisplay("Count = {Count}")]
[Serializable]
- [System.Runtime.InteropServices.ComVisible(false)]
public class Dictionary<TKey,TValue>: IDictionary<TKey,TValue>, IDictionary, IReadOnlyDictionary<TKey, TValue>, ISerializable, IDeserializationCallback {
private struct Entry {
diff --git a/src/mscorlib/src/System/Collections/Generic/EqualityComparer.cs b/src/mscorlib/src/System/Collections/Generic/EqualityComparer.cs
index 3731114119..0f9259d2f3 100644
--- a/src/mscorlib/src/System/Collections/Generic/EqualityComparer.cs
+++ b/src/mscorlib/src/System/Collections/Generic/EqualityComparer.cs
@@ -6,7 +6,6 @@ using System;
using System.Collections;
using System.Collections.Generic;
using System.Security;
-using System.Runtime.Serialization;
namespace System.Collections.Generic
{
@@ -367,7 +366,7 @@ namespace System.Collections.Generic
}
[Serializable]
- internal class EnumEqualityComparer<T> : EqualityComparer<T>, ISerializable where T : struct
+ internal class EnumEqualityComparer<T> : EqualityComparer<T> where T : struct
{
[Pure]
public override bool Equals(T x, T y) {
@@ -384,16 +383,6 @@ namespace System.Collections.Generic
public EnumEqualityComparer() { }
- // This is used by the serialization engine.
- protected EnumEqualityComparer(SerializationInfo information, StreamingContext context) { }
-
- public void GetObjectData(SerializationInfo info, StreamingContext context) {
- // For back-compat we need to serialize the comparers for enums with underlying types other than int as ObjectEqualityComparer
- if (Type.GetTypeCode(Enum.GetUnderlyingType(typeof(T))) != TypeCode.Int32) {
- info.SetType(typeof(ObjectEqualityComparer<T>));
- }
- }
-
// Equals method for the comparer itself.
public override bool Equals(Object obj) =>
obj != null && GetType() == obj.GetType();
@@ -427,13 +416,10 @@ namespace System.Collections.Generic
}
[Serializable]
- internal sealed class SByteEnumEqualityComparer<T> : EnumEqualityComparer<T>, ISerializable where T : struct
+ internal sealed class SByteEnumEqualityComparer<T> : EnumEqualityComparer<T> where T : struct
{
public SByteEnumEqualityComparer() { }
- // This is used by the serialization engine.
- public SByteEnumEqualityComparer(SerializationInfo information, StreamingContext context) { }
-
[Pure]
public override int GetHashCode(T obj) {
int x_final = System.Runtime.CompilerServices.JitHelpers.UnsafeEnumCast(obj);
@@ -442,13 +428,10 @@ namespace System.Collections.Generic
}
[Serializable]
- internal sealed class ShortEnumEqualityComparer<T> : EnumEqualityComparer<T>, ISerializable where T : struct
+ internal sealed class ShortEnumEqualityComparer<T> : EnumEqualityComparer<T> where T : struct
{
public ShortEnumEqualityComparer() { }
- // This is used by the serialization engine.
- public ShortEnumEqualityComparer(SerializationInfo information, StreamingContext context) { }
-
[Pure]
public override int GetHashCode(T obj) {
int x_final = System.Runtime.CompilerServices.JitHelpers.UnsafeEnumCast(obj);
@@ -457,7 +440,7 @@ namespace System.Collections.Generic
}
[Serializable]
- internal sealed class LongEnumEqualityComparer<T> : EqualityComparer<T>, ISerializable where T : struct
+ internal sealed class LongEnumEqualityComparer<T> : EqualityComparer<T> where T : struct
{
[Pure]
public override bool Equals(T x, T y) {
@@ -481,16 +464,6 @@ namespace System.Collections.Generic
public LongEnumEqualityComparer() { }
- // This is used by the serialization engine.
- public LongEnumEqualityComparer(SerializationInfo information, StreamingContext context) { }
-
- public void GetObjectData(SerializationInfo info, StreamingContext context)
- {
- // The LongEnumEqualityComparer does not exist on 4.0 so we need to serialize this comparer as ObjectEqualityComparer
- // to allow for roundtrip between 4.0 and 4.5.
- info.SetType(typeof(ObjectEqualityComparer<T>));
- }
-
internal override int IndexOf(T[] array, T value, int startIndex, int count)
{
long toFind = JitHelpers.UnsafeEnumCastLong(value);
@@ -515,122 +488,4 @@ namespace System.Collections.Generic
return -1;
}
}
-
-#if FEATURE_RANDOMIZED_STRING_HASHING
- // This type is not serializeable by design. It does not exist in previous versions and will be removed
- // Once we move the framework to using secure hashing by default.
- internal sealed class RandomizedStringEqualityComparer : IEqualityComparer<String>, IEqualityComparer, IWellKnownStringEqualityComparer
- {
- private long _entropy;
-
- public RandomizedStringEqualityComparer() {
- _entropy = HashHelpers.GetEntropy();
- }
-
- public new bool Equals(object x, object y) {
- if (x == y) return true;
- if (x == null || y == null) return false;
- if ((x is string) && (y is string)) return Equals((string)x, (string)y);
- ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_InvalidArgumentForComparison);
- return false;
- }
-
- [Pure]
- public bool Equals(string x, string y) {
- if (x != null) {
- if (y != null) return x.Equals(y);
- return false;
- }
- if (y != null) return false;
- return true;
- }
-
- [Pure]
- public int GetHashCode(String obj) {
- if(obj == null) return 0;
- return String.InternalMarvin32HashString(obj, obj.Length, _entropy);
- }
-
- [Pure]
- public int GetHashCode(Object obj) {
- if(obj == null) return 0;
-
- string sObj = obj as string;
- if(sObj != null) return String.InternalMarvin32HashString(sObj, sObj.Length, _entropy);
-
- return obj.GetHashCode();
- }
-
- // Equals method for the comparer itself.
- public override bool Equals(Object obj) {
- RandomizedStringEqualityComparer comparer = obj as RandomizedStringEqualityComparer;
- return (comparer != null) && (this._entropy == comparer._entropy);
- }
-
- public override int GetHashCode() {
- return (this.GetType().GetHashCode() ^ ((int) (_entropy & 0x7FFFFFFF)));
- }
-
-
- IEqualityComparer IWellKnownStringEqualityComparer.GetRandomizedEqualityComparer() {
- return new RandomizedStringEqualityComparer();
- }
-
- // We want to serialize the old comparer.
- IEqualityComparer IWellKnownStringEqualityComparer.GetEqualityComparerForSerialization() {
- return EqualityComparer<string>.Default;
- }
- }
-
- // This type is not serializeable by design. It does not exist in previous versions and will be removed
- // Once we move the framework to using secure hashing by default.
- internal sealed class RandomizedObjectEqualityComparer : IEqualityComparer, IWellKnownStringEqualityComparer
- {
- private long _entropy;
-
- public RandomizedObjectEqualityComparer() {
- _entropy = HashHelpers.GetEntropy();
- }
-
- [Pure]
- public new bool Equals(Object x, Object y) {
- if (x != null) {
- if (y != null) return x.Equals(y);
- return false;
- }
- if (y != null) return false;
- return true;
- }
-
- [Pure]
- public int GetHashCode(Object obj) {
- if(obj == null) return 0;
-
- string sObj = obj as string;
- if(sObj != null) return String.InternalMarvin32HashString(sObj, sObj.Length, _entropy);
-
- return obj.GetHashCode();
- }
-
- // Equals method for the comparer itself.
- public override bool Equals(Object obj){
- RandomizedObjectEqualityComparer comparer = obj as RandomizedObjectEqualityComparer;
- return (comparer != null) && (this._entropy == comparer._entropy);
- }
-
- public override int GetHashCode() {
- return (this.GetType().GetHashCode() ^ ((int) (_entropy & 0x7FFFFFFF)));
- }
-
- IEqualityComparer IWellKnownStringEqualityComparer.GetRandomizedEqualityComparer() {
- return new RandomizedObjectEqualityComparer();
- }
-
- // We want to serialize the old comparer, which in this case was null.
- IEqualityComparer IWellKnownStringEqualityComparer.GetEqualityComparerForSerialization() {
- return null;
- }
- }
-#endif
}
-
diff --git a/src/mscorlib/src/System/Collections/Generic/KeyNotFoundException.cs b/src/mscorlib/src/System/Collections/Generic/KeyNotFoundException.cs
index ffcd0405fd..1cd18cf808 100644
--- a/src/mscorlib/src/System/Collections/Generic/KeyNotFoundException.cs
+++ b/src/mscorlib/src/System/Collections/Generic/KeyNotFoundException.cs
@@ -20,7 +20,6 @@ namespace System.Collections.Generic {
using System.Runtime.Serialization;
[Serializable]
- [System.Runtime.InteropServices.ComVisible(true)]
public class KeyNotFoundException : SystemException, ISerializable {
public KeyNotFoundException ()
diff --git a/src/mscorlib/src/System/Collections/Generic/KeyValuePair.cs b/src/mscorlib/src/System/Collections/Generic/KeyValuePair.cs
index ad9f7472aa..ba98adad7d 100644
--- a/src/mscorlib/src/System/Collections/Generic/KeyValuePair.cs
+++ b/src/mscorlib/src/System/Collections/Generic/KeyValuePair.cs
@@ -16,6 +16,7 @@
namespace System.Collections.Generic {
using System;
+ using System.ComponentModel;
using System.Text;
// Provides the Create factory method for KeyValuePair<TKey, TValue>.
@@ -63,7 +64,7 @@ namespace System.Collections.Generic {
return StringBuilderCache.GetStringAndRelease(s);
}
- // BLOCKED (do not add now): [EditorBrowsable(EditorBrowsableState.Never)]
+ [EditorBrowsable(EditorBrowsableState.Never)]
public void Deconstruct(out TKey key, out TValue value)
{
key = Key;
diff --git a/src/mscorlib/src/System/Collections/Generic/List.cs b/src/mscorlib/src/System/Collections/Generic/List.cs
index 3e2947f5f9..362e26599d 100644
--- a/src/mscorlib/src/System/Collections/Generic/List.cs
+++ b/src/mscorlib/src/System/Collections/Generic/List.cs
@@ -20,7 +20,6 @@ namespace System.Collections.Generic {
using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Collections.ObjectModel;
- using System.Security.Permissions;
// Implements a variable-size List that uses an array of objects to store the
// elements. A List has a capacity, which is the allocated length
@@ -927,7 +926,9 @@ namespace System.Collections.Generic {
ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_InvalidOffLen);
Contract.EndContractBlock();
- Array.Reverse(_items, index, count);
+ if (count > 1) {
+ Array.Reverse(_items, index, count);
+ }
_version++;
}
@@ -966,7 +967,9 @@ namespace System.Collections.Generic {
ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_InvalidOffLen);
Contract.EndContractBlock();
- Array.Sort<T>(_items, index, count, comparer);
+ if (count > 1) {
+ Array.Sort<T>(_items, index, count, comparer);
+ }
_version++;
}
@@ -976,9 +979,10 @@ namespace System.Collections.Generic {
}
Contract.EndContractBlock();
- if( _size > 0) {
+ if (_size > 1) {
ArraySortHelper<T>.Sort(_items, 0, _size, comparison);
}
+ _version++;
}
// ToArray returns an array containing the contents of the List.
diff --git a/src/mscorlib/src/System/Collections/Hashtable.cs b/src/mscorlib/src/System/Collections/Hashtable.cs
index d4c7d8d673..d1831dd97d 100644
--- a/src/mscorlib/src/System/Collections/Hashtable.cs
+++ b/src/mscorlib/src/System/Collections/Hashtable.cs
@@ -17,7 +17,6 @@ namespace System.Collections {
using System;
using System.Runtime;
using System.Runtime.Serialization;
- using System.Security.Permissions;
using System.Diagnostics;
using System.Threading;
using System.Runtime.CompilerServices;
@@ -66,9 +65,8 @@ namespace System.Collections {
//
[DebuggerTypeProxy(typeof(System.Collections.Hashtable.HashtableDebugView))]
[DebuggerDisplay("Count = {Count}")]
- [System.Runtime.InteropServices.ComVisible(true)]
[Serializable]
- public class Hashtable : IDictionary, ISerializable, IDeserializationCallback, ICloneable {
+ internal class Hashtable : IDictionary, ISerializable, IDeserializationCallback, ICloneable {
/*
Implementation Notes:
The generic Dictionary was copied from Hashtable's source - any bug
@@ -165,75 +163,6 @@ namespace System.Collections {
private IEqualityComparer _keycomparer;
private Object _syncRoot;
- [Obsolete("Please use EqualityComparer property.")]
- protected IHashCodeProvider hcp
- {
- get
- {
- if( _keycomparer is CompatibleComparer) {
- return ((CompatibleComparer)_keycomparer).HashCodeProvider;
- }
- else if( _keycomparer == null) {
- return null;
- }
- else {
- throw new ArgumentException(Environment.GetResourceString("Arg_CannotMixComparisonInfrastructure"));
- }
- }
- set
- {
- if (_keycomparer is CompatibleComparer) {
- CompatibleComparer keyComparer = (CompatibleComparer)_keycomparer;
- _keycomparer = new CompatibleComparer(keyComparer.Comparer, value);
- }
- else if( _keycomparer == null) {
- _keycomparer = new CompatibleComparer((IComparer)null, value);
- }
- else {
- throw new ArgumentException(Environment.GetResourceString("Arg_CannotMixComparisonInfrastructure"));
- }
- }
- }
-
-
- [Obsolete("Please use KeyComparer properties.")]
- protected IComparer comparer
- {
- get
- {
- if( _keycomparer is CompatibleComparer) {
- return ((CompatibleComparer)_keycomparer).Comparer;
- }
- else if( _keycomparer == null) {
- return null;
- }
- else {
- throw new ArgumentException(Environment.GetResourceString("Arg_CannotMixComparisonInfrastructure"));
- }
- }
- set
- {
- if (_keycomparer is CompatibleComparer) {
- CompatibleComparer keyComparer = (CompatibleComparer)_keycomparer;
- _keycomparer = new CompatibleComparer(value, keyComparer.HashCodeProvider);
- }
- else if( _keycomparer == null) {
- _keycomparer = new CompatibleComparer(value, (IHashCodeProvider)null);
- }
- else {
- throw new ArgumentException(Environment.GetResourceString("Arg_CannotMixComparisonInfrastructure"));
- }
- }
- }
-
- protected IEqualityComparer EqualityComparer
- {
- get
- {
- return _keycomparer;
- }
- }
-
// Note: this constructor is a bogus constructor that does nothing
// and is for use only with SyncHashtable.
internal Hashtable( bool trash )
@@ -290,126 +219,31 @@ namespace System.Collections {
Debug.Assert( loadsize < hashsize, "Invalid hashtable loadsize!");
}
- // Constructs a new hashtable with the given initial capacity and load
- // factor. The capacity argument serves as an indication of the
- // number of entries the hashtable will contain. When this number (or an
- // approximation) is known, specifying it in the constructor can eliminate
- // a number of resizing operations that would otherwise be performed when
- // elements are added to the hashtable. The loadFactor argument
- // indicates the maximum ratio of hashtable entries to hashtable buckets.
- // Smaller load factors cause faster average lookup times at the cost of
- // increased memory consumption. A load factor of 1.0 generally provides
- // the best balance between speed and size. The hcp argument
- // is used to specify an Object that will provide hash codes for all
- // the Objects in the table. Using this, you can in effect override
- // GetHashCode() on each Object using your own hash function. The
- // comparer argument will let you specify a custom function for
- // comparing keys. By specifying user-defined objects for hcp
- // and comparer, users could make a hash table using strings
- // as keys do case-insensitive lookups.
- //
- [Obsolete("Please use Hashtable(int, float, IEqualityComparer) instead.")]
- public Hashtable(int capacity, float loadFactor, IHashCodeProvider hcp, IComparer comparer) : this(capacity, loadFactor) {
- if (hcp == null && comparer == null) {
- this._keycomparer = null;
- }
- else {
- this._keycomparer = new CompatibleComparer(comparer,hcp);
- }
- }
-
public Hashtable(int capacity, float loadFactor, IEqualityComparer equalityComparer) : this(capacity, loadFactor) {
this._keycomparer = equalityComparer;
}
-
- // Constructs a new hashtable using a custom hash function
- // and a custom comparison function for keys. This will enable scenarios
- // such as doing lookups with case-insensitive strings.
- //
- [Obsolete("Please use Hashtable(IEqualityComparer) instead.")]
- public Hashtable(IHashCodeProvider hcp, IComparer comparer) : this(0, 1.0f, hcp, comparer) {
- }
public Hashtable(IEqualityComparer equalityComparer) : this(0, 1.0f, equalityComparer) {
}
-
- // Constructs a new hashtable using a custom hash function
- // and a custom comparison function for keys. This will enable scenarios
- // such as doing lookups with case-insensitive strings.
- //
- [Obsolete("Please use Hashtable(int, IEqualityComparer) instead.")]
- public Hashtable(int capacity, IHashCodeProvider hcp, IComparer comparer)
- : this(capacity, 1.0f, hcp, comparer) {
- }
public Hashtable(int capacity, IEqualityComparer equalityComparer)
: this(capacity, 1.0f, equalityComparer) {
}
-
- // Constructs a new hashtable containing a copy of the entries in the given
- // dictionary. The hashtable is created with a load factor of 1.0.
- //
- public Hashtable(IDictionary d) : this(d, 1.0f) {
- }
-
- // Constructs a new hashtable containing a copy of the entries in the given
- // dictionary. The hashtable is created with the given load factor.
- //
- public Hashtable(IDictionary d, float loadFactor)
- : this(d, loadFactor, (IEqualityComparer)null) {
- }
-
- [Obsolete("Please use Hashtable(IDictionary, IEqualityComparer) instead.")]
- public Hashtable(IDictionary d, IHashCodeProvider hcp, IComparer comparer)
- : this(d, 1.0f, hcp, comparer) {
- }
-
- public Hashtable(IDictionary d, IEqualityComparer equalityComparer)
- : this(d, 1.0f, equalityComparer) {
- }
- [Obsolete("Please use Hashtable(IDictionary, float, IEqualityComparer) instead.")]
- 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(nameof(d), Environment.GetResourceString("ArgumentNull_Dictionary"));
- Contract.EndContractBlock();
-
- IDictionaryEnumerator e = d.GetEnumerator();
- while (e.MoveNext()) Add(e.Key, e.Value);
- }
-
- public Hashtable(IDictionary d, float loadFactor, IEqualityComparer equalityComparer)
- : this((d != null ? d.Count : 0), loadFactor, equalityComparer) {
- if (d==null)
- throw new ArgumentNullException(nameof(d), Environment.GetResourceString("ArgumentNull_Dictionary"));
- Contract.EndContractBlock();
-
- IDictionaryEnumerator e = d.GetEnumerator();
- while (e.MoveNext()) Add(e.Key, e.Value);
- }
-
- protected Hashtable(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 reasonable estimate that GetHashCode is not going to fail. For the time being,
- //we'll just cache this. The graph is not valid until OnDeserialization has been called.
- HashHelpers.SerializationInfoTable.Add(this, info);
- }
-
- // ‘InitHash’ is basically an implementation of classic DoubleHashing (see http://en.wikipedia.org/wiki/Double_hashing)
+ // InitHash is basically an implementation of classic DoubleHashing (see http://en.wikipedia.org/wiki/Double_hashing)
//
- // 1) The only ‘correctness’ requirement is that the ‘increment’ used to probe
+ // 1) The only correctness requirement is that the increment used to probe
// a. Be non-zero
- // b. Be relatively prime to the table size ‘hashSize’. (This is needed to insure you probe all entries in the table before you ‘wrap’ and visit entries already probed)
+ // b. Be relatively prime to the table size hashSize. (This is needed to insure you probe all entries in the table before you wrap and visit entries already probed)
// 2) Because we choose table sizes to be primes, we just need to insure that the increment is 0 < incr < hashSize
//
// Thus this function would work: Incr = 1 + (seed % (hashSize-1))
//
- // While this works well for ‘uniformly distributed’ keys, in practice, non-uniformity is common.
- // In particular in practice we can see ‘mostly sequential’ where you get long clusters of keys that ‘pack’.
- // To avoid bad behavior you want it to be the case that the increment is ‘large’ even for ‘small’ values (because small
- // values tend to happen more in practice). Thus we multiply ‘seed’ by a number that will make these small values
- // bigger (and not hurt large values). We picked HashPrime (101) because it was prime, and if ‘hashSize-1’ is not a multiple of HashPrime
+ // While this works well for uniformly distributed keys, in practice, non-uniformity is common.
+ // In particular in practice we can see mostly sequential where you get long clusters of keys that pack.
+ // To avoid bad behavior you want it to be the case that the increment is large even for small values (because small
+ // values tend to happen more in practice). Thus we multiply seed by a number that will make these small values
+ // bigger (and not hurt large values). We picked HashPrime (101) because it was prime, and if hashSize-1 is not a multiple of HashPrime
// (enforced in GetPrime), then incr has the potential of being every value from 1 to hashSize-1. The choice was largely arbitrary.
//
// Computes the hash function: H(key, i) = h1(key) + i*h2(key, hashSize).
@@ -439,7 +273,6 @@ namespace System.Collections {
}
// Removes all entries from this hashtable.
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
public virtual void Clear() {
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.");
@@ -517,29 +350,6 @@ 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
- // search and is thus be substantially slower than the ContainsKey
- // method.
- //
- public virtual bool ContainsValue(Object value) {
-
- if (value == null) {
- for (int i = buckets.Length; --i >= 0;) {
- if (buckets[i].key != null && buckets[i].key != buckets && buckets[i].val == null)
- return true;
- }
- }
- else {
- for (int i = buckets.Length; --i >= 0;) {
- Object val = buckets[i].val;
- if (val!=null && val.Equals(value)) return true;
- }
- }
- return false;
- }
// Copies the keys of this hashtable to a given array starting at a given
// index. This method is used by the implementation of the CopyTo method in
@@ -590,25 +400,6 @@ namespace System.Collections {
CopyEntries(array, arrayIndex);
}
- // Copies the values in this Hashtable to an KeyValuePairs array.
- // KeyValuePairs is different from Dictionary Entry in that it has special
- // debugger attributes on its fields.
-
- internal virtual KeyValuePairs[] ToKeyValuePairsArray() {
-
- KeyValuePairs[] array = new KeyValuePairs[count];
- int index = 0;
- bucket[] lbuckets = buckets;
- for (int i = lbuckets.Length; --i >= 0;) {
- Object keyv = lbuckets[i].key;
- if ((keyv != null) && (keyv != buckets)){
- array[index++] = new KeyValuePairs(keyv,lbuckets[i].val);
- }
- }
-
- return array;
- }
-
// Copies the values of this hashtable to a given array starting at a given
// index. This method is used by the implementation of the CopyTo method in
@@ -720,7 +511,6 @@ namespace System.Collections {
version++;
}
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
private void rehash( int newsize, bool forceNewHashCode ) {
// reset occupancy
@@ -853,7 +643,6 @@ namespace System.Collections {
// Inserts an entry into this hashtable. This method is called from the Set
// and Add methods. If the add parameter is true and the given key already
// exists in the hashtable, an exception is thrown.
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
private void Insert (Object key, Object nvalue, bool add) {
if (key == null) {
throw new ArgumentNullException(nameof(key), Environment.GetResourceString("ArgumentNull_Key"));
@@ -987,7 +776,6 @@ namespace System.Collections {
// key exists in the hashtable, it is removed. An ArgumentException is
// thrown if the key is null.
//
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
public virtual void Remove(Object key) {
if (key == null) {
throw new ArgumentNullException(nameof(key), Environment.GetResourceString("ArgumentNull_Key"));
@@ -1293,13 +1081,6 @@ namespace System.Collections {
internal SyncHashtable(Hashtable table) : base(false) {
_table = table;
}
-
- internal SyncHashtable(SerializationInfo info, StreamingContext context) : base (info, context) {
- _table = (Hashtable)info.GetValue("ParentTable", typeof(Hashtable));
- if (_table==null) {
- throw new SerializationException(Environment.GetResourceString("Serialization_InsufficientState"));
- }
- }
/*================================GetObjectData=================================
@@ -1379,12 +1160,6 @@ namespace System.Collections {
return _table.ContainsKey(key);
}
- public override bool ContainsValue(Object key) {
- lock(_table.SyncRoot) {
- return _table.ContainsValue(key);
- }
- }
-
public override void CopyTo(Array array, int arrayIndex) {
lock (_table.SyncRoot) {
_table.CopyTo(array, arrayIndex);
@@ -1438,10 +1213,6 @@ namespace System.Collections {
public override void OnDeserialization(Object sender) {
return;
}
-
- internal override KeyValuePairs[] ToKeyValuePairsArray() {
- return _table.ToKeyValuePairsArray();
- }
}
@@ -1539,23 +1310,6 @@ namespace System.Collections {
// internal debug view class for hashtable
internal class HashtableDebugView {
private Hashtable hashtable;
-
- public HashtableDebugView( Hashtable hashtable) {
- if( hashtable == null) {
- throw new ArgumentNullException(nameof(hashtable));
- }
- Contract.EndContractBlock();
-
- this.hashtable = hashtable;
- }
-
-
- [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)]
- public KeyValuePairs[] Items {
- get {
- return hashtable.ToKeyValuePairsArray();
- }
- }
}
}
@@ -1605,7 +1359,6 @@ namespace System.Collections {
}
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
public static bool IsPrime(int candidate)
{
if ((candidate & 1) != 0)
@@ -1621,7 +1374,6 @@ namespace System.Collections {
return (candidate == 2);
}
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
public static int GetPrime(int min)
{
if (min < 0)
@@ -1644,11 +1396,6 @@ namespace System.Collections {
return min;
}
- public static int GetMinPrime()
- {
- return primes[0];
- }
-
// Returns size of hashtable to grow to.
public static int ExpandPrime(int oldSize)
{
@@ -1670,33 +1417,6 @@ namespace System.Collections {
public const int MaxPrimeArrayLength = 0x7FEFFFFD;
#if FEATURE_RANDOMIZED_STRING_HASHING
- public static bool IsWellKnownEqualityComparer(object comparer)
- {
- return (comparer == null || comparer == System.Collections.Generic.EqualityComparer<string>.Default || comparer is IWellKnownStringEqualityComparer);
- }
-
- public static IEqualityComparer GetRandomizedEqualityComparer(object comparer)
- {
- Debug.Assert(comparer == null || comparer == System.Collections.Generic.EqualityComparer<string>.Default || comparer is IWellKnownStringEqualityComparer);
-
- if(comparer == null) {
- return new System.Collections.Generic.RandomizedObjectEqualityComparer();
- }
-
- if(comparer == System.Collections.Generic.EqualityComparer<string>.Default) {
- return new System.Collections.Generic.RandomizedStringEqualityComparer();
- }
-
- IWellKnownStringEqualityComparer cmp = comparer as IWellKnownStringEqualityComparer;
-
- if(cmp != null) {
- return cmp.GetRandomizedEqualityComparer();
- }
-
- Debug.Assert(false, "Missing case in GetRandomizedEqualityComparer!");
-
- return null;
- }
public static object GetEqualityComparerForSerialization(object comparer)
{
@@ -1716,33 +1436,8 @@ namespace System.Collections {
}
private const int bufferSize = 1024;
- private static byte[] data;
private static int currentIndex = bufferSize;
private static readonly object lockObj = new Object();
-
- internal static long GetEntropy()
- {
- lock(lockObj) {
- long ret;
-
- if(currentIndex == bufferSize)
- {
- if(data == null)
- {
- data = new byte[bufferSize];
- Debug.Assert(bufferSize % 8 == 0, "We increment our current index by 8, so our buffer size must be a multiple of 8");
- }
-
- Microsoft.Win32.Win32Native.Random(true, data, data.Length);
- currentIndex = 0;
- }
-
- ret = BitConverter.ToInt64(data, currentIndex);
- currentIndex += 8;
-
- return ret;
- }
- }
#endif // FEATURE_RANDOMIZED_STRING_HASHING
}
}
diff --git a/src/mscorlib/src/System/Collections/ICollection.cs b/src/mscorlib/src/System/Collections/ICollection.cs
index 6d4d6e1a93..088928a0ef 100644
--- a/src/mscorlib/src/System/Collections/ICollection.cs
+++ b/src/mscorlib/src/System/Collections/ICollection.cs
@@ -19,7 +19,6 @@ namespace System.Collections {
// Base interface for all collections, defining enumerators, size, and
// synchronization methods.
- [System.Runtime.InteropServices.ComVisible(true)]
public interface ICollection : IEnumerable
{
// Interfaces are not serialable
diff --git a/src/mscorlib/src/System/Collections/IComparer.cs b/src/mscorlib/src/System/Collections/IComparer.cs
index d5a3448934..574af1a768 100644
--- a/src/mscorlib/src/System/Collections/IComparer.cs
+++ b/src/mscorlib/src/System/Collections/IComparer.cs
@@ -21,7 +21,6 @@ namespace System.Collections {
// the Array and List classes.
//
// Interfaces are not serializable
- [System.Runtime.InteropServices.ComVisible(true)]
public interface IComparer {
// Compares two objects. An implementation of this method must return a
// value less than zero if x is less than y, zero if x is equal to y, or a
diff --git a/src/mscorlib/src/System/Collections/IDictionary.cs b/src/mscorlib/src/System/Collections/IDictionary.cs
index 4da89d6983..519d53ed55 100644
--- a/src/mscorlib/src/System/Collections/IDictionary.cs
+++ b/src/mscorlib/src/System/Collections/IDictionary.cs
@@ -21,7 +21,6 @@ namespace System.Collections {
// Keys can be any non-null object. Values can be any object.
// You can look up a value in an IDictionary via the default indexed
// property, Items.
- [System.Runtime.InteropServices.ComVisible(true)]
public interface IDictionary : ICollection
{
// Interfaces are not serializable
diff --git a/src/mscorlib/src/System/Collections/IDictionaryEnumerator.cs b/src/mscorlib/src/System/Collections/IDictionaryEnumerator.cs
index b995a04a0e..2f1add682c 100644
--- a/src/mscorlib/src/System/Collections/IDictionaryEnumerator.cs
+++ b/src/mscorlib/src/System/Collections/IDictionaryEnumerator.cs
@@ -44,7 +44,6 @@ namespace System.Collections {
// return the same DictionaryEntry and avoids boxing the DictionaryEntry (boxing
// is somewhat expensive).
//
-[System.Runtime.InteropServices.ComVisible(true)]
public interface IDictionaryEnumerator : IEnumerator
{
// Returns the key of the current element of the enumeration. The returned
diff --git a/src/mscorlib/src/System/Collections/IEnumerable.cs b/src/mscorlib/src/System/Collections/IEnumerable.cs
index 5fa63f15d0..1d8e71cf07 100644
--- a/src/mscorlib/src/System/Collections/IEnumerable.cs
+++ b/src/mscorlib/src/System/Collections/IEnumerable.cs
@@ -21,7 +21,6 @@ namespace System.Collections {
// Implement this interface if you need to support VB's foreach semantics.
// Also, COM classes that support an enumerator will also implement this interface.
[Guid("496B0ABE-CDEE-11d3-88E8-00902754C43A")]
- [System.Runtime.InteropServices.ComVisible(true)]
public interface IEnumerable
{
// Interfaces are not serializable
diff --git a/src/mscorlib/src/System/Collections/IEnumerator.cs b/src/mscorlib/src/System/Collections/IEnumerator.cs
index 99509d15ea..4c4fc085e8 100644
--- a/src/mscorlib/src/System/Collections/IEnumerator.cs
+++ b/src/mscorlib/src/System/Collections/IEnumerator.cs
@@ -20,7 +20,6 @@ namespace System.Collections {
// Base interface for all enumerators, providing a simple approach
// to iterating over a collection.
[Guid("496B0ABF-CDEE-11d3-88E8-00902754C43A")]
- [System.Runtime.InteropServices.ComVisible(true)]
public interface IEnumerator
{
// Interfaces are not serializable
diff --git a/src/mscorlib/src/System/Collections/IEqualityComparer.cs b/src/mscorlib/src/System/Collections/IEqualityComparer.cs
index 50c732f47c..f591b11152 100644
--- a/src/mscorlib/src/System/Collections/IEqualityComparer.cs
+++ b/src/mscorlib/src/System/Collections/IEqualityComparer.cs
@@ -19,7 +19,6 @@ namespace System.Collections {
using System;
// An IEqualityComparer is a mechanism to consume custom performant comparison infrastructure
// that can be consumed by some of the common collections.
- [System.Runtime.InteropServices.ComVisible(true)]
public interface IEqualityComparer {
bool Equals(Object x, Object y);
int GetHashCode(Object obj);
diff --git a/src/mscorlib/src/System/Collections/IHashCodeProvider.cs b/src/mscorlib/src/System/Collections/IHashCodeProvider.cs
index aefa15e1e5..0ae1e3295b 100644
--- a/src/mscorlib/src/System/Collections/IHashCodeProvider.cs
+++ b/src/mscorlib/src/System/Collections/IHashCodeProvider.cs
@@ -19,8 +19,7 @@ namespace System.Collections {
// Provides a mechanism for a hash table user to override the default
// GetHashCode() function on Objects, providing their own hash function.
[Obsolete("Please use IEqualityComparer instead.")]
- [System.Runtime.InteropServices.ComVisible(true)]
- public interface IHashCodeProvider
+ internal interface IHashCodeProvider
{
// Interfaces are not serializable
// Returns a hash code for the given object.
diff --git a/src/mscorlib/src/System/Collections/IList.cs b/src/mscorlib/src/System/Collections/IList.cs
index 8bdfe4c1d0..8b63400852 100644
--- a/src/mscorlib/src/System/Collections/IList.cs
+++ b/src/mscorlib/src/System/Collections/IList.cs
@@ -21,7 +21,6 @@ namespace System.Collections {
// An IList is an ordered collection of objects. The exact ordering
// is up to the implementation of the list, ranging from a sorted
// order to insertion order.
- [System.Runtime.InteropServices.ComVisible(true)]
public interface IList : ICollection
{
// The Item property provides methods to read and edit entries in the List.
diff --git a/src/mscorlib/src/System/Collections/KeyValuePairs.cs b/src/mscorlib/src/System/Collections/KeyValuePairs.cs
deleted file mode 100644
index 22bf92c456..0000000000
--- a/src/mscorlib/src/System/Collections/KeyValuePairs.cs
+++ /dev/null
@@ -1,40 +0,0 @@
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-// See the LICENSE file in the project root for more information.
-
-/*============================================================
-**
-**
-**
-**
-**
-** Purpose: KeyValuePairs to display items in collection class under debugger
-**
-**
-===========================================================*/
-
-namespace System.Collections {
- using System.Diagnostics;
-
- [DebuggerDisplay("{value}", Name = "[{key}]", Type = "" )]
- internal class KeyValuePairs {
- [DebuggerBrowsable(DebuggerBrowsableState.Never)]
- private object key;
-
- [DebuggerBrowsable(DebuggerBrowsableState.Never)]
- private object value;
-
- public KeyValuePairs(object key, object value) {
- this.value = value;
- this.key = key;
- }
-
- public object Key {
- get { return key; }
- }
-
- public object Value {
- get { return value; }
- }
- }
-}
diff --git a/src/mscorlib/src/System/Collections/ListDictionaryInternal.cs b/src/mscorlib/src/System/Collections/ListDictionaryInternal.cs
index be5490b194..617c33707a 100644
--- a/src/mscorlib/src/System/Collections/ListDictionaryInternal.cs
+++ b/src/mscorlib/src/System/Collections/ListDictionaryInternal.cs
@@ -49,13 +49,6 @@ namespace System.Collections {
}
Contract.EndContractBlock();
-#if FEATURE_SERIALIZATION
- if (!key.GetType().IsSerializable)
- throw new ArgumentException(Environment.GetResourceString("Argument_NotSerializable"), nameof(key));
-
- if( (value != null) && (!value.GetType().IsSerializable ) )
- throw new ArgumentException(Environment.GetResourceString("Argument_NotSerializable"), nameof(value));
-#endif
version++;
DictionaryNode last = null;
@@ -136,13 +129,6 @@ namespace System.Collections {
}
Contract.EndContractBlock();
-#if FEATURE_SERIALIZATION
- if (!key.GetType().IsSerializable)
- throw new ArgumentException(Environment.GetResourceString("Argument_NotSerializable"), nameof(key) );
-
- if( (value != null) && (!value.GetType().IsSerializable) )
- throw new ArgumentException(Environment.GetResourceString("Argument_NotSerializable"), nameof(value));
-#endif
version++;
DictionaryNode last = null;
diff --git a/src/mscorlib/src/System/Collections/ObjectModel/Collection.cs b/src/mscorlib/src/System/Collections/ObjectModel/Collection.cs
index a3804ad7ab..b3b19fb616 100644
--- a/src/mscorlib/src/System/Collections/ObjectModel/Collection.cs
+++ b/src/mscorlib/src/System/Collections/ObjectModel/Collection.cs
@@ -13,7 +13,6 @@ namespace System.Collections.ObjectModel
using System.Runtime;
[Serializable]
- [System.Runtime.InteropServices.ComVisible(false)]
[DebuggerTypeProxy(typeof(Mscorlib_CollectionDebugView<>))]
[DebuggerDisplay("Count = {Count}")]
public class Collection<T>: IList<T>, IList, IReadOnlyList<T>
diff --git a/src/mscorlib/src/System/Collections/ObjectModel/KeyedCollection.cs b/src/mscorlib/src/System/Collections/ObjectModel/KeyedCollection.cs
index b6fe6ded29..3fe7716203 100644
--- a/src/mscorlib/src/System/Collections/ObjectModel/KeyedCollection.cs
+++ b/src/mscorlib/src/System/Collections/ObjectModel/KeyedCollection.cs
@@ -12,7 +12,6 @@ namespace System.Collections.ObjectModel
using System.Diagnostics.Contracts;
[Serializable]
- [System.Runtime.InteropServices.ComVisible(false)]
[DebuggerTypeProxy(typeof(Mscorlib_KeyedCollectionDebugView<,>))]
[DebuggerDisplay("Count = {Count}")]
public abstract class KeyedCollection<TKey,TItem>: Collection<TItem>
diff --git a/src/mscorlib/src/System/Collections/ObjectModel/ReadOnlyCollection.cs b/src/mscorlib/src/System/Collections/ObjectModel/ReadOnlyCollection.cs
index a0b8b3b459..10c48cf76d 100644
--- a/src/mscorlib/src/System/Collections/ObjectModel/ReadOnlyCollection.cs
+++ b/src/mscorlib/src/System/Collections/ObjectModel/ReadOnlyCollection.cs
@@ -13,7 +13,6 @@ namespace System.Collections.ObjectModel
using System.Runtime;
[Serializable]
- [System.Runtime.InteropServices.ComVisible(false)]
[DebuggerTypeProxy(typeof(Mscorlib_CollectionDebugView<>))]
[DebuggerDisplay("Count = {Count}")]
public class ReadOnlyCollection<T>: IList<T>, IList, IReadOnlyList<T>
diff --git a/src/mscorlib/src/System/Collections/SortedList.cs b/src/mscorlib/src/System/Collections/SortedList.cs
deleted file mode 100644
index 4a480a2c37..0000000000
--- a/src/mscorlib/src/System/Collections/SortedList.cs
+++ /dev/null
@@ -1,1008 +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 sorted dictionary.
-**
-**
-===========================================================*/
-namespace System.Collections {
- using System;
- using System.Security.Permissions;
- using System.Diagnostics;
- using System.Diagnostics.CodeAnalysis;
- using System.Diagnostics.Contracts;
- using System.Globalization;
-
- // The SortedList class implements a sorted list of keys and values. Entries in
- // a sorted list are sorted by their keys and are accessible both by key and by
- // index. The keys of a sorted list can be ordered either according to a
- // specific IComparer implementation given when the sorted list is
- // instantiated, or according to the IComparable implementation provided
- // by the keys themselves. In either case, a sorted list does not allow entries
- // with duplicate keys.
- //
- // A sorted list internally maintains two arrays that store the keys and
- // values of the entries. The capacity of a sorted list is the allocated
- // length of these internal arrays. As elements are added to a sorted list, the
- // capacity of the sorted list is automatically increased as required by
- // reallocating the internal arrays. The capacity is never automatically
- // decreased, but users can call either TrimToSize or
- // Capacity explicitly.
- //
- // The GetKeyList and GetValueList methods of a sorted list
- // provides access to the keys and values of the sorted list in the form of
- // List implementations. The List objects returned by these
- // methods are aliases for the underlying sorted list, so modifications
- // made to those lists are directly reflected in the sorted list, and vice
- // versa.
- //
- // The SortedList class provides a convenient way to create a sorted
- // copy of another dictionary, such as a Hashtable. For example:
- //
- // Hashtable h = new Hashtable();
- // h.Add(...);
- // h.Add(...);
- // ...
- // SortedList s = new SortedList(h);
- //
- // The last line above creates a sorted list that contains a copy of the keys
- // and values stored in the hashtable. In this particular example, the keys
- // will be ordered according to the IComparable interface, which they
- // all must implement. To impose a different ordering, SortedList also
- // has a constructor that allows a specific IComparer implementation to
- // be specified.
- //
- [DebuggerTypeProxy(typeof(System.Collections.SortedList.SortedListDebugView))]
- [DebuggerDisplay("Count = {Count}")]
- [System.Runtime.InteropServices.ComVisible(true)]
- [Obsolete("Non-generic collections have been deprecated. Please use collections in System.Collections.Generic.")]
- [Serializable]
- public class SortedList : IDictionary, ICloneable
- {
- private Object[] keys;
- private Object[] values;
- private int _size;
- private int version;
- private IComparer comparer;
- private KeyList keyList;
- private ValueList valueList;
- [NonSerialized]
- private Object _syncRoot;
-
- private const int _defaultCapacity = 16;
-
- private static Object[] emptyArray = EmptyArray<Object>.Value;
-
- // Constructs a new sorted list. The sorted list is initially empty and has
- // a capacity of zero. Upon adding the first element to the sorted list the
- // capacity is increased to 16, and then increased in multiples of two as
- // required. The elements of the sorted list are ordered according to the
- // IComparable interface, which must be implemented by the keys of
- // all entries added to the sorted list.
- public SortedList() {
- Init();
- }
- private void Init()
- {
- keys = emptyArray;
- values = emptyArray;
- _size = 0;
- comparer = new Comparer(CultureInfo.CurrentCulture);
- }
-
- // Constructs a new sorted list. The sorted list is initially empty and has
- // a capacity of zero. Upon adding the first element to the sorted list the
- // capacity is increased to 16, and then increased in multiples of two as
- // required. The elements of the sorted list are ordered according to the
- // IComparable interface, which must be implemented by the keys of
- // all entries added to the sorted list.
- //
- public SortedList(int initialCapacity) {
- if (initialCapacity < 0)
- throw new ArgumentOutOfRangeException(nameof(initialCapacity), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
- Contract.EndContractBlock();
- keys = new Object[initialCapacity];
- values = new Object[initialCapacity];
- comparer = new Comparer(CultureInfo.CurrentCulture);
- }
-
- // Constructs a new sorted list with a given IComparer
- // implementation. The sorted list is initially empty and has a capacity of
- // zero. Upon adding the first element to the sorted list the capacity is
- // increased to 16, and then increased in multiples of two as required. The
- // elements of the sorted list are ordered according to the given
- // IComparer implementation. If comparer is null, the
- // elements are compared to each other using the IComparable
- // interface, which in that case must be implemented by the keys of all
- // entries added to the sorted list.
- //
- public SortedList(IComparer comparer)
- : this() {
- if (comparer != null) this.comparer = comparer;
- }
-
- // Constructs a new sorted list with a given IComparer
- // implementation and a given initial capacity. The sorted list is
- // initially empty, but will have room for the given number of elements
- // before any reallocations are required. The elements of the sorted list
- // are ordered according to the given IComparer implementation. If
- // comparer is null, the elements are compared to each other using
- // the IComparable interface, which in that case must be implemented
- // by the keys of all entries added to the sorted list.
- //
- public SortedList(IComparer comparer, int capacity)
- : this(comparer) {
- Capacity = capacity;
- }
-
- // Constructs a new sorted list containing a copy of the entries in the
- // given dictionary. The elements of the sorted list are ordered according
- // to the IComparable interface, which must be implemented by the
- // keys of all entries in the the given dictionary as well as keys
- // subsequently added to the sorted list.
- //
- public SortedList(IDictionary d)
- : this(d, null) {
- }
-
- // Constructs a new sorted list containing a copy of the entries in the
- // given dictionary. The elements of the sorted list are ordered according
- // to the given IComparer implementation. If comparer is
- // null, the elements are compared to each other using the
- // IComparable interface, which in that case must be implemented
- // by the keys of all entries in the the given dictionary as well as keys
- // subsequently added to the sorted list.
- //
- public SortedList(IDictionary d, IComparer comparer)
- : this(comparer, (d != null ? d.Count : 0)) {
- if (d==null)
- throw new ArgumentNullException(nameof(d), Environment.GetResourceString("ArgumentNull_Dictionary"));
- Contract.EndContractBlock();
- d.Keys.CopyTo(keys, 0);
- d.Values.CopyTo(values, 0);
- Array.Sort(keys, values, comparer);
- _size = d.Count;
- }
-
- // Adds an entry with the given key and value to this sorted list. An
- // 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(nameof(key), Environment.GetResourceString("ArgumentNull_Key"));
- Contract.EndContractBlock();
- int i = Array.BinarySearch(keys, 0, _size, key, comparer);
- if (i >= 0)
- throw new ArgumentException(Environment.GetResourceString("Argument_AddingDuplicate__", GetKey(i), key));
- Insert(~i, key, value);
- }
-
- // Returns the capacity of this sorted list. The capacity of a sorted list
- // represents the allocated length of the internal arrays used to store the
- // keys and values of the list, and thus also indicates the maximum number
- // of entries the list can contain before a reallocation of the internal
- // arrays is required.
- //
- public virtual int Capacity {
- get {
- return keys.Length;
- }
- set {
- if (value < Count) {
- throw new ArgumentOutOfRangeException(nameof(value), Environment.GetResourceString("ArgumentOutOfRange_SmallCapacity"));
- }
- Contract.EndContractBlock();
-
- if (value != keys.Length) {
- if (value > 0) {
- Object[] newKeys = new Object[value];
- Object[] newValues = new Object[value];
- if (_size > 0) {
- Array.Copy(keys, 0, newKeys, 0, _size);
- Array.Copy(values, 0, newValues, 0, _size);
- }
- keys = newKeys;
- values = newValues;
- }
- else {
- // size can only be zero here.
- Debug.Assert( _size == 0, "Size is not zero");
- keys = emptyArray;
- values = emptyArray;
- }
- }
- }
- }
-
- // Returns the number of entries in this sorted list.
- //
- public virtual int Count {
- get {
- return _size;
- }
- }
-
- // Returns a collection representing the keys of this sorted list. This
- // method returns the same object as GetKeyList, but typed as an
- // ICollection instead of an IList.
- //
- public virtual ICollection Keys {
- get {
- return GetKeyList();
- }
- }
-
- // Returns a collection representing the values of this sorted list. This
- // method returns the same object as GetValueList, but typed as an
- // ICollection instead of an IList.
- //
- public virtual ICollection Values {
- get {
- return GetValueList();
- }
- }
-
- // Is this SortedList read-only?
- public virtual bool IsReadOnly {
- get { return false; }
- }
-
- public virtual bool IsFixedSize {
- get { return false; }
- }
-
- // Is this SortedList synchronized (thread-safe)?
- public virtual bool IsSynchronized {
- get { return false; }
- }
-
- // Synchronization root for this object.
- public virtual Object SyncRoot {
- get {
- if( _syncRoot == null) {
- System.Threading.Interlocked.CompareExchange<Object>(ref _syncRoot, new Object(), null);
- }
- return _syncRoot;
- }
- }
-
- // Removes all entries from this sorted list.
- public virtual void Clear() {
- // clear does not change the capacity
- version++;
- Array.Clear(keys, 0, _size); // Don't need to doc this but we clear the elements so that the gc can reclaim the references.
- Array.Clear(values, 0, _size); // Don't need to doc this but we clear the elements so that the gc can reclaim the references.
- _size = 0;
-
- }
-
- // Makes a virtually identical copy of this SortedList. This is a shallow
- // copy. IE, the Objects in the SortedList are not cloned - we copy the
- // references to those objects.
- public virtual Object Clone()
- {
- SortedList sl = new SortedList(_size);
- Array.Copy(keys, 0, sl.keys, 0, _size);
- Array.Copy(values, 0, sl.values, 0, _size);
- sl._size = _size;
- sl.version = version;
- sl.comparer = comparer;
- // Don't copy keyList nor valueList.
- return sl;
- }
-
-
- // Checks if this sorted list contains an entry with the given key.
- //
- public virtual bool Contains(Object key) {
- return IndexOfKey(key) >= 0;
- }
-
- // Checks if this sorted list contains an entry with the given key.
- //
- public virtual bool ContainsKey(Object key) {
- // Yes, this is a SPEC'ed duplicate of Contains().
- return IndexOfKey(key) >= 0;
- }
-
- // Checks if this sorted list contains an entry with the given value. The
- // values of the entries of the sorted list are compared to the given value
- // using the Object.Equals method. This method performs a linear
- // search and is substantially slower than the Contains
- // method.
- //
- public virtual bool ContainsValue(Object value) {
- return IndexOfValue(value) >= 0;
- }
-
- // Copies the values in this SortedList to an array.
- public virtual void CopyTo(Array array, int arrayIndex) {
- if (array == null)
- 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(nameof(arrayIndex), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
- if (array.Length - arrayIndex < Count)
- throw new ArgumentException(Environment.GetResourceString("Arg_ArrayPlusOffTooSmall"));
- Contract.EndContractBlock();
- for (int i = 0; i<Count; i++) {
- DictionaryEntry entry = new DictionaryEntry(keys[i],values[i]);
- array.SetValue(entry, i + arrayIndex);
- }
- }
-
- // Copies the values in this SortedList to an KeyValuePairs array.
- // KeyValuePairs is different from Dictionary Entry in that it has special
- // debugger attributes on its fields.
-
- internal virtual KeyValuePairs[] ToKeyValuePairsArray() {
- KeyValuePairs[] array = new KeyValuePairs[Count];
- for (int i = 0; i < Count; i++) {
- array[i] = new KeyValuePairs(keys[i],values[i]);
- }
- return array;
- }
-
- // Ensures that the capacity of this sorted list is at least the given
- // minimum value. If the currect capacity of the list is less than
- // min, the capacity is increased to twice the current capacity or
- // to min, whichever is larger.
- private void EnsureCapacity(int min) {
- int newCapacity = keys.Length == 0? 16: keys.Length * 2;
- // Allow the list to grow to maximum possible capacity (~2G elements) before encountering overflow.
- // Note that this check works even when _items.Length overflowed thanks to the (uint) cast
- if ((uint)newCapacity > Array.MaxArrayLength) newCapacity = Array.MaxArrayLength;
- if (newCapacity < min) newCapacity = min;
- Capacity = newCapacity;
- }
-
- // Returns the value of the entry at the given index.
- //
- public virtual Object GetByIndex(int index) {
- if (index < 0 || index >= Count)
- throw new ArgumentOutOfRangeException(nameof(index), Environment.GetResourceString("ArgumentOutOfRange_Index"));
- Contract.EndContractBlock();
- return values[index];
- }
-
- // Returns an IEnumerator for this sorted list. If modifications
- // made to the sorted list while an enumeration is in progress,
- // the MoveNext and Remove methods
- // of the enumerator will throw an exception.
- //
- IEnumerator IEnumerable.GetEnumerator() {
- return new SortedListEnumerator(this, 0, _size, SortedListEnumerator.DictEntry);
- }
-
- // Returns an IDictionaryEnumerator for this sorted list. If modifications
- // made to the sorted list while an enumeration is in progress,
- // the MoveNext and Remove methods
- // of the enumerator will throw an exception.
- //
- public virtual IDictionaryEnumerator GetEnumerator() {
- return new SortedListEnumerator(this, 0, _size, SortedListEnumerator.DictEntry);
- }
-
- // Returns the key of the entry at the given index.
- //
- public virtual Object GetKey(int index) {
- if (index < 0 || index >= Count) throw new ArgumentOutOfRangeException(nameof(index), Environment.GetResourceString("ArgumentOutOfRange_Index"));
- Contract.EndContractBlock();
- return keys[index];
- }
-
- // Returns an IList representing the keys of this sorted list. The
- // returned list is an alias for the keys of this sorted list, so
- // modifications made to the returned list are directly reflected in the
- // underlying sorted list, and vice versa. The elements of the returned
- // list are ordered in the same way as the elements of the sorted list. The
- // returned list does not support adding, inserting, or modifying elements
- // (the Add, AddRange, Insert, InsertRange,
- // Reverse, Set, SetRange, and Sort methods
- // throw exceptions), but it does allow removal of elements (through the
- // Remove and RemoveRange methods or through an enumerator).
- // Null is an invalid key value.
- //
- public virtual IList GetKeyList() {
- if (keyList == null) keyList = new KeyList(this);
- return keyList;
- }
-
- // Returns an IList representing the values of this sorted list. The
- // returned list is an alias for the values of this sorted list, so
- // modifications made to the returned list are directly reflected in the
- // underlying sorted list, and vice versa. The elements of the returned
- // list are ordered in the same way as the elements of the sorted list. The
- // returned list does not support adding or inserting elements (the
- // Add, AddRange, Insert and InsertRange
- // methods throw exceptions), but it does allow modification and removal of
- // elements (through the Remove, RemoveRange, Set and
- // SetRange methods or through an enumerator).
- //
- public virtual IList GetValueList() {
- if (valueList == null) valueList = new ValueList(this);
- return valueList;
- }
-
- // Returns the value associated with the given key. If an entry with the
- // given key is not found, the returned value is null.
- //
- public virtual Object this[Object key] {
- get {
- int i = IndexOfKey(key);
- if (i >= 0) return values[i];
- return null;
- }
- set {
- 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) {
- values[i] = value;
- version++;
- return;
- }
- Insert(~i, key, value);
- }
- }
-
- // Returns the index of the entry with a given key in this sorted list. The
- // key is located through a binary search, and thus the average execution
- // time of this method is proportional to Log2(size), where
- // size is the size of this sorted list. The returned value is -1 if
- // the given key does not occur in this sorted list. Null is an invalid
- // key value.
- //
- public virtual int IndexOfKey(Object key) {
- if (key == null)
- 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;
- }
-
- // Returns the index of the first occurrence of an entry with a given value
- // in this sorted list. The entry is located through a linear search, and
- // thus the average execution time of this method is proportional to the
- // size of this sorted list. The elements of the list are compared to the
- // given value using the Object.Equals method.
- //
- public virtual int IndexOfValue(Object value) {
- return Array.IndexOf(values, value, 0, _size);
- }
-
- // Inserts an entry with a given key and value at a given index.
- private void Insert(int index, Object key, Object value) {
- if (_size == keys.Length) EnsureCapacity(_size + 1);
- if (index < _size) {
- Array.Copy(keys, index, keys, index + 1, _size - index);
- Array.Copy(values, index, values, index + 1, _size - index);
- }
- keys[index] = key;
- values[index] = value;
- _size++;
- version++;
- }
-
- // Removes the entry at the given index. The size of the sorted list is
- // decreased by one.
- //
- public virtual void RemoveAt(int index) {
- if (index < 0 || index >= Count) throw new ArgumentOutOfRangeException(nameof(index), Environment.GetResourceString("ArgumentOutOfRange_Index"));
- Contract.EndContractBlock();
- _size--;
- if (index < _size) {
- Array.Copy(keys, index + 1, keys, index, _size - index);
- Array.Copy(values, index + 1, values, index, _size - index);
- }
- keys[_size] = null;
- values[_size] = null;
- version++;
- }
-
- // Removes an entry from this sorted list. If an entry with the specified
- // key exists in the sorted list, it is removed. An ArgumentException is
- // thrown if the key is null.
- //
- public virtual void Remove(Object key) {
- int i = IndexOfKey(key);
- if (i >= 0)
- RemoveAt(i);
- }
-
- // Sets the value at an index to a given value. The previous value of
- // the given entry is overwritten.
- //
- public virtual void SetByIndex(int index, Object value) {
- if (index < 0 || index >= Count) throw new ArgumentOutOfRangeException(nameof(index), Environment.GetResourceString("ArgumentOutOfRange_Index"));
- Contract.EndContractBlock();
- values[index] = value;
- version++;
- }
-
- // Returns a thread-safe SortedList.
- //
- public static SortedList Synchronized(SortedList list) {
- if (list==null)
- throw new ArgumentNullException(nameof(list));
- Contract.EndContractBlock();
- return new SyncSortedList(list);
- }
-
- // Sets the capacity of this sorted list to the size of the sorted list.
- // This method can be used to minimize a sorted list's memory overhead once
- // it is known that no new elements will be added to the sorted list. To
- // completely clear a sorted list and release all memory referenced by the
- // sorted list, execute the following statements:
- //
- // sortedList.Clear();
- // sortedList.TrimToSize();
- //
- public virtual void TrimToSize() {
- Capacity = _size;
- }
-
- [Serializable]
- private class SyncSortedList : SortedList
- {
- private SortedList _list;
- private Object _root;
-
-
- internal SyncSortedList(SortedList list) {
- _list = list;
- _root = list.SyncRoot;
- }
-
- public override int Count {
- get { lock(_root) { return _list.Count; } }
- }
-
- public override Object SyncRoot {
- get { return _root; }
- }
-
- public override bool IsReadOnly {
- get { return _list.IsReadOnly; }
- }
-
- public override bool IsFixedSize {
- get { return _list.IsFixedSize; }
- }
-
-
- public override bool IsSynchronized {
- get { return true; }
- }
-
- public override Object this[Object key] {
- get {
- lock(_root) {
- return _list[key];
- }
- }
- set {
- lock(_root) {
- _list[key] = value;
- }
- }
- }
-
- public override void Add(Object key, Object value) {
- lock(_root) {
- _list.Add(key, value);
- }
- }
-
- public override int Capacity {
- get{ lock(_root) { return _list.Capacity; } }
- }
-
- public override void Clear() {
- lock(_root) {
- _list.Clear();
- }
- }
-
- public override Object Clone() {
- lock(_root) {
- return _list.Clone();
- }
- }
-
- public override bool Contains(Object key) {
- lock(_root) {
- return _list.Contains(key);
- }
- }
-
- public override bool ContainsKey(Object key) {
- lock(_root) {
- return _list.ContainsKey(key);
- }
- }
-
- public override bool ContainsValue(Object key) {
- lock(_root) {
- return _list.ContainsValue(key);
- }
- }
-
- public override void CopyTo(Array array, int index) {
- lock(_root) {
- _list.CopyTo(array, index);
- }
- }
-
- [SuppressMessage("Microsoft.Contracts", "CC1055")] // Skip extra error checking to avoid *potential* AppCompat problems.
- public override Object GetByIndex(int index) {
- lock(_root) {
- return _list.GetByIndex(index);
- }
- }
-
- public override IDictionaryEnumerator GetEnumerator() {
- lock(_root) {
- return _list.GetEnumerator();
- }
- }
-
- [SuppressMessage("Microsoft.Contracts", "CC1055")] // Skip extra error checking to avoid *potential* AppCompat problems.
- public override Object GetKey(int index) {
- lock(_root) {
- return _list.GetKey(index);
- }
- }
-
- public override IList GetKeyList() {
- lock(_root) {
- return _list.GetKeyList();
- }
- }
-
- public override IList GetValueList() {
- lock(_root) {
- return _list.GetValueList();
- }
- }
-
- public override int IndexOfKey(Object key) {
- if (key == null)
- throw new ArgumentNullException(nameof(key), Environment.GetResourceString("ArgumentNull_Key"));
- Contract.EndContractBlock();
-
- lock(_root) {
- return _list.IndexOfKey(key);
- }
- }
-
- [SuppressMessage("Microsoft.Contracts", "CC1055")] // Skip extra error checking to avoid *potential* AppCompat problems.
- public override int IndexOfValue(Object value) {
- lock(_root) {
- return _list.IndexOfValue(value);
- }
- }
-
- [SuppressMessage("Microsoft.Contracts", "CC1055")] // Skip extra error checking to avoid *potential* AppCompat problems.
- public override void RemoveAt(int index) {
- lock(_root) {
- _list.RemoveAt(index);
- }
- }
-
- public override void Remove(Object key) {
- lock(_root) {
- _list.Remove(key);
- }
- }
-
- [SuppressMessage("Microsoft.Contracts", "CC1055")] // Skip extra error checking to avoid *potential* AppCompat problems.
- public override void SetByIndex(int index, Object value) {
- lock(_root) {
- _list.SetByIndex(index, value);
- }
- }
-
- internal override KeyValuePairs[] ToKeyValuePairsArray() {
- return _list.ToKeyValuePairsArray();
- }
-
- public override void TrimToSize() {
- lock(_root) {
- _list.TrimToSize();
- }
- }
- }
-
-
- [Serializable]
- private class SortedListEnumerator : IDictionaryEnumerator, ICloneable
- {
- private SortedList sortedList;
- private Object key;
- private Object value;
- private int index;
- private int startIndex; // Store for Reset.
- private int endIndex;
- private int version;
- private bool current; // Is the current element valid?
- private int getObjectRetType; // What should GetObject return?
-
- internal const int Keys = 1;
- internal const int Values = 2;
- internal const int DictEntry = 3;
-
- internal SortedListEnumerator(SortedList sortedList, int index, int count,
- int getObjRetType) {
- this.sortedList = sortedList;
- this.index = index;
- startIndex = index;
- endIndex = index + count;
- version = sortedList.version;
- getObjectRetType = getObjRetType;
- current = false;
- }
-
- public Object Clone()
- {
- return MemberwiseClone();
- }
-
- public virtual Object Key {
- get {
- if (version != sortedList.version) throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_EnumFailedVersion"));
- if (current == false) throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_EnumOpCantHappen"));
- return key;
- }
- }
-
- public virtual bool MoveNext() {
- if (version != sortedList.version) throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_EnumFailedVersion"));
- if (index < endIndex) {
- key = sortedList.keys[index];
- value = sortedList.values[index];
- index++;
- current = true;
- return true;
- }
- key = null;
- value = null;
- current = false;
- return false;
- }
-
- public virtual DictionaryEntry Entry {
- get {
- if (version != sortedList.version) throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_EnumFailedVersion"));
- if (current == false) throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_EnumOpCantHappen"));
- return new DictionaryEntry(key, value);
- }
- }
-
- public virtual Object Current {
- get {
- if (current == false) throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_EnumOpCantHappen"));
-
- if (getObjectRetType==Keys)
- return key;
- else if (getObjectRetType==Values)
- return value;
- else
- return new DictionaryEntry(key, value);
- }
- }
-
- public virtual Object Value {
- get {
- if (version != sortedList.version) throw new InvalidOperationException(Environment.GetResourceString(ResId.InvalidOperation_EnumFailedVersion));
- if (current == false) throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_EnumOpCantHappen"));
- return value;
- }
- }
-
- public virtual void Reset() {
- if (version != sortedList.version) throw new InvalidOperationException(Environment.GetResourceString(ResId.InvalidOperation_EnumFailedVersion));
- index = startIndex;
- current = false;
- key = null;
- value = null;
- }
- }
-
- [Serializable]
- private class KeyList : IList
- {
- private SortedList sortedList;
-
- internal KeyList(SortedList sortedList) {
- this.sortedList = sortedList;
- }
-
- public virtual int Count {
- get { return sortedList._size; }
- }
-
- public virtual bool IsReadOnly {
- get { return true; }
- }
-
- public virtual bool IsFixedSize {
- get { return true; }
- }
-
- public virtual bool IsSynchronized {
- get { return sortedList.IsSynchronized; }
- }
-
- public virtual Object SyncRoot {
- get { return sortedList.SyncRoot; }
- }
-
- public virtual int Add(Object key) {
- throw new NotSupportedException(Environment.GetResourceString(ResId.NotSupported_SortedListNestedWrite));
- // return 0; // suppress compiler warning
- }
-
- public virtual void Clear() {
- throw new NotSupportedException(Environment.GetResourceString(ResId.NotSupported_SortedListNestedWrite));
- }
-
- public virtual bool Contains(Object key) {
- return sortedList.Contains(key);
- }
-
- public virtual void CopyTo(Array array, int arrayIndex) {
- if (array != null && array.Rank != 1)
- throw new ArgumentException(Environment.GetResourceString("Arg_RankMultiDimNotSupported"));
- Contract.EndContractBlock();
-
- // defer error checking to Array.Copy
- Array.Copy(sortedList.keys, 0, array, arrayIndex, sortedList.Count);
- }
-
- public virtual void Insert(int index, Object value) {
- throw new NotSupportedException(Environment.GetResourceString(ResId.NotSupported_SortedListNestedWrite));
- }
-
- public virtual Object this[int index] {
- get {
- return sortedList.GetKey(index);
- }
- set {
- throw new NotSupportedException(Environment.GetResourceString("NotSupported_KeyCollectionSet"));
- }
- }
-
- public virtual IEnumerator GetEnumerator() {
- return new SortedListEnumerator(sortedList, 0, sortedList.Count, SortedListEnumerator.Keys);
- }
-
- public virtual int IndexOf(Object key) {
- if (key==null)
- throw new ArgumentNullException(nameof(key), Environment.GetResourceString("ArgumentNull_Key"));
- Contract.EndContractBlock();
-
- int i = Array.BinarySearch(sortedList.keys, 0,
- sortedList.Count, key, sortedList.comparer);
- if (i >= 0) return i;
- return -1;
- }
-
- public virtual void Remove(Object key) {
- throw new NotSupportedException(Environment.GetResourceString(ResId.NotSupported_SortedListNestedWrite));
- }
-
- public virtual void RemoveAt(int index) {
- throw new NotSupportedException(Environment.GetResourceString(ResId.NotSupported_SortedListNestedWrite));
- }
- }
-
- [Serializable]
- private class ValueList : IList
- {
- private SortedList sortedList;
-
- internal ValueList(SortedList sortedList) {
- this.sortedList = sortedList;
- }
-
- public virtual int Count {
- get { return sortedList._size; }
- }
-
- public virtual bool IsReadOnly {
- get { return true; }
- }
-
- public virtual bool IsFixedSize {
- get { return true; }
- }
-
- public virtual bool IsSynchronized {
- get { return sortedList.IsSynchronized; }
- }
-
- public virtual Object SyncRoot {
- get { return sortedList.SyncRoot; }
- }
-
- public virtual int Add(Object key) {
- throw new NotSupportedException(Environment.GetResourceString(ResId.NotSupported_SortedListNestedWrite));
- }
-
- public virtual void Clear() {
- throw new NotSupportedException(Environment.GetResourceString(ResId.NotSupported_SortedListNestedWrite));
- }
-
- public virtual bool Contains(Object value) {
- return sortedList.ContainsValue(value);
- }
-
- public virtual void CopyTo(Array array, int arrayIndex) {
- if (array != null && array.Rank != 1)
- throw new ArgumentException(Environment.GetResourceString("Arg_RankMultiDimNotSupported"));
- Contract.EndContractBlock();
-
- // defer error checking to Array.Copy
- Array.Copy(sortedList.values, 0, array, arrayIndex, sortedList.Count);
- }
-
- public virtual void Insert(int index, Object value) {
- throw new NotSupportedException(Environment.GetResourceString(ResId.NotSupported_SortedListNestedWrite));
- }
-
- public virtual Object this[int index] {
- get {
- return sortedList.GetByIndex(index);
- }
- set {
- throw new NotSupportedException(Environment.GetResourceString(ResId.NotSupported_SortedListNestedWrite));
- }
- }
-
- public virtual IEnumerator GetEnumerator() {
- return new SortedListEnumerator(sortedList, 0, sortedList.Count, SortedListEnumerator.Values);
- }
-
- public virtual int IndexOf(Object value) {
- return Array.IndexOf(sortedList.values, value, 0, sortedList.Count);
- }
-
- public virtual void Remove(Object value) {
- throw new NotSupportedException(Environment.GetResourceString(ResId.NotSupported_SortedListNestedWrite));
- }
-
- public virtual void RemoveAt(int index) {
- throw new NotSupportedException(Environment.GetResourceString(ResId.NotSupported_SortedListNestedWrite));
- }
-
- }
-
- // internal debug view class for sorted list
- internal class SortedListDebugView {
- private SortedList sortedList;
-
- public SortedListDebugView( SortedList sortedList) {
- if( sortedList == null) {
- throw new ArgumentNullException(nameof(sortedList));
- }
- Contract.EndContractBlock();
-
- this.sortedList = sortedList;
- }
-
- [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)]
- public KeyValuePairs[] Items {
- get {
- return sortedList.ToKeyValuePairsArray();
- }
- }
- }
- }
-}
diff --git a/src/mscorlib/src/System/Collections/Stack.cs b/src/mscorlib/src/System/Collections/Stack.cs
deleted file mode 100644
index c3ad15abd8..0000000000
--- a/src/mscorlib/src/System/Collections/Stack.cs
+++ /dev/null
@@ -1,379 +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: An array implementation of a stack.
-**
-**
-=============================================================================*/
-namespace System.Collections {
- using System;
- using System.Security.Permissions;
- using System.Diagnostics;
- using System.Diagnostics.CodeAnalysis;
- using System.Diagnostics.Contracts;
-
- // A simple stack of objects. Internally it is implemented as an array,
- // so Push can be O(n). Pop is O(1).
- [DebuggerTypeProxy(typeof(System.Collections.Stack.StackDebugView))]
- [DebuggerDisplay("Count = {Count}")]
-[System.Runtime.InteropServices.ComVisible(true)]
- [Serializable]
- public class Stack : ICollection, ICloneable {
- private Object[] _array; // Storage for stack elements
- [ContractPublicPropertyName("Count")]
- private int _size; // Number of items in the stack.
- private int _version; // Used to keep enumerator in sync w/ collection.
- [NonSerialized]
- private Object _syncRoot;
-
- private const int _defaultCapacity = 10;
-
- public Stack() {
- _array = new Object[_defaultCapacity];
- _size = 0;
- _version = 0;
- }
-
- // Create a stack with a specific initial capacity. The initial capacity
- // must be a non-negative number.
- public Stack(int initialCapacity) {
- if (initialCapacity < 0)
- throw new ArgumentOutOfRangeException(nameof(initialCapacity), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
- Contract.EndContractBlock();
- if (initialCapacity < _defaultCapacity)
- initialCapacity = _defaultCapacity; // Simplify doubling logic in Push.
- _array = new Object[initialCapacity];
- _size = 0;
- _version = 0;
- }
-
- // Fills a Stack with the contents of a particular collection. The items are
- // pushed onto the stack in the same order they are read by the enumerator.
- //
- public Stack(ICollection col) : this((col==null ? 32 : col.Count))
- {
- if (col==null)
- throw new ArgumentNullException(nameof(col));
- Contract.EndContractBlock();
- IEnumerator en = col.GetEnumerator();
- while(en.MoveNext())
- Push(en.Current);
- }
-
- public virtual int Count {
- get {
- Contract.Ensures(Contract.Result<int>() >= 0);
- return _size;
- }
- }
-
- public virtual bool IsSynchronized {
- get { return false; }
- }
-
- public virtual Object SyncRoot {
- get {
- if( _syncRoot == null) {
- System.Threading.Interlocked.CompareExchange<Object>(ref _syncRoot, new Object(), null);
- }
- return _syncRoot;
- }
- }
-
- // Removes all Objects from the Stack.
- public virtual void Clear() {
- Array.Clear(_array, 0, _size); // Don't need to doc this but we clear the elements so that the gc can reclaim the references.
- _size = 0;
- _version++;
- }
-
- public virtual Object Clone() {
- Contract.Ensures(Contract.Result<Object>() != null);
-
- Stack s = new Stack(_size);
- s._size = _size;
- Array.Copy(_array, 0, s._array, 0, _size);
- s._version = _version;
- return s;
- }
-
- public virtual bool Contains(Object obj) {
- int count = _size;
-
- while (count-- > 0) {
- if (obj == null) {
- if (_array[count] == null)
- return true;
- }
- else if (_array[count] != null && _array[count].Equals(obj)) {
- return true;
- }
- }
- return false;
- }
-
- // Copies the stack into an array.
- public virtual void CopyTo(Array array, int index) {
- if (array==null)
- throw new ArgumentNullException(nameof(array));
- if (array.Rank != 1)
- throw new ArgumentException(Environment.GetResourceString("Arg_RankMultiDimNotSupported"));
- if (index < 0)
- throw new ArgumentOutOfRangeException(nameof(index), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
- if (array.Length - index < _size)
- throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen"));
- Contract.EndContractBlock();
-
- int i = 0;
- if (array is Object[]) {
- Object[] objArray = (Object[]) array;
- while(i < _size) {
- objArray[i+index] = _array[_size-i-1];
- i++;
- }
- }
- else {
- while(i < _size) {
- array.SetValue(_array[_size-i-1], i+index);
- i++;
- }
- }
- }
-
- // Returns an IEnumerator for this Stack.
- public virtual IEnumerator GetEnumerator() {
- Contract.Ensures(Contract.Result<IEnumerator>() != null);
- return new StackEnumerator(this);
- }
-
- // Returns the top object on the stack without removing it. If the stack
- // is empty, Peek throws an InvalidOperationException.
- public virtual Object Peek() {
- if (_size==0)
- throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_EmptyStack"));
- Contract.EndContractBlock();
- return _array[_size-1];
- }
-
- // Pops an item from the top of the stack. If the stack is empty, Pop
- // throws an InvalidOperationException.
- public virtual Object Pop() {
- if (_size == 0)
- throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_EmptyStack"));
- //Contract.Ensures(Count == Contract.OldValue(Count) - 1);
- Contract.EndContractBlock();
- _version++;
- Object obj = _array[--_size];
- _array[_size] = null; // Free memory quicker.
- return obj;
- }
-
- // Pushes an item to the top of the stack.
- //
- public virtual void Push(Object obj) {
- //Contract.Ensures(Count == Contract.OldValue(Count) + 1);
- if (_size == _array.Length) {
- Object[] newArray = new Object[2*_array.Length];
- Array.Copy(_array, 0, newArray, 0, _size);
- _array = newArray;
- }
- _array[_size++] = obj;
- _version++;
- }
-
- // Returns a synchronized Stack.
- //
- public static Stack Synchronized(Stack stack) {
- if (stack==null)
- throw new ArgumentNullException(nameof(stack));
- Contract.Ensures(Contract.Result<Stack>() != null);
- Contract.EndContractBlock();
- return new SyncStack(stack);
- }
-
-
- // Copies the Stack to an array, in the same order Pop would return the items.
- public virtual Object[] ToArray()
- {
- Contract.Ensures(Contract.Result<Object[]>() != null);
-
- Object[] objArray = new Object[_size];
- int i = 0;
- while(i < _size) {
- objArray[i] = _array[_size-i-1];
- i++;
- }
- return objArray;
- }
-
- [Serializable]
- private class SyncStack : Stack
- {
- private Stack _s;
- private Object _root;
-
- internal SyncStack(Stack stack) {
- _s = stack;
- _root = stack.SyncRoot;
- }
-
- public override bool IsSynchronized {
- get { return true; }
- }
-
- public override Object SyncRoot {
- get {
- return _root;
- }
- }
-
- public override int Count {
- get {
- lock (_root) {
- return _s.Count;
- }
- }
- }
-
- public override bool Contains(Object obj) {
- lock (_root) {
- return _s.Contains(obj);
- }
- }
-
- public override Object Clone()
- {
- lock (_root) {
- return new SyncStack((Stack)_s.Clone());
- }
- }
-
- public override void Clear() {
- lock (_root) {
- _s.Clear();
- }
- }
-
- public override void CopyTo(Array array, int arrayIndex) {
- lock (_root) {
- _s.CopyTo(array, arrayIndex);
- }
- }
-
- public override void Push(Object value) {
- lock (_root) {
- _s.Push(value);
- }
- }
-
- [SuppressMessage("Microsoft.Contracts", "CC1055")] // Thread safety problems with precondition - can't express the precondition as of Dev10.
- public override Object Pop() {
- lock (_root) {
- return _s.Pop();
- }
- }
-
- public override IEnumerator GetEnumerator() {
- lock (_root) {
- return _s.GetEnumerator();
- }
- }
-
- [SuppressMessage("Microsoft.Contracts", "CC1055")] // Thread safety problems with precondition - can't express the precondition as of Dev10.
- public override Object Peek() {
- lock (_root) {
- return _s.Peek();
- }
- }
-
- public override Object[] ToArray() {
- lock (_root) {
- return _s.ToArray();
- }
- }
- }
-
-
- [Serializable]
- private class StackEnumerator : IEnumerator, ICloneable
- {
- private Stack _stack;
- private int _index;
- private int _version;
- private Object currentElement;
-
- internal StackEnumerator(Stack stack) {
- _stack = stack;
- _version = _stack._version;
- _index = -2;
- currentElement = null;
- }
-
- public Object Clone()
- {
- return MemberwiseClone();
- }
-
- public virtual bool MoveNext() {
- bool retval;
- if (_version != _stack._version) throw new InvalidOperationException(Environment.GetResourceString(ResId.InvalidOperation_EnumFailedVersion));
- if (_index == -2) { // First call to enumerator.
- _index = _stack._size-1;
- retval = ( _index >= 0);
- if (retval)
- currentElement = _stack._array[_index];
- return retval;
- }
- if (_index == -1) { // End of enumeration.
- return false;
- }
-
- retval = (--_index >= 0);
- if (retval)
- currentElement = _stack._array[_index];
- else
- currentElement = null;
- return retval;
- }
-
- public virtual Object Current {
- get {
- if (_index == -2) throw new InvalidOperationException(Environment.GetResourceString(ResId.InvalidOperation_EnumNotStarted));
- if (_index == -1) throw new InvalidOperationException(Environment.GetResourceString(ResId.InvalidOperation_EnumEnded));
- return currentElement;
- }
- }
-
- public virtual void Reset() {
- if (_version != _stack._version) throw new InvalidOperationException(Environment.GetResourceString(ResId.InvalidOperation_EnumFailedVersion));
- _index = -2;
- currentElement = null;
- }
- }
-
- internal class StackDebugView {
- private Stack stack;
-
- public StackDebugView( Stack stack) {
- if( stack == null)
- throw new ArgumentNullException(nameof(stack));
- Contract.EndContractBlock();
-
- this.stack = stack;
- }
-
- [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)]
- public Object[] Items {
- get {
- return stack.ToArray();
- }
- }
- }
- }
-}
diff --git a/src/mscorlib/src/System/CompatibilitySwitches.cs b/src/mscorlib/src/System/CompatibilitySwitches.cs
index bb2f02a679..58dd640f88 100644
--- a/src/mscorlib/src/System/CompatibilitySwitches.cs
+++ b/src/mscorlib/src/System/CompatibilitySwitches.cs
@@ -10,7 +10,6 @@ namespace System
internal static class CompatibilitySwitches
{
private static bool s_AreSwitchesSet;
- private static bool s_useLatestBehaviorWhenTFMNotSpecified; // Which behavior to use when the TFM is not specified.
public static bool IsCompatibilityBehaviorDefined
{
@@ -20,39 +19,9 @@ namespace System
}
}
- private static bool IsCompatibilitySwitchSet(string compatibilitySwitch)
- {
- bool? result = AppDomain.CurrentDomain.IsCompatibilitySwitchSet(compatibilitySwitch);
- return (result.HasValue && result.Value);
- }
-
internal static void InitializeSwitches()
{
s_AreSwitchesSet = true;
}
-
- public static bool IsNetFx40TimeSpanLegacyFormatMode
- {
- get
- {
- return false;
- }
- }
-
- public static bool IsNetFx40LegacySecurityPolicy
- {
- get
- {
- return false;
- }
- }
-
- public static bool IsNetFx45LegacyManagedDeflateStream
- {
- get
- {
- return false;
- }
- }
}
}
diff --git a/src/mscorlib/src/System/ComponentModel/EditorBrowsableAttribute.cs b/src/mscorlib/src/System/ComponentModel/EditorBrowsableAttribute.cs
new file mode 100644
index 0000000000..a7946f8203
--- /dev/null
+++ b/src/mscorlib/src/System/ComponentModel/EditorBrowsableAttribute.cs
@@ -0,0 +1,48 @@
+// 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.ComponentModel
+{
+ [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Enum | AttributeTargets.Constructor | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Delegate | AttributeTargets.Interface)]
+ public sealed class EditorBrowsableAttribute : Attribute
+ {
+ private EditorBrowsableState browsableState;
+
+ public EditorBrowsableAttribute(EditorBrowsableState state)
+ {
+ browsableState = state;
+ }
+
+ public EditorBrowsableAttribute () : this(EditorBrowsableState.Always) { }
+
+ public EditorBrowsableState State
+ {
+ get { return browsableState; }
+ }
+
+ public override bool Equals(object obj)
+ {
+ if (obj == this)
+ {
+ return true;
+ }
+
+ EditorBrowsableAttribute other = obj as EditorBrowsableAttribute;
+
+ return (other != null) && other.browsableState == browsableState;
+ }
+
+ public override int GetHashCode()
+ {
+ return base.GetHashCode();
+ }
+ }
+
+ public enum EditorBrowsableState
+ {
+ Always,
+ Never,
+ Advanced
+ }
+}
diff --git a/src/mscorlib/src/System/Configuration/Assemblies/AssemblyHash.cs b/src/mscorlib/src/System/Configuration/Assemblies/AssemblyHash.cs
deleted file mode 100644
index a7b0e70266..0000000000
--- a/src/mscorlib/src/System/Configuration/Assemblies/AssemblyHash.cs
+++ /dev/null
@@ -1,74 +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:
-**
-**
-===========================================================*/
-namespace System.Configuration.Assemblies {
- using System;
- [Serializable]
- [System.Runtime.InteropServices.ComVisible(true)]
- [Obsolete("The AssemblyHash class has been deprecated. http://go.microsoft.com/fwlink/?linkid=14202")]
- public struct AssemblyHash : ICloneable
- {
- private AssemblyHashAlgorithm _Algorithm;
- private byte[] _Value;
-
- [Obsolete("The AssemblyHash class has been deprecated. http://go.microsoft.com/fwlink/?linkid=14202")]
- public static readonly AssemblyHash Empty = new AssemblyHash(AssemblyHashAlgorithm.None, null);
-
- [Obsolete("The AssemblyHash class has been deprecated. http://go.microsoft.com/fwlink/?linkid=14202")]
- public AssemblyHash(byte[] value) {
- _Algorithm = AssemblyHashAlgorithm.SHA1;
- _Value = null;
-
- if (value != null) {
- int length = value.Length;
- _Value = new byte[length];
- Array.Copy(value, _Value, length);
- }
- }
-
- [Obsolete("The AssemblyHash class has been deprecated. http://go.microsoft.com/fwlink/?linkid=14202")]
- public AssemblyHash(AssemblyHashAlgorithm algorithm, byte[] value) {
- _Algorithm = algorithm;
- _Value = null;
-
- if (value != null) {
- int length = value.Length;
- _Value = new byte[length];
- Array.Copy(value, _Value, length);
- }
- }
-
- // Hash is made up of a byte array and a value from a class of supported
- // algorithm types.
- [Obsolete("The AssemblyHash class has been deprecated. http://go.microsoft.com/fwlink/?linkid=14202")]
- public AssemblyHashAlgorithm Algorithm {
- get { return _Algorithm; }
- set { _Algorithm = value; }
- }
-
- [Obsolete("The AssemblyHash class has been deprecated. http://go.microsoft.com/fwlink/?linkid=14202")]
- public byte[] GetValue() {
- return _Value;
- }
-
- [Obsolete("The AssemblyHash class has been deprecated. http://go.microsoft.com/fwlink/?linkid=14202")]
- public void SetValue(byte[] value) {
- _Value = value;
- }
-
- [Obsolete("The AssemblyHash class has been deprecated. http://go.microsoft.com/fwlink/?linkid=14202")]
- public Object Clone() {
- return new AssemblyHash(_Algorithm, _Value);
- }
- }
-
-}
diff --git a/src/mscorlib/src/System/Configuration/Assemblies/AssemblyHashAlgorithm.cs b/src/mscorlib/src/System/Configuration/Assemblies/AssemblyHashAlgorithm.cs
index 6c4fb3febf..a19d0344b1 100644
--- a/src/mscorlib/src/System/Configuration/Assemblies/AssemblyHashAlgorithm.cs
+++ b/src/mscorlib/src/System/Configuration/Assemblies/AssemblyHashAlgorithm.cs
@@ -16,17 +16,13 @@ namespace System.Configuration.Assemblies {
using System;
[Serializable]
- [System.Runtime.InteropServices.ComVisible(true)]
public enum AssemblyHashAlgorithm
{
None = 0,
MD5 = 0x8003,
SHA1 = 0x8004,
- [ComVisible(false)]
SHA256 = 0x800c,
- [ComVisible(false)]
SHA384 = 0x800d,
- [ComVisible(false)]
SHA512 = 0x800e,
}
}
diff --git a/src/mscorlib/src/System/Configuration/Assemblies/AssemblyVersionCompatibility.cs b/src/mscorlib/src/System/Configuration/Assemblies/AssemblyVersionCompatibility.cs
index 4b0f1e4236..b7e9c30c62 100644
--- a/src/mscorlib/src/System/Configuration/Assemblies/AssemblyVersionCompatibility.cs
+++ b/src/mscorlib/src/System/Configuration/Assemblies/AssemblyVersionCompatibility.cs
@@ -14,7 +14,6 @@ namespace System.Configuration.Assemblies {
using System;
[Serializable]
-[System.Runtime.InteropServices.ComVisible(true)]
public enum AssemblyVersionCompatibility
{
SameMachine = 1,
diff --git a/src/mscorlib/src/System/ContextMarshalException.cs b/src/mscorlib/src/System/ContextMarshalException.cs
deleted file mode 100644
index f74a62b991..0000000000
--- a/src/mscorlib/src/System/ContextMarshalException.cs
+++ /dev/null
@@ -1,45 +0,0 @@
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-// See the LICENSE file in the project root for more information.
-
-/*=============================================================================
-**
-**
-**
-** Purpose: Exception class for attempting to pass an instance through a context
-** boundary, when the formal type and the instance's marshal style are
-** incompatible or cannot be marshaled.
-**
-** This is thrown by the VM when attempts to marshal the exception
-** object at the AppDomain transition boundary fails.
-=============================================================================*/
-
-namespace System {
- using System.Runtime.InteropServices;
- using System.Runtime.Remoting;
- using System;
- using System.Runtime.Serialization;
- [System.Runtime.InteropServices.ComVisible(true)]
- [Serializable]
- public class ContextMarshalException : SystemException {
- public ContextMarshalException()
- : base(Environment.GetResourceString("Arg_ContextMarshalException")) {
- SetErrorCode(__HResults.COR_E_CONTEXTMARSHAL);
- }
-
- public ContextMarshalException(String message)
- : base(message) {
- SetErrorCode(__HResults.COR_E_CONTEXTMARSHAL);
- }
-
- public ContextMarshalException(String message, Exception inner)
- : base(message, inner) {
- SetErrorCode(__HResults.COR_E_CONTEXTMARSHAL);
- }
-
- protected ContextMarshalException(SerializationInfo info, StreamingContext context) : base(info, context) {
- }
-
- }
-
-}
diff --git a/src/mscorlib/src/System/Convert.cs b/src/mscorlib/src/System/Convert.cs
index 0e14f93fee..0cd3c5d715 100644
--- a/src/mscorlib/src/System/Convert.cs
+++ b/src/mscorlib/src/System/Convert.cs
@@ -2158,7 +2158,6 @@ namespace System {
return ToBase64String(inArray, 0, inArray.Length, Base64FormattingOptions.None);
}
- [System.Runtime.InteropServices.ComVisible(false)]
public static String ToBase64String(byte[] inArray, Base64FormattingOptions options) {
if (inArray==null) {
throw new ArgumentNullException(nameof(inArray));
@@ -2172,7 +2171,6 @@ namespace System {
return ToBase64String(inArray, offset, length, Base64FormattingOptions.None);
}
- [System.Runtime.InteropServices.ComVisible(false)]
public static unsafe String ToBase64String(byte[] inArray, int offset, int length, Base64FormattingOptions options) {
//Do data verfication
if (inArray==null)
@@ -2202,7 +2200,7 @@ namespace System {
string returnString = string.FastAllocateString(stringLength);
fixed (char* outChars = returnString){
- fixed (byte* inData = inArray) {
+ fixed (byte* inData = &inArray[0]) {
int j = ConvertToBase64Array(outChars,inData,offset,length, insertLineBreaks);
BCLDebug.Assert(returnString.Length == j, "returnString.Length == j");
return returnString;
@@ -2218,7 +2216,6 @@ namespace System {
return ToBase64CharArray(inArray, offsetIn, length, outArray, offsetOut, Base64FormattingOptions.None);
}
- [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)
@@ -2265,7 +2262,7 @@ namespace System {
throw new ArgumentOutOfRangeException(nameof(offsetOut), Environment.GetResourceString("ArgumentOutOfRange_OffsetOut"));
fixed (char* outChars = &outArray[offsetOut]) {
- fixed (byte* inData = inArray) {
+ fixed (byte* inData = &inArray[0]) {
retVal = ConvertToBase64Array(outChars,inData,offsetIn,length, insertLineBreaks);
}
}
@@ -2282,7 +2279,7 @@ namespace System {
int i;
// get a pointer to the base64Table to avoid unnecessary range checking
- fixed(char* base64 = base64Table) {
+ fixed(char* base64 = &base64Table[0]) {
for (i=offset; i<calcLength; i+=3)
{
if (insertLineBreaks) {
diff --git a/src/mscorlib/src/System/DBNull.cs b/src/mscorlib/src/System/DBNull.cs
index 6f80af7e21..65c85ba968 100644
--- a/src/mscorlib/src/System/DBNull.cs
+++ b/src/mscorlib/src/System/DBNull.cs
@@ -11,8 +11,6 @@ namespace System {
using System;
using System.Runtime.Remoting;
using System.Runtime.Serialization;
- using System.Security.Permissions;
- [System.Runtime.InteropServices.ComVisible(true)]
[Serializable]
public sealed class DBNull : ISerializable, IConvertible {
diff --git a/src/mscorlib/src/System/DataMisalignedException.cs b/src/mscorlib/src/System/DataMisalignedException.cs
index e5332bb9b7..a3653e7219 100644
--- a/src/mscorlib/src/System/DataMisalignedException.cs
+++ b/src/mscorlib/src/System/DataMisalignedException.cs
@@ -9,37 +9,31 @@
**
=============================================================================*/
-namespace System
-{
- using System;
- using System.Runtime.Serialization;
+using System.Runtime.Serialization;
+namespace System
+{
[Serializable]
- [System.Runtime.InteropServices.ComVisible(true)]
public sealed class DataMisalignedException : SystemException
{
- public DataMisalignedException()
- : base(Environment.GetResourceString("Arg_DataMisalignedException"))
- {
- SetErrorCode(__HResults.COR_E_DATAMISALIGNED);
- }
-
- public DataMisalignedException(String message)
- : base(message)
+ public DataMisalignedException()
+ : base(SR.Arg_DataMisalignedException)
{
- SetErrorCode(__HResults.COR_E_DATAMISALIGNED);
+ HResult = __HResults.COR_E_DATAMISALIGNED;
}
- public DataMisalignedException(String message, Exception innerException)
- : base(message, innerException)
+ public DataMisalignedException(String message)
+ : base(message)
{
- SetErrorCode(__HResults.COR_E_DATAMISALIGNED);
+ HResult = __HResults.COR_E_DATAMISALIGNED;
}
- internal DataMisalignedException(SerializationInfo info, StreamingContext context)
- : base (info, context)
+ public DataMisalignedException(String message, Exception innerException)
+ : base(message, innerException)
{
+ HResult = __HResults.COR_E_DATAMISALIGNED;
}
- }
+ internal DataMisalignedException(SerializationInfo info, StreamingContext context) : base(info, context) { }
+ }
}
diff --git a/src/mscorlib/src/System/DateTime.cs b/src/mscorlib/src/System/DateTime.cs
index e93346c42f..3de50336a9 100644
--- a/src/mscorlib/src/System/DateTime.cs
+++ b/src/mscorlib/src/System/DateTime.cs
@@ -13,7 +13,6 @@ namespace System {
using System.Runtime.Serialization;
using System.Runtime.Versioning;
using System.Security;
- using System.Security.Permissions;
using System.Diagnostics.Contracts;
using CultureInfo = System.Globalization.CultureInfo;
using Calendar = System.Globalization.Calendar;
@@ -461,7 +460,12 @@ namespace System {
// parts of the result are the same as those of this DateTime.
//
public DateTime AddYears(int value) {
- if (value < -10000 || value > 10000) throw new ArgumentOutOfRangeException("years", Environment.GetResourceString("ArgumentOutOfRange_DateTimeBadYears"));
+ if (value < -10000 || value > 10000)
+ {
+ // DateTimeOffset.AddYears(int years) is implemented on top of DateTime.AddYears(int value). Use the more appropriate
+ // parameter name out of the two for the exception.
+ throw new ArgumentOutOfRangeException("years", Environment.GetResourceString("ArgumentOutOfRange_DateTimeBadYears"));
+ }
Contract.EndContractBlock();
return AddMonths(value * 12);
}
@@ -658,7 +662,6 @@ namespace System {
return new DateTime(DoubleDateToTicks(d), DateTimeKind.Unspecified);
}
- [System.Security.SecurityCritical /*auto-generated_required*/]
void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context) {
if (info==null) {
throw new ArgumentNullException(nameof(info));
@@ -705,12 +708,6 @@ namespace System {
return (Int64)dateData;
}
}
-
- // Return the underlying data, without adjust local times to the right time zone. Needed if performance
- // or compatibility are important.
- internal Int64 ToBinaryRaw() {
- return (Int64)dateData;
- }
// Returns the date part of this DateTime. The resulting value
// corresponds to this DateTime with the time-of-day part set to
diff --git a/src/mscorlib/src/System/DateTimeKind.cs b/src/mscorlib/src/System/DateTimeKind.cs
index 1a8a4ff6b4..6b5e690df0 100644
--- a/src/mscorlib/src/System/DateTimeKind.cs
+++ b/src/mscorlib/src/System/DateTimeKind.cs
@@ -2,14 +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 {
-
+namespace System
+{
// This enum is used to indentify DateTime instances in cases when they are known to be in local time,
// UTC time or if this information has not been specified or is not applicable.
[Serializable]
-[System.Runtime.InteropServices.ComVisible(true)]
public enum DateTimeKind
{
Unspecified = 0,
diff --git a/src/mscorlib/src/System/DateTimeOffset.cs b/src/mscorlib/src/System/DateTimeOffset.cs
index 5bdaa18aaa..d64ba1582e 100644
--- a/src/mscorlib/src/System/DateTimeOffset.cs
+++ b/src/mscorlib/src/System/DateTimeOffset.cs
@@ -10,7 +10,6 @@ namespace System {
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
using System.Runtime.Serialization;
- using System.Security.Permissions;
using System.Diagnostics;
using System.Diagnostics.Contracts;
diff --git a/src/mscorlib/src/System/DayOfWeek.cs b/src/mscorlib/src/System/DayOfWeek.cs
index 37b8f8975d..5d84257158 100644
--- a/src/mscorlib/src/System/DayOfWeek.cs
+++ b/src/mscorlib/src/System/DayOfWeek.cs
@@ -10,11 +10,12 @@
**
**
============================================================*/
-namespace System {
+namespace System
+{
[Serializable]
-[System.Runtime.InteropServices.ComVisible(true)]
- public enum DayOfWeek {
+ public enum DayOfWeek
+ {
Sunday = 0,
Monday = 1,
Tuesday = 2,
diff --git a/src/mscorlib/src/System/Decimal.cs b/src/mscorlib/src/System/Decimal.cs
index fd16697199..a01ed19753 100644
--- a/src/mscorlib/src/System/Decimal.cs
+++ b/src/mscorlib/src/System/Decimal.cs
@@ -57,7 +57,6 @@ namespace System {
// the range of the Decimal type.
[StructLayout(LayoutKind.Sequential)]
[Serializable]
- [System.Runtime.InteropServices.ComVisible(true)]
[System.Runtime.Versioning.NonVersionable] // This only applies to field layout
public struct Decimal : IFormattable, IComparable, IConvertible, IComparable<Decimal>, IEquatable<Decimal>, IDeserializationCallback
{
@@ -346,9 +345,6 @@ namespace System {
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern void FCallAddSub(ref Decimal d1, ref Decimal d2, byte bSign);
- [MethodImplAttribute(MethodImplOptions.InternalCall)]
- private static extern void FCallAddSubOverflowed(ref Decimal d1, ref Decimal d2, byte bSign, ref bool overflowed);
-
// Rounds a Decimal to an integer value. The Decimal argument is rounded
// towards positive infinity.
public static Decimal Ceiling(Decimal d) {
@@ -358,13 +354,11 @@ namespace System {
// Compares two Decimal values, returning an integer that indicates their
// relationship.
//
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
public static int Compare(Decimal d1, Decimal d2) {
return FCallCompare(ref d1, ref d2);
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
private static extern int FCallCompare(ref Decimal d1, ref Decimal d2);
// Compares this object to another object, returning an integer that
@@ -403,9 +397,6 @@ namespace System {
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern void FCallDivide(ref Decimal d1, ref Decimal d2);
- [MethodImplAttribute(MethodImplOptions.InternalCall)]
- private static extern void FCallDivideOverflowed(ref Decimal d1, ref Decimal d2, ref bool overflowed);
-
// Checks if this Decimal is equal to a given object. Returns true
// if the given object is a boxed Decimal and its value is equal to the
@@ -628,14 +619,12 @@ namespace System {
// Returns the larger of two Decimal values.
//
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
internal static Decimal Max(Decimal d1, Decimal d2) {
return FCallCompare(ref d1, ref d2) >= 0? d1: d2;
}
// Returns the smaller of two Decimal values.
//
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
internal static Decimal Min(Decimal d1, Decimal d2) {
return FCallCompare(ref d1, ref d2) < 0? d1: d2;
}
@@ -697,9 +686,6 @@ namespace System {
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern void FCallMultiply(ref Decimal d1, ref Decimal d2);
- [MethodImplAttribute(MethodImplOptions.InternalCall)]
- private static extern void FCallMultiplyOverflowed(ref Decimal d1, ref Decimal d2, ref bool overflowed);
-
// Returns the negated value of the given Decimal. If d is non-zero,
// the result is -d. If d is zero, the result is zero.
//
diff --git a/src/mscorlib/src/System/Delegate.cs b/src/mscorlib/src/System/Delegate.cs
index bca88c18e9..fb9dc4b110 100644
--- a/src/mscorlib/src/System/Delegate.cs
+++ b/src/mscorlib/src/System/Delegate.cs
@@ -191,7 +191,6 @@ namespace System {
return a.CombineImpl(b);
}
- [System.Runtime.InteropServices.ComVisible(true)]
public static Delegate Combine(params Delegate[] delegates)
{
if (delegates == null || delegates.Length == 0)
diff --git a/src/mscorlib/src/System/DelegateSerializationHolder.cs b/src/mscorlib/src/System/DelegateSerializationHolder.cs
index 83fe35ad1e..061f92d42e 100644
--- a/src/mscorlib/src/System/DelegateSerializationHolder.cs
+++ b/src/mscorlib/src/System/DelegateSerializationHolder.cs
@@ -7,7 +7,6 @@ using System;
using System.Reflection;
using System.Runtime.Remoting;
using System.Runtime.Serialization;
-using System.Security.Permissions;
using System.Globalization;
using System.Diagnostics.Contracts;
@@ -25,10 +24,7 @@ namespace System
if (method == null)
throw new ArgumentNullException(nameof(method));
Contract.EndContractBlock();
-
- if (!method.IsPublic || (method.DeclaringType != null && !method.DeclaringType.IsVisible))
- new ReflectionPermission(ReflectionPermissionFlag.MemberAccess).Demand();
-
+
Type c = delegateType.BaseType;
if (c == null || (c != typeof(Delegate) && c != typeof(MulticastDelegate)))
@@ -231,9 +227,6 @@ namespace System
else
d = Delegate.CreateDelegate(type, targetType, de.methodName);
}
-
- if ((d.Method != null && !d.Method.IsPublic) || (d.Method.DeclaringType != null && !d.Method.DeclaringType.IsVisible))
- new ReflectionPermission(ReflectionPermissionFlag.MemberAccess).Demand();
}
catch (Exception e)
{
diff --git a/src/mscorlib/src/System/Diagnostics/Assert.cs b/src/mscorlib/src/System/Diagnostics/Assert.cs
index 77cc6d8e46..9f4b86b7e4 100644
--- a/src/mscorlib/src/System/Diagnostics/Assert.cs
+++ b/src/mscorlib/src/System/Diagnostics/Assert.cs
@@ -4,7 +4,6 @@
namespace System.Diagnostics {
using System;
- using System.Security.Permissions;
using System.IO;
using System.Reflection;
using System.Runtime.CompilerServices;
@@ -36,14 +35,6 @@ namespace System.Diagnostics {
}
}
- internal static void Check(bool condition, String conditionString, String message, int exitCode)
- {
- if (!condition)
- {
- Fail(conditionString, message, null, exitCode);
- }
- }
-
internal static void Fail(String conditionString, String message)
{
Fail(conditionString, message, null, COR_E_FAILFAST);
diff --git a/src/mscorlib/src/System/Diagnostics/ConditionalAttribute.cs b/src/mscorlib/src/System/Diagnostics/ConditionalAttribute.cs
index b20931f9c3..c57fb59319 100644
--- a/src/mscorlib/src/System/Diagnostics/ConditionalAttribute.cs
+++ b/src/mscorlib/src/System/Diagnostics/ConditionalAttribute.cs
@@ -7,7 +7,6 @@ using System;
namespace System.Diagnostics {
[Serializable]
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, AllowMultiple=true)]
- [System.Runtime.InteropServices.ComVisible(true)]
public sealed class ConditionalAttribute : Attribute
{
public ConditionalAttribute(String conditionString)
diff --git a/src/mscorlib/src/System/Diagnostics/Contracts/Contracts.cs b/src/mscorlib/src/System/Diagnostics/Contracts/Contracts.cs
index 27f4f4cdaa..93d6c48701 100644
--- a/src/mscorlib/src/System/Diagnostics/Contracts/Contracts.cs
+++ b/src/mscorlib/src/System/Diagnostics/Contracts/Contracts.cs
@@ -41,7 +41,6 @@ using System.Runtime.ConstrainedExecution;
#endif
#if FEATURE_UNTRUSTED_CALLERS
using System.Security;
-using System.Security.Permissions;
#endif
namespace System.Diagnostics.Contracts {
@@ -294,7 +293,6 @@ namespace System.Diagnostics.Contracts {
[Conditional("DEBUG")]
[Conditional("CONTRACTS_FULL")]
#if FEATURE_RELIABILITY_CONTRACTS
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
#endif
public static void Assume(bool condition)
{
@@ -315,7 +313,6 @@ namespace System.Diagnostics.Contracts {
[Conditional("DEBUG")]
[Conditional("CONTRACTS_FULL")]
#if FEATURE_RELIABILITY_CONTRACTS
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
#endif
public static void Assume(bool condition, String userMessage)
{
@@ -336,7 +333,6 @@ namespace System.Diagnostics.Contracts {
[Conditional("DEBUG")]
[Conditional("CONTRACTS_FULL")]
#if FEATURE_RELIABILITY_CONTRACTS
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
#endif
public static void Assert(bool condition)
{
@@ -353,7 +349,6 @@ namespace System.Diagnostics.Contracts {
[Conditional("DEBUG")]
[Conditional("CONTRACTS_FULL")]
#if FEATURE_RELIABILITY_CONTRACTS
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
#endif
public static void Assert(bool condition, String userMessage)
{
@@ -377,7 +372,6 @@ namespace System.Diagnostics.Contracts {
[Pure]
[Conditional("CONTRACTS_FULL")]
#if FEATURE_RELIABILITY_CONTRACTS
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
#endif
public static void Requires(bool condition)
{
@@ -397,7 +391,6 @@ namespace System.Diagnostics.Contracts {
[Pure]
[Conditional("CONTRACTS_FULL")]
#if FEATURE_RELIABILITY_CONTRACTS
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
#endif
public static void Requires(bool condition, String userMessage)
{
@@ -417,7 +410,6 @@ namespace System.Diagnostics.Contracts {
[SuppressMessage("Microsoft.Design", "CA1004:GenericMethodsShouldProvideTypeParameter")]
[Pure]
#if FEATURE_RELIABILITY_CONTRACTS
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
#endif
public static void Requires<TException>(bool condition) where TException : Exception
{
@@ -439,7 +431,6 @@ namespace System.Diagnostics.Contracts {
[SuppressMessage("Microsoft.Design", "CA1004:GenericMethodsShouldProvideTypeParameter")]
[Pure]
#if FEATURE_RELIABILITY_CONTRACTS
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
#endif
public static void Requires<TException>(bool condition, String userMessage) where TException : Exception
{
@@ -462,7 +453,6 @@ namespace System.Diagnostics.Contracts {
[Pure]
[Conditional("CONTRACTS_FULL")]
#if FEATURE_RELIABILITY_CONTRACTS
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
#endif
public static void Ensures(bool condition)
{
@@ -482,7 +472,6 @@ namespace System.Diagnostics.Contracts {
[Pure]
[Conditional("CONTRACTS_FULL")]
#if FEATURE_RELIABILITY_CONTRACTS
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
#endif
public static void Ensures(bool condition, String userMessage)
{
@@ -503,7 +492,6 @@ namespace System.Diagnostics.Contracts {
[Conditional("CONTRACTS_FULL")]
[SuppressMessage("Microsoft.Design", "CA1004:GenericMethodsShouldProvideTypeParameter", Justification = "Exception type used in tools.")]
#if FEATURE_RELIABILITY_CONTRACTS
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
#endif
public static void EnsuresOnThrow<TException>(bool condition) where TException : Exception
{
@@ -525,7 +513,6 @@ namespace System.Diagnostics.Contracts {
[Conditional("CONTRACTS_FULL")]
[SuppressMessage("Microsoft.Design", "CA1004:GenericMethodsShouldProvideTypeParameter", Justification = "Exception type used in tools.")]
#if FEATURE_RELIABILITY_CONTRACTS
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
#endif
public static void EnsuresOnThrow<TException>(bool condition, String userMessage) where TException : Exception
{
@@ -545,7 +532,6 @@ namespace System.Diagnostics.Contracts {
[SuppressMessage("Microsoft.Design", "CA1004:GenericMethodsShouldProvideTypeParameter", Justification = "Not intended to be called at runtime.")]
[Pure]
#if FEATURE_RELIABILITY_CONTRACTS
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
#endif
public static T Result<T>() { return default(T); }
@@ -561,7 +547,6 @@ namespace System.Diagnostics.Contracts {
[SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", MessageId = "0#", Justification = "Not intended to be called at runtime.")]
[Pure]
#if FEATURE_RELIABILITY_CONTRACTS
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
#endif
public static T ValueAtReturn<T>(out T value) { value = default(T); return value; }
@@ -577,7 +562,6 @@ namespace System.Diagnostics.Contracts {
[SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "value")]
[Pure]
#if FEATURE_RELIABILITY_CONTRACTS
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
#endif
public static T OldValue<T>(T value) { return default(T); }
@@ -599,7 +583,6 @@ namespace System.Diagnostics.Contracts {
[Pure]
[Conditional("CONTRACTS_FULL")]
#if FEATURE_RELIABILITY_CONTRACTS
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
#endif
public static void Invariant(bool condition)
{
@@ -619,7 +602,6 @@ namespace System.Diagnostics.Contracts {
[Pure]
[Conditional("CONTRACTS_FULL")]
#if FEATURE_RELIABILITY_CONTRACTS
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
#endif
public static void Invariant(bool condition, String userMessage)
{
@@ -644,7 +626,6 @@ namespace System.Diagnostics.Contracts {
/// <seealso cref="System.Collections.Generic.List&lt;T&gt;.TrueForAll"/>
[Pure]
#if FEATURE_RELIABILITY_CONTRACTS
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)] // Assumes predicate obeys CER rules.
#endif
public static bool ForAll(int fromInclusive, int toExclusive, Predicate<int> predicate)
{
@@ -675,7 +656,6 @@ namespace System.Diagnostics.Contracts {
/// <seealso cref="System.Collections.Generic.List&lt;T&gt;.TrueForAll"/>
[Pure]
#if FEATURE_RELIABILITY_CONTRACTS
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)] // Assumes predicate & collection enumerator obey CER rules.
#endif
public static bool ForAll<T>(IEnumerable<T> collection, Predicate<T> predicate)
{
@@ -706,7 +686,6 @@ namespace System.Diagnostics.Contracts {
/// <seealso cref="System.Collections.Generic.List&lt;T&gt;.Exists"/>
[Pure]
#if FEATURE_RELIABILITY_CONTRACTS
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)] // Assumes predicate obeys CER rules.
#endif
public static bool Exists(int fromInclusive, int toExclusive, Predicate<int> predicate)
{
@@ -736,7 +715,6 @@ namespace System.Diagnostics.Contracts {
/// <seealso cref="System.Collections.Generic.List&lt;T&gt;.Exists"/>
[Pure]
#if FEATURE_RELIABILITY_CONTRACTS
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)] // Assumes predicate & collection enumerator obey CER rules.
#endif
public static bool Exists<T>(IEnumerable<T> collection, Predicate<T> predicate)
{
@@ -756,107 +734,6 @@ namespace System.Diagnostics.Contracts {
#endregion Quantifiers
#region Pointers
-#if FEATURE_UNSAFE_CONTRACTS
- /// <summary>
- /// Runtime checking for pointer bounds is not currently feasible. Thus, at runtime, we just return
- /// a very long extent for each pointer that is writable. As long as assertions are of the form
- /// WritableBytes(ptr) >= ..., the runtime assertions will not fail.
- /// The runtime value is 2^64 - 1 or 2^32 - 1.
- /// </summary>
- [SuppressMessage("Microsoft.Performance", "CA1802", Justification = "FxCop is confused")]
- static readonly ulong MaxWritableExtent = (UIntPtr.Size == 4) ? UInt32.MaxValue : UInt64.MaxValue;
-
- /// <summary>
- /// Allows specifying a writable extent for a UIntPtr, similar to SAL's writable extent.
- /// NOTE: this is for static checking only. No useful runtime code can be generated for this
- /// at the moment.
- /// </summary>
- /// <param name="startAddress">Start of memory region</param>
- /// <returns>The result is the number of bytes writable starting at <paramref name="startAddress"/></returns>
- [CLSCompliant(false)]
- [Pure]
- [ContractRuntimeIgnored]
-#if FEATURE_RELIABILITY_CONTRACTS
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
-#endif
- public static ulong WritableBytes(UIntPtr startAddress) { return MaxWritableExtent - startAddress.ToUInt64(); }
-
- /// <summary>
- /// Allows specifying a writable extent for a UIntPtr, similar to SAL's writable extent.
- /// NOTE: this is for static checking only. No useful runtime code can be generated for this
- /// at the moment.
- /// </summary>
- /// <param name="startAddress">Start of memory region</param>
- /// <returns>The result is the number of bytes writable starting at <paramref name="startAddress"/></returns>
- [CLSCompliant(false)]
- [Pure]
- [ContractRuntimeIgnored]
-#if FEATURE_RELIABILITY_CONTRACTS
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
-#endif
- public static ulong WritableBytes(IntPtr startAddress) { return MaxWritableExtent - (ulong)startAddress; }
-
- /// <summary>
- /// Allows specifying a writable extent for a UIntPtr, similar to SAL's writable extent.
- /// NOTE: this is for static checking only. No useful runtime code can be generated for this
- /// at the moment.
- /// </summary>
- /// <param name="startAddress">Start of memory region</param>
- /// <returns>The result is the number of bytes writable starting at <paramref name="startAddress"/></returns>
- [CLSCompliant(false)]
- [Pure]
- [ContractRuntimeIgnored]
-#if FEATURE_RELIABILITY_CONTRACTS
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
-#endif
-
- unsafe public static ulong WritableBytes(void* startAddress) { return MaxWritableExtent - (ulong)startAddress; }
-
- /// <summary>
- /// Allows specifying a readable extent for a UIntPtr, similar to SAL's readable extent.
- /// NOTE: this is for static checking only. No useful runtime code can be generated for this
- /// at the moment.
- /// </summary>
- /// <param name="startAddress">Start of memory region</param>
- /// <returns>The result is the number of bytes readable starting at <paramref name="startAddress"/></returns>
- [CLSCompliant(false)]
- [Pure]
- [ContractRuntimeIgnored]
-#if FEATURE_RELIABILITY_CONTRACTS
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
-#endif
- public static ulong ReadableBytes(UIntPtr startAddress) { return MaxWritableExtent - startAddress.ToUInt64(); }
-
- /// <summary>
- /// Allows specifying a readable extent for a UIntPtr, similar to SAL's readable extent.
- /// NOTE: this is for static checking only. No useful runtime code can be generated for this
- /// at the moment.
- /// </summary>
- /// <param name="startAddress">Start of memory region</param>
- /// <returns>The result is the number of bytes readable starting at <paramref name="startAddress"/></returns>
- [CLSCompliant(false)]
- [Pure]
- [ContractRuntimeIgnored]
-#if FEATURE_RELIABILITY_CONTRACTS
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
-#endif
- public static ulong ReadableBytes(IntPtr startAddress) { return MaxWritableExtent - (ulong)startAddress; }
-
- /// <summary>
- /// Allows specifying a readable extent for a UIntPtr, similar to SAL's readable extent.
- /// NOTE: this is for static checking only. No useful runtime code can be generated for this
- /// at the moment.
- /// </summary>
- /// <param name="startAddress">Start of memory region</param>
- /// <returns>The result is the number of bytes readable starting at <paramref name="startAddress"/></returns>
- [CLSCompliant(false)]
- [Pure]
- [ContractRuntimeIgnored]
-#if FEATURE_RELIABILITY_CONTRACTS
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
-#endif
- unsafe public static ulong ReadableBytes(void* startAddress) { return MaxWritableExtent - (ulong)startAddress; }
-#endif // FEATURE_UNSAFE_CONTRACTS
#endregion
#region Misc.
@@ -866,7 +743,6 @@ namespace System.Diagnostics.Contracts {
/// </summary>
[Conditional("CONTRACTS_FULL")]
#if FEATURE_RELIABILITY_CONTRACTS
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
#endif
public static void EndContractBlock() { }
@@ -927,7 +803,6 @@ namespace System.Diagnostics.Contracts.Internal
[SuppressMessage("Microsoft.Design", "CA1030:UseEventsWhereAppropriate")]
[System.Diagnostics.DebuggerNonUserCode]
#if FEATURE_RELIABILITY_CONTRACTS
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
#endif
public static string RaiseContractFailedEvent(ContractFailureKind failureKind, String userMessage, String conditionText, Exception innerException)
{
@@ -939,7 +814,6 @@ namespace System.Diagnostics.Contracts.Internal
/// </summary>
[System.Diagnostics.DebuggerNonUserCode]
#if FEATURE_RELIABILITY_CONTRACTS
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
#endif
public static void TriggerFailure(ContractFailureKind kind, String displayMessage, String userMessage, String conditionText, Exception innerException)
{
@@ -966,7 +840,6 @@ namespace System.Runtime.CompilerServices
[SuppressMessage("Microsoft.Design", "CA1030:UseEventsWhereAppropriate")]
[System.Diagnostics.DebuggerNonUserCode]
#if FEATURE_RELIABILITY_CONTRACTS
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
#endif
public static string RaiseContractFailedEvent(ContractFailureKind failureKind, String userMessage, String conditionText, Exception innerException)
{
@@ -981,7 +854,6 @@ namespace System.Runtime.CompilerServices
/// </summary>
[System.Diagnostics.DebuggerNonUserCode]
#if FEATURE_RELIABILITY_CONTRACTS
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
#endif
public static void TriggerFailure(ContractFailureKind kind, String displayMessage, String userMessage, String conditionText, Exception innerException)
{
diff --git a/src/mscorlib/src/System/Diagnostics/Contracts/ContractsBCL.cs b/src/mscorlib/src/System/Diagnostics/Contracts/ContractsBCL.cs
index d5e3f29e6c..5f4de4f666 100644
--- a/src/mscorlib/src/System/Diagnostics/Contracts/ContractsBCL.cs
+++ b/src/mscorlib/src/System/Diagnostics/Contracts/ContractsBCL.cs
@@ -35,7 +35,6 @@ using System.Runtime.ConstrainedExecution;
#endif
#if FEATURE_UNTRUSTED_CALLERS
using System.Security;
-using System.Security.Permissions;
#endif
namespace System.Diagnostics.Contracts {
@@ -93,7 +92,6 @@ namespace System.Diagnostics.Contracts {
[SuppressMessage("Microsoft.Portability", "CA1903:UseOnlyApiFromTargetedFramework", MessageId = "System.Security.SecuritySafeCriticalAttribute")]
[System.Diagnostics.DebuggerNonUserCode]
#if FEATURE_RELIABILITY_CONTRACTS
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
#endif
static partial void ReportFailure(ContractFailureKind failureKind, String userMessage, String conditionText, Exception innerException)
{
@@ -120,15 +118,11 @@ namespace System.Diagnostics.Contracts {
/// </summary>
public static event EventHandler<ContractFailedEventArgs> ContractFailed {
#if FEATURE_UNTRUSTED_CALLERS
-#if FEATURE_LINK_DEMAND
-#endif
#endif
add {
System.Runtime.CompilerServices.ContractHelper.InternalContractFailed += value;
}
#if FEATURE_UNTRUSTED_CALLERS
-#if FEATURE_LINK_DEMAND
-#endif
#endif
remove {
System.Runtime.CompilerServices.ContractHelper.InternalContractFailed -= value;
@@ -149,7 +143,6 @@ namespace System.Diagnostics.Contracts {
internal Exception thrownDuringHandler;
#if FEATURE_RELIABILITY_CONTRACTS
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
#endif
public ContractFailedEventArgs(ContractFailureKind failureKind, String message, String condition, Exception originalException)
{
@@ -171,8 +164,6 @@ namespace System.Diagnostics.Contracts {
}
#if FEATURE_UNTRUSTED_CALLERS
-#if FEATURE_LINK_DEMAND
-#endif
#endif
public void SetHandled()
{
@@ -184,8 +175,6 @@ namespace System.Diagnostics.Contracts {
}
#if FEATURE_UNTRUSTED_CALLERS
-#if FEATURE_LINK_DEMAND
-#endif
#endif
public void SetUnwind()
{
@@ -233,10 +222,6 @@ namespace System.Diagnostics.Contracts {
_Condition = info.GetString("Condition");
}
-#if FEATURE_UNTRUSTED_CALLERS && FEATURE_SERIALIZATION
-#if FEATURE_LINK_DEMAND && FEATURE_SERIALIZATION
-#endif // FEATURE_LINK_DEMAND
-#endif // FEATURE_UNTRUSTED_CALLERS
public override void GetObjectData(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context)
{
base.GetObjectData(info, context);
@@ -434,7 +419,6 @@ namespace System.Runtime.CompilerServices
}
#if FEATURE_RELIABILITY_CONTRACTS
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
#endif
private static String GetDisplayMessage(ContractFailureKind failureKind, String userMessage, String conditionText)
{
diff --git a/src/mscorlib/src/System/Diagnostics/Debugger.cs b/src/mscorlib/src/System/Diagnostics/Debugger.cs
index 8ebbc0a354..21c57dbfaf 100644
--- a/src/mscorlib/src/System/Diagnostics/Debugger.cs
+++ b/src/mscorlib/src/System/Diagnostics/Debugger.cs
@@ -13,11 +13,9 @@ namespace System.Diagnostics
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Security;
- using System.Security.Permissions;
using System.Runtime.Versioning;
// No data, does not need to be marked with the serializable attribute
- [System.Runtime.InteropServices.ComVisible(true)]
public sealed class Debugger
{
// This should have been a static class, but wasn't as of v3.5. Clearly, this is
@@ -34,42 +32,12 @@ namespace System.Diagnostics
// debugger is launched.
public static void Break()
{
- if (!Debugger.IsAttached)
- {
- // Try and demand UnmanagedCodePermission. This is done in a try block because if this
- // fails we want to be able to silently eat the exception and just return so
- // that the call to Break does not possibly cause an unhandled exception.
- // The idea here is that partially trusted code shouldn't be able to launch a debugger
- // without the user going through Watson.
- try
- {
-#pragma warning disable 618
- new SecurityPermission(SecurityPermissionFlag.UnmanagedCode).Demand();
-#pragma warning restore 618
- }
-
- // If we enter this block, we do not have permission to break into the debugger
- // and so we just return.
- catch (SecurityException)
- {
- return;
- }
- }
-
// Causing a break is now allowed.
BreakInternal();
}
static void BreakCanThrow()
{
- if (!Debugger.IsAttached)
- {
-#pragma warning disable 618
- new SecurityPermission(SecurityPermissionFlag.UnmanagedCode).Demand();
-#pragma warning restore 618
- }
-
- // Causing a break is now allowed.
BreakInternal();
}
@@ -84,25 +52,6 @@ namespace System.Diagnostics
if (Debugger.IsAttached)
return (true);
- // Try and demand UnmanagedCodePermission. This is done in a try block because if this
- // fails we want to be able to silently eat the exception and just return so
- // that the call to Break does not possibly cause an unhandled exception.
- // The idea here is that partially trusted code shouldn't be able to launch a debugger
- // without the user going through Watson.
- try
- {
-#pragma warning disable 618
- new SecurityPermission(SecurityPermissionFlag.UnmanagedCode).Demand();
-#pragma warning restore 618
- }
-
- // If we enter this block, we do not have permission to break into the debugger
- // and so we just return.
- catch (SecurityException)
- {
- return (false);
- }
-
// Causing the debugger to launch is now allowed.
return (LaunchInternal());
}
@@ -134,7 +83,6 @@ namespace System.Diagnostics
// notification will apprise the debugger that it will need to slip a thread or abort the funceval
// in such a situation. The notification is subject to collection after this function returns.
//
- [method:System.Runtime.InteropServices.ComVisible(false)]
public static void NotifyOfCrossThreadDependency()
{
if (Debugger.IsAttached)
diff --git a/src/mscorlib/src/System/Diagnostics/DebuggerAttributes.cs b/src/mscorlib/src/System/Diagnostics/DebuggerAttributes.cs
index e75b653a0b..ce9987b9e2 100644
--- a/src/mscorlib/src/System/Diagnostics/DebuggerAttributes.cs
+++ b/src/mscorlib/src/System/Diagnostics/DebuggerAttributes.cs
@@ -19,23 +19,13 @@ namespace System.Diagnostics {
[Serializable]
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Constructor, Inherited = false)]
- [ComVisible(true)]
public sealed class DebuggerStepThroughAttribute : Attribute
{
public DebuggerStepThroughAttribute () {}
}
[Serializable]
-[AttributeUsage(AttributeTargets.Method | AttributeTargets.Constructor, Inherited = false)]
- [ComVisible(true)]
- public sealed class DebuggerStepperBoundaryAttribute : Attribute
- {
- public DebuggerStepperBoundaryAttribute () {}
- }
-
-[Serializable]
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Constructor, Inherited = false)]
- [ComVisible(true)]
public sealed class DebuggerHiddenAttribute : Attribute
{
public DebuggerHiddenAttribute () {}
@@ -43,7 +33,6 @@ namespace System.Diagnostics {
[Serializable]
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Constructor |AttributeTargets.Struct, Inherited = false)]
- [ComVisible(true)]
public sealed class DebuggerNonUserCodeAttribute : Attribute
{
public DebuggerNonUserCodeAttribute () {}
@@ -58,11 +47,9 @@ namespace System.Diagnostics {
// won't preserve the debugging info, which will make debugging after
// a JIT attach difficult.
[AttributeUsage(AttributeTargets.Assembly|AttributeTargets.Module, AllowMultiple = false)]
- [ComVisible(true)]
public sealed class DebuggableAttribute : Attribute
{
[Flags]
- [ComVisible(true)]
public enum DebuggingModes
{
None = 0x0,
@@ -121,7 +108,6 @@ namespace System.Diagnostics {
// Please also change the code which validates DebuggerBrowsableState variable (in this file)
// if you change this enum.
- [ComVisible(true)]
public enum DebuggerBrowsableState
{
Never = 0,
@@ -135,7 +121,6 @@ namespace System.Diagnostics {
// the one currently supported with the csee.dat
// (mcee.dat, autoexp.dat) file.
[AttributeUsage(AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = false)]
- [ComVisible(true)]
public sealed class DebuggerBrowsableAttribute: Attribute
{
private DebuggerBrowsableState state;
@@ -156,7 +141,6 @@ namespace System.Diagnostics {
// DebuggerTypeProxyAttribute
[AttributeUsage(AttributeTargets.Struct | AttributeTargets.Class | AttributeTargets.Assembly, AllowMultiple = true)]
- [ComVisible(true)]
public sealed class DebuggerTypeProxyAttribute: Attribute
{
private string typeName;
@@ -215,7 +199,6 @@ namespace System.Diagnostics {
// however: there is no access to aliases, locals, or pointers.
// In addition, attributes on properties referenced in the expression are not processed.
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Delegate | AttributeTargets.Enum | AttributeTargets.Field | AttributeTargets.Property | AttributeTargets.Assembly, AllowMultiple = true)]
- [ComVisible(true)]
public sealed class DebuggerDisplayAttribute : Attribute
{
private string name;
@@ -274,105 +257,6 @@ namespace System.Diagnostics {
}
}
-
-
- /// <summary>
- /// Signifies that the attributed type has a visualizer which is pointed
- /// to by the parameter type name strings.
- /// </summary>
- [AttributeUsage(AttributeTargets.Struct | AttributeTargets.Class | AttributeTargets.Assembly, AllowMultiple = true)]
- [ComVisible(true)]
- public sealed class DebuggerVisualizerAttribute: Attribute
- {
- private string visualizerObjectSourceName;
- private string visualizerName;
- private string description;
- private string targetName;
- private Type target;
-
- public DebuggerVisualizerAttribute(string visualizerTypeName)
- {
- this.visualizerName = visualizerTypeName;
- }
- public DebuggerVisualizerAttribute(string visualizerTypeName, string visualizerObjectSourceTypeName)
- {
- this.visualizerName = visualizerTypeName;
- this.visualizerObjectSourceName = visualizerObjectSourceTypeName;
- }
- public DebuggerVisualizerAttribute(string visualizerTypeName, Type visualizerObjectSource)
- {
- if (visualizerObjectSource == null) {
- throw new ArgumentNullException(nameof(visualizerObjectSource));
- }
- Contract.EndContractBlock();
- this.visualizerName = visualizerTypeName;
- this.visualizerObjectSourceName = visualizerObjectSource.AssemblyQualifiedName;
- }
- public DebuggerVisualizerAttribute(Type visualizer)
- {
- if (visualizer == null) {
- throw new ArgumentNullException(nameof(visualizer));
- }
- Contract.EndContractBlock();
- this.visualizerName = visualizer.AssemblyQualifiedName;
- }
- public DebuggerVisualizerAttribute(Type visualizer, Type visualizerObjectSource)
- {
- if (visualizer == null) {
- throw new ArgumentNullException(nameof(visualizer));
- }
- if (visualizerObjectSource == null) {
- throw new ArgumentNullException(nameof(visualizerObjectSource));
- }
- Contract.EndContractBlock();
- this.visualizerName = visualizer.AssemblyQualifiedName;
- this.visualizerObjectSourceName = visualizerObjectSource.AssemblyQualifiedName;
- }
- public DebuggerVisualizerAttribute(Type visualizer, string visualizerObjectSourceTypeName)
- {
- if (visualizer == null) {
- throw new ArgumentNullException(nameof(visualizer));
- }
- Contract.EndContractBlock();
- this.visualizerName = visualizer.AssemblyQualifiedName;
- this.visualizerObjectSourceName = visualizerObjectSourceTypeName;
- }
-
- public string VisualizerObjectSourceTypeName
- {
- get { return visualizerObjectSourceName; }
- }
- public string VisualizerTypeName
- {
- get { return visualizerName; }
- }
- public string Description
- {
- get { return description; }
- set { description = value; }
- }
-
- public Type Target
- {
- set {
- if( value == null) {
- throw new ArgumentNullException(nameof(value));
- }
- Contract.EndContractBlock();
-
- targetName = value.AssemblyQualifiedName;
- target = value;
- }
-
- get { return target; }
- }
-
- public string TargetTypeName
- {
- set { targetName = value; }
- get { return targetName; }
- }
- }
}
diff --git a/src/mscorlib/src/System/Diagnostics/Eventing/EventDescriptor.cs b/src/mscorlib/src/System/Diagnostics/Eventing/EventDescriptor.cs
index 11b6e6bac2..116b50f86c 100644
--- a/src/mscorlib/src/System/Diagnostics/Eventing/EventDescriptor.cs
+++ b/src/mscorlib/src/System/Diagnostics/Eventing/EventDescriptor.cs
@@ -22,7 +22,9 @@ namespace System.Diagnostics.Tracing
#endif
{
[StructLayout(LayoutKind.Explicit, Size = 16)]
+#if !CORECLR
[System.Security.Permissions.HostProtection(MayLeakOnAbort = true)]
+#endif // CORECLR
internal struct EventDescriptor
{
# region private
diff --git a/src/mscorlib/src/System/Diagnostics/Eventing/EventProvider.cs b/src/mscorlib/src/System/Diagnostics/Eventing/EventProvider.cs
index ce0fcb6acb..1da6a46707 100644
--- a/src/mscorlib/src/System/Diagnostics/Eventing/EventProvider.cs
+++ b/src/mscorlib/src/System/Diagnostics/Eventing/EventProvider.cs
@@ -8,7 +8,9 @@ using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Runtime.InteropServices;
using System.Security;
+#if !CORECLR
using System.Security.Permissions;
+#endif // !CORECLR
using System.Threading;
using System;
@@ -43,7 +45,9 @@ namespace System.Diagnostics.Tracing
/// Only here because System.Diagnostics.EventProvider needs one more extensibility hook (when it gets a
/// controller callback)
/// </summary>
+#if !CORECLR
[System.Security.Permissions.HostProtection(MayLeakOnAbort = true)]
+#endif // CORECLR
internal partial class EventProvider : IDisposable
{
// This is the windows EVENT_DATA_DESCRIPTOR structure. We expose it because this is what
@@ -341,9 +345,10 @@ namespace System.Diagnostics.Tracing
{
List<SessionInfo> liveSessionList = null;
- GetSessionInfo((Action<int, long>)
- ((etwSessionId, matchAllKeywords) =>
- GetSessionInfoCallback(etwSessionId, matchAllKeywords, ref liveSessionList)));
+ GetSessionInfo(
+ (int etwSessionId, long matchAllKeywords, ref List<SessionInfo> sessionList) =>
+ GetSessionInfoCallback(etwSessionId, matchAllKeywords, ref sessionList),
+ ref liveSessionList);
List<Tuple<SessionInfo, bool>> changedSessionList = new List<Tuple<SessionInfo, bool>>();
@@ -407,12 +412,14 @@ namespace System.Diagnostics.Tracing
}
}
+ private delegate void SessionInfoCallback(int etwSessionId, long matchAllKeywords, ref List<SessionInfo> sessionList);
+
/// <summary>
/// This method enumerates over all active ETW sessions that have enabled 'this.m_Guid'
/// 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>
- private unsafe void GetSessionInfo(Action<int, long> action)
+ private unsafe void GetSessionInfo(SessionInfoCallback action, ref List<SessionInfo> sessionList)
{
// We wish the EventSource package to be legal for Windows Store applications.
// Currently EnumerateTraceGuidsEx is not an allowed API, so we avoid its use here
@@ -453,7 +460,7 @@ namespace System.Diagnostics.Tracing
var enabledInfos = (UnsafeNativeMethods.ManifestEtw.TRACE_ENABLE_INFO*)&providerInstance[1];
// iterate over the list of active ETW sessions "listening" to the current provider
for (int j = 0; j < providerInstance->EnableCount; j++)
- action(enabledInfos[j].LoggerId, enabledInfos[j].MatchAllKeyword);
+ action(enabledInfos[j].LoggerId, enabledInfos[j].MatchAllKeyword, ref sessionList);
}
if (providerInstance->NextOffset == 0)
break;
@@ -503,7 +510,7 @@ namespace System.Diagnostics.Tracing
string keywordBitString = dataAsString.Substring(startIdx, endIdx-startIdx);
int keywordBit;
if (0 < endIdx && int.TryParse(keywordBitString, out keywordBit))
- action(etwSessionId, 1L << keywordBit);
+ action(etwSessionId, 1L << keywordBit, ref sessionList);
}
}
}
@@ -556,7 +563,9 @@ namespace System.Diagnostics.Tracing
string valueName = "ControllerData_Session_" + etwSessionId.ToString(CultureInfo.InvariantCulture);
// we need to assert this permission for partial trust scenarios
+#if !CORECLR
(new RegistryPermission(RegistryPermissionAccess.Read, regKey)).Assert();
+#endif
data = Microsoft.Win32.Registry.GetValue(regKey, valueName, null) as byte[];
if (data != null)
{
diff --git a/src/mscorlib/src/System/Diagnostics/Eventing/EventSource.cs b/src/mscorlib/src/System/Diagnostics/Eventing/EventSource.cs
index aa0d8d72d1..a558a1647e 100644
--- a/src/mscorlib/src/System/Diagnostics/Eventing/EventSource.cs
+++ b/src/mscorlib/src/System/Diagnostics/Eventing/EventSource.cs
@@ -187,7 +187,9 @@ using System.Globalization;
using System.Reflection;
using System.Resources;
using System.Security;
+#if !CORECLR
using System.Security.Permissions;
+#endif // !CORECLR
using System.Text;
using System.Threading;
@@ -3047,7 +3049,7 @@ namespace System.Diagnostics.Tracing
}
if (s_currentPid == 0)
{
-#if ES_BUILD_STANDALONE && !ES_BUILD_PCL
+#if ES_BUILD_STANDALONE && !ES_BUILD_PCL && !CORECLR
// for non-BCL EventSource we must assert SecurityPermission
new SecurityPermission(PermissionState.Unrestricted).Assert();
#endif
@@ -3803,7 +3805,9 @@ namespace System.Diagnostics.Tracing
// RET
//
// If we find this pattern we return the XXX. Otherwise we return -1.
+#if !CORECLR
(new ReflectionPermission(ReflectionPermissionFlag.MemberAccess)).Assert();
+#endif
byte[] instrs = method.GetMethodBody().GetILAsByteArray();
int retVal = -1;
for (int idx = 0; idx < instrs.Length;)
@@ -4221,7 +4225,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((EventListener)obj));
}
/// <summary>
@@ -6741,6 +6745,7 @@ namespace System.Diagnostics.Tracing
stringBuilder.Append(eventMessage, startIndex, count);
}
+ private static readonly string[] s_escapes = { "&amp;", "&lt;", "&gt;", "&apos;", "&quot;", "%r", "%n", "%t" };
// Manifest messages use %N conventions for their message substitutions. Translate from
// .NET conventions. We can't use RegEx for this (we are in mscorlib), so we do it 'by hand'
private string TranslateToManifestConvention(string eventMessage, string evtName)
@@ -6808,16 +6813,10 @@ namespace System.Diagnostics.Tracing
}
else if ((chIdx = "&<>'\"\r\n\t".IndexOf(eventMessage[i])) >= 0)
{
- string[] escapes = { "&amp;", "&lt;", "&gt;", "&apos;", "&quot;", "%r", "%n", "%t" };
- var update = new Action<char, string>(
- (ch, escape) =>
- {
- UpdateStringBuilder(ref stringBuilder, eventMessage, writtenSoFar, i - writtenSoFar);
- i++;
- stringBuilder.Append(escape);
- writtenSoFar = i;
- });
- update(eventMessage[i], escapes[chIdx]);
+ UpdateStringBuilder(ref stringBuilder, eventMessage, writtenSoFar, i - writtenSoFar);
+ i++;
+ stringBuilder.Append(s_escapes[chIdx]);
+ writtenSoFar = i;
}
else
i++;
diff --git a/src/mscorlib/src/System/Diagnostics/Eventing/FrameworkEventSource.cs b/src/mscorlib/src/System/Diagnostics/Eventing/FrameworkEventSource.cs
index 6d3e28fcab..80c524b350 100644
--- a/src/mscorlib/src/System/Diagnostics/Eventing/FrameworkEventSource.cs
+++ b/src/mscorlib/src/System/Diagnostics/Eventing/FrameworkEventSource.cs
@@ -86,7 +86,10 @@ namespace System.Diagnostics.Tracing {
// WriteEvent overloads (to avoid the "params" EventSource.WriteEvent
// optimized for common signatures (used by the ThreadTransferSend/Receive events)
- [NonEvent, System.Security.SecuritySafeCritical]
+ [NonEvent]
+#if !CORECLR
+ [System.Security.SecuritySafeCritical]
+#endif // !CORECLR
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Concurrency", "CA8001", Justification = "This does not need to be correct when racing with other threads")]
private unsafe void WriteEvent(int eventId, long arg1, int arg2, string arg3, bool arg4)
{
@@ -110,7 +113,10 @@ namespace System.Diagnostics.Tracing {
}
// optimized for common signatures (used by the ThreadTransferSend/Receive events)
- [NonEvent, System.Security.SecuritySafeCritical]
+ [NonEvent]
+#if !CORECLR
+ [System.Security.SecuritySafeCritical]
+#endif // !CORECLR
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Concurrency", "CA8001", Justification = "This does not need to be correct when racing with other threads")]
private unsafe void WriteEvent(int eventId, long arg1, int arg2, string arg3)
{
@@ -132,7 +138,10 @@ namespace System.Diagnostics.Tracing {
}
// optimized for common signatures (used by the BeginGetResponse/BeginGetRequestStream events)
- [NonEvent, System.Security.SecuritySafeCritical]
+ [NonEvent]
+#if !CORECLR
+ [System.Security.SecuritySafeCritical]
+#endif // !CORECLR
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Concurrency", "CA8001", Justification = "This does not need to be correct when racing with other threads")]
private unsafe void WriteEvent(int eventId, long arg1, string arg2, bool arg3, bool arg4)
{
@@ -156,7 +165,10 @@ namespace System.Diagnostics.Tracing {
}
// optimized for common signatures (used by the EndGetRequestStream event)
- [NonEvent, System.Security.SecuritySafeCritical]
+ [NonEvent]
+#if !CORECLR
+ [System.Security.SecuritySafeCritical]
+#endif // !CORECLR
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Concurrency", "CA8001", Justification = "This does not need to be correct when racing with other threads")]
private unsafe void WriteEvent(int eventId, long arg1, bool arg2, bool arg3)
{
@@ -174,7 +186,10 @@ namespace System.Diagnostics.Tracing {
}
// optimized for common signatures (used by the EndGetResponse event)
- [NonEvent, System.Security.SecuritySafeCritical]
+ [NonEvent]
+#if !CORECLR
+ [System.Security.SecuritySafeCritical]
+#endif // !CORECLR
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Concurrency", "CA8001", Justification = "This does not need to be correct when racing with other threads")]
private unsafe void WriteEvent(int eventId, long arg1, bool arg2, bool arg3, int arg4)
{
@@ -479,7 +494,10 @@ namespace System.Diagnostics.Tracing {
public void ThreadPoolEnqueueWork(long workID) {
WriteEvent(30, workID);
}
- [NonEvent, System.Security.SecuritySafeCritical]
+ [NonEvent]
+#if !CORECLR
+ [System.Security.SecuritySafeCritical]
+#endif // !CORECLR
public unsafe void ThreadPoolEnqueueWorkObject(object workID) {
// convert the Object Id to a long
ThreadPoolEnqueueWork((long) *((void**) JitHelpers.UnsafeCastToStackPointer(ref workID)));
@@ -490,7 +508,10 @@ namespace System.Diagnostics.Tracing {
WriteEvent(31, workID);
}
- [NonEvent, System.Security.SecuritySafeCritical]
+ [NonEvent]
+#if !CORECLR
+ [System.Security.SecuritySafeCritical]
+#endif // !CORECLR
public unsafe void ThreadPoolDequeueWorkObject(object workID) {
// convert the Object Id to a long
ThreadPoolDequeueWork((long) *((void**) JitHelpers.UnsafeCastToStackPointer(ref workID)));
@@ -524,25 +545,37 @@ namespace System.Diagnostics.Tracing {
WriteEvent(143, id, success, synchronous);
}
- [NonEvent, System.Security.SecuritySafeCritical]
+ [NonEvent]
+#if !CORECLR
+ [System.Security.SecuritySafeCritical]
+#endif // !CORECLR
public unsafe void BeginGetResponse(object id, string uri, bool success, bool synchronous) {
if (IsEnabled())
GetResponseStart(IdForObject(id), uri, success, synchronous);
}
- [NonEvent, System.Security.SecuritySafeCritical]
+ [NonEvent]
+#if !CORECLR
+ [System.Security.SecuritySafeCritical]
+#endif // !CORECLR
public unsafe void EndGetResponse(object id, bool success, bool synchronous, int statusCode) {
if (IsEnabled())
GetResponseStop(IdForObject(id), success, synchronous, statusCode);
}
- [NonEvent, System.Security.SecuritySafeCritical]
+ [NonEvent]
+#if !CORECLR
+ [System.Security.SecuritySafeCritical]
+#endif // !CORECLR
public unsafe void BeginGetRequestStream(object id, string uri, bool success, bool synchronous) {
if (IsEnabled())
GetRequestStreamStart(IdForObject(id), uri, success, synchronous);
}
- [NonEvent, System.Security.SecuritySafeCritical]
+ [NonEvent]
+#if !CORECLR
+ [System.Security.SecuritySafeCritical]
+#endif // !CORECLR
public unsafe void EndGetRequestStream(object id, bool success, bool synchronous) {
if (IsEnabled())
GetRequestStreamStop(IdForObject(id), success, synchronous);
@@ -563,7 +596,10 @@ namespace System.Diagnostics.Tracing {
// id - is a managed object. it gets translated to the object's address. ETW listeners must
// keep track of GC movements in order to correlate the value passed to XyzSend with the
// (possibly changed) value passed to XyzReceive
- [NonEvent, System.Security.SecuritySafeCritical]
+ [NonEvent]
+#if !CORECLR
+ [System.Security.SecuritySafeCritical]
+#endif // !CORECLR
public unsafe void ThreadTransferSendObj(object id, int kind, string info, bool multiDequeues) {
ThreadTransferSend((long) *((void**) JitHelpers.UnsafeCastToStackPointer(ref id)), kind, info, multiDequeues);
}
@@ -583,7 +619,10 @@ namespace System.Diagnostics.Tracing {
// id - is a managed object. it gets translated to the object's address. ETW listeners must
// keep track of GC movements in order to correlate the value passed to XyzSend with the
// (possibly changed) value passed to XyzReceive
- [NonEvent, System.Security.SecuritySafeCritical]
+ [NonEvent]
+#if !CORECLR
+ [System.Security.SecuritySafeCritical]
+#endif // !CORECLR
public unsafe void ThreadTransferReceiveObj(object id, int kind, string info) {
ThreadTransferReceive((long) *((void**) JitHelpers.UnsafeCastToStackPointer(ref id)), kind, info);
}
@@ -603,7 +642,10 @@ namespace System.Diagnostics.Tracing {
// id - is a managed object. it gets translated to the object's address. ETW listeners must
// keep track of GC movements in order to correlate the value passed to XyzSend with the
// (possibly changed) value passed to XyzReceive
- [NonEvent, System.Security.SecuritySafeCritical]
+ [NonEvent]
+#if !CORECLR
+ [System.Security.SecuritySafeCritical]
+#endif // !CORECLR
public unsafe void ThreadTransferReceiveHandledObj(object id, int kind, string info) {
ThreadTransferReceive((long) *((void**) JitHelpers.UnsafeCastToStackPointer(ref id)), kind, info);
}
diff --git a/src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/TraceLoggingTypeInfo.cs b/src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/TraceLoggingTypeInfo.cs
index 0cc17e02f3..d68e106b0b 100644
--- a/src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/TraceLoggingTypeInfo.cs
+++ b/src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/TraceLoggingTypeInfo.cs
@@ -61,7 +61,7 @@ namespace System.Diagnostics.Tracing
if (name == null)
{
- throw new ArgumentNullException("eventName");
+ throw new ArgumentNullException(nameof(name));
}
Contract.EndContractBlock();
diff --git a/src/mscorlib/src/System/Diagnostics/Eventing/XplatEventLogger.cs b/src/mscorlib/src/System/Diagnostics/Eventing/XplatEventLogger.cs
index c96d2129f0..00155d72a0 100644
--- a/src/mscorlib/src/System/Diagnostics/Eventing/XplatEventLogger.cs
+++ b/src/mscorlib/src/System/Diagnostics/Eventing/XplatEventLogger.cs
@@ -23,7 +23,6 @@ namespace System.Diagnostics.Tracing
private static bool initializedPersistentListener = false;
- [System.Security.SecuritySafeCritical]
public static EventListener InitializePersistentListener()
{
try{
@@ -150,7 +149,6 @@ namespace System.Diagnostics.Tracing
}
}
- [System.Security.SecuritySafeCritical]
private void LogOnEventWritten(EventWrittenEventArgs eventData)
{
string payload = "";
diff --git a/src/mscorlib/src/System/Diagnostics/LogSwitch.cs b/src/mscorlib/src/System/Diagnostics/LogSwitch.cs
index 84f6b91f65..14f0f26d98 100644
--- a/src/mscorlib/src/System/Diagnostics/LogSwitch.cs
+++ b/src/mscorlib/src/System/Diagnostics/LogSwitch.cs
@@ -79,19 +79,6 @@ namespace System.Diagnostics {
get { return strName;}
}
- // Get property returns the description of the switch
- public virtual String Description
- {
- get {return strDescription;}
- }
-
-
- // Get property returns the parent of the switch
- public virtual LogSwitch Parent
- {
- get { return ParentSwitch; }
- }
-
// Property to Get/Set the level of log messages which are "on" for the switch.
//
diff --git a/src/mscorlib/src/System/Diagnostics/Stackframe.cs b/src/mscorlib/src/System/Diagnostics/Stackframe.cs
index 06d675ea08..13d8f5cdcc 100644
--- a/src/mscorlib/src/System/Diagnostics/Stackframe.cs
+++ b/src/mscorlib/src/System/Diagnostics/Stackframe.cs
@@ -8,12 +8,10 @@ namespace System.Diagnostics {
using System;
using System.IO;
using System.Reflection;
- using System.Security.Permissions;
using System.Diagnostics.Contracts;
// There is no good reason for the methods of this class to be virtual.
[Serializable]
- [System.Runtime.InteropServices.ComVisible(true)]
public class StackFrame
{
private MethodBase method;
@@ -23,10 +21,8 @@ namespace System.Diagnostics {
private int iLineNumber;
private int iColumnNumber;
-#if FEATURE_EXCEPTIONDISPATCHINFO
[System.Runtime.Serialization.OptionalField]
private bool fIsLastFrameFromForeignExceptionStackTrace;
-#endif // FEATURE_EXCEPTIONDISPATCHINFO
internal void InitMembers()
{
@@ -36,9 +32,7 @@ namespace System.Diagnostics {
strFileName = null;
iLineNumber = 0;
iColumnNumber = 0;
-#if FEATURE_EXCEPTIONDISPATCHINFO
fIsLastFrameFromForeignExceptionStackTrace = false;
-#endif // FEATURE_EXCEPTIONDISPATCHINFO
}
@@ -142,7 +136,6 @@ namespace System.Diagnostics {
iColumnNumber = iCol;
}
-#if FEATURE_EXCEPTIONDISPATCHINFO
internal virtual void SetIsLastFrameFromForeignExceptionStackTrace (bool fIsLastFrame)
{
fIsLastFrameFromForeignExceptionStackTrace = fIsLastFrame;
@@ -152,7 +145,6 @@ namespace System.Diagnostics {
{
return fIsLastFrameFromForeignExceptionStackTrace;
}
-#endif // FEATURE_EXCEPTIONDISPATCHINFO
// Returns the method the frame is executing
//
@@ -187,17 +179,6 @@ namespace System.Diagnostics {
//
public virtual String GetFileName()
{
- if (strFileName != null)
- {
- // This isn't really correct, but we don't have
- // a permission that protects discovery of potentially
- // local urls so we'll use this.
-
- FileIOPermission perm = new FileIOPermission( PermissionState.None );
- perm.AllFiles = FileIOPermissionAccess.PathDiscovery;
- perm.Demand();
- }
-
return strFileName;
}
@@ -262,24 +243,6 @@ namespace System.Diagnostics {
bool useFileName = (strFileName != null);
- if (useFileName)
- {
- try
- {
- // This isn't really correct, but we don't have
- // a permission that protects discovery of potentially
- // local urls so we'll use this.
-
- FileIOPermission perm = new FileIOPermission(PermissionState.None);
- perm.AllFiles = FileIOPermissionAccess.PathDiscovery;
- perm.Demand();
- }
- catch (System.Security.SecurityException)
- {
- useFileName = false;
- }
- }
-
if (!useFileName)
sb.Append("<filename unknown>");
else
diff --git a/src/mscorlib/src/System/Diagnostics/Stacktrace.cs b/src/mscorlib/src/System/Diagnostics/Stacktrace.cs
index 7dc5d9df09..cd88f5108f 100644
--- a/src/mscorlib/src/System/Diagnostics/Stacktrace.cs
+++ b/src/mscorlib/src/System/Diagnostics/Stacktrace.cs
@@ -8,7 +8,6 @@ namespace System.Diagnostics {
using System.Text;
using System.Threading;
using System.Security;
- using System.Security.Permissions;
using System.IO;
using System.Reflection;
using System.Runtime.InteropServices;
@@ -49,10 +48,8 @@ namespace System.Diagnostics {
private String[] rgFilename;
private int[] rgiLineNumber;
private int[] rgiColumnNumber;
-#if FEATURE_EXCEPTIONDISPATCHINFO
[OptionalField]
private bool[] rgiLastFrameFromForeignExceptionStackTrace;
-#endif // FEATURE_EXCEPTIONDISPATCHINFO
private GetSourceLineInfoDelegate getSourceLineInfo;
private int iFrameCount;
#pragma warning restore 414
@@ -86,9 +83,7 @@ namespace System.Diagnostics {
rgiColumnNumber = null;
getSourceLineInfo = null;
-#if FEATURE_EXCEPTIONDISPATCHINFO
rgiLastFrameFromForeignExceptionStackTrace = null;
-#endif // FEATURE_EXCEPTIONDISPATCHINFO
// 0 means capture all frames. For StackTraces from an Exception, the EE always
// captures all frames. For other uses of StackTraces, we can abort stack walking after
@@ -198,15 +193,12 @@ namespace System.Diagnostics {
public virtual int GetLineNumber(int i) { return rgiLineNumber == null ? 0 : rgiLineNumber[i];}
public virtual int GetColumnNumber(int i) { return rgiColumnNumber == null ? 0 : rgiColumnNumber[i];}
-#if FEATURE_EXCEPTIONDISPATCHINFO
public virtual bool IsLastFrameFromForeignExceptionStackTrace(int i)
{
return (rgiLastFrameFromForeignExceptionStackTrace == null)?false:rgiLastFrameFromForeignExceptionStackTrace[i];
}
-#endif // FEATURE_EXCEPTIONDISPATCHINFO
public virtual int GetNumberOfFrames() { return iFrameCount;}
- public virtual void SetNumberOfFrames(int i) { iFrameCount = i;}
//
// serialization implementation
@@ -259,7 +251,6 @@ namespace System.Diagnostics {
// StackTrace, we use an InheritanceDemand to prevent partially-trusted
// subclasses.
[Serializable]
- [System.Runtime.InteropServices.ComVisible(true)]
public class StackTrace
{
private StackFrame[] frames;
@@ -468,9 +459,7 @@ namespace System.Diagnostics {
sfTemp.SetOffset(StackF.GetOffset(i));
sfTemp.SetILOffset(StackF.GetILOffset(i));
-#if FEATURE_EXCEPTIONDISPATCHINFO
sfTemp.SetIsLastFrameFromForeignExceptionStackTrace(StackF.IsLastFrameFromForeignExceptionStackTrace(i));
-#endif // FEATURE_EXCEPTIONDISPATCHINFO
if (fNeedFileInfo)
{
@@ -524,7 +513,6 @@ namespace System.Diagnostics {
// The nth element of this array is the same as GetFrame(n).
// The length of the array is the same as FrameCount.
//
- [ComVisible(false)]
public virtual StackFrame [] GetFrames()
{
if (frames == null || m_iNumOfFrames <= 0)
@@ -680,13 +668,11 @@ namespace System.Diagnostics {
}
}
-#if FEATURE_EXCEPTIONDISPATCHINFO
if (sf.GetIsLastFrameFromForeignExceptionStackTrace())
{
sb.Append(Environment.NewLine);
sb.Append(Environment.GetResourceString("Exception_EndStackTraceFromPreviousThrow"));
}
-#endif // FEATURE_EXCEPTIONDISPATCHINFO
}
}
diff --git a/src/mscorlib/src/System/Diagnostics/SymbolStore/ISymBinder.cs b/src/mscorlib/src/System/Diagnostics/SymbolStore/ISymBinder.cs
deleted file mode 100644
index 1ce870f983..0000000000
--- a/src/mscorlib/src/System/Diagnostics/SymbolStore/ISymBinder.cs
+++ /dev/null
@@ -1,42 +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.
-
-
-/*============================================================
-**
-**
-**
-** Represents a symbol binder for managed code.
-**
-**
-===========================================================*/
-namespace System.Diagnostics.SymbolStore {
-
- using System;
- using System.Text;
- using System.Runtime.InteropServices;
-
- // Interface does not need to be marked with the serializable attribute
-[System.Runtime.InteropServices.ComVisible(true)]
- public interface ISymbolBinder
- {
- // The importer parameter should be an IntPtr, not an int. This interface can not be modified without
- // a breaking change, and so ISymbolBinderEx.GetReader() has been added with the correct marshalling layout.
- [Obsolete("The recommended alternative is ISymbolBinder1.GetReader. ISymbolBinder1.GetReader takes the importer interface pointer as an IntPtr instead of an Int32, and thus works on both 32-bit and 64-bit architectures. http://go.microsoft.com/fwlink/?linkid=14202=14202")]
- ISymbolReader GetReader(int importer, String filename,
- String searchPath);
- }
-
- // This interface has a revised ISymbolBinder.GetReader() with the proper signature.
- // It is not called ISymbolBinder2 because it maps to the IUnmanagedSymbolBinder interfaces, and
- // does not wrap the IUnmanagedSymbolBinder2 interfaces declared in CorSym.idl.
-[System.Runtime.InteropServices.ComVisible(true)]
- public interface ISymbolBinder1
- {
-
- ISymbolReader GetReader(IntPtr importer, String filename,
- String searchPath);
- }
-
-}
diff --git a/src/mscorlib/src/System/Diagnostics/SymbolStore/ISymDocument.cs b/src/mscorlib/src/System/Diagnostics/SymbolStore/ISymDocument.cs
deleted file mode 100644
index c458b8e8a9..0000000000
--- a/src/mscorlib/src/System/Diagnostics/SymbolStore/ISymDocument.cs
+++ /dev/null
@@ -1,48 +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.
-
-/*============================================================
-**
-**
-**
-** Represents a document referenced by a symbol store. A document is
-** defined by a URL and a document type GUID. Using the document type
-** GUID and the URL, one can locate the document however it is
-** stored. Document source can optionally be stored in the symbol
-** store. This interface also provides access to that source if it is
-** present.
-**
-**
-===========================================================*/
-namespace System.Diagnostics.SymbolStore {
-
- using System;
-
- // Interface does not need to be marked with the serializable attribute
-[System.Runtime.InteropServices.ComVisible(true)]
- public interface ISymbolDocument
- {
- // Properties of the document.
- String URL { get; }
- Guid DocumentType { get; }
-
- // Language of the document.
- Guid Language { get; }
- Guid LanguageVendor { get; }
-
- // Check sum information.
- Guid CheckSumAlgorithmId { get; }
- byte[] GetCheckSum();
-
- // Given a line in this document that may or may not be a sequence
- // point, return the closest line that is a sequence point.
- int FindClosestLine(int line);
-
- // Access to embedded source.
- bool HasEmbeddedSource { get; }
- int SourceLength { get; }
- byte[] GetSourceRange(int startLine, int startColumn,
- int endLine, int endColumn);
- }
-}
diff --git a/src/mscorlib/src/System/Diagnostics/SymbolStore/ISymDocumentWriter.cs b/src/mscorlib/src/System/Diagnostics/SymbolStore/ISymDocumentWriter.cs
index 2b7b078dbc..a1a2366c0a 100644
--- a/src/mscorlib/src/System/Diagnostics/SymbolStore/ISymDocumentWriter.cs
+++ b/src/mscorlib/src/System/Diagnostics/SymbolStore/ISymDocumentWriter.cs
@@ -17,7 +17,6 @@ namespace System.Diagnostics.SymbolStore {
using System;
// Interface does not need to be marked with the serializable attribute
- [System.Runtime.InteropServices.ComVisible(true)]
public interface ISymbolDocumentWriter
{
// SetSource will store the raw source for a document into the
diff --git a/src/mscorlib/src/System/Diagnostics/SymbolStore/ISymMethod.cs b/src/mscorlib/src/System/Diagnostics/SymbolStore/ISymMethod.cs
deleted file mode 100644
index 5edabb1194..0000000000
--- a/src/mscorlib/src/System/Diagnostics/SymbolStore/ISymMethod.cs
+++ /dev/null
@@ -1,86 +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.
-
-/*============================================================
-**
-**
-**
-** Represents a method within a symbol reader. This provides access to
-** only the symbol-related attributes of a method, such as sequence
-** points, lexical scopes, and parameter information. Use it in
-** conjucntion with other means to read the type-related attrbiutes of
-** a method, such as Reflections.
-**
-**
-===========================================================*/
-namespace System.Diagnostics.SymbolStore {
- using System.Runtime.InteropServices;
- using System;
-
- // Interface does not need to be marked with the serializable attribute
-[System.Runtime.InteropServices.ComVisible(true)]
- public interface ISymbolMethod
- {
- // Get the token for this method.
- SymbolToken Token { get; }
-
- // Get the count of sequence points.
- int SequencePointCount { get; }
-
- // Get the sequence points for this method. The sequence points
- // are sorted by offset and are for all documents in the
- // method. Use GetSequencePointCount to retrieve the count of all
- // sequence points and create arrays of the proper size.
- // GetSequencePoints will verify the size of each array and place
- // the sequence point information into each. If any array is NULL,
- // then the data for that array is simply not returned.
- void GetSequencePoints(int[] offsets,
- ISymbolDocument[] documents,
- int[] lines,
- int[] columns,
- int[] endLines,
- int[] endColumns);
-
- // Get the root lexical scope for this method. This scope encloses
- // the entire method.
- ISymbolScope RootScope { get; }
-
- // Given an offset within the method, returns the most enclosing
- // lexical scope. This can be used to start local variable
- // searches.
- ISymbolScope GetScope(int offset);
-
- // Given a position in a document, return the offset within the
- // method that corresponds to the position.
- int GetOffset(ISymbolDocument document,
- int line,
- int column);
-
- // Given a position in a document, return an array of start/end
- // offset paris that correspond to the ranges of IL that the
- // position covers within this method. The array is an array of
- // integers and is [start,end,start,end]. The number of range
- // pairs is the length of the array / 2.
- int[] GetRanges(ISymbolDocument document,
- int line,
- int column);
-
- // Get the parameters for this method. The paraemeters are
- // returned in the order they are defined within the method's
- // signature.
- ISymbolVariable[] GetParameters();
-
- // Get the namespace that this method is defined within.
- ISymbolNamespace GetNamespace();
-
- // Get the start/end document positions for the source of this
- // method. The first array position is the start while the second
- // is the end. Returns true if positions were defined, false
- // otherwise.
- bool GetSourceStartEnd(ISymbolDocument[] docs,
- int[] lines,
- int[] columns);
- }
-
-}
diff --git a/src/mscorlib/src/System/Diagnostics/SymbolStore/ISymNamespace.cs b/src/mscorlib/src/System/Diagnostics/SymbolStore/ISymNamespace.cs
deleted file mode 100644
index 1dee13ef69..0000000000
--- a/src/mscorlib/src/System/Diagnostics/SymbolStore/ISymNamespace.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.
-
-/*============================================================
-**
-**
-**
-** Represents a namespace within a symbol reader.
-**
-**
-===========================================================*/
-namespace System.Diagnostics.SymbolStore {
-
- using System;
-
- // Interface does not need to be marked with the serializable attribute
-[System.Runtime.InteropServices.ComVisible(true)]
- public interface ISymbolNamespace
- {
- // Get the name of this namespace
- String Name { get; }
-
- // Get the children of this namespace
- ISymbolNamespace[] GetNamespaces();
-
- // Get the variables in this namespace
- ISymbolVariable[] GetVariables();
- }
-}
diff --git a/src/mscorlib/src/System/Diagnostics/SymbolStore/ISymReader.cs b/src/mscorlib/src/System/Diagnostics/SymbolStore/ISymReader.cs
deleted file mode 100644
index 8bc75e5aba..0000000000
--- a/src/mscorlib/src/System/Diagnostics/SymbolStore/ISymReader.cs
+++ /dev/null
@@ -1,68 +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.
-
-/*============================================================
-**
-**
-**
-** Represents a symbol reader for managed code. Provides access to
-** documents, methods, and variables.
-**
-**
-===========================================================*/
-namespace System.Diagnostics.SymbolStore {
- // Interface does not need to be marked with the serializable attribute
- using System;
- using System.Runtime.InteropServices;
-
-
-[System.Runtime.InteropServices.ComVisible(true)]
- public interface ISymbolReader
- {
- // Find a document. Language, vendor, and document type are
- // optional.
- ISymbolDocument GetDocument(String url,
- Guid language,
- Guid languageVendor,
- Guid documentType);
-
- // Return an array of all of the documents defined in the symbol
- // store.
- ISymbolDocument[] GetDocuments();
-
- // Return the method that was specified as the user entry point
- // for the module, if any. This would be, perhaps, the user's main
- // method rather than compiler generated stubs before main.
- SymbolToken UserEntryPoint { get; }
-
- // Get a symbol reader method given the id of a method.
- ISymbolMethod GetMethod(SymbolToken method);
-
- // Get a symbol reader method given the id of a method and an E&C
- // version number. Version numbers start a 1 and are incremented
- // each time the method is changed due to an E&C operation.
- ISymbolMethod GetMethod(SymbolToken method, int version);
-
- // Return a non-local variable given its parent and name.
- ISymbolVariable[] GetVariables(SymbolToken parent);
-
- // Return a non-local variable given its parent and name.
- ISymbolVariable[] GetGlobalVariables();
-
- // Given a position in a document, return the ISymbolMethod that
- // contains that position.
- ISymbolMethod GetMethodFromDocumentPosition(ISymbolDocument document,
- int line,
- int column);
-
- // Gets a custom attribute based upon its name. Not to be
- // confused with Metadata custom attributes, these attributes are
- // held in the symbol store.
- byte[] GetSymAttribute(SymbolToken parent, String name);
-
- // Get the namespaces defined at global scope within this symbol store.
- ISymbolNamespace[] GetNamespaces();
- }
-
-}
diff --git a/src/mscorlib/src/System/Diagnostics/SymbolStore/ISymScope.cs b/src/mscorlib/src/System/Diagnostics/SymbolStore/ISymScope.cs
deleted file mode 100644
index 859d7d42c8..0000000000
--- a/src/mscorlib/src/System/Diagnostics/SymbolStore/ISymScope.cs
+++ /dev/null
@@ -1,47 +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.
-
-/*============================================================
-**
-**
-**
-** Represents a lexical scope within a ISymbolMethod. Provides access to
-** the start and end offsets of the scope, as well as its child and
-** parent scopes. Also provides access to all the locals defined
-** within this scope.
-**
-**
-===========================================================*/
-namespace System.Diagnostics.SymbolStore {
- // Interface does not need to be marked with the serializable attribute
- using System;
- using System.Text;
- using System.Runtime.InteropServices;
-
-[System.Runtime.InteropServices.ComVisible(true)]
- public interface ISymbolScope
- {
- // Get the method that contains this scope.
- ISymbolMethod Method { get; }
-
- // Get the parent scope of this scope.
- ISymbolScope Parent { get; }
-
- // Get any child scopes of this scope.
- ISymbolScope[] GetChildren();
-
- // Get the start and end offsets for this scope.
- int StartOffset { get; }
- int EndOffset { get; }
-
- // Get the locals within this scope. They are returned in no
- // particular order. Note: if a local variable changes its address
- // within this scope then that variable will be returned multiple
- // times, each with a different offset range.
- ISymbolVariable[] GetLocals();
-
- // Get the namespaces that are being "used" within this scope.
- ISymbolNamespace[] GetNamespaces();
- }
-}
diff --git a/src/mscorlib/src/System/Diagnostics/SymbolStore/ISymVariable.cs b/src/mscorlib/src/System/Diagnostics/SymbolStore/ISymVariable.cs
deleted file mode 100644
index 857d24b2b6..0000000000
--- a/src/mscorlib/src/System/Diagnostics/SymbolStore/ISymVariable.cs
+++ /dev/null
@@ -1,41 +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.
-
-/*============================================================
-**
-**
-**
-** Represents a variable within a symbol store. This could be a
-** parameter, local variable, or some other non-local variable.
-**
-**
-===========================================================*/
-namespace System.Diagnostics.SymbolStore {
- // Interface does not need to be marked with the serializable attribute
- using System;
-
-[System.Runtime.InteropServices.ComVisible(true)]
- public interface ISymbolVariable
- {
- // Get the name of this variable.
- String Name { get; }
-
- // Get the attributes of this variable.
- Object Attributes { get; }
-
- // Get the signature of this variable.
- byte[] GetSignature();
-
- SymAddressKind AddressKind { get; }
- int AddressField1 { get; }
- int AddressField2 { get; }
- int AddressField3 { get; }
-
- // Get the start/end offsets of this variable within its
- // parent. If this is a local variable within a scope, these will
- // fall within the offsets defined for the scope.
- int StartOffset { get; }
- int EndOffset { get; }
- }
-}
diff --git a/src/mscorlib/src/System/Diagnostics/SymbolStore/ISymWriter.cs b/src/mscorlib/src/System/Diagnostics/SymbolStore/ISymWriter.cs
index a0d3640c2c..bfe9133aee 100644
--- a/src/mscorlib/src/System/Diagnostics/SymbolStore/ISymWriter.cs
+++ b/src/mscorlib/src/System/Diagnostics/SymbolStore/ISymWriter.cs
@@ -20,13 +20,8 @@ namespace System.Diagnostics.SymbolStore {
using System.Runtime.Versioning;
// Interface does not need to be marked with the serializable attribute
-[System.Runtime.InteropServices.ComVisible(true)]
- public interface ISymbolWriter
+ internal interface ISymbolWriter
{
- // Set the IMetadataEmitter that this symbol writer is associated
- // with. This must be done only once before any other ISymbolWriter
- // methods are called.
- void Initialize(IntPtr emitter, String filename, bool fFullBuild);
// Define a source document. Guid's will be provided for the
// languages, vendors, and document types that we currently know
@@ -36,11 +31,6 @@ namespace System.Diagnostics.SymbolStore {
Guid languageVendor,
Guid documentType);
- // 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.
- void SetUserEntryPoint(SymbolToken entryMethod);
-
// Open a method to emit symbol information into. The given method
// becomes the current method for calls do define sequence points,
// parameters and lexical scopes. There is an implicit lexical
@@ -88,9 +78,6 @@ namespace System.Diagnostics.SymbolStore {
// last instruction in the scope.
void CloseScope(int endOffset);
- // Define the offset range for a given lexical scope.
- void SetScopeRange(int scopeID, int startOffset, int endOffset);
-
// Define a single variable in the current lexical
// scope. startOffset and endOffset are optional. If 0, then they
// are ignored and the variable is defined over the entire
@@ -109,80 +96,17 @@ namespace System.Diagnostics.SymbolStore {
int startOffset,
int endOffset);
- // Define a single parameter in the current method. The type of
- // each parameter is taken from its position (sequence) within the
- // method's signature.
- //
- // Note: if parameters are defined in the metadata for a given
- // method, then clearly one would not have to define them again
- // with calls to this method. The symbol readers will have to be
- // smart enough to check the normal metadata for these first then
- // fall back to the symbol store.
- void DefineParameter(String name,
- ParameterAttributes attributes,
- int sequence,
- SymAddressKind addrKind,
- int addr1,
- int addr2,
- int addr3);
-
- // Define a single variable not within a method. This is used for
- // certian fields in classes, bitfields, etc.
- void DefineField(SymbolToken parent,
- String name,
- FieldAttributes attributes,
- byte[] signature,
- SymAddressKind addrKind,
- int addr1,
- int addr2,
- int addr3);
-
- // Define a single global variable.
- void DefineGlobalVariable(String name,
- FieldAttributes attributes,
- byte[] signature,
- SymAddressKind addrKind,
- int addr1,
- int addr2,
- int addr3);
-
- // Close will close the ISymbolWriter and commit the symbols
- // to the symbol store. The ISymbolWriter becomes invalid
- // after this call for further updates.
- void Close();
-
// Defines a custom attribute based upon its name. Not to be
// confused with Metadata custom attributes, these attributes are
// held in the symbol store.
void SetSymAttribute(SymbolToken parent, String name, byte[] data);
- // Opens a new namespace. Call this before defining methods or
- // variables that live within a namespace. Namespaces can be nested.
- void OpenNamespace(String name);
-
- // Close the most recently opened namespace.
- void CloseNamespace();
-
// Specifies that the given, fully qualified namespace name is
// being used within the currently open lexical scope. Closing the
// 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.
void UsingNamespace(String fullName);
-
- // Specifies the true start and end of a method within a source
- // file. Use this to specify the extent of a method independently
- // of what sequence points exist within the method.
- void SetMethodSourceRange(ISymbolDocumentWriter startDoc,
- int startLine,
- int startColumn,
- ISymbolDocumentWriter endDoc,
- int endLine,
- int endColumn);
-
- // Used to set the underlying ISymUnmanagedWriter that a
- // managed ISymbolWriter may use to emit symbols with.
- void SetUnderlyingWriter(IntPtr underlyingWriter);
}
}
diff --git a/src/mscorlib/src/System/Diagnostics/SymbolStore/SymAddressKind.cs b/src/mscorlib/src/System/Diagnostics/SymbolStore/SymAddressKind.cs
index a7f866f2ec..bb50d9841b 100644
--- a/src/mscorlib/src/System/Diagnostics/SymbolStore/SymAddressKind.cs
+++ b/src/mscorlib/src/System/Diagnostics/SymbolStore/SymAddressKind.cs
@@ -16,8 +16,7 @@ namespace System.Diagnostics.SymbolStore {
using System;
[Serializable]
-[System.Runtime.InteropServices.ComVisible(true)]
- public enum SymAddressKind
+ internal enum SymAddressKind
{
// ILOffset: addr1 = IL local var or param index.
ILOffset = 1,
diff --git a/src/mscorlib/src/System/Diagnostics/SymbolStore/SymDocumentType.cs b/src/mscorlib/src/System/Diagnostics/SymbolStore/SymDocumentType.cs
deleted file mode 100644
index f7c7fea867..0000000000
--- a/src/mscorlib/src/System/Diagnostics/SymbolStore/SymDocumentType.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.
-
-/*============================================================
-**
-**
-**
-[System.Runtime.InteropServices.ComVisible(true)]
-** A class to hold public guids for document types to be used with the
-** symbol store.
-**
-**
-===========================================================*/
-namespace System.Diagnostics.SymbolStore {
- // Only statics does not need to be marked with the serializable attribute
- using System;
-
-[System.Runtime.InteropServices.ComVisible(true)]
- public class SymDocumentType
- {
- public static readonly Guid Text = new Guid(0x5a869d0b, 0x6611, 0x11d3, 0xbd, 0x2a, 0x0, 0x0, 0xf8, 0x8, 0x49, 0xbd);
- }
-}
diff --git a/src/mscorlib/src/System/Diagnostics/SymbolStore/SymLanguageType.cs b/src/mscorlib/src/System/Diagnostics/SymbolStore/SymLanguageType.cs
deleted file mode 100644
index a67ba297af..0000000000
--- a/src/mscorlib/src/System/Diagnostics/SymbolStore/SymLanguageType.cs
+++ /dev/null
@@ -1,42 +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.
-
-/*============================================================
-**
-**
-**
-[System.Runtime.InteropServices.ComVisible(true)]
-** A class to hold public guids for languages types.
-**
-**
-===========================================================*/
-namespace System.Diagnostics.SymbolStore {
- // Only statics, does not need to be marked with the serializable attribute
- using System;
-
-[System.Runtime.InteropServices.ComVisible(true)]
- public class SymLanguageType
- {
- public static readonly Guid C = new Guid(0x63a08714, unchecked((short) 0xfc37), 0x11d2, 0x90, 0x4c, 0x0, 0xc0, 0x4f, 0xa3, 0x02, 0xa1);
- public static readonly Guid CPlusPlus = new Guid(0x3a12d0b7, unchecked((short)0xc26c), 0x11d0, 0xb4, 0x42, 0x0, 0xa0, 0x24, 0x4a, 0x1d, 0xd2);
-
- public static readonly Guid CSharp = new Guid(0x3f5162f8, unchecked((short)0x07c6), 0x11d3, 0x90, 0x53, 0x0, 0xc0, 0x4f, 0xa3, 0x02, 0xa1);
-
- public static readonly Guid Basic = new Guid(0x3a12d0b8, unchecked((short)0xc26c), 0x11d0, 0xb4, 0x42, 0x0, 0xa0, 0x24, 0x4a, 0x1d, 0xd2);
-
- public static readonly Guid Java = new Guid(0x3a12d0b4, unchecked((short)0xc26c), 0x11d0, 0xb4, 0x42, 0x0, 0xa0, 0x24, 0x4a, 0x1d, 0xd2);
-
- public static readonly Guid Cobol = new Guid(unchecked((int)0xaf046cd1), unchecked((short)0xd0e1), 0x11d2, 0x97, 0x7c, 0x0, 0xa0, 0xc9, 0xb4, 0xd5, 0xc);
-
- public static readonly Guid Pascal = new Guid(unchecked((int)0xaf046cd2), unchecked((short) 0xd0e1), 0x11d2, 0x97, 0x7c, 0x0, 0xa0, 0xc9, 0xb4, 0xd5, 0xc);
-
- public static readonly Guid ILAssembly = new Guid(unchecked((int)0xaf046cd3), unchecked((short)0xd0e1), 0x11d2, 0x97, 0x7c, 0x0, 0xa0, 0xc9, 0xb4, 0xd5, 0xc);
-
- public static readonly Guid JScript = new Guid(0x3a12d0b6, unchecked((short)0xc26c), 0x11d0, 0xb4, 0x42, 0x00, 0xa0, 0x24, 0x4a, 0x1d, 0xd2);
-
- public static readonly Guid SMC = new Guid(unchecked((int)0xd9b9f7b), 0x6611, unchecked((short)0x11d3), 0xbd, 0x2a, 0x0, 0x0, 0xf8, 0x8, 0x49, 0xbd);
-
- public static readonly Guid MCPlusPlus = new Guid(0x4b35fde8, unchecked((short)0x07c6), 0x11d3, 0x90, 0x53, 0x0, 0xc0, 0x4f, 0xa3, 0x02, 0xa1);
- }
-}
diff --git a/src/mscorlib/src/System/Diagnostics/SymbolStore/SymLanguageVendor.cs b/src/mscorlib/src/System/Diagnostics/SymbolStore/SymLanguageVendor.cs
deleted file mode 100644
index 8bef10bdad..0000000000
--- a/src/mscorlib/src/System/Diagnostics/SymbolStore/SymLanguageVendor.cs
+++ /dev/null
@@ -1,23 +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.
-
-/*============================================================
-**
-**
-**
-[System.Runtime.InteropServices.ComVisible(true)]
-** A class to hold public guids for language vendors.
-**
-**
-===========================================================*/
-namespace System.Diagnostics.SymbolStore {
- // Only statics, does not need to be marked with the serializable attribute
- using System;
-
-[System.Runtime.InteropServices.ComVisible(true)]
- public class SymLanguageVendor
- {
- public static readonly Guid Microsoft = new Guid(unchecked((int)0x994b45c4), unchecked((short) 0xe6e9), 0x11d2, 0x90, 0x3f, 0x00, 0xc0, 0x4f, 0xa3, 0x02, 0xa1);
- }
-}
diff --git a/src/mscorlib/src/System/Diagnostics/SymbolStore/Token.cs b/src/mscorlib/src/System/Diagnostics/SymbolStore/Token.cs
index a8a6675a2f..cc1e4a865f 100644
--- a/src/mscorlib/src/System/Diagnostics/SymbolStore/Token.cs
+++ b/src/mscorlib/src/System/Diagnostics/SymbolStore/Token.cs
@@ -14,8 +14,7 @@ namespace System.Diagnostics.SymbolStore {
using System;
using System.Runtime.InteropServices;
- [ComVisible(true)]
- public struct SymbolToken
+ internal struct SymbolToken
{
internal int m_token;
@@ -37,15 +36,5 @@ namespace System.Diagnostics.SymbolStore {
{
return obj.m_token == m_token;
}
-
- public static bool operator ==(SymbolToken a, SymbolToken b)
- {
- return a.Equals(b);
- }
-
- public static bool operator !=(SymbolToken a, SymbolToken b)
- {
- return !(a == b);
- }
}
}
diff --git a/src/mscorlib/src/System/Diagnostics/log.cs b/src/mscorlib/src/System/Diagnostics/log.cs
index 6916ce3a0a..d297b8fa08 100644
--- a/src/mscorlib/src/System/Diagnostics/log.cs
+++ b/src/mscorlib/src/System/Diagnostics/log.cs
@@ -5,7 +5,6 @@
namespace System.Diagnostics {
using System.Runtime.Remoting;
using System;
- using System.Security.Permissions;
using System.IO;
using System.Collections;
using System.Runtime.CompilerServices;
@@ -13,18 +12,6 @@ namespace System.Diagnostics {
using System.Runtime.Versioning;
using System.Diagnostics.Contracts;
using System.Diagnostics.CodeAnalysis;
-
- // LogMessageEventHandlers are triggered when a message is generated which is
- // "on" per its switch.
- //
- // By default, the debugger (if attached) is the only event handler.
- // There is also a "built-in" console device which can be enabled
- // programatically, by registry (specifics....) or environment
- // variables.
- [Serializable]
- internal delegate void LogMessageEventHandler(LoggingLevels level, LogSwitch category,
- String message,
- StackTrace location);
// LogSwitchLevelHandlers are triggered when the level of a LogSwitch is modified
@@ -49,7 +36,6 @@ namespace System.Diagnostics {
// desired events are actually reported to the debugger.
internal static Hashtable m_Hashtable;
private static volatile bool m_fConsoleDeviceEnabled;
- private static LogMessageEventHandler _LogMessageEventHandler;
private static volatile LogSwitchLevelHandler _LogSwitchLevelHandler;
private static Object locker;
@@ -72,35 +58,6 @@ namespace System.Diagnostics {
GlobalSwitch.MinimumLevel = LoggingLevels.ErrorLevel;
}
- public static void AddOnLogMessage(LogMessageEventHandler handler)
- {
- lock (locker)
- _LogMessageEventHandler =
- (LogMessageEventHandler) MulticastDelegate.Combine(_LogMessageEventHandler, handler);
- }
-
- public static void RemoveOnLogMessage(LogMessageEventHandler handler)
- {
-
- lock (locker)
- _LogMessageEventHandler =
- (LogMessageEventHandler) MulticastDelegate.Remove(_LogMessageEventHandler, handler);
- }
-
- public static void AddOnLogSwitchLevel(LogSwitchLevelHandler handler)
- {
- lock (locker)
- _LogSwitchLevelHandler =
- (LogSwitchLevelHandler) MulticastDelegate.Combine(_LogSwitchLevelHandler, handler);
- }
-
- public static void RemoveOnLogSwitchLevel(LogSwitchLevelHandler handler)
- {
- lock (locker)
- _LogSwitchLevelHandler =
- (LogSwitchLevelHandler) MulticastDelegate.Remove(_LogSwitchLevelHandler, handler);
- }
-
internal static void InvokeLogSwitchLevelHandlers (LogSwitch ls, LoggingLevels newLevel)
{
LogSwitchLevelHandler handler = _LogSwitchLevelHandler;
@@ -119,15 +76,6 @@ namespace System.Diagnostics {
get { return m_fConsoleDeviceEnabled; }
set { m_fConsoleDeviceEnabled = value; }
}
-
- // Generates a log message. If its switch (or a parent switch) allows the
- // level for the message, it is "broadcast" to all of the log
- // devices.
- //
- public static void LogMessage(LoggingLevels level, String message)
- {
- LogMessage (level, GlobalSwitch, message);
- }
// Generates a log message. If its switch (or a parent switch) allows the
// level for the message, it is "broadcast" to all of the log
@@ -168,74 +116,10 @@ namespace System.Diagnostics {
LogMessage (LoggingLevels.TraceLevel0, logswitch, message);
}
- public static void Trace(String switchname, String message)
- {
- LogSwitch ls;
- ls = LogSwitch.GetSwitch (switchname);
- LogMessage (LoggingLevels.TraceLevel0, ls, message);
- }
-
public static void Trace(String message)
{
LogMessage (LoggingLevels.TraceLevel0, GlobalSwitch, message);
}
-
- public static void Status(LogSwitch logswitch, String message)
- {
- LogMessage (LoggingLevels.StatusLevel0, logswitch, message);
- }
-
- public static void Status(String switchname, String message)
- {
- LogSwitch ls;
- ls = LogSwitch.GetSwitch (switchname);
- LogMessage (LoggingLevels.StatusLevel0, ls, message);
- }
-
- public static void Status(String message)
- {
- LogMessage (LoggingLevels.StatusLevel0, GlobalSwitch, message);
- }
-
- public static void Warning(LogSwitch logswitch, String message)
- {
- LogMessage (LoggingLevels.WarningLevel, logswitch, message);
- }
-
- public static void Warning(String switchname, String message)
- {
- LogSwitch ls;
- ls = LogSwitch.GetSwitch (switchname);
- LogMessage (LoggingLevels.WarningLevel, ls, message);
- }
-
- public static void Warning(String message)
- {
- LogMessage (LoggingLevels.WarningLevel, GlobalSwitch, message);
- }
-
- public static void Error(LogSwitch logswitch, String message)
- {
- LogMessage (LoggingLevels.ErrorLevel, logswitch, message);
- }
-
- public static void Error(String switchname, String message)
- {
- LogSwitch ls;
- ls = LogSwitch.GetSwitch (switchname);
- LogMessage (LoggingLevels.ErrorLevel, ls, message);
-
- }
-
- public static void Error(String message)
- {
- LogMessage (LoggingLevels.ErrorLevel, GlobalSwitch, message);
- }
-
- public static void Panic(String message)
- {
- LogMessage (LoggingLevels.PanicLevel, GlobalSwitch, message);
- }
// Native method to inform the EE about the creation of a new LogSwitch
diff --git a/src/mscorlib/src/System/DivideByZeroException.cs b/src/mscorlib/src/System/DivideByZeroException.cs
index b975e81df6..4abd43adaf 100644
--- a/src/mscorlib/src/System/DivideByZeroException.cs
+++ b/src/mscorlib/src/System/DivideByZeroException.cs
@@ -11,29 +11,31 @@
**
=============================================================================*/
-namespace System {
-
- using System;
- using System.Runtime.Serialization;
-[System.Runtime.InteropServices.ComVisible(true)]
+using System.Runtime.Serialization;
+
+namespace System
+{
[Serializable]
- public class DivideByZeroException : ArithmeticException {
- public DivideByZeroException()
- : base(Environment.GetResourceString("Arg_DivideByZero")) {
- SetErrorCode(__HResults.COR_E_DIVIDEBYZERO);
- }
-
- public DivideByZeroException(String message)
- : base(message) {
- SetErrorCode(__HResults.COR_E_DIVIDEBYZERO);
+ public class DivideByZeroException : ArithmeticException
+ {
+ public DivideByZeroException()
+ : base(SR.Arg_DivideByZero)
+ {
+ HResult = __HResults.COR_E_DIVIDEBYZERO;
}
-
- public DivideByZeroException(String message, Exception innerException)
- : base(message, innerException) {
- SetErrorCode(__HResults.COR_E_DIVIDEBYZERO);
+
+ public DivideByZeroException(String message)
+ : base(message)
+ {
+ HResult = __HResults.COR_E_DIVIDEBYZERO;
}
- protected DivideByZeroException(SerializationInfo info, StreamingContext context) : base(info, context) {
+ public DivideByZeroException(String message, Exception innerException)
+ : base(message, innerException)
+ {
+ HResult = __HResults.COR_E_DIVIDEBYZERO;
}
+
+ protected DivideByZeroException(SerializationInfo info, StreamingContext context) : base(info, context) { }
}
}
diff --git a/src/mscorlib/src/System/DllNotFoundException.cs b/src/mscorlib/src/System/DllNotFoundException.cs
index f860904f3f..43bb57fec2 100644
--- a/src/mscorlib/src/System/DllNotFoundException.cs
+++ b/src/mscorlib/src/System/DllNotFoundException.cs
@@ -16,7 +16,6 @@ namespace System {
using System;
using System.Runtime.Serialization;
- [System.Runtime.InteropServices.ComVisible(true)]
[Serializable]
public class DllNotFoundException : TypeLoadException {
public DllNotFoundException()
diff --git a/src/mscorlib/src/System/Double.cs b/src/mscorlib/src/System/Double.cs
index ce146a1227..1e4e477366 100644
--- a/src/mscorlib/src/System/Double.cs
+++ b/src/mscorlib/src/System/Double.cs
@@ -22,7 +22,6 @@ namespace System {
[Serializable]
[StructLayout(LayoutKind.Sequential)]
-[System.Runtime.InteropServices.ComVisible(true)]
public struct Double : IComparable, IFormattable, IConvertible
, IComparable<Double>, IEquatable<Double>
{
@@ -83,7 +82,6 @@ namespace System {
}
[Pure]
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
[System.Runtime.Versioning.NonVersionable]
public unsafe static bool IsNaN(double d)
{
diff --git a/src/mscorlib/src/System/DuplicateWaitObjectException.cs b/src/mscorlib/src/System/DuplicateWaitObjectException.cs
index d358d964c2..da29e2ad76 100644
--- a/src/mscorlib/src/System/DuplicateWaitObjectException.cs
+++ b/src/mscorlib/src/System/DuplicateWaitObjectException.cs
@@ -11,53 +11,55 @@
**
=============================================================================*/
-namespace System {
-
- using System;
- using System.Runtime.Remoting;
- using System.Runtime.Serialization;
+using System.Runtime.Serialization;
+namespace System
+{
// The DuplicateWaitObjectException is thrown when an object
// appears more than once in the list of objects to WaitAll or WaitAny.
//
- [System.Runtime.InteropServices.ComVisible(true)]
[Serializable]
- public class DuplicateWaitObjectException : ArgumentException {
+ public class DuplicateWaitObjectException : ArgumentException
+ {
+ private static volatile String s_duplicateWaitObjectMessage = null;
- private static volatile String _duplicateWaitObjectMessage = null;
-
- private static String DuplicateWaitObjectMessage {
- get {
- if (_duplicateWaitObjectMessage == null)
- _duplicateWaitObjectMessage = Environment.GetResourceString("Arg_DuplicateWaitObjectException");
- return _duplicateWaitObjectMessage;
+ private static String DuplicateWaitObjectMessage
+ {
+ get
+ {
+ if (s_duplicateWaitObjectMessage == null)
+ s_duplicateWaitObjectMessage = SR.Arg_DuplicateWaitObjectException;
+ return s_duplicateWaitObjectMessage;
}
}
// Creates a new DuplicateWaitObjectException with its message
// string set to a default message.
- public DuplicateWaitObjectException()
- : base(DuplicateWaitObjectMessage) {
- SetErrorCode(__HResults.COR_E_DUPLICATEWAITOBJECT);
+ public DuplicateWaitObjectException()
+ : base(DuplicateWaitObjectMessage)
+ {
+ HResult = __HResults.COR_E_DUPLICATEWAITOBJECT;
}
- public DuplicateWaitObjectException(String parameterName)
- : base(DuplicateWaitObjectMessage, parameterName) {
- SetErrorCode(__HResults.COR_E_DUPLICATEWAITOBJECT);
+ public DuplicateWaitObjectException(String parameterName)
+ : base(DuplicateWaitObjectMessage, parameterName)
+ {
+ HResult = __HResults.COR_E_DUPLICATEWAITOBJECT;
}
- public DuplicateWaitObjectException(String parameterName, String message)
- : base(message, parameterName) {
- SetErrorCode(__HResults.COR_E_DUPLICATEWAITOBJECT);
+ public DuplicateWaitObjectException(String parameterName, String message)
+ : base(message, parameterName)
+ {
+ HResult = __HResults.COR_E_DUPLICATEWAITOBJECT;
}
- public DuplicateWaitObjectException(String message, Exception innerException)
- : base(message, innerException) {
- SetErrorCode(__HResults.COR_E_DUPLICATEWAITOBJECT);
+ public DuplicateWaitObjectException(String message, Exception innerException)
+ : base(message, innerException)
+ {
+ HResult = __HResults.COR_E_DUPLICATEWAITOBJECT;
}
// This constructor is required for serialization
- protected DuplicateWaitObjectException(SerializationInfo info, StreamingContext context) : base (info, context) {
- }
+ protected DuplicateWaitObjectException(SerializationInfo info, StreamingContext context) : base(info, context) { }
}
}
diff --git a/src/mscorlib/src/System/EntryPointNotFoundException.cs b/src/mscorlib/src/System/EntryPointNotFoundException.cs
index a65d80058e..835d33413d 100644
--- a/src/mscorlib/src/System/EntryPointNotFoundException.cs
+++ b/src/mscorlib/src/System/EntryPointNotFoundException.cs
@@ -11,32 +11,32 @@
**
=============================================================================*/
-namespace System {
-
- using System;
- using System.Runtime.Serialization;
- [System.Runtime.InteropServices.ComVisible(true)]
+using System;
+using System.Runtime.Serialization;
+
+namespace System
+{
[Serializable]
- public class EntryPointNotFoundException : TypeLoadException {
- public EntryPointNotFoundException()
- : base(Environment.GetResourceString("Arg_EntryPointNotFoundException")) {
- SetErrorCode(__HResults.COR_E_ENTRYPOINTNOTFOUND);
- }
-
- public EntryPointNotFoundException(String message)
- : base(message) {
- SetErrorCode(__HResults.COR_E_ENTRYPOINTNOTFOUND);
+ public class EntryPointNotFoundException : TypeLoadException
+ {
+ public EntryPointNotFoundException()
+ : base(SR.Arg_EntryPointNotFoundException)
+ {
+ HResult = __HResults.COR_E_ENTRYPOINTNOTFOUND;
}
-
- public EntryPointNotFoundException(String message, Exception inner)
- : base(message, inner) {
- SetErrorCode(__HResults.COR_E_ENTRYPOINTNOTFOUND);
+
+ public EntryPointNotFoundException(String message)
+ : base(message)
+ {
+ HResult = __HResults.COR_E_ENTRYPOINTNOTFOUND;
}
- protected EntryPointNotFoundException(SerializationInfo info, StreamingContext context) : base(info, context) {
+ public EntryPointNotFoundException(String message, Exception inner)
+ : base(message, inner)
+ {
+ HResult = __HResults.COR_E_ENTRYPOINTNOTFOUND;
}
-
-
- }
+ protected EntryPointNotFoundException(SerializationInfo info, StreamingContext context) : base(info, context) { }
+ }
}
diff --git a/src/mscorlib/src/System/Enum.cs b/src/mscorlib/src/System/Enum.cs
index d39e005d48..97cfdf1b23 100644
--- a/src/mscorlib/src/System/Enum.cs
+++ b/src/mscorlib/src/System/Enum.cs
@@ -15,7 +15,6 @@ using System.Diagnostics.Contracts;
namespace System
{
[Serializable]
- [System.Runtime.InteropServices.ComVisible(true)]
public abstract class Enum : ValueType, IComparable, IFormattable, IConvertible
{
#region Private Constants
@@ -70,7 +69,6 @@ namespace System
case CorElementType.U8:
return (*(ulong*)pValue).ToString("X16", null);
default:
- Debug.Assert(false, "Invalid Object type in Format");
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_UnknownEnumType"));
}
}
@@ -105,7 +103,6 @@ namespace System
return ((UInt64)(Int64)value).ToString("X16", null);
// All unsigned types will be directly cast
default:
- Debug.Assert(false, "Invalid Object type in Format");
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_UnknownEnumType"));
}
}
@@ -159,7 +156,7 @@ namespace System
Debug.Assert(names.Length == values.Length);
int index = values.Length - 1;
- StringBuilder retval = new StringBuilder();
+ StringBuilder sb = StringBuilderCache.Acquire();
bool firstTime = true;
ulong saveResult = result;
@@ -175,31 +172,40 @@ namespace System
{
result -= values[index];
if (!firstTime)
- retval.Insert(0, enumSeparatorString);
+ sb.Insert(0, enumSeparatorString);
- retval.Insert(0, names[index]);
+ sb.Insert(0, names[index]);
firstTime = false;
}
index--;
}
- // We were unable to represent this number as a bitwise or of valid flags
+ string returnString;
if (result != 0)
- return null; // return null so the caller knows to .ToString() the input
-
- // For the case when we have zero
- if (saveResult == 0)
{
+ // We were unable to represent this number as a bitwise or of valid flags
+ returnString = null; // return null so the caller knows to .ToString() the input
+ }
+ else if (saveResult == 0)
+ {
+ // For the cases when we have zero
if (values.Length > 0 && values[0] == 0)
- return names[0]; // Zero was one of the enum values.
+ {
+ returnString = names[0]; // Zero was one of the enum values.
+ }
else
- return "0";
+ {
+ returnString = "0";
+ }
}
else
{
- return retval.ToString(); // Return the string representation
+ returnString = sb.ToString(); // Return the string representation
}
+
+ StringBuilderCache.Release(sb);
+ return returnString;
}
internal static ulong ToUInt64(Object value)
@@ -244,7 +250,6 @@ namespace System
break;
// All unsigned types will be directly cast
default:
- Debug.Assert(false, "Invalid Object type in ToUInt64");
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_UnknownEnumType"));
}
@@ -361,13 +366,11 @@ namespace System
return retValue;
}
- [System.Runtime.InteropServices.ComVisible(true)]
public static Object Parse(Type enumType, String value)
{
return Parse(enumType, value, false);
}
- [System.Runtime.InteropServices.ComVisible(true)]
public static Object Parse(Type enumType, String value, bool ignoreCase)
{
EnumResult parseResult = new EnumResult() { canThrow = true };
@@ -525,7 +528,6 @@ namespace System
}
}
- [System.Runtime.InteropServices.ComVisible(true)]
public static Type GetUnderlyingType(Type enumType)
{
if (enumType == null)
@@ -536,7 +538,6 @@ namespace System
return enumType.GetEnumUnderlyingType();
}
- [System.Runtime.InteropServices.ComVisible(true)]
public static Array GetValues(Type enumType)
{
if (enumType == null)
@@ -553,7 +554,6 @@ namespace System
return GetCachedValuesAndNames(enumType, false).Values;
}
- [System.Runtime.InteropServices.ComVisible(true)]
public static String GetName(Type enumType, Object value)
{
if (enumType == null)
@@ -563,7 +563,6 @@ namespace System
return enumType.GetEnumName(value);
}
- [System.Runtime.InteropServices.ComVisible(true)]
public static String[] GetNames(Type enumType)
{
if (enumType == null)
@@ -580,7 +579,6 @@ namespace System
return GetCachedValuesAndNames(enumType, true).Names;
}
- [System.Runtime.InteropServices.ComVisible(true)]
public static Object ToObject(Type enumType, Object value)
{
if (value == null)
@@ -629,7 +627,6 @@ namespace System
}
[Pure]
- [System.Runtime.InteropServices.ComVisible(true)]
public static bool IsDefined(Type enumType, Object value)
{
if (enumType == null)
@@ -639,7 +636,6 @@ namespace System
return enumType.IsEnumDefined(value);
}
- [System.Runtime.InteropServices.ComVisible(true)]
public static String Format(Type enumType, Object value, String format)
{
if (enumType == null)
@@ -899,8 +895,8 @@ namespace System
public int CompareTo(Object target)
{
const int retIncompatibleMethodTables = 2; // indicates that the method tables did not match
- const int retInvalidEnumType = 3; // indicates that the enum was of an unknown/unsupported unerlying type
-
+ const int retInvalidEnumType = 3; // indicates that the enum was of an unknown/unsupported underlying type
+
if (this == null)
throw new NullReferenceException();
Contract.EndContractBlock();
@@ -978,61 +974,31 @@ namespace System
#region IConvertable
public TypeCode GetTypeCode()
{
- Type enumType = this.GetType();
- Type underlyingType = GetUnderlyingType(enumType);
-
- if (underlyingType == typeof(Int32))
- {
- return TypeCode.Int32;
- }
-
- if (underlyingType == typeof(sbyte))
- {
- return TypeCode.SByte;
- }
-
- if (underlyingType == typeof(Int16))
- {
- return TypeCode.Int16;
- }
-
- if (underlyingType == typeof(Int64))
+ switch (InternalGetCorElementType())
{
- return TypeCode.Int64;
- }
-
- if (underlyingType == typeof(UInt32))
- {
- return TypeCode.UInt32;
- }
-
- if (underlyingType == typeof(byte))
- {
- return TypeCode.Byte;
- }
-
- if (underlyingType == typeof(UInt16))
- {
- return TypeCode.UInt16;
- }
-
- if (underlyingType == typeof(UInt64))
- {
- return TypeCode.UInt64;
- }
-
- if (underlyingType == typeof(Boolean))
- {
- return TypeCode.Boolean;
- }
-
- if (underlyingType == typeof(Char))
- {
- return TypeCode.Char;
+ case CorElementType.I1:
+ return TypeCode.SByte;
+ case CorElementType.U1:
+ return TypeCode.Byte;
+ case CorElementType.Boolean:
+ return TypeCode.Boolean;
+ case CorElementType.I2:
+ return TypeCode.Int16;
+ case CorElementType.U2:
+ return TypeCode.UInt16;
+ case CorElementType.Char:
+ return TypeCode.Char;
+ case CorElementType.I4:
+ return TypeCode.Int32;
+ case CorElementType.U4:
+ return TypeCode.UInt32;
+ case CorElementType.I8:
+ return TypeCode.Int64;
+ case CorElementType.U8:
+ return TypeCode.UInt64;
+ default:
+ throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_UnknownEnumType"));
}
-
- Debug.Assert(false, "Unknown underlying type.");
- throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_UnknownEnumType"));
}
/// <internalonly/>
@@ -1128,7 +1094,6 @@ namespace System
#region ToObject
[CLSCompliant(false)]
- [System.Runtime.InteropServices.ComVisible(true)]
public static Object ToObject(Type enumType, sbyte value)
{
if (enumType == null)
@@ -1142,7 +1107,6 @@ namespace System
return InternalBoxEnum(rtType, value);
}
- [System.Runtime.InteropServices.ComVisible(true)]
public static Object ToObject(Type enumType, short value)
{
if (enumType == null)
@@ -1156,7 +1120,6 @@ namespace System
return InternalBoxEnum(rtType, value);
}
- [System.Runtime.InteropServices.ComVisible(true)]
public static Object ToObject(Type enumType, int value)
{
if (enumType == null)
@@ -1170,7 +1133,6 @@ namespace System
return InternalBoxEnum(rtType, value);
}
- [System.Runtime.InteropServices.ComVisible(true)]
public static Object ToObject(Type enumType, byte value)
{
if (enumType == null)
@@ -1185,7 +1147,6 @@ namespace System
}
[CLSCompliant(false)]
- [System.Runtime.InteropServices.ComVisible(true)]
public static Object ToObject(Type enumType, ushort value)
{
if (enumType == null)
@@ -1200,7 +1161,6 @@ namespace System
}
[CLSCompliant(false)]
- [System.Runtime.InteropServices.ComVisible(true)]
public static Object ToObject(Type enumType, uint value)
{
if (enumType == null)
@@ -1214,7 +1174,6 @@ namespace System
return InternalBoxEnum(rtType, value);
}
- [System.Runtime.InteropServices.ComVisible(true)]
public static Object ToObject(Type enumType, long value)
{
if (enumType == null)
@@ -1229,7 +1188,6 @@ namespace System
}
[CLSCompliant(false)]
- [System.Runtime.InteropServices.ComVisible(true)]
public static Object ToObject(Type enumType, ulong value)
{
if (enumType == null)
diff --git a/src/mscorlib/src/System/Environment.cs b/src/mscorlib/src/System/Environment.cs
index 835219a01c..8fa4ce4ff5 100644
--- a/src/mscorlib/src/System/Environment.cs
+++ b/src/mscorlib/src/System/Environment.cs
@@ -18,7 +18,6 @@ namespace System {
using System.Globalization;
using System.Collections;
using System.Collections.Generic;
- using System.Security.Permissions;
using System.Text;
using System.Configuration.Assemblies;
using System.Runtime.InteropServices;
@@ -31,7 +30,6 @@ namespace System {
using System.Runtime.Versioning;
using System.Diagnostics.Contracts;
- [ComVisible(true)]
public enum EnvironmentVariableTarget
{
Process = 0,
@@ -39,7 +37,6 @@ namespace System {
Machine = 2,
}
- [ComVisible(true)]
public static partial class Environment
{
// Assume the following constants include the terminating '\0' - use <, not <=
@@ -72,23 +69,7 @@ namespace System {
// Is this thread currently doing infinite resource lookups?
private int infinitelyRecursingCount;
-
- // Data representing one individual resource lookup on a thread.
- internal class GetResourceStringUserData
- {
- public ResourceHelper m_resourceHelper;
- public String m_key;
- public String m_retVal;
- public bool m_lockWasTaken;
-
- public GetResourceStringUserData(ResourceHelper resourceHelper, String key)
- {
- m_resourceHelper = resourceHelper;
- m_key = key;
- }
- }
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
internal String GetResourceString(String key) {
if (key == null || key.Length == 0) {
Debug.Assert(false, "Environment::GetResourceString with null or empty key. Bug in caller, or weird recursive loading problem?");
@@ -114,111 +95,85 @@ namespace System {
// returning, we're going into an infinite loop and we should
// return a bogus string.
- GetResourceStringUserData userData = new GetResourceStringUserData(this, key);
-
- RuntimeHelpers.TryCode tryCode = new RuntimeHelpers.TryCode(GetResourceStringCode);
- RuntimeHelpers.CleanupCode cleanupCode = new RuntimeHelpers.CleanupCode(GetResourceStringBackoutCode);
-
- RuntimeHelpers.ExecuteCodeWithGuaranteedCleanup(tryCode, cleanupCode, userData);
- return userData.m_retVal;
- }
-
- private void GetResourceStringCode(Object userDataIn)
- {
- GetResourceStringUserData userData = (GetResourceStringUserData) userDataIn;
- ResourceHelper rh = userData.m_resourceHelper;
- String key = userData.m_key;
-
- Monitor.Enter(rh, ref userData.m_lockWasTaken);
-
- // Are we recursively looking up the same resource? Note - our backout code will set
- // the ResourceHelper's currentlyLoading stack to null if an exception occurs.
- if (rh.currentlyLoading != null && rh.currentlyLoading.Count > 0 && rh.currentlyLoading.LastIndexOf(key) != -1) {
- // We can start infinitely recursing for one resource lookup,
- // then during our failure reporting, start infinitely recursing again.
- // avoid that.
- if (rh.infinitelyRecursingCount > 0) {
- userData.m_retVal = "[Resource lookup failed - infinite recursion or critical failure detected.]";
- return;
- }
- rh.infinitelyRecursingCount++;
+ bool lockTaken = false;
+ try
+ {
+ Monitor.Enter(this, ref lockTaken);
- // Note: our infrastructure for reporting this exception will again cause resource lookup.
- // This is the most direct way of dealing with that problem.
- String message = "Infinite recursion during resource lookup within "+System.CoreLib.Name+". This may be a bug in "+System.CoreLib.Name+", or potentially in certain extensibility points such as assembly resolve events or CultureInfo names. Resource name: " + key;
- Assert.Fail("[Recursive resource lookup bug]", message, Assert.COR_E_FAILFAST, System.Diagnostics.StackTrace.TraceFormat.NoResourceLookup);
- Environment.FailFast(message);
- }
- if (rh.currentlyLoading == null)
- rh.currentlyLoading = new List<string>();
+ // Are we recursively looking up the same resource? Note - our backout code will set
+ // the ResourceHelper's currentlyLoading stack to null if an exception occurs.
+ if (currentlyLoading != null && currentlyLoading.Count > 0 && currentlyLoading.LastIndexOf(key) != -1)
+ {
+ // We can start infinitely recursing for one resource lookup,
+ // then during our failure reporting, start infinitely recursing again.
+ // avoid that.
+ if (infinitelyRecursingCount > 0)
+ {
+ return "[Resource lookup failed - infinite recursion or critical failure detected.]";
+ }
+ infinitelyRecursingCount++;
- // Call class constructors preemptively, so that we cannot get into an infinite
- // loop constructing a TypeInitializationException. If this were omitted,
- // we could get the Infinite recursion assert above by failing type initialization
- // between the Push and Pop calls below.
-
- if (!rh.resourceManagerInited)
- {
- // process-critical code here. No ThreadAbortExceptions
- // can be thrown here. Other exceptions percolate as normal.
- RuntimeHelpers.PrepareConstrainedRegions();
- try {
+ // Note: our infrastructure for reporting this exception will again cause resource lookup.
+ // This is the most direct way of dealing with that problem.
+ string message = $"Infinite recursion during resource lookup within {System.CoreLib.Name}. This may be a bug in {System.CoreLib.Name}, or potentially in certain extensibility points such as assembly resolve events or CultureInfo names. Resource name: {key}";
+ Assert.Fail("[Recursive resource lookup bug]", message, Assert.COR_E_FAILFAST, System.Diagnostics.StackTrace.TraceFormat.NoResourceLookup);
+ Environment.FailFast(message);
}
- finally {
+ if (currentlyLoading == null)
+ currentlyLoading = new List<string>();
+
+ // Call class constructors preemptively, so that we cannot get into an infinite
+ // loop constructing a TypeInitializationException. If this were omitted,
+ // we could get the Infinite recursion assert above by failing type initialization
+ // between the Push and Pop calls below.
+ if (!resourceManagerInited)
+ {
RuntimeHelpers.RunClassConstructor(typeof(ResourceManager).TypeHandle);
RuntimeHelpers.RunClassConstructor(typeof(ResourceReader).TypeHandle);
RuntimeHelpers.RunClassConstructor(typeof(RuntimeResourceSet).TypeHandle);
RuntimeHelpers.RunClassConstructor(typeof(BinaryReader).TypeHandle);
- rh.resourceManagerInited = true;
+ resourceManagerInited = true;
}
-
- }
-
- rh.currentlyLoading.Add(key); // Push
-
- if (rh.SystemResMgr == null) {
- rh.SystemResMgr = new ResourceManager(m_name, typeof(Object).Assembly);
- }
- String s = rh.SystemResMgr.GetString(key, null);
- rh.currentlyLoading.RemoveAt(rh.currentlyLoading.Count - 1); // Pop
- 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+"\"");
+ currentlyLoading.Add(key); // Push
- userData.m_retVal = s;
- }
-
- [PrePrepareMethod]
- private void GetResourceStringBackoutCode(Object userDataIn, bool exceptionThrown)
- {
- GetResourceStringUserData userData = (GetResourceStringUserData) userDataIn;
- ResourceHelper rh = userData.m_resourceHelper;
+ if (SystemResMgr == null)
+ {
+ SystemResMgr = new ResourceManager(m_name, typeof(Object).Assembly);
+ }
+ string s = SystemResMgr.GetString(key, null);
+ currentlyLoading.RemoveAt(currentlyLoading.Count - 1); // Pop
- if (exceptionThrown)
+ 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 + "\"");
+ return s;
+ }
+ catch
{
- if (userData.m_lockWasTaken)
+ if (lockTaken)
{
// Backout code - throw away potentially corrupt state
- rh.SystemResMgr = null;
- rh.currentlyLoading = null;
+ SystemResMgr = null;
+ currentlyLoading = null;
}
+ throw;
}
- // Release the lock, if we took it.
- if (userData.m_lockWasTaken)
+ finally
{
- Monitor.Exit(rh);
+ if (lockTaken)
+ {
+ Monitor.Exit(this);
+ }
}
}
-
}
- private static volatile ResourceHelper m_resHelper; // Doesn't need to be initialized as they're zero-init.
+ private static volatile ResourceHelper m_resHelper; // Doesn't need to be initialized as they're zero-init.
private const int MaxMachineNameLength = 256;
// Private object for locking instead of locking on a public type for SQL reliability work.
private static Object s_InternalSyncObject;
private static Object InternalSyncObject {
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
get {
if (s_InternalSyncObject == null) {
Object o = new Object();
@@ -266,9 +221,6 @@ namespace System {
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public static extern void FailFast(String message);
- [MethodImplAttribute(MethodImplOptions.InternalCall)]
- internal static extern void FailFast(String message, uint exitCode);
-
// This overload of FailFast will allow you to specify the exception object
// whose bucket details *could* be used when undergoing the failfast process.
// To be specific:
@@ -292,7 +244,7 @@ namespace System {
**Arguments: The current directory to which to switch to the setter.
**Exceptions:
==============================================================================*/
- public static String CurrentDirectory
+ internal static String CurrentDirectory
{
get{
return Directory.GetCurrentDirectory();
@@ -304,7 +256,7 @@ namespace System {
}
// Returns the system directory (ie, C:\WinNT\System32).
- public static String SystemDirectory {
+ internal static String SystemDirectory {
get {
StringBuilder sb = new StringBuilder(Path.MaxPath);
int r = Win32Native.GetSystemDirectory(sb, Path.MaxPath);
@@ -316,20 +268,6 @@ namespace System {
}
}
- // Returns the windows directory (ie, C:\WinNT).
- // Used by NLS+ custom culures only at the moment.
- internal static String InternalWindowsDirectory {
- get {
- StringBuilder sb = new StringBuilder(Path.MaxPath);
- int r = Win32Native.GetWindowsDirectory(sb, Path.MaxPath);
- Debug.Assert(r < Path.MaxPath, "r < Path.MaxPath");
- if (r==0) __Error.WinIOError();
- String path = sb.ToString();
-
- return path;
- }
- }
-
public static String ExpandEnvironmentVariables(String name)
{
if (name == null)
@@ -421,15 +359,6 @@ namespace System {
}
}
- public static int SystemPageSize {
- get {
- (new EnvironmentPermission(PermissionState.Unrestricted)).Demand();
- Win32Native.SYSTEM_INFO info = new Win32Native.SYSTEM_INFO();
- Win32Native.GetSystemInfo(ref info);
- return info.dwPageSize;
- }
- }
-
/*==============================GetCommandLineArgs==============================
**Action: Gets the command line and splits it appropriately to deal with whitespace,
** quotes, and escape characters.
@@ -439,7 +368,6 @@ namespace System {
==============================================================================*/
public static String[] GetCommandLineArgs()
{
- new EnvironmentPermission(EnvironmentPermissionAccess.Read, "Path").Demand();
/*
* There are multiple entry points to a hosted app.
* The host could use ::ExecuteAssembly() or ::CreateDelegate option
@@ -515,38 +443,6 @@ namespace System {
return block;
}
- /*===============================GetLogicalDrives===============================
- **Action: Retrieves the names of the logical drives on this machine in the form "C:\".
- **Arguments: None.
- **Exceptions: IOException.
- **Permissions: SystemInfo Permission.
- ==============================================================================*/
- public static String[] GetLogicalDrives() {
- new EnvironmentPermission(PermissionState.Unrestricted).Demand();
-
- int drives = Win32Native.GetLogicalDrives();
- if (drives==0)
- __Error.WinIOError();
- uint d = (uint)drives;
- int count = 0;
- while (d != 0) {
- if (((int)d & 1) != 0) count++;
- d >>= 1;
- }
- String[] result = new String[count];
- char[] root = new char[] {'A', ':', '\\'};
- d = (uint)drives;
- count = 0;
- while (d != 0) {
- if (((int)d & 1) != 0) {
- result[count++] = new String(root);
- }
- d >>= 1;
- root[0]++;
- }
- return result;
- }
-
/*===================================NewLine====================================
**Action: A property which returns the appropriate newline string for the given
** platform.
@@ -583,31 +479,13 @@ namespace System {
}
}
-
- /*==================================WorkingSet==================================
- **Action:
- **Returns:
- **Arguments:
- **Exceptions:
- ==============================================================================*/
- [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode), SuppressUnmanagedCodeSecurity]
- private static extern long GetWorkingSet();
-
- public static long WorkingSet {
- get {
- new EnvironmentPermission(PermissionState.Unrestricted).Demand();
- return GetWorkingSet();
- }
- }
-
-
/*==================================OSVersion===================================
**Action:
**Returns:
**Arguments:
**Exceptions:
==============================================================================*/
- public static OperatingSystem OSVersion {
+ internal static OperatingSystem OSVersion {
get {
Contract.Ensures(Contract.Result<OperatingSystem>() != null);
@@ -636,7 +514,6 @@ namespace System {
}
}
-#if FEATURE_CORESYSTEM
internal static bool IsWindows8OrAbove {
get {
@@ -652,47 +529,6 @@ namespace System {
}
#endif // FEATURE_COMINTEROP
-#else // FEATURE_CORESYSTEM
-
- private static volatile bool s_IsWindows8OrAbove;
- private static volatile bool s_CheckedOSWin8OrAbove;
-
- // Windows 8 version is 6.2
- internal static bool IsWindows8OrAbove {
- get {
- if (!s_CheckedOSWin8OrAbove) {
- OperatingSystem OS = Environment.OSVersion;
- s_IsWindows8OrAbove = (OS.Platform == PlatformID.Win32NT &&
- ((OS.Version.Major == 6 && OS.Version.Minor >= 2) || (OS.Version.Major > 6)));
- s_CheckedOSWin8OrAbove = true;
- }
- return s_IsWindows8OrAbove;
- }
- }
-
-#if FEATURE_COMINTEROP
- private static volatile bool s_WinRTSupported;
- private static volatile bool s_CheckedWinRT;
-
- // Does the current version of Windows have Windows Runtime suppport?
- internal static bool IsWinRTSupported {
- get {
- if (!s_CheckedWinRT) {
- s_WinRTSupported = WinRTSupported();
- s_CheckedWinRT = true;
- }
-
- return s_WinRTSupported;
- }
- }
-
- [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
- [SuppressUnmanagedCodeSecurity]
- [return: MarshalAs(UnmanagedType.Bool)]
- private static extern bool WinRTSupported();
-#endif // FEATURE_COMINTEROP
-
-#endif // FEATURE_CORESYSTEM
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern bool GetVersion(Microsoft.Win32.Win32Native.OSVERSIONINFO osVer);
@@ -711,7 +547,6 @@ namespace System {
get {
Contract.Ensures(Contract.Result<String>() != null);
- new EnvironmentPermission(PermissionState.Unrestricted).Demand();
return GetStackTrace(null, true);
}
}
@@ -806,16 +641,6 @@ namespace System {
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);
@@ -829,321 +654,74 @@ namespace System {
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
- private static String GetRuntimeResourceString(String key) {
- return GetResourceString(key);
- }
-
- private static String GetRuntimeResourceString(String key, params Object[] values) {
- return GetResourceStringFormatted(key,values);
- }
-
- public static bool Is64BitProcess {
- get {
-#if BIT64
- return true;
-#else // 32
- return false;
-#endif
- }
- }
-
- public static bool Is64BitOperatingSystem {
- get {
-#if BIT64
- // 64-bit programs run only on 64-bit
- return true;
-#else // 32
- bool isWow64; // WinXP SP2+ and Win2k3 SP1+
- return Win32Native.DoesWin32MethodExist(Win32Native.KERNEL32, "IsWow64Process")
- && Win32Native.IsWow64Process(Win32Native.GetCurrentProcess(), out isWow64)
- && isWow64;
-#endif
- }
- }
-
public static extern bool HasShutdownStarted {
[MethodImplAttribute(MethodImplOptions.InternalCall)]
get;
}
- public static string UserName {
- get {
- new EnvironmentPermission(EnvironmentPermissionAccess.Read,"UserName").Demand();
-
- StringBuilder sb = new StringBuilder(256);
- int size = sb.Capacity;
- if (Win32Native.GetUserName(sb, ref size))
- {
- return sb.ToString();
- }
- return String.Empty;
- }
- }
-
- public static bool UserInteractive
+ internal static bool UserInteractive
{
get {
return true;
}
}
-
- public static string GetFolderPath(SpecialFolder folder) {
- if (!Enum.IsDefined(typeof(SpecialFolder), folder))
- throw new ArgumentException(Environment.GetResourceString("Arg_EnumIllegalVal", (int)folder));
- Contract.EndContractBlock();
-
- return InternalGetFolderPath(folder, SpecialFolderOption.None);
- }
-
- public static string GetFolderPath(SpecialFolder folder, SpecialFolderOption option) {
- if (!Enum.IsDefined(typeof(SpecialFolder),folder))
- throw new ArgumentException(Environment.GetResourceString("Arg_EnumIllegalVal", (int)folder));
- if (!Enum.IsDefined(typeof(SpecialFolderOption),option))
- throw new ArgumentException(Environment.GetResourceString("Arg_EnumIllegalVal", (int)option));
- Contract.EndContractBlock();
-
- return InternalGetFolderPath(folder, option);
+ public static int CurrentManagedThreadId
+ {
+ get
+ {
+ return Thread.CurrentThread.ManagedThreadId;
+ }
}
- internal static string UnsafeGetFolderPath(SpecialFolder folder)
+ internal static extern int CurrentProcessorNumber
{
- return InternalGetFolderPath(folder, SpecialFolderOption.None, suppressSecurityChecks: true);
+ [MethodImplAttribute(MethodImplOptions.InternalCall)]
+ get;
}
- private static string InternalGetFolderPath(SpecialFolder folder, SpecialFolderOption option, bool suppressSecurityChecks = false)
- {
-#if FEATURE_CORESYSTEM
- // This is currently customized for Windows Phone since CoreSystem doesn't support
- // SHGetFolderPath. The allowed folder values are based on the version of .NET CF WP7 was using.
- switch (folder)
- {
- case SpecialFolder.System:
- return SystemDirectory;
- case SpecialFolder.ApplicationData:
- case SpecialFolder.Favorites:
- case SpecialFolder.Programs:
- case SpecialFolder.StartMenu:
- case SpecialFolder.Startup:
- case SpecialFolder.Personal:
- throw new PlatformNotSupportedException();
- default:
- throw new PlatformNotSupportedException();
- }
-#else // FEATURE_CORESYSTEM
-
- StringBuilder sb = new StringBuilder(Path.MaxPath);
- int hresult = Win32Native.SHGetFolderPath(IntPtr.Zero, /* hwndOwner: [in] Reserved */
- ((int)folder | (int)option), /* nFolder: [in] CSIDL */
- IntPtr.Zero, /* hToken: [in] access token */
- Win32Native.SHGFP_TYPE_CURRENT, /* dwFlags: [in] retrieve current path */
- sb); /* pszPath: [out]resultant path */
- String s;
- if (hresult < 0)
- {
- switch (hresult)
- {
- default:
- // The previous incarnation threw away all errors. In order to limit
- // breaking changes, we will be permissive about these errors
- // instead of calling ThowExceptionForHR.
- //Runtime.InteropServices.Marshal.ThrowExceptionForHR(hresult);
- break;
- case __HResults.COR_E_PLATFORMNOTSUPPORTED:
- // This one error is the one we do want to throw.
+ // The upper bits of t_executionIdCache are the executionId. The lower bits of
+ // the t_executionIdCache are counting down to get it periodically refreshed.
+ // TODO: Consider flushing the executionIdCache on Wait operations or similar
+ // actions that are likely to result in changing the executing core
+ [ThreadStatic]
+ static int t_executionIdCache;
- throw new PlatformNotSupportedException();
- }
+ const int ExecutionIdCacheShift = 16;
+ const int ExecutionIdCacheCountDownMask = (1 << ExecutionIdCacheShift) - 1;
+ const int ExecutionIdRefreshRate = 5000;
- // SHGetFolderPath does not initialize the output buffer on error
- s = String.Empty;
- }
- else
- {
- s = sb.ToString();
- }
+ private static int RefreshExecutionId()
+ {
+ int executionId = CurrentProcessorNumber;
- if (!suppressSecurityChecks)
- {
- // 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 (option == SpecialFolderOption.None)
- {
- FileSecurityState state = new FileSecurityState(FileSecurityStateAccess.PathDiscovery, String.Empty, s);
- state.EnsureState();
- }
- else
- {
- new FileIOPermission(FileIOPermissionAccess.PathDiscovery, s).Demand();
- }
- }
- return s;
-#endif // FEATURE_CORESYSTEM
- }
+ // On Unix, CurrentProcessorNumber is implemented in terms of sched_getcpu, which
+ // doesn't exist on all platforms. On those it doesn't exist on, GetCurrentProcessorNumber
+ // returns -1. As a fallback in that case and to spread the threads across the buckets
+ // by default, we use the current managed thread ID as a proxy.
+ if (executionId < 0) executionId = Environment.CurrentManagedThreadId;
- public static string UserDomainName
- {
- get {
- new EnvironmentPermission(EnvironmentPermissionAccess.Read,"UserDomain").Demand();
-
- byte[] sid = new byte[1024];
- int sidLen = sid.Length;
- StringBuilder domainName = new StringBuilder(1024);
- uint domainNameLen = (uint) domainName.Capacity;
- int peUse;
-
- byte ret = Win32Native.GetUserNameEx(Win32Native.NameSamCompatible, domainName, ref domainNameLen);
- if (ret == 1) {
- string samName = domainName.ToString();
- int index = samName.IndexOf('\\');
- if( index != -1) {
- return samName.Substring(0, index);
- }
- }
- domainNameLen = (uint) domainName.Capacity;
-
- bool success = Win32Native.LookupAccountName(null, UserName, sid, ref sidLen, domainName, ref domainNameLen, out peUse);
- if (!success) {
- int errorCode = Marshal.GetLastWin32Error();
- throw new InvalidOperationException(Win32Native.GetMessage(errorCode));
- }
+ Debug.Assert(ExecutionIdRefreshRate <= ExecutionIdCacheCountDownMask);
- return domainName.ToString();
- }
- }
+ // Mask with Int32.MaxValue to ensure the execution Id is not negative
+ t_executionIdCache = ((executionId << ExecutionIdCacheShift) & Int32.MaxValue) | ExecutionIdRefreshRate;
- public enum SpecialFolderOption {
- None = 0,
- Create = Win32Native.CSIDL_FLAG_CREATE,
- DoNotVerify = Win32Native.CSIDL_FLAG_DONT_VERIFY,
- }
-
-//////!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!////////
-//////!!!!!! Keep the following locations synchronized !!!!!!////////
-//////!!!!!! 1) ndp\clr\src\BCL\Microsoft\Win32\Win32Native.cs !!!!!!////////
-//////!!!!!! 2) ndp\clr\src\BCL\System\Environment.cs !!!!!!////////
-//////!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!////////
- [ComVisible(true)]
- public enum SpecialFolder {
- //
- // Represents the file system directory that serves as a common repository for
- // application-specific data for the current, roaming user.
- // A roaming user works on more than one computer on a network. A roaming user's
- // profile is kept on a server on the network and is loaded onto a system when the
- // user logs on.
- //
- ApplicationData = Win32Native.CSIDL_APPDATA,
- //
- // Represents the file system directory that serves as a common repository for application-specific data that
- // is used by all users.
- //
- CommonApplicationData = Win32Native.CSIDL_COMMON_APPDATA,
- //
- // Represents the file system directory that serves as a common repository for application specific data that
- // is used by the current, non-roaming user.
- //
- LocalApplicationData = Win32Native.CSIDL_LOCAL_APPDATA,
- //
- // Represents the file system directory that serves as a common repository for Internet
- // cookies.
- //
- Cookies = Win32Native.CSIDL_COOKIES,
- Desktop = Win32Native.CSIDL_DESKTOP,
- //
- // Represents the file system directory that serves as a common repository for the user's
- // favorite items.
- //
- Favorites = Win32Native.CSIDL_FAVORITES,
- //
- // Represents the file system directory that serves as a common repository for Internet
- // history items.
- //
- History = Win32Native.CSIDL_HISTORY,
- //
- // Represents the file system directory that serves as a common repository for temporary
- // Internet files.
- //
- InternetCache = Win32Native.CSIDL_INTERNET_CACHE,
- //
- // Represents the file system directory that contains
- // the user's program groups.
- //
- Programs = Win32Native.CSIDL_PROGRAMS,
- MyComputer = Win32Native.CSIDL_DRIVES,
- MyMusic = Win32Native.CSIDL_MYMUSIC,
- MyPictures = Win32Native.CSIDL_MYPICTURES,
- // "My Videos" folder
- MyVideos = Win32Native.CSIDL_MYVIDEO,
- //
- // Represents the file system directory that contains the user's most recently used
- // documents.
- //
- Recent = Win32Native.CSIDL_RECENT,
- //
- // Represents the file system directory that contains Send To menu items.
- //
- SendTo = Win32Native.CSIDL_SENDTO,
- //
- // Represents the file system directory that contains the Start menu items.
- //
- StartMenu = Win32Native.CSIDL_STARTMENU,
- //
- // Represents the file system directory that corresponds to the user's Startup program group. The system
- // starts these programs whenever any user logs on to Windows NT, or
- // starts Windows 95 or Windows 98.
- //
- Startup = Win32Native.CSIDL_STARTUP,
- //
- // System directory.
- //
- System = Win32Native.CSIDL_SYSTEM,
- //
- // Represents the file system directory that serves as a common repository for document
- // templates.
- //
- Templates = Win32Native.CSIDL_TEMPLATES,
- //
- // Represents the file system directory used to physically store file objects on the desktop.
- // This should not be confused with the desktop folder itself, which is
- // a virtual folder.
- //
- DesktopDirectory = Win32Native.CSIDL_DESKTOPDIRECTORY,
- //
- // Represents the file system directory that serves as a common repository for documents.
- //
- Personal = Win32Native.CSIDL_PERSONAL,
- //
- // "MyDocuments" is a better name than "Personal"
- //
- MyDocuments = Win32Native.CSIDL_PERSONAL,
- //
- // Represents the program files folder.
- //
- ProgramFiles = Win32Native.CSIDL_PROGRAM_FILES,
- //
- // Represents the folder for components that are shared across applications.
- //
- CommonProgramFiles = Win32Native.CSIDL_PROGRAM_FILES_COMMON,
+ return executionId;
}
- public static int CurrentManagedThreadId
+ // Cached processor number used as a hint for which per-core stack to access. It is periodically
+ // refreshed to trail the actual thread core affinity.
+ internal static int CurrentExecutionId
{
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
get
{
- return Thread.CurrentThread.ManagedThreadId;
+ int executionIdCache = t_executionIdCache--;
+ if ((executionIdCache & ExecutionIdCacheCountDownMask) == 0)
+ return RefreshExecutionId();
+ return (executionIdCache >> ExecutionIdCacheShift);
}
}
- internal static extern int CurrentProcessorNumber
- {
- [MethodImplAttribute(MethodImplOptions.InternalCall)]
- get;
- }
-
public static string GetEnvironmentVariable(string variable)
{
if (variable == null)
@@ -1155,7 +733,7 @@ namespace System {
return GetEnvironmentVariableCore(variable);
}
- public static string GetEnvironmentVariable(string variable, EnvironmentVariableTarget target)
+ internal static string GetEnvironmentVariable(string variable, EnvironmentVariableTarget target)
{
if (variable == null)
{
@@ -1173,7 +751,7 @@ namespace System {
return GetEnvironmentVariablesCore();
}
- public static IDictionary GetEnvironmentVariables(EnvironmentVariableTarget target)
+ internal static IDictionary GetEnvironmentVariables(EnvironmentVariableTarget target)
{
ValidateTarget(target);
@@ -1188,7 +766,7 @@ namespace System {
SetEnvironmentVariableCore(variable, value);
}
- public static void SetEnvironmentVariable(string variable, string value, EnvironmentVariableTarget target)
+ internal static void SetEnvironmentVariable(string variable, string value, EnvironmentVariableTarget target)
{
ValidateVariableAndValue(variable, ref value);
ValidateTarget(target);
diff --git a/src/mscorlib/src/System/EventArgs.cs b/src/mscorlib/src/System/EventArgs.cs
index 349de857d8..c0356613de 100644
--- a/src/mscorlib/src/System/EventArgs.cs
+++ b/src/mscorlib/src/System/EventArgs.cs
@@ -2,16 +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.
-namespace System {
-
- using System;
+using System;
+
+namespace System
+{
// The base class for all event classes.
[Serializable]
- [System.Runtime.InteropServices.ComVisible(true)]
- public class EventArgs {
+ public class EventArgs
+ {
public static readonly EventArgs Empty = new EventArgs();
-
- public EventArgs()
+
+ public EventArgs()
{
}
}
diff --git a/src/mscorlib/src/System/EventHandler.cs b/src/mscorlib/src/System/EventHandler.cs
index 517e1f7c26..e6923cf637 100644
--- a/src/mscorlib/src/System/EventHandler.cs
+++ b/src/mscorlib/src/System/EventHandler.cs
@@ -2,10 +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 {
-
+using System;
+
+namespace System
+{
[Serializable]
- [System.Runtime.InteropServices.ComVisible(true)]
public delegate void EventHandler(Object sender, EventArgs e);
[Serializable]
diff --git a/src/mscorlib/src/System/Exception.cs b/src/mscorlib/src/System/Exception.cs
index a8ee328f1c..a166c1ab0a 100644
--- a/src/mscorlib/src/System/Exception.cs
+++ b/src/mscorlib/src/System/Exception.cs
@@ -18,7 +18,6 @@ namespace System {
using System.Runtime.Serialization;
using System.Runtime.Versioning;
using System.Diagnostics;
- using System.Security.Permissions;
using System.Security;
using System.IO;
using System.Text;
@@ -27,11 +26,8 @@ namespace System {
using System.Globalization;
using System.Diagnostics.Contracts;
- [ClassInterface(ClassInterfaceType.None)]
- [ComDefaultInterface(typeof(_Exception))]
[Serializable]
- [ComVisible(true)]
- public class Exception : ISerializable, _Exception
+ public class Exception : ISerializable
{
private void Init()
{
@@ -48,9 +44,6 @@ namespace System {
// Initialize the watson bucketing IP
_ipForWatsonBuckets = UIntPtr.Zero;
-#if FEATURE_SERIALIZATION
- _safeSerializationManager = new SafeSerializationManager();
-#endif // FEATURE_SERIALIZATION
}
public Exception() {
@@ -100,9 +93,6 @@ namespace System {
// get null.
_watsonBuckets = (Object)info.GetValueNoThrow("WatsonBuckets", typeof(byte[]));
-#if FEATURE_SERIALIZATION
- _safeSerializationManager = info.GetValueNoThrow("SafeSerializationManager", typeof(SafeSerializationManager)) as SafeSerializationManager;
-#endif // FEATURE_SERIALIZATION
if (_className == null || HResult==0)
throw new SerializationException(Environment.GetResourceString("Serialization_InsufficientState"));
@@ -493,19 +483,11 @@ namespace System {
return result;
}
-#if FEATURE_SERIALIZATION
- protected event EventHandler<SafeSerializationEventArgs> SerializeObjectState
- {
- 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
public virtual void GetObjectData(SerializationInfo info, StreamingContext context)
{
@@ -549,50 +531,6 @@ namespace System {
// Serialize the Watson bucket details as well
info.AddValue("WatsonBuckets", _watsonBuckets, typeof(byte[]));
-#if FEATURE_SERIALIZATION
- if (_safeSerializationManager != null && _safeSerializationManager.IsActive)
- {
- info.AddValue("SafeSerializationManager", _safeSerializationManager, typeof(SafeSerializationManager));
-
- // User classes derived from Exception must have a valid _safeSerializationManager.
- // Exceptions defined in mscorlib don't use this field might not have it initalized (since they are
- // 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
- 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
- _safeSerializationManager.CompleteSerialization(this, info, context);
- }
-#endif // FEATURE_SERIALIZATION
- }
-
- // This is used by remoting to preserve the server side stack trace
- // by appending it to the message ... before the exception is rethrown
- // at the client call site.
- internal Exception PrepForRemoting()
- {
- String tmp = null;
-
- if (_remoteStackIndex == 0)
- {
- tmp = Environment.NewLine+ "Server stack trace: " + Environment.NewLine
- + StackTrace
- + Environment.NewLine + Environment.NewLine
- + "Exception rethrown at ["+_remoteStackIndex+"]: " + Environment.NewLine;
- }
- else
- {
- tmp = StackTrace
- + Environment.NewLine + Environment.NewLine
- + "Exception rethrown at ["+_remoteStackIndex+"]: " + Environment.NewLine;
- }
-
- _remoteStackTraceString = tmp;
- _remoteStackIndex++;
-
- return this;
}
// This method will clear the _stackTrace of the exception object upon deserialization
@@ -610,16 +548,6 @@ namespace System {
// Hence, we set it to zero when deserialization takes place.
_ipForWatsonBuckets = UIntPtr.Zero;
-#if FEATURE_SERIALIZATION
- if (_safeSerializationManager == null)
- {
- _safeSerializationManager = new SafeSerializationManager();
- }
- else
- {
- _safeSerializationManager.CompleteDeserialization(this);
- }
-#endif // FEATURE_SERIALIZATION
}
// This is used by the runtime when re-throwing a managed exception. It will
@@ -642,11 +570,9 @@ namespace System {
}
else
#else // FEATURE_APPX
-#if FEATURE_CORESYSTEM
// Preinitialize _source on CoreSystem as well. The legacy behavior is not ideal and
// we keep it for back compat but we can afford to make the change on the Phone.
string source = Source;
-#endif // FEATURE_CORESYSTEM
#endif // FEATURE_APPX
{
// Call the StackTrace getter in classic for compat.
@@ -662,7 +588,6 @@ namespace System {
_stackTraceString = null;
}
-#if FEATURE_EXCEPTIONDISPATCHINFO
// This is the object against which a lock will be taken
// when attempt to restore the EDI. Since its static, its possible
@@ -786,7 +711,6 @@ namespace System {
}
}
}
-#endif // FEATURE_EXCEPTIONDISPATCHINFO
private String _className; //Needed for serialization.
private MethodBase _exceptionMethod; //Needed for serialization.
@@ -834,10 +758,6 @@ namespace System {
[OptionalField]
private UIntPtr _ipForWatsonBuckets; // Used to persist the IP for Watson Bucketing
-#if FEATURE_SERIALIZATION
- [OptionalField(VersionAdded = 4)]
- private SafeSerializationManager _safeSerializationManager;
-#endif // FEATURE_SERIALIZATION
// See src\inc\corexcep.h's EXCEPTION_COMPLUS definition:
private const int _COMPlusExceptionCode = unchecked((int)0xe0434352); // Win32 exception code for COM+ exceptions
@@ -846,19 +766,6 @@ namespace System {
// and create a corresponding CrossAppDomainMarshaledException
internal virtual String InternalToString()
{
- try
- {
-#pragma warning disable 618
- SecurityPermission sp= new SecurityPermission(SecurityPermissionFlag.ControlEvidence | SecurityPermissionFlag.ControlPolicy);
-#pragma warning restore 618
- sp.Assert();
- }
- catch
- {
- //under normal conditions there should be no exceptions
- //however if something wrong happens we still can call the usual ToString
- }
-
// Get the current stack trace string.
return ToString(true, true);
}
@@ -917,9 +824,6 @@ namespace System {
// The Message field is set to the ToString() output of the original exception.
//--------------------------------------------------------------------------
-#if FEATURE_SERIALIZATION
- [Serializable]
-#endif
internal sealed class CrossAppDomainMarshaledException : SystemException
{
public CrossAppDomainMarshaledException(String message, int errorCode)
diff --git a/src/mscorlib/src/System/ExecutionEngineException.cs b/src/mscorlib/src/System/ExecutionEngineException.cs
index 5b2592cca9..bebfd493a0 100644
--- a/src/mscorlib/src/System/ExecutionEngineException.cs
+++ b/src/mscorlib/src/System/ExecutionEngineException.cs
@@ -15,30 +15,33 @@
**
=============================================================================*/
-namespace System {
+using System;
+using System.Runtime.Serialization;
- using System;
- using System.Runtime.Serialization;
+namespace System
+{
[Obsolete("This type previously indicated an unspecified fatal error in the runtime. The runtime no longer raises this exception so this type is obsolete.")]
- [System.Runtime.InteropServices.ComVisible(true)]
[Serializable]
- public sealed class ExecutionEngineException : SystemException {
- public ExecutionEngineException()
- : base(Environment.GetResourceString("Arg_ExecutionEngineException")) {
- SetErrorCode(__HResults.COR_E_EXECUTIONENGINE);
+ public sealed class ExecutionEngineException : SystemException
+ {
+ public ExecutionEngineException()
+ : base(SR.Arg_ExecutionEngineException)
+ {
+ HResult = __HResults.COR_E_EXECUTIONENGINE;
}
-
- public ExecutionEngineException(String message)
- : base(message) {
- SetErrorCode(__HResults.COR_E_EXECUTIONENGINE);
- }
-
- public ExecutionEngineException(String message, Exception innerException)
- : base(message, innerException) {
- SetErrorCode(__HResults.COR_E_EXECUTIONENGINE);
+
+ public ExecutionEngineException(String message)
+ : base(message)
+ {
+ HResult = __HResults.COR_E_EXECUTIONENGINE;
}
- internal ExecutionEngineException(SerializationInfo info, StreamingContext context) : base(info, context) {
+ public ExecutionEngineException(String message, Exception innerException)
+ : base(message, innerException)
+ {
+ HResult = __HResults.COR_E_EXECUTIONENGINE;
}
+
+ internal ExecutionEngineException(SerializationInfo info, StreamingContext context) : base(info, context) { }
}
}
diff --git a/src/mscorlib/src/System/FieldAccessException.cs b/src/mscorlib/src/System/FieldAccessException.cs
index fbc3b1f592..ac62c0fcac 100644
--- a/src/mscorlib/src/System/FieldAccessException.cs
+++ b/src/mscorlib/src/System/FieldAccessException.cs
@@ -9,31 +9,31 @@
**
=============================================================================*/
-namespace System {
-
- using System;
- using System.Runtime.Serialization;
- [System.Runtime.InteropServices.ComVisible(true)]
+using System.Runtime.Serialization;
+
+namespace System
+{
[Serializable]
- public class FieldAccessException : MemberAccessException {
- public FieldAccessException()
- : base(Environment.GetResourceString("Arg_FieldAccessException")) {
- SetErrorCode(__HResults.COR_E_FIELDACCESS);
- }
-
- public FieldAccessException(String message)
- : base(message) {
- SetErrorCode(__HResults.COR_E_FIELDACCESS);
+ public class FieldAccessException : MemberAccessException
+ {
+ public FieldAccessException()
+ : base(SR.Arg_FieldAccessException)
+ {
+ HResult = __HResults.COR_E_FIELDACCESS;
}
-
- public FieldAccessException(String message, Exception inner)
- : base(message, inner) {
- SetErrorCode(__HResults.COR_E_FIELDACCESS);
+
+ public FieldAccessException(String message)
+ : base(message)
+ {
+ HResult = __HResults.COR_E_FIELDACCESS;
}
- protected FieldAccessException(SerializationInfo info, StreamingContext context) : base(info, context) {
+ public FieldAccessException(String message, Exception inner)
+ : base(message, inner)
+ {
+ HResult = __HResults.COR_E_FIELDACCESS;
}
+ protected FieldAccessException(SerializationInfo info, StreamingContext context) : base(info, context) { }
}
-
}
diff --git a/src/mscorlib/src/System/FlagsAttribute.cs b/src/mscorlib/src/System/FlagsAttribute.cs
index cb955cf3a1..5f8c108ae4 100644
--- a/src/mscorlib/src/System/FlagsAttribute.cs
+++ b/src/mscorlib/src/System/FlagsAttribute.cs
@@ -4,16 +4,15 @@
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
-namespace System {
-
- using System;
+
+namespace System
+{
// Custom attribute to indicate that the enum
// should be treated as a bitfield (or set of flags).
// An IDE may use this information to provide a richer
// development experience.
[Serializable]
[AttributeUsage(AttributeTargets.Enum, Inherited = false)]
- [System.Runtime.InteropServices.ComVisible(true)]
public class FlagsAttribute : Attribute
{
public FlagsAttribute()
diff --git a/src/mscorlib/src/System/FormatException.cs b/src/mscorlib/src/System/FormatException.cs
index 2e1c8a9cd4..c5758e11cd 100644
--- a/src/mscorlib/src/System/FormatException.cs
+++ b/src/mscorlib/src/System/FormatException.cs
@@ -10,30 +10,32 @@
**
**
===========================================================*/
-namespace System {
-
- using System.Runtime.Serialization;
- [System.Runtime.InteropServices.ComVisible(true)]
+
+using System.Runtime.Serialization;
+
+namespace System
+{
[Serializable]
- public class FormatException : SystemException {
- public FormatException()
- : base(Environment.GetResourceString("Arg_FormatException")) {
- SetErrorCode(__HResults.COR_E_FORMAT);
- }
-
- public FormatException(String message)
- : base(message) {
- SetErrorCode(__HResults.COR_E_FORMAT);
+ public class FormatException : SystemException
+ {
+ public FormatException()
+ : base(SR.Arg_FormatException)
+ {
+ HResult = __HResults.COR_E_FORMAT;
}
-
- public FormatException(String message, Exception innerException)
- : base(message, innerException) {
- SetErrorCode(__HResults.COR_E_FORMAT);
+
+ public FormatException(String message)
+ : base(message)
+ {
+ HResult = __HResults.COR_E_FORMAT;
}
- protected FormatException(SerializationInfo info, StreamingContext context) : base(info, context) {
+ public FormatException(String message, Exception innerException)
+ : base(message, innerException)
+ {
+ HResult = __HResults.COR_E_FORMAT;
}
+ protected FormatException(SerializationInfo info, StreamingContext context) : base(info, context) { }
}
-
}
diff --git a/src/mscorlib/src/System/FormattableString.cs b/src/mscorlib/src/System/FormattableString.cs
index 294b2c1846..6369363b5d 100644
--- a/src/mscorlib/src/System/FormattableString.cs
+++ b/src/mscorlib/src/System/FormattableString.cs
@@ -4,13 +4,13 @@
/*============================================================
**
-** Class: FormattableString
**
**
** Purpose: implementation of the FormattableString
** class.
**
===========================================================*/
+
namespace System
{
/// <summary>
diff --git a/src/mscorlib/src/System/GC.cs b/src/mscorlib/src/System/GC.cs
index e338e44526..fd09ef7984 100644
--- a/src/mscorlib/src/System/GC.cs
+++ b/src/mscorlib/src/System/GC.cs
@@ -16,7 +16,6 @@ namespace System {
//This class only static members and doesn't require the serializable keyword.
using System;
- using System.Security.Permissions;
using System.Reflection;
using System.Security;
using System.Threading;
@@ -98,7 +97,6 @@ namespace System {
private static extern int GetMaxGeneration();
[MethodImplAttribute(MethodImplOptions.InternalCall)]
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
private static extern int _CollectionCount (int generation, int getSpecialGCCount);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
@@ -206,7 +204,6 @@ namespace System {
_Collect(generation, iInternalModes);
}
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
public static int CollectionCount (int generation)
{
if (generation<0)
@@ -216,18 +213,6 @@ namespace System {
Contract.EndContractBlock();
return _CollectionCount(generation, 0);
}
-
- // pass in true to get the BGC or FGC count.
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
- internal static int CollectionCount (int generation, bool getSpecialGCCount)
- {
- if (generation<0)
- {
- throw new ArgumentOutOfRangeException(nameof(generation), Environment.GetResourceString("ArgumentOutOfRange_GenericPositive"));
- }
- Contract.EndContractBlock();
- return _CollectionCount(generation, (getSpecialGCCount ? 1 : 0));
- }
// This method DOES NOT DO ANYTHING in and of itself. It's used to
// prevent a finalizable object from losing any outstanding references
@@ -265,7 +250,6 @@ namespace System {
// If we insert a call to GC.KeepAlive(this) at the end of Problem(), then
// Foo doesn't get finalized and the stream stays open.
[MethodImplAttribute(MethodImplOptions.NoInlining)] // disable optimizations
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
public static void KeepAlive(Object obj)
{
}
@@ -296,10 +280,8 @@ namespace System {
// Indicates that the system should not call the Finalize() method on
// an object that would normally require this call.
[MethodImplAttribute(MethodImplOptions.InternalCall)]
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
private static extern void _SuppressFinalize(Object o);
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
public static void SuppressFinalize(Object obj) {
if (obj == null)
throw new ArgumentNullException(nameof(obj));
diff --git a/src/mscorlib/src/System/Globalization/Calendar.cs b/src/mscorlib/src/System/Globalization/Calendar.cs
index d0460386b6..1ff795ddc5 100644
--- a/src/mscorlib/src/System/Globalization/Calendar.cs
+++ b/src/mscorlib/src/System/Globalization/Calendar.cs
@@ -31,7 +31,6 @@ namespace System.Globalization {
// since most of the calendars (or all?) have the same way of calcuating hour/minute/second.
[Serializable]
- [System.Runtime.InteropServices.ComVisible(true)]
public abstract class Calendar : ICloneable
{
@@ -98,7 +97,6 @@ namespace System.Globalization {
// The minimum supported DateTime range for the calendar.
- [System.Runtime.InteropServices.ComVisible(false)]
public virtual DateTime MinSupportedDateTime
{
get
@@ -109,7 +107,6 @@ namespace System.Globalization {
// The maximum supported DateTime range for the calendar.
- [System.Runtime.InteropServices.ComVisible(false)]
public virtual DateTime MaxSupportedDateTime
{
get
@@ -145,7 +142,6 @@ namespace System.Globalization {
// Returns the type of the calendar.
//
- [System.Runtime.InteropServices.ComVisible(false)]
public virtual CalendarAlgorithmType AlgorithmType
{
get
@@ -161,7 +157,6 @@ namespace System.Globalization {
// Detect if the object is readonly.
//
////////////////////////////////////////////////////////////////////////
- [System.Runtime.InteropServices.ComVisible(false)]
public bool IsReadOnly
{
get { return (m_isReadOnly); }
@@ -174,7 +169,6 @@ namespace System.Globalization {
// Is the implementation of ICloneable.
//
////////////////////////////////////////////////////////////////////////
- [System.Runtime.InteropServices.ComVisible(false)]
public virtual Object Clone()
{
object o = MemberwiseClone();
@@ -190,7 +184,6 @@ namespace System.Globalization {
// readonly.
//
////////////////////////////////////////////////////////////////////////
- [System.Runtime.InteropServices.ComVisible(false)]
public static Calendar ReadOnly(Calendar calendar)
{
if (calendar == null) { throw new ArgumentNullException(nameof(calendar)); }
@@ -709,7 +702,6 @@ namespace System.Globalization {
// if this calendar does not have leap month, or this year is not a leap year.
//
- [System.Runtime.InteropServices.ComVisible(false)]
public virtual int GetLeapMonth(int year)
{
return (GetLeapMonth(year, CurrentEra));
@@ -719,7 +711,6 @@ namespace System.Globalization {
// if this calendar does not have leap month, or this year is not a leap year.
//
- [System.Runtime.InteropServices.ComVisible(false)]
public virtual int GetLeapMonth(int year, int era)
{
if (!IsLeapYear(year, era))
diff --git a/src/mscorlib/src/System/Globalization/CalendarAlgorithmType.cs b/src/mscorlib/src/System/Globalization/CalendarAlgorithmType.cs
index 4bf636656f..33b5035a8d 100644
--- a/src/mscorlib/src/System/Globalization/CalendarAlgorithmType.cs
+++ b/src/mscorlib/src/System/Globalization/CalendarAlgorithmType.cs
@@ -5,7 +5,6 @@
namespace System.Globalization {
using System;
-[System.Runtime.InteropServices.ComVisible(true)]
public enum CalendarAlgorithmType {
Unknown = 0, // This is the default value to return in the Calendar base class.
SolarCalendar = 1, // Solar-base calendar, such as GregorianCalendar, jaoaneseCalendar, JulianCalendar, etc.
diff --git a/src/mscorlib/src/System/Globalization/CalendarData.cs b/src/mscorlib/src/System/Globalization/CalendarData.cs
index 6f583fbcbc..d66331b31d 100644
--- a/src/mscorlib/src/System/Globalization/CalendarData.cs
+++ b/src/mscorlib/src/System/Globalization/CalendarData.cs
@@ -400,41 +400,6 @@ namespace System.Globalization
return "en-US";
}
- internal void FixupWin7MonthDaySemicolonBug()
- {
- int unescapedCharacterIndex = FindUnescapedCharacter(sMonthDay, ';');
- if (unescapedCharacterIndex > 0)
- {
- sMonthDay = sMonthDay.Substring(0, unescapedCharacterIndex);
- }
- }
- private static int FindUnescapedCharacter(string s, char charToFind)
- {
- bool inComment = false;
- int length = s.Length;
- for (int i = 0; i < length; i++)
- {
- char c = s[i];
-
- switch (c)
- {
- case '\'':
- inComment = !inComment;
- break;
- case '\\':
- i++; // escape sequence -- skip next character
- break;
- default:
- if (!inComment && charToFind == c)
- {
- return i;
- }
- break;
- }
- }
- return -1;
- }
-
// Get native two digit year max
[MethodImplAttribute(MethodImplOptions.InternalCall)]
diff --git a/src/mscorlib/src/System/Globalization/CalendarWeekRule.cs b/src/mscorlib/src/System/Globalization/CalendarWeekRule.cs
index 578b5672fc..fa2a6429f1 100644
--- a/src/mscorlib/src/System/Globalization/CalendarWeekRule.cs
+++ b/src/mscorlib/src/System/Globalization/CalendarWeekRule.cs
@@ -7,7 +7,6 @@ namespace System.Globalization {
[Serializable]
-[System.Runtime.InteropServices.ComVisible(true)]
public enum CalendarWeekRule
{
diff --git a/src/mscorlib/src/System/Globalization/ChineseLunisolarCalendar.cs b/src/mscorlib/src/System/Globalization/ChineseLunisolarCalendar.cs
index 6479152e09..374ed0dcfa 100644
--- a/src/mscorlib/src/System/Globalization/ChineseLunisolarCalendar.cs
+++ b/src/mscorlib/src/System/Globalization/ChineseLunisolarCalendar.cs
@@ -44,7 +44,6 @@ namespace System.Globalization {
internal static DateTime minDate = new DateTime(MIN_GREGORIAN_YEAR, MIN_GREGORIAN_MONTH, MIN_GREGORIAN_DAY);
internal static DateTime maxDate = new DateTime((new DateTime(MAX_GREGORIAN_YEAR, MAX_GREGORIAN_MONTH, MAX_GREGORIAN_DAY, 23, 59, 59, 999)).Ticks + 9999);
- [System.Runtime.InteropServices.ComVisible(false)]
public override DateTime MinSupportedDateTime {
get
{
@@ -53,7 +52,6 @@ namespace System.Globalization {
}
- [System.Runtime.InteropServices.ComVisible(false)]
public override DateTime MaxSupportedDateTime {
get
{
@@ -371,7 +369,6 @@ namespace System.Globalization {
}
- [System.Runtime.InteropServices.ComVisible(false)]
public override int GetEra(DateTime time) {
CheckTicksRange(time.Ticks);
return (ChineseEra);
@@ -391,7 +388,6 @@ namespace System.Globalization {
}
- [System.Runtime.InteropServices.ComVisible(false)]
public override int[] Eras {
get {
return (new int[] {ChineseEra});
diff --git a/src/mscorlib/src/System/Globalization/CompareInfo.cs b/src/mscorlib/src/System/Globalization/CompareInfo.cs
index dcf1f32e4a..6c2230b66b 100644
--- a/src/mscorlib/src/System/Globalization/CompareInfo.cs
+++ b/src/mscorlib/src/System/Globalization/CompareInfo.cs
@@ -29,7 +29,6 @@ namespace System.Globalization {
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Threading;
- using System.Security.Permissions;
using Microsoft.Win32;
using System.Security;
using System.Diagnostics;
@@ -45,7 +44,6 @@ namespace System.Globalization {
[Serializable]
[Flags]
- [System.Runtime.InteropServices.ComVisible(true)]
public enum CompareOptions
{
None = 0x00000000,
@@ -66,7 +64,6 @@ namespace System.Globalization {
[Serializable]
- [System.Runtime.InteropServices.ComVisible(true)]
public partial class CompareInfo : IDeserializationCallback
{
// Mask used to check if IndexOf()/LastIndexOf()/IsPrefix()/IsPostfix() has the right flags.
@@ -217,12 +214,10 @@ namespace System.Globalization {
return CultureInfo.GetCultureInfo(name).CompareInfo;
}
- [System.Runtime.InteropServices.ComVisible(false)]
public static bool IsSortable(char ch) {
return(IsSortable(ch.ToString()));
}
- [System.Runtime.InteropServices.ComVisible(false)]
public static bool IsSortable(String text) {
if (text == null) {
// A null param is invalid here.
@@ -316,7 +311,6 @@ namespace System.Globalization {
//
////////////////////////////////////////////////////////////////////////
- [System.Runtime.InteropServices.ComVisible(false)]
public virtual String Name
{
get
diff --git a/src/mscorlib/src/System/Globalization/CultureData.cs b/src/mscorlib/src/System/Globalization/CultureData.cs
index 0bcb796152..a93b7d43bb 100644
--- a/src/mscorlib/src/System/Globalization/CultureData.cs
+++ b/src/mscorlib/src/System/Globalization/CultureData.cs
@@ -1,4 +1,4 @@
-// Licensed to the .NET Foundation under one or more agreements.
+// 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.
@@ -1102,15 +1102,6 @@ namespace System.Globalization
}
}
- // (user can override) country code (RegionInfo)
- internal int ICOUNTRY
- {
- get
- {
- return DoGetLocaleInfoInt(LOCALE_ICOUNTRY);
- }
- }
-
// GeoId
internal int IGEOID
{
@@ -1214,15 +1205,6 @@ namespace System.Globalization
}
}
- // Default Country
- private int IDEFAULTCOUNTRY
- {
- get
- {
- return DoGetLocaleInfoInt(LOCALE_IDEFAULTCOUNTRY);
- }
- }
-
// Console fallback name (ie: locale to use for console apps for unicode-only locales)
internal int IINPUTLANGUAGEHANDLE
{
@@ -1262,26 +1244,6 @@ namespace System.Globalization
}
}
- /////////////
- // Numbers //
- ////////////
-
- // internal String sPositiveSign ; // (user can override) positive sign
- // internal String sNegativeSign ; // (user can override) negative sign
- // internal String[] saNativeDigits ; // (user can override) native characters for digits 0-9
- // internal int iDigitSubstitution ; // (user can override) Digit substitution 0=context, 1=none/arabic, 2=Native/national (2 seems to be unused) (Windows Only)
- // internal int iDigits ; // (user can override) number of fractional digits
- // internal int iNegativeNumber ; // (user can override) negative number format
-
- // Leading zeroes
- private bool ILEADINGZEROS
- {
- get
- {
- return (DoGetLocaleInfoInt(LOCALE_ILZERO) == 1);
- }
- }
-
// (user can override) grouping of digits
internal int[] WAGROUPING
@@ -1506,15 +1468,6 @@ namespace System.Globalization
}
}
- // Paper size
- private int IPAPERSIZE
- {
- get
- {
- return DoGetLocaleInfoInt(LOCALE_IPAPERSIZE);
- }
- }
-
////////////////////////////
// Calendar/Time (Gregorian) //
////////////////////////////
@@ -1712,20 +1665,6 @@ namespace System.Globalization
return index;
}
- // time duration format
- internal String[] SADURATION
- {
- get
- {
- if (this.saDurationFormats == null)
- {
- String durationFormat = DoGetLocaleInfo(LOCALE_SDURATION);
- this.saDurationFormats = new String[] { ReescapeWin32String(durationFormat) };
- }
- return this.saDurationFormats;
- }
- }
-
// (user can override) first day of week
internal int IFIRSTDAYOFWEEK
{
@@ -1944,11 +1883,6 @@ namespace System.Globalization
return calendarData;
}
- internal int CurrentEra(int calendarId)
- {
- return GetCalendar(calendarId).iCurrentEra;
- }
-
///////////////////
// Text Information //
///////////////////
@@ -2054,48 +1988,6 @@ namespace System.Globalization
}
}
- // Typical Scripts for this locale (latn;cyrl; etc)
-
- private String SSCRIPTS
- {
- get
- {
- if (this.sScripts == null)
- {
- this.sScripts = DoGetLocaleInfo(LOCALE_SSCRIPTS);
- }
- return this.sScripts;
- }
- }
-
- private String SOPENTYPELANGUAGETAG
- {
- get
- {
- return DoGetLocaleInfo(LOCALE_SOPENTYPELANGUAGETAG);
- }
- }
-
- private String FONTSIGNATURE
- {
- get
- {
- if (this.fontSignature == null)
- {
- this.fontSignature = DoGetLocaleInfo(LOCALE_FONTSIGNATURE);
- }
- return this.fontSignature;
- }
- }
-
- private String SKEYBOARDSTOINSTALL
- {
- get
- {
- return DoGetLocaleInfo(LOCALE_SKEYBOARDSTOINSTALL);
- }
- }
-
internal int IDEFAULTANSICODEPAGE // default ansi code page ID (ACP)
{
diff --git a/src/mscorlib/src/System/Globalization/CultureInfo.cs b/src/mscorlib/src/System/Globalization/CultureInfo.cs
index 9f306c3c99..ba61c146f6 100644
--- a/src/mscorlib/src/System/Globalization/CultureInfo.cs
+++ b/src/mscorlib/src/System/Globalization/CultureInfo.cs
@@ -36,7 +36,6 @@ namespace System.Globalization {
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
using System.Runtime.Versioning;
- using System.Security.Permissions;
using System.Reflection;
using Microsoft.Win32;
using System.Diagnostics;
@@ -44,7 +43,6 @@ namespace System.Globalization {
using System.Resources;
[Serializable]
- [System.Runtime.InteropServices.ComVisible(true)]
public partial class CultureInfo : ICloneable, IFormatProvider {
//--------------------------------------------------------------------//
// Internal Information //
@@ -82,10 +80,6 @@ namespace System.Globalization {
[NonSerialized]internal CultureData m_cultureData;
[NonSerialized]internal bool m_isInherited;
-#if FEATURE_LEAK_CULTURE_INFO
- [NonSerialized]private bool m_isSafeCrossDomain;
- [NonSerialized]private int m_createdDomainID;
-#endif // !FEATURE_LEAK_CULTURE_INFO
[NonSerialized]private CultureInfo m_consoleFallbackCulture;
// Names are confusing. Here are 3 names we have:
@@ -370,25 +364,6 @@ namespace System.Globalization {
}
#endif // FEATURE_USE_LCID
- //
- // CheckDomainSafetyObject throw if the object is customized object which cannot be attached to
- // other object (like CultureInfo or DateTimeFormatInfo).
- //
-
- internal static void CheckDomainSafetyObject(Object obj, Object container)
- {
- if (obj.GetType().Assembly != typeof(System.Globalization.CultureInfo).Assembly) {
-
- throw new InvalidOperationException(
- String.Format(
- CultureInfo.CurrentCulture,
- Environment.GetResourceString("InvalidOperation_SubclassedObject"),
- obj.GetType(),
- container.GetType()));
- }
- Contract.EndContractBlock();
- }
-
#region Serialization
// We need to store the override from the culture data record.
private bool m_useUserOverride;
@@ -421,21 +396,6 @@ namespace System.Globalization {
}
#endif
m_isInherited = (this.GetType() != typeof(System.Globalization.CultureInfo));
-
- // in case we have non customized CultureInfo object we shouldn't allow any customized object
- // to be attached to it for cross app domain safety.
- if (this.GetType().Assembly == typeof(System.Globalization.CultureInfo).Assembly)
- {
- if (textInfo != null)
- {
- CheckDomainSafetyObject(textInfo, this);
- }
-
- if (compareInfo != null)
- {
- CheckDomainSafetyObject(compareInfo, this);
- }
- }
}
#if FEATURE_USE_LCID
@@ -470,57 +430,8 @@ namespace System.Globalization {
this.cultureID = this.m_cultureData.ILANGUAGE;
#endif
}
-#endregion Serialization
-
-#if FEATURE_LEAK_CULTURE_INFO
- // Is it safe to send this CultureInfo as an instance member of a Thread cross AppDomain boundaries?
- // For Silverlight, the answer is always no.
- internal bool IsSafeCrossDomain {
- get {
- Debug.Assert(m_createdDomainID != 0, "[CultureInfo.IsSafeCrossDomain] m_createdDomainID != 0");
- return m_isSafeCrossDomain;
- }
- }
-
- internal int CreatedDomainID {
- get {
- Debug.Assert(m_createdDomainID != 0, "[CultureInfo.CreatedDomain] m_createdDomainID != 0");
- return m_createdDomainID;
- }
- }
-
- internal void StartCrossDomainTracking() {
-
- // If we have decided about cross domain safety of this instance, we are done
- if (m_createdDomainID != 0)
- return;
-
- // If FEATURE_LEAK_CULTURE_INFO isn't enabled, we never want to pass
- // CultureInfo as an instance member of a Thread.
- if (CanSendCrossDomain())
- {
- m_isSafeCrossDomain = true;
- }
-
- // m_createdDomainID has to be assigned last. We use it to signal that we have
- // completed the check.
- System.Threading.Thread.MemoryBarrier();
- m_createdDomainID = Thread.GetDomainID();
- }
-#endif // FEATURE_LEAK_CULTURE_INFO
- // Is it safe to pass the CultureInfo cross AppDomain boundaries, not necessarily as an instance
- // member of Thread. This is different from IsSafeCrossDomain, which implies passing the CultureInfo
- // as a Thread instance member.
- internal bool CanSendCrossDomain()
- {
- bool isSafe = false;
- if (this.GetType() == typeof(System.Globalization.CultureInfo))
- {
- isSafe = true;
- }
- return isSafe;
- }
+#endregion Serialization
// Constructor called by SQL Server's special munged culture - creates a culture with
// a TextInfo and CompareInfo that come from a supplied alternate source. This object
@@ -949,7 +860,6 @@ namespace System.Globalization {
//
////////////////////////////////////////////////////////////////////////
#if FEATURE_USE_LCID
- [System.Runtime.InteropServices.ComVisible(false)]
public virtual int KeyboardLayoutId
{
get
@@ -1010,7 +920,6 @@ namespace System.Globalization {
}
}
- [System.Runtime.InteropServices.ComVisible(false)]
public String IetfLanguageTag
{
get
@@ -1258,7 +1167,6 @@ namespace System.Globalization {
}
}
- [System.Runtime.InteropServices.ComVisible(false)]
public CultureTypes CultureTypes
{
get
@@ -1473,7 +1381,6 @@ namespace System.Globalization {
}
}
- [System.Runtime.InteropServices.ComVisible(false)]
public CultureInfo GetConsoleFallbackUICulture()
{
Contract.Ensures(Contract.Result<CultureInfo>() != null);
@@ -1885,9 +1792,6 @@ namespace System.Globalization {
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern int nativeGetLocaleInfoExInt(String localeName, uint field);
- [MethodImplAttribute(MethodImplOptions.InternalCall)]
- internal static extern bool nativeSetThreadLocale(String localeName);
-
private static String GetDefaultLocaleName(int localeType)
{
Debug.Assert(localeType == LOCALE_USER_DEFAULT || localeType == LOCALE_SYSTEM_DEFAULT, "[CultureInfo.GetDefaultLocaleName] localeType must be LOCALE_USER_DEFAULT or LOCALE_SYSTEM_DEFAULT");
diff --git a/src/mscorlib/src/System/Globalization/CultureNotFoundException.cs b/src/mscorlib/src/System/Globalization/CultureNotFoundException.cs
index 17c0b43f9c..d4ab700a16 100644
--- a/src/mscorlib/src/System/Globalization/CultureNotFoundException.cs
+++ b/src/mscorlib/src/System/Globalization/CultureNotFoundException.cs
@@ -10,7 +10,6 @@ namespace System.Globalization {
using System.Threading;
using System.Diagnostics.Contracts;
- [System.Runtime.InteropServices.ComVisible(true)]
[Serializable]
public partial class CultureNotFoundException : ArgumentException, ISerializable
{
diff --git a/src/mscorlib/src/System/Globalization/CultureTypes.cs b/src/mscorlib/src/System/Globalization/CultureTypes.cs
index d506d50c9d..b19ab86bb1 100644
--- a/src/mscorlib/src/System/Globalization/CultureTypes.cs
+++ b/src/mscorlib/src/System/Globalization/CultureTypes.cs
@@ -11,7 +11,6 @@ namespace System.Globalization {
[Serializable]
[Flags]
- [System.Runtime.InteropServices.ComVisible(true)]
public enum CultureTypes
{
NeutralCultures = 0x0001, // Neutral cultures are cultures like "en", "de", "zh", etc, for enumeration this includes ALL neutrals regardless of other flags
diff --git a/src/mscorlib/src/System/Globalization/DateTimeFormat.cs b/src/mscorlib/src/System/Globalization/DateTimeFormat.cs
index c6e0591a74..1ace207952 100644
--- a/src/mscorlib/src/System/Globalization/DateTimeFormat.cs
+++ b/src/mscorlib/src/System/Globalization/DateTimeFormat.cs
@@ -1124,14 +1124,6 @@ namespace System {
// local DateTime with a format that will be interpreted as UTC.
internal static void InvalidFormatForLocal(String format, DateTime dateTime) {
}
-
- // This is an MDA for cases when the user is using a local format with
- // a Utc DateTime.
- internal static void InvalidFormatForUtc(String format, DateTime dateTime) {
-#if MDA_SUPPORTED
- Mda.DateTimeInvalidLocalFormat();
-#endif
- }
}
diff --git a/src/mscorlib/src/System/Globalization/DateTimeFormatInfo.cs b/src/mscorlib/src/System/Globalization/DateTimeFormatInfo.cs
index 14cdeb60e9..b2374ef0b2 100644
--- a/src/mscorlib/src/System/Globalization/DateTimeFormatInfo.cs
+++ b/src/mscorlib/src/System/Globalization/DateTimeFormatInfo.cs
@@ -10,7 +10,6 @@ namespace System.Globalization {
using System.Collections;
using System.Collections.Generic;
using System.Runtime.Serialization;
- using System.Security.Permissions;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Text;
@@ -56,7 +55,6 @@ namespace System.Globalization {
[Serializable]
- [System.Runtime.InteropServices.ComVisible(true)]
public sealed class DateTimeFormatInfo : ICloneable, IFormatProvider
{
//
@@ -378,8 +376,6 @@ namespace System.Globalization {
private int nDataItem;
[OptionalField(VersionAdded = 2)]
internal bool m_isDefaultCalendar; // NEVER USED, DO NOT USE THIS! (Serialized in Whidbey)
- [OptionalField(VersionAdded = 2)]
- private static volatile Hashtable s_calendarNativeNames; // NEVER USED, DO NOT USE THIS! (Serialized in Whidbey)
// This was synthesized by Whidbey so we knew what words might appear in the middle of a date string
// Now we always synthesize so its not helpful
@@ -408,10 +404,6 @@ namespace System.Globalization {
calendar = (Calendar) GregorianCalendar.GetDefaultInstance().Clone();
calendar.SetReadOnlyState(m_isReadOnly);
}
- else
- {
- CultureInfo.CheckDomainSafetyObject(calendar, this);
- }
InitializeOverridableProperties(m_cultureData, calendar.ID);
//
@@ -587,12 +579,6 @@ namespace System.Globalization {
return;
}
- //
- // Because the culture is agile object which can be attached to a thread and then thread can travel
- // to another app domain then we prevent attaching any customized object to culture that we cannot contol.
- //
- CultureInfo.CheckDomainSafetyObject(value, this);
-
for (int i = 0; i < this.OptionalCalendars.Length; i++)
{
if (this.OptionalCalendars[i] == value.ID)
@@ -1370,7 +1356,6 @@ namespace System.Globalization {
// Returns the string array of the one-letter day of week names.
- [System.Runtime.InteropServices.ComVisible(false)]
public String[] ShortestDayNames
{
get
@@ -1593,7 +1578,6 @@ namespace System.Globalization {
// Returns the super short day of week names for the specified day of week.
- [System.Runtime.InteropServices.ComVisible(false)]
public String GetShortestDayName(DayOfWeek dayOfWeek)
{
@@ -1971,7 +1955,6 @@ namespace System.Globalization {
// String nativeName = dtfi.NativeCalendarName; // Get the Japanese name for the Japanese calendar.
// DateTimeFormatInfo dtfi = new CultureInfo("ja-JP", false).DateTimeFormat.Calendar = new GregorianCalendar(GregorianCalendarTypes.Localized);
// String nativeName = dtfi.NativeCalendarName; // Get the Japanese name for the Gregorian calendar.
- [System.Runtime.InteropServices.ComVisible(false)]
public String NativeCalendarName
{
get
@@ -1998,7 +1981,6 @@ namespace System.Globalization {
// WARNING: If more validation is ever done in one place, it should be done in the other.
//
- [System.Runtime.InteropServices.ComVisible(false)]
public void SetAllDateTimePatterns(String[] patterns, char format)
{
if (IsReadOnly)
@@ -2061,7 +2043,6 @@ namespace System.Globalization {
return;
}
- [System.Runtime.InteropServices.ComVisible(false)]
public String[] AbbreviatedMonthGenitiveNames
{
get
@@ -2089,7 +2070,6 @@ namespace System.Globalization {
}
}
- [System.Runtime.InteropServices.ComVisible(false)]
public String[] MonthGenitiveNames
{
get
@@ -2455,7 +2435,7 @@ namespace System.Globalization {
case DateTimeFormatInfoScanner.IgnorableSymbolChar:
String symbol = dateWords[i].Substring(1);
InsertHash(temp, symbol, TokenType.IgnorableSymbol, 0);
- if (this.DateSeparator.Trim(null).Equals(symbol))
+ if (this.DateSeparator.Trim().Equals(symbol))
{
// The date separator is the same as the ingorable symbol.
useDateSepAsIgnorableSymbol = true;
@@ -2802,7 +2782,7 @@ namespace System.Globalization {
// If there is whitespace characters in the beginning and end of the string, trim them since whitespaces are skipped by
// DateTime.Parse().
if (Char.IsWhiteSpace(str[0]) || Char.IsWhiteSpace(str[str.Length - 1])) {
- str = str.Trim(null); // Trim white space characters.
+ str = str.Trim(); // Trim white space characters.
// Could have space for separators
if (str.Length == 0)
return;
diff --git a/src/mscorlib/src/System/Globalization/DateTimeStyles.cs b/src/mscorlib/src/System/Globalization/DateTimeStyles.cs
index ddae7b2f29..eadeda8e72 100644
--- a/src/mscorlib/src/System/Globalization/DateTimeStyles.cs
+++ b/src/mscorlib/src/System/Globalization/DateTimeStyles.cs
@@ -16,7 +16,6 @@ namespace System.Globalization {
[Serializable]
[Flags]
-[System.Runtime.InteropServices.ComVisible(true)]
public enum DateTimeStyles {
// Bit flag indicating that leading whitespace is allowed. Character values
// 0x0009, 0x000A, 0x000B, 0x000C, 0x000D, and 0x0020 are considered to be
diff --git a/src/mscorlib/src/System/Globalization/DaylightTime.cs b/src/mscorlib/src/System/Globalization/DaylightTime.cs
index a164867576..a21e092955 100644
--- a/src/mscorlib/src/System/Globalization/DaylightTime.cs
+++ b/src/mscorlib/src/System/Globalization/DaylightTime.cs
@@ -8,7 +8,6 @@ namespace System.Globalization
{
// This class represents a starting/ending time for a period of daylight saving time.
[Serializable]
- [ComVisible(true)]
public class DaylightTime
{
internal DateTime m_start;
diff --git a/src/mscorlib/src/System/Globalization/DigitShapes.cs b/src/mscorlib/src/System/Globalization/DigitShapes.cs
index d5b5ecc89c..1513d56f5c 100644
--- a/src/mscorlib/src/System/Globalization/DigitShapes.cs
+++ b/src/mscorlib/src/System/Globalization/DigitShapes.cs
@@ -9,7 +9,6 @@ namespace System.Globalization {
[Serializable]
-[System.Runtime.InteropServices.ComVisible(true)]
public enum DigitShapes : int {
Context = 0x0000, // The shape depends on the previous text in the same output.
diff --git a/src/mscorlib/src/System/Globalization/EastAsianLunisolarCalendar.cs b/src/mscorlib/src/System/Globalization/EastAsianLunisolarCalendar.cs
index 3c9391fa63..3f6df52a96 100644
--- a/src/mscorlib/src/System/Globalization/EastAsianLunisolarCalendar.cs
+++ b/src/mscorlib/src/System/Globalization/EastAsianLunisolarCalendar.cs
@@ -14,7 +14,6 @@ namespace System.Globalization {
[Serializable]
-[System.Runtime.InteropServices.ComVisible(true)]
public abstract class EastAsianLunisolarCalendar : Calendar {
internal const int LeapMonth = 0;
internal const int Jan1Month = 1;
diff --git a/src/mscorlib/src/System/Globalization/EncodingTable.cs b/src/mscorlib/src/System/Globalization/EncodingTable.cs
index d908a2ac2b..b7c268a956 100644
--- a/src/mscorlib/src/System/Globalization/EncodingTable.cs
+++ b/src/mscorlib/src/System/Globalization/EncodingTable.cs
@@ -203,10 +203,6 @@ namespace System.Globalization
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private unsafe static extern InternalCodePageDataItem* GetCodePageData();
-
- [MethodImplAttribute(MethodImplOptions.InternalCall)]
- internal unsafe static extern byte* nativeCreateOpenFileMapping(
- String inSectionName, int inBytesToAllocate, out IntPtr mappedFileHandle);
}
/*=================================InternalEncodingDataItem==========================
diff --git a/src/mscorlib/src/System/Globalization/GlobalizationAssembly.cs b/src/mscorlib/src/System/Globalization/GlobalizationAssembly.cs
index 0810d67b59..e203223eb0 100644
--- a/src/mscorlib/src/System/Globalization/GlobalizationAssembly.cs
+++ b/src/mscorlib/src/System/Globalization/GlobalizationAssembly.cs
@@ -10,7 +10,6 @@ namespace System.Globalization {
using System.Collections.Generic;
using System.Threading;
using System.Security;
- using System.Security.Permissions;
using System.Runtime.CompilerServices;
using System.Runtime.ConstrainedExecution;
using System.Runtime.Versioning;
diff --git a/src/mscorlib/src/System/Globalization/GregorianCalendar.cs b/src/mscorlib/src/System/Globalization/GregorianCalendar.cs
index 6cf9b2eb85..9083e6de27 100644
--- a/src/mscorlib/src/System/Globalization/GregorianCalendar.cs
+++ b/src/mscorlib/src/System/Globalization/GregorianCalendar.cs
@@ -22,7 +22,6 @@ namespace System.Globalization {
// 0 CurrentEra (AD)
// 1 BeforeCurrentEra (BC)
- [System.Runtime.InteropServices.ComVisible(true)]
[Serializable]
public class GregorianCalendar : Calendar
{
@@ -77,7 +76,6 @@ namespace System.Globalization {
}
#endregion Serialization
- [System.Runtime.InteropServices.ComVisible(false)]
public override DateTime MinSupportedDateTime
{
get
@@ -86,7 +84,6 @@ namespace System.Globalization {
}
}
- [System.Runtime.InteropServices.ComVisible(false)]
public override DateTime MaxSupportedDateTime
{
get
@@ -98,7 +95,6 @@ namespace System.Globalization {
// Return the type of the Gregorian calendar.
//
- [System.Runtime.InteropServices.ComVisible(false)]
public override CalendarAlgorithmType AlgorithmType
{
get
@@ -495,7 +491,6 @@ namespace System.Globalization {
// if this calendar does not have leap month, or this year is not a leap year.
//
- [System.Runtime.InteropServices.ComVisible(false)]
public override int GetLeapMonth(int year, int era)
{
if (era != CurrentEra && era != ADEra)
diff --git a/src/mscorlib/src/System/Globalization/GregorianCalendarTypes.cs b/src/mscorlib/src/System/Globalization/GregorianCalendarTypes.cs
index a9e25d06bf..1af5e9221c 100644
--- a/src/mscorlib/src/System/Globalization/GregorianCalendarTypes.cs
+++ b/src/mscorlib/src/System/Globalization/GregorianCalendarTypes.cs
@@ -6,7 +6,6 @@ namespace System.Globalization {
using System;
[Serializable]
-[System.Runtime.InteropServices.ComVisible(true)]
public enum GregorianCalendarTypes {
Localized = Calendar.CAL_GREGORIAN,
USEnglish = Calendar.CAL_GREGORIAN_US,
diff --git a/src/mscorlib/src/System/Globalization/HebrewCalendar.cs b/src/mscorlib/src/System/Globalization/HebrewCalendar.cs
index 44cbdb8bde..190c3f17d2 100644
--- a/src/mscorlib/src/System/Globalization/HebrewCalendar.cs
+++ b/src/mscorlib/src/System/Globalization/HebrewCalendar.cs
@@ -64,7 +64,6 @@ namespace System.Globalization {
[Serializable]
-[System.Runtime.InteropServices.ComVisible(true)]
public class HebrewCalendar : Calendar {
diff --git a/src/mscorlib/src/System/Globalization/HijriCalendar.cs b/src/mscorlib/src/System/Globalization/HijriCalendar.cs
index 39a01e5774..061d380285 100644
--- a/src/mscorlib/src/System/Globalization/HijriCalendar.cs
+++ b/src/mscorlib/src/System/Globalization/HijriCalendar.cs
@@ -49,7 +49,6 @@ namespace System.Globalization {
*/
[Serializable]
-[System.Runtime.InteropServices.ComVisible(true)]
public class HijriCalendar : Calendar {
@@ -84,7 +83,6 @@ namespace System.Globalization {
internal static readonly DateTime calendarMaxValue = DateTime.MaxValue;
- [System.Runtime.InteropServices.ComVisible(false)]
public override DateTime MinSupportedDateTime
{
get
@@ -94,7 +92,6 @@ namespace System.Globalization {
}
- [System.Runtime.InteropServices.ComVisible(false)]
public override DateTime MaxSupportedDateTime
{
get
@@ -106,7 +103,6 @@ namespace System.Globalization {
// Return the type of the Hijri calendar.
//
- [System.Runtime.InteropServices.ComVisible(false)]
public override CalendarAlgorithmType AlgorithmType
{
get
@@ -614,7 +610,6 @@ namespace System.Globalization {
// if this calendar does not have leap month, or this year is not a leap year.
//
- [System.Runtime.InteropServices.ComVisible(false)]
public override int GetLeapMonth(int year, int era)
{
CheckYearRange(year, era);
diff --git a/src/mscorlib/src/System/Globalization/JapaneseCalendar.cs b/src/mscorlib/src/System/Globalization/JapaneseCalendar.cs
index 6b168ce916..72331f8346 100644
--- a/src/mscorlib/src/System/Globalization/JapaneseCalendar.cs
+++ b/src/mscorlib/src/System/Globalization/JapaneseCalendar.cs
@@ -8,8 +8,6 @@ namespace System.Globalization {
using System.Diagnostics.CodeAnalysis;
using System.Diagnostics.Contracts;
using Microsoft.Win32;
- using PermissionSet = System.Security.PermissionSet;
- using System.Security.Permissions;
/*=================================JapaneseCalendar==========================
**
@@ -41,13 +39,11 @@ namespace System.Globalization {
[Serializable]
-[System.Runtime.InteropServices.ComVisible(true)]
public class JapaneseCalendar : Calendar
{
internal static readonly DateTime calendarMinValue = new DateTime(1868, 9, 8);
- [System.Runtime.InteropServices.ComVisible(false)]
public override DateTime MinSupportedDateTime
{
get
@@ -56,7 +52,6 @@ namespace System.Globalization {
}
}
- [System.Runtime.InteropServices.ComVisible(false)]
public override DateTime MaxSupportedDateTime
{
get
@@ -68,7 +63,6 @@ namespace System.Globalization {
// Return the type of the Japanese calendar.
//
- [System.Runtime.InteropServices.ComVisible(false)]
public override CalendarAlgorithmType AlgorithmType
{
get
@@ -167,10 +161,6 @@ namespace System.Globalization {
try
{
- // Need to access registry
- PermissionSet permSet = new PermissionSet(PermissionState.None);
- permSet.AddPermission(new RegistryPermission(RegistryPermissionAccess.Read, c_japaneseErasHivePermissionList));
- permSet.Assert();
RegistryKey key = Registry.LocalMachine.OpenSubKey(c_japaneseErasHive, writable: false);
// Abort if we didn't find anything
@@ -311,7 +301,7 @@ namespace System.Globalization {
// Get Strings
//
// Needs to be a certain length e_a_E_A at least (7 chars, exactly 4 groups)
- String[] names = data.Split(new char[] {'_'});
+ String[] names = data.Split('_');
// Should have exactly 4 parts
// 0 - Era Name
@@ -425,7 +415,6 @@ namespace System.Globalization {
[SuppressMessage("Microsoft.Contracts", "CC1055")] // Skip extra error checking to avoid *potential* AppCompat problems.
- [System.Runtime.InteropServices.ComVisible(false)]
public override int GetWeekOfYear(DateTime time, CalendarWeekRule rule, DayOfWeek firstDayOfWeek)
{
return (helper.GetWeekOfYear(time, rule, firstDayOfWeek));
@@ -469,7 +458,6 @@ namespace System.Globalization {
// if this calendar does not have leap month, or this year is not a leap year.
//
- [System.Runtime.InteropServices.ComVisible(false)]
public override int GetLeapMonth(int year, int era)
{
return (helper.GetLeapMonth(year, era));
diff --git a/src/mscorlib/src/System/Globalization/JulianCalendar.cs b/src/mscorlib/src/System/Globalization/JulianCalendar.cs
index db286e0363..ff8801433c 100644
--- a/src/mscorlib/src/System/Globalization/JulianCalendar.cs
+++ b/src/mscorlib/src/System/Globalization/JulianCalendar.cs
@@ -18,7 +18,6 @@ namespace System.Globalization {
//* Julia 0001/01/03 9999/10/19
[Serializable]
-[System.Runtime.InteropServices.ComVisible(true)]
public class JulianCalendar : Calendar {
@@ -51,7 +50,6 @@ namespace System.Globalization {
internal int MaxYear = 9999;
- [System.Runtime.InteropServices.ComVisible(false)]
public override DateTime MinSupportedDateTime
{
get
@@ -60,7 +58,6 @@ namespace System.Globalization {
}
}
- [System.Runtime.InteropServices.ComVisible(false)]
public override DateTime MaxSupportedDateTime
{
get
@@ -72,7 +69,6 @@ namespace System.Globalization {
// Return the type of the Julian calendar.
//
- [System.Runtime.InteropServices.ComVisible(false)]
public override CalendarAlgorithmType AlgorithmType
{
get
@@ -344,7 +340,6 @@ namespace System.Globalization {
// if this calendar does not have leap month, or this year is not a leap year.
//
- [System.Runtime.InteropServices.ComVisible(false)]
public override int GetLeapMonth(int year, int era)
{
CheckYearEraRange(year, era);
diff --git a/src/mscorlib/src/System/Globalization/KoreanCalendar.cs b/src/mscorlib/src/System/Globalization/KoreanCalendar.cs
index dde82b6e6b..6c5a03b7e8 100644
--- a/src/mscorlib/src/System/Globalization/KoreanCalendar.cs
+++ b/src/mscorlib/src/System/Globalization/KoreanCalendar.cs
@@ -24,7 +24,6 @@ namespace System.Globalization {
============================================================================*/
-[System.Runtime.InteropServices.ComVisible(true)]
[Serializable] public class KoreanCalendar: Calendar {
//
// The era value for the current era.
@@ -49,7 +48,6 @@ namespace System.Globalization {
internal GregorianCalendarHelper helper;
- [System.Runtime.InteropServices.ComVisible(false)]
public override DateTime MinSupportedDateTime
{
get
@@ -58,7 +56,6 @@ namespace System.Globalization {
}
}
- [System.Runtime.InteropServices.ComVisible(false)]
public override DateTime MaxSupportedDateTime
{
get
@@ -70,7 +67,6 @@ namespace System.Globalization {
// Return the type of the Korean calendar.
//
- [System.Runtime.InteropServices.ComVisible(false)]
public override CalendarAlgorithmType AlgorithmType
{
get
@@ -165,7 +161,6 @@ namespace System.Globalization {
[SuppressMessage("Microsoft.Contracts", "CC1055")] // Skip extra error checking to avoid *potential* AppCompat problems.
- [System.Runtime.InteropServices.ComVisible(false)]
public override int GetWeekOfYear(DateTime time, CalendarWeekRule rule, DayOfWeek firstDayOfWeek)
{
return (helper.GetWeekOfYear(time, rule, firstDayOfWeek));
@@ -200,7 +195,6 @@ namespace System.Globalization {
// if this calendar does not have leap month, or this year is not a leap year.
//
- [System.Runtime.InteropServices.ComVisible(false)]
public override int GetLeapMonth(int year, int era)
{
return (helper.GetLeapMonth(year, era));
diff --git a/src/mscorlib/src/System/Globalization/NumberFormatInfo.cs b/src/mscorlib/src/System/Globalization/NumberFormatInfo.cs
index a5dce46aa4..d95aac3d3d 100644
--- a/src/mscorlib/src/System/Globalization/NumberFormatInfo.cs
+++ b/src/mscorlib/src/System/Globalization/NumberFormatInfo.cs
@@ -3,7 +3,6 @@
// See the LICENSE file in the project root for more information.
namespace System.Globalization {
- using System.Security.Permissions;
using System.Runtime.Serialization;
using System.Text;
using System;
@@ -41,7 +40,6 @@ namespace System.Globalization {
//
[Serializable]
-[System.Runtime.InteropServices.ComVisible(true)]
sealed public partial class NumberFormatInfo : ICloneable, IFormatProvider
{
// invariantInfo is constant irrespective of your current culture.
@@ -312,7 +310,7 @@ namespace System.Globalization {
get { return currencyDecimalSeparator; }
set {
VerifyWritable();
- VerifyDecimalSeparator(value, "CurrencyDecimalSeparator");
+ VerifyDecimalSeparator(value, nameof(CurrencyDecimalSeparator));
currencyDecimalSeparator = value;
}
}
@@ -361,7 +359,7 @@ namespace System.Globalization {
VerifyWritable();
Int32[] inputSizes = (Int32[])value.Clone();
- CheckGroupSize("CurrencyGroupSizes", inputSizes);
+ CheckGroupSize(nameof(CurrencyGroupSizes), inputSizes);
currencyGroupSizes = inputSizes;
}
@@ -382,7 +380,7 @@ namespace System.Globalization {
VerifyWritable();
Int32[] inputSizes = (Int32[])value.Clone();
- CheckGroupSize("NumberGroupSizes", inputSizes);
+ CheckGroupSize(nameof(NumberGroupSizes), inputSizes);
numberGroupSizes = inputSizes;
}
}
@@ -400,7 +398,7 @@ namespace System.Globalization {
Contract.EndContractBlock();
VerifyWritable();
Int32[] inputSizes = (Int32[])value.Clone();
- CheckGroupSize("PercentGroupSizes", inputSizes);
+ CheckGroupSize(nameof(PercentGroupSizes), inputSizes);
percentGroupSizes = inputSizes;
}
@@ -411,7 +409,7 @@ namespace System.Globalization {
get { return currencyGroupSeparator; }
set {
VerifyWritable();
- VerifyGroupSeparator(value, "CurrencyGroupSeparator");
+ VerifyGroupSeparator(value, nameof(CurrencyGroupSeparator));
currencyGroupSeparator = value;
}
}
@@ -602,7 +600,7 @@ namespace System.Globalization {
get { return numberDecimalSeparator; }
set {
VerifyWritable();
- VerifyDecimalSeparator(value, "NumberDecimalSeparator");
+ VerifyDecimalSeparator(value, nameof(NumberDecimalSeparator));
numberDecimalSeparator = value;
}
}
@@ -612,7 +610,7 @@ namespace System.Globalization {
get { return numberGroupSeparator; }
set {
VerifyWritable();
- VerifyGroupSeparator(value, "NumberGroupSeparator");
+ VerifyGroupSeparator(value, nameof(NumberGroupSeparator));
numberGroupSeparator = value;
}
}
@@ -690,7 +688,7 @@ namespace System.Globalization {
get { return percentDecimalSeparator; }
set {
VerifyWritable();
- VerifyDecimalSeparator(value, "PercentDecimalSeparator");
+ VerifyDecimalSeparator(value, nameof(PercentDecimalSeparator));
percentDecimalSeparator = value;
}
}
@@ -700,7 +698,7 @@ namespace System.Globalization {
get { return percentGroupSeparator; }
set {
VerifyWritable();
- VerifyGroupSeparator(value, "PercentGroupSeparator");
+ VerifyGroupSeparator(value, nameof(PercentGroupSeparator));
percentGroupSeparator = value;
}
}
@@ -736,26 +734,24 @@ namespace System.Globalization {
}
- [System.Runtime.InteropServices.ComVisible(false)]
public String[] NativeDigits
{
get { return (String[])nativeDigits.Clone(); }
set
{
VerifyWritable();
- VerifyNativeDigits(value, "NativeDigits");
+ VerifyNativeDigits(value, nameof(NativeDigits));
nativeDigits = value;
}
}
- [System.Runtime.InteropServices.ComVisible(false)]
public DigitShapes DigitSubstitution
{
get { return (DigitShapes)digitSubstitution; }
set
{
VerifyWritable();
- VerifyDigitSubstitution(value, "DigitSubstitution");
+ VerifyDigitSubstitution(value, nameof(DigitSubstitution));
digitSubstitution = (int)value;
}
}
diff --git a/src/mscorlib/src/System/Globalization/NumberStyles.cs b/src/mscorlib/src/System/Globalization/NumberStyles.cs
index 42b9847ed3..969c07fc2a 100644
--- a/src/mscorlib/src/System/Globalization/NumberStyles.cs
+++ b/src/mscorlib/src/System/Globalization/NumberStyles.cs
@@ -16,7 +16,6 @@ namespace System.Globalization {
using System;
[Serializable]
[Flags]
- [System.Runtime.InteropServices.ComVisible(true)]
public enum NumberStyles {
// Bit flag indicating that leading whitespace is allowed. Character values
// 0x0009, 0x000A, 0x000B, 0x000C, 0x000D, and 0x0020 are considered to be
diff --git a/src/mscorlib/src/System/Globalization/RegionInfo.cs b/src/mscorlib/src/System/Globalization/RegionInfo.cs
index 4bed87570f..b719af7128 100644
--- a/src/mscorlib/src/System/Globalization/RegionInfo.cs
+++ b/src/mscorlib/src/System/Globalization/RegionInfo.cs
@@ -23,7 +23,6 @@ namespace System.Globalization {
using System.Diagnostics.Contracts;
[Serializable]
- [System.Runtime.InteropServices.ComVisible(true)]
public partial class RegionInfo
{
//--------------------------------------------------------------------//
@@ -259,7 +258,6 @@ namespace System.Globalization {
// WARNING: You need a full locale name for this to make sense.
//
////////////////////////////////////////////////////////////////////////
- [System.Runtime.InteropServices.ComVisible(false)]
public virtual String NativeName
{
get
@@ -329,7 +327,6 @@ namespace System.Globalization {
}
- [System.Runtime.InteropServices.ComVisible(false)]
public virtual int GeoId
{
get
@@ -345,7 +342,6 @@ namespace System.Globalization {
// English name for this region's currency, ie: Swiss Franc
//
////////////////////////////////////////////////////////////////////////
- [System.Runtime.InteropServices.ComVisible(false)]
public virtual String CurrencyEnglishName
{
get
@@ -362,7 +358,6 @@ namespace System.Globalization {
// WARNING: You need a full locale name for this to make sense.
//
////////////////////////////////////////////////////////////////////////
- [System.Runtime.InteropServices.ComVisible(false)]
public virtual String CurrencyNativeName
{
get
diff --git a/src/mscorlib/src/System/Globalization/SortKey.cs b/src/mscorlib/src/System/Globalization/SortKey.cs
index 9c35f485e5..7c7408b009 100644
--- a/src/mscorlib/src/System/Globalization/SortKey.cs
+++ b/src/mscorlib/src/System/Globalization/SortKey.cs
@@ -19,7 +19,6 @@ namespace System.Globalization {
using System.Diagnostics;
using System.Diagnostics.Contracts;
- [System.Runtime.InteropServices.ComVisible(true)]
[Serializable]
public partial class SortKey
{
diff --git a/src/mscorlib/src/System/Globalization/StringInfo.cs b/src/mscorlib/src/System/Globalization/StringInfo.cs
index d86e11592e..dc32fe9493 100644
--- a/src/mscorlib/src/System/Globalization/StringInfo.cs
+++ b/src/mscorlib/src/System/Globalization/StringInfo.cs
@@ -16,12 +16,10 @@ namespace System.Globalization {
using System;
using System.Runtime.Serialization;
- using System.Security.Permissions;
using System.Diagnostics;
using System.Diagnostics.Contracts;
[Serializable]
- [System.Runtime.InteropServices.ComVisible(true)]
public class StringInfo
{
@@ -57,7 +55,6 @@ namespace System.Globalization {
}
#endregion Serialization
- [System.Runtime.InteropServices.ComVisible(false)]
public override bool Equals(Object value)
{
StringInfo that = value as StringInfo;
@@ -68,7 +65,6 @@ namespace System.Globalization {
return (false);
}
- [System.Runtime.InteropServices.ComVisible(false)]
public override int GetHashCode()
{
return this.m_str.GetHashCode();
diff --git a/src/mscorlib/src/System/Globalization/TaiwanCalendar.cs b/src/mscorlib/src/System/Globalization/TaiwanCalendar.cs
index 476ddeef7c..ec84a06b76 100644
--- a/src/mscorlib/src/System/Globalization/TaiwanCalendar.cs
+++ b/src/mscorlib/src/System/Globalization/TaiwanCalendar.cs
@@ -22,7 +22,6 @@ namespace System.Globalization {
============================================================================*/
/* SSS_WARNINGS_ON */ /* SSS_DROP_END */
- [System.Runtime.InteropServices.ComVisible(true)]
[Serializable] public class TaiwanCalendar: Calendar {
//
// The era value for the current era.
@@ -62,7 +61,6 @@ namespace System.Globalization {
internal static readonly DateTime calendarMinValue = new DateTime(1912, 1, 1);
- [System.Runtime.InteropServices.ComVisible(false)]
public override DateTime MinSupportedDateTime
{
get
@@ -71,7 +69,6 @@ namespace System.Globalization {
}
}
- [System.Runtime.InteropServices.ComVisible(false)]
public override DateTime MaxSupportedDateTime
{
get
@@ -83,7 +80,6 @@ namespace System.Globalization {
// Return the type of the Taiwan calendar.
//
- [System.Runtime.InteropServices.ComVisible(false)]
public override CalendarAlgorithmType AlgorithmType
{
get
@@ -151,7 +147,6 @@ namespace System.Globalization {
[SuppressMessage("Microsoft.Contracts", "CC1055")] // Skip extra error checking to avoid *potential* AppCompat problems.
- [System.Runtime.InteropServices.ComVisible(false)]
public override int GetWeekOfYear(DateTime time, CalendarWeekRule rule, DayOfWeek firstDayOfWeek)
{
return (helper.GetWeekOfYear(time, rule, firstDayOfWeek));
@@ -186,7 +181,6 @@ namespace System.Globalization {
// if this calendar does not have leap month, or this year is not a leap year.
//
- [System.Runtime.InteropServices.ComVisible(false)]
public override int GetLeapMonth(int year, int era)
{
return (helper.GetLeapMonth(year, era));
diff --git a/src/mscorlib/src/System/Globalization/TextElementEnumerator.cs b/src/mscorlib/src/System/Globalization/TextElementEnumerator.cs
index 049ccf6f81..0fee7a0745 100644
--- a/src/mscorlib/src/System/Globalization/TextElementEnumerator.cs
+++ b/src/mscorlib/src/System/Globalization/TextElementEnumerator.cs
@@ -23,7 +23,6 @@ namespace System.Globalization {
//
[Serializable]
- [System.Runtime.InteropServices.ComVisible(true)]
public class TextElementEnumerator: IEnumerator
{
private String str;
diff --git a/src/mscorlib/src/System/Globalization/TextInfo.cs b/src/mscorlib/src/System/Globalization/TextInfo.cs
index c8108e4922..9ece275dd3 100644
--- a/src/mscorlib/src/System/Globalization/TextInfo.cs
+++ b/src/mscorlib/src/System/Globalization/TextInfo.cs
@@ -23,13 +23,11 @@ namespace System.Globalization {
using System.Runtime.CompilerServices;
using System.Runtime.Serialization;
using System.Runtime.Versioning;
- using System.Security.Permissions;
using System.Diagnostics;
using System.Diagnostics.Contracts;
[Serializable]
- [System.Runtime.InteropServices.ComVisible(true)]
public partial class TextInfo : ICloneable, IDeserializationCallback
{
//--------------------------------------------------------------------//
@@ -378,7 +376,6 @@ namespace System.Globalization {
////////////////////////////////////////////////////////////////////////
#if FEATURE_USE_LCID
- [System.Runtime.InteropServices.ComVisible(false)]
public int LCID
{
get
@@ -395,7 +392,6 @@ namespace System.Globalization {
// The name of the culture associated with the current TextInfo.
//
////////////////////////////////////////////////////////////////////////
- [System.Runtime.InteropServices.ComVisible(false)]
public string CultureName
{
get
@@ -411,7 +407,6 @@ namespace System.Globalization {
// Detect if the object is readonly.
//
////////////////////////////////////////////////////////////////////////
- [System.Runtime.InteropServices.ComVisible(false)]
public bool IsReadOnly
{
get { return (m_isReadOnly); }
@@ -424,7 +419,6 @@ namespace System.Globalization {
// Is the implementation of ICloneable.
//
////////////////////////////////////////////////////////////////////////
- [System.Runtime.InteropServices.ComVisible(false)]
public virtual Object Clone()
{
object o = MemberwiseClone();
@@ -440,7 +434,6 @@ namespace System.Globalization {
// readonly.
//
////////////////////////////////////////////////////////////////////////
- [System.Runtime.InteropServices.ComVisible(false)]
public static TextInfo ReadOnly(TextInfo textInfo)
{
if (textInfo == null) { throw new ArgumentNullException(nameof(textInfo)); }
@@ -487,7 +480,6 @@ namespace System.Globalization {
return (m_listSeparator);
}
- [System.Runtime.InteropServices.ComVisible(false)]
set
{
if (value == null)
@@ -901,7 +893,6 @@ namespace System.Globalization {
//
// Returns true if the dominant direction of text and UI such as the relative position of buttons and scroll bars
//
- [System.Runtime.InteropServices.ComVisible(false)]
public bool IsRightToLeft
{
get
diff --git a/src/mscorlib/src/System/Globalization/ThaiBuddhistCalendar.cs b/src/mscorlib/src/System/Globalization/ThaiBuddhistCalendar.cs
index e294b51325..762c3ca7cb 100644
--- a/src/mscorlib/src/System/Globalization/ThaiBuddhistCalendar.cs
+++ b/src/mscorlib/src/System/Globalization/ThaiBuddhistCalendar.cs
@@ -21,7 +21,6 @@ namespace System.Globalization {
============================================================================*/
-[System.Runtime.InteropServices.ComVisible(true)]
[Serializable] public class ThaiBuddhistCalendar: Calendar {
// Initialize our era info.
@@ -40,7 +39,6 @@ namespace System.Globalization {
internal GregorianCalendarHelper helper;
- [System.Runtime.InteropServices.ComVisible(false)]
public override DateTime MinSupportedDateTime
{
get
@@ -49,7 +47,6 @@ namespace System.Globalization {
}
}
- [System.Runtime.InteropServices.ComVisible(false)]
public override DateTime MaxSupportedDateTime
{
get
@@ -61,7 +58,6 @@ namespace System.Globalization {
// Return the type of the Thai Buddhist calendar.
//
- [System.Runtime.InteropServices.ComVisible(false)]
public override CalendarAlgorithmType AlgorithmType
{
get
@@ -123,7 +119,6 @@ namespace System.Globalization {
[SuppressMessage("Microsoft.Contracts", "CC1055")] // Skip extra error checking to avoid *potential* AppCompat problems.
- [System.Runtime.InteropServices.ComVisible(false)]
public override int GetWeekOfYear(DateTime time, CalendarWeekRule rule, DayOfWeek firstDayOfWeek)
{
return (helper.GetWeekOfYear(time, rule, firstDayOfWeek));
@@ -158,7 +153,6 @@ namespace System.Globalization {
// if this calendar does not have leap month, or this year is not a leap year.
//
- [System.Runtime.InteropServices.ComVisible(false)]
public override int GetLeapMonth(int year, int era)
{
return (helper.GetLeapMonth(year, era));
diff --git a/src/mscorlib/src/System/Globalization/UnicodeCategory.cs b/src/mscorlib/src/System/Globalization/UnicodeCategory.cs
index 3848b6142f..c9898f135b 100644
--- a/src/mscorlib/src/System/Globalization/UnicodeCategory.cs
+++ b/src/mscorlib/src/System/Globalization/UnicodeCategory.cs
@@ -13,7 +13,6 @@
namespace System.Globalization {
[Serializable]
-[System.Runtime.InteropServices.ComVisible(true)]
public enum UnicodeCategory {
UppercaseLetter = 0,
diff --git a/src/mscorlib/src/System/Guid.cs b/src/mscorlib/src/System/Guid.cs
index e2e36ba1b2..1116faf027 100644
--- a/src/mscorlib/src/System/Guid.cs
+++ b/src/mscorlib/src/System/Guid.cs
@@ -16,7 +16,6 @@ namespace System {
// Represents a Globally Unique Identifier.
[StructLayout(LayoutKind.Sequential)]
[Serializable]
-[System.Runtime.InteropServices.ComVisible(true)]
[System.Runtime.Versioning.NonVersionable] // This only applies to field layout
public struct Guid : IFormattable, IComparable
, IComparable<Guid>, IEquatable<Guid>
@@ -756,11 +755,6 @@ namespace System {
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);
}
- 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);
- }
- }
private static unsafe bool StringToShort(String str, int* parsePos, int requiredLength, int flags, out short result, ref GuidResult parseResult) {
result = 0;
int x;
@@ -813,9 +807,6 @@ namespace System {
}
return true;
}
- private static unsafe bool StringToLong(String str, int flags, out long result, ref GuidResult parseResult) {
- return StringToLong(str, null, flags, out result, ref parseResult);
- }
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);
diff --git a/src/mscorlib/src/System/IAppDomain.cs b/src/mscorlib/src/System/IAppDomain.cs
deleted file mode 100644
index cdb83166c8..0000000000
--- a/src/mscorlib/src/System/IAppDomain.cs
+++ /dev/null
@@ -1,28 +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.
-
-/*============================================================
-**
-** Interface: IAppDomain
-**
-**
-**
-**
-** Purpose: Properties and methods exposed to COM
-**
-**
-===========================================================*/
-namespace System
-{
- using System.Runtime.InteropServices;
-
- [GuidAttribute("05F696DC-2B29-3663-AD8B-C4389CF2A713")]
- [InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)]
- [CLSCompliant(false)]
- [System.Runtime.InteropServices.ComVisible(true)]
- public interface _AppDomain
- {
- }
-}
-
diff --git a/src/mscorlib/src/System/IAppDomainPauseManager.cs b/src/mscorlib/src/System/IAppDomainPauseManager.cs
index 902a79bd2a..cd3a9033de 100644
--- a/src/mscorlib/src/System/IAppDomainPauseManager.cs
+++ b/src/mscorlib/src/System/IAppDomainPauseManager.cs
@@ -32,46 +32,6 @@ namespace System
}
static readonly AppDomainPauseManager instance = new AppDomainPauseManager();
- internal static AppDomainPauseManager Instance
- {
- 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
- public void Pausing()
- {
- }
-
- public void Paused()
- {
- Debug.Assert(!isPaused);
-
- if(ResumeEvent == null)
- ResumeEvent = new ManualResetEvent(false);
- else
- ResumeEvent.Reset();
-
- Timer.Pause();
-
- // Set IsPaused at the last as other threads seeing it set, will expect a valid
- // reset ResumeEvent. Also the requirement here is that only after Paused
- // returns other threads should block on this event. So there is a race condition here.
- isPaused = true;
- }
-
- public void Resuming()
- {
- Debug.Assert(isPaused);
- isPaused = false;
- ResumeEvent.Set();
- }
-
- public void Resumed()
- {
- Timer.Resume();
- }
private static volatile bool isPaused;
diff --git a/src/mscorlib/src/System/IAppDomainSetup.cs b/src/mscorlib/src/System/IAppDomainSetup.cs
deleted file mode 100644
index a088c629d8..0000000000
--- a/src/mscorlib/src/System/IAppDomainSetup.cs
+++ /dev/null
@@ -1,84 +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.
-
-/*============================================================
-**
-** Interface: IAppDomainSetup
-**
-**
-**
-**
-** Purpose: Properties exposed to COM
-**
-**
-===========================================================*/
-namespace System {
-
- using System.Runtime.InteropServices;
-
- [GuidAttribute("27FFF232-A7A8-40dd-8D4A-734AD59FCD41")]
- [InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)]
-[System.Runtime.InteropServices.ComVisible(true)]
- public interface IAppDomainSetup
- {
- String ApplicationBase {
- get;
- set;
- }
-
- String ApplicationName
- {
- get;
- set;
- }
-
- String CachePath
- {
- get;
- set;
- }
-
- String ConfigurationFile {
- get;
- set;
- }
-
- String DynamicBase
- {
- get;
- set;
- }
-
- String LicenseFile
- {
- get;
- set;
- }
-
- String PrivateBinPath
- {
- get;
- set;
- }
-
- String PrivateBinPathProbe
- {
- get;
- set;
- }
-
- String ShadowCopyDirectories
- {
- get;
- set;
- }
-
- String ShadowCopyFiles
- {
- get;
- set;
- }
-
- }
-}
diff --git a/src/mscorlib/src/System/IAsyncResult.cs b/src/mscorlib/src/System/IAsyncResult.cs
index 2591c726c7..0abeaca525 100644
--- a/src/mscorlib/src/System/IAsyncResult.cs
+++ b/src/mscorlib/src/System/IAsyncResult.cs
@@ -10,11 +10,12 @@
** operation
**
===========================================================*/
-namespace System {
-
- using System;
- using System.Threading;
-[System.Runtime.InteropServices.ComVisible(true)]
+
+using System;
+using System.Threading;
+
+namespace System
+{
public interface IAsyncResult
{
bool IsCompleted { get; }
@@ -22,11 +23,8 @@ namespace System {
WaitHandle AsyncWaitHandle { get; }
- Object AsyncState { get; }
+ Object AsyncState { get; }
- bool CompletedSynchronously { get; }
-
-
+ bool CompletedSynchronously { get; }
}
-
}
diff --git a/src/mscorlib/src/System/ICloneable.cs b/src/mscorlib/src/System/ICloneable.cs
index 2931802539..49657c2765 100644
--- a/src/mscorlib/src/System/ICloneable.cs
+++ b/src/mscorlib/src/System/ICloneable.cs
@@ -16,7 +16,6 @@ namespace System {
// method which is called to create a clone of the object. Object defines a method
// MemberwiseClone to support default clone operations.
//
- [System.Runtime.InteropServices.ComVisible(true)]
public interface ICloneable
{
// Interface does not need to be marked with the serializable attribute
diff --git a/src/mscorlib/src/System/IComparable.cs b/src/mscorlib/src/System/IComparable.cs
index 111d892129..72aeeb027c 100644
--- a/src/mscorlib/src/System/IComparable.cs
+++ b/src/mscorlib/src/System/IComparable.cs
@@ -2,18 +2,16 @@
// 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;
+namespace System
+{
// The IComparable interface is implemented by classes that support an
// ordering of instances of the class. The ordering represented by
// IComparable can be used to sort arrays and collections of objects
// that implement the interface.
//
-[System.Runtime.InteropServices.ComVisible(true)]
public interface IComparable
{
- // Interface does not need to be marked with the serializable attribute
+ // Interface does not need to be marked with the serializable attribute
// Compares this object to another object, returning an integer that
// indicates the relationship. An implementation of this method must return
// a value less than zero if this is less than object, zero
diff --git a/src/mscorlib/src/System/IConvertible.cs b/src/mscorlib/src/System/IConvertible.cs
index 174b25b180..87351127f2 100644
--- a/src/mscorlib/src/System/IConvertible.cs
+++ b/src/mscorlib/src/System/IConvertible.cs
@@ -2,15 +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 {
-
- using System.Diagnostics.Contracts;
- using System.Threading;
-
+namespace System
+{
// The IConvertible interface represents an object that contains a value. This
// interface is implemented by the following types in the System namespace:
// Boolean, Char, SByte, Byte, Int16, UInt16, Int32, UInt32, Int64, UInt64,
- // Single, Double, Decimal, DateTime, TimeSpan, and String. The interface may
+ // Single, Double, Decimal, DateTime, and String. The interface may
// be implemented by other types that are to be considered values. For example,
// a library of nullable database types could implement IConvertible.
//
@@ -23,7 +20,6 @@ namespace System {
// IConvertible implementation should simply throw an InvalidCastException.
[CLSCompliant(false)]
- [System.Runtime.InteropServices.ComVisible(true)]
public interface IConvertible
{
// Returns the type code of this object. An implementation of this method
diff --git a/src/mscorlib/src/System/ICustomFormatter.cs b/src/mscorlib/src/System/ICustomFormatter.cs
index cbc3816a82..47340f3093 100644
--- a/src/mscorlib/src/System/ICustomFormatter.cs
+++ b/src/mscorlib/src/System/ICustomFormatter.cs
@@ -11,15 +11,14 @@
**
**
===========================================================*/
-namespace System {
-
- using System;
- using System.Runtime.Serialization;
- [System.Runtime.InteropServices.ComVisible(true)]
+using System;
+
+namespace System
+{
public interface ICustomFormatter
{
// Interface does not need to be marked with the serializable attribute
- String Format (String format, Object arg, IFormatProvider formatProvider);
+ String Format(String format, Object arg, IFormatProvider formatProvider);
}
}
diff --git a/src/mscorlib/src/System/IDisposable.cs b/src/mscorlib/src/System/IDisposable.cs
index fcb65bea14..24f0740edc 100644
--- a/src/mscorlib/src/System/IDisposable.cs
+++ b/src/mscorlib/src/System/IDisposable.cs
@@ -11,7 +11,9 @@
**
**
===========================================================*/
-namespace System {
+
+namespace System
+{
// IDisposable is an attempt at helping to solve problems with deterministic
// finalization. The GC of course doesn't leave any way to deterministically
// know when a finalizer will run. This forces classes that hold onto OS
@@ -51,8 +53,8 @@ namespace System {
// data buffered by the StreamWriter cannot be written to the Stream. In this
// case, it doesn't make much sense to provide a finalizer on the StreamWriter
// since you cannot solve this problem correctly.
-[System.Runtime.InteropServices.ComVisible(true)]
- public interface IDisposable {
+ public interface IDisposable
+ {
void Dispose();
}
}
diff --git a/src/mscorlib/src/System/IEquatable.cs b/src/mscorlib/src/System/IEquatable.cs
index aa034da68c..1264fdd57a 100644
--- a/src/mscorlib/src/System/IEquatable.cs
+++ b/src/mscorlib/src/System/IEquatable.cs
@@ -2,13 +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 {
-
- using System;
+using System;
+
+namespace System
+{
public interface IEquatable<T>
{
bool Equals(T other);
}
-
}
diff --git a/src/mscorlib/src/System/IFormatProvider.cs b/src/mscorlib/src/System/IFormatProvider.cs
index a5cc783969..0c17354af3 100644
--- a/src/mscorlib/src/System/IFormatProvider.cs
+++ b/src/mscorlib/src/System/IFormatProvider.cs
@@ -10,11 +10,11 @@
**
**
============================================================*/
-namespace System {
-
- using System;
- [System.Runtime.InteropServices.ComVisible(true)]
+using System;
+
+namespace System
+{
public interface IFormatProvider
{
// Interface does not need to be marked with the serializable attribute
diff --git a/src/mscorlib/src/System/IFormattable.cs b/src/mscorlib/src/System/IFormattable.cs
index 414b4686df..28a7d70571 100644
--- a/src/mscorlib/src/System/IFormattable.cs
+++ b/src/mscorlib/src/System/IFormattable.cs
@@ -2,12 +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 {
-
- using System;
- using System.Diagnostics.Contracts;
+using System;
+using System.Diagnostics.Contracts;
- [System.Runtime.InteropServices.ComVisible(true)]
+namespace System
+{
public interface IFormattable
{
[Pure]
diff --git a/src/mscorlib/src/System/IO/BinaryReader.cs b/src/mscorlib/src/System/IO/BinaryReader.cs
index 4145a7f4f6..d973860472 100644
--- a/src/mscorlib/src/System/IO/BinaryReader.cs
+++ b/src/mscorlib/src/System/IO/BinaryReader.cs
@@ -23,7 +23,6 @@ namespace System.IO {
using System.Diagnostics.Contracts;
using System.Security;
-[System.Runtime.InteropServices.ComVisible(true)]
public class BinaryReader : IDisposable
{
private const int MaxCharBytesSize = 128;
diff --git a/src/mscorlib/src/System/IO/BinaryWriter.cs b/src/mscorlib/src/System/IO/BinaryWriter.cs
index f99b4d3d42..b6c562534c 100644
--- a/src/mscorlib/src/System/IO/BinaryWriter.cs
+++ b/src/mscorlib/src/System/IO/BinaryWriter.cs
@@ -26,7 +26,6 @@ namespace System.IO {
// give unique encodings.
//
[Serializable]
- [System.Runtime.InteropServices.ComVisible(true)]
public class BinaryWriter : IDisposable
{
public static readonly BinaryWriter Null = new BinaryWriter();
@@ -185,7 +184,7 @@ namespace System.IO {
Debug.Assert(_encoding.GetMaxByteCount(1) <= 16, "_encoding.GetMaxByteCount(1) <= 16)");
int numBytes = 0;
- fixed(byte * pBytes = _buffer) {
+ fixed(byte * pBytes = &_buffer[0]) {
numBytes = _encoder.GetBytes(&ch, 1, pBytes, _buffer.Length, flush: true);
}
OutStream.Write(_buffer, 0, numBytes);
@@ -382,7 +381,7 @@ namespace System.IO {
}
fixed (char* pChars = value)
{
- fixed (byte* pBytes = _largeByteBuffer)
+ fixed (byte* pBytes = &_largeByteBuffer[0])
{
byteLen = _encoder.GetBytes(pChars + charStart, charCount, pBytes, _largeByteBuffer.Length, charCount == numLeft);
}
diff --git a/src/mscorlib/src/System/IO/Directory.cs b/src/mscorlib/src/System/IO/Directory.cs
index d6b68222cd..88a669a971 100644
--- a/src/mscorlib/src/System/IO/Directory.cs
+++ b/src/mscorlib/src/System/IO/Directory.cs
@@ -17,7 +17,6 @@
using System.Collections.Generic;
using System.Security;
-using System.Security.Permissions;
using Microsoft.Win32;
using Microsoft.Win32.SafeHandles;
using System.Runtime.InteropServices;
@@ -26,404 +25,7 @@ using System.Diagnostics.Contracts;
namespace System.IO
{
- [ComVisible(true)]
- public static class Directory {
- public static DirectoryInfo GetParent(String path)
- {
- if (path==null)
- throw new ArgumentNullException(nameof(path));
-
- if (path.Length==0)
- throw new ArgumentException(Environment.GetResourceString("Argument_PathEmpty"), nameof(path));
- Contract.EndContractBlock();
-
- string fullPath = Path.GetFullPath(path);
-
- string s = Path.GetDirectoryName(fullPath);
- if (s==null)
- return null;
- return new DirectoryInfo(s);
- }
-
- public static DirectoryInfo CreateDirectory(String path) {
- if (path == null)
- throw new ArgumentNullException(nameof(path));
- if (path.Length == 0)
- throw new ArgumentException(Environment.GetResourceString("Argument_PathEmpty"));
- Contract.EndContractBlock();
-
- return InternalCreateDirectoryHelper(path);
- }
-
- internal static DirectoryInfo InternalCreateDirectoryHelper(String path)
- {
- Contract.Requires(path != null);
- Contract.Requires(path.Length != 0);
-
- String fullPath = Path.GetFullPath(path);
-
- InternalCreateDirectory(fullPath, path, null);
-
- return new DirectoryInfo(fullPath, false);
- }
-
- internal unsafe static void InternalCreateDirectory(String fullPath, String path, Object dirSecurityObj)
- {
- 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 && PathInternal.IsDirectorySeparator(fullPath[length - 1]))
- length--;
-
- int lengthRoot = PathInternal.GetRootLength(fullPath);
-
- // For UNC paths that are only // or ///
- 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
- // saves us in the case where sub paths are inaccessible (due to ERROR_ACCESS_DENIED) but the
- // final path is accessable and the directory already exists. For example, consider trying
- // to create c:\Foo\Bar\Baz, where everything already exists but ACLS prevent access to c:\Foo
- // and c:\Foo\Bar. In that case, this code will think it needs to create c:\Foo, and c:\Foo\Bar
- // and fail to due so, causing an exception to be thrown. This is not what we want.
- if (InternalExists(fullPath)) {
- return;
- }
-
- List<string> stackDir = new List<string>();
-
- // Attempt to figure out which directories don't exist, and only
- // create the ones we need. Note that InternalExists may fail due
- // to Win32 ACL's preventing us from seeing a directory, and this
- // isn't threadsafe.
-
- bool somepathexists = false;
-
- if (length > lengthRoot) { // Special case root (fullpath = X:\\)
- int i = length-1;
- while (i >= lengthRoot && !somepathexists) {
- String dir = fullPath.Substring(0, i+1);
-
- if (!InternalExists(dir)) // Create only the ones missing
- stackDir.Add(dir);
- else
- somepathexists = true;
-
- while (i > lengthRoot && fullPath[i] != Path.DirectorySeparatorChar && fullPath[i] != Path.AltDirectorySeparatorChar) i--;
- i--;
- }
- }
-
- int count = stackDir.Count;
-
- // 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;
-
- bool r = true;
- int firstError = 0;
- String errorString = path;
- // If all the security checks succeeded create all the directories
- while (stackDir.Count > 0) {
- String name = stackDir[stackDir.Count - 1];
- stackDir.RemoveAt(stackDir.Count - 1);
- if (PathInternal.IsDirectoryTooLong(name))
- throw new PathTooLongException(Environment.GetResourceString("IO.PathTooLong"));
- r = Win32Native.CreateDirectory(name, secAttrs);
- if (!r && (firstError == 0)) {
- int currentError = Marshal.GetLastWin32Error();
- // While we tried to avoid creating directories that don't
- // exist above, there are at least two cases that will
- // cause us to see ERROR_ALREADY_EXISTS here. InternalExists
- // can fail because we didn't have permission to the
- // directory. Secondly, another thread or process could
- // create the directory between the time we check and the
- // time we try using the directory. Thirdly, it could
- // fail because the target does exist, but is a file.
- if (currentError != Win32Native.ERROR_ALREADY_EXISTS)
- 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))
- {
- firstError = currentError;
- errorString = name;
- }
- }
- }
- }
-
- // We need this check to mask OS differences
- // Handle CreateDirectory("X:\\foo") when X: doesn't exist. Similarly for n/w paths.
- if ((count == 0) && !somepathexists) {
- String root = InternalGetDirectoryRoot(fullPath);
- if (!InternalExists(root)) {
- // Extract the root from the passed in path again for security.
- __Error.WinIOError(Win32Native.ERROR_PATH_NOT_FOUND, InternalGetDirectoryRoot(path));
- }
- return;
- }
-
- // Only throw an exception if creating the exact directory we
- // wanted failed to work correctly.
- if (!r && (firstError != 0)) {
- __Error.WinIOError(firstError, errorString);
- }
- }
-
-
- // Tests if the given path refers to an existing DirectoryInfo on disk.
- //
- // Your application must have Read permission to the directory's
- // contents.
- //
- public static bool Exists(String path)
- {
- return InternalExistsHelper(path);
- }
-
- internal static bool InternalExistsHelper(String path) {
- try
- {
- if (path == null)
- return false;
- if (path.Length == 0)
- return false;
-
- return InternalExists(Path.GetFullPath(path));
- }
- catch (ArgumentException) { }
- catch (NotSupportedException) { } // Security can throw this on ":"
- catch (SecurityException) { }
- catch (IOException) { }
- catch (UnauthorizedAccessException)
- {
- 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.
- internal static bool InternalExists(String path) {
- int lastError = Win32Native.ERROR_SUCCESS;
- return InternalExists(path, out lastError);
- }
-
- // Determine whether path describes an existing directory
- // on disk, avoiding security checks.
- 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);
-
- return (lastError == 0) && (data.fileAttributes != -1)
- && ((data.fileAttributes & Win32Native.FILE_ATTRIBUTE_DIRECTORY) != 0);
- }
-
- public static DateTime GetCreationTime(String path)
- {
- return File.GetCreationTime(path);
- }
-
- public static DateTime GetCreationTimeUtc(String path)
- {
- return File.GetCreationTimeUtc(path);
- }
-
- public static DateTime GetLastWriteTime(String path)
- {
- return File.GetLastWriteTime(path);
- }
-
- public static DateTime GetLastWriteTimeUtc(String path)
- {
- return File.GetLastWriteTimeUtc(path);
- }
-
- public static DateTime GetLastAccessTime(String path)
- {
- return File.GetLastAccessTime(path);
- }
-
- public static DateTime GetLastAccessTimeUtc(String path)
- {
- return File.GetLastAccessTimeUtc(path);
- }
-
- // Returns an array of filenames in the DirectoryInfo specified by path
- public static String[] GetFiles(String path)
- {
- if (path == null)
- throw new ArgumentNullException(nameof(path));
- Contract.Ensures(Contract.Result<String[]>() != null);
- Contract.EndContractBlock();
-
- return InternalGetFiles(path, "*", SearchOption.TopDirectoryOnly);
- }
-
- // Returns an array of Files in the current DirectoryInfo matching the
- // given search pattern (ie, "*.txt").
- public static String[] GetFiles(String path, String searchPattern)
- {
- if (path == null)
- throw new ArgumentNullException(nameof(path));
- if (searchPattern == null)
- throw new ArgumentNullException(nameof(searchPattern));
- Contract.Ensures(Contract.Result<String[]>() != null);
- Contract.EndContractBlock();
-
- return InternalGetFiles(path, searchPattern, SearchOption.TopDirectoryOnly);
- }
-
- // Returns an array of Files in the current DirectoryInfo matching the
- // given search pattern (ie, "*.txt") and search option
- public static String[] GetFiles(String path, String searchPattern, SearchOption searchOption)
- {
- if (path == null)
- throw new ArgumentNullException(nameof(path));
- if (searchPattern == null)
- throw new ArgumentNullException(nameof(searchPattern));
- if ((searchOption != SearchOption.TopDirectoryOnly) && (searchOption != SearchOption.AllDirectories))
- throw new ArgumentOutOfRangeException(nameof(searchOption), Environment.GetResourceString("ArgumentOutOfRange_Enum"));
- Contract.Ensures(Contract.Result<String[]>() != null);
- Contract.EndContractBlock();
-
- return InternalGetFiles(path, searchPattern, searchOption);
- }
-
- // Returns an array of Files in the current DirectoryInfo matching the
- // given search pattern (ie, "*.txt") and search option
- private static String[] InternalGetFiles(String path, String searchPattern, SearchOption searchOption)
- {
- Contract.Requires(path != null);
- Contract.Requires(searchPattern != null);
- Contract.Requires(searchOption == SearchOption.AllDirectories || searchOption == SearchOption.TopDirectoryOnly);
-
- return InternalGetFileDirectoryNames(path, path, searchPattern, true, false, searchOption, true);
- }
-
- internal static String[] UnsafeGetFiles(String path, String searchPattern, SearchOption searchOption)
- {
- Contract.Requires(path != null);
- Contract.Requires(searchPattern != null);
- Contract.Requires(searchOption == SearchOption.AllDirectories || searchOption == SearchOption.TopDirectoryOnly);
-
- return InternalGetFileDirectoryNames(path, path, searchPattern, true, false, searchOption, false);
- }
-
- // Returns an array of Directories in the current directory.
- public static String[] GetDirectories(String path)
- {
- if (path == null)
- throw new ArgumentNullException(nameof(path));
- Contract.Ensures(Contract.Result<String[]>() != null);
- Contract.EndContractBlock();
-
- return InternalGetDirectories(path, "*", SearchOption.TopDirectoryOnly);
- }
-
- // Returns an array of Directories in the current DirectoryInfo matching the
- // given search criteria (ie, "*.txt").
- public static String[] GetDirectories(String path, String searchPattern)
- {
- if (path == null)
- throw new ArgumentNullException(nameof(path));
- if (searchPattern == null)
- throw new ArgumentNullException(nameof(searchPattern));
- Contract.Ensures(Contract.Result<String[]>() != null);
- Contract.EndContractBlock();
-
- return InternalGetDirectories(path, searchPattern, SearchOption.TopDirectoryOnly);
- }
-
- // Returns an array of Directories in the current DirectoryInfo matching the
- // given search criteria (ie, "*.txt").
- public static String[] GetDirectories(String path, String searchPattern, SearchOption searchOption)
- {
- if (path == null)
- throw new ArgumentNullException(nameof(path));
- if (searchPattern == null)
- throw new ArgumentNullException(nameof(searchPattern));
- if ((searchOption != SearchOption.TopDirectoryOnly) && (searchOption != SearchOption.AllDirectories))
- throw new ArgumentOutOfRangeException(nameof(searchOption), Environment.GetResourceString("ArgumentOutOfRange_Enum"));
- Contract.Ensures(Contract.Result<String[]>() != null);
- Contract.EndContractBlock();
-
- return InternalGetDirectories(path, searchPattern, searchOption);
- }
-
- // Returns an array of Directories in the current DirectoryInfo matching the
- // given search criteria (ie, "*.txt").
- private static String[] InternalGetDirectories(String path, String searchPattern, SearchOption searchOption)
- {
- Contract.Requires(path != null);
- Contract.Requires(searchPattern != null);
- Contract.Requires(searchOption == SearchOption.AllDirectories || searchOption == SearchOption.TopDirectoryOnly);
- Contract.Ensures(Contract.Result<String[]>() != null);
-
- return InternalGetFileDirectoryNames(path, path, searchPattern, false, true, searchOption, true);
- }
-
- internal static String[] UnsafeGetDirectories(String path, String searchPattern, SearchOption searchOption)
- {
- Contract.Requires(path != null);
- Contract.Requires(searchPattern != null);
- Contract.Requires(searchOption == SearchOption.AllDirectories || searchOption == SearchOption.TopDirectoryOnly);
- Contract.Ensures(Contract.Result<String[]>() != null);
-
- return InternalGetFileDirectoryNames(path, path, searchPattern, false, true, searchOption, false);
- }
-
- // Returns an array of strongly typed FileSystemInfo entries in the path
- public static String[] GetFileSystemEntries(String path)
- {
- if (path == null)
- throw new ArgumentNullException(nameof(path));
- Contract.Ensures(Contract.Result<String[]>() != null);
- Contract.EndContractBlock();
-
- return InternalGetFileSystemEntries(path, "*", SearchOption.TopDirectoryOnly);
- }
-
- // Returns an array of strongly typed FileSystemInfo entries in the path with the
- // given search criteria (ie, "*.txt"). We disallow .. as a part of the search criteria
- public static String[] GetFileSystemEntries(String path, String searchPattern)
- {
- if (path == null)
- throw new ArgumentNullException(nameof(path));
- if (searchPattern == null)
- throw new ArgumentNullException(nameof(searchPattern));
- Contract.Ensures(Contract.Result<String[]>() != null);
- Contract.EndContractBlock();
-
- return InternalGetFileSystemEntries(path, searchPattern, SearchOption.TopDirectoryOnly);
- }
-
- // Returns an array of strongly typed FileSystemInfo entries in the path with the
- // given search criteria (ie, "*.txt"). We disallow .. as a part of the search criteria
- public static String[] GetFileSystemEntries(String path, String searchPattern, SearchOption searchOption)
- {
- if (path == null)
- throw new ArgumentNullException(nameof(path));
- if (searchPattern == null)
- throw new ArgumentNullException(nameof(searchPattern));
- if ((searchOption != SearchOption.TopDirectoryOnly) && (searchOption != SearchOption.AllDirectories))
- throw new ArgumentOutOfRangeException(nameof(searchOption), Environment.GetResourceString("ArgumentOutOfRange_Enum"));
- Contract.Ensures(Contract.Result<String[]>() != null);
- Contract.EndContractBlock();
-
- return InternalGetFileSystemEntries(path, searchPattern, searchOption);
- }
-
- private static String[] InternalGetFileSystemEntries(String path, String searchPattern, SearchOption searchOption)
- {
- Contract.Requires(path != null);
- Contract.Requires(searchPattern != null);
- Contract.Requires(searchOption == SearchOption.AllDirectories || searchOption == SearchOption.TopDirectoryOnly);
-
- return InternalGetFileDirectoryNames(path, path, searchPattern, true, true, searchOption, true);
- }
+ internal static class Directory {
// Private class that holds search data that is passed around
// in the heap based stack recursion
@@ -445,90 +47,7 @@ namespace System.IO
public readonly SearchOption searchOption;
}
-
- // Returns fully qualified user path of dirs/files that matches the search parameters.
- // For recursive search this method will search through all the sub dirs and execute
- // the given search criteria against every dir.
- // For all the dirs/files returned, it will then demand path discovery permission for
- // their parent folders (it will avoid duplicate permission checks)
- internal static String[] InternalGetFileDirectoryNames(String path, String userPathOriginal, String searchPattern, bool includeFiles, bool includeDirs, SearchOption searchOption, bool checkHost)
- {
- Contract.Requires(path != null);
- Contract.Requires(userPathOriginal != null);
- Contract.Requires(searchPattern != null);
- Contract.Requires(searchOption == SearchOption.AllDirectories || searchOption == SearchOption.TopDirectoryOnly);
-
- IEnumerable<String> enble = FileSystemEnumerableFactory.CreateFileNameIterator(
- path, userPathOriginal, searchPattern,
- includeFiles, includeDirs, searchOption, checkHost);
- List<String> fileList = new List<String>(enble);
- return fileList.ToArray();
- }
-
- public static IEnumerable<String> EnumerateDirectories(String path)
- {
- if (path == null)
- throw new ArgumentNullException(nameof(path));
- Contract.EndContractBlock();
-
- return InternalEnumerateDirectories(path, "*", SearchOption.TopDirectoryOnly);
- }
-
- public static IEnumerable<String> EnumerateDirectories(String path, String searchPattern)
- {
- if (path == null)
- throw new ArgumentNullException(nameof(path));
- if (searchPattern == null)
- throw new ArgumentNullException(nameof(searchPattern));
- Contract.EndContractBlock();
-
- return InternalEnumerateDirectories(path, searchPattern, SearchOption.TopDirectoryOnly);
- }
-
- public static IEnumerable<String> EnumerateDirectories(String path, String searchPattern, SearchOption searchOption)
- {
- if (path == null)
- throw new ArgumentNullException(nameof(path));
- if (searchPattern == null)
- throw new ArgumentNullException(nameof(searchPattern));
- if ((searchOption != SearchOption.TopDirectoryOnly) && (searchOption != SearchOption.AllDirectories))
- throw new ArgumentOutOfRangeException(nameof(searchOption), Environment.GetResourceString("ArgumentOutOfRange_Enum"));
- Contract.EndContractBlock();
-
- return InternalEnumerateDirectories(path, searchPattern, searchOption);
- }
-
- private static IEnumerable<String> InternalEnumerateDirectories(String path, String searchPattern, SearchOption searchOption)
- {
- Contract.Requires(path != null);
- Contract.Requires(searchPattern != null);
- Contract.Requires(searchOption == SearchOption.AllDirectories || searchOption == SearchOption.TopDirectoryOnly);
-
- return EnumerateFileSystemNames(path, searchPattern, searchOption, false, true);
- }
-
- public static IEnumerable<String> EnumerateFiles(String path)
- {
- if (path == null)
- throw new ArgumentNullException(nameof(path));
- Contract.Ensures(Contract.Result<IEnumerable<String>>() != null);
- Contract.EndContractBlock();
-
- return InternalEnumerateFiles(path, "*", SearchOption.TopDirectoryOnly);
- }
-
- public static IEnumerable<String> EnumerateFiles(String path, String searchPattern)
- {
- if (path == null)
- throw new ArgumentNullException(nameof(path));
- if (searchPattern == null)
- throw new ArgumentNullException(nameof(searchPattern));
- Contract.Ensures(Contract.Result<IEnumerable<String>>() != null);
- Contract.EndContractBlock();
-
- return InternalEnumerateFiles(path, searchPattern, SearchOption.TopDirectoryOnly);
- }
-
+#if PLATFORM_UNIX
public static IEnumerable<String> EnumerateFiles(String path, String searchPattern, SearchOption searchOption)
{
if (path == null)
@@ -553,52 +72,6 @@ namespace System.IO
return EnumerateFileSystemNames(path, searchPattern, searchOption, true, false);
}
- public static IEnumerable<String> EnumerateFileSystemEntries(String path)
- {
- if (path == null)
- throw new ArgumentNullException(nameof(path));
- Contract.Ensures(Contract.Result<IEnumerable<String>>() != null);
- Contract.EndContractBlock();
-
- return InternalEnumerateFileSystemEntries(path, "*", SearchOption.TopDirectoryOnly);
- }
-
- public static IEnumerable<String> EnumerateFileSystemEntries(String path, String searchPattern)
- {
- if (path == null)
- throw new ArgumentNullException(nameof(path));
- if (searchPattern == null)
- throw new ArgumentNullException(nameof(searchPattern));
- Contract.Ensures(Contract.Result<IEnumerable<String>>() != null);
- Contract.EndContractBlock();
-
- return InternalEnumerateFileSystemEntries(path, searchPattern, SearchOption.TopDirectoryOnly);
- }
-
- public static IEnumerable<String> EnumerateFileSystemEntries(String path, String searchPattern, SearchOption searchOption)
- {
- if (path == null)
- throw new ArgumentNullException(nameof(path));
- if (searchPattern == null)
- throw new ArgumentNullException(nameof(searchPattern));
- if ((searchOption != SearchOption.TopDirectoryOnly) && (searchOption != SearchOption.AllDirectories))
- throw new ArgumentOutOfRangeException(nameof(searchOption), Environment.GetResourceString("ArgumentOutOfRange_Enum"));
- Contract.Ensures(Contract.Result<IEnumerable<String>>() != null);
- Contract.EndContractBlock();
-
- return InternalEnumerateFileSystemEntries(path, searchPattern, searchOption);
- }
-
- private static IEnumerable<String> InternalEnumerateFileSystemEntries(String path, String searchPattern, SearchOption searchOption)
- {
- Contract.Requires(path != null);
- Contract.Requires(searchPattern != null);
- Contract.Requires(searchOption == SearchOption.AllDirectories || searchOption == SearchOption.TopDirectoryOnly);
- Contract.Ensures(Contract.Result<IEnumerable<String>>() != null);
-
- return EnumerateFileSystemNames(path, searchPattern, searchOption, true, true);
- }
-
private static IEnumerable<String> EnumerateFileSystemNames(String path, String searchPattern, SearchOption searchOption,
bool includeFiles, bool includeDirs)
{
@@ -610,60 +83,14 @@ namespace System.IO
return FileSystemEnumerableFactory.CreateFileNameIterator(path, path, searchPattern,
includeFiles, includeDirs, searchOption, true);
}
-
- // Retrieves the names of the logical drives on this machine in the
- // form "C:\".
- //
- // Your application must have System Info permission.
- //
- public static String[] GetLogicalDrives()
- {
- Contract.Ensures(Contract.Result<String[]>() != null);
-
-#pragma warning disable 618
- new SecurityPermission(SecurityPermissionFlag.UnmanagedCode).Demand();
-#pragma warning restore 618
-
- int drives = Win32Native.GetLogicalDrives();
- if (drives==0)
- __Error.WinIOError();
- uint d = (uint)drives;
- int count = 0;
- while (d != 0) {
- if (((int)d & 1) != 0) count++;
- d >>= 1;
- }
- String[] result = new String[count];
- char[] root = new char[] {'A', ':', '\\'};
- d = (uint)drives;
- count = 0;
- while (d != 0) {
- if (((int)d & 1) != 0) {
- result[count++] = new String(root);
- }
- d >>= 1;
- root[0]++;
- }
- return result;
- }
-
- public static String GetDirectoryRoot(String path) {
- if (path==null)
- throw new ArgumentNullException(nameof(path));
- Contract.EndContractBlock();
-
- string fullPath = Path.GetFullPath(path);
- string root = fullPath.Substring(0, PathInternal.GetRootLength(fullPath));
-
- return root;
- }
+#endif // PLATFORM_UNIX
internal static String InternalGetDirectoryRoot(String path) {
if (path == null) return null;
return path.Substring(0, PathInternal.GetRootLength(path));
}
- /*===============================CurrentDirectory===============================
+ /*===============================CurrentDirectory===============================
**Action: Provides a getter and setter for the current directory. The original
** current DirectoryInfo is the one from which the process was started.
**Returns: The current DirectoryInfo (from the getter). Void from the setter.
@@ -673,20 +100,21 @@ namespace System.IO
public static String GetCurrentDirectory()
{
// Start with a buffer the size of MAX_PATH
- using (StringBuffer buffer = new StringBuffer(260))
+ StringBuffer buffer = new StringBuffer(260);
+ try
{
uint result = 0;
- while ((result = Win32Native.GetCurrentDirectoryW(buffer.CharCapacity, buffer.GetHandle())) > buffer.CharCapacity)
+ while ((result = Win32Native.GetCurrentDirectoryW((uint)buffer.Capacity, buffer.UnderlyingArray)) > buffer.Capacity)
{
// Reported size is greater than the buffer size. Increase the capacity.
// The size returned includes the null only if more space is needed (this case).
- buffer.EnsureCharCapacity(result);
+ buffer.EnsureCapacity(checked((int)result));
}
if (result == 0)
__Error.WinIOError();
- buffer.Length = result;
+ buffer.Length = (int)result;
#if !PLATFORM_UNIX
if (buffer.Contains('~'))
@@ -695,12 +123,16 @@ namespace System.IO
return buffer.ToString();
}
+ finally
+ {
+ buffer.Free();
+ }
}
public static void SetCurrentDirectory(String path)
{
if (path==null)
- throw new ArgumentNullException("value");
+ throw new ArgumentNullException(nameof(path));
if (path.Length==0)
throw new ArgumentException(Environment.GetResourceString("Argument_PathEmpty"));
if (path.Length >= Path.MaxPath)
@@ -718,216 +150,6 @@ namespace System.IO
__Error.WinIOError(errorCode, fulldestDirName);
}
}
-
- public static void Move(String sourceDirName,String destDirName)
- {
- if (sourceDirName==null)
- throw new ArgumentNullException(nameof(sourceDirName));
- if (sourceDirName.Length==0)
- throw new ArgumentException(Environment.GetResourceString("Argument_EmptyFileName"), nameof(sourceDirName));
- if (destDirName==null)
- throw new ArgumentNullException(nameof(destDirName));
- if (destDirName.Length==0)
- throw new ArgumentException(Environment.GetResourceString("Argument_EmptyFileName"), nameof(destDirName));
-
- 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"));
-
- String sourceRoot = Path.GetPathRoot(sourcePath);
- String destinationRoot = Path.GetPathRoot(destPath);
- if (String.Compare(sourceRoot, destinationRoot, StringComparison.OrdinalIgnoreCase) != 0)
- throw new IOException(Environment.GetResourceString("IO.IO_SourceDestMustHaveSameRoot"));
-
- if (!Win32Native.MoveFile(sourceDirName, destDirName))
- {
- int hr = Marshal.GetLastWin32Error();
- if (hr == Win32Native.ERROR_FILE_NOT_FOUND) // Source dir not found
- {
- hr = Win32Native.ERROR_PATH_NOT_FOUND;
- __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.
- throw new IOException(Environment.GetResourceString("UnauthorizedAccess_IODenied_Path", sourceDirName), Win32Native.MakeHRFromErrorCode(hr));
- __Error.WinIOError(hr, String.Empty);
- }
- }
-
- public static void Delete(String path)
- {
- String fullPath = Path.GetFullPath(path);
- Delete(fullPath, path, false);
- }
-
- public static void Delete(String path, bool recursive)
- {
- String fullPath = Path.GetFullPath(path);
- Delete(fullPath, path, recursive);
- }
-
- // Called from DirectoryInfo as well. FullPath is fully qualified,
- // while the user path is used for feedback in exceptions.
- internal static void Delete(String fullPath, String userPath, bool recursive)
- {
- // 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.
- // This applies to symbolic links and mount points.
- Win32Native.WIN32_FILE_ATTRIBUTE_DATA data = new Win32Native.WIN32_FILE_ATTRIBUTE_DATA();
- int dataInitialised = File.FillAttributeInfo(fullPath, ref data, false, true);
- if (dataInitialised != 0) {
- // Ensure we throw a DirectoryNotFoundException.
- if (dataInitialised == Win32Native.ERROR_FILE_NOT_FOUND)
- dataInitialised = Win32Native.ERROR_PATH_NOT_FOUND;
- __Error.WinIOError(dataInitialised, fullPath);
- }
-
- if (((FileAttributes)data.fileAttributes & FileAttributes.ReparsePoint) != 0)
- recursive = false;
-
- DeleteHelper(fullPath, userPath, recursive, true);
- }
-
- // 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;
- int hr;
- Exception ex = null;
-
- // 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.
- // This applies to symbolic links and mount points.
- // Note the logic to check whether fullPath is a reparse point is
- // in Delete(String, String, bool), and will set "recursive" to false.
- // Note that Win32's DeleteFile and RemoveDirectory will just delete
- // the reparse point itself.
-
- if (recursive) {
- Win32Native.WIN32_FIND_DATA data = new Win32Native.WIN32_FIND_DATA();
-
- // Open a Find handle
- 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) {
- // Skip ".", "..".
- if (data.cFileName.Equals(".") || data.cFileName.Equals(".."))
- continue;
-
- // Recurse for all directories, unless they are
- // reparse points. Do not follow mount points nor
- // symbolic links, but do delete the reparse point
- // itself.
- bool shouldRecurse = (0 == (data.dwFileAttributes & (int) FileAttributes.ReparsePoint));
- if (shouldRecurse) {
- String newFullPath = Path.Combine(fullPath, data.cFileName);
- String newUserPath = Path.Combine(userPath, data.cFileName);
- try {
- DeleteHelper(newFullPath, newUserPath, recursive, false);
- }
- catch(Exception e) {
- if (ex == null) {
- ex = e;
- }
- }
- }
- else {
- // Check to see if this is a mount point, and
- // unmount it.
- if (data.dwReserved0 == Win32Native.IO_REPARSE_TAG_MOUNT_POINT) {
- // Use full path plus a trailing '\'
- String mountPoint = Path.Combine(fullPath, data.cFileName + Path.DirectorySeparatorChar);
- r = Win32Native.DeleteVolumeMountPoint(mountPoint);
- if (!r) {
- hr = Marshal.GetLastWin32Error();
- if (hr != Win32Native.ERROR_PATH_NOT_FOUND) {
- try {
- __Error.WinIOError(hr, data.cFileName);
- }
- catch(Exception e) {
- if (ex == null) {
- ex = e;
- }
- }
- }
- }
- }
-
- // RemoveDirectory on a symbolic link will
- // remove the link itself.
- String reparsePoint = Path.Combine(fullPath, data.cFileName);
- r = Win32Native.RemoveDirectory(reparsePoint);
- if (!r) {
- hr = Marshal.GetLastWin32Error();
- if (hr != Win32Native.ERROR_PATH_NOT_FOUND) {
- try {
- __Error.WinIOError(hr, data.cFileName);
- }
- catch(Exception e) {
- if (ex == null) {
- ex = e;
- }
- }
- }
- }
- }
- }
- else {
- String fileName = Path.Combine(fullPath, data.cFileName);
- r = Win32Native.DeleteFile(fileName);
- if (!r) {
- hr = Marshal.GetLastWin32Error();
- if (hr != Win32Native.ERROR_FILE_NOT_FOUND) {
- try {
- __Error.WinIOError(hr, data.cFileName);
- }
- catch (Exception e) {
- if (ex == null) {
- ex = e;
- }
- }
- }
- }
- }
- } while (Win32Native.FindNextFile(hnd, data));
- // Make sure we quit with a sensible error.
- hr = Marshal.GetLastWin32Error();
- }
-
- if (ex != null)
- throw ex;
- if (hr!=0 && hr!=Win32Native.ERROR_NO_MORE_FILES)
- __Error.WinIOError(hr, userPath);
- }
-
- r = Win32Native.RemoveDirectory(fullPath);
-
- if (!r) {
- hr = Marshal.GetLastWin32Error();
- if (hr == Win32Native.ERROR_FILE_NOT_FOUND) // A dubious error code.
- hr = Win32Native.ERROR_PATH_NOT_FOUND;
- // 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)
- throw new IOException(Environment.GetResourceString("UnauthorizedAccess_IODenied_Path", userPath));
-
- // don't throw the DirectoryNotFoundException since this is a subdir and there could be a race condition
- // between two Directory.Delete callers
- if (hr == Win32Native.ERROR_PATH_NOT_FOUND && !throwOnTopLevelDirectoryNotFound)
- return;
-
- __Error.WinIOError(hr, fullPath);
- }
- }
}
}
diff --git a/src/mscorlib/src/System/IO/DirectoryInfo.cs b/src/mscorlib/src/System/IO/DirectoryInfo.cs
deleted file mode 100644
index c4c350d245..0000000000
--- a/src/mscorlib/src/System/IO/DirectoryInfo.cs
+++ /dev/null
@@ -1,511 +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 enumerating through a
-** directory.
-**
-** April 11,2000
-**
-===========================================================*/
-
-using System.Collections.Generic;
-using Microsoft.Win32;
-using System.Runtime.InteropServices;
-using System.Runtime.Serialization;
-using System.Runtime.Versioning;
-using System.Diagnostics;
-using System.Diagnostics.Contracts;
-
-namespace System.IO
-{
- [Serializable]
- [ComVisible(true)]
- public sealed class DirectoryInfo : FileSystemInfo
- {
- // Migrating InheritanceDemands requires this default ctor, so we can annotate it.
- private DirectoryInfo(){}
-
- public DirectoryInfo(String path)
- {
- if (path==null)
- throw new ArgumentNullException(nameof(path));
- Contract.EndContractBlock();
-
- Init(path);
- }
-
- private void Init(String path)
- {
- // Special case "<DriveLetter>:" to point to "<CurrentDirectory>" instead
- if ((path.Length == 2) && (path[1] == ':'))
- {
- OriginalPath = ".";
- }
- else
- {
- OriginalPath = path;
- }
-
- FullPath = Path.GetFullPath(path); ;
- DisplayPath = GetDisplayName(OriginalPath, FullPath);
- }
-
- internal DirectoryInfo(String fullPath, bool junk)
- {
- 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);
- }
-
- private DirectoryInfo(SerializationInfo info, StreamingContext context) : base(info, context)
- {
- DisplayPath = GetDisplayName(OriginalPath, FullPath);
- }
-
- public override String Name
- {
- get
- {
- // DisplayPath is dir name for coreclr
- return DisplayPath;
- }
- }
-
- public DirectoryInfo Parent {
- 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);
- parentName = Path.GetDirectoryName(s);
- if (parentName==null)
- return null;
-
- return new DirectoryInfo(parentName, false);
- }
- }
-
- public DirectoryInfo CreateSubdirectory(String path) {
- if (path == null)
- throw new ArgumentNullException(nameof(path));
- Contract.EndContractBlock();
-
- return CreateSubdirectory(path, null);
- }
-
- public DirectoryInfo CreateSubdirectory(String path, Object directorySecurity)
- {
- if (path == null)
- throw new ArgumentNullException(nameof(path));
- Contract.EndContractBlock();
-
- return CreateSubdirectoryHelper(path, directorySecurity);
- }
-
- private DirectoryInfo CreateSubdirectoryHelper(String path, Object directorySecurity)
- {
- Contract.Requires(path != null);
-
- 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));
- }
-
- Directory.InternalCreateDirectory(fullPath, path, directorySecurity);
-
- // Check for read permission to directory we hand back by calling this constructor.
- return new DirectoryInfo(fullPath);
- }
-
- public void Create()
- {
- Directory.InternalCreateDirectory(FullPath, OriginalPath, null);
- }
-
- // Tests if the given path refers to an existing DirectoryInfo on disk.
- public override bool Exists {
- get
- {
- try
- {
- if (_dataInitialised == -1)
- 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
- {
- return false;
- }
- }
- }
-
- // 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(nameof(searchPattern));
- Contract.EndContractBlock();
-
- return InternalGetFiles(searchPattern, SearchOption.TopDirectoryOnly);
- }
-
- // Returns an array of Files in the current DirectoryInfo matching the
- // given search criteria (ie, "*.txt").
- public FileInfo[] GetFiles(String searchPattern, SearchOption searchOption)
- {
- if (searchPattern == null)
- throw new ArgumentNullException(nameof(searchPattern));
- if ((searchOption != SearchOption.TopDirectoryOnly) && (searchOption != SearchOption.AllDirectories))
- throw new ArgumentOutOfRangeException(nameof(searchOption), Environment.GetResourceString("ArgumentOutOfRange_Enum"));
- Contract.EndContractBlock();
-
- return InternalGetFiles(searchPattern, searchOption);
- }
-
- // Returns an array of Files in the current DirectoryInfo matching the
- // given search criteria (ie, "*.txt").
- private FileInfo[] InternalGetFiles(String searchPattern, SearchOption searchOption)
- {
- Contract.Requires(searchPattern != null);
- Contract.Requires(searchOption == SearchOption.AllDirectories || searchOption == SearchOption.TopDirectoryOnly);
-
- IEnumerable<FileInfo> enble = FileSystemEnumerableFactory.CreateFileInfoIterator(FullPath, OriginalPath, searchPattern, searchOption);
- List<FileInfo> fileList = new List<FileInfo>(enble);
- return fileList.ToArray();
- }
-
- // Returns an array of Files in the DirectoryInfo specified by path
- public FileInfo[] GetFiles()
- {
- return InternalGetFiles("*", SearchOption.TopDirectoryOnly);
- }
-
- // Returns an array of Directories in the current directory.
- public DirectoryInfo[] GetDirectories()
- {
- return InternalGetDirectories("*", SearchOption.TopDirectoryOnly);
- }
-
- // Returns an array of strongly typed FileSystemInfo entries in the path with the
- // given search criteria (ie, "*.txt").
- public FileSystemInfo[] GetFileSystemInfos(String searchPattern)
- {
- if (searchPattern == null)
- throw new ArgumentNullException(nameof(searchPattern));
- Contract.EndContractBlock();
-
- return InternalGetFileSystemInfos(searchPattern, SearchOption.TopDirectoryOnly);
- }
-
- // Returns an array of strongly typed FileSystemInfo entries in the path with the
- // given search criteria (ie, "*.txt").
- public FileSystemInfo[] GetFileSystemInfos(String searchPattern, SearchOption searchOption)
- {
- if (searchPattern == null)
- throw new ArgumentNullException(nameof(searchPattern));
- if ((searchOption != SearchOption.TopDirectoryOnly) && (searchOption != SearchOption.AllDirectories))
- throw new ArgumentOutOfRangeException(nameof(searchOption), Environment.GetResourceString("ArgumentOutOfRange_Enum"));
- Contract.EndContractBlock();
-
- return InternalGetFileSystemInfos(searchPattern, searchOption);
- }
-
- // Returns an array of strongly typed FileSystemInfo entries in the path with the
- // given search criteria (ie, "*.txt").
- private FileSystemInfo[] InternalGetFileSystemInfos(String searchPattern, SearchOption searchOption)
- {
- Contract.Requires(searchPattern != null);
- Contract.Requires(searchOption == SearchOption.AllDirectories || searchOption == SearchOption.TopDirectoryOnly);
-
- IEnumerable<FileSystemInfo> enble = FileSystemEnumerableFactory.CreateFileSystemInfoIterator(FullPath, OriginalPath, searchPattern, searchOption);
- List<FileSystemInfo> fileList = new List<FileSystemInfo>(enble);
- return fileList.ToArray();
- }
-
- // Returns an array of strongly typed FileSystemInfo entries which will contain a listing
- // of all the files and directories.
- public FileSystemInfo[] GetFileSystemInfos()
- {
- return InternalGetFileSystemInfos("*", SearchOption.TopDirectoryOnly);
- }
-
- // Returns an array of Directories in the current DirectoryInfo matching the
- // given search criteria (ie, "System*" could match the System & System32
- // directories).
- public DirectoryInfo[] GetDirectories(String searchPattern)
- {
- if (searchPattern == null)
- throw new ArgumentNullException(nameof(searchPattern));
- Contract.EndContractBlock();
-
- return InternalGetDirectories(searchPattern, SearchOption.TopDirectoryOnly);
- }
-
- // Returns an array of Directories in the current DirectoryInfo matching the
- // given search criteria (ie, "System*" could match the System & System32
- // directories).
- public DirectoryInfo[] GetDirectories(String searchPattern, SearchOption searchOption)
- {
- if (searchPattern == null)
- throw new ArgumentNullException(nameof(searchPattern));
- if ((searchOption != SearchOption.TopDirectoryOnly) && (searchOption != SearchOption.AllDirectories))
- throw new ArgumentOutOfRangeException(nameof(searchOption), Environment.GetResourceString("ArgumentOutOfRange_Enum"));
- Contract.EndContractBlock();
-
- return InternalGetDirectories(searchPattern, searchOption);
- }
-
- // Returns an array of Directories in the current DirectoryInfo matching the
- // given search criteria (ie, "System*" could match the System & System32
- // directories).
- private DirectoryInfo[] InternalGetDirectories(String searchPattern, SearchOption searchOption)
- {
- Contract.Requires(searchPattern != null);
- Contract.Requires(searchOption == SearchOption.AllDirectories || searchOption == SearchOption.TopDirectoryOnly);
-
- IEnumerable<DirectoryInfo> enble = FileSystemEnumerableFactory.CreateDirectoryInfoIterator(FullPath, OriginalPath, searchPattern, searchOption);
- List<DirectoryInfo> fileList = new List<DirectoryInfo>(enble);
- return fileList.ToArray();
- }
-
- public IEnumerable<DirectoryInfo> EnumerateDirectories()
- {
- return InternalEnumerateDirectories("*", SearchOption.TopDirectoryOnly);
- }
-
- public IEnumerable<DirectoryInfo> EnumerateDirectories(String searchPattern)
- {
- if (searchPattern == null)
- throw new ArgumentNullException(nameof(searchPattern));
- Contract.EndContractBlock();
-
- return InternalEnumerateDirectories(searchPattern, SearchOption.TopDirectoryOnly);
- }
-
- public IEnumerable<DirectoryInfo> EnumerateDirectories(String searchPattern, SearchOption searchOption)
- {
- if (searchPattern == null)
- throw new ArgumentNullException(nameof(searchPattern));
- if ((searchOption != SearchOption.TopDirectoryOnly) && (searchOption != SearchOption.AllDirectories))
- throw new ArgumentOutOfRangeException(nameof(searchOption), Environment.GetResourceString("ArgumentOutOfRange_Enum"));
- Contract.EndContractBlock();
-
- return InternalEnumerateDirectories(searchPattern, searchOption);
- }
-
- private IEnumerable<DirectoryInfo> InternalEnumerateDirectories(String searchPattern, SearchOption searchOption)
- {
- Contract.Requires(searchPattern != null);
- Contract.Requires(searchOption == SearchOption.AllDirectories || searchOption == SearchOption.TopDirectoryOnly);
-
- return FileSystemEnumerableFactory.CreateDirectoryInfoIterator(FullPath, OriginalPath, searchPattern, searchOption);
- }
-
- public IEnumerable<FileInfo> EnumerateFiles()
- {
- return InternalEnumerateFiles("*", SearchOption.TopDirectoryOnly);
- }
-
- public IEnumerable<FileInfo> EnumerateFiles(String searchPattern)
- {
- if (searchPattern == null)
- throw new ArgumentNullException(nameof(searchPattern));
- Contract.EndContractBlock();
-
- return InternalEnumerateFiles(searchPattern, SearchOption.TopDirectoryOnly);
- }
-
- public IEnumerable<FileInfo> EnumerateFiles(String searchPattern, SearchOption searchOption)
- {
- if (searchPattern == null)
- throw new ArgumentNullException(nameof(searchPattern));
- if ((searchOption != SearchOption.TopDirectoryOnly) && (searchOption != SearchOption.AllDirectories))
- throw new ArgumentOutOfRangeException(nameof(searchOption), Environment.GetResourceString("ArgumentOutOfRange_Enum"));
- Contract.EndContractBlock();
-
- return InternalEnumerateFiles(searchPattern, searchOption);
- }
-
- private IEnumerable<FileInfo> InternalEnumerateFiles(String searchPattern, SearchOption searchOption)
- {
- Contract.Requires(searchPattern != null);
- Contract.Requires(searchOption == SearchOption.AllDirectories || searchOption == SearchOption.TopDirectoryOnly);
-
- return FileSystemEnumerableFactory.CreateFileInfoIterator(FullPath, OriginalPath, searchPattern, searchOption);
- }
-
- public IEnumerable<FileSystemInfo> EnumerateFileSystemInfos()
- {
- return InternalEnumerateFileSystemInfos("*", SearchOption.TopDirectoryOnly);
- }
-
- public IEnumerable<FileSystemInfo> EnumerateFileSystemInfos(String searchPattern)
- {
- if (searchPattern == null)
- throw new ArgumentNullException(nameof(searchPattern));
- Contract.EndContractBlock();
-
- return InternalEnumerateFileSystemInfos(searchPattern, SearchOption.TopDirectoryOnly);
- }
-
- public IEnumerable<FileSystemInfo> EnumerateFileSystemInfos(String searchPattern, SearchOption searchOption)
- {
- if (searchPattern == null)
- throw new ArgumentNullException(nameof(searchPattern));
- if ((searchOption != SearchOption.TopDirectoryOnly) && (searchOption != SearchOption.AllDirectories))
- throw new ArgumentOutOfRangeException(nameof(searchOption), Environment.GetResourceString("ArgumentOutOfRange_Enum"));
- Contract.EndContractBlock();
-
- return InternalEnumerateFileSystemInfos(searchPattern, searchOption);
- }
-
- private IEnumerable<FileSystemInfo> InternalEnumerateFileSystemInfos(String searchPattern, SearchOption searchOption)
- {
- Contract.Requires(searchPattern != null);
- Contract.Requires(searchOption == SearchOption.AllDirectories || searchOption == SearchOption.TopDirectoryOnly);
-
- 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
- // 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.
- public DirectoryInfo Root {
- get
- {
- int rootLength = PathInternal.GetRootLength(FullPath);
- String rootPath = FullPath.Substring(0, rootLength);
-
- return new DirectoryInfo(rootPath);
- }
- }
-
- public void MoveTo(String destDirName) {
- if (destDirName==null)
- throw new ArgumentNullException(nameof(destDirName));
- if (destDirName.Length==0)
- throw new ArgumentException(Environment.GetResourceString("Argument_EmptyFileName"), nameof(destDirName));
- Contract.EndContractBlock();
-
- String fullDestDirName = Path.GetFullPath(destDirName);
- if (!fullDestDirName.EndsWith(Path.DirectorySeparatorChar))
- fullDestDirName = fullDestDirName + Path.DirectorySeparatorChar;
-
- String fullSourcePath;
- if (FullPath.EndsWith(Path.DirectorySeparatorChar))
- fullSourcePath = FullPath;
- else
- fullSourcePath = FullPath + Path.DirectorySeparatorChar;
-
- if (String.Compare(fullSourcePath, fullDestDirName, StringComparison.OrdinalIgnoreCase) == 0)
- throw new IOException(Environment.GetResourceString("IO.IO_SourceDestMustBeDifferent"));
-
- String sourceRoot = Path.GetPathRoot(fullSourcePath);
- String destinationRoot = Path.GetPathRoot(fullDestDirName);
-
- if (String.Compare(sourceRoot, destinationRoot, StringComparison.OrdinalIgnoreCase) != 0)
- throw new IOException(Environment.GetResourceString("IO.IO_SourceDestMustHaveSameRoot"));
-
- if (!Win32Native.MoveFile(FullPath, destDirName))
- {
- int hr = Marshal.GetLastWin32Error();
- if (hr == Win32Native.ERROR_FILE_NOT_FOUND) // A dubious error code
- {
- hr = Win32Native.ERROR_PATH_NOT_FOUND;
- __Error.WinIOError(hr, DisplayPath);
- }
-
- if (hr == Win32Native.ERROR_ACCESS_DENIED) // We did this for Win9x. We can't change it for backcomp.
- throw new IOException(Environment.GetResourceString("UnauthorizedAccess_IODenied_Path", DisplayPath));
-
- __Error.WinIOError(hr,String.Empty);
- }
- FullPath = fullDestDirName;
- OriginalPath = destDirName;
- DisplayPath = GetDisplayName(OriginalPath, FullPath);
-
- // Flush any cached information about the directory.
- _dataInitialised = -1;
- }
-
- public override void Delete()
- {
- Directory.Delete(FullPath, OriginalPath, false);
- }
-
- public void Delete(bool recursive)
- {
- Directory.Delete(FullPath, OriginalPath, recursive);
- }
-
- // Returns the fully qualified path
- public override String ToString()
- {
- return DisplayPath;
- }
-
- private static String GetDisplayName(String originalPath, String fullPath)
- {
- Debug.Assert(originalPath != null);
- Debug.Assert(fullPath != null);
-
- String displayName = "";
-
- // Special case "<DriveLetter>:" to point to "<CurrentDirectory>" instead
- if ((originalPath.Length == 2) && (originalPath[1] == ':'))
- {
- displayName = ".";
- }
- else
- {
- displayName = GetDirName(fullPath);
- }
- return displayName;
- }
-
- private static String GetDirName(String fullPath)
- {
- Debug.Assert(fullPath != null);
-
- String dirName = null;
- if (fullPath.Length > 3)
- {
- String s = fullPath;
- if (fullPath.EndsWith(Path.DirectorySeparatorChar))
- {
- s = fullPath.Substring(0, fullPath.Length - 1);
- }
- dirName = Path.GetFileName(s);
- }
- else
- {
- dirName = fullPath; // For rooted paths, like "c:\"
- }
- return dirName;
- }
- }
-}
-
diff --git a/src/mscorlib/src/System/IO/DirectoryNotFoundException.cs b/src/mscorlib/src/System/IO/DirectoryNotFoundException.cs
index 09d7e7d4e7..21211a61e7 100644
--- a/src/mscorlib/src/System/IO/DirectoryNotFoundException.cs
+++ b/src/mscorlib/src/System/IO/DirectoryNotFoundException.cs
@@ -23,7 +23,6 @@ namespace System.IO {
* and STG_E_PATHNOTFOUND (0x80030003).
*/
[Serializable]
- [System.Runtime.InteropServices.ComVisible(true)]
public class DirectoryNotFoundException : IOException {
public DirectoryNotFoundException()
: base(Environment.GetResourceString("Arg_DirectoryNotFoundException")) {
diff --git a/src/mscorlib/src/System/IO/DriveNotFoundException.cs b/src/mscorlib/src/System/IO/DriveNotFoundException.cs
index 04155bcc0e..f0245a8b28 100644
--- a/src/mscorlib/src/System/IO/DriveNotFoundException.cs
+++ b/src/mscorlib/src/System/IO/DriveNotFoundException.cs
@@ -17,8 +17,7 @@ namespace System.IO {
//Thrown when trying to access a drive that is not availabe.
[Serializable]
- [System.Runtime.InteropServices.ComVisible(true)]
- public class DriveNotFoundException : IOException {
+ internal class DriveNotFoundException : IOException {
public DriveNotFoundException()
: base(Environment.GetResourceString("Arg_DriveNotFoundException")) {
SetErrorCode(__HResults.COR_E_DIRECTORYNOTFOUND);
@@ -28,11 +27,6 @@ namespace System.IO {
: base(message) {
SetErrorCode(__HResults.COR_E_DIRECTORYNOTFOUND);
}
-
- public DriveNotFoundException(String message, Exception innerException)
- : base(message, innerException) {
- SetErrorCode(__HResults.COR_E_DIRECTORYNOTFOUND);
- }
protected DriveNotFoundException(SerializationInfo info, StreamingContext context) : base(info, context) {
}
diff --git a/src/mscorlib/src/System/IO/EndOfStreamException.cs b/src/mscorlib/src/System/IO/EndOfStreamException.cs
index 60f5109a0f..558c792a9e 100644
--- a/src/mscorlib/src/System/IO/EndOfStreamException.cs
+++ b/src/mscorlib/src/System/IO/EndOfStreamException.cs
@@ -18,7 +18,6 @@ using System.Runtime.Serialization;
namespace System.IO {
[Serializable]
- [System.Runtime.InteropServices.ComVisible(true)]
public class EndOfStreamException : IOException
{
public EndOfStreamException()
diff --git a/src/mscorlib/src/System/IO/File.cs b/src/mscorlib/src/System/IO/File.cs
index 9f89f81a91..7cc3f431a9 100644
--- a/src/mscorlib/src/System/IO/File.cs
+++ b/src/mscorlib/src/System/IO/File.cs
@@ -14,7 +14,6 @@
**
===========================================================*/
-using System.Security.Permissions;
using Win32Native = Microsoft.Win32.Win32Native;
using System.Runtime.InteropServices;
using System.Security;
@@ -28,155 +27,13 @@ namespace System.IO
{
// Class for creating FileStream objects, and some basic file management
// routines such as Delete, etc.
- [ComVisible(true)]
- public static class File
+ internal 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(nameof(path));
- Contract.EndContractBlock();
- return new StreamReader(path);
- }
-
- public static StreamWriter CreateText(String path)
- {
- if (path == null)
- throw new ArgumentNullException(nameof(path));
- Contract.EndContractBlock();
- return new StreamWriter(path,false);
- }
-
- public static StreamWriter AppendText(String path)
- {
- if (path == null)
- throw new ArgumentNullException(nameof(path));
- Contract.EndContractBlock();
- return new StreamWriter(path,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.
- public static void Copy(String sourceFileName, String destFileName) {
- if (sourceFileName == null)
- throw new ArgumentNullException(nameof(sourceFileName), Environment.GetResourceString("ArgumentNull_FileName"));
- if (destFileName == null)
- throw new ArgumentNullException(nameof(destFileName), Environment.GetResourceString("ArgumentNull_FileName"));
- if (sourceFileName.Length == 0)
- throw new ArgumentException(Environment.GetResourceString("Argument_EmptyFileName"), nameof(sourceFileName));
- if (destFileName.Length == 0)
- throw new ArgumentException(Environment.GetResourceString("Argument_EmptyFileName"), nameof(destFileName));
- Contract.EndContractBlock();
-
- 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.
- public static void Copy(String sourceFileName, String destFileName, bool overwrite) {
- if (sourceFileName == null)
- throw new ArgumentNullException(nameof(sourceFileName), Environment.GetResourceString("ArgumentNull_FileName"));
- if (destFileName == null)
- throw new ArgumentNullException(nameof(destFileName), Environment.GetResourceString("ArgumentNull_FileName"));
- if (sourceFileName.Length == 0)
- throw new ArgumentException(Environment.GetResourceString("Argument_EmptyFileName"), nameof(sourceFileName));
- if (destFileName.Length == 0)
- throw new ArgumentException(Environment.GetResourceString("Argument_EmptyFileName"), nameof(destFileName));
- Contract.EndContractBlock();
-
- InternalCopy(sourceFileName, destFileName, overwrite);
- }
-
- /// <devdoc>
- /// Note: This returns the fully qualified name of the destination file.
- /// </devdoc>
- 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.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.
- int errorCode = Marshal.GetLastWin32Error();
- String fileName = destFileName;
-
- if (errorCode != Win32Native.ERROR_FILE_EXISTS) {
- if (errorCode == Win32Native.ERROR_ACCESS_DENIED) {
- if (Directory.InternalExists(fullDestFileName))
- throw new IOException(Environment.GetResourceString("Arg_FileIsDirectory_Name", destFileName), Win32Native.ERROR_ACCESS_DENIED, fullDestFileName);
- }
- }
-
- __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.
- public static FileStream Create(String path) {
- return Create(path, FileStream.DefaultBufferSize);
- }
-
- // Creates a file in a particular path. If the file exists, it is replaced.
- // 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.
- public static FileStream Create(String path, int bufferSize) {
- return new FileStream(path, FileMode.Create, FileAccess.ReadWrite, FileShare.None, bufferSize);
- }
-
- public static FileStream Create(String path, int bufferSize, FileOptions options) {
- return new FileStream(path, FileMode.Create, FileAccess.ReadWrite,
- FileShare.None, bufferSize, options);
- }
-
- // 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.
- public static void Delete(String path) {
- if (path == null)
- throw new ArgumentNullException(nameof(path));
- Contract.EndContractBlock();
-
- InternalDelete(path);
- }
-
- internal static void InternalDelete(String path)
- {
- String fullPath = Path.GetFullPath(path);
- bool r = Win32Native.DeleteFile(fullPath);
- if (!r) {
- int hr = Marshal.GetLastWin32Error();
- if (hr==Win32Native.ERROR_FILE_NOT_FOUND)
- return;
- else
- __Error.WinIOError(hr, 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,
@@ -225,193 +82,11 @@ namespace System.IO
&& ((data.fileAttributes & Win32Native.FILE_ATTRIBUTE_DIRECTORY) == 0);
}
- public static FileStream Open(String path, FileMode mode) {
- return Open(path, mode, (mode == FileMode.Append ? FileAccess.Write : FileAccess.ReadWrite), FileShare.None);
- }
-
- public static FileStream Open(String path, FileMode mode, FileAccess access) {
- return Open(path,mode, access, FileShare.None);
- }
-
- public static FileStream Open(String path, FileMode mode, FileAccess access, FileShare share) {
- return new FileStream(path, mode, access, share);
- }
-
- public static DateTime GetCreationTime(String path)
- {
- return InternalGetCreationTimeUtc(path).ToLocalTime();
- }
-
- public static DateTime GetCreationTimeUtc(String path)
- {
- return InternalGetCreationTimeUtc(path); // this API isn't exposed in Silverlight
- }
-
- private static DateTime InternalGetCreationTimeUtc(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);
- if (dataInitialised != 0)
- __Error.WinIOError(dataInitialised, fullPath);
-
- long dt = ((long)(data.ftCreationTimeHigh) << 32) | ((long)data.ftCreationTimeLow);
- return DateTime.FromFileTimeUtc(dt);
- }
-
- public static DateTime GetLastAccessTime(String path)
- {
- return InternalGetLastAccessTimeUtc(path).ToLocalTime();
- }
-
- public static DateTime GetLastAccessTimeUtc(String path)
- {
- return InternalGetLastAccessTimeUtc(path);
- }
-
- 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);
- if (dataInitialised != 0)
- __Error.WinIOError(dataInitialised, fullPath);
-
- long dt = ((long)(data.ftLastAccessTimeHigh) << 32) | ((long)data.ftLastAccessTimeLow);
- return DateTime.FromFileTimeUtc(dt);
- }
-
- public static DateTime GetLastWriteTime(String path)
- {
- return InternalGetLastWriteTimeUtc(path).ToLocalTime();
- }
-
- public static DateTime GetLastWriteTimeUtc(String path)
- {
- return InternalGetLastWriteTimeUtc(path);
- }
-
- private static DateTime InternalGetLastWriteTimeUtc(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);
- if (dataInitialised != 0)
- __Error.WinIOError(dataInitialised, fullPath);
-
- long dt = ((long)data.ftLastWriteTimeHigh << 32) | ((long)data.ftLastWriteTimeLow);
- return DateTime.FromFileTimeUtc(dt);
- }
-
- public static FileAttributes GetAttributes(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, true);
- if (dataInitialised != 0)
- __Error.WinIOError(dataInitialised, fullPath);
-
- return (FileAttributes) data.fileAttributes;
- }
-
- public static void SetAttributes(String path, FileAttributes fileAttributes)
- {
- String fullPath = Path.GetFullPath(path);
- bool r = Win32Native.SetFileAttributes(fullPath, (int) fileAttributes);
- if (!r) {
- int hr = Marshal.GetLastWin32Error();
- if (hr==ERROR_INVALID_PARAMETER)
- throw new ArgumentException(Environment.GetResourceString("Arg_InvalidFileAttrs"));
- __Error.WinIOError(hr, fullPath);
- }
- }
-
- 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);
- }
-
- public static String ReadAllText(String path)
- {
- if (path == null)
- throw new ArgumentNullException(nameof(path));
- if (path.Length == 0)
- throw new ArgumentException(Environment.GetResourceString("Argument_EmptyPath"));
- Contract.EndContractBlock();
-
- return InternalReadAllText(path, Encoding.UTF8);
- }
-
- public static String ReadAllText(String path, Encoding encoding)
- {
- if (path == null)
- throw new ArgumentNullException(nameof(path));
- if (encoding == null)
- throw new ArgumentNullException(nameof(encoding));
- if (path.Length == 0)
- throw new ArgumentException(Environment.GetResourceString("Argument_EmptyPath"));
- Contract.EndContractBlock();
-
- return InternalReadAllText(path, encoding);
- }
-
- 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))
- return sr.ReadToEnd();
- }
-
- public static void WriteAllText(String path, String contents)
- {
- if (path == null)
- throw new ArgumentNullException(nameof(path));
- if (path.Length == 0)
- throw new ArgumentException(Environment.GetResourceString("Argument_EmptyPath"));
- Contract.EndContractBlock();
-
- InternalWriteAllText(path, contents, StreamWriter.UTF8NoBOM);
- }
-
- public static void WriteAllText(String path, String contents, Encoding encoding)
- {
- if (path == null)
- throw new ArgumentNullException(nameof(path));
- if (encoding == null)
- throw new ArgumentNullException(nameof(encoding));
- if (path.Length == 0)
- throw new ArgumentException(Environment.GetResourceString("Argument_EmptyPath"));
- Contract.EndContractBlock();
-
- InternalWriteAllText(path, contents, encoding);
- }
-
- 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))
- sw.Write(contents);
- }
-
public static byte[] ReadAllBytes(String path)
{
byte[] bytes;
using(FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read,
- FileStream.DefaultBufferSize, FileOptions.None, Path.GetFileName(path), false, false)) {
+ FileStream.DefaultBufferSize, FileOptions.None)) {
// Do a blocking read
int index = 0;
long fileLength = fs.Length;
@@ -430,32 +105,7 @@ namespace System.IO
return bytes;
}
- public static void WriteAllBytes(String path, byte[] bytes)
- {
- if (path == null)
- 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(nameof(bytes));
- Contract.EndContractBlock();
-
- InternalWriteAllBytes(path, bytes);
- }
-
- 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))
- {
- fs.Write(bytes, 0, bytes.Length);
- }
- }
-
+#if PLATFORM_UNIX
public static String[] ReadAllLines(String path)
{
if (path == null)
@@ -467,19 +117,6 @@ namespace System.IO
return InternalReadAllLines(path, Encoding.UTF8);
}
- public static String[] ReadAllLines(String path, Encoding encoding)
- {
- if (path == null)
- throw new ArgumentNullException(nameof(path));
- if (encoding == null)
- throw new ArgumentNullException(nameof(encoding));
- if (path.Length == 0)
- throw new ArgumentException(Environment.GetResourceString("Argument_EmptyPath"));
- Contract.EndContractBlock();
-
- return InternalReadAllLines(path, encoding);
- }
-
private static String[] InternalReadAllLines(String path, Encoding encoding)
{
Contract.Requires(path != null);
@@ -495,236 +132,8 @@ namespace System.IO
return lines.ToArray();
}
-
- public static IEnumerable<String> ReadLines(String path)
- {
- if (path == null)
- throw new ArgumentNullException(nameof(path));
- if (path.Length == 0)
- throw new ArgumentException(Environment.GetResourceString("Argument_EmptyPath"), nameof(path));
- Contract.EndContractBlock();
-
- return ReadLinesIterator.CreateIterator(path, Encoding.UTF8);
- }
-
- public static IEnumerable<String> ReadLines(String path, Encoding encoding)
- {
- if (path == null)
- throw new ArgumentNullException(nameof(path));
- if (encoding == null)
- throw new ArgumentNullException(nameof(encoding));
- if (path.Length == 0)
- throw new ArgumentException(Environment.GetResourceString("Argument_EmptyPath"), nameof(path));
- Contract.EndContractBlock();
-
- return ReadLinesIterator.CreateIterator(path, encoding);
- }
-
- public static void WriteAllLines(String path, String[] contents)
- {
- if (path == null)
- throw new ArgumentNullException(nameof(path));
- if (contents == null)
- throw new ArgumentNullException(nameof(contents));
- if (path.Length == 0)
- throw new ArgumentException(Environment.GetResourceString("Argument_EmptyPath"));
- Contract.EndContractBlock();
-
- InternalWriteAllLines(new StreamWriter(path, false, StreamWriter.UTF8NoBOM), contents);
- }
-
- public static void WriteAllLines(String path, String[] contents, Encoding encoding)
- {
- if (path == null)
- throw new ArgumentNullException(nameof(path));
- if (contents == null)
- throw new ArgumentNullException(nameof(contents));
- if (encoding == null)
- throw new ArgumentNullException(nameof(encoding));
- if (path.Length == 0)
- throw new ArgumentException(Environment.GetResourceString("Argument_EmptyPath"));
- Contract.EndContractBlock();
-
- InternalWriteAllLines(new StreamWriter(path, false, encoding), contents);
- }
-
- public static void WriteAllLines(String path, IEnumerable<String> contents)
- {
- if (path == null)
- throw new ArgumentNullException(nameof(path));
- if (contents == null)
- throw new ArgumentNullException(nameof(contents));
- if (path.Length == 0)
- throw new ArgumentException(Environment.GetResourceString("Argument_EmptyPath"));
- Contract.EndContractBlock();
-
- InternalWriteAllLines(new StreamWriter(path, false, StreamWriter.UTF8NoBOM), contents);
- }
-
- public static void WriteAllLines(String path, IEnumerable<String> contents, Encoding encoding)
- {
- if (path == null)
- throw new ArgumentNullException(nameof(path));
- if (contents == null)
- throw new ArgumentNullException(nameof(contents));
- if (encoding == null)
- throw new ArgumentNullException(nameof(encoding));
- if (path.Length == 0)
- throw new ArgumentException(Environment.GetResourceString("Argument_EmptyPath"));
- Contract.EndContractBlock();
-
- InternalWriteAllLines(new StreamWriter(path, false, encoding), contents);
- }
-
- private static void InternalWriteAllLines(TextWriter writer, IEnumerable<String> contents)
- {
- Contract.Requires(writer != null);
- Contract.Requires(contents != null);
-
- using (writer)
- {
- foreach (String line in contents)
- {
- writer.WriteLine(line);
- }
- }
- }
-
- public static void AppendAllText(String path, String contents)
- {
- if (path == null)
- throw new ArgumentNullException(nameof(path));
- if (path.Length == 0)
- throw new ArgumentException(Environment.GetResourceString("Argument_EmptyPath"));
- Contract.EndContractBlock();
-
- InternalAppendAllText(path, contents, StreamWriter.UTF8NoBOM);
- }
-
- public static void AppendAllText(String path, String contents, Encoding encoding)
- {
- if (path == null)
- throw new ArgumentNullException(nameof(path));
- if (encoding == null)
- throw new ArgumentNullException(nameof(encoding));
- if (path.Length == 0)
- throw new ArgumentException(Environment.GetResourceString("Argument_EmptyPath"));
- Contract.EndContractBlock();
-
- InternalAppendAllText(path, contents, encoding);
- }
-
- private static void InternalAppendAllText(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, true, encoding))
- sw.Write(contents);
- }
-
- public static void AppendAllLines(String path, IEnumerable<String> contents)
- {
- if (path == null)
- throw new ArgumentNullException(nameof(path));
- if (contents == null)
- throw new ArgumentNullException(nameof(contents));
- if (path.Length == 0)
- throw new ArgumentException(Environment.GetResourceString("Argument_EmptyPath"));
- Contract.EndContractBlock();
-
- InternalWriteAllLines(new StreamWriter(path, true, StreamWriter.UTF8NoBOM), contents);
- }
-
- public static void AppendAllLines(String path, IEnumerable<String> contents, Encoding encoding)
- {
- if (path == null)
- throw new ArgumentNullException(nameof(path));
- if (contents == null)
- throw new ArgumentNullException(nameof(contents));
- if (encoding == null)
- throw new ArgumentNullException(nameof(encoding));
- if (path.Length == 0)
- throw new ArgumentException(Environment.GetResourceString("Argument_EmptyPath"));
- Contract.EndContractBlock();
-
- InternalWriteAllLines(new StreamWriter(path, true, encoding), contents);
- }
-
- // Moves a specified file to a new location and potentially a new file name.
- // This method does work across volumes.
- public static void Move(String sourceFileName, String destFileName) {
- InternalMove(sourceFileName, destFileName);
- }
-
- private static void InternalMove(String sourceFileName, String destFileName) {
- if (sourceFileName == null)
- throw new ArgumentNullException(nameof(sourceFileName), Environment.GetResourceString("ArgumentNull_FileName"));
- if (destFileName == null)
- throw new ArgumentNullException(nameof(destFileName), Environment.GetResourceString("ArgumentNull_FileName"));
- if (sourceFileName.Length == 0)
- throw new ArgumentException(Environment.GetResourceString("Argument_EmptyFileName"), nameof(sourceFileName));
- if (destFileName.Length == 0)
- throw new ArgumentException(Environment.GetResourceString("Argument_EmptyFileName"), nameof(destFileName));
- Contract.EndContractBlock();
-
- String fullSourceFileName = Path.GetFullPath(sourceFileName);
- String fullDestFileName = Path.GetFullPath(destFileName);
-
- if (!InternalExists(fullSourceFileName))
- __Error.WinIOError(Win32Native.ERROR_FILE_NOT_FOUND, fullSourceFileName);
-
- if (!Win32Native.MoveFile(fullSourceFileName, fullDestFileName))
- {
- __Error.WinIOError();
- }
- }
-
-
- public static void Replace(String sourceFileName, String destinationFileName, String destinationBackupFileName)
- {
- if (sourceFileName == null)
- throw new ArgumentNullException(nameof(sourceFileName));
- if (destinationFileName == null)
- throw new ArgumentNullException(nameof(destinationFileName));
- Contract.EndContractBlock();
-
- InternalReplace(sourceFileName, destinationFileName, destinationBackupFileName, false);
- }
-
- public static void Replace(String sourceFileName, String destinationFileName, String destinationBackupFileName, bool ignoreMetadataErrors)
- {
- if (sourceFileName == null)
- throw new ArgumentNullException(nameof(sourceFileName));
- if (destinationFileName == null)
- throw new ArgumentNullException(nameof(destinationFileName));
- Contract.EndContractBlock();
-
- InternalReplace(sourceFileName, destinationFileName, destinationBackupFileName, ignoreMetadataErrors);
- }
-
- private static void InternalReplace(String sourceFileName, String destinationFileName, String destinationBackupFileName, bool ignoreMetadataErrors)
- {
- Contract.Requires(sourceFileName != null);
- Contract.Requires(destinationFileName != null);
-
- String fullSrcPath = Path.GetFullPath(sourceFileName);
- String fullDestPath = Path.GetFullPath(destinationFileName);
- String fullBackupPath = null;
- if (destinationBackupFileName != null)
- fullBackupPath = Path.GetFullPath(destinationBackupFileName);
-
- int flags = Win32Native.REPLACEFILE_WRITE_THROUGH;
- if (ignoreMetadataErrors)
- flags |= Win32Native.REPLACEFILE_IGNORE_MERGE_ERRORS;
-
- bool r = Win32Native.ReplaceFile(fullDestPath, fullSrcPath, fullBackupPath, flags, IntPtr.Zero, IntPtr.Zero);
- if (!r)
- __Error.WinIOError();
- }
-
-
+#endif // PLATFORM_UNIX
+
// Returns 0 on success, otherwise a Win32 error code. Note that
// classes should use -1 as the uninitialized state for dataInitialized.
internal static int FillAttributeInfo(String path, ref Win32Native.WIN32_FILE_ATTRIBUTE_DATA data, bool tryagain, bool returnErrorOnNotFound)
diff --git a/src/mscorlib/src/System/IO/FileAccess.cs b/src/mscorlib/src/System/IO/FileAccess.cs
index f708a284c1..707b58f78b 100644
--- a/src/mscorlib/src/System/IO/FileAccess.cs
+++ b/src/mscorlib/src/System/IO/FileAccess.cs
@@ -23,7 +23,6 @@ namespace System.IO {
//
[Serializable]
[Flags]
-[System.Runtime.InteropServices.ComVisible(true)]
public enum FileAccess
{
// Specifies read access to the file. Data can be read from the file and
diff --git a/src/mscorlib/src/System/IO/FileAttributes.cs b/src/mscorlib/src/System/IO/FileAttributes.cs
deleted file mode 100644
index 51ef597f9d..0000000000
--- a/src/mscorlib/src/System/IO/FileAttributes.cs
+++ /dev/null
@@ -1,39 +0,0 @@
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-// See the LICENSE file in the project root for more information.
-
-/*============================================================
-**
-**
-** Purpose: File attribute flags corresponding to NT's flags.
-**
-**
-===========================================================*/
-using System;
-
-namespace System.IO
-{
- // File attributes for use with the FileEnumerator class.
- // These constants correspond to the constants in WinNT.h.
- [Serializable]
- [Flags]
- [System.Runtime.InteropServices.ComVisible(true)]
- public enum FileAttributes
- {
- // From WinNT.h (FILE_ATTRIBUTE_XXX)
- ReadOnly = 0x1,
- Hidden = 0x2,
- System = 0x4,
- Directory = 0x10,
- Archive = 0x20,
- Device = 0x40,
- Normal = 0x80,
- Temporary = 0x100,
- SparseFile = 0x200,
- ReparsePoint = 0x400,
- Compressed = 0x800,
- Offline = 0x1000,
- NotContentIndexed = 0x2000,
- Encrypted = 0x4000,
- }
-}
diff --git a/src/mscorlib/src/System/IO/FileInfo.cs b/src/mscorlib/src/System/IO/FileInfo.cs
deleted file mode 100644
index 32622c63a1..0000000000
--- a/src/mscorlib/src/System/IO/FileInfo.cs
+++ /dev/null
@@ -1,270 +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 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
-{
- // Class for creating FileStream objects, and some basic file management
- // routines such as Delete, etc.
- [Serializable]
- [ComVisible(true)]
- public sealed class FileInfo: FileSystemInfo
- {
- private String _name;
-
- // Migrating InheritanceDemands requires this default ctor, so we can annotate it.
- private FileInfo(){}
-
- public FileInfo(String fileName)
- {
- if (fileName == null)
- throw new ArgumentNullException(nameof(fileName));
- Contract.EndContractBlock();
-
- Init(fileName);
- }
-
- private void Init(String fileName)
- {
- OriginalPath = fileName;
- _name = Path.GetFileName(fileName);
- FullPath = Path.GetFullPath(fileName);
- DisplayPath = GetDisplayPath(fileName);
- }
-
- private String GetDisplayPath(String originalPath)
- {
- return Path.GetFileName(originalPath);
- }
-
- private FileInfo(SerializationInfo info, StreamingContext context) : base(info, context)
- {
- _name = Path.GetFileName(OriginalPath);
- DisplayPath = GetDisplayPath(OriginalPath);
- }
-
- internal FileInfo(String fullPath, bool ignoreThis)
- {
- Debug.Assert(PathInternal.GetRootLength(fullPath) > 0, "fullPath must be fully qualified!");
- _name = Path.GetFileName(fullPath);
- OriginalPath = _name;
- FullPath = fullPath;
- DisplayPath = _name;
- }
-
- public override String Name {
- get { return _name; }
- }
-
- public long Length {
- get {
- if (_dataInitialised == -1)
- Refresh();
-
- if (_dataInitialised != 0) // Refresh was unable to initialise the data
- __Error.WinIOError(_dataInitialised, DisplayPath);
-
- if ((_data.fileAttributes & Win32Native.FILE_ATTRIBUTE_DIRECTORY) != 0)
- __Error.WinIOError(Win32Native.ERROR_FILE_NOT_FOUND, DisplayPath);
-
- return ((long)_data.fileSizeHigh) << 32 | ((long)_data.fileSizeLow & 0xFFFFFFFFL);
- }
- }
-
- /* Returns the name of the directory that the file is in */
- public String DirectoryName
- {
- get
- {
- return Path.GetDirectoryName(FullPath);
- }
- }
-
- /* Creates an instance of the the parent directory */
- public DirectoryInfo Directory
- {
- get
- {
- String dirName = DirectoryName;
- if (dirName == null)
- return null;
- return new DirectoryInfo(dirName);
- }
- }
-
- public bool IsReadOnly {
- get {
- return (Attributes & FileAttributes.ReadOnly) != 0;
- }
- set {
- if (value)
- Attributes |= FileAttributes.ReadOnly;
- else
- Attributes &= ~FileAttributes.ReadOnly;
- }
- }
-
- public StreamReader OpenText()
- {
- return new StreamReader(FullPath, Encoding.UTF8, true, StreamReader.DefaultBufferSize);
- }
-
- public StreamWriter CreateText()
- {
- return new StreamWriter(FullPath,false);
- }
-
- public StreamWriter AppendText()
- {
- 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.
- public FileInfo CopyTo(String destFileName) {
- if (destFileName == null)
- throw new ArgumentNullException(nameof(destFileName), Environment.GetResourceString("ArgumentNull_FileName"));
- if (destFileName.Length == 0)
- throw new ArgumentException(Environment.GetResourceString("Argument_EmptyFileName"), nameof(destFileName));
- Contract.EndContractBlock();
-
- 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.
- public FileInfo CopyTo(String destFileName, bool overwrite) {
- if (destFileName == null)
- throw new ArgumentNullException(nameof(destFileName), Environment.GetResourceString("ArgumentNull_FileName"));
- if (destFileName.Length == 0)
- throw new ArgumentException(Environment.GetResourceString("Argument_EmptyFileName"), nameof(destFileName));
- Contract.EndContractBlock();
-
- destFileName = File.InternalCopy(FullPath, destFileName, overwrite);
- return new FileInfo(destFileName, false);
- }
-
- public FileStream Create() {
- return File.Create(FullPath);
- }
-
- // 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.
- public override void Delete()
- {
- bool r = Win32Native.DeleteFile(FullPath);
- if (!r) {
- int hr = Marshal.GetLastWin32Error();
- if (hr==Win32Native.ERROR_FILE_NOT_FOUND)
- return;
- else
- __Error.WinIOError(hr, DisplayPath);
- }
- }
-
- // Tests if the given file exists. The result is true if the file
- // given by the specified path exists; otherwise, the result is
- // false.
- public override bool Exists {
- get {
- try {
- if (_dataInitialised == -1)
- Refresh();
- if (_dataInitialised != 0) {
- // Refresh was unable to initialise the data.
- // We should normally be throwing an exception here,
- // but Exists is supposed to return true or false.
- return false;
- }
- return (_data.fileAttributes & Win32Native.FILE_ATTRIBUTE_DIRECTORY) == 0;
- }
- catch
- {
- return false;
- }
- }
- }
-
- // User must explicitly specify opening a new file or appending to one.
- public FileStream Open(FileMode mode) {
- return Open(mode, FileAccess.ReadWrite, FileShare.None);
- }
-
- public FileStream Open(FileMode mode, FileAccess access) {
- return Open(mode, access, FileShare.None);
- }
-
- public FileStream Open(FileMode mode, FileAccess access, FileShare share) {
- return new FileStream(FullPath, mode, access, share);
- }
-
- 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.
- public void MoveTo(String destFileName) {
- if (destFileName==null)
- throw new ArgumentNullException(nameof(destFileName));
- if (destFileName.Length==0)
- throw new ArgumentException(Environment.GetResourceString("Argument_EmptyFileName"), nameof(destFileName));
- Contract.EndContractBlock();
-
- string fullDestFileName = Path.GetFullPath(destFileName);
-
- if (!Win32Native.MoveFile(FullPath, fullDestFileName))
- __Error.WinIOError();
- FullPath = fullDestFileName;
- OriginalPath = destFileName;
- _name = Path.GetFileName(fullDestFileName);
- DisplayPath = GetDisplayPath(destFileName);
- // Flush any cached information about the file.
- _dataInitialised = -1;
- }
-
- [ComVisible(false)]
- public FileInfo Replace(String destinationFileName, String destinationBackupFileName)
- {
- return Replace(destinationFileName, destinationBackupFileName, false);
- }
-
- [ComVisible(false)]
- public FileInfo Replace(String destinationFileName, String destinationBackupFileName, bool ignoreMetadataErrors)
- {
- File.Replace(FullPath, destinationFileName, destinationBackupFileName, ignoreMetadataErrors);
- return new FileInfo(destinationFileName);
- }
-
- // Returns the display path
- public override String ToString()
- {
- return DisplayPath;
- }
- }
-}
diff --git a/src/mscorlib/src/System/IO/FileLoadException.cs b/src/mscorlib/src/System/IO/FileLoadException.cs
index 2b56c00191..980d2514aa 100644
--- a/src/mscorlib/src/System/IO/FileLoadException.cs
+++ b/src/mscorlib/src/System/IO/FileLoadException.cs
@@ -20,14 +20,12 @@ using System.Runtime.Serialization;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
using System.Security;
-using System.Security.Permissions;
using System.Runtime.Versioning;
using SecurityException = System.Security.SecurityException;
namespace System.IO {
[Serializable]
- [System.Runtime.InteropServices.ComVisible(true)]
public class FileLoadException : IOException {
private String _fileName; // the name of the file we could not load.
diff --git a/src/mscorlib/src/System/IO/FileMode.cs b/src/mscorlib/src/System/IO/FileMode.cs
index 9b9c2024a7..3972cf0533 100644
--- a/src/mscorlib/src/System/IO/FileMode.cs
+++ b/src/mscorlib/src/System/IO/FileMode.cs
@@ -27,7 +27,6 @@ namespace System.IO {
// exist, use Create.
//
[Serializable]
-[System.Runtime.InteropServices.ComVisible(true)]
public enum FileMode
{
// Creates a new file. An exception is raised if the file already exists.
diff --git a/src/mscorlib/src/System/IO/FileNotFoundException.cs b/src/mscorlib/src/System/IO/FileNotFoundException.cs
index 8cc75f8232..ad6b5386ba 100644
--- a/src/mscorlib/src/System/IO/FileNotFoundException.cs
+++ b/src/mscorlib/src/System/IO/FileNotFoundException.cs
@@ -16,14 +16,12 @@
using System;
using System.Runtime.Serialization;
-using System.Security.Permissions;
using SecurityException = System.Security.SecurityException;
using System.Globalization;
namespace System.IO {
// Thrown when trying to access a file that doesn't exist on disk.
[Serializable]
- [System.Runtime.InteropServices.ComVisible(true)]
public class FileNotFoundException : IOException {
private String _fileName; // The name of the file that isn't found.
diff --git a/src/mscorlib/src/System/IO/FileOptions.cs b/src/mscorlib/src/System/IO/FileOptions.cs
index ffd6ddad90..02bc99eea4 100644
--- a/src/mscorlib/src/System/IO/FileOptions.cs
+++ b/src/mscorlib/src/System/IO/FileOptions.cs
@@ -24,7 +24,6 @@ namespace System.IO {
// a number of them made sense in managed code, at least not yet.
[Serializable]
[Flags]
- [ComVisible(true)]
public enum FileOptions
{
// NOTE: any change to FileOptions enum needs to be
diff --git a/src/mscorlib/src/System/IO/FileShare.cs b/src/mscorlib/src/System/IO/FileShare.cs
index ad76d5da09..8a7d1f05e9 100644
--- a/src/mscorlib/src/System/IO/FileShare.cs
+++ b/src/mscorlib/src/System/IO/FileShare.cs
@@ -28,7 +28,6 @@ namespace System.IO {
//
[Serializable]
[Flags]
-[System.Runtime.InteropServices.ComVisible(true)]
public enum FileShare
{
// No sharing. Any request to open the file (by this process or another
diff --git a/src/mscorlib/src/System/IO/FileSystemEnumerable.cs b/src/mscorlib/src/System/IO/FileSystemEnumerable.cs
index f861805ccf..0316de0f93 100644
--- a/src/mscorlib/src/System/IO/FileSystemEnumerable.cs
+++ b/src/mscorlib/src/System/IO/FileSystemEnumerable.cs
@@ -25,7 +25,6 @@ using System.Threading;
namespace System.IO
{
-
// Overview:
// The key methods instantiate FileSystemEnumerableIterators. These compose the iterator with search result
// handlers that instantiate the FileInfo, DirectoryInfo, String, etc. The handlers then perform any
@@ -42,37 +41,6 @@ namespace System.IO
SearchResultHandler<String> handler = new StringResultHandler(includeFiles, includeDirs);
return new FileSystemEnumerableIterator<String>(path, originalUserPath, searchPattern, searchOption, handler, checkHost);
}
-
- internal static IEnumerable<FileInfo> CreateFileInfoIterator(String path, String originalUserPath, String searchPattern, SearchOption searchOption)
- {
- Contract.Requires(path != null);
- Contract.Requires(originalUserPath != null);
- Contract.Requires(searchPattern != null);
-
- SearchResultHandler<FileInfo> handler = new FileInfoResultHandler();
- return new FileSystemEnumerableIterator<FileInfo>(path, originalUserPath, searchPattern, searchOption, handler, true);
- }
-
- internal static IEnumerable<DirectoryInfo> CreateDirectoryInfoIterator(String path, String originalUserPath, String searchPattern, SearchOption searchOption)
- {
-
- Contract.Requires(path != null);
- Contract.Requires(originalUserPath != null);
- Contract.Requires(searchPattern != null);
-
- SearchResultHandler<DirectoryInfo> handler = new DirectoryInfoResultHandler();
- return new FileSystemEnumerableIterator<DirectoryInfo>(path, originalUserPath, searchPattern, searchOption, handler, true);
- }
-
- internal static IEnumerable<FileSystemInfo> CreateFileSystemInfoIterator(String path, String originalUserPath, String searchPattern, SearchOption searchOption)
- {
- Contract.Requires(path != null);
- Contract.Requires(originalUserPath != null);
- Contract.Requires(searchPattern != null);
-
- SearchResultHandler<FileSystemInfo> handler = new FileSystemInfoResultHandler();
- return new FileSystemEnumerableIterator<FileSystemInfo>(path, originalUserPath, searchPattern, searchOption, handler, true);
- }
}
// Abstract Iterator, borrowed from Linq. Used in anticipation of need for similar enumerables
@@ -166,11 +134,11 @@ namespace System.IO
private String searchCriteria;
SafeFindHandle _hnd = null;
- // 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
- // 2. we’re enumerating only the top directory and found no matches during the first call
- // This flag allows us to return early for these cases. We can’t know this in advance for
- // SearchOption.AllDirectories because we do a “*” search for subdirs and then use the
+ // 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
+ // 2. we're enumerating only the top directory and found no matches during the first call
+ // This flag allows us to return early for these cases. We can't know this in advance for
+ // SearchOption.AllDirectories because we do a "*" search for subdirs and then use the
// searchPattern at each directory level.
bool empty;
@@ -603,71 +571,6 @@ namespace System.IO
}
}
- internal class FileInfoResultHandler : SearchResultHandler<FileInfo>
- {
- internal override bool IsResultIncluded(SearchResult result)
- {
- return FileSystemEnumerableHelpers.IsFile(result.FindData);
- }
-
- internal override FileInfo CreateObject(SearchResult result)
- {
- String name = result.FullPath;
- FileInfo fi = new FileInfo(name, false);
- fi.InitializeFrom(result.FindData);
- return fi;
- }
- }
-
- internal class DirectoryInfoResultHandler : SearchResultHandler<DirectoryInfo>
- {
- internal override bool IsResultIncluded(SearchResult result)
- {
- return FileSystemEnumerableHelpers.IsDir(result.FindData);
- }
-
- internal override DirectoryInfo CreateObject(SearchResult result)
- {
- DirectoryInfo di = new DirectoryInfo(result.FullPath, false);
- di.InitializeFrom(result.FindData);
- return di;
- }
- }
-
- internal class FileSystemInfoResultHandler : SearchResultHandler<FileSystemInfo>
- {
-
- internal override bool IsResultIncluded(SearchResult result)
- {
- bool includeFile = FileSystemEnumerableHelpers.IsFile(result.FindData);
- bool includeDir = FileSystemEnumerableHelpers.IsDir(result.FindData);
- Debug.Assert(!(includeFile && includeDir), result.FindData.cFileName + ": current item can't be both file and dir!");
-
- return (includeDir || includeFile);
- }
-
- internal override FileSystemInfo CreateObject(SearchResult result)
- {
- bool isFile = FileSystemEnumerableHelpers.IsFile(result.FindData);
- bool isDir = FileSystemEnumerableHelpers.IsDir(result.FindData);
-
- if (isDir)
- {
- DirectoryInfo di = new DirectoryInfo(result.FullPath, false);
- di.InitializeFrom(result.FindData);
- return di;
- }
- else
- {
- Contract.Assert(isFile);
- FileInfo fi = new FileInfo(result.FullPath, false);
- fi.InitializeFrom(result.FindData);
- return fi;
- }
- }
-
- }
-
internal sealed class SearchResult
{
private String fullPath; // fully-qualifed path
diff --git a/src/mscorlib/src/System/IO/FileSystemInfo.cs b/src/mscorlib/src/System/IO/FileSystemInfo.cs
deleted file mode 100644
index 94cd531b07..0000000000
--- a/src/mscorlib/src/System/IO/FileSystemInfo.cs
+++ /dev/null
@@ -1,240 +0,0 @@
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-// See the LICENSE file in the project root for more information.
-
-using Microsoft.Win32;
-using System.Runtime.InteropServices;
-using System.Runtime.Serialization;
-using System.Diagnostics.Contracts;
-
-namespace System.IO
-{
-#if FEATURE_SERIALIZATION
- [Serializable]
-#endif
- [ComVisible(true)]
- public abstract class FileSystemInfo : MarshalByRefObject, ISerializable {
-
- 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
- // give back a generic error back.
-
- private const int ERROR_INVALID_PARAMETER = 87;
- internal const int ERROR_ACCESS_DENIED = 0x5;
-
- protected String FullPath; // fully qualified path of the directory
- protected String OriginalPath; // path passed in by the user
- private String _displayPath = ""; // path that can be displayed to the user
-
- protected FileSystemInfo()
- {
- }
-
- protected FileSystemInfo(SerializationInfo info, StreamingContext context)
- {
- if (info == null)
- throw new ArgumentNullException(nameof(info));
- Contract.EndContractBlock();
-
- // Must use V1 field names here, since V1 didn't implement
- // ISerializable.
- FullPath = Path.GetFullPath(info.GetString("FullPath"));
- OriginalPath = info.GetString("OriginalPath");
-
- // Lazily initialize the file attributes.
- _dataInitialised = -1;
- }
-
- internal void InitializeFrom(Win32Native.WIN32_FIND_DATA findData)
- {
- _data = new Win32Native.WIN32_FILE_ATTRIBUTE_DATA();
- _data.PopulateFrom(findData);
- _dataInitialised = 0;
- }
-
- // Full path of the direcory/file
- public virtual String FullName {
- get
- {
- return FullPath;
- }
- }
-
- public String Extension
- {
- get
- {
- // GetFullPathInternal would have already stripped out the terminating "." if present.
- int length = FullPath.Length;
- for (int i = length; --i >= 0;) {
- char ch = FullPath[i];
- if (ch == '.')
- return FullPath.Substring(i, length - i);
- if (ch == Path.DirectorySeparatorChar || ch == Path.AltDirectorySeparatorChar || ch == Path.VolumeSeparatorChar)
- break;
- }
- return String.Empty;
- }
- }
-
- // For files name of the file is returned, for directories the last directory in hierarchy is returned if possible,
- // otherwise the fully qualified name s returned
- public abstract String Name {
- get;
- }
-
- // Whether a file/directory exists
- public abstract bool Exists
- {
- get;
- }
-
- // Delete a file/directory
- public abstract void Delete();
-
- public DateTime CreationTime
- {
- get {
- // depends on the security check in get_CreationTimeUtc
- return CreationTimeUtc.ToLocalTime();
- }
- }
-
- [ComVisible(false)]
- public DateTime CreationTimeUtc {
- get {
- if (_dataInitialised == -1) {
- _data = new Win32Native.WIN32_FILE_ATTRIBUTE_DATA();
- Refresh();
- }
-
- if (_dataInitialised != 0) // Refresh was unable to initialise the data
- __Error.WinIOError(_dataInitialised, DisplayPath);
-
- long fileTime = ((long)_data.ftCreationTimeHigh << 32) | _data.ftCreationTimeLow;
- return DateTime.FromFileTimeUtc(fileTime);
-
- }
- }
-
- public DateTime LastAccessTime
- {
- get {
- // depends on the security check in get_LastAccessTimeUtc
- return LastAccessTimeUtc.ToLocalTime();
- }
- set {
- LastAccessTimeUtc = value.ToUniversalTime();
- }
- }
-
- [ComVisible(false)]
- public DateTime LastAccessTimeUtc {
- get {
- if (_dataInitialised == -1) {
- _data = new Win32Native.WIN32_FILE_ATTRIBUTE_DATA();
- Refresh();
- }
-
- if (_dataInitialised != 0) // Refresh was unable to initialise the data
- __Error.WinIOError(_dataInitialised, DisplayPath);
-
- long fileTime = ((long)_data.ftLastAccessTimeHigh << 32) | _data.ftLastAccessTimeLow;
- return DateTime.FromFileTimeUtc(fileTime);
- }
-
- set {
- }
- }
-
- public DateTime LastWriteTime
- {
- get {
- // depends on the security check in get_LastWriteTimeUtc
- return LastWriteTimeUtc.ToLocalTime();
- }
-
- set {
- LastWriteTimeUtc = value.ToUniversalTime();
- }
- }
-
- [ComVisible(false)]
- public DateTime LastWriteTimeUtc {
- get {
- if (_dataInitialised == -1) {
- _data = new Win32Native.WIN32_FILE_ATTRIBUTE_DATA();
- Refresh();
- }
-
- if (_dataInitialised != 0) // Refresh was unable to initialise the data
- __Error.WinIOError(_dataInitialised, DisplayPath);
-
-
- long fileTime = ((long)_data.ftLastWriteTimeHigh << 32) | _data.ftLastWriteTimeLow;
- return DateTime.FromFileTimeUtc(fileTime);
- }
-
- set {
- }
- }
-
- public void Refresh()
- {
- _dataInitialised = File.FillAttributeInfo(FullPath, ref _data, false, false);
- }
-
- public FileAttributes Attributes {
- get
- {
- if (_dataInitialised == -1) {
- _data = new Win32Native.WIN32_FILE_ATTRIBUTE_DATA();
- Refresh(); // Call refresh to intialise the data
- }
-
- if (_dataInitialised != 0) // Refresh was unable to initialise the data
- __Error.WinIOError(_dataInitialised, DisplayPath);
-
- return (FileAttributes) _data.fileAttributes;
- }
-
- set {
- bool r = Win32Native.SetFileAttributes(FullPath, (int) value);
- if (!r) {
- int hr = Marshal.GetLastWin32Error();
-
- if (hr==ERROR_INVALID_PARAMETER)
- throw new ArgumentException(Environment.GetResourceString("Arg_InvalidFileAttrs"));
-
- // For whatever reason we are turning ERROR_ACCESS_DENIED into
- // ArgumentException here (probably done for some 9x code path).
- // We can't change this now but special casing the error message instead.
- if (hr == ERROR_ACCESS_DENIED)
- throw new ArgumentException(Environment.GetResourceString("UnauthorizedAccess_IODenied_NoPathName"));
- __Error.WinIOError(hr, DisplayPath);
- }
- _dataInitialised = -1;
- }
- }
-
- [ComVisible(false)]
- public virtual void GetObjectData(SerializationInfo info, StreamingContext context)
- {
- info.AddValue("OriginalPath", OriginalPath, typeof(String));
- info.AddValue("FullPath", FullPath, typeof(String));
- }
-
- internal String DisplayPath
- {
- get
- {
- return _displayPath;
- }
- set
- {
- _displayPath = value;
- }
- }
- }
-}
diff --git a/src/mscorlib/src/System/IO/IOException.cs b/src/mscorlib/src/System/IO/IOException.cs
index b3db033b0d..ab612811b0 100644
--- a/src/mscorlib/src/System/IO/IOException.cs
+++ b/src/mscorlib/src/System/IO/IOException.cs
@@ -19,7 +19,6 @@ using System.Runtime.Serialization;
namespace System.IO {
[Serializable]
- [System.Runtime.InteropServices.ComVisible(true)]
public class IOException : SystemException
{
// For debugging purposes, store the complete path in the IOException
diff --git a/src/mscorlib/src/System/IO/MemoryStream.cs b/src/mscorlib/src/System/IO/MemoryStream.cs
index bdddc83818..05aac909b5 100644
--- a/src/mscorlib/src/System/IO/MemoryStream.cs
+++ b/src/mscorlib/src/System/IO/MemoryStream.cs
@@ -23,7 +23,6 @@ using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Threading;
using System.Threading.Tasks;
-using System.Security.Permissions;
namespace System.IO {
// A MemoryStream represents a Stream in memory (ie, it has no backing store).
@@ -35,7 +34,6 @@ namespace System.IO {
// memory streams are resizable, while ones created with a byte array provide
// a stream "view" of the data.
[Serializable]
- [ComVisible(true)]
public class MemoryStream : Stream
{
private byte[] _buffer; // Either allocated internally or externally.
@@ -181,7 +179,6 @@ namespace System.IO {
public override void Flush() {
}
- [ComVisible(false)]
public override Task FlushAsync(CancellationToken cancellationToken) {
if (cancellationToken.IsCancellationRequested)
@@ -357,7 +354,6 @@ namespace System.IO {
return n;
}
- [ComVisible(false)]
public override Task<int> ReadAsync(Byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
if (buffer==null)
@@ -589,7 +585,6 @@ namespace System.IO {
}
- [ComVisible(false)]
public override Task WriteAsync(Byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
if (buffer == null)
diff --git a/src/mscorlib/src/System/IO/PathTooLongException.cs b/src/mscorlib/src/System/IO/PathTooLongException.cs
index b1063232a1..a84fdfbb36 100644
--- a/src/mscorlib/src/System/IO/PathTooLongException.cs
+++ b/src/mscorlib/src/System/IO/PathTooLongException.cs
@@ -20,7 +20,6 @@ using System.Runtime.Serialization;
namespace System.IO {
[Serializable]
- [System.Runtime.InteropServices.ComVisible(true)]
public class PathTooLongException : IOException
{
public PathTooLongException()
diff --git a/src/mscorlib/src/System/IO/PinnedBufferMemoryStream.cs b/src/mscorlib/src/System/IO/PinnedBufferMemoryStream.cs
index 890669fa58..2cbd14f734 100644
--- a/src/mscorlib/src/System/IO/PinnedBufferMemoryStream.cs
+++ b/src/mscorlib/src/System/IO/PinnedBufferMemoryStream.cs
@@ -42,8 +42,8 @@ namespace System.IO {
_pinningHandle = new GCHandle(array, GCHandleType.Pinned);
// Now the byte[] is pinned for the lifetime of this instance.
// But I also need to get a pointer to that block of memory...
- fixed(byte* ptr = _array)
- Initialize(ptr, len, len, FileAccess.Read, true);
+ fixed(byte* ptr = &_array[0])
+ Initialize(ptr, len, len, FileAccess.Read);
}
~PinnedBufferMemoryStream()
diff --git a/src/mscorlib/src/System/IO/ReadLinesIterator.cs b/src/mscorlib/src/System/IO/ReadLinesIterator.cs
deleted file mode 100644
index ce2ad2ad0f..0000000000
--- a/src/mscorlib/src/System/IO/ReadLinesIterator.cs
+++ /dev/null
@@ -1,102 +0,0 @@
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-// See the LICENSE file in the project root for more information.
-using System;
-using System.Diagnostics.Contracts;
-using System.Runtime.Versioning;
-using System.Text;
-
-namespace System.IO
-{
- // An iterator that returns a single line at-a-time from a given file.
- //
- // Known issues which cannot be changed to remain compatible with 4.0:
- //
- // - The underlying StreamReader is allocated upfront for the IEnumerable<T> before
- // GetEnumerator has even been called. While this is good in that exceptions such as
- // DirectoryNotFoundException and FileNotFoundException are thrown directly by
- // File.ReadLines (which the user probably expects), it also means that the reader
- // will be leaked if the user never actually foreach's over the enumerable (and hence
- // calls Dispose on at least one IEnumerator<T> instance).
- //
- // - Reading to the end of the IEnumerator<T> disposes it. This means that Dispose
- // is called twice in a normal foreach construct.
- //
- // - IEnumerator<T> instances from the same IEnumerable<T> party on the same underlying
- // reader (Dev10 Bugs 904764).
- //
- internal class ReadLinesIterator : Iterator<string>
- {
- private readonly string _path;
- private readonly Encoding _encoding;
- private StreamReader _reader;
-
- private ReadLinesIterator(string path, Encoding encoding, StreamReader reader)
- {
- Contract.Requires(path != null);
- Contract.Requires(path.Length > 0);
- Contract.Requires(encoding != null);
- Contract.Requires(reader != null);
-
- _path = path;
- _encoding = encoding;
- _reader = reader;
- }
-
- public override bool MoveNext()
- {
- if (this._reader != null)
- {
- this.current = _reader.ReadLine();
- if (this.current != null)
- return true;
-
- // To maintain 4.0 behavior we Dispose
- // after reading to the end of the reader.
- Dispose();
- }
-
- return false;
- }
-
- protected override Iterator<string> Clone()
- {
- // NOTE: To maintain the same behavior with the previous yield-based
- // iterator in 4.0, we have all the IEnumerator<T> instances share the same
- // underlying reader. If we have already been disposed, _reader will be null,
- // which will cause CreateIterator to simply new up a new instance to start up
- // a new iteration. Dev10 Bugs 904764 has been filed to fix this in next side-
- // by-side release.
- return CreateIterator(_path, _encoding, _reader);
- }
-
- protected override void Dispose(bool disposing)
- {
- try
- {
- if (disposing)
- {
- if (_reader != null)
- {
- _reader.Dispose();
- }
- }
- }
- finally
- {
- _reader = null;
- base.Dispose(disposing);
- }
- }
-
- internal static ReadLinesIterator CreateIterator(string path, Encoding encoding)
- {
- return CreateIterator(path, encoding, (StreamReader)null);
- }
-
- private static ReadLinesIterator CreateIterator(string path, Encoding encoding, StreamReader reader)
- {
- return new ReadLinesIterator(path, encoding, reader ?? new StreamReader(path, encoding));
- }
- }
-}
diff --git a/src/mscorlib/src/System/IO/SearchOption.cs b/src/mscorlib/src/System/IO/SearchOption.cs
index aa9b9e37f8..e2f761cd54 100644
--- a/src/mscorlib/src/System/IO/SearchOption.cs
+++ b/src/mscorlib/src/System/IO/SearchOption.cs
@@ -20,7 +20,6 @@ using System;
namespace System.IO {
[Serializable]
-[System.Runtime.InteropServices.ComVisible(true)]
public enum SearchOption
{
// Include only the current directory in the search operation
diff --git a/src/mscorlib/src/System/IO/SeekOrigin.cs b/src/mscorlib/src/System/IO/SeekOrigin.cs
index a0a013e7aa..bff49e610f 100644
--- a/src/mscorlib/src/System/IO/SeekOrigin.cs
+++ b/src/mscorlib/src/System/IO/SeekOrigin.cs
@@ -21,7 +21,6 @@ namespace System.IO {
// Provides seek reference points. To seek to the end of a stream,
// call stream.Seek(0, SeekOrigin.End).
[Serializable]
- [System.Runtime.InteropServices.ComVisible(true)]
public enum SeekOrigin
{
// These constants match Win32's FILE_BEGIN, FILE_CURRENT, and FILE_END
diff --git a/src/mscorlib/src/System/IO/Stream.cs b/src/mscorlib/src/System/IO/Stream.cs
index 3cdfad613e..790f0a09ab 100644
--- a/src/mscorlib/src/System/IO/Stream.cs
+++ b/src/mscorlib/src/System/IO/Stream.cs
@@ -23,14 +23,12 @@ 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)]
public abstract class Stream : MarshalByRefObject, IDisposable {
public static readonly Stream Null = new NullStream();
@@ -65,7 +63,6 @@ namespace System.IO {
get;
}
- [ComVisible(false)]
public virtual bool CanTimeout {
[Pure]
get {
@@ -87,7 +84,6 @@ namespace System.IO {
set;
}
- [ComVisible(false)]
public virtual int ReadTimeout {
get {
Contract.Ensures(Contract.Result<int>() >= 0);
@@ -98,7 +94,6 @@ namespace System.IO {
}
}
- [ComVisible(false)]
public virtual int WriteTimeout {
get {
Contract.Ensures(Contract.Result<int>() >= 0);
@@ -109,7 +104,6 @@ namespace System.IO {
}
}
- [ComVisible(false)]
public Task CopyToAsync(Stream destination)
{
int bufferSize = _DefaultCopyBufferSize;
@@ -146,13 +140,11 @@ namespace System.IO {
return CopyToAsync(destination, bufferSize);
}
- [ComVisible(false)]
public Task CopyToAsync(Stream destination, Int32 bufferSize)
{
return CopyToAsync(destination, bufferSize, CancellationToken.None);
}
- [ComVisible(false)]
public virtual Task CopyToAsync(Stream destination, Int32 bufferSize, CancellationToken cancellationToken)
{
StreamHelpers.ValidateCopyToArgs(this, destination, bufferSize);
@@ -278,13 +270,11 @@ namespace System.IO {
public abstract void Flush();
- [ComVisible(false)]
public Task FlushAsync()
{
return FlushAsync(CancellationToken.None);
}
- [ComVisible(false)]
public virtual Task FlushAsync(CancellationToken cancellationToken)
{
return Task.Factory.StartNew(state => ((Stream)state).Flush(), this,
@@ -398,13 +388,11 @@ namespace System.IO {
}
}
- [ComVisible(false)]
public Task<int> ReadAsync(Byte[] buffer, int offset, int count)
{
return ReadAsync(buffer, offset, count, CancellationToken.None);
}
- [ComVisible(false)]
public virtual Task<int> ReadAsync(Byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
// If cancellation was requested, bail early with an already completed task.
@@ -617,7 +605,6 @@ namespace System.IO {
_buffer = null;
}
- [MethodImpl(MethodImplOptions.NoInlining)]
public ReadWriteTask(
bool isRead,
bool apm,
@@ -630,8 +617,6 @@ namespace System.IO {
Contract.Requires(buffer != null);
Contract.EndContractBlock();
- StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
-
// Store the arguments
_isRead = isRead;
_apm = apm;
@@ -648,8 +633,7 @@ namespace System.IO {
if (callback != null)
{
_callback = callback;
- _context = ExecutionContext.Capture(ref stackMark,
- ExecutionContext.CaptureOptions.OptimizeDefaultCase | ExecutionContext.CaptureOptions.IgnoreSyncCtx);
+ _context = ExecutionContext.Capture();
base.AddCompletionAction(this);
}
}
@@ -683,14 +667,13 @@ namespace System.IO {
var invokeAsyncCallback = s_invokeAsyncCallback;
if (invokeAsyncCallback == null) s_invokeAsyncCallback = invokeAsyncCallback = InvokeAsyncCallback; // benign race condition
- using(context) ExecutionContext.Run(context, invokeAsyncCallback, this, true);
+ ExecutionContext.Run(context, invokeAsyncCallback, this);
}
}
bool ITaskCompletionAction.InvokeMayRunArbitraryCode { get { return true; } }
}
- [ComVisible(false)]
public Task WriteAsync(Byte[] buffer, int offset, int count)
{
return WriteAsync(buffer, offset, count, CancellationToken.None);
@@ -698,7 +681,6 @@ namespace System.IO {
- [ComVisible(false)]
public virtual Task WriteAsync(Byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
// If cancellation was requested, bail early with an already completed task.
@@ -906,7 +888,6 @@ namespace System.IO {
{
}
- [ComVisible(false)]
public override Task FlushAsync(CancellationToken cancellationToken)
{
return cancellationToken.IsCancellationRequested ?
@@ -951,7 +932,6 @@ namespace System.IO {
return 0;
}
- [ComVisible(false)]
public override Task<int> ReadAsync(Byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
var nullReadTask = s_nullReadTask;
@@ -970,7 +950,6 @@ namespace System.IO {
{
}
- [ComVisible(false)]
public override Task WriteAsync(Byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
return cancellationToken.IsCancellationRequested ?
@@ -1106,7 +1085,6 @@ namespace System.IO {
get { return _stream.CanSeek; }
}
- [ComVisible(false)]
public override bool CanTimeout {
[Pure]
get {
@@ -1135,7 +1113,6 @@ namespace System.IO {
}
}
- [ComVisible(false)]
public override int ReadTimeout {
get {
return _stream.ReadTimeout;
@@ -1145,7 +1122,6 @@ namespace System.IO {
}
}
- [ComVisible(false)]
public override int WriteTimeout {
get {
return _stream.WriteTimeout;
diff --git a/src/mscorlib/src/System/IO/StreamReader.cs b/src/mscorlib/src/System/IO/StreamReader.cs
index 708db088e8..6d50347b1a 100644
--- a/src/mscorlib/src/System/IO/StreamReader.cs
+++ b/src/mscorlib/src/System/IO/StreamReader.cs
@@ -8,7 +8,6 @@ using System.Runtime.Versioning;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Diagnostics.Contracts;
-using System.Security.Permissions;
using System.Threading.Tasks;
namespace System.IO
@@ -18,8 +17,7 @@ namespace System.IO
// whereas the Stream class is designed for byte input and output.
//
[Serializable]
- [System.Runtime.InteropServices.ComVisible(true)]
- public class StreamReader : TextReader
+ internal class StreamReader : TextReader
{
// StreamReader.Null is threadsafe.
public new static readonly StreamReader Null = new NullStreamReader();
@@ -188,7 +186,7 @@ namespace System.IO
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);
+ Stream stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read, DefaultFileStreamBufferSize, FileOptions.SequentialScan);
Init(stream, encoding, detectEncodingFromByteOrderMarks, bufferSize, false);
}
@@ -757,7 +755,6 @@ namespace System.IO
}
#region Task based Async APIs
- [ComVisible(false)]
public override Task<String> ReadLineAsync()
{
// If we have been inherited into a subclass, the following implementation could be incorrect
@@ -837,7 +834,6 @@ namespace System.IO
return GetStringAndReleaseSharedStringBuilder(sb);
}
- [ComVisible(false)]
public override Task<String> ReadToEndAsync()
{
// If we have been inherited into a subclass, the following implementation could be incorrect
@@ -873,7 +869,6 @@ namespace System.IO
return GetStringAndReleaseSharedStringBuilder(sb);
}
- [ComVisible(false)]
public override Task<int> ReadAsync(char[] buffer, int index, int count)
{
if (buffer==null)
@@ -1060,7 +1055,6 @@ namespace System.IO
return charsRead;
}
- [ComVisible(false)]
public override Task<int> ReadBlockAsync(char[] buffer, int index, int count)
{
if (buffer==null)
diff --git a/src/mscorlib/src/System/IO/StreamWriter.cs b/src/mscorlib/src/System/IO/StreamWriter.cs
deleted file mode 100644
index 22eba82605..0000000000
--- a/src/mscorlib/src/System/IO/StreamWriter.cs
+++ /dev/null
@@ -1,765 +0,0 @@
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-// See the LICENSE file in the project root for more information.
-
-using System.Text;
-using System.Runtime.CompilerServices;
-using System.Security.Permissions;
-using System.Runtime.Serialization;
-using System.Diagnostics;
-using System.Diagnostics.Contracts;
-using System.Runtime.InteropServices;
-using System.Threading.Tasks;
-
-namespace System.IO
-{
- // This class implements a TextWriter for writing characters to a Stream.
- // This is designed for character output in a particular Encoding,
- // whereas the Stream class is designed for byte input and output.
- //
- [Serializable]
- [ComVisible(true)]
- public class StreamWriter : TextWriter
- {
- // For UTF-8, the values of 1K for the default buffer size and 4K for the
- // file stream buffer size are reasonable & give very reasonable
- // performance for in terms of construction time for the StreamWriter and
- // write perf. Note that for UTF-8, we end up allocating a 4K byte buffer,
- // which means we take advantage of adaptive buffering code.
- // The performance using UnicodeEncoding is acceptable.
- internal const int DefaultBufferSize = 1024; // char[]
- private const int DefaultFileStreamBufferSize = 4096;
- private const int MinBufferSize = 128;
-
- // Bit bucket - Null has no backing store. Non closable.
- public new static readonly StreamWriter Null = new StreamWriter(Stream.Null, UTF8NoBOM, MinBufferSize, true);
-
- private Stream stream;
- private Encoding encoding;
- private Encoder encoder;
- private byte[] byteBuffer;
- private char[] charBuffer;
- private int charPos;
- private int charLen;
- private bool autoFlush;
- private bool haveWrittenPreamble;
- private bool closable;
-
- // 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.
- [NonSerialized]
- private volatile Task _asyncWriteTask;
-
- private void CheckAsyncTaskInProgress()
- {
- // We are not locking the access to _asyncWriteTask because this is not meant to guarantee thread safety.
- // We are simply trying to deter calling any Write APIs while an async Write from the same thread is in progress.
-
- Task t = _asyncWriteTask;
-
- if (t != null && !t.IsCompleted)
- throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_AsyncIOInProgress"));
- }
-
- // The high level goal is to be tolerant of encoding errors when we read and very strict
- // when we write. Hence, default StreamWriter encoding will throw on encoding error.
- // Note: when StreamWriter throws on invalid encoding chars (for ex, high surrogate character
- // D800-DBFF without a following low surrogate character DC00-DFFF), it will cause the
- // internal StreamWriter's state to be irrecoverable as it would have buffered the
- // illegal chars and any subsequent call to Flush() would hit the encoding error again.
- // 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!
- internal static Encoding UTF8NoBOM {
- [FriendAccessAllowed]
- get { return EncodingCache.UTF8NoBOM; }
- }
-
-
- internal StreamWriter(): base(null) { // Ask for CurrentCulture all the time
- }
-
- public StreamWriter(Stream stream)
- : this(stream, UTF8NoBOM, DefaultBufferSize, false) {
- }
-
- public StreamWriter(Stream stream, Encoding encoding)
- : this(stream, encoding, DefaultBufferSize, false) {
- }
-
- // Creates a new StreamWriter for the given stream. The
- // character encoding is set by encoding and the buffer size,
- // in number of 16-bit characters, is set by bufferSize.
- //
- public StreamWriter(Stream stream, Encoding encoding, int bufferSize)
- : this(stream, encoding, bufferSize, false) {
- }
-
- public StreamWriter(Stream stream, Encoding encoding, int bufferSize, bool leaveOpen)
- : base(null) // Ask for CurrentCulture all the time
- {
- if (stream == null || encoding == null)
- 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(nameof(bufferSize), Environment.GetResourceString("ArgumentOutOfRange_NeedPosNum"));
- Contract.EndContractBlock();
-
- Init(stream, encoding, bufferSize, leaveOpen);
- }
-
- public StreamWriter(String path)
- : this(path, false, UTF8NoBOM, DefaultBufferSize) {
- }
-
- public StreamWriter(String path, bool append)
- : this(path, append, UTF8NoBOM, DefaultBufferSize) {
- }
-
- public StreamWriter(String path, bool append, Encoding encoding)
- : this(path, append, encoding, DefaultBufferSize) {
- }
-
- public StreamWriter(String path, bool append, Encoding encoding, int bufferSize)
- : base(null)
- {
- // Ask for CurrentCulture all the time
- if (path == null)
- throw new ArgumentNullException(nameof(path));
- if (encoding == null)
- throw new ArgumentNullException(nameof(encoding));
- if (path.Length == 0)
- throw new ArgumentException(Environment.GetResourceString("Argument_EmptyPath"));
- if (bufferSize <= 0) throw new ArgumentOutOfRangeException(nameof(bufferSize), Environment.GetResourceString("ArgumentOutOfRange_NeedPosNum"));
- Contract.EndContractBlock();
-
- Stream stream = CreateFile(path, append);
- Init(stream, encoding, bufferSize, false);
- }
-
- private void Init(Stream streamArg, Encoding encodingArg, int bufferSize, bool shouldLeaveOpen)
- {
- this.stream = streamArg;
- this.encoding = encodingArg;
- this.encoder = encoding.GetEncoder();
- if (bufferSize < MinBufferSize) bufferSize = MinBufferSize;
- charBuffer = new char[bufferSize];
- byteBuffer = new byte[encoding.GetMaxByteCount(bufferSize)];
- charLen = bufferSize;
- // If we're appending to a Stream that already has data, don't write
- // the preamble.
- if (stream.CanSeek && stream.Position > 0)
- haveWrittenPreamble = true;
- closable = !shouldLeaveOpen;
- }
-
- 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);
- return f;
- }
-
- public override void Close() {
- Dispose(true);
- GC.SuppressFinalize(this);
- }
-
- protected override void Dispose(bool disposing) {
- try {
- // We need to flush any buffered data if we are being closed/disposed.
- // Also, we never close the handles for stdout & friends. So we can safely
- // write any buffered data to those streams even during finalization, which
- // is generally the right thing to do.
- if (stream != null) {
- // Note: flush on the underlying stream can throw (ex., low disk space)
- if (disposing)
- {
- CheckAsyncTaskInProgress();
-
- Flush(true, true);
- }
- }
- }
- finally {
- // Dispose of our resources if this StreamWriter is closable.
- // Note: Console.Out and other such non closable streamwriters should be left alone
- if (!LeaveOpen && stream != null) {
- try {
- // Attempt to close the stream even if there was an IO error from Flushing.
- // Note that Stream.Close() can potentially throw here (may or may not be
- // due to the same Flush error). In this case, we still need to ensure
- // cleaning up internal resources, hence the finally block.
- if (disposing)
- stream.Close();
- }
- finally {
- stream = null;
- byteBuffer = null;
- charBuffer = null;
- encoding = null;
- encoder = null;
- charLen = 0;
- base.Dispose(disposing);
- }
- }
- }
- }
-
- public override void Flush()
- {
- CheckAsyncTaskInProgress();
-
- Flush(true, true);
- }
-
- private void Flush(bool flushStream, bool flushEncoder)
- {
- // flushEncoder should be true at the end of the file and if
- // the user explicitly calls Flush (though not if AutoFlush is true).
- // This is required to flush any dangling characters from our UTF-7
- // and UTF-8 encoders.
- if (stream == null)
- __Error.WriterClosed();
-
- // Perf boost for Flush on non-dirty writers.
- if (charPos==0 && (!flushStream && !flushEncoder))
- return;
-
- if (!haveWrittenPreamble) {
- haveWrittenPreamble = true;
- byte[] preamble = encoding.GetPreamble();
- if (preamble.Length > 0)
- stream.Write(preamble, 0, preamble.Length);
- }
-
- int count = encoder.GetBytes(charBuffer, 0, charPos, byteBuffer, 0, flushEncoder);
- charPos = 0;
- if (count > 0)
- stream.Write(byteBuffer, 0, count);
- // By definition, calling Flush should flush the stream, but this is
- // only necessary if we passed in true for flushStream. The Web
- // Services guys have some perf tests where flushing needlessly hurts.
- if (flushStream)
- stream.Flush();
- }
-
- public virtual bool AutoFlush {
- get { return autoFlush; }
-
- set
- {
- CheckAsyncTaskInProgress();
-
- autoFlush = value;
- if (value) Flush(true, false);
- }
- }
-
- public virtual Stream BaseStream {
- get { return stream; }
- }
-
- internal bool LeaveOpen {
- get { return !closable; }
- }
-
- internal bool HaveWrittenPreamble {
- set { haveWrittenPreamble= value; }
- }
-
- public override Encoding Encoding {
- get { return encoding; }
- }
-
- public override void Write(char value)
- {
- CheckAsyncTaskInProgress();
-
- if (charPos == charLen) Flush(false, false);
- charBuffer[charPos] = value;
- charPos++;
- if (autoFlush) Flush(true, false);
- }
-
- public override void Write(char[] buffer)
- {
- // This may be faster than the one with the index & count since it
- // has to do less argument checking.
- if (buffer==null)
- return;
-
- CheckAsyncTaskInProgress();
-
- int index = 0;
- int count = buffer.Length;
- while (count > 0) {
- if (charPos == charLen) Flush(false, false);
- int n = charLen - charPos;
- if (n > count) n = count;
- 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;
- count -= n;
- }
- if (autoFlush) Flush(true, false);
- }
-
- public override void Write(char[] buffer, int index, int count) {
- if (buffer==null)
- throw new ArgumentNullException(nameof(buffer), Environment.GetResourceString("ArgumentNull_Buffer"));
- 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 (buffer.Length - index < count)
- throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen"));
- Contract.EndContractBlock();
-
- CheckAsyncTaskInProgress();
-
- while (count > 0) {
- if (charPos == charLen) Flush(false, false);
- int n = charLen - charPos;
- if (n > count) n = count;
- 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;
- count -= n;
- }
- if (autoFlush) Flush(true, false);
- }
-
- public override void Write(String value)
- {
- if (value != null)
- {
-
- CheckAsyncTaskInProgress();
-
- int count = value.Length;
- int index = 0;
- while (count > 0) {
- if (charPos == charLen) Flush(false, false);
- int n = charLen - charPos;
- if (n > count) n = count;
- 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;
- count -= n;
- }
- if (autoFlush) Flush(true, false);
- }
- }
-
- #region Task based Async APIs
- [ComVisible(false)]
- public override Task WriteAsync(char value)
- {
- // If we have been inherited into a subclass, the following implementation could be incorrect
- // since it does not call through to Write() 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) when we are not sure.
- if (this.GetType() != typeof(StreamWriter))
- return base.WriteAsync(value);
-
- if (stream == null)
- __Error.WriterClosed();
-
- CheckAsyncTaskInProgress();
-
- Task task = WriteAsyncInternal(this, value, charBuffer, charPos, charLen, CoreNewLine, autoFlush, appendNewLine: false);
- _asyncWriteTask = task;
-
- return task;
- }
-
- // We pass in private instance fields of this MarshalByRefObject-derived type as local params
- // to ensure performant access inside the state machine that corresponds this async method.
- // Fields that are written to must be assigned at the end of the method *and* before instance invocations.
- private static async Task WriteAsyncInternal(StreamWriter _this, Char value,
- Char[] charBuffer, Int32 charPos, Int32 charLen, Char[] coreNewLine,
- bool autoFlush, bool appendNewLine)
- {
- if (charPos == charLen) {
- await _this.FlushAsyncInternal(false, false, charBuffer, charPos).ConfigureAwait(false);
- Debug.Assert(_this.charPos == 0);
- charPos = 0;
- }
-
- charBuffer[charPos] = value;
- charPos++;
-
- if (appendNewLine)
- {
- for (Int32 i = 0; i < coreNewLine.Length; i++) // Expect 2 iterations, no point calling BlockCopy
- {
- if (charPos == charLen) {
- await _this.FlushAsyncInternal(false, false, charBuffer, charPos).ConfigureAwait(false);
- Debug.Assert(_this.charPos == 0);
- charPos = 0;
- }
-
- charBuffer[charPos] = coreNewLine[i];
- charPos++;
- }
- }
-
- if (autoFlush) {
- await _this.FlushAsyncInternal(true, false, charBuffer, charPos).ConfigureAwait(false);
- Debug.Assert(_this.charPos == 0);
- charPos = 0;
- }
-
- _this.CharPos_Prop = charPos;
- }
-
- [ComVisible(false)]
- public override Task WriteAsync(String value)
- {
- // If we have been inherited into a subclass, the following implementation could be incorrect
- // since it does not call through to Write() 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) when we are not sure.
- if (this.GetType() != typeof(StreamWriter))
- return base.WriteAsync(value);
-
- if (value != null)
- {
- if (stream == null)
- __Error.WriterClosed();
-
- CheckAsyncTaskInProgress();
-
- Task task = WriteAsyncInternal(this, value, charBuffer, charPos, charLen, CoreNewLine, autoFlush, appendNewLine: false);
- _asyncWriteTask = task;
-
- return task;
- }
- else
- {
- return Task.CompletedTask;
- }
- }
-
- // We pass in private instance fields of this MarshalByRefObject-derived type as local params
- // to ensure performant access inside the state machine that corresponds this async method.
- // Fields that are written to must be assigned at the end of the method *and* before instance invocations.
- private static async Task WriteAsyncInternal(StreamWriter _this, String value,
- Char[] charBuffer, Int32 charPos, Int32 charLen, Char[] coreNewLine,
- bool autoFlush, bool appendNewLine)
- {
- Contract.Requires(value != null);
-
- int count = value.Length;
- int index = 0;
-
- while (count > 0)
- {
- if (charPos == charLen) {
- await _this.FlushAsyncInternal(false, false, charBuffer, charPos).ConfigureAwait(false);
- Debug.Assert(_this.charPos == 0);
- charPos = 0;
- }
-
- int n = charLen - charPos;
- if (n > count)
- n = count;
-
- 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;
- count -= n;
- }
-
- if (appendNewLine)
- {
- for (Int32 i = 0; i < coreNewLine.Length; i++) // Expect 2 iterations, no point calling BlockCopy
- {
- if (charPos == charLen) {
- await _this.FlushAsyncInternal(false, false, charBuffer, charPos).ConfigureAwait(false);
- Debug.Assert(_this.charPos == 0);
- charPos = 0;
- }
-
- charBuffer[charPos] = coreNewLine[i];
- charPos++;
- }
- }
-
- if (autoFlush) {
- await _this.FlushAsyncInternal(true, false, charBuffer, charPos).ConfigureAwait(false);
- Debug.Assert(_this.charPos == 0);
- charPos = 0;
- }
-
- _this.CharPos_Prop = charPos;
- }
-
- [ComVisible(false)]
- public override Task WriteAsync(char[] buffer, int index, int count)
- {
- if (buffer==null)
- throw new ArgumentNullException(nameof(buffer), Environment.GetResourceString("ArgumentNull_Buffer"));
- 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 (buffer.Length - index < 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() 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) when we are not sure.
- if (this.GetType() != typeof(StreamWriter))
- return base.WriteAsync(buffer, index, count);
-
- if (stream == null)
- __Error.WriterClosed();
-
- CheckAsyncTaskInProgress();
-
- Task task = WriteAsyncInternal(this, buffer, index, count, charBuffer, charPos, charLen, CoreNewLine, autoFlush, appendNewLine: false);
- _asyncWriteTask = task;
-
- return task;
- }
-
- // We pass in private instance fields of this MarshalByRefObject-derived type as local params
- // to ensure performant access inside the state machine that corresponds this async method.
- // Fields that are written to must be assigned at the end of the method *and* before instance invocations.
- private static async Task WriteAsyncInternal(StreamWriter _this, Char[] buffer, Int32 index, Int32 count,
- Char[] charBuffer, Int32 charPos, Int32 charLen, Char[] coreNewLine,
- bool autoFlush, bool appendNewLine)
- {
- Contract.Requires(count == 0 || (count > 0 && buffer != null));
- Contract.Requires(index >= 0);
- Contract.Requires(count >= 0);
- Contract.Requires(buffer == null || (buffer != null && buffer.Length - index >= count));
-
- while (count > 0)
- {
- if (charPos == charLen) {
- await _this.FlushAsyncInternal(false, false, charBuffer, charPos).ConfigureAwait(false);
- Debug.Assert(_this.charPos == 0);
- charPos = 0;
- }
-
- int n = charLen - charPos;
- if (n > count) n = count;
-
- 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;
- count -= n;
- }
-
- if (appendNewLine)
- {
- for (Int32 i = 0; i < coreNewLine.Length; i++) // Expect 2 iterations, no point calling BlockCopy
- {
- if (charPos == charLen) {
- await _this.FlushAsyncInternal(false, false, charBuffer, charPos).ConfigureAwait(false);
- Debug.Assert(_this.charPos == 0);
- charPos = 0;
- }
-
- charBuffer[charPos] = coreNewLine[i];
- charPos++;
- }
- }
-
- if (autoFlush) {
- await _this.FlushAsyncInternal(true, false, charBuffer, charPos).ConfigureAwait(false);
- Debug.Assert(_this.charPos == 0);
- charPos = 0;
- }
-
- _this.CharPos_Prop = charPos;
- }
-
- [ComVisible(false)]
- public override Task WriteLineAsync()
- {
- // If we have been inherited into a subclass, the following implementation could be incorrect
- // since it does not call through to Write() 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) when we are not sure.
- if (this.GetType() != typeof(StreamWriter))
- return base.WriteLineAsync();
-
- if (stream == null)
- __Error.WriterClosed();
-
- CheckAsyncTaskInProgress();
-
- Task task = WriteAsyncInternal(this, null, 0, 0, charBuffer, charPos, charLen, CoreNewLine, autoFlush, appendNewLine: true);
- _asyncWriteTask = task;
-
- return task;
- }
-
-
- [ComVisible(false)]
- public override Task WriteLineAsync(char value)
- {
- // If we have been inherited into a subclass, the following implementation could be incorrect
- // since it does not call through to Write() 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) when we are not sure.
- if (this.GetType() != typeof(StreamWriter))
- return base.WriteLineAsync(value);
-
- if (stream == null)
- __Error.WriterClosed();
-
- CheckAsyncTaskInProgress();
-
- Task task = WriteAsyncInternal(this, value, charBuffer, charPos, charLen, CoreNewLine, autoFlush, appendNewLine: true);
- _asyncWriteTask = task;
-
- return task;
- }
-
-
- [ComVisible(false)]
- public override Task WriteLineAsync(String value)
- {
- // If we have been inherited into a subclass, the following implementation could be incorrect
- // since it does not call through to Write() 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) when we are not sure.
- if (this.GetType() != typeof(StreamWriter))
- return base.WriteLineAsync(value);
-
- if (stream == null)
- __Error.WriterClosed();
-
- CheckAsyncTaskInProgress();
-
- Task task = WriteAsyncInternal(this, value, charBuffer, charPos, charLen, CoreNewLine, autoFlush, appendNewLine: true);
- _asyncWriteTask = task;
-
- return task;
- }
-
-
- [ComVisible(false)]
- public override Task WriteLineAsync(char[] buffer, int index, int count)
- {
- if (buffer==null)
- throw new ArgumentNullException(nameof(buffer), Environment.GetResourceString("ArgumentNull_Buffer"));
- 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 (buffer.Length - index < 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() 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) when we are not sure.
- if (this.GetType() != typeof(StreamWriter))
- return base.WriteLineAsync(buffer, index, count);
-
- if (stream == null)
- __Error.WriterClosed();
-
- CheckAsyncTaskInProgress();
-
- Task task = WriteAsyncInternal(this, buffer, index, count, charBuffer, charPos, charLen, CoreNewLine, autoFlush, appendNewLine: true);
- _asyncWriteTask = task;
-
- return task;
- }
-
-
- [ComVisible(false)]
- public override Task FlushAsync()
- {
- // 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(StreamWriter))
- return base.FlushAsync();
-
- // flushEncoder should be true at the end of the file and if
- // the user explicitly calls Flush (though not if AutoFlush is true).
- // This is required to flush any dangling characters from our UTF-7
- // and UTF-8 encoders.
- if (stream == null)
- __Error.WriterClosed();
-
- CheckAsyncTaskInProgress();
-
- Task task = FlushAsyncInternal(true, true, charBuffer, charPos);
- _asyncWriteTask = task;
-
- return task;
- }
-
- private Int32 CharPos_Prop {
- set { this.charPos = value; }
- }
-
- private bool HaveWrittenPreamble_Prop {
- set { this.haveWrittenPreamble = value; }
- }
-
- private Task FlushAsyncInternal(bool flushStream, bool flushEncoder,
- Char[] sCharBuffer, Int32 sCharPos) {
-
- // Perf boost for Flush on non-dirty writers.
- if (sCharPos == 0 && !flushStream && !flushEncoder)
- return Task.CompletedTask;
-
- Task flushTask = FlushAsyncInternal(this, flushStream, flushEncoder, sCharBuffer, sCharPos, this.haveWrittenPreamble,
- this.encoding, this.encoder, this.byteBuffer, this.stream);
-
- this.charPos = 0;
- return flushTask;
- }
-
-
- // We pass in private instance fields of this MarshalByRefObject-derived type as local params
- // to ensure performant access inside the state machine that corresponds this async method.
- private static async Task FlushAsyncInternal(StreamWriter _this, bool flushStream, bool flushEncoder,
- Char[] charBuffer, Int32 charPos, bool haveWrittenPreamble,
- Encoding encoding, Encoder encoder, Byte[] byteBuffer, Stream stream)
- {
- if (!haveWrittenPreamble)
- {
- _this.HaveWrittenPreamble_Prop = true;
- byte[] preamble = encoding.GetPreamble();
- if (preamble.Length > 0)
- await stream.WriteAsync(preamble, 0, preamble.Length).ConfigureAwait(false);
- }
-
- int count = encoder.GetBytes(charBuffer, 0, charPos, byteBuffer, 0, flushEncoder);
- if (count > 0)
- await stream.WriteAsync(byteBuffer, 0, count).ConfigureAwait(false);
-
- // By definition, calling Flush should flush the stream, but this is
- // only necessary if we passed in true for flushStream. The Web
- // Services guys have some perf tests where flushing needlessly hurts.
- if (flushStream)
- await stream.FlushAsync().ConfigureAwait(false);
- }
- #endregion
- } // class StreamWriter
-} // namespace
diff --git a/src/mscorlib/src/System/IO/TextReader.cs b/src/mscorlib/src/System/IO/TextReader.cs
index 6cbadfbce5..15ba8fba7d 100644
--- a/src/mscorlib/src/System/IO/TextReader.cs
+++ b/src/mscorlib/src/System/IO/TextReader.cs
@@ -17,7 +17,6 @@
using System.Text;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
-using System.Security.Permissions;
using System.Diagnostics.CodeAnalysis;
using System.Diagnostics.Contracts;
using System.Threading;
@@ -32,8 +31,7 @@ namespace System.IO {
// This class is intended for character input, not bytes.
// There are methods on the Stream class for reading bytes.
[Serializable]
- [ComVisible(true)]
- public abstract class TextReader : MarshalByRefObject, IDisposable {
+ internal abstract class TextReader : MarshalByRefObject, IDisposable {
public static readonly TextReader Null = new NullTextReader();
@@ -170,7 +168,6 @@ namespace System.IO {
}
#region Task based Async APIs
- [ComVisible(false)]
public virtual Task<String> ReadLineAsync()
{
return Task<String>.Factory.StartNew(state =>
@@ -180,7 +177,6 @@ namespace System.IO {
this, CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default);
}
- [ComVisible(false)]
public async virtual Task<String> ReadToEndAsync()
{
char[] chars = new char[4096];
@@ -193,7 +189,6 @@ namespace System.IO {
return sb.ToString();
}
- [ComVisible(false)]
public virtual Task<int> ReadAsync(char[] buffer, int index, int count)
{
if (buffer==null)
@@ -223,7 +218,6 @@ namespace System.IO {
tuple, CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default);
}
- [ComVisible(false)]
public virtual Task<int> ReadBlockAsync(char[] buffer, int index, int count)
{
if (buffer==null)
@@ -352,21 +346,18 @@ namespace System.IO {
// On SyncTextReader all APIs should run synchronously, even the async ones.
//
- [ComVisible(false)]
[MethodImplAttribute(MethodImplOptions.Synchronized)]
public override Task<String> ReadLineAsync()
{
return Task.FromResult(ReadLine());
}
- [ComVisible(false)]
[MethodImplAttribute(MethodImplOptions.Synchronized)]
public override Task<String> ReadToEndAsync()
{
return Task.FromResult(ReadToEnd());
}
- [ComVisible(false)]
[MethodImplAttribute(MethodImplOptions.Synchronized)]
public override Task<int> ReadBlockAsync(char[] buffer, int index, int count)
{
@@ -382,7 +373,6 @@ namespace System.IO {
return Task.FromResult(ReadBlock(buffer, index, count));
}
- [ComVisible(false)]
[MethodImplAttribute(MethodImplOptions.Synchronized)]
public override Task<int> ReadAsync(char[] buffer, int index, int count)
{
diff --git a/src/mscorlib/src/System/IO/TextWriter.cs b/src/mscorlib/src/System/IO/TextWriter.cs
deleted file mode 100644
index 131f69d35d..0000000000
--- a/src/mscorlib/src/System/IO/TextWriter.cs
+++ /dev/null
@@ -1,886 +0,0 @@
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-// See the LICENSE file in the project root for more information.
-
-using System.Text;
-using System.Threading;
-using System.Runtime.CompilerServices;
-using System.Runtime.InteropServices;
-using System.Security.Permissions;
-using System.Globalization;
-using System.Diagnostics.CodeAnalysis;
-using System.Diagnostics.Contracts;
-using System.Threading.Tasks;
-
-namespace System.IO {
- // This abstract base class represents a writer that can write a sequential
- // stream of characters. A subclass must minimally implement the
- // Write(char) method.
- //
- // This class is intended for character output, not bytes.
- // There are methods on the Stream class for writing bytes.
- [Serializable]
- [ComVisible(true)]
- public abstract class TextWriter : MarshalByRefObject, IDisposable {
- public static readonly TextWriter Null = new NullTextWriter();
-
- // This should be initialized to Environment.NewLine, but
- // to avoid loading Environment unnecessarily so I've duplicated
- // the value here.
-#if !PLATFORM_UNIX
- private const String InitialNewLine = "\r\n";
-
- protected char[] CoreNewLine = new char[] { '\r', '\n' };
-#else
- private const String InitialNewLine = "\n";
-
- protected char[] CoreNewLine = new char[] {'\n'};
-#endif // !PLATFORM_UNIX
-
- // Can be null - if so, ask for the Thread's CurrentCulture every time.
- private IFormatProvider InternalFormatProvider;
-
- protected TextWriter()
- {
- InternalFormatProvider = null; // Ask for CurrentCulture all the time.
- }
-
- protected TextWriter(IFormatProvider formatProvider)
- {
- InternalFormatProvider = formatProvider;
- }
-
- public virtual IFormatProvider FormatProvider {
- get {
- if (InternalFormatProvider == null)
- return Thread.CurrentThread.CurrentCulture;
- else
- return InternalFormatProvider;
- }
- }
-
- // Closes this TextWriter and releases any system resources associated with the
- // TextWriter. Following a call to Close, any operations on the TextWriter
- // may raise exceptions. This default method is empty, but descendant
- // classes can override the method to provide the appropriate
- // functionality.
- public virtual void Close() {
- Dispose(true);
- GC.SuppressFinalize(this);
- }
-
- protected virtual void Dispose(bool disposing)
- {
- }
-
-
- public void Dispose()
- {
- Dispose(true);
- GC.SuppressFinalize(this);
- }
-
- // Clears all buffers for this TextWriter and causes any buffered data to be
- // written to the underlying device. This default method is empty, but
- // descendant classes can override the method to provide the appropriate
- // functionality.
- public virtual void Flush() {
- }
-
- public abstract Encoding Encoding {
- get;
- }
-
- // Returns the line terminator string used by this TextWriter. The default line
- // terminator string is a carriage return followed by a line feed ("\r\n").
- //
- // Sets the line terminator string for this TextWriter. The line terminator
- // string is written to the text stream whenever one of the
- // WriteLine methods are called. In order for text written by
- // the TextWriter to be readable by a TextReader, only one of the following line
- // terminator strings should be used: "\r", "\n", or "\r\n".
- //
- public virtual String NewLine {
- get { return new String(CoreNewLine); }
- set {
- if (value == null)
- value = InitialNewLine;
- CoreNewLine = value.ToCharArray();
- }
- }
-
-
- public static TextWriter Synchronized(TextWriter writer) {
- if (writer==null)
- throw new ArgumentNullException(nameof(writer));
- Contract.Ensures(Contract.Result<TextWriter>() != null);
- Contract.EndContractBlock();
-
- if (writer is SyncTextWriter)
- return writer;
-
- return new SyncTextWriter(writer);
- }
-
- // Writes a character to the text stream. This default method is empty,
- // but descendant classes can override the method to provide the
- // appropriate functionality.
- //
- public virtual void Write(char value) {
- }
-
- // Writes a character array to the text stream. This default method calls
- // Write(char) for each of the characters in the character array.
- // If the character array is null, nothing is written.
- //
- public virtual void Write(char[] buffer) {
- if (buffer != null) Write(buffer, 0, buffer.Length);
- }
-
- // Writes a range of a character array to the text stream. This method will
- // write count characters of data into this TextWriter from the
- // buffer character array starting at position index.
- //
- public virtual void Write(char[] buffer, int index, int count) {
- if (buffer==null)
- throw new ArgumentNullException(nameof(buffer), Environment.GetResourceString("ArgumentNull_Buffer"));
- 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 (buffer.Length - index < count)
- throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen"));
- Contract.EndContractBlock();
-
- for (int i = 0; i < count; i++) Write(buffer[index + i]);
- }
-
- // Writes the text representation of a boolean to the text stream. This
- // method outputs either Boolean.TrueString or Boolean.FalseString.
- //
- public virtual void Write(bool value) {
- Write(value ? Boolean.TrueLiteral : Boolean.FalseLiteral);
- }
-
- // Writes the text representation of an integer to the text stream. The
- // text representation of the given value is produced by calling the
- // Int32.ToString() method.
- //
- public virtual void Write(int value) {
- Write(value.ToString(FormatProvider));
- }
-
- // Writes the text representation of an integer to the text stream. The
- // text representation of the given value is produced by calling the
- // UInt32.ToString() method.
- //
- [CLSCompliant(false)]
- public virtual void Write(uint value) {
- Write(value.ToString(FormatProvider));
- }
-
- // Writes the text representation of a long to the text stream. The
- // text representation of the given value is produced by calling the
- // Int64.ToString() method.
- //
- public virtual void Write(long value) {
- Write(value.ToString(FormatProvider));
- }
-
- // Writes the text representation of an unsigned long to the text
- // stream. The text representation of the given value is produced
- // by calling the UInt64.ToString() method.
- //
- [CLSCompliant(false)]
- public virtual void Write(ulong value) {
- Write(value.ToString(FormatProvider));
- }
-
- // Writes the text representation of a float to the text stream. The
- // text representation of the given value is produced by calling the
- // Float.toString(float) method.
- //
- public virtual void Write(float value) {
- Write(value.ToString(FormatProvider));
- }
-
- // Writes the text representation of a double to the text stream. The
- // text representation of the given value is produced by calling the
- // Double.toString(double) method.
- //
- public virtual void Write(double value) {
- Write(value.ToString(FormatProvider));
- }
-
- public virtual void Write(Decimal value) {
- Write(value.ToString(FormatProvider));
- }
-
- // Writes a string to the text stream. If the given string is null, nothing
- // is written to the text stream.
- //
- public virtual void Write(String value) {
- if (value != null) Write(value.ToCharArray());
- }
-
- // Writes the text representation of an object to the text stream. If the
- // given object is null, nothing is written to the text stream.
- // Otherwise, the object's ToString method is called to produce the
- // string representation, and the resulting string is then written to the
- // output stream.
- //
- public virtual void Write(Object value) {
- if (value != null) {
- IFormattable f = value as IFormattable;
- if (f != null)
- Write(f.ToString(null, FormatProvider));
- else
- Write(value.ToString());
- }
- }
-
-#if false
- // // Converts the wchar * to a string and writes this to the stream.
- // //
- // __attribute NonCLSCompliantAttribute()
- // public void Write(wchar *value) {
- // Write(new String(value));
- // }
-
- // // Treats the byte* as a LPCSTR, converts it to a string, and writes it to the stream.
- // //
- // __attribute NonCLSCompliantAttribute()
- // public void Write(byte *value) {
- // Write(new String(value));
- // }
-#endif
-
-
- // Writes out a formatted string. Uses the same semantics as
- // String.Format.
- //
- public virtual void Write(String format, Object arg0)
- {
- Write(String.Format(FormatProvider, format, arg0));
- }
-
- // Writes out a formatted string. Uses the same semantics as
- // String.Format.
- //
- public virtual void Write(String format, Object arg0, Object arg1)
- {
- Write(String.Format(FormatProvider, format, arg0, arg1));
- }
-
- // Writes out a formatted string. Uses the same semantics as
- // String.Format.
- //
- public virtual void Write(String format, Object arg0, Object arg1, Object arg2)
- {
- Write(String.Format(FormatProvider, format, arg0, arg1, arg2));
- }
-
- // Writes out a formatted string. Uses the same semantics as
- // String.Format.
- //
- public virtual void Write(String format, params Object[] arg)
- {
- Write(String.Format(FormatProvider, format, arg));
- }
-
-
- // Writes a line terminator to the text stream. The default line terminator
- // is a carriage return followed by a line feed ("\r\n"), but this value
- // can be changed by setting the NewLine property.
- //
- public virtual void WriteLine() {
- Write(CoreNewLine);
- }
-
- // Writes a character followed by a line terminator to the text stream.
- //
- public virtual void WriteLine(char value) {
- Write(value);
- WriteLine();
- }
-
- // Writes an array of characters followed by a line terminator to the text
- // stream.
- //
- public virtual void WriteLine(char[] buffer) {
- Write(buffer);
- WriteLine();
- }
-
- // Writes a range of a character array followed by a line terminator to the
- // text stream.
- //
- public virtual void WriteLine(char[] buffer, int index, int count) {
- Write(buffer, index, count);
- WriteLine();
- }
-
- // Writes the text representation of a boolean followed by a line
- // terminator to the text stream.
- //
- public virtual void WriteLine(bool value) {
- Write(value);
- WriteLine();
- }
-
- // Writes the text representation of an integer followed by a line
- // terminator to the text stream.
- //
- public virtual void WriteLine(int value) {
- Write(value);
- WriteLine();
- }
-
- // Writes the text representation of an unsigned integer followed by
- // a line terminator to the text stream.
- //
- [CLSCompliant(false)]
- public virtual void WriteLine(uint value) {
- Write(value);
- WriteLine();
- }
-
- // Writes the text representation of a long followed by a line terminator
- // to the text stream.
- //
- public virtual void WriteLine(long value) {
- Write(value);
- WriteLine();
- }
-
- // Writes the text representation of an unsigned long followed by
- // a line terminator to the text stream.
- //
- [CLSCompliant(false)]
- public virtual void WriteLine(ulong value) {
- Write(value);
- WriteLine();
- }
-
- // Writes the text representation of a float followed by a line terminator
- // to the text stream.
- //
- public virtual void WriteLine(float value) {
- Write(value);
- WriteLine();
- }
-
- // Writes the text representation of a double followed by a line terminator
- // to the text stream.
- //
- public virtual void WriteLine(double value) {
- Write(value);
- WriteLine();
- }
-
- public virtual void WriteLine(decimal value) {
- Write(value);
- WriteLine();
- }
-
- // Writes a string followed by a line terminator to the text stream.
- //
- public virtual void WriteLine(String value) {
-
- if (value==null) {
- WriteLine();
- }
- else {
- // We'd ideally like WriteLine to be atomic, in that one call
- // to WriteLine equals one call to the OS (ie, so writing to
- // console while simultaneously calling printf will guarantee we
- // write out a string and new line chars, without any interference).
- // Additionally, we need to call ToCharArray on Strings anyways,
- // so allocating a char[] here isn't any worse than what we were
- // doing anyways. We do reduce the number of calls to the
- // backing store this way, potentially.
- int vLen = value.Length;
- int nlLen = CoreNewLine.Length;
- char[] chars = new char[vLen+nlLen];
- value.CopyTo(0, chars, 0, vLen);
- // CoreNewLine will almost always be 2 chars, and possibly 1.
- if (nlLen == 2) {
- chars[vLen] = CoreNewLine[0];
- chars[vLen+1] = CoreNewLine[1];
- }
- else if (nlLen == 1)
- chars[vLen] = CoreNewLine[0];
- else
- Buffer.InternalBlockCopy(CoreNewLine, 0, chars, vLen * 2, nlLen * 2);
- Write(chars, 0, vLen + nlLen);
- }
- /*
- Write(value); // We could call Write(String) on StreamWriter...
- WriteLine();
- */
- }
-
- // Writes the text representation of an object followed by a line
- // terminator to the text stream.
- //
- public virtual void WriteLine(Object value) {
- if (value==null) {
- WriteLine();
- }
- else {
- // Call WriteLine(value.ToString), not Write(Object), WriteLine().
- // This makes calls to WriteLine(Object) atomic.
- IFormattable f = value as IFormattable;
- if (f != null)
- WriteLine(f.ToString(null, FormatProvider));
- else
- WriteLine(value.ToString());
- }
- }
-
- // Writes out a formatted string and a new line. Uses the same
- // semantics as String.Format.
- //
- public virtual void WriteLine(String format, Object arg0)
- {
- WriteLine(String.Format(FormatProvider, format, arg0));
- }
-
- // Writes out a formatted string and a new line. Uses the same
- // semantics as String.Format.
- //
- public virtual void WriteLine (String format, Object arg0, Object arg1)
- {
- WriteLine(String.Format(FormatProvider, format, arg0, arg1));
- }
-
- // Writes out a formatted string and a new line. Uses the same
- // semantics as String.Format.
- //
- public virtual void WriteLine (String format, Object arg0, Object arg1, Object arg2)
- {
- WriteLine(String.Format(FormatProvider, format, arg0, arg1, arg2));
- }
-
- // Writes out a formatted string and a new line. Uses the same
- // semantics as String.Format.
- //
- public virtual void WriteLine (String format, params Object[] arg)
- {
- WriteLine(String.Format(FormatProvider, format, arg));
- }
-
- #region Task based Async APIs
- [ComVisible(false)]
- public virtual Task WriteAsync(char value)
- {
- var tuple = new Tuple<TextWriter, char>(this, value);
- return Task.Factory.StartNew(state =>
- {
- var t = (Tuple<TextWriter, char>)state;
- t.Item1.Write(t.Item2);
- },
- tuple, CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default);
- }
-
- [ComVisible(false)]
- public virtual Task WriteAsync(String value)
- {
- var tuple = new Tuple<TextWriter, string>(this, value);
- return Task.Factory.StartNew(state =>
- {
- var t = (Tuple<TextWriter, string>)state;
- t.Item1.Write(t.Item2);
- },
- tuple, CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default);
- }
-
- [ComVisible(false)]
- public Task WriteAsync(char[] buffer)
- {
- if (buffer == null) return Task.CompletedTask;
- return WriteAsync(buffer, 0, buffer.Length);
- }
-
- [ComVisible(false)]
- public virtual Task WriteAsync(char[] buffer, int index, int count)
- {
- var tuple = new Tuple<TextWriter, char[], int, int>(this, buffer, index, count);
- return Task.Factory.StartNew(state =>
- {
- var t = (Tuple<TextWriter, char[], int, int>)state;
- t.Item1.Write(t.Item2, t.Item3, t.Item4);
- },
- tuple, CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default);
- }
-
- [ComVisible(false)]
- public virtual Task WriteLineAsync(char value)
- {
- var tuple = new Tuple<TextWriter, char>(this, value);
- return Task.Factory.StartNew(state =>
- {
- var t = (Tuple<TextWriter, char>)state;
- t.Item1.WriteLine(t.Item2);
- },
- tuple, CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default);
- }
-
- [ComVisible(false)]
- public virtual Task WriteLineAsync(String value)
- {
- var tuple = new Tuple<TextWriter, string>(this, value);
- return Task.Factory.StartNew(state =>
- {
- var t = (Tuple<TextWriter, string>)state;
- t.Item1.WriteLine(t.Item2);
- },
- tuple, CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default);
- }
-
- [ComVisible(false)]
- public Task WriteLineAsync(char[] buffer)
- {
- if (buffer == null) return Task.CompletedTask;
- return WriteLineAsync(buffer, 0, buffer.Length);
- }
-
- [ComVisible(false)]
- public virtual Task WriteLineAsync(char[] buffer, int index, int count)
- {
- var tuple = new Tuple<TextWriter, char[], int, int>(this, buffer, index, count);
- return Task.Factory.StartNew(state =>
- {
- var t = (Tuple<TextWriter, char[], int, int>)state;
- t.Item1.WriteLine(t.Item2, t.Item3, t.Item4);
- },
- tuple, CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default);
- }
-
- [ComVisible(false)]
- public virtual Task WriteLineAsync()
- {
- return WriteAsync(CoreNewLine);
- }
-
- [ComVisible(false)]
- public virtual Task FlushAsync()
- {
- return Task.Factory.StartNew(state =>
- {
- ((TextWriter)state).Flush();
- },
- this, CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default);
- }
- #endregion
-
- [Serializable]
- private sealed class NullTextWriter : TextWriter
- {
- internal NullTextWriter(): base(CultureInfo.InvariantCulture) {
- }
-
- public override Encoding Encoding {
- get { return Encoding.Default; }
- }
-
- [SuppressMessage("Microsoft.Contracts", "CC1055")] // Skip extra error checking to avoid *potential* AppCompat problems.
- public override void Write(char[] buffer, int index, int count) {
- }
-
- public override void Write(String value) {
- }
-
- // Not strictly necessary, but for perf reasons
- public override void WriteLine() {
- }
-
- // Not strictly necessary, but for perf reasons
- public override void WriteLine(String value) {
- }
-
- public override void WriteLine(Object value) {
- }
- }
-
- [Serializable]
- internal sealed class SyncTextWriter : TextWriter, IDisposable
- {
- private TextWriter _out;
-
- internal SyncTextWriter(TextWriter t): base(t.FormatProvider) {
- _out = t;
- }
-
- public override Encoding Encoding {
- get { return _out.Encoding; }
- }
-
- public override IFormatProvider FormatProvider {
- get { return _out.FormatProvider; }
- }
-
- public override String NewLine {
- [MethodImplAttribute(MethodImplOptions.Synchronized)]
- get { return _out.NewLine; }
- [MethodImplAttribute(MethodImplOptions.Synchronized)]
- set { _out.NewLine = value; }
- }
-
- [MethodImplAttribute(MethodImplOptions.Synchronized)]
- public override void Close() {
- // So that any overriden Close() gets run
- _out.Close();
- }
-
- [MethodImplAttribute(MethodImplOptions.Synchronized)]
- protected override void Dispose(bool disposing) {
- // Explicitly pick up a potentially methodimpl'ed Dispose
- if (disposing)
- ((IDisposable)_out).Dispose();
- }
-
- [MethodImplAttribute(MethodImplOptions.Synchronized)]
- public override void Flush() {
- _out.Flush();
- }
-
- [MethodImplAttribute(MethodImplOptions.Synchronized)]
- public override void Write(char value) {
- _out.Write(value);
- }
-
- [MethodImplAttribute(MethodImplOptions.Synchronized)]
- public override void Write(char[] buffer) {
- _out.Write(buffer);
- }
-
- [SuppressMessage("Microsoft.Contracts", "CC1055")] // Skip extra error checking to avoid *potential* AppCompat problems.
- [MethodImplAttribute(MethodImplOptions.Synchronized)]
- public override void Write(char[] buffer, int index, int count) {
- _out.Write(buffer, index, count);
- }
-
- [MethodImplAttribute(MethodImplOptions.Synchronized)]
- public override void Write(bool value) {
- _out.Write(value);
- }
-
- [MethodImplAttribute(MethodImplOptions.Synchronized)]
- public override void Write(int value) {
- _out.Write(value);
- }
-
- [MethodImplAttribute(MethodImplOptions.Synchronized)]
- public override void Write(uint value) {
- _out.Write(value);
- }
-
- [MethodImplAttribute(MethodImplOptions.Synchronized)]
- public override void Write(long value) {
- _out.Write(value);
- }
-
- [MethodImplAttribute(MethodImplOptions.Synchronized)]
- public override void Write(ulong value) {
- _out.Write(value);
- }
-
- [MethodImplAttribute(MethodImplOptions.Synchronized)]
- public override void Write(float value) {
- _out.Write(value);
- }
-
- [MethodImplAttribute(MethodImplOptions.Synchronized)]
- public override void Write(double value) {
- _out.Write(value);
- }
-
- [MethodImplAttribute(MethodImplOptions.Synchronized)]
- public override void Write(Decimal value) {
- _out.Write(value);
- }
-
- [MethodImplAttribute(MethodImplOptions.Synchronized)]
- public override void Write(String value) {
- _out.Write(value);
- }
-
- [MethodImplAttribute(MethodImplOptions.Synchronized)]
- public override void Write(Object value) {
- _out.Write(value);
- }
-
- [MethodImplAttribute(MethodImplOptions.Synchronized)]
- public override void Write(String format, Object arg0) {
- _out.Write(format, arg0);
- }
-
- [MethodImplAttribute(MethodImplOptions.Synchronized)]
- public override void Write(String format, Object arg0, Object arg1) {
- _out.Write(format, arg0, arg1);
- }
-
- [MethodImplAttribute(MethodImplOptions.Synchronized)]
- public override void Write(String format, Object arg0, Object arg1, Object arg2) {
- _out.Write(format, arg0, arg1, arg2);
- }
-
- [MethodImplAttribute(MethodImplOptions.Synchronized)]
- public override void Write(String format, Object[] arg) {
- _out.Write(format, arg);
- }
-
- [MethodImplAttribute(MethodImplOptions.Synchronized)]
- public override void WriteLine() {
- _out.WriteLine();
- }
-
- [MethodImplAttribute(MethodImplOptions.Synchronized)]
- public override void WriteLine(char value) {
- _out.WriteLine(value);
- }
-
- [MethodImplAttribute(MethodImplOptions.Synchronized)]
- public override void WriteLine(decimal value) {
- _out.WriteLine(value);
- }
-
- [MethodImplAttribute(MethodImplOptions.Synchronized)]
- public override void WriteLine(char[] buffer) {
- _out.WriteLine(buffer);
- }
-
- [MethodImplAttribute(MethodImplOptions.Synchronized)]
- public override void WriteLine(char[] buffer, int index, int count) {
- _out.WriteLine(buffer, index, count);
- }
-
- [MethodImplAttribute(MethodImplOptions.Synchronized)]
- public override void WriteLine(bool value) {
- _out.WriteLine(value);
- }
-
- [MethodImplAttribute(MethodImplOptions.Synchronized)]
- public override void WriteLine(int value) {
- _out.WriteLine(value);
- }
-
- [MethodImplAttribute(MethodImplOptions.Synchronized)]
- public override void WriteLine(uint value) {
- _out.WriteLine(value);
- }
-
- [MethodImplAttribute(MethodImplOptions.Synchronized)]
- public override void WriteLine(long value) {
- _out.WriteLine(value);
- }
-
- [MethodImplAttribute(MethodImplOptions.Synchronized)]
- public override void WriteLine(ulong value) {
- _out.WriteLine(value);
- }
-
- [MethodImplAttribute(MethodImplOptions.Synchronized)]
- public override void WriteLine(float value) {
- _out.WriteLine(value);
- }
-
- [MethodImplAttribute(MethodImplOptions.Synchronized)]
- public override void WriteLine(double value) {
- _out.WriteLine(value);
- }
-
- [MethodImplAttribute(MethodImplOptions.Synchronized)]
- public override void WriteLine(String value) {
- _out.WriteLine(value);
- }
-
- [MethodImplAttribute(MethodImplOptions.Synchronized)]
- public override void WriteLine(Object value) {
- _out.WriteLine(value);
- }
-
- [MethodImplAttribute(MethodImplOptions.Synchronized)]
- public override void WriteLine(String format, Object arg0) {
- _out.WriteLine(format, arg0);
- }
-
- [MethodImplAttribute(MethodImplOptions.Synchronized)]
- public override void WriteLine(String format, Object arg0, Object arg1) {
- _out.WriteLine(format, arg0, arg1);
- }
-
- [MethodImplAttribute(MethodImplOptions.Synchronized)]
- public override void WriteLine(String format, Object arg0, Object arg1, Object arg2) {
- _out.WriteLine(format, arg0, arg1, arg2);
- }
-
- [MethodImplAttribute(MethodImplOptions.Synchronized)]
- public override void WriteLine(String format, Object[] arg) {
- _out.WriteLine(format, arg);
- }
-
-
- //
- // On SyncTextWriter all APIs should run synchronously, even the async ones.
- //
-
- [MethodImplAttribute(MethodImplOptions.Synchronized)]
- [ComVisible(false)]
- public override Task WriteAsync(char value)
- {
- Write(value);
- return Task.CompletedTask;
- }
-
- [MethodImplAttribute(MethodImplOptions.Synchronized)]
- [ComVisible(false)]
- public override Task WriteAsync(String value)
- {
- Write(value);
- return Task.CompletedTask;
- }
-
- [MethodImplAttribute(MethodImplOptions.Synchronized)]
- [ComVisible(false)]
- public override Task WriteAsync(char[] buffer, int index, int count)
- {
- Write(buffer, index, count);
- return Task.CompletedTask;
- }
-
- [MethodImplAttribute(MethodImplOptions.Synchronized)]
- [ComVisible(false)]
- public override Task WriteLineAsync(char value)
- {
- WriteLine(value);
- return Task.CompletedTask;
- }
-
- [MethodImplAttribute(MethodImplOptions.Synchronized)]
- [ComVisible(false)]
- public override Task WriteLineAsync(String value)
- {
- WriteLine(value);
- return Task.CompletedTask;
- }
-
- [MethodImplAttribute(MethodImplOptions.Synchronized)]
- [ComVisible(false)]
- public override Task WriteLineAsync(char[] buffer, int index, int count)
- {
- WriteLine(buffer, index, count);
- return Task.CompletedTask;
- }
-
- [MethodImplAttribute(MethodImplOptions.Synchronized)]
- [ComVisible(false)]
- public override Task FlushAsync()
- {
- Flush();
- return Task.CompletedTask;
- }
- }
- }
-}
diff --git a/src/mscorlib/src/System/IO/UnmanagedMemoryAccessor.cs b/src/mscorlib/src/System/IO/UnmanagedMemoryAccessor.cs
index 4208ebfb6d..f3fd71833c 100644
--- a/src/mscorlib/src/System/IO/UnmanagedMemoryAccessor.cs
+++ b/src/mscorlib/src/System/IO/UnmanagedMemoryAccessor.cs
@@ -17,7 +17,6 @@ using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
using System.Runtime.ConstrainedExecution;
using System.Runtime.Versioning;
-using System.Security.Permissions;
using Microsoft.Win32.SafeHandles;
using System.Diagnostics;
using System.Diagnostics.Contracts;
diff --git a/src/mscorlib/src/System/IO/UnmanagedMemoryStream.cs b/src/mscorlib/src/System/IO/UnmanagedMemoryStream.cs
index d78632639b..165b6d2b19 100644
--- a/src/mscorlib/src/System/IO/UnmanagedMemoryStream.cs
+++ b/src/mscorlib/src/System/IO/UnmanagedMemoryStream.cs
@@ -17,7 +17,6 @@ using System.Runtime;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Security;
-using System.Security.Permissions;
using System.Threading;
using System.Diagnostics;
using System.Diagnostics.Contracts;
@@ -108,25 +107,14 @@ namespace System.IO {
}
public UnmanagedMemoryStream(SafeBuffer buffer, long offset, long length) {
- Initialize(buffer, offset, length, FileAccess.Read, false);
+ Initialize(buffer, offset, length, FileAccess.Read);
}
public UnmanagedMemoryStream(SafeBuffer buffer, long offset, long length, FileAccess access) {
- Initialize(buffer, offset, length, access, false);
- }
-
- // 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.
- internal UnmanagedMemoryStream(SafeBuffer buffer, long offset, long length, FileAccess access, bool skipSecurityCheck) {
- Initialize(buffer, offset, length, access, skipSecurityCheck);
+ Initialize(buffer, offset, length, access);
}
protected void Initialize(SafeBuffer buffer, long offset, long length, FileAccess access) {
- Initialize(buffer, offset, length, access, false);
- }
-
- internal void Initialize(SafeBuffer buffer, long offset, long length, FileAccess access, bool skipSecurityCheck) {
if (buffer == null) {
throw new ArgumentNullException(nameof(buffer));
}
@@ -147,11 +135,6 @@ namespace System.IO {
if (_isOpen) {
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_CalledTwice"));
}
- if (!skipSecurityCheck) {
-#pragma warning disable 618
- new SecurityPermission(SecurityPermissionFlag.UnmanagedCode).Demand();
-#pragma warning restore 618
- }
// check for wraparound
unsafe {
@@ -181,31 +164,18 @@ namespace System.IO {
[CLSCompliant(false)]
public unsafe UnmanagedMemoryStream(byte* pointer, long length)
{
- Initialize(pointer, length, length, FileAccess.Read, false);
+ Initialize(pointer, length, length, FileAccess.Read);
}
[CLSCompliant(false)]
public unsafe UnmanagedMemoryStream(byte* pointer, long length, long capacity, FileAccess access)
{
- Initialize(pointer, length, capacity, access, false);
- }
-
- // 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.
- internal unsafe UnmanagedMemoryStream(byte* pointer, long length, long capacity, FileAccess access, bool skipSecurityCheck)
- {
- Initialize(pointer, length, capacity, access, skipSecurityCheck);
+ Initialize(pointer, length, capacity, access);
}
[CLSCompliant(false)]
protected unsafe void Initialize(byte* pointer, long length, long capacity, FileAccess access)
{
- Initialize(pointer, length, capacity, access, false);
- }
-
- internal unsafe void Initialize(byte* pointer, long length, long capacity, FileAccess access, bool skipSecurityCheck)
- {
if (pointer == null)
throw new ArgumentNullException(nameof(pointer));
if (length < 0 || capacity < 0)
@@ -221,12 +191,6 @@ namespace System.IO {
if (_isOpen)
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_CalledTwice"));
- if (!skipSecurityCheck) {
-#pragma warning disable 618
- new SecurityPermission(SecurityPermissionFlag.UnmanagedCode).Demand();
-#pragma warning restore 618
- }
-
_mem = pointer;
_offset = 0;
_length = length;
@@ -265,7 +229,6 @@ namespace System.IO {
if (!_isOpen) __Error.StreamIsClosed();
}
- [ComVisible(false)]
public override Task FlushAsync(CancellationToken cancellationToken) {
if (cancellationToken.IsCancellationRequested)
@@ -421,7 +384,6 @@ namespace System.IO {
return nInt;
}
- [ComVisible(false)]
public override Task<Int32> ReadAsync(Byte[] buffer, Int32 offset, Int32 count, CancellationToken cancellationToken) {
if (buffer==null)
throw new ArgumentNullException(nameof(buffer), Environment.GetResourceString("ArgumentNull_Buffer"));
@@ -618,7 +580,6 @@ namespace System.IO {
return;
}
- [ComVisible(false)]
public override Task WriteAsync(Byte[] buffer, Int32 offset, Int32 count, CancellationToken cancellationToken) {
if (buffer==null)
diff --git a/src/mscorlib/src/System/IO/UnmanagedMemoryStreamWrapper.cs b/src/mscorlib/src/System/IO/UnmanagedMemoryStreamWrapper.cs
index 040ddbb3d7..99b257ea56 100644
--- a/src/mscorlib/src/System/IO/UnmanagedMemoryStreamWrapper.cs
+++ b/src/mscorlib/src/System/IO/UnmanagedMemoryStreamWrapper.cs
@@ -13,7 +13,6 @@
using System;
using System.Runtime.InteropServices;
-using System.Security.Permissions;
using System.Diagnostics.CodeAnalysis;
using System.Diagnostics.Contracts;
using System.Threading;
diff --git a/src/mscorlib/src/System/IO/__Error.cs b/src/mscorlib/src/System/IO/__Error.cs
index ad4972de54..955ddbec63 100644
--- a/src/mscorlib/src/System/IO/__Error.cs
+++ b/src/mscorlib/src/System/IO/__Error.cs
@@ -21,7 +21,6 @@ using Win32Native = Microsoft.Win32.Win32Native;
using System.Text;
using System.Globalization;
using System.Security;
-using System.Security.Permissions;
using System.Diagnostics.Contracts;
namespace System.IO {
@@ -51,10 +50,6 @@ namespace System.IO {
internal static void ReadNotSupported() {
throw new NotSupportedException(Environment.GetResourceString("NotSupported_UnreadableStream"));
}
-
- internal static void SeekNotSupported() {
- throw new NotSupportedException(Environment.GetResourceString("NotSupported_UnseekableStream"));
- }
internal static void WrongAsyncResult() {
throw new ArgumentException(Environment.GetResourceString("Arg_WrongAsyncResult"));
@@ -187,34 +182,11 @@ namespace System.IO {
throw new IOException(Win32Native.GetMessage(errorCode), Win32Native.MakeHRFromErrorCode(errorCode), maybeFullPath);
}
}
-
- // An alternative to WinIOError with friendlier messages for drives
- internal static void WinIODriveError(String driveName) {
- int errorCode = Marshal.GetLastWin32Error();
- WinIODriveError(driveName, errorCode);
- }
-
- internal static void WinIODriveError(String driveName, int errorCode)
- {
- switch (errorCode) {
- case Win32Native.ERROR_PATH_NOT_FOUND:
- case Win32Native.ERROR_INVALID_DRIVE:
- throw new DriveNotFoundException(Environment.GetResourceString("IO.DriveNotFound_Drive", driveName));
-
- default:
- WinIOError(errorCode, driveName);
- break;
- }
- }
internal static void WriteNotSupported() {
throw new NotSupportedException(Environment.GetResourceString("NotSupported_UnwritableStream"));
}
- internal static void WriterClosed() {
- throw new ObjectDisposedException(null, Environment.GetResourceString("ObjectDisposed_WriterClosed"));
- }
-
// From WinError.h
internal const int ERROR_FILE_NOT_FOUND = Win32Native.ERROR_FILE_NOT_FOUND;
internal const int ERROR_PATH_NOT_FOUND = Win32Native.ERROR_PATH_NOT_FOUND;
diff --git a/src/mscorlib/src/System/IObservable.cs b/src/mscorlib/src/System/IObservable.cs
index c231c45485..aabb0b8fb4 100644
--- a/src/mscorlib/src/System/IObservable.cs
+++ b/src/mscorlib/src/System/IObservable.cs
@@ -2,23 +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: Interface for exposing an Observable in the
-** Observer pattern
-**
-**
-===========================================================*/
-
namespace System
{
public interface IObservable<out T>
{
IDisposable Subscribe(IObserver<T> observer);
}
-
}
diff --git a/src/mscorlib/src/System/IObserver.cs b/src/mscorlib/src/System/IObserver.cs
index 7f55ce0c46..39e123de8d 100644
--- a/src/mscorlib/src/System/IObserver.cs
+++ b/src/mscorlib/src/System/IObserver.cs
@@ -2,20 +2,6 @@
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
-/*============================================================
-**
-**
-**
-**
-**
-** Purpose: Interface for exposing an Observer in the
-** Observer pattern
-**
-**
-===========================================================*/
-
-using System;
-
namespace System
{
public interface IObserver<in T>
diff --git a/src/mscorlib/src/System/IProgress.cs b/src/mscorlib/src/System/IProgress.cs
index e1043015ce..724c7bdce9 100644
--- a/src/mscorlib/src/System/IProgress.cs
+++ b/src/mscorlib/src/System/IProgress.cs
@@ -2,17 +2,6 @@
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
-/*============================================================
-**
-**
-**
-**
-**
-** Purpose: Interface for providing progress updates.
-**
-**
-===========================================================*/
-
namespace System
{
/// <summary>Defines a provider for progress updates.</summary>
diff --git a/src/mscorlib/src/System/IndexOutOfRangeException.cs b/src/mscorlib/src/System/IndexOutOfRangeException.cs
index e641b5eab4..4969c2b86d 100644
--- a/src/mscorlib/src/System/IndexOutOfRangeException.cs
+++ b/src/mscorlib/src/System/IndexOutOfRangeException.cs
@@ -11,30 +11,31 @@
**
=============================================================================*/
-namespace System {
-
- using System.Runtime.Serialization;
- [System.Runtime.InteropServices.ComVisible(true)]
+using System.Runtime.Serialization;
+
+namespace System
+{
[Serializable]
- public sealed class IndexOutOfRangeException : SystemException {
- public IndexOutOfRangeException()
- : base(Environment.GetResourceString("Arg_IndexOutOfRangeException")) {
- SetErrorCode(__HResults.COR_E_INDEXOUTOFRANGE);
- }
-
- public IndexOutOfRangeException(String message)
- : base(message) {
- SetErrorCode(__HResults.COR_E_INDEXOUTOFRANGE);
+ public sealed class IndexOutOfRangeException : SystemException
+ {
+ public IndexOutOfRangeException()
+ : base(SR.Arg_IndexOutOfRangeException)
+ {
+ HResult = __HResults.COR_E_INDEXOUTOFRANGE;
}
-
- public IndexOutOfRangeException(String message, Exception innerException)
- : base(message, innerException) {
- SetErrorCode(__HResults.COR_E_INDEXOUTOFRANGE);
+
+ public IndexOutOfRangeException(String message)
+ : base(message)
+ {
+ HResult = __HResults.COR_E_INDEXOUTOFRANGE;
}
- internal IndexOutOfRangeException(SerializationInfo info, StreamingContext context) : base(info, context) {
+ public IndexOutOfRangeException(String message, Exception innerException)
+ : base(message, innerException)
+ {
+ HResult = __HResults.COR_E_INDEXOUTOFRANGE;
}
+ internal IndexOutOfRangeException(SerializationInfo info, StreamingContext context) : base(info, context) { }
}
-
}
diff --git a/src/mscorlib/src/System/InsufficientExecutionStackException.cs b/src/mscorlib/src/System/InsufficientExecutionStackException.cs
index 6b02f46f29..b9a4a12ddd 100644
--- a/src/mscorlib/src/System/InsufficientExecutionStackException.cs
+++ b/src/mscorlib/src/System/InsufficientExecutionStackException.cs
@@ -2,46 +2,31 @@
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
-/*=============================================================================
-**
-**
-**
-** Purpose: The exception class used when there is insufficient execution stack
-** to allow most Framework methods to execute.
-**
-**
-=============================================================================*/
-
-namespace System {
-
- using System;
- using System.Runtime.Serialization;
+using System.Runtime.Serialization;
+namespace System
+{
[Serializable]
- public sealed class InsufficientExecutionStackException : SystemException
+ public sealed class InsufficientExecutionStackException : SystemException
{
public InsufficientExecutionStackException()
- : base(Environment.GetResourceString("Arg_InsufficientExecutionStackException"))
- {
- SetErrorCode(__HResults.COR_E_INSUFFICIENTEXECUTIONSTACK);
- }
-
- public InsufficientExecutionStackException(String message)
- : base(message)
+ : base(SR.Arg_InsufficientExecutionStackException)
{
- SetErrorCode(__HResults.COR_E_INSUFFICIENTEXECUTIONSTACK);
+ HResult = __HResults.COR_E_INSUFFICIENTEXECUTIONSTACK;
}
-
- public InsufficientExecutionStackException(String message, Exception innerException)
- : base(message, innerException)
+
+ public InsufficientExecutionStackException(String message)
+ : base(message)
{
- SetErrorCode(__HResults.COR_E_INSUFFICIENTEXECUTIONSTACK);
+ HResult = __HResults.COR_E_INSUFFICIENTEXECUTIONSTACK;
}
- private InsufficientExecutionStackException(SerializationInfo info, StreamingContext context)
- : base(info, context)
+ public InsufficientExecutionStackException(String message, Exception innerException)
+ : base(message, innerException)
{
+ HResult = __HResults.COR_E_INSUFFICIENTEXECUTIONSTACK;
}
-
+
+ internal InsufficientExecutionStackException(SerializationInfo info, StreamingContext context) : base(info, context) { }
}
}
diff --git a/src/mscorlib/src/System/Int16.cs b/src/mscorlib/src/System/Int16.cs
index f02a5f2cda..a5e62233e4 100644
--- a/src/mscorlib/src/System/Int16.cs
+++ b/src/mscorlib/src/System/Int16.cs
@@ -19,7 +19,6 @@ namespace System {
using System.Runtime.InteropServices;
using System.Diagnostics.Contracts;
-[System.Runtime.InteropServices.ComVisible(true)]
[Serializable]
[System.Runtime.InteropServices.StructLayout(LayoutKind.Sequential)]
public struct Int16 : IComparable, IFormattable, IConvertible
diff --git a/src/mscorlib/src/System/Int32.cs b/src/mscorlib/src/System/Int32.cs
index 2da55bf089..0e1ed56a41 100644
--- a/src/mscorlib/src/System/Int32.cs
+++ b/src/mscorlib/src/System/Int32.cs
@@ -21,7 +21,6 @@ namespace System {
[Serializable]
[System.Runtime.InteropServices.StructLayout(LayoutKind.Sequential)]
-[System.Runtime.InteropServices.ComVisible(true)]
public struct Int32 : IComparable, IFormattable, IConvertible
, IComparable<Int32>, IEquatable<Int32>
{
diff --git a/src/mscorlib/src/System/Int64.cs b/src/mscorlib/src/System/Int64.cs
index e5fcf86c3b..3520ede533 100644
--- a/src/mscorlib/src/System/Int64.cs
+++ b/src/mscorlib/src/System/Int64.cs
@@ -20,7 +20,6 @@ namespace System {
[Serializable]
[System.Runtime.InteropServices.StructLayout(LayoutKind.Sequential)]
-[System.Runtime.InteropServices.ComVisible(true)]
public struct Int64 : IComparable, IFormattable, IConvertible
, IComparable<Int64>, IEquatable<Int64>
{
diff --git a/src/mscorlib/src/System/IntPtr.cs b/src/mscorlib/src/System/IntPtr.cs
index 2d66652ab8..dbddcd319a 100644
--- a/src/mscorlib/src/System/IntPtr.cs
+++ b/src/mscorlib/src/System/IntPtr.cs
@@ -23,7 +23,6 @@ namespace System {
using System.Diagnostics.Contracts;
[Serializable]
- [System.Runtime.InteropServices.ComVisible(true)]
public struct IntPtr : IEquatable<IntPtr>, ISerializable
{
unsafe private void* m_value; // The compiler treats void* closest to uint hence explicit casts are required to preserve int behavior
@@ -32,13 +31,11 @@ namespace System {
// fast way to compare IntPtr to (IntPtr)0 while IntPtr.Zero doesn't work due to slow statics access
[Pure]
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
internal unsafe bool IsNull()
{
return (this.m_value == null);
}
- [ReliabilityContract(Consistency.MayCorruptInstance, Cer.MayFail)]
[System.Runtime.Versioning.NonVersionable]
public unsafe IntPtr(int value)
{
@@ -49,7 +46,6 @@ namespace System {
#endif
}
- [ReliabilityContract(Consistency.MayCorruptInstance, Cer.MayFail)]
[System.Runtime.Versioning.NonVersionable]
public unsafe IntPtr(long value)
{
@@ -61,7 +57,6 @@ namespace System {
}
[CLSCompliant(false)]
- [ReliabilityContract(Consistency.MayCorruptInstance, Cer.MayFail)]
[System.Runtime.Versioning.NonVersionable]
public unsafe IntPtr(void* value)
{
@@ -111,7 +106,6 @@ namespace System {
#endif
}
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
[System.Runtime.Versioning.NonVersionable]
public unsafe int ToInt32() {
#if BIT64
@@ -122,7 +116,6 @@ namespace System {
#endif
}
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
[System.Runtime.Versioning.NonVersionable]
public unsafe long ToInt64() {
#if BIT64
@@ -152,14 +145,12 @@ namespace System {
}
- [ReliabilityContract(Consistency.MayCorruptInstance, Cer.MayFail)]
[System.Runtime.Versioning.NonVersionable]
public static explicit operator IntPtr (int value)
{
return new IntPtr(value);
}
- [ReliabilityContract(Consistency.MayCorruptInstance, Cer.MayFail)]
[System.Runtime.Versioning.NonVersionable]
public static explicit operator IntPtr (long value)
{
@@ -201,28 +192,24 @@ namespace System {
#endif
}
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
[System.Runtime.Versioning.NonVersionable]
public unsafe static bool operator == (IntPtr value1, IntPtr value2)
{
return value1.m_value == value2.m_value;
}
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
[System.Runtime.Versioning.NonVersionable]
public unsafe static bool operator != (IntPtr value1, IntPtr value2)
{
return value1.m_value != value2.m_value;
}
- [ReliabilityContract(Consistency.MayCorruptInstance, Cer.MayFail)]
[System.Runtime.Versioning.NonVersionable]
public static IntPtr Add(IntPtr pointer, int offset)
{
return pointer + offset;
}
- [ReliabilityContract(Consistency.MayCorruptInstance, Cer.MayFail)]
[System.Runtime.Versioning.NonVersionable]
public static IntPtr operator +(IntPtr pointer, int offset)
{
@@ -233,13 +220,11 @@ namespace System {
#endif
}
- [ReliabilityContract(Consistency.MayCorruptInstance, Cer.MayFail)]
[System.Runtime.Versioning.NonVersionable]
public static IntPtr Subtract(IntPtr pointer, int offset) {
return pointer - offset;
}
- [ReliabilityContract(Consistency.MayCorruptInstance, Cer.MayFail)]
[System.Runtime.Versioning.NonVersionable]
public static IntPtr operator -(IntPtr pointer, int offset) {
#if BIT64
@@ -252,7 +237,6 @@ namespace System {
public static int Size
{
[Pure]
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
[System.Runtime.Versioning.NonVersionable]
get
{
@@ -266,7 +250,6 @@ namespace System {
[CLSCompliant(false)]
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
[System.Runtime.Versioning.NonVersionable]
public unsafe void* ToPointer()
{
diff --git a/src/mscorlib/src/System/Internal.cs b/src/mscorlib/src/System/Internal.cs
index 0eb2bced72..b0860109d9 100644
--- a/src/mscorlib/src/System/Internal.cs
+++ b/src/mscorlib/src/System/Internal.cs
@@ -19,15 +19,7 @@ using System.StubHelpers;
using System.Threading.Tasks;
#if FEATURE_COMINTEROP
-
using System.Runtime.InteropServices.WindowsRuntime;
-
-[assembly:Guid("BED7F4EA-1A96-11d2-8F08-00A0C9A6186D")]
-
-// The following attribute are required to ensure COM compatibility.
-[assembly:System.Runtime.InteropServices.ComCompatibleVersion(1, 0, 3300, 0)]
-[assembly:System.Runtime.InteropServices.TypeLibVersion(2, 4)]
-
#endif // FEATURE_COMINTEROP
[assembly:DefaultDependencyAttribute(LoadHint.Always)]
diff --git a/src/mscorlib/src/System/InvalidCastException.cs b/src/mscorlib/src/System/InvalidCastException.cs
index ba7b722434..01d92b2837 100644
--- a/src/mscorlib/src/System/InvalidCastException.cs
+++ b/src/mscorlib/src/System/InvalidCastException.cs
@@ -4,42 +4,41 @@
/*=============================================================================
**
-**
-**
-** Purpose: Exception class for bad cast conditions!
-**
+** Purpose: Exception class for invalid cast conditions!
**
=============================================================================*/
-namespace System {
-
- using System.Runtime.Serialization;
- [System.Runtime.InteropServices.ComVisible(true)]
+using System.Runtime.Serialization;
+
+namespace System
+{
[Serializable]
- public class InvalidCastException : SystemException {
- public InvalidCastException()
- : base(Environment.GetResourceString("Arg_InvalidCastException")) {
- SetErrorCode(__HResults.COR_E_INVALIDCAST);
- }
-
- public InvalidCastException(String message)
- : base(message) {
- SetErrorCode(__HResults.COR_E_INVALIDCAST);
+ public class InvalidCastException : SystemException
+ {
+ public InvalidCastException()
+ : base(SR.Arg_InvalidCastException)
+ {
+ HResult = __HResults.COR_E_INVALIDCAST;
}
- public InvalidCastException(String message, Exception innerException)
- : base(message, innerException) {
- SetErrorCode(__HResults.COR_E_INVALIDCAST);
+ public InvalidCastException(String message)
+ : base(message)
+ {
+ HResult = __HResults.COR_E_INVALIDCAST;
}
- protected InvalidCastException(SerializationInfo info, StreamingContext context) : base(info, context) {
+ public InvalidCastException(String message, Exception innerException)
+ : base(message, innerException)
+ {
+ HResult = __HResults.COR_E_INVALIDCAST;
}
- public InvalidCastException(String message, int errorCode)
- : base(message) {
- SetErrorCode(errorCode);
+ public InvalidCastException(String message, int errorCode)
+ : base(message)
+ {
+ HResult = errorCode;
}
+ protected InvalidCastException(SerializationInfo info, StreamingContext context) : base(info, context) { }
}
-
}
diff --git a/src/mscorlib/src/System/InvalidOperationException.cs b/src/mscorlib/src/System/InvalidOperationException.cs
index 5f29e79056..24a08c8089 100644
--- a/src/mscorlib/src/System/InvalidOperationException.cs
+++ b/src/mscorlib/src/System/InvalidOperationException.cs
@@ -11,31 +11,32 @@
**
**
=============================================================================*/
-namespace System {
-
- using System.Runtime.Serialization;
- [System.Runtime.InteropServices.ComVisible(true)]
+
+using System.Runtime.Serialization;
+
+namespace System
+{
[Serializable]
public class InvalidOperationException : SystemException
{
- public InvalidOperationException()
- : base(Environment.GetResourceString("Arg_InvalidOperationException")) {
- SetErrorCode(__HResults.COR_E_INVALIDOPERATION);
- }
-
- public InvalidOperationException(String message)
- : base(message) {
- SetErrorCode(__HResults.COR_E_INVALIDOPERATION);
+ public InvalidOperationException()
+ : base(SR.Arg_InvalidOperationException)
+ {
+ HResult = __HResults.COR_E_INVALIDOPERATION;
}
-
- public InvalidOperationException(String message, Exception innerException)
- : base(message, innerException) {
- SetErrorCode(__HResults.COR_E_INVALIDOPERATION);
+
+ public InvalidOperationException(String message)
+ : base(message)
+ {
+ HResult = __HResults.COR_E_INVALIDOPERATION;
}
- protected InvalidOperationException(SerializationInfo info, StreamingContext context) : base(info, context) {
+ public InvalidOperationException(String message, Exception innerException)
+ : base(message, innerException)
+ {
+ HResult = __HResults.COR_E_INVALIDOPERATION;
}
+ protected InvalidOperationException(SerializationInfo info, StreamingContext context) : base(info, context) { }
}
}
-
diff --git a/src/mscorlib/src/System/InvalidProgramException.cs b/src/mscorlib/src/System/InvalidProgramException.cs
index 649849a8bd..401b3a0ddb 100644
--- a/src/mscorlib/src/System/InvalidProgramException.cs
+++ b/src/mscorlib/src/System/InvalidProgramException.cs
@@ -11,31 +11,31 @@
**
=============================================================================*/
-namespace System {
+using System.Runtime.Serialization;
- using System;
- using System.Runtime.Serialization;
+namespace System
+{
[Serializable]
- [System.Runtime.InteropServices.ComVisible(true)]
- public sealed class InvalidProgramException : SystemException {
- public InvalidProgramException()
- : base(Environment.GetResourceString("InvalidProgram_Default")) {
- SetErrorCode(__HResults.COR_E_INVALIDPROGRAM);
+ public sealed class InvalidProgramException : SystemException
+ {
+ public InvalidProgramException()
+ : base(SR.InvalidProgram_Default)
+ {
+ HResult = __HResults.COR_E_INVALIDPROGRAM;
}
-
- public InvalidProgramException(String message)
- : base(message) {
- SetErrorCode(__HResults.COR_E_INVALIDPROGRAM);
- }
-
- public InvalidProgramException(String message, Exception inner)
- : base(message, inner) {
- SetErrorCode(__HResults.COR_E_INVALIDPROGRAM);
+
+ public InvalidProgramException(String message)
+ : base(message)
+ {
+ HResult = __HResults.COR_E_INVALIDPROGRAM;
}
- internal InvalidProgramException(SerializationInfo info, StreamingContext context) : base(info, context) {
+ public InvalidProgramException(String message, Exception inner)
+ : base(message, inner)
+ {
+ HResult = __HResults.COR_E_INVALIDPROGRAM;
}
+ internal InvalidProgramException(SerializationInfo info, StreamingContext context) : base(info, context) { }
}
-
}
diff --git a/src/mscorlib/src/System/InvalidTimeZoneException.cs b/src/mscorlib/src/System/InvalidTimeZoneException.cs
index f33475497a..8f0751c426 100644
--- a/src/mscorlib/src/System/InvalidTimeZoneException.cs
+++ b/src/mscorlib/src/System/InvalidTimeZoneException.cs
@@ -6,19 +6,23 @@ using System.Runtime.Serialization;
namespace System
{
- [Serializable]
- [System.Security.Permissions.HostProtection(MayLeakOnAbort = true)]
- public class InvalidTimeZoneException : Exception
- {
- public InvalidTimeZoneException(String message)
- : base(message) { }
+ [Serializable]
+ public class InvalidTimeZoneException : Exception
+ {
+ public InvalidTimeZoneException()
+ {
+ }
- public InvalidTimeZoneException(String message, Exception innerException)
- : base(message, innerException) { }
+ public InvalidTimeZoneException(String message)
+ : base(message)
+ {
+ }
- protected InvalidTimeZoneException(SerializationInfo info, StreamingContext context)
- : base(info, context) { }
+ public InvalidTimeZoneException(String message, Exception innerException)
+ : base(message, innerException)
+ {
+ }
- public InvalidTimeZoneException() { }
- }
+ protected InvalidTimeZoneException(SerializationInfo info, StreamingContext context) : base(info, context) { }
+ }
}
diff --git a/src/mscorlib/src/System/Lazy.cs b/src/mscorlib/src/System/Lazy.cs
index 85cbb9816a..0ddd6da3a2 100644
--- a/src/mscorlib/src/System/Lazy.cs
+++ b/src/mscorlib/src/System/Lazy.cs
@@ -18,7 +18,6 @@
using System.Runtime;
using System.Runtime.InteropServices;
using System.Security;
-using System.Security.Permissions;
using System.Diagnostics;
using System.Runtime.Serialization;
using System.Threading;
@@ -47,7 +46,6 @@ namespace System
/// </para>
/// </remarks>
[Serializable]
- [ComVisible(false)]
[DebuggerTypeProxy(typeof(System_LazyDebugView<>))]
[DebuggerDisplay("ThreadSafetyMode={Mode}, IsValueCreated={IsValueCreated}, IsValueFaulted={IsValueFaulted}, Value={ValueForDebugDisplay}")]
public class Lazy<T>
diff --git a/src/mscorlib/src/System/LowLevelConsole.cs b/src/mscorlib/src/System/LowLevelConsole.cs
index 316583e276..29e69185ac 100644
--- a/src/mscorlib/src/System/LowLevelConsole.cs
+++ b/src/mscorlib/src/System/LowLevelConsole.cs
@@ -10,18 +10,14 @@ using Microsoft.Win32.SafeHandles;
namespace System
{
//
- // Simple limited console class for internal printf-style debugging in mscorlib
- // and low-level tests that just want to depend on mscorlib.
+ // Simple limited console class for internal printf-style debugging in System.Private.CoreLib
+ // and low-level tests that want to call System.Private.CoreLib directly
//
- public static class Console
+ public static class LowLevelConsole
{
- static SafeFileHandle _outputHandle;
-
- static Console()
- {
- _outputHandle = new SafeFileHandle(Win32Native.GetStdHandle(Win32Native.STD_OUTPUT_HANDLE), false);
- }
+ private static readonly SafeFileHandle _outputHandle =
+ new SafeFileHandle(Win32Native.GetStdHandle(Win32Native.STD_OUTPUT_HANDLE), false);
public static unsafe void Write(string s)
{
@@ -44,4 +40,26 @@ namespace System
Write(Environment.NewLine);
}
}
+
+ //
+ // Internal wrapper with the regular name for convenience. Note that it cannot be public to avoid colliding
+ // with the full Console type.
+ //
+ internal static class Console
+ {
+ public static void Write(string s)
+ {
+ LowLevelConsole.Write(s);
+ }
+
+ public static void WriteLine(string s)
+ {
+ LowLevelConsole.WriteLine(s);
+ }
+
+ public static void WriteLine()
+ {
+ LowLevelConsole.WriteLine();
+ }
+ }
}
diff --git a/src/mscorlib/src/System/MarshalByRefObject.cs b/src/mscorlib/src/System/MarshalByRefObject.cs
index 53ebda7672..9014de00c7 100644
--- a/src/mscorlib/src/System/MarshalByRefObject.cs
+++ b/src/mscorlib/src/System/MarshalByRefObject.cs
@@ -2,32 +2,25 @@
// 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 marshal by reference aka
-** AppDomain bound types
-**
-**
-**
-===========================================================*/
namespace System
{
[Serializable]
- [System.Runtime.InteropServices.ComVisible(true)]
- public abstract class MarshalByRefObject
+ public abstract class MarshalByRefObject
{
- protected MarshalByRefObject() { }
+ protected MarshalByRefObject()
+ {
+ }
+
public object GetLifetimeService()
{
throw new PlatformNotSupportedException();
}
+
public virtual object InitializeLifetimeService()
{
throw new PlatformNotSupportedException();
}
+
protected MarshalByRefObject MemberwiseClone(bool cloneIdentity)
{
MarshalByRefObject mbr = (MarshalByRefObject)base.MemberwiseClone();
diff --git a/src/mscorlib/src/System/Math.cs b/src/mscorlib/src/System/Math.cs
index 3ac1f0694a..8b2af3d3e4 100644
--- a/src/mscorlib/src/System/Math.cs
+++ b/src/mscorlib/src/System/Math.cs
@@ -149,7 +149,6 @@ namespace System {
return InternalTruncate(d);
}
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public static extern double Sqrt(double d);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
@@ -294,58 +293,49 @@ namespace System {
**Returns the larger of val1 and val2
============================================================================*/
[CLSCompliant(false)]
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
[System.Runtime.Versioning.NonVersionable]
public static sbyte Max(sbyte val1, sbyte val2) {
return (val1>=val2)?val1:val2;
}
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
[System.Runtime.Versioning.NonVersionable]
public static byte Max(byte val1, byte val2) {
return (val1>=val2)?val1:val2;
}
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
[System.Runtime.Versioning.NonVersionable]
public static short Max(short val1, short val2) {
return (val1>=val2)?val1:val2;
}
[CLSCompliant(false)]
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
[System.Runtime.Versioning.NonVersionable]
public static ushort Max(ushort val1, ushort val2) {
return (val1>=val2)?val1:val2;
}
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
[System.Runtime.Versioning.NonVersionable]
public static int Max(int val1, int val2) {
return (val1>=val2)?val1:val2;
}
[CLSCompliant(false)]
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
[System.Runtime.Versioning.NonVersionable]
public static uint Max(uint val1, uint val2) {
return (val1>=val2)?val1:val2;
}
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
[System.Runtime.Versioning.NonVersionable]
public static long Max(long val1, long val2) {
return (val1>=val2)?val1:val2;
}
[CLSCompliant(false)]
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
[System.Runtime.Versioning.NonVersionable]
public static ulong Max(ulong val1, ulong val2) {
return (val1>=val2)?val1:val2;
}
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
public static float Max(float val1, float val2) {
if (val1 > val2)
return val1;
@@ -356,7 +346,6 @@ namespace System {
return val2;
}
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
public static double Max(double val1, double val2) {
if (val1 > val2)
return val1;
@@ -367,7 +356,6 @@ namespace System {
return val2;
}
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
public static Decimal Max(Decimal val1, Decimal val2) {
return Decimal.Max(val1,val2);
}
@@ -376,58 +364,49 @@ namespace System {
**Returns the smaller of val1 and val2.
============================================================================*/
[CLSCompliant(false)]
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
[System.Runtime.Versioning.NonVersionable]
public static sbyte Min(sbyte val1, sbyte val2) {
return (val1<=val2)?val1:val2;
}
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
[System.Runtime.Versioning.NonVersionable]
public static byte Min(byte val1, byte val2) {
return (val1<=val2)?val1:val2;
}
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
[System.Runtime.Versioning.NonVersionable]
public static short Min(short val1, short val2) {
return (val1<=val2)?val1:val2;
}
[CLSCompliant(false)]
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
[System.Runtime.Versioning.NonVersionable]
public static ushort Min(ushort val1, ushort val2) {
return (val1<=val2)?val1:val2;
}
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
[System.Runtime.Versioning.NonVersionable]
public static int Min(int val1, int val2) {
return (val1<=val2)?val1:val2;
}
[CLSCompliant(false)]
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
[System.Runtime.Versioning.NonVersionable]
public static uint Min(uint val1, uint val2) {
return (val1<=val2)?val1:val2;
}
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
[System.Runtime.Versioning.NonVersionable]
public static long Min(long val1, long val2) {
return (val1<=val2)?val1:val2;
}
[CLSCompliant(false)]
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
[System.Runtime.Versioning.NonVersionable]
public static ulong Min(ulong val1, ulong val2) {
return (val1<=val2)?val1:val2;
}
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
public static float Min(float val1, float val2) {
if (val1 < val2)
return val1;
@@ -438,7 +417,6 @@ namespace System {
return val2;
}
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
public static double Min(double val1, double val2) {
if (val1 < val2)
return val1;
@@ -449,7 +427,6 @@ namespace System {
return val2;
}
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
public static Decimal Min(Decimal val1, Decimal val2) {
return Decimal.Min(val1,val2);
}
diff --git a/src/mscorlib/src/System/MathF.cs b/src/mscorlib/src/System/MathF.cs
index fb800924b5..545774cc32 100644
--- a/src/mscorlib/src/System/MathF.cs
+++ b/src/mscorlib/src/System/MathF.cs
@@ -143,10 +143,8 @@ namespace System {
[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)]
@@ -201,7 +199,6 @@ namespace System {
[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);
diff --git a/src/mscorlib/src/System/MemberAccessException.cs b/src/mscorlib/src/System/MemberAccessException.cs
index bc21248dae..54eee67b07 100644
--- a/src/mscorlib/src/System/MemberAccessException.cs
+++ b/src/mscorlib/src/System/MemberAccessException.cs
@@ -8,41 +8,41 @@
// access, due to it being removed, private or something similar.
////////////////////////////////////////////////////////////////////////////////
-namespace System {
-
- using System;
- using System.Runtime.Serialization;
+using System.Runtime.Serialization;
+
+namespace System
+{
// The MemberAccessException is thrown when trying to access a class
// member fails.
//
- [System.Runtime.InteropServices.ComVisible(true)]
[Serializable]
- public class MemberAccessException : SystemException {
-
+ public class MemberAccessException : SystemException
+ {
// Creates a new MemberAccessException with its message string set to
// the empty string, its HRESULT set to COR_E_MEMBERACCESS,
// and its ExceptionInfo reference set to null.
- public MemberAccessException()
- : base(Environment.GetResourceString("Arg_AccessException")) {
- SetErrorCode(__HResults.COR_E_MEMBERACCESS);
+ public MemberAccessException()
+ : base(SR.Arg_AccessException)
+ {
+ HResult = __HResults.COR_E_MEMBERACCESS;
}
-
+
// Creates a new MemberAccessException with its message string set to
// message, its HRESULT set to COR_E_ACCESS,
// and its ExceptionInfo reference set to null.
//
- public MemberAccessException(String message)
- : base(message) {
- SetErrorCode(__HResults.COR_E_MEMBERACCESS);
- }
-
- public MemberAccessException(String message, Exception inner)
- : base(message, inner) {
- SetErrorCode(__HResults.COR_E_MEMBERACCESS);
+ public MemberAccessException(String message)
+ : base(message)
+ {
+ HResult = __HResults.COR_E_MEMBERACCESS;
}
- protected MemberAccessException(SerializationInfo info, StreamingContext context) : base(info, context) {
+ public MemberAccessException(String message, Exception inner)
+ : base(message, inner)
+ {
+ HResult = __HResults.COR_E_MEMBERACCESS;
}
+ protected MemberAccessException(SerializationInfo info, StreamingContext context) : base(info, context) { }
}
}
diff --git a/src/mscorlib/src/System/MethodAccessException.cs b/src/mscorlib/src/System/MethodAccessException.cs
index 3feaf3ed54..2ecbd14d6d 100644
--- a/src/mscorlib/src/System/MethodAccessException.cs
+++ b/src/mscorlib/src/System/MethodAccessException.cs
@@ -9,31 +9,31 @@
**
=============================================================================*/
-namespace System {
-
- using System;
- using System.Runtime.Serialization;
- [System.Runtime.InteropServices.ComVisible(true)]
+using System.Runtime.Serialization;
+
+namespace System
+{
[Serializable]
- public class MethodAccessException : MemberAccessException {
- public MethodAccessException()
- : base(Environment.GetResourceString("Arg_MethodAccessException")) {
- SetErrorCode(__HResults.COR_E_METHODACCESS);
- }
-
- public MethodAccessException(String message)
- : base(message) {
- SetErrorCode(__HResults.COR_E_METHODACCESS);
+ public class MethodAccessException : MemberAccessException
+ {
+ public MethodAccessException()
+ : base(SR.Arg_MethodAccessException)
+ {
+ HResult = __HResults.COR_E_METHODACCESS;
}
-
- public MethodAccessException(String message, Exception inner)
- : base(message, inner) {
- SetErrorCode(__HResults.COR_E_METHODACCESS);
+
+ public MethodAccessException(String message)
+ : base(message)
+ {
+ HResult = __HResults.COR_E_METHODACCESS;
}
- protected MethodAccessException(SerializationInfo info, StreamingContext context) : base(info, context) {
+ public MethodAccessException(String message, Exception inner)
+ : base(message, inner)
+ {
+ HResult = __HResults.COR_E_METHODACCESS;
}
+ protected MethodAccessException(SerializationInfo info, StreamingContext context) : base(info, context) { }
}
-
}
diff --git a/src/mscorlib/src/System/MidpointRounding.cs b/src/mscorlib/src/System/MidpointRounding.cs
index ff709240c5..a75de43e65 100644
--- a/src/mscorlib/src/System/MidpointRounding.cs
+++ b/src/mscorlib/src/System/MidpointRounding.cs
@@ -2,11 +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 {
-
-[System.Runtime.InteropServices.ComVisible(true)]
- public enum MidpointRounding {
+namespace System
+{
+ public enum MidpointRounding
+ {
ToEven = 0,
AwayFromZero = 1,
}
diff --git a/src/mscorlib/src/System/MissingFieldException.cs b/src/mscorlib/src/System/MissingFieldException.cs
index d96d0378e3..660e39cb47 100644
--- a/src/mscorlib/src/System/MissingFieldException.cs
+++ b/src/mscorlib/src/System/MissingFieldException.cs
@@ -16,7 +16,6 @@ namespace System {
using System.Runtime.Serialization;
using System.Runtime.CompilerServices;
using System.Globalization;
- [System.Runtime.InteropServices.ComVisible(true)]
[Serializable]
public class MissingFieldException : MissingMemberException, ISerializable {
public MissingFieldException()
@@ -51,14 +50,6 @@ namespace System {
}
}
- // Called from the EE
- private MissingFieldException(String className, String fieldName, byte[] signature)
- {
- ClassName = className;
- MemberName = fieldName;
- Signature = signature;
- }
-
public MissingFieldException(String className, String fieldName)
{
ClassName = className;
diff --git a/src/mscorlib/src/System/MissingMemberException.cs b/src/mscorlib/src/System/MissingMemberException.cs
index ab773dc467..bb9be8827a 100644
--- a/src/mscorlib/src/System/MissingMemberException.cs
+++ b/src/mscorlib/src/System/MissingMemberException.cs
@@ -18,11 +18,9 @@ namespace System {
using System.Runtime.Serialization;
using System.Runtime.CompilerServices;
using System.Globalization;
- using System.Security.Permissions;
using System.Runtime.Versioning;
using System.Diagnostics.Contracts;
- [System.Runtime.InteropServices.ComVisible(true)]
[Serializable]
public class MissingMemberException : MemberAccessException, ISerializable {
public MissingMemberException()
@@ -64,16 +62,6 @@ namespace System {
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern String FormatSignature(byte [] signature);
-
-
- // Potentially called from the EE
- private MissingMemberException(String className, String memberName, byte[] signature)
- {
- ClassName = className;
- MemberName = memberName;
- Signature = signature;
- }
-
public MissingMemberException(String className, String memberName)
{
ClassName = className;
diff --git a/src/mscorlib/src/System/MissingMethodException.cs b/src/mscorlib/src/System/MissingMethodException.cs
index 79434900a1..426711f953 100644
--- a/src/mscorlib/src/System/MissingMethodException.cs
+++ b/src/mscorlib/src/System/MissingMethodException.cs
@@ -18,7 +18,6 @@ namespace System {
using System.Runtime.Serialization;
using System.Runtime.CompilerServices;
using System.Globalization;
- [System.Runtime.InteropServices.ComVisible(true)]
[Serializable]
public class MissingMethodException : MissingMemberException, ISerializable {
public MissingMethodException()
@@ -53,14 +52,6 @@ namespace System {
}
}
- // Called from the EE
- private MissingMethodException(String className, String methodName, byte[] signature)
- {
- ClassName = className;
- MemberName = methodName;
- Signature = signature;
- }
-
public MissingMethodException(String className, String methodName)
{
ClassName = className;
diff --git a/src/mscorlib/src/System/MulticastDelegate.cs b/src/mscorlib/src/System/MulticastDelegate.cs
index a7b244cdae..aa3271ceab 100644
--- a/src/mscorlib/src/System/MulticastDelegate.cs
+++ b/src/mscorlib/src/System/MulticastDelegate.cs
@@ -466,10 +466,9 @@ namespace System
{
// Create an array of delegate copies and each
// element into the array
- int invocationCount = (int)_invocationCount;
- del = new Delegate[invocationCount];
+ del = new Delegate[(int)_invocationCount];
- for (int i = 0; i < invocationCount; i++)
+ for (int i = 0; i < del.Length; i++)
del[i] = (Delegate)invocationList[i];
}
return del;
diff --git a/src/mscorlib/src/System/MulticastNotSupportedException.cs b/src/mscorlib/src/System/MulticastNotSupportedException.cs
index ad8eeebb21..4fcaa9857d 100644
--- a/src/mscorlib/src/System/MulticastNotSupportedException.cs
+++ b/src/mscorlib/src/System/MulticastNotSupportedException.cs
@@ -7,31 +7,31 @@
// This is thrown when you add multiple callbacks to a non-multicast delegate.
////////////////////////////////////////////////////////////////////////////////
-namespace System {
-
- using System;
- using System.Runtime.Serialization;
- [System.Runtime.InteropServices.ComVisible(true)]
+using System.Runtime.Serialization;
+
+namespace System
+{
[Serializable]
- public sealed class MulticastNotSupportedException : SystemException {
-
- public MulticastNotSupportedException()
- : base(Environment.GetResourceString("Arg_MulticastNotSupportedException")) {
- SetErrorCode(__HResults.COR_E_MULTICASTNOTSUPPORTED);
- }
-
- public MulticastNotSupportedException(String message)
- : base(message) {
- SetErrorCode(__HResults.COR_E_MULTICASTNOTSUPPORTED);
+ public sealed class MulticastNotSupportedException : SystemException
+ {
+ public MulticastNotSupportedException()
+ : base(SR.Arg_MulticastNotSupportedException)
+ {
+ HResult = __HResults.COR_E_MULTICASTNOTSUPPORTED;
}
-
- public MulticastNotSupportedException(String message, Exception inner)
- : base(message, inner) {
- SetErrorCode(__HResults.COR_E_MULTICASTNOTSUPPORTED);
+
+ public MulticastNotSupportedException(String message)
+ : base(message)
+ {
+ HResult = __HResults.COR_E_MULTICASTNOTSUPPORTED;
}
- internal MulticastNotSupportedException(SerializationInfo info, StreamingContext context) : base(info, context) {
+ public MulticastNotSupportedException(String message, Exception inner)
+ : base(message, inner)
+ {
+ HResult = __HResults.COR_E_MULTICASTNOTSUPPORTED;
}
+ internal MulticastNotSupportedException(SerializationInfo info, StreamingContext context) : base(info, context) { }
}
}
diff --git a/src/mscorlib/src/System/NonSerializedAttribute.cs b/src/mscorlib/src/System/NonSerializedAttribute.cs
index c3cd9a540c..39f186212a 100644
--- a/src/mscorlib/src/System/NonSerializedAttribute.cs
+++ b/src/mscorlib/src/System/NonSerializedAttribute.cs
@@ -15,7 +15,6 @@ namespace System
using System.Reflection;
[AttributeUsage(AttributeTargets.Field, Inherited=false)]
- [System.Runtime.InteropServices.ComVisible(true)]
public sealed class NonSerializedAttribute : Attribute
{
internal static Attribute GetCustomAttribute(RuntimeFieldInfo field)
diff --git a/src/mscorlib/src/System/NotFiniteNumberException.cs b/src/mscorlib/src/System/NotFiniteNumberException.cs
index 3a896ce548..68e8f88d81 100644
--- a/src/mscorlib/src/System/NotFiniteNumberException.cs
+++ b/src/mscorlib/src/System/NotFiniteNumberException.cs
@@ -2,68 +2,70 @@
// 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;
- using System.Runtime.Serialization;
- using System.Security.Permissions;
- using System.Diagnostics.Contracts;
+using System.Runtime.Serialization;
- [System.Runtime.InteropServices.ComVisible(true)]
+namespace System
+{
[Serializable]
- public class NotFiniteNumberException : ArithmeticException {
+ public class NotFiniteNumberException : ArithmeticException
+ {
private double _offendingNumber;
public NotFiniteNumberException()
- : base(Environment.GetResourceString("Arg_NotFiniteNumberException")) {
+ : base(SR.Arg_NotFiniteNumberException)
+ {
_offendingNumber = 0;
- SetErrorCode(__HResults.COR_E_NOTFINITENUMBER);
+ HResult = __HResults.COR_E_NOTFINITENUMBER;
}
public NotFiniteNumberException(double offendingNumber)
- : base() {
+ : base()
+ {
_offendingNumber = offendingNumber;
- SetErrorCode(__HResults.COR_E_NOTFINITENUMBER);
+ HResult = __HResults.COR_E_NOTFINITENUMBER;
}
public NotFiniteNumberException(String message)
- : base(message) {
+ : base(message)
+ {
_offendingNumber = 0;
- SetErrorCode(__HResults.COR_E_NOTFINITENUMBER);
+ HResult = __HResults.COR_E_NOTFINITENUMBER;
}
public NotFiniteNumberException(String message, double offendingNumber)
- : base(message) {
+ : base(message)
+ {
_offendingNumber = offendingNumber;
- SetErrorCode(__HResults.COR_E_NOTFINITENUMBER);
+ HResult = __HResults.COR_E_NOTFINITENUMBER;
}
public NotFiniteNumberException(String message, Exception innerException)
- : base(message, innerException) {
- SetErrorCode(__HResults.COR_E_NOTFINITENUMBER);
+ : base(message, innerException)
+ {
+ HResult = __HResults.COR_E_NOTFINITENUMBER;
}
public NotFiniteNumberException(String message, double offendingNumber, Exception innerException)
- : base(message, innerException) {
+ : base(message, innerException)
+ {
_offendingNumber = offendingNumber;
- SetErrorCode(__HResults.COR_E_NOTFINITENUMBER);
+ HResult = __HResults.COR_E_NOTFINITENUMBER;
}
- protected NotFiniteNumberException(SerializationInfo info, StreamingContext context) : base(info, context) {
+ protected NotFiniteNumberException(SerializationInfo info, StreamingContext context) : base(info, context)
+ {
_offendingNumber = info.GetInt32("OffendingNumber");
}
- public double OffendingNumber {
- get { return _offendingNumber; }
- }
-
- public override void GetObjectData(SerializationInfo info, StreamingContext context) {
- if (info==null) {
- throw new ArgumentNullException(nameof(info));
- }
- Contract.EndContractBlock();
+ public override void GetObjectData(SerializationInfo info, StreamingContext context)
+ {
base.GetObjectData(info, context);
info.AddValue("OffendingNumber", _offendingNumber, typeof(Int32));
}
+
+ public double OffendingNumber
+ {
+ get { return _offendingNumber; }
+ }
}
}
diff --git a/src/mscorlib/src/System/NotImplementedException.cs b/src/mscorlib/src/System/NotImplementedException.cs
index d6c966805a..4d141eac8c 100644
--- a/src/mscorlib/src/System/NotImplementedException.cs
+++ b/src/mscorlib/src/System/NotImplementedException.cs
@@ -12,29 +12,29 @@
**
=============================================================================*/
-namespace System {
-
- using System;
- using System.Runtime.Serialization;
+using System.Runtime.Serialization;
- [System.Runtime.InteropServices.ComVisible(true)]
+namespace System
+{
[Serializable]
public class NotImplementedException : SystemException
{
- public NotImplementedException()
- : base(Environment.GetResourceString("Arg_NotImplementedException")) {
- SetErrorCode(__HResults.E_NOTIMPL);
+ public NotImplementedException()
+ : base(SR.Arg_NotImplementedException)
+ {
+ HResult = __HResults.E_NOTIMPL;
}
- public NotImplementedException(String message)
- : base(message) {
- SetErrorCode(__HResults.E_NOTIMPL);
+ public NotImplementedException(String message)
+ : base(message)
+ {
+ HResult = __HResults.E_NOTIMPL;
}
- public NotImplementedException(String message, Exception inner)
- : base(message, inner) {
- SetErrorCode(__HResults.E_NOTIMPL);
+ public NotImplementedException(String message, Exception inner)
+ : base(message, inner)
+ {
+ HResult = __HResults.E_NOTIMPL;
}
- protected NotImplementedException(SerializationInfo info, StreamingContext context) : base(info, context) {
- }
+ protected NotImplementedException(SerializationInfo info, StreamingContext context) : base(info, context) { }
}
}
diff --git a/src/mscorlib/src/System/NotSupportedException.cs b/src/mscorlib/src/System/NotSupportedException.cs
index ecef1d199a..21b2d54a46 100644
--- a/src/mscorlib/src/System/NotSupportedException.cs
+++ b/src/mscorlib/src/System/NotSupportedException.cs
@@ -11,31 +11,31 @@
**
=============================================================================*/
-namespace System {
-
- using System;
- using System.Runtime.Serialization;
- [System.Runtime.InteropServices.ComVisible(true)]
+using System.Runtime.Serialization;
+
+namespace System
+{
[Serializable]
public class NotSupportedException : SystemException
{
- public NotSupportedException()
- : base(Environment.GetResourceString("Arg_NotSupportedException")) {
- SetErrorCode(__HResults.COR_E_NOTSUPPORTED);
- }
-
- public NotSupportedException(String message)
- : base(message) {
- SetErrorCode(__HResults.COR_E_NOTSUPPORTED);
+ public NotSupportedException()
+ : base(SR.Arg_NotSupportedException)
+ {
+ HResult = __HResults.COR_E_NOTSUPPORTED;
}
-
- public NotSupportedException(String message, Exception innerException)
- : base(message, innerException) {
- SetErrorCode(__HResults.COR_E_NOTSUPPORTED);
+
+ public NotSupportedException(String message)
+ : base(message)
+ {
+ HResult = __HResults.COR_E_NOTSUPPORTED;
}
- protected NotSupportedException(SerializationInfo info, StreamingContext context) : base(info, context) {
+ public NotSupportedException(String message, Exception innerException)
+ : base(message, innerException)
+ {
+ HResult = __HResults.COR_E_NOTSUPPORTED;
}
+ protected NotSupportedException(SerializationInfo info, StreamingContext context) : base(info, context) { }
}
}
diff --git a/src/mscorlib/src/System/NullReferenceException.cs b/src/mscorlib/src/System/NullReferenceException.cs
index d66ad9ca41..0aa5c6197a 100644
--- a/src/mscorlib/src/System/NullReferenceException.cs
+++ b/src/mscorlib/src/System/NullReferenceException.cs
@@ -11,30 +11,31 @@
**
=============================================================================*/
-namespace System {
-
- using System;
- using System.Runtime.Serialization;
- [System.Runtime.InteropServices.ComVisible(true)]
+using System.Runtime.Serialization;
+
+namespace System
+{
[Serializable]
- public class NullReferenceException : SystemException {
- public NullReferenceException()
- : base(Environment.GetResourceString("Arg_NullReferenceException")) {
- SetErrorCode(__HResults.COR_E_NULLREFERENCE);
- }
-
- public NullReferenceException(String message)
- : base(message) {
- SetErrorCode(__HResults.COR_E_NULLREFERENCE);
+ public class NullReferenceException : SystemException
+ {
+ public NullReferenceException()
+ : base(SR.Arg_NullReferenceException)
+ {
+ HResult = __HResults.COR_E_NULLREFERENCE;
}
-
- public NullReferenceException(String message, Exception innerException)
- : base(message, innerException) {
- SetErrorCode(__HResults.COR_E_NULLREFERENCE);
+
+ public NullReferenceException(String message)
+ : base(message)
+ {
+ HResult = __HResults.COR_E_NULLREFERENCE;
}
- protected NullReferenceException(SerializationInfo info, StreamingContext context) : base(info, context) {}
+ public NullReferenceException(String message, Exception innerException)
+ : base(message, innerException)
+ {
+ HResult = __HResults.COR_E_NULLREFERENCE;
+ }
+ protected NullReferenceException(SerializationInfo info, StreamingContext context) : base(info, context) { }
}
-
}
diff --git a/src/mscorlib/src/System/Nullable.cs b/src/mscorlib/src/System/Nullable.cs
index 8a22c8e65c..5ade2875c5 100644
--- a/src/mscorlib/src/System/Nullable.cs
+++ b/src/mscorlib/src/System/Nullable.cs
@@ -101,10 +101,8 @@ namespace System
// bool IEquatable<Nullable<T>>.Equals(Nullable<T> other)
}
- [System.Runtime.InteropServices.ComVisible(true)]
public static class Nullable
{
- [System.Runtime.InteropServices.ComVisible(true)]
public static int Compare<T>(Nullable<T> n1, Nullable<T> n2) where T : struct
{
if (n1.HasValue) {
@@ -115,7 +113,6 @@ namespace System
return 0;
}
- [System.Runtime.InteropServices.ComVisible(true)]
public static bool Equals<T>(Nullable<T> n1, Nullable<T> n2) where T : struct
{
if (n1.HasValue) {
diff --git a/src/mscorlib/src/System/Number.cs b/src/mscorlib/src/System/Number.cs
index 3412c02c31..66d05673a6 100644
--- a/src/mscorlib/src/System/Number.cs
+++ b/src/mscorlib/src/System/Number.cs
@@ -310,10 +310,6 @@ namespace System {
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal unsafe static extern Boolean NumberBufferToDouble(byte* number, ref Double value);
- [MethodImplAttribute(MethodImplOptions.InternalCall)]
- [System.Runtime.CompilerServices.FriendAccessAllowed]
- internal static extern unsafe string FormatNumberBuffer(byte* number, string format, NumberFormatInfo info, char* allDigits);
-
// Constants used by number parsing
private const Int32 NumberMaxDigits = 50;
diff --git a/src/mscorlib/src/System/Numerics/Hashing/HashHelpers.cs b/src/mscorlib/src/System/Numerics/Hashing/HashHelpers.cs
index 0314d1af3c..f017309a90 100644
--- a/src/mscorlib/src/System/Numerics/Hashing/HashHelpers.cs
+++ b/src/mscorlib/src/System/Numerics/Hashing/HashHelpers.cs
@@ -8,12 +8,14 @@ namespace System.Numerics.Hashing
internal static class HashHelpers
{
+ public static readonly int RandomSeed = new Random().Next(Int32.MinValue, Int32.MaxValue);
+
public static int Combine(int h1, int h2)
{
- // The jit optimizes this to use the ROL instruction on x86
+ // RyuJIT optimizes this to use the ROL instruction
// Related GitHub pull request: dotnet/coreclr#1830
- uint shift5 = ((uint)h1 << 5) | ((uint)h1 >> 27);
- return ((int)shift5 + h1) ^ h2;
+ uint rol5 = ((uint)h1 << 5) | ((uint)h1 >> 27);
+ return ((int)rol5 + h1) ^ h2;
}
}
}
diff --git a/src/mscorlib/src/System/Object.cs b/src/mscorlib/src/System/Object.cs
index d8d9a0e36c..1f47d8cdef 100644
--- a/src/mscorlib/src/System/Object.cs
+++ b/src/mscorlib/src/System/Object.cs
@@ -37,7 +37,6 @@ namespace System
public class Object
{
// Creates a new instance of an Object.
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
[System.Runtime.Versioning.NonVersionable]
public Object()
{
@@ -73,7 +72,6 @@ public class Object
return objA.Equals(objB);
}
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
[System.Runtime.Versioning.NonVersionable]
public static bool ReferenceEquals (Object objA, Object objB) {
return objA == objB;
@@ -101,7 +99,6 @@ public class Object
// Allow an object to free resources before the object is reclaimed by the GC.
//
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
[System.Runtime.Versioning.NonVersionable]
~Object()
{
diff --git a/src/mscorlib/src/System/ObjectDisposedException.cs b/src/mscorlib/src/System/ObjectDisposedException.cs
index d2eca37325..1f77b1f009 100644
--- a/src/mscorlib/src/System/ObjectDisposedException.cs
+++ b/src/mscorlib/src/System/ObjectDisposedException.cs
@@ -2,72 +2,81 @@
// 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;
- using System.Runtime.Serialization;
- using System.Globalization;
- using System.Security.Permissions;
+using System.Globalization;
+using System.Runtime.Serialization;
+namespace System
+{
/// <devdoc>
/// <para> The exception that is thrown when accessing an object that was
/// disposed.</para>
/// </devdoc>
- [System.Runtime.InteropServices.ComVisible(true)]
[Serializable]
- public class ObjectDisposedException : InvalidOperationException {
- private String objectName;
+ public class ObjectDisposedException : InvalidOperationException
+ {
+ private String _objectName;
// This constructor should only be called by the EE (COMPlusThrow)
- private ObjectDisposedException() :
- this(null ,Environment.GetResourceString("ObjectDisposed_Generic")) {
+ private ObjectDisposedException() :
+ this(null, SR.ObjectDisposed_Generic)
+ {
}
- public ObjectDisposedException(String objectName) :
- this(objectName, Environment.GetResourceString("ObjectDisposed_Generic")) {
+ public ObjectDisposedException(String objectName) :
+ this(objectName, SR.ObjectDisposed_Generic)
+ {
}
- public ObjectDisposedException(String objectName, String message) : base(message) {
- SetErrorCode(__HResults.COR_E_OBJECTDISPOSED);
- this.objectName = objectName;
+ public ObjectDisposedException(String objectName, String message) : base(message)
+ {
+ HResult = __HResults.COR_E_OBJECTDISPOSED;
+ _objectName = objectName;
}
- public ObjectDisposedException(String message, Exception innerException)
- : base(message, innerException) {
- SetErrorCode(__HResults.COR_E_OBJECTDISPOSED);
+ public ObjectDisposedException(String message, Exception innerException)
+ : base(message, innerException)
+ {
+ HResult = __HResults.COR_E_OBJECTDISPOSED;
+ }
+
+ protected ObjectDisposedException(SerializationInfo info, StreamingContext context)
+ : base(info, context)
+ {
+ _objectName = info.GetString("ObjectName");
+ }
+
+ public override void GetObjectData(SerializationInfo info, StreamingContext context)
+ {
+ base.GetObjectData(info, context);
+ info.AddValue("ObjectName",ObjectName,typeof(String));
}
/// <devdoc>
/// <para>Gets the text for the message for this exception.</para>
/// </devdoc>
- public override String Message {
- get {
+ public override String Message
+ {
+ get
+ {
String name = ObjectName;
if (name == null || name.Length == 0)
return base.Message;
- String objectDisposed = Environment.GetResourceString("ObjectDisposed_ObjectName_Name", name);
+ String objectDisposed = SR.Format(SR.ObjectDisposed_ObjectName_Name, name);
return base.Message + Environment.NewLine + objectDisposed;
}
}
- public String ObjectName {
- get {
- if (objectName == null)
+ public String ObjectName
+ {
+ get
+ {
+ if ((_objectName == null)) // && !CompatibilitySwitches.IsAppEarlierThanWindowsPhone8)
{
return String.Empty;
}
- return objectName;
+ return _objectName;
}
}
-
- protected ObjectDisposedException(SerializationInfo info, StreamingContext context) : base(info, context) {
- objectName = info.GetString("ObjectName");
- }
-
- 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/ObsoleteAttribute.cs b/src/mscorlib/src/System/ObsoleteAttribute.cs
index 679e32a974..f183685998 100644
--- a/src/mscorlib/src/System/ObsoleteAttribute.cs
+++ b/src/mscorlib/src/System/ObsoleteAttribute.cs
@@ -10,51 +10,52 @@
**
**
===========================================================*/
-namespace System {
-
- using System;
- using System.Runtime.Remoting;
+
+using System;
+
+namespace System
+{
// This attribute is attached to members that are not to be used any longer.
// Message is some human readable explanation of what to use
// Error indicates if the compiler should treat usage of such a method as an
// error. (this would be used if the actual implementation of the obsolete
// method's implementation had changed).
//
-[Serializable]
-[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Enum |
- AttributeTargets.Interface | AttributeTargets.Constructor | AttributeTargets.Method| AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Delegate
+ [Serializable]
+ [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Enum |
+ AttributeTargets.Interface | AttributeTargets.Constructor | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Delegate
, Inherited = false)]
-[System.Runtime.InteropServices.ComVisible(true)]
public sealed class ObsoleteAttribute : Attribute
{
private String _message;
private bool _error;
-
- public ObsoleteAttribute ()
+
+ public ObsoleteAttribute()
{
_message = null;
_error = false;
}
-
- public ObsoleteAttribute (String message)
+
+ public ObsoleteAttribute(String message)
{
_message = message;
_error = false;
}
-
- public ObsoleteAttribute (String message, bool error)
+
+ public ObsoleteAttribute(String message, bool error)
{
_message = message;
_error = error;
}
-
- public String Message {
- get {return _message;}
+
+ public String Message
+ {
+ get { return _message; }
}
-
- public bool IsError{
- get {return _error;}
+
+ public bool IsError
+ {
+ get { return _error; }
}
-
}
}
diff --git a/src/mscorlib/src/System/OperatingSystem.cs b/src/mscorlib/src/System/OperatingSystem.cs
index a11d4bcce8..a388fc6e33 100644
--- a/src/mscorlib/src/System/OperatingSystem.cs
+++ b/src/mscorlib/src/System/OperatingSystem.cs
@@ -13,14 +13,12 @@
namespace System {
using System.Runtime.Serialization;
using System.Globalization;
- using System.Security.Permissions;
using System.Runtime.InteropServices;
using System.Diagnostics.Contracts;
- [ComVisible(true)]
[Serializable]
- public sealed class OperatingSystem : ICloneable , ISerializable
+ internal sealed class OperatingSystem : ICloneable , ISerializable
{
private Version _version;
private PlatformID _platform;
@@ -30,9 +28,6 @@ namespace System {
private OperatingSystem()
{
}
-
- public OperatingSystem(PlatformID platform, Version version) : this(platform, version, null) {
- }
internal OperatingSystem(PlatformID platform, Version version, string servicePack) {
if( platform < PlatformID.Win32S || platform > PlatformID.MacOSX) {
@@ -82,20 +77,6 @@ namespace System {
info.AddValue("_servicePack", _servicePack);
}
- public PlatformID Platform {
- get { return _platform; }
- }
-
- public string ServicePack {
- get {
- if( _servicePack == null) {
- return string.Empty;
- }
-
- return _servicePack;
- }
- }
-
public Version Version {
get { return _version; }
}
diff --git a/src/mscorlib/src/System/OperationCanceledException.cs b/src/mscorlib/src/System/OperationCanceledException.cs
index 14781f5653..061201637a 100644
--- a/src/mscorlib/src/System/OperationCanceledException.cs
+++ b/src/mscorlib/src/System/OperationCanceledException.cs
@@ -18,7 +18,6 @@ using System.Threading;
namespace System {
[Serializable]
- [System.Runtime.InteropServices.ComVisible(true)]
public class OperationCanceledException : SystemException
{
[NonSerialized]
diff --git a/src/mscorlib/src/System/OutOfMemoryException.cs b/src/mscorlib/src/System/OutOfMemoryException.cs
index 9bea0b46d7..46d5195405 100644
--- a/src/mscorlib/src/System/OutOfMemoryException.cs
+++ b/src/mscorlib/src/System/OutOfMemoryException.cs
@@ -16,7 +16,6 @@ namespace System {
using System;
using System.Runtime.Serialization;
- [System.Runtime.InteropServices.ComVisible(true)]
[Serializable]
public class OutOfMemoryException : SystemException {
public OutOfMemoryException()
diff --git a/src/mscorlib/src/System/OverflowException.cs b/src/mscorlib/src/System/OverflowException.cs
index ab717fb065..e28c688dd6 100644
--- a/src/mscorlib/src/System/OverflowException.cs
+++ b/src/mscorlib/src/System/OverflowException.cs
@@ -11,32 +11,31 @@
**
=============================================================================*/
-namespace System {
-
-
- using System;
- using System.Runtime.Serialization;
- [System.Runtime.InteropServices.ComVisible(true)]
+using System.Runtime.Serialization;
+
+namespace System
+{
[Serializable]
- public class OverflowException : ArithmeticException {
- public OverflowException()
- : base(Environment.GetResourceString("Arg_OverflowException")) {
- SetErrorCode(__HResults.COR_E_OVERFLOW);
- }
-
- public OverflowException(String message)
- : base(message) {
- SetErrorCode(__HResults.COR_E_OVERFLOW);
+ public class OverflowException : ArithmeticException
+ {
+ public OverflowException()
+ : base(SR.Arg_OverflowException)
+ {
+ HResult = __HResults.COR_E_OVERFLOW;
}
-
- public OverflowException(String message, Exception innerException)
- : base(message, innerException) {
- SetErrorCode(__HResults.COR_E_OVERFLOW);
+
+ public OverflowException(String message)
+ : base(message)
+ {
+ HResult = __HResults.COR_E_OVERFLOW;
}
- protected OverflowException(SerializationInfo info, StreamingContext context) : base(info, context) {
+ public OverflowException(String message, Exception innerException)
+ : base(message, innerException)
+ {
+ HResult = __HResults.COR_E_OVERFLOW;
}
+ protected OverflowException(SerializationInfo info, StreamingContext context) : base(info, context) { }
}
-
}
diff --git a/src/mscorlib/src/System/ParamArrayAttribute.cs b/src/mscorlib/src/System/ParamArrayAttribute.cs
index 3a8e2e8302..d3c3d46d56 100644
--- a/src/mscorlib/src/System/ParamArrayAttribute.cs
+++ b/src/mscorlib/src/System/ParamArrayAttribute.cs
@@ -10,13 +10,12 @@
**
**
=============================================================================*/
+
namespace System
{
-//This class contains only static members and does not need to be serializable
- [AttributeUsage (AttributeTargets.Parameter, Inherited=true, AllowMultiple=false)]
-[System.Runtime.InteropServices.ComVisible(true)]
- public sealed class ParamArrayAttribute : Attribute
- {
- public ParamArrayAttribute () {}
- }
+ [AttributeUsage(AttributeTargets.Parameter, Inherited = true, AllowMultiple = false)]
+ public sealed class ParamArrayAttribute : Attribute
+ {
+ public ParamArrayAttribute() { }
+ }
}
diff --git a/src/mscorlib/src/System/PlatformID.cs b/src/mscorlib/src/System/PlatformID.cs
index 57941996ee..16128079e2 100644
--- a/src/mscorlib/src/System/PlatformID.cs
+++ b/src/mscorlib/src/System/PlatformID.cs
@@ -13,8 +13,7 @@
namespace System {
[Serializable]
-[System.Runtime.InteropServices.ComVisible(true)]
- public enum PlatformID
+ internal enum PlatformID
{
Win32S = 0,
Win32Windows = 1,
diff --git a/src/mscorlib/src/System/PlatformNotSupportedException.cs b/src/mscorlib/src/System/PlatformNotSupportedException.cs
index 75d6d1d110..d2370b3924 100644
--- a/src/mscorlib/src/System/PlatformNotSupportedException.cs
+++ b/src/mscorlib/src/System/PlatformNotSupportedException.cs
@@ -11,32 +11,31 @@
**
=============================================================================*/
-namespace System {
-
- using System;
- using System.Runtime.Serialization;
+using System.Runtime.Serialization;
- [System.Runtime.InteropServices.ComVisible(true)]
+namespace System
+{
[Serializable]
public class PlatformNotSupportedException : NotSupportedException
{
- public PlatformNotSupportedException()
- : base(Environment.GetResourceString("Arg_PlatformNotSupported")) {
- SetErrorCode(__HResults.COR_E_PLATFORMNOTSUPPORTED);
+ public PlatformNotSupportedException()
+ : base(SR.Arg_PlatformNotSupported)
+ {
+ HResult = __HResults.COR_E_PLATFORMNOTSUPPORTED;
}
-
- public PlatformNotSupportedException(String message)
- : base(message) {
- SetErrorCode(__HResults.COR_E_PLATFORMNOTSUPPORTED);
- }
-
- public PlatformNotSupportedException(String message, Exception inner)
- : base(message, inner) {
- SetErrorCode(__HResults.COR_E_PLATFORMNOTSUPPORTED);
+
+ public PlatformNotSupportedException(String message)
+ : base(message)
+ {
+ HResult = __HResults.COR_E_PLATFORMNOTSUPPORTED;
}
- protected PlatformNotSupportedException(SerializationInfo info, StreamingContext context) : base(info, context) {
+ public PlatformNotSupportedException(String message, Exception inner)
+ : base(message, inner)
+ {
+ HResult = __HResults.COR_E_PLATFORMNOTSUPPORTED;
}
+ protected PlatformNotSupportedException(SerializationInfo info, StreamingContext context) : base(info, context) { }
}
}
diff --git a/src/mscorlib/src/System/Progress.cs b/src/mscorlib/src/System/Progress.cs
index 72c43c304d..755e7719fe 100644
--- a/src/mscorlib/src/System/Progress.cs
+++ b/src/mscorlib/src/System/Progress.cs
@@ -2,21 +2,9 @@
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
-/*============================================================
-**
-**
-**
-**
-**
-** Purpose: Event-based implementation of IProgress<T>.
-**
-**
-===========================================================*/
-
using System;
using System.Threading;
using System.Diagnostics;
-using System.Diagnostics.Contracts;
namespace System
{
@@ -34,22 +22,20 @@ namespace System
public class Progress<T> : IProgress<T>
{
/// <summary>The synchronization context captured upon construction. This will never be null.</summary>
- private readonly SynchronizationContext m_synchronizationContext;
+ private readonly SynchronizationContext _synchronizationContext;
/// <summary>The handler specified to the constructor. This may be null.</summary>
- private readonly Action<T> m_handler;
+ private readonly Action<T> _handler;
/// <summary>A cached delegate used to post invocation to the synchronization context.</summary>
- private readonly SendOrPostCallback m_invokeHandlers;
+ private readonly SendOrPostCallback _invokeHandlers;
/// <summary>Initializes the <see cref="Progress{T}"/>.</summary>
public Progress()
{
- // Capture the current synchronization context. "current" is determined by CurrentNoFlow,
- // which doesn't consider the sync ctx flown with an ExecutionContext, avoiding
- // sync ctx reference identity issues where the sync ctx for one thread could be Current on another.
+ // Capture the current synchronization context.
// If there is no current context, we use a default instance targeting the ThreadPool.
- m_synchronizationContext = SynchronizationContext.CurrentNoFlow ?? ProgressStatics.DefaultContext;
- Debug.Assert(m_synchronizationContext != null);
- m_invokeHandlers = new SendOrPostCallback(InvokeHandlers);
+ _synchronizationContext = SynchronizationContext.Current ?? ProgressStatics.DefaultContext;
+ Debug.Assert(_synchronizationContext != null);
+ _invokeHandlers = new SendOrPostCallback(InvokeHandlers);
}
/// <summary>Initializes the <see cref="Progress{T}"/> with the specified callback.</summary>
@@ -64,7 +50,7 @@ namespace System
public Progress(Action<T> handler) : this()
{
if (handler == null) throw new ArgumentNullException(nameof(handler));
- m_handler = handler;
+ _handler = handler;
}
/// <summary>Raised for each reported progress value.</summary>
@@ -81,13 +67,13 @@ namespace System
// If there's no handler, don't bother going through the sync context.
// Inside the callback, we'll need to check again, in case
// an event handler is removed between now and then.
- Action<T> handler = m_handler;
+ Action<T> handler = _handler;
EventHandler<T> changedEvent = ProgressChanged;
if (handler != null || changedEvent != null)
{
// Post the processing to the sync context.
// (If T is a value type, it will get boxed here.)
- m_synchronizationContext.Post(m_invokeHandlers, value);
+ _synchronizationContext.Post(_invokeHandlers, value);
}
}
@@ -101,7 +87,7 @@ namespace System
{
T value = (T)state;
- Action<T> handler = m_handler;
+ Action<T> handler = _handler;
EventHandler<T> changedEvent = ProgressChanged;
if (handler != null) handler(value);
diff --git a/src/mscorlib/src/System/Random.cs b/src/mscorlib/src/System/Random.cs
index f5941d6718..db6da0ea8b 100644
--- a/src/mscorlib/src/System/Random.cs
+++ b/src/mscorlib/src/System/Random.cs
@@ -18,7 +18,6 @@ namespace System {
using System.Globalization;
using System.Diagnostics.Contracts;
- [System.Runtime.InteropServices.ComVisible(true)]
[Serializable]
public class Random {
//
diff --git a/src/mscorlib/src/System/RankException.cs b/src/mscorlib/src/System/RankException.cs
index 8639bba30e..612d0f086c 100644
--- a/src/mscorlib/src/System/RankException.cs
+++ b/src/mscorlib/src/System/RankException.cs
@@ -12,31 +12,31 @@
**
=============================================================================*/
-namespace System {
-
- using System;
- using System.Runtime.Serialization;
- [System.Runtime.InteropServices.ComVisible(true)]
+using System.Runtime.Serialization;
+
+namespace System
+{
[Serializable]
public class RankException : SystemException
{
- public RankException()
- : base(Environment.GetResourceString("Arg_RankException")) {
- SetErrorCode(__HResults.COR_E_RANK);
- }
-
- public RankException(String message)
- : base(message) {
- SetErrorCode(__HResults.COR_E_RANK);
+ public RankException()
+ : base(SR.Arg_RankException)
+ {
+ HResult = __HResults.COR_E_RANK;
}
-
- public RankException(String message, Exception innerException)
- : base(message, innerException) {
- SetErrorCode(__HResults.COR_E_RANK);
+
+ public RankException(String message)
+ : base(message)
+ {
+ HResult = __HResults.COR_E_RANK;
}
- protected RankException(SerializationInfo info, StreamingContext context) : base(info, context) {
+ public RankException(String message, Exception innerException)
+ : base(message, innerException)
+ {
+ HResult = __HResults.COR_E_RANK;
}
+ protected RankException(SerializationInfo info, StreamingContext context) : base(info, context) { }
}
}
diff --git a/src/mscorlib/src/System/ReadOnlySpan.cs b/src/mscorlib/src/System/ReadOnlySpan.cs
index b0919d3208..76c63d5d8b 100644
--- a/src/mscorlib/src/System/ReadOnlySpan.cs
+++ b/src/mscorlib/src/System/ReadOnlySpan.cs
@@ -2,17 +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.
-using System.Collections.Generic;
using System.Diagnostics;
using System.Runtime.CompilerServices;
+using EditorBrowsableState = System.ComponentModel.EditorBrowsableState;
+using EditorBrowsableAttribute = System.ComponentModel.EditorBrowsableAttribute;
#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
+ /// ReadOnlySpan represents a contiguous region of arbitrary memory. 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>
@@ -23,11 +23,12 @@ namespace System
private readonly int _length;
/// <summary>
- /// Creates a new span over the entirety of the target array.
+ /// Creates a new read-only 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>
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
public ReadOnlySpan(T[] array)
{
if (array == null)
@@ -38,16 +39,17 @@ namespace System
}
/// <summary>
- /// Creates a new span over the portion of the target array beginning
+ /// Creates a new read-only 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>
+ /// <param name="start">The index at which to begin the read-only 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).
+ /// Thrown when the specified <paramref name="start"/> is not in the range (&lt;0 or &gt;=Length).
/// </exception>
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
public ReadOnlySpan(T[] array, int start)
{
if (array == null)
@@ -60,17 +62,18 @@ namespace System
}
/// <summary>
- /// Creates a new span over the portion of the target array beginning
+ /// Creates a new read-only 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>
+ /// <param name="start">The index at which to begin the read-only span.</param>
+ /// <param name="length">The number of items in the read-only 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).
+ /// Thrown when the specified <paramref name="start"/> or end index is not in the range (&lt;0 or &gt;=Length).
/// </exception>
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
public ReadOnlySpan(T[] array, int start, int length)
{
if (array == null)
@@ -83,12 +86,12 @@ namespace System
}
/// <summary>
- /// Creates a new span over the target unmanaged buffer. Clearly this
+ /// Creates a new read-only 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="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.
@@ -97,6 +100,7 @@ namespace System
/// Thrown when the specified <paramref name="length"/> is negative.
/// </exception>
[CLSCompliant(false)]
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
public unsafe ReadOnlySpan(void* pointer, int length)
{
if (JitHelpers.ContainsReferences<T>())
@@ -109,52 +113,6 @@ namespace System
}
/// <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.
@@ -168,6 +126,7 @@ namespace System
/// <exception cref="System.ArgumentOutOfRangeException">
/// Thrown when the specified <paramref name="length"/> is negative.
/// </exception>
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
public static ReadOnlySpan<T> DangerousCreate(object obj, ref T objectData, int length)
{
if (obj == null)
@@ -178,120 +137,57 @@ namespace System
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)
+ // Constructor for internal use only.
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ internal ReadOnlySpan(ref T ptr, int length)
{
- return new ReadOnlySpan<T>(array);
- }
+ Debug.Assert(length >= 0);
- /// <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);
+ _pointer = new ByReference<T>(ref ptr);
+ _length = length;
}
/// <summary>
- /// Gets the number of elements contained in the <see cref="ReadOnlySpan{T}"/>
+ /// 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 int Length
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public ref T DangerousGetPinnableReference()
{
- get { return _length; }
+ return ref _pointer.Value;
}
/// <summary>
- /// Returns an empty <see cref="ReadOnlySpan{T}"/>
+ /// The number of items in the read-only span.
/// </summary>
- public static ReadOnlySpan<T> Empty
- {
- get { return default(ReadOnlySpan<T>); }
- }
+ public int Length => _length;
/// <summary>
- /// Returns whether the <see cref="ReadOnlySpan{T}"/> is empty.
+ /// Returns true if Length is 0.
/// </summary>
- public bool IsEmpty
- {
- get { return _length == 0; }
- }
+ public bool IsEmpty => _length == 0;
/// <summary>
- /// Fetches the element at the specified index.
+ /// Returns the specified element of the read-only span.
/// </summary>
+ /// <param name="index"></param>
+ /// <returns></returns>
/// <exception cref="System.IndexOutOfRangeException">
- /// Thrown when the specified <paramref name="index"/> is not in range (&lt;0 or &gt;&eq;Length).
+ /// Thrown when index less than 0 or index greater than or equal to Length
/// </exception>
public T this[int index]
{
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
get
{
if ((uint)index >= (uint)_length)
ThrowHelper.ThrowIndexOutOfRangeException();
- return Unsafe.Add(ref DangerousGetPinnableReference(), index);
+ return Unsafe.Add(ref _pointer.Value, 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.
@@ -307,17 +203,19 @@ namespace System
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.
+ /// 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.
/// </summary>
+ /// <returns>If the destination span is shorter than the source span, this method
+ /// return false and no data is written to the destination.</returns>
/// <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);
+ SpanHelper.CopyTo<T>(ref destination.DangerousGetPinnableReference(), ref _pointer.Value, _length);
return true;
}
@@ -327,7 +225,7 @@ namespace System
/// </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());
+ return left._length == right._length && Unsafe.AreSame<T>(ref left._pointer.Value, ref right._pointer.Value);
}
/// <summary>
@@ -335,63 +233,98 @@ namespace System
/// 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.
+ /// 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>
- /// <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)
+ [Obsolete("Equals() on Span will always throw an exception. Use == instead.")]
+ [EditorBrowsable(EditorBrowsableState.Never)]
+ public override bool Equals(object obj)
{
- if (text == null)
- ThrowHelper.ThrowArgumentNullException(ExceptionArgument.text);
+ ThrowHelper.ThrowNotSupportedException_CannotCallEqualsOnSpan();
+ // Prevent compiler error CS0161: 'Span<T>.Equals(object)': not all code paths return a value
+ return default(bool);
+ }
- return new ReadOnlySpan<char>(ref text.GetFirstCharRef(), text.Length);
+ /// <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.")]
+ [EditorBrowsable(EditorBrowsableState.Never)]
+ 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>
- /// Creates a new readonly span over the portion of the target string, beginning at 'start'.
+ /// Defines an implicit conversion of an array to a <see cref="ReadOnlySpan{T}"/>
+ /// </summary>
+ public static implicit operator ReadOnlySpan<T>(T[] array) => 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) => new ReadOnlySpan<T>(arraySegment.Array, arraySegment.Offset, arraySegment.Count);
+
+ /// <summary>
+ /// Forms a slice out of the given read-only span, 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).
+ /// 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)
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public ReadOnlySpan<T> Slice(int start)
{
- if (text == null)
- ThrowHelper.ThrowArgumentNullException(ExceptionArgument.text);
- if ((uint)start > (uint)text.Length)
+ if ((uint)start > (uint)_length)
ThrowHelper.ThrowArgumentOutOfRangeException();
- return new ReadOnlySpan<char>(ref Unsafe.Add(ref text.GetFirstCharRef(), start), text.Length - start);
+ return new ReadOnlySpan<T>(ref Unsafe.Add(ref _pointer.Value, start), _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"/>.
+ /// Forms a slice out of the given read-only span, beginning at 'start', of given 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>
+ /// <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).
+ /// Thrown when the specified <paramref name="start"/> or end index is not in range (&lt;0 or &gt;=Length).
/// </exception>
- public static ReadOnlySpan<char> Slice(this string text, int start, int length)
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public ReadOnlySpan<T> Slice(int start, int length)
{
- if (text == null)
- ThrowHelper.ThrowArgumentNullException(ExceptionArgument.text);
- if ((uint)start > (uint)text.Length || (uint)length > (uint)(text.Length - start))
+ if ((uint)start > (uint)_length || (uint)length > (uint)(_length - start))
ThrowHelper.ThrowArgumentOutOfRangeException();
- return new ReadOnlySpan<char>(ref Unsafe.Add(ref text.GetFirstCharRef(), start), length);
+ return new ReadOnlySpan<T>(ref Unsafe.Add(ref _pointer.Value, start), length);
+ }
+
+ /// <summary>
+ /// Copies the contents of this read-only 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 _pointer.Value, _length);
+ return destination;
}
+
+ /// <summary>
+ /// Returns a 0-length read-only span whose base is the null pointer.
+ /// </summary>
+ public static ReadOnlySpan<T> Empty => default(ReadOnlySpan<T>);
}
}
diff --git a/src/mscorlib/src/System/Reflection/AmbiguousMatchException.cs b/src/mscorlib/src/System/Reflection/AmbiguousMatchException.cs
index 6df371bd11..795a8714d1 100644
--- a/src/mscorlib/src/System/Reflection/AmbiguousMatchException.cs
+++ b/src/mscorlib/src/System/Reflection/AmbiguousMatchException.cs
@@ -18,7 +18,6 @@ namespace System.Reflection {
using SystemException = System.SystemException;
using System.Runtime.Serialization;
[Serializable]
- [System.Runtime.InteropServices.ComVisible(true)]
public sealed class AmbiguousMatchException : SystemException
{
diff --git a/src/mscorlib/src/System/Reflection/Assembly.cs b/src/mscorlib/src/System/Reflection/Assembly.cs
index 677e4aa964..eaedc6ded4 100644
--- a/src/mscorlib/src/System/Reflection/Assembly.cs
+++ b/src/mscorlib/src/System/Reflection/Assembly.cs
@@ -22,15 +22,12 @@ namespace System.Reflection
using CultureInfo = System.Globalization.CultureInfo;
using System.Security;
using System.Security.Policy;
- using System.Security.Permissions;
using System.IO;
using StringBuilder = System.Text.StringBuilder;
using System.Configuration.Assemblies;
using StackCrawlMark = System.Threading.StackCrawlMark;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
- using SecurityZone = System.Security.SecurityZone;
- using IEvidenceFactory = System.Security.IEvidenceFactory;
using System.Runtime.Serialization;
using Microsoft.Win32;
using System.Threading;
@@ -40,15 +37,11 @@ namespace System.Reflection
using System.Runtime.Loader;
[Serializable]
- [System.Runtime.InteropServices.ComVisible(true)]
public delegate Module ModuleResolveEventHandler(Object sender, ResolveEventArgs e);
[Serializable]
- [ClassInterface(ClassInterfaceType.None)]
- [ComDefaultInterface(typeof(_Assembly))]
- [System.Runtime.InteropServices.ComVisible(true)]
- public abstract class Assembly : _Assembly, IEvidenceFactory, ICustomAttributeProvider, ISerializable
+ public abstract class Assembly : ICustomAttributeProvider, ISerializable
{
protected Assembly() {}
@@ -112,24 +105,17 @@ namespace System.Reflection
[MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
public static Assembly ReflectionOnlyLoadFrom(String assemblyFile)
{
- Contract.Ensures(Contract.Result<Assembly>() != null);
-
- StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
-
- return RuntimeAssembly.InternalLoadFrom(
- assemblyFile,
- null, //securityEvidence
- null, //hashValue
- AssemblyHashAlgorithm.None,
- true, //forIntrospection
- false, //suppressSecurityChecks
- ref stackMark);
+ if (assemblyFile == null)
+ throw new ArgumentNullException(nameof(assemblyFile));
+ if (assemblyFile.Length == 0)
+ throw new ArgumentException(Environment.GetResourceString("Format_StringZeroLength"));
+ throw new NotSupportedException(Environment.GetResourceString("NotSupported_ReflectionOnlyLoad"));
}
// Evidence is protected in Assembly.Load()
[Obsolete("This method is obsolete and will be removed in a future release of the .NET Framework. Please use an overload of LoadFrom which does not take an Evidence parameter. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.")]
[MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
- public static Assembly LoadFrom(String assemblyFile,
+ internal static Assembly LoadFrom(String assemblyFile,
Evidence securityEvidence)
{
Contract.Ensures(Contract.Result<Assembly>() != null);
@@ -142,29 +128,6 @@ namespace System.Reflection
null, // hashValue
AssemblyHashAlgorithm.None,
false,// forIntrospection);
- false,// suppressSecurityChecks
- ref stackMark);
- }
-
- // Evidence is protected in Assembly.Load()
- [Obsolete("This method is obsolete and will be removed in a future release of the .NET Framework. Please use an overload of LoadFrom which does not take an Evidence parameter. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.")]
- [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
- public static Assembly LoadFrom(String assemblyFile,
- Evidence securityEvidence,
- byte[] hashValue,
- AssemblyHashAlgorithm hashAlgorithm)
- {
- Contract.Ensures(Contract.Result<Assembly>() != null);
-
- StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
-
- return RuntimeAssembly.InternalLoadFrom(
- assemblyFile,
- securityEvidence,
- hashValue,
- hashAlgorithm,
- false,
- false,
ref stackMark);
}
@@ -218,7 +181,7 @@ namespace System.Reflection
assembly = RuntimeAssembly.InternalLoadAssemblyName(
assemblyName, null, null, ref stackMark,
- true /*thrownOnFileNotFound*/, false /*forIntrospection*/, false /*suppressSecurityChecks*/);
+ true /*thrownOnFileNotFound*/, false /*forIntrospection*/);
}
return assembly.GetType(typeName, true /*throwOnError*/, false /*ignoreCase*/);
}
@@ -229,21 +192,11 @@ namespace System.Reflection
[MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
public static Assembly ReflectionOnlyLoad(String assemblyString)
{
- Contract.Ensures(Contract.Result<Assembly>() != null);
-
- StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
- return RuntimeAssembly.InternalLoad(assemblyString, null, ref stackMark, true /*forIntrospection*/);
- }
-
- [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)
- {
- Contract.Ensures(Contract.Result<Assembly>() != null);
- Contract.Ensures(!Contract.Result<Assembly>().ReflectionOnly);
-
- StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
- return RuntimeAssembly.InternalLoad(assemblyString, assemblySecurity, ref stackMark, false /*forIntrospection*/);
+ if (assemblyString == null)
+ throw new ArgumentNullException(nameof(assemblyString));
+ if (assemblyString.Length == 0)
+ throw new ArgumentException(Environment.GetResourceString("Format_StringZeroLength"));
+ throw new NotSupportedException(Environment.GetResourceString("NotSupported_ReflectionOnlyLoad"));
}
// Locate an assembly by its name. The name can be strong or
@@ -254,15 +207,13 @@ namespace System.Reflection
Contract.Ensures(Contract.Result<Assembly>() != null);
Contract.Ensures(!Contract.Result<Assembly>().ReflectionOnly);
-#if FEATURE_WINDOWSPHONE
if (assemblyRef != null && assemblyRef.CodeBase != null)
{
throw new NotSupportedException(Environment.GetResourceString("NotSupported_AssemblyLoadCodeBase"));
}
-#endif
StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
- return RuntimeAssembly.InternalLoadAssemblyName(assemblyRef, null, null, ref stackMark, true /*thrownOnFileNotFound*/, false /*forIntrospection*/, false /*suppressSecurityChecks*/);
+ return RuntimeAssembly.InternalLoadAssemblyName(assemblyRef, null, null, ref stackMark, true /*thrownOnFileNotFound*/, false /*forIntrospection*/);
}
// Locate an assembly by its name. The name can be strong or
@@ -273,26 +224,13 @@ namespace System.Reflection
Contract.Ensures(Contract.Result<Assembly>() != null);
Contract.Ensures(!Contract.Result<Assembly>().ReflectionOnly);
-#if FEATURE_WINDOWSPHONE
if (assemblyRef != null && assemblyRef.CodeBase != null)
{
throw new NotSupportedException(Environment.GetResourceString("NotSupported_AssemblyLoadCodeBase"));
}
-#endif
StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
- return RuntimeAssembly.InternalLoadAssemblyName(assemblyRef, null, null, ref stackMark, true /*thrownOnFileNotFound*/, false /*forIntrospection*/, false /*suppressSecurityChecks*/, ptrLoadContextBinder);
- }
-
- [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)
- {
- Contract.Ensures(Contract.Result<Assembly>() != null);
- Contract.Ensures(!Contract.Result<Assembly>().ReflectionOnly);
-
- StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
- return RuntimeAssembly.InternalLoadAssemblyName(assemblyRef, assemblySecurity, null, ref stackMark, true /*thrownOnFileNotFound*/, false /*forIntrospection*/, false /*suppressSecurityChecks*/);
+ return RuntimeAssembly.InternalLoadAssemblyName(assemblyRef, null, null, ref stackMark, true /*thrownOnFileNotFound*/, false /*forIntrospection*/, ptrLoadContextBinder);
}
[Obsolete("This method has been deprecated. Please use Assembly.Load() instead. http://go.microsoft.com/fwlink/?linkid=14202")]
@@ -323,18 +261,9 @@ namespace System.Reflection
[MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
public static Assembly ReflectionOnlyLoad(byte[] rawAssembly)
{
- Contract.Ensures(Contract.Result<Assembly>() != null);
-
- AppDomain.CheckReflectionOnlyLoadSupported();
-
- StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
- return RuntimeAssembly.nLoadImage(
- rawAssembly,
- null, // symbol store
- null, // evidence
- ref stackMark,
- true, // fIntrospection
- SecurityContextSource.CurrentAssembly);
+ if (rawAssembly == null)
+ throw new ArgumentNullException(nameof(rawAssembly));
+ throw new NotSupportedException(Environment.GetResourceString("NotSupported_ReflectionOnlyLoad"));
}
// Loads the assembly with a COFF based IMAGE containing
@@ -358,33 +287,6 @@ namespace System.Reflection
return alc.LoadFromStream(assemblyStream, symbolStream);
}
- // Load an assembly from a byte array, controlling where the grant set of this assembly is
- // propigated from.
- [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);
-
- AppDomain.CheckLoadByteArraySupported();
-
- if (securityContextSource < SecurityContextSource.CurrentAppDomain ||
- securityContextSource > SecurityContextSource.CurrentAssembly)
- {
- throw new ArgumentOutOfRangeException(nameof(securityContextSource));
- }
-
- StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
- return RuntimeAssembly.nLoadImage(rawAssembly,
- rawSymbolStore,
- null, // evidence
- ref stackMark,
- false, // fIntrospection
- securityContextSource);
- }
-
private static Dictionary<string, Assembly> s_loadfile = new Dictionary<string, Assembly>();
public static Assembly LoadFile(String path)
@@ -416,25 +318,6 @@ namespace System.Reflection
return result;
}
- [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
- public static Assembly Load(Stream assemblyStream, Stream pdbStream)
- {
- Contract.Ensures(Contract.Result<Assembly>() != null);
- Contract.Ensures(!Contract.Result<Assembly>().ReflectionOnly);
-
- StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
- return RuntimeAssembly.InternalLoadFromStream(assemblyStream, pdbStream, ref stackMark);
- }
- [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
- public static Assembly Load(Stream assemblyStream)
- {
- Contract.Ensures(Contract.Result<Assembly>() != null);
- Contract.Ensures(!Contract.Result<Assembly>().ReflectionOnly);
-
- StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
- return RuntimeAssembly.InternalLoadFromStream(assemblyStream, null, ref stackMark);
- }
-
/*
* Get the assembly that the current code is running from.
*/
@@ -573,11 +456,10 @@ namespace System.Reflection
{
Module[] m = GetModules(false);
- int iNumModules = m.Length;
int iFinalLength = 0;
- Type[][] ModuleTypes = new Type[iNumModules][];
+ Type[][] ModuleTypes = new Type[m.Length][];
- for (int i = 0; i < iNumModules; i++)
+ for (int i = 0; i < ModuleTypes.Length; i++)
{
ModuleTypes[i] = m[i].GetTypes();
iFinalLength += ModuleTypes[i].Length;
@@ -585,7 +467,7 @@ namespace System.Reflection
int iCurrent = 0;
Type[] ret = new Type[iFinalLength];
- for (int i = 0; i < iNumModules; i++)
+ for (int i = 0; i < ModuleTypes.Length; i++)
{
int iLength = ModuleTypes[i].Length;
Array.Copy(ModuleTypes[i], 0, ret, iCurrent, iLength);
@@ -639,7 +521,6 @@ namespace System.Reflection
throw new NotImplementedException();
}
- [ComVisible(false)]
public virtual Module ManifestModule
{
get
@@ -684,9 +565,6 @@ namespace System.Reflection
throw new NotImplementedException();
}
- // To not break compatibility with the V1 _Assembly interface we need to make this
- // new member ComVisible(false).
- [ComVisible(false)]
public virtual bool ReflectionOnly
{
get
@@ -836,9 +714,6 @@ namespace System.Reflection
}
}
- // To not break compatibility with the V1 _Assembly interface we need to make this
- // new member ComVisible(false).
- [ComVisible(false)]
public virtual String ImageRuntimeVersion
{
get
@@ -858,7 +733,6 @@ namespace System.Reflection
}
}
- [ComVisible(false)]
public virtual Int64 HostContext
{
get
@@ -885,15 +759,6 @@ namespace System.Reflection
}
- // Keep this in sync with LOADCTX_TYPE defined in fusionpriv.idl
- internal enum LoadContext
- {
- DEFAULT,
- LOADFROM,
- UNKNOWN,
- HOSTED,
- }
-
[Serializable]
internal class RuntimeAssembly : Assembly
{
@@ -915,7 +780,6 @@ namespace System.Reflection
internal RuntimeAssembly() { throw new NotSupportedException(); }
#region private data members
- [method: System.Security.SecurityCritical]
private event ModuleResolveEventHandler _ModuleResolve;
private string m_fullname;
private object m_syncRoot; // Used to keep collectible types alive and as the syncroot for reflection.emit
@@ -997,7 +861,6 @@ namespace System.Reflection
{
get {
String codeBase = GetCodeBase(false);
- VerifyCodeBaseDiscovery(codeBase);
return codeBase;
}
}
@@ -1015,7 +878,6 @@ namespace System.Reflection
AssemblyName an = new AssemblyName();
String codeBase = GetCodeBase(copiedName);
- VerifyCodeBaseDiscovery(codeBase);
an.Init(GetSimpleName(),
GetPublicKey(),
@@ -1104,10 +966,6 @@ namespace System.Reflection
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
- internal extern static void GetForwardedTypes(RuntimeAssembly assembly, ObjectHandleOnStack retTypes);
-
- [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
- [SuppressUnmanagedCodeSecurity]
private extern static void GetExportedTypes(RuntimeAssembly assembly, ObjectHandleOnStack retTypes);
public override Type[] GetExportedTypes()
@@ -1217,7 +1075,6 @@ namespace System.Reflection
byte[] hashValue,
AssemblyHashAlgorithm hashAlgorithm,
bool forIntrospection,
- bool suppressSecurityChecks,
ref StackCrawlMark stackMark)
{
if (assemblyFile == null)
@@ -1229,7 +1086,7 @@ namespace System.Reflection
an.CodeBase = assemblyFile;
an.SetHashControl(hashValue, hashAlgorithm);
// The stack mark is used for MDA filtering
- return InternalLoadAssemblyName(an, securityEvidence, null, ref stackMark, true /*thrownOnFileNotFound*/, forIntrospection, suppressSecurityChecks);
+ return InternalLoadAssemblyName(an, securityEvidence, null, ref stackMark, true /*thrownOnFileNotFound*/, forIntrospection);
}
// Wrapper function to wrap the typical use of InternalLoad.
@@ -1258,7 +1115,7 @@ namespace System.Reflection
return InternalLoadAssemblyName(an, assemblySecurity, null, ref stackMark,
pPrivHostBinder,
- true /*thrownOnFileNotFound*/, forIntrospection, false /* suppressSecurityChecks */);
+ true /*thrownOnFileNotFound*/, forIntrospection);
}
// Creates AssemblyName. Fills assembly if AssemblyResolve event has been raised.
@@ -1294,10 +1151,9 @@ namespace System.Reflection
ref StackCrawlMark stackMark,
bool throwOnFileNotFound,
bool forIntrospection,
- bool suppressSecurityChecks,
IntPtr ptrLoadContextBinder = default(IntPtr))
{
- return InternalLoadAssemblyName(assemblyRef, assemblySecurity, reqAssembly, ref stackMark, IntPtr.Zero, true /*throwOnError*/, forIntrospection, suppressSecurityChecks, ptrLoadContextBinder);
+ return InternalLoadAssemblyName(assemblyRef, assemblySecurity, reqAssembly, ref stackMark, IntPtr.Zero, true /*throwOnError*/, forIntrospection, ptrLoadContextBinder);
}
internal static RuntimeAssembly InternalLoadAssemblyName(
@@ -1308,7 +1164,6 @@ namespace System.Reflection
IntPtr pPrivHostBinder,
bool throwOnFileNotFound,
bool forIntrospection,
- bool suppressSecurityChecks,
IntPtr ptrLoadContextBinder = default(IntPtr))
{
@@ -1322,42 +1177,17 @@ namespace System.Reflection
}
assemblyRef = (AssemblyName)assemblyRef.Clone();
-#if FEATURE_VERSIONING
if (!forIntrospection &&
(assemblyRef.ProcessorArchitecture != ProcessorArchitecture.None)) {
// PA does not have a semantics for by-name binds for execution
assemblyRef.ProcessorArchitecture = ProcessorArchitecture.None;
}
-#endif
-
- if (assemblySecurity != null)
- {
- if (!suppressSecurityChecks)
- {
-#pragma warning disable 618
- new SecurityPermission(SecurityPermissionFlag.ControlEvidence).Demand();
-#pragma warning restore 618
- }
- }
String codeBase = VerifyCodeBase(assemblyRef.CodeBase);
- 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");
- }
- 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,
pPrivHostBinder,
- throwOnFileNotFound, forIntrospection, suppressSecurityChecks, ptrLoadContextBinder);
+ throwOnFileNotFound, forIntrospection, ptrLoadContextBinder);
}
// These are the framework assemblies that does reflection invocation
@@ -1383,15 +1213,6 @@ namespace System.Reflection
ASSEMBLY_FLAGS flags = Flags;
return (flags & ASSEMBLY_FLAGS.ASSEMBLY_FLAGS_SAFE_REFLECTION) != 0;
}
-
- private bool IsDesignerBindingContext()
- {
- return RuntimeAssembly.nIsDesignerBindingContext(this);
- }
-
- [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
- [SuppressUnmanagedCodeSecurity]
- private extern static bool nIsDesignerBindingContext(RuntimeAssembly assembly);
#endif
[MethodImplAttribute(MethodImplOptions.InternalCall)]
@@ -1414,19 +1235,16 @@ namespace System.Reflection
IntPtr pPrivHostBinder,
bool throwOnFileNotFound,
bool forIntrospection,
- bool suppressSecurityChecks, IntPtr ptrLoadContextBinder = default(IntPtr))
+ IntPtr ptrLoadContextBinder = default(IntPtr))
{
return _nLoad(fileName, codeBase, assemblySecurity, locationHint, ref stackMark,
pPrivHostBinder,
- throwOnFileNotFound, forIntrospection, suppressSecurityChecks, ptrLoadContextBinder);
+ throwOnFileNotFound, forIntrospection, true /* suppressSecurityChecks */, ptrLoadContextBinder);
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern bool IsReflectionOnly(RuntimeAssembly assembly);
- // To not break compatibility with the V1 _Assembly interface we need to make this
- // new member ComVisible(false).
- [ComVisible(false)]
public override bool ReflectionOnly
{
get
@@ -1435,57 +1253,6 @@ namespace System.Reflection
}
}
- // Loads the assembly with a COFF based IMAGE containing
- // an emitted assembly. The assembly is loaded into the domain
- // of the caller. Currently is implemented only for UnmanagedMemoryStream
- // (no derived classes since we are not calling Read())
- internal static RuntimeAssembly InternalLoadFromStream(Stream assemblyStream, Stream pdbStream, ref StackCrawlMark stackMark)
- {
- if (assemblyStream == null)
- throw new ArgumentNullException(nameof(assemblyStream));
-
- if (assemblyStream.GetType()!=typeof(UnmanagedMemoryStream))
- throw new NotSupportedException();
-
- if (pdbStream!= null && pdbStream.GetType()!=typeof(UnmanagedMemoryStream))
- throw new NotSupportedException();
-
- AppDomain.CheckLoadFromSupported();
-
- UnmanagedMemoryStream umAssemblyStream = (UnmanagedMemoryStream)assemblyStream;
- UnmanagedMemoryStream umPdbStream = (UnmanagedMemoryStream)pdbStream;
-
- unsafe
- {
- byte* umAssemblyStreamBuffer=umAssemblyStream.PositionPointer;
- byte* umPdbStreamBuffer=(umPdbStream!=null)?umPdbStream.PositionPointer:null;
- long assemblyDataLength = umAssemblyStream.Length-umAssemblyStream.Position;
- long pdbDataLength = (umPdbStream!=null)?(umPdbStream.Length-umPdbStream.Position):0;
-
- // use Seek() to benefit from boundary checking, the actual read is done using *StreamBuffer
- umAssemblyStream.Seek(assemblyDataLength,SeekOrigin.Current);
-
- if(umPdbStream != null)
- {
- umPdbStream.Seek(pdbDataLength,SeekOrigin.Current);
- }
-
- BCLDebug.Assert(assemblyDataLength > 0L, "assemblyDataLength > 0L");
-
- RuntimeAssembly assembly = null;
-
- nLoadFromUnmanagedArray(false,
- umAssemblyStreamBuffer,
- (ulong)assemblyDataLength,
- umPdbStreamBuffer,
- (ulong)pdbDataLength,
- JitHelpers.GetStackCrawlMarkHandle(ref stackMark),
- JitHelpers.GetObjectHandleOnStack(ref assembly));
-
- return assembly;
- }
- }
-
// Returns the module in this assembly with name 'name'
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
@@ -1515,13 +1282,14 @@ namespace System.Reflection
public override FileStream[] GetFiles(bool getResourceModules)
{
Module[] m = GetModules(getResourceModules);
- int iLength = m.Length;
- FileStream[] fs = new FileStream[iLength];
+ FileStream[] fs = new FileStream[m.Length];
- for(int i = 0; i < iLength; i++)
+ for (int i = 0; i < fs.Length; i++)
+ {
fs[i] = new FileStream(((RuntimeModule)m[i]).GetFullyQualifiedName(),
FileMode.Open,
FileAccess.Read, FileShare.Read, FileStream.DefaultBufferSize, false);
+ }
return fs;
}
@@ -1593,9 +1361,6 @@ namespace System.Reflection
GetLocation(GetNativeHandle(), JitHelpers.GetStringHandleOnStack(ref location));
- if (location != null)
- new FileIOPermission( FileIOPermissionAccess.PathDiscovery, location ).Demand();
-
return location;
}
}
@@ -1604,9 +1369,6 @@ namespace System.Reflection
[SuppressUnmanagedCodeSecurity]
private extern static void GetImageRuntimeVersion(RuntimeAssembly assembly, StringHandleOnStack retString);
- // To not break compatibility with the V1 _Assembly interface we need to make this
- // new member ComVisible(false).
- [ComVisible(false)]
public override String ImageRuntimeVersion
{
get{
@@ -1616,10 +1378,6 @@ namespace System.Reflection
}
}
-
- [MethodImplAttribute(MethodImplOptions.InternalCall)]
- private extern static bool IsGlobalAssemblyCache(RuntimeAssembly assembly);
-
public override bool GlobalAssemblyCache
{
get
@@ -1628,10 +1386,6 @@ namespace System.Reflection
}
}
- [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
- [SuppressUnmanagedCodeSecurity]
- private extern static Int64 GetHostContext(RuntimeAssembly assembly);
-
public override Int64 HostContext
{
get
@@ -1713,7 +1467,7 @@ namespace System.Reflection
if (length > Int64.MaxValue)
throw new NotImplementedException(Environment.GetResourceString("NotImplemented_ResourcesLongerThan2^63"));
- return new UnmanagedMemoryStream(pbInMemoryResource, (long)length, (long)length, FileAccess.Read, true);
+ return new UnmanagedMemoryStream(pbInMemoryResource, (long)length, (long)length, FileAccess.Read);
}
//Console.WriteLine("GetManifestResourceStream: Blob "+name+" not found...");
@@ -1761,15 +1515,6 @@ namespace System.Reflection
}
}
- private void VerifyCodeBaseDiscovery(String codeBase)
- {
- 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 );
- new FileIOPermission( FileIOPermissionAccess.PathDiscovery, urlString.GetFileName() ).Demand();
- }
- }
-
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private static extern void GetSimpleName(RuntimeAssembly assembly, StringHandleOnStack retSimpleName);
@@ -1801,19 +1546,6 @@ namespace System.Reflection
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
- private static extern void GetRawBytes(RuntimeAssembly assembly, ObjectHandleOnStack retRawBytes);
-
- // Get the raw bytes of the assembly
- internal byte[] GetRawBytes()
- {
- byte[] rawBytes = null;
-
- GetRawBytes(GetNativeHandle(), JitHelpers.GetObjectHandleOnStack(ref rawBytes));
- return rawBytes;
- }
-
- [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
- [SuppressUnmanagedCodeSecurity]
private static extern void GetPublicKey(RuntimeAssembly assembly, ObjectHandleOnStack retPublicKey);
internal byte[] GetPublicKey()
@@ -1825,50 +1557,6 @@ namespace System.Reflection
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
- private extern static void GetGrantSet(RuntimeAssembly assembly, ObjectHandleOnStack granted, ObjectHandleOnStack denied);
-
- internal void GetGrantSet(out PermissionSet newGrant, out PermissionSet newDenied)
- {
- PermissionSet granted = null, denied = null;
- GetGrantSet(GetNativeHandle(), JitHelpers.GetObjectHandleOnStack(ref granted), JitHelpers.GetObjectHandleOnStack(ref denied));
- newGrant = granted; newDenied = denied;
- }
-
- [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
- internal bool IsAllSecurityCritical()
- {
- return IsAllSecurityCritical(GetNativeHandle());
- }
-
- [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
- internal bool IsAllSecuritySafeCritical()
- {
- return IsAllSecuritySafeCritical(GetNativeHandle());
- }
-
- [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
- internal bool IsAllPublicAreaSecuritySafeCritical()
- {
- return IsAllPublicAreaSecuritySafeCritical(GetNativeHandle());
- }
-
- [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
- [SuppressUnmanagedCodeSecurity]
[return: MarshalAs(UnmanagedType.Bool)]
private extern static bool IsAllSecurityTransparent(RuntimeAssembly assembly);
@@ -1948,7 +1636,7 @@ namespace System.Reflection
RuntimeAssembly retAssembly = nLoad(an, null, null, this, ref stackMark,
IntPtr.Zero,
- throwOnFileNotFound, false, false);
+ throwOnFileNotFound, false);
if (retAssembly == this || (retAssembly == null && throwOnFileNotFound))
{
@@ -1958,135 +1646,6 @@ namespace System.Reflection
return retAssembly;
}
- // Helper method used by InternalGetSatelliteAssembly only. Not abstracted for use elsewhere.
- [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
- private RuntimeAssembly InternalProbeForSatelliteAssemblyNextToParentAssembly(AssemblyName an,
- String name,
- String codeBase,
- CultureInfo culture,
- bool throwOnFileNotFound,
- bool useLoadFile,
- ref StackCrawlMark stackMark)
- {
- // if useLoadFile == false, we do LoadFrom binds
-
- RuntimeAssembly retAssembly = null;
- String location = null;
-
- if (useLoadFile)
- location = Location;
-
- FileNotFoundException dllNotFoundException = null;
-
- StringBuilder assemblyFile = new StringBuilder(useLoadFile ? location : codeBase,
- 0,
- useLoadFile ? location.LastIndexOf('\\') + 1 : codeBase.LastIndexOf('/') + 1,
- Path.MaxPath);
- assemblyFile.Append(an.CultureInfo.Name);
- assemblyFile.Append(useLoadFile ? '\\' : '/');
- assemblyFile.Append(name);
- assemblyFile.Append(".DLL");
-
- string fileNameOrCodeBase = assemblyFile.ToString();
-
- AssemblyName loadFromAsmName = null;
-
- if (useLoadFile == false)
- {
- loadFromAsmName = new AssemblyName();
- // set just the codebase - we want this to be a pure LoadFrom
- loadFromAsmName.CodeBase = fileNameOrCodeBase;
- }
-
- try
- {
- try
- {
- retAssembly = useLoadFile ? nLoadFile(fileNameOrCodeBase, null) :
- nLoad(loadFromAsmName, fileNameOrCodeBase, null, this, ref stackMark,
- IntPtr.Zero,
- throwOnFileNotFound, false, false);
- }
- catch (FileNotFoundException)
- {
- // Create our own exception since the one caught doesn't have a filename associated with it, making it less useful for debugging.
- dllNotFoundException = new FileNotFoundException(String.Format(culture,
- Environment.GetResourceString("IO.FileNotFound_FileName"),
- fileNameOrCodeBase),
- fileNameOrCodeBase); // Save this exception so we can throw it if we also don't find the .EXE
- retAssembly = null;
- }
-
- if (retAssembly == null)
- {
- // LoadFile will always throw, but LoadFrom will only throw if throwOnFileNotFound is true.
- // If an exception was thrown, we must have a dllNotFoundException ready for throwing later.
- BCLDebug.Assert((useLoadFile == false && throwOnFileNotFound == false) || dllNotFoundException != null,
- "(useLoadFile == false && throwOnFileNotFound == false) || dllNotFoundException != null");
-
- assemblyFile.Remove(assemblyFile.Length - 4, 4);
- assemblyFile.Append(".EXE");
- fileNameOrCodeBase = assemblyFile.ToString();
-
- if (useLoadFile == false)
- loadFromAsmName.CodeBase = fileNameOrCodeBase;
-
- try
- {
- retAssembly = useLoadFile ? nLoadFile(fileNameOrCodeBase, null) :
- nLoad(loadFromAsmName, fileNameOrCodeBase, null, this, ref stackMark,
- IntPtr.Zero,
- false /* do not throw on file not found */, false, false);
-
- }
- catch (FileNotFoundException)
- {
- retAssembly = null;
- }
-
- // It would be messy to have a FileNotFoundException that reports both .DLL and .EXE not found.
- // Using a .DLL extension for satellite assemblies is the more common scenario,
- // so just throw that exception.
-
- // In classic (i.e. non-AppX) mode, if binder logging is turned on, there will be separate logs for
- // the .DLL and .EXE load attempts if the user is interested in digging deeper.
-
- if (retAssembly == null && throwOnFileNotFound)
- throw dllNotFoundException;
- }
- }
- catch (DirectoryNotFoundException)
- {
- if (throwOnFileNotFound)
- throw;
- retAssembly = null;
- }
- // No other exceptions should be caught here.
-
- return retAssembly;
- }
-
- [MethodImplAttribute(MethodImplOptions.InternalCall)]
- static internal extern RuntimeAssembly nLoadFile(String path, Evidence evidence);
-
- [MethodImplAttribute(MethodImplOptions.InternalCall)]
- static internal extern RuntimeAssembly nLoadImage(byte[] rawAssembly,
- byte[] rawSymbolStore,
- Evidence evidence,
- ref StackCrawlMark stackMark,
- bool fIntrospection,
- SecurityContextSource securityContextSource);
-
- [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
- [SuppressUnmanagedCodeSecurity]
- static internal extern unsafe void nLoadFromUnmanagedArray(bool fIntrospection,
- byte* assemblyContent,
- ulong assemblySize,
- byte* pdbContent,
- ulong pdbSize,
- StackCrawlMarkHandle stackMark,
- ObjectHandleOnStack retAssembly);
-
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private extern static void GetModules(RuntimeAssembly assembly,
diff --git a/src/mscorlib/src/System/Reflection/AssemblyAttributes.cs b/src/mscorlib/src/System/Reflection/AssemblyAttributes.cs
index b2e44b0034..1e6688d1f4 100644
--- a/src/mscorlib/src/System/Reflection/AssemblyAttributes.cs
+++ b/src/mscorlib/src/System/Reflection/AssemblyAttributes.cs
@@ -20,7 +20,6 @@ namespace System.Reflection {
using System.Diagnostics.Contracts;
[AttributeUsage (AttributeTargets.Assembly, Inherited=false)]
-[System.Runtime.InteropServices.ComVisible(true)]
public sealed class AssemblyCopyrightAttribute : Attribute
{
private String m_copyright;
@@ -38,7 +37,6 @@ namespace System.Reflection {
[AttributeUsage (AttributeTargets.Assembly, Inherited=false)]
-[System.Runtime.InteropServices.ComVisible(true)]
public sealed class AssemblyTrademarkAttribute : Attribute
{
private String m_trademark;
@@ -56,7 +54,6 @@ namespace System.Reflection {
[AttributeUsage (AttributeTargets.Assembly, Inherited=false)]
-[System.Runtime.InteropServices.ComVisible(true)]
public sealed class AssemblyProductAttribute : Attribute
{
private String m_product;
@@ -74,7 +71,6 @@ namespace System.Reflection {
[AttributeUsage (AttributeTargets.Assembly, Inherited=false)]
-[System.Runtime.InteropServices.ComVisible(true)]
public sealed class AssemblyCompanyAttribute : Attribute
{
private String m_company;
@@ -92,7 +88,6 @@ namespace System.Reflection {
[AttributeUsage (AttributeTargets.Assembly, Inherited=false)]
-[System.Runtime.InteropServices.ComVisible(true)]
public sealed class AssemblyDescriptionAttribute : Attribute
{
private String m_description;
@@ -110,7 +105,6 @@ namespace System.Reflection {
[AttributeUsage (AttributeTargets.Assembly, Inherited=false)]
-[System.Runtime.InteropServices.ComVisible(true)]
public sealed class AssemblyTitleAttribute : Attribute
{
private String m_title;
@@ -128,7 +122,6 @@ namespace System.Reflection {
[AttributeUsage (AttributeTargets.Assembly, Inherited=false)]
-[System.Runtime.InteropServices.ComVisible(true)]
public sealed class AssemblyConfigurationAttribute : Attribute
{
private String m_configuration;
@@ -146,7 +139,6 @@ namespace System.Reflection {
[AttributeUsage (AttributeTargets.Assembly, Inherited=false)]
-[System.Runtime.InteropServices.ComVisible(true)]
public sealed class AssemblyDefaultAliasAttribute : Attribute
{
private String m_defaultAlias;
@@ -164,7 +156,6 @@ namespace System.Reflection {
[AttributeUsage (AttributeTargets.Assembly, Inherited=false)]
-[System.Runtime.InteropServices.ComVisible(true)]
public sealed class AssemblyInformationalVersionAttribute : Attribute
{
private String m_informationalVersion;
@@ -182,7 +173,6 @@ namespace System.Reflection {
[AttributeUsage(AttributeTargets.Assembly, Inherited=false)]
-[System.Runtime.InteropServices.ComVisible(true)]
public sealed class AssemblyFileVersionAttribute : Attribute
{
private String _version;
@@ -202,7 +192,6 @@ namespace System.Reflection {
[AttributeUsage (AttributeTargets.Assembly, Inherited=false)]
-[System.Runtime.InteropServices.ComVisible(true)]
public unsafe sealed class AssemblyCultureAttribute : Attribute
{
private String m_culture;
@@ -220,7 +209,6 @@ namespace System.Reflection {
[AttributeUsage (AttributeTargets.Assembly, Inherited=false)]
-[System.Runtime.InteropServices.ComVisible(true)]
public unsafe sealed class AssemblyVersionAttribute : Attribute
{
private String m_version;
@@ -238,7 +226,6 @@ namespace System.Reflection {
[AttributeUsage (AttributeTargets.Assembly, Inherited=false)]
-[System.Runtime.InteropServices.ComVisible(true)]
public sealed class AssemblyKeyFileAttribute : Attribute
{
private String m_keyFile;
@@ -256,7 +243,6 @@ namespace System.Reflection {
[AttributeUsage (AttributeTargets.Assembly, Inherited=false)]
-[System.Runtime.InteropServices.ComVisible(true)]
public sealed class AssemblyDelaySignAttribute : Attribute
{
private bool m_delaySign;
@@ -274,7 +260,6 @@ namespace System.Reflection {
[AttributeUsage(AttributeTargets.Assembly, Inherited=false)]
-[System.Runtime.InteropServices.ComVisible(true)]
public unsafe sealed class AssemblyAlgorithmIdAttribute : Attribute
{
private uint m_algId;
@@ -299,7 +284,6 @@ namespace System.Reflection {
[AttributeUsage(AttributeTargets.Assembly, Inherited=false)]
-[System.Runtime.InteropServices.ComVisible(true)]
public unsafe sealed class AssemblyFlagsAttribute : Attribute
{
private AssemblyNameFlags m_flags;
@@ -360,7 +344,6 @@ namespace System.Reflection {
}
}
-#if FEATURE_STRONGNAME_MIGRATION
[AttributeUsage(AttributeTargets.Assembly, Inherited = false, AllowMultiple=false)]
public sealed class AssemblySignatureKeyAttribute : Attribute
{
@@ -383,10 +366,8 @@ namespace System.Reflection {
get { return _countersignature; }
}
}
-#endif
[AttributeUsage (AttributeTargets.Assembly, Inherited=false)]
-[System.Runtime.InteropServices.ComVisible(true)]
public sealed class AssemblyKeyNameAttribute : Attribute
{
private String m_keyName;
diff --git a/src/mscorlib/src/System/Reflection/AssemblyName.cs b/src/mscorlib/src/System/Reflection/AssemblyName.cs
index 48eab33ee5..01be855646 100644
--- a/src/mscorlib/src/System/Reflection/AssemblyName.cs
+++ b/src/mscorlib/src/System/Reflection/AssemblyName.cs
@@ -20,17 +20,13 @@ namespace System.Reflection {
using System.Runtime.CompilerServices;
using CultureInfo = System.Globalization.CultureInfo;
using System.Runtime.Serialization;
- using System.Security.Permissions;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Diagnostics.Contracts;
using System.Text;
[Serializable]
- [ClassInterface(ClassInterfaceType.None)]
- [ComDefaultInterface(typeof(_AssemblyName))]
- [System.Runtime.InteropServices.ComVisible(true)]
- public sealed class AssemblyName : _AssemblyName, ICloneable, ISerializable, IDeserializationCallback
+ public sealed class AssemblyName : ICloneable, ISerializable, IDeserializationCallback
{
//
// READ ME
@@ -136,7 +132,6 @@ namespace System.Reflection {
}
}
- [System.Runtime.InteropServices.ComVisible(false)]
public AssemblyContentType ContentType
{
get
@@ -192,7 +187,6 @@ namespace System.Reflection {
// Assembly.GetNameInternal() will not demand path discovery
// permission, so do that first.
string fullPath = Path.GetFullPath(assemblyFile);
- new FileIOPermission( FileIOPermissionAccess.PathDiscovery, fullPath ).Demand();
return nGetFileInformation(fullPath);
}
diff --git a/src/mscorlib/src/System/Reflection/AssemblyNameFlags.cs b/src/mscorlib/src/System/Reflection/AssemblyNameFlags.cs
index 35a5370cc6..b86955efa5 100644
--- a/src/mscorlib/src/System/Reflection/AssemblyNameFlags.cs
+++ b/src/mscorlib/src/System/Reflection/AssemblyNameFlags.cs
@@ -19,7 +19,6 @@ namespace System.Reflection {
using System;
[Serializable]
[FlagsAttribute()]
- [System.Runtime.InteropServices.ComVisible(true)]
public enum AssemblyNameFlags
{
None = 0x0000,
@@ -35,7 +34,6 @@ namespace System.Reflection {
}
[Serializable]
- [System.Runtime.InteropServices.ComVisible(false)]
public enum AssemblyContentType
{
Default = 0x0000,
@@ -43,7 +41,6 @@ namespace System.Reflection {
}
[Serializable]
- [System.Runtime.InteropServices.ComVisible(true)]
public enum ProcessorArchitecture
{
None = 0x0000,
diff --git a/src/mscorlib/src/System/Reflection/AssemblyNameProxy.cs b/src/mscorlib/src/System/Reflection/AssemblyNameProxy.cs
deleted file mode 100644
index 8c8fa8d286..0000000000
--- a/src/mscorlib/src/System/Reflection/AssemblyNameProxy.cs
+++ /dev/null
@@ -1,28 +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: Remotable version the AssemblyName
-**
-**
-===========================================================*/
-namespace System.Reflection {
- using System;
- using System.Runtime.Versioning;
-
- [System.Runtime.InteropServices.ComVisible(true)]
- public class AssemblyNameProxy : MarshalByRefObject
- {
- public AssemblyName GetAssemblyName(String assemblyFile)
- {
- return AssemblyName.GetAssemblyName(assemblyFile);
- }
- }
-}
diff --git a/src/mscorlib/src/System/Reflection/Binder.cs b/src/mscorlib/src/System/Reflection/Binder.cs
index d06899f6c6..bf4545fe81 100644
--- a/src/mscorlib/src/System/Reflection/Binder.cs
+++ b/src/mscorlib/src/System/Reflection/Binder.cs
@@ -16,8 +16,6 @@ namespace System.Reflection {
using CultureInfo = System.Globalization.CultureInfo;
[Serializable]
- [ClassInterface(ClassInterfaceType.AutoDual)]
-[System.Runtime.InteropServices.ComVisible(true)]
public abstract class Binder
{
// Given a set of methods that match the basic criteria, select a method to
diff --git a/src/mscorlib/src/System/Reflection/BindingFlags.cs b/src/mscorlib/src/System/Reflection/BindingFlags.cs
index 591dfbb249..ae0a6d68d3 100644
--- a/src/mscorlib/src/System/Reflection/BindingFlags.cs
+++ b/src/mscorlib/src/System/Reflection/BindingFlags.cs
@@ -17,7 +17,6 @@ namespace System.Reflection {
using System;
[Serializable]
[Flags]
- [System.Runtime.InteropServices.ComVisible(true)]
public enum BindingFlags
{
diff --git a/src/mscorlib/src/System/Reflection/CallingConventions.cs b/src/mscorlib/src/System/Reflection/CallingConventions.cs
index 6ca11c9021..266dd55184 100644
--- a/src/mscorlib/src/System/Reflection/CallingConventions.cs
+++ b/src/mscorlib/src/System/Reflection/CallingConventions.cs
@@ -15,7 +15,6 @@ namespace System.Reflection {
using System;
[Serializable]
[Flags]
- [System.Runtime.InteropServices.ComVisible(true)]
public enum CallingConventions
{
//NOTE: If you change this please update COMMember.cpp. These
diff --git a/src/mscorlib/src/System/Reflection/ComInterfaces.cs b/src/mscorlib/src/System/Reflection/ComInterfaces.cs
deleted file mode 100644
index 6e4b0cc19a..0000000000
--- a/src/mscorlib/src/System/Reflection/ComInterfaces.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
-{
- [GuidAttribute("BCA8B44D-AAD6-3A86-8AB7-03349F4F2DA2")]
- [CLSCompliant(false)]
- [InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)]
- [TypeLibImportClassAttribute(typeof(System.Type))]
- [System.Runtime.InteropServices.ComVisible(true)]
- public interface _Type
- {
- }
-
- [GuidAttribute("17156360-2f1a-384a-bc52-fde93c215c5b")]
- [InterfaceTypeAttribute(ComInterfaceType.InterfaceIsDual)]
- [TypeLibImportClassAttribute(typeof(System.Reflection.Assembly))]
- [CLSCompliant(false)]
- [System.Runtime.InteropServices.ComVisible(true)]
- public interface _Assembly
- {
- }
-
- [GuidAttribute("f7102fa9-cabb-3a74-a6da-b4567ef1b079")]
- [InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)]
- [TypeLibImportClassAttribute(typeof(System.Reflection.MemberInfo))]
- [CLSCompliant(false)]
- [System.Runtime.InteropServices.ComVisible(true)]
- public interface _MemberInfo
- {
- }
-
- [GuidAttribute("6240837A-707F-3181-8E98-A36AE086766B")]
- [InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)]
- [CLSCompliant(false)]
- [TypeLibImportClassAttribute(typeof(System.Reflection.MethodBase))]
- [System.Runtime.InteropServices.ComVisible(true)]
- public interface _MethodBase
- {
- }
-
- [GuidAttribute("FFCC1B5D-ECB8-38DD-9B01-3DC8ABC2AA5F")]
- [InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)]
- [CLSCompliant(false)]
- [TypeLibImportClassAttribute(typeof(System.Reflection.MethodInfo))]
- [System.Runtime.InteropServices.ComVisible(true)]
- public interface _MethodInfo
- {
- }
-
- [GuidAttribute("E9A19478-9646-3679-9B10-8411AE1FD57D")]
- [InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)]
- [CLSCompliant(false)]
- [TypeLibImportClassAttribute(typeof(System.Reflection.ConstructorInfo))]
- [System.Runtime.InteropServices.ComVisible(true)]
- public interface _ConstructorInfo
- {
- }
-
- [GuidAttribute("8A7C1442-A9FB-366B-80D8-4939FFA6DBE0")]
- [InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)]
- [CLSCompliant(false)]
- [TypeLibImportClassAttribute(typeof(System.Reflection.FieldInfo))]
- [System.Runtime.InteropServices.ComVisible(true)]
- public interface _FieldInfo
- {
- }
-
- [GuidAttribute("F59ED4E4-E68F-3218-BD77-061AA82824BF")]
- [InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)]
- [CLSCompliant(false)]
- [TypeLibImportClassAttribute(typeof(System.Reflection.PropertyInfo))]
- [System.Runtime.InteropServices.ComVisible(true)]
- public interface _PropertyInfo
- {
- }
-
- [GuidAttribute("9DE59C64-D889-35A1-B897-587D74469E5B")]
- [InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)]
- [CLSCompliant(false)]
- [TypeLibImportClassAttribute(typeof(System.Reflection.EventInfo))]
- [System.Runtime.InteropServices.ComVisible(true)]
- public interface _EventInfo
- {
- }
-
- [GuidAttribute("993634C4-E47A-32CC-BE08-85F567DC27D6")]
- [InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)]
- [CLSCompliant(false)]
- [TypeLibImportClassAttribute(typeof(System.Reflection.ParameterInfo))]
- [System.Runtime.InteropServices.ComVisible(true)]
- public interface _ParameterInfo
- {
- }
-
- [GuidAttribute("D002E9BA-D9E3-3749-B1D3-D565A08B13E7")]
- [InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)]
- [CLSCompliant(false)]
- [TypeLibImportClassAttribute(typeof(System.Reflection.Module))]
- [System.Runtime.InteropServices.ComVisible(true)]
- public interface _Module
- {
- }
-
- [GuidAttribute("B42B6AAC-317E-34D5-9FA9-093BB4160C50")]
- [InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)]
- [CLSCompliant(false)]
- [TypeLibImportClassAttribute(typeof(System.Reflection.AssemblyName))]
- [System.Runtime.InteropServices.ComVisible(true)]
- public interface _AssemblyName
- {
- }
-}
-
diff --git a/src/mscorlib/src/System/Reflection/ConstructorInfo.cs b/src/mscorlib/src/System/Reflection/ConstructorInfo.cs
index 3d927fc85c..c8d71bc1f9 100644
--- a/src/mscorlib/src/System/Reflection/ConstructorInfo.cs
+++ b/src/mscorlib/src/System/Reflection/ConstructorInfo.cs
@@ -16,23 +16,17 @@ namespace System.Reflection
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
using System.Security;
- using System.Security.Permissions;
using System.Threading;
using MemberListType = System.RuntimeType.MemberListType;
using RuntimeTypeCache = System.RuntimeType.RuntimeTypeCache;
using System.Runtime.CompilerServices;
[Serializable]
- [ClassInterface(ClassInterfaceType.None)]
- [ComDefaultInterface(typeof(_ConstructorInfo))]
- [System.Runtime.InteropServices.ComVisible(true)]
- public abstract class ConstructorInfo : MethodBase, _ConstructorInfo
+ public abstract class ConstructorInfo : MethodBase
{
#region Static Members
- [System.Runtime.InteropServices.ComVisible(true)]
public readonly static String ConstructorName = ".ctor";
- [System.Runtime.InteropServices.ComVisible(true)]
public readonly static String TypeConstructorName = ".cctor";
#endregion
@@ -73,7 +67,6 @@ namespace System.Reflection
#endregion
#region MemberInfo Overrides
- [System.Runtime.InteropServices.ComVisible(true)]
public override MemberTypes MemberType { get { return System.Reflection.MemberTypes.Constructor; } }
#endregion
@@ -136,14 +129,6 @@ namespace System.Reflection
return false;
}
-
- internal override bool IsDynamicallyInvokable
- {
- get
- {
- return !AppDomain.ProfileAPICheck || !IsNonW8PFrameworkAPI();
- }
- }
#endif // FEATURE_APPX
internal INVOCATION_FLAGS InvocationFlags
@@ -226,7 +211,6 @@ namespace System.Reflection
}
}
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
internal override bool CacheEquals(object o)
{
RuntimeConstructorInfo m = o as RuntimeConstructorInfo;
@@ -271,20 +255,6 @@ namespace System.Reflection
}
internal BindingFlags BindingFlags { get { return m_bindingFlags; } }
-
- // Differs from MethodHandle in that it will return a valid handle even for reflection only loaded types
- internal RuntimeMethodHandle GetMethodHandle()
- {
- return new RuntimeMethodHandle(this);
- }
-
- internal bool IsOverloaded
- {
- get
- {
- return m_reflectedTypeCache.GetConstructorList(MemberListType.CaseSensitive, Name).Length > 1;
- }
- }
#endregion
#region Object Overrides
@@ -344,7 +314,6 @@ namespace System.Reflection
{
get { return RuntimeMethodHandle.GetName(this); }
}
-[System.Runtime.InteropServices.ComVisible(true)]
public override MemberTypes MemberType { get { return MemberTypes.Constructor; } }
public override Type DeclaringType
@@ -537,11 +506,7 @@ namespace System.Reflection
}
return RuntimeMethodHandle.InvokeMethod(obj, null, sig, false);
}
-
-#pragma warning disable 618
- [ReflectionPermissionAttribute(SecurityAction.Demand, Flags = ReflectionPermissionFlag.MemberAccess)]
-#pragma warning restore 618
public override MethodBody GetMethodBody()
{
MethodBody mb = RuntimeMethodHandle.GetMethodBody(this, ReflectedTypeInternal);
@@ -644,11 +609,6 @@ namespace System.Reflection
// We don't need the return type for constructors.
return FormatNameAndSig(true);
}
-
- internal void SerializationInvoke(Object target, SerializationInfo info, StreamingContext context)
- {
- RuntimeMethodHandle.SerializationInvoke(this, target, info, ref context);
- }
#endregion
}
}
diff --git a/src/mscorlib/src/System/Reflection/CustomAttribute.cs b/src/mscorlib/src/System/Reflection/CustomAttribute.cs
index e568a1702f..b71c7bbff3 100644
--- a/src/mscorlib/src/System/Reflection/CustomAttribute.cs
+++ b/src/mscorlib/src/System/Reflection/CustomAttribute.cs
@@ -14,7 +14,6 @@ using System.Diagnostics;
using System.Diagnostics.Tracing;
using System.Globalization;
using System.Security;
-using System.Security.Permissions;
using System.Runtime.ConstrainedExecution;
using System.Runtime.Versioning;
using System.Diagnostics.Contracts;
@@ -22,7 +21,6 @@ using System.Diagnostics.Contracts;
namespace System.Reflection
{
[Serializable]
- [System.Runtime.InteropServices.ComVisible(true)]
public class CustomAttributeData
{
#region Public Static Members
@@ -515,10 +513,8 @@ namespace System.Reflection
#region Public Members
public Type AttributeType { get { return Constructor.DeclaringType; } }
- [System.Runtime.InteropServices.ComVisible(true)]
public virtual ConstructorInfo Constructor { get { return m_ctor; } }
- [System.Runtime.InteropServices.ComVisible(true)]
public virtual IList<CustomAttributeTypedArgument> ConstructorArguments
{
get
@@ -576,7 +572,6 @@ namespace System.Reflection
}
[Serializable]
- [System.Runtime.InteropServices.ComVisible(true)]
public struct CustomAttributeNamedArgument
{
#region Public Static Members
@@ -666,7 +661,6 @@ namespace System.Reflection
}
[Serializable]
- [ComVisible(true)]
public struct CustomAttributeTypedArgument
{
#region Public Static Members
@@ -1106,24 +1100,6 @@ namespace System.Reflection
#endregion
}
- // Note: This is a managed representation of a frame type defined in vm\frames.h; please ensure the layout remains
- // synchronized.
- [StructLayout(LayoutKind.Sequential)]
- internal struct SecurityContextFrame
- {
- IntPtr m_GSCookie; // This is actually at a negative offset in the real frame definition
- IntPtr __VFN_table; // This is the real start of the SecurityContextFrame
- IntPtr m_Next;
- IntPtr m_Assembly;
-
- [MethodImplAttribute(MethodImplOptions.InternalCall)]
- public extern void Push(RuntimeAssembly assembly);
-
- [MethodImplAttribute(MethodImplOptions.InternalCall)]
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
- public extern void Pop();
- }
-
[Serializable]
[StructLayout(LayoutKind.Auto)]
internal struct CustomAttributeType
@@ -1153,7 +1129,6 @@ namespace System.Reflection
public CustomAttributeEncoding EncodedType { get { return m_encodedType; } }
public CustomAttributeEncoding EncodedEnumType { get { return m_encodedEnumType; } }
public CustomAttributeEncoding EncodedArrayType { get { return m_encodedArrayType; } }
- [System.Runtime.InteropServices.ComVisible(true)]
public string EnumName { get { return m_enumName; } }
#endregion
}
@@ -1621,16 +1596,6 @@ namespace System.Reflection
object[] attributes = CreateAttributeArrayHelper(arrayType, car.Length);
int cAttributes = 0;
- // Custom attribute security checks are done with respect to the assembly *decorated* with the
- // custom attribute as opposed to the *caller of GetCustomAttributes*.
- // Since this assembly might not be on the stack and the attribute ctor or property setters we're about to invoke may
- // make security demands, we push a frame on the stack as a proxy for the decorated assembly (this frame will be picked
- // up an interpreted by the security stackwalker).
- // Once we push the frame it will be automatically popped in the event of an exception, so no need to use CERs or the
- // like.
- SecurityContextFrame frame = new SecurityContextFrame();
- frame.Push(decoratedModule.GetRuntimeAssembly());
-
// Optimization for the case where attributes decorate entities in the same assembly in which case
// we can cache the successful APTCA check between the decorated and the declared assembly.
Assembly lastAptcaOkAssembly = null;
@@ -1780,10 +1745,6 @@ namespace System.Reflection
attributes[cAttributes++] = attribute;
}
- // The frame will be popped automatically if we take an exception any time after we pushed it. So no need of a catch or
- // finally or CERs here.
- frame.Pop();
-
if (cAttributes == car.Length && pcaCount == 0)
return attributes;
@@ -2069,9 +2030,8 @@ namespace System.Reflection
#region Internal Static
internal static bool IsSecurityAttribute(RuntimeType type)
{
-#pragma warning disable 618
- return type == (RuntimeType)typeof(SecurityAttribute) || type.IsSubclassOf(typeof(SecurityAttribute));
-#pragma warning restore 618
+ // TODO: Cleanup
+ return false;
}
internal static Attribute[] GetCustomAttributes(RuntimeType type, RuntimeType caType, bool includeSecCa, out int count)
diff --git a/src/mscorlib/src/System/Reflection/CustomAttributeFormatException.cs b/src/mscorlib/src/System/Reflection/CustomAttributeFormatException.cs
index 3eb8b1f1ef..9aee911a6c 100644
--- a/src/mscorlib/src/System/Reflection/CustomAttributeFormatException.cs
+++ b/src/mscorlib/src/System/Reflection/CustomAttributeFormatException.cs
@@ -15,7 +15,6 @@ namespace System.Reflection {
using ApplicationException = System.ApplicationException;
using System.Runtime.Serialization;
[Serializable]
- [System.Runtime.InteropServices.ComVisible(true)]
public class CustomAttributeFormatException : FormatException {
public CustomAttributeFormatException()
diff --git a/src/mscorlib/src/System/Reflection/DefaultMemberAttribute.cs b/src/mscorlib/src/System/Reflection/DefaultMemberAttribute.cs
index 1fec75906a..4232fcd2a1 100644
--- a/src/mscorlib/src/System/Reflection/DefaultMemberAttribute.cs
+++ b/src/mscorlib/src/System/Reflection/DefaultMemberAttribute.cs
@@ -19,7 +19,6 @@ namespace System.Reflection {
[Serializable]
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Interface)]
-[System.Runtime.InteropServices.ComVisible(true)]
public sealed class DefaultMemberAttribute : Attribute
{
// The name of the member
diff --git a/src/mscorlib/src/System/Reflection/Emit/AssemblyBuilder.cs b/src/mscorlib/src/System/Reflection/Emit/AssemblyBuilder.cs
index 9331ae193c..5575e28917 100644
--- a/src/mscorlib/src/System/Reflection/Emit/AssemblyBuilder.cs
+++ b/src/mscorlib/src/System/Reflection/Emit/AssemblyBuilder.cs
@@ -38,7 +38,6 @@ namespace System.Reflection.Emit
using System.Runtime.Serialization;
using System.Runtime.Versioning;
using System.Security;
- using System.Security.Permissions;
using System.Security.Policy;
using System.Threading;
@@ -156,10 +155,7 @@ namespace System.Reflection.Emit
// AssemblyBuilder class.
// deliberately not [serializable]
- [ClassInterface(ClassInterfaceType.None)]
- [ComDefaultInterface(typeof(_AssemblyBuilder))]
- [ComVisible(true)]
- public sealed class AssemblyBuilder : Assembly, _AssemblyBuilder
+ public sealed class AssemblyBuilder : Assembly
{
#region FCALL
[MethodImplAttribute(MethodImplOptions.InternalCall)]
@@ -221,11 +217,6 @@ namespace System.Reflection.Emit
return InternalAssembly.GetNativeHandle();
}
- internal Version GetVersion()
- {
- return InternalAssembly.GetVersion();
- }
-
#if FEATURE_APPX
internal bool ProfileAPICheck
{
@@ -243,9 +234,6 @@ namespace System.Reflection.Emit
AssemblyBuilderAccess access,
String dir,
Evidence evidence,
- PermissionSet requiredPermissions,
- PermissionSet optionalPermissions,
- PermissionSet refusedPermissions,
ref StackCrawlMark stackMark,
IEnumerable<CustomAttributeBuilder> unsafeAssemblyAttributes,
SecurityContextSource securityContextSource)
@@ -257,9 +245,7 @@ namespace System.Reflection.Emit
#if FEATURE_REFLECTION_ONLY_LOAD
&& access != AssemblyBuilderAccess.ReflectionOnly
#endif // FEATURE_REFLECTION_ONLY_LOAD
-#if FEATURE_COLLECTIBLE_TYPES
&& access != AssemblyBuilderAccess.RunAndCollect
-#endif // FEATURE_COLLECTIBLE_TYPES
)
{
throw new ArgumentException(Environment.GetResourceString("Arg_EnumIllegalVal", (int)access), nameof(access));
@@ -274,18 +260,6 @@ namespace System.Reflection.Emit
// Clone the name in case the caller modifies it underneath us.
name = (AssemblyName)name.Clone();
- // If the caller is trusted they can supply identity
- // evidence for the new assembly. Otherwise we copy the
- // current grant and deny sets from the caller's assembly,
- // inject them into the new assembly and mark policy as
- // resolved. If/when the assembly is persisted and
- // reloaded, the normal rules for gathering evidence will
- // be used.
- if (evidence != null)
-#pragma warning disable 618
- new SecurityPermission(SecurityPermissionFlag.ControlEvidence).Demand();
-#pragma warning restore 618
-
// 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.
@@ -320,9 +294,6 @@ namespace System.Reflection.Emit
name,
evidence,
ref stackMark,
- requiredPermissions,
- optionalPermissions,
- refusedPermissions,
securityRulesBlob,
aptcaBlob,
access,
@@ -333,10 +304,6 @@ namespace System.Reflection.Emit
name.Name,
access,
dir);
- m_assemblyData.AddPermissionRequests(requiredPermissions,
- optionalPermissions,
- refusedPermissions);
-
#if FEATURE_APPX
if (AppDomain.ProfileAPICheck)
{
@@ -393,7 +360,7 @@ namespace System.Reflection.Emit
StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
return InternalDefineDynamicAssembly(name, access, null,
- null, null, null, null, ref stackMark, null, SecurityContextSource.CurrentAssembly);
+ null, ref stackMark, null, SecurityContextSource.CurrentAssembly);
}
[MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
@@ -407,7 +374,7 @@ namespace System.Reflection.Emit
StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
return InternalDefineDynamicAssembly(name,
access,
- null, null, null, null, null,
+ null, null,
ref stackMark,
assemblyAttributes, SecurityContextSource.CurrentAssembly);
}
@@ -418,9 +385,6 @@ namespace System.Reflection.Emit
AssemblyName name,
Evidence identity,
ref StackCrawlMark stackMark,
- PermissionSet requiredPermissions,
- PermissionSet optionalPermissions,
- PermissionSet refusedPermissions,
byte[] securityRulesBlob,
byte[] aptcaBlob,
AssemblyBuilderAccess access,
@@ -434,9 +398,6 @@ namespace System.Reflection.Emit
AssemblyBuilderAccess access,
String dir,
Evidence evidence,
- PermissionSet requiredPermissions,
- PermissionSet optionalPermissions,
- PermissionSet refusedPermissions,
ref StackCrawlMark stackMark,
IEnumerable<CustomAttributeBuilder> unsafeAssemblyAttributes,
SecurityContextSource securityContextSource)
@@ -449,9 +410,6 @@ namespace System.Reflection.Emit
access,
dir,
evidence,
- requiredPermissions,
- optionalPermissions,
- refusedPermissions,
ref stackMark,
unsafeAssemblyAttributes,
securityContextSource);
@@ -532,12 +490,6 @@ namespace System.Reflection.Emit
if (emitSymbolInfo)
{
writer = SymWrapperCore.SymWriter.CreateSymWriter();
- // Set the underlying writer for the managed writer
- // that we're using. Note that this function requires
- // unmanaged code access.
-#pragma warning disable 618
- new SecurityPermission(SecurityPermissionFlag.UnmanagedCode).Assert();
-#pragma warning restore 618
String fileName = "Unused"; // this symfile is never written to disk so filename does not matter.
@@ -559,19 +511,8 @@ namespace System.Reflection.Emit
return dynModule;
} // DefineDynamicModuleInternalNoLock
- #endregion
-
- private Assembly LoadISymWrapper()
- {
- if (m_assemblyData.m_ISymWrapperAssembly != null)
- return m_assemblyData.m_ISymWrapperAssembly;
- Assembly assem = Assembly.Load("ISymWrapper, Version=" + ThisAssembly.Version +
- ", Culture=neutral, PublicKeyToken=" + AssemblyRef.MicrosoftPublicKeyToken);
-
- m_assemblyData.m_ISymWrapperAssembly = assem;
- return assem;
- }
+#endregion
internal void CheckContext(params Type[][] typess)
{
@@ -839,52 +780,11 @@ namespace System.Reflection.Emit
}
return null;
}
-
- /**********************************************
- *
- * Setting the entry point if the assembly builder is building
- * an exe.
- *
- **********************************************/
- public void SetEntryPoint(
- MethodInfo entryMethod)
- {
- SetEntryPoint(entryMethod, PEFileKinds.ConsoleApplication);
- }
- 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.
- {
- lock(SyncRoot)
- {
- SetEntryPointNoLock(entryMethod, fileKind);
- }
- }
-
- private void SetEntryPointNoLock(
- MethodInfo entryMethod, // entry method for the assembly. We use this to determine the entry module
- PEFileKinds fileKind) // file kind for the assembly.
- {
-
- if (entryMethod == null)
- throw new ArgumentNullException(nameof(entryMethod));
- Contract.EndContractBlock();
-
- BCLDebug.Log("DYNIL", "## DYNIL LOGGING: AssemblyBuilder.SetEntryPoint");
-
- Module tmpModule = entryMethod.Module;
- if (tmpModule == null || !InternalAssembly.Equals(tmpModule.Assembly))
- throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_EntryMethodNotDefinedInAssembly"));
-
- m_assemblyData.m_entryPointMethod = entryMethod;
- m_assemblyData.m_peFileKind = fileKind;
- }
/**********************************************
* Use this function if client decides to form the custom attribute blob themselves
**********************************************/
- [System.Runtime.InteropServices.ComVisible(true)]
public void SetCustomAttribute(ConstructorInfo con, byte[] binaryAttribute)
{
if (con == null)
@@ -947,78 +847,6 @@ namespace System.Reflection.Emit
}
}
-
- /**********************************************
- *
- * Saves the assembly to disk. Also saves all dynamic modules defined
- * in this dynamic assembly. Assembly file name can be the same as one of
- * the module's name. If so, assembly info is stored within that module.
- * Assembly file name can be different from all of the modules underneath. In
- * this case, assembly is stored stand alone.
- *
- **********************************************/
-
- public void Save(String assemblyFileName) // assembly file name
- {
- Save(assemblyFileName, System.Reflection.PortableExecutableKinds.ILOnly, System.Reflection.ImageFileMachine.I386);
- }
-
- public void Save(String assemblyFileName,
- PortableExecutableKinds portableExecutableKind, ImageFileMachine imageFileMachine)
- {
- lock(SyncRoot)
- {
- SaveNoLock(assemblyFileName, portableExecutableKind, imageFileMachine);
- }
- }
-
- private void SaveNoLock(String assemblyFileName,
- PortableExecutableKinds portableExecutableKind, ImageFileMachine imageFileMachine)
- {
- // AssemblyBuilderAccess.Save can never be set in CoreCLR
- throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_CantSaveTransientAssembly"));
- }
-
- internal bool IsPersistable()
- {
- {
- return false;
- }
- }
-
- /**********************************************
- *
- * Internal helper to walk the nested type hierachy
- *
- **********************************************/
- private int DefineNestedComType(Type type, int tkResolutionScope, int tkTypeDef)
- {
- Type enclosingType = type.DeclaringType;
- if (enclosingType == null)
- {
- // Use full type name for non-nested types.
- return AddExportedTypeOnDisk(GetNativeHandle(), type.FullName, tkResolutionScope, tkTypeDef, type.Attributes);
- }
-
- tkResolutionScope = DefineNestedComType(enclosingType, tkResolutionScope, tkTypeDef);
- // Use simple name for nested types.
- return AddExportedTypeOnDisk(GetNativeHandle(), type.Name, tkResolutionScope, tkTypeDef, type.Attributes);
- }
-
- internal int DefineExportedTypeInMemory(Type type, int tkResolutionScope, int tkTypeDef)
- {
- Type enclosingType = type.DeclaringType;
- if (enclosingType == null)
- {
- // Use full type name for non-nested types.
- return AddExportedTypeInMemory(GetNativeHandle(), type.FullName, tkResolutionScope, tkTypeDef, type.Attributes);
- }
-
- tkResolutionScope = DefineExportedTypeInMemory(enclosingType, tkResolutionScope, tkTypeDef);
- // Use simple name for nested types.
- return AddExportedTypeInMemory(GetNativeHandle(), type.Name, tkResolutionScope, tkTypeDef, type.Attributes);
- }
-
/**********************************************
*
* Private methods
@@ -1030,105 +858,5 @@ namespace System.Reflection.Emit
* @internonly
**********************************************/
private AssemblyBuilder() {}
-
- // Create a new module in which to emit code. This module will not contain the manifest.
- [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
- [SuppressUnmanagedCodeSecurity]
- static private extern void DefineDynamicModule(RuntimeAssembly containingAssembly,
- bool emitSymbolInfo,
- String name,
- String filename,
- StackCrawlMarkHandle stackMark,
- ref IntPtr pInternalSymWriter,
- ObjectHandleOnStack retModule,
- bool fIsTransient,
- out int tkFile);
-
- private static Module DefineDynamicModule(RuntimeAssembly containingAssembly,
- bool emitSymbolInfo,
- String name,
- String filename,
- ref StackCrawlMark stackMark,
- ref IntPtr pInternalSymWriter,
- bool fIsTransient,
- out int tkFile)
- {
- RuntimeModule retModule = null;
-
- DefineDynamicModule(containingAssembly.GetNativeHandle(),
- emitSymbolInfo,
- name,
- filename,
- JitHelpers.GetStackCrawlMarkHandle(ref stackMark),
- ref pInternalSymWriter,
- JitHelpers.GetObjectHandleOnStack(ref retModule),
- fIsTransient,
- out tkFile);
-
- return retModule;
- }
-
- // The following functions are native helpers for creating on-disk manifest
- [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
-
- [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
- [SuppressUnmanagedCodeSecurity]
- static private extern void SaveManifestToDisk(RuntimeAssembly assembly,
- String strFileName,
- int entryPoint,
- int fileKind,
- int portableExecutableKind,
- int ImageFileMachine);
-
- [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
- [SuppressUnmanagedCodeSecurity]
- static private extern int AddFile(RuntimeAssembly assembly, String strFileName);
-
- [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
- [SuppressUnmanagedCodeSecurity]
- static private extern void SetFileHashValue(RuntimeAssembly assembly,
- int tkFile,
- String strFullFileName);
-
- [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
- [SuppressUnmanagedCodeSecurity]
- static private extern int AddExportedTypeInMemory(RuntimeAssembly assembly,
- String strComTypeName,
- int tkAssemblyRef,
- int tkTypeDef,
- TypeAttributes flags);
-
- [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
- [SuppressUnmanagedCodeSecurity]
- static private extern int AddExportedTypeOnDisk(RuntimeAssembly assembly,
- String strComTypeName,
- int tkAssemblyRef,
- int tkTypeDef,
- TypeAttributes flags);
-
- // Add an entry to assembly's manifestResource table for a stand alone resource.
- [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
- [SuppressUnmanagedCodeSecurity]
- static private extern void AddStandAloneResource(RuntimeAssembly assembly,
- String strName,
- String strFileName,
- String strFullFileName,
- int attribute);
-
- [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
- [SuppressUnmanagedCodeSecurity]
-#pragma warning disable 618
- static private extern void AddDeclarativeSecurity(RuntimeAssembly assembly, SecurityAction action, byte[] blob, int length);
-#pragma warning restore 618
-
- // Functions for defining unmanaged resources.
- [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
- [SuppressUnmanagedCodeSecurity]
- static private extern void CreateVersionInfoResource(String filename, String title, String iconFilename, String description,
- String copyright, String trademark, String company, String product,
- String productVersion, String fileVersion, int lcid, bool isDll,
- StringHandleOnStack retFileName);
}
}
diff --git a/src/mscorlib/src/System/Reflection/Emit/AssemblyBuilderAccess.cs b/src/mscorlib/src/System/Reflection/Emit/AssemblyBuilderAccess.cs
index 5c86d8ec87..b3d1711307 100644
--- a/src/mscorlib/src/System/Reflection/Emit/AssemblyBuilderAccess.cs
+++ b/src/mscorlib/src/System/Reflection/Emit/AssemblyBuilderAccess.cs
@@ -10,7 +10,6 @@ using System;
namespace System.Reflection.Emit
{
[Serializable]
- [System.Runtime.InteropServices.ComVisible(true)]
[Flags]
public enum AssemblyBuilderAccess
{
@@ -18,8 +17,6 @@ namespace System.Reflection.Emit
#if FEATURE_REFLECTION_ONLY_LOAD
ReflectionOnly = 6, // 4 | Save,
#endif // FEATURE_REFLECTION_ONLY_LOAD
-#if FEATURE_COLLECTIBLE_TYPES
RunAndCollect = 8 | Run
-#endif
}
}
diff --git a/src/mscorlib/src/System/Reflection/Emit/AssemblyBuilderData.cs b/src/mscorlib/src/System/Reflection/Emit/AssemblyBuilderData.cs
index f0f83e7d2a..7ac9daeac0 100644
--- a/src/mscorlib/src/System/Reflection/Emit/AssemblyBuilderData.cs
+++ b/src/mscorlib/src/System/Reflection/Emit/AssemblyBuilderData.cs
@@ -14,7 +14,6 @@ namespace System.Reflection.Emit {
using System.Security;
using System.Diagnostics;
using CultureInfo = System.Globalization.CultureInfo;
- using IResourceWriter = System.Resources.IResourceWriter;
using System.IO;
using System.Runtime.Versioning;
using System.Diagnostics.SymbolStore;
@@ -52,12 +51,6 @@ namespace System.Reflection.Emit {
{
m_moduleBuilderList.Add(dynModule);
}
-
- // Helper to add a resource information into the tracking list
- internal void AddResWriter(ResWriterData resData)
- {
- m_resWriterList.Add(resData);
- }
// Helper to track CAs to persist onto disk
@@ -110,194 +103,6 @@ namespace System.Reflection.Emit {
m_CACons[m_iCAs] = con;
m_iCAs++;
}
-
- // Helper to calculate unmanaged version info from Assembly's custom attributes.
- // If DefineUnmanagedVersionInfo is called, the parameter provided will override
- // the CA's value.
- //
- internal void FillUnmanagedVersionInfo()
- {
- // Get the lcid set on the assembly name as default if available
- // Note that if LCID is not avaible from neither AssemblyName or AssemblyCultureAttribute,
- // it is default to -1 which is treated as language neutral.
- //
- CultureInfo locale = m_assembly.GetLocale();
-#if FEATURE_USE_LCID
- if (locale != null)
- m_nativeVersion.m_lcid = locale.LCID;
-#endif
-
- for (int i = 0; i < m_iCABuilder; i++)
- {
- // check for known attributes
- Type conType = m_CABuilders[i].m_con.DeclaringType;
- if (m_CABuilders[i].m_constructorArgs.Length == 0 || m_CABuilders[i].m_constructorArgs[0] == null)
- continue;
-
- if (conType.Equals(typeof(System.Reflection.AssemblyCopyrightAttribute)))
- {
- // assert that we should only have one argument for this CA and the type should
- // be a string.
- //
- if (m_CABuilders[i].m_constructorArgs.Length != 1)
- {
- throw new ArgumentException(Environment.GetResourceString(
- "Argument_BadCAForUnmngRSC",
- m_CABuilders[i].m_con.ReflectedType.Name));
- }
- if (m_OverrideUnmanagedVersionInfo == false)
- {
- m_nativeVersion.m_strCopyright = m_CABuilders[i].m_constructorArgs[0].ToString();
- }
- }
- else if (conType.Equals(typeof(System.Reflection.AssemblyTrademarkAttribute)))
- {
- // assert that we should only have one argument for this CA and the type should
- // be a string.
- //
- if (m_CABuilders[i].m_constructorArgs.Length != 1)
- {
- throw new ArgumentException(Environment.GetResourceString(
- "Argument_BadCAForUnmngRSC",
- m_CABuilders[i].m_con.ReflectedType.Name));
- }
- if (m_OverrideUnmanagedVersionInfo == false)
- {
- m_nativeVersion.m_strTrademark = m_CABuilders[i].m_constructorArgs[0].ToString();
- }
- }
- else if (conType.Equals(typeof(System.Reflection.AssemblyProductAttribute)))
- {
- if (m_OverrideUnmanagedVersionInfo == false)
- {
- // assert that we should only have one argument for this CA and the type should
- // be a string.
- //
- m_nativeVersion.m_strProduct = m_CABuilders[i].m_constructorArgs[0].ToString();
- }
- }
- else if (conType.Equals(typeof(System.Reflection.AssemblyCompanyAttribute)))
- {
- if (m_CABuilders[i].m_constructorArgs.Length != 1)
- {
- throw new ArgumentException(Environment.GetResourceString(
- "Argument_BadCAForUnmngRSC",
- m_CABuilders[i].m_con.ReflectedType.Name));
- }
- if (m_OverrideUnmanagedVersionInfo == false)
- {
- // assert that we should only have one argument for this CA and the type should
- // be a string.
- //
- m_nativeVersion.m_strCompany = m_CABuilders[i].m_constructorArgs[0].ToString();
- }
- }
- else if (conType.Equals(typeof(System.Reflection.AssemblyDescriptionAttribute)))
- {
- if (m_CABuilders[i].m_constructorArgs.Length != 1)
- {
- throw new ArgumentException(Environment.GetResourceString(
- "Argument_BadCAForUnmngRSC",
- m_CABuilders[i].m_con.ReflectedType.Name));
- }
- m_nativeVersion.m_strDescription = m_CABuilders[i].m_constructorArgs[0].ToString();
- }
- else if (conType.Equals(typeof(System.Reflection.AssemblyTitleAttribute)))
- {
- if (m_CABuilders[i].m_constructorArgs.Length != 1)
- {
- throw new ArgumentException(Environment.GetResourceString(
- "Argument_BadCAForUnmngRSC",
- m_CABuilders[i].m_con.ReflectedType.Name));
- }
- m_nativeVersion.m_strTitle = m_CABuilders[i].m_constructorArgs[0].ToString();
- }
- else if (conType.Equals(typeof(System.Reflection.AssemblyInformationalVersionAttribute)))
- {
- if (m_CABuilders[i].m_constructorArgs.Length != 1)
- {
- throw new ArgumentException(Environment.GetResourceString(
- "Argument_BadCAForUnmngRSC",
- m_CABuilders[i].m_con.ReflectedType.Name));
- }
- if (m_OverrideUnmanagedVersionInfo == false)
- {
- m_nativeVersion.m_strProductVersion = m_CABuilders[i].m_constructorArgs[0].ToString();
- }
- }
- else if (conType.Equals(typeof(System.Reflection.AssemblyCultureAttribute)))
- {
- // retrieve the LCID
- if (m_CABuilders[i].m_constructorArgs.Length != 1)
- {
- throw new ArgumentException(Environment.GetResourceString(
- "Argument_BadCAForUnmngRSC",
- m_CABuilders[i].m_con.ReflectedType.Name));
- }
- // CultureInfo attribute overrides the lcid from AssemblyName.
- CultureInfo culture = new CultureInfo(m_CABuilders[i].m_constructorArgs[0].ToString());
-#if FEATURE_USE_LCID
- m_nativeVersion.m_lcid = culture.LCID;
-#endif
- }
- else if (conType.Equals(typeof(System.Reflection.AssemblyFileVersionAttribute)))
- {
- if (m_CABuilders[i].m_constructorArgs.Length != 1)
- {
- throw new ArgumentException(Environment.GetResourceString(
- "Argument_BadCAForUnmngRSC",
- m_CABuilders[i].m_con.ReflectedType.Name));
- }
- if (m_OverrideUnmanagedVersionInfo == false)
- {
- m_nativeVersion.m_strFileVersion = m_CABuilders[i].m_constructorArgs[0].ToString();
- }
- }
- }
- }
-
-
- // Helper to ensure the resource name is unique underneath assemblyBuilder
- internal void CheckResNameConflict(String strNewResName)
- {
- int size = m_resWriterList.Count;
- int i;
- for (i = 0; i < size; i++)
- {
- ResWriterData resWriter = m_resWriterList[i];
- if (resWriter.m_strName.Equals(strNewResName))
- {
- // Cannot have two resources with the same name
- throw new ArgumentException(Environment.GetResourceString("Argument_DuplicateResourceName"));
- }
- }
- }
-
-
- // Helper to ensure the module name is unique underneath assemblyBuilder
- internal void CheckNameConflict(String strNewModuleName)
- {
- int size = m_moduleBuilderList.Count;
- int i;
- for (i = 0; i < size; i++)
- {
- ModuleBuilder moduleBuilder = m_moduleBuilderList[i];
- if (moduleBuilder.m_moduleData.m_strModuleName.Equals(strNewModuleName))
- {
- // Cannot have two dynamic modules with the same name
- throw new ArgumentException(Environment.GetResourceString("Argument_DuplicateModuleName"));
- }
- }
-
- // Right now dynamic modules can only be added to dynamic assemblies in which
- // all modules are dynamic. Otherwise we would also need to check the static modules
- // with this:
- // if (m_assembly.GetModule(strNewModuleName) != null)
- // {
- // // Cannot have two dynamic modules with the same name
- // throw new ArgumentException(Environment.GetResourceString("Argument_DuplicateModuleName"));
- // }
- }
// Helper to ensure the type name is unique underneath assemblyBuilder
internal void CheckTypeNameConflict(String strTypeName, TypeBuilder enclosingType)
@@ -320,134 +125,6 @@ namespace System.Reflection.Emit {
// }
}
-
- // Helper to ensure the file name is unique underneath assemblyBuilder. This includes
- // modules and resources.
- //
- //
- //
- internal void CheckFileNameConflict(String strFileName)
- {
- int size = m_moduleBuilderList.Count;
- int i;
- for (i = 0; i < size; i++)
- {
- ModuleBuilder moduleBuilder = m_moduleBuilderList[i];
- if (moduleBuilder.m_moduleData.m_strFileName != null)
- {
- if (String.Compare(moduleBuilder.m_moduleData.m_strFileName, strFileName, StringComparison.OrdinalIgnoreCase) == 0)
- {
- // Cannot have two dynamic module with the same name
- throw new ArgumentException(Environment.GetResourceString("Argument_DuplicatedFileName"));
- }
- }
- }
- size = m_resWriterList.Count;
- for (i = 0; i < size; i++)
- {
- ResWriterData resWriter = m_resWriterList[i];
- if (resWriter.m_strFileName != null)
- {
- if (String.Compare(resWriter.m_strFileName, strFileName, StringComparison.OrdinalIgnoreCase) == 0)
- {
- // Cannot have two dynamic module with the same name
- throw new ArgumentException(Environment.GetResourceString("Argument_DuplicatedFileName"));
- }
- }
- }
-
- }
-
- // Helper to look up which module that assembly is supposed to be stored at
- //
- //
- //
- internal ModuleBuilder FindModuleWithFileName(String strFileName)
- {
- int size = m_moduleBuilderList.Count;
- int i;
- for (i = 0; i < size; i++)
- {
- ModuleBuilder moduleBuilder = m_moduleBuilderList[i];
- if (moduleBuilder.m_moduleData.m_strFileName != null)
- {
- if (String.Compare(moduleBuilder.m_moduleData.m_strFileName, strFileName, StringComparison.OrdinalIgnoreCase) == 0)
- {
- return moduleBuilder;
- }
- }
- }
- return null;
- }
-
- // Helper to look up module by name.
- //
- //
- //
- internal ModuleBuilder FindModuleWithName(String strName)
- {
- int size = m_moduleBuilderList.Count;
- int i;
- for (i = 0; i < size; i++)
- {
- ModuleBuilder moduleBuilder = m_moduleBuilderList[i];
- if (moduleBuilder.m_moduleData.m_strModuleName != null)
- {
- if (String.Compare(moduleBuilder.m_moduleData.m_strModuleName, strName, StringComparison.OrdinalIgnoreCase) == 0)
- return moduleBuilder;
- }
- }
- return null;
- }
-
-
- // add type to public COMType tracking list
- internal void AddPublicComType(Type type)
- {
- BCLDebug.Log("DYNIL","## DYNIL LOGGING: AssemblyBuilderData.AddPublicComType( " + type.FullName + " )");
- if (m_isSaved == true)
- {
- // assembly has been saved before!
- throw new InvalidOperationException(Environment.GetResourceString(
- "InvalidOperation_CannotAlterAssembly"));
- }
- EnsurePublicComTypeCapacity();
- m_publicComTypeList[m_iPublicComTypeCount] = type;
- m_iPublicComTypeCount++;
- }
-
- // add security permission requests
- internal void AddPermissionRequests(
- PermissionSet required,
- PermissionSet optional,
- PermissionSet refused)
- {
- BCLDebug.Log("DYNIL","## DYNIL LOGGING: AssemblyBuilderData.AddPermissionRequests");
- if (m_isSaved == true)
- {
- // assembly has been saved before!
- throw new InvalidOperationException(Environment.GetResourceString(
- "InvalidOperation_CannotAlterAssembly"));
- }
- m_RequiredPset = required;
- m_OptionalPset = optional;
- m_RefusedPset = refused;
- }
-
- private void EnsurePublicComTypeCapacity()
- {
- if (m_publicComTypeList == null)
- {
- m_publicComTypeList = new Type[m_iInitialSize];
- }
- if (m_iPublicComTypeCount == m_publicComTypeList.Length)
- {
- Type[] tempTypeList = new Type[m_iPublicComTypeCount * 2];
- Array.Copy(m_publicComTypeList, 0, tempTypeList, 0, m_iPublicComTypeCount);
- m_publicComTypeList = tempTypeList;
- }
- }
-
internal List<ModuleBuilder> m_moduleBuilderList;
internal List<ResWriterData> m_resWriterList;
internal String m_strAssemblyName;
@@ -463,11 +140,6 @@ 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;
- internal PermissionSet m_RefusedPset;
// tracking AssemblyDef's CAs for persistence to disk
internal CustomAttributeBuilder[] m_CABuilders;
@@ -497,24 +169,6 @@ namespace System.Reflection.Emit {
**********************************************/
internal class ResWriterData
{
- internal ResWriterData(
- IResourceWriter 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;
- }
-
- 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
deleted file mode 100644
index 8dba934bde..0000000000
--- a/src/mscorlib/src/System/Reflection/Emit/ComInterfaces.cs
+++ /dev/null
@@ -1,143 +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
-{
- [GuidAttribute("BEBB2505-8B54-3443-AEAD-142A16DD9CC7")]
- [InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)]
- [CLSCompliant(false)]
- [TypeLibImportClassAttribute(typeof(System.Reflection.Emit.AssemblyBuilder))]
- [System.Runtime.InteropServices.ComVisible(true)]
- public interface _AssemblyBuilder
- {
- }
-
- [GuidAttribute("ED3E4384-D7E2-3FA7-8FFD-8940D330519A")]
- [InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)]
- [CLSCompliant(false)]
- [TypeLibImportClassAttribute(typeof(System.Reflection.Emit.ConstructorBuilder))]
- [System.Runtime.InteropServices.ComVisible(true)]
- public interface _ConstructorBuilder
- {
- }
-
- [GuidAttribute("BE9ACCE8-AAFF-3B91-81AE-8211663F5CAD")]
- [InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)]
- [CLSCompliant(false)]
- [TypeLibImportClassAttribute(typeof(System.Reflection.Emit.CustomAttributeBuilder))]
- [System.Runtime.InteropServices.ComVisible(true)]
- public interface _CustomAttributeBuilder
- {
- }
-
- [GuidAttribute("C7BD73DE-9F85-3290-88EE-090B8BDFE2DF")]
- [InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)]
- [CLSCompliant(false)]
- [TypeLibImportClassAttribute(typeof(System.Reflection.Emit.EnumBuilder))]
- [System.Runtime.InteropServices.ComVisible(true)]
- public interface _EnumBuilder
- {
- }
-
- [GuidAttribute("AADABA99-895D-3D65-9760-B1F12621FAE8")]
- [InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)]
- [CLSCompliant(false)]
- [TypeLibImportClassAttribute(typeof(System.Reflection.Emit.EventBuilder))]
- [System.Runtime.InteropServices.ComVisible(true)]
- public interface _EventBuilder
- {
- }
-
- [GuidAttribute("CE1A3BF5-975E-30CC-97C9-1EF70F8F3993")]
- [InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)]
- [CLSCompliant(false)]
- [TypeLibImportClassAttribute(typeof(System.Reflection.Emit.FieldBuilder))]
- [System.Runtime.InteropServices.ComVisible(true)]
- public interface _FieldBuilder
- {
- }
-
- [GuidAttribute("A4924B27-6E3B-37F7-9B83-A4501955E6A7")]
- [InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)]
- [CLSCompliant(false)]
- [TypeLibImportClassAttribute(typeof(System.Reflection.Emit.ILGenerator))]
- [System.Runtime.InteropServices.ComVisible(true)]
- public interface _ILGenerator
- {
- }
-
- [GuidAttribute("4E6350D1-A08B-3DEC-9A3E-C465F9AEEC0C")]
- [InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)]
- [CLSCompliant(false)]
- [TypeLibImportClassAttribute(typeof(System.Reflection.Emit.LocalBuilder))]
- [System.Runtime.InteropServices.ComVisible(true)]
- public interface _LocalBuilder
- {
- }
-
- [GuidAttribute("007D8A14-FDF3-363E-9A0B-FEC0618260A2")]
- [InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)]
- [CLSCompliant(false)]
- [TypeLibImportClassAttribute(typeof(System.Reflection.Emit.MethodBuilder))]
- [System.Runtime.InteropServices.ComVisible(true)]
- public interface _MethodBuilder
- {
- }
-
-#if FEATURE_METHOD_RENTAL
- [GuidAttribute("C2323C25-F57F-3880-8A4D-12EBEA7A5852")]
- [InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)]
- [CLSCompliant(false)]
- [TypeLibImportClassAttribute(typeof(System.Reflection.Emit.MethodRental))]
- [System.Runtime.InteropServices.ComVisible(true)]
- public interface _MethodRental
- {
- }
-#endif
-
- [GuidAttribute("D05FFA9A-04AF-3519-8EE1-8D93AD73430B")]
- [InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)]
- [CLSCompliant(false)]
- [TypeLibImportClassAttribute(typeof(System.Reflection.Emit.ModuleBuilder))]
- [System.Runtime.InteropServices.ComVisible(true)]
- public interface _ModuleBuilder
- {
- }
-
- [GuidAttribute("36329EBA-F97A-3565-BC07-0ED5C6EF19FC")]
- [InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)]
- [CLSCompliant(false)]
- [TypeLibImportClassAttribute(typeof(System.Reflection.Emit.ParameterBuilder))]
- [System.Runtime.InteropServices.ComVisible(true)]
- public interface _ParameterBuilder
- {
- }
-
- [GuidAttribute("15F9A479-9397-3A63-ACBD-F51977FB0F02")]
- [InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)]
- [CLSCompliant(false)]
- [TypeLibImportClassAttribute(typeof(System.Reflection.Emit.PropertyBuilder))]
- [System.Runtime.InteropServices.ComVisible(true)]
- public interface _PropertyBuilder
- {
- }
-
- [GuidAttribute("7D13DD37-5A04-393C-BBCA-A5FEA802893D")]
- [InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)]
- [CLSCompliant(false)]
- [TypeLibImportClassAttribute(typeof(System.Reflection.Emit.SignatureHelper))]
- [System.Runtime.InteropServices.ComVisible(true)]
- public interface _SignatureHelper
- {
- }
-
- [GuidAttribute("7E5678EE-48B3-3F83-B076-C58543498A58")]
- [InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)]
- [CLSCompliant(false)]
- [TypeLibImportClassAttribute(typeof(System.Reflection.Emit.TypeBuilder))]
- [System.Runtime.InteropServices.ComVisible(true)]
- public interface _TypeBuilder
- {
- }
-}
diff --git a/src/mscorlib/src/System/Reflection/Emit/ConstructorBuilder.cs b/src/mscorlib/src/System/Reflection/Emit/ConstructorBuilder.cs
index ef76adcf80..3bc02860a1 100644
--- a/src/mscorlib/src/System/Reflection/Emit/ConstructorBuilder.cs
+++ b/src/mscorlib/src/System/Reflection/Emit/ConstructorBuilder.cs
@@ -12,14 +12,10 @@ namespace System.Reflection.Emit
using System.Collections.Generic;
using System.Diagnostics.SymbolStore;
using System.Security;
- using System.Security.Permissions;
using System.Runtime.InteropServices;
using System.Diagnostics.Contracts;
- [ClassInterface(ClassInterfaceType.None)]
- [ComDefaultInterface(typeof(_ConstructorBuilder))]
- [System.Runtime.InteropServices.ComVisible(true)]
- public sealed class ConstructorBuilder : ConstructorInfo, _ConstructorBuilder
+ public sealed class ConstructorBuilder : ConstructorInfo
{
private readonly MethodBuilder m_methodBuilder;
internal bool m_isDefaultConstructor;
@@ -65,11 +61,6 @@ namespace System.Reflection.Emit
{
return m_methodBuilder.GetTypeBuilder();
}
-
- internal ModuleBuilder GetModuleBuilder()
- {
- return GetTypeBuilder().GetModuleBuilder();
- }
#endregion
#region Object Overrides
@@ -181,11 +172,6 @@ namespace System.Reflection.Emit
return m_methodBuilder.DefineParameter(iSequence, attributes, strParamName);
}
- public void SetSymCustomAttribute(String name, byte[] data)
- {
- m_methodBuilder.SetSymCustomAttribute(name, data);
- }
-
public ILGenerator GetILGenerator()
{
if (m_isDefaultConstructor)
@@ -202,16 +188,6 @@ namespace System.Reflection.Emit
return m_methodBuilder.GetILGenerator(streamSize);
}
- public void SetMethodBody(byte[] il, int maxStack, byte[] localSignature, IEnumerable<ExceptionHandler> exceptionHandlers, IEnumerable<int> tokenFixups)
- {
- if (m_isDefaultConstructor)
- {
- throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_DefaultConstructorDefineBody"));
- }
-
- m_methodBuilder.SetMethodBody(il, maxStack, localSignature, exceptionHandlers, tokenFixups);
- }
-
public override CallingConventions CallingConvention
{
get
@@ -227,13 +203,6 @@ namespace System.Reflection.Emit
{
return m_methodBuilder.GetModule();
}
-
-
- [Obsolete("This property has been deprecated. http://go.microsoft.com/fwlink/?linkid=14202")] //It always returns null.
- public Type ReturnType
- {
- get { return GetReturnType(); }
- }
// This always returns null. Is that what we want?
internal override Type GetReturnType()
@@ -246,7 +215,6 @@ namespace System.Reflection.Emit
get { return m_methodBuilder.Signature; }
}
- [System.Runtime.InteropServices.ComVisible(true)]
public void SetCustomAttribute(ConstructorInfo con, byte[] binaryAttribute)
{
m_methodBuilder.SetCustomAttribute(con, binaryAttribute);
diff --git a/src/mscorlib/src/System/Reflection/Emit/CustomAttributeBuilder.cs b/src/mscorlib/src/System/Reflection/Emit/CustomAttributeBuilder.cs
index 545657a053..5d08ca08f0 100644
--- a/src/mscorlib/src/System/Reflection/Emit/CustomAttributeBuilder.cs
+++ b/src/mscorlib/src/System/Reflection/Emit/CustomAttributeBuilder.cs
@@ -19,16 +19,12 @@ namespace System.Reflection.Emit {
using System.Reflection;
using System.IO;
using System.Text;
- using System.Security.Permissions;
using System.Runtime.InteropServices;
using System.Globalization;
using System.Diagnostics;
using System.Diagnostics.Contracts;
- [ClassInterface(ClassInterfaceType.None)]
- [ComDefaultInterface(typeof(_CustomAttributeBuilder))]
- [System.Runtime.InteropServices.ComVisible(true)]
- public class CustomAttributeBuilder : _CustomAttributeBuilder
+ public class CustomAttributeBuilder
{
// public constructor to form the custom attribute with constructor and constructor
// parameters.
@@ -556,18 +552,6 @@ namespace System.Reflection.Emit {
}
//*************************************************
- // Upon saving to disk, we need to create the memberRef token for the custom attribute's type
- // first of all. So when we snap the in-memory module for on disk, this token will be there.
- // We also need to enforce the use of MemberRef. Because MemberDef token might move.
- // This function has to be called before we snap the in-memory module for on disk (i.e. Presave on
- // ModuleBuilder.
- //*************************************************
- internal int PrepareCreateCustomAttributeToDisk(ModuleBuilder mod)
- {
- return mod.InternalGetConstructorToken(m_con, true).Token;
- }
-
- //*************************************************
// Call this function with toDisk=1, after on disk module has been snapped.
//*************************************************
internal void CreateCustomAttribute(ModuleBuilder mod, int tkOwner, int tkAttrib, bool toDisk)
diff --git a/src/mscorlib/src/System/Reflection/Emit/DynamicILGenerator.cs b/src/mscorlib/src/System/Reflection/Emit/DynamicILGenerator.cs
index 9e1d82986a..cb2667a104 100644
--- a/src/mscorlib/src/System/Reflection/Emit/DynamicILGenerator.cs
+++ b/src/mscorlib/src/System/Reflection/Emit/DynamicILGenerator.cs
@@ -14,7 +14,6 @@ namespace System.Reflection.Emit
using System.Reflection;
using System.Collections;
using System.Collections.Generic;
- using System.Security.Permissions;
using System.Threading;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
@@ -142,7 +141,6 @@ namespace System.Reflection.Emit
PutInteger4(token);
}
- [System.Runtime.InteropServices.ComVisible(true)]
public override void Emit(OpCode opcode, ConstructorInfo con)
{
if (con == null)
@@ -267,43 +265,6 @@ namespace System.Reflection.Emit
PutInteger4(token);
}
- public override void EmitCalli(OpCode opcode,
- CallingConvention unmanagedCallConv,
- Type returnType,
- Type[] parameterTypes)
- {
- int stackchange = 0;
- int cParams = 0;
- int i;
- SignatureHelper sig;
-
- if (parameterTypes != null)
- cParams = parameterTypes.Length;
-
- sig = SignatureHelper.GetMethodSigHelper(unmanagedCallConv, returnType);
-
- if (parameterTypes != null)
- for (i = 0; i < cParams; i++)
- sig.AddArgument(parameterTypes[i]);
-
- // If there is a non-void return type, push one.
- if (returnType != typeof(void))
- stackchange++;
-
- // Pop off arguments if any.
- if (parameterTypes != null)
- stackchange -= cParams;
-
- // Pop the native function pointer.
- stackchange--;
- UpdateStackSize(OpCodes.Calli, stackchange);
-
- EnsureCapacity(7);
- Emit(OpCodes.Calli);
- int token = GetTokenForSig(sig.GetSignature(true));
- PutInteger4(token);
- }
-
public override void EmitCall(OpCode opcode, MethodInfo methodInfo, Type[] optionalParameterTypes)
{
if (methodInfo == null)
@@ -379,19 +340,20 @@ namespace System.Reflection.Emit
// Exception related generation
//
//
- public override Label BeginExceptionBlock()
+ public override void BeginExceptFilterBlock()
{
- return base.BeginExceptionBlock();
- }
+ // Begins an exception filter block. Emits a branch instruction to the end of the current exception block.
- public override void EndExceptionBlock()
- {
- base.EndExceptionBlock();
- }
+ if (CurrExcStackCount == 0)
+ throw new NotSupportedException(Environment.GetResourceString("Argument_NotInExceptionBlock"));
- public override void BeginExceptFilterBlock()
- {
- throw new NotSupportedException(Environment.GetResourceString("InvalidOperation_NotAllowedInDynamicMethod"));
+ __ExceptionInfo current = CurrExcStack[CurrExcStackCount - 1];
+
+ Label endLabel = current.GetEndLabel();
+ Emit(OpCodes.Leave, endLabel);
+ UpdateStackSize(OpCodes.Nop, 1);
+
+ current.MarkFilterAddr(ILOffset);
}
public override void BeginCatchBlock(Type exceptionType)
@@ -412,6 +374,8 @@ namespace System.Reflection.Emit
}
this.Emit(OpCodes.Endfilter);
+
+ current.MarkCatchAddr(ILOffset, null);
}
else
{
@@ -427,24 +391,14 @@ namespace System.Reflection.Emit
// if this is a catch block the exception will be pushed on the stack and we need to update the stack info
UpdateStackSize(OpCodes.Nop, 1);
- }
-
- current.MarkCatchAddr(ILOffset, exceptionType);
-
- // this is relying on too much implementation details of the base and so it's highly breaking
- // Need to have a more integreted story for exceptions
- current.m_filterAddr[current.m_currentCatch - 1] = GetTokenFor(rtType);
- }
+ current.MarkCatchAddr(ILOffset, exceptionType);
- public override void BeginFaultBlock()
- {
- throw new NotSupportedException(Environment.GetResourceString("InvalidOperation_NotAllowedInDynamicMethod"));
- }
- public override void BeginFinallyBlock()
- {
- base.BeginFinallyBlock();
+ // this is relying on too much implementation details of the base and so it's highly breaking
+ // Need to have a more integrated story for exceptions
+ current.m_filterAddr[current.m_currentCatch - 1] = GetTokenFor(rtType);
+ }
}
//
@@ -520,22 +474,18 @@ namespace System.Reflection.Emit
Type[] parameterTypes,
Type[] optionalParameterTypes)
{
- int cParams;
- int i;
- SignatureHelper sig;
- if (parameterTypes == null)
- cParams = 0;
- else
- cParams = parameterTypes.Length;
- sig = SignatureHelper.GetMethodSigHelper(call, returnType);
- for (i = 0; i < cParams; i++)
- sig.AddArgument(parameterTypes[i]);
+ SignatureHelper sig = SignatureHelper.GetMethodSigHelper(call, returnType);
+ if (parameterTypes != null)
+ {
+ foreach (Type t in parameterTypes)
+ sig.AddArgument(t);
+ }
if (optionalParameterTypes != null && optionalParameterTypes.Length != 0)
{
// add the sentinel
sig.AddSentinel();
- for (i = 0; i < optionalParameterTypes.Length; i++)
- sig.AddArgument(optionalParameterTypes[i]);
+ foreach (Type t in optionalParameterTypes)
+ sig.AddArgument(t);
}
return sig;
}
@@ -811,17 +761,6 @@ namespace System.Reflection.Emit
typeOwner = m_method.m_typeOwner;
-#if FEATURE_COMPRESSEDSTACK
- if (m_method.m_creationContext != null)
- {
- flags |= SecurityControlFlags.HasCreationContext;
- if(m_method.m_creationContext.CanSkipEvaluation)
- {
- flags |= SecurityControlFlags.CanSkipCSEvaluation;
- }
- }
-
-#endif // FEATURE_COMPRESSEDSTACK
securityControlFlags = (int)flags;
@@ -904,12 +843,6 @@ namespace System.Reflection.Emit
internal override String GetStringLiteral(int token) { return m_scope.GetString(token); }
-#if FEATURE_COMPRESSEDSTACK
- internal override CompressedStack GetSecurityContext()
- {
- return m_method.m_creationContext;
- }
-#endif // FEATURE_COMPRESSEDSTACK
internal override void ResolveToken(int token, out IntPtr typeHandle, out IntPtr methodHandle, out IntPtr fieldHandle)
{
@@ -991,8 +924,7 @@ namespace System.Reflection.Emit
}
- [System.Runtime.InteropServices.ComVisible(true)]
- public class DynamicILInfo
+ internal class DynamicILInfo
{
#region Private Data Members
private DynamicMethod m_method;
@@ -1004,18 +936,6 @@ namespace System.Reflection.Emit
private int m_methodSignature;
#endregion
- #region Constructor
- internal DynamicILInfo(DynamicScope scope, DynamicMethod method, byte[] methodSignature)
- {
- m_method = method;
- m_scope = scope;
- m_methodSignature = m_scope.GetTokenFor(methodSignature);
- m_exceptions = EmptyArray<Byte>.Value;
- m_code = EmptyArray<Byte>.Value;
- m_localSignature = EmptyArray<Byte>.Value;
- }
- #endregion
-
#region Internal Methods
internal void GetCallableMethod(RuntimeModule module, DynamicMethod dm)
{
@@ -1042,113 +962,8 @@ namespace System.Reflection.Emit
public DynamicMethod DynamicMethod { get { return m_method; } }
internal DynamicScope DynamicScope { get { return m_scope; } }
- public void SetCode(byte[] code, int maxStackSize)
- {
- m_code = (code != null) ? (byte[])code.Clone() : EmptyArray<Byte>.Value;
- m_maxStackSize = maxStackSize;
- }
-
- [CLSCompliant(false)]
- public unsafe void SetCode(byte* code, int codeSize, int maxStackSize)
- {
- if (codeSize < 0)
- throw new ArgumentOutOfRangeException(nameof(codeSize), Environment.GetResourceString("ArgumentOutOfRange_GenericPositive"));
-
- if (codeSize > 0 && code == null)
- throw new ArgumentNullException(nameof(code));
- Contract.EndContractBlock();
-
- m_code = new byte[codeSize];
- for (int i = 0; i < codeSize; i++)
- {
- m_code[i] = *code;
- code++;
- }
-
- m_maxStackSize = maxStackSize;
- }
-
- public void SetExceptions(byte[] exceptions)
- {
- m_exceptions = (exceptions != null) ? (byte[])exceptions.Clone() : EmptyArray<Byte>.Value;
- }
-
- [CLSCompliant(false)]
- public unsafe void SetExceptions(byte* exceptions, int exceptionsSize)
- {
- if (exceptionsSize < 0)
- throw new ArgumentOutOfRangeException(nameof(exceptionsSize), Environment.GetResourceString("ArgumentOutOfRange_GenericPositive"));
-
- if (exceptionsSize > 0 && exceptions == null)
- throw new ArgumentNullException(nameof(exceptions));
- Contract.EndContractBlock();
-
- m_exceptions = new byte[exceptionsSize];
-
- for (int i = 0; i < exceptionsSize; i++)
- {
- m_exceptions[i] = *exceptions;
- exceptions++;
- }
- }
-
- public void SetLocalSignature(byte[] localSignature)
- {
- m_localSignature = (localSignature != null) ? (byte[])localSignature.Clone() : EmptyArray<Byte>.Value;
- }
-
- [CLSCompliant(false)]
- public unsafe void SetLocalSignature(byte* localSignature, int signatureSize)
- {
- if (signatureSize < 0)
- throw new ArgumentOutOfRangeException(nameof(signatureSize), Environment.GetResourceString("ArgumentOutOfRange_GenericPositive"));
-
- if (signatureSize > 0 && localSignature == null)
- throw new ArgumentNullException(nameof(localSignature));
- Contract.EndContractBlock();
-
- m_localSignature = new byte[signatureSize];
- for (int i = 0; i < signatureSize; i++)
- {
- m_localSignature[i] = *localSignature;
- localSignature++;
- }
- }
- #endregion
-
- #region Public Scope Methods
- public int GetTokenFor(RuntimeMethodHandle method)
- {
- return DynamicScope.GetTokenFor(method);
- }
- public int GetTokenFor(DynamicMethod method)
- {
- return DynamicScope.GetTokenFor(method);
- }
- public int GetTokenFor(RuntimeMethodHandle method, RuntimeTypeHandle contextType)
- {
- return DynamicScope.GetTokenFor(method, contextType);
- }
- public int GetTokenFor(RuntimeFieldHandle field)
- {
- return DynamicScope.GetTokenFor(field);
- }
- public int GetTokenFor(RuntimeFieldHandle field, RuntimeTypeHandle contextType)
- {
- return DynamicScope.GetTokenFor(field, contextType);
- }
- public int GetTokenFor(RuntimeTypeHandle type)
- {
- return DynamicScope.GetTokenFor(type);
- }
- public int GetTokenFor(string literal)
- {
- return DynamicScope.GetTokenFor(literal);
- }
- public int GetTokenFor(byte[] signature)
- {
- return DynamicScope.GetTokenFor(signature);
- }
+#endregion
+#region Public Scope Methods
#endregion
}
diff --git a/src/mscorlib/src/System/Reflection/Emit/DynamicMethod.cs b/src/mscorlib/src/System/Reflection/Emit/DynamicMethod.cs
index 1b8c97de65..f1d99d3c2c 100644
--- a/src/mscorlib/src/System/Reflection/Emit/DynamicMethod.cs
+++ b/src/mscorlib/src/System/Reflection/Emit/DynamicMethod.cs
@@ -11,7 +11,6 @@ namespace System.Reflection.Emit
using CultureInfo = System.Globalization.CultureInfo;
using System.Reflection;
using System.Security;
- using System.Security.Permissions;
using System.Threading;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
@@ -19,7 +18,6 @@ namespace System.Reflection.Emit
using System.Diagnostics.Contracts;
using System.Runtime.InteropServices;
- [System.Runtime.InteropServices.ComVisible(true)]
public sealed class DynamicMethod : MethodInfo
{
private RuntimeType[] m_parameterTypes;
@@ -58,9 +56,6 @@ namespace System.Reflection.Emit
// We capture the creation context so that we can do the checks against the same context,
// irrespective of when the method gets compiled. Note that the DynamicMethod does not know when
// it is ready for use since there is not API which indictates that IL generation has completed.
-#if FEATURE_COMPRESSEDSTACK
- internal CompressedStack m_creationContext;
-#endif // FEATURE_COMPRESSEDSTACK
private static volatile InternalModuleBuilder s_anonymouslyHostedDynamicMethodsModule;
private static readonly object s_anonymouslyHostedDynamicMethodsModuleLock = new object();
@@ -274,7 +269,7 @@ namespace System.Reflection.Emit
AssemblyBuilder assembly = AssemblyBuilder.InternalDefineDynamicAssembly(
assemblyName,
AssemblyBuilderAccess.Run,
- null, null, null, null, null,
+ null, null,
ref stackMark,
assemblyAttributes,
SecurityContextSource.CurrentAssembly);
@@ -330,9 +325,6 @@ namespace System.Reflection.Emit
m_restrictedSkipVisibility = true;
}
-#if FEATURE_COMPRESSEDSTACK
- m_creationContext = CompressedStack.Capture();
-#endif // FEATURE_COMPRESSEDSTACK
}
else
{
@@ -401,7 +393,6 @@ namespace System.Reflection.Emit
// Delegate and method creation
//
- [System.Runtime.InteropServices.ComVisible(true)]
public sealed override Delegate CreateDelegate(Type delegateType) {
if (m_restrictedSkipVisibility)
{
@@ -416,7 +407,6 @@ namespace System.Reflection.Emit
return d;
}
- [System.Runtime.InteropServices.ComVisible(true)]
public sealed override Delegate CreateDelegate(Type delegateType, Object target) {
if (m_restrictedSkipVisibility)
{
@@ -594,30 +584,6 @@ namespace System.Reflection.Emit
return null;
}
- public DynamicILInfo GetDynamicILInfo()
- {
-#pragma warning disable 618
- new SecurityPermission(SecurityPermissionFlag.UnmanagedCode).Demand();
-#pragma warning restore 618
-
- if (m_DynamicILInfo != null)
- return m_DynamicILInfo;
-
- return GetDynamicILInfo(new DynamicScope());
- }
-
- internal DynamicILInfo GetDynamicILInfo(DynamicScope scope)
- {
- if (m_DynamicILInfo == null)
- {
- byte[] methodSignature = SignatureHelper.GetMethodSigHelper(
- null, CallingConvention, ReturnType, null, null, m_parameterTypes, null, null).GetSignature(true);
- m_DynamicILInfo = new DynamicILInfo(scope, this, methodSignature);
- }
-
- return m_DynamicILInfo;
- }
-
public ILGenerator GetILGenerator() {
return GetILGenerator(64);
}
diff --git a/src/mscorlib/src/System/Reflection/Emit/EnumBuilder.cs b/src/mscorlib/src/System/Reflection/Emit/EnumBuilder.cs
index 82dc2828ca..96564d537b 100644
--- a/src/mscorlib/src/System/Reflection/Emit/EnumBuilder.cs
+++ b/src/mscorlib/src/System/Reflection/Emit/EnumBuilder.cs
@@ -20,13 +20,8 @@ namespace System.Reflection.Emit {
using System.Reflection;
using System.Runtime.InteropServices;
using CultureInfo = System.Globalization.CultureInfo;
- using System.Security.Permissions;
-
- [ClassInterface(ClassInterfaceType.None)]
- [ComDefaultInterface(typeof(_EnumBuilder))]
-[System.Runtime.InteropServices.ComVisible(true)]
- sealed public class EnumBuilder : TypeInfo, _EnumBuilder
+ sealed public class EnumBuilder : TypeInfo
{
public override bool IsAssignableFrom(System.Reflection.TypeInfo typeInfo){
if(typeInfo==null) return false;
@@ -137,7 +132,6 @@ namespace System.Reflection.Emit {
types, modifiers);
}
-[System.Runtime.InteropServices.ComVisible(true)]
public override ConstructorInfo[] GetConstructors(BindingFlags bindingAttr)
{
return m_typeBuilder.GetConstructors(bindingAttr);
@@ -218,7 +212,6 @@ namespace System.Reflection.Emit {
return m_typeBuilder.GetMembers(bindingAttr);
}
-[System.Runtime.InteropServices.ComVisible(true)]
public override InterfaceMapping GetInterfaceMap(Type interfaceType)
{
return m_typeBuilder.GetInterfaceMap(interfaceType);
@@ -312,7 +305,6 @@ namespace System.Reflection.Emit {
// Use this function if client decides to form the custom attribute blob themselves
-[System.Runtime.InteropServices.ComVisible(true)]
public void SetCustomAttribute(ConstructorInfo con, byte[] binaryAttribute)
{
m_typeBuilder.SetCustomAttribute(con, binaryAttribute);
@@ -341,9 +333,6 @@ namespace System.Reflection.Emit {
{
return m_typeBuilder.IsDefined(attributeType, inherit);
}
-
-
- internal int MetadataTokenInternal { get { return m_typeBuilder.MetadataTokenInternal; } }
/*****************************************************
*
diff --git a/src/mscorlib/src/System/Reflection/Emit/EventBuilder.cs b/src/mscorlib/src/System/Reflection/Emit/EventBuilder.cs
index 449b20824c..34c76b93d1 100644
--- a/src/mscorlib/src/System/Reflection/Emit/EventBuilder.cs
+++ b/src/mscorlib/src/System/Reflection/Emit/EventBuilder.cs
@@ -16,7 +16,6 @@ namespace System.Reflection.Emit {
using System;
using System.Reflection;
- using System.Security.Permissions;
using System.Runtime.InteropServices;
using System.Diagnostics.Contracts;
@@ -24,10 +23,7 @@ namespace System.Reflection.Emit {
// A EventBuilder is always associated with a TypeBuilder. The TypeBuilder.DefineEvent
// method will return a new EventBuilder to a client.
//
- [ClassInterface(ClassInterfaceType.None)]
- [ComDefaultInterface(typeof(_EventBuilder))]
-[System.Runtime.InteropServices.ComVisible(true)]
- public sealed class EventBuilder : _EventBuilder
+ public sealed class EventBuilder
{
// Make a private constructor so these cannot be constructed externally.
@@ -95,7 +91,6 @@ namespace System.Reflection.Emit {
// Use this function if client decides to form the custom attribute blob themselves
-[System.Runtime.InteropServices.ComVisible(true)]
public void SetCustomAttribute(ConstructorInfo con, byte[] binaryAttribute)
{
if (con == null)
diff --git a/src/mscorlib/src/System/Reflection/Emit/EventToken.cs b/src/mscorlib/src/System/Reflection/Emit/EventToken.cs
index 0642cec822..8ffdce9732 100644
--- a/src/mscorlib/src/System/Reflection/Emit/EventToken.cs
+++ b/src/mscorlib/src/System/Reflection/Emit/EventToken.cs
@@ -16,9 +16,7 @@ namespace System.Reflection.Emit {
using System;
using System.Reflection;
- using System.Security.Permissions;
[Serializable]
-[System.Runtime.InteropServices.ComVisible(true)]
public struct EventToken
{
public static readonly EventToken Empty = new EventToken();
diff --git a/src/mscorlib/src/System/Reflection/Emit/FieldBuilder.cs b/src/mscorlib/src/System/Reflection/Emit/FieldBuilder.cs
index 595d60ada0..5953b67173 100644
--- a/src/mscorlib/src/System/Reflection/Emit/FieldBuilder.cs
+++ b/src/mscorlib/src/System/Reflection/Emit/FieldBuilder.cs
@@ -10,13 +10,9 @@ namespace System.Reflection.Emit
using System;
using CultureInfo = System.Globalization.CultureInfo;
using System.Reflection;
- using System.Security.Permissions;
using System.Diagnostics.Contracts;
- [ClassInterface(ClassInterfaceType.None)]
- [ComDefaultInterface(typeof(_FieldBuilder))]
-[System.Runtime.InteropServices.ComVisible(true)]
- public sealed class FieldBuilder : FieldInfo, _FieldBuilder
+ public sealed class FieldBuilder : FieldInfo
{
#region Private Data Members
private int m_fieldTok;
@@ -71,8 +67,6 @@ namespace System.Reflection.Emit
{
ModuleBuilder.SetFieldRVAContent(m_typeBuilder.GetModuleBuilder().GetNativeHandle(), m_tkField.Token, data, size);
}
-
- internal TypeBuilder GetTypeBuilder() { return m_typeBuilder; }
#endregion
#region MemberInfo Overrides
@@ -185,20 +179,6 @@ namespace System.Reflection.Emit
TypeBuilder.SetFieldLayoutOffset(m_typeBuilder.GetModuleBuilder().GetNativeHandle(), GetToken().Token, iOffset);
}
- [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(nameof(unmanagedMarshal));
- Contract.EndContractBlock();
-
- m_typeBuilder.ThrowIfCreated();
-
- byte[] ubMarshal = unmanagedMarshal.InternalGetBytes();
-
- TypeBuilder.SetFieldMarshal(m_typeBuilder.GetModuleBuilder().GetNativeHandle(), GetToken().Token, ubMarshal, ubMarshal.Length);
- }
-
public void SetConstant(Object defaultValue)
{
m_typeBuilder.ThrowIfCreated();
@@ -207,7 +187,6 @@ namespace System.Reflection.Emit
}
-[System.Runtime.InteropServices.ComVisible(true)]
public void SetCustomAttribute(ConstructorInfo con, byte[] binaryAttribute)
{
if (con == null)
diff --git a/src/mscorlib/src/System/Reflection/Emit/FieldToken.cs b/src/mscorlib/src/System/Reflection/Emit/FieldToken.cs
index 42fd684e7c..add428f96e 100644
--- a/src/mscorlib/src/System/Reflection/Emit/FieldToken.cs
+++ b/src/mscorlib/src/System/Reflection/Emit/FieldToken.cs
@@ -16,14 +16,12 @@ namespace System.Reflection.Emit {
using System;
using System.Reflection;
- using System.Security.Permissions;
// The FieldToken class is an opaque representation of the Token returned
// by the Metadata to represent the field. FieldTokens are generated by
// Module.GetFieldToken(). There are no meaningful accessors on this class,
// but it can be passed to ILGenerator which understands it's internals.
[Serializable]
- [System.Runtime.InteropServices.ComVisible(true)]
public struct FieldToken
{
public static readonly FieldToken Empty = new FieldToken();
diff --git a/src/mscorlib/src/System/Reflection/Emit/FlowControl.cs b/src/mscorlib/src/System/Reflection/Emit/FlowControl.cs
index 31bb564cf4..9e528b2551 100644
--- a/src/mscorlib/src/System/Reflection/Emit/FlowControl.cs
+++ b/src/mscorlib/src/System/Reflection/Emit/FlowControl.cs
@@ -16,7 +16,6 @@ namespace System.Reflection.Emit {
using System;
[Serializable]
-[System.Runtime.InteropServices.ComVisible(true)]
public enum FlowControl
{
diff --git a/src/mscorlib/src/System/Reflection/Emit/GenericTypeParameterBuilder.cs b/src/mscorlib/src/System/Reflection/Emit/GenericTypeParameterBuilder.cs
index 6987ea139d..894f57d49c 100644
--- a/src/mscorlib/src/System/Reflection/Emit/GenericTypeParameterBuilder.cs
+++ b/src/mscorlib/src/System/Reflection/Emit/GenericTypeParameterBuilder.cs
@@ -13,7 +13,6 @@ namespace System.Reflection.Emit
using System.Globalization;
using System.Diagnostics.Contracts;
-[System.Runtime.InteropServices.ComVisible(true)]
public sealed class GenericTypeParameterBuilder: TypeInfo
{
public override bool IsAssignableFrom(System.Reflection.TypeInfo typeInfo){
@@ -118,7 +117,6 @@ namespace System.Reflection.Emit
protected override ConstructorInfo GetConstructorImpl(BindingFlags bindingAttr, Binder binder, CallingConventions callConvention, Type[] types, ParameterModifier[] modifiers) { throw new NotSupportedException(); }
-[System.Runtime.InteropServices.ComVisible(true)]
public override ConstructorInfo[] GetConstructors(BindingFlags bindingAttr) { throw new NotSupportedException(); }
protected override MethodInfo GetMethodImpl(String name, BindingFlags bindingAttr, Binder binder, CallingConventions callConvention, Type[] types, ParameterModifier[] modifiers) { throw new NotSupportedException(); }
@@ -147,7 +145,6 @@ namespace System.Reflection.Emit
public override MemberInfo[] GetMember(String name, MemberTypes type, BindingFlags bindingAttr) { throw new NotSupportedException(); }
-[System.Runtime.InteropServices.ComVisible(true)]
public override InterfaceMapping GetInterfaceMap(Type interfaceType) { throw new NotSupportedException(); }
public override EventInfo[] GetEvents(BindingFlags bindingAttr) { throw new NotSupportedException(); }
@@ -198,7 +195,6 @@ namespace System.Reflection.Emit
public override bool IsAssignableFrom(Type c) { throw new NotSupportedException(); }
- [System.Runtime.InteropServices.ComVisible(true)]
[Pure]
public override bool IsSubclassOf(Type c) { throw new NotSupportedException(); }
#endregion
@@ -228,7 +224,6 @@ namespace System.Reflection.Emit
m_type.SetParent(baseTypeConstraint);
}
- [System.Runtime.InteropServices.ComVisible(true)]
public void SetInterfaceConstraints(params Type[] interfaceConstraints)
{
m_type.CheckContext(interfaceConstraints);
diff --git a/src/mscorlib/src/System/Reflection/Emit/ILGenerator.cs b/src/mscorlib/src/System/Reflection/Emit/ILGenerator.cs
index ed0763bfda..2cee63ff2e 100644
--- a/src/mscorlib/src/System/Reflection/Emit/ILGenerator.cs
+++ b/src/mscorlib/src/System/Reflection/Emit/ILGenerator.cs
@@ -10,15 +10,11 @@ namespace System.Reflection.Emit
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)]
- [ComDefaultInterface(typeof(_ILGenerator))]
- [System.Runtime.InteropServices.ComVisible(true)]
- public class ILGenerator : _ILGenerator
+ public class ILGenerator
{
#region Const Members
private const int defaultSize = 16;
@@ -388,20 +384,17 @@ namespace System.Reflection.Emit
// Just a cheap insertion sort. We don't expect many exceptions (<10), where InsertionSort beats QuickSort.
// If we have more exceptions than this in real life, we should consider moving to a QuickSort.
- int least;
- __ExceptionInfo temp;
- int length = exceptions.Length;
- for (int i =0; i < length; i++)
+ for (int i = 0; i < exceptions.Length; i++)
{
- least = i;
- for (int j =i + 1; j < length; j++)
+ int least = i;
+ for (int j = i + 1; j < exceptions.Length; j++)
{
if (exceptions[least].IsInner(exceptions[j]))
{
least = j;
}
}
- temp = exceptions[i];
+ __ExceptionInfo temp = exceptions[i];
exceptions[i] = exceptions[least];
exceptions[least] = temp;
}
@@ -543,51 +536,6 @@ namespace System.Reflection.Emit
PutInteger4(modBuilder.GetSignatureToken(sig).Token);
}
- public virtual void EmitCalli(OpCode opcode, CallingConvention unmanagedCallConv, Type returnType, Type[] parameterTypes)
- {
- int stackchange = 0;
- int cParams = 0;
- int i;
- SignatureHelper sig;
-
- ModuleBuilder modBuilder = (ModuleBuilder) m_methodBuilder.Module;
-
- if (parameterTypes != null)
- {
- cParams = parameterTypes.Length;
- }
-
- sig = SignatureHelper.GetMethodSigHelper(
- modBuilder,
- unmanagedCallConv,
- returnType);
-
- if (parameterTypes != null)
- {
- for (i = 0; i < cParams; i++)
- {
- sig.AddArgument(parameterTypes[i]);
- }
- }
-
- // If there is a non-void return type, push one.
- if (returnType != typeof(void))
- stackchange++;
-
- // Pop off arguments if any.
- if (parameterTypes != null)
- stackchange -= cParams;
-
- // Pop the native function pointer.
- stackchange--;
- UpdateStackSize(OpCodes.Calli, stackchange);
-
- EnsureCapacity(7);
- Emit(OpCodes.Calli);
- RecordTokenFixup();
- PutInteger4(modBuilder.GetSignatureToken(sig).Token);
- }
-
public virtual void EmitCall(OpCode opcode, MethodInfo methodInfo, Type[] optionalParameterTypes)
{
if (methodInfo == null)
@@ -660,7 +608,6 @@ namespace System.Reflection.Emit
PutInteger4(tempVal);
}
- [System.Runtime.InteropServices.ComVisible(true)]
public virtual void Emit(OpCode opcode, ConstructorInfo con)
{
if (con == null)
@@ -1160,13 +1107,9 @@ namespace System.Reflection.Emit
private static Type GetConsoleType()
{
-#if FEATURE_LEGACYSURFACE
- return typeof(Console);
-#else
return Type.GetType(
"System.Console, System.Console, Version=4.0.0.0, Culture=neutral, PublicKeyToken=" + AssemblyRef.MicrosoftPublicKeyToken,
throwOnError: true);
-#endif
}
public virtual void EmitWriteLine(String value)
diff --git a/src/mscorlib/src/System/Reflection/Emit/ISymWrapperCore.cs b/src/mscorlib/src/System/Reflection/Emit/ISymWrapperCore.cs
index a737895829..e6f4622f0e 100644
--- a/src/mscorlib/src/System/Reflection/Emit/ISymWrapperCore.cs
+++ b/src/mscorlib/src/System/Reflection/Emit/ISymWrapperCore.cs
@@ -166,23 +166,6 @@ namespace System.Reflection.Emit
private SymWriter()
{
}
-
- //=========================================================================================
- // Public interface methods start here.
- //=========================================================================================
-
-
- //------------------------------------------------------------------------------
- // Initialize() wrapper
- //------------------------------------------------------------------------------
- void ISymbolWriter.Initialize(IntPtr emitter, String filename, bool fFullBuild)
- {
- int hr = m_vtable.Initialize(m_pWriter, emitter, filename, (IntPtr)0, fFullBuild);
- if (hr < 0)
- {
- throw Marshal.GetExceptionForHR(hr);
- }
- }
//------------------------------------------------------------------------------
// DefineDocument() wrapper
@@ -207,18 +190,6 @@ namespace System.Reflection.Emit
}
//------------------------------------------------------------------------------
- // SetUserEntryPoint() wrapper
- //------------------------------------------------------------------------------
- void ISymbolWriter.SetUserEntryPoint(SymbolToken entryMethod)
- {
- int hr = m_vtable.SetUserEntryPoint(m_pWriter, entryMethod.GetToken());
- if (hr < 0)
- {
- throw Marshal.GetExceptionForHR(hr);
- }
- }
-
- //------------------------------------------------------------------------------
// OpenMethod() wrapper
//------------------------------------------------------------------------------
void ISymbolWriter.OpenMethod(SymbolToken method)
@@ -326,18 +297,6 @@ namespace System.Reflection.Emit
throw Marshal.GetExceptionForHR(hr);
}
}
-
- //------------------------------------------------------------------------------
- // SetScopeRange() wrapper
- //------------------------------------------------------------------------------
- void ISymbolWriter.SetScopeRange(int scopeID, int startOffset, int endOffset)
- {
- int hr = m_vtable.SetScopeRange(m_pWriter, scopeID, startOffset, endOffset);
- if (hr < 0)
- {
- throw Marshal.GetExceptionForHR(hr);
- }
- }
//------------------------------------------------------------------------------
// DefineLocalVariable() wrapper
@@ -368,62 +327,7 @@ namespace System.Reflection.Emit
throw Marshal.GetExceptionForHR(hr);
}
}
-
- //------------------------------------------------------------------------------
- // DefineParameter() wrapper
- //------------------------------------------------------------------------------
- void ISymbolWriter.DefineParameter(String name,
- ParameterAttributes attributes,
- int sequence,
- SymAddressKind addrKind,
- int addr1,
- int addr2,
- int addr3)
- {
- throw new NotSupportedException(); // Intentionally not supported to match desktop CLR
- }
-
- //------------------------------------------------------------------------------
- // DefineField() wrapper
- //------------------------------------------------------------------------------
- void ISymbolWriter.DefineField(SymbolToken parent,
- String name,
- FieldAttributes attributes,
- byte[] signature,
- SymAddressKind addrKind,
- int addr1,
- int addr2,
- int addr3)
- {
- throw new NotSupportedException(); // Intentionally not supported to match desktop CLR
- }
-
- //------------------------------------------------------------------------------
- // DefineGlobalVariable() wrapper
- //------------------------------------------------------------------------------
- void ISymbolWriter.DefineGlobalVariable(String name,
- FieldAttributes attributes,
- byte[] signature,
- SymAddressKind addrKind,
- int addr1,
- int addr2,
- int addr3)
- {
- throw new NotSupportedException(); // Intentionally not supported to match desktop CLR
- }
-
- //------------------------------------------------------------------------------
- // Close() wrapper
- //------------------------------------------------------------------------------
- void ISymbolWriter.Close()
- {
- int hr = m_vtable.Close(m_pWriter);
- if (hr < 0)
- {
- throw Marshal.GetExceptionForHR(hr);
- }
- }
-
+
//------------------------------------------------------------------------------
// SetSymAttribute() wrapper
//------------------------------------------------------------------------------
@@ -437,30 +341,6 @@ namespace System.Reflection.Emit
}
//------------------------------------------------------------------------------
- // OpenNamespace() wrapper
- //------------------------------------------------------------------------------
- void ISymbolWriter.OpenNamespace(String name)
- {
- int hr = m_vtable.OpenNamespace(m_pWriter, name);
- if (hr < 0)
- {
- throw Marshal.GetExceptionForHR(hr);
- }
- }
-
- //------------------------------------------------------------------------------
- // CloseNamespace() wrapper
- //------------------------------------------------------------------------------
- void ISymbolWriter.CloseNamespace()
- {
- int hr = m_vtable.CloseNamespace(m_pWriter);
- if (hr < 0)
- {
- throw Marshal.GetExceptionForHR(hr);
- }
- }
-
- //------------------------------------------------------------------------------
// UsingNamespace() wrapper
//------------------------------------------------------------------------------
void ISymbolWriter.UsingNamespace(String name)
@@ -471,27 +351,6 @@ namespace System.Reflection.Emit
throw Marshal.GetExceptionForHR(hr);
}
}
-
- //------------------------------------------------------------------------------
- // SetMethodSourceRange() wrapper
- //------------------------------------------------------------------------------
- void ISymbolWriter.SetMethodSourceRange(ISymbolDocumentWriter startDoc,
- int startLine,
- int startColumn,
- ISymbolDocumentWriter endDoc,
- int endLine,
- int endColumn)
- {
- throw new NotSupportedException(); // Intentionally not supported to match desktop CLR
- }
-
- //------------------------------------------------------------------------------
- // SetUnderlyingWriter() wrapper.
- //------------------------------------------------------------------------------
- void ISymbolWriter.SetUnderlyingWriter(IntPtr ppUnderlyingWriter)
- {
- throw new NotSupportedException(); // Intentionally not supported on Telesto as it's a very unsafe api
- }
//------------------------------------------------------------------------------
// InternalSetUnderlyingWriter() wrapper.
diff --git a/src/mscorlib/src/System/Reflection/Emit/Label.cs b/src/mscorlib/src/System/Reflection/Emit/Label.cs
index dd248b62fe..c7b987ff10 100644
--- a/src/mscorlib/src/System/Reflection/Emit/Label.cs
+++ b/src/mscorlib/src/System/Reflection/Emit/Label.cs
@@ -16,7 +16,6 @@
namespace System.Reflection.Emit {
using System;
using System.Reflection;
- using System.Security.Permissions;
using System.Runtime.InteropServices;
// The Label class is an opaque representation of a label used by the
@@ -26,7 +25,6 @@ namespace System.Reflection.Emit {
// Labels are created by using ILGenerator.CreateLabel and their position is set
// by using ILGenerator.MarkLabel.
[Serializable]
- [ComVisible(true)]
public struct Label {
internal int m_label;
diff --git a/src/mscorlib/src/System/Reflection/Emit/LocalBuilder.cs b/src/mscorlib/src/System/Reflection/Emit/LocalBuilder.cs
index a34d5ebe5d..fe4c33160a 100644
--- a/src/mscorlib/src/System/Reflection/Emit/LocalBuilder.cs
+++ b/src/mscorlib/src/System/Reflection/Emit/LocalBuilder.cs
@@ -4,15 +4,11 @@
using System;
using System.Reflection;
-using System.Security.Permissions;
using System.Runtime.InteropServices;
namespace System.Reflection.Emit
{
- [ClassInterface(ClassInterfaceType.None)]
- [ComDefaultInterface(typeof(_LocalBuilder))]
- [System.Runtime.InteropServices.ComVisible(true)]
- public sealed class LocalBuilder : LocalVariableInfo, _LocalBuilder
+ public sealed class LocalBuilder : LocalVariableInfo
{
#region Private Data Members
private int m_localIndex;
diff --git a/src/mscorlib/src/System/Reflection/Emit/MethodBuilder.cs b/src/mscorlib/src/System/Reflection/Emit/MethodBuilder.cs
index 654e166a05..17c8ce074d 100644
--- a/src/mscorlib/src/System/Reflection/Emit/MethodBuilder.cs
+++ b/src/mscorlib/src/System/Reflection/Emit/MethodBuilder.cs
@@ -14,15 +14,11 @@ namespace System.Reflection.Emit
using System.Security;
using System.Collections;
using System.Collections.Generic;
- using System.Security.Permissions;
using System.Runtime.InteropServices;
using System.Diagnostics;
using System.Diagnostics.Contracts;
- [ClassInterface(ClassInterfaceType.None)]
- [ComDefaultInterface(typeof(_MethodBuilder))]
- [System.Runtime.InteropServices.ComVisible(true)]
- public sealed class MethodBuilder : MethodInfo, _MethodBuilder
+ public sealed class MethodBuilder : MethodInfo
{
#region Private Data Members
// Identity
@@ -67,11 +63,6 @@ namespace System.Reflection.Emit
#endregion
#region Constructor
- internal MethodBuilder(String name, MethodAttributes attributes, CallingConventions callingConvention,
- Type returnType, Type[] parameterTypes, ModuleBuilder mod, TypeBuilder type, bool bIsGlobalMethod)
- {
- Init(name, attributes, callingConvention, returnType, null, null, parameterTypes, null, null, mod, type, bIsGlobalMethod);
- }
internal MethodBuilder(String name, MethodAttributes attributes, CallingConventions callingConvention,
Type returnType, Type[] returnTypeRequiredCustomModifiers, Type[] returnTypeOptionalCustomModifiers,
@@ -371,11 +362,6 @@ namespace System.Reflection.Emit
}
}
- internal void SetToken(MethodToken token)
- {
- m_tkMethod = token;
- }
-
internal byte[] GetBody()
{
// Returns the il bytes of this method.
@@ -851,199 +837,13 @@ namespace System.Reflection.Emit
return new ParameterBuilder(this, position, attributes, strParamName);
}
- [Obsolete("An alternate API is available: Emit the MarshalAs custom attribute instead. http://go.microsoft.com/fwlink/?linkid=14202")]
- public void SetMarshal(UnmanagedMarshal unmanagedMarshal)
- {
- ThrowIfGeneric ();
-
- // set Marshal info for the return type
-
- m_containingType.ThrowIfCreated();
-
- if (m_retParam == null)
- {
- m_retParam = new ParameterBuilder(this, 0, 0, null);
- }
-
- m_retParam.SetMarshal(unmanagedMarshal);
- }
-
private List<SymCustomAttr> m_symCustomAttrs;
private struct SymCustomAttr
{
- public SymCustomAttr(String name, byte[] data)
- {
- m_name = name;
- m_data = data;
- }
public String m_name;
public byte[] m_data;
}
- public void SetSymCustomAttribute(String name, byte[] data)
- {
- // Note that this API is rarely used. Support for custom attributes in PDB files was added in
- // Whidbey and as of 8/2007 the only known user is the C# compiler. There seems to be little
- // value to this for Reflection.Emit users since they can always use metadata custom attributes.
- // Some versions of the symbol writer used in the CLR will ignore these entirely. This API has
- // been removed from the Silverlight API surface area, but we should also consider removing it
- // from future desktop product versions as well.
-
- ThrowIfGeneric ();
-
- // This is different from CustomAttribute. This is stored into the SymWriter.
- m_containingType.ThrowIfCreated();
-
- ModuleBuilder dynMod = (ModuleBuilder) m_module;
- if ( dynMod.GetSymWriter() == null)
- {
- // Cannot SetSymCustomAttribute when it is not a debug module
- throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_NotADebugModule"));
- }
-
- if (m_symCustomAttrs == null)
- m_symCustomAttrs = new List<SymCustomAttr>();
-
- m_symCustomAttrs.Add(new SymCustomAttr(name, data));
- }
-
- public void SetMethodBody(byte[] il, int maxStack, byte[] localSignature, IEnumerable<ExceptionHandler> exceptionHandlers, IEnumerable<int> tokenFixups)
- {
- if (il == null)
- {
- throw new ArgumentNullException(nameof(il), Environment.GetResourceString("ArgumentNull_Array"));
- }
- if (maxStack < 0)
- {
- throw new ArgumentOutOfRangeException(nameof(maxStack), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
- }
- Contract.EndContractBlock();
-
- if (m_bIsBaked)
- {
- throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_MethodBaked"));
- }
-
- m_containingType.ThrowIfCreated();
- ThrowIfGeneric();
-
- byte[] newLocalSignature = null;
- ExceptionHandler[] newHandlers = null;
- int[] newTokenFixups = null;
-
- byte[] newIL = (byte[])il.Clone();
-
- if (localSignature != null)
- {
- newLocalSignature = (byte[])localSignature.Clone();
- }
-
- if (exceptionHandlers != null)
- {
- newHandlers = ToArray(exceptionHandlers);
- CheckExceptionHandlerRanges(newHandlers, newIL.Length);
-
- // Note: Fixup entries for type tokens stored in ExceptionHandlers are added by the method body emitter.
- }
-
- if (tokenFixups != null)
- {
- newTokenFixups = ToArray(tokenFixups);
- int maxTokenOffset = newIL.Length - 4;
-
- for (int i = 0; i < newTokenFixups.Length; i++)
- {
- // Check that fixups are within the range of this method's IL, otherwise some random memory might get "fixed up".
- if (newTokenFixups[i] < 0 || newTokenFixups[i] > maxTokenOffset)
- {
- throw new ArgumentOutOfRangeException("tokenFixups[" + i + "]", Environment.GetResourceString("ArgumentOutOfRange_Range", 0, maxTokenOffset));
- }
- }
- }
-
- m_ubBody = newIL;
- m_localSignature = newLocalSignature;
- m_exceptions = newHandlers;
- m_mdMethodFixups = newTokenFixups;
- m_maxStack = maxStack;
-
- // discard IL generator, all information stored in it is now irrelevant
- m_ilGenerator = null;
- m_bIsBaked = true;
- }
-
- private static T[] ToArray<T>(IEnumerable<T> sequence)
- {
- T[] array = sequence as T[];
- if (array != null)
- {
- return (T[])array.Clone();
- }
-
- return new List<T>(sequence).ToArray();
- }
-
- private static void CheckExceptionHandlerRanges(ExceptionHandler[] exceptionHandlers, int maxOffset)
- {
- // Basic checks that the handler ranges are within the method body (ranges are end-exclusive).
- // Doesn't verify that the ranges are otherwise correct - it is very well possible to emit invalid IL.
- for (int i = 0; i < exceptionHandlers.Length; i++)
- {
- var handler = exceptionHandlers[i];
- if (handler.m_filterOffset > maxOffset || handler.m_tryEndOffset > maxOffset || handler.m_handlerEndOffset > maxOffset)
- {
- throw new ArgumentOutOfRangeException("exceptionHandlers[" + i + "]", Environment.GetResourceString("ArgumentOutOfRange_Range", 0, maxOffset));
- }
-
- // Type token might be 0 if the ExceptionHandler was created via a default constructor.
- // 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 (handler.Kind == ExceptionHandlingClauseOptions.Clause && handler.ExceptionTypeToken == 0)
- {
- throw new ArgumentException(Environment.GetResourceString("Argument_InvalidTypeToken", handler.ExceptionTypeToken), "exceptionHandlers[" + i + "]");
- }
- }
- }
-
- /// <summary>
- /// Obsolete.
- /// </summary>
- public void CreateMethodBody(byte[] il, int count)
- {
- ThrowIfGeneric();
-
- // Note that when user calls this function, there are a few information that client is
- // not able to supply: local signature, exception handlers, max stack size, a list of Token fixup, a list of RVA fixup
-
- if (m_bIsBaked)
- {
- throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_MethodBaked"));
- }
-
- m_containingType.ThrowIfCreated();
-
- if (il != null && (count < 0 || count > il.Length))
- {
- throw new ArgumentOutOfRangeException(nameof(count), Environment.GetResourceString("ArgumentOutOfRange_Index"));
- }
-
- if (il == null)
- {
- m_ubBody = null;
- return;
- }
-
- m_ubBody = new byte[count];
- Buffer.BlockCopy(il, 0, m_ubBody, 0, count);
-
- m_localSignature = null;
- m_exceptions = null;
- m_mdMethodFixups = null;
- m_maxStack = DefaultMaxStack;
-
- m_bIsBaked = true;
- }
-
public void SetImplementationFlags(MethodImplAttributes attributes)
{
ThrowIfGeneric ();
@@ -1113,7 +913,6 @@ namespace System.Reflection.Emit
}
-[System.Runtime.InteropServices.ComVisible(true)]
public void SetCustomAttribute(ConstructorInfo con, byte[] binaryAttribute)
{
if (con == null)
@@ -1314,8 +1113,7 @@ namespace System.Reflection.Emit
/// Describes exception handler in a method body.
/// </summary>
[StructLayout(LayoutKind.Sequential)]
- [ComVisible(false)]
- public struct ExceptionHandler : IEquatable<ExceptionHandler>
+ internal struct ExceptionHandler : IEquatable<ExceptionHandler>
{
// Keep in sync with unmanged structure.
internal readonly int m_exceptionClass;
@@ -1326,118 +1124,7 @@ namespace System.Reflection.Emit
internal readonly int m_handlerEndOffset;
internal readonly ExceptionHandlingClauseOptions m_kind;
- public int ExceptionTypeToken
- {
- get { return m_exceptionClass; }
- }
-
- public int TryOffset
- {
- get { return m_tryStartOffset; }
- }
-
- public int TryLength
- {
- get { return m_tryEndOffset - m_tryStartOffset; }
- }
-
- public int FilterOffset
- {
- get { return m_filterOffset; }
- }
-
- public int HandlerOffset
- {
- get { return m_handlerStartOffset; }
- }
-
- public int HandlerLength
- {
- get { return m_handlerEndOffset - m_handlerStartOffset; }
- }
-
- public ExceptionHandlingClauseOptions Kind
- {
- get { return m_kind; }
- }
-
- #region Constructors
-
- /// <summary>
- /// Creates a description of an exception handler.
- /// </summary>
- /// <param name="tryOffset">The offset of the first instruction protected by this handler.</param>
- /// <param name="tryLength">The number of bytes protected by this handler.</param>
- /// <param name="filterOffset">The filter code begins at the specified offset and ends at the first instruction of the handler block. Specify 0 if not applicable (this is not a filter handler).</param>
- /// <param name="handlerOffset">The offset of the first instruction of this handler.</param>
- /// <param name="handlerLength">The number of bytes of the handler.</param>
- /// <param name="kind">The kind of handler, the handler might be a catch handler, filter handler, fault handler, or finally handler.</param>
- /// <param name="exceptionTypeToken">The token of the exception type handled by this handler. Specify 0 if not applicable (this is finally handler).</param>
- /// <exception cref="ArgumentOutOfRangeException">
- /// Some of the instruction offset is negative,
- /// the end offset of specified range is less than its start offset,
- /// or <paramref name="kind"/> has an invalid value.
- /// </exception>
- public ExceptionHandler(int tryOffset, int tryLength, int filterOffset, int handlerOffset, int handlerLength,
- ExceptionHandlingClauseOptions kind, int exceptionTypeToken)
- {
- if (tryOffset < 0)
- {
- throw new ArgumentOutOfRangeException(nameof(tryOffset), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
- }
-
- if (tryLength < 0)
- {
- throw new ArgumentOutOfRangeException(nameof(tryLength), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
- }
-
- if (filterOffset < 0)
- {
- throw new ArgumentOutOfRangeException(nameof(filterOffset), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
- }
-
- if (handlerOffset < 0)
- {
- throw new ArgumentOutOfRangeException(nameof(handlerOffset), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
- }
-
- if (handlerLength < 0)
- {
- throw new ArgumentOutOfRangeException(nameof(handlerLength), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
- }
-
- if ((long)tryOffset + tryLength > Int32.MaxValue)
- {
- throw new ArgumentOutOfRangeException(nameof(tryLength), Environment.GetResourceString("ArgumentOutOfRange_Range", 0, Int32.MaxValue - tryOffset));
- }
-
- if ((long)handlerOffset + handlerLength > Int32.MaxValue)
- {
- 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), nameof(exceptionTypeToken));
- }
-
- Contract.EndContractBlock();
-
- if (!IsValidKind(kind))
- {
- throw new ArgumentOutOfRangeException(nameof(kind), Environment.GetResourceString("ArgumentOutOfRange_Enum"));
- }
-
- m_tryStartOffset = tryOffset;
- m_tryEndOffset = tryOffset + tryLength;
- m_filterOffset = filterOffset;
- m_handlerStartOffset = handlerOffset;
- m_handlerEndOffset = handlerOffset + handlerLength;
- m_kind = kind;
- m_exceptionClass = exceptionTypeToken;
- }
+#region Constructors
internal ExceptionHandler(int tryStartOffset, int tryEndOffset, int filterOffset, int handlerStartOffset, int handlerEndOffset,
int kind, int exceptionTypeToken)
diff --git a/src/mscorlib/src/System/Reflection/Emit/MethodBuilderInstantiation.cs b/src/mscorlib/src/System/Reflection/Emit/MethodBuilderInstantiation.cs
index 5b69b6e607..57ad1665c0 100644
--- a/src/mscorlib/src/System/Reflection/Emit/MethodBuilderInstantiation.cs
+++ b/src/mscorlib/src/System/Reflection/Emit/MethodBuilderInstantiation.cs
@@ -53,7 +53,6 @@ namespace System.Reflection.Emit
public override Object[] GetCustomAttributes(Type attributeType, bool inherit) { return m_method.GetCustomAttributes(attributeType, inherit); }
public override bool IsDefined(Type attributeType, bool inherit) { return m_method.IsDefined(attributeType, inherit); }
public override Module Module { get { return m_method.Module; } }
- public new Type GetType() { return base.GetType(); }
#endregion
#region MethodBase Members
diff --git a/src/mscorlib/src/System/Reflection/Emit/MethodToken.cs b/src/mscorlib/src/System/Reflection/Emit/MethodToken.cs
index cc28e173d7..76b7279f30 100644
--- a/src/mscorlib/src/System/Reflection/Emit/MethodToken.cs
+++ b/src/mscorlib/src/System/Reflection/Emit/MethodToken.cs
@@ -16,10 +16,8 @@ namespace System.Reflection.Emit {
using System;
using System.Reflection;
- using System.Security.Permissions;
[Serializable]
- [System.Runtime.InteropServices.ComVisible(true)]
public struct MethodToken
{
public static readonly MethodToken Empty = new MethodToken();
diff --git a/src/mscorlib/src/System/Reflection/Emit/ModuleBuilder.cs b/src/mscorlib/src/System/Reflection/Emit/ModuleBuilder.cs
index 6884f50b0e..30e6382550 100644
--- a/src/mscorlib/src/System/Reflection/Emit/ModuleBuilder.cs
+++ b/src/mscorlib/src/System/Reflection/Emit/ModuleBuilder.cs
@@ -15,7 +15,6 @@ namespace System.Reflection.Emit
using System.IO;
using System.Resources;
using System.Security;
- using System.Security.Permissions;
using System.Runtime.Serialization;
using System.Text;
using System.Threading;
@@ -50,10 +49,7 @@ namespace System.Reflection.Emit
}
// deliberately not [serializable]
- [ClassInterface(ClassInterfaceType.None)]
- [ComDefaultInterface(typeof(_ModuleBuilder))]
- [System.Runtime.InteropServices.ComVisible(true)]
- public class ModuleBuilder : Module, _ModuleBuilder
+ public class ModuleBuilder : Module
{
#region FCalls
@@ -248,61 +244,8 @@ namespace System.Reflection.Emit
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
- private extern static void PreSavePEFile(RuntimeModule module, int portableExecutableKind, int imageFileMachine);
-
- [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
- [SuppressUnmanagedCodeSecurity]
- private extern static void SavePEFile(RuntimeModule module, String fileName, int entryPoint, int isExe, bool isManifestFile);
-
- [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
- [SuppressUnmanagedCodeSecurity]
- private extern static void AddResource(
- RuntimeModule module, String strName,
- byte[] resBytes, int resByteCount, int tkFile, int attribute,
- int portableExecutableKind, int imageFileMachine);
-
- [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
- [SuppressUnmanagedCodeSecurity]
- private extern static void SetModuleName(RuntimeModule module, String strModuleName);
-
- [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
- [SuppressUnmanagedCodeSecurity]
internal extern static void SetFieldRVAContent(RuntimeModule module, int fdToken, byte[] data, int length);
- [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
- [SuppressUnmanagedCodeSecurity]
- private extern static void DefineNativeResourceFile(RuntimeModule module,
- String strFilename,
- int portableExecutableKind,
- int ImageFileMachine);
-
- [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
- [SuppressUnmanagedCodeSecurity]
- private extern static void DefineNativeResourceBytes(RuntimeModule module,
- byte[] pbResource, int cbResource,
- int portableExecutableKind,
- int imageFileMachine);
-
- internal void DefineNativeResource(PortableExecutableKinds portableExecutableKind, ImageFileMachine imageFileMachine)
- {
- string strResourceFileName = m_moduleData.m_strResourceFileName;
- byte[] resourceBytes = m_moduleData.m_resourceBytes;
-
- if (strResourceFileName != null)
- {
- DefineNativeResourceFile(GetNativeHandle(),
- strResourceFileName,
- (int)portableExecutableKind, (int)imageFileMachine);
- }
- else
- if (resourceBytes != null)
- {
- DefineNativeResourceBytes(GetNativeHandle(),
- resourceBytes, resourceBytes.Length,
- (int)portableExecutableKind, (int)imageFileMachine);
- }
- }
-
#endregion
#region Internal Members
@@ -404,12 +347,11 @@ namespace System.Reflection.Emit
if (parameters == null)
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidConstructorInfo"));
- int count = parameters.Length;
- Type[] parameterTypes = new Type[count];
- Type[][] requiredCustomModifiers = new Type[count][];
- Type[][] optionalCustomModifiers = new Type[count][];
+ Type[] parameterTypes = new Type[parameters.Length];
+ Type[][] requiredCustomModifiers = new Type[parameters.Length][];
+ Type[][] optionalCustomModifiers = new Type[parameters.Length][];
- for (int i = 0; i < count; i++)
+ for (int i = 0; i < parameters.Length; i++)
{
if (parameters[i] == null)
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidConstructorInfo"));
@@ -437,17 +379,6 @@ namespace System.Reflection.Emit
m_TypeBuilderDict = new Dictionary<string, Type>();
}
- // This is a method for changing module and file name of the manifest module (created by default for
- // each assembly).
- internal void ModifyModuleName(string name)
- {
- // Reset the names in the managed ModuleBuilderData
- m_moduleData.ModifyModuleName(name);
-
- // Reset the name in the underlying metadata
- ModuleBuilder.SetModuleName(GetNativeHandle(), name);
- }
-
internal void SetSymWriter(ISymbolWriter writer)
{
m_iSymWriter = writer;
@@ -603,12 +534,14 @@ namespace System.Reflection.Emit
internal SignatureHelper GetMemberRefSignature(CallingConventions call, Type returnType,
Type[] parameterTypes, IEnumerable<Type> optionalParameterTypes, int cGenericParameters)
{
- int cParams = (parameterTypes == null) ? 0 : parameterTypes.Length;
SignatureHelper sig = SignatureHelper.GetMethodSigHelper(this, call, returnType, cGenericParameters);
- for (int i = 0; i < cParams; i++)
+ if (parameterTypes != null)
{
- sig.AddArgument(parameterTypes[i]);
+ foreach (Type t in parameterTypes)
+ {
+ sig.AddArgument(t);
+ }
}
if (optionalParameterTypes != null) {
@@ -699,19 +632,16 @@ namespace System.Reflection.Emit
return typeList;
}
- [System.Runtime.InteropServices.ComVisible(true)]
public override Type GetType(String className)
{
return GetType(className, false, false);
}
- [System.Runtime.InteropServices.ComVisible(true)]
public override Type GetType(String className, bool ignoreCase)
{
return GetType(className, false, ignoreCase);
}
- [System.Runtime.InteropServices.ComVisible(true)]
public override Type GetType(String className, bool throwOnError, bool ignoreCase)
{
lock(SyncRoot)
@@ -830,11 +760,6 @@ namespace System.Reflection.Emit
fullyQualifiedName = Path.Combine(ContainingAssemblyBuilder.m_assemblyData.m_strDir, fullyQualifiedName);
fullyQualifiedName = Path.GetFullPath(fullyQualifiedName);
}
-
- if (ContainingAssemblyBuilder.m_assemblyData.m_strDir != null && fullyQualifiedName != null)
- {
- new FileIOPermission( FileIOPermissionAccess.PathDiscovery, fullyQualifiedName ).Demand();
- }
return fullyQualifiedName;
}
@@ -1009,7 +934,6 @@ namespace System.Reflection.Emit
}
}
- [System.Runtime.InteropServices.ComVisible(true)]
public TypeBuilder DefineType(String name, TypeAttributes attr, Type parent, Type[] interfaces)
{
Contract.Ensures(Contract.Result<TypeBuilder>() != null);
@@ -1060,10 +984,16 @@ namespace System.Reflection.Emit
EnumBuilder enumBuilder = DefineEnumNoLock(name, visibility, underlyingType);
// This enum is not generic, nested, and cannot have any element type.
- Debug.Assert(name == enumBuilder.FullName);
+
+ // We ought to be able to make the following assertions:
+ //
+ // Debug.Assert(name == enumBuilder.FullName);
+ // Debug.Assert(enumBuilder.m_typeBuilder == m_TypeBuilderDict[name]);
+ //
+ // but we can't because an embedded null ('\0') in the name will cause it to be truncated
+ // incorrectly. Fixing that would be a breaking change.
// Replace the TypeBuilder object in m_TypeBuilderDict with this EnumBuilder object.
- Debug.Assert(enumBuilder.m_typeBuilder == m_TypeBuilderDict[name]);
m_TypeBuilderDict[name] = enumBuilder;
return enumBuilder;
@@ -1141,47 +1071,6 @@ namespace System.Reflection.Emit
parameterTypes, requiredParameterTypeCustomModifiers, optionalParameterTypeCustomModifiers);
}
- public MethodBuilder DefinePInvokeMethod(String name, String dllName, MethodAttributes attributes,
- CallingConventions callingConvention, Type returnType, Type[] parameterTypes,
- CallingConvention nativeCallConv, CharSet nativeCharSet)
- {
- Contract.Ensures(Contract.Result<MethodBuilder>() != null);
-
- return DefinePInvokeMethod(name, dllName, name, attributes, callingConvention, returnType, parameterTypes, nativeCallConv, nativeCharSet);
- }
-
- public MethodBuilder DefinePInvokeMethod(String name, String dllName, String entryName, MethodAttributes attributes,
- CallingConventions callingConvention, Type returnType, Type[] parameterTypes, CallingConvention nativeCallConv,
- CharSet nativeCharSet)
- {
- Contract.Ensures(Contract.Result<MethodBuilder>() != null);
-
- lock(SyncRoot)
- {
- return DefinePInvokeMethodNoLock(name, dllName, entryName, attributes, callingConvention,
- returnType, parameterTypes, nativeCallConv, nativeCharSet);
- }
- }
-
- private MethodBuilder DefinePInvokeMethodNoLock(String name, String dllName, String entryName, MethodAttributes attributes,
- CallingConventions callingConvention, Type returnType, Type[] parameterTypes, CallingConvention nativeCallConv,
- CharSet nativeCharSet)
- {
- //Global methods must be static.
- if ((attributes & MethodAttributes.Static) == 0)
- {
- throw new ArgumentException(Environment.GetResourceString("Argument_GlobalFunctionHasToBeStatic"));
- }
- Contract.Ensures(Contract.Result<MethodBuilder>() != null);
- Contract.EndContractBlock();
-
- CheckContext(returnType);
- CheckContext(parameterTypes);
-
- m_moduleData.m_fHasGlobal = true;
- return m_moduleData.m_globalTypeBuilder.DefinePInvokeMethod(name, dllName, entryName, attributes, callingConvention, returnType, parameterTypes, nativeCallConv, nativeCharSet);
- }
-
public void CreateGlobalFunctions()
{
lock(SyncRoot)
@@ -1510,41 +1399,6 @@ namespace System.Reflection.Emit
return new MethodToken(mr);
}
- public MethodToken GetConstructorToken(ConstructorInfo constructor, IEnumerable<Type> optionalParameterTypes)
- {
- if (constructor == null)
- {
- throw new ArgumentNullException(nameof(constructor));
- }
-
- lock (SyncRoot)
- {
- // useMethodDef is not applicable - constructors aren't generic
- return new MethodToken(GetMethodTokenInternal(constructor, optionalParameterTypes, false));
- }
- }
-
- public MethodToken GetMethodToken(MethodInfo method, IEnumerable<Type> optionalParameterTypes)
- {
- if (method == null)
- {
- throw new ArgumentNullException(nameof(method));
- }
-
- // useMethodDef flag only affects the result if we pass in a generic method definition.
- // If the caller is looking for a token for an ldtoken/ldftn/ldvirtftn instruction and passes in a generic method definition info/builder,
- // we correclty return the MethodDef/Ref token of the generic definition that can be used with ldtoken/ldftn/ldvirtftn.
- //
- // If the caller is looking for a token for a call/callvirt/jmp instruction and passes in a generic method definition info/builder,
- // we also return the generic MethodDef/Ref token, which is indeed not acceptable for call/callvirt/jmp instruction.
- // But the caller can always instantiate the info/builder and pass it in. Then we build the right MethodSpec.
-
- lock (SyncRoot)
- {
- return new MethodToken(GetMethodTokenInternal(method, optionalParameterTypes, true));
- }
- }
-
internal int GetMethodTokenInternal(MethodBase method, IEnumerable<Type> optionalParameterTypes, bool useMethodDef)
{
int tk = 0;
@@ -1671,7 +1525,6 @@ namespace System.Reflection.Emit
return new SymbolMethod(this, token, arrayClass, methodName, callingConvention, returnType, parameterTypes);
}
- [System.Runtime.InteropServices.ComVisible(true)]
public MethodToken GetConstructorToken(ConstructorInfo con)
{
// Return a token for the ConstructorInfo relative to the Module.
@@ -1689,7 +1542,7 @@ namespace System.Reflection.Emit
private FieldToken GetFieldTokenNoLock(FieldInfo field)
{
if (field == null) {
- throw new ArgumentNullException("con");
+ throw new ArgumentNullException(nameof(field));
}
Contract.EndContractBlock();
@@ -1821,7 +1674,6 @@ namespace System.Reflection.Emit
#region Other
- [System.Runtime.InteropServices.ComVisible(true)]
public void SetCustomAttribute(ConstructorInfo con, byte[] binaryAttribute)
{
if (con == null)
@@ -1878,7 +1730,7 @@ namespace System.Reflection.Emit
// For these reasons, we should consider making this API internal in Arrowhead
// (as it is in Silverlight), and consider validating that we're within a call
// to TypeBuilder.CreateType whenever this is used.
- public ISymbolWriter GetSymWriter()
+ internal ISymbolWriter GetSymWriter()
{
return m_iSymWriter;
}
@@ -1907,81 +1759,6 @@ namespace System.Reflection.Emit
return m_iSymWriter.DefineDocument(url, language, languageVendor, documentType);
}
- public void SetUserEntryPoint(MethodInfo entryPoint)
- {
- lock(SyncRoot)
- {
- SetUserEntryPointNoLock(entryPoint);
- }
- }
-
- private void SetUserEntryPointNoLock(MethodInfo entryPoint)
- {
- // Set the user entry point. Compiler may generate startup stub before calling user main.
- // The startup stub will be the entry point. While the user "main" will be the user entry
- // point so that debugger will not step into the compiler entry point.
-
- if (entryPoint == null)
- {
- throw new ArgumentNullException(nameof(entryPoint));
- }
- Contract.EndContractBlock();
-
- if (m_iSymWriter == null)
- {
- // Cannot set entry point when it is not a debug module
- throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_NotADebugModule"));
- }
-
- if (entryPoint.DeclaringType != null)
- {
- if (!entryPoint.Module.Equals(this))
- {
- // you cannot pass in a MethodInfo that is not contained by this ModuleBuilder
- throw new InvalidOperationException(Environment.GetResourceString("Argument_NotInTheSameModuleBuilder"));
- }
- }
- else
- {
- // unfortunately this check is missing for global function passed in as RuntimeMethodInfo.
- // The problem is that Reflection does not
- // allow us to get the containing module giving a global function
- MethodBuilder mb = entryPoint as MethodBuilder;
- if (mb != null && mb.GetModuleBuilder() != this)
- {
- // you cannot pass in a MethodInfo that is not contained by this ModuleBuilder
- throw new InvalidOperationException(Environment.GetResourceString("Argument_NotInTheSameModuleBuilder"));
- }
- }
-
- // get the metadata token value and create the SymbolStore's token value class
- SymbolToken tkMethod = new SymbolToken(GetMethodTokenInternal(entryPoint).Token);
-
- // set the UserEntryPoint
- m_iSymWriter.SetUserEntryPoint(tkMethod);
- }
-
- public void SetSymCustomAttribute(String name, byte[] data)
- {
- lock(SyncRoot)
- {
- SetSymCustomAttributeNoLock(name, data);
- }
- }
-
- private void SetSymCustomAttributeNoLock(String name, byte[] data)
- {
- if (m_iSymWriter == null)
- {
- // Cannot SetSymCustomAttribute when it is not a debug module
- throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_NotADebugModule"));
- }
-
- // This API has never worked. It seems like we might want to call m_iSymWriter.SetSymAttribute,
- // but we don't have a metadata token to associate the attribute with. Instead
- // MethodBuilder.SetSymCustomAttribute could be used to associate a symbol attribute with a specific method.
- }
-
[Pure]
public bool IsTransient()
{
diff --git a/src/mscorlib/src/System/Reflection/Emit/ModuleBuilderData.cs b/src/mscorlib/src/System/Reflection/Emit/ModuleBuilderData.cs
index 96e60d9a4e..4b6f8b4efe 100644
--- a/src/mscorlib/src/System/Reflection/Emit/ModuleBuilderData.cs
+++ b/src/mscorlib/src/System/Reflection/Emit/ModuleBuilderData.cs
@@ -52,36 +52,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).
- internal virtual void ModifyModuleName(String strModuleName)
- {
- Debug.Assert(m_strModuleName == AssemblyBuilder.MANIFEST_MODULE_NAME, "Changing names for non-manifest module");
- InitNames(strModuleName, null /*strFileName*/);
- }
-
- internal int FileToken
- {
- get
- {
- // Before save, the scope of m_tkFile is the in-memory assembly manifest
- // During save, the scope of m_tkFile is the on-disk assembly manifest
- // For transient modules m_tkFile never change.
-
- // Theoretically no one should emit anything after a dynamic assembly has
- // been saved. So m_tkFile shouldn't used when m_isSaved is true.
- // But that was never completely enforced: you can still emit everything after
- // the assembly has been saved (except for public types in persistent modules).
-
- return m_tkFile;
- }
-
- set
- {
- m_tkFile = value;
- }
- }
-
internal String m_strModuleName; // scope name (can be different from file name)
internal String m_strFileName;
internal bool m_fGlobalBeenCreated;
@@ -93,8 +63,6 @@ namespace System.Reflection.Emit
private int m_tkFile;
internal bool m_isSaved;
- [NonSerialized]
- internal ResWriterData m_embeddedRes;
internal const String MULTI_BYTE_VALUE_CLASS = "$ArrayType$";
internal String m_strResourceFileName;
internal byte[] m_resourceBytes;
diff --git a/src/mscorlib/src/System/Reflection/Emit/OpCodes.cs b/src/mscorlib/src/System/Reflection/Emit/OpCodes.cs
index 345694ec80..324fad9ceb 100644
--- a/src/mscorlib/src/System/Reflection/Emit/OpCodes.cs
+++ b/src/mscorlib/src/System/Reflection/Emit/OpCodes.cs
@@ -13,7 +13,6 @@
namespace System.Reflection.Emit {
using System;
-using System.Security.Permissions;
//
// Internal enums for opcode values. Note that the value names are used to construct
@@ -250,7 +249,6 @@ internal enum OpCodeValues {
// If you add more opcodes here, modify OpCode.Name to handle them correctly
};
-[System.Runtime.InteropServices.ComVisible(true)]
public class OpCodes {
/// <summary>
@@ -1419,7 +1417,6 @@ public class OpCodes {
(1 << OpCode.StackChangeShift)
);
- [System.Runtime.InteropServices.ComVisible(true)]
public static readonly OpCode Castclass = new OpCode(OpCodeValues.Castclass,
((int)OperandType.InlineType) |
((int)FlowControl.Next << OpCode.FlowControlShift) |
diff --git a/src/mscorlib/src/System/Reflection/Emit/Opcode.cs b/src/mscorlib/src/System/Reflection/Emit/Opcode.cs
index d7bfacd568..74a9de16b6 100644
--- a/src/mscorlib/src/System/Reflection/Emit/Opcode.cs
+++ b/src/mscorlib/src/System/Reflection/Emit/Opcode.cs
@@ -5,10 +5,8 @@
namespace System.Reflection.Emit {
using System;
using System.Threading;
-using System.Security.Permissions;
using System.Diagnostics.Contracts;
-[System.Runtime.InteropServices.ComVisible(true)]
public struct OpCode
{
//
diff --git a/src/mscorlib/src/System/Reflection/Emit/OpcodeType.cs b/src/mscorlib/src/System/Reflection/Emit/OpcodeType.cs
index 3636cb7377..87dea058e5 100644
--- a/src/mscorlib/src/System/Reflection/Emit/OpcodeType.cs
+++ b/src/mscorlib/src/System/Reflection/Emit/OpcodeType.cs
@@ -17,7 +17,6 @@ namespace System.Reflection.Emit {
using System;
[Serializable]
-[System.Runtime.InteropServices.ComVisible(true)]
public enum OpCodeType
{
diff --git a/src/mscorlib/src/System/Reflection/Emit/OperandType.cs b/src/mscorlib/src/System/Reflection/Emit/OperandType.cs
index 808844a017..e972e8603d 100644
--- a/src/mscorlib/src/System/Reflection/Emit/OperandType.cs
+++ b/src/mscorlib/src/System/Reflection/Emit/OperandType.cs
@@ -17,7 +17,6 @@ namespace System.Reflection.Emit {
using System;
[Serializable]
-[System.Runtime.InteropServices.ComVisible(true)]
public enum OperandType
{
diff --git a/src/mscorlib/src/System/Reflection/Emit/PEFileKinds.cs b/src/mscorlib/src/System/Reflection/Emit/PEFileKinds.cs
index d9c9c0327c..531ff41dd7 100644
--- a/src/mscorlib/src/System/Reflection/Emit/PEFileKinds.cs
+++ b/src/mscorlib/src/System/Reflection/Emit/PEFileKinds.cs
@@ -7,7 +7,6 @@ namespace System.Reflection.Emit {
using System;
// This Enum matchs the CorFieldAttr defined in CorHdr.h
[Serializable]
- [System.Runtime.InteropServices.ComVisible(true)]
public enum PEFileKinds
{
Dll = 0x0001,
diff --git a/src/mscorlib/src/System/Reflection/Emit/ParameterBuilder.cs b/src/mscorlib/src/System/Reflection/Emit/ParameterBuilder.cs
index 7909562baa..1b3babf595 100644
--- a/src/mscorlib/src/System/Reflection/Emit/ParameterBuilder.cs
+++ b/src/mscorlib/src/System/Reflection/Emit/ParameterBuilder.cs
@@ -16,31 +16,10 @@ namespace System.Reflection.Emit {
using System.Runtime.InteropServices;
using System;
using System.Reflection;
- using System.Security.Permissions;
using System.Diagnostics.Contracts;
- [ClassInterface(ClassInterfaceType.None)]
- [ComDefaultInterface(typeof(_ParameterBuilder))]
-[System.Runtime.InteropServices.ComVisible(true)]
- public class ParameterBuilder : _ParameterBuilder
+ public class ParameterBuilder
{
- // set ParamMarshal
- [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(nameof(unmanagedMarshal));
- }
- Contract.EndContractBlock();
-
- byte [] ubMarshal = unmanagedMarshal.InternalGetBytes();
- TypeBuilder.SetFieldMarshal(
- m_methodBuilder.GetModuleBuilder().GetNativeHandle(),
- m_pdToken.Token,
- ubMarshal,
- ubMarshal.Length);
- }
// Set the default value of the parameter
public virtual void SetConstant(Object defaultValue)
@@ -54,7 +33,6 @@ namespace System.Reflection.Emit {
// Use this function if client decides to form the custom attribute blob themselves
- [System.Runtime.InteropServices.ComVisible(true)]
public void SetCustomAttribute(ConstructorInfo con, byte[] binaryAttribute)
{
if (con == null)
@@ -111,8 +89,6 @@ namespace System.Reflection.Emit {
{
return m_pdToken;
}
-
- internal int MetadataTokenInternal { get { return m_pdToken.Token; } }
public virtual String Name {
get {return m_strParamName;}
diff --git a/src/mscorlib/src/System/Reflection/Emit/ParameterToken.cs b/src/mscorlib/src/System/Reflection/Emit/ParameterToken.cs
index d65368bf0d..a4a32a51fb 100644
--- a/src/mscorlib/src/System/Reflection/Emit/ParameterToken.cs
+++ b/src/mscorlib/src/System/Reflection/Emit/ParameterToken.cs
@@ -16,22 +16,15 @@ namespace System.Reflection.Emit {
using System;
using System.Reflection;
- using System.Security.Permissions;
// The ParameterToken class is an opaque representation of the Token returned
// by the Metadata to represent the parameter.
[Serializable]
- [System.Runtime.InteropServices.ComVisible(true)]
public struct ParameterToken {
public static readonly ParameterToken Empty = new ParameterToken();
internal int m_tkParameter;
-#if false
- public ParameterToken() {
- m_tkParameter=0;
- }
-#endif
internal ParameterToken(int tkParam) {
m_tkParameter = tkParam;
diff --git a/src/mscorlib/src/System/Reflection/Emit/PropertyBuilder.cs b/src/mscorlib/src/System/Reflection/Emit/PropertyBuilder.cs
index e7442b4e02..7c4ed9dc0f 100644
--- a/src/mscorlib/src/System/Reflection/Emit/PropertyBuilder.cs
+++ b/src/mscorlib/src/System/Reflection/Emit/PropertyBuilder.cs
@@ -17,7 +17,6 @@ namespace System.Reflection.Emit {
using System;
using System.Reflection;
using CultureInfo = System.Globalization.CultureInfo;
- using System.Security.Permissions;
using System.Runtime.InteropServices;
using System.Diagnostics.Contracts;
@@ -25,10 +24,7 @@ namespace System.Reflection.Emit {
// A PropertyBuilder is always associated with a TypeBuilder. The TypeBuilder.DefineProperty
// method will return a new PropertyBuilder to a client.
//
- [ClassInterface(ClassInterfaceType.None)]
- [ComDefaultInterface(typeof(_PropertyBuilder))]
- [System.Runtime.InteropServices.ComVisible(true)]
- public sealed class PropertyBuilder : PropertyInfo, _PropertyBuilder
+ public sealed class PropertyBuilder : PropertyInfo
{
// Make a private constructor so these cannot be constructed externally.
@@ -84,14 +80,6 @@ namespace System.Reflection.Emit {
{
get {return m_prToken;}
}
-
- internal int MetadataTokenInternal
- {
- get
- {
- return m_tkProperty;
- }
- }
public override Module Module
{
@@ -135,7 +123,6 @@ namespace System.Reflection.Emit {
// Use this function if client decides to form the custom attribute blob themselves
-[System.Runtime.InteropServices.ComVisible(true)]
public void SetCustomAttribute(ConstructorInfo con, byte[] binaryAttribute)
{
if (con == null)
diff --git a/src/mscorlib/src/System/Reflection/Emit/PropertyToken.cs b/src/mscorlib/src/System/Reflection/Emit/PropertyToken.cs
index d70cad057a..72ab983bb9 100644
--- a/src/mscorlib/src/System/Reflection/Emit/PropertyToken.cs
+++ b/src/mscorlib/src/System/Reflection/Emit/PropertyToken.cs
@@ -16,10 +16,8 @@ namespace System.Reflection.Emit {
using System;
using System.Reflection;
- using System.Security.Permissions;
[Serializable]
- [System.Runtime.InteropServices.ComVisible(true)]
public struct PropertyToken {
public static readonly PropertyToken Empty = new PropertyToken();
diff --git a/src/mscorlib/src/System/Reflection/Emit/SignatureHelper.cs b/src/mscorlib/src/System/Reflection/Emit/SignatureHelper.cs
index c40035bc40..b43abcb51c 100644
--- a/src/mscorlib/src/System/Reflection/Emit/SignatureHelper.cs
+++ b/src/mscorlib/src/System/Reflection/Emit/SignatureHelper.cs
@@ -14,12 +14,8 @@ namespace System.Reflection.Emit
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
- using System.Security.Permissions;
- [ClassInterface(ClassInterfaceType.None)]
- [ComDefaultInterface(typeof(_SignatureHelper))]
-[System.Runtime.InteropServices.ComVisible(true)]
- public sealed class SignatureHelper : _SignatureHelper
+ public sealed class SignatureHelper
{
#region Consts Fields
private const int NO_SIZE_IN_SIG = -1;
@@ -186,15 +182,15 @@ namespace System.Reflection.Emit
return sigHelp;
}
- internal static SignatureHelper GetTypeSigToken(Module mod, Type type)
+ internal static SignatureHelper GetTypeSigToken(Module module, Type type)
{
- if (mod == null)
- throw new ArgumentNullException("module");
+ if (module == null)
+ throw new ArgumentNullException(nameof(module));
if (type == null)
throw new ArgumentNullException(nameof(type));
- return new SignatureHelper(mod, type);
+ return new SignatureHelper(module, type);
}
#endregion
@@ -518,36 +514,6 @@ namespace System.Reflection.Emit
}
}
-
- private void AddData(uint data)
- {
- if (m_currSig + 4 > m_signature.Length)
- {
- m_signature = ExpandArray(m_signature);
- }
-
- m_signature[m_currSig++] = (byte)((data) & 0xFF);
- m_signature[m_currSig++] = (byte)((data>>8) & 0xFF);
- m_signature[m_currSig++] = (byte)((data>>16) & 0xFF);
- m_signature[m_currSig++] = (byte)((data>>24) & 0xFF);
- }
-
- private void AddData(ulong data)
- {
- if (m_currSig + 8 > m_signature.Length)
- {
- m_signature = ExpandArray(m_signature);
- }
-
- m_signature[m_currSig++] = (byte)((data) & 0xFF);
- m_signature[m_currSig++] = (byte)((data>>8) & 0xFF);
- m_signature[m_currSig++] = (byte)((data>>16) & 0xFF);
- m_signature[m_currSig++] = (byte)((data>>24) & 0xFF);
- m_signature[m_currSig++] = (byte)((data>>32) & 0xFF);
- m_signature[m_currSig++] = (byte)((data>>40) & 0xFF);
- m_signature[m_currSig++] = (byte)((data>>48) & 0xFF);
- m_signature[m_currSig++] = (byte)((data>>56) & 0xFF);
- }
private void AddElementType(CorElementType cvt)
{
diff --git a/src/mscorlib/src/System/Reflection/Emit/SignatureToken.cs b/src/mscorlib/src/System/Reflection/Emit/SignatureToken.cs
index 0a87ac1398..5c908b89c7 100644
--- a/src/mscorlib/src/System/Reflection/Emit/SignatureToken.cs
+++ b/src/mscorlib/src/System/Reflection/Emit/SignatureToken.cs
@@ -17,9 +17,7 @@ namespace System.Reflection.Emit {
using System;
using System.Reflection;
- using System.Security.Permissions;
- [System.Runtime.InteropServices.ComVisible(true)]
public struct SignatureToken {
public static readonly SignatureToken Empty = new SignatureToken();
diff --git a/src/mscorlib/src/System/Reflection/Emit/StackBehaviour.cs b/src/mscorlib/src/System/Reflection/Emit/StackBehaviour.cs
index 2d2c35ef26..8a447d03fc 100644
--- a/src/mscorlib/src/System/Reflection/Emit/StackBehaviour.cs
+++ b/src/mscorlib/src/System/Reflection/Emit/StackBehaviour.cs
@@ -17,7 +17,6 @@ namespace System.Reflection.Emit {
using System;
[Serializable]
-[System.Runtime.InteropServices.ComVisible(true)]
public enum StackBehaviour
{
diff --git a/src/mscorlib/src/System/Reflection/Emit/StringToken.cs b/src/mscorlib/src/System/Reflection/Emit/StringToken.cs
index cb0e979a7a..852225697c 100644
--- a/src/mscorlib/src/System/Reflection/Emit/StringToken.cs
+++ b/src/mscorlib/src/System/Reflection/Emit/StringToken.cs
@@ -16,10 +16,8 @@ namespace System.Reflection.Emit {
using System;
using System.Reflection;
- using System.Security.Permissions;
[Serializable]
- [System.Runtime.InteropServices.ComVisible(true)]
public struct StringToken {
internal int m_string;
diff --git a/src/mscorlib/src/System/Reflection/Emit/SymbolType.cs b/src/mscorlib/src/System/Reflection/Emit/SymbolType.cs
index 84ece90982..205299125b 100644
--- a/src/mscorlib/src/System/Reflection/Emit/SymbolType.cs
+++ b/src/mscorlib/src/System/Reflection/Emit/SymbolType.cs
@@ -419,7 +419,6 @@ namespace System.Reflection.Emit
throw new NotSupportedException(Environment.GetResourceString("NotSupported_NonReflectedType"));
}
-[System.Runtime.InteropServices.ComVisible(true)]
public override ConstructorInfo[] GetConstructors(BindingFlags bindingAttr)
{
throw new NotSupportedException(Environment.GetResourceString("NotSupported_NonReflectedType"));
@@ -497,7 +496,6 @@ namespace System.Reflection.Emit
throw new NotSupportedException(Environment.GetResourceString("NotSupported_NonReflectedType"));
}
-[System.Runtime.InteropServices.ComVisible(true)]
public override InterfaceMapping GetInterfaceMap(Type interfaceType)
{
throw new NotSupportedException(Environment.GetResourceString("NotSupported_NonReflectedType"));
diff --git a/src/mscorlib/src/System/Reflection/Emit/TypeBuilder.cs b/src/mscorlib/src/System/Reflection/Emit/TypeBuilder.cs
index 73778d5f27..88502cb096 100644
--- a/src/mscorlib/src/System/Reflection/Emit/TypeBuilder.cs
+++ b/src/mscorlib/src/System/Reflection/Emit/TypeBuilder.cs
@@ -9,7 +9,6 @@ namespace System.Reflection.Emit {
using System;
using System.Reflection;
using System.Security;
- using System.Security.Permissions;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
using System.Collections.Generic;
@@ -21,7 +20,6 @@ namespace System.Reflection.Emit {
[Serializable]
- [System.Runtime.InteropServices.ComVisible(true)]
public enum PackingSize
{
Unspecified = 0,
@@ -35,10 +33,7 @@ namespace System.Reflection.Emit {
Size128 = 128,
}
- [ClassInterface(ClassInterfaceType.None)]
- [ComDefaultInterface(typeof(_TypeBuilder))]
- [System.Runtime.InteropServices.ComVisible(true)]
- public sealed class TypeBuilder : TypeInfo, _TypeBuilder
+ public sealed class TypeBuilder : TypeInfo
{
public override bool IsAssignableFrom(System.Reflection.TypeInfo typeInfo){
if(typeInfo==null) return false;
@@ -227,10 +222,6 @@ namespace System.Reflection.Emit {
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
- internal static extern void SetPInvokeData(RuntimeModule module, String DllName, String name, int token, int linkFlags);
-
- [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
- [SuppressUnmanagedCodeSecurity]
internal static extern int DefineProperty(RuntimeModule module, int tkParent, String name, PropertyAttributes attributes,
byte[] signature, int sigLength);
@@ -270,42 +261,10 @@ namespace System.Reflection.Emit {
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
- internal static extern void SetFieldMarshal(RuntimeModule module, int tk, byte[] ubMarshal, int ubSize);
-
- [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
- [SuppressUnmanagedCodeSecurity]
private static extern unsafe void SetConstantValue(RuntimeModule module, int tk, int corType, void* pValue);
- #endregion
-
- #region Internal\Private Static Members
- private static bool IsPublicComType(Type type)
- {
- // Internal Helper to determine if a type should be added to ComType table.
- // A top level type should be added if it is Public.
- // A nested type should be added if the top most enclosing type is Public
- // and all the enclosing types are NestedPublic
- Type enclosingType = type.DeclaringType;
- if (enclosingType != null)
- {
- if (IsPublicComType(enclosingType))
- {
- if ((type.Attributes & TypeAttributes.VisibilityMask) == TypeAttributes.NestedPublic)
- {
- return true;
- }
- }
- }
- else
- {
- if ((type.Attributes & TypeAttributes.VisibilityMask) == TypeAttributes.Public)
- {
- return true;
- }
- }
-
- return false;
- }
+#endregion
+#region Internal\Private Static Members
[Pure]
internal static bool IsTypeEqual(Type t1, Type t2)
@@ -656,127 +615,8 @@ namespace System.Reflection.Emit {
m_module.AddType(FullName, this);
}
- #endregion
-
- #region Private Members
- private MethodBuilder DefinePInvokeMethodHelper(
- String name, String dllName, String importName, MethodAttributes attributes, CallingConventions callingConvention,
- Type returnType, Type[] returnTypeRequiredCustomModifiers, Type[] returnTypeOptionalCustomModifiers,
- Type[] parameterTypes, Type[][] parameterTypeRequiredCustomModifiers, Type[][] parameterTypeOptionalCustomModifiers,
- CallingConvention nativeCallConv, CharSet nativeCharSet)
- {
- CheckContext(returnType);
- CheckContext(returnTypeRequiredCustomModifiers, returnTypeOptionalCustomModifiers, parameterTypes);
- CheckContext(parameterTypeRequiredCustomModifiers);
- CheckContext(parameterTypeOptionalCustomModifiers);
-
- AppDomain.CheckDefinePInvokeSupported();
-
- lock (SyncRoot)
- {
- return DefinePInvokeMethodHelperNoLock(name, dllName, importName, attributes, callingConvention,
- returnType, returnTypeRequiredCustomModifiers, returnTypeOptionalCustomModifiers,
- parameterTypes, parameterTypeRequiredCustomModifiers, parameterTypeOptionalCustomModifiers,
- nativeCallConv, nativeCharSet);
- }
- }
-
- private MethodBuilder DefinePInvokeMethodHelperNoLock(
- String name, String dllName, String importName, MethodAttributes attributes, CallingConventions callingConvention,
- Type returnType, Type[] returnTypeRequiredCustomModifiers, Type[] returnTypeOptionalCustomModifiers,
- Type[] parameterTypes, Type[][] parameterTypeRequiredCustomModifiers, Type[][] parameterTypeOptionalCustomModifiers,
- CallingConvention nativeCallConv, CharSet nativeCharSet)
- {
- if (name == null)
- throw new ArgumentNullException(nameof(name));
-
- if (name.Length == 0)
- throw new ArgumentException(Environment.GetResourceString("Argument_EmptyName"), nameof(name));
-
- if (dllName == null)
- throw new ArgumentNullException(nameof(dllName));
-
- if (dllName.Length == 0)
- throw new ArgumentException(Environment.GetResourceString("Argument_EmptyName"), nameof(dllName));
-
- if (importName == null)
- throw new ArgumentNullException(nameof(importName));
-
- if (importName.Length == 0)
- throw new ArgumentException(Environment.GetResourceString("Argument_EmptyName"), nameof(importName));
-
- if ((attributes & MethodAttributes.Abstract) != 0)
- throw new ArgumentException(Environment.GetResourceString("Argument_BadPInvokeMethod"));
- Contract.EndContractBlock();
-
- if ((m_iAttr & TypeAttributes.ClassSemanticsMask) == TypeAttributes.Interface)
- throw new ArgumentException(Environment.GetResourceString("Argument_BadPInvokeOnInterface"));
-
- ThrowIfCreated();
-
- attributes = attributes | MethodAttributes.PinvokeImpl;
- MethodBuilder method = new MethodBuilder(name, attributes, callingConvention,
- returnType, returnTypeRequiredCustomModifiers, returnTypeOptionalCustomModifiers,
- parameterTypes, parameterTypeRequiredCustomModifiers, parameterTypeOptionalCustomModifiers,
- m_module, this, false);
-
- //The signature grabbing code has to be up here or the signature won't be finished
- //and our equals check won't work.
- int sigLength;
- byte[] sigBytes = method.GetMethodSignature().InternalGetSignature(out sigLength);
-
- if (m_listMethods.Contains(method))
- {
- throw new ArgumentException(Environment.GetResourceString("Argument_MethodRedefined"));
- }
- m_listMethods.Add(method);
-
- MethodToken token = method.GetToken();
-
- int linkFlags = 0;
- switch(nativeCallConv)
- {
- case CallingConvention.Winapi:
- linkFlags =(int)PInvokeMap.CallConvWinapi;
- break;
- case CallingConvention.Cdecl:
- linkFlags =(int)PInvokeMap.CallConvCdecl;
- break;
- case CallingConvention.StdCall:
- linkFlags =(int)PInvokeMap.CallConvStdcall;
- break;
- case CallingConvention.ThisCall:
- linkFlags =(int)PInvokeMap.CallConvThiscall;
- break;
- case CallingConvention.FastCall:
- linkFlags =(int)PInvokeMap.CallConvFastcall;
- break;
- }
- switch(nativeCharSet)
- {
- case CharSet.None:
- linkFlags |=(int)PInvokeMap.CharSetNotSpec;
- break;
- case CharSet.Ansi:
- linkFlags |=(int)PInvokeMap.CharSetAnsi;
- break;
- case CharSet.Unicode:
- linkFlags |=(int)PInvokeMap.CharSetUnicode;
- break;
- case CharSet.Auto:
- linkFlags |=(int)PInvokeMap.CharSetAuto;
- break;
- }
-
- SetPInvokeData(m_module.GetNativeHandle(),
- dllName,
- importName,
- token.Token,
- linkFlags);
- method.SetToken(token);
-
- return method;
- }
+#endregion
+#region Private Members
private FieldBuilder DefineDataHelper(String name, byte[] data, int size, FieldAttributes attributes)
{
@@ -1050,7 +890,6 @@ namespace System.Reflection.Emit {
return m_bakedRuntimeType.GetConstructor(bindingAttr, binder, callConvention, types, modifiers);
}
- [System.Runtime.InteropServices.ComVisible(true)]
public override ConstructorInfo[] GetConstructors(BindingFlags bindingAttr)
{
if (!IsCreated())
@@ -1188,7 +1027,6 @@ namespace System.Reflection.Emit {
return m_bakedRuntimeType.GetMember(name, type, bindingAttr);
}
- [System.Runtime.InteropServices.ComVisible(true)]
public override InterfaceMapping GetInterfaceMap(Type interfaceType)
{
if (!IsCreated())
@@ -1319,7 +1157,6 @@ namespace System.Reflection.Emit {
get { return false; }
}
- [System.Runtime.InteropServices.ComVisible(true)]
[Pure]
public override bool IsSubclassOf(Type c)
{
@@ -1642,7 +1479,6 @@ namespace System.Reflection.Emit {
#endregion
#region Define Constructor
- [System.Runtime.InteropServices.ComVisible(true)]
public ConstructorBuilder DefineTypeInitializer()
{
lock(SyncRoot)
@@ -1664,7 +1500,6 @@ namespace System.Reflection.Emit {
return constBuilder;
}
- [System.Runtime.InteropServices.ComVisible(true)]
public ConstructorBuilder DefineDefaultConstructor(MethodAttributes attributes)
{
if ((m_iAttr & TypeAttributes.Interface) == TypeAttributes.Interface)
@@ -1732,13 +1567,11 @@ namespace System.Reflection.Emit {
return constBuilder;
}
- [System.Runtime.InteropServices.ComVisible(true)]
public ConstructorBuilder DefineConstructor(MethodAttributes attributes, CallingConventions callingConvention, Type[] parameterTypes)
{
return DefineConstructor(attributes, callingConvention, parameterTypes, null, null);
}
- [System.Runtime.InteropServices.ComVisible(true)]
public ConstructorBuilder DefineConstructor(MethodAttributes attributes, CallingConventions callingConvention,
Type[] parameterTypes, Type[][] requiredCustomModifiers, Type[][] optionalCustomModifiers)
{
@@ -1786,41 +1619,6 @@ namespace System.Reflection.Emit {
#endregion
- #region Define PInvoke
- public MethodBuilder DefinePInvokeMethod(String name, String dllName, MethodAttributes attributes,
- CallingConventions callingConvention, Type returnType, Type[] parameterTypes,
- CallingConvention nativeCallConv, CharSet nativeCharSet)
- {
- MethodBuilder method = DefinePInvokeMethodHelper(
- name, dllName, name, attributes, callingConvention, returnType, null, null,
- parameterTypes, null, null, nativeCallConv, nativeCharSet);
- return method;
- }
-
- public MethodBuilder DefinePInvokeMethod(String name, String dllName, String entryName, MethodAttributes attributes,
- CallingConventions callingConvention, Type returnType, Type[] parameterTypes,
- CallingConvention nativeCallConv, CharSet nativeCharSet)
- {
- MethodBuilder method = DefinePInvokeMethodHelper(
- name, dllName, entryName, attributes, callingConvention, returnType, null, null,
- parameterTypes, null, null, nativeCallConv, nativeCharSet);
- return method;
- }
-
- public MethodBuilder DefinePInvokeMethod(String name, String dllName, String entryName, MethodAttributes attributes,
- CallingConventions callingConvention,
- Type returnType, Type[] returnTypeRequiredCustomModifiers, Type[] returnTypeOptionalCustomModifiers,
- Type[] parameterTypes, Type[][] parameterTypeRequiredCustomModifiers, Type[][] parameterTypeOptionalCustomModifiers,
- CallingConvention nativeCallConv, CharSet nativeCharSet)
- {
- MethodBuilder method = DefinePInvokeMethodHelper(
- name, dllName, entryName, attributes, callingConvention, returnType, returnTypeRequiredCustomModifiers, returnTypeOptionalCustomModifiers,
- parameterTypes, parameterTypeRequiredCustomModifiers, parameterTypeOptionalCustomModifiers, nativeCallConv, nativeCharSet);
- return method;
- }
-
- #endregion
-
#region Define Nested Type
public TypeBuilder DefineNestedType(String name)
{
@@ -1830,7 +1628,6 @@ namespace System.Reflection.Emit {
}
}
- [System.Runtime.InteropServices.ComVisible(true)]
public TypeBuilder DefineNestedType(String name, TypeAttributes attr, Type parent, Type[] interfaces)
{
lock(SyncRoot)
@@ -2343,7 +2140,6 @@ namespace System.Reflection.Emit {
}
}
- [System.Runtime.InteropServices.ComVisible(true)]
public void AddInterfaceImplementation(Type interfaceType)
{
if (interfaceType == null)
@@ -2374,7 +2170,6 @@ public TypeToken TypeToken
}
- [System.Runtime.InteropServices.ComVisible(true)]
public void SetCustomAttribute(ConstructorInfo con, byte[] binaryAttribute)
{
if (con == null)
diff --git a/src/mscorlib/src/System/Reflection/Emit/TypeBuilderInstantiation.cs b/src/mscorlib/src/System/Reflection/Emit/TypeBuilderInstantiation.cs
index 3bae585953..da5a56ba28 100644
--- a/src/mscorlib/src/System/Reflection/Emit/TypeBuilderInstantiation.cs
+++ b/src/mscorlib/src/System/Reflection/Emit/TypeBuilderInstantiation.cs
@@ -168,7 +168,6 @@ namespace System.Reflection.Emit
}
protected override ConstructorInfo GetConstructorImpl(BindingFlags bindingAttr, Binder binder, CallingConventions callConvention, Type[] types, ParameterModifier[] modifiers) { throw new NotSupportedException(); }
- [System.Runtime.InteropServices.ComVisible(true)]
public override ConstructorInfo[] GetConstructors(BindingFlags bindingAttr) { throw new NotSupportedException(); }
protected override MethodInfo GetMethodImpl(String name, BindingFlags bindingAttr, Binder binder, CallingConventions callConvention, Type[] types, ParameterModifier[] modifiers) { throw new NotSupportedException(); }
public override MethodInfo[] GetMethods(BindingFlags bindingAttr) { throw new NotSupportedException(); }
@@ -184,7 +183,6 @@ namespace System.Reflection.Emit
public override Type GetNestedType(String name, BindingFlags bindingAttr) { throw new NotSupportedException(); }
public override MemberInfo[] GetMember(String name, MemberTypes type, BindingFlags bindingAttr) { throw new NotSupportedException(); }
- [System.Runtime.InteropServices.ComVisible(true)]
public override InterfaceMapping GetInterfaceMap(Type interfaceType) { throw new NotSupportedException(); }
public override EventInfo[] GetEvents(BindingFlags bindingAttr) { throw new NotSupportedException(); }
public override MemberInfo[] GetMembers(BindingFlags bindingAttr) { throw new NotSupportedException(); }
@@ -222,7 +220,6 @@ namespace System.Reflection.Emit
public override Type MakeGenericType(params Type[] inst) { throw new InvalidOperationException(Environment.GetResourceString("Arg_NotGenericTypeDefinition")); }
public override bool IsAssignableFrom(Type c) { throw new NotSupportedException(); }
- [System.Runtime.InteropServices.ComVisible(true)]
[Pure]
public override bool IsSubclassOf(Type c)
{
diff --git a/src/mscorlib/src/System/Reflection/Emit/TypeToken.cs b/src/mscorlib/src/System/Reflection/Emit/TypeToken.cs
index 228755641c..4fa851c529 100644
--- a/src/mscorlib/src/System/Reflection/Emit/TypeToken.cs
+++ b/src/mscorlib/src/System/Reflection/Emit/TypeToken.cs
@@ -17,21 +17,14 @@ namespace System.Reflection.Emit {
using System;
using System.Reflection;
using System.Threading;
- using System.Security.Permissions;
[Serializable]
- [System.Runtime.InteropServices.ComVisible(true)]
public struct TypeToken {
public static readonly TypeToken Empty = new TypeToken();
internal int m_class;
-#if false
- public TypeToken() {
- m_class=0;
- }
-#endif
internal TypeToken(int str) {
m_class=str;
diff --git a/src/mscorlib/src/System/Reflection/Emit/UnmanagedMarshal.cs b/src/mscorlib/src/System/Reflection/Emit/UnmanagedMarshal.cs
deleted file mode 100644
index 28e95e2456..0000000000
--- a/src/mscorlib/src/System/Reflection/Emit/UnmanagedMarshal.cs
+++ /dev/null
@@ -1,183 +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.Reflection.Emit
-{
- using System.Runtime.InteropServices;
- using System;
- using System.Security.Permissions;
-
- // This class is describing the fieldmarshal.
- [Serializable]
- [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
- {
- /******************************
-[System.Runtime.InteropServices.ComVisible(true)]
- * public static constructors. You can only construct
- * UnmanagedMarshal using these static constructors.
- ******************************/
- public static UnmanagedMarshal DefineUnmanagedMarshal(UnmanagedType unmanagedType)
- {
- if (unmanagedType == UnmanagedType.ByValTStr ||
- unmanagedType == UnmanagedType.SafeArray ||
- unmanagedType == UnmanagedType.CustomMarshaler ||
- unmanagedType == UnmanagedType.ByValArray ||
- unmanagedType == UnmanagedType.LPArray)
- {
- // not a simple native marshal
- throw new ArgumentException(Environment.GetResourceString("Argument_NotASimpleNativeType"));
- }
- return new UnmanagedMarshal(unmanagedType, Guid.Empty, 0, (UnmanagedType) 0);
- }
- public static UnmanagedMarshal DefineByValTStr(int elemCount)
- {
- return new UnmanagedMarshal(UnmanagedType.ByValTStr, Guid.Empty, elemCount, (UnmanagedType) 0);
- }
-
- public static UnmanagedMarshal DefineSafeArray(UnmanagedType elemType)
- {
- return new UnmanagedMarshal(UnmanagedType.SafeArray, Guid.Empty, 0, elemType);
- }
-
- public static UnmanagedMarshal DefineByValArray(int elemCount)
- {
- return new UnmanagedMarshal(UnmanagedType.ByValArray, Guid.Empty, elemCount, (UnmanagedType) 0);
- }
-
- public static UnmanagedMarshal DefineLPArray(UnmanagedType elemType)
- {
- return new UnmanagedMarshal(UnmanagedType.LPArray, Guid.Empty, 0, elemType);
- }
-
-
-
-
-
-
- // accessor function for the native type
- public UnmanagedType GetUnmanagedType
- {
- get { return m_unmanagedType; }
- }
-
- public Guid IIDGuid
- {
- get
- {
- if (m_unmanagedType == UnmanagedType.CustomMarshaler)
- return m_guid;
-
- // throw exception here. There is Guid only if CustomMarshaler
- throw new ArgumentException(Environment.GetResourceString("Argument_NotACustomMarshaler"));
- }
- }
- public int ElementCount
- {
- get
- {
- if (m_unmanagedType != UnmanagedType.ByValArray &&
- m_unmanagedType != UnmanagedType.ByValTStr)
- {
- // throw exception here. There is NumElement only if NativeTypeFixedArray
- throw new ArgumentException(Environment.GetResourceString("Argument_NoUnmanagedElementCount"));
- }
- return m_numElem;
- }
- }
- public UnmanagedType BaseType
- {
- get
- {
- if (m_unmanagedType != UnmanagedType.LPArray && m_unmanagedType != UnmanagedType.SafeArray)
- {
- // throw exception here. There is NestedUnmanagedType only if LPArray or SafeArray
- throw new ArgumentException(Environment.GetResourceString("Argument_NoNestedMarshal"));
- }
- return m_baseType;
- }
- }
-
- private UnmanagedMarshal(UnmanagedType unmanagedType, Guid guid, int numElem, UnmanagedType type)
- {
- m_unmanagedType = unmanagedType;
- m_guid = guid;
- m_numElem = numElem;
- m_baseType = type;
- }
-
- /************************
- *
- * Data member
- *
- *************************/
- internal UnmanagedType m_unmanagedType;
- internal Guid m_guid;
- internal int m_numElem;
- internal UnmanagedType m_baseType;
-
-
- /************************
- * this function return the byte representation of the marshal info.
- *************************/
- internal byte[] InternalGetBytes()
- {
- byte[] buf;
- if (m_unmanagedType == UnmanagedType.SafeArray || m_unmanagedType == UnmanagedType.LPArray)
- {
-
- // syntax for NativeTypeSafeArray is
- // <SafeArray | LPArray> <base type>
- //
- int cBuf = 2;
- buf = new byte[cBuf];
- buf[0] = (byte) (m_unmanagedType);
- buf[1] = (byte) (m_baseType);
- return buf;
- }
- else
- if (m_unmanagedType == UnmanagedType.ByValArray ||
- m_unmanagedType == UnmanagedType.ByValTStr)
- {
- // <ByValArray | ByValTStr> <encoded integer>
- //
- int cBuf;
- int iBuf = 0;
-
- if (m_numElem <= 0x7f)
- cBuf = 1;
- else if (m_numElem <= 0x3FFF)
- cBuf = 2;
- else
- cBuf = 4;
-
- // the total buffer size is the one byte + encoded integer size
- cBuf = cBuf + 1;
- buf = new byte[cBuf];
-
-
- buf[iBuf++] = (byte) (m_unmanagedType);
- if (m_numElem <= 0x7F)
- {
- buf[iBuf++] = (byte)(m_numElem & 0xFF);
- } else if (m_numElem <= 0x3FFF)
- {
- buf[iBuf++] = (byte)((m_numElem >> 8) | 0x80);
- buf[iBuf++] = (byte)(m_numElem & 0xFF);
- } else if (m_numElem <= 0x1FFFFFFF)
- {
- buf[iBuf++] = (byte)((m_numElem >> 24) | 0xC0);
- buf[iBuf++] = (byte)((m_numElem >> 16) & 0xFF);
- buf[iBuf++] = (byte)((m_numElem >> 8) & 0xFF);
- buf[iBuf++] = (byte)((m_numElem) & 0xFF);
- }
- return buf;
- }
- buf = new byte[1];
- buf[0] = (byte) (m_unmanagedType);
- return buf;
- }
- }
-}
diff --git a/src/mscorlib/src/System/Reflection/Emit/XXXOnTypeBuilderInstantiation.cs b/src/mscorlib/src/System/Reflection/Emit/XXXOnTypeBuilderInstantiation.cs
index aaaffc0df6..ca0faf31ca 100644
--- a/src/mscorlib/src/System/Reflection/Emit/XXXOnTypeBuilderInstantiation.cs
+++ b/src/mscorlib/src/System/Reflection/Emit/XXXOnTypeBuilderInstantiation.cs
@@ -51,23 +51,7 @@ namespace System.Reflection.Emit
public override Object[] GetCustomAttributes(bool inherit) { return m_method.GetCustomAttributes(inherit); }
public override Object[] GetCustomAttributes(Type attributeType, bool inherit) { return m_method.GetCustomAttributes(attributeType, inherit); }
public override bool IsDefined(Type attributeType, bool inherit) { return m_method.IsDefined(attributeType, inherit); }
- internal int MetadataTokenInternal
- {
- get
- {
- MethodBuilder mb = m_method as MethodBuilder;
-
- if (mb != null)
- return mb.MetadataTokenInternal;
- else
- {
- Debug.Assert(m_method is RuntimeMethodInfo);
- return m_method.MetadataToken;
- }
- }
- }
public override Module Module { get { return m_method.Module; } }
- public new Type GetType() { return base.GetType(); }
#endregion
#region MethodBase Members
@@ -164,7 +148,6 @@ namespace System.Reflection.Emit
}
}
public override Module Module { get { return m_ctor.Module; } }
- public new Type GetType() { return base.GetType(); }
#endregion
#region MethodBase Members
@@ -265,7 +248,6 @@ namespace System.Reflection.Emit
}
}
public override Module Module { get { return m_field.Module; } }
- public new Type GetType() { return base.GetType(); }
#endregion
#region Public Abstract\Virtual Members
diff --git a/src/mscorlib/src/System/Reflection/EventAttributes.cs b/src/mscorlib/src/System/Reflection/EventAttributes.cs
index c0285652ff..4cc08f62d3 100644
--- a/src/mscorlib/src/System/Reflection/EventAttributes.cs
+++ b/src/mscorlib/src/System/Reflection/EventAttributes.cs
@@ -16,7 +16,6 @@ namespace System.Reflection {
using System;
[Serializable]
[Flags]
- [System.Runtime.InteropServices.ComVisible(true)]
public enum EventAttributes {
None = 0x0000,
diff --git a/src/mscorlib/src/System/Reflection/EventInfo.cs b/src/mscorlib/src/System/Reflection/EventInfo.cs
index 0eabb9d03a..9b529c2960 100644
--- a/src/mscorlib/src/System/Reflection/EventInfo.cs
+++ b/src/mscorlib/src/System/Reflection/EventInfo.cs
@@ -13,14 +13,10 @@ namespace System.Reflection
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
using System.Runtime.ConstrainedExecution;
- using System.Security.Permissions;
using RuntimeTypeCache = System.RuntimeType.RuntimeTypeCache;
[Serializable]
- [ClassInterface(ClassInterfaceType.None)]
- [ComDefaultInterface(typeof(_EventInfo))]
- [System.Runtime.InteropServices.ComVisible(true)]
- public abstract class EventInfo : MemberInfo, _EventInfo
+ public abstract class EventInfo : MemberInfo
{
#region Constructor
protected EventInfo() { }
@@ -236,7 +232,6 @@ namespace System.Reflection
#endregion
#region Internal Members
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
internal override bool CacheEquals(object o)
{
RuntimeEventInfo m = o as RuntimeEventInfo;
diff --git a/src/mscorlib/src/System/Reflection/FieldAttributes.cs b/src/mscorlib/src/System/Reflection/FieldAttributes.cs
index 48c90a1a38..e49a0a45b1 100644
--- a/src/mscorlib/src/System/Reflection/FieldAttributes.cs
+++ b/src/mscorlib/src/System/Reflection/FieldAttributes.cs
@@ -8,7 +8,6 @@ namespace System.Reflection
// This Enum matchs the CorFieldAttr defined in CorHdr.h
[Serializable]
[Flags()]
- [System.Runtime.InteropServices.ComVisible(true)]
public enum FieldAttributes
{
// member access mask - Use this mask to retrieve accessibility information.
diff --git a/src/mscorlib/src/System/Reflection/FieldInfo.cs b/src/mscorlib/src/System/Reflection/FieldInfo.cs
index e61207a686..7b6517c2bb 100644
--- a/src/mscorlib/src/System/Reflection/FieldInfo.cs
+++ b/src/mscorlib/src/System/Reflection/FieldInfo.cs
@@ -16,15 +16,11 @@ namespace System.Reflection
using System.Runtime.ConstrainedExecution;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
- using System.Security.Permissions;
using System.Threading;
using RuntimeTypeCache = System.RuntimeType.RuntimeTypeCache;
[Serializable]
- [ClassInterface(ClassInterfaceType.None)]
- [ComDefaultInterface(typeof(_FieldInfo))]
- [System.Runtime.InteropServices.ComVisible(true)]
- public abstract class FieldInfo : MemberInfo, _FieldInfo
+ public abstract class FieldInfo : MemberInfo
{
#region Static Members
public static FieldInfo GetFieldFromHandle(RuntimeFieldHandle handle)
@@ -43,7 +39,6 @@ namespace System.Reflection
return f;
}
- [System.Runtime.InteropServices.ComVisible(false)]
public static FieldInfo GetFieldFromHandle(RuntimeFieldHandle handle, RuntimeTypeHandle declaringType)
{
if (handle.IsNullHandle())
@@ -454,7 +449,6 @@ namespace System.Reflection
}
}
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
internal override bool CacheEquals(object o)
{
RtFieldInfo m = o as RtFieldInfo;
@@ -757,7 +751,6 @@ namespace System.Reflection
#endregion
#region Internal Members
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
internal override bool CacheEquals(object o)
{
MdFieldInfo m = o as MdFieldInfo;
diff --git a/src/mscorlib/src/System/Reflection/ICustomAttributeProvider.cs b/src/mscorlib/src/System/Reflection/ICustomAttributeProvider.cs
index 1fd361c889..faea91a81e 100644
--- a/src/mscorlib/src/System/Reflection/ICustomAttributeProvider.cs
+++ b/src/mscorlib/src/System/Reflection/ICustomAttributeProvider.cs
@@ -15,7 +15,6 @@ namespace System.Reflection {
using System;
// Interface does not need to be marked with the serializable attribute
-[System.Runtime.InteropServices.ComVisible(true)]
public interface ICustomAttributeProvider
{
diff --git a/src/mscorlib/src/System/Reflection/IReflect.cs b/src/mscorlib/src/System/Reflection/IReflect.cs
index 92ce3412fc..1c3c57613b 100644
--- a/src/mscorlib/src/System/Reflection/IReflect.cs
+++ b/src/mscorlib/src/System/Reflection/IReflect.cs
@@ -20,7 +20,6 @@ namespace System.Reflection {
// Interface does not need to be marked with the serializable attribute
[Guid("AFBF15E5-C37C-11d2-B88E-00A0C9B471B8")]
-[System.Runtime.InteropServices.ComVisible(true)]
public interface IReflect
{
// Return the requested method if it is implemented by the Reflection object. The
diff --git a/src/mscorlib/src/System/Reflection/InterfaceMapping.cs b/src/mscorlib/src/System/Reflection/InterfaceMapping.cs
index 488ef4484d..bf994f7b47 100644
--- a/src/mscorlib/src/System/Reflection/InterfaceMapping.cs
+++ b/src/mscorlib/src/System/Reflection/InterfaceMapping.cs
@@ -13,15 +13,10 @@
namespace System.Reflection {
using System;
-[System.Runtime.InteropServices.ComVisible(true)]
public struct InterfaceMapping {
-[System.Runtime.InteropServices.ComVisible(true)]
public Type TargetType; // The type implementing the interface
-[System.Runtime.InteropServices.ComVisible(true)]
public Type InterfaceType; // The type representing the interface
-[System.Runtime.InteropServices.ComVisible(true)]
public MethodInfo[] TargetMethods; // The methods implementing the interface
-[System.Runtime.InteropServices.ComVisible(true)]
public MethodInfo[] InterfaceMethods; // The methods defined on the interface
}
}
diff --git a/src/mscorlib/src/System/Reflection/InvalidFilterCriteriaException.cs b/src/mscorlib/src/System/Reflection/InvalidFilterCriteriaException.cs
index fa95e37ad5..8b8c06d9cf 100644
--- a/src/mscorlib/src/System/Reflection/InvalidFilterCriteriaException.cs
+++ b/src/mscorlib/src/System/Reflection/InvalidFilterCriteriaException.cs
@@ -18,7 +18,6 @@ namespace System.Reflection {
using System.Runtime.Serialization;
using ApplicationException = System.ApplicationException;
[Serializable]
- [System.Runtime.InteropServices.ComVisible(true)]
public class InvalidFilterCriteriaException : ApplicationException {
public InvalidFilterCriteriaException()
: base(Environment.GetResourceString("Arg_InvalidFilterCriteriaException")) {
diff --git a/src/mscorlib/src/System/Reflection/ManifestResourceInfo.cs b/src/mscorlib/src/System/Reflection/ManifestResourceInfo.cs
index a53d32abdb..91c7ceb2ea 100644
--- a/src/mscorlib/src/System/Reflection/ManifestResourceInfo.cs
+++ b/src/mscorlib/src/System/Reflection/ManifestResourceInfo.cs
@@ -16,7 +16,6 @@
namespace System.Reflection {
using System;
-[System.Runtime.InteropServices.ComVisible(true)]
public class ManifestResourceInfo {
private Assembly _containingAssembly;
private String _containingFileName;
@@ -57,7 +56,6 @@ namespace System.Reflection {
// Linked means not Embedded.
[Serializable]
[Flags]
-[System.Runtime.InteropServices.ComVisible(true)]
public enum ResourceLocation
{
Embedded = 0x1,
diff --git a/src/mscorlib/src/System/Reflection/MdImport.cs b/src/mscorlib/src/System/Reflection/MdImport.cs
index bbdf948f99..b1d9c5eae8 100644
--- a/src/mscorlib/src/System/Reflection/MdImport.cs
+++ b/src/mscorlib/src/System/Reflection/MdImport.cs
@@ -9,7 +9,6 @@ using System.Reflection;
using System.Globalization;
using System.Threading;
using System.Diagnostics;
-using System.Security.Permissions;
using System.Collections;
using System.Runtime.CompilerServices;
using System.Security;
@@ -408,7 +407,7 @@ namespace System.Reflection
return null;
char[] c = new char[length];
- for (int i = 0; i < length; i ++)
+ for (int i = 0; i < c.Length; i ++)
{
#if ALIGN_ACCESS
c[i] = (char)Marshal.ReadInt16( (IntPtr) (((char*)name) + i) );
diff --git a/src/mscorlib/src/System/Reflection/MemberFilter.cs b/src/mscorlib/src/System/Reflection/MemberFilter.cs
index b476409d5d..56fc9c0804 100644
--- a/src/mscorlib/src/System/Reflection/MemberFilter.cs
+++ b/src/mscorlib/src/System/Reflection/MemberFilter.cs
@@ -14,6 +14,5 @@ namespace System.Reflection {
// Define the delegate
[Serializable]
- [System.Runtime.InteropServices.ComVisible(true)]
public delegate bool MemberFilter(MemberInfo m, Object filterCriteria);
}
diff --git a/src/mscorlib/src/System/Reflection/MemberInfo.cs b/src/mscorlib/src/System/Reflection/MemberInfo.cs
index 96a89ad37b..5ecbfe06a1 100644
--- a/src/mscorlib/src/System/Reflection/MemberInfo.cs
+++ b/src/mscorlib/src/System/Reflection/MemberInfo.cs
@@ -11,13 +11,9 @@ namespace System.Reflection
using System.Diagnostics.Contracts;
using System.Runtime;
using System.Runtime.InteropServices;
- using System.Security.Permissions;
[Serializable]
- [ClassInterface(ClassInterfaceType.None)]
- [ComDefaultInterface(typeof(_MemberInfo))]
- [System.Runtime.InteropServices.ComVisible(true)]
- public abstract class MemberInfo : ICustomAttributeProvider, _MemberInfo
+ public abstract class MemberInfo : ICustomAttributeProvider
{
#region Constructor
protected MemberInfo() { }
diff --git a/src/mscorlib/src/System/Reflection/MemberTypes.cs b/src/mscorlib/src/System/Reflection/MemberTypes.cs
index 352a80244e..95c41022f1 100644
--- a/src/mscorlib/src/System/Reflection/MemberTypes.cs
+++ b/src/mscorlib/src/System/Reflection/MemberTypes.cs
@@ -17,7 +17,6 @@ namespace System.Reflection {
// This Enum matchs the CorTypeAttr defined in CorHdr.h
[Serializable]
[Flags()]
- [System.Runtime.InteropServices.ComVisible(true)]
public enum MemberTypes
{
// The following are the known classes which extend MemberInfo
diff --git a/src/mscorlib/src/System/Reflection/MethodAttributes.cs b/src/mscorlib/src/System/Reflection/MethodAttributes.cs
index 92b637b9c0..7e4391cccd 100644
--- a/src/mscorlib/src/System/Reflection/MethodAttributes.cs
+++ b/src/mscorlib/src/System/Reflection/MethodAttributes.cs
@@ -10,7 +10,6 @@ namespace System.Reflection
using System;
[Serializable]
[Flags]
- [System.Runtime.InteropServices.ComVisible(true)]
public enum MethodAttributes
{
// NOTE: This Enum matchs the CorMethodAttr defined in CorHdr.h
diff --git a/src/mscorlib/src/System/Reflection/MethodBase.cs b/src/mscorlib/src/System/Reflection/MethodBase.cs
index 644a1ac0b0..3109821ac9 100644
--- a/src/mscorlib/src/System/Reflection/MethodBase.cs
+++ b/src/mscorlib/src/System/Reflection/MethodBase.cs
@@ -11,7 +11,6 @@ namespace System.Reflection
using System.Globalization;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
- using System.Security.Permissions;
using System.Text;
using System.Threading;
@@ -48,10 +47,7 @@ namespace System.Reflection
}
[Serializable]
- [ClassInterface(ClassInterfaceType.None)]
- [ComDefaultInterface(typeof(_MethodBase))]
- [System.Runtime.InteropServices.ComVisible(true)]
- public abstract class MethodBase : MemberInfo, _MethodBase
+ public abstract class MethodBase : MemberInfo
{
#region Static Members
public static MethodBase GetMethodFromHandle(RuntimeMethodHandle handle)
@@ -70,7 +66,6 @@ namespace System.Reflection
return m;
}
- [System.Runtime.InteropServices.ComVisible(false)]
public static MethodBase GetMethodFromHandle(RuntimeMethodHandle handle, RuntimeTypeHandle declaringType)
{
if (handle.IsNullHandle())
@@ -131,20 +126,6 @@ namespace System.Reflection
private IntPtr GetMethodDesc() { return MethodHandle.Value; }
#if FEATURE_APPX
-
- // The C# dynamic and VB late bound binders need to call this API. Since we don't have time to make this
- // public in Dev11, the C# and VB binders currently call this through a delegate.
- // When we make this API public (hopefully) in Dev12 we need to change the C# and VB binders to call this
- // probably statically. The code is located in:
- // C#: ndp\fx\src\CSharp\Microsoft\CSharp\SymbolTable.cs - Microsoft.CSharp.RuntimeBinder.SymbolTable..cctor
- // VB: vb\runtime\msvbalib\helpers\Symbols.vb - Microsoft.VisualBasic.CompilerServices.Symbols..cctor
- internal virtual bool IsDynamicallyInvokable
- {
- get
- {
- return true;
- }
- }
#endif
#endregion
@@ -172,7 +153,6 @@ namespace System.Reflection
public virtual CallingConventions CallingConvention { get { return CallingConventions.Standard; } }
- [System.Runtime.InteropServices.ComVisible(true)]
public virtual Type[] GetGenericArguments() { throw new NotSupportedException(Environment.GetResourceString("NotSupported_SubclassOverride")); }
public virtual bool IsGenericMethodDefinition { get { return false; } }
@@ -227,7 +207,6 @@ namespace System.Reflection
public bool IsSpecialName { get { return(Attributes & MethodAttributes.SpecialName) != 0; } }
- [System.Runtime.InteropServices.ComVisible(true)]
public bool IsConstructor
{
get
@@ -239,9 +218,6 @@ namespace System.Reflection
}
}
-#pragma warning disable 618
- [ReflectionPermissionAttribute(SecurityAction.Demand, Flags=ReflectionPermissionFlag.MemberAccess)]
-#pragma warning restore 618
public virtual MethodBody GetMethodBody()
{
throw new InvalidOperationException();
@@ -269,7 +245,7 @@ namespace System.Reflection
// Why don't we just use "&"?
if (t.IsByRef && !serialization)
{
- sbParamList.Append(typeName.TrimEnd(new char[] { '&' }));
+ sbParamList.Append(typeName.TrimEnd('&'));
sbParamList.Append(" ByRef");
}
else
diff --git a/src/mscorlib/src/System/Reflection/MethodBody.cs b/src/mscorlib/src/System/Reflection/MethodBody.cs
index 4634623e26..7cbaeaf9b9 100644
--- a/src/mscorlib/src/System/Reflection/MethodBody.cs
+++ b/src/mscorlib/src/System/Reflection/MethodBody.cs
@@ -13,7 +13,6 @@ using System.Diagnostics.Contracts;
namespace System.Reflection
{
[Flags()]
- [System.Runtime.InteropServices.ComVisible(true)]
public enum ExceptionHandlingClauseOptions: int
{
Clause = 0x0,
@@ -22,7 +21,6 @@ namespace System.Reflection
Fault = 0x4,
}
- [System.Runtime.InteropServices.ComVisible(true)]
public class ExceptionHandlingClause
{
#region costructor
@@ -107,7 +105,6 @@ namespace System.Reflection
#endregion
}
- [System.Runtime.InteropServices.ComVisible(true)]
public class MethodBody
{
#region costructor
@@ -135,7 +132,6 @@ namespace System.Reflection
#endregion
}
- [System.Runtime.InteropServices.ComVisible(true)]
public class LocalVariableInfo
{
#region Private Data Members
diff --git a/src/mscorlib/src/System/Reflection/MethodImplAttributes.cs b/src/mscorlib/src/System/Reflection/MethodImplAttributes.cs
index 0fa4d00f19..1bd6b9dbd1 100644
--- a/src/mscorlib/src/System/Reflection/MethodImplAttributes.cs
+++ b/src/mscorlib/src/System/Reflection/MethodImplAttributes.cs
@@ -10,7 +10,6 @@ namespace System.Reflection
using System;
// This Enum matchs the CorMethodImpl defined in CorHdr.h
[Serializable]
-[System.Runtime.InteropServices.ComVisible(true)]
public enum MethodImplAttributes
{
// code impl mask
@@ -36,7 +35,6 @@ namespace System.Reflection
Synchronized = 0x0020, // Method is single threaded through the body.
NoInlining = 0x0008, // Method may not be inlined.
- [System.Runtime.InteropServices.ComVisible(false)]
AggressiveInlining = 0x0100, // Method should be inlined if possible.
NoOptimization = 0x0040, // Method may not be optimized.
diff --git a/src/mscorlib/src/System/Reflection/MethodInfo.cs b/src/mscorlib/src/System/Reflection/MethodInfo.cs
index 39387b1f8f..5ce124614c 100644
--- a/src/mscorlib/src/System/Reflection/MethodInfo.cs
+++ b/src/mscorlib/src/System/Reflection/MethodInfo.cs
@@ -16,7 +16,6 @@ namespace System.Reflection
using System.Runtime.ConstrainedExecution;
using System.Runtime.Serialization;
using System.Security;
- using System.Security.Permissions;
using System.Text;
using System.Threading;
using MemberListType = System.RuntimeType.MemberListType;
@@ -24,10 +23,7 @@ namespace System.Reflection
using System.Runtime.CompilerServices;
[Serializable]
- [ClassInterface(ClassInterfaceType.None)]
- [ComDefaultInterface(typeof(_MethodInfo))]
- [System.Runtime.InteropServices.ComVisible(true)]
- public abstract class MethodInfo : MethodBase, _MethodInfo
+ public abstract class MethodInfo : MethodBase
{
#region Constructor
protected MethodInfo() { }
@@ -74,10 +70,8 @@ namespace System.Reflection
public abstract MethodInfo GetBaseDefinition();
- [System.Runtime.InteropServices.ComVisible(true)]
public override Type[] GetGenericArguments() { throw new NotSupportedException(Environment.GetResourceString("NotSupported_SubclassOverride")); }
- [System.Runtime.InteropServices.ComVisible(true)]
public virtual MethodInfo GetGenericMethodDefinition() { throw new NotSupportedException(Environment.GetResourceString("NotSupported_SubclassOverride")); }
public virtual MethodInfo MakeGenericMethod(params Type[] typeArguments) { throw new NotSupportedException(Environment.GetResourceString("NotSupported_SubclassOverride")); }
@@ -133,14 +127,6 @@ namespace System.Reflection
return false;
}
-
- internal override bool IsDynamicallyInvokable
- {
- get
- {
- return !AppDomain.ProfileAPICheck || !IsNonW8PFrameworkAPI();
- }
- }
#endif
internal INVOCATION_FLAGS InvocationFlags
@@ -279,7 +265,6 @@ namespace System.Reflection
return sbName.ToString();
}
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
internal override bool CacheEquals(object o)
{
RuntimeMethodInfo m = o as RuntimeMethodInfo;
@@ -303,12 +288,6 @@ namespace System.Reflection
internal BindingFlags BindingFlags { get { return m_bindingFlags; } }
- // Differs from MethodHandle in that it will return a valid handle even for reflection only loaded types
- internal RuntimeMethodHandle GetMethodHandle()
- {
- return new RuntimeMethodHandle(this);
- }
-
internal RuntimeMethodInfo GetParentDefinition()
{
if (!IsVirtual || m_declaringType.IsInterface)
@@ -522,14 +501,6 @@ namespace System.Reflection
return RuntimeMethodHandle.GetImplAttributes(this);
}
- internal bool IsOverloaded
- {
- get
- {
- return m_reflectedTypeCache.GetMethodList(MemberListType.CaseSensitive, Name).Length > 1;
- }
- }
-
public override RuntimeMethodHandle MethodHandle
{
get
diff --git a/src/mscorlib/src/System/Reflection/Missing.cs b/src/mscorlib/src/System/Reflection/Missing.cs
index 24bf77bd4e..f62c5b538c 100644
--- a/src/mscorlib/src/System/Reflection/Missing.cs
+++ b/src/mscorlib/src/System/Reflection/Missing.cs
@@ -9,12 +9,10 @@ namespace System.Reflection
using System;
using System.Runtime.Remoting;
using System.Runtime.Serialization;
- using System.Security.Permissions;
using System.Diagnostics.Contracts;
// This is not serializable because it is a reflection command.
[Serializable]
- [System.Runtime.InteropServices.ComVisible(true)]
public sealed class Missing : ISerializable
{
public static readonly Missing Value = new Missing();
diff --git a/src/mscorlib/src/System/Reflection/Module.cs b/src/mscorlib/src/System/Reflection/Module.cs
index b6be38e434..bdf95fca26 100644
--- a/src/mscorlib/src/System/Reflection/Module.cs
+++ b/src/mscorlib/src/System/Reflection/Module.cs
@@ -17,7 +17,6 @@ namespace System.Reflection
using System.Threading;
using System.Runtime.CompilerServices;
using System.Security;
- using System.Security.Permissions;
using System.IO;
using System.Globalization;
using System.Runtime.Versioning;
@@ -25,7 +24,6 @@ namespace System.Reflection
[Serializable]
[Flags]
- [System.Runtime.InteropServices.ComVisible(true)]
public enum PortableExecutableKinds
{
NotAPortableExecutableImage = 0x0,
@@ -38,12 +36,10 @@ namespace System.Reflection
Unmanaged32Bit = 0x8,
- [ComVisible(false)]
Preferred32Bit = 0x10,
}
[Serializable]
- [System.Runtime.InteropServices.ComVisible(true)]
public enum ImageFileMachine
{
I386 = 0x014c,
@@ -56,10 +52,7 @@ namespace System.Reflection
}
[Serializable]
- [ClassInterface(ClassInterfaceType.None)]
- [ComDefaultInterface(typeof(_Module))]
- [System.Runtime.InteropServices.ComVisible(true)]
- public abstract class Module : _Module, ISerializable, ICustomAttributeProvider
+ public abstract class Module : ISerializable, ICustomAttributeProvider
{
#region Static Constructor
static Module()
@@ -276,18 +269,15 @@ namespace System.Reflection
throw new NotImplementedException();
}
- [System.Runtime.InteropServices.ComVisible(true)]
public virtual Type GetType(String className, bool ignoreCase)
{
return GetType(className, false, ignoreCase);
}
- [System.Runtime.InteropServices.ComVisible(true)]
public virtual Type GetType(String className) {
return GetType(className, false, false);
}
- [System.Runtime.InteropServices.ComVisible(true)]
public virtual Type GetType(String className, bool throwOnError, bool ignoreCase)
{
throw new NotImplementedException();
@@ -983,7 +973,6 @@ namespace System.Reflection
UnitySerializationHolder.GetUnitySerializationInfo(info, UnitySerializationHolder.ModuleUnity, this.ScopeName, this.GetRuntimeAssembly());
}
- [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"
@@ -1008,22 +997,7 @@ namespace System.Reflection
{
get
{
- String fullyQualifiedName = GetFullyQualifiedName();
-
- if (fullyQualifiedName != null) {
- bool checkPermission = true;
- try {
- Path.GetFullPath(fullyQualifiedName);
- }
- catch(ArgumentException) {
- checkPermission = false;
- }
- if (checkPermission) {
- new FileIOPermission( FileIOPermissionAccess.PathDiscovery, fullyQualifiedName ).Demand();
- }
- }
-
- return fullyQualifiedName;
+ return GetFullyQualifiedName();
}
}
diff --git a/src/mscorlib/src/System/Reflection/ObfuscateAssemblyAttribute.cs b/src/mscorlib/src/System/Reflection/ObfuscateAssemblyAttribute.cs
index b852e5a4c2..787f37bced 100644
--- a/src/mscorlib/src/System/Reflection/ObfuscateAssemblyAttribute.cs
+++ b/src/mscorlib/src/System/Reflection/ObfuscateAssemblyAttribute.cs
@@ -11,7 +11,6 @@ using System.Reflection;
namespace System.Reflection
{
[AttributeUsage (AttributeTargets.Assembly, AllowMultiple=false, Inherited=false)]
-[System.Runtime.InteropServices.ComVisible(true)]
public sealed class ObfuscateAssemblyAttribute : Attribute
{
private bool m_assemblyIsPrivate;
diff --git a/src/mscorlib/src/System/Reflection/ObfuscationAttribute.cs b/src/mscorlib/src/System/Reflection/ObfuscationAttribute.cs
index 0b987ce06d..c7c7c18550 100644
--- a/src/mscorlib/src/System/Reflection/ObfuscationAttribute.cs
+++ b/src/mscorlib/src/System/Reflection/ObfuscationAttribute.cs
@@ -11,7 +11,6 @@ namespace System.Reflection
{
[AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Parameter | AttributeTargets.Field | AttributeTargets.Property | AttributeTargets.Event | AttributeTargets.Interface | AttributeTargets.Enum | AttributeTargets.Delegate,
AllowMultiple = true, Inherited = false)]
-[System.Runtime.InteropServices.ComVisible(true)]
public sealed class ObfuscationAttribute: Attribute
{
private bool m_strip = true;
diff --git a/src/mscorlib/src/System/Reflection/ParameterAttributes.cs b/src/mscorlib/src/System/Reflection/ParameterAttributes.cs
index 12f8145ddd..acae3a6ec1 100644
--- a/src/mscorlib/src/System/Reflection/ParameterAttributes.cs
+++ b/src/mscorlib/src/System/Reflection/ParameterAttributes.cs
@@ -16,7 +16,6 @@ namespace System.Reflection {
// This Enum matchs the CorParamAttr defined in CorHdr.h
[Serializable]
[Flags]
- [System.Runtime.InteropServices.ComVisible(true)]
public enum ParameterAttributes
{
None = 0x0000, // no flag is specified
diff --git a/src/mscorlib/src/System/Reflection/ParameterInfo.cs b/src/mscorlib/src/System/Reflection/ParameterInfo.cs
index 6592e5aa20..fad4402aff 100644
--- a/src/mscorlib/src/System/Reflection/ParameterInfo.cs
+++ b/src/mscorlib/src/System/Reflection/ParameterInfo.cs
@@ -13,15 +13,11 @@ namespace System.Reflection
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
using System.Runtime.CompilerServices;
- using System.Security.Permissions;
using System.Threading;
using MdToken = System.Reflection.MetadataToken;
[Serializable]
- [ClassInterface(ClassInterfaceType.None)]
- [ComDefaultInterface(typeof(_ParameterInfo))]
- [System.Runtime.InteropServices.ComVisible(true)]
- public class ParameterInfo : _ParameterInfo, ICustomAttributeProvider, IObjectReference
+ public class ParameterInfo : ICustomAttributeProvider, IObjectReference
{
#region Legacy Protected Members
protected String NameImpl;
diff --git a/src/mscorlib/src/System/Reflection/ParameterModifier.cs b/src/mscorlib/src/System/Reflection/ParameterModifier.cs
index 97da1b9e00..a2bfeab934 100644
--- a/src/mscorlib/src/System/Reflection/ParameterModifier.cs
+++ b/src/mscorlib/src/System/Reflection/ParameterModifier.cs
@@ -7,7 +7,6 @@ namespace System.Reflection
using System;
[Serializable]
-[System.Runtime.InteropServices.ComVisible(true)]
public struct ParameterModifier
{
#region Private Data Members
diff --git a/src/mscorlib/src/System/Reflection/Pointer.cs b/src/mscorlib/src/System/Reflection/Pointer.cs
index 95025b20ed..9f1a38366a 100644
--- a/src/mscorlib/src/System/Reflection/Pointer.cs
+++ b/src/mscorlib/src/System/Reflection/Pointer.cs
@@ -19,7 +19,6 @@ namespace System.Reflection {
[CLSCompliant(false)]
[Serializable]
- [System.Runtime.InteropServices.ComVisible(true)]
public sealed class Pointer : ISerializable
{
unsafe private void* _ptr;
diff --git a/src/mscorlib/src/System/Reflection/PropertyAttributes.cs b/src/mscorlib/src/System/Reflection/PropertyAttributes.cs
index d7c3d79b6a..4a5617ba5e 100644
--- a/src/mscorlib/src/System/Reflection/PropertyAttributes.cs
+++ b/src/mscorlib/src/System/Reflection/PropertyAttributes.cs
@@ -16,7 +16,6 @@ namespace System.Reflection {
// This Enum matchs the CorPropertyAttr defined in CorHdr.h
[Serializable]
[Flags]
-[System.Runtime.InteropServices.ComVisible(true)]
public enum PropertyAttributes
{
None = 0x0000,
diff --git a/src/mscorlib/src/System/Reflection/PropertyInfo.cs b/src/mscorlib/src/System/Reflection/PropertyInfo.cs
index e31b378924..e8c2837785 100644
--- a/src/mscorlib/src/System/Reflection/PropertyInfo.cs
+++ b/src/mscorlib/src/System/Reflection/PropertyInfo.cs
@@ -15,15 +15,11 @@ namespace System.Reflection
using System.Runtime.ConstrainedExecution;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
- using System.Security.Permissions;
using System.Text;
using RuntimeTypeCache = System.RuntimeType.RuntimeTypeCache;
[Serializable]
- [ClassInterface(ClassInterfaceType.None)]
- [ComDefaultInterface(typeof(_PropertyInfo))]
- [System.Runtime.InteropServices.ComVisible(true)]
- public abstract class PropertyInfo : MemberInfo, _PropertyInfo
+ public abstract class PropertyInfo : MemberInfo
{
#region Constructor
protected PropertyInfo() { }
@@ -196,7 +192,6 @@ namespace System.Reflection
#endregion
#region Internal Members
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
internal override bool CacheEquals(object o)
{
RuntimePropertyInfo m = o as RuntimePropertyInfo;
diff --git a/src/mscorlib/src/System/Reflection/ReflectionTypeLoadException.cs b/src/mscorlib/src/System/Reflection/ReflectionTypeLoadException.cs
index 70681138c5..cccf060645 100644
--- a/src/mscorlib/src/System/Reflection/ReflectionTypeLoadException.cs
+++ b/src/mscorlib/src/System/Reflection/ReflectionTypeLoadException.cs
@@ -19,10 +19,8 @@ namespace System.Reflection {
using System;
using System.Runtime.Serialization;
- using System.Security.Permissions;
using System.Diagnostics.Contracts;
[Serializable]
- [System.Runtime.InteropServices.ComVisible(true)]
public sealed class ReflectionTypeLoadException : SystemException, ISerializable {
private Type[] _classes;
private Exception[] _exceptions;
@@ -33,11 +31,6 @@ namespace System.Reflection {
SetErrorCode(__HResults.COR_E_REFLECTIONTYPELOAD);
}
- // private constructor. This is called from inside the runtime.
- private ReflectionTypeLoadException(String message) : base(message) {
- SetErrorCode(__HResults.COR_E_REFLECTIONTYPELOAD);
- }
-
public ReflectionTypeLoadException(Type[] classes, Exception[] exceptions) : base(null)
{
_classes = classes;
diff --git a/src/mscorlib/src/System/Reflection/ResourceAttributes.cs b/src/mscorlib/src/System/Reflection/ResourceAttributes.cs
index 646572677f..5c419ebb2d 100644
--- a/src/mscorlib/src/System/Reflection/ResourceAttributes.cs
+++ b/src/mscorlib/src/System/Reflection/ResourceAttributes.cs
@@ -15,7 +15,6 @@ namespace System.Reflection {
using System;
[Serializable]
[Flags]
-[System.Runtime.InteropServices.ComVisible(true)]
public enum ResourceAttributes
{
Public = 0x0001,
diff --git a/src/mscorlib/src/System/Reflection/RuntimeReflectionExtensions.cs b/src/mscorlib/src/System/Reflection/RuntimeReflectionExtensions.cs
index 00ab975842..49262634e3 100644
--- a/src/mscorlib/src/System/Reflection/RuntimeReflectionExtensions.cs
+++ b/src/mscorlib/src/System/Reflection/RuntimeReflectionExtensions.cs
@@ -10,16 +10,16 @@ namespace System.Reflection
{
private const BindingFlags everything = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static;
- private static void CheckAndThrow(Type t)
+ private static void CheckAndThrow(Type type)
{
- if (t == null) throw new ArgumentNullException("type");
- if (!(t is RuntimeType)) throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeType"));
+ if (type == null) throw new ArgumentNullException(nameof(type));
+ if (!(type is RuntimeType)) throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeType"));
}
- private static void CheckAndThrow(MethodInfo m)
+ private static void CheckAndThrow(MethodInfo method)
{
- if (m == null) throw new ArgumentNullException("method");
- if (!(m is RuntimeMethodInfo)) throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeMethodInfo"));
+ if (method == null) throw new ArgumentNullException(nameof(method));
+ if (!(method is RuntimeMethodInfo)) throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeMethodInfo"));
}
public static IEnumerable<PropertyInfo> GetRuntimeProperties(this Type type)
diff --git a/src/mscorlib/src/System/Reflection/StrongNameKeyPair.cs b/src/mscorlib/src/System/Reflection/StrongNameKeyPair.cs
index 8107cf4159..0121982489 100644
--- a/src/mscorlib/src/System/Reflection/StrongNameKeyPair.cs
+++ b/src/mscorlib/src/System/Reflection/StrongNameKeyPair.cs
@@ -22,13 +22,11 @@ namespace System.Reflection
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
using System.Security;
- using System.Security.Permissions;
using System.Runtime.Versioning;
using Microsoft.Win32;
using System.Diagnostics.Contracts;
[Serializable]
- [System.Runtime.InteropServices.ComVisible(true)]
public class StrongNameKeyPair : IDeserializationCallback, ISerializable
{
private bool _keyPairExported;
diff --git a/src/mscorlib/src/System/Reflection/TargetException.cs b/src/mscorlib/src/System/Reflection/TargetException.cs
index 9c56c121cc..dcbb38833e 100644
--- a/src/mscorlib/src/System/Reflection/TargetException.cs
+++ b/src/mscorlib/src/System/Reflection/TargetException.cs
@@ -18,7 +18,6 @@ namespace System.Reflection {
using System;
using System.Runtime.Serialization;
[Serializable]
- [System.Runtime.InteropServices.ComVisible(true)]
public class TargetException : ApplicationException {
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 4a32ed245d..7bbc93df2a 100644
--- a/src/mscorlib/src/System/Reflection/TargetInvocationException.cs
+++ b/src/mscorlib/src/System/Reflection/TargetInvocationException.cs
@@ -18,7 +18,6 @@ namespace System.Reflection {
using System;
using System.Runtime.Serialization;
[Serializable]
- [System.Runtime.InteropServices.ComVisible(true)]
public sealed class TargetInvocationException : ApplicationException {
// This exception is not creatable without specifying the
// inner exception.
diff --git a/src/mscorlib/src/System/Reflection/TargetParameterCountException.cs b/src/mscorlib/src/System/Reflection/TargetParameterCountException.cs
index 846732b449..7a07b20acd 100644
--- a/src/mscorlib/src/System/Reflection/TargetParameterCountException.cs
+++ b/src/mscorlib/src/System/Reflection/TargetParameterCountException.cs
@@ -18,7 +18,6 @@ namespace System.Reflection {
using SystemException = System.SystemException;
using System.Runtime.Serialization;
[Serializable]
- [System.Runtime.InteropServices.ComVisible(true)]
public sealed class TargetParameterCountException : ApplicationException {
public TargetParameterCountException()
: base(Environment.GetResourceString("Arg_TargetParameterCountException")) {
diff --git a/src/mscorlib/src/System/Reflection/TypeAttributes.cs b/src/mscorlib/src/System/Reflection/TypeAttributes.cs
index 4fa6fb06ba..25aa113d2e 100644
--- a/src/mscorlib/src/System/Reflection/TypeAttributes.cs
+++ b/src/mscorlib/src/System/Reflection/TypeAttributes.cs
@@ -8,7 +8,6 @@ namespace System.Reflection {
// This Enum matchs the CorTypeAttr defined in CorHdr.h
[Serializable]
[Flags]
-[System.Runtime.InteropServices.ComVisible(true)]
public enum TypeAttributes
{
VisibilityMask = 0x00000007,
@@ -43,7 +42,6 @@ namespace System.Reflection {
Import = 0x00001000, // Class / interface is imported
Serializable = 0x00002000, // The class is Serializable.
- [ComVisible(false)]
WindowsRuntime = 0x00004000, // Type is a Windows Runtime type.
// Use tdStringFormatMask to retrieve string information for native interop
diff --git a/src/mscorlib/src/System/Reflection/TypeDelegator.cs b/src/mscorlib/src/System/Reflection/TypeDelegator.cs
index d715df8950..6a77a95853 100644
--- a/src/mscorlib/src/System/Reflection/TypeDelegator.cs
+++ b/src/mscorlib/src/System/Reflection/TypeDelegator.cs
@@ -14,7 +14,6 @@ namespace System.Reflection {
using CultureInfo = System.Globalization.CultureInfo;
[Serializable]
-[System.Runtime.InteropServices.ComVisible(true)]
public class TypeDelegator : TypeInfo
{
public override bool IsAssignableFrom(System.Reflection.TypeInfo typeInfo){
@@ -86,7 +85,6 @@ namespace System.Reflection {
return typeImpl.GetConstructor(bindingAttr,binder,callConvention,types,modifiers);
}
-[System.Runtime.InteropServices.ComVisible(true)]
public override ConstructorInfo[] GetConstructors(BindingFlags bindingAttr)
{
return typeImpl.GetConstructors(bindingAttr);
@@ -251,7 +249,6 @@ namespace System.Reflection {
return typeImpl.IsDefined(attributeType, inherit);
}
-[System.Runtime.InteropServices.ComVisible(true)]
public override InterfaceMapping GetInterfaceMap(Type interfaceType)
{
return typeImpl.GetInterfaceMap(interfaceType);
diff --git a/src/mscorlib/src/System/Reflection/TypeFilter.cs b/src/mscorlib/src/System/Reflection/TypeFilter.cs
index 560618ff79..4837a303a1 100644
--- a/src/mscorlib/src/System/Reflection/TypeFilter.cs
+++ b/src/mscorlib/src/System/Reflection/TypeFilter.cs
@@ -14,6 +14,5 @@ namespace System.Reflection {
// Define the delegate
[Serializable]
- [System.Runtime.InteropServices.ComVisible(true)]
public delegate bool TypeFilter(Type m, Object filterCriteria);
}
diff --git a/src/mscorlib/src/System/Reflection/TypeInfo.cs b/src/mscorlib/src/System/Reflection/TypeInfo.cs
index 706fb0a61a..61d7bb27a9 100644
--- a/src/mscorlib/src/System/Reflection/TypeInfo.cs
+++ b/src/mscorlib/src/System/Reflection/TypeInfo.cs
@@ -22,7 +22,6 @@ namespace System.Reflection
//all today's runtime Type derivations derive now from TypeInfo
//we make TypeInfo implement IRCT - simplifies work
- [System.Runtime.InteropServices.ComVisible(true)]
[Serializable]
public abstract class TypeInfo:Type,IReflectableType
{
diff --git a/src/mscorlib/src/System/Resources/FileBasedResourceGroveler.cs b/src/mscorlib/src/System/Resources/FileBasedResourceGroveler.cs
index 76bf0008f9..c5e92165f1 100644
--- a/src/mscorlib/src/System/Resources/FileBasedResourceGroveler.cs
+++ b/src/mscorlib/src/System/Resources/FileBasedResourceGroveler.cs
@@ -47,36 +47,28 @@ namespace System.Resources {
ResourceSet rs = null;
// Don't use Assembly manifest, but grovel on disk for a file.
- try
- {
- new System.Security.Permissions.FileIOPermission(System.Security.Permissions.PermissionState.Unrestricted).Assert();
- // Create new ResourceSet, if a file exists on disk for it.
- String tempFileName = _mediator.GetResourceFileName(culture);
- fileName = FindResourceFile(culture, tempFileName);
- if (fileName == null)
+ // Create new ResourceSet, if a file exists on disk for it.
+ String tempFileName = _mediator.GetResourceFileName(culture);
+ fileName = FindResourceFile(culture, tempFileName);
+ if (fileName == null)
+ {
+ if (tryParents)
{
- if (tryParents)
+ // If we've hit top of the Culture tree, return.
+ if (culture.HasInvariantCultureName)
{
- // If we've hit top of the Culture tree, return.
- if (culture.HasInvariantCultureName)
- {
- // We really don't think this should happen - we always
- // expect the neutral locale's resources to be present.
- throw new MissingManifestResourceException(Environment.GetResourceString("MissingManifestResource_NoNeutralDisk") + Environment.NewLine + "baseName: " + _mediator.BaseNameField + " locationInfo: " + (_mediator.LocationInfo == null ? "<null>" : _mediator.LocationInfo.FullName) + " fileName: " + _mediator.GetResourceFileName(culture));
- }
+ // We really don't think this should happen - we always
+ // expect the neutral locale's resources to be present.
+ throw new MissingManifestResourceException(Environment.GetResourceString("MissingManifestResource_NoNeutralDisk") + Environment.NewLine + "baseName: " + _mediator.BaseNameField + " locationInfo: " + (_mediator.LocationInfo == null ? "<null>" : _mediator.LocationInfo.FullName) + " fileName: " + _mediator.GetResourceFileName(culture));
}
}
- else
- {
- rs = CreateResourceSet(fileName);
- }
- return rs;
}
- finally
+ else
{
- System.Security.CodeAccessPermission.RevertAssert();
+ rs = CreateResourceSet(fileName);
}
+ return rs;
}
// Given a CultureInfo, it generates the path &; file name for
diff --git a/src/mscorlib/src/System/Resources/IResourceReader.cs b/src/mscorlib/src/System/Resources/IResourceReader.cs
index 7ab25ec1a0..de8f9db18e 100644
--- a/src/mscorlib/src/System/Resources/IResourceReader.cs
+++ b/src/mscorlib/src/System/Resources/IResourceReader.cs
@@ -17,7 +17,6 @@ namespace System.Resources {
using System.IO;
using System.Collections;
- [System.Runtime.InteropServices.ComVisible(true)]
public interface IResourceReader : IEnumerable, IDisposable
{
// Interface does not need to be marked with the serializable attribute
diff --git a/src/mscorlib/src/System/Resources/IResourceWriter.cs b/src/mscorlib/src/System/Resources/IResourceWriter.cs
deleted file mode 100644
index ae41b84cd7..0000000000
--- a/src/mscorlib/src/System/Resources/IResourceWriter.cs
+++ /dev/null
@@ -1,45 +0,0 @@
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-// See the LICENSE file in the project root for more information.
-
-/*============================================================
-**
-**
-**
-**
-**
-** Purpose: Default way to write strings to a COM+ resource
-** file.
-**
-**
-===========================================================*/
-namespace System.Resources {
- using System;
- using System.IO;
- [System.Runtime.InteropServices.ComVisible(true)]
- public interface IResourceWriter : IDisposable
- {
- // Interface does not need to be marked with the serializable attribute
- // Adds a string resource to the list of resources to be written to a file.
- // They aren't written until WriteFile() is called.
- //
- void AddResource(String name, String value);
-
- // Adds a resource to the list of resources to be written to a file.
- // They aren't written until WriteFile() is called.
- //
- void AddResource(String name, Object value);
-
- // Adds a named byte array as a resource to the list of resources to
- // be written to a file. They aren't written until WriteFile() is called.
- //
- void AddResource(String name, byte[] value);
-
- // Closes the underlying resource file.
- void Close();
-
- // After calling AddResource, this writes all resources to the output
- // stream. This does NOT close the output stream.
- void Generate();
- }
-}
diff --git a/src/mscorlib/src/System/Resources/LooselyLinkedResourceReference.cs b/src/mscorlib/src/System/Resources/LooselyLinkedResourceReference.cs
index 15a076bc5c..9287ae4590 100644
--- a/src/mscorlib/src/System/Resources/LooselyLinkedResourceReference.cs
+++ b/src/mscorlib/src/System/Resources/LooselyLinkedResourceReference.cs
@@ -28,7 +28,6 @@ namespace System.Resources {
[Serializable]
-[System.Runtime.InteropServices.ComVisible(true)]
public struct LooselyLinkedResourceReference {
private String _manifestResourceName;
private String _typeName;
diff --git a/src/mscorlib/src/System/Resources/MissingManifestResourceException.cs b/src/mscorlib/src/System/Resources/MissingManifestResourceException.cs
index e616bfe68b..2e82f19c7b 100644
--- a/src/mscorlib/src/System/Resources/MissingManifestResourceException.cs
+++ b/src/mscorlib/src/System/Resources/MissingManifestResourceException.cs
@@ -18,7 +18,6 @@ using System.Runtime.Serialization;
namespace System.Resources {
[Serializable]
- [System.Runtime.InteropServices.ComVisible(true)]
public class MissingManifestResourceException : SystemException
{
public MissingManifestResourceException()
diff --git a/src/mscorlib/src/System/Resources/MissingSatelliteAssemblyException.cs b/src/mscorlib/src/System/Resources/MissingSatelliteAssemblyException.cs
index 3d59f856b1..fc676a8dd5 100644
--- a/src/mscorlib/src/System/Resources/MissingSatelliteAssemblyException.cs
+++ b/src/mscorlib/src/System/Resources/MissingSatelliteAssemblyException.cs
@@ -20,7 +20,6 @@ using System.Runtime.Serialization;
namespace System.Resources {
[Serializable]
- [System.Runtime.InteropServices.ComVisible(true)]
public class MissingSatelliteAssemblyException : SystemException
{
private String _cultureName;
diff --git a/src/mscorlib/src/System/Resources/NeutralResourcesLanguageAttribute.cs b/src/mscorlib/src/System/Resources/NeutralResourcesLanguageAttribute.cs
index 6517a56b6a..a2ed6fbd57 100644
--- a/src/mscorlib/src/System/Resources/NeutralResourcesLanguageAttribute.cs
+++ b/src/mscorlib/src/System/Resources/NeutralResourcesLanguageAttribute.cs
@@ -26,7 +26,6 @@ namespace System.Resources {
using System.Diagnostics.Contracts;
[AttributeUsage(AttributeTargets.Assembly, AllowMultiple=false)]
- [System.Runtime.InteropServices.ComVisible(true)]
public sealed class NeutralResourcesLanguageAttribute : Attribute
{
private String _culture;
diff --git a/src/mscorlib/src/System/Resources/ResourceManager.cs b/src/mscorlib/src/System/Resources/ResourceManager.cs
index 15f6af7bcf..f17a7c8f8e 100644
--- a/src/mscorlib/src/System/Resources/ResourceManager.cs
+++ b/src/mscorlib/src/System/Resources/ResourceManager.cs
@@ -23,7 +23,6 @@ namespace System.Resources {
using System.Reflection;
using System.Runtime.Serialization;
using System.Security;
- using System.Security.Permissions;
using System.Threading;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
@@ -149,7 +148,6 @@ namespace System.Resources {
//
[Serializable]
- [System.Runtime.InteropServices.ComVisible(true)]
public class ResourceManager
{
@@ -162,7 +160,7 @@ namespace System.Resources {
// Sets is a many-to-one table of CultureInfos mapped to ResourceSets.
// Don't synchronize ResourceSets - too fine-grained a lock to be effective
[Obsolete("call InternalGetResourceSet instead")]
- protected Hashtable ResourceSets;
+ internal Hashtable ResourceSets;
// don't serialize the cache of ResourceSets
@@ -738,48 +736,9 @@ namespace System.Resources {
}
Contract.EndContractBlock();
-#if !FEATURE_WINDOWSPHONE
- String v = null;
- if (a.ReflectionOnly) {
- foreach (CustomAttributeData data in CustomAttributeData.GetCustomAttributes(a)) {
- if (data.Constructor.DeclaringType == typeof(SatelliteContractVersionAttribute)) {
- v = (String)data.ConstructorArguments[0].Value;
- break;
- }
- }
-
- if (v == null)
- return null;
- }
- else {
- Object[] attrs = a.GetCustomAttributes(typeof(SatelliteContractVersionAttribute), false);
- if (attrs.Length == 0)
- return null;
- Debug.Assert(attrs.Length == 1, "Cannot have multiple instances of SatelliteContractVersionAttribute on an assembly!");
- v = ((SatelliteContractVersionAttribute)attrs[0]).Version;
- }
- Version ver;
- try {
- ver = new Version(v);
- }
- catch(ArgumentOutOfRangeException e) {
- // Note we are prone to hitting infinite loops if mscorlib's
- // SatelliteContractVersionAttribute contains bogus values.
- // If this assert fires, please fix the build process for the
- // BCL directory.
- if (a == typeof(Object).Assembly) {
- Debug.Assert(false, System.CoreLib.Name+"'s SatelliteContractVersionAttribute is a malformed version string!");
- return null;
- }
-
- throw new ArgumentException(Environment.GetResourceString("Arg_InvalidSatelliteContract_Asm_Ver", a.ToString(), v), e);
- }
- return ver;
-#else
- // On the phone return null. The calling code will use the assembly version instead to avoid potential type
+ // Return null. The calling code will use the assembly version instead to avoid potential type
// and library loads caused by CA lookup. NetCF uses the assembly version always.
return null;
-#endif
}
protected static CultureInfo GetNeutralResourcesLanguage(Assembly a)
@@ -1285,12 +1244,10 @@ namespace System.Resources {
return null;
}
- [ComVisible(false)]
public UnmanagedMemoryStream GetStream(String name) {
return GetStream(name, (CultureInfo)null);
}
- [ComVisible(false)]
public UnmanagedMemoryStream GetStream(String name, CultureInfo culture) {
Object obj = GetObject(name, culture, false);
UnmanagedMemoryStream ums = obj as UnmanagedMemoryStream;
diff --git a/src/mscorlib/src/System/Resources/ResourceReader.cs b/src/mscorlib/src/System/Resources/ResourceReader.cs
index 89cfdb1b9f..d752771020 100644
--- a/src/mscorlib/src/System/Resources/ResourceReader.cs
+++ b/src/mscorlib/src/System/Resources/ResourceReader.cs
@@ -20,13 +20,7 @@ namespace System.Resources {
using System.Text;
using System.Collections;
using System.Collections.Generic;
-#if FEATURE_SERIALIZATION
- using System.Runtime.Serialization;
- using System.Runtime.Serialization.Formatters;
- using System.Runtime.Serialization.Formatters.Binary;
-#endif // FEATURE_SERIALIZATION
using System.Reflection;
- using System.Security.Permissions;
using System.Security;
using System.Globalization;
using System.Configuration.Assemblies;
@@ -73,7 +67,6 @@ namespace System.Resources {
}
- [System.Runtime.InteropServices.ComVisible(true)]
public sealed class ResourceReader : IResourceReader
{
// A reasonable default buffer size for reading from files, especially
@@ -100,9 +93,6 @@ namespace System.Resources {
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
-#if FEATURE_SERIALIZATION
- private BinaryFormatter _objFormatter; // Deserialization stuff.
-#endif // FEATURE_SERIALIZATION
private int _numResources; // Num of resources files, in case arrays aren't allocated.
// We'll include a separate code path that uses UnmanagedMemoryStream to
@@ -116,45 +106,11 @@ namespace System.Resources {
private bool _debug; // Whether this file has debugging stuff in it.
#endif
-#if FEATURE_SERIALIZATION
- private bool[] _safeToDeserialize; // Whether to assert serialization permission
- private TypeLimitingDeserializationBinder _typeLimitingBinder;
-
- // One of our goals is to make sure localizable Windows Forms apps
- // work in semi-trusted scenarios (ie, without serialization permission).
- // Unfortunate we're serializing out some complex types that currently
- // require a security check on deserialization. We may fix this
- // in a next version, but for now just hard-code a list.
- // Hard-code in the assembly name (minus version) so people can't spoof us.
- private static readonly String[] TypesSafeForDeserialization = {
- "System.String[], mscorlib, Culture=neutral, PublicKeyToken=" + AssemblyRef.MicrosoftPublicKeyToken,
- "System.DateTime[], mscorlib, Culture=neutral, PublicKeyToken=" + AssemblyRef.MicrosoftPublicKeyToken,
- "System.Drawing.Bitmap, System.Drawing, Culture=neutral, PublicKeyToken=" + AssemblyRef.MicrosoftPublicKeyToken,
- "System.Drawing.Imaging.Metafile, System.Drawing, Culture=neutral, PublicKeyToken=" + AssemblyRef.MicrosoftPublicKeyToken,
- "System.Drawing.Point, System.Drawing, Culture=neutral, PublicKeyToken=" + AssemblyRef.MicrosoftPublicKeyToken,
- "System.Drawing.PointF, System.Drawing, Culture=neutral, PublicKeyToken=" + AssemblyRef.MicrosoftPublicKeyToken,
- "System.Drawing.Size, System.Drawing, Culture=neutral, PublicKeyToken=" + AssemblyRef.MicrosoftPublicKeyToken,
- "System.Drawing.SizeF, System.Drawing, Culture=neutral, PublicKeyToken=" + AssemblyRef.MicrosoftPublicKeyToken,
- "System.Drawing.Font, System.Drawing, Culture=neutral, PublicKeyToken=" + AssemblyRef.MicrosoftPublicKeyToken,
- "System.Drawing.Icon, System.Drawing, Culture=neutral, PublicKeyToken=" + AssemblyRef.MicrosoftPublicKeyToken,
- "System.Drawing.Color, System.Drawing, Culture=neutral, PublicKeyToken=" + AssemblyRef.MicrosoftPublicKeyToken,
- "System.Windows.Forms.Cursor, System.Windows.Forms, Culture=neutral, PublicKeyToken=" + AssemblyRef.EcmaPublicKeyToken,
- "System.Windows.Forms.Padding, System.Windows.Forms, Culture=neutral, PublicKeyToken=" + AssemblyRef.EcmaPublicKeyToken,
- "System.Windows.Forms.LinkArea, System.Windows.Forms, Culture=neutral, PublicKeyToken=" + AssemblyRef.EcmaPublicKeyToken,
- "System.Windows.Forms.ImageListStreamer, System.Windows.Forms, Culture=neutral, PublicKeyToken=" + AssemblyRef.EcmaPublicKeyToken,
- "System.Windows.Forms.ListViewGroup, System.Windows.Forms, Culture=neutral, PublicKeyToken=" + AssemblyRef.EcmaPublicKeyToken,
- "System.Windows.Forms.ListViewItem, System.Windows.Forms, Culture=neutral, PublicKeyToken=" + AssemblyRef.EcmaPublicKeyToken,
- "System.Windows.Forms.ListViewItem+ListViewSubItem, System.Windows.Forms, Culture=neutral, PublicKeyToken=" + AssemblyRef.EcmaPublicKeyToken,
- "System.Windows.Forms.ListViewItem+ListViewSubItem+SubItemStyle, System.Windows.Forms, Culture=neutral, PublicKeyToken=" + AssemblyRef.EcmaPublicKeyToken,
- "System.Windows.Forms.OwnerDrawPropertyBag, System.Windows.Forms, Culture=neutral, PublicKeyToken=" + AssemblyRef.EcmaPublicKeyToken,
- "System.Windows.Forms.TreeNode, System.Windows.Forms, Culture=neutral, PublicKeyToken=" + AssemblyRef.EcmaPublicKeyToken
- };
-#endif // FEATURE_SERIALIZATION
public ResourceReader(String fileName)
{
_resCache = new Dictionary<String, ResourceLocator>(FastResourceComparer.Default);
- _store = new BinaryReader(new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read, DefaultFileStreamBufferSize, FileOptions.RandomAccess, Path.GetFileName(fileName), false), Encoding.UTF8);
+ _store = new BinaryReader(new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read, DefaultFileStreamBufferSize, FileOptions.RandomAccess), Encoding.UTF8);
BCLDebug.Log("RESMGRFILEFORMAT", "ResourceReader .ctor(String). UnmanagedMemoryStream: "+(_ums!=null));
try {
@@ -240,10 +196,6 @@ namespace System.Resources {
// Unaligned, little endian format
return buffer[0] | (buffer[1] << 8) | (buffer[2] << 16) | (buffer[3] << 24);
}
-
- private void SkipInt32() {
- _store.BaseStream.Seek(4, SeekOrigin.Current);
- }
private void SkipString() {
@@ -580,8 +532,6 @@ namespace System.Resources {
}
}
-#if FEATURE_SERIALIZATION
-#endif
private Object _LoadObjectV1(int pos) {
_store.BaseStream.Seek(_dataSectionOffset+pos, SeekOrigin.Begin);
int typeIndex = _store.Read7BitEncodedInt();
@@ -629,11 +579,7 @@ namespace System.Resources {
return new Decimal(bits);
}
else {
-#if FEATURE_SERIALIZATION
- return DeserializeObject(typeIndex);
-#else
throw new NotSupportedException(Environment.GetResourceString("NotSupported_ResourceObjectSerialization"));
-#endif // FEATURE_SERIALIZATION
}
}
@@ -759,7 +705,7 @@ namespace System.Resources {
// For the case that we've memory mapped in the .resources
// file, just return a Stream pointing to that block of memory.
unsafe {
- return new UnmanagedMemoryStream(_ums.PositionPointer, len, len, FileAccess.Read, true);
+ return new UnmanagedMemoryStream(_ums.PositionPointer, len, len, FileAccess.Read);
}
}
@@ -771,57 +717,10 @@ namespace System.Resources {
}
// Normal serialized objects
-#if FEATURE_SERIALIZATION
- int typeIndex = typeCode - ResourceTypeCode.StartOfUserTypes;
- return DeserializeObject(typeIndex);
-#else
throw new NotSupportedException(Environment.GetResourceString("NotSupported_ResourceObjectSerialization"));
-#endif // FEATURE_SERIALIZATION
}
-#if FEATURE_SERIALIZATION
- // Helper method to safely deserialize a type, using a type-limiting
- // 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.
- private Object DeserializeObject(int typeIndex)
- {
- RuntimeType type = FindType(typeIndex);
- // Initialize deserialization permission array, if needed
- if (_safeToDeserialize == null)
- InitSafeToDeserializeArray();
-
- // Ensure that the object we deserialized is exactly the same
- // type of object we thought we should be deserializing. This
- // will help prevent malformed .resources files from using our
- // serialization permission assert to deserialize anything
- // via a malformed type ID.
-
- Object graph;
- if (_safeToDeserialize[typeIndex]) {
- // Don't assert serialization permission - just ask the binary
- // formatter to avoid a permission check. This ensures that any
- // types which do demand serialization permission in their
- // deserialization .cctors will fail.
- // Also, use a serialization binder to limit bind requests to
- // our allowed list of WinForms types.
- _objFormatter.Binder = _typeLimitingBinder;
- _typeLimitingBinder.ExpectingToDeserialize(type);
- graph = _objFormatter.UnsafeDeserialize(_store.BaseStream, null);
- }
- else {
- _objFormatter.Binder = null;
- graph = _objFormatter.Deserialize(_store.BaseStream);
- }
-
- // This check is about correctness, not security at this point.
- if (graph.GetType() != type)
- throw new BadImageFormatException(Environment.GetResourceString("BadImageFormat_ResType&SerBlobMismatch", type.FullName, graph.GetType().FullName));
-
- return graph;
- }
-#endif // FEATURE_SERIALIZATION
// Reads in the header information for a .resources file. Verifies some
// of the assumptions about this resource set, and builds the class table
@@ -829,12 +728,6 @@ namespace System.Resources {
private void ReadResources()
{
Debug.Assert(_store != null, "ResourceReader is closed!");
-#if FEATURE_SERIALIZATION
- BinaryFormatter bf = new BinaryFormatter(null, new StreamingContext(StreamingContextStates.File | StreamingContextStates.Persistence));
- _typeLimitingBinder = new TypeLimitingDeserializationBinder();
- bf.Binder = _typeLimitingBinder;
- _objFormatter = bf;
-#endif // FEATURE_SERIALIZATION
try {
// mega try-catch performs exceptionally bad on x64; factored out body into
@@ -918,7 +811,7 @@ namespace System.Resources {
throw new BadImageFormatException(Environment.GetResourceString("BadImageFormat_ResourcesHeaderCorrupted"));
}
BCLDebug.Log("RESMGRFILEFORMAT", "ReadResources: Expecting " + _numResources + " resources.");
-#if _DEBUG
+#if RESOURCE_FILE_FORMAT_DEBUG
if (ResourceManager.DEBUG >= 4)
Console.WriteLine("ResourceReader::ReadResources - Reading in "+_numResources+" resources");
#endif
@@ -938,7 +831,7 @@ namespace System.Resources {
SkipString();
}
-#if _DEBUG
+#if RESOURCE_FILE_FORMAT_DEBUG
if (ResourceManager.DEBUG >= 5)
Console.WriteLine("ResourceReader::ReadResources - Reading in "+numTypes+" type table entries");
#endif
@@ -1049,7 +942,6 @@ namespace System.Resources {
String typeName = _store.ReadString();
_typeTable[typeIndex] = (RuntimeType)Type.GetType(typeName, true);
}
-#if !FEATURE_SERIALIZATION
// If serialization isn't supported, we convert FileNotFoundException to
// NotSupportedException for consistency with v2. This is a corner-case, but the
// idea is that we want to give the user a more accurate error message. Even if
@@ -1064,7 +956,6 @@ namespace System.Resources {
{
throw new NotSupportedException(Environment.GetResourceString("NotSupported_ResourceObjectSerialization"));
}
-#endif // FEATURE_SERIALIZATION
finally {
_store.BaseStream.Position = oldPos;
}
@@ -1073,74 +964,6 @@ namespace System.Resources {
return _typeTable[typeIndex];
}
-#if FEATURE_SERIALIZATION
- private void InitSafeToDeserializeArray()
- {
- _safeToDeserialize = new bool[_typeTable.Length];
- for(int i=0; i<_typeTable.Length; i++) {
- long oldPos = _store.BaseStream.Position;
- String typeName;
- try {
- _store.BaseStream.Position = _typeNamePositions[i];
- typeName = _store.ReadString();
- }
- finally {
- _store.BaseStream.Position = oldPos;
- }
-
- AssemblyName an;
- String typePart;
- RuntimeType resourceType = (RuntimeType)Type.GetType(typeName, false);
- if (resourceType == null) {
- an = null;
- typePart = typeName;
- }
- else {
- // Enums should be safe to deserialize, and this helps out
- // partially trusted, localized WinForms apps.
- if (resourceType.BaseType == typeof(Enum)) {
- _safeToDeserialize[i] = true;
- continue;
- }
-
- // For most types, check our TypesSafeForDeserialization.
- typePart = resourceType.FullName;
-
- an = new AssemblyName();
-
- // resourceType is retrieved via Type.GetType and must be a RuntimeType
- RuntimeAssembly a = (RuntimeAssembly)resourceType.Assembly;
- an.Init(a.GetSimpleName(),
- a.GetPublicKey(),
- null, // public key token
- null, // version
- a.GetLocale(),
- AssemblyHashAlgorithm.None,
- AssemblyVersionCompatibility.SameMachine,
- null, // codebase
- AssemblyNameFlags.PublicKey,
- null); // strong name key pair
- }
-
- foreach(String safeType in TypesSafeForDeserialization) {
- if (ResourceManager.CompareNames(safeType, typePart, an)) {
-#if _DEBUG
- if (ResourceManager.DEBUG >= 7)
- Console.WriteLine("ResReader: Found a type-safe type to deserialize! Type name: {0}", typeName);
-#endif
- _safeToDeserialize[i] = true;
- continue;
- }
- }
-
-#if _DEBUG
- if (ResourceManager.DEBUG >= 7)
- if (!_safeToDeserialize[i])
- Console.WriteLine("ResReader: Found a type that wasn't safe to deserialize: {0}", typeName);
-#endif
- }
- }
-#endif // FEATURE_SERIALIZATION
public void GetResourceData(String resourceName, out String resourceType, out byte[] resourceData)
{
@@ -1224,72 +1047,6 @@ namespace System.Resources {
}
}
-#if FEATURE_SERIALIZATION
- // We need to build a type-limiting deserializer. We know exactly which
- // type we want to deserialize, and if someone tells us we have type X
- // (which might be safe to deserialize) and they give us a serialized
- // form of type Y, we don't want to run the deserialization constructor
- // because we've asserted serialization formatter permission. Instead,
- // limit the binary formatter's type binding to precisely the type we
- // expect. If they ever don't match, that's a corrupt .resources file.
- // We also must check the complete object graph to ensure all of the
- // graph contains safe objects.
- // Note this is tightly coupled to the BinaryFormatter, since we use
- // its internal ObjectReader::FastBindToType method, and we had to
- // change the ObjectReader to register itself with this type.
- internal sealed class TypeLimitingDeserializationBinder : SerializationBinder
- {
- private RuntimeType _typeToDeserialize;
- // This is tightly coupled with the binary formatter, because we
- // want to use exactly the same code found in the ObjectReader
- // to do the lookup, then just give a thumbs up or down based on
- // a type equality comparison. In the future, we could consider
- // some better refactoring of this code.
- private ObjectReader _objectReader;
-
- internal ObjectReader ObjectReader {
- get { return _objectReader; }
- set { _objectReader = value; }
- }
-
- internal void ExpectingToDeserialize(RuntimeType type)
- {
- _typeToDeserialize = type;
- }
-
- public override Type BindToType(string assemblyName, string typeName)
- {
- // BinaryObjectReader::Bind tries us first, then its own code.
- // Returning null means let the default binding rules happen.
- AssemblyName an = new AssemblyName(assemblyName);
-
- bool safe = false;
- foreach(String safeType in TypesSafeForDeserialization) {
- if (ResourceManager.CompareNames(safeType, typeName, an)) {
- safe = true;
- break;
- }
- }
-
- // WinForms types may internally use some enums that aren't
- // on our safe to deserialize list, like Font using FontStyle.
- Type t = ObjectReader.FastBindToType(assemblyName, typeName);
- if (t.IsEnum)
- safe = true;
-
- if (safe)
- return null;
-
- // Throw instead of returning null.
- // If you're looking at this in a debugger, you've either
- // got a malformed .resources file on your hands, or WinForms
- // types have taken a new dependency on another type. Check
- // whether assemblyName & typeName refer to a trustworthy type,
- // & consider adding it to the TypesSafeToDeserialize list.
- throw new BadImageFormatException(Environment.GetResourceString("BadImageFormat_ResType&SerBlobMismatch", _typeToDeserialize.FullName, typeName));
- }
- }
-#endif // FEATURE_SERIALIZATION
internal sealed class ResourceEnumerator : IDictionaryEnumerator
diff --git a/src/mscorlib/src/System/Resources/ResourceSet.cs b/src/mscorlib/src/System/Resources/ResourceSet.cs
index 1b272fc6ff..8fd9346f91 100644
--- a/src/mscorlib/src/System/Resources/ResourceSet.cs
+++ b/src/mscorlib/src/System/Resources/ResourceSet.cs
@@ -17,7 +17,6 @@ namespace System.Resources {
using System.Collections;
using System.IO;
using System.Globalization;
- using System.Security.Permissions;
using System.Runtime.InteropServices;
using System.Reflection;
using System.Runtime.Serialization;
@@ -31,7 +30,6 @@ namespace System.Resources {
// stores them in a hash table. Custom IResourceReaders can be used.
//
[Serializable]
- [System.Runtime.InteropServices.ComVisible(true)]
public class ResourceSet : IDisposable, IEnumerable
{
[NonSerialized] protected IResourceReader Reader;
@@ -158,7 +156,6 @@ namespace System.Resources {
#if LOOSELY_LINKED_RESOURCE_REFERENCE
// Optional - used for resolving assembly manifest resource references.
// This can safely be null.
- [ComVisible(false)]
public Assembly Assembly {
get { return _assembly; }
/*protected*/ set { _assembly = value; }
@@ -181,7 +178,6 @@ namespace System.Resources {
return Type.GetType("System.Resources.ResourceWriter, System.Resources.Writer, Version=4.0.1.0, Culture=neutral, PublicKeyToken=" + AssemblyRef.MicrosoftPublicKeyToken, throwOnError: true);
}
- [ComVisible(false)]
public virtual IDictionaryEnumerator GetEnumerator()
{
return GetEnumeratorHelper();
diff --git a/src/mscorlib/src/System/Resources/SatelliteContractVersionAttribute.cs b/src/mscorlib/src/System/Resources/SatelliteContractVersionAttribute.cs
index 327279062a..86e972efdd 100644
--- a/src/mscorlib/src/System/Resources/SatelliteContractVersionAttribute.cs
+++ b/src/mscorlib/src/System/Resources/SatelliteContractVersionAttribute.cs
@@ -19,7 +19,6 @@ namespace System.Resources {
using System.Diagnostics.Contracts;
[AttributeUsage(AttributeTargets.Assembly, AllowMultiple=false)]
-[System.Runtime.InteropServices.ComVisible(true)]
public sealed class SatelliteContractVersionAttribute : Attribute
{
private String _version;
diff --git a/src/mscorlib/src/System/Resources/UltimateResourceFallbackLocation.cs b/src/mscorlib/src/System/Resources/UltimateResourceFallbackLocation.cs
index 5785bfd357..aa4069a366 100644
--- a/src/mscorlib/src/System/Resources/UltimateResourceFallbackLocation.cs
+++ b/src/mscorlib/src/System/Resources/UltimateResourceFallbackLocation.cs
@@ -20,7 +20,6 @@ using System;
namespace System.Resources {
[Serializable]
-[System.Runtime.InteropServices.ComVisible(true)]
public enum UltimateResourceFallbackLocation
{
MainAssembly,
diff --git a/src/mscorlib/src/System/RtType.cs b/src/mscorlib/src/System/RtType.cs
index 168beefd4e..a24ee679d3 100644
--- a/src/mscorlib/src/System/RtType.cs
+++ b/src/mscorlib/src/System/RtType.cs
@@ -16,7 +16,6 @@ using System.Runtime.ConstrainedExecution;
using System.Globalization;
using System.Threading;
using System.Diagnostics;
-using System.Security.Permissions;
using System.Collections;
using System.Collections.Generic;
using System.Runtime;
@@ -343,7 +342,8 @@ namespace System
// no one should be looking for a member whose name is longer than 1024
if (cUtf8Name > MAXNAMELEN)
{
- fixed (byte* pUtf8Name = new byte[cUtf8Name])
+ byte[] utf8Name = new byte[cUtf8Name];
+ fixed (byte* pUtf8Name = &utf8Name[0])
{
list = GetListByName(pName, cNameLen, pUtf8Name, cUtf8Name, listType, cacheType);
}
@@ -403,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.
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
internal void Insert(ref T[] list, string name, MemberListType listType)
{
bool lockTaken = false;
@@ -481,7 +480,6 @@ namespace System
}
// Modifies the existing list.
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
private void MergeWithGlobalList(T[] list)
{
T[] cachedMembers = m_allMembers;
@@ -967,29 +965,6 @@ namespace System
}
}
- private static void AddElementTypes(Type template, IList<Type> types)
- {
- if (!template.HasElementType)
- return;
-
- AddElementTypes(template.GetElementType(), types);
-
- for (int i = 0; i < types.Count; i ++)
- {
- if (template.IsArray)
- {
- if (template.IsSzArray)
- types[i] = types[i].MakeArrayType();
- else
- types[i] = types[i].MakeArrayType(template.GetArrayRank());
- }
- else if (template.IsPointer)
- {
- types[i] = types[i].MakePointerType();
- }
- }
- }
-
private void AddSpecialInterface(ref ListBuilder<RuntimeType> list, Filter filter, RuntimeType iList, bool addSubInterface)
{
if (iList.IsAssignableFrom(ReflectedType))
@@ -1629,7 +1604,6 @@ namespace System
internal bool IsGlobal
{
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
get { return m_isGlobal; }
}
@@ -2524,8 +2498,6 @@ namespace System
private static readonly RuntimeType ObjectType = (RuntimeType)typeof(System.Object);
private static readonly RuntimeType StringType = (RuntimeType)typeof(System.String);
private static readonly RuntimeType DelegateType = (RuntimeType)typeof(System.Delegate);
-
- private static Type[] s_SICtorParamTypes;
#endregion
#region Constructor
@@ -2533,7 +2505,6 @@ namespace System
#endregion
#region Private\Internal Members
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
internal override bool CacheEquals(object o)
{
RuntimeType m = o as RuntimeType;
@@ -2753,7 +2724,6 @@ namespace System
return GetMethodCandidates(null, bindingAttr, CallingConventions.Any, null, false).ToArray();
}
-[System.Runtime.InteropServices.ComVisible(true)]
public override ConstructorInfo[] GetConstructors(BindingFlags bindingAttr)
{
return GetConstructorCandidates(null, bindingAttr, CallingConventions.Any, null, false).ToArray();
@@ -3246,7 +3216,6 @@ namespace System
}
}
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
internal sealed override RuntimeTypeHandle GetTypeHandleInternal()
{
return new RuntimeTypeHandle(this);
@@ -3342,7 +3311,6 @@ namespace System
return RuntimeTypeHandle.IsInstanceOfType(this, o);
}
- [System.Runtime.InteropServices.ComVisible(true)]
[Pure]
public override bool IsSubclassOf(Type type)
{
@@ -3582,11 +3550,6 @@ namespace System
#endif // FEATURE_COMINTEROP
- internal override bool HasProxyAttributeImpl()
- {
- return RuntimeTypeHandle.HasProxyAttribute(this);
- }
-
internal bool IsDelegate()
{
return GetBaseType() == typeof(System.MulticastDelegate);
@@ -4784,33 +4747,6 @@ namespace System
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();
-#pragma warning restore 618
- }
- catch
- {
- throw new NotSupportedException(String.Format(CultureInfo.CurrentCulture, Environment.GetResourceString("NotSupported_DelegateCreationFromPT")));
- }
- }
-
if (invokeMethod.GetParametersNoCopy().Length == 0)
{
if (args.Length != 0)
@@ -4868,17 +4804,8 @@ namespace System
readonly ActivatorCacheEntry[] cache = new ActivatorCacheEntry[CACHE_SIZE];
volatile ConstructorInfo delegateCtorInfo;
- volatile PermissionSet delegateCreatePermissions;
private void InitializeDelegateCreator() {
- // No synchronization needed here. In the worst case we create extra garbage
- PermissionSet ps = new PermissionSet(PermissionState.None);
- ps.AddPermission(new ReflectionPermission(ReflectionPermissionFlag.MemberAccess));
-#pragma warning disable 618
- ps.AddPermission(new SecurityPermission(SecurityPermissionFlag.UnmanagedCode));
-#pragma warning restore 618
- delegateCreatePermissions = ps;
-
ConstructorInfo ctorInfo = typeof(CtorDelegate).GetConstructor(new Type[] {typeof(Object), typeof(IntPtr)});
delegateCtorInfo = ctorInfo; // this assignment should be last
}
@@ -4891,7 +4818,6 @@ namespace System
if (delegateCtorInfo == null)
InitializeDelegateCreator();
- delegateCreatePermissions.Assert();
// No synchronization needed here. In the worst case we create extra garbage
CtorDelegate ctor = (CtorDelegate)delegateCtorInfo.Invoke(new Object[] { null, RuntimeMethodHandle.GetFunctionPointer(ace.m_hCtorMethodHandle) });
@@ -5045,10 +4971,12 @@ namespace System
return _CreateEnum(enumType, value);
}
+#if FEATURE_COMINTEROP
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private extern Object InvokeDispMethod(
String name, BindingFlags invokeAttr, Object target, Object[] args,
bool[] byrefModifiers, int culture, String[] namedParameters);
+#endif // FEATURE_COMINTEROP
#if FEATURE_COMINTEROP_UNMANAGED_ACTIVATION
[MethodImplAttribute(MethodImplOptions.InternalCall)]
diff --git a/src/mscorlib/src/System/Runtime/CompilerServices/AccessedThroughPropertyAttribute.cs b/src/mscorlib/src/System/Runtime/CompilerServices/AccessedThroughPropertyAttribute.cs
index b0010fd7bd..34e66beade 100644
--- a/src/mscorlib/src/System/Runtime/CompilerServices/AccessedThroughPropertyAttribute.cs
+++ b/src/mscorlib/src/System/Runtime/CompilerServices/AccessedThroughPropertyAttribute.cs
@@ -9,7 +9,6 @@ namespace System.Runtime.CompilerServices
using System;
[AttributeUsage(AttributeTargets.Field)]
-[System.Runtime.InteropServices.ComVisible(true)]
public sealed class AccessedThroughPropertyAttribute : Attribute
{
private readonly string propertyName;
diff --git a/src/mscorlib/src/System/Runtime/CompilerServices/AssemblyAttributesGoHere.cs b/src/mscorlib/src/System/Runtime/CompilerServices/AssemblyAttributesGoHere.cs
deleted file mode 100644
index c021353475..0000000000
--- a/src/mscorlib/src/System/Runtime/CompilerServices/AssemblyAttributesGoHere.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.
-
-////////////////////////////////////////////////////////////////////////////////
-////////////////////////////////////////////////////////////////////////////////
-namespace System.Runtime.CompilerServices {
-
- using System;
-
- // NOTE TO DEVELOPERS: These classes are used by ALink (the assembly linker).
- // They're used for metadata tokens for making multi-module assemblies.
- // Do not randomly touch these classes.
- [System.Runtime.CompilerServices.FriendAccessAllowed]
- internal sealed class AssemblyAttributesGoHere
- {
-
- internal AssemblyAttributesGoHere()
- {
- }
- }
- [System.Runtime.CompilerServices.FriendAccessAllowed]
- internal sealed class AssemblyAttributesGoHereS
- {
- internal AssemblyAttributesGoHereS()
- {
- }
- }
- [System.Runtime.CompilerServices.FriendAccessAllowed]
- internal sealed class AssemblyAttributesGoHereM
- {
- internal AssemblyAttributesGoHereM()
- {
- }
- }
- [System.Runtime.CompilerServices.FriendAccessAllowed]
- internal sealed class AssemblyAttributesGoHereSM
- {
- internal AssemblyAttributesGoHereSM()
- {
- }
- }
-}
diff --git a/src/mscorlib/src/System/Runtime/CompilerServices/AsyncMethodBuilder.cs b/src/mscorlib/src/System/Runtime/CompilerServices/AsyncMethodBuilder.cs
index 6a16462383..afb0c22778 100644
--- a/src/mscorlib/src/System/Runtime/CompilerServices/AsyncMethodBuilder.cs
+++ b/src/mscorlib/src/System/Runtime/CompilerServices/AsyncMethodBuilder.cs
@@ -18,7 +18,6 @@ using System.Diagnostics.CodeAnalysis;
using System.Diagnostics.Contracts;
using System.Runtime.ExceptionServices;
using System.Security;
-using System.Security.Permissions;
using System.Threading;
using System.Threading.Tasks;
@@ -840,36 +839,6 @@ namespace System.Runtime.CompilerServices
// This method is copy&pasted into the public Start methods to avoid size overhead of valuetype generic instantiations.
// Ideally, we would build intrinsics to get the raw ref address and raw code address of MoveNext, and just use the shared implementation.
-#if false
- /// <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>
- /// <exception cref="System.ArgumentNullException">The <paramref name="stateMachine"/> argument is null (Nothing in Visual Basic).</exception>
- [DebuggerStepThrough]
- internal static void Start<TStateMachine>(ref TStateMachine stateMachine)
- where TStateMachine : IAsyncStateMachine
- {
- if (stateMachine == null) throw new ArgumentNullException(nameof(stateMachine));
- Contract.EndContractBlock();
-
- // Run the MoveNext method within a copy-on-write ExecutionContext scope.
- // This allows us to undo any ExecutionContext changes made in MoveNext,
- // so that they won't "leak" out of the first await.
-
- Thread currentThread = Thread.CurrentThread;
- ExecutionContextSwitcher ecs = default(ExecutionContextSwitcher);
- RuntimeHelpers.PrepareConstrainedRegions();
- try
- {
- ExecutionContext.EstablishCopyOnWriteScope(currentThread, ref ecs);
- stateMachine.MoveNext();
- }
- finally
- {
- ecs.Undo(currentThread);
- }
- }
-#endif
/// <summary>Associates the builder with the state machine it represents.</summary>
/// <param name="stateMachine">The heap-allocated state machine object.</param>
@@ -906,12 +875,12 @@ namespace System.Runtime.CompilerServices
Debugger.NotifyOfCrossThreadDependency();
// The builder needs to flow ExecutionContext, so capture it.
- var capturedContext = ExecutionContext.FastCapture(); // ok to use FastCapture as we haven't made any permission demands/asserts
+ var capturedContext = ExecutionContext.Capture();
// If the ExecutionContext is the default context, try to use a cached delegate, creating one if necessary.
Action action;
MoveNextRunner runner;
- if (capturedContext != null && capturedContext.IsPreAllocatedDefault)
+ if (capturedContext == ExecutionContext.Default)
{
// Get the cached delegate, and if it's non-null, return it.
action = m_defaultContextAction;
@@ -1046,12 +1015,8 @@ namespace System.Runtime.CompilerServices
if (m_context != null)
{
- try
- {
- // Use the context and callback to invoke m_stateMachine.MoveNext.
- ExecutionContext.Run(m_context, InvokeMoveNextCallback, m_stateMachine, preserveSyncCtx: true);
- }
- finally { m_context.Dispose(); }
+ // Use the context and callback to invoke m_stateMachine.MoveNext.
+ ExecutionContext.Run(m_context, InvokeMoveNextCallback, m_stateMachine);
}
else
{
@@ -1076,24 +1041,11 @@ namespace System.Runtime.CompilerServices
internal void RunWithDefaultContext()
{
Debug.Assert(m_stateMachine != null, "The state machine must have been set before calling Run.");
- ExecutionContext.Run(ExecutionContext.PreAllocatedDefault, InvokeMoveNextCallback, m_stateMachine, preserveSyncCtx: true);
+ ExecutionContext.Run(ExecutionContext.Default, InvokeMoveNextCallback, m_stateMachine);
}
/// <summary>Gets a delegate to the InvokeMoveNext method.</summary>
- protected static ContextCallback InvokeMoveNextCallback
- {
- get { return s_invokeMoveNext ?? (s_invokeMoveNext = InvokeMoveNext); }
- }
-
- /// <summary>Cached delegate used with ExecutionContext.Run.</summary>
- 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>
- private static void InvokeMoveNext(object stateMachine)
- {
- ((IAsyncStateMachine)stateMachine).MoveNext();
- }
+ protected static readonly ContextCallback InvokeMoveNextCallback = sm => ((IAsyncStateMachine)sm).MoveNext();
}
/// <summary>
diff --git a/src/mscorlib/src/System/Runtime/CompilerServices/CompilationRelaxations.cs b/src/mscorlib/src/System/Runtime/CompilerServices/CompilationRelaxations.cs
index 5e4f19410b..c3679b610c 100644
--- a/src/mscorlib/src/System/Runtime/CompilerServices/CompilationRelaxations.cs
+++ b/src/mscorlib/src/System/Runtime/CompilerServices/CompilationRelaxations.cs
@@ -13,7 +13,6 @@ namespace System.Runtime.CompilerServices
/// IMPORTANT: Keep this in sync with corhdr.h
[Serializable]
[Flags]
-[System.Runtime.InteropServices.ComVisible(true)]
public enum CompilationRelaxations : int
{
NoStringInterning = 0x0008, // Start in 0x0008, we had other non public flags in this enum before,
@@ -23,7 +22,6 @@ namespace System.Runtime.CompilerServices
[Serializable]
[AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Module | AttributeTargets.Class | AttributeTargets.Method)]
-[System.Runtime.InteropServices.ComVisible(true)]
public class CompilationRelaxationsAttribute : Attribute
{
private int m_relaxations; // The relaxations.
diff --git a/src/mscorlib/src/System/Runtime/CompilerServices/CompilerGlobalScopeAttribute.cs b/src/mscorlib/src/System/Runtime/CompilerServices/CompilerGlobalScopeAttribute.cs
index 65755f6baa..1cd830cfca 100644
--- a/src/mscorlib/src/System/Runtime/CompilerServices/CompilerGlobalScopeAttribute.cs
+++ b/src/mscorlib/src/System/Runtime/CompilerServices/CompilerGlobalScopeAttribute.cs
@@ -18,7 +18,6 @@ namespace System.Runtime.CompilerServices
{
[Serializable]
[AttributeUsage(AttributeTargets.Class)]
- [System.Runtime.InteropServices.ComVisible(true)]
public class CompilerGlobalScopeAttribute : Attribute
{
public CompilerGlobalScopeAttribute () {}
diff --git a/src/mscorlib/src/System/Runtime/CompilerServices/ConditionalWeakTable.cs b/src/mscorlib/src/System/Runtime/CompilerServices/ConditionalWeakTable.cs
index 74559673bb..4b2648ba6f 100644
--- a/src/mscorlib/src/System/Runtime/CompilerServices/ConditionalWeakTable.cs
+++ b/src/mscorlib/src/System/Runtime/CompilerServices/ConditionalWeakTable.cs
@@ -46,7 +46,6 @@
** expose the full public surface area.
**
**
-**
** Thread safety guarantees:
**
** ConditionalWeakTable is fully thread-safe and requires no
@@ -60,6 +59,7 @@
** may be delayed until appdomain shutdown.
===========================================================*/
+using System.Collections;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Threading;
@@ -67,8 +67,7 @@ using System.Threading;
namespace System.Runtime.CompilerServices
{
#region ConditionalWeakTable
- [ComVisible(false)]
- public sealed class ConditionalWeakTable<TKey, TValue>
+ public sealed class ConditionalWeakTable<TKey, TValue> : IEnumerable<KeyValuePair<TKey, TValue>>
where TKey : class
where TValue : class
{
@@ -76,6 +75,7 @@ namespace System.Runtime.CompilerServices
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.
+ private int _activeEnumeratorRefCount; // The number of outstanding enumerators on the table
#endregion
#region Constructors
@@ -190,6 +190,34 @@ namespace System.Runtime.CompilerServices
}
}
+ //--------------------------------------------------------------------------------------------
+ // Clear all the key/value pairs
+ //--------------------------------------------------------------------------------------------
+ public void Clear()
+ {
+ lock (_lock)
+ {
+ // To clear, we would prefer to simply drop the existing container
+ // and replace it with an empty one, as that's overall more efficient.
+ // However, if there are any active enumerators, we don't want to do
+ // that as it will end up removing all of the existing entries and
+ // allowing new items to be added at the same indices when the container
+ // is filled and replaced, and one of the guarantees we try to make with
+ // enumeration is that new items added after enumeration starts won't be
+ // included in the enumeration. As such, if there are active enumerators,
+ // we simply use the container's removal functionality to remove all of the
+ // keys; then when the table is resized, if there are still active enumerators,
+ // these empty slots will be maintained.
+ if (_activeEnumeratorRefCount > 0)
+ {
+ _container.RemoveAllKeys();
+ }
+ else
+ {
+ _container = new Container(this);
+ }
+ }
+ }
//--------------------------------------------------------------------------------------------
// key: key of the value to find. Cannot be null.
@@ -256,6 +284,148 @@ namespace System.Runtime.CompilerServices
public delegate TValue CreateValueCallback(TKey key);
+ //--------------------------------------------------------------------------------------------
+ // Gets an enumerator for the table. The returned enumerator will not extend the lifetime of
+ // any object pairs in the table, other than the one that's Current. It will not return entries
+ // that have already been collected, nor will it return entries added after the enumerator was
+ // retrieved. It may not return all entries that were present when the enumerat was retrieved,
+ // however, such as not returning entries that were collected or removed after the enumerator
+ // was retrieved but before they were enumerated.
+ //--------------------------------------------------------------------------------------------
+ IEnumerator<KeyValuePair<TKey, TValue>> IEnumerable<KeyValuePair<TKey, TValue>>.GetEnumerator()
+ {
+ lock (_lock)
+ {
+ Container c = _container;
+ return c == null || c.FirstFreeEntry == 0 ?
+ ((IEnumerable<KeyValuePair<TKey, TValue>>)Array.Empty<KeyValuePair<TKey, TValue>>()).GetEnumerator() :
+ new Enumerator(this);
+ }
+ }
+
+ IEnumerator IEnumerable.GetEnumerator() => ((IEnumerable<KeyValuePair<TKey, TValue>>)this).GetEnumerator();
+
+ /// <summary>Provides an enumerator for the table.</summary>
+ private sealed class Enumerator : IEnumerator<KeyValuePair<TKey, TValue>>
+ {
+ // The enumerator would ideally hold a reference to the Container and the end index within that
+ // container. However, the safety of the CWT depends on the only reference to the Container being
+ // from the CWT itself; the Container then employs a two-phase finalization scheme, where the first
+ // phase nulls out that parent CWT's reference, guaranteeing that the second time it's finalized there
+ // can be no other existing references to it in use that would allow for concurrent usage of the
+ // native handles with finalization. We would break that if we allowed this Enumerator to hold a
+ // reference to the Container. Instead, the Enumerator holds a reference to the CWT rather than to
+ // the Container, and it maintains the CWT._activeEnumeratorRefCount field to track whether there
+ // are outstanding enumerators that have yet to be disposed/finalized. If there aren't any, the CWT
+ // behaves as it normally does. If there are, certain operations are affected, in particular resizes.
+ // Normally when the CWT is resized, it enumerates the contents of the table looking for indices that
+ // contain entries which have been collected or removed, and it frees those up, effectively moving
+ // down all subsequent entries in the container (not in the existing container, but in a replacement).
+ // This, however, would cause the enumerator's understanding of indices to break. So, as long as
+ // there is any outstanding enumerator, no compaction is performed.
+
+ private ConditionalWeakTable<TKey, TValue> _table; // parent table, set to null when disposed
+ private readonly int _maxIndexInclusive; // last index in the container that should be enumerated
+ private int _currentIndex = -1; // the current index into the container
+ private KeyValuePair<TKey, TValue> _current; // the current entry set by MoveNext and returned from Current
+
+ public Enumerator(ConditionalWeakTable<TKey, TValue> table)
+ {
+ Debug.Assert(table != null, "Must provide a valid table");
+ Debug.Assert(Monitor.IsEntered(table._lock), "Must hold the _lock lock to construct the enumerator");
+ Debug.Assert(table._container != null, "Should not be used on a finalized table");
+ Debug.Assert(table._container.FirstFreeEntry > 0, "Should have returned an empty enumerator instead");
+
+ // Store a reference to the parent table and increase its active enumerator count.
+ _table = table;
+ Debug.Assert(table._activeEnumeratorRefCount >= 0, "Should never have a negative ref count before incrementing");
+ table._activeEnumeratorRefCount++;
+
+ // Store the max index to be enumerated.
+ _maxIndexInclusive = table._container.FirstFreeEntry - 1;
+ _currentIndex = -1;
+ }
+
+ ~Enumerator() { Dispose(); }
+
+ public void Dispose()
+ {
+ // Use an interlocked operation to ensure that only one thread can get access to
+ // the _table for disposal and thus only decrement the ref count once.
+ ConditionalWeakTable<TKey, TValue> table = Interlocked.Exchange(ref _table, null);
+ if (table != null)
+ {
+ // Ensure we don't keep the last current alive unnecessarily
+ _current = default(KeyValuePair<TKey, TValue>);
+
+ // Decrement the ref count that was incremented when constructed
+ lock (table._lock)
+ {
+ table._activeEnumeratorRefCount--;
+ Debug.Assert(table._activeEnumeratorRefCount >= 0, "Should never have a negative ref count after decrementing");
+ }
+
+ // Finalization is purely to decrement the ref count. We can suppress it now.
+ GC.SuppressFinalize(this);
+ }
+ }
+
+ public bool MoveNext()
+ {
+ // Start by getting the current table. If it's already been disposed, it will be null.
+ ConditionalWeakTable<TKey, TValue> table = _table;
+ if (table != null)
+ {
+ // Once have the table, we need to lock to synchronize with other operations on
+ // the table, like adding.
+ lock (table._lock)
+ {
+ // From the table, we have to get the current container. This could have changed
+ // since we grabbed the enumerator, but the index-to-pair mapping should not have
+ // due to there being at least one active enumerator. If the table (or rather its
+ // container at the time) has already been finalized, this will be null.
+ Container c = table._container;
+ if (c != null)
+ {
+ // We have the container. Find the next entry to return, if there is one.
+ // We need to loop as we may try to get an entry that's already been removed
+ // or collected, in which case we try again.
+ while (_currentIndex < _maxIndexInclusive)
+ {
+ _currentIndex++;
+ TKey key;
+ TValue value;
+ if (c.TryGetEntry(_currentIndex, out key, out value))
+ {
+ _current = new KeyValuePair<TKey, TValue>(key, value);
+ return true;
+ }
+ }
+ }
+ }
+ }
+
+ // Nothing more to enumerate.
+ return false;
+ }
+
+ public KeyValuePair<TKey, TValue> Current
+ {
+ get
+ {
+ if (_currentIndex < 0)
+ {
+ ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumOpCantHappen();
+ }
+ return _current;
+ }
+ }
+
+ object IEnumerator.Current => Current;
+
+ public void Reset() { }
+ }
+
#endregion
#region Internal members
@@ -305,17 +475,6 @@ namespace System.Runtime.CompilerServices
}
}
- //--------------------------------------------------------------------------------------------
- // Clear all the key/value pairs
- //--------------------------------------------------------------------------------------------
- internal void Clear()
- {
- lock (_lock)
- {
- _container = new Container(this);
- }
- }
-
#endregion
#region Private Members
@@ -435,6 +594,8 @@ namespace System.Runtime.CompilerServices
internal bool HasCapacity => _firstFreeEntry < _entries.Length;
+ internal int FirstFreeEntry => _firstFreeEntry;
+
//----------------------------------------------------------------------------------------
// Worker for adding a new key/value pair.
// Preconditions:
@@ -508,6 +669,44 @@ namespace System.Runtime.CompilerServices
return -1;
}
+ //----------------------------------------------------------------------------------------
+ // Gets the entry at the specified entry index.
+ //----------------------------------------------------------------------------------------
+ internal bool TryGetEntry(int index, out TKey key, out TValue value)
+ {
+ if (index < _entries.Length)
+ {
+ object oKey, oValue;
+ _entries[index].depHnd.GetPrimaryAndSecondary(out oKey, out oValue);
+ GC.KeepAlive(this); // ensure we don't get finalized while accessing DependentHandles.
+
+ if (oKey != null)
+ {
+ key = JitHelpers.UnsafeCast<TKey>(oKey);
+ value = JitHelpers.UnsafeCast<TValue>(oValue);
+ return true;
+ }
+ }
+
+ key = default(TKey);
+ value = default(TValue);
+ return false;
+ }
+
+ //----------------------------------------------------------------------------------------
+ // Removes all of the keys in the table.
+ //----------------------------------------------------------------------------------------
+ internal void RemoveAllKeys()
+ {
+ for (int i = 0; i < _firstFreeEntry; i++)
+ {
+ RemoveIndex(i);
+ }
+ }
+
+ //----------------------------------------------------------------------------------------
+ // Removes the specified key from the table, if it exists.
+ //----------------------------------------------------------------------------------------
internal bool Remove(TKey key)
{
VerifyIntegrity();
@@ -516,22 +715,27 @@ namespace System.Runtime.CompilerServices
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);
-
+ RemoveIndex(entryIndex);
return true;
}
return false;
}
+ private void RemoveIndex(int entryIndex)
+ {
+ Debug.Assert(entryIndex >= 0 && entryIndex < _firstFreeEntry);
+
+ 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);
+ }
internal void UpdateValue(int entryIndex, TValue newValue)
{
@@ -556,25 +760,33 @@ namespace System.Runtime.CompilerServices
//----------------------------------------------------------------------------------------
internal Container Resize()
{
- // Start by assuming we won't resize.
- int newSize = _buckets.Length;
+ Debug.Assert(!HasCapacity);
- // If any expired or removed keys exist, we won't resize.
bool hasExpiredEntries = false;
- for (int entriesIndex = 0; entriesIndex < _entries.Length; entriesIndex++)
+ int newSize = _buckets.Length;
+
+ if (_parent == null || _parent._activeEnumeratorRefCount == 0)
{
- if (_entries[entriesIndex].HashCode == -1)
+ // If any expired or removed keys exist, we won't resize.
+ // If there any active enumerators, though, we don't want
+ // to compact and thus have no expired entries.
+ for (int entriesIndex = 0; entriesIndex < _entries.Length; entriesIndex++)
{
- // the entry was removed
- hasExpiredEntries = true;
- break;
- }
+ ref Entry entry = ref _entries[entriesIndex];
- if (_entries[entriesIndex].depHnd.IsAllocated && _entries[entriesIndex].depHnd.GetPrimary() == null)
- {
- // the entry has expired
- hasExpiredEntries = true;
- break;
+ if (entry.HashCode == -1)
+ {
+ // the entry was removed
+ hasExpiredEntries = true;
+ break;
+ }
+
+ if (entry.depHnd.IsAllocated && entry.depHnd.GetPrimary() == null)
+ {
+ // the entry has expired
+ hasExpiredEntries = true;
+ break;
+ }
}
}
@@ -585,44 +797,73 @@ namespace System.Runtime.CompilerServices
}
return Resize(newSize);
- }
+ }
internal Container Resize(int newSize)
{
+ Debug.Assert(newSize >= _buckets.Length);
Debug.Assert(IsPowerOfTwo(newSize));
// 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++)
+ for (int bucketIndex = 0; bucketIndex < newBuckets.Length; bucketIndex++)
{
newBuckets[bucketIndex] = -1;
}
Entry[] newEntries = new Entry[newSize];
int newEntriesIndex = 0;
+ bool activeEnumerators = _parent != null && _parent._activeEnumeratorRefCount > 0;
// Migrate existing entries to the new table.
- for (int entriesIndex = 0; entriesIndex < _entries.Length; entriesIndex++)
+ if (activeEnumerators)
{
- int hashCode = _entries[entriesIndex].HashCode;
- DependentHandle depHnd = _entries[entriesIndex].depHnd;
- if (hashCode != -1 && depHnd.IsAllocated)
+ // There's at least one active enumerator, which means we don't want to
+ // remove any expired/removed entries, in order to not affect existing
+ // entries indices. Copy over the entries while rebuilding the buckets list,
+ // as the buckets are dependent on the buckets list length, which is changing.
+ for (; newEntriesIndex < _entries.Length; newEntriesIndex++)
{
- 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
+ ref Entry oldEntry = ref _entries[newEntriesIndex];
+ ref Entry newEntry = ref newEntries[newEntriesIndex];
+ int hashCode = oldEntry.HashCode;
+
+ newEntry.HashCode = hashCode;
+ newEntry.depHnd = oldEntry.depHnd;
+ int bucket = hashCode & (newBuckets.Length - 1);
+ newEntry.Next = newBuckets[bucket];
+ newBuckets[bucket] = newEntriesIndex;
+ }
+ }
+ else
+ {
+ // There are no active enumerators, which means we want to compact by
+ // removing expired/removed entries.
+ for (int entriesIndex = 0; entriesIndex < _entries.Length; entriesIndex++)
+ {
+ ref Entry oldEntry = ref _entries[entriesIndex];
+ int hashCode = oldEntry.HashCode;
+ DependentHandle depHnd = oldEntry.depHnd;
+ if (hashCode != -1 && depHnd.IsAllocated)
{
- // Pretend the item was removed, so that this container's finalizer
- // will clean up this dependent handle.
- Volatile.Write(ref _entries[entriesIndex].HashCode, -1);
+ if (depHnd.GetPrimary() != null)
+ {
+ ref Entry newEntry = ref newEntries[newEntriesIndex];
+
+ // Entry is used and has not expired. Link it into the appropriate bucket list.
+ newEntry.HashCode = hashCode;
+ newEntry.depHnd = depHnd;
+ int bucket = hashCode & (newBuckets.Length - 1);
+ newEntry.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 oldEntry.HashCode, -1);
+ }
}
}
}
@@ -632,6 +873,14 @@ namespace System.Runtime.CompilerServices
// 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);
+ if (activeEnumerators)
+ {
+ // If there are active enumerators, both the old container and the new container may be storing
+ // the same entries with -1 hash codes, which the finalizer will clean up even if the container
+ // is not the active container for the table. To prevent that, we want to stop the old container
+ // from being finalized, as it no longer has any responsibility for any cleanup.
+ GC.SuppressFinalize(this);
+ }
_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.
@@ -815,7 +1064,6 @@ namespace System.Runtime.CompilerServices
// This struct intentionally does no self-synchronization. It's up to the caller to
// to use DependentHandles in a thread-safe way.
//=========================================================================================
- [ComVisible(false)]
internal struct DependentHandle
{
#region Constructors
diff --git a/src/mscorlib/src/System/Runtime/CompilerServices/CustomConstantAttribute.cs b/src/mscorlib/src/System/Runtime/CompilerServices/CustomConstantAttribute.cs
index c912095bda..1a5dcfdc11 100644
--- a/src/mscorlib/src/System/Runtime/CompilerServices/CustomConstantAttribute.cs
+++ b/src/mscorlib/src/System/Runtime/CompilerServices/CustomConstantAttribute.cs
@@ -9,7 +9,6 @@ namespace System.Runtime.CompilerServices
{
[Serializable]
[AttributeUsage(AttributeTargets.Field | AttributeTargets.Parameter, Inherited=false)]
- [System.Runtime.InteropServices.ComVisible(true)]
public abstract class CustomConstantAttribute : Attribute
{
public abstract Object Value { get; }
diff --git a/src/mscorlib/src/System/Runtime/CompilerServices/DateTimeConstantAttribute.cs b/src/mscorlib/src/System/Runtime/CompilerServices/DateTimeConstantAttribute.cs
index 4362aa84a1..148d916be1 100644
--- a/src/mscorlib/src/System/Runtime/CompilerServices/DateTimeConstantAttribute.cs
+++ b/src/mscorlib/src/System/Runtime/CompilerServices/DateTimeConstantAttribute.cs
@@ -9,7 +9,6 @@ namespace System.Runtime.CompilerServices
{
[Serializable]
[AttributeUsage(AttributeTargets.Field | AttributeTargets.Parameter, Inherited=false)]
- [System.Runtime.InteropServices.ComVisible(true)]
public sealed class DateTimeConstantAttribute : CustomConstantAttribute
{
public DateTimeConstantAttribute(long ticks)
diff --git a/src/mscorlib/src/System/Runtime/CompilerServices/DecimalConstantAttribute.cs b/src/mscorlib/src/System/Runtime/CompilerServices/DecimalConstantAttribute.cs
index 7bfaa7aafd..f05191840d 100644
--- a/src/mscorlib/src/System/Runtime/CompilerServices/DecimalConstantAttribute.cs
+++ b/src/mscorlib/src/System/Runtime/CompilerServices/DecimalConstantAttribute.cs
@@ -14,7 +14,6 @@ namespace System.Runtime.CompilerServices
{
[Serializable]
[AttributeUsage(AttributeTargets.Field | AttributeTargets.Parameter, Inherited=false)]
- [System.Runtime.InteropServices.ComVisible(true)]
public sealed class DecimalConstantAttribute : Attribute
{
[CLSCompliant(false)]
diff --git a/src/mscorlib/src/System/Runtime/CompilerServices/DecoratedNameAttribute.cs b/src/mscorlib/src/System/Runtime/CompilerServices/DecoratedNameAttribute.cs
deleted file mode 100644
index 75558d4e7e..0000000000
--- a/src/mscorlib/src/System/Runtime/CompilerServices/DecoratedNameAttribute.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.
-
-using System;
-using System.Runtime.InteropServices;
-
-namespace System.Runtime.CompilerServices
-{
- [AttributeUsage(AttributeTargets.All),
- ComVisible(false)]
- internal sealed class DecoratedNameAttribute : Attribute
- {
- public DecoratedNameAttribute(string decoratedName)
- {}
- }
-}
-
diff --git a/src/mscorlib/src/System/Runtime/CompilerServices/DiscardableAttribute.cs b/src/mscorlib/src/System/Runtime/CompilerServices/DiscardableAttribute.cs
index 303151f576..3fda4624d4 100644
--- a/src/mscorlib/src/System/Runtime/CompilerServices/DiscardableAttribute.cs
+++ b/src/mscorlib/src/System/Runtime/CompilerServices/DiscardableAttribute.cs
@@ -9,7 +9,6 @@ namespace System.Runtime.CompilerServices {
using System;
// Custom attribute to indicating a TypeDef is a discardable attribute
-[System.Runtime.InteropServices.ComVisible(true)]
public class DiscardableAttribute : Attribute
{
public DiscardableAttribute()
diff --git a/src/mscorlib/src/System/Runtime/CompilerServices/ITuple.cs b/src/mscorlib/src/System/Runtime/CompilerServices/ITuple.cs
new file mode 100644
index 0000000000..cafee11f8a
--- /dev/null
+++ b/src/mscorlib/src/System/Runtime/CompilerServices/ITuple.cs
@@ -0,0 +1,22 @@
+// 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
+{
+ /// <summary>
+ /// This interface is required for types that want to be indexed into by dynamic patterns.
+ /// </summary>
+ public interface ITuple
+ {
+ /// <summary>
+ /// The number of positions in this data structure.
+ /// </summary>
+ int Length { get; }
+
+ /// <summary>
+ /// Get the element at position <param name="index"/>.
+ /// </summary>
+ object this[int index] { get; }
+ }
+}
diff --git a/src/mscorlib/src/System/Runtime/CompilerServices/IndexerNameAttribute.cs b/src/mscorlib/src/System/Runtime/CompilerServices/IndexerNameAttribute.cs
index 0323fe0cf6..c32be6f3a2 100644
--- a/src/mscorlib/src/System/Runtime/CompilerServices/IndexerNameAttribute.cs
+++ b/src/mscorlib/src/System/Runtime/CompilerServices/IndexerNameAttribute.cs
@@ -8,7 +8,6 @@ namespace System.Runtime.CompilerServices
[Serializable]
[AttributeUsage(AttributeTargets.Property, Inherited = true)]
-[System.Runtime.InteropServices.ComVisible(true)]
public sealed class IndexerNameAttribute: Attribute
{
public IndexerNameAttribute(String indexerName)
diff --git a/src/mscorlib/src/System/Runtime/CompilerServices/IsVolatile.cs b/src/mscorlib/src/System/Runtime/CompilerServices/IsVolatile.cs
index ea2fe032c6..5287e82b7b 100644
--- a/src/mscorlib/src/System/Runtime/CompilerServices/IsVolatile.cs
+++ b/src/mscorlib/src/System/Runtime/CompilerServices/IsVolatile.cs
@@ -4,7 +4,6 @@
namespace System.Runtime.CompilerServices
{
-[System.Runtime.InteropServices.ComVisible(true)]
public static class IsVolatile
{
// no instantiation, please!
diff --git a/src/mscorlib/src/System/Runtime/CompilerServices/MethodImplAttribute.cs b/src/mscorlib/src/System/Runtime/CompilerServices/MethodImplAttribute.cs
index d081d70070..b4991110f8 100644
--- a/src/mscorlib/src/System/Runtime/CompilerServices/MethodImplAttribute.cs
+++ b/src/mscorlib/src/System/Runtime/CompilerServices/MethodImplAttribute.cs
@@ -12,7 +12,6 @@ namespace System.Runtime.CompilerServices {
[Serializable]
[Flags]
-[System.Runtime.InteropServices.ComVisible(true)]
public enum MethodImplOptions
{
Unmanaged = System.Reflection.MethodImplAttributes.Unmanaged,
@@ -21,14 +20,12 @@ namespace System.Runtime.CompilerServices {
InternalCall = System.Reflection.MethodImplAttributes.InternalCall,
Synchronized = System.Reflection.MethodImplAttributes.Synchronized,
NoInlining = System.Reflection.MethodImplAttributes.NoInlining,
- [System.Runtime.InteropServices.ComVisible(false)]
AggressiveInlining = System.Reflection.MethodImplAttributes.AggressiveInlining,
NoOptimization = System.Reflection.MethodImplAttributes.NoOptimization,
// **** If you add something, update internal MethodImplAttribute(MethodImplAttributes methodImplAttributes)! ****
}
[Serializable]
-[System.Runtime.InteropServices.ComVisible(true)]
public enum MethodCodeType
{
IL = System.Reflection.MethodImplAttributes.IL,
@@ -41,7 +38,6 @@ namespace System.Runtime.CompilerServices {
// Custom attribute to specify additional method properties.
[Serializable]
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Constructor, Inherited = false)]
-[System.Runtime.InteropServices.ComVisible(true)]
sealed public class MethodImplAttribute : Attribute
{
internal MethodImplOptions _val;
diff --git a/src/mscorlib/src/System/Runtime/CompilerServices/RuntimeHelpers.cs b/src/mscorlib/src/System/Runtime/CompilerServices/RuntimeHelpers.cs
index 926eb6c3cb..509e527ecb 100644
--- a/src/mscorlib/src/System/Runtime/CompilerServices/RuntimeHelpers.cs
+++ b/src/mscorlib/src/System/Runtime/CompilerServices/RuntimeHelpers.cs
@@ -18,7 +18,6 @@ namespace System.Runtime.CompilerServices {
using System.Runtime.InteropServices;
using System.Runtime.ConstrainedExecution;
using System.Runtime.Serialization;
- using System.Security.Permissions;
using System.Threading;
using System.Runtime.Versioning;
using System.Diagnostics.Contracts;
@@ -131,7 +130,6 @@ namespace System.Runtime.CompilerServices {
// Note: this method is not part of the CER support, and is not to be confused with ProbeForSufficientStack
// below.
[MethodImplAttribute(MethodImplOptions.InternalCall)]
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
public static extern void EnsureSufficientExecutionStack();
// This method ensures that there is sufficient stack to execute the average Framework function.
@@ -139,7 +137,6 @@ namespace System.Runtime.CompilerServices {
// Note: this method is not part of the CER support, and is not to be confused with ProbeForSufficientStack
// below.
[MethodImplAttribute(MethodImplOptions.InternalCall)]
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
public static extern bool TryEnsureSufficientExecutionStack();
public static void ProbeForSufficientStack()
@@ -148,7 +145,6 @@ namespace System.Runtime.CompilerServices {
// 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.
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
public static void PrepareConstrainedRegions()
{
ProbeForSufficientStack();
@@ -156,7 +152,6 @@ 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.
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
public static void PrepareConstrainedRegionsNoOP()
{
}
@@ -168,7 +163,6 @@ namespace System.Runtime.CompilerServices {
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public static extern void ExecuteCodeWithGuaranteedCleanup(TryCode code, CleanupCode backoutCode, Object userData);
- [PrePrepareMethod]
internal static void ExecuteBackoutCodeHelper(Object backoutCode, Object userData, bool exceptionThrown)
{
((CleanupCode)backoutCode)(userData, exceptionThrown);
diff --git a/src/mscorlib/src/System/Runtime/CompilerServices/RuntimeWrappedException.cs b/src/mscorlib/src/System/Runtime/CompilerServices/RuntimeWrappedException.cs
index d2691df6b9..e3b2d2ce62 100644
--- a/src/mscorlib/src/System/Runtime/CompilerServices/RuntimeWrappedException.cs
+++ b/src/mscorlib/src/System/Runtime/CompilerServices/RuntimeWrappedException.cs
@@ -15,7 +15,6 @@ namespace System.Runtime.CompilerServices {
using System;
using System.Runtime.Serialization;
using System.Runtime.Remoting;
- using System.Security.Permissions;
using System.Diagnostics.Contracts;
[Serializable]
diff --git a/src/mscorlib/src/System/Runtime/CompilerServices/TaskAwaiter.cs b/src/mscorlib/src/System/Runtime/CompilerServices/TaskAwaiter.cs
index 98a81ea470..f01900a5bf 100644
--- a/src/mscorlib/src/System/Runtime/CompilerServices/TaskAwaiter.cs
+++ b/src/mscorlib/src/System/Runtime/CompilerServices/TaskAwaiter.cs
@@ -44,7 +44,6 @@ using System.Diagnostics.Contracts;
using System.Security;
using System.Threading;
using System.Threading.Tasks;
-using System.Security.Permissions;
using System.Diagnostics.Tracing;
// NOTE: For performance reasons, initialization is not verified. If a developer
@@ -198,21 +197,19 @@ 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>
- [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var have to be marked non-inlineable
internal static void OnCompletedInternal(Task task, Action continuation, bool continueOnCapturedContext, bool flowExecutionContext)
{
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
// and set up an ending event to be traced when the asynchronous await completes.
- if ( TplEtwProvider.Log.IsEnabled() || Task.s_asyncDebuggingEnabled)
+ if (TplEtwProvider.Log.IsEnabled() || Task.s_asyncDebuggingEnabled)
{
continuation = OutputWaitEtwEvents(task, continuation);
}
// Set the continuation onto the awaited task.
- task.SetContinuationForAwait(continuation, continueOnCapturedContext, flowExecutionContext, ref stackMark);
+ task.SetContinuationForAwait(continuation, continueOnCapturedContext, flowExecutionContext);
}
/// <summary>
@@ -244,7 +241,7 @@ namespace System.Runtime.CompilerServices
(currentTaskAtBegin != null ? currentTaskAtBegin.m_taskScheduler.Id : TaskScheduler.Default.Id),
(currentTaskAtBegin != null ? currentTaskAtBegin.Id : 0),
task.Id, TplEtwProvider.TaskWaitBehavior.Asynchronous,
- (continuationTask != null ? continuationTask.Id : 0), System.Threading.Thread.GetDomainID());
+ (continuationTask != null ? continuationTask.Id : 0));
}
// Create a continuation action that outputs the end event and then invokes the user
diff --git a/src/mscorlib/src/System/Runtime/CompilerServices/TupleElementNamesAttribute.cs b/src/mscorlib/src/System/Runtime/CompilerServices/TupleElementNamesAttribute.cs
new file mode 100644
index 0000000000..65b120e6b4
--- /dev/null
+++ b/src/mscorlib/src/System/Runtime/CompilerServices/TupleElementNamesAttribute.cs
@@ -0,0 +1,57 @@
+// 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;
+
+namespace System.Runtime.CompilerServices
+{
+ /// <summary>
+ /// Indicates that the use of <see cref="System.ValueTuple"/> on a member is meant to be treated as a tuple with element names.
+ /// </summary>
+ [CLSCompliant(false)]
+ [AttributeUsage(AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.Property | AttributeTargets.ReturnValue | AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Event)]
+ public sealed class TupleElementNamesAttribute : Attribute
+ {
+ private readonly string[] _transformNames;
+
+ /// <summary>
+ /// Initializes a new instance of the <see
+ /// cref="TupleElementNamesAttribute"/> class.
+ /// </summary>
+ /// <param name="transformNames">
+ /// Specifies, in a pre-order depth-first traversal of a type's
+ /// construction, which <see cref="System.ValueType"/> occurrences are
+ /// meant to carry element names.
+ /// </param>
+ /// <remarks>
+ /// This constructor is meant to be used on types that contain an
+ /// instantiation of <see cref="System.ValueType"/> that contains
+ /// element names. For instance, if <c>C</c> is a generic type with
+ /// two type parameters, then a use of the constructed type <c>C{<see
+ /// cref="System.ValueTuple{T1, T2}"/>, <see
+ /// cref="System.ValueTuple{T1, T2, T3}"/></c> might be intended to
+ /// treat the first type argument as a tuple with element names and the
+ /// second as a tuple without element names. In which case, the
+ /// appropriate attribute specification should use a
+ /// <c>transformNames</c> value of <c>{ "name1", "name2", null, null,
+ /// null }</c>.
+ /// </remarks>
+ public TupleElementNamesAttribute(string[] transformNames)
+ {
+ if (transformNames == null)
+ {
+ throw new ArgumentNullException(nameof(transformNames));
+ }
+
+ _transformNames = transformNames;
+ }
+
+ /// <summary>
+ /// Specifies, in a pre-order depth-first traversal of a type's
+ /// construction, which <see cref="System.ValueTuple"/> elements are
+ /// meant to carry element names.
+ /// </summary>
+ public IList<string> TransformNames => _transformNames;
+ }
+} \ No newline at end of file
diff --git a/src/mscorlib/src/System/Runtime/CompilerServices/TypeForwardedToAttribute.cs b/src/mscorlib/src/System/Runtime/CompilerServices/TypeForwardedToAttribute.cs
index d9e067bd4c..147c103047 100644
--- a/src/mscorlib/src/System/Runtime/CompilerServices/TypeForwardedToAttribute.cs
+++ b/src/mscorlib/src/System/Runtime/CompilerServices/TypeForwardedToAttribute.cs
@@ -26,18 +26,6 @@ namespace System.Runtime.CompilerServices
}
}
- internal static TypeForwardedToAttribute[] GetCustomAttribute(RuntimeAssembly assembly)
- {
- Type[] types = null;
- RuntimeAssembly.GetForwardedTypes(assembly.GetNativeHandle(), JitHelpers.GetObjectHandleOnStack(ref types));
-
- TypeForwardedToAttribute[] attributes = new TypeForwardedToAttribute[types.Length];
- for (int i = 0; i < types.Length; ++i)
- attributes[i] = new TypeForwardedToAttribute(types[i]);
-
- return attributes;
- }
-
}
}
diff --git a/src/mscorlib/src/System/Runtime/CompilerServices/Unsafe.cs b/src/mscorlib/src/System/Runtime/CompilerServices/Unsafe.cs
index b212f4555b..adfa015161 100644
--- a/src/mscorlib/src/System/Runtime/CompilerServices/Unsafe.cs
+++ b/src/mscorlib/src/System/Runtime/CompilerServices/Unsafe.cs
@@ -76,5 +76,18 @@ namespace System.Runtime.CompilerServices
// See getILIntrinsicImplementationForUnsafe for how this happens.
throw new InvalidOperationException();
}
+
+ /// <summary>
+ /// Initializes a block of memory at the given location with a given initial value
+ /// without assuming architecture dependent alignment of the address.
+ /// </summary>
+ [NonVersionable]
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static void InitBlockUnaligned(ref byte startAddress, byte value, uint byteCount)
+ {
+ // 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 86789bf12d..92d1b4f95b 100644
--- a/src/mscorlib/src/System/Runtime/CompilerServices/YieldAwaitable.cs
+++ b/src/mscorlib/src/System/Runtime/CompilerServices/YieldAwaitable.cs
@@ -28,7 +28,6 @@ using System.Diagnostics.Contracts;
using System.Diagnostics.Tracing;
using System.Threading;
using System.Threading.Tasks;
-using System.Security.Permissions;
namespace System.Runtime.CompilerServices
{
diff --git a/src/mscorlib/src/System/Runtime/CompilerServices/jithelpers.cs b/src/mscorlib/src/System/Runtime/CompilerServices/jithelpers.cs
index c1346f7527..080e42f46f 100644
--- a/src/mscorlib/src/System/Runtime/CompilerServices/jithelpers.cs
+++ b/src/mscorlib/src/System/Runtime/CompilerServices/jithelpers.cs
@@ -216,7 +216,6 @@ namespace System.Runtime.CompilerServices {
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!!!
@@ -239,6 +238,5 @@ namespace System.Runtime.CompilerServices {
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/CorruptingExceptionCommon.cs b/src/mscorlib/src/System/Runtime/ExceptionServices/CorruptingExceptionCommon.cs
index e12df10462..f04ddf065a 100644
--- a/src/mscorlib/src/System/Runtime/ExceptionServices/CorruptingExceptionCommon.cs
+++ b/src/mscorlib/src/System/Runtime/ExceptionServices/CorruptingExceptionCommon.cs
@@ -1,7 +1,6 @@
// 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_CORRUPTING_EXCEPTIONS
/*=============================================================================
**
@@ -28,4 +27,3 @@ namespace System.Runtime.ExceptionServices {
}
}
}
-#endif // FEATURE_CORRUPTING_EXCEPTIONS
diff --git a/src/mscorlib/src/System/Runtime/ExceptionServices/ExceptionNotification.cs b/src/mscorlib/src/System/Runtime/ExceptionServices/ExceptionNotification.cs
index b084891768..1b3e25b8b2 100644
--- a/src/mscorlib/src/System/Runtime/ExceptionServices/ExceptionNotification.cs
+++ b/src/mscorlib/src/System/Runtime/ExceptionServices/ExceptionNotification.cs
@@ -13,7 +13,6 @@
** <owner>gkhanna</owner>
**
=============================================================================*/
-#if FEATURE_EXCEPTION_NOTIFICATIONS
namespace System.Runtime.ExceptionServices {
using System;
using System.Runtime.ConstrainedExecution;
@@ -30,7 +29,6 @@ namespace System.Runtime.ExceptionServices {
// Returns the exception object pertaining to the first chance exception
public Exception Exception
{
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
get { return m_Exception; }
}
@@ -38,4 +36,3 @@ namespace System.Runtime.ExceptionServices {
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 905f12dfb5..e8eb6916b7 100644
--- a/src/mscorlib/src/System/Runtime/ExceptionServices/ExceptionServicesCommon.cs
+++ b/src/mscorlib/src/System/Runtime/ExceptionServices/ExceptionServicesCommon.cs
@@ -15,7 +15,6 @@
**
=============================================================================*/
-#if FEATURE_EXCEPTIONDISPATCHINFO
namespace System.Runtime.ExceptionServices {
using System;
@@ -132,4 +131,3 @@ namespace System.Runtime.ExceptionServices {
}
}
}
-#endif // FEATURE_EXCEPTIONDISPATCHINFO
diff --git a/src/mscorlib/src/System/Runtime/GcSettings.cs b/src/mscorlib/src/System/Runtime/GcSettings.cs
index 91997f5297..11143c5ee2 100644
--- a/src/mscorlib/src/System/Runtime/GcSettings.cs
+++ b/src/mscorlib/src/System/Runtime/GcSettings.cs
@@ -7,7 +7,6 @@ namespace System.Runtime {
using System;
using System.Runtime.CompilerServices;
using System.Runtime.ConstrainedExecution;
- using System.Security.Permissions;
using System.Diagnostics.Contracts;
// These settings are the same format as in clr\src\vm\gcpriv.h
@@ -37,17 +36,15 @@ namespace System.Runtime {
Succeeded = 0,
NoGCInProgress = 1 // NoGCRegion is in progress, can't change pause mode.
};
-
+
public static GCLatencyMode LatencyMode
{
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
get
{
return (GCLatencyMode)(GC.GetGCLatencyMode());
}
// We don't want to allow this API when hosted.
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
set
{
if ((value < GCLatencyMode.Batch) || (value > GCLatencyMode.SustainedLowLatency))
@@ -63,14 +60,12 @@ namespace System.Runtime {
public static GCLargeObjectHeapCompactionMode LargeObjectHeapCompactionMode
{
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
get
{
return (GCLargeObjectHeapCompactionMode)(GC.GetLOHCompactionMode());
}
// We don't want to allow this API when hosted.
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
set
{
if ((value < GCLargeObjectHeapCompactionMode.Default) ||
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/ArrayWithOffset.cs b/src/mscorlib/src/System/Runtime/InteropServices/ArrayWithOffset.cs
index 77db3a7f2c..fc15f4e1a7 100644
--- a/src/mscorlib/src/System/Runtime/InteropServices/ArrayWithOffset.cs
+++ b/src/mscorlib/src/System/Runtime/InteropServices/ArrayWithOffset.cs
@@ -9,7 +9,6 @@ namespace System.Runtime.InteropServices {
using System.Runtime.Versioning;
[Serializable]
- [System.Runtime.InteropServices.ComVisible(true)]
public struct ArrayWithOffset
{
//private ArrayWithOffset()
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/Attributes.cs b/src/mscorlib/src/System/Runtime/InteropServices/Attributes.cs
index 2de7304a0b..b5bde22057 100644
--- a/src/mscorlib/src/System/Runtime/InteropServices/Attributes.cs
+++ b/src/mscorlib/src/System/Runtime/InteropServices/Attributes.cs
@@ -12,7 +12,6 @@ namespace System.Runtime.InteropServices{
using System.Diagnostics.Contracts;
[AttributeUsage(AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)]
- [System.Runtime.InteropServices.ComVisible(true)]
public sealed class UnmanagedFunctionPointerAttribute : Attribute
{
CallingConvention m_callingConvention;
@@ -33,7 +32,6 @@ namespace System.Runtime.InteropServices{
}
[AttributeUsage(AttributeTargets.Interface | AttributeTargets.Enum | AttributeTargets.Struct | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)]
- [System.Runtime.InteropServices.ComVisible(false)]
public sealed class TypeIdentifierAttribute : Attribute
{
public TypeIdentifierAttribute() { }
@@ -57,7 +55,6 @@ namespace System.Runtime.InteropServices{
}
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Field | AttributeTargets.Property | AttributeTargets.Event, Inherited = false)]
- [System.Runtime.InteropServices.ComVisible(true)]
public sealed class DispIdAttribute : Attribute
{
internal int _val;
@@ -69,19 +66,16 @@ namespace System.Runtime.InteropServices{
}
[Serializable]
- [System.Runtime.InteropServices.ComVisible(true)]
public enum ComInterfaceType
{
InterfaceIsDual = 0,
InterfaceIsIUnknown = 1,
InterfaceIsIDispatch = 2,
- [System.Runtime.InteropServices.ComVisible(false)]
InterfaceIsIInspectable = 3,
}
[AttributeUsage(AttributeTargets.Interface, Inherited = false)]
- [System.Runtime.InteropServices.ComVisible(true)]
public sealed class InterfaceTypeAttribute : Attribute
{
internal ComInterfaceType _val;
@@ -97,7 +91,6 @@ namespace System.Runtime.InteropServices{
}
[AttributeUsage(AttributeTargets.Class, Inherited = false)]
- [System.Runtime.InteropServices.ComVisible(true)]
public sealed class ComDefaultInterfaceAttribute : Attribute
{
internal Type _val;
@@ -111,7 +104,6 @@ namespace System.Runtime.InteropServices{
}
[Serializable]
- [System.Runtime.InteropServices.ComVisible(true)]
public enum ClassInterfaceType
{
None = 0,
@@ -120,7 +112,6 @@ namespace System.Runtime.InteropServices{
}
[AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Class, Inherited = false)]
- [System.Runtime.InteropServices.ComVisible(true)]
public sealed class ClassInterfaceAttribute : Attribute
{
internal ClassInterfaceType _val;
@@ -137,7 +128,6 @@ namespace System.Runtime.InteropServices{
}
[AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Interface | AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Delegate | AttributeTargets.Enum | AttributeTargets.Field | AttributeTargets.Method | AttributeTargets.Property, Inherited = false)]
- [System.Runtime.InteropServices.ComVisible(true)]
public sealed class ComVisibleAttribute : Attribute
{
internal bool _val;
@@ -148,20 +138,7 @@ namespace System.Runtime.InteropServices{
public bool Value { get { return _val; } }
}
- [AttributeUsage(AttributeTargets.Interface, Inherited = false)]
- [System.Runtime.InteropServices.ComVisible(true)]
- public sealed class TypeLibImportClassAttribute : Attribute
- {
- internal String _importClassName;
- public TypeLibImportClassAttribute(Type importClass)
- {
- _importClassName = importClass.ToString();
- }
- public String Value { get { return _importClassName; } }
- }
-
- [AttributeUsage(AttributeTargets.Method, Inherited = false)]
- [System.Runtime.InteropServices.ComVisible(true)]
+ [AttributeUsage(AttributeTargets.Method, Inherited = false)]
public sealed class LCIDConversionAttribute : Attribute
{
internal int _val;
@@ -169,29 +146,10 @@ namespace System.Runtime.InteropServices{
{
_val = lcid;
}
- public int Value { get {return _val;} }
- }
-
- [AttributeUsage(AttributeTargets.Method, Inherited = false)]
- [System.Runtime.InteropServices.ComVisible(true)]
- public sealed class ComRegisterFunctionAttribute : Attribute
- {
- public ComRegisterFunctionAttribute()
- {
- }
+ public int Value { get {return _val;} }
}
- [AttributeUsage(AttributeTargets.Method, Inherited = false)]
- [System.Runtime.InteropServices.ComVisible(true)]
- public sealed class ComUnregisterFunctionAttribute : Attribute
- {
- public ComUnregisterFunctionAttribute()
- {
- }
- }
-
- [AttributeUsage(AttributeTargets.Class, Inherited = false)]
- [System.Runtime.InteropServices.ComVisible(true)]
+ [AttributeUsage(AttributeTargets.Class, Inherited = false)]
public sealed class ProgIdAttribute : Attribute
{
internal String _val;
@@ -199,50 +157,10 @@ namespace System.Runtime.InteropServices{
{
_val = progId;
}
- public String Value { get {return _val;} }
- }
-
- [AttributeUsage(AttributeTargets.Assembly, Inherited = false)]
- [System.Runtime.InteropServices.ComVisible(true)]
- public sealed class ImportedFromTypeLibAttribute : Attribute
- {
- internal String _val;
- public ImportedFromTypeLibAttribute(String tlbFile)
- {
- _val = tlbFile;
- }
public String Value { get {return _val;} }
}
- [Obsolete("The IDispatchImplAttribute is deprecated.", false)]
- [Serializable]
- [System.Runtime.InteropServices.ComVisible(true)]
- public enum IDispatchImplType
- {
- SystemDefinedImpl = 0,
- InternalImpl = 1,
- CompatibleImpl = 2,
- }
-
- [AttributeUsage(AttributeTargets.Class | AttributeTargets.Assembly, Inherited = false)]
- [Obsolete("This attribute is deprecated and will be removed in a future version.", false)]
- [System.Runtime.InteropServices.ComVisible(true)]
- public sealed class IDispatchImplAttribute : Attribute
- {
- internal IDispatchImplType _val;
- public IDispatchImplAttribute(IDispatchImplType implType)
- {
- _val = implType;
- }
- public IDispatchImplAttribute(short implType)
- {
- _val = (IDispatchImplType)implType;
- }
- public IDispatchImplType Value { get {return _val;} }
- }
-
[AttributeUsage(AttributeTargets.Class, Inherited = true)]
- [System.Runtime.InteropServices.ComVisible(true)]
public sealed class ComSourceInterfacesAttribute : Attribute
{
internal String _val;
@@ -269,126 +187,7 @@ namespace System.Runtime.InteropServices{
public String Value { get {return _val;} }
}
- [AttributeUsage(AttributeTargets.All, Inherited = false)]
- [System.Runtime.InteropServices.ComVisible(true)]
- public sealed class ComConversionLossAttribute : Attribute
- {
- public ComConversionLossAttribute()
- {
- }
- }
-
-[Serializable]
-[Flags()]
- [System.Runtime.InteropServices.ComVisible(true)]
- public enum TypeLibTypeFlags
- {
- FAppObject = 0x0001,
- FCanCreate = 0x0002,
- FLicensed = 0x0004,
- FPreDeclId = 0x0008,
- FHidden = 0x0010,
- FControl = 0x0020,
- FDual = 0x0040,
- FNonExtensible = 0x0080,
- FOleAutomation = 0x0100,
- FRestricted = 0x0200,
- FAggregatable = 0x0400,
- FReplaceable = 0x0800,
- FDispatchable = 0x1000,
- FReverseBind = 0x2000,
- }
-
-[Serializable]
-[Flags()]
- [System.Runtime.InteropServices.ComVisible(true)]
- public enum TypeLibFuncFlags
- {
- FRestricted = 0x0001,
- FSource = 0x0002,
- FBindable = 0x0004,
- FRequestEdit = 0x0008,
- FDisplayBind = 0x0010,
- FDefaultBind = 0x0020,
- FHidden = 0x0040,
- FUsesGetLastError = 0x0080,
- FDefaultCollelem = 0x0100,
- FUiDefault = 0x0200,
- FNonBrowsable = 0x0400,
- FReplaceable = 0x0800,
- FImmediateBind = 0x1000,
- }
-
-[Serializable]
-[Flags()]
- [System.Runtime.InteropServices.ComVisible(true)]
- public enum TypeLibVarFlags
- {
- FReadOnly = 0x0001,
- FSource = 0x0002,
- FBindable = 0x0004,
- FRequestEdit = 0x0008,
- FDisplayBind = 0x0010,
- FDefaultBind = 0x0020,
- FHidden = 0x0040,
- FRestricted = 0x0080,
- FDefaultCollelem = 0x0100,
- FUiDefault = 0x0200,
- FNonBrowsable = 0x0400,
- FReplaceable = 0x0800,
- FImmediateBind = 0x1000,
- }
-
- [AttributeUsage(AttributeTargets.Class | AttributeTargets.Interface | AttributeTargets.Enum | AttributeTargets.Struct, Inherited = false)]
- [System.Runtime.InteropServices.ComVisible(true)]
- public sealed class TypeLibTypeAttribute : Attribute
- {
- internal TypeLibTypeFlags _val;
- public TypeLibTypeAttribute(TypeLibTypeFlags flags)
- {
- _val = flags;
- }
- public TypeLibTypeAttribute(short flags)
- {
- _val = (TypeLibTypeFlags)flags;
- }
- public TypeLibTypeFlags Value { get {return _val;} }
- }
-
- [AttributeUsage(AttributeTargets.Method, Inherited = false)]
- [System.Runtime.InteropServices.ComVisible(true)]
- public sealed class TypeLibFuncAttribute : Attribute
- {
- internal TypeLibFuncFlags _val;
- public TypeLibFuncAttribute(TypeLibFuncFlags flags)
- {
- _val = flags;
- }
- public TypeLibFuncAttribute(short flags)
- {
- _val = (TypeLibFuncFlags)flags;
- }
- public TypeLibFuncFlags Value { get {return _val;} }
- }
-
- [AttributeUsage(AttributeTargets.Field, Inherited = false)]
- [System.Runtime.InteropServices.ComVisible(true)]
- public sealed class TypeLibVarAttribute : Attribute
- {
- internal TypeLibVarFlags _val;
- public TypeLibVarAttribute(TypeLibVarFlags flags)
- {
- _val = flags;
- }
- public TypeLibVarAttribute(short flags)
- {
- _val = (TypeLibVarFlags)flags;
- }
- public TypeLibVarFlags Value { get {return _val;} }
- }
-
[Serializable]
- [System.Runtime.InteropServices.ComVisible(true)]
public enum VarEnum
{
VT_EMPTY = 0,
@@ -438,7 +237,6 @@ namespace System.Runtime.InteropServices{
}
[Serializable]
- [System.Runtime.InteropServices.ComVisible(true)]
// Note that this enum should remain in-sync with the CorNativeType enum in corhdr.h
public enum UnmanagedType
{
@@ -512,18 +310,14 @@ namespace System.Runtime.InteropServices{
Error = 0x2d,
- [System.Runtime.InteropServices.ComVisible(false)]
IInspectable = 0x2e,
- [System.Runtime.InteropServices.ComVisible(false)]
HString = 0x2f, // Windows Runtime HSTRING
- [System.Runtime.InteropServices.ComVisible(false)]
LPUTF8Str = 0x30, // UTF8 string
}
[AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Field | AttributeTargets.ReturnValue, Inherited = false)]
- [System.Runtime.InteropServices.ComVisible(true)]
public unsafe sealed class MarshalAsAttribute : Attribute
{
internal static Attribute GetCustomAttribute(RuntimeParameterInfo parameter)
@@ -622,15 +416,12 @@ namespace System.Runtime.InteropServices{
public int SizeConst; // constant C
// Fields used with SubType = CustomMarshaler
- [System.Runtime.InteropServices.ComVisible(true)]
public String MarshalType; // Name of marshaler class
- [System.Runtime.InteropServices.ComVisible(true)]
public Type MarshalTypeRef; // Type of marshaler class
public String MarshalCookie; // cookie to pass to marshaler
}
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Interface, Inherited = false)]
- [System.Runtime.InteropServices.ComVisible(true)]
public sealed class ComImportAttribute : Attribute
{
internal static Attribute GetCustomAttribute(RuntimeType type)
@@ -652,7 +443,6 @@ namespace System.Runtime.InteropServices{
}
[AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Interface | AttributeTargets.Class | AttributeTargets.Enum | AttributeTargets.Struct | AttributeTargets.Delegate, Inherited = false)]
- [System.Runtime.InteropServices.ComVisible(true)]
public sealed class GuidAttribute : Attribute
{
internal String _val;
@@ -664,7 +454,6 @@ namespace System.Runtime.InteropServices{
}
[AttributeUsage(AttributeTargets.Method, Inherited = false)]
- [System.Runtime.InteropServices.ComVisible(true)]
public sealed class PreserveSigAttribute : Attribute
{
internal static Attribute GetCustomAttribute(RuntimeMethodInfo method)
@@ -686,7 +475,6 @@ namespace System.Runtime.InteropServices{
}
[AttributeUsage(AttributeTargets.Parameter, Inherited = false)]
- [System.Runtime.InteropServices.ComVisible(true)]
public sealed class InAttribute : Attribute
{
internal static Attribute GetCustomAttribute(RuntimeParameterInfo parameter)
@@ -704,7 +492,6 @@ namespace System.Runtime.InteropServices{
}
[AttributeUsage(AttributeTargets.Parameter, Inherited = false)]
- [System.Runtime.InteropServices.ComVisible(true)]
public sealed class OutAttribute : Attribute
{
internal static Attribute GetCustomAttribute(RuntimeParameterInfo parameter)
@@ -722,7 +509,6 @@ namespace System.Runtime.InteropServices{
}
[AttributeUsage(AttributeTargets.Parameter, Inherited = false)]
- [System.Runtime.InteropServices.ComVisible(true)]
public sealed class OptionalAttribute : Attribute
{
internal static Attribute GetCustomAttribute(RuntimeParameterInfo parameter)
@@ -752,7 +538,6 @@ namespace System.Runtime.InteropServices{
}
[AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Method, AllowMultiple = false)]
- [System.Runtime.InteropServices.ComVisible(false)]
public sealed class DefaultDllImportSearchPathsAttribute : Attribute
{
internal DllImportSearchPath _paths;
@@ -765,7 +550,6 @@ namespace System.Runtime.InteropServices{
}
[AttributeUsage(AttributeTargets.Method, Inherited = false)]
- [System.Runtime.InteropServices.ComVisible(true)]
public unsafe sealed class DllImportAttribute : Attribute
{
internal static Attribute GetCustomAttribute(RuntimeMethodInfo method)
@@ -859,7 +643,6 @@ namespace System.Runtime.InteropServices{
}
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct, Inherited = false)]
- [System.Runtime.InteropServices.ComVisible(true)]
public unsafe sealed class StructLayoutAttribute : Attribute
{
private const int DEFAULT_PACKING_SIZE = 8;
@@ -931,7 +714,6 @@ namespace System.Runtime.InteropServices{
}
[AttributeUsage(AttributeTargets.Field, Inherited = false)]
- [System.Runtime.InteropServices.ComVisible(true)]
public unsafe sealed class FieldOffsetAttribute : Attribute
{
internal static Attribute GetCustomAttribute(RuntimeFieldInfo field)
@@ -958,49 +740,7 @@ namespace System.Runtime.InteropServices{
public int Value { get { return _val; } }
}
- [AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Field | AttributeTargets.Property | AttributeTargets.ReturnValue, Inherited = false)]
- [System.Runtime.InteropServices.ComVisible(true)]
- public sealed class ComAliasNameAttribute : Attribute
- {
- internal String _val;
- public ComAliasNameAttribute(String alias)
- {
- _val = alias;
- }
- public String Value { get {return _val;} }
- }
-
- [AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Class | AttributeTargets.Interface, Inherited = false)]
- [System.Runtime.InteropServices.ComVisible(true)]
- public sealed class AutomationProxyAttribute : Attribute
- {
- internal bool _val;
- public AutomationProxyAttribute(bool val)
- {
- _val = val;
- }
- public bool Value { get {return _val;} }
- }
-
- [AttributeUsage(AttributeTargets.Assembly, Inherited = false, AllowMultiple = true)]
- [System.Runtime.InteropServices.ComVisible(true)]
- public sealed class PrimaryInteropAssemblyAttribute : Attribute
- {
- internal int _major;
- internal int _minor;
-
- public PrimaryInteropAssemblyAttribute(int major, int minor)
- {
- _major = major;
- _minor = minor;
- }
-
- public int MajorVersion { get {return _major;} }
- public int MinorVersion { get {return _minor;} }
- }
-
[AttributeUsage(AttributeTargets.Interface, Inherited = false)]
- [System.Runtime.InteropServices.ComVisible(true)]
public sealed class CoClassAttribute : Attribute
{
internal Type _CoClass;
@@ -1013,65 +753,7 @@ namespace System.Runtime.InteropServices{
public Type CoClass { get { return _CoClass; } }
}
- [AttributeUsage(AttributeTargets.Interface, Inherited = false)]
- [System.Runtime.InteropServices.ComVisible(true)]
- public sealed class ComEventInterfaceAttribute : Attribute
- {
- internal Type _SourceInterface;
- internal Type _EventProvider;
-
- public ComEventInterfaceAttribute(Type SourceInterface, Type EventProvider)
- {
- _SourceInterface = SourceInterface;
- _EventProvider = EventProvider;
- }
-
- public Type SourceInterface { get {return _SourceInterface;} }
- public Type EventProvider { get {return _EventProvider;} }
- }
-
- [AttributeUsage(AttributeTargets.Assembly, Inherited = false)]
- [System.Runtime.InteropServices.ComVisible(true)]
- public sealed class TypeLibVersionAttribute : Attribute
- {
- internal int _major;
- internal int _minor;
-
- public TypeLibVersionAttribute(int major, int minor)
- {
- _major = major;
- _minor = minor;
- }
-
- public int MajorVersion { get {return _major;} }
- public int MinorVersion { get {return _minor;} }
- }
-
- [AttributeUsage(AttributeTargets.Assembly, Inherited = false)]
- [System.Runtime.InteropServices.ComVisible(true)]
- public sealed class ComCompatibleVersionAttribute : Attribute
- {
- internal int _major;
- internal int _minor;
- internal int _build;
- internal int _revision;
-
- public ComCompatibleVersionAttribute(int major, int minor, int build, int revision)
- {
- _major = major;
- _minor = minor;
- _build = build;
- _revision = revision;
- }
-
- public int MajorVersion { get {return _major;} }
- public int MinorVersion { get {return _minor;} }
- public int BuildNumber { get {return _build;} }
- public int RevisionNumber { get {return _revision;} }
- }
-
[AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Interface | AttributeTargets.Class | AttributeTargets.Struct, Inherited = false)]
- [System.Runtime.InteropServices.ComVisible(true)]
public sealed class BestFitMappingAttribute : Attribute
{
internal bool _bestFitMapping;
@@ -1086,7 +768,6 @@ namespace System.Runtime.InteropServices{
}
[AttributeUsage(AttributeTargets.Module, Inherited = false)]
- [System.Runtime.InteropServices.ComVisible(true)]
public sealed class DefaultCharSetAttribute : Attribute
{
internal CharSet _CharSet;
@@ -1098,33 +779,5 @@ namespace System.Runtime.InteropServices{
public CharSet CharSet { get { return _CharSet; } }
}
-
- [Obsolete("This attribute has been deprecated. Application Domains no longer respect Activation Context boundaries in IDispatch calls.", false)]
- [AttributeUsage(AttributeTargets.Assembly, Inherited = false)]
- [System.Runtime.InteropServices.ComVisible(true)]
- public sealed class SetWin32ContextInIDispatchAttribute : Attribute
- {
- public SetWin32ContextInIDispatchAttribute()
- {
- }
- }
-
- [AttributeUsage(AttributeTargets.Method, Inherited = false, AllowMultiple = false)]
- [System.Runtime.InteropServices.ComVisible(false)]
- public sealed class ManagedToNativeComInteropStubAttribute : Attribute
- {
- internal Type _classType;
- internal String _methodName;
-
- public ManagedToNativeComInteropStubAttribute(Type classType, String methodName)
- {
- _classType = classType;
- _methodName = methodName;
- }
-
- public Type ClassType { get { return _classType; } }
- public String MethodName { get { return _methodName; } }
- }
-
}
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/BStrWrapper.cs b/src/mscorlib/src/System/Runtime/InteropServices/BStrWrapper.cs
index 1673c913a6..d36f8cfa39 100644
--- a/src/mscorlib/src/System/Runtime/InteropServices/BStrWrapper.cs
+++ b/src/mscorlib/src/System/Runtime/InteropServices/BStrWrapper.cs
@@ -15,10 +15,8 @@ namespace System.Runtime.InteropServices {
using System;
using System.Security;
- using System.Security.Permissions;
[Serializable]
-[System.Runtime.InteropServices.ComVisible(true)]
public sealed class BStrWrapper
{
public BStrWrapper(String value)
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/COMException.cs b/src/mscorlib/src/System/Runtime/InteropServices/COMException.cs
index fd500fdbce..87e6be6d4e 100644
--- a/src/mscorlib/src/System/Runtime/InteropServices/COMException.cs
+++ b/src/mscorlib/src/System/Runtime/InteropServices/COMException.cs
@@ -21,7 +21,6 @@ namespace System.Runtime.InteropServices {
// Exception for COM Interop errors where we don't recognize the HResult.
//
- [ComVisible(true)]
[Serializable]
public class COMException : ExternalException {
public COMException()
@@ -46,18 +45,6 @@ namespace System.Runtime.InteropServices {
SetErrorCode(errorCode);
}
- internal COMException(int hresult)
- : base(Win32Native.GetMessage(hresult))
- {
- SetErrorCode(hresult);
- }
-
- internal COMException(String message, int hresult, Exception inner)
- : base(message, inner)
- {
- SetErrorCode(hresult);
- }
-
protected COMException(SerializationInfo info, StreamingContext context) : base(info, context) {
}
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/CallingConvention.cs b/src/mscorlib/src/System/Runtime/InteropServices/CallingConvention.cs
index cf4eb48af0..2ef1cf496e 100644
--- a/src/mscorlib/src/System/Runtime/InteropServices/CallingConvention.cs
+++ b/src/mscorlib/src/System/Runtime/InteropServices/CallingConvention.cs
@@ -9,7 +9,6 @@ namespace System.Runtime.InteropServices {
using System;
// Used for the CallingConvention named argument to the DllImport attribute
[Serializable]
-[System.Runtime.InteropServices.ComVisible(true)]
public enum CallingConvention
{
Winapi = 1,
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/CharSet.cs b/src/mscorlib/src/System/Runtime/InteropServices/CharSet.cs
index 3c0710a558..e60d676557 100644
--- a/src/mscorlib/src/System/Runtime/InteropServices/CharSet.cs
+++ b/src/mscorlib/src/System/Runtime/InteropServices/CharSet.cs
@@ -13,7 +13,6 @@ namespace System.Runtime.InteropServices {
// Generally you probably want to use Auto, which does the
// right thing 99% of the time.
[Serializable]
-[System.Runtime.InteropServices.ComVisible(true)]
public enum CharSet
{
None = 1, // User didn't specify how to marshal strings.
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/ComEventsMethod.cs b/src/mscorlib/src/System/Runtime/InteropServices/ComEventsMethod.cs
index 2da0c5eea3..c2f56b0580 100644
--- a/src/mscorlib/src/System/Runtime/InteropServices/ComEventsMethod.cs
+++ b/src/mscorlib/src/System/Runtime/InteropServices/ComEventsMethod.cs
@@ -45,52 +45,6 @@ namespace System.Runtime.InteropServices {
get { return _d; }
set { _d = value; }
}
-
- public object Invoke(object[] args) {
- if (_d == null)
- return null;
-
- if (_once == false) {
- PreProcessSignature();
- _once = true;
- }
-
- if (_cachedTargetTypes != null && _expectedParamsCount == args.Length) {
- for (int i = 0; i < _expectedParamsCount; i++) {
- if (_cachedTargetTypes[i] != null) {
- args[i] = Enum.ToObject(_cachedTargetTypes[i], args[i]);
- }
- }
- }
-
- return _d.DynamicInvoke(args);
- }
-
- private void PreProcessSignature() {
- ParameterInfo[] parameters = _d.Method.GetParameters();
- _expectedParamsCount = parameters.Length;
-
- Type[] enumTypes = new Type[_expectedParamsCount];
-
- bool needToHandleCoercion = false;
-
- for (int i = 0; i < _expectedParamsCount; i++) {
- ParameterInfo pi = parameters[i];
- // recognize only 'ref Enum' signatures and cache
- // both enum type and the underlying type.
- if (pi.ParameterType.IsByRef &&
- pi.ParameterType.HasElementType &&
- pi.ParameterType.GetElementType().IsEnum) {
-
- needToHandleCoercion = true;
- enumTypes[i] = pi.ParameterType.GetElementType();
- }
- }
-
- if (needToHandleCoercion == true) {
- _cachedTargetTypes = enumTypes;
- }
- }
}
#region private fields
@@ -145,15 +99,9 @@ namespace System.Runtime.InteropServices {
return methods;
}
-
- #endregion
-
- #region public properties / methods
-
- internal int DispId {
- get { return _dispid; }
- }
+#endregion
+#region public properties / methods
internal bool Empty {
get { return _delegateWrappers == null || _delegateWrappers.Length == 0; }
@@ -225,22 +173,6 @@ namespace System.Runtime.InteropServices {
_delegateWrappers = newDelegateWrappers;
}
- internal object Invoke(object[] args) {
- BCLDebug.Assert(Empty == false, "event sink is executed but delegates list is empty");
-
- // Issue: see code:ComEventsHelper#ComEventsRetValIssue
- object result = null;
- DelegateWrapper[] invocationList = _delegateWrappers;
- foreach (DelegateWrapper wrapper in invocationList) {
- if (wrapper == null || wrapper.Delegate == null)
- continue;
-
- result = wrapper.Invoke(args);
- }
-
- return result;
- }
-
#endregion
}
}
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/ComEventsSink.cs b/src/mscorlib/src/System/Runtime/InteropServices/ComEventsSink.cs
index 05978a607f..f2b22e3ceb 100644
--- a/src/mscorlib/src/System/Runtime/InteropServices/ComEventsSink.cs
+++ b/src/mscorlib/src/System/Runtime/InteropServices/ComEventsSink.cs
@@ -16,7 +16,7 @@ namespace System.Runtime.InteropServices {
using System.Diagnostics;
// see code:ComEventsHelper#ComEventsArchitecture
- internal class ComEventsSink : NativeMethods.IDispatch, ICustomQueryInterface
+ internal class ComEventsSink : ICustomQueryInterface
{
#region private fields
@@ -108,122 +108,6 @@ namespace System.Runtime.InteropServices {
#endregion
-
-#region IDispatch Members
-
- void NativeMethods.IDispatch.GetTypeInfoCount(out uint pctinfo) {
- pctinfo = 0;
- }
-
- void NativeMethods.IDispatch.GetTypeInfo(uint iTInfo, int lcid, out IntPtr info) {
- throw new NotImplementedException();
- }
-
- void NativeMethods.IDispatch.GetIDsOfNames(ref Guid iid, string[] names, uint cNames, int lcid, int[] rgDispId) {
- throw new NotImplementedException();
- }
-
- private const VarEnum VT_BYREF_VARIANT = VarEnum.VT_BYREF | VarEnum.VT_VARIANT;
- private const VarEnum VT_TYPEMASK = (VarEnum) 0x0fff;
- private const VarEnum VT_BYREF_TYPEMASK = VT_TYPEMASK | VarEnum.VT_BYREF;
-
- private static unsafe Variant *GetVariant(Variant *pSrc)
- {
- if (pSrc->VariantType == VT_BYREF_VARIANT)
- {
- // For VB6 compatibility reasons, if the VARIANT is a VT_BYREF | VT_VARIANT that
- // contains another VARIANT with VT_BYREF | VT_VARIANT, then we need to extract the
- // inner VARIANT and use it instead of the outer one. Note that if the inner VARIANT
- // is VT_BYREF | VT_VARIANT | VT_ARRAY, it will pass the below test too.
- Variant *pByRefVariant = (Variant *)pSrc->AsByRefVariant;
- if ((pByRefVariant->VariantType & VT_BYREF_TYPEMASK) == VT_BYREF_VARIANT)
- return (Variant *)pByRefVariant;
- }
-
- return pSrc;
- }
-
- unsafe void NativeMethods.IDispatch.Invoke(
- int dispid,
- ref Guid riid,
- int lcid,
- ComTypes.INVOKEKIND wFlags,
- ref ComTypes.DISPPARAMS pDispParams,
- IntPtr pvarResult,
- IntPtr pExcepInfo,
- IntPtr puArgErr) {
-
- ComEventsMethod method = FindMethod(dispid);
- if (method == null)
- return;
-
- // notice the unsafe pointers we are using. This is to avoid unnecessary
- // arguments marshalling. see code:ComEventsHelper#ComEventsArgsMarshalling
-
- object [] args = new object[pDispParams.cArgs];
- int [] byrefsMap = new int[pDispParams.cArgs];
- bool [] usedArgs = new bool[pDispParams.cArgs];
-
- Variant* pvars = (Variant*)pDispParams.rgvarg;
- int* pNamedArgs = (int*)pDispParams.rgdispidNamedArgs;
-
- // copy the named args (positional) as specified
- int i;
- int pos;
- for (i = 0; i < pDispParams.cNamedArgs; i++) {
- pos = pNamedArgs[i];
-
- Variant* pvar = GetVariant(&pvars[i]);
- args[pos] = pvar->ToObject();
- usedArgs[pos] = true;
-
- if (pvar->IsByRef) {
- byrefsMap[pos] = i;
- } else {
- byrefsMap[pos] = -1;
- }
- }
-
- // copy the rest of the arguments in the reverse order
- pos = 0;
- for (; i < pDispParams.cArgs; i++) {
- // find the next unassigned argument
- while (usedArgs[pos]) {
- ++pos;
- }
-
- Variant* pvar = GetVariant(&pvars[pDispParams.cArgs - 1 - i]);
- args[pos] = pvar->ToObject();
-
- if (pvar->IsByRef)
- byrefsMap[pos] = pDispParams.cArgs - 1 - i;
- else
- byrefsMap[pos] = -1;
-
- pos++;
- }
-
- // Do the actual delegate invocation
- object result;
- result = method.Invoke(args);
-
- // convert result to VARIANT
- if (pvarResult != IntPtr.Zero) {
- Marshal.GetNativeVariantForObject(result, pvarResult);
- }
-
- // Now we need to marshal all the byrefs back
- for (i = 0; i < pDispParams.cArgs; i++) {
- int idxToPos = byrefsMap[i];
- if (idxToPos == -1)
- continue;
-
- GetVariant(&pvars[idxToPos])->CopyFromIndirect(args[i]);
- }
- }
-
-#endregion
-
static Guid IID_IManagedObject = new Guid("{C3FCC19E-A970-11D2-8B5A-00A0C9B7C9C4}");
CustomQueryInterfaceResult ICustomQueryInterface.GetInterface(ref Guid iid, out IntPtr ppv) {
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/ComMemberType.cs b/src/mscorlib/src/System/Runtime/InteropServices/ComMemberType.cs
index 3be2a56da5..c61d1b21be 100644
--- a/src/mscorlib/src/System/Runtime/InteropServices/ComMemberType.cs
+++ b/src/mscorlib/src/System/Runtime/InteropServices/ComMemberType.cs
@@ -9,7 +9,6 @@ namespace System.Runtime.InteropServices {
using System;
[Serializable]
-[System.Runtime.InteropServices.ComVisible(true)]
public enum ComMemberType
{
Method = 0,
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/ComTypes/IEnumerable.cs b/src/mscorlib/src/System/Runtime/InteropServices/ComTypes/IEnumerable.cs
deleted file mode 100644
index 1a13399a88..0000000000
--- a/src/mscorlib/src/System/Runtime/InteropServices/ComTypes/IEnumerable.cs
+++ /dev/null
@@ -1,28 +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.
-
-/*==========================================================================
-**
-** Interface: IEnumerable
-**
-**
-** Purpose:
-** This interface is redefined here since the original IEnumerable interface
-** has all its methods marked as ecall's since it is a managed standard
-** interface. This interface is used from within the runtime to make a call
-** on the COM server directly when it implements the IEnumerable interface.
-**
-**
-==========================================================================*/
-namespace System.Runtime.InteropServices.ComTypes
-{
- using System;
-
- [Guid("496B0ABE-CDEE-11d3-88E8-00902754C43A")]
- internal interface IEnumerable
- {
- [DispId(-4)]
- System.Collections.IEnumerator GetEnumerator();
- }
-}
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/ComTypes/IEnumerator.cs b/src/mscorlib/src/System/Runtime/InteropServices/ComTypes/IEnumerator.cs
deleted file mode 100644
index aea2017b1e..0000000000
--- a/src/mscorlib/src/System/Runtime/InteropServices/ComTypes/IEnumerator.cs
+++ /dev/null
@@ -1,34 +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.
-
-/*==========================================================================
-**
-** Interface: IEnumerator
-**
-**
-** Purpose:
-** This interface is redefined here since the original IEnumerator interface
-** has all its methods marked as ecall's since it is a managed standard
-** interface. This interface is used from within the runtime to make a call
-** on the COM server directly when it implements the IEnumerator interface.
-**
-**
-==========================================================================*/
-namespace System.Runtime.InteropServices.ComTypes
-{
- using System;
-
- [Guid("496B0ABF-CDEE-11d3-88E8-00902754C43A")]
- internal interface IEnumerator
- {
- bool MoveNext();
-
- Object Current
- {
- get;
- }
-
- void Reset();
- }
-}
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/ComTypes/IExpando.cs b/src/mscorlib/src/System/Runtime/InteropServices/ComTypes/IExpando.cs
deleted file mode 100644
index ad4ed0b8be..0000000000
--- a/src/mscorlib/src/System/Runtime/InteropServices/ComTypes/IExpando.cs
+++ /dev/null
@@ -1,31 +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.
-
-/*==========================================================================
-**
-** Interface: IExpando
-**
-**
-** Purpose:
-** This interface is redefined here since the original IExpando interface
-** has all its methods marked as ecall's since it is a managed standard
-** interface. This interface is used from within the runtime to make a call
-** on the COM server directly when it implements the IExpando interface.
-**
-**
-==========================================================================*/
-namespace System.Runtime.InteropServices.ComTypes
-{
- using System;
- using System.Reflection;
-
- [Guid("AFBF15E6-C37C-11d2-B88E-00A0C9B471B8")]
- internal interface IExpando : IReflect
- {
- FieldInfo AddField(String name);
- PropertyInfo AddProperty(String name);
- MethodInfo AddMethod(String name, Delegate method);
- void RemoveMember(MemberInfo m);
- }
-}
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/ComTypes/IReflect.cs b/src/mscorlib/src/System/Runtime/InteropServices/ComTypes/IReflect.cs
deleted file mode 100644
index c86f961d01..0000000000
--- a/src/mscorlib/src/System/Runtime/InteropServices/ComTypes/IReflect.cs
+++ /dev/null
@@ -1,79 +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.
-
-/*==========================================================================
-**
-** Interface: IReflect
-**
-**
-** Purpose:
-** This interface is redefined here since the original IReflect interface
-** has all its methods marked as ecall's since it is a managed standard
-** interface. This interface is used from within the runtime to make a call
-** on the COM server directly when it implements the IReflect interface.
-**
-**
-==========================================================================*/
-namespace System.Runtime.InteropServices.ComTypes
-{
- using System;
- using System.Reflection;
- using CultureInfo = System.Globalization.CultureInfo;
-
- [Guid("AFBF15E5-C37C-11d2-B88E-00A0C9B471B8")]
- internal interface IReflect
- {
- 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;
- }
- }
-}
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/CriticalHandle.cs b/src/mscorlib/src/System/Runtime/InteropServices/CriticalHandle.cs
index 700e059293..840270141b 100644
--- a/src/mscorlib/src/System/Runtime/InteropServices/CriticalHandle.cs
+++ b/src/mscorlib/src/System/Runtime/InteropServices/CriticalHandle.cs
@@ -48,7 +48,6 @@
using System;
using System.Reflection;
using System.Threading;
-using System.Security.Permissions;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Runtime.ConstrainedExecution;
@@ -150,7 +149,6 @@ public abstract class CriticalHandle : CriticalFinalizerObject, IDisposable
private bool _isClosed; // Set by SetHandleAsInvalid or Close/Dispose/finalization.
// Creates a CriticalHandle class. Users must then set the Handle property or allow P/Invoke marshaling to set it implicitly.
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
protected CriticalHandle(IntPtr invalidHandleValue)
{
handle = invalidHandleValue;
@@ -167,13 +165,11 @@ public abstract class CriticalHandle : CriticalFinalizerObject, IDisposable
// Adding an empty default constructor for annotation purposes
private CriticalHandle(){}
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
~CriticalHandle()
{
Dispose(false);
}
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
private void Cleanup()
{
if (IsClosed)
@@ -197,10 +193,8 @@ public abstract class CriticalHandle : CriticalFinalizerObject, IDisposable
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
private extern void FireCustomerDebugProbe();
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
protected void SetHandle(IntPtr handle) {
this.handle = handle;
}
@@ -208,7 +202,6 @@ public abstract class CriticalHandle : CriticalFinalizerObject, IDisposable
// Returns whether the handle has been explicitly marked as closed
// (Close/Dispose) or invalid (SetHandleAsInvalid).
public bool IsClosed {
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
get { return _isClosed; }
}
@@ -217,22 +210,18 @@ public abstract class CriticalHandle : CriticalFinalizerObject, IDisposable
// know what an invalid handle looks like, so this method is abstract and
// must be provided by a derived type.
public abstract bool IsInvalid {
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
get;
}
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
public void Close() {
Dispose(true);
}
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
public void Dispose()
{
Dispose(true);
}
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
protected virtual void Dispose(bool disposing)
{
Cleanup();
@@ -242,7 +231,6 @@ public abstract class CriticalHandle : 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!
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
public void SetHandleAsInvalid()
{
_isClosed = true;
@@ -257,7 +245,6 @@ public abstract class CriticalHandle : CriticalFinalizerObject, IDisposable
// The boolean returned should be true for success and false if a
// catastrophic error occurred and you wish to trigger a diagnostic for
// debugging purposes (the SafeHandleCriticalFailure MDA).
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
protected abstract bool ReleaseHandle();
}
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/CurrencyWrapper.cs b/src/mscorlib/src/System/Runtime/InteropServices/CurrencyWrapper.cs
index 470e7b20dd..304419e5b0 100644
--- a/src/mscorlib/src/System/Runtime/InteropServices/CurrencyWrapper.cs
+++ b/src/mscorlib/src/System/Runtime/InteropServices/CurrencyWrapper.cs
@@ -16,7 +16,6 @@ namespace System.Runtime.InteropServices {
using System;
[Serializable]
-[System.Runtime.InteropServices.ComVisible(true)]
public sealed class CurrencyWrapper
{
public CurrencyWrapper(Decimal obj)
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/DispatchWrapper.cs b/src/mscorlib/src/System/Runtime/InteropServices/DispatchWrapper.cs
index 47b7542caf..ccf25af0f9 100644
--- a/src/mscorlib/src/System/Runtime/InteropServices/DispatchWrapper.cs
+++ b/src/mscorlib/src/System/Runtime/InteropServices/DispatchWrapper.cs
@@ -15,10 +15,8 @@ namespace System.Runtime.InteropServices {
using System;
using System.Security;
- using System.Security.Permissions;
[Serializable]
-[System.Runtime.InteropServices.ComVisible(true)]
public sealed class DispatchWrapper
{
public DispatchWrapper(Object obj)
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/ErrorWrapper.cs b/src/mscorlib/src/System/Runtime/InteropServices/ErrorWrapper.cs
index a9fa58f65f..da02893b1e 100644
--- a/src/mscorlib/src/System/Runtime/InteropServices/ErrorWrapper.cs
+++ b/src/mscorlib/src/System/Runtime/InteropServices/ErrorWrapper.cs
@@ -14,10 +14,8 @@
namespace System.Runtime.InteropServices {
using System;
- using System.Security.Permissions;
[Serializable]
-[System.Runtime.InteropServices.ComVisible(true)]
public sealed class ErrorWrapper
{
public ErrorWrapper(int errorCode)
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/Expando/IExpando.cs b/src/mscorlib/src/System/Runtime/InteropServices/Expando/IExpando.cs
index 62b65d1aff..429ce13918 100644
--- a/src/mscorlib/src/System/Runtime/InteropServices/Expando/IExpando.cs
+++ b/src/mscorlib/src/System/Runtime/InteropServices/Expando/IExpando.cs
@@ -17,22 +17,12 @@ namespace System.Runtime.InteropServices.Expando {
using System.Reflection;
[Guid("AFBF15E6-C37C-11d2-B88E-00A0C9B471B8")]
-[System.Runtime.InteropServices.ComVisible(true)]
- public interface IExpando : IReflect
+ internal interface IExpando : IReflect
{
// Add a new Field to the reflection object. The field has
// name as its name.
FieldInfo AddField(String name);
- // Add a new Property to the reflection object. The property has
- // name as its name.
- PropertyInfo AddProperty(String name);
-
- // Add a new Method to the reflection object. The method has
- // name as its name and method is a delegate
- // to the method.
- MethodInfo AddMethod(String name, Delegate method);
-
// Removes the specified member.
void RemoveMember(MemberInfo m);
}
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/ExtensibleClassFactory.cs b/src/mscorlib/src/System/Runtime/InteropServices/ExtensibleClassFactory.cs
deleted file mode 100644
index a12a38ec6d..0000000000
--- a/src/mscorlib/src/System/Runtime/InteropServices/ExtensibleClassFactory.cs
+++ /dev/null
@@ -1,40 +0,0 @@
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-// See the LICENSE file in the project root for more information.
-
-/*=============================================================================
-**
-**
-**
-** Purpose: Methods used to customize the creation of managed objects that
-** extend from unmanaged objects.
-**
-**
-=============================================================================*/
-
-namespace System.Runtime.InteropServices {
- using System.Runtime.InteropServices;
- using System.Runtime.Remoting;
- using System.Runtime.CompilerServices;
- using System.Runtime.Versioning;
-
- using System;
-[System.Runtime.InteropServices.ComVisible(true)]
- public sealed class ExtensibleClassFactory
- {
-
- // Prevent instantiation.
- private ExtensibleClassFactory() {}
-
- // Register a delegate that will be called whenever an instance of a managed
- // type that extends from an unmanaged type needs to allocate the aggregated
- // unmanaged object. This delegate is expected to allocate and aggregate the
- // unmanaged object and is called in place of a CoCreateInstance. This
- // routine must be called in the context of the static initializer for the
- // 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.
- [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 70a6dfe366..7e1f395e4e 100644
--- a/src/mscorlib/src/System/Runtime/InteropServices/ExternalException.cs
+++ b/src/mscorlib/src/System/Runtime/InteropServices/ExternalException.cs
@@ -20,7 +20,6 @@ namespace System.Runtime.InteropServices {
// Base exception for COM Interop errors &; Structured Exception Handler
// exceptions.
//
- [System.Runtime.InteropServices.ComVisible(true)]
[Serializable]
public class ExternalException : SystemException {
public ExternalException()
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/GcHandle.cs b/src/mscorlib/src/System/Runtime/InteropServices/GcHandle.cs
index 5530819c5f..598fee0618 100644
--- a/src/mscorlib/src/System/Runtime/InteropServices/GcHandle.cs
+++ b/src/mscorlib/src/System/Runtime/InteropServices/GcHandle.cs
@@ -5,18 +5,20 @@
namespace System.Runtime.InteropServices
{
using System;
- using System.Security.Permissions;
using System.Runtime.CompilerServices;
using System.Threading;
- using System.Runtime.Versioning;
using System.Diagnostics.Contracts;
+#if BIT64
+ using nint = System.Int64;
+#else
+ using nint = System.Int32;
+#endif
// These are the types of handles used by the EE.
// IMPORTANT: These must match the definitions in ObjectHandle.h in the EE.
// IMPORTANT: If new values are added to the enum the GCHandle::MaxHandleType
// constant must be updated.
[Serializable]
- [System.Runtime.InteropServices.ComVisible(true)]
public enum GCHandleType
{
Weak = 0,
@@ -40,7 +42,6 @@ namespace System.Runtime.InteropServices
//
[StructLayout(LayoutKind.Sequential)]
- [System.Runtime.InteropServices.ComVisible(true)]
public struct GCHandle
{
// IMPORTANT: This must be kept in sync with the GCHandleType enum.
@@ -60,20 +61,23 @@ namespace System.Runtime.InteropServices
{
// Make sure the type parameter is within the valid range for the enum.
if ((uint)type > (uint)MaxHandleType)
- throw new ArgumentOutOfRangeException(nameof(type), Environment.GetResourceString("ArgumentOutOfRange_Enum"));
+ ThrowArgumentOutOfRangeException_ArgumentOutOfRange_Enum();
Contract.EndContractBlock();
- m_handle = InternalAlloc(value, type);
+ IntPtr handle = InternalAlloc(value, type);
- // Record if the handle is pinned.
if (type == GCHandleType.Pinned)
- SetIsPinned();
- }
+ {
+ // Record if the handle is pinned.
+ handle = (IntPtr)((nint)handle | 1);
+ }
+
+ m_handle = handle;
+ }
// Used in the conversion functions below.
internal GCHandle(IntPtr handle)
{
- InternalCheckDomain(handle);
m_handle = handle;
}
@@ -93,36 +97,21 @@ namespace System.Runtime.InteropServices
return new GCHandle(value, type);
}
-
// Frees a GC handle.
public void Free()
{
- // Copy the handle instance member to a local variable. This is required to prevent
- // race conditions releasing the handle.
- IntPtr handle = m_handle;
-
// Free the handle if it hasn't already been freed.
- if (handle != IntPtr.Zero && Interlocked.CompareExchange(ref m_handle, IntPtr.Zero, handle) == handle)
- {
+ IntPtr handle = Interlocked.Exchange(ref m_handle, IntPtr.Zero);
+ ValidateHandle(handle);
#if MDA_SUPPORTED
- // If this handle was passed out to unmanaged code, we need to remove it
- // from the cookie table.
- // NOTE: the entry in the cookie table must be released before the
- // internal handle is freed to prevent a race with reusing GC handles.
- if (s_probeIsActive)
- s_cookieTable.RemoveHandleIfPresent(handle);
-#endif
-
-#if BIT64
- InternalFree((IntPtr)(((long)handle) & ~1L));
-#else // BIT64 (32)
- InternalFree((IntPtr)(((int)handle) & ~1));
+ // If this handle was passed out to unmanaged code, we need to remove it
+ // from the cookie table.
+ // NOTE: the entry in the cookie table must be released before the
+ // internal handle is freed to prevent a race with reusing GC handles.
+ if (s_probeIsActive)
+ s_cookieTable.RemoveHandleIfPresent(handle);
#endif
- }
- else
- {
- throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_HandleIsNotInitialized"));
- }
+ InternalFree(GetHandleValue(handle));
}
// Target property - allows getting / updating of the handle's referent.
@@ -130,23 +119,17 @@ namespace System.Runtime.InteropServices
{
get
{
- // Check if the handle was never initialized or was freed.
- if (m_handle == IntPtr.Zero)
- throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_HandleIsNotInitialized"));
-
+ ValidateHandle();
return InternalGet(GetHandleValue());
}
set
{
- // Check if the handle was never initialized or was freed.
- if (m_handle == IntPtr.Zero)
- throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_HandleIsNotInitialized"));
-
+ ValidateHandle();
InternalSet(GetHandleValue(), value, IsPinned());
}
}
-
+
// Retrieve the address of an object in a Pinned handle. This throws
// an exception if the handle is any type other than Pinned.
public IntPtr AddrOfPinnedObject()
@@ -154,9 +137,7 @@ namespace System.Runtime.InteropServices
// Check if the handle was not a pinned handle.
if (!IsPinned())
{
- // Check if the handle was never initialized for was freed.
- if (m_handle == IntPtr.Zero)
- throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_HandleIsNotInitialized"));
+ ValidateHandle();
// You can only get the address of pinned handles.
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_HandleIsNotPinned"));
@@ -167,30 +148,23 @@ namespace System.Runtime.InteropServices
}
// Determine whether this handle has been allocated or not.
- public bool IsAllocated
- {
- get
- {
- return m_handle != IntPtr.Zero;
- }
- }
+ public bool IsAllocated => !m_handle.IsNull();
// Used to create a GCHandle from an int. This is intended to
// be used with the reverse conversion.
public static explicit operator GCHandle(IntPtr value)
{
- return FromIntPtr(value);
+ ValidateHandle(value);
+ return new GCHandle(value);
}
public static GCHandle FromIntPtr(IntPtr value)
{
- if (value == IntPtr.Zero)
- throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_HandleIsNotInitialized"));
+ ValidateHandle(value);
Contract.EndContractBlock();
- IntPtr handle = value;
-
#if MDA_SUPPORTED
+ IntPtr handle = value;
if (s_probeIsActive)
{
// Make sure this cookie matches up with a GCHandle we've passed out a cookie for.
@@ -201,10 +175,10 @@ namespace System.Runtime.InteropServices
Mda.FireInvalidGCHandleCookieProbe(value);
return new GCHandle(IntPtr.Zero);
}
+ return new GCHandle(handle);
}
#endif
-
- return new GCHandle(handle);
+ return new GCHandle(value);
}
// Used to get the internal integer representation of the handle out.
@@ -256,29 +230,19 @@ namespace System.Runtime.InteropServices
internal IntPtr GetHandleValue()
{
-#if BIT64
- return new IntPtr(((long)m_handle) & ~1L);
-#else // !BIT64 (32)
- return new IntPtr(((int)m_handle) & ~1);
-#endif
+ return GetHandleValue(m_handle);
}
- internal bool IsPinned()
+ private static IntPtr GetHandleValue(IntPtr handle)
{
-#if BIT64
- return (((long)m_handle) & 1) != 0;
-#else // !BIT64 (32)
- return (((int)m_handle) & 1) != 0;
-#endif
+ // Remove Pin flag
+ return new IntPtr((nint)handle & ~(nint)1);
}
- internal void SetIsPinned()
+ internal bool IsPinned()
{
-#if BIT64
- m_handle = new IntPtr(((long)m_handle) | 1L);
-#else // !BIT64 (32)
- m_handle = new IntPtr(((int)m_handle) | 1);
-#endif
+ // Check Pin flag
+ return ((nint)m_handle & 1) != 0;
}
// Internal native calls that this implementation uses.
@@ -294,10 +258,6 @@ namespace System.Runtime.InteropServices
internal static extern Object InternalCompareExchange(IntPtr handle, Object value, Object oldValue, bool isPinned);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern IntPtr InternalAddrOfPinnedObject(IntPtr handle);
- [MethodImplAttribute(MethodImplOptions.InternalCall)]
- internal static extern void InternalCheckDomain(IntPtr handle);
- [MethodImplAttribute(MethodImplOptions.InternalCall)]
- internal static extern GCHandleType InternalGetHandleType(IntPtr handle);
// The actual integer handle value that the EE uses internally.
private IntPtr m_handle;
@@ -307,5 +267,29 @@ namespace System.Runtime.InteropServices
static private volatile GCHandleCookieTable s_cookieTable = null;
static private volatile bool s_probeIsActive = false;
#endif
+
+ private void ValidateHandle()
+ {
+ // Check if the handle was never initialized or was freed.
+ if (m_handle.IsNull())
+ ThrowInvalidOperationException_HandleIsNotInitialized();
+ }
+
+ private static void ValidateHandle(IntPtr handle)
+ {
+ // Check if the handle was never initialized or was freed.
+ if (handle.IsNull())
+ ThrowInvalidOperationException_HandleIsNotInitialized();
+ }
+
+ private static void ThrowArgumentOutOfRangeException_ArgumentOutOfRange_Enum()
+ {
+ throw ThrowHelper.GetArgumentOutOfRangeException(ExceptionArgument.type, ExceptionResource.ArgumentOutOfRange_Enum);
+ }
+
+ private static void ThrowInvalidOperationException_HandleIsNotInitialized()
+ {
+ throw ThrowHelper.GetInvalidOperationException(ExceptionResource.InvalidOperation_HandleIsNotInitialized);
+ }
}
}
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/HandleRef.cs b/src/mscorlib/src/System/Runtime/InteropServices/HandleRef.cs
index d76750fdd7..b1171025ee 100644
--- a/src/mscorlib/src/System/Runtime/InteropServices/HandleRef.cs
+++ b/src/mscorlib/src/System/Runtime/InteropServices/HandleRef.cs
@@ -7,7 +7,6 @@ namespace System.Runtime.InteropServices
using System;
- [System.Runtime.InteropServices.ComVisible(true)]
public struct HandleRef
{
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/ICustomAdapter.cs b/src/mscorlib/src/System/Runtime/InteropServices/ICustomAdapter.cs
index 00abf7b3bf..002c48a171 100644
--- a/src/mscorlib/src/System/Runtime/InteropServices/ICustomAdapter.cs
+++ b/src/mscorlib/src/System/Runtime/InteropServices/ICustomAdapter.cs
@@ -15,7 +15,6 @@
namespace System.Runtime.InteropServices {
using System;
-[System.Runtime.InteropServices.ComVisible(true)]
public interface ICustomAdapter
{
[return:MarshalAs(UnmanagedType.IUnknown)] Object GetUnderlyingObject();
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/ICustomFactory.cs b/src/mscorlib/src/System/Runtime/InteropServices/ICustomFactory.cs
index 33d2556bd0..8e7af10b6e 100644
--- a/src/mscorlib/src/System/Runtime/InteropServices/ICustomFactory.cs
+++ b/src/mscorlib/src/System/Runtime/InteropServices/ICustomFactory.cs
@@ -8,7 +8,6 @@ namespace System.Runtime.InteropServices {
using System;
-[System.Runtime.InteropServices.ComVisible(true)]
public interface ICustomFactory
{
MarshalByRefObject CreateInstance(Type serverType);
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/ICustomMarshaler.cs b/src/mscorlib/src/System/Runtime/InteropServices/ICustomMarshaler.cs
index 4db4acceeb..d9ed289145 100644
--- a/src/mscorlib/src/System/Runtime/InteropServices/ICustomMarshaler.cs
+++ b/src/mscorlib/src/System/Runtime/InteropServices/ICustomMarshaler.cs
@@ -15,7 +15,6 @@
namespace System.Runtime.InteropServices {
using System;
-[System.Runtime.InteropServices.ComVisible(true)]
public interface ICustomMarshaler
{
Object MarshalNativeToManaged( IntPtr pNativeData );
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/ICustomQueryInterface.cs b/src/mscorlib/src/System/Runtime/InteropServices/ICustomQueryInterface.cs
index c7d7937895..5675b1f2d6 100644
--- a/src/mscorlib/src/System/Runtime/InteropServices/ICustomQueryInterface.cs
+++ b/src/mscorlib/src/System/Runtime/InteropServices/ICustomQueryInterface.cs
@@ -19,7 +19,6 @@ namespace System.Runtime.InteropServices {
// The enum of the return value of IQuerable.GetInterface
//====================================================================
[Serializable]
- [System.Runtime.InteropServices.ComVisible(false)]
public enum CustomQueryInterfaceResult
{
Handled = 0,
@@ -30,7 +29,6 @@ namespace System.Runtime.InteropServices {
//====================================================================
// The interface for customizing IQueryInterface
//====================================================================
- [System.Runtime.InteropServices.ComVisible(false)]
public interface ICustomQueryInterface
{
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 2330365834..895aa54781 100644
--- a/src/mscorlib/src/System/Runtime/InteropServices/IException.cs
+++ b/src/mscorlib/src/System/Runtime/InteropServices/IException.cs
@@ -17,13 +17,11 @@ namespace System.Runtime.InteropServices {
using System;
using System.Reflection;
using System.Runtime.Serialization;
- using System.Security.Permissions;
[GuidAttribute("b36b5c63-42ef-38bc-a07e-0b34c98f164a")]
[InterfaceTypeAttribute(ComInterfaceType.InterfaceIsDual)]
[CLSCompliant(false)]
- [System.Runtime.InteropServices.ComVisible(true)]
- public interface _Exception
+ internal interface _Exception
{
//
// This method is intentionally included in CoreCLR to make Exception.get_InnerException "newslot virtual final".
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/IRegistrationServices.cs b/src/mscorlib/src/System/Runtime/InteropServices/IRegistrationServices.cs
deleted file mode 100644
index f2f7c61843..0000000000
--- a/src/mscorlib/src/System/Runtime/InteropServices/IRegistrationServices.cs
+++ /dev/null
@@ -1,50 +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 interface provides services for registering and unregistering
-** a managed server for use by COM.
-**
-**
-=============================================================================*/
-
-namespace System.Runtime.InteropServices {
-
- using System;
- using System.Reflection;
- using System.Security;
- using System.Security.Permissions;
-
- [Flags()]
-[System.Runtime.InteropServices.ComVisible(true)]
- public enum AssemblyRegistrationFlags
- {
- None = 0x00000000,
- SetCodeBase = 0x00000001,
- }
-
- [Guid("CCBD682C-73A5-4568-B8B0-C7007E11ABA2")]
-[System.Runtime.InteropServices.ComVisible(true)]
- public interface IRegistrationServices
- {
- bool RegisterAssembly(Assembly assembly, AssemblyRegistrationFlags flags);
-
- bool UnregisterAssembly(Assembly assembly);
-
- Type[] GetRegistrableTypesInAssembly(Assembly assembly);
-
- String GetProgIdForType(Type type);
-
- void RegisterTypeForComClients(Type type, ref Guid g);
-
- Guid GetManagedCategoryGuid();
-
- bool TypeRequiresRegistration(Type type);
-
- bool TypeRepresentsComType(Type type);
- }
-}
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/ITypeLibConverter.cs b/src/mscorlib/src/System/Runtime/InteropServices/ITypeLibConverter.cs
index a7b6889c55..afa934caaf 100644
--- a/src/mscorlib/src/System/Runtime/InteropServices/ITypeLibConverter.cs
+++ b/src/mscorlib/src/System/Runtime/InteropServices/ITypeLibConverter.cs
@@ -21,126 +21,4 @@ namespace System.Runtime.InteropServices {
using System;
using System.Reflection;
using System.Reflection.Emit;
-
-[Serializable]
-[Flags()]
-[System.Runtime.InteropServices.ComVisible(true)]
- public enum TypeLibImporterFlags
- {
- None = 0x00000000,
- PrimaryInteropAssembly = 0x00000001,
- UnsafeInterfaces = 0x00000002,
- SafeArrayAsSystemArray = 0x00000004,
- TransformDispRetVals = 0x00000008,
- PreventClassMembers = 0x00000010,
- SerializableValueClasses = 0x00000020,
- ImportAsX86 = 0x00000100,
- ImportAsX64 = 0x00000200,
- ImportAsItanium = 0x00000400,
- ImportAsAgnostic = 0x00000800,
- ReflectionOnlyLoading = 0x00001000,
- NoDefineVersionResource = 0x00002000,
- ImportAsArm = 0x00004000,
- }
-
-[Serializable]
-[Flags()]
-[System.Runtime.InteropServices.ComVisible(true)]
- public enum TypeLibExporterFlags
- {
- None = 0x00000000,
- OnlyReferenceRegistered = 0x00000001,
- CallerResolvedReferences = 0x00000002,
- OldNames = 0x00000004,
- ExportAs32Bit = 0x00000010,
- ExportAs64Bit = 0x00000020,
- }
-
- [Serializable]
-[System.Runtime.InteropServices.ComVisible(true)]
- public enum ImporterEventKind
- {
- NOTIF_TYPECONVERTED = 0,
- NOTIF_CONVERTWARNING = 1,
- ERROR_REFTOINVALIDTYPELIB = 2,
- }
-
- [Serializable]
-[System.Runtime.InteropServices.ComVisible(true)]
- public enum ExporterEventKind
- {
- NOTIF_TYPECONVERTED = 0,
- NOTIF_CONVERTWARNING = 1,
- ERROR_REFTOINVALIDASSEMBLY = 2
- }
-
- [GuidAttribute("F1C3BF76-C3E4-11d3-88E7-00902754C43A")]
- [InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)]
-[System.Runtime.InteropServices.ComVisible(true)]
- public interface ITypeLibImporterNotifySink
- {
- void ReportEvent(
- ImporterEventKind eventKind,
- int eventCode,
- String eventMsg);
- Assembly ResolveRef(
- [MarshalAs(UnmanagedType.Interface)] Object typeLib);
- }
-
- [GuidAttribute("F1C3BF77-C3E4-11d3-88E7-00902754C43A")]
- [InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)]
-[System.Runtime.InteropServices.ComVisible(true)]
- public interface ITypeLibExporterNotifySink
- {
- void ReportEvent(
- ExporterEventKind eventKind,
- int eventCode,
- String eventMsg);
-
- [return : MarshalAs(UnmanagedType.Interface)]
- Object ResolveRef(
- Assembly assembly);
- }
-
- [GuidAttribute("F1C3BF78-C3E4-11d3-88E7-00902754C43A")]
- [InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)]
-[System.Runtime.InteropServices.ComVisible(true)]
- public interface ITypeLibConverter
- {
- AssemblyBuilder ConvertTypeLibToAssembly(
- [MarshalAs(UnmanagedType.Interface)] Object typeLib,
- String asmFileName,
- TypeLibImporterFlags flags,
- ITypeLibImporterNotifySink notifySink,
- byte[] publicKey,
- StrongNameKeyPair keyPair,
- String asmNamespace,
- Version asmVersion);
-
- [return : MarshalAs(UnmanagedType.Interface)]
- Object ConvertAssemblyToTypeLib(
- Assembly assembly,
- String typeLibName,
- TypeLibExporterFlags flags,
- ITypeLibExporterNotifySink notifySink);
-
- bool GetPrimaryInteropAssembly(Guid g, Int32 major, Int32 minor, Int32 lcid, out String asmName, out String asmCodeBase);
-
- AssemblyBuilder ConvertTypeLibToAssembly([MarshalAs(UnmanagedType.Interface)] Object typeLib,
- String asmFileName,
- int flags,
- ITypeLibImporterNotifySink notifySink,
- byte[] publicKey,
- StrongNameKeyPair keyPair,
- bool unsafeInterfaces);
- }
-
- [GuidAttribute("FA1F3615-ACB9-486d-9EAC-1BEF87E36B09")]
- [InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)]
-[System.Runtime.InteropServices.ComVisible(true)]
- public interface ITypeLibExporterNameProvider
- {
- [return : MarshalAs(UnmanagedType.SafeArray, SafeArraySubType=VarEnum.VT_BSTR)]
- String[] GetNames();
- }
}
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/InvalidComObjectException.cs b/src/mscorlib/src/System/Runtime/InteropServices/InvalidComObjectException.cs
index ac8258b872..760210bc28 100644
--- a/src/mscorlib/src/System/Runtime/InteropServices/InvalidComObjectException.cs
+++ b/src/mscorlib/src/System/Runtime/InteropServices/InvalidComObjectException.cs
@@ -16,7 +16,6 @@ namespace System.Runtime.InteropServices {
using System;
using System.Runtime.Serialization;
- [System.Runtime.InteropServices.ComVisible(true)]
[Serializable]
public class InvalidComObjectException : SystemException {
public InvalidComObjectException()
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/InvalidOleVariantTypeException.cs b/src/mscorlib/src/System/Runtime/InteropServices/InvalidOleVariantTypeException.cs
index 60c9aa67b4..4ca3da5619 100644
--- a/src/mscorlib/src/System/Runtime/InteropServices/InvalidOleVariantTypeException.cs
+++ b/src/mscorlib/src/System/Runtime/InteropServices/InvalidOleVariantTypeException.cs
@@ -15,7 +15,6 @@ namespace System.Runtime.InteropServices {
using System;
using System.Runtime.Serialization;
- [System.Runtime.InteropServices.ComVisible(true)]
[Serializable]
public class InvalidOleVariantTypeException : SystemException {
public InvalidOleVariantTypeException()
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/LayoutKind.cs b/src/mscorlib/src/System/Runtime/InteropServices/LayoutKind.cs
index 231779872e..f7def3a8e9 100644
--- a/src/mscorlib/src/System/Runtime/InteropServices/LayoutKind.cs
+++ b/src/mscorlib/src/System/Runtime/InteropServices/LayoutKind.cs
@@ -7,7 +7,6 @@
namespace System.Runtime.InteropServices {
using System;
// Used in the StructLayoutAttribute class
- [System.Runtime.InteropServices.ComVisible(true)]
[Serializable]
public enum LayoutKind
{
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/Marshal.cs b/src/mscorlib/src/System/Runtime/InteropServices/Marshal.cs
index 3a79650bd9..9e9103b9c2 100644
--- a/src/mscorlib/src/System/Runtime/InteropServices/Marshal.cs
+++ b/src/mscorlib/src/System/Runtime/InteropServices/Marshal.cs
@@ -19,7 +19,6 @@ namespace System.Runtime.InteropServices
using System.Reflection;
using System.Reflection.Emit;
using System.Security;
- using System.Security.Permissions;
using System.Text;
using System.Threading;
using System.Runtime.Remoting;
@@ -76,7 +75,6 @@ namespace System.Runtime.InteropServices
#endif
}
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
private static bool IsNotWin32Atom(IntPtr ptr)
{
#if FEATURE_PAL
@@ -213,7 +211,6 @@ namespace System.Runtime.InteropServices
//====================================================================
// SizeOf()
//====================================================================
- [System.Runtime.InteropServices.ComVisible(true)]
public static int SizeOf(Object structure)
{
if (structure == null)
@@ -253,7 +250,6 @@ namespace System.Runtime.InteropServices
/// </summary>
/// <typeparam name="T">Provide a value type to figure out its size</typeparam>
/// <returns>The aligned size of T in bytes.</returns>
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
internal static uint AlignedSizeOf<T>() where T : struct
{
uint size = SizeOfType(typeof(T));
@@ -271,13 +267,11 @@ namespace System.Runtime.InteropServices
// Type must be a value type with no object reference fields. We only
// assert this, due to the lack of a suitable generic constraint.
[MethodImpl(MethodImplOptions.InternalCall)]
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
internal static extern uint SizeOfType(Type type);
// Type must be a value type with no object reference fields. We only
// assert this, due to the lack of a suitable generic constraint.
[MethodImpl(MethodImplOptions.InternalCall)]
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
private static extern uint AlignedSizeOfType(Type type);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
@@ -470,7 +464,6 @@ namespace System.Runtime.InteropServices
throw new PlatformNotSupportedException();
}
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
public static unsafe int ReadInt32(IntPtr ptr, int ofs)
{
try
@@ -500,13 +493,11 @@ namespace System.Runtime.InteropServices
}
}
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
public static int ReadInt32(IntPtr ptr)
{
return ReadInt32(ptr,0);
}
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
public static IntPtr ReadIntPtr([MarshalAs(UnmanagedType.AsAny),In] Object ptr, int ofs)
{
#if BIT64
@@ -516,7 +507,6 @@ namespace System.Runtime.InteropServices
#endif
}
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
public static IntPtr ReadIntPtr(IntPtr ptr, int ofs)
{
#if BIT64
@@ -526,7 +516,6 @@ namespace System.Runtime.InteropServices
#endif
}
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
public static IntPtr ReadIntPtr(IntPtr ptr)
{
#if BIT64
@@ -574,7 +563,6 @@ namespace System.Runtime.InteropServices
}
}
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
public static long ReadInt64(IntPtr ptr)
{
return ReadInt64(ptr,0);
@@ -768,7 +756,6 @@ namespace System.Runtime.InteropServices
// GetLastWin32Error
//====================================================================
[MethodImplAttribute(MethodImplOptions.InternalCall)]
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
public static extern int GetLastWin32Error();
@@ -776,14 +763,12 @@ namespace System.Runtime.InteropServices
// SetLastWin32Error
//====================================================================
[MethodImplAttribute(MethodImplOptions.InternalCall)]
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
internal static extern void SetLastWin32Error(int error);
//====================================================================
// GetHRForLastWin32Error
//====================================================================
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
public static int GetHRForLastWin32Error()
{
int dwLastError = GetLastWin32Error();
@@ -830,34 +815,6 @@ namespace System.Runtime.InteropServices
}
}
- //====================================================================
- // NumParamBytes
- //====================================================================
- public static int NumParamBytes(MethodInfo m)
- {
- if (m == null)
- throw new ArgumentNullException(nameof(m));
- Contract.EndContractBlock();
-
- RuntimeMethodInfo rmi = m as RuntimeMethodInfo;
- if (rmi == null)
- throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeMethodInfo"));
-
- return InternalNumParamBytes(rmi);
- }
-
- [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode), SuppressUnmanagedCodeSecurity]
- private static extern int InternalNumParamBytes(IRuntimeMethodInfo m);
-
- //====================================================================
- // Win32 Exception stuff
- // These are mostly interesting for Structured exception handling,
- // but need to be exposed for all exceptions (not just SEHException).
- //====================================================================
- [MethodImplAttribute(MethodImplOptions.InternalCall)]
- [System.Runtime.InteropServices.ComVisible(true)]
- public static extern /* struct _EXCEPTION_POINTERS* */ IntPtr GetExceptionPointers();
-
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public static extern int GetExceptionCode();
@@ -868,7 +825,6 @@ namespace System.Runtime.InteropServices
// "fDeleteOld" is true, this routine will call DestroyStructure() first.
//====================================================================
[MethodImplAttribute(MethodImplOptions.InternalCall), ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
- [System.Runtime.InteropServices.ComVisible(true)]
public static extern void StructureToPtr(Object structure, IntPtr ptr, bool fDeleteOld);
public static void StructureToPtr<T>(T structure, IntPtr ptr, bool fDeleteOld)
@@ -879,7 +835,6 @@ namespace System.Runtime.InteropServices
//====================================================================
// Marshals data from a native memory block to a preallocated structure class.
//====================================================================
- [System.Runtime.InteropServices.ComVisible(true)]
public static void PtrToStructure(IntPtr ptr, Object structure)
{
PtrToStructureHelper(ptr, structure, false);
@@ -894,7 +849,6 @@ namespace System.Runtime.InteropServices
// Creates a new instance of "structuretype" and marshals data from a
// native memory block to it.
//====================================================================
- [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)
{
@@ -935,7 +889,6 @@ namespace System.Runtime.InteropServices
// "structureclass" is used to provide layout information.
//====================================================================
[MethodImplAttribute(MethodImplOptions.InternalCall)]
- [System.Runtime.InteropServices.ComVisible(true)]
public static extern void DestroyStructure(IntPtr ptr, Type structuretype);
public static void DestroyStructure<T>(IntPtr ptr)
@@ -1015,45 +968,8 @@ namespace System.Runtime.InteropServices
//====================================================================
- // This method is intended for compiler code generators rather
- // than applications.
- //====================================================================
- [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);
-
- //====================================================================
- // This method is intended for compiler code generators rather
- // than applications.
- //====================================================================
- [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);
-
- //====================================================================
- // The hosting APIs allow a sophisticated host to schedule fibers
- // onto OS threads, so long as they notify the runtime of this
- // activity. A fiber cookie can be redeemed for its managed Thread
- // object by calling the following service.
- //====================================================================
- [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"), nameof(cookie));
- Contract.EndContractBlock();
-
- return InternalGetThreadFromFiberCookie(cookie);
- }
-
- [MethodImplAttribute(MethodImplOptions.InternalCall)]
- private static extern Thread InternalGetThreadFromFiberCookie(int cookie);
-
-
- //====================================================================
// Memory allocation and deallocation.
//====================================================================
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
public static IntPtr AllocHGlobal(IntPtr cb)
{
// For backwards compatibility on 32 bit platforms, ensure we pass values between
@@ -1077,13 +993,11 @@ namespace System.Runtime.InteropServices
return pNewMem;
}
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
public static IntPtr AllocHGlobal(int cb)
{
return AllocHGlobal((IntPtr)cb);
}
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
public static void FreeHGlobal(IntPtr hglobal)
{
if (IsNotWin32Atom(hglobal)) {
@@ -1192,185 +1106,6 @@ namespace System.Runtime.InteropServices
internal static extern int GetHRForException_WinRT(Exception e);
internal static readonly Guid ManagedNameGuid = new Guid("{0F21F359-AB84-41E8-9A78-36D110E6D2F9}");
-
- //====================================================================
- // Given a managed object that wraps a UCOMITypeLib, return its name
- //====================================================================
- [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)
- {
- return GetTypeLibName((ITypeLib)pTLB);
- }
-
-
- //====================================================================
- // Given a managed object that wraps an ITypeLib, return its name
- //====================================================================
- public static String GetTypeLibName(ITypeLib typelib)
- {
- if (typelib == null)
- throw new ArgumentNullException(nameof(typelib));
- Contract.EndContractBlock();
-
- String strTypeLibName = null;
- String strDocString = null;
- int dwHelpContext = 0;
- String strHelpFile = null;
-
- typelib.GetDocumentation(-1, out strTypeLibName, out strDocString, out dwHelpContext, out strHelpFile);
-
- return strTypeLibName;
- }
-
- //====================================================================
- // Internal version of GetTypeLibName
- // Support GUID_ManagedName which aligns with TlbImp
- //====================================================================
- internal static String GetTypeLibNameInternal(ITypeLib typelib)
- {
- if (typelib == null)
- throw new ArgumentNullException(nameof(typelib));
- Contract.EndContractBlock();
-
- // Try GUID_ManagedName first
- ITypeLib2 typeLib2 = typelib as ITypeLib2;
- if (typeLib2 != null)
- {
- Guid guid = ManagedNameGuid;
- object val;
-
- try
- {
- typeLib2.GetCustData(ref guid, out val);
- }
- catch(Exception)
- {
- val = null;
- }
-
- if (val != null && val.GetType() == typeof(string))
- {
- string customManagedNamespace = (string)val;
- customManagedNamespace = customManagedNamespace.Trim();
- if (customManagedNamespace.EndsWith(".DLL", StringComparison.OrdinalIgnoreCase))
- customManagedNamespace = customManagedNamespace.Substring(0, customManagedNamespace.Length - 4);
- else if (customManagedNamespace.EndsWith(".EXE", StringComparison.OrdinalIgnoreCase))
- customManagedNamespace = customManagedNamespace.Substring(0, customManagedNamespace.Length - 4);
- return customManagedNamespace;
- }
- }
-
- return GetTypeLibName(typelib);
- }
-
-
- //====================================================================
- // Given an managed object that wraps an UCOMITypeLib, return its guid
- //====================================================================
- [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)
- {
- return GetTypeLibGuid((ITypeLib)pTLB);
- }
-
- //====================================================================
- // Given an managed object that wraps an ITypeLib, return its guid
- //====================================================================
- public static Guid GetTypeLibGuid(ITypeLib typelib)
- {
- Guid result = new Guid ();
- FCallGetTypeLibGuid (ref result, typelib);
- return result;
- }
-
- [MethodImplAttribute(MethodImplOptions.InternalCall)]
- private static extern void FCallGetTypeLibGuid(ref Guid result, ITypeLib pTLB);
-
- //====================================================================
- // Given a managed object that wraps a UCOMITypeLib, return its lcid
- //====================================================================
- [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)
- {
- return GetTypeLibLcid((ITypeLib)pTLB);
- }
-
- //====================================================================
- // Given a managed object that wraps an ITypeLib, return its lcid
- //====================================================================
- [MethodImplAttribute(MethodImplOptions.InternalCall)]
- public static extern int GetTypeLibLcid(ITypeLib typelib);
-
- //====================================================================
- // Given a managed object that wraps an ITypeLib, return it's
- // version information.
- //====================================================================
- [MethodImplAttribute(MethodImplOptions.InternalCall)]
- internal static extern void GetTypeLibVersion(ITypeLib typeLibrary, out int major, out int minor);
-
- //====================================================================
- // Given a managed object that wraps an ITypeInfo, return its guid.
- //====================================================================
- internal static Guid GetTypeInfoGuid(ITypeInfo typeInfo)
- {
- Guid result = new Guid ();
- FCallGetTypeInfoGuid (ref result, typeInfo);
- return result;
- }
-
- [MethodImplAttribute(MethodImplOptions.InternalCall)]
- private static extern void FCallGetTypeInfoGuid(ref Guid result, ITypeInfo typeInfo);
-
- //====================================================================
- // Given a assembly, return the TLBID that will be generated for the
- // typelib exported from the assembly.
- //====================================================================
- public static Guid GetTypeLibGuidForAssembly(Assembly asm)
- {
- if (asm == null)
- throw new ArgumentNullException(nameof(asm));
- Contract.EndContractBlock();
-
- RuntimeAssembly rtAssembly = asm as RuntimeAssembly;
- if (rtAssembly == null)
- throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeAssembly"), nameof(asm));
-
- Guid result = new Guid();
- FCallGetTypeLibGuidForAssembly(ref result, rtAssembly);
- return result;
- }
-
- [MethodImplAttribute(MethodImplOptions.InternalCall)]
- private static extern void FCallGetTypeLibGuidForAssembly(ref Guid result, RuntimeAssembly asm);
-
- //====================================================================
- // Given a assembly, return the version number of the type library
- // that would be exported from the assembly.
- //====================================================================
- [MethodImplAttribute(MethodImplOptions.InternalCall)]
- private static extern void _GetTypeLibVersionForAssembly(RuntimeAssembly inputAssembly, out int majorVersion, out int minorVersion);
-
- public static void GetTypeLibVersionForAssembly(Assembly inputAssembly, out int majorVersion, out int minorVersion)
- {
- if (inputAssembly == null)
- throw new ArgumentNullException(nameof(inputAssembly));
- Contract.EndContractBlock();
-
- RuntimeAssembly rtAssembly = inputAssembly as RuntimeAssembly;
- if (rtAssembly == null)
- throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeAssembly"), nameof(inputAssembly));
-
- _GetTypeLibVersionForAssembly(rtAssembly, out majorVersion, out minorVersion);
- }
-
- //====================================================================
- // Given a managed object that wraps an UCOMITypeInfo, return its name
- //====================================================================
- [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)
- {
- return GetTypeInfoName((ITypeInfo)pTI);
- }
//====================================================================
// Given a managed object that wraps an ITypeInfo, return its name
@@ -1391,65 +1126,6 @@ namespace System.Runtime.InteropServices
return strTypeLibName;
}
- //====================================================================
- // Internal version of GetTypeInfoName
- // Support GUID_ManagedName which aligns with TlbImp
- //====================================================================
- internal static String GetTypeInfoNameInternal(ITypeInfo typeInfo, out bool hasManagedName)
- {
- if (typeInfo == null)
- throw new ArgumentNullException(nameof(typeInfo));
- Contract.EndContractBlock();
-
- // Try ManagedNameGuid first
- ITypeInfo2 typeInfo2 = typeInfo as ITypeInfo2;
- if (typeInfo2 != null)
- {
- Guid guid = ManagedNameGuid;
- object val;
-
- try
- {
- typeInfo2.GetCustData(ref guid, out val);
- }
- catch(Exception)
- {
- val = null;
- }
-
- if (val != null && val.GetType() == typeof(string))
- {
- hasManagedName = true;
- return (string)val;
- }
- }
-
- hasManagedName = false;
- return GetTypeInfoName(typeInfo);
- }
-
- //====================================================================
- // Get the corresponding managed name as converted by TlbImp
- // Used to get the type using GetType() from imported assemblies
- //====================================================================
- internal static String GetManagedTypeInfoNameInternal(ITypeLib typeLib, ITypeInfo typeInfo)
- {
- bool hasManagedName;
- string name = GetTypeInfoNameInternal(typeInfo, out hasManagedName);
- if (hasManagedName)
- return name;
- else
- return GetTypeLibNameInternal(typeLib) + "." + name;
- }
-
- //====================================================================
- // If a type with the specified GUID is loaded, this method will
- // return the reflection type that represents it. Otherwise it returns
- // NULL.
- //====================================================================
- [MethodImplAttribute(MethodImplOptions.InternalCall)]
- private static extern Type GetLoadedTypeForGUID(ref Guid guid);
-
// This method is identical to Type.GetTypeFromCLSID. Since it's interop specific, we expose it
// on Marshal for more consistent API surface.
public static Type GetTypeFromCLSID(Guid clsid)
@@ -1458,12 +1134,6 @@ namespace System.Runtime.InteropServices
}
//====================================================================
- // map Type to ITypeInfo*
- //====================================================================
- [MethodImplAttribute(MethodImplOptions.InternalCall)]
- public static extern IntPtr /* ITypeInfo* */ GetITypeInfoForType(Type t);
-
- //====================================================================
// return the IUnknown* for an Object if the current context
// is the one where the RCW was first seen. Will return null
// otherwise.
@@ -1473,11 +1143,6 @@ namespace System.Runtime.InteropServices
return GetIUnknownForObjectNative(o, false);
}
- public static IntPtr /* IUnknown* */ GetIUnknownForObjectInContext(Object o)
- {
- return GetIUnknownForObjectNative(o, true);
- }
-
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern IntPtr /* IUnknown* */ GetIUnknownForObjectNative(Object o, bool onlyInContext);
@@ -1499,18 +1164,6 @@ namespace System.Runtime.InteropServices
}
#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.
- //====================================================================
- public static IntPtr /* IUnknown* */ GetIDispatchForObjectInContext(Object o)
- {
- return GetIDispatchForObjectNative(o, true);
- }
-
- [MethodImplAttribute(MethodImplOptions.InternalCall)]
- private static extern IntPtr /* IUnknown* */ GetIDispatchForObjectNative(Object o, bool onlyInContext);
//====================================================================
// return the IUnknown* representing the interface for the Object
@@ -1537,17 +1190,6 @@ namespace System.Runtime.InteropServices
return GetComInterfaceForObjectNative(o, T, false, bEnableCustomizedQueryInterface);
}
- //====================================================================
- // return the IUnknown* representing the interface for the Object
- // Object o should support Type T if the current context
- // is the one where the RCW was first seen. Will return null
- // otherwise.
- //====================================================================
- public static IntPtr /* IUnknown* */ GetComInterfaceForObjectInContext(Object o, Type t)
- {
- return GetComInterfaceForObjectNative(o, t, true, true);
- }
-
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern IntPtr /* IUnknown* */ GetComInterfaceForObjectNative(Object o, Type t, bool onlyInContext, bool fEnalbeCustomizedQueryInterface);
@@ -1892,21 +1534,6 @@ namespace System.Runtime.InteropServices
private static extern Object InternalCreateWrapperOfType(Object o, Type t);
//====================================================================
- // There may be a thread-based cache of COM components. This service can
- // force the aggressive release of the current thread's cache.
- //====================================================================
- [Obsolete("This API did not perform any operation and will be removed in future versions of the CLR.", false)]
- public static void ReleaseThreadCache()
- {
- }
-
- //====================================================================
- // check if the type is visible from COM.
- //====================================================================
- [MethodImplAttribute(MethodImplOptions.InternalCall)]
- public static extern bool IsTypeVisibleFromCom(Type t);
-
- //====================================================================
// IUnknown Helpers
//====================================================================
[MethodImplAttribute(MethodImplOptions.InternalCall)]
@@ -1915,7 +1542,6 @@ namespace System.Runtime.InteropServices
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public static extern int /* ULONG */ AddRef(IntPtr /* IUnknown */ pUnk );
[MethodImplAttribute(MethodImplOptions.InternalCall)]
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
public static extern int /* ULONG */ Release(IntPtr /* IUnknown */ pUnk );
[MethodImplAttribute(MethodImplOptions.InternalCall)]
@@ -1958,45 +1584,6 @@ namespace System.Runtime.InteropServices
[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>
- [MethodImplAttribute(MethodImplOptions.InternalCall)]
- public static extern int GetEndComSlot(Type t);
-
- /// <summary>
- /// <para>Returns the MemberInfo that COM callers calling through the exposed
- /// vtable on the given slot will be calling. The slot should take into account
- /// if the exposed interface is IUnknown based or IDispatch based.
- /// For classes, the lookup is done on the default interface that will be
- /// exposed for the class. </para>
- /// </summary>
- [MethodImplAttribute(MethodImplOptions.InternalCall)]
- public static extern MemberInfo GetMethodInfoForComSlot(Type t, int slot, ref ComMemberType memberType);
-
- /// <summary>
- /// <para>Returns the COM slot for a memeber info, taking into account whether
- /// the exposed interface is IUnknown based or IDispatch based</para>
- /// </summary>
- public static int GetComSlotForMethodInfo(MemberInfo m)
- {
- if (m== null)
- throw new ArgumentNullException(nameof(m));
-
- if (!(m is RuntimeMethodInfo))
- throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeMethodInfo"), nameof(m));
-
- if (!m.DeclaringType.IsInterface)
- throw new ArgumentException(Environment.GetResourceString("Argument_MustBeInterfaceMethod"), nameof(m));
- if (m.DeclaringType.IsGenericType)
- throw new ArgumentException(Environment.GetResourceString("Argument_NeedNonGenericType"), nameof(m));
- Contract.EndContractBlock();
-
- return InternalGetComSlotForMethodInfo((IRuntimeMethodInfo)m);
- }
-
- [MethodImplAttribute(MethodImplOptions.InternalCall)]
- private static extern int InternalGetComSlotForMethodInfo(IRuntimeMethodInfo m);
#endif // FEATURE_COMINTEROP
//====================================================================
@@ -2069,38 +1656,6 @@ namespace System.Runtime.InteropServices
return obj;
}
- //====================================================================
- // This method gets the currently running object.
- //====================================================================
- public static Object GetActiveObject(String progID)
- {
- Object obj = null;
- Guid clsid;
-
- // Call CLSIDFromProgIDEx first then fall back on CLSIDFromProgID if
- // CLSIDFromProgIDEx doesn't exist.
- try
- {
- CLSIDFromProgIDEx(progID, out clsid);
- }
-// catch
- catch(Exception)
- {
- CLSIDFromProgID(progID, out clsid);
- }
-
- GetActiveObject(ref clsid, IntPtr.Zero, out obj);
- return obj;
- }
-
- [DllImport(Microsoft.Win32.Win32Native.OLE32, PreserveSig = false)]
- [SuppressUnmanagedCodeSecurity]
- private static extern void CLSIDFromProgIDEx([MarshalAs(UnmanagedType.LPWStr)] String progId, out Guid clsid);
-
- [DllImport(Microsoft.Win32.Win32Native.OLE32, PreserveSig = false)]
- [SuppressUnmanagedCodeSecurity]
- private static extern void CLSIDFromProgID([MarshalAs(UnmanagedType.LPWStr)] String progId, out Guid clsid);
-
[DllImport(Microsoft.Win32.Win32Native.OLE32, PreserveSig = false)]
[SuppressUnmanagedCodeSecurity]
private static extern void CreateBindCtx(UInt32 reserved, out IBindCtx ppbc);
@@ -2113,19 +1668,6 @@ namespace System.Runtime.InteropServices
[SuppressUnmanagedCodeSecurity]
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]
- private static extern void GetActiveObject(ref Guid rclsid, IntPtr reserved, [MarshalAs(UnmanagedType.Interface)] out Object ppunk);
-
- //========================================================================
- // Private method called from remoting to support ServicedComponents.
- //========================================================================
- [MethodImplAttribute(MethodImplOptions.InternalCall)]
- internal static extern bool InternalSwitchCCW(Object oldtp, Object newtp);
-
- [MethodImplAttribute(MethodImplOptions.InternalCall)]
- internal static extern Object InternalWrapIUnknownWithComObject(IntPtr i);
-
//========================================================================
// Private method called from EE upon use of license/ICF2 marshaling.
//========================================================================
@@ -2156,86 +1698,6 @@ namespace System.Runtime.InteropServices
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern object GetNativeActivationFactory(Type type);
- //========================================================================
- // Methods allowing retrieval of the IIDs exposed by an underlying WinRT
- // object, as specified by the object's IInspectable::GetIids()
- //========================================================================
- [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode), SuppressUnmanagedCodeSecurity]
- private static extern void _GetInspectableIids(ObjectHandleOnStack obj, ObjectHandleOnStack guids);
-
- internal static System.Guid[] GetInspectableIids(object obj)
- {
- System.Guid[] result = null;
- System.__ComObject comObj = obj as System.__ComObject;
- if (comObj != null)
- {
- _GetInspectableIids(JitHelpers.GetObjectHandleOnStack(ref comObj),
- JitHelpers.GetObjectHandleOnStack(ref result));
- }
-
- return result;
- }
-
- //========================================================================
- // Methods allowing retrieval of the cached WinRT type corresponding to
- // the specified GUID
- //========================================================================
- [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode), SuppressUnmanagedCodeSecurity]
- private static extern void _GetCachedWinRTTypeByIid(
- ObjectHandleOnStack appDomainObj,
- System.Guid iid,
- out IntPtr rthHandle);
-
- internal static System.Type GetCachedWinRTTypeByIid(
- System.AppDomain ad,
- System.Guid iid)
- {
- IntPtr rthHandle;
- _GetCachedWinRTTypeByIid(JitHelpers.GetObjectHandleOnStack(ref ad),
- iid,
- out rthHandle);
- System.Type res = Type.GetTypeFromHandleUnsafe(rthHandle);
- return res;
- }
-
-
- //========================================================================
- // Methods allowing retrieval of the WinRT types cached in the specified
- // app domain
- //========================================================================
- [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode), SuppressUnmanagedCodeSecurity]
- private static extern void _GetCachedWinRTTypes(
- ObjectHandleOnStack appDomainObj,
- ref int epoch,
- ObjectHandleOnStack winrtTypes);
-
- internal static System.Type[] GetCachedWinRTTypes(
- System.AppDomain ad,
- ref int epoch)
- {
- System.IntPtr[] res = null;
-
- _GetCachedWinRTTypes(JitHelpers.GetObjectHandleOnStack(ref ad),
- ref epoch,
- JitHelpers.GetObjectHandleOnStack(ref res));
-
- System.Type[] result = new System.Type[res.Length];
- for (int i = 0; i < res.Length; ++i)
- {
- result[i] = Type.GetTypeFromHandleUnsafe(res[i]);
- }
-
- return result;
- }
-
- internal static System.Type[] GetCachedWinRTTypes(
- System.AppDomain ad)
- {
- int dummyEpoch = 0;
- return GetCachedWinRTTypes(ad, ref dummyEpoch);
- }
-
-
#endif // FEATURE_COMINTEROP
public static Delegate GetDelegateForFunctionPointer(IntPtr ptr, Type t)
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/MarshalDirectiveException.cs b/src/mscorlib/src/System/Runtime/InteropServices/MarshalDirectiveException.cs
index b916778019..ec1014ecf8 100644
--- a/src/mscorlib/src/System/Runtime/InteropServices/MarshalDirectiveException.cs
+++ b/src/mscorlib/src/System/Runtime/InteropServices/MarshalDirectiveException.cs
@@ -16,7 +16,6 @@ namespace System.Runtime.InteropServices {
using System;
using System.Runtime.Serialization;
- [System.Runtime.InteropServices.ComVisible(true)]
[Serializable]
public class MarshalDirectiveException : SystemException {
public MarshalDirectiveException()
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/NativeMethods.cs b/src/mscorlib/src/System/Runtime/InteropServices/NativeMethods.cs
index 650ea65697..818034ee34 100644
--- a/src/mscorlib/src/System/Runtime/InteropServices/NativeMethods.cs
+++ b/src/mscorlib/src/System/Runtime/InteropServices/NativeMethods.cs
@@ -18,42 +18,11 @@ namespace System.Runtime.InteropServices {
[
System.Security.SuppressUnmanagedCodeSecurity,
- DllImport("oleaut32.dll", PreserveSig = false),
- System.Security.SecurityCritical
- ]
- internal static extern void VariantClear(IntPtr variant);
-
- [
- System.Security.SuppressUnmanagedCodeSecurity,
ComImport,
InterfaceType(ComInterfaceType.InterfaceIsIUnknown),
Guid("00020400-0000-0000-C000-000000000046")
]
internal interface IDispatch {
-
- void GetTypeInfoCount(out uint pctinfo);
-
- void GetTypeInfo(uint iTInfo, int lcid, out IntPtr info);
-
- void GetIDsOfNames(
- ref Guid iid,
- [MarshalAs(UnmanagedType.LPArray, ArraySubType = UnmanagedType.LPWStr, SizeParamIndex = 2)]
- string[] names,
- uint cNames,
- int lcid,
- [Out]
- [MarshalAs(UnmanagedType.LPArray, ArraySubType = UnmanagedType.I4, SizeParamIndex = 2)]
- int[] rgDispId);
-
- void Invoke(
- int dispIdMember,
- ref Guid riid,
- int lcid,
- ComTypes.INVOKEKIND wFlags,
- ref ComTypes.DISPPARAMS pDispParams,
- IntPtr pvarResult,
- IntPtr pExcepInfo,
- IntPtr puArgErr);
}
}
}
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/NonPortable.cs b/src/mscorlib/src/System/Runtime/InteropServices/NonPortable.cs
index 0c8ae7649c..ae974460f7 100644
--- a/src/mscorlib/src/System/Runtime/InteropServices/NonPortable.cs
+++ b/src/mscorlib/src/System/Runtime/InteropServices/NonPortable.cs
@@ -8,91 +8,76 @@ namespace System.Runtime.InteropServices
{
public static partial class Marshal
{
- [System.Security.SecurityCritical]
public static int GetHRForException(Exception e)
{
return (e != null) ? e.HResult : 0;
}
- [System.Security.SecurityCriticalAttribute]
public static int AddRef(System.IntPtr pUnk)
{
throw new PlatformNotSupportedException();
}
- [System.Security.SecurityCriticalAttribute]
public static bool AreComObjectsAvailableForCleanup()
{
return false;
}
- [System.Security.SecurityCriticalAttribute]
public static System.IntPtr CreateAggregatedObject(System.IntPtr pOuter, object o)
{
throw new PlatformNotSupportedException();
}
- [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();
}
- [System.Security.SecurityCriticalAttribute]
public static object CreateWrapperOfType(object o, System.Type t)
{
throw new PlatformNotSupportedException();
}
- [System.Security.SecurityCriticalAttribute]
public static TWrapper CreateWrapperOfType<T, TWrapper>(T o)
{
throw new PlatformNotSupportedException();
}
- [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();
}
- [System.Security.SecurityCriticalAttribute]
public static System.IntPtr GetComInterfaceForObject(object o, System.Type T)
{
throw new PlatformNotSupportedException();
}
- [System.Security.SecurityCriticalAttribute]
public static System.IntPtr GetComInterfaceForObject(object o, System.Type T, System.Runtime.InteropServices.CustomQueryInterfaceMode mode)
{
throw new PlatformNotSupportedException();
}
- [System.Security.SecurityCriticalAttribute]
public static System.IntPtr GetComInterfaceForObject<T, TInterface>(T o)
{
throw new PlatformNotSupportedException();
}
- [System.Security.SecurityCriticalAttribute]
public static System.IntPtr GetHINSTANCE(System.Reflection.Module m)
{
if (m == null)
@@ -102,61 +87,51 @@ namespace System.Runtime.InteropServices
return (System.IntPtr) (-1);
}
- [System.Security.SecurityCriticalAttribute]
public static System.IntPtr GetIUnknownForObject(object o)
{
throw new PlatformNotSupportedException();
}
- [System.Security.SecurityCriticalAttribute]
public static void GetNativeVariantForObject(object obj, System.IntPtr pDstNativeVariant)
{
throw new PlatformNotSupportedException();
}
- [System.Security.SecurityCriticalAttribute]
public static void GetNativeVariantForObject<T>(T obj, System.IntPtr pDstNativeVariant)
{
throw new PlatformNotSupportedException();
}
- [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();
}
- [System.Security.SecurityCriticalAttribute]
public static object GetObjectForNativeVariant(System.IntPtr pSrcNativeVariant)
{
throw new PlatformNotSupportedException();
}
- [System.Security.SecurityCriticalAttribute]
public static T GetObjectForNativeVariant<T>(System.IntPtr pSrcNativeVariant)
{
throw new PlatformNotSupportedException();
}
- [System.Security.SecurityCriticalAttribute]
public static object[] GetObjectsForNativeVariants(System.IntPtr aSrcNativeVariant, int cVars)
{
throw new PlatformNotSupportedException();
}
- [System.Security.SecurityCriticalAttribute]
public static T[] GetObjectsForNativeVariants<T>(System.IntPtr aSrcNativeVariant, int cVars)
{
throw new PlatformNotSupportedException();
}
- [System.Security.SecurityCriticalAttribute]
public static int GetStartComSlot(System.Type t)
{
throw new PlatformNotSupportedException();
@@ -167,13 +142,11 @@ namespace System.Runtime.InteropServices
throw new PlatformNotSupportedException();
}
- [System.Security.SecurityCriticalAttribute]
public static string GetTypeInfoName(System.Runtime.InteropServices.ComTypes.ITypeInfo typeInfo)
{
throw new PlatformNotSupportedException();
}
- [System.Security.SecurityCriticalAttribute]
public static object GetUniqueObjectForIUnknown(System.IntPtr unknown)
{
throw new PlatformNotSupportedException();
@@ -184,25 +157,21 @@ namespace System.Runtime.InteropServices
return false;
}
- [System.Security.SecurityCriticalAttribute]
public static int QueryInterface(System.IntPtr pUnk, ref System.Guid iid, out System.IntPtr ppv)
{
throw new PlatformNotSupportedException();
}
- [System.Security.SecurityCriticalAttribute]
public static int Release(System.IntPtr pUnk)
{
throw new PlatformNotSupportedException();
}
- [System.Security.SecurityCriticalAttribute]
public static int ReleaseComObject(object o)
{
throw new PlatformNotSupportedException();
}
- [System.Security.SecurityCriticalAttribute]
public static void ZeroFreeBSTR(System.IntPtr s)
{
throw new PlatformNotSupportedException();
@@ -227,13 +196,11 @@ namespace System.Runtime.InteropServices
public static class ComEventsHelper
{
- [System.Security.SecurityCriticalAttribute]
public static void Combine(object rcw, System.Guid iid, int dispid, System.Delegate d)
{
throw new PlatformNotSupportedException();
}
- [System.Security.SecurityCriticalAttribute]
public static System.Delegate Remove(object rcw, System.Guid iid, int dispid, System.Delegate d)
{
throw new PlatformNotSupportedException();
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/ObjectCreationDelegate.cs b/src/mscorlib/src/System/Runtime/InteropServices/ObjectCreationDelegate.cs
deleted file mode 100644
index f011253e1e..0000000000
--- a/src/mscorlib/src/System/Runtime/InteropServices/ObjectCreationDelegate.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.
-
-/*=============================================================================
-**
-** Delegate: ObjectCreationDelegate
-**
-**
-** Purpose: Delegate called to create a classic COM object as an alternative to
-** CoCreateInstance.
-**
-**
-=============================================================================*/
-
-namespace System.Runtime.InteropServices {
-
- // Delegate called when a managed object wishes to instantiate its unmanaged
- // portion. The IUnknown of the managed object (the aggregator) is passed as a
- // parameter and the delegate should return the IUnknown of the unmanaged object
- // (the aggregatee). Both are passed as int's to avoid any marshalling.
-[System.Runtime.InteropServices.ComVisible(true)]
- public delegate IntPtr ObjectCreationDelegate(IntPtr aggregator);
-}
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/RegistrationServices.cs b/src/mscorlib/src/System/Runtime/InteropServices/RegistrationServices.cs
deleted file mode 100644
index 0105866415..0000000000
--- a/src/mscorlib/src/System/Runtime/InteropServices/RegistrationServices.cs
+++ /dev/null
@@ -1,1059 +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 provides services for registering and unregistering
-** a managed server for use by COM.
-**
-**
-**
-**
-** Change the way how to register and unregister a managed server
-**
-=============================================================================*/
-namespace System.Runtime.InteropServices {
-
- using System;
- using System.Collections;
- using System.IO;
- using System.Reflection;
- using System.Security;
- using System.Security.Permissions;
- using System.Text;
- using System.Threading;
- using Microsoft.Win32;
- using System.Runtime.CompilerServices;
- using System.Globalization;
- using System.Runtime.Versioning;
- using System.Diagnostics;
- using System.Diagnostics.Contracts;
-
- [Flags]
- public enum RegistrationClassContext
- {
-
-
- InProcessServer = 0x1,
- InProcessHandler = 0x2,
- LocalServer = 0x4,
- InProcessServer16 = 0x8,
- RemoteServer = 0x10,
- InProcessHandler16 = 0x20,
- Reserved1 = 0x40,
- Reserved2 = 0x80,
- Reserved3 = 0x100,
- Reserved4 = 0x200,
- NoCodeDownload = 0x400,
- Reserved5 = 0x800,
- NoCustomMarshal = 0x1000,
- EnableCodeDownload = 0x2000,
- NoFailureLog = 0x4000,
- DisableActivateAsActivator = 0x8000,
- EnableActivateAsActivator = 0x10000,
- FromDefaultContext = 0x20000
- }
-
-
- [Flags]
- public enum RegistrationConnectionType
- {
- SingleUse = 0,
- MultipleUse = 1,
- MultiSeparate = 2,
- Suspended = 4,
- Surrogate = 8,
- }
-
- [Guid("475E398F-8AFA-43a7-A3BE-F4EF8D6787C9")]
- [ClassInterface(ClassInterfaceType.None)]
-[System.Runtime.InteropServices.ComVisible(true)]
- public class RegistrationServices : IRegistrationServices
- {
- #region Constants
-
- private const String strManagedCategoryGuid = "{62C8FE65-4EBB-45e7-B440-6E39B2CDBF29}";
- private const String strDocStringPrefix = "";
- private const String strManagedTypeThreadingModel = "Both";
- private const String strComponentCategorySubKey = "Component Categories";
- private const String strManagedCategoryDescription = ".NET Category";
- private const String strImplementedCategoriesSubKey = "Implemented Categories";
- private const String strMsCorEEFileName = "mscoree.dll";
- private const String strRecordRootName = "Record";
- private const String strClsIdRootName = "CLSID";
- private const String strTlbRootName = "TypeLib";
- private static Guid s_ManagedCategoryGuid = new Guid(strManagedCategoryGuid);
-
- #endregion
-
-
- #region IRegistrationServices
-
- public virtual bool RegisterAssembly(Assembly assembly, AssemblyRegistrationFlags flags)
- {
- // Validate the arguments.
- if (assembly == null)
- throw new ArgumentNullException(nameof(assembly));
-
- if (assembly.ReflectionOnly)
- throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_AsmLoadedForReflectionOnly"));
- Contract.EndContractBlock();
-
- RuntimeAssembly rtAssembly = assembly as RuntimeAssembly;
- if (rtAssembly == null)
- throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeAssembly"));
-
- // Retrieve the assembly names.
- String strAsmName = assembly.FullName;
- if (strAsmName == null)
- throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_NoAsmName"));
-
- // Retrieve the assembly codebase.
- String strAsmCodeBase = null;
- if ((flags & AssemblyRegistrationFlags.SetCodeBase) != 0)
- {
- strAsmCodeBase = rtAssembly.GetCodeBase(false);
- if (strAsmCodeBase == null)
- throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_NoAsmCodeBase"));
- }
-
- // Go through all the registerable types in the assembly and register them.
- Type[] aTypes = GetRegistrableTypesInAssembly(assembly);
- int NumTypes = aTypes.Length;
-
- String strAsmVersion = rtAssembly.GetVersion().ToString();
-
- // Retrieve the runtime version used to build the assembly.
- String strRuntimeVersion = assembly.ImageRuntimeVersion;
-
- for (int cTypes = 0; cTypes < NumTypes; cTypes++)
- {
- if (IsRegisteredAsValueType(aTypes[cTypes]))
- RegisterValueType(aTypes[cTypes], strAsmName, strAsmVersion, strAsmCodeBase, strRuntimeVersion);
- else if (TypeRepresentsComType(aTypes[cTypes]))
- RegisterComImportedType(aTypes[cTypes], strAsmName, strAsmVersion, strAsmCodeBase, strRuntimeVersion);
- else
- RegisterManagedType(aTypes[cTypes], strAsmName, strAsmVersion, strAsmCodeBase, strRuntimeVersion);
-
- CallUserDefinedRegistrationMethod(aTypes[cTypes], true);
- }
-
- // If this assembly has the PIA attribute, then register it as a PIA.
- Object[] aPIAAttrs = assembly.GetCustomAttributes(typeof(PrimaryInteropAssemblyAttribute), false);
- int NumPIAAttrs = aPIAAttrs.Length;
- for (int cPIAAttrs = 0; cPIAAttrs < NumPIAAttrs; cPIAAttrs++)
- RegisterPrimaryInteropAssembly(rtAssembly, strAsmCodeBase, (PrimaryInteropAssemblyAttribute)aPIAAttrs[cPIAAttrs]);
-
- // Return value indicating if we actually registered any types.
- if (aTypes.Length > 0 || NumPIAAttrs > 0)
- return true;
- else
- return false;
- }
-
- public virtual bool UnregisterAssembly(Assembly assembly)
- {
- // Validate the arguments.
- if (assembly == null)
- throw new ArgumentNullException(nameof(assembly));
-
- if (assembly.ReflectionOnly)
- throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_AsmLoadedForReflectionOnly"));
- Contract.EndContractBlock();
-
- RuntimeAssembly rtAssembly = assembly as RuntimeAssembly;
- if (rtAssembly == null)
- throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeAssembly"));
-
- bool bAllVersionsGone = true;
-
- // Go through all the registrable types in the assembly and register them.
- Type[] aTypes = GetRegistrableTypesInAssembly(assembly);
- int NumTypes = aTypes.Length;
-
- // Retrieve the assembly version
- String strAsmVersion = rtAssembly.GetVersion().ToString();
- for (int cTypes = 0;cTypes < NumTypes;cTypes++)
- {
- CallUserDefinedRegistrationMethod(aTypes[cTypes], false);
-
- if (IsRegisteredAsValueType(aTypes[cTypes]))
- {
- if (!UnregisterValueType(aTypes[cTypes], strAsmVersion))
- bAllVersionsGone = false;
- }
- else if (TypeRepresentsComType(aTypes[cTypes]))
- {
- if (!UnregisterComImportedType(aTypes[cTypes], strAsmVersion))
- bAllVersionsGone = false;
- }
- else
- {
- if (!UnregisterManagedType(aTypes[cTypes], strAsmVersion))
- bAllVersionsGone = false;
- }
- }
-
- // If this assembly has the PIA attribute, then unregister it as a PIA.
- Object[] aPIAAttrs = assembly.GetCustomAttributes(typeof(PrimaryInteropAssemblyAttribute),false);
- int NumPIAAttrs = aPIAAttrs.Length;
- if (bAllVersionsGone)
- {
- for (int cPIAAttrs = 0;cPIAAttrs < NumPIAAttrs;cPIAAttrs++)
- UnregisterPrimaryInteropAssembly(assembly, (PrimaryInteropAssemblyAttribute)aPIAAttrs[cPIAAttrs]);
- }
-
- // Return value indicating if we actually un-registered any types.
- if (aTypes.Length > 0 || NumPIAAttrs > 0)
- return true;
- else
- return false;
- }
-
- public virtual Type[] GetRegistrableTypesInAssembly(Assembly assembly)
- {
- // Validate the arguments.
- if (assembly == null)
- throw new ArgumentNullException(nameof(assembly));
- Contract.EndContractBlock();
-
- if (!(assembly is RuntimeAssembly))
- throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeAssembly"), nameof(assembly));
-
- // Retrieve the list of types in the assembly.
- Type[] aTypes = assembly.GetExportedTypes();
- int NumTypes = aTypes.Length;
-
- // Create an array list that will be filled in.
- ArrayList TypeList = new ArrayList();
-
- // Register all the types that require registration.
- for (int cTypes = 0; cTypes < NumTypes; cTypes++)
- {
- Type CurrentType = aTypes[cTypes];
- if (TypeRequiresRegistration(CurrentType))
- TypeList.Add(CurrentType);
- }
-
- // Copy the array list to an array and return it.
- Type[] RetArray = new Type[TypeList.Count];
- TypeList.CopyTo(RetArray);
- return RetArray;
- }
-
- public virtual String GetProgIdForType(Type type)
- {
- return Marshal.GenerateProgIdForType(type);
- }
-
- public virtual void RegisterTypeForComClients(Type type, ref Guid g)
- {
-#if FEATURE_COMINTEROP_MANAGED_ACTIVATION
- if(type == null)
- throw new ArgumentNullException(nameof(type));
- Contract.EndContractBlock();
- if((type as RuntimeType) == null)
- throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeType"),nameof(type));
- if(!TypeRequiresRegistration(type))
- throw new ArgumentException(Environment.GetResourceString("Argument_TypeMustBeComCreatable"),nameof(type));
-
- // Call the native method to do CoRegisterClassObject
- RegisterTypeForComClientsNative(type, ref g);
-#else // FEATURE_COMINTEROP_MANAGED_ACTIVATION
- throw new NotImplementedException("CoreCLR_REMOVED -- managed activation removed");
-#endif // FEATURE_COMINTEROP_MANAGED_ACTIVATION
- }
-
- public virtual Guid GetManagedCategoryGuid()
- {
- return s_ManagedCategoryGuid;
- }
-
- public virtual bool TypeRequiresRegistration(Type type)
- {
- return TypeRequiresRegistrationHelper(type);
- }
-
- public virtual bool TypeRepresentsComType(Type type)
- {
- // If the type is not a COM import, then it does not represent a COM type.
- if (!type.IsCOMObject)
- return false;
-
- // If it is marked as tdImport, then it represents a COM type directly.
- if (type.IsImport)
- return true;
-
- // 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);
- Debug.Assert(baseComImportType != null, "baseComImportType != null");
- if (Marshal.GenerateGuidForType(type) == Marshal.GenerateGuidForType(baseComImportType))
- return true;
-
- return false;
- }
-
- #endregion
-
-
- #region Public methods not on IRegistrationServices
- [ComVisible(false)]
- public virtual int RegisterTypeForComClients(Type type, RegistrationClassContext classContext, RegistrationConnectionType flags)
- {
-#if FEATURE_COMINTEROP_MANAGED_ACTIVATION
- if (type == null)
- throw new ArgumentNullException(nameof(type));
- Contract.EndContractBlock();
- if ((type as RuntimeType) == null)
- throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeType"),nameof(type));
- if (!TypeRequiresRegistration(type))
- throw new ArgumentException(Environment.GetResourceString("Argument_TypeMustBeComCreatable"),nameof(type));
-
- // Call the native method to do CoRegisterClassObject
- return RegisterTypeForComClientsExNative(type, classContext, flags);
-#else // FEATURE_COMINTEROP_MANAGED_ACTIVATION
- throw new NotImplementedException("CoreCLR_REMOVED -- managed activation removed");
-#endif // FEATURE_COMINTEROP_MANAGED_ACTIVATION
- }
-
- [ComVisible(false)]
- public virtual void UnregisterTypeForComClients(int cookie)
- {
- // Call the native method to do CoRevokeClassObject.
- CoRevokeClassObject(cookie);
- }
-
- #endregion
-
-
- #region Internal helpers
-
- internal static bool TypeRequiresRegistrationHelper(Type type)
- {
- // If the type is not a class or a value class, then it does not get registered.
- if (!type.IsClass && !type.IsValueType)
- return false;
-
- // If the type is abstract then it does not get registered.
- if (type.IsAbstract)
- return false;
-
- // If the does not have a public default constructor then is not creatable from COM so
- // it does not require registration unless it is a value class.
- if (!type.IsValueType && type.GetConstructor(BindingFlags.Instance | BindingFlags.Public,null,Array.Empty<Type>(),null) == null)
- return false;
-
- // All other conditions are met so check to see if the type is visible from COM.
- return Marshal.IsTypeVisibleFromCom(type);
- }
-
- #endregion
-
-
- #region Private helpers
-
- private void RegisterValueType(Type type, String strAsmName, String strAsmVersion, String strAsmCodeBase, String strRuntimeVersion)
- {
- // Retrieve some information that will be used during the registration process.
- String strRecordId = "{" + Marshal.GenerateGuidForType(type).ToString().ToUpper(CultureInfo.InvariantCulture) + "}";
-
- // Create the HKEY_CLASS_ROOT\Record key.
- using (RegistryKey RecordRootKey = Registry.ClassesRoot.CreateSubKey(strRecordRootName))
- {
- // Create the HKEY_CLASS_ROOT\Record\<RecordID> key.
- using (RegistryKey RecordKey = RecordRootKey.CreateSubKey(strRecordId))
- {
- // Create the HKEY_CLASS_ROOT\Record\<RecordId>\<version> key.
- using (RegistryKey RecordVersionKey = RecordKey.CreateSubKey(strAsmVersion))
- {
- // Set the class value.
- RecordVersionKey.SetValue("Class", type.FullName);
-
- // Set the assembly value.
- RecordVersionKey.SetValue("Assembly", strAsmName);
-
- // Set the runtime version value.
- RecordVersionKey.SetValue("RuntimeVersion", strRuntimeVersion);
-
- // Set the assembly code base value if a code base was specified.
- if (strAsmCodeBase != null)
- RecordVersionKey.SetValue("CodeBase", strAsmCodeBase);
- }
- }
- }
- }
-
- private void RegisterManagedType(Type type, String strAsmName, String strAsmVersion, String strAsmCodeBase, String strRuntimeVersion)
- {
- //
- // Retrieve some information that will be used during the registration process.
- //
-
- String strDocString = strDocStringPrefix + type.FullName;
- String strClsId = "{" + Marshal.GenerateGuidForType(type).ToString().ToUpper(CultureInfo.InvariantCulture) + "}";
- String strProgId = GetProgIdForType(type);
-
-
- //
- // Write the actual type information in the registry.
- //
-
- if (strProgId != String.Empty)
- {
- // Create the HKEY_CLASS_ROOT\<wzProgId> key.
- using (RegistryKey TypeNameKey = Registry.ClassesRoot.CreateSubKey(strProgId))
- {
- TypeNameKey.SetValue("", strDocString);
-
- // Create the HKEY_CLASS_ROOT\<wzProgId>\CLSID key.
- using (RegistryKey ProgIdClsIdKey = TypeNameKey.CreateSubKey("CLSID"))
- {
- ProgIdClsIdKey.SetValue("", strClsId);
- }
- }
- }
-
- // Create the HKEY_CLASS_ROOT\CLSID key.
- using (RegistryKey ClsIdRootKey = Registry.ClassesRoot.CreateSubKey(strClsIdRootName))
- {
- // Create the HKEY_CLASS_ROOT\CLSID\<CLSID> key.
- using (RegistryKey ClsIdKey = ClsIdRootKey.CreateSubKey(strClsId))
- {
- ClsIdKey.SetValue("", strDocString);
-
- // Create the HKEY_CLASS_ROOT\CLSID\<CLSID>\InprocServer32 key.
- using (RegistryKey InProcServerKey = ClsIdKey.CreateSubKey("InprocServer32"))
- {
- InProcServerKey.SetValue("", strMsCorEEFileName);
- InProcServerKey.SetValue("ThreadingModel", strManagedTypeThreadingModel);
- InProcServerKey.SetValue("Class", type.FullName);
- InProcServerKey.SetValue("Assembly", strAsmName);
- InProcServerKey.SetValue("RuntimeVersion", strRuntimeVersion);
- if (strAsmCodeBase != null)
- InProcServerKey.SetValue("CodeBase", strAsmCodeBase);
-
- // Create the HKEY_CLASS_ROOT\CLSID\<CLSID>\InprocServer32\<Version> subkey
- using (RegistryKey VersionSubKey = InProcServerKey.CreateSubKey(strAsmVersion))
- {
- VersionSubKey.SetValue("Class", type.FullName);
- VersionSubKey.SetValue("Assembly", strAsmName);
- VersionSubKey.SetValue("RuntimeVersion", strRuntimeVersion);
- if (strAsmCodeBase != null)
- VersionSubKey.SetValue("CodeBase", strAsmCodeBase);
- }
-
- if (strProgId != String.Empty)
- {
- // Create the HKEY_CLASS_ROOT\CLSID\<CLSID>\ProdId key.
- using (RegistryKey ProgIdKey = ClsIdKey.CreateSubKey("ProgId"))
- {
- ProgIdKey.SetValue("", strProgId);
- }
- }
- }
-
- // Create the HKEY_CLASS_ROOT\CLSID\<CLSID>\Implemented Categories\<Managed Category Guid> key.
- using (RegistryKey CategoryKey = ClsIdKey.CreateSubKey(strImplementedCategoriesSubKey))
- {
- using (RegistryKey ManagedCategoryKey = CategoryKey.CreateSubKey(strManagedCategoryGuid)) {}
- }
- }
- }
-
-
- //
- // Ensure that the managed category exists.
- //
-
- EnsureManagedCategoryExists();
- }
-
- private void RegisterComImportedType(Type type, String strAsmName, String strAsmVersion, String strAsmCodeBase, String strRuntimeVersion)
- {
- // Retrieve some information that will be used during the registration process.
- String strClsId = "{" + Marshal.GenerateGuidForType(type).ToString().ToUpper(CultureInfo.InvariantCulture) + "}";
-
- // Create the HKEY_CLASS_ROOT\CLSID key.
- using (RegistryKey ClsIdRootKey = Registry.ClassesRoot.CreateSubKey(strClsIdRootName))
- {
- // Create the HKEY_CLASS_ROOT\CLSID\<CLSID> key.
- using (RegistryKey ClsIdKey = ClsIdRootKey.CreateSubKey(strClsId))
- {
- // Create the HKEY_CLASS_ROOT\CLSID\<CLSID>\InProcServer32 key.
- using (RegistryKey InProcServerKey = ClsIdKey.CreateSubKey("InprocServer32"))
- {
- // Set the class value.
- InProcServerKey.SetValue("Class", type.FullName);
-
- // Set the assembly value.
- InProcServerKey.SetValue("Assembly", strAsmName);
-
- // Set the runtime version value.
- InProcServerKey.SetValue("RuntimeVersion", strRuntimeVersion);
-
- // Set the assembly code base value if a code base was specified.
- if (strAsmCodeBase != null)
- InProcServerKey.SetValue("CodeBase", strAsmCodeBase);
-
- // Create the HKEY_CLASS_ROOT\CLSID\<CLSID>\InprocServer32\<Version> subkey
- using (RegistryKey VersionSubKey = InProcServerKey.CreateSubKey(strAsmVersion))
- {
- VersionSubKey.SetValue("Class", type.FullName);
- VersionSubKey.SetValue("Assembly", strAsmName);
- VersionSubKey.SetValue("RuntimeVersion", strRuntimeVersion);
- if (strAsmCodeBase != null)
- VersionSubKey.SetValue("CodeBase", strAsmCodeBase);
- }
- }
- }
- }
- }
-
- private bool UnregisterValueType(Type type, String strAsmVersion)
- {
- bool bAllVersionsGone = true;
-
- // Try to open the HKEY_CLASS_ROOT\Record key.
- String strRecordId = "{" + Marshal.GenerateGuidForType(type).ToString().ToUpper(CultureInfo.InvariantCulture) + "}";
-
- using (RegistryKey RecordRootKey = Registry.ClassesRoot.OpenSubKey(strRecordRootName, true))
- {
- if (RecordRootKey != null)
- {
- // Open the HKEY_CLASS_ROOT\Record\{RecordId} key.
- using (RegistryKey RecordKey = RecordRootKey.OpenSubKey(strRecordId,true))
- {
- if (RecordKey != null)
- {
- using (RegistryKey VersionSubKey = RecordKey.OpenSubKey(strAsmVersion,true))
- {
- if (VersionSubKey != null)
- {
- // Delete the values we created.
- VersionSubKey.DeleteValue("Assembly",false);
- VersionSubKey.DeleteValue("Class",false);
- VersionSubKey.DeleteValue("CodeBase",false);
- VersionSubKey.DeleteValue("RuntimeVersion",false);
-
- // delete the version sub key if no value or subkeys under it
- if ((VersionSubKey.SubKeyCount == 0) && (VersionSubKey.ValueCount == 0))
- RecordKey.DeleteSubKey(strAsmVersion);
- }
- }
-
- // If there are sub keys left then there are versions left.
- if (RecordKey.SubKeyCount != 0)
- bAllVersionsGone = false;
-
- // If there are no other values or subkeys then we can delete the HKEY_CLASS_ROOT\Record\{RecordId}.
- if ((RecordKey.SubKeyCount == 0) && (RecordKey.ValueCount == 0))
- RecordRootKey.DeleteSubKey(strRecordId);
- }
- }
-
- // If there are no other values or subkeys then we can delete the HKEY_CLASS_ROOT\Record.
- if ((RecordRootKey.SubKeyCount == 0) && (RecordRootKey.ValueCount == 0))
- Registry.ClassesRoot.DeleteSubKey(strRecordRootName);
- }
- }
-
- return bAllVersionsGone;
- }
-
- // UnregisterManagedType
- //
- // Return :
- // true: All versions are gone.
- // false: Some versions are still left in registry
- private bool UnregisterManagedType(Type type,String strAsmVersion)
- {
- bool bAllVersionsGone = true;
-
- //
- // Create the CLSID string.
- //
-
- String strClsId = "{" + Marshal.GenerateGuidForType(type).ToString().ToUpper(CultureInfo.InvariantCulture) + "}";
- String strProgId = GetProgIdForType(type);
-
-
- //
- // Remove the entries under HKEY_CLASS_ROOT\CLSID key.
- //
-
- using (RegistryKey ClsIdRootKey = Registry.ClassesRoot.OpenSubKey(strClsIdRootName, true))
- {
- if (ClsIdRootKey != null)
- {
- //
- // Remove the entries under HKEY_CLASS_ROOT\CLSID\<CLSID> key.
- //
-
- using (RegistryKey ClsIdKey = ClsIdRootKey.OpenSubKey(strClsId, true))
- {
- if (ClsIdKey != null)
- {
- //
- // Remove the entries in the HKEY_CLASS_ROOT\CLSID\<CLSID>\InprocServer32 key.
- //
-
- using (RegistryKey InProcServerKey = ClsIdKey.OpenSubKey("InprocServer32", true))
- {
- if (InProcServerKey != null)
- {
- //
- // Remove the entries in HKEY_CLASS_ROOT\CLSID\<CLSID>\InprocServer32\<Version>
- //
-
- using (RegistryKey VersionSubKey = InProcServerKey.OpenSubKey(strAsmVersion, true))
- {
- if (VersionSubKey != null)
- {
- // Delete the values we created
- VersionSubKey.DeleteValue("Assembly",false);
- VersionSubKey.DeleteValue("Class",false);
- VersionSubKey.DeleteValue("RuntimeVersion",false);
- VersionSubKey.DeleteValue("CodeBase",false);
-
- // If there are no other values or subkeys then we can delete the VersionSubKey.
- if ((VersionSubKey.SubKeyCount == 0) && (VersionSubKey.ValueCount == 0))
- InProcServerKey.DeleteSubKey(strAsmVersion);
- }
- }
-
- // If there are sub keys left then there are versions left.
- if (InProcServerKey.SubKeyCount != 0)
- bAllVersionsGone = false;
-
- // If there are no versions left, then delete the threading model and default value.
- if (bAllVersionsGone)
- {
- InProcServerKey.DeleteValue("",false);
- InProcServerKey.DeleteValue("ThreadingModel",false);
- }
-
- InProcServerKey.DeleteValue("Assembly",false);
- InProcServerKey.DeleteValue("Class",false);
- InProcServerKey.DeleteValue("RuntimeVersion",false);
- InProcServerKey.DeleteValue("CodeBase",false);
-
- // If there are no other values or subkeys then we can delete the InProcServerKey.
- if ((InProcServerKey.SubKeyCount == 0) && (InProcServerKey.ValueCount == 0))
- ClsIdKey.DeleteSubKey("InprocServer32");
- }
- }
-
- // remove HKEY_CLASS_ROOT\CLSID\<CLSID>\ProgId
- // and HKEY_CLASS_ROOT\CLSID\<CLSID>\Implemented Category
- // only when all versions are removed
- if (bAllVersionsGone)
- {
- // Delete the value we created.
- ClsIdKey.DeleteValue("",false);
-
- if (strProgId != String.Empty)
- {
- //
- // Remove the entries in the HKEY_CLASS_ROOT\CLSID\<CLSID>\ProgId key.
- //
-
- using (RegistryKey ProgIdKey = ClsIdKey.OpenSubKey("ProgId", true))
- {
- if (ProgIdKey != null)
- {
- // Delete the value we created.
- ProgIdKey.DeleteValue("",false);
-
- // If there are no other values or subkeys then we can delete the ProgIdSubKey.
- if ((ProgIdKey.SubKeyCount == 0) && (ProgIdKey.ValueCount == 0))
- ClsIdKey.DeleteSubKey("ProgId");
- }
- }
- }
-
-
- //
- // Remove entries in the HKEY_CLASS_ROOT\CLSID\<CLSID>\Implemented Categories\<Managed Category Guid> key.
- //
-
- using (RegistryKey CategoryKey = ClsIdKey.OpenSubKey(strImplementedCategoriesSubKey, true))
- {
- if (CategoryKey != null)
- {
- using (RegistryKey ManagedCategoryKey = CategoryKey.OpenSubKey(strManagedCategoryGuid, true))
- {
- if (ManagedCategoryKey != null)
- {
- // If there are no other values or subkeys then we can delete the ManagedCategoryKey.
- if ((ManagedCategoryKey.SubKeyCount == 0) && (ManagedCategoryKey.ValueCount == 0))
- CategoryKey.DeleteSubKey(strManagedCategoryGuid);
- }
- }
-
- // If there are no other values or subkeys then we can delete the CategoryKey.
- if ((CategoryKey.SubKeyCount == 0) && (CategoryKey.ValueCount == 0))
- ClsIdKey.DeleteSubKey(strImplementedCategoriesSubKey);
- }
- }
- }
-
- // If there are no other values or subkeys then we can delete the ClsIdKey.
- if ((ClsIdKey.SubKeyCount == 0) && (ClsIdKey.ValueCount == 0))
- ClsIdRootKey.DeleteSubKey(strClsId);
- }
- }
-
- // If there are no other values or subkeys then we can delete the CLSID key.
- if ((ClsIdRootKey.SubKeyCount == 0) && (ClsIdRootKey.ValueCount == 0))
- Registry.ClassesRoot.DeleteSubKey(strClsIdRootName);
- }
-
-
- //
- // Remove the entries under HKEY_CLASS_ROOT\<wzProgId> key.
- //
-
- if (bAllVersionsGone)
- {
- if (strProgId != String.Empty)
- {
- using (RegistryKey TypeNameKey = Registry.ClassesRoot.OpenSubKey(strProgId, true))
- {
- if (TypeNameKey != null)
- {
- // Delete the values we created.
- TypeNameKey.DeleteValue("",false);
-
-
- //
- // Remove the entries in the HKEY_CLASS_ROOT\<wzProgId>\CLSID key.
- //
-
- using (RegistryKey ProgIdClsIdKey = TypeNameKey.OpenSubKey("CLSID", true))
- {
- if (ProgIdClsIdKey != null)
- {
- // Delete the values we created.
- ProgIdClsIdKey.DeleteValue("",false);
-
- // If there are no other values or subkeys then we can delete the ProgIdClsIdKey.
- if ((ProgIdClsIdKey.SubKeyCount == 0) && (ProgIdClsIdKey.ValueCount == 0))
- TypeNameKey.DeleteSubKey("CLSID");
- }
- }
-
- // If there are no other values or subkeys then we can delete the TypeNameKey.
- if ((TypeNameKey.SubKeyCount == 0) && (TypeNameKey.ValueCount == 0))
- Registry.ClassesRoot.DeleteSubKey(strProgId);
- }
- }
- }
- }
- }
-
- return bAllVersionsGone;
- }
-
- // UnregisterComImportedType
- // Return:
- // true: All version information are gone.
- // false: There are still some version left in registry
- private bool UnregisterComImportedType(Type type, String strAsmVersion)
- {
- bool bAllVersionsGone = true;
-
- String strClsId = "{" + Marshal.GenerateGuidForType(type).ToString().ToUpper(CultureInfo.InvariantCulture) + "}";
-
- // Try to open the HKEY_CLASS_ROOT\CLSID key.
- using (RegistryKey ClsIdRootKey = Registry.ClassesRoot.OpenSubKey(strClsIdRootName, true))
- {
- if (ClsIdRootKey != null)
- {
- // Try to open the HKEY_CLASS_ROOT\CLSID\<CLSID> key.
- using (RegistryKey ClsIdKey = ClsIdRootKey.OpenSubKey(strClsId, true))
- {
- if (ClsIdKey != null)
- {
- // Try to open the HKEY_CLASS_ROOT\CLSID\<CLSID>\InProcServer32 key.
- using (RegistryKey InProcServerKey = ClsIdKey.OpenSubKey("InprocServer32", true))
- {
- if (InProcServerKey != null)
- {
- // Delete the values we created.
- InProcServerKey.DeleteValue("Assembly",false);
- InProcServerKey.DeleteValue("Class",false);
- InProcServerKey.DeleteValue("RuntimeVersion",false);
- InProcServerKey.DeleteValue("CodeBase",false);
-
- // Try to open the entries in HKEY_CLASS_ROOT\CLSID\<CLSID>\InProcServer32\<Version>
- using (RegistryKey VersionSubKey = InProcServerKey.OpenSubKey(strAsmVersion,true))
- {
- if (VersionSubKey != null)
- {
- // Delete the value we created
- VersionSubKey.DeleteValue("Assembly",false);
- VersionSubKey.DeleteValue("Class",false);
- VersionSubKey.DeleteValue("RuntimeVersion",false);
- VersionSubKey.DeleteValue("CodeBase",false);
-
- // If there are no other values or subkeys then we can delete the VersionSubKey
- if ((VersionSubKey.SubKeyCount == 0) && (VersionSubKey.ValueCount == 0))
- InProcServerKey.DeleteSubKey(strAsmVersion);
- }
- }
-
- // If there are sub keys left then there are versions left.
- if (InProcServerKey.SubKeyCount != 0)
- bAllVersionsGone = false;
-
- // If there are no other values or subkeys then we can delete the InProcServerKey.
- if ((InProcServerKey.SubKeyCount == 0) && (InProcServerKey.ValueCount == 0))
- ClsIdKey.DeleteSubKey("InprocServer32");
- }
- }
-
- // If there are no other values or subkeys then we can delete the ClsIdKey.
- if ((ClsIdKey.SubKeyCount == 0) && (ClsIdKey.ValueCount == 0))
- ClsIdRootKey.DeleteSubKey(strClsId);
- }
- }
-
- // If there are no other values or subkeys then we can delete the CLSID key.
- if ((ClsIdRootKey.SubKeyCount == 0) && (ClsIdRootKey.ValueCount == 0))
- Registry.ClassesRoot.DeleteSubKey(strClsIdRootName);
- }
- }
-
- return bAllVersionsGone;
- }
-
- private void RegisterPrimaryInteropAssembly(RuntimeAssembly assembly, String strAsmCodeBase, PrimaryInteropAssemblyAttribute attr)
- {
- // Validate that the PIA has a strong name.
- if (assembly.GetPublicKey().Length == 0)
- throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_PIAMustBeStrongNamed"));
-
- String strTlbId = "{" + Marshal.GetTypeLibGuidForAssembly(assembly).ToString().ToUpper(CultureInfo.InvariantCulture) + "}";
- String strVersion = attr.MajorVersion.ToString("x", CultureInfo.InvariantCulture) + "." + attr.MinorVersion.ToString("x", CultureInfo.InvariantCulture);
-
- // Create the HKEY_CLASS_ROOT\TypeLib key.
- using (RegistryKey TypeLibRootKey = Registry.ClassesRoot.CreateSubKey(strTlbRootName))
- {
- // Create the HKEY_CLASS_ROOT\TypeLib\<TLBID> key.
- using (RegistryKey TypeLibKey = TypeLibRootKey.CreateSubKey(strTlbId))
- {
- // Create the HKEY_CLASS_ROOT\TypeLib\<TLBID>\<Major.Minor> key.
- using (RegistryKey VersionSubKey = TypeLibKey.CreateSubKey(strVersion))
- {
- // Create the HKEY_CLASS_ROOT\TypeLib\<TLBID>\PrimaryInteropAssembly key.
- VersionSubKey.SetValue("PrimaryInteropAssemblyName", assembly.FullName);
- if (strAsmCodeBase != null)
- VersionSubKey.SetValue("PrimaryInteropAssemblyCodeBase", strAsmCodeBase);
- }
- }
- }
- }
-
- private void UnregisterPrimaryInteropAssembly(Assembly assembly, PrimaryInteropAssemblyAttribute attr)
- {
- String strTlbId = "{" + Marshal.GetTypeLibGuidForAssembly(assembly).ToString().ToUpper(CultureInfo.InvariantCulture) + "}";
- String strVersion = attr.MajorVersion.ToString("x", CultureInfo.InvariantCulture) + "." + attr.MinorVersion.ToString("x", CultureInfo.InvariantCulture);
-
- // Try to open the HKEY_CLASS_ROOT\TypeLib key.
- using (RegistryKey TypeLibRootKey = Registry.ClassesRoot.OpenSubKey(strTlbRootName, true))
- {
- if (TypeLibRootKey != null)
- {
- // Try to open the HKEY_CLASS_ROOT\TypeLib\<TLBID> key.
- using (RegistryKey TypeLibKey = TypeLibRootKey.OpenSubKey(strTlbId, true))
- {
- if (TypeLibKey != null)
- {
- // Try to open the HKEY_CLASS_ROOT\TypeLib<TLBID>\<Major.Minor> key.
- using (RegistryKey VersionSubKey = TypeLibKey.OpenSubKey(strVersion, true))
- {
- if (VersionSubKey != null)
- {
- // Delete the values we created.
- VersionSubKey.DeleteValue("PrimaryInteropAssemblyName",false);
- VersionSubKey.DeleteValue("PrimaryInteropAssemblyCodeBase",false);
-
- // If there are no other values or subkeys then we can delete the VersionKey.
- if ((VersionSubKey.SubKeyCount == 0) && (VersionSubKey.ValueCount == 0))
- TypeLibKey.DeleteSubKey(strVersion);
- }
- }
-
- // If there are no other values or subkeys then we can delete the TypeLibKey.
- if ((TypeLibKey.SubKeyCount == 0) && (TypeLibKey.ValueCount == 0))
- TypeLibRootKey.DeleteSubKey(strTlbId);
- }
- }
-
- // If there are no other values or subkeys then we can delete the TypeLib key.
- if ((TypeLibRootKey.SubKeyCount == 0) && (TypeLibRootKey.ValueCount == 0))
- Registry.ClassesRoot.DeleteSubKey(strTlbRootName);
- }
- }
- }
-
- private void EnsureManagedCategoryExists()
- {
- if (!ManagedCategoryExists())
- {
- // Create the HKEY_CLASS_ROOT\Component Category key.
- using (RegistryKey ComponentCategoryKey = Registry.ClassesRoot.CreateSubKey(strComponentCategorySubKey))
- {
- // Create the HKEY_CLASS_ROOT\Component Category\<Managed Category Guid> key.
- using (RegistryKey ManagedCategoryKey = ComponentCategoryKey.CreateSubKey(strManagedCategoryGuid))
- {
- ManagedCategoryKey.SetValue("0", strManagedCategoryDescription);
- }
- }
- }
- }
-
- private static bool ManagedCategoryExists()
- {
- using (RegistryKey componentCategoryKey = Registry.ClassesRoot.OpenSubKey(strComponentCategorySubKey,
- false))
- {
- if (componentCategoryKey == null)
- return false;
- using (RegistryKey managedCategoryKey = componentCategoryKey.OpenSubKey(strManagedCategoryGuid,
- false))
- {
- if (managedCategoryKey == null)
- return false;
- object value = managedCategoryKey.GetValue("0");
- if (value == null || value.GetType() != typeof(string))
- return false;
- string stringValue = (string)value;
- if (stringValue != strManagedCategoryDescription)
- return false;
- }
- }
-
- return true;
- }
-
- private void CallUserDefinedRegistrationMethod(Type type, bool bRegister)
- {
- bool bFunctionCalled = false;
-
- // Retrieve the attribute type to use to determine if a function is the requested user defined
- // registration function.
- Type RegFuncAttrType = null;
- if(bRegister)
- RegFuncAttrType = typeof(ComRegisterFunctionAttribute);
- else
- RegFuncAttrType = typeof(ComUnregisterFunctionAttribute);
-
- for(Type currType = type; !bFunctionCalled && currType != null; currType = currType.BaseType)
- {
- // Retrieve all the methods.
- MethodInfo[] aMethods = currType.GetMethods(BindingFlags.Instance|BindingFlags.Public|BindingFlags.NonPublic|BindingFlags.Static);
- int NumMethods = aMethods.Length;
-
- // Go through all the methods and check for the ComRegisterMethod custom attribute.
- for(int cMethods = 0;cMethods < NumMethods;cMethods++)
- {
- MethodInfo CurrentMethod = aMethods[cMethods];
-
- // Check to see if the method has the custom attribute.
- if(CurrentMethod.GetCustomAttributes(RegFuncAttrType, true).Length != 0)
- {
- // Check to see if the method is static before we call it.
- if(!CurrentMethod.IsStatic)
- {
- if(bRegister)
- throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_NonStaticComRegFunction",CurrentMethod.Name,currType.Name));
- else
- throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_NonStaticComUnRegFunction",CurrentMethod.Name,currType.Name));
- }
-
- // Finally check that the signature is string ret void.
- ParameterInfo[] aParams = CurrentMethod.GetParameters();
- if (CurrentMethod.ReturnType != typeof(void) ||
- aParams == null ||
- aParams.Length != 1 ||
- (aParams[0].ParameterType != typeof(String) && aParams[0].ParameterType != typeof(Type)))
- {
- if(bRegister)
- throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_InvalidComRegFunctionSig",CurrentMethod.Name,currType.Name));
- else
- throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_InvalidComUnRegFunctionSig",CurrentMethod.Name,currType.Name));
- }
-
- // There can only be one register and one unregister function per type.
- if(bFunctionCalled)
- {
- if(bRegister)
- throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_MultipleComRegFunctions",currType.Name));
- else
- throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_MultipleComUnRegFunctions",currType.Name));
- }
-
- // The function is valid so set up the arguments to call it.
- Object[] objs = new Object[1];
- if(aParams[0].ParameterType == typeof(String))
- {
- // We are dealing with the string overload of the function.
- objs[0] = "HKEY_CLASSES_ROOT\\CLSID\\{" + Marshal.GenerateGuidForType(type).ToString().ToUpper(CultureInfo.InvariantCulture) + "}";
- }
- else
- {
- // We are dealing with the type overload of the function.
- objs[0] = type;
- }
-
- // Invoke the COM register function.
- CurrentMethod.Invoke(null, objs);
-
- // Mark the function as having been called.
- bFunctionCalled = true;
- }
- }
- }
- }
-
- private Type GetBaseComImportType(Type type)
- {
- for (; type != null && !type.IsImport; type = type.BaseType);
- return type;
- }
-
- private bool IsRegisteredAsValueType(Type type)
- {
- if (!type.IsValueType)
- return false;
-
- return true;
- }
-
- #endregion
-
-
- #region FCalls and DllImports
-
-#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.
- [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.
- [MethodImplAttribute(MethodImplOptions.InternalCall)]
- private static extern int RegisterTypeForComClientsExNative(Type t, RegistrationClassContext clsContext, RegistrationConnectionType flags);
-#endif // FEATURE_COMINTEROP_MANAGED_ACTIVATION
-
- [DllImport(Win32Native.OLE32,CharSet=CharSet.Auto,PreserveSig=false)]
- private static extern void CoRevokeClassObject(int cookie);
- #endregion
- }
-}
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/RuntimeEnvironment.cs b/src/mscorlib/src/System/Runtime/InteropServices/RuntimeEnvironment.cs
index a5c058da43..28abe0cb3b 100644
--- a/src/mscorlib/src/System/Runtime/InteropServices/RuntimeEnvironment.cs
+++ b/src/mscorlib/src/System/Runtime/InteropServices/RuntimeEnvironment.cs
@@ -17,7 +17,6 @@ using System.IO;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Security;
-using System.Security.Permissions;
using System.Reflection;
using Microsoft.Win32;
using System.Runtime.Versioning;
@@ -25,96 +24,18 @@ using StackCrawlMark = System.Threading.StackCrawlMark;
namespace System.Runtime.InteropServices
{
- [System.Runtime.InteropServices.ComVisible(true)]
- static public class RuntimeEnvironment {
+ static internal class RuntimeEnvironment {
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern String GetModuleFileName();
- [MethodImplAttribute(MethodImplOptions.InternalCall)]
- internal static extern String GetDeveloperPath();
-
- [MethodImplAttribute(MethodImplOptions.InternalCall)]
- internal static extern String GetHostBindingFile();
-
- public static bool FromGlobalAccessCache(Assembly a)
- {
- return a.GlobalAssemblyCache;
- }
-
[MethodImpl (MethodImplOptions.NoInlining)]
public static String GetSystemVersion()
{
return Assembly.GetExecutingAssembly().ImageRuntimeVersion;
}
- public static String GetRuntimeDirectory()
- {
- String dir = GetRuntimeDirectoryImpl();
- new FileIOPermission(FileIOPermissionAccess.PathDiscovery, dir).Demand();
- return dir;
- }
-
- [MethodImplAttribute(MethodImplOptions.InternalCall)]
- internal static extern String GetRuntimeDirectoryImpl();
-
- // Returns the system ConfigurationFile
- public static String SystemConfigurationFile {
- get {
- StringBuilder sb = new StringBuilder(Path.MaxPath);
- sb.Append(GetRuntimeDirectory());
- sb.Append(AppDomainSetup.RuntimeConfigurationFile);
- String path = sb.ToString();
-
- // Do security check
- new FileIOPermission(FileIOPermissionAccess.PathDiscovery, path).Demand();
-
- return path;
- }
- }
-
#if FEATURE_COMINTEROP
- [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
- [SuppressUnmanagedCodeSecurity]
- private static extern IntPtr GetRuntimeInterfaceImpl(
- [In, MarshalAs(UnmanagedType.LPStruct)] Guid clsid,
- [In, MarshalAs(UnmanagedType.LPStruct)] Guid riid);
-
- //
- // This function does the equivalent of calling GetInterface(clsid, riid) on the
- // ICLRRuntimeInfo representing this runtime. See MetaHost.idl for a list of
- // CLSIDs and IIDs supported by this method.
- //
- // Returns unmanaged pointer to requested interface on success. Throws
- // COMException with failed HR if there is a QI failure.
- //
- [ComVisible(false)]
- public static IntPtr GetRuntimeInterfaceAsIntPtr(Guid clsid, Guid riid)
- {
- return GetRuntimeInterfaceImpl(clsid, riid);
- }
-
- //
- // This function does the equivalent of calling GetInterface(clsid, riid) on the
- // ICLRRuntimeInfo representing this runtime. See MetaHost.idl for a list of
- // CLSIDs and IIDs supported by this method.
- //
- // Returns an RCW to requested interface on success. Throws
- // COMException with failed HR if there is a QI failure.
- //
- [ComVisible(false)]
- public static object GetRuntimeInterfaceAsObject(Guid clsid, Guid riid)
- {
- IntPtr p = IntPtr.Zero;
- try {
- p = GetRuntimeInterfaceImpl(clsid, riid);
- return Marshal.GetObjectForIUnknown(p);
- } finally {
- if(p != IntPtr.Zero) {
- Marshal.Release(p);
- }
- }
- }
#endif // FEATURE_COMINTEROP
}
}
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/SEHException.cs b/src/mscorlib/src/System/Runtime/InteropServices/SEHException.cs
index b418d914ed..72b98738ae 100644
--- a/src/mscorlib/src/System/Runtime/InteropServices/SEHException.cs
+++ b/src/mscorlib/src/System/Runtime/InteropServices/SEHException.cs
@@ -17,7 +17,6 @@ namespace System.Runtime.InteropServices {
using System.Runtime.Serialization;
// Exception for Structured Exception Handler exceptions.
//
- [System.Runtime.InteropServices.ComVisible(true)]
[Serializable]
public class SEHException : ExternalException {
public SEHException()
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/SafeArrayRankMismatchException.cs b/src/mscorlib/src/System/Runtime/InteropServices/SafeArrayRankMismatchException.cs
index 0f4caa21a1..12bf7e7e47 100644
--- a/src/mscorlib/src/System/Runtime/InteropServices/SafeArrayRankMismatchException.cs
+++ b/src/mscorlib/src/System/Runtime/InteropServices/SafeArrayRankMismatchException.cs
@@ -15,7 +15,6 @@ namespace System.Runtime.InteropServices {
using System;
using System.Runtime.Serialization;
- [System.Runtime.InteropServices.ComVisible(true)]
[Serializable]
public class SafeArrayRankMismatchException : SystemException {
public SafeArrayRankMismatchException()
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/SafeArrayTypeMismatchException.cs b/src/mscorlib/src/System/Runtime/InteropServices/SafeArrayTypeMismatchException.cs
index a5711c1ade..050772af2c 100644
--- a/src/mscorlib/src/System/Runtime/InteropServices/SafeArrayTypeMismatchException.cs
+++ b/src/mscorlib/src/System/Runtime/InteropServices/SafeArrayTypeMismatchException.cs
@@ -16,7 +16,6 @@ namespace System.Runtime.InteropServices {
using System;
using System.Runtime.Serialization;
- [System.Runtime.InteropServices.ComVisible(true)]
[Serializable]
public class SafeArrayTypeMismatchException : SystemException {
public SafeArrayTypeMismatchException()
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/SafeBuffer.cs b/src/mscorlib/src/System/Runtime/InteropServices/SafeBuffer.cs
index eba67ae74e..ee5c3d8e87 100644
--- a/src/mscorlib/src/System/Runtime/InteropServices/SafeBuffer.cs
+++ b/src/mscorlib/src/System/Runtime/InteropServices/SafeBuffer.cs
@@ -69,7 +69,6 @@
namespace System.Runtime.InteropServices
{
using System;
-using System.Security.Permissions;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
using System.Runtime.ConstrainedExecution;
@@ -175,7 +174,6 @@ using System.Diagnostics.Contracts;
/// the pointer from within the SafeBuffer. You must set
/// pointer to null before calling this method.</param>
[CLSCompliant(false)]
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
public void AcquirePointer(ref byte* pointer)
{
if (_numBytes == Uninitialized)
@@ -194,7 +192,6 @@ using System.Diagnostics.Contracts;
}
}
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
public void ReleasePointer()
{
if (_numBytes == Uninitialized)
@@ -212,7 +209,6 @@ using System.Diagnostics.Contracts;
/// may have to consider alignment.</param>
/// <returns>An instance of T read from memory.</returns>
[CLSCompliant(false)]
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
public T Read<T>(ulong byteOffset) where T : struct {
if (_numBytes == Uninitialized)
throw NotInitialized();
@@ -240,7 +236,6 @@ using System.Diagnostics.Contracts;
}
[CLSCompliant(false)]
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
public void ReadArray<T>(ulong byteOffset, T[] array, int index, int count)
where T : struct
{
@@ -287,7 +282,6 @@ using System.Diagnostics.Contracts;
/// may have to consider alignment.</param>
/// <param name="value">The value type to write to memory.</param>
[CLSCompliant(false)]
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
public void Write<T>(ulong byteOffset, T value) where T : struct {
if (_numBytes == Uninitialized)
throw NotInitialized();
@@ -312,7 +306,6 @@ using System.Diagnostics.Contracts;
}
[CLSCompliant(false)]
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
public void WriteArray<T>(ulong byteOffset, T[] array, int index, int count)
where T : struct
{
@@ -355,7 +348,6 @@ using System.Diagnostics.Contracts;
/// </summary>
[CLSCompliant(false)]
public ulong ByteLength {
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
get {
if (_numBytes == Uninitialized)
throw NotInitialized();
@@ -367,7 +359,6 @@ using System.Diagnostics.Contracts;
/* No indexer. The perf would be misleadingly bad. People should use
* AcquirePointer and ReleasePointer instead. */
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
private void SpaceCheck(byte* ptr, ulong sizeInBytes)
{
if ((ulong)_numBytes < sizeInBytes)
@@ -376,13 +367,11 @@ using System.Diagnostics.Contracts;
NotEnoughRoom();
}
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
private static void NotEnoughRoom()
{
throw new ArgumentException(Environment.GetResourceString("Arg_BufferTooSmall"));
}
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
private static InvalidOperationException NotInitialized()
{
Debug.Assert(false, "Uninitialized SafeBuffer! Someone needs to call Initialize before using this instance!");
@@ -391,7 +380,6 @@ using System.Diagnostics.Contracts;
// FCALL limitations mean we can't have generic FCALL methods. However, we can pass
// TypedReferences to FCALL methods.
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
internal static void GenericPtrToStructure<T>(byte* ptr, out T structure, uint sizeofT) where T : struct
{
structure = default(T); // Dummy assignment to silence the compiler
@@ -399,17 +387,14 @@ using System.Diagnostics.Contracts;
}
[MethodImpl(MethodImplOptions.InternalCall)]
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
private static extern void PtrToStructureNative(byte* ptr, /*out T*/ TypedReference structure, uint sizeofT);
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
internal static void GenericStructureToPtr<T>(ref T structure, byte* ptr, uint sizeofT) where T : struct
{
StructureToPtrNative(__makeref(structure), ptr, sizeofT);
}
[MethodImpl(MethodImplOptions.InternalCall)]
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
private static extern void StructureToPtrNative(/*ref T*/ TypedReference structure, byte* ptr, uint sizeofT);
}
}
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/SafeHandle.cs b/src/mscorlib/src/System/Runtime/InteropServices/SafeHandle.cs
index ed9910e4e4..591caa2877 100644
--- a/src/mscorlib/src/System/Runtime/InteropServices/SafeHandle.cs
+++ b/src/mscorlib/src/System/Runtime/InteropServices/SafeHandle.cs
@@ -19,7 +19,6 @@ namespace System.Runtime.InteropServices {
using System;
using System.Reflection;
using System.Threading;
-using System.Security.Permissions;
using System.Runtime;
using System.Runtime.CompilerServices;
using System.IO;
@@ -154,7 +153,6 @@ public abstract class SafeHandle : CriticalFinalizerObject, IDisposable
// Creates a SafeHandle class. Users must then set the Handle property.
// To prevent the SafeHandle from being freed, write a subclass that
// doesn't define a finalizer.
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
protected SafeHandle(IntPtr invalidHandleValue, bool ownsHandle)
{
handle = invalidHandleValue;
@@ -190,11 +188,9 @@ public abstract class SafeHandle : CriticalFinalizerObject, IDisposable
Dispose(false);
}
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
extern void InternalFinalize();
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
protected void SetHandle(IntPtr handle) {
this.handle = handle;
}
@@ -213,33 +209,27 @@ public abstract class SafeHandle : CriticalFinalizerObject, IDisposable
// any way, this can lead to a handle recycling security attack (i.e. an
// untrusted caller can query data on the handle you've just returned
// and get back information for an entirely unrelated resource).
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
public IntPtr DangerousGetHandle()
{
return handle;
}
public bool IsClosed {
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
get { return (_state & 1) == 1; }
}
public abstract bool IsInvalid {
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
get;
}
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
public void Close() {
Dispose(true);
}
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
public void Dispose() {
Dispose(true);
}
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
protected virtual void Dispose(bool disposing)
{
if (disposing)
@@ -248,7 +238,6 @@ public abstract class SafeHandle : CriticalFinalizerObject, IDisposable
InternalFinalize();
}
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private extern void InternalDispose();
@@ -256,7 +245,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!
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public extern void SetHandleAsInvalid();
@@ -268,7 +256,6 @@ public abstract class SafeHandle : CriticalFinalizerObject, IDisposable
// The boolean returned should be true for success and false if the runtime
// should fire a SafeHandleCriticalFailure MDA (CustomerDebugProbe) if that
// MDA is enabled.
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
protected abstract bool ReleaseHandle();
// Add a reason why this handle should not be relinquished (i.e. have
@@ -284,7 +271,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.
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public extern void DangerousAddRef(ref bool success);
@@ -297,7 +283,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.
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public extern void DangerousRelease();
}
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/TCEAdapterGen/EventItfInfo.cs b/src/mscorlib/src/System/Runtime/InteropServices/TCEAdapterGen/EventItfInfo.cs
deleted file mode 100644
index 29b094c9e8..0000000000
--- a/src/mscorlib/src/System/Runtime/InteropServices/TCEAdapterGen/EventItfInfo.cs
+++ /dev/null
@@ -1,53 +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.TCEAdapterGen {
-
- using System;
- using System.Reflection;
- using System.Collections;
-
- internal class EventItfInfo
- {
- public EventItfInfo(String strEventItfName,
- String strSrcItfName,
- String strEventProviderName,
- RuntimeAssembly asmImport,
- RuntimeAssembly asmSrcItf)
- {
- m_strEventItfName = strEventItfName;
- m_strSrcItfName = strSrcItfName;
- m_strEventProviderName = strEventProviderName;
- m_asmImport = asmImport;
- m_asmSrcItf = asmSrcItf;
- }
-
- public Type GetEventItfType()
- {
- Type t = m_asmImport.GetType(m_strEventItfName, true, false);
- if (t != null && !t.IsVisible)
- t = null;
- return t;
- }
-
- public Type GetSrcItfType()
- {
- Type t = m_asmSrcItf.GetType(m_strSrcItfName, true, false);
- if (t != null && !t.IsVisible)
- t = null;
- return t;
- }
-
- public String GetEventProviderName()
- {
- return m_strEventProviderName;
- }
-
- private String m_strEventItfName;
- private String m_strSrcItfName;
- private String m_strEventProviderName;
- private RuntimeAssembly m_asmImport;
- private RuntimeAssembly m_asmSrcItf;
- }
-}
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/TCEAdapterGen/EventProviderWriter.cs b/src/mscorlib/src/System/Runtime/InteropServices/TCEAdapterGen/EventProviderWriter.cs
deleted file mode 100644
index 160a0ab491..0000000000
--- a/src/mscorlib/src/System/Runtime/InteropServices/TCEAdapterGen/EventProviderWriter.cs
+++ /dev/null
@@ -1,774 +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.TCEAdapterGen {
- using System.Runtime.InteropServices.ComTypes;
- using ubyte = System.Byte;
- using System;
- using System.Reflection;
- using System.Reflection.Emit;
- using System.Collections;
- using System.Threading;
- using System.Diagnostics;
- using System.Diagnostics.Contracts;
-
- internal class EventProviderWriter
- {
- private const BindingFlags DefaultLookup = BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public;
-
- private readonly Type[] MonitorEnterParamTypes = new Type[] { typeof(Object), Type.GetType("System.Boolean&") };
-
- public EventProviderWriter( ModuleBuilder OutputModule, String strDestTypeName, Type EventItfType, Type SrcItfType, Type SinkHelperType )
- {
- m_OutputModule = OutputModule;
- m_strDestTypeName = strDestTypeName;
- m_EventItfType = EventItfType;
- m_SrcItfType = SrcItfType;
- m_SinkHelperType = SinkHelperType;
- }
-
- public Type Perform()
- {
- // Create the event provider class.
- TypeBuilder OutputTypeBuilder = m_OutputModule.DefineType(
- m_strDestTypeName,
- TypeAttributes.Sealed | TypeAttributes.NotPublic,
- typeof(Object),
- new Type[]{m_EventItfType, typeof(IDisposable)}
- );
-
- // Create the event source field.
- FieldBuilder fbCPC = OutputTypeBuilder.DefineField(
- "m_ConnectionPointContainer",
- typeof(IConnectionPointContainer),
- FieldAttributes.Private
- );
-
- // Create array of event sink helpers.
- FieldBuilder fbSinkHelper = OutputTypeBuilder.DefineField(
- "m_aEventSinkHelpers",
- typeof(ArrayList),
- FieldAttributes.Private
- );
-
- // Define the connection point field.
- FieldBuilder fbEventCP = OutputTypeBuilder.DefineField(
- "m_ConnectionPoint",
- typeof(IConnectionPoint),
- FieldAttributes.Private
- );
-
- // Define the InitXXX method.
- MethodBuilder InitSrcItfMethodBuilder =
- DefineInitSrcItfMethod( OutputTypeBuilder, m_SrcItfType, fbSinkHelper, fbEventCP, fbCPC );
-
- // Process all the methods in the event interface.
- MethodInfo[] aMethods = TCEAdapterGenerator.GetNonPropertyMethods(m_SrcItfType);
- for ( int cMethods = 0; cMethods < aMethods.Length; cMethods++ )
- {
- if ( m_SrcItfType == aMethods[cMethods].DeclaringType )
- {
- // Define the add_XXX method.
- MethodBuilder AddEventMethodBuilder = DefineAddEventMethod(
- OutputTypeBuilder, aMethods[cMethods], m_SinkHelperType, fbSinkHelper, fbEventCP, InitSrcItfMethodBuilder );
-
- // Define the remove_XXX method.
- MethodBuilder RemoveEventMethodBuilder = DefineRemoveEventMethod(
- OutputTypeBuilder, aMethods[cMethods], m_SinkHelperType, fbSinkHelper, fbEventCP );
- }
- }
-
- // Define the constructor.
- DefineConstructor( OutputTypeBuilder, fbCPC );
-
- // Define the finalize method.
- MethodBuilder FinalizeMethod = DefineFinalizeMethod( OutputTypeBuilder, m_SinkHelperType, fbSinkHelper, fbEventCP );
-
- // Define the Dispose method.
- DefineDisposeMethod( OutputTypeBuilder, FinalizeMethod);
-
- return OutputTypeBuilder.CreateType();
- }
-
- private MethodBuilder DefineAddEventMethod( TypeBuilder OutputTypeBuilder, MethodInfo SrcItfMethod, Type SinkHelperClass, FieldBuilder fbSinkHelperArray, FieldBuilder fbEventCP, MethodBuilder mbInitSrcItf )
- {
- Type[] aParamTypes;
-
- // Find the delegate on the event sink helper.
- FieldInfo DelegateField = SinkHelperClass.GetField( "m_" + SrcItfMethod.Name + "Delegate" );
- 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" );
- 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 );
- Debug.Assert(SinkHelperCons != null, "Unable to find the constructor for the sink helper");
-
- // Retrieve the IConnectionPoint.Advise method.
- MethodInfo CPAdviseMethod = typeof(IConnectionPoint).GetMethod( "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 );
- Debug.Assert(ArrayListAddMethod != null, "Unable to find the method ArrayList.Add");
-
- // Retrieve the Monitor.Enter() method.
- MethodInfo MonitorEnterMethod = typeof(Monitor).GetMethod( "Enter", MonitorEnterParamTypes, null );
- 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 );
- Debug.Assert(MonitorExitMethod != null, "Unable to find the method Monitor.Exit()");
-
- // Define the add_XXX method.
- Type[] parameterTypes;
- parameterTypes = new Type[1];
- parameterTypes[0] = DelegateField.FieldType;
- MethodBuilder Meth = OutputTypeBuilder.DefineMethod(
- "add_" + SrcItfMethod.Name,
- MethodAttributes.Public | MethodAttributes.Virtual,
- null,
- parameterTypes );
-
- ILGenerator il = Meth.GetILGenerator();
-
- // Define a label for the m_IFooEventsCP comparision.
- Label EventCPNonNullLabel = il.DefineLabel();
-
- // Declare the local variables.
- LocalBuilder ltSinkHelper = il.DeclareLocal( SinkHelperClass );
- LocalBuilder ltCookie = il.DeclareLocal( typeof(Int32) );
- LocalBuilder ltLockTaken = il.DeclareLocal( typeof(bool) );
-
- // Generate the following code:
- // try {
- il.BeginExceptionBlock();
-
- // Generate the following code:
- // Monitor.Enter(this, ref lockTaken);
- il.Emit(OpCodes.Ldarg, (short)0);
- il.Emit(OpCodes.Ldloca_S, ltLockTaken);
- il.Emit(OpCodes.Call, MonitorEnterMethod);
-
- // Generate the following code:
- // if ( m_IFooEventsCP != null ) goto EventCPNonNullLabel;
- il.Emit( OpCodes.Ldarg, (short)0 );
- il.Emit( OpCodes.Ldfld, fbEventCP );
- il.Emit( OpCodes.Brtrue, EventCPNonNullLabel );
-
- // Generate the following code:
- // InitIFooEvents();
- il.Emit( OpCodes.Ldarg, (short)0 );
- il.Emit( OpCodes.Call, mbInitSrcItf );
-
- // Mark this as label to jump to if the CP is not null.
- il.MarkLabel( EventCPNonNullLabel );
-
- // Generate the following code:
- // IFooEvents_SinkHelper SinkHelper = new IFooEvents_SinkHelper;
- il.Emit( OpCodes.Newobj, SinkHelperCons );
- il.Emit( OpCodes.Stloc, ltSinkHelper );
-
- // Generate the following code:
- // dwCookie = 0;
- il.Emit( OpCodes.Ldc_I4_0 );
- il.Emit( OpCodes.Stloc, ltCookie );
-
- // Generate the following code:
- // m_IFooEventsCP.Advise( SinkHelper, dwCookie );
- il.Emit( OpCodes.Ldarg, (short)0 );
- il.Emit( OpCodes.Ldfld, fbEventCP );
- il.Emit( OpCodes.Ldloc, ltSinkHelper );
- il.Emit( OpCodes.Castclass, typeof(Object) );
- il.Emit( OpCodes.Ldloca, ltCookie );
- il.Emit( OpCodes.Callvirt, CPAdviseMethod );
-
- // Generate the following code:
- // SinkHelper.m_dwCookie = dwCookie;
- il.Emit( OpCodes.Ldloc, ltSinkHelper );
- il.Emit( OpCodes.Ldloc, ltCookie );
- il.Emit( OpCodes.Stfld, CookieField );
-
- // Generate the following code:
- // SinkHelper.m_FooDelegate = d;
- il.Emit( OpCodes.Ldloc, ltSinkHelper );
- il.Emit( OpCodes.Ldarg, (short)1 );
- il.Emit( OpCodes.Stfld, DelegateField );
-
- // Generate the following code:
- // m_aIFooEventsHelpers.Add( SinkHelper );
- il.Emit( OpCodes.Ldarg, (short)0 );
- il.Emit( OpCodes.Ldfld, fbSinkHelperArray );
- il.Emit( OpCodes.Ldloc, ltSinkHelper );
- il.Emit( OpCodes.Castclass, typeof(Object) );
- il.Emit( OpCodes.Callvirt, ArrayListAddMethod );
- il.Emit( OpCodes.Pop );
-
- // Generate the following code:
- // } finally {
- il.BeginFinallyBlock();
-
- // Generate the following code:
- // if (lockTaken)
- // Monitor.Exit(this);
- Label skipExit = il.DefineLabel();
- il.Emit( OpCodes.Ldloc, ltLockTaken );
- il.Emit( OpCodes.Brfalse_S, skipExit );
- il.Emit( OpCodes.Ldarg, (short)0 );
- il.Emit( OpCodes.Call, MonitorExitMethod );
- il.MarkLabel(skipExit);
-
- // Generate the following code:
- // }
- il.EndExceptionBlock();
-
- // Generate the return opcode.
- il.Emit( OpCodes.Ret );
-
- return Meth;
- }
-
- private MethodBuilder DefineRemoveEventMethod( TypeBuilder OutputTypeBuilder, MethodInfo SrcItfMethod, Type SinkHelperClass, FieldBuilder fbSinkHelperArray, FieldBuilder fbEventCP )
- {
- Type[] aParamTypes;
-
- // Find the delegate on the event sink helper.
- FieldInfo DelegateField = SinkHelperClass.GetField( "m_" + SrcItfMethod.Name + "Delegate" );
- 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" );
- 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 );
- Debug.Assert(ArrayListRemoveMethod != null, "Unable to find the method ArrayList.RemoveAt()");
-
- // Retrieve the ArrayList.Item property get method.
- PropertyInfo ArrayListItemProperty = typeof(ArrayList).GetProperty( "Item" );
- Debug.Assert(ArrayListItemProperty != null, "Unable to find the property ArrayList.Item");
- MethodInfo ArrayListItemGetMethod = ArrayListItemProperty.GetGetMethod();
- 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" );
- Debug.Assert(ArrayListSizeProperty != null, "Unable to find the property ArrayList.Count");
- MethodInfo ArrayListSizeGetMethod = ArrayListSizeProperty.GetGetMethod();
- 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 );
- Debug.Assert(DelegateEqualsMethod != null, "Unable to find the method Delegate.Equlals()");
-
- // Retrieve the Monitor.Enter() method.
- MethodInfo MonitorEnterMethod = typeof(Monitor).GetMethod("Enter", MonitorEnterParamTypes, null);
- 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 );
- Debug.Assert(MonitorExitMethod != null, "Unable to find the method Monitor.Exit()");
-
- // Retrieve the ConnectionPoint.Unadvise() method.
- MethodInfo CPUnadviseMethod = typeof(IConnectionPoint).GetMethod( "Unadvise" );
- Debug.Assert(CPUnadviseMethod != null, "Unable to find the method ConnectionPoint.Unadvise()");
-
- // Retrieve the Marshal.ReleaseComObject() method.
- MethodInfo ReleaseComObjectMethod = typeof(Marshal).GetMethod( "ReleaseComObject" );
- Debug.Assert(ReleaseComObjectMethod != null, "Unable to find the method Marshal.ReleaseComObject()");
-
- // Define the remove_XXX method.
- Type[] parameterTypes;
- parameterTypes = new Type[1];
- parameterTypes[0] = DelegateField.FieldType;
- MethodBuilder Meth = OutputTypeBuilder.DefineMethod(
- "remove_" + SrcItfMethod.Name,
- MethodAttributes.Public | MethodAttributes.Virtual,
- null,
- parameterTypes );
-
- ILGenerator il = Meth.GetILGenerator();
-
- // Declare the local variables.
- LocalBuilder ltNumSinkHelpers = il.DeclareLocal( typeof(Int32) );
- LocalBuilder ltSinkHelperCounter = il.DeclareLocal( typeof(Int32) );
- LocalBuilder ltCurrSinkHelper = il.DeclareLocal( SinkHelperClass );
- LocalBuilder ltLockTaken = il.DeclareLocal(typeof(bool));
-
- // Generate the labels for the for loop.
- Label ForBeginLabel = il.DefineLabel();
- Label ForEndLabel = il.DefineLabel();
- Label FalseIfLabel = il.DefineLabel();
- Label MonitorExitLabel = il.DefineLabel();
-
- // Generate the following code:
- // try {
- il.BeginExceptionBlock();
-
- // Generate the following code:
- // Monitor.Enter(this, ref lockTaken);
- il.Emit(OpCodes.Ldarg, (short)0);
- il.Emit(OpCodes.Ldloca_S, ltLockTaken);
- il.Emit(OpCodes.Call, MonitorEnterMethod);
-
- // Generate the following code:
- // if ( m_aIFooEventsHelpers == null ) goto ForEndLabel;
- il.Emit( OpCodes.Ldarg, (short)0 );
- il.Emit( OpCodes.Ldfld, fbSinkHelperArray );
- il.Emit( OpCodes.Brfalse, ForEndLabel );
-
- // Generate the following code:
- // int NumEventHelpers = m_aIFooEventsHelpers.Count;
- // int cEventHelpers = 0;
- il.Emit( OpCodes.Ldarg, (short)0 );
- il.Emit( OpCodes.Ldfld, fbSinkHelperArray );
- il.Emit( OpCodes.Callvirt, ArrayListSizeGetMethod );
- il.Emit( OpCodes.Stloc, ltNumSinkHelpers );
- il.Emit( OpCodes.Ldc_I4, 0 );
- il.Emit( OpCodes.Stloc, ltSinkHelperCounter );
-
- // Generate the following code:
- // if ( 0 >= NumEventHelpers ) goto ForEndLabel;
- il.Emit( OpCodes.Ldc_I4, 0 );
- il.Emit( OpCodes.Ldloc, ltNumSinkHelpers );
- il.Emit( OpCodes.Bge, ForEndLabel );
-
- // Mark this as the beginning of the for loop's body.
- il.MarkLabel( ForBeginLabel );
-
- // Generate the following code:
- // CurrentHelper = (IFooEvents_SinkHelper)m_aIFooEventsHelpers.Get( cEventHelpers );
- il.Emit( OpCodes.Ldarg, (short)0 );
- il.Emit( OpCodes.Ldfld, fbSinkHelperArray );
- il.Emit( OpCodes.Ldloc, ltSinkHelperCounter );
- il.Emit( OpCodes.Callvirt, ArrayListItemGetMethod );
- il.Emit( OpCodes.Castclass, SinkHelperClass );
- il.Emit( OpCodes.Stloc, ltCurrSinkHelper );
-
- // Generate the following code:
- // if ( CurrentHelper.m_FooDelegate )
- il.Emit( OpCodes.Ldloc, ltCurrSinkHelper );
- il.Emit( OpCodes.Ldfld, DelegateField );
- il.Emit( OpCodes.Ldnull );
- il.Emit( OpCodes.Beq, FalseIfLabel );
-
- // Generate the following code:
- // if ( CurrentHelper.m_FooDelegate.Equals( d ) )
- il.Emit( OpCodes.Ldloc, ltCurrSinkHelper );
- il.Emit( OpCodes.Ldfld, DelegateField );
- il.Emit( OpCodes.Ldarg, (short)1 );
- il.Emit( OpCodes.Castclass, typeof(Object) );
- il.Emit( OpCodes.Callvirt, DelegateEqualsMethod );
- il.Emit( OpCodes.Ldc_I4, 0xff );
- il.Emit( OpCodes.And );
- il.Emit( OpCodes.Ldc_I4, 0 );
- il.Emit( OpCodes.Beq, FalseIfLabel );
-
- // Generate the following code:
- // m_aIFooEventsHelpers.RemoveAt( cEventHelpers );
- il.Emit( OpCodes.Ldarg, (short)0 );
- il.Emit( OpCodes.Ldfld, fbSinkHelperArray );
- il.Emit( OpCodes.Ldloc, ltSinkHelperCounter );
- il.Emit( OpCodes.Callvirt, ArrayListRemoveMethod );
-
- // Generate the following code:
- // m_IFooEventsCP.Unadvise( CurrentHelper.m_dwCookie );
- il.Emit( OpCodes.Ldarg, (short)0 );
- il.Emit( OpCodes.Ldfld, fbEventCP );
- il.Emit( OpCodes.Ldloc, ltCurrSinkHelper );
- il.Emit( OpCodes.Ldfld, CookieField );
- il.Emit( OpCodes.Callvirt, CPUnadviseMethod );
-
- // Generate the following code:
- // if ( NumEventHelpers > 1) break;
- il.Emit( OpCodes.Ldloc, ltNumSinkHelpers );
- il.Emit( OpCodes.Ldc_I4, 1 );
- il.Emit( OpCodes.Bgt, ForEndLabel );
-
- // Generate the following code:
- // Marshal.ReleaseComObject(m_IFooEventsCP);
- il.Emit( OpCodes.Ldarg, (short)0 );
- il.Emit( OpCodes.Ldfld, fbEventCP );
- il.Emit( OpCodes.Call, ReleaseComObjectMethod );
- il.Emit( OpCodes.Pop );
-
- // Generate the following code:
- // m_IFooEventsCP = null;
- il.Emit( OpCodes.Ldarg, (short)0 );
- il.Emit( OpCodes.Ldnull );
- il.Emit( OpCodes.Stfld, fbEventCP );
-
- // Generate the following code:
- // m_aIFooEventsHelpers = null;
- il.Emit( OpCodes.Ldarg, (short)0 );
- il.Emit( OpCodes.Ldnull );
- il.Emit( OpCodes.Stfld, fbSinkHelperArray );
-
- // Generate the following code:
- // break;
- il.Emit( OpCodes.Br, ForEndLabel );
-
- // Mark this as the label to jump to when the if statement is false.
- il.MarkLabel( FalseIfLabel );
-
- // Generate the following code:
- // cEventHelpers++;
- il.Emit( OpCodes.Ldloc, ltSinkHelperCounter );
- il.Emit( OpCodes.Ldc_I4, 1 );
- il.Emit( OpCodes.Add );
- il.Emit( OpCodes.Stloc, ltSinkHelperCounter );
-
- // Generate the following code:
- // if ( cEventHelpers < NumEventHelpers ) goto ForBeginLabel;
- il.Emit( OpCodes.Ldloc, ltSinkHelperCounter );
- il.Emit( OpCodes.Ldloc, ltNumSinkHelpers );
- il.Emit( OpCodes.Blt, ForBeginLabel );
-
- // Mark this as the end of the for loop's body.
- il.MarkLabel( ForEndLabel );
-
- // Generate the following code:
- // } finally {
- il.BeginFinallyBlock();
-
- // Generate the following code:
- // if (lockTaken)
- // Monitor.Exit(this);
- Label skipExit = il.DefineLabel();
- il.Emit(OpCodes.Ldloc, ltLockTaken);
- il.Emit(OpCodes.Brfalse_S, skipExit);
- il.Emit(OpCodes.Ldarg, (short)0);
- il.Emit(OpCodes.Call, MonitorExitMethod);
- il.MarkLabel(skipExit);
-
- // Generate the following code:
- // }
- il.EndExceptionBlock();
-
- // Generate the return opcode.
- il.Emit( OpCodes.Ret );
-
- return Meth;
- }
-
- private MethodBuilder DefineInitSrcItfMethod( TypeBuilder OutputTypeBuilder, Type SourceInterface, FieldBuilder fbSinkHelperArray, FieldBuilder fbEventCP, FieldBuilder fbCPC )
- {
- // Retrieve the constructor info for the array list's default constructor.
- ConstructorInfo DefaultArrayListCons = typeof(ArrayList).GetConstructor(EventProviderWriter.DefaultLookup, null, Array.Empty<Type>(), null );
- Debug.Assert(DefaultArrayListCons != null, "Unable to find the constructor for class ArrayList");
-
- // Temp byte array for Guid
- ubyte[] rgByteGuid = new ubyte[16];
-
- // Retrieve the constructor info for the Guid constructor.
- Type[] aParamTypes = new Type[1];
- aParamTypes[0] = typeof(Byte[]);
- ConstructorInfo ByteArrayGUIDCons = typeof(Guid).GetConstructor(EventProviderWriter.DefaultLookup, null, aParamTypes, null );
- 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" );
- Debug.Assert(CPCFindCPMethod != null, "Unable to find the method ConnectionPointContainer.FindConnectionPoint()");
-
- // Define the Init method itself.
- MethodBuilder Meth = OutputTypeBuilder.DefineMethod(
- "Init",
- MethodAttributes.Private,
- null,
- null );
-
- ILGenerator il = Meth.GetILGenerator();
-
- // Declare the local variables.
- LocalBuilder ltCP = il.DeclareLocal( typeof(IConnectionPoint) );
- LocalBuilder ltEvGuid = il.DeclareLocal( typeof(Guid) );
- LocalBuilder ltByteArrayGuid = il.DeclareLocal( typeof(Byte[]) );
-
- // Generate the following code:
- // IConnectionPoint CP = NULL;
- il.Emit( OpCodes.Ldnull );
- il.Emit( OpCodes.Stloc, ltCP );
-
- // Get unsigned byte array for the GUID of the event interface.
- rgByteGuid = SourceInterface.GUID.ToByteArray();
-
- // Generate the following code:
- // ubyte rgByteArray[] = new ubyte [16];
- il.Emit( OpCodes.Ldc_I4, 0x10 );
- il.Emit( OpCodes.Newarr, typeof(Byte) );
- il.Emit( OpCodes.Stloc, ltByteArrayGuid );
-
- // Generate the following code:
- // rgByteArray[i] = rgByteGuid[i];
- for (int i = 0; i < 16; i++ )
- {
- il.Emit( OpCodes.Ldloc, ltByteArrayGuid );
- il.Emit( OpCodes.Ldc_I4, i );
- il.Emit( OpCodes.Ldc_I4, (int) (rgByteGuid[i]) );
- il.Emit( OpCodes.Stelem_I1);
- }
-
- // Generate the following code:
- // EventItfGuid = Guid( ubyte b[] );
- il.Emit( OpCodes.Ldloca, ltEvGuid );
- il.Emit( OpCodes.Ldloc, ltByteArrayGuid );
- il.Emit( OpCodes.Call, ByteArrayGUIDCons );
-
- // Generate the following code:
- // m_ConnectionPointContainer.FindConnectionPoint( EventItfGuid, CP );
- il.Emit( OpCodes.Ldarg, (short)0 );
- il.Emit( OpCodes.Ldfld, fbCPC );
- il.Emit( OpCodes.Ldloca, ltEvGuid );
- il.Emit( OpCodes.Ldloca, ltCP );
- il.Emit( OpCodes.Callvirt, CPCFindCPMethod );
-
- // Generate the following code:
- // m_ConnectionPoint = (IConnectionPoint)CP;
- il.Emit( OpCodes.Ldarg, (short)0 );
- il.Emit( OpCodes.Ldloc, ltCP );
- il.Emit( OpCodes.Castclass, typeof(IConnectionPoint) );
- il.Emit( OpCodes.Stfld, fbEventCP );
-
- // Generate the following code:
- // m_aEventSinkHelpers = new ArrayList;
- il.Emit( OpCodes.Ldarg, (short)0 );
- il.Emit( OpCodes.Newobj, DefaultArrayListCons );
- il.Emit( OpCodes.Stfld, fbSinkHelperArray );
-
- // Generate the return opcode.
- il.Emit( OpCodes.Ret );
-
- return Meth;
- }
-
- private void DefineConstructor( TypeBuilder OutputTypeBuilder, FieldBuilder fbCPC )
- {
- // Retrieve the constructor info for the base class's constructor.
- ConstructorInfo DefaultBaseClsCons = typeof(Object).GetConstructor(BindingFlags.Instance | BindingFlags.Public, null, Array.Empty<Type>(), null );
- 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);
- MethodBuilder Cons = OutputTypeBuilder.DefineMethod(
- ".ctor",
- ctorAttributes,
- null,
- new Type[]{typeof(Object)} );
-
- ILGenerator il = Cons.GetILGenerator();
-
- // Generate the call to the base class constructor.
- il.Emit( OpCodes.Ldarg, (short)0 );
- il.Emit( OpCodes.Call, DefaultBaseClsCons );
-
- // Generate the following code:
- // m_ConnectionPointContainer = (IConnectionPointContainer)EventSource;
- il.Emit( OpCodes.Ldarg, (short)0 );
- il.Emit( OpCodes.Ldarg, (short)1 );
- il.Emit( OpCodes.Castclass, typeof(IConnectionPointContainer) );
- il.Emit( OpCodes.Stfld, fbCPC );
-
- // Generate the return opcode.
- il.Emit( OpCodes.Ret );
- }
-
- private MethodBuilder DefineFinalizeMethod( TypeBuilder OutputTypeBuilder, Type SinkHelperClass, FieldBuilder fbSinkHelper, FieldBuilder fbEventCP )
- {
- // Find the cookie on the event sink helper.
- FieldInfo CookieField = SinkHelperClass.GetField( "m_dwCookie" );
- 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" );
- Debug.Assert(ArrayListItemProperty != null, "Unable to find the property ArrayList.Item");
- MethodInfo ArrayListItemGetMethod = ArrayListItemProperty.GetGetMethod();
- 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" );
- Debug.Assert(ArrayListSizeProperty != null, "Unable to find the property ArrayList.Count");
- MethodInfo ArrayListSizeGetMethod = ArrayListSizeProperty.GetGetMethod();
- 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" );
- Debug.Assert(CPUnadviseMethod != null, "Unable to find the method ConnectionPoint.Unadvise()");
-
- // Retrieve the Marshal.ReleaseComObject() method.
- MethodInfo ReleaseComObjectMethod = typeof(Marshal).GetMethod( "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);
- 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 );
- 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 );
-
- ILGenerator il = Meth.GetILGenerator();
-
- // Declare the local variables.
- LocalBuilder ltNumSinkHelpers = il.DeclareLocal( typeof(Int32) );
- LocalBuilder ltSinkHelperCounter = il.DeclareLocal( typeof(Int32) );
- LocalBuilder ltCurrSinkHelper = il.DeclareLocal( SinkHelperClass );
- LocalBuilder ltLockTaken = il.DeclareLocal(typeof(bool));
-
- // Generate the following code:
- // try {
- il.BeginExceptionBlock();
-
- // Generate the following code:
- // Monitor.Enter(this, ref lockTaken);
- il.Emit(OpCodes.Ldarg, (short)0);
- il.Emit(OpCodes.Ldloca_S, ltLockTaken);
- il.Emit(OpCodes.Call, MonitorEnterMethod);
-
- // Generate the labels.
- Label ForBeginLabel = il.DefineLabel();
- Label ReleaseComObjectLabel = il.DefineLabel();
- Label AfterReleaseComObjectLabel = il.DefineLabel();
-
- // Generate the following code:
- // if ( m_IFooEventsCP == null ) goto AfterReleaseComObjectLabel;
- il.Emit( OpCodes.Ldarg, (short)0 );
- il.Emit( OpCodes.Ldfld, fbEventCP );
- il.Emit( OpCodes.Brfalse, AfterReleaseComObjectLabel );
-
- // Generate the following code:
- // int NumEventHelpers = m_aIFooEventsHelpers.Count;
- // int cEventHelpers = 0;
- il.Emit( OpCodes.Ldarg, (short)0 );
- il.Emit( OpCodes.Ldfld, fbSinkHelper );
- il.Emit( OpCodes.Callvirt, ArrayListSizeGetMethod );
- il.Emit( OpCodes.Stloc, ltNumSinkHelpers );
- il.Emit( OpCodes.Ldc_I4, 0 );
- il.Emit( OpCodes.Stloc, ltSinkHelperCounter );
-
- // Generate the following code:
- // if ( 0 >= NumEventHelpers ) goto ReleaseComObjectLabel;
- il.Emit( OpCodes.Ldc_I4, 0 );
- il.Emit( OpCodes.Ldloc, ltNumSinkHelpers );
- il.Emit( OpCodes.Bge, ReleaseComObjectLabel );
-
- // Mark this as the beginning of the for loop's body.
- il.MarkLabel( ForBeginLabel );
-
- // Generate the following code:
- // CurrentHelper = (IFooEvents_SinkHelper)m_aIFooEventsHelpers.Get( cEventHelpers );
- il.Emit( OpCodes.Ldarg, (short)0 );
- il.Emit( OpCodes.Ldfld, fbSinkHelper );
- il.Emit( OpCodes.Ldloc, ltSinkHelperCounter );
- il.Emit( OpCodes.Callvirt, ArrayListItemGetMethod );
- il.Emit( OpCodes.Castclass, SinkHelperClass );
- il.Emit( OpCodes.Stloc, ltCurrSinkHelper );
-
- // Generate the following code:
- // m_IFooEventsCP.Unadvise( CurrentHelper.m_dwCookie );
- il.Emit( OpCodes.Ldarg, (short)0 );
- il.Emit( OpCodes.Ldfld, fbEventCP );
- il.Emit( OpCodes.Ldloc, ltCurrSinkHelper );
- il.Emit( OpCodes.Ldfld, CookieField );
- il.Emit( OpCodes.Callvirt, CPUnadviseMethod );
-
- // Generate the following code:
- // cEventHelpers++;
- il.Emit( OpCodes.Ldloc, ltSinkHelperCounter );
- il.Emit( OpCodes.Ldc_I4, 1 );
- il.Emit( OpCodes.Add );
- il.Emit( OpCodes.Stloc, ltSinkHelperCounter );
-
- // Generate the following code:
- // if ( cEventHelpers < NumEventHelpers ) goto ForBeginLabel;
- il.Emit( OpCodes.Ldloc, ltSinkHelperCounter );
- il.Emit( OpCodes.Ldloc, ltNumSinkHelpers );
- il.Emit( OpCodes.Blt, ForBeginLabel );
-
- // Mark this as the end of the for loop's body.
- il.MarkLabel( ReleaseComObjectLabel );
-
- // Generate the following code:
- // Marshal.ReleaseComObject(m_IFooEventsCP);
- il.Emit( OpCodes.Ldarg, (short)0 );
- il.Emit( OpCodes.Ldfld, fbEventCP );
- il.Emit( OpCodes.Call, ReleaseComObjectMethod );
- il.Emit( OpCodes.Pop );
-
- // Mark this as the end of the for loop's body.
- il.MarkLabel( AfterReleaseComObjectLabel );
-
- // Generate the following code:
- // } catch {
- il.BeginCatchBlock(typeof(System.Exception));
- il.Emit( OpCodes.Pop );
-
- // Generate the following code:
- // } finally {
- il.BeginFinallyBlock();
-
- // Generate the following code:
- // if (lockTaken)
- // Monitor.Exit(this);
- Label skipExit = il.DefineLabel();
- il.Emit(OpCodes.Ldloc, ltLockTaken);
- il.Emit(OpCodes.Brfalse_S, skipExit);
- il.Emit(OpCodes.Ldarg, (short)0);
- il.Emit(OpCodes.Call, MonitorExitMethod);
- il.MarkLabel(skipExit);
-
- // Generate the following code:
- // }
- il.EndExceptionBlock();
-
- // Generate the return opcode.
- il.Emit( OpCodes.Ret );
-
- return Meth;
- }
-
- private void DefineDisposeMethod( TypeBuilder OutputTypeBuilder, MethodBuilder FinalizeMethod )
- {
- // Retrieve the method info for GC.SuppressFinalize().
- MethodInfo SuppressFinalizeMethod = typeof(GC).GetMethod("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 );
-
- ILGenerator il = Meth.GetILGenerator();
-
- // Generate the following code:
- // Finalize()
- il.Emit( OpCodes.Ldarg, (short)0 );
- il.Emit( OpCodes.Callvirt, FinalizeMethod );
-
- // Generate the following code:
- // GC.SuppressFinalize()
- il.Emit( OpCodes.Ldarg, (short)0 );
- il.Emit( OpCodes.Call, SuppressFinalizeMethod );
-
- // Generate the return opcode.
- il.Emit( OpCodes.Ret );
- }
-
- private ModuleBuilder m_OutputModule;
- private String m_strDestTypeName;
- private Type m_EventItfType;
- private Type m_SrcItfType;
- private Type m_SinkHelperType;
- }
-}
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/TCEAdapterGen/EventSinkHelperWriter.cs b/src/mscorlib/src/System/Runtime/InteropServices/TCEAdapterGen/EventSinkHelperWriter.cs
deleted file mode 100644
index 862419cc98..0000000000
--- a/src/mscorlib/src/System/Runtime/InteropServices/TCEAdapterGen/EventSinkHelperWriter.cs
+++ /dev/null
@@ -1,298 +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.TCEAdapterGen {
- using System.Runtime.InteropServices;
- using System;
- using System.Reflection;
- using System.Reflection.Emit;
- using System.Collections;
- using System.Diagnostics;
- using System.Diagnostics.Contracts;
- internal class EventSinkHelperWriter
- {
- public static readonly String GeneratedTypeNamePostfix = "_SinkHelper";
-
- public EventSinkHelperWriter( ModuleBuilder OutputModule, Type InputType, Type EventItfType )
- {
- m_InputType = InputType;
- m_OutputModule = OutputModule;
- m_EventItfType = EventItfType;
- }
-
- public Type Perform()
- {
- // Create the output Type.
- Type[] aInterfaces = new Type[1];
- aInterfaces[0] = m_InputType;
- String strFullName = null;
- String strNameSpace = NameSpaceExtractor.ExtractNameSpace( m_EventItfType.FullName );
-
- if (strNameSpace != "")
- strFullName = strNameSpace + ".";
-
- strFullName += m_InputType.Name + GeneratedTypeNamePostfix;
- TypeBuilder OutputTypeBuilder = TCEAdapterGenerator.DefineUniqueType(
- strFullName,
- TypeAttributes.Sealed | TypeAttributes.Public,
- null,
- aInterfaces,
- m_OutputModule
- );
- // Hide the _SinkProvider interface
- TCEAdapterGenerator.SetHiddenAttribute(OutputTypeBuilder);
-
- // Set the class interface to none.
- TCEAdapterGenerator.SetClassInterfaceTypeToNone(OutputTypeBuilder);
-
- // Retrieve the property methods on the input interface and give them a dummy implementation.
- MethodInfo[] pMethods = TCEAdapterGenerator.GetPropertyMethods(m_InputType);
- foreach (MethodInfo method in pMethods)
- {
- DefineBlankMethod(OutputTypeBuilder, method);
- }
-
- // Retrieve the non-property methods on the input interface.
- MethodInfo[] aMethods = TCEAdapterGenerator.GetNonPropertyMethods(m_InputType);
-
- // Allocate an array to contain the delegate fields.
- FieldBuilder[] afbDelegates = new FieldBuilder[aMethods.Length];
- // Process all the methods on the input interface.
- for ( int cMethods = 0; cMethods < aMethods.Length; cMethods++ )
- {
- if ( m_InputType == aMethods[cMethods].DeclaringType )
- {
- // Retrieve the delegate type from the add_XXX method.
- MethodInfo AddMeth = m_EventItfType.GetMethod( "add_" + aMethods[cMethods].Name );
- ParameterInfo[] aParams = AddMeth.GetParameters();
- 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.
- afbDelegates[cMethods] = OutputTypeBuilder.DefineField(
- "m_" + aMethods[cMethods].Name + "Delegate",
- DelegateCls,
- FieldAttributes.Public
- );
-
- // Define the event method itself.
- DefineEventMethod( OutputTypeBuilder, aMethods[cMethods], DelegateCls, afbDelegates[cMethods] );
- }
- }
-
- // Create the cookie field.
- FieldBuilder fbCookie = OutputTypeBuilder.DefineField(
- "m_dwCookie",
- typeof(Int32),
- FieldAttributes.Public
- );
-
- // Define the constructor.
- DefineConstructor( OutputTypeBuilder, fbCookie, afbDelegates );
-
- return OutputTypeBuilder.CreateType();
- }
-
- private void DefineBlankMethod(TypeBuilder OutputTypeBuilder, MethodInfo Method)
- {
- ParameterInfo[] PIs = Method.GetParameters();
- Type[] parameters = new Type[PIs.Length];
- for (int i=0; i < PIs.Length; i++)
- {
- parameters[i] = PIs[i].ParameterType;
- }
-
- MethodBuilder Meth = OutputTypeBuilder.DefineMethod(Method.Name,
- Method.Attributes & ~MethodAttributes.Abstract,
- Method.CallingConvention,
- Method.ReturnType,
- parameters);
-
- ILGenerator il = Meth.GetILGenerator();
-
- AddReturn(Method.ReturnType, il, Meth);
-
- il.Emit(OpCodes.Ret);
- }
-
- private void DefineEventMethod( TypeBuilder OutputTypeBuilder, MethodInfo Method, Type DelegateCls, FieldBuilder fbDelegate )
- {
- // Retrieve the method info for the invoke method on the delegate.
- MethodInfo DelegateInvokeMethod = DelegateCls.GetMethod( "Invoke" );
- Debug.Assert(DelegateInvokeMethod != null, "Unable to find method Delegate.Invoke()");
-
- // Retrieve the return type.
- Type ReturnType = Method.ReturnType;
-
- // Define the actual event method.
- ParameterInfo[] paramInfos = Method.GetParameters();
- Type[] parameterTypes;
- if (paramInfos != null)
- {
- parameterTypes = new Type[paramInfos.Length];
- for (int i = 0; i < paramInfos.Length; i++)
- {
- parameterTypes[i] = paramInfos[i].ParameterType;
- }
- }
- else
- parameterTypes = null;
-
- MethodAttributes attr = MethodAttributes.Public | MethodAttributes.Virtual;
- MethodBuilder Meth = OutputTypeBuilder.DefineMethod( Method.Name,
- attr,
- CallingConventions.Standard,
- ReturnType,
- parameterTypes);
-
- // We explicitly do not specify parameter name and attributes since this Type
- // is not meant to be exposed to the user. It is only used internally to do the
- // connection point to TCE mapping.
-
- ILGenerator il = Meth.GetILGenerator();
-
- // Create the exit branch.
- Label ExitLabel = il.DefineLabel();
-
- // Generate the code that verifies that the delegate is not null.
- il.Emit( OpCodes.Ldarg, (short)0 );
- il.Emit( OpCodes.Ldfld, fbDelegate );
- il.Emit( OpCodes.Brfalse, ExitLabel );
-
- // The delegate is not NULL so we need to invoke it.
- il.Emit( OpCodes.Ldarg, (short)0 );
- il.Emit( OpCodes.Ldfld, fbDelegate );
-
- // Generate the code to load the arguments before we call invoke.
- ParameterInfo[] aParams = Method.GetParameters();
- for ( int cParams = 0; cParams < aParams.Length; cParams++ )
- {
- il.Emit( OpCodes.Ldarg, (short)(cParams + 1) );
- }
-
- // Generate a tail call to invoke. This will cause the callvirt to return
- // directly to the caller of the current method instead of actually coming
- // back to the current method and returning. This will cause the value returned
- // from the call to the COM server to be returned to the caller of this method.
-
- il.Emit( OpCodes.Callvirt, DelegateInvokeMethod );
- il.Emit( OpCodes.Ret );
-
- // This is the label that will be jumped to if no delegate is present.
- il.MarkLabel( ExitLabel );
-
- AddReturn(ReturnType, il, Meth);
-
- il.Emit( OpCodes.Ret );
-
- }
-
- private void AddReturn(Type ReturnType, ILGenerator il, MethodBuilder Meth)
- {
- // Place a dummy return value on the stack before we return.
- if ( ReturnType == typeof(void) )
- {
- // There is nothing to place on the stack.
- }
- else if ( ReturnType.IsPrimitive )
- {
- switch (System.Type.GetTypeCode(ReturnType))
- {
- case TypeCode.Boolean:
- case TypeCode.Char:
- case TypeCode.Byte:
- case TypeCode.SByte:
- case TypeCode.Int16:
- case TypeCode.UInt16:
- case TypeCode.Int32:
- case TypeCode.UInt32:
- il.Emit( OpCodes.Ldc_I4_0 );
- break;
-
- case TypeCode.Int64:
- case TypeCode.UInt64:
- il.Emit( OpCodes.Ldc_I4_0 );
- il.Emit( OpCodes.Conv_I8 );
- break;
-
- case TypeCode.Single:
- il.Emit( OpCodes.Ldc_R4, 0 );
- break;
-
- case TypeCode.Double:
- il.Emit( OpCodes.Ldc_R4, 0 );
- il.Emit( OpCodes.Conv_R8 );
- break;
-
- default:
- // "TypeCode" does not include IntPtr, so special case it.
- if ( ReturnType == typeof(IntPtr) )
- il.Emit( OpCodes.Ldc_I4_0 );
- else
- Debug.Assert(false, "Unexpected type for Primitive type.");
- break;
- }
- }
- else if ( ReturnType.IsValueType )
- {
- // Allocate stack space for the return value type. Zero-init.
- Meth.InitLocals = true;
- LocalBuilder ltRetVal = il.DeclareLocal( ReturnType );
-
- // Load the value class on the stack.
- il.Emit( OpCodes.Ldloc_S, ltRetVal );
-
- }
- else
- {
- // The return type is a normal type.
- il.Emit( OpCodes.Ldnull );
- }
- }
-
- private void DefineConstructor( TypeBuilder OutputTypeBuilder, FieldBuilder fbCookie, FieldBuilder[] afbDelegates )
- {
- // 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 );
- Debug.Assert(DefaultBaseClsCons != null, "Unable to find the constructor for class " + m_InputType.Name);
-
- // Define the default constructor.
- MethodBuilder Cons = OutputTypeBuilder.DefineMethod( ".ctor",
- MethodAttributes.Assembly | MethodAttributes.SpecialName,
- CallingConventions.Standard,
- null,
- null);
-
- ILGenerator il = Cons.GetILGenerator();
-
- // Generate the code to call the constructor of the base class.
- il.Emit( OpCodes.Ldarg, (short)0 );
- il.Emit( OpCodes.Call, DefaultBaseClsCons );
-
- // Generate the code to set the cookie field to 0.
- il.Emit( OpCodes.Ldarg, (short)0 );
- il.Emit( OpCodes.Ldc_I4, 0 );
- il.Emit( OpCodes.Stfld, fbCookie );
-
- // Generate the code to set all the delegates to NULL.
- for ( int cDelegates = 0; cDelegates < afbDelegates.Length; cDelegates++ )
- {
- if (afbDelegates[cDelegates] != null)
- {
- il.Emit( OpCodes.Ldarg,(short)0 );
- il.Emit( OpCodes.Ldnull );
- il.Emit( OpCodes.Stfld, afbDelegates[cDelegates] );
- }
- }
-
- // Emit the return opcode.
- il.Emit( OpCodes.Ret );
-
- }
-
- private Type m_InputType;
- private Type m_EventItfType;
- private ModuleBuilder m_OutputModule;
- }
-}
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/TCEAdapterGen/NameSpaceExtractor.cs b/src/mscorlib/src/System/Runtime/InteropServices/TCEAdapterGen/NameSpaceExtractor.cs
deleted file mode 100644
index 8018ad4c66..0000000000
--- a/src/mscorlib/src/System/Runtime/InteropServices/TCEAdapterGen/NameSpaceExtractor.cs
+++ /dev/null
@@ -1,21 +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.TCEAdapterGen {
-
- using System;
- internal static class NameSpaceExtractor
- {
- private static char NameSpaceSeperator = '.';
-
- public static String ExtractNameSpace(String FullyQualifiedTypeName)
- {
- int TypeNameStartPos = FullyQualifiedTypeName.LastIndexOf(NameSpaceSeperator);
- if (TypeNameStartPos == -1)
- return "";
- else
- return FullyQualifiedTypeName.Substring(0, TypeNameStartPos);
- }
- }
-}
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/TCEAdapterGen/TCEAdapterGenerator.cs b/src/mscorlib/src/System/Runtime/InteropServices/TCEAdapterGen/TCEAdapterGenerator.cs
deleted file mode 100644
index c6e4415246..0000000000
--- a/src/mscorlib/src/System/Runtime/InteropServices/TCEAdapterGen/TCEAdapterGenerator.cs
+++ /dev/null
@@ -1,141 +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.TCEAdapterGen {
- using System.Runtime.InteropServices;
- using System;
- using System.Reflection;
- using System.Reflection.Emit;
- using System.Collections;
- using System.Threading;
-
- internal class TCEAdapterGenerator
- {
- public void Process(ModuleBuilder ModBldr, ArrayList EventItfList)
- {
- // Store the input/output module.
- m_Module = ModBldr;
-
- // Generate the TCE adapters for all the event sources.
- int NumEvItfs = EventItfList.Count;
- for ( int cEventItfs = 0; cEventItfs < NumEvItfs; cEventItfs++ )
- {
- // Retrieve the event interface info.
- EventItfInfo CurrEventItf = (EventItfInfo)EventItfList[cEventItfs];
-
- // Retrieve the information from the event interface info.
- Type EventItfType = CurrEventItf.GetEventItfType();
- Type SrcItfType = CurrEventItf.GetSrcItfType();
- String EventProviderName = CurrEventItf.GetEventProviderName();
-
- // Generate the sink interface helper.
- Type SinkHelperType = new EventSinkHelperWriter( m_Module, SrcItfType, EventItfType ).Perform();
-
- // Generate the event provider.
- new EventProviderWriter( m_Module, EventProviderName, EventItfType, SrcItfType, SinkHelperType ).Perform();
- }
- }
-
- internal static void SetClassInterfaceTypeToNone(TypeBuilder tb)
- {
- // Create the ClassInterface(ClassInterfaceType.None) CA builder if we haven't created it yet.
- if (s_NoClassItfCABuilder == null)
- {
- Type []aConsParams = new Type[1];
- aConsParams[0] = typeof(ClassInterfaceType);
- ConstructorInfo Cons = typeof(ClassInterfaceAttribute).GetConstructor(aConsParams);
-
- Object[] aArgs = new Object[1];
- aArgs[0] = ClassInterfaceType.None;
- s_NoClassItfCABuilder = new CustomAttributeBuilder(Cons, aArgs);
- }
-
- // Set the class interface type to none.
- tb.SetCustomAttribute(s_NoClassItfCABuilder);
- }
-
- internal static TypeBuilder DefineUniqueType(String strInitFullName, TypeAttributes attrs, Type BaseType, Type[] aInterfaceTypes, ModuleBuilder mb)
- {
- String strFullName = strInitFullName;
- int PostFix = 2;
-
- // Find the first unique name for the type.
- for (; mb.GetType(strFullName) != null; strFullName = strInitFullName + "_" + PostFix, PostFix++);
-
- // Define a type with the determined unique name.
- return mb.DefineType(strFullName, attrs, BaseType, aInterfaceTypes);
- }
-
- internal static void SetHiddenAttribute(TypeBuilder tb)
- {
- if (s_HiddenCABuilder == null)
- {
- // Hide the type from Object Browsers
- Type []aConsParams = new Type[1];
- aConsParams[0] = typeof(TypeLibTypeFlags);
- ConstructorInfo Cons = typeof(TypeLibTypeAttribute).GetConstructor(aConsParams);
-
- Object []aArgs = new Object[1];
- aArgs[0] = TypeLibTypeFlags.FHidden;
- s_HiddenCABuilder = new CustomAttributeBuilder(Cons, aArgs);
- }
-
- tb.SetCustomAttribute(s_HiddenCABuilder);
- }
-
- internal static MethodInfo[] GetNonPropertyMethods(Type type)
- {
- MethodInfo[] aMethods = type.GetMethods();
- ArrayList methods = new ArrayList(aMethods);
-
- PropertyInfo[] props = type.GetProperties();
-
- foreach(PropertyInfo prop in props)
- {
- MethodInfo[] accessors = prop.GetAccessors();
- foreach (MethodInfo accessor in accessors)
- {
- for (int i=0; i < methods.Count; i++)
- {
- if ((MethodInfo)methods[i] == accessor)
- methods.RemoveAt(i);
- }
- }
- }
-
- MethodInfo[] retMethods = new MethodInfo[methods.Count];
- methods.CopyTo(retMethods);
-
- return retMethods;
- }
-
- internal static MethodInfo[] GetPropertyMethods(Type type)
- {
- MethodInfo[] aMethods = type.GetMethods();
- ArrayList methods = new ArrayList();
-
- PropertyInfo[] props = type.GetProperties();
-
- foreach(PropertyInfo prop in props)
- {
- MethodInfo[] accessors = prop.GetAccessors();
- foreach (MethodInfo accessor in accessors)
- {
- methods.Add(accessor);
- }
- }
-
- MethodInfo[] retMethods = new MethodInfo[methods.Count];
- methods.CopyTo(retMethods);
-
- return retMethods;
- }
-
-
- private ModuleBuilder m_Module = null;
- private Hashtable m_SrcItfToSrcItfInfoMap = new Hashtable();
- private static volatile CustomAttributeBuilder s_NoClassItfCABuilder = null;
- private static volatile CustomAttributeBuilder s_HiddenCABuilder = null;
- }
-}
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/UCOMIBindCtx.cs b/src/mscorlib/src/System/Runtime/InteropServices/UCOMIBindCtx.cs
deleted file mode 100644
index 8c6e1bcd64..0000000000
--- a/src/mscorlib/src/System/Runtime/InteropServices/UCOMIBindCtx.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.
-
-/*=============================================================================
-**
-**
-**
-** Purpose: UCOMIBindCtx interface definition.
-**
-**
-=============================================================================*/
-
-namespace System.Runtime.InteropServices {
-
- using System;
-
- [Obsolete("Use System.Runtime.InteropServices.ComTypes.BIND_OPTS instead. http://go.microsoft.com/fwlink/?linkid=14202", false)]
- [StructLayout(LayoutKind.Sequential)]
-
- public struct BIND_OPTS
- {
- public int cbStruct;
- public int grfFlags;
- public int grfMode;
- public int dwTickCountDeadline;
- }
-
- [Obsolete("Use System.Runtime.InteropServices.ComTypes.IBindCtx instead. http://go.microsoft.com/fwlink/?linkid=14202", false)]
- [Guid("0000000e-0000-0000-C000-000000000046")]
- [InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)]
- [ComImport]
- public interface UCOMIBindCtx
- {
- void RegisterObjectBound([MarshalAs(UnmanagedType.Interface)] Object punk);
- void RevokeObjectBound([MarshalAs(UnmanagedType.Interface)] Object punk);
- void ReleaseBoundObjects();
- void SetBindOptions([In()] ref BIND_OPTS pbindopts);
- void GetBindOptions(ref BIND_OPTS pbindopts);
- void GetRunningObjectTable(out UCOMIRunningObjectTable pprot);
- void RegisterObjectParam([MarshalAs(UnmanagedType.LPWStr)] String pszKey, [MarshalAs(UnmanagedType.Interface)] Object punk);
- void GetObjectParam([MarshalAs(UnmanagedType.LPWStr)] String pszKey, [MarshalAs(UnmanagedType.Interface)] out Object ppunk);
- void EnumObjectParam(out UCOMIEnumString ppenum);
- void RevokeObjectParam([MarshalAs(UnmanagedType.LPWStr)] String pszKey);
- }
-}
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/UCOMIConnectionPoint.cs b/src/mscorlib/src/System/Runtime/InteropServices/UCOMIConnectionPoint.cs
deleted file mode 100644
index b12e1f7a8c..0000000000
--- a/src/mscorlib/src/System/Runtime/InteropServices/UCOMIConnectionPoint.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.
-
-/*=============================================================================
-**
-**
-**
-** Purpose: UCOMIConnectionPoint interface definition.
-**
-**
-=============================================================================*/
-
-namespace System.Runtime.InteropServices
-{
- using System;
-
- [Obsolete("Use System.Runtime.InteropServices.ComTypes.IConnectionPoint instead. http://go.microsoft.com/fwlink/?linkid=14202", false)]
- [Guid("B196B286-BAB4-101A-B69C-00AA00341D07")]
- [InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)]
- [ComImport]
- public interface UCOMIConnectionPoint
- {
- void GetConnectionInterface(out Guid pIID);
- void GetConnectionPointContainer(out UCOMIConnectionPointContainer ppCPC);
- void Advise([MarshalAs(UnmanagedType.Interface)] Object pUnkSink, out int pdwCookie);
- void Unadvise(int dwCookie);
- void EnumConnections(out UCOMIEnumConnections ppEnum);
- }
-}
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/UCOMIConnectionPointContainer.cs b/src/mscorlib/src/System/Runtime/InteropServices/UCOMIConnectionPointContainer.cs
deleted file mode 100644
index 212d643e03..0000000000
--- a/src/mscorlib/src/System/Runtime/InteropServices/UCOMIConnectionPointContainer.cs
+++ /dev/null
@@ -1,27 +0,0 @@
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-// See the LICENSE file in the project root for more information.
-
-/*=============================================================================
-**
-**
-**
-** Purpose: UCOMIConnectionPointContainer interface definition.
-**
-**
-=============================================================================*/
-
-namespace System.Runtime.InteropServices
-{
- using System;
-
- [Obsolete("Use System.Runtime.InteropServices.ComTypes.IConnectionPointContainer instead. http://go.microsoft.com/fwlink/?linkid=14202", false)]
- [Guid("B196B284-BAB4-101A-B69C-00AA00341D07")]
- [InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)]
- [ComImport]
- public interface UCOMIConnectionPointContainer
- {
- void EnumConnectionPoints(out UCOMIEnumConnectionPoints ppEnum);
- void FindConnectionPoint(ref Guid riid, out UCOMIConnectionPoint ppCP);
- }
-}
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/UCOMIEnumConnectionPoints.cs b/src/mscorlib/src/System/Runtime/InteropServices/UCOMIEnumConnectionPoints.cs
deleted file mode 100644
index 5180018088..0000000000
--- a/src/mscorlib/src/System/Runtime/InteropServices/UCOMIEnumConnectionPoints.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: UCOMIEnumConnectionPoints interface definition.
-**
-**
-=============================================================================*/
-
-namespace System.Runtime.InteropServices
-{
- using System;
-
- [Obsolete("Use System.Runtime.InteropServices.ComTypes.IEnumConnectionPoints instead. http://go.microsoft.com/fwlink/?linkid=14202", false)]
- [Guid("B196B285-BAB4-101A-B69C-00AA00341D07")]
- [InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)]
- [ComImport]
- public interface UCOMIEnumConnectionPoints
- {
- [PreserveSig]
- int Next(int celt, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 0), Out] UCOMIConnectionPoint[] rgelt, out int pceltFetched);
- [PreserveSig]
- int Skip(int celt);
- [PreserveSig]
- int Reset();
- void Clone(out UCOMIEnumConnectionPoints ppenum);
- }
-}
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/UCOMIEnumConnections.cs b/src/mscorlib/src/System/Runtime/InteropServices/UCOMIEnumConnections.cs
deleted file mode 100644
index 87273b34f7..0000000000
--- a/src/mscorlib/src/System/Runtime/InteropServices/UCOMIEnumConnections.cs
+++ /dev/null
@@ -1,42 +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: UCOMIEnumConnections interface definition.
-**
-**
-=============================================================================*/
-
-namespace System.Runtime.InteropServices
-{
- using System;
-
- [Obsolete("Use System.Runtime.InteropServices.ComTypes.CONNECTDATA instead. http://go.microsoft.com/fwlink/?linkid=14202", false)]
- [StructLayout(LayoutKind.Sequential, CharSet=CharSet.Unicode)]
-
- public struct CONNECTDATA
- {
- [MarshalAs(UnmanagedType.Interface)]
- public Object pUnk;
- public int dwCookie;
- }
-
- [Obsolete("Use System.Runtime.InteropServices.ComTypes.IEnumConnections instead. http://go.microsoft.com/fwlink/?linkid=14202", false)]
- [Guid("B196B287-BAB4-101A-B69C-00AA00341D07")]
- [InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)]
- [ComImport]
- public interface UCOMIEnumConnections
- {
- [PreserveSig]
- int Next(int celt, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 0), Out] CONNECTDATA[] rgelt, out int pceltFetched);
- [PreserveSig]
- int Skip(int celt);
- [PreserveSig]
- void Reset();
- void Clone(out UCOMIEnumConnections ppenum);
- }
-}
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/UCOMIEnumMoniker.cs b/src/mscorlib/src/System/Runtime/InteropServices/UCOMIEnumMoniker.cs
deleted file mode 100644
index 40787fcd5c..0000000000
--- a/src/mscorlib/src/System/Runtime/InteropServices/UCOMIEnumMoniker.cs
+++ /dev/null
@@ -1,33 +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: UCOMIEnumMoniker interface definition.
-**
-**
-=============================================================================*/
-
-namespace System.Runtime.InteropServices
-{
- using System;
- using DWORD = System.UInt32;
-
- [Obsolete("Use System.Runtime.InteropServices.ComTypes.IEnumMoniker instead. http://go.microsoft.com/fwlink/?linkid=14202", false)]
- [Guid("00000102-0000-0000-C000-000000000046")]
- [InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)]
- [ComImport]
- public interface UCOMIEnumMoniker
- {
- [PreserveSig]
- int Next(int celt, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 0), Out] UCOMIMoniker[] rgelt, out int pceltFetched);
- [PreserveSig]
- int Skip(int celt);
- [PreserveSig]
- int Reset();
- void Clone(out UCOMIEnumMoniker ppenum);
- }
-}
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/UCOMIEnumString.cs b/src/mscorlib/src/System/Runtime/InteropServices/UCOMIEnumString.cs
deleted file mode 100644
index 9d0552a0df..0000000000
--- a/src/mscorlib/src/System/Runtime/InteropServices/UCOMIEnumString.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: UCOMIEnumString interface definition.
-**
-**
-=============================================================================*/
-
-namespace System.Runtime.InteropServices
-{
- using System;
-
- [Obsolete("Use System.Runtime.InteropServices.ComTypes.IEnumString instead. http://go.microsoft.com/fwlink/?linkid=14202", false)]
- [Guid("00000101-0000-0000-C000-000000000046")]
- [InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)]
- [ComImport]
- public interface UCOMIEnumString
- {
- [PreserveSig]
- int Next(int celt, [MarshalAs(UnmanagedType.LPArray, ArraySubType = UnmanagedType.LPWStr, SizeParamIndex = 0), Out] String[] rgelt, out int pceltFetched);
- [PreserveSig]
- int Skip(int celt);
- [PreserveSig]
- int Reset();
- void Clone(out UCOMIEnumString ppenum);
- }
-}
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/UCOMIEnumVARIANT.cs b/src/mscorlib/src/System/Runtime/InteropServices/UCOMIEnumVARIANT.cs
deleted file mode 100644
index 0d8585ffdb..0000000000
--- a/src/mscorlib/src/System/Runtime/InteropServices/UCOMIEnumVARIANT.cs
+++ /dev/null
@@ -1,35 +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: UCOMIEnumVARIANT interface definition.
-**
-**
-=============================================================================*/
-
-namespace System.Runtime.InteropServices
-{
- using System;
-
- [Obsolete("Use System.Runtime.InteropServices.ComTypes.IEnumVARIANT instead. http://go.microsoft.com/fwlink/?linkid=14202", false)]
- [Guid("00020404-0000-0000-C000-000000000046")]
- [InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)]
- [ComImport]
- public interface UCOMIEnumVARIANT
- {
- [PreserveSig]
- int Next(int celt, int rgvar, int pceltFetched);
-
- [PreserveSig]
- int Skip(int celt);
-
- [PreserveSig]
- int Reset();
-
- void Clone(int ppenum);
- }
-}
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/UCOMIEnumerable.cs b/src/mscorlib/src/System/Runtime/InteropServices/UCOMIEnumerable.cs
deleted file mode 100644
index 81e0133923..0000000000
--- a/src/mscorlib/src/System/Runtime/InteropServices/UCOMIEnumerable.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.
-
-/*==========================================================================
-**
-** Interface: UCOMIEnumerable
-**
-**
-** Purpose:
-** This interface is redefined here since the original IEnumerable interface
-** has all its methods marked as ecall's since it is a managed standard
-** interface. This interface is used from within the runtime to make a call
-** on the COM server directly when it implements the IEnumerable interface.
-**
-**
-==========================================================================*/
-namespace System.Runtime.InteropServices
-{
- using System;
- using System.Collections;
-
- [Obsolete("Use System.Runtime.InteropServices.ComTypes.IEnumerable instead. http://go.microsoft.com/fwlink/?linkid=14202", false)]
- [Guid("496B0ABE-CDEE-11d3-88E8-00902754C43A")]
- internal interface UCOMIEnumerable
- {
- [DispId(-4)]
- IEnumerator GetEnumerator();
- }
-}
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/UCOMIEnumerator.cs b/src/mscorlib/src/System/Runtime/InteropServices/UCOMIEnumerator.cs
deleted file mode 100644
index af886c46ac..0000000000
--- a/src/mscorlib/src/System/Runtime/InteropServices/UCOMIEnumerator.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.
-
-/*==========================================================================
-**
-** Interface: UCOMIEnumerator
-**
-**
-** Purpose:
-** This interface is redefined here since the original IEnumerator interface
-** has all its methods marked as ecall's since it is a managed standard
-** interface. This interface is used from within the runtime to make a call
-** on the COM server directly when it implements the IEnumerator interface.
-**
-**
-==========================================================================*/
-namespace System.Runtime.InteropServices
-{
- using System;
-
- [Obsolete("Use System.Runtime.InteropServices.ComTypes.IEnumerator instead. http://go.microsoft.com/fwlink/?linkid=14202", false)]
- [Guid("496B0ABF-CDEE-11d3-88E8-00902754C43A")]
- internal interface UCOMIEnumerator
- {
- bool MoveNext();
- Object Current {
- get;
- }
- void Reset();
- }
-}
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/UCOMIExpando.cs b/src/mscorlib/src/System/Runtime/InteropServices/UCOMIExpando.cs
deleted file mode 100644
index 2f85c14bc6..0000000000
--- a/src/mscorlib/src/System/Runtime/InteropServices/UCOMIExpando.cs
+++ /dev/null
@@ -1,33 +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.
-
-/*==========================================================================
-**
-** Interface: UCOMIExpando
-**
-**
-** Purpose:
-** This interface is redefined here since the original IExpando interface
-** has all its methods marked as ecall's since it is a managed standard
-** interface. This interface is used from within the runtime to make a call
-** on the COM server directly when it implements the IExpando interface.
-**
-**
-==========================================================================*/
-namespace System.Runtime.InteropServices
-{
-
- using System;
- using System.Reflection;
-
- [Obsolete("Use System.Runtime.InteropServices.ComTypes.IExpando instead. http://go.microsoft.com/fwlink/?linkid=14202", false)]
- [Guid("AFBF15E6-C37C-11d2-B88E-00A0C9B471B8")]
- internal interface UCOMIExpando : UCOMIReflect
- {
- FieldInfo AddField(String name);
- PropertyInfo AddProperty(String name);
- MethodInfo AddMethod(String name, Delegate method);
- void RemoveMember(MemberInfo m);
- }
-}
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/UCOMIMoniker.cs b/src/mscorlib/src/System/Runtime/InteropServices/UCOMIMoniker.cs
deleted file mode 100644
index bd5b6f4916..0000000000
--- a/src/mscorlib/src/System/Runtime/InteropServices/UCOMIMoniker.cs
+++ /dev/null
@@ -1,60 +0,0 @@
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-// See the LICENSE file in the project root for more information.
-
-/*=============================================================================
-**
-**
-**
-** Purpose: UCOMIMoniker interface definition.
-**
-**
-=============================================================================*/
-
-namespace System.Runtime.InteropServices
-{
- using System;
-
- [Obsolete("Use System.Runtime.InteropServices.ComTypes.FILETIME instead. http://go.microsoft.com/fwlink/?linkid=14202", false)]
- [StructLayout(LayoutKind.Sequential)]
-
- public struct FILETIME
- {
- public int dwLowDateTime;
- public int dwHighDateTime;
- }
-
- [Obsolete("Use System.Runtime.InteropServices.ComTypes.IMoniker instead. http://go.microsoft.com/fwlink/?linkid=14202", false)]
- [Guid("0000000f-0000-0000-C000-000000000046")]
- [InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)]
- [ComImport]
- public interface UCOMIMoniker
- {
- // IPersist portion
- void GetClassID(out Guid pClassID);
-
- // IPersistStream portion
- [PreserveSig]
- int IsDirty();
- void Load(UCOMIStream pStm);
- void Save(UCOMIStream pStm, [MarshalAs(UnmanagedType.Bool)] bool fClearDirty);
- void GetSizeMax(out Int64 pcbSize);
-
- // IMoniker portion
- void BindToObject(UCOMIBindCtx pbc, UCOMIMoniker pmkToLeft, [In()] ref Guid riidResult, [MarshalAs(UnmanagedType.Interface)] out Object ppvResult);
- void BindToStorage(UCOMIBindCtx pbc, UCOMIMoniker pmkToLeft, [In()] ref Guid riid, [MarshalAs(UnmanagedType.Interface)] out Object ppvObj);
- void Reduce(UCOMIBindCtx pbc, int dwReduceHowFar, ref UCOMIMoniker ppmkToLeft, out UCOMIMoniker ppmkReduced);
- void ComposeWith(UCOMIMoniker pmkRight, [MarshalAs(UnmanagedType.Bool)] bool fOnlyIfNotGeneric, out UCOMIMoniker ppmkComposite);
- void Enum([MarshalAs(UnmanagedType.Bool)] bool fForward, out UCOMIEnumMoniker ppenumMoniker);
- void IsEqual(UCOMIMoniker pmkOtherMoniker);
- void Hash(out int pdwHash);
- void IsRunning(UCOMIBindCtx pbc, UCOMIMoniker pmkToLeft, UCOMIMoniker pmkNewlyRunning);
- void GetTimeOfLastChange(UCOMIBindCtx pbc, UCOMIMoniker pmkToLeft, out FILETIME pFileTime);
- void Inverse(out UCOMIMoniker ppmk);
- void CommonPrefixWith(UCOMIMoniker pmkOther, out UCOMIMoniker ppmkPrefix);
- void RelativePathTo(UCOMIMoniker pmkOther, out UCOMIMoniker ppmkRelPath);
- void GetDisplayName(UCOMIBindCtx pbc, UCOMIMoniker pmkToLeft, [MarshalAs(UnmanagedType.LPWStr)] out String ppszDisplayName);
- void ParseDisplayName(UCOMIBindCtx pbc, UCOMIMoniker pmkToLeft, [MarshalAs(UnmanagedType.LPWStr)] String pszDisplayName, out int pchEaten, out UCOMIMoniker ppmkOut);
- void IsSystemMoniker(out int pdwMksys);
- }
-}
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/UCOMIPersistFile.cs b/src/mscorlib/src/System/Runtime/InteropServices/UCOMIPersistFile.cs
deleted file mode 100644
index ac465e771f..0000000000
--- a/src/mscorlib/src/System/Runtime/InteropServices/UCOMIPersistFile.cs
+++ /dev/null
@@ -1,36 +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: UCOMIPersistFile interface definition.
-**
-**
-=============================================================================*/
-
-namespace System.Runtime.InteropServices {
-
- using System;
- using DWORD = System.UInt32;
-
- [Obsolete("Use System.Runtime.InteropServices.ComTypes.IPersistFile instead. http://go.microsoft.com/fwlink/?linkid=14202", false)]
- [Guid("0000010b-0000-0000-C000-000000000046")]
- [InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)]
- [ComImport]
- public interface UCOMIPersistFile
- {
- // IPersist portion
- void GetClassID(out Guid pClassID);
-
- // IPersistFile portion
- [PreserveSig]
- int IsDirty();
- void Load([MarshalAs(UnmanagedType.LPWStr)] String pszFileName, int dwMode);
- void Save([MarshalAs(UnmanagedType.LPWStr)] String pszFileName, [MarshalAs(UnmanagedType.Bool)] bool fRemember);
- void SaveCompleted([MarshalAs(UnmanagedType.LPWStr)] String pszFileName);
- void GetCurFile([MarshalAs(UnmanagedType.LPWStr)] out String ppszFileName);
- }
-}
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/UCOMIReflect.cs b/src/mscorlib/src/System/Runtime/InteropServices/UCOMIReflect.cs
deleted file mode 100644
index d6cdd6828e..0000000000
--- a/src/mscorlib/src/System/Runtime/InteropServices/UCOMIReflect.cs
+++ /dev/null
@@ -1,79 +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.
-
-/*==========================================================================
-**
-** Interface: UCOMIReflect
-**
-**
-** Purpose:
-** This interface is redefined here since the original IReflect interface
-** has all its methods marked as ecall's since it is a managed standard
-** interface. This interface is used from within the runtime to make a call
-** on the COM server directly when it implements the IReflect interface.
-**
-**
-==========================================================================*/
-namespace System.Runtime.InteropServices
-{
- using System;
- using System.Reflection;
- using CultureInfo = System.Globalization.CultureInfo;
-
- [Obsolete("Use System.Runtime.InteropServices.ComTypes.IReflect instead. http://go.microsoft.com/fwlink/?linkid=14202", false)]
- [Guid("AFBF15E5-C37C-11d2-B88E-00A0C9B471B8")]
- internal interface UCOMIReflect
- {
- 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;
- }
- }
-}
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/UCOMIRunningObjectTable.cs b/src/mscorlib/src/System/Runtime/InteropServices/UCOMIRunningObjectTable.cs
deleted file mode 100644
index 8088c0417f..0000000000
--- a/src/mscorlib/src/System/Runtime/InteropServices/UCOMIRunningObjectTable.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: UCOMIRunningObjectTable interface definition.
-**
-**
-=============================================================================*/
-
-namespace System.Runtime.InteropServices
-{
- using System;
-
- [Obsolete("Use System.Runtime.InteropServices.ComTypes.IRunningObjectTable instead. http://go.microsoft.com/fwlink/?linkid=14202", false)]
- [Guid("00000010-0000-0000-C000-000000000046")]
- [InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)]
- [ComImport]
- public interface UCOMIRunningObjectTable
- {
- void Register(int grfFlags, [MarshalAs(UnmanagedType.Interface)] Object punkObject, UCOMIMoniker pmkObjectName, out int pdwRegister);
- void Revoke(int dwRegister);
- void IsRunning(UCOMIMoniker pmkObjectName);
- void GetObject(UCOMIMoniker pmkObjectName, [MarshalAs(UnmanagedType.Interface)] out Object ppunkObject);
- void NoteChangeTime(int dwRegister, ref FILETIME pfiletime);
- void GetTimeOfLastChange(UCOMIMoniker pmkObjectName, out FILETIME pfiletime);
- void EnumRunning(out UCOMIEnumMoniker ppenumMoniker);
- }
-}
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/UCOMIStream.cs b/src/mscorlib/src/System/Runtime/InteropServices/UCOMIStream.cs
deleted file mode 100644
index dc2cb53d97..0000000000
--- a/src/mscorlib/src/System/Runtime/InteropServices/UCOMIStream.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: UCOMIStream interface definition.
-**
-**
-=============================================================================*/
-
-namespace System.Runtime.InteropServices
-{
- using System;
-
- [Obsolete("Use System.Runtime.InteropServices.ComTypes.STATSTG instead. http://go.microsoft.com/fwlink/?linkid=14202", false)]
- [StructLayout(LayoutKind.Sequential, CharSet=CharSet.Unicode)]
-
- public struct STATSTG
- {
- public String pwcsName;
- public int type;
- public Int64 cbSize;
- public FILETIME mtime;
- public FILETIME ctime;
- public FILETIME atime;
- public int grfMode;
- public int grfLocksSupported;
- public Guid clsid;
- public int grfStateBits;
- public int reserved;
- }
-
- [Obsolete("Use System.Runtime.InteropServices.ComTypes.IStream instead. http://go.microsoft.com/fwlink/?linkid=14202", false)]
- [Guid("0000000c-0000-0000-C000-000000000046")]
- [InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)]
- [ComImport]
- public interface UCOMIStream
- {
- // ISequentialStream portion
- void Read([MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 1), Out] Byte[] pv, int cb,IntPtr pcbRead);
- void Write([MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 1)] Byte[] pv, int cb, IntPtr pcbWritten);
-
- // IStream portion
- void Seek(Int64 dlibMove, int dwOrigin, IntPtr plibNewPosition);
- void SetSize(Int64 libNewSize);
- void CopyTo(UCOMIStream pstm, Int64 cb, IntPtr pcbRead, IntPtr pcbWritten);
- void Commit(int grfCommitFlags);
- void Revert();
- void LockRegion(Int64 libOffset, Int64 cb, int dwLockType);
- void UnlockRegion(Int64 libOffset, Int64 cb, int dwLockType);
- void Stat(out STATSTG pstatstg, int grfStatFlag);
- void Clone(out UCOMIStream ppstm);
- }
-}
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/UCOMITypeComp.cs b/src/mscorlib/src/System/Runtime/InteropServices/UCOMITypeComp.cs
deleted file mode 100644
index 0ef1e549a5..0000000000
--- a/src/mscorlib/src/System/Runtime/InteropServices/UCOMITypeComp.cs
+++ /dev/null
@@ -1,52 +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: UCOMITypeComp interface definition.
-**
-**
-=============================================================================*/
-
-namespace System.Runtime.InteropServices
-{
- using System;
-
- [Obsolete("Use System.Runtime.InteropServices.ComTypes.DESCKIND instead. http://go.microsoft.com/fwlink/?linkid=14202", false)]
- [Serializable]
- public enum DESCKIND
- {
- DESCKIND_NONE = 0,
- DESCKIND_FUNCDESC = DESCKIND_NONE + 1,
- DESCKIND_VARDESC = DESCKIND_FUNCDESC + 1,
- DESCKIND_TYPECOMP = DESCKIND_VARDESC + 1,
- DESCKIND_IMPLICITAPPOBJ = DESCKIND_TYPECOMP + 1,
- DESCKIND_MAX = DESCKIND_IMPLICITAPPOBJ + 1
- }
-
- [Obsolete("Use System.Runtime.InteropServices.ComTypes.BINDPTR instead. http://go.microsoft.com/fwlink/?linkid=14202", false)]
- [StructLayout(LayoutKind.Explicit, CharSet=CharSet.Unicode)]
-
- public struct BINDPTR
- {
- [FieldOffset(0)]
- public IntPtr lpfuncdesc;
- [FieldOffset(0)]
- public IntPtr lpvardesc;
- [FieldOffset(0)]
- public IntPtr lptcomp;
- }
-
- [Obsolete("Use System.Runtime.InteropServices.ComTypes.ITypeComp instead. http://go.microsoft.com/fwlink/?linkid=14202", false)]
- [Guid("00020403-0000-0000-C000-000000000046")]
- [InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)]
- [ComImport]
- public interface UCOMITypeComp
- {
- void Bind([MarshalAs(UnmanagedType.LPWStr)] String szName, int lHashVal, Int16 wFlags, out UCOMITypeInfo ppTInfo, out DESCKIND pDescKind, out BINDPTR pBindPtr);
- void BindType([MarshalAs(UnmanagedType.LPWStr)] String szName, int lHashVal, out UCOMITypeInfo ppTInfo, out UCOMITypeComp ppTComp);
- }
-}
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/UCOMITypeInfo.cs b/src/mscorlib/src/System/Runtime/InteropServices/UCOMITypeInfo.cs
deleted file mode 100644
index e26964f5a3..0000000000
--- a/src/mscorlib/src/System/Runtime/InteropServices/UCOMITypeInfo.cs
+++ /dev/null
@@ -1,330 +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: UCOMITypeInfo interface definition.
-**
-**
-=============================================================================*/
-
-namespace System.Runtime.InteropServices
-{
- using System;
-
- [Obsolete("Use System.Runtime.InteropServices.ComTypes.TYPEKIND instead. http://go.microsoft.com/fwlink/?linkid=14202", false)]
- [Serializable]
- public enum TYPEKIND
- {
- TKIND_ENUM = 0,
- TKIND_RECORD = TKIND_ENUM + 1,
- TKIND_MODULE = TKIND_RECORD + 1,
- TKIND_INTERFACE = TKIND_MODULE + 1,
- TKIND_DISPATCH = TKIND_INTERFACE + 1,
- TKIND_COCLASS = TKIND_DISPATCH + 1,
- TKIND_ALIAS = TKIND_COCLASS + 1,
- TKIND_UNION = TKIND_ALIAS + 1,
- TKIND_MAX = TKIND_UNION + 1
- }
-
- [Obsolete("Use System.Runtime.InteropServices.ComTypes.TYPEFLAGS instead. http://go.microsoft.com/fwlink/?linkid=14202", false)]
-[Serializable]
-[Flags()]
- public enum TYPEFLAGS : short
- {
- TYPEFLAG_FAPPOBJECT = 0x1,
- TYPEFLAG_FCANCREATE = 0x2,
- TYPEFLAG_FLICENSED = 0x4,
- TYPEFLAG_FPREDECLID = 0x8,
- TYPEFLAG_FHIDDEN = 0x10,
- TYPEFLAG_FCONTROL = 0x20,
- TYPEFLAG_FDUAL = 0x40,
- TYPEFLAG_FNONEXTENSIBLE = 0x80,
- TYPEFLAG_FOLEAUTOMATION = 0x100,
- TYPEFLAG_FRESTRICTED = 0x200,
- TYPEFLAG_FAGGREGATABLE = 0x400,
- TYPEFLAG_FREPLACEABLE = 0x800,
- TYPEFLAG_FDISPATCHABLE = 0x1000,
- TYPEFLAG_FREVERSEBIND = 0x2000,
- TYPEFLAG_FPROXY = 0x4000
- }
-
- [Obsolete("Use System.Runtime.InteropServices.ComTypes.IMPLTYPEFLAGS instead. http://go.microsoft.com/fwlink/?linkid=14202", false)]
-[Serializable]
-[Flags()]
- public enum IMPLTYPEFLAGS
- {
- IMPLTYPEFLAG_FDEFAULT = 0x1,
- IMPLTYPEFLAG_FSOURCE = 0x2,
- IMPLTYPEFLAG_FRESTRICTED = 0x4,
- IMPLTYPEFLAG_FDEFAULTVTABLE = 0x8,
- }
-
- [Obsolete("Use System.Runtime.InteropServices.ComTypes.TYPEATTR instead. http://go.microsoft.com/fwlink/?linkid=14202", false)]
- [StructLayout(LayoutKind.Sequential, CharSet=CharSet.Unicode)]
- public struct TYPEATTR
- {
- // Constant used with the memid fields.
- public const int MEMBER_ID_NIL = unchecked((int)0xFFFFFFFF);
-
- // Actual fields of the TypeAttr struct.
- public Guid guid;
- public Int32 lcid;
- public Int32 dwReserved;
- public Int32 memidConstructor;
- public Int32 memidDestructor;
- public IntPtr lpstrSchema;
- public Int32 cbSizeInstance;
- public TYPEKIND typekind;
- public Int16 cFuncs;
- public Int16 cVars;
- public Int16 cImplTypes;
- public Int16 cbSizeVft;
- public Int16 cbAlignment;
- public TYPEFLAGS wTypeFlags;
- public Int16 wMajorVerNum;
- public Int16 wMinorVerNum;
- public TYPEDESC tdescAlias;
- public IDLDESC idldescType;
- }
-
- [Obsolete("Use System.Runtime.InteropServices.ComTypes.FUNCDESC instead. http://go.microsoft.com/fwlink/?linkid=14202", false)]
- [StructLayout(LayoutKind.Sequential)]
- public struct FUNCDESC
- {
- public int memid; //MEMBERID memid;
- public IntPtr lprgscode; // /* [size_is(cScodes)] */ SCODE RPC_FAR *lprgscode;
- public IntPtr lprgelemdescParam; // /* [size_is(cParams)] */ ELEMDESC __RPC_FAR *lprgelemdescParam;
- public FUNCKIND funckind; //FUNCKIND funckind;
- public INVOKEKIND invkind; //INVOKEKIND invkind;
- public CALLCONV callconv; //CALLCONV callconv;
- public Int16 cParams; //short cParams;
- public Int16 cParamsOpt; //short cParamsOpt;
- public Int16 oVft; //short oVft;
- public Int16 cScodes; //short cScodes;
- public ELEMDESC elemdescFunc; //ELEMDESC elemdescFunc;
- public Int16 wFuncFlags; //WORD wFuncFlags;
- }
-
- [Obsolete("Use System.Runtime.InteropServices.ComTypes.IDLFLAG instead. http://go.microsoft.com/fwlink/?linkid=14202", false)]
-[Serializable]
-[Flags()]
- public enum IDLFLAG : short
- {
- IDLFLAG_NONE = PARAMFLAG.PARAMFLAG_NONE,
- IDLFLAG_FIN = PARAMFLAG.PARAMFLAG_FIN,
- IDLFLAG_FOUT = PARAMFLAG.PARAMFLAG_FOUT,
- IDLFLAG_FLCID = PARAMFLAG.PARAMFLAG_FLCID,
- IDLFLAG_FRETVAL = PARAMFLAG.PARAMFLAG_FRETVAL
- }
-
- [Obsolete("Use System.Runtime.InteropServices.ComTypes.IDLDESC instead. http://go.microsoft.com/fwlink/?linkid=14202", false)]
- [StructLayout(LayoutKind.Sequential, CharSet=CharSet.Unicode)]
- public struct IDLDESC
- {
- public int dwReserved;
- public IDLFLAG wIDLFlags;
- }
-
- [Obsolete("Use System.Runtime.InteropServices.ComTypes.PARAMFLAG instead. http://go.microsoft.com/fwlink/?linkid=14202", false)]
-[Serializable]
-[Flags()]
- public enum PARAMFLAG :short
- {
- PARAMFLAG_NONE = 0,
- PARAMFLAG_FIN = 0x1,
- PARAMFLAG_FOUT = 0x2,
- PARAMFLAG_FLCID = 0x4,
- PARAMFLAG_FRETVAL = 0x8,
- PARAMFLAG_FOPT = 0x10,
- PARAMFLAG_FHASDEFAULT = 0x20,
- PARAMFLAG_FHASCUSTDATA = 0x40
- }
-
- [Obsolete("Use System.Runtime.InteropServices.ComTypes.PARAMDESC instead. http://go.microsoft.com/fwlink/?linkid=14202", false)]
- [StructLayout(LayoutKind.Sequential, CharSet=CharSet.Unicode)]
- public struct PARAMDESC
- {
- public IntPtr lpVarValue;
- public PARAMFLAG wParamFlags;
- }
-
- [Obsolete("Use System.Runtime.InteropServices.ComTypes.TYPEDESC instead. http://go.microsoft.com/fwlink/?linkid=14202", false)]
- [StructLayout(LayoutKind.Sequential, CharSet=CharSet.Unicode)]
- public struct TYPEDESC
- {
- public IntPtr lpValue;
- public Int16 vt;
- }
-
- [Obsolete("Use System.Runtime.InteropServices.ComTypes.ELEMDESC instead. http://go.microsoft.com/fwlink/?linkid=14202", false)]
- [StructLayout(LayoutKind.Sequential, CharSet=CharSet.Unicode)]
- public struct ELEMDESC
- {
- public TYPEDESC tdesc;
-
- [System.Runtime.InteropServices.StructLayout(LayoutKind.Explicit, CharSet=CharSet.Unicode)]
- [ComVisible(false)]
- public struct DESCUNION
- {
- [FieldOffset(0)]
- public IDLDESC idldesc;
- [FieldOffset(0)]
- public PARAMDESC paramdesc;
- };
- public DESCUNION desc;
- }
-
- [Obsolete("Use System.Runtime.InteropServices.ComTypes.VARDESC instead. http://go.microsoft.com/fwlink/?linkid=14202", false)]
- [StructLayout(LayoutKind.Sequential, CharSet=CharSet.Unicode)]
- public struct VARDESC
- {
- public int memid;
- public String lpstrSchema;
-
- [System.Runtime.InteropServices.StructLayout(LayoutKind.Explicit, CharSet=CharSet.Unicode)]
- [ComVisible(false)]
- public struct DESCUNION
- {
- [FieldOffset(0)]
- public int oInst;
- [FieldOffset(0)]
- public IntPtr lpvarValue;
- };
-
- public ELEMDESC elemdescVar;
- public short wVarFlags;
- public VarEnum varkind;
- }
-
- [Obsolete("Use System.Runtime.InteropServices.ComTypes.DISPPARAMS instead. http://go.microsoft.com/fwlink/?linkid=14202", false)]
- [StructLayout(LayoutKind.Sequential, CharSet=CharSet.Unicode)]
- public struct DISPPARAMS
- {
- public IntPtr rgvarg;
- public IntPtr rgdispidNamedArgs;
- public int cArgs;
- public int cNamedArgs;
- }
-
- [Obsolete("Use System.Runtime.InteropServices.ComTypes.EXCEPINFO instead. http://go.microsoft.com/fwlink/?linkid=14202", false)]
- [StructLayout(LayoutKind.Sequential, CharSet=CharSet.Unicode)]
- public struct EXCEPINFO
- {
- public Int16 wCode;
- public Int16 wReserved;
- [MarshalAs(UnmanagedType.BStr)] public String bstrSource;
- [MarshalAs(UnmanagedType.BStr)] public String bstrDescription;
- [MarshalAs(UnmanagedType.BStr)] public String bstrHelpFile;
- public int dwHelpContext;
- public IntPtr pvReserved;
- public IntPtr pfnDeferredFillIn;
- }
-
- [Obsolete("Use System.Runtime.InteropServices.ComTypes.FUNCKIND instead. http://go.microsoft.com/fwlink/?linkid=14202", false)]
- [Serializable]
- public enum FUNCKIND : int
- {
- FUNC_VIRTUAL = 0,
- FUNC_PUREVIRTUAL = 1,
- FUNC_NONVIRTUAL = 2,
- FUNC_STATIC = 3,
- FUNC_DISPATCH = 4
- }
-
- [Obsolete("Use System.Runtime.InteropServices.ComTypes.INVOKEKIND instead. http://go.microsoft.com/fwlink/?linkid=14202", false)]
- [Serializable]
- public enum INVOKEKIND : int
- {
- INVOKE_FUNC = 0x1,
- INVOKE_PROPERTYGET = 0x2,
- INVOKE_PROPERTYPUT = 0x4,
- INVOKE_PROPERTYPUTREF = 0x8
- }
-
- [Obsolete("Use System.Runtime.InteropServices.ComTypes.CALLCONV instead. http://go.microsoft.com/fwlink/?linkid=14202", false)]
- [Serializable]
- public enum CALLCONV : int
- {
- CC_CDECL =1,
- CC_MSCPASCAL=2,
- CC_PASCAL =CC_MSCPASCAL,
- CC_MACPASCAL=3,
- CC_STDCALL =4,
- CC_RESERVED =5,
- CC_SYSCALL =6,
- CC_MPWCDECL =7,
- CC_MPWPASCAL=8,
- CC_MAX =9
- }
-
- [Obsolete("Use System.Runtime.InteropServices.ComTypes.FUNCFLAGS instead. http://go.microsoft.com/fwlink/?linkid=14202", false)]
-[Serializable]
-[Flags()]
- public enum FUNCFLAGS : short
- {
- FUNCFLAG_FRESTRICTED= 0x1,
- FUNCFLAG_FSOURCE = 0x2,
- FUNCFLAG_FBINDABLE = 0x4,
- FUNCFLAG_FREQUESTEDIT = 0x8,
- FUNCFLAG_FDISPLAYBIND = 0x10,
- FUNCFLAG_FDEFAULTBIND = 0x20,
- FUNCFLAG_FHIDDEN = 0x40,
- FUNCFLAG_FUSESGETLASTERROR= 0x80,
- FUNCFLAG_FDEFAULTCOLLELEM= 0x100,
- FUNCFLAG_FUIDEFAULT = 0x200,
- FUNCFLAG_FNONBROWSABLE = 0x400,
- FUNCFLAG_FREPLACEABLE = 0x800,
- FUNCFLAG_FIMMEDIATEBIND = 0x1000
- }
-
- [Obsolete("Use System.Runtime.InteropServices.ComTypes.VARFLAGS instead. http://go.microsoft.com/fwlink/?linkid=14202", false)]
-[Serializable]
-[Flags()]
- public enum VARFLAGS : short
- {
- VARFLAG_FREADONLY =0x1,
- VARFLAG_FSOURCE =0x2,
- VARFLAG_FBINDABLE =0x4,
- VARFLAG_FREQUESTEDIT =0x8,
- VARFLAG_FDISPLAYBIND =0x10,
- VARFLAG_FDEFAULTBIND =0x20,
- VARFLAG_FHIDDEN =0x40,
- VARFLAG_FRESTRICTED =0x80,
- VARFLAG_FDEFAULTCOLLELEM =0x100,
- VARFLAG_FUIDEFAULT =0x200,
- VARFLAG_FNONBROWSABLE =0x400,
- VARFLAG_FREPLACEABLE =0x800,
- VARFLAG_FIMMEDIATEBIND =0x1000
- }
-
- [Obsolete("Use System.Runtime.InteropServices.ComTypes.ITypeInfo instead. http://go.microsoft.com/fwlink/?linkid=14202", false)]
- [Guid("00020401-0000-0000-C000-000000000046")]
- [InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)]
- [ComImport]
- public interface UCOMITypeInfo
- {
- void GetTypeAttr(out IntPtr ppTypeAttr);
- void GetTypeComp(out UCOMITypeComp ppTComp);
- void GetFuncDesc(int index, out IntPtr ppFuncDesc);
- void GetVarDesc(int index, out IntPtr ppVarDesc);
- void GetNames(int memid, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 2), Out] String[] rgBstrNames, int cMaxNames, out int pcNames);
- void GetRefTypeOfImplType(int index, out int href);
- void GetImplTypeFlags(int index, out int pImplTypeFlags);
- void GetIDsOfNames([MarshalAs(UnmanagedType.LPArray, ArraySubType = UnmanagedType.LPWStr, SizeParamIndex = 1), In] String[] rgszNames, int cNames, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 1), Out] int[] pMemId);
- void Invoke([MarshalAs(UnmanagedType.IUnknown)] Object pvInstance, int memid, Int16 wFlags, ref DISPPARAMS pDispParams, out Object pVarResult, out EXCEPINFO pExcepInfo, out int puArgErr);
- void GetDocumentation(int index, out String strName, out String strDocString, out int dwHelpContext, out String strHelpFile);
- void GetDllEntry(int memid, INVOKEKIND invKind, out String pBstrDllName, out String pBstrName, out Int16 pwOrdinal);
- void GetRefTypeInfo(int hRef, out UCOMITypeInfo ppTI);
- void AddressOfMember(int memid, INVOKEKIND invKind, out IntPtr ppv);
- void CreateInstance([MarshalAs(UnmanagedType.IUnknown)] Object pUnkOuter, ref Guid riid, [MarshalAs(UnmanagedType.IUnknown), Out] out Object ppvObj);
- void GetMops(int memid, out String pBstrMops);
- void GetContainingTypeLib(out UCOMITypeLib ppTLB, out int pIndex);
- void ReleaseTypeAttr(IntPtr pTypeAttr);
- void ReleaseFuncDesc(IntPtr pFuncDesc);
- void ReleaseVarDesc(IntPtr pVarDesc);
- }
-}
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/UCOMITypeLib.cs b/src/mscorlib/src/System/Runtime/InteropServices/UCOMITypeLib.cs
deleted file mode 100644
index c8b63deff6..0000000000
--- a/src/mscorlib/src/System/Runtime/InteropServices/UCOMITypeLib.cs
+++ /dev/null
@@ -1,71 +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: UCOMITypeLib interface definition.
-**
-**
-=============================================================================*/
-
-namespace System.Runtime.InteropServices
-{
- using System;
-
- [Obsolete("Use System.Runtime.InteropServices.ComTypes.SYSKIND instead. http://go.microsoft.com/fwlink/?linkid=14202", false)]
- [Serializable]
- public enum SYSKIND
- {
- SYS_WIN16 = 0,
- SYS_WIN32 = SYS_WIN16 + 1,
- SYS_MAC = SYS_WIN32 + 1
- }
-
- [Obsolete("Use System.Runtime.InteropServices.ComTypes.LIBFLAGS instead. http://go.microsoft.com/fwlink/?linkid=14202", false)]
-[Serializable]
-[Flags()]
- public enum LIBFLAGS : short
- {
- LIBFLAG_FRESTRICTED = 0x1,
- LIBFLAG_FCONTROL = 0x2,
- LIBFLAG_FHIDDEN = 0x4,
- LIBFLAG_FHASDISKIMAGE = 0x8
- }
-
- [Obsolete("Use System.Runtime.InteropServices.ComTypes.TYPELIBATTR instead. http://go.microsoft.com/fwlink/?linkid=14202", false)]
- [StructLayout(LayoutKind.Sequential, CharSet=CharSet.Unicode)]
- [Serializable]
- public struct TYPELIBATTR
- {
- public Guid guid;
- public int lcid;
- public SYSKIND syskind;
- public Int16 wMajorVerNum;
- public Int16 wMinorVerNum;
- public LIBFLAGS wLibFlags;
- }
-
- [Obsolete("Use System.Runtime.InteropServices.ComTypes.ITypeLib instead. http://go.microsoft.com/fwlink/?linkid=14202", false)]
- [Guid("00020402-0000-0000-C000-000000000046")]
- [InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)]
- [ComImport]
- public interface UCOMITypeLib
- {
- [PreserveSig]
- int GetTypeInfoCount();
- void GetTypeInfo(int index, out UCOMITypeInfo ppTI);
- void GetTypeInfoType(int index, out TYPEKIND pTKind);
- void GetTypeInfoOfGuid(ref Guid guid, out UCOMITypeInfo ppTInfo);
- void GetLibAttr(out IntPtr ppTLibAttr);
- void GetTypeComp(out UCOMITypeComp ppTComp);
- void GetDocumentation(int index, out String strName, out String strDocString, out int dwHelpContext, out String strHelpFile);
- [return : MarshalAs(UnmanagedType.Bool)]
- bool IsName([MarshalAs(UnmanagedType.LPWStr)] String szNameBuf, int lHashVal);
- void FindName([MarshalAs(UnmanagedType.LPWStr)] String szNameBuf, int lHashVal, [MarshalAs(UnmanagedType.LPArray), Out] UCOMITypeInfo[] ppTInfo, [MarshalAs(UnmanagedType.LPArray), Out] int[] rgMemId, ref Int16 pcFound);
- [PreserveSig]
- void ReleaseTLibAttr(IntPtr pTLibAttr);
- }
-}
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/UnknownWrapper.cs b/src/mscorlib/src/System/Runtime/InteropServices/UnknownWrapper.cs
index 69ef2dcc06..1f70108a02 100644
--- a/src/mscorlib/src/System/Runtime/InteropServices/UnknownWrapper.cs
+++ b/src/mscorlib/src/System/Runtime/InteropServices/UnknownWrapper.cs
@@ -16,7 +16,6 @@ namespace System.Runtime.InteropServices {
using System;
[Serializable]
-[System.Runtime.InteropServices.ComVisible(true)]
public sealed class UnknownWrapper
{
public UnknownWrapper(Object obj)
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/Variant.cs b/src/mscorlib/src/System/Runtime/InteropServices/Variant.cs
deleted file mode 100644
index c7bbb78ae6..0000000000
--- a/src/mscorlib/src/System/Runtime/InteropServices/Variant.cs
+++ /dev/null
@@ -1,658 +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 {
- using System.Diagnostics;
-
- /// <summary>
- /// Variant is the basic COM type for late-binding. It can contain any other COM data type.
- /// This type definition precisely matches the unmanaged data layout so that the struct can be passed
- /// to and from COM calls.
- /// </summary>
- [StructLayout(LayoutKind.Explicit)]
- internal struct Variant {
-
-#if DEBUG
- static Variant() {
- // Variant size is the size of 4 pointers (16 bytes) on a 32-bit processor,
- // and 3 pointers (24 bytes) on a 64-bit processor.
- int variantSize = Marshal.SizeOf(typeof(Variant));
- if (IntPtr.Size == 4) {
- BCLDebug.Assert(variantSize == (4 * IntPtr.Size), "variant");
- } else {
- BCLDebug.Assert(IntPtr.Size == 8, "variant");
- BCLDebug.Assert(variantSize == (3 * IntPtr.Size), "variant");
- }
- }
-#endif
-
- // Most of the data types in the Variant are carried in _typeUnion
- [FieldOffset(0)] private TypeUnion _typeUnion;
-
- // Decimal is the largest data type and it needs to use the space that is normally unused in TypeUnion._wReserved1, etc.
- // Hence, it is declared to completely overlap with TypeUnion. A Decimal does not use the first two bytes, and so
- // TypeUnion._vt can still be used to encode the type.
- [FieldOffset(0)] private Decimal _decimal;
-
- [StructLayout(LayoutKind.Sequential)]
- private struct TypeUnion {
- internal ushort _vt;
- internal ushort _wReserved1;
- internal ushort _wReserved2;
- internal ushort _wReserved3;
-
- internal UnionTypes _unionTypes;
- }
-
- [StructLayout(LayoutKind.Sequential)]
- private struct Record {
- private IntPtr _record;
- private IntPtr _recordInfo;
- }
-
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1049:TypesThatOwnNativeResourcesShouldBeDisposable")]
- [StructLayout(LayoutKind.Explicit)]
- private struct UnionTypes {
- #region Generated Variant union types
-
- // *** BEGIN GENERATED CODE ***
- // generated by function: gen_UnionTypes from: generate_comdispatch.py
-
- [FieldOffset(0)] internal SByte _i1;
- [FieldOffset(0)] internal Int16 _i2;
- [FieldOffset(0)] internal Int32 _i4;
- [FieldOffset(0)] internal Int64 _i8;
- [FieldOffset(0)] internal Byte _ui1;
- [FieldOffset(0)] internal UInt16 _ui2;
- [FieldOffset(0)] internal UInt32 _ui4;
- [FieldOffset(0)] internal UInt64 _ui8;
- [FieldOffset(0)] internal Int32 _int;
- [FieldOffset(0)] internal UInt32 _uint;
- [FieldOffset(0)] internal Int16 _bool;
- [FieldOffset(0)] internal Int32 _error;
- [FieldOffset(0)] internal Single _r4;
- [FieldOffset(0)] internal Double _r8;
- [FieldOffset(0)] internal Int64 _cy;
- [FieldOffset(0)] internal double _date;
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources")]
- [FieldOffset(0)] internal IntPtr _bstr;
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources")]
- [FieldOffset(0)] internal IntPtr _unknown;
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources")]
- [FieldOffset(0)] internal IntPtr _dispatch;
-
- // *** END GENERATED CODE ***
-
- #endregion
-
- [FieldOffset(0)] internal IntPtr _pvarVal;
- [FieldOffset(0)] internal IntPtr _byref;
- [FieldOffset(0)] internal Record _record;
- }
-
- /// <summary>
- /// Primitive types are the basic COM types. It includes valuetypes like ints, but also reference types
- /// like BStrs. It does not include composite types like arrays and user-defined COM types (IUnknown/IDispatch).
- /// </summary>
- internal static bool IsPrimitiveType(VarEnum varEnum) {
- switch(varEnum) {
- #region Generated Variant IsPrimitiveType
-
- // *** BEGIN GENERATED CODE ***
- // generated by function: gen_IsPrimitiveType from: generate_comdispatch.py
-
- case VarEnum.VT_I1:
- case VarEnum.VT_I2:
- case VarEnum.VT_I4:
- case VarEnum.VT_I8:
- case VarEnum.VT_UI1:
- case VarEnum.VT_UI2:
- case VarEnum.VT_UI4:
- case VarEnum.VT_UI8:
- case VarEnum.VT_INT:
- case VarEnum.VT_UINT:
- case VarEnum.VT_BOOL:
- case VarEnum.VT_R4:
- case VarEnum.VT_R8:
- case VarEnum.VT_DECIMAL:
- case VarEnum.VT_DATE:
- case VarEnum.VT_BSTR:
-
- // *** END GENERATED CODE ***
-
- #endregion
- return true;
- }
-
- return false;
- }
-
- unsafe public void CopyFromIndirect(object value) {
-
- VarEnum vt = (VarEnum)(((int)this.VariantType) & ~((int)VarEnum.VT_BYREF));
-
- if (value == null) {
- if (vt == VarEnum.VT_DISPATCH || vt == VarEnum.VT_UNKNOWN || vt == VarEnum.VT_BSTR) {
- *(IntPtr*)this._typeUnion._unionTypes._byref = IntPtr.Zero;
- }
- return;
- }
-
- switch (vt) {
- case VarEnum.VT_I1:
- *(sbyte*)this._typeUnion._unionTypes._byref = (sbyte)value;
- break;
-
- case VarEnum.VT_UI1:
- *(byte*)this._typeUnion._unionTypes._byref = (byte)value;
- break;
-
- case VarEnum.VT_I2:
- *(short*)this._typeUnion._unionTypes._byref = (short)value;
- break;
-
- case VarEnum.VT_UI2:
- *(ushort*)this._typeUnion._unionTypes._byref = (ushort)value;
- break;
-
- case VarEnum.VT_BOOL:
- *(short*)this._typeUnion._unionTypes._byref = (bool)value ? (short)-1 : (short)0;
- break;
-
- case VarEnum.VT_I4:
- case VarEnum.VT_INT:
- *(int*)this._typeUnion._unionTypes._byref = (int)value;
- break;
-
- case VarEnum.VT_UI4:
- case VarEnum.VT_UINT:
- *(uint*)this._typeUnion._unionTypes._byref = (uint)value;
- break;
-
- case VarEnum.VT_ERROR:
- *(int*)this._typeUnion._unionTypes._byref = ((ErrorWrapper)value).ErrorCode;
- break;
-
- case VarEnum.VT_I8:
- *(Int64*)this._typeUnion._unionTypes._byref = (Int64)value;
- break;
-
- case VarEnum.VT_UI8:
- *(UInt64*)this._typeUnion._unionTypes._byref = (UInt64)value;
- break;
-
- case VarEnum.VT_R4:
- *(float*)this._typeUnion._unionTypes._byref = (float)value;
- break;
-
- case VarEnum.VT_R8:
- *(double*)this._typeUnion._unionTypes._byref = (double)value;
- break;
-
- case VarEnum.VT_DATE:
- *(double*)this._typeUnion._unionTypes._byref = ((DateTime)value).ToOADate();
- break;
-
- case VarEnum.VT_UNKNOWN:
- *(IntPtr*)this._typeUnion._unionTypes._byref = Marshal.GetIUnknownForObject(value);
- break;
-
- case VarEnum.VT_DISPATCH:
- *(IntPtr*)this._typeUnion._unionTypes._byref = Marshal.GetIDispatchForObject(value);
- break;
-
- case VarEnum.VT_BSTR:
- *(IntPtr*)this._typeUnion._unionTypes._byref = Marshal.StringToBSTR((string)value);
- break;
-
- case VarEnum.VT_CY:
- *(long*)this._typeUnion._unionTypes._byref = decimal.ToOACurrency((decimal)value);
- break;
-
- case VarEnum.VT_DECIMAL:
- *(decimal*)this._typeUnion._unionTypes._byref = (decimal)value;
- break;
-
- case VarEnum.VT_VARIANT:
- Marshal.GetNativeVariantForObject(value, this._typeUnion._unionTypes._byref);
- break;
-
- default:
- throw new ArgumentException("invalid argument type");
- }
- }
-
- /// <summary>
- /// Get the managed object representing the Variant.
- /// </summary>
- /// <returns></returns>
- public object ToObject() {
- // Check the simple case upfront
- if (IsEmpty) {
- return null;
- }
-
- switch (VariantType) {
- case VarEnum.VT_NULL: return DBNull.Value;
-
- #region Generated Variant ToObject
-
- // *** BEGIN GENERATED CODE ***
- // generated by function: gen_ToObject from: generate_comdispatch.py
-
- case VarEnum.VT_I1: return AsI1;
- case VarEnum.VT_I2: return AsI2;
- case VarEnum.VT_I4: return AsI4;
- case VarEnum.VT_I8: return AsI8;
- case VarEnum.VT_UI1: return AsUi1;
- case VarEnum.VT_UI2: return AsUi2;
- case VarEnum.VT_UI4: return AsUi4;
- case VarEnum.VT_UI8: return AsUi8;
- case VarEnum.VT_INT: return AsInt;
- case VarEnum.VT_UINT: return AsUint;
- case VarEnum.VT_BOOL: return AsBool;
- case VarEnum.VT_ERROR: return AsError;
- case VarEnum.VT_R4: return AsR4;
- case VarEnum.VT_R8: return AsR8;
- case VarEnum.VT_DECIMAL: return AsDecimal;
- case VarEnum.VT_CY: return AsCy;
- case VarEnum.VT_DATE: return AsDate;
- case VarEnum.VT_BSTR: return AsBstr;
- case VarEnum.VT_UNKNOWN: return AsUnknown;
- case VarEnum.VT_DISPATCH: return AsDispatch;
- // VarEnum.VT_VARIANT is handled by Marshal.GetObjectForNativeVariant below
-
- // *** END GENERATED CODE ***
-
- #endregion
-
- default:
- try {
- unsafe {
- fixed (void* pThis = &this) {
- return Marshal.GetObjectForNativeVariant((System.IntPtr)pThis);
- }
- }
- }
- catch (Exception ex) {
- throw new NotImplementedException("Variant.ToObject cannot handle" + VariantType, ex);
- }
- }
- }
-
- /// <summary>
- /// Release any unmanaged memory associated with the Variant
- /// </summary>
- /// <returns></returns>
- public void Clear() {
- // We do not need to call OLE32's VariantClear for primitive types or ByRefs
- // to safe ourselves the cost of interop transition.
- // ByRef indicates the memory is not owned by the VARIANT itself while
- // primitive types do not have any resources to free up.
- // Hence, only safearrays, BSTRs, interfaces and user types are
- // handled differently.
- VarEnum vt = VariantType;
- if ((vt & VarEnum.VT_BYREF) != 0) {
- VariantType = VarEnum.VT_EMPTY;
- } else if (
- ((vt & VarEnum.VT_ARRAY) != 0) ||
- ((vt) == VarEnum.VT_BSTR) ||
- ((vt) == VarEnum.VT_UNKNOWN) ||
- ((vt) == VarEnum.VT_DISPATCH) ||
- ((vt) == VarEnum.VT_VARIANT) ||
- ((vt) == VarEnum.VT_RECORD) ||
- ((vt) == VarEnum.VT_VARIANT)
- ) {
- unsafe {
- fixed (void* pThis = &this) {
- NativeMethods.VariantClear((IntPtr)pThis);
- }
- }
- BCLDebug.Assert(IsEmpty, "variant");
- } else {
- VariantType = VarEnum.VT_EMPTY;
- }
- }
-
- public VarEnum VariantType {
- get {
- return (VarEnum)_typeUnion._vt;
- }
- set {
- _typeUnion._vt = (ushort)value;
- }
- }
-
- internal bool IsEmpty {
- get {
- return _typeUnion._vt == ((ushort)VarEnum.VT_EMPTY);
- }
- }
-
- internal bool IsByRef {
- get {
- return (_typeUnion._vt & ((ushort)VarEnum.VT_BYREF)) != 0;
- }
- }
-
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly")]
- public void SetAsNULL() {
- BCLDebug.Assert(IsEmpty, "variant"); // The setter can only be called once as VariantClear might be needed otherwise
- VariantType = VarEnum.VT_NULL;
- }
-
- #region Generated Variant accessors
-
- // *** BEGIN GENERATED CODE ***
- // generated by function: gen_accessors from: generate_comdispatch.py
-
- // VT_I1
-
- public SByte AsI1 {
- get {
- BCLDebug.Assert(VariantType == VarEnum.VT_I1, "variant");
- return _typeUnion._unionTypes._i1;
- }
- set {
- BCLDebug.Assert(IsEmpty, "variant"); // The setter can only be called once as VariantClear might be needed otherwise
- VariantType = VarEnum.VT_I1;
- _typeUnion._unionTypes._i1 = value;
- }
- }
-
- // VT_I2
-
- public Int16 AsI2 {
- get {
- BCLDebug.Assert(VariantType == VarEnum.VT_I2, "variant");
- return _typeUnion._unionTypes._i2;
- }
- set {
- BCLDebug.Assert(IsEmpty, "variant"); // The setter can only be called once as VariantClear might be needed otherwise
- VariantType = VarEnum.VT_I2;
- _typeUnion._unionTypes._i2 = value;
- }
- }
-
- // VT_I4
-
- public Int32 AsI4 {
- get {
- BCLDebug.Assert(VariantType == VarEnum.VT_I4, "variant");
- return _typeUnion._unionTypes._i4;
- }
- set {
- BCLDebug.Assert(IsEmpty, "variant"); // The setter can only be called once as VariantClear might be needed otherwise
- VariantType = VarEnum.VT_I4;
- _typeUnion._unionTypes._i4 = value;
- }
- }
-
- // VT_I8
-
- public Int64 AsI8 {
- get {
- BCLDebug.Assert(VariantType == VarEnum.VT_I8, "variant");
- return _typeUnion._unionTypes._i8;
- }
- set {
- BCLDebug.Assert(IsEmpty, "variant"); // The setter can only be called once as VariantClear might be needed otherwise
- VariantType = VarEnum.VT_I8;
- _typeUnion._unionTypes._i8 = value;
- }
- }
-
- // VT_UI1
-
- public Byte AsUi1 {
- get {
- BCLDebug.Assert(VariantType == VarEnum.VT_UI1, "variant");
- return _typeUnion._unionTypes._ui1;
- }
- set {
- BCLDebug.Assert(IsEmpty, "variant"); // The setter can only be called once as VariantClear might be needed otherwise
- VariantType = VarEnum.VT_UI1;
- _typeUnion._unionTypes._ui1 = value;
- }
- }
-
- // VT_UI2
-
- public UInt16 AsUi2 {
- get {
- BCLDebug.Assert(VariantType == VarEnum.VT_UI2, "variant");
- return _typeUnion._unionTypes._ui2;
- }
- set {
- BCLDebug.Assert(IsEmpty, "variant"); // The setter can only be called once as VariantClear might be needed otherwise
- VariantType = VarEnum.VT_UI2;
- _typeUnion._unionTypes._ui2 = value;
- }
- }
-
- // VT_UI4
-
- public UInt32 AsUi4 {
- get {
- BCLDebug.Assert(VariantType == VarEnum.VT_UI4, "variant");
- return _typeUnion._unionTypes._ui4;
- }
- set {
- BCLDebug.Assert(IsEmpty, "variant"); // The setter can only be called once as VariantClear might be needed otherwise
- VariantType = VarEnum.VT_UI4;
- _typeUnion._unionTypes._ui4 = value;
- }
- }
-
- // VT_UI8
-
- public UInt64 AsUi8 {
- get {
- BCLDebug.Assert(VariantType == VarEnum.VT_UI8, "variant");
- return _typeUnion._unionTypes._ui8;
- }
- set {
- BCLDebug.Assert(IsEmpty, "variant"); // The setter can only be called once as VariantClear might be needed otherwise
- VariantType = VarEnum.VT_UI8;
- _typeUnion._unionTypes._ui8 = value;
- }
- }
-
- // VT_INT
-
- public Int32 AsInt {
- get {
- BCLDebug.Assert(VariantType == VarEnum.VT_INT, "variant");
- return _typeUnion._unionTypes._int;
- }
- set {
- BCLDebug.Assert(IsEmpty, "variant"); // The setter can only be called once as VariantClear might be needed otherwise
- VariantType = VarEnum.VT_INT;
- _typeUnion._unionTypes._int = value;
- }
- }
-
- // VT_UINT
-
- public UInt32 AsUint {
- get {
- BCLDebug.Assert(VariantType == VarEnum.VT_UINT, "variant");
- return _typeUnion._unionTypes._uint;
- }
- set {
- BCLDebug.Assert(IsEmpty, "variant"); // The setter can only be called once as VariantClear might be needed otherwise
- VariantType = VarEnum.VT_UINT;
- _typeUnion._unionTypes._uint = value;
- }
- }
-
- // VT_BOOL
-
- public bool AsBool {
- get {
- BCLDebug.Assert(VariantType == VarEnum.VT_BOOL, "variant");
- return _typeUnion._unionTypes._bool != 0;
- }
- set {
- BCLDebug.Assert(IsEmpty, "variant"); // The setter can only be called once as VariantClear might be needed otherwise
- VariantType = VarEnum.VT_BOOL;
- _typeUnion._unionTypes._bool = value ? (short)-1 : (short)0;
- }
- }
-
- // VT_ERROR
-
- public Int32 AsError {
- get {
- BCLDebug.Assert(VariantType == VarEnum.VT_ERROR, "variant");
- return _typeUnion._unionTypes._error;
- }
- set {
- BCLDebug.Assert(IsEmpty, "variant"); // The setter can only be called once as VariantClear might be needed otherwise
- VariantType = VarEnum.VT_ERROR;
- _typeUnion._unionTypes._error = value;
- }
- }
-
- // VT_R4
-
- public Single AsR4 {
- get {
- BCLDebug.Assert(VariantType == VarEnum.VT_R4, "variant");
- return _typeUnion._unionTypes._r4;
- }
- set {
- BCLDebug.Assert(IsEmpty, "variant"); // The setter can only be called once as VariantClear might be needed otherwise
- VariantType = VarEnum.VT_R4;
- _typeUnion._unionTypes._r4 = value;
- }
- }
-
- // VT_R8
-
- public Double AsR8 {
- get {
- BCLDebug.Assert(VariantType == VarEnum.VT_R8, "variant");
- return _typeUnion._unionTypes._r8;
- }
- set {
- BCLDebug.Assert(IsEmpty, "variant"); // The setter can only be called once as VariantClear might be needed otherwise
- VariantType = VarEnum.VT_R8;
- _typeUnion._unionTypes._r8 = value;
- }
- }
-
- // VT_DECIMAL
-
- public Decimal AsDecimal {
- get {
- BCLDebug.Assert(VariantType == VarEnum.VT_DECIMAL, "variant");
- // The first byte of Decimal is unused, but usually set to 0
- Variant v = this;
- v._typeUnion._vt = 0;
- return v._decimal;
- }
- set {
- BCLDebug.Assert(IsEmpty, "variant"); // The setter can only be called once as VariantClear might be needed otherwise
- VariantType = VarEnum.VT_DECIMAL;
- _decimal = value;
- // _vt overlaps with _decimal, and should be set after setting _decimal
- _typeUnion._vt = (ushort)VarEnum.VT_DECIMAL;
- }
- }
-
- // VT_CY
-
- public Decimal AsCy {
- get {
- BCLDebug.Assert(VariantType == VarEnum.VT_CY, "variant");
- return Decimal.FromOACurrency(_typeUnion._unionTypes._cy);
- }
- set {
- BCLDebug.Assert(IsEmpty, "variant"); // The setter can only be called once as VariantClear might be needed otherwise
- VariantType = VarEnum.VT_CY;
- _typeUnion._unionTypes._cy = Decimal.ToOACurrency(value);
- }
- }
-
- // VT_DATE
-
- public DateTime AsDate {
- get {
- BCLDebug.Assert(VariantType == VarEnum.VT_DATE, "variant");
- return DateTime.FromOADate(_typeUnion._unionTypes._date);
- }
- set {
- BCLDebug.Assert(IsEmpty, "variant"); // The setter can only be called once as VariantClear might be needed otherwise
- VariantType = VarEnum.VT_DATE;
- _typeUnion._unionTypes._date = value.ToOADate();
- }
- }
-
- // VT_BSTR
-
- public String AsBstr {
- get {
- BCLDebug.Assert(VariantType == VarEnum.VT_BSTR, "variant");
- return (string)Marshal.PtrToStringBSTR(this._typeUnion._unionTypes._bstr);
- }
- set {
- BCLDebug.Assert(IsEmpty, "variant"); // The setter can only be called once as VariantClear might be needed otherwise
- VariantType = VarEnum.VT_BSTR;
- this._typeUnion._unionTypes._bstr = Marshal.StringToBSTR(value);
- }
- }
-
- // VT_UNKNOWN
-
- public Object AsUnknown {
- get {
- BCLDebug.Assert(VariantType == VarEnum.VT_UNKNOWN, "variant");
- if (_typeUnion._unionTypes._unknown == IntPtr.Zero)
- return null;
- return Marshal.GetObjectForIUnknown(_typeUnion._unionTypes._unknown);
- }
- set {
- BCLDebug.Assert(IsEmpty, "variant"); // The setter can only be called once as VariantClear might be needed otherwise
- VariantType = VarEnum.VT_UNKNOWN;
- if (value == null)
- _typeUnion._unionTypes._unknown = IntPtr.Zero;
- else
- _typeUnion._unionTypes._unknown = Marshal.GetIUnknownForObject(value);
- }
- }
-
- // VT_DISPATCH
-
- public Object AsDispatch {
- get {
- BCLDebug.Assert(VariantType == VarEnum.VT_DISPATCH, "variant");
- if (_typeUnion._unionTypes._dispatch == IntPtr.Zero)
- return null;
- return Marshal.GetObjectForIUnknown(_typeUnion._unionTypes._dispatch);
- }
- set {
- BCLDebug.Assert(IsEmpty, "variant"); // The setter can only be called once as VariantClear might be needed otherwise
- VariantType = VarEnum.VT_DISPATCH;
- if (value == null)
- _typeUnion._unionTypes._dispatch = IntPtr.Zero;
- else
- _typeUnion._unionTypes._dispatch = Marshal.GetIDispatchForObject(value);
- }
- }
-
-
- // *** END GENERATED CODE ***
-
- internal IntPtr AsByRefVariant
- {
- get {
- BCLDebug.Assert(VariantType == (VarEnum.VT_BYREF | VarEnum.VT_VARIANT), "variant");
- return _typeUnion._unionTypes._pvarVal;
- }
- }
-
- #endregion
- }
-}
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/Attributes.cs b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/Attributes.cs
index 80b24f5529..7fa2420530 100644
--- a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/Attributes.cs
+++ b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/Attributes.cs
@@ -35,7 +35,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime
[System.Runtime.CompilerServices.FriendAccessAllowed]
internal sealed class WindowsRuntimeImportAttribute : Attribute
{
- public WindowsRuntimeImportAttribute()
+ internal WindowsRuntimeImportAttribute()
{ }
}
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/CLRIPropertyValueImpl.cs b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/CLRIPropertyValueImpl.cs
index 702e0c9e52..b7dad17a6b 100644
--- a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/CLRIPropertyValueImpl.cs
+++ b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/CLRIPropertyValueImpl.cs
@@ -148,15 +148,6 @@ namespace System.Runtime.InteropServices.WindowsRuntime
return CoerceScalarValue<String>(PropertyType.String);
}
- [Pure]
- public Object GetInspectable()
- {
- if (this.Type != PropertyType.Inspectable)
- throw new InvalidCastException(Environment.GetResourceString("InvalidCast_WinRTIPropertyValueElement", this.Type, "Inspectable"), __HResults.TYPE_E_TYPEMISMATCH);
- Contract.EndContractBlock();
- return _data;
- }
-
[Pure]
public Guid GetGuid()
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/ConstantSplittableMap.cs b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/ConstantSplittableMap.cs
index a5abb4f23e..3a896ecbe3 100644
--- a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/ConstantSplittableMap.cs
+++ b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/ConstantSplittableMap.cs
@@ -53,25 +53,6 @@ namespace System.Runtime.InteropServices.WindowsRuntime
this.items = CreateKeyValueArray(data.Count, data.GetEnumerator());
}
- internal ConstantSplittableMap(IMapView<TKey, TValue> data)
- {
- if (data == null)
- throw new ArgumentNullException(nameof(data));
-
- if (((UInt32)Int32.MaxValue) < data.Size)
- {
- Exception e = new InvalidOperationException(Environment.GetResourceString("InvalidOperation_CollectionBackingDictionaryTooLarge"));
- e.SetErrorCode(__HResults.E_BOUNDS);
- throw e;
- }
-
- int size = (int)data.Size;
-
- this.firstItemIndex = 0;
- this.lastItemIndex = size - 1;
- this.items = CreateKeyValueArray(size, data.GetEnumerator());
- }
-
private ConstantSplittableMap(KeyValuePair<TKey, TValue>[] items, Int32 firstItemIndex, Int32 lastItemIndex)
{
@@ -94,22 +75,6 @@ namespace System.Runtime.InteropServices.WindowsRuntime
return kvArray;
}
- private KeyValuePair<TKey, TValue>[] CreateKeyValueArray(Int32 count, IEnumerator<IKeyValuePair<TKey, TValue>> data)
- {
- KeyValuePair<TKey, TValue>[] kvArray = new KeyValuePair<TKey, TValue>[count];
-
- Int32 i = 0;
- while (data.MoveNext())
- {
- IKeyValuePair<TKey, TValue> current = data.Current;
- kvArray[i++] = new KeyValuePair<TKey, TValue>(current.Key, current.Value);
- }
-
- Array.Sort(kvArray, keyValuePairComparator);
-
- return kvArray;
- }
-
public int Count {
get {
@@ -179,14 +144,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime
secondPartition = new ConstantSplittableMap<TKey, TValue>(items, pivot + 1, lastItemIndex);
}
- #region IReadOnlyDictionary members
-
- public bool ContainsKey(TKey key)
- {
- KeyValuePair<TKey, TValue> searchKey = new KeyValuePair<TKey, TValue>(key, default(TValue));
- int index = Array.BinarySearch(items, firstItemIndex, Count, searchKey, keyValuePairComparator);
- return index >= 0;
- }
+#region IReadOnlyDictionary members
public bool TryGetValue(TKey key, out TValue value)
{
@@ -203,24 +161,6 @@ namespace System.Runtime.InteropServices.WindowsRuntime
return true;
}
- public TValue this[TKey key] {
- get {
- return Lookup(key);
- }
- }
-
- public IEnumerable<TKey> Keys {
- get {
- throw new NotImplementedException("NYI");
- }
- }
-
- public IEnumerable<TValue> Values {
- get {
- throw new NotImplementedException("NYI");
- }
- }
-
#endregion IReadOnlyDictionary members
#region IKeyValuePair Enumerator
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/CustomPropertyImpl.cs b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/CustomPropertyImpl.cs
index d575201bb9..9f822d5ced 100644
--- a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/CustomPropertyImpl.cs
+++ b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/CustomPropertyImpl.cs
@@ -123,7 +123,6 @@ 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.
- 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/IVector.cs b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/IVector.cs
index a77ff005b9..6982911a13 100644
--- a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/IVector.cs
+++ b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/IVector.cs
@@ -57,9 +57,6 @@ namespace System.Runtime.InteropServices.WindowsRuntime
void Append(T value);
void RemoveAtEnd();
void Clear();
- [Pure]
- uint GetMany(uint startIndex, [Out] T[] items);
- void ReplaceAll(T[] items);
}
[ComImport]
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/NativeMethods.cs b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/NativeMethods.cs
index 4380369754..627de8d400 100644
--- a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/NativeMethods.cs
+++ b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/NativeMethods.cs
@@ -21,7 +21,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime
internal static class UnsafeNativeMethods
{
- [DllImport("api-ms-win-core-winrt-error-l1-1-1.dll", PreserveSig = false)]
+ [DllImport("api-ms-win-core-winrt-error-l1-1-0.dll", PreserveSig = false)]
[SuppressUnmanagedCodeSecurity]
internal static extern IRestrictedErrorInfo GetRestrictedErrorInfo();
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/WindowsRuntimeBufferHelper.cs b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/WindowsRuntimeBufferHelper.cs
index a786880fab..551ee65153 100644
--- a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/WindowsRuntimeBufferHelper.cs
+++ b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/WindowsRuntimeBufferHelper.cs
@@ -21,12 +21,10 @@ internal static class WindowsRuntimeBufferHelper {
[DllImport(JitHelpers.QCall)]
[SuppressUnmanagedCodeSecurity]
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
private unsafe extern static void StoreOverlappedPtrInCCW(ObjectHandleOnStack windowsRuntimeBuffer, NativeOverlapped* overlapped);
[FriendAccessAllowed]
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
internal unsafe static void StoreOverlappedInCCW(Object windowsRuntimeBuffer, NativeOverlapped* overlapped) {
StoreOverlappedPtrInCCW(JitHelpers.GetObjectHandleOnStack(ref windowsRuntimeBuffer), overlapped);
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/WindowsRuntimeMarshal.cs b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/WindowsRuntimeMarshal.cs
index a7ad4912de..57655ec861 100644
--- a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/WindowsRuntimeMarshal.cs
+++ b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/WindowsRuntimeMarshal.cs
@@ -135,12 +135,6 @@ namespace System.Runtime.InteropServices.WindowsRuntime
restTokens = null;
}
- internal EventRegistrationTokenList(EventRegistrationTokenList list)
- {
- firstToken = list.firstToken;
- restTokens = list.restTokens;
- }
-
// Push a new token into this list
// Returns true if you need to copy back this list into the dictionary (so that you
// don't lose change outside the dictionary). false otherwise.
@@ -1203,42 +1197,6 @@ namespace System.Runtime.InteropServices.WindowsRuntime
return activationFactory;
}
-#if FEATURE_COMINTEROP_WINRT_DESKTOP_HOST
- // Currently we use only a single class activator since we have a requirement that all class activations come from the same
- // app base and we haven't sorted through the various code sharing implications of spinning up multiple AppDomains. This
- // holds the IWinRTClassActivator* that is used for the process
- private static IntPtr s_pClassActivator = IntPtr.Zero;
-
- internal static IntPtr GetClassActivatorForApplication(string appBase)
- {
- if (s_pClassActivator == IntPtr.Zero)
- {
- AppDomainSetup hostDomainSetup = new AppDomainSetup()
- {
- ApplicationBase = appBase,
- };
-
- AppDomain hostDomain = AppDomain.CreateDomain(Environment.GetResourceString("WinRTHostDomainName", appBase), null, hostDomainSetup);
- WinRTClassActivator activator = (WinRTClassActivator)hostDomain.CreateInstanceAndUnwrap(typeof(WinRTClassActivator).Assembly.FullName, typeof(WinRTClassActivator).FullName);
- IntPtr pActivator = activator.GetIWinRTClassActivator();
-
- if (Interlocked.CompareExchange(ref s_pClassActivator, pActivator, IntPtr.Zero) != IntPtr.Zero)
- {
- Marshal.Release(pActivator);
- activator = null;
-
- try
- {
- AppDomain.Unload(hostDomain);
- }
- catch (CannotUnloadAppDomainException) { }
- }
- }
-
- Marshal.AddRef(s_pClassActivator);
- return s_pClassActivator;
- }
-#endif // FEATURE_COMINTEROP_WINRT_DESKTOP_HOST
#endif // FEATURE_COMINTEROP_WINRT_MANAGED_ACTIVATION
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/WindowsRuntimeMetadata.cs b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/WindowsRuntimeMetadata.cs
index 9ca959c528..f097c6a0db 100644
--- a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/WindowsRuntimeMetadata.cs
+++ b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/WindowsRuntimeMetadata.cs
@@ -16,94 +16,10 @@ namespace System.Runtime.InteropServices.WindowsRuntime
using System.Runtime.InteropServices;
using System.Security;
- public static class WindowsRuntimeMetadata
+ internal static class WindowsRuntimeMetadata
{
- // Wrapper for Win8 API RoResolveNamespace with default Windows SDK path as installed .winmd files in %WINDIR%\system32\WinMetadata.
- public static IEnumerable<string> ResolveNamespace(string namespaceName, IEnumerable<string> packageGraphFilePaths)
- {
- return ResolveNamespace(namespaceName, null, packageGraphFilePaths);
- }
-
- // Wrapper for Win8 API RoResolveNamespace.
- public static IEnumerable<string> ResolveNamespace(string namespaceName, string windowsSdkFilePath, IEnumerable<string> packageGraphFilePaths)
- {
- if (namespaceName == null)
- throw new ArgumentNullException(nameof(namespaceName));
- Contract.EndContractBlock();
-
- string[] packageGraphFilePathsArray = null;
- if (packageGraphFilePaths != null)
- {
- List<string> packageGraphFilePathsList = new List<string>(packageGraphFilePaths);
- packageGraphFilePathsArray = new string[packageGraphFilePathsList.Count];
-
- int index = 0;
- foreach (string packageGraphFilePath in packageGraphFilePathsList)
- {
- packageGraphFilePathsArray[index] = packageGraphFilePath;
- index++;
- }
- }
-
- string[] retFileNames = null;
- nResolveNamespace(
- namespaceName,
- windowsSdkFilePath,
- packageGraphFilePathsArray,
- ((packageGraphFilePathsArray == null) ? 0 : packageGraphFilePathsArray.Length),
- JitHelpers.GetObjectHandleOnStack(ref retFileNames));
-
- return retFileNames;
- }
-
- [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
- [SuppressUnmanagedCodeSecurity]
- private extern static void nResolveNamespace(
- string namespaceName,
- string windowsSdkFilePath,
- string[] packageGraphFilePaths,
- int cPackageGraphFilePaths,
- ObjectHandleOnStack retFileNames);
+ private static EventHandler<DesignerNamespaceResolveEventArgs> DesignerNamespaceResolve;
-#if FEATURE_REFLECTION_ONLY_LOAD
- [method: System.Security.SecurityCritical]
- public static event EventHandler<NamespaceResolveEventArgs> ReflectionOnlyNamespaceResolve;
-
- internal static RuntimeAssembly[] OnReflectionOnlyNamespaceResolveEvent(AppDomain appDomain, RuntimeAssembly assembly, string namespaceName)
- {
- EventHandler<NamespaceResolveEventArgs> eventHandler = ReflectionOnlyNamespaceResolve;
- if (eventHandler != null)
- {
- Delegate[] ds = eventHandler.GetInvocationList();
- int len = ds.Length;
- for (int i = 0; i < len; i++)
- {
- NamespaceResolveEventArgs eventArgs = new NamespaceResolveEventArgs(namespaceName, assembly);
-
- ((EventHandler<NamespaceResolveEventArgs>)ds[i])(appDomain, eventArgs);
-
- Collection<Assembly> assembliesCollection = eventArgs.ResolvedAssemblies;
- if (assembliesCollection.Count > 0)
- {
- RuntimeAssembly[] retAssemblies = new RuntimeAssembly[assembliesCollection.Count];
- int retIndex = 0;
- foreach (Assembly asm in assembliesCollection)
- {
- retAssemblies[retIndex] = AppDomain.GetRuntimeAssembly(asm);
- retIndex++;
- }
- return retAssemblies;
- }
- }
- }
-
- return null;
- }
-#endif //FEATURE_REFLECTION_ONLY
-
- [method: System.Security.SecurityCritical]
- public static event EventHandler<DesignerNamespaceResolveEventArgs> DesignerNamespaceResolve;
-
internal static string[] OnDesignerNamespaceResolveEvent(AppDomain appDomain, string namespaceName)
{
EventHandler<DesignerNamespaceResolveEventArgs> eventHandler = DesignerNamespaceResolve;
@@ -142,7 +58,6 @@ namespace System.Runtime.InteropServices.WindowsRuntime
}
#if FEATURE_REFLECTION_ONLY_LOAD
- [ComVisible(false)]
public class NamespaceResolveEventArgs : EventArgs
{
private string _NamespaceName;
@@ -182,20 +97,11 @@ namespace System.Runtime.InteropServices.WindowsRuntime
}
#endif //FEATURE_REFLECTION_ONLY
- [ComVisible(false)]
- public class DesignerNamespaceResolveEventArgs : EventArgs
+ internal class DesignerNamespaceResolveEventArgs : EventArgs
{
private string _NamespaceName;
private Collection<string> _ResolvedAssemblyFiles;
- public string NamespaceName
- {
- get
- {
- return _NamespaceName;
- }
- }
-
public Collection<string> ResolvedAssemblyFiles
{
get
diff --git a/src/mscorlib/src/System/Runtime/Loader/AssemblyLoadContext.cs b/src/mscorlib/src/System/Runtime/Loader/AssemblyLoadContext.cs
index e158a5aa8a..2be8b13274 100644
--- a/src/mscorlib/src/System/Runtime/Loader/AssemblyLoadContext.cs
+++ b/src/mscorlib/src/System/Runtime/Loader/AssemblyLoadContext.cs
@@ -13,15 +13,11 @@ using System.Runtime.InteropServices;
using System.Security;
using System.Threading;
-#if FEATURE_HOST_ASSEMBLY_RESOLVER
namespace System.Runtime.Loader
{
public abstract class AssemblyLoadContext
{
- [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
- [SuppressUnmanagedCodeSecurity]
- private static extern bool OverrideDefaultAssemblyLoadContextForCurrentDomain(IntPtr ptrNativeAssemblyLoadContext);
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
@@ -30,16 +26,11 @@ namespace System.Runtime.Loader
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private static extern IntPtr InitializeAssemblyLoadContext(IntPtr ptrAssemblyLoadContext, bool fRepresentsTPALoadContext);
-
- [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
- [SuppressUnmanagedCodeSecurity]
- private static extern IntPtr LoadFromAssemblyName(IntPtr ptrNativeAssemblyLoadContext, bool fRepresentsTPALoadContext);
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private static extern IntPtr LoadFromStream(IntPtr ptrNativeAssemblyLoadContext, IntPtr ptrAssemblyArray, int iAssemblyArrayLen, IntPtr ptrSymbols, int iSymbolArrayLen, ObjectHandleOnStack retAssembly);
-#if FEATURE_MULTICOREJIT
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
internal static extern void InternalSetProfileRoot(string directoryPath);
@@ -47,7 +38,6 @@ namespace System.Runtime.Loader
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
internal static extern void InternalStartProfile(string profile, IntPtr ptrNativeAssemblyLoadContext);
-#endif // FEATURE_MULTICOREJIT
protected AssemblyLoadContext()
{
@@ -75,7 +65,7 @@ namespace System.Runtime.Loader
// Since unloading an AssemblyLoadContext is not yet implemented, this is a temporary solution to raise the
// Unloading event on process exit. Register for the current AppDomain's ProcessExit event, and the handler will in
// turn raise the Unloading event.
- AppDomain.CurrentDomain.ProcessExit += OnProcessExit;
+ AppContext.Unloading += OnAppContextUnloading;
}
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
@@ -354,28 +344,6 @@ namespace System.Runtime.Loader
return s_DefaultAssemblyLoadContext;
}
}
-
- // This will be used to set the AssemblyLoadContext for DefaultContext, for the AppDomain,
- // by a host. Once set, the runtime will invoke the LoadFromAssemblyName method against it to perform
- // assembly loads for the DefaultContext.
- //
- // This method will throw if the Default AssemblyLoadContext is already set or the Binding model is already locked.
- public static void InitializeDefaultContext(AssemblyLoadContext context)
- {
- if (context == null)
- {
- throw new ArgumentNullException(nameof(context));
- }
-
- // Try to override the default assembly load context
- if (!AssemblyLoadContext.OverrideDefaultAssemblyLoadContextForCurrentDomain(context.m_pNativeAssemblyLoadContext))
- {
- throw new InvalidOperationException(Environment.GetResourceString("AppDomain_BindingModelIsLocked"));
- }
-
- // Update the managed side as well.
- s_DefaultAssemblyLoadContext = context;
- }
// This call opens and closes the file, but does not add the
// assembly to the domain.
@@ -433,20 +401,16 @@ namespace System.Runtime.Loader
// Set the root directory path for profile optimization.
public void SetProfileOptimizationRoot(string directoryPath)
{
-#if FEATURE_MULTICOREJIT
InternalSetProfileRoot(directoryPath);
-#endif // FEATURE_MULTICOREJIT
}
// Start profile optimization for the specified profile name.
public void StartProfileOptimization(string profile)
{
-#if FEATURE_MULTICOREJIT
InternalStartProfile(profile, m_pNativeAssemblyLoadContext);
-#endif // FEATURE_MULTICOREJI
}
- private void OnProcessExit(object sender, EventArgs e)
+ private void OnAppContextUnloading(object sender, EventArgs e)
{
var unloading = Unloading;
if (unloading != null)
@@ -526,4 +490,3 @@ namespace System.Runtime.Loader
}
}
-#endif // FEATURE_HOST_ASSEMBLY_RESOLVER
diff --git a/src/mscorlib/src/System/Runtime/MemoryFailPoint.cs b/src/mscorlib/src/System/Runtime/MemoryFailPoint.cs
index bd87d9027c..84b8ba9e1e 100644
--- a/src/mscorlib/src/System/Runtime/MemoryFailPoint.cs
+++ b/src/mscorlib/src/System/Runtime/MemoryFailPoint.cs
@@ -20,7 +20,6 @@ using System.Runtime.InteropServices;
using System.Threading;
using System.Runtime.CompilerServices;
using System.Runtime.ConstrainedExecution;
-using System.Security.Permissions;
using System.Runtime.Versioning;
using System.Diagnostics;
using System.Diagnostics.Contracts;
@@ -394,7 +393,6 @@ namespace System.Runtime
GC.SuppressFinalize(this);
}
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
private void Dispose(bool disposing)
{
// This is just bookkeeping to ensure multiple threads can really
@@ -472,10 +470,6 @@ namespace System.Runtime
_availPageFile >> 20, _totalFreeAddressSpace >> 20,
_lastKnownFreeAddressSpace >> 20, _reservedMem);
}
-
- public String StackTrace {
- get { return _stackTrace; }
- }
}
#endif
}
diff --git a/src/mscorlib/src/System/Runtime/ProfileOptimization.cs b/src/mscorlib/src/System/Runtime/ProfileOptimization.cs
deleted file mode 100644
index 1e42308ecc..0000000000
--- a/src/mscorlib/src/System/Runtime/ProfileOptimization.cs
+++ /dev/null
@@ -1,50 +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.
-
-////////////////////////////////////////////////////////////////////////////////
-////////////////////////////////////////////////////////////////////////////////
-//
-// This class defines entry point for multi-core JIT API
-//
-//
-namespace System.Runtime {
-
- using System;
-
- using System.Reflection;
-
- using System.Security;
- using System.Security.Permissions;
-
- using System.Runtime;
- using System.Runtime.InteropServices;
- using System.Runtime.Versioning;
- using System.Runtime.CompilerServices;
-
-#if FEATURE_MULTICOREJIT
-
- public static class ProfileOptimization
- {
- [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
- [SuppressUnmanagedCodeSecurity]
- internal static extern void InternalSetProfileRoot(string directoryPath);
-
- [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
- [SuppressUnmanagedCodeSecurity]
- internal static extern void InternalStartProfile(string profile, IntPtr ptrNativeAssemblyLoadContext);
-
- public static void SetProfileRoot(string directoryPath)
- {
- InternalSetProfileRoot(directoryPath);
- }
-
- public static void StartProfile(string profile)
- {
- InternalStartProfile(profile, IntPtr.Zero);
- }
- }
-
-#endif
-}
-
diff --git a/src/mscorlib/src/System/Runtime/Reliability/CriticalFinalizerObject.cs b/src/mscorlib/src/System/Runtime/Reliability/CriticalFinalizerObject.cs
index eb5a186b65..6d6d6f3e77 100644
--- a/src/mscorlib/src/System/Runtime/Reliability/CriticalFinalizerObject.cs
+++ b/src/mscorlib/src/System/Runtime/Reliability/CriticalFinalizerObject.cs
@@ -17,20 +17,16 @@
===========================================================*/
using System;
-using System.Security.Permissions;
using System.Runtime.InteropServices;
namespace System.Runtime.ConstrainedExecution
{
- [System.Runtime.InteropServices.ComVisible(true)]
public abstract class CriticalFinalizerObject
{
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
protected CriticalFinalizerObject()
{
}
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
~CriticalFinalizerObject()
{
}
diff --git a/src/mscorlib/src/System/Runtime/Reliability/PrePrepareMethodAttribute.cs b/src/mscorlib/src/System/Runtime/Reliability/PrePrepareMethodAttribute.cs
index d9774d636b..67c934d034 100644
--- a/src/mscorlib/src/System/Runtime/Reliability/PrePrepareMethodAttribute.cs
+++ b/src/mscorlib/src/System/Runtime/Reliability/PrePrepareMethodAttribute.cs
@@ -23,7 +23,7 @@ namespace System.Runtime.ConstrainedExecution
[AttributeUsage(AttributeTargets.Constructor | AttributeTargets.Method, Inherited = false)]
- public sealed class PrePrepareMethodAttribute : Attribute
+ internal sealed class PrePrepareMethodAttribute : Attribute
{
public PrePrepareMethodAttribute()
{
diff --git a/src/mscorlib/src/System/Runtime/Remoting/ObjectHandle.cs b/src/mscorlib/src/System/Runtime/Remoting/ObjectHandle.cs
index 5555670498..ed3444e15d 100644
--- a/src/mscorlib/src/System/Runtime/Remoting/ObjectHandle.cs
+++ b/src/mscorlib/src/System/Runtime/Remoting/ObjectHandle.cs
@@ -19,10 +19,7 @@ namespace System.Runtime.Remoting
using System;
using System.Runtime.InteropServices;
- [ClassInterface(ClassInterfaceType.AutoDual)]
- [System.Runtime.InteropServices.ComVisible(true)]
- public class ObjectHandle:
- IObjectHandle
+ public class ObjectHandle
{
private Object WrappedObject;
@@ -30,12 +27,12 @@ namespace System.Runtime.Remoting
{
}
- public ObjectHandle(Object o)
+ internal ObjectHandle(Object o)
{
WrappedObject = o;
}
- public Object Unwrap()
+ internal Object Unwrap()
{
return WrappedObject;
}
diff --git a/src/mscorlib/src/System/Runtime/Serialization/FormatterConverter.cs b/src/mscorlib/src/System/Runtime/Serialization/FormatterConverter.cs
index b710ed0b3a..27f7ecf9d2 100644
--- a/src/mscorlib/src/System/Runtime/Serialization/FormatterConverter.cs
+++ b/src/mscorlib/src/System/Runtime/Serialization/FormatterConverter.cs
@@ -17,8 +17,7 @@ namespace System.Runtime.Serialization {
using System.Globalization;
using System.Diagnostics.Contracts;
-[System.Runtime.InteropServices.ComVisible(true)]
- public class FormatterConverter : IFormatterConverter {
+ internal class FormatterConverter : IFormatterConverter {
public FormatterConverter() {
}
diff --git a/src/mscorlib/src/System/Runtime/Serialization/FormatterServices.cs b/src/mscorlib/src/System/Runtime/Serialization/FormatterServices.cs
index 27c3f15136..c3f9eb4452 100644
--- a/src/mscorlib/src/System/Runtime/Serialization/FormatterServices.cs
+++ b/src/mscorlib/src/System/Runtime/Serialization/FormatterServices.cs
@@ -18,10 +18,6 @@ namespace System.Runtime.Serialization {
using System.Collections;
using System.Collections.Generic;
using System.Security;
- using System.Security.Permissions;
-#if FEATURE_SERIALIZATION
- using System.Runtime.Serialization.Formatters;
-#endif
using System.Runtime.Remoting;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
@@ -32,211 +28,7 @@ namespace System.Runtime.Serialization {
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);
- private static bool unsafeTypeForwardersIsEnabled = false;
-
- private static volatile bool unsafeTypeForwardersIsEnabledInitialized = false;
-
- private static Object s_FormatterServicesSyncObject = null;
-
- private static Object formatterServicesSyncObject
- {
- get
- {
- if (s_FormatterServicesSyncObject == null)
- {
- Object o = new Object();
- Interlocked.CompareExchange<Object>(ref s_FormatterServicesSyncObject, o, null);
- }
- return s_FormatterServicesSyncObject;
- }
- }
-
- static FormatterServices()
- {
- // Static initialization touches security critical types, so we need an
- // explicit static constructor to allow us to mark it safe critical.
- }
-
- private static MemberInfo[] GetSerializableMembers(RuntimeType type) {
- // get the list of all fields
- FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
- int countProper = 0;
- for (int i = 0; i < fields.Length; i++) {
- if ((fields[i].Attributes & FieldAttributes.NotSerialized) == FieldAttributes.NotSerialized)
- continue;
- countProper++;
- }
- if (countProper != fields.Length) {
- FieldInfo[] properFields = new FieldInfo[countProper];
- countProper = 0;
- for (int i = 0; i < fields.Length; i++) {
- if ((fields[i].Attributes & FieldAttributes.NotSerialized) == FieldAttributes.NotSerialized)
- continue;
- properFields[countProper] = fields[i];
- countProper++;
- }
- return properFields;
- }
- else
- return fields;
- }
-
- private static bool CheckSerializable(RuntimeType type) {
- if (type.IsSerializable) {
- return true;
- }
- return false;
- }
-
- private static MemberInfo[] InternalGetSerializableMembers(RuntimeType type) {
- List<SerializationFieldInfo> allMembers = null;
- MemberInfo[] typeMembers;
- FieldInfo [] typeFields;
- RuntimeType parentType;
-
- Debug.Assert((object)type != null, "[GetAllSerializableMembers]type!=null");
-
- if (type.IsInterface) {
- return new MemberInfo[0];
- }
-
- if (!(CheckSerializable(type))) {
- throw new SerializationException(Environment.GetResourceString("Serialization_NonSerType", type.FullName, type.Module.Assembly.FullName));
- }
-
- //Get all of the serializable members in the class to be serialized.
- typeMembers = GetSerializableMembers(type);
-
- //If this class doesn't extend directly from object, walk its hierarchy and
- //get all of the private and assembly-access fields (e.g. all fields that aren't
- //virtual) and include them in the list of things to be serialized.
- parentType = (RuntimeType)(type.BaseType);
- if (parentType != null && parentType != (RuntimeType)typeof(Object)) {
- RuntimeType[] parentTypes = null;
- int parentTypeCount = 0;
- bool classNamesUnique = GetParentTypes(parentType, out parentTypes, out parentTypeCount);
- if (parentTypeCount > 0){
- allMembers = new List<SerializationFieldInfo>();
- for (int i = 0; i < parentTypeCount;i++){
- parentType = parentTypes[i];
- if (!CheckSerializable(parentType)) {
- throw new SerializationException(Environment.GetResourceString("Serialization_NonSerType", parentType.FullName, parentType.Module.Assembly.FullName));
- }
-
- typeFields = parentType.GetFields(BindingFlags.NonPublic | BindingFlags.Instance);
- String typeName = classNamesUnique ? parentType.Name : parentType.FullName;
- foreach (FieldInfo field in typeFields) {
- // Family and Assembly fields will be gathered by the type itself.
- if (!field.IsNotSerialized) {
- allMembers.Add(new SerializationFieldInfo((RuntimeFieldInfo)field, typeName));
- }
- }
- }
- //If we actually found any new MemberInfo's, we need to create a new MemberInfo array and
- //copy all of the members which we've found so far into that.
- if (allMembers!=null && allMembers.Count>0) {
- MemberInfo[] membersTemp = new MemberInfo[allMembers.Count + typeMembers.Length];
- Array.Copy(typeMembers, membersTemp, typeMembers.Length);
- ((ICollection)allMembers).CopyTo(membersTemp, typeMembers.Length);
- typeMembers = membersTemp;
- }
- }
- }
- return typeMembers;
- }
-
- private static bool GetParentTypes(RuntimeType parentType, out RuntimeType[] parentTypes, out int parentTypeCount){
- //Check if there are any dup class names. Then we need to include as part of
- //typeName to prefix the Field names in SerializationFieldInfo
- /*out*/ parentTypes = null;
- /*out*/ parentTypeCount = 0;
- bool unique = true;
- RuntimeType objectType = (RuntimeType)typeof(object);
- for (RuntimeType t1 = parentType; t1 != objectType; t1 = (RuntimeType)t1.BaseType)
- {
- if (t1.IsInterface) continue;
- string t1Name = t1.Name;
- for(int i=0;unique && i<parentTypeCount;i++){
- string t2Name = parentTypes[i].Name;
- if (t2Name.Length == t1Name.Length && t2Name[0] == t1Name[0] && t1Name == t2Name){
- unique = false;
- break;
- }
- }
- //expand array if needed
- if (parentTypes == null || parentTypeCount == parentTypes.Length){
- RuntimeType[] tempParentTypes = new RuntimeType[Math.Max(parentTypeCount*2, 12)];
- if (parentTypes != null)
- Array.Copy(parentTypes, 0, tempParentTypes, 0, parentTypeCount);
- parentTypes = tempParentTypes;
- }
- parentTypes[parentTypeCount++] = t1;
- }
- return unique;
- }
-
- // Get all of the Serializable members for a particular class. For all practical intents and
- // purposes, this is the non-transient, non-static members (fields and properties). In order to
- // 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).
- public static MemberInfo[] GetSerializableMembers(Type type) {
- return GetSerializableMembers(type, new StreamingContext(StreamingContextStates.All));
- }
-
- // 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.
- public static MemberInfo[] GetSerializableMembers(Type type, StreamingContext context) {
- MemberInfo[] members;
-
- if ((object)type==null) {
- throw new ArgumentNullException(nameof(type));
- }
- Contract.EndContractBlock();
-
- if (!(type is RuntimeType)) {
- throw new SerializationException(Environment.GetResourceString("Serialization_InvalidType", type.ToString()));
- }
-
- MemberHolder mh = new MemberHolder(type, context);
-
- //If we've already gathered the members for this type, just return them.
- if (m_MemberInfoTable.ContainsKey(mh)) {
- return m_MemberInfoTable[mh];
- }
-
- lock (formatterServicesSyncObject) {
- //If we've already gathered the members for this type, just return them.
- if (m_MemberInfoTable.ContainsKey(mh)) {
- return m_MemberInfoTable[mh];
- }
-
- members = InternalGetSerializableMembers((RuntimeType)type);
-
- m_MemberInfoTable[mh] = members;
- }
-
- return members;
- }
-
- static readonly Type[] advancedTypes = new Type[]{
- typeof(System.DelegateSerializationHolder),
- };
-
- 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))
- throw new SecurityException(Environment.GetResourceString("Serialization_TypeSecurity", advancedTypes[i].FullName, t.FullName));
- }
- }
- }
-#endif // FEATURE_SERIALIZATION
// Gets a new instance of the object. The entire object is initalized to 0 and no
// constructors have been run. **THIS MEANS THAT THE OBJECT MAY NOT BE IN A STATE
@@ -258,188 +50,9 @@ namespace System.Runtime.Serialization {
return nativeGetUninitializedObject((RuntimeType)type);
}
- public static Object GetSafeUninitializedObject(Type type) {
- if ((object)type == null) {
- throw new ArgumentNullException(nameof(type));
- }
- Contract.EndContractBlock();
-
- if (!(type is RuntimeType)) {
- throw new SerializationException(Environment.GetResourceString("Serialization_InvalidType", type.ToString()));
- }
-
- try {
- return nativeGetSafeUninitializedObject((RuntimeType)type);
- }
- catch(SecurityException e) {
- throw new SerializationException(Environment.GetResourceString("Serialization_Security", type.FullName), e);
- }
- }
-
- [MethodImplAttribute(MethodImplOptions.InternalCall)]
- private static extern Object nativeGetSafeUninitializedObject(RuntimeType type);
-
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern Object nativeGetUninitializedObject(RuntimeType type);
-#if FEATURE_SERIALIZATION
- [MethodImplAttribute(MethodImplOptions.InternalCall)]
- private static extern bool GetEnableUnsafeTypeForwarders();
-
- internal static bool UnsafeTypeForwardersIsEnabled()
- {
- if (!unsafeTypeForwardersIsEnabledInitialized)
- {
- unsafeTypeForwardersIsEnabled = GetEnableUnsafeTypeForwarders();
- unsafeTypeForwardersIsEnabledInitialized = true;
- }
-
- return unsafeTypeForwardersIsEnabled;
- }
-#endif
private static Binder s_binder = Type.DefaultBinder;
- internal static void SerializationSetValue(MemberInfo fi, Object target, Object value)
- {
- Contract.Requires(fi != null);
-
- RtFieldInfo rtField = fi as RtFieldInfo;
-
- if (rtField != null)
- {
- rtField.CheckConsistency(target);
- rtField.UnsafeSetValue(target, value, BindingFlags.Default, s_binder, null);
- return;
- }
-
- SerializationFieldInfo serField = fi as SerializationFieldInfo;
- if (serField != null)
- {
- serField.InternalSetValue(target, value, BindingFlags.Default, s_binder, null);
- return;
- }
-
- throw new ArgumentException(Environment.GetResourceString("Argument_InvalidFieldInfo"));
- }
-
- // Fill in the members of obj with the data contained in data.
- // Returns the number of members populated.
- //
- public static Object PopulateObjectMembers(Object obj, MemberInfo[] members, Object[] data) {
- if (obj==null) {
- throw new ArgumentNullException(nameof(obj));
- }
-
- if (members==null) {
- throw new ArgumentNullException(nameof(members));
- }
-
- if (data==null) {
- throw new ArgumentNullException(nameof(data));
- }
-
- if (members.Length!=data.Length) {
- throw new ArgumentException(Environment.GetResourceString("Argument_DataLengthDifferent"));
- }
- Contract.EndContractBlock();
-
- MemberInfo mi;
-
- BCLDebug.Trace("SER", "[PopulateObjectMembers]Enter.");
-
- for (int i=0; i<members.Length; i++) {
- mi = members[i];
-
- if (mi==null) {
- 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.
- //This is either a forward reference or a null. In either case, this may break some of the
- //invariants mantained by the setter, so we'll do nothing with it for right now.
- if (data[i]!=null) {
- if (mi.MemberType==MemberTypes.Field) {
- SerializationSetValue(mi, obj, data[i]);
- } else {
- throw new SerializationException(Environment.GetResourceString("Serialization_UnknownMemberInfo"));
- }
-
- BCLDebug.Trace("SER", "[PopulateObjectMembers]\tType:", obj.GetType(), "\tMember:",
- members[i].Name, " with member type: ", ((FieldInfo)members[i]).FieldType);
- }
- //Console.WriteLine("X");
- }
-
- BCLDebug.Trace("SER", "[PopulateObjectMembers]Leave.");
-
- return obj;
- }
-
- // Extracts the data from obj. members is the array of members which we wish to
- // extract (must be FieldInfos or PropertyInfos). For each supplied member, extract the matching value and
- // return it in a Object[] of the same size.
- //
- public static Object[] GetObjectData(Object obj, MemberInfo[] members) {
-
- if (obj==null) {
- throw new ArgumentNullException(nameof(obj));
- }
-
- if (members==null) {
- throw new ArgumentNullException(nameof(members));
- }
- Contract.EndContractBlock();
-
- int numberOfMembers = members.Length;
-
- Object[] data = new Object[numberOfMembers];
- MemberInfo mi;
-
- for (int i=0; i<numberOfMembers; i++) {
- mi=members[i];
-
- if (mi==null) {
- throw new ArgumentNullException(nameof(members), Environment.GetResourceString("ArgumentNull_NullMember", i));
- }
-
- if (mi.MemberType==MemberTypes.Field) {
- Debug.Assert(mi is RuntimeFieldInfo || mi is SerializationFieldInfo,
- "[FormatterServices.GetObjectData]mi is RuntimeFieldInfo || mi is SerializationFieldInfo.");
-
- RtFieldInfo rfi = mi as RtFieldInfo;
- if (rfi != null) {
- rfi.CheckConsistency(obj);
- data[i] = rfi.UnsafeGetValue(obj);
- } else {
- data[i] = ((SerializationFieldInfo)mi).InternalGetValue(obj);
- }
- } else {
- throw new SerializationException(Environment.GetResourceString("Serialization_UnknownMemberInfo"));
- }
- }
-
- return data;
- }
-
- [System.Runtime.InteropServices.ComVisible(false)]
- public static ISerializationSurrogate GetSurrogateForCyclicalReference(ISerializationSurrogate innerSurrogate)
- {
- if (innerSurrogate == null)
- throw new ArgumentNullException(nameof(innerSurrogate));
- Contract.EndContractBlock();
- return new SurrogateForCyclicalReference(innerSurrogate);
- }
-
- /*=============================GetTypeFromAssembly==============================
- **Action:
- **Returns:
- **Arguments:
- **Exceptions:
- ==============================================================================*/
- public static Type GetTypeFromAssembly(Assembly assem, String name) {
- if (assem==null)
- throw new ArgumentNullException(nameof(assem));
- Contract.EndContractBlock();
- return assem.GetType(name, false, false);
- }
/*============================LoadAssemblyFromString============================
**Action: Loads an assembly from a given string. The current assembly loading story
@@ -460,99 +73,6 @@ namespace System.Runtime.Serialization {
Assembly found = Assembly.Load(assemblyName);
return found;
}
-
- internal static Assembly LoadAssemblyFromStringNoThrow(String assemblyName) {
- try {
- return LoadAssemblyFromString(assemblyName);
- }
- catch (Exception e){
- BCLDebug.Trace("SER", "[LoadAssemblyFromString]", e.ToString());
- }
- return null;
- }
-
- internal static string GetClrAssemblyName(Type type, out bool hasTypeForwardedFrom) {
- if ((object)type == null) {
- throw new ArgumentNullException(nameof(type));
- }
-
- object[] typeAttributes = type.GetCustomAttributes(typeof(TypeForwardedFromAttribute), false);
- if (typeAttributes != null && typeAttributes.Length > 0) {
- hasTypeForwardedFrom = true;
- TypeForwardedFromAttribute typeForwardedFromAttribute = (TypeForwardedFromAttribute)typeAttributes[0];
- return typeForwardedFromAttribute.AssemblyFullName;
- }
- else {
- hasTypeForwardedFrom = false;
- return type.Assembly.FullName;
- }
- }
-
- internal static string GetClrTypeFullName(Type type) {
- if (type.IsArray) {
- return GetClrTypeFullNameForArray(type);
- }
- else {
- return GetClrTypeFullNameForNonArrayTypes(type);
- }
- }
-
- static string GetClrTypeFullNameForArray(Type type) {
- int rank = type.GetArrayRank();
- if (rank == 1)
- {
- return String.Format(CultureInfo.InvariantCulture, "{0}{1}", GetClrTypeFullName(type.GetElementType()), "[]");
- }
- else
- {
- StringBuilder builder = new StringBuilder(GetClrTypeFullName(type.GetElementType())).Append("[");
- for (int commaIndex = 1; commaIndex < rank; commaIndex++)
- {
- builder.Append(",");
- }
- builder.Append("]");
- return builder.ToString();
- }
- }
-
- static string GetClrTypeFullNameForNonArrayTypes(Type type) {
- if (!type.IsGenericType) {
- return type.FullName;
- }
-
- Type[] genericArguments = type.GetGenericArguments();
- StringBuilder builder = new StringBuilder(type.GetGenericTypeDefinition().FullName).Append("[");
- bool hasTypeForwardedFrom;
-
- foreach (Type genericArgument in genericArguments) {
- builder.Append("[").Append(GetClrTypeFullName(genericArgument)).Append(", ");
- builder.Append(GetClrAssemblyName(genericArgument, out hasTypeForwardedFrom)).Append("],");
- }
-
- //remove the last comma and close typename for generic with a close bracket
- return builder.Remove(builder.Length - 1, 1).Append("]").ToString();
- }
- }
-
- internal sealed class SurrogateForCyclicalReference : ISerializationSurrogate
- {
- ISerializationSurrogate innerSurrogate;
- internal SurrogateForCyclicalReference(ISerializationSurrogate innerSurrogate)
- {
- if (innerSurrogate == null)
- throw new ArgumentNullException(nameof(innerSurrogate));
- this.innerSurrogate = innerSurrogate;
- }
-
- public void GetObjectData(Object obj, SerializationInfo info, StreamingContext context)
- {
- innerSurrogate.GetObjectData(obj, info, context);
- }
-
- 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/IDeserializationCallback.cs b/src/mscorlib/src/System/Runtime/Serialization/IDeserializationCallback.cs
index e2497e5d34..2911a4016e 100644
--- a/src/mscorlib/src/System/Runtime/Serialization/IDeserializationCallback.cs
+++ b/src/mscorlib/src/System/Runtime/Serialization/IDeserializationCallback.cs
@@ -16,7 +16,6 @@ namespace System.Runtime.Serialization {
using System;
// Interface does not need to be marked with the serializable attribute
- [System.Runtime.InteropServices.ComVisible(true)]
public interface IDeserializationCallback {
void OnDeserialization(Object sender);
}
diff --git a/src/mscorlib/src/System/Runtime/Serialization/IFormatter.cs b/src/mscorlib/src/System/Runtime/Serialization/IFormatter.cs
deleted file mode 100644
index 8d91d95acf..0000000000
--- a/src/mscorlib/src/System/Runtime/Serialization/IFormatter.cs
+++ /dev/null
@@ -1,41 +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.
-
-/*============================================================
-**
-** Interface: IFormatter;
-**
-**
-** Purpose: The interface for all formatters.
-**
-**
-===========================================================*/
-namespace System.Runtime.Serialization {
- using System.Runtime.Remoting;
- using System;
- using System.IO;
-
-[System.Runtime.InteropServices.ComVisible(true)]
- public interface IFormatter {
- Object Deserialize(Stream serializationStream);
-
- void Serialize(Stream serializationStream, Object graph);
-
-
- ISurrogateSelector SurrogateSelector {
- get;
- set;
- }
-
- SerializationBinder Binder {
- get;
- set;
- }
-
- StreamingContext Context {
- get;
- set;
- }
- }
-}
diff --git a/src/mscorlib/src/System/Runtime/Serialization/IFormatterConverter.cs b/src/mscorlib/src/System/Runtime/Serialization/IFormatterConverter.cs
index 182cc93412..0be0db9acd 100644
--- a/src/mscorlib/src/System/Runtime/Serialization/IFormatterConverter.cs
+++ b/src/mscorlib/src/System/Runtime/Serialization/IFormatterConverter.cs
@@ -17,7 +17,6 @@ namespace System.Runtime.Serialization {
using System;
[CLSCompliant(false)]
-[System.Runtime.InteropServices.ComVisible(true)]
public interface IFormatterConverter {
Object Convert(Object value, Type type);
Object Convert(Object value, TypeCode typeCode);
diff --git a/src/mscorlib/src/System/Runtime/Serialization/IObjectReference.cs b/src/mscorlib/src/System/Runtime/Serialization/IObjectReference.cs
index 42662a10f6..ef5ee6ade0 100644
--- a/src/mscorlib/src/System/Runtime/Serialization/IObjectReference.cs
+++ b/src/mscorlib/src/System/Runtime/Serialization/IObjectReference.cs
@@ -18,9 +18,7 @@
namespace System.Runtime.Serialization {
using System;
- using System.Security.Permissions;
// Interface does not need to be marked with the serializable attribute
-[System.Runtime.InteropServices.ComVisible(true)]
public interface IObjectReference {
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 fc283d41f1..816aa0484b 100644
--- a/src/mscorlib/src/System/Runtime/Serialization/ISerializable.cs
+++ b/src/mscorlib/src/System/Runtime/Serialization/ISerializable.cs
@@ -16,11 +16,9 @@
namespace System.Runtime.Serialization {
using System.Runtime.Remoting;
using System.Runtime.Serialization;
- using System.Security.Permissions;
using System;
using System.Reflection;
- [System.Runtime.InteropServices.ComVisible(true)]
public interface ISerializable {
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
deleted file mode 100644
index 226bbdcc75..0000000000
--- a/src/mscorlib/src/System/Runtime/Serialization/ISerializationSurrogate.cs
+++ /dev/null
@@ -1,34 +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.
-
-/*============================================================
-**
-** Interface: ISurrogate
-**
-**
-** Purpose: The interface implemented by an object which
-** supports surrogates.
-**
-**
-===========================================================*/
-namespace System.Runtime.Serialization {
- using System.Runtime.Remoting;
- using System.Runtime.Serialization;
- using System.Security.Permissions;
- using System;
- using System.Reflection;
-[System.Runtime.InteropServices.ComVisible(true)]
- public interface ISerializationSurrogate {
- // Interface does not need to be marked with the serializable attribute
- // Returns a SerializationInfo completely populated with all of the data needed to reinstantiate the
- // the object at the other end of serialization.
- //
- 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.
- //
- 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
deleted file mode 100644
index 87b7845894..0000000000
--- a/src/mscorlib/src/System/Runtime/Serialization/ISurrogateSelector.cs
+++ /dev/null
@@ -1,34 +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.
-
-/*============================================================
-**
-** Interface: ISurrogateSelector
-**
-**
-** Purpose: A user-supplied class for doing the type to surrogate
-** mapping.
-**
-**
-===========================================================*/
-namespace System.Runtime.Serialization {
-
- using System.Runtime.Remoting;
- using System.Security.Permissions;
- using System;
-[System.Runtime.InteropServices.ComVisible(true)]
- public interface ISurrogateSelector {
- // 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.
- void ChainSelector(ISurrogateSelector selector);
-
- // Returns the appropriate surrogate for the given type in the given context.
- ISerializationSurrogate GetSurrogate(Type type, StreamingContext context, out ISurrogateSelector selector);
-
-
- // Return the next surrogate in the chain. Returns null if no more exist.
- ISurrogateSelector GetNextSelector();
- }
-}
diff --git a/src/mscorlib/src/System/Runtime/Serialization/MemberHolder.cs b/src/mscorlib/src/System/Runtime/Serialization/MemberHolder.cs
deleted file mode 100644
index 1303e40c27..0000000000
--- a/src/mscorlib/src/System/Runtime/Serialization/MemberHolder.cs
+++ /dev/null
@@ -1,51 +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 is a lightweight class designed to hold the members
-** and StreamingContext for a particular class.
-**
-**
-============================================================*/
-namespace System.Runtime.Serialization {
-
- using System.Runtime.Remoting;
- using System;
- using System.Reflection;
- [Serializable]
- internal class MemberHolder {
-// disable csharp compiler warning #0414: field assigned unused value
-#pragma warning disable 0414
- internal MemberInfo[] members = null;
-#pragma warning restore 0414
- internal Type memberType;
- internal StreamingContext context;
-
- internal MemberHolder(Type type, StreamingContext ctx) {
- memberType = type;
- context = ctx;
- }
-
- public override int GetHashCode() {
- return memberType.GetHashCode();
- }
-
- public override bool Equals(Object obj) {
- if (!(obj is MemberHolder)) {
- return false;
- }
-
- MemberHolder temp = (MemberHolder)obj;
-
- if (Object.ReferenceEquals(temp.memberType, memberType) && temp.context.State == context.State) {
- return true;
- }
-
- return false;
- }
- }
-}
diff --git a/src/mscorlib/src/System/Runtime/Serialization/SafeSerializationManager.cs b/src/mscorlib/src/System/Runtime/Serialization/SafeSerializationManager.cs
index 585d367605..260e873bc7 100644
--- a/src/mscorlib/src/System/Runtime/Serialization/SafeSerializationManager.cs
+++ b/src/mscorlib/src/System/Runtime/Serialization/SafeSerializationManager.cs
@@ -1,4 +1,4 @@
-// Licensed to the .NET Foundation under one or more agreements.
+// 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;
@@ -211,10 +211,7 @@ namespace System.Runtime.Serialization
private StreamingContext m_streamingContext;
private List<object> m_serializedStates = new List<object>();
- internal SafeSerializationEventArgs(StreamingContext streamingContext)
- {
- m_streamingContext = streamingContext;
- }
+ internal SafeSerializationEventArgs() {}
public void AddSerializedState(ISafeSerializationData serializedState)
{
@@ -226,11 +223,6 @@ namespace System.Runtime.Serialization
m_serializedStates.Add(serializedState);
}
- internal IList<object> SerializedStates
- {
- get { return m_serializedStates; }
- }
-
public StreamingContext StreamingContext
{
get { return m_streamingContext; }
@@ -245,202 +237,4 @@ namespace System.Runtime.Serialization
// 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/SerializationAttributes.cs b/src/mscorlib/src/System/Runtime/Serialization/SerializationAttributes.cs
index 27c5751cc6..38abffa66e 100644
--- a/src/mscorlib/src/System/Runtime/Serialization/SerializationAttributes.cs
+++ b/src/mscorlib/src/System/Runtime/Serialization/SerializationAttributes.cs
@@ -17,7 +17,6 @@ namespace System.Runtime.Serialization
using System.Reflection;
[AttributeUsage(AttributeTargets.Field, Inherited=false)]
-[System.Runtime.InteropServices.ComVisible(true)]
public sealed class OptionalFieldAttribute : Attribute
{
int versionAdded = 1;
@@ -38,25 +37,21 @@ namespace System.Runtime.Serialization
}
[AttributeUsage(AttributeTargets.Method, Inherited=false)]
-[System.Runtime.InteropServices.ComVisible(true)]
public sealed class OnSerializingAttribute : Attribute
{
}
[AttributeUsage(AttributeTargets.Method, Inherited=false)]
-[System.Runtime.InteropServices.ComVisible(true)]
public sealed class OnSerializedAttribute : Attribute
{
}
[AttributeUsage(AttributeTargets.Method, Inherited=false)]
-[System.Runtime.InteropServices.ComVisible(true)]
public sealed class OnDeserializingAttribute : Attribute
{
}
[AttributeUsage(AttributeTargets.Method, Inherited=false)]
-[System.Runtime.InteropServices.ComVisible(true)]
public sealed class OnDeserializedAttribute : Attribute
{
}
diff --git a/src/mscorlib/src/System/Runtime/Serialization/SerializationBinder.cs b/src/mscorlib/src/System/Runtime/Serialization/SerializationBinder.cs
deleted file mode 100644
index 7457991008..0000000000
--- a/src/mscorlib/src/System/Runtime/Serialization/SerializationBinder.cs
+++ /dev/null
@@ -1,29 +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.
-
-/*============================================================
-**
-** Interface: SerializationBinder
-**
-**
-** Purpose: The base class of serialization binders.
-**
-**
-===========================================================*/
-namespace System.Runtime.Serialization {
- using System;
-
- [Serializable]
-[System.Runtime.InteropServices.ComVisible(true)]
- public abstract class SerializationBinder {
-
- public virtual void BindToName(Type serializedType, out String assemblyName, out String typeName)
- {
- assemblyName = null;
- typeName = null;
- }
-
- public abstract Type BindToType(String assemblyName, String typeName);
- }
-}
diff --git a/src/mscorlib/src/System/Runtime/Serialization/SerializationException.cs b/src/mscorlib/src/System/Runtime/Serialization/SerializationException.cs
index b88ccfd706..e9cb79b7af 100644
--- a/src/mscorlib/src/System/Runtime/Serialization/SerializationException.cs
+++ b/src/mscorlib/src/System/Runtime/Serialization/SerializationException.cs
@@ -17,7 +17,6 @@ namespace System.Runtime.Serialization {
using System;
using System.Runtime.Serialization;
- [System.Runtime.InteropServices.ComVisible(true)]
[Serializable]
public class SerializationException : SystemException {
diff --git a/src/mscorlib/src/System/Runtime/Serialization/SerializationFieldInfo.cs b/src/mscorlib/src/System/Runtime/Serialization/SerializationFieldInfo.cs
deleted file mode 100644
index 82536ce3b4..0000000000
--- a/src/mscorlib/src/System/Runtime/Serialization/SerializationFieldInfo.cs
+++ /dev/null
@@ -1,136 +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: Provides a methods of representing imaginary fields
-** which are unique to serialization. In this case, what we're
-** representing is the private members of parent classes. We
-** aggregate the RuntimeFieldInfo associated with this member
-** and return a managled form of the name. The name that we
-** return is .parentname.fieldname
-**
-**
-============================================================*/
-
-namespace System.Runtime.Serialization {
-
- using System;
- using System.Reflection;
- using System.Globalization;
- using System.Diagnostics;
- using System.Diagnostics.Contracts;
- using System.Threading;
-
- internal sealed class SerializationFieldInfo : FieldInfo {
-
- internal const String FakeNameSeparatorString = "+";
-
- private RuntimeFieldInfo m_field;
- private String m_serializationName;
-
- public override Module Module { get { return m_field.Module; } }
- public override int MetadataToken { get { return m_field.MetadataToken; } }
-
- internal SerializationFieldInfo(RuntimeFieldInfo field, String namePrefix) {
- 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);
- }
-
- //
- // MemberInfo methods
- //
- public override String Name {
- get {
- return m_serializationName;
- }
- }
-
- public override Type DeclaringType {
- get {
- return m_field.DeclaringType;
- }
- }
-
- public override Type ReflectedType {
- get {
- return m_field.ReflectedType;
- }
- }
-
- public override Object[] GetCustomAttributes(bool inherit) {
- return m_field.GetCustomAttributes(inherit);
- }
-
- public override Object[] GetCustomAttributes(Type attributeType, bool inherit) {
- return m_field.GetCustomAttributes(attributeType, inherit);
- }
-
- public override bool IsDefined(Type attributeType, bool inherit) {
- return m_field.IsDefined(attributeType, inherit);
- }
-
- //
- // FieldInfo methods
- //
- public override Type FieldType {
- get {
- return m_field.FieldType;
- }
- }
-
- public override Object GetValue(Object obj) {
- return m_field.GetValue(obj);
- }
-
- internal Object InternalGetValue(Object obj) {
- RtFieldInfo field = m_field as RtFieldInfo;
- if (field != null)
- {
- field.CheckConsistency(obj);
- return field.UnsafeGetValue(obj);
- }
- else
- return m_field.GetValue(obj);
- }
-
- public override void SetValue(Object obj, Object value, BindingFlags invokeAttr, Binder binder, CultureInfo culture) {
- m_field.SetValue(obj, value, invokeAttr, binder, culture);
- }
-
- internal void InternalSetValue(Object obj, Object value, BindingFlags invokeAttr, Binder binder, CultureInfo culture) {
- RtFieldInfo field = m_field as RtFieldInfo;
- if (field != null)
- {
- field.CheckConsistency(obj);
- field.UnsafeSetValue(obj, value, invokeAttr, binder, culture);
- }
- else
- m_field.SetValue(obj, value, invokeAttr, binder, culture);
- }
-
- internal RuntimeFieldInfo FieldInfo {
- get {
- return m_field;
- }
- }
-
- public override RuntimeFieldHandle FieldHandle {
- get {
- return m_field.FieldHandle;
- }
- }
-
- public override FieldAttributes Attributes {
- get {
- return m_field.Attributes;
- }
- }
- }
-}
diff --git a/src/mscorlib/src/System/Runtime/Serialization/SerializationInfo.cs b/src/mscorlib/src/System/Runtime/Serialization/SerializationInfo.cs
index 55909c85fd..45521f2397 100644
--- a/src/mscorlib/src/System/Runtime/Serialization/SerializationInfo.cs
+++ b/src/mscorlib/src/System/Runtime/Serialization/SerializationInfo.cs
@@ -24,7 +24,6 @@ namespace System.Runtime.Serialization
using System.Security;
using System.Runtime.CompilerServices;
- [System.Runtime.InteropServices.ComVisible(true)]
public sealed class SerializationInfo
{
private const int defaultSize = 4;
@@ -146,49 +145,10 @@ namespace System.Runtime.Serialization
}
}
- private static bool Compare(byte[] a, byte[] b)
- {
- // if either or both assemblies do not have public key token, we should demand, hence, returning false will force a demand
- if (a == null || b == null || a.Length == 0 || b.Length == 0 || a.Length != b.Length)
- {
- return false;
- }
- else
- {
- for (int i = 0; i < a.Length; i++)
- {
- if (a[i] != b[i]) return false;
- }
-
- return true;
- }
- }
-
internal static void DemandForUnsafeAssemblyNameAssignments(string originalAssemblyName, string newAssemblyName)
{
}
- internal static bool IsAssemblyNameAssignmentSafe(string originalAssemblyName, string newAssemblyName)
- {
- if (originalAssemblyName == newAssemblyName)
- {
- return true;
- }
-
- AssemblyName originalAssembly = new AssemblyName(originalAssemblyName);
- AssemblyName newAssembly = new AssemblyName(newAssemblyName);
-
- // mscorlib will get loaded by the runtime regardless of its string casing or its public key token,
- // so setting the assembly name to mscorlib must always be protected by a demand
- if (string.Equals(newAssembly.Name, s_mscorlibAssemblySimpleName, StringComparison.OrdinalIgnoreCase) ||
- string.Equals(newAssembly.Name, s_mscorlibFileName, StringComparison.OrdinalIgnoreCase))
- {
- return false;
- }
-
- return Compare(originalAssembly.GetPublicKeyToken(), newAssembly.GetPublicKeyToken());
- }
-
public int MemberCount
{
get
@@ -467,7 +427,6 @@ namespace System.Runtime.Serialization
return m_data[index];
}
- [System.Runtime.InteropServices.ComVisible(true)]
private Object GetElementNoThrow(String name, out Type foundType)
{
int index = FindElement(name);
@@ -518,7 +477,6 @@ namespace System.Runtime.Serialization
return m_converter.Convert(value, type);
}
- [System.Runtime.InteropServices.ComVisible(true)]
internal Object GetValueNoThrow(String name, Type type)
{
Type foundType;
@@ -741,22 +699,5 @@ namespace System.Runtime.Serialization
return m_converter.ToString(value);
}
- internal string[] MemberNames
- {
- get
- {
- return m_members;
- }
-
- }
-
- internal object[] MemberValues
- {
- get
- {
- return m_data;
- }
- }
-
}
}
diff --git a/src/mscorlib/src/System/Runtime/Serialization/SerializationInfoEnumerator.cs b/src/mscorlib/src/System/Runtime/Serialization/SerializationInfoEnumerator.cs
index 32c65492e1..0858dfc19f 100644
--- a/src/mscorlib/src/System/Runtime/Serialization/SerializationInfoEnumerator.cs
+++ b/src/mscorlib/src/System/Runtime/Serialization/SerializationInfoEnumerator.cs
@@ -21,7 +21,6 @@ namespace System.Runtime.Serialization {
//
// The tuple returned by SerializationInfoEnumerator.Current.
//
-[System.Runtime.InteropServices.ComVisible(true)]
public struct SerializationEntry {
private Type m_type;
private Object m_value;
@@ -57,7 +56,6 @@ namespace System.Runtime.Serialization {
// This does not snapshot the values, it just keeps pointers to the
// member variables of the SerializationInfo that created it.
//
-[System.Runtime.InteropServices.ComVisible(true)]
public sealed class SerializationInfoEnumerator : IEnumerator {
String[] m_members;
Object[] m_data;
diff --git a/src/mscorlib/src/System/Runtime/Serialization/StreamingContext.cs b/src/mscorlib/src/System/Runtime/Serialization/StreamingContext.cs
index ef4a096a51..c01a3edc4f 100644
--- a/src/mscorlib/src/System/Runtime/Serialization/StreamingContext.cs
+++ b/src/mscorlib/src/System/Runtime/Serialization/StreamingContext.cs
@@ -16,7 +16,6 @@ namespace System.Runtime.Serialization {
using System.Runtime.Remoting;
using System;
[Serializable]
-[System.Runtime.InteropServices.ComVisible(true)]
public struct StreamingContext {
internal Object m_additionalContext;
internal StreamingContextStates m_state;
@@ -59,7 +58,6 @@ namespace System.Runtime.Serialization {
// **********************************************************
[Serializable]
[Flags]
-[System.Runtime.InteropServices.ComVisible(true)]
public enum StreamingContextStates {
CrossProcess=0x01,
CrossMachine=0x02,
diff --git a/src/mscorlib/src/System/Runtime/Versioning/CompatibilitySwitch.cs b/src/mscorlib/src/System/Runtime/Versioning/CompatibilitySwitch.cs
index 6bf8f8cf45..3410f020be 100644
--- a/src/mscorlib/src/System/Runtime/Versioning/CompatibilitySwitch.cs
+++ b/src/mscorlib/src/System/Runtime/Versioning/CompatibilitySwitch.cs
@@ -7,7 +7,7 @@ using System.Runtime.CompilerServices;
namespace System.Runtime.Versioning
{
- public static class CompatibilitySwitch
+ internal static class CompatibilitySwitch
{
/* This class contains 3 sets of api:
* 1. internal apis : These apis are supposed to be used by mscorlib.dll and other assemblies which use the <runtime> section in config
@@ -19,38 +19,14 @@ namespace System.Runtime.Versioning
* 3. specialized apis: These apis are defined in order to retrieve a specific value defined in CLR Config. That value can have specific look-up rules
* for the order and location of the config sources used.
*
- * 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
+ * These apis are for internal use only for FX assemblies. It has not been decided if they can be used by OOB components due to EULA restrictions
*/
- public static bool IsEnabled(string compatibilitySwitchName)
- {
- return IsEnabledInternalCall(compatibilitySwitchName, true);
- }
-
- public static string GetValue(string compatibilitySwitchName)
- {
- // This is used by AppContext.TryGetSwitch to check switch overrides in the Windows Quirk DB
- // If this method is updated to check other locations than the DB, please ensure compat with
- // the AppContext class.
- return GetValueInternalCall(compatibilitySwitchName, true);
- }
-
- internal static bool IsEnabledInternal(string compatibilitySwitchName)
- {
- return IsEnabledInternalCall(compatibilitySwitchName, false);
- }
-
internal static string GetValueInternal(string compatibilitySwitchName)
{
return GetValueInternalCall(compatibilitySwitchName, false);
}
[MethodImpl(MethodImplOptions.InternalCall)]
- internal static extern string GetAppContextOverridesInternalCall();
-
- [MethodImpl(MethodImplOptions.InternalCall)]
- private static extern bool IsEnabledInternalCall(string compatibilitySwitchName, bool onlyDB);
-
- [MethodImpl(MethodImplOptions.InternalCall)]
private static extern string GetValueInternalCall(string compatibilitySwitchName, bool onlyDB);
}
}
diff --git a/src/mscorlib/src/System/Runtime/Versioning/TargetFrameworkId.cs b/src/mscorlib/src/System/Runtime/Versioning/TargetFrameworkId.cs
deleted file mode 100644
index 0a5e668a92..0000000000
--- a/src/mscorlib/src/System/Runtime/Versioning/TargetFrameworkId.cs
+++ /dev/null
@@ -1,28 +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: Describe the target framework of the application or AppDomain.
-**
-===========================================================*/
-using System;
-using System.Runtime.CompilerServices;
-
-namespace System.Runtime.Versioning
-{
- // What type of .NET Framework was this application compiled against?
- [FriendAccessAllowed]
- internal enum TargetFrameworkId
- {
- NotYetChecked = 0,
- Unrecognized = 1, // Unknown type, such as a new SKU (like watches or cars)
- Unspecified = 2, // The TargetFrameworkAttribute was created in v4.0. And apps compiled outside VS will not have this attribute.
- NetFramework = 3, // Desktop - Client or Server or ServerCore.
- Portable = 4, // Portable Library v1 Note: We do not expect people to build executables against portable libraries!
- NetCore = 5, // .NET Core = Windows 8 Immersive and Portable Library v2+
- Silverlight = 6, // Silverlight but not the Phone
- Phone = 7, // Windows Phone 7 or higher
- }
-}
diff --git a/src/mscorlib/src/System/RuntimeArgumentHandle.cs b/src/mscorlib/src/System/RuntimeArgumentHandle.cs
index d1bc86b49a..3e13614930 100644
--- a/src/mscorlib/src/System/RuntimeArgumentHandle.cs
+++ b/src/mscorlib/src/System/RuntimeArgumentHandle.cs
@@ -13,7 +13,6 @@ namespace System {
// This corresponds to EE VARARGS cookie.
// Cannot be serialized
- [System.Runtime.InteropServices.ComVisible(true)]
public struct RuntimeArgumentHandle
{
private IntPtr m_ptr;
diff --git a/src/mscorlib/src/System/RuntimeHandles.cs b/src/mscorlib/src/System/RuntimeHandles.cs
index 127da1e0da..39c85ad4e2 100644
--- a/src/mscorlib/src/System/RuntimeHandles.cs
+++ b/src/mscorlib/src/System/RuntimeHandles.cs
@@ -19,13 +19,11 @@ namespace System
using System.Text;
using System.Globalization;
using System.Security;
- using System.Security.Permissions;
using Microsoft.Win32.SafeHandles;
using System.Diagnostics.Contracts;
using StackCrawlMark = System.Threading.StackCrawlMark;
[Serializable]
- [System.Runtime.InteropServices.ComVisible(true)]
public unsafe struct RuntimeTypeHandle : ISerializable
{
// Returns handle for interop with EE. The handle is guaranteed to be non-null.
@@ -89,14 +87,6 @@ namespace System
public static bool operator !=(RuntimeTypeHandle left, object right) { return !left.Equals(right); }
public static bool operator !=(object left, RuntimeTypeHandle right) { return !right.Equals(left); }
-
- internal static RuntimeTypeHandle EmptyHandle
- {
- get
- {
- return new RuntimeTypeHandle(null);
- }
- }
// This is the RuntimeType for the type
@@ -107,7 +97,6 @@ namespace System
return m_type != null ? m_type.GetHashCode() : 0;
}
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
public override bool Equals(object obj)
{
if(!(obj is RuntimeTypeHandle))
@@ -117,7 +106,6 @@ namespace System
return handle.m_type == m_type;
}
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
public bool Equals(RuntimeTypeHandle handle)
{
return handle.m_type == m_type;
@@ -139,11 +127,6 @@ namespace System
m_type = type;
}
- internal bool IsNullHandle()
- {
- return m_type == null;
- }
-
internal static bool IsPrimitive(RuntimeType type)
{
CorElementType corElemType = GetCorElementType(type);
@@ -243,11 +226,9 @@ namespace System
internal extern static RuntimeAssembly GetAssembly(RuntimeType type);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
internal extern static RuntimeModule GetModule(RuntimeType type);
[CLSCompliant(false)]
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
public ModuleHandle GetModuleHandle()
{
return new ModuleHandle(RuntimeTypeHandle.GetModule(m_type));
@@ -376,9 +357,6 @@ namespace System
internal extern static bool IsComObject(RuntimeType type, bool isGenericCOM);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
- internal extern static bool IsContextful(RuntimeType type);
-
- [MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern static bool IsInterface(RuntimeType type);
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
@@ -423,9 +401,6 @@ namespace System
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
- internal extern static bool HasProxyAttribute(RuntimeType type);
-
- [MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern static bool IsValueType(RuntimeType type);
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
@@ -503,11 +478,6 @@ namespace System
return type;
}
- internal static Type GetTypeByName(string name, ref StackCrawlMark stackMark)
- {
- return GetTypeByName(name, false, false, false, ref stackMark, false);
- }
-
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private extern static void GetTypeByNameUsingCARules(string name, RuntimeModule scope, ObjectHandleOnStack type);
@@ -612,11 +582,6 @@ namespace System
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern static bool HasInstantiation(RuntimeType type);
- internal bool HasInstantiation()
- {
- return HasInstantiation(GetTypeChecked());
- }
-
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private extern static void GetGenericTypeDefinition(RuntimeTypeHandle type, ObjectHandleOnStack retType);
@@ -637,11 +602,6 @@ namespace System
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern static bool IsGenericVariable(RuntimeType type);
- internal bool IsGenericVariable()
- {
- return IsGenericVariable(GetTypeChecked());
- }
-
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private extern static int GetGenericVariableIndex(RuntimeType type);
@@ -806,7 +766,6 @@ namespace System
}
[Serializable]
- [System.Runtime.InteropServices.ComVisible(true)]
public unsafe struct RuntimeMethodHandle : ISerializable
{
// Returns handle for interop with EE. The handle is guaranteed to be non-null.
@@ -817,11 +776,6 @@ namespace System
return method;
}
- internal static RuntimeMethodHandle EmptyHandle
- {
- get { return new RuntimeMethodHandle(); }
- }
-
private IRuntimeMethodInfo m_value;
internal RuntimeMethodHandle(IRuntimeMethodInfo method)
@@ -883,7 +837,6 @@ namespace System
return ValueType.GetHashCodeOfPtr(Value);
}
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
public override bool Equals(object obj)
{
if (!(obj is RuntimeMethodHandle))
@@ -904,7 +857,6 @@ namespace System
return !left.Equals(right);
}
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
public bool Equals(RuntimeMethodHandle handle)
{
return handle.Value == Value;
@@ -1032,52 +984,6 @@ namespace System
#endregion
- [DebuggerStepThroughAttribute]
- [Diagnostics.DebuggerHidden]
- [MethodImplAttribute(MethodImplOptions.InternalCall)]
- internal extern static void SerializationInvoke(IRuntimeMethodInfo method,
- Object target, SerializationInfo info, ref StreamingContext context);
-
- // This returns true if the token is SecurityTransparent:
- // just the token - does not consider including module/type etc.
- [MethodImplAttribute(MethodImplOptions.InternalCall)]
- internal static extern bool _IsTokenSecurityTransparent(RuntimeModule module, int metaDataToken);
-
- internal static bool IsTokenSecurityTransparent(Module module, int metaDataToken)
- {
- return _IsTokenSecurityTransparent(module.ModuleHandle.GetRuntimeModule(), metaDataToken);
- }
-
- [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
- [SuppressUnmanagedCodeSecurity]
- [return: MarshalAs(UnmanagedType.Bool)]
- private static extern bool _IsSecurityCritical(IRuntimeMethodInfo method);
-
- internal static bool IsSecurityCritical(IRuntimeMethodInfo method)
- {
- return _IsSecurityCritical(method);
- }
-
- [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
- [SuppressUnmanagedCodeSecurity]
- [return: MarshalAs(UnmanagedType.Bool)]
- private static extern bool _IsSecuritySafeCritical(IRuntimeMethodInfo method);
-
- internal static bool IsSecuritySafeCritical(IRuntimeMethodInfo method)
- {
- return _IsSecuritySafeCritical(method);
- }
-
- [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
- [SuppressUnmanagedCodeSecurity]
- [return: MarshalAs(UnmanagedType.Bool)]
- private static extern bool _IsSecurityTransparent(IRuntimeMethodInfo method);
-
- internal static bool IsSecurityTransparent(IRuntimeMethodInfo method)
- {
- return _IsSecurityTransparent(method);
- }
-
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private extern static void GetMethodInstantiation(RuntimeMethodHandleInternal method, ObjectHandleOnStack types, bool fAsRuntimeTypeArray);
@@ -1170,17 +1076,6 @@ namespace System
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern static Resolver GetResolver(RuntimeMethodHandleInternal method);
- [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
- [SuppressUnmanagedCodeSecurity]
- private static extern void GetCallerType(StackCrawlMarkHandle stackMark, ObjectHandleOnStack retType);
-
- internal static RuntimeType GetCallerType(ref StackCrawlMark stackMark)
- {
- RuntimeType type = null;
- GetCallerType(JitHelpers.GetStackCrawlMarkHandle(ref stackMark), JitHelpers.GetObjectHandleOnStack(ref type));
- return type;
- }
-
[MethodImpl(MethodImplOptions.InternalCall)]
internal extern static MethodBody GetMethodBody(IRuntimeMethodInfo method, RuntimeType declaringType);
@@ -1202,13 +1097,6 @@ namespace System
// When in doubt, do not use.
internal struct RuntimeFieldHandleInternal
{
- internal static RuntimeFieldHandleInternal EmptyHandle
- {
- get
- {
- return new RuntimeFieldHandleInternal();
- }
- }
internal bool IsNullHandle()
{
@@ -1242,11 +1130,6 @@ namespace System
[StructLayout(LayoutKind.Sequential)]
internal class RuntimeFieldInfoStub : IRuntimeFieldInfo
{
- public RuntimeFieldInfoStub(IntPtr methodHandleValue, object keepalive)
- {
- m_keepalive = keepalive;
- m_fieldHandle = new RuntimeFieldHandleInternal(methodHandleValue);
- }
// These unused variables are used to ensure that this class has the same layout as RuntimeFieldInfo
#pragma warning disable 169
@@ -1268,7 +1151,6 @@ namespace System
}
[Serializable]
- [System.Runtime.InteropServices.ComVisible(true)]
public unsafe struct RuntimeFieldHandle : ISerializable
{
// Returns handle for interop with EE. The handle is guaranteed to be non-null.
@@ -1311,7 +1193,6 @@ namespace System
return ValueType.GetHashCodeOfPtr(Value);
}
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
public override bool Equals(object obj)
{
if (!(obj is RuntimeFieldHandle))
@@ -1322,7 +1203,6 @@ namespace System
return handle.Value == Value;
}
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
public unsafe bool Equals(RuntimeFieldHandle handle)
{
return handle.Value == Value;
@@ -1367,7 +1247,7 @@ namespace System
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern Object GetValue(RtFieldInfo field, Object instance, RuntimeType fieldType, RuntimeType declaringType, ref bool domainInitialized);
-
+
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern Object GetValueDirect(RtFieldInfo field, RuntimeType fieldType, void *pTypedRef, RuntimeType contextType);
@@ -1450,7 +1330,6 @@ namespace System
}
}
-[System.Runtime.InteropServices.ComVisible(true)]
public unsafe struct ModuleHandle
{
// Returns handle for interop with EE. The handle is guaranteed to be non-null.
@@ -1480,18 +1359,12 @@ namespace System
{
return m_ptr;
}
-
- internal bool IsNullHandle()
- {
- return m_ptr == null;
- }
public override int GetHashCode()
{
return m_ptr != null ? m_ptr.GetHashCode() : 0;
}
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
public override bool Equals(object obj)
{
if (!(obj is ModuleHandle))
@@ -1502,7 +1375,6 @@ namespace System
return handle.m_ptr == m_ptr;
}
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
public unsafe bool Equals(ModuleHandle handle)
{
return handle.m_ptr == m_ptr;
@@ -1546,7 +1418,7 @@ namespace System
{
ValidateModulePointer(module);
if (!ModuleHandle.GetMetadataImport(module).IsValidToken(typeToken))
- throw new ArgumentOutOfRangeException("metadataToken",
+ throw new ArgumentOutOfRangeException(nameof(typeToken),
Environment.GetResourceString("Argument_InvalidToken", typeToken, new ModuleHandle(module)));
int typeInstCount, methodInstCount;
@@ -1600,7 +1472,7 @@ namespace System
{
ValidateModulePointer(module);
if (!ModuleHandle.GetMetadataImport(module.GetNativeHandle()).IsValidToken(methodToken))
- throw new ArgumentOutOfRangeException("metadataToken",
+ throw new ArgumentOutOfRangeException(nameof(methodToken),
Environment.GetResourceString("Argument_InvalidToken", methodToken, new ModuleHandle(module)));
fixed (IntPtr* typeInstArgs = typeInstantiationContext, methodInstArgs = methodInstantiationContext)
@@ -1628,7 +1500,7 @@ namespace System
{
ValidateModulePointer(module);
if (!ModuleHandle.GetMetadataImport(module.GetNativeHandle()).IsValidToken(fieldToken))
- throw new ArgumentOutOfRangeException("metadataToken",
+ throw new ArgumentOutOfRangeException(nameof(fieldToken),
Environment.GetResourceString("Argument_InvalidToken", fieldToken, new ModuleHandle(module)));
// defensive copy to be sure array is not mutated from the outside during processing
@@ -1667,17 +1539,6 @@ namespace System
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
- private extern static void GetAssembly(RuntimeModule handle, ObjectHandleOnStack retAssembly);
-
- internal static RuntimeAssembly GetAssembly(RuntimeModule module)
- {
- RuntimeAssembly retAssembly = null;
- GetAssembly(module.GetNativeHandle(), JitHelpers.GetObjectHandleOnStack(ref retAssembly));
- return retAssembly;
- }
-
- [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
- [SuppressUnmanagedCodeSecurity]
internal extern static void GetModuleType(RuntimeModule handle, ObjectHandleOnStack type);
internal static RuntimeType GetModuleType(RuntimeModule module)
@@ -1836,9 +1697,6 @@ namespace System
internal abstract byte[] ResolveSignature(int token, int fromMethod);
//
internal abstract MethodInfo GetDynamicMethod();
-#if FEATURE_COMPRESSEDSTACK
- internal abstract CompressedStack GetSecurityContext();
-#endif
}
}
diff --git a/src/mscorlib/src/System/SByte.cs b/src/mscorlib/src/System/SByte.cs
index da6ac5c88f..e738dfc546 100644
--- a/src/mscorlib/src/System/SByte.cs
+++ b/src/mscorlib/src/System/SByte.cs
@@ -19,7 +19,6 @@ namespace System {
// A place holder class for signed bytes.
[Serializable]
[CLSCompliant(false), System.Runtime.InteropServices.StructLayout(LayoutKind.Sequential)]
-[System.Runtime.InteropServices.ComVisible(true)]
public struct SByte : IComparable, IFormattable, IConvertible
, IComparable<SByte>, IEquatable<SByte>
{
diff --git a/src/mscorlib/src/System/Security/AccessControl/Enums.cs b/src/mscorlib/src/System/Security/AccessControl/Enums.cs
deleted file mode 100644
index 20f5c5f91a..0000000000
--- a/src/mscorlib/src/System/Security/AccessControl/Enums.cs
+++ /dev/null
@@ -1,75 +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.Security.AccessControl
-{
- [Flags]
- public enum InheritanceFlags
- {
- None = 0x00,
- ContainerInherit = 0x01,
- ObjectInherit = 0x02,
- }
-
- [Flags]
- public enum PropagationFlags
- {
- None = 0x00,
- NoPropagateInherit = 0x01,
- InheritOnly = 0x02,
- }
-
- [Flags]
- public enum AuditFlags
- {
- None = 0x00,
- Success = 0x01,
- Failure = 0x02,
- }
-
- [Flags]
- public enum SecurityInfos
- {
- Owner = 0x00000001,
- Group = 0x00000002,
- DiscretionaryAcl = 0x00000004,
- SystemAcl = 0x00000008,
-
- }
-
-
- public enum ResourceType
- {
- Unknown = 0x00,
- FileObject = 0x01,
- Service = 0x02,
- Printer = 0x03,
- RegistryKey = 0x04,
- LMShare = 0x05,
- KernelObject = 0x06,
- WindowObject = 0x07,
- DSObject = 0x08,
- DSObjectAll = 0x09,
- ProviderDefined = 0x0A,
- WmiGuidObject = 0x0B,
- RegistryWow6432Key = 0x0C,
- }
-
- [Flags]
- public enum AccessControlSections {
- None = 0,
- Audit = 0x1,
- Access = 0x2,
- Owner = 0x4,
- Group = 0x8,
- All = 0xF
- }
-
- [Flags]
- public enum AccessControlActions {
- None = 0
- }
-}
diff --git a/src/mscorlib/src/System/Security/Attributes.cs b/src/mscorlib/src/System/Security/Attributes.cs
index e4ebc53053..f67a9f0ad1 100644
--- a/src/mscorlib/src/System/Security/Attributes.cs
+++ b/src/mscorlib/src/System/Security/Attributes.cs
@@ -19,7 +19,6 @@ namespace System.Security
// Indicates that the target P/Invoke method(s) should skip the per-call
// security checked for unmanaged code permission.
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = true, Inherited = false )]
- [System.Runtime.InteropServices.ComVisible(true)]
sealed public class SuppressUnmanagedCodeSecurityAttribute : System.Attribute
{
}
@@ -27,7 +26,6 @@ namespace System.Security
// UnverifiableCodeAttribute:
// Indicates that the target module contains unverifiable code.
[AttributeUsage(AttributeTargets.Module, AllowMultiple = true, Inherited = false )]
-[System.Runtime.InteropServices.ComVisible(true)]
sealed public class UnverifiableCodeAttribute : System.Attribute
{
}
@@ -38,7 +36,6 @@ namespace System.Security
// For v.1, this is valid only on Assemblies, but could be expanded to
// include Module, Method, class
[AttributeUsage(AttributeTargets.Assembly, AllowMultiple = false, Inherited = false )]
- [System.Runtime.InteropServices.ComVisible(true)]
sealed public class AllowPartiallyTrustedCallersAttribute : System.Attribute
{
private PartialTrustVisibilityLevel _visibilityLevel;
diff --git a/src/mscorlib/src/System/Security/BuiltInPermissionSets.cs b/src/mscorlib/src/System/Security/BuiltInPermissionSets.cs
deleted file mode 100644
index 48539574af..0000000000
--- a/src/mscorlib/src/System/Security/BuiltInPermissionSets.cs
+++ /dev/null
@@ -1,255 +0,0 @@
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-// See the LICENSE file in the project root for more information.
-
-//
-//
-
-using System;
-using System.Diagnostics;
-using System.Diagnostics.Contracts;
-using System.Security.Permissions;
-using Microsoft.Win32;
-
-namespace System.Security
-{
- internal static class BuiltInPermissionSets
- {
- //
- // Raw PermissionSet XML - the built in permission sets are expressed in XML form since they contain
- // permissions from assemblies other than mscorlib.
- //
-
- private static readonly string s_everythingXml =
- @"<PermissionSet class = ""System.Security.NamedPermissionSet""
- version = ""1""
- Name = ""Everything""
- Description = """ + Environment.GetResourceString("Policy_PS_Everything") + @"""
- <IPermission class = ""System.Data.OleDb.OleDbPermission, " + AssemblyRef.SystemData + @"""
- version = ""1""
- Unrestricted = ""true"" />
- <IPermission class = ""System.Data.SqlClient.SqlClientPermission, " + AssemblyRef.SystemData + @"""
- version = ""1""
- Unrestricted = ""true"" />
- <IPermission class = ""System.Diagnostics.PerformanceCounterPermission, " + AssemblyRef.System + @"""
- version = ""1""
- Unrestricted = ""true"" />
- <IPermission class = ""System.Net.DnsPermission, " + AssemblyRef.System + @"""
- version = ""1""
- Unrestricted = ""true"" />
- <IPermission class = ""System.Net.SocketPermission, " + AssemblyRef.System + @"""
- version = ""1""
- Unrestricted = ""true"" />
- <IPermission class = ""System.Net.WebPermission, " + AssemblyRef.System + @"""
- version = ""1""
- Unrestricted = ""true"" />
- <IPermission class = ""System.Security.Permissions.DataProtectionPermission, " + AssemblyRef.SystemSecurity + @"""
- version = ""1""
- Unrestricted = ""true"" />
- <IPermission class = ""System.Security.Permissions.EnvironmentPermission, " + AssemblyRef.Mscorlib + @"""
- version = ""1""
- Unrestricted = ""true"" />
- <IPermission class = ""System.Diagnostics.EventLogPermission, " + AssemblyRef.System + @"""
- version = ""1""
- Unrestricted = ""true"" />
- <IPermission class = ""System.Security.Permissions.FileDialogPermission, " + AssemblyRef.Mscorlib + @"""
- version = ""1""
- Unrestricted = ""true"" />
- <IPermission class = ""System.Security.Permissions.FileIOPermission, " + AssemblyRef.Mscorlib + @"""
- version = ""1""
- Unrestricted = ""true"" />
- <IPermission class = ""System.Security.Permissions.IsolatedStorageFilePermission, " + AssemblyRef.Mscorlib + @"""
- version = ""1""
- Unrestricted = ""true"" />
- <IPermission class = ""System.Security.Permissions.KeyContainerPermission, " + AssemblyRef.Mscorlib + @"""
- version = ""1""
- Unrestricted = ""true"" />
- <IPermission class = ""System.Drawing.Printing.PrintingPermission, " + AssemblyRef.SystemDrawing + @"""
- version = ""1""
- Unrestricted = ""true"" />
- <IPermission class = ""System.Security.Permissions.ReflectionPermission, " + AssemblyRef.Mscorlib + @"""
- version = ""1""
- Unrestricted = ""true"" />
- <IPermission class = ""System.Security.Permissions.RegistryPermission, " + AssemblyRef.Mscorlib + @"""
- version = ""1""
- Unrestricted = ""true"" />
- <IPermission class = ""System.Security.Permissions.SecurityPermission, " + AssemblyRef.Mscorlib + @"""
- version = ""1""
- Flags = ""Assertion, UnmanagedCode, Execution, ControlThread, ControlEvidence, ControlPolicy, ControlAppDomain, SerializationFormatter, ControlDomainPolicy, ControlPrincipal, RemotingConfiguration, Infrastructure, BindingRedirects"" />
- <IPermission class = ""System.Security.Permissions.UIPermission, " + AssemblyRef.Mscorlib + @"""
- version = ""1""
- Unrestricted = ""true"" />
- <IPermission class = ""System.Security.Permissions.StorePermission, " + AssemblyRef.System + @"""
- version = ""1""
- Unrestricted = ""true"" />
- <IPermission class = ""System.Security.Permissions.TypeDescriptorPermission, " + AssemblyRef.System + @"""
- version = ""1""
- Unrestricted = ""true"" />
- </PermissionSet>";
-
- private static readonly string s_executionXml =
- @"<PermissionSet class = ""System.Security.NamedPermissionSet""
- version = ""1""
- Name = ""Execution""
- Description = """ + Environment.GetResourceString("Policy_PS_Execution") + @""">
- <IPermission class = ""System.Security.Permissions.SecurityPermission, " + AssemblyRef.Mscorlib + @"""
- version = ""1""
- Flags = ""Execution"" />
- </PermissionSet>";
-
- private static readonly string s_fullTrustXml =
- @"<PermissionSet class = ""System.Security.NamedPermissionSet""
- version = ""1""
- Unrestricted = ""true""
- Name = ""FullTrust""
- Description = """ + Environment.GetResourceString("Policy_PS_FullTrust") + @""" />";
-
- private static readonly string s_internetXml =
- @"<PermissionSet class = ""System.Security.NamedPermissionSet""
- version = ""1""
- Name = ""Internet""
- Description = """ + Environment.GetResourceString("Policy_PS_Internet") + @""">
- <IPermission class = ""System.Drawing.Printing.PrintingPermission, " + AssemblyRef.SystemDrawing + @"""
- version = ""1""
- Level = ""SafePrinting"" />
- <IPermission class = ""System.Security.Permissions.FileDialogPermission, " + AssemblyRef.Mscorlib + @"""
- version = ""1""
- Access = ""Open"" />
- <IPermission class = ""System.Security.Permissions.IsolatedStorageFilePermission, " + AssemblyRef.Mscorlib + @"""
- version = ""1""
- UserQuota = ""1024000""
- Allowed = ""ApplicationIsolationByUser"" />
- <IPermission class = ""System.Security.Permissions.SecurityPermission, " + AssemblyRef.Mscorlib + @"""
- version = ""1""
- Flags = ""Execution"" />
- <IPermission class = ""System.Security.Permissions.UIPermission, " + AssemblyRef.Mscorlib + @"""
- version = ""1""
- Window = ""SafeTopLevelWindows""
- Clipboard = ""OwnClipboard"" />
- </PermissionSet>";
-
- private static readonly string s_localIntranetXml =
- @"<PermissionSet class = ""System.Security.NamedPermissionSet""
- version = ""1""
- Name = ""LocalIntranet""
- Description = """ + Environment.GetResourceString("Policy_PS_LocalIntranet") + @""" >
- <IPermission class = ""System.Drawing.Printing.PrintingPermission, " + AssemblyRef.SystemDrawing + @"""
- version = ""1""
- Level = ""DefaultPrinting"" />
- <IPermission class = ""System.Net.DnsPermission, " + AssemblyRef.System + @"""
- version = ""1""
- Unrestricted = ""true"" />
- <IPermission class = ""System.Security.Permissions.EnvironmentPermission, " + AssemblyRef.Mscorlib + @"""
- version = ""1""
- Read = ""USERNAME"" />
- <IPermission class = ""System.Security.Permissions.FileDialogPermission, " + AssemblyRef.Mscorlib + @"""
- version = ""1""
- Unrestricted = ""true"" />
- <IPermission class = ""System.Security.Permissions.IsolatedStorageFilePermission, " + AssemblyRef.Mscorlib + @"""
- version = ""1""
- Allowed = ""AssemblyIsolationByUser""
- UserQuota = ""9223372036854775807""
- Expiry = ""9223372036854775807""
- Permanent = ""true"" />
- <IPermission class = ""System.Security.Permissions.ReflectionPermission, " + AssemblyRef.Mscorlib + @"""
- version = ""1""
- Flags = ""ReflectionEmit, RestrictedMemberAccess"" />
- <IPermission class = ""System.Security.Permissions.SecurityPermission, " + AssemblyRef.Mscorlib + @"""
- version = ""1""
- Flags = ""Execution, Assertion, BindingRedirects "" />
- <IPermission class = ""System.Security.Permissions.TypeDescriptorPermission, " + AssemblyRef.System + @"""
- version = ""1""
- Flags = ""RestrictedRegistrationAccess"" />
- <IPermission class = ""System.Security.Permissions.UIPermission, " + AssemblyRef.Mscorlib + @"""
- version = ""1""
- Unrestricted = ""true"" />
- </PermissionSet>";
-
- private static readonly string s_nothingXml =
- @"<PermissionSet class = ""System.Security.NamedPermissionSet""
- version = ""1""
- Name = ""Nothing""
- Description = """ + Environment.GetResourceString("Policy_PS_Nothing") + @""" />";
-
- private static readonly string s_skipVerificationXml =
- @"<PermissionSet class = ""System.Security.NamedPermissionSet""
- version = ""1""
- Name = ""SkipVerification""
- Description = """ + Environment.GetResourceString("Policy_PS_SkipVerification") + @""">
- <IPermission class = ""System.Security.Permissions.SecurityPermission, " + AssemblyRef.Mscorlib + @"""
- version = ""1""
- Flags = ""SkipVerification"" />
- </PermissionSet>";
-
- //
- // Built in permission set objects
- //
-
- private static NamedPermissionSet s_everything;
- private static NamedPermissionSet s_execution;
- private static NamedPermissionSet s_fullTrust;
- private static NamedPermissionSet s_internet;
- private static NamedPermissionSet s_localIntranet;
- private static NamedPermissionSet s_nothing;
- private static NamedPermissionSet s_skipVerification;
-
- //
- // Standard permission sets
- //
-
- internal static NamedPermissionSet Everything
- {
- get { return GetOrDeserializeExtendablePermissionSet(ref s_everything, s_everythingXml); }
- }
-
- internal static NamedPermissionSet Execution
- {
- get { return GetOrDeserializePermissionSet(ref s_execution, s_executionXml); }
- }
-
- internal static NamedPermissionSet FullTrust
- {
- get { return GetOrDeserializePermissionSet(ref s_fullTrust, s_fullTrustXml); }
- }
-
- internal static NamedPermissionSet Internet
- {
- get { return GetOrDeserializeExtendablePermissionSet(ref s_internet, s_internetXml); }
- }
-
- internal static NamedPermissionSet LocalIntranet
- {
- get { return GetOrDeserializeExtendablePermissionSet(ref s_localIntranet, s_localIntranetXml); }
- }
-
- internal static NamedPermissionSet Nothing
- {
- get { return GetOrDeserializePermissionSet(ref s_nothing, s_nothingXml); }
- }
-
- internal static NamedPermissionSet SkipVerification
- {
- get { return GetOrDeserializePermissionSet(ref s_skipVerification, s_skipVerificationXml); }
- }
-
- //
- // Utility methods to construct the permission set objects from the well known XML and any permission
- // set extensions if necessary
- //
-
- private static NamedPermissionSet GetOrDeserializeExtendablePermissionSet(
- ref NamedPermissionSet permissionSet,
- string permissionSetXml)
- {
- Contract.Requires(!String.IsNullOrEmpty(permissionSetXml));
- return permissionSet.Copy() as NamedPermissionSet;
- }
-
- private static NamedPermissionSet GetOrDeserializePermissionSet(ref NamedPermissionSet permissionSet,
- string permissionSetXml)
- {
- Debug.Assert(!String.IsNullOrEmpty(permissionSetXml));
- return permissionSet.Copy() as NamedPermissionSet;
- }
- }
-}
diff --git a/src/mscorlib/src/System/Security/CodeAccessPermission.cs b/src/mscorlib/src/System/Security/CodeAccessPermission.cs
deleted file mode 100644
index 70504d902e..0000000000
--- a/src/mscorlib/src/System/Security/CodeAccessPermission.cs
+++ /dev/null
@@ -1,229 +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.Security
-{
- using System.IO;
- using System.Threading;
- using System.Security;
- using System.Security.Util;
- using System.Security.Permissions;
- using System.Runtime.CompilerServices;
- using System.Collections;
- using System.Text;
- using System;
- using System.Diagnostics;
- using System.Diagnostics.Contracts;
- using IUnrestrictedPermission = System.Security.Permissions.IUnrestrictedPermission;
-
- [Serializable]
- [System.Runtime.InteropServices.ComVisible(true)]
- abstract public class CodeAccessPermission
- : IPermission, ISecurityEncodable, IStackWalk
- {
- // Static methods for manipulation of stack
- [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
- public static void RevertAssert()
- {
- StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
- SecurityRuntime.RevertAssert(ref stackMark);
- }
-
- [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()
- {
- StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
- SecurityRuntime.RevertDeny(ref stackMark);
- }
-
- [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
- public static void RevertPermitOnly()
- {
- StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
- SecurityRuntime.RevertPermitOnly(ref stackMark);
- }
-
- [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
- public static void RevertAll()
- {
- StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
- SecurityRuntime.RevertAll(ref stackMark);
- }
-
- //
- // Standard implementation of IPermission methods for
- // code-access permissions.
- //
-
- // 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).
- [DynamicSecurityMethodAttribute()]
- [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
- public void Demand()
- {
- if (!this.CheckDemand( null ))
- {
- StackCrawlMark stackMark = StackCrawlMark.LookForMyCallersCaller;
- CodeAccessSecurityEngine.Check(this, ref stackMark);
- }
- }
-
- [DynamicSecurityMethodAttribute()]
- [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
- internal static void Demand(PermissionType permissionType)
- {
- // The intent of the method is to be an internal mscorlib helper that Demands a specific permissiontype
- // 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.
- Debug.Assert(new StackFrame().GetMethod().Name.Equals("Demand"), "This method needs to be named Demand");
-
- StackCrawlMark stackMark = StackCrawlMark.LookForMyCallersCaller;
- CodeAccessSecurityEngine.SpecialDemand(permissionType, ref stackMark);
- }
-
- // Metadata for this method should be flaged with REQ_SQ so that
- // EE can allocate space on the stack frame for FrameSecurityDescriptor
-
- [DynamicSecurityMethodAttribute()]
- [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
- public void Assert()
- {
- StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
- CodeAccessSecurityEngine.Assert(this, ref stackMark);
- }
-
-
- [DynamicSecurityMethodAttribute()]
- [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
- static internal void Assert(bool allPossible)
- {
- // The intent of the method is to be an internal mscorlib helper that easily asserts for all possible permissions
- // 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.
- Debug.Assert(new StackFrame().GetMethod().Name.Equals("Assert"), "This method needs to be named Assert");
-
- StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
- SecurityRuntime.AssertAllPossible(ref stackMark);
- }
-
- // Metadata for this method should be flaged with REQ_SQ so that
- // EE can allocate space on the stack frame for FrameSecurityDescriptor
-
- [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.")]
- public void Deny()
- {
- StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
- CodeAccessSecurityEngine.Deny(this, ref stackMark);
- }
-
- // Metadata for this method should be flaged with REQ_SQ so that
- // EE can allocate space on the stack frame for FrameSecurityDescriptor
-
- [DynamicSecurityMethodAttribute()]
- [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
- public void PermitOnly()
- {
- StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
- CodeAccessSecurityEngine.PermitOnly(this, ref stackMark);
- }
-
- // IPermission interfaces
-
- // We provide a default implementation of Union here.
- // Any permission that doesn't provide its own representation
- // of Union will get this one and trigger CompoundPermission
- // We can take care of simple cases here...
-
- public virtual IPermission Union(IPermission other) {
- // The other guy could be null
- if (other == null) return(this.Copy());
-
- // otherwise we don't support it.
- throw new NotSupportedException(Environment.GetResourceString( "NotSupported_SecurityPermissionUnion" ));
- }
-
- //
- // HELPERS FOR IMPLEMENTING ABSTRACT METHODS
- //
-
- //
- // Protected helper
- //
-
- internal bool VerifyType(IPermission perm)
- {
- // if perm is null, then obviously not of the same type
- if ((perm == null) || (perm.GetType() != this.GetType())) {
- return(false);
- } else {
- return(true);
- }
- }
-
- // The IPermission Interface
- public abstract IPermission Copy();
- public abstract IPermission Intersect(IPermission target);
- public abstract bool IsSubsetOf(IPermission target);
-
- [System.Runtime.InteropServices.ComVisible(false)]
- public override bool Equals(Object obj)
- {
- IPermission perm = obj as IPermission;
- if(obj != null && perm == null)
- return false;
- try {
- if(!this.IsSubsetOf(perm))
- return false;
- if(perm != null && !perm.IsSubsetOf(this))
- return false;
- }
- catch (ArgumentException)
- {
- // Any argument exception implies inequality
- // Note that we require a try/catch block here because we have to deal with
- // custom permissions that may throw exceptions indiscriminately.
- return false;
- }
- return true;
- }
-
- [System.Runtime.InteropServices.ComVisible(false)]
- public override int GetHashCode()
- {
- // This implementation is only to silence a compiler warning.
- return base.GetHashCode();
- }
-
-
- internal bool CheckDemand(CodeAccessPermission grant)
- {
- 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)
- {
- 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)
- {
- 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)
- {
- 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
deleted file mode 100644
index d86897c02e..0000000000
--- a/src/mscorlib/src/System/Security/CodeAccessSecurityEngine.cs
+++ /dev/null
@@ -1,400 +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.Security {
- using System;
- using System.Threading;
- using System.Security.Util;
- using System.Collections;
- using System.Runtime.CompilerServices;
- using System.Security.Permissions;
- using System.Reflection;
- 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
- // KEEP IN SYNC WITH DEFINITIONS IN SECURITYPOLICY.H
- [Serializable]
- internal enum PermissionType
- {
- // special flags
- SecurityUnmngdCodeAccess = 0,
- SecuritySkipVerification = 1,
- ReflectionTypeInfo = 2,
- SecurityAssert = 3,
- ReflectionMemberAccess = 4,
- SecuritySerialization = 5,
- ReflectionRestrictedMemberAccess = 6,
- FullTrust = 7,
- SecurityBindingRedirects = 8,
-
- // special permissions
- UIPermission = 9,
- EnvironmentPermission = 10,
- FileDialogPermission = 11,
- FileIOPermission = 12,
- ReflectionPermission = 13,
- SecurityPermission = 14,
-
- // additional special flags
- SecurityControlEvidence = 16,
- SecurityControlPrincipal = 17
- }
-
- internal static class CodeAccessSecurityEngine
- {
-
- internal static SecurityPermission AssertPermission;
- internal static PermissionToken AssertPermissionToken;
-
- [MethodImplAttribute(MethodImplOptions.InternalCall)]
- internal static extern void SpecialDemand(PermissionType whatPermission, ref StackCrawlMark stackMark);
-
- [System.Diagnostics.Conditional( "_DEBUG" )]
- private static void DEBUG_OUT( String str )
- {
-#if _DEBUG
- if (debug)
- Console.WriteLine( str );
-#endif
- }
-
-#if _DEBUG
- private static bool debug = false;
- private const String file = "d:\\foo\\debug.txt";
-#endif
-
- // static default constructor. This will be called before any of the static members are accessed.
- static CodeAccessSecurityEngine()
- {
-#pragma warning disable 618
- AssertPermission = new SecurityPermission(SecurityPermissionFlag.Assertion);
-#pragma warning restore 618
- AssertPermissionToken = PermissionToken.GetToken(AssertPermission);
- }
-
-#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
- {
- AssemblyName asmName = null;
- Evidence asmEvidence = null;
- if (asm != null)
- {
- // Assert here because reflection will check grants and if we fail the check,
- // there will be an infinite recursion that overflows the stack.
- PermissionSet.s_fullTrust.Assert();
- asmName = asm.GetName();
- }
- throw SecurityException.MakeSecurityException(asmName, asmEvidence, granted, refused, rmh, action, demand, permThatFailed);
- }
-
-#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
- {
- 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);
- else
- {
- AssemblyName asmName = new AssemblyName((String)assemblyOrString);
- throw SecurityException.MakeSecurityException(asmName, null, granted, refused, rmh, action, demand, permThatFailed);
- }
- }
-
-#if FEATURE_COMPRESSEDSTACK
- internal static void CheckSetHelper(CompressedStack cs,
- PermissionSet grants,
- PermissionSet refused,
- PermissionSet demands,
- RuntimeMethodHandleInternal rmh,
- RuntimeAssembly asm,
- SecurityAction action)
- {
- if (cs != null)
- cs.CheckSetDemand(demands, rmh);
- else
- CheckSetHelper(grants, refused, demands, rmh, (Object)asm, action, true);
- }
-#else // FEATURE_COMPRESSEDSTACK
-#pragma warning disable 618
- internal static void CheckSetHelper(Object notUsed,
- PermissionSet grants,
- PermissionSet refused,
- PermissionSet demands,
- RuntimeMethodHandleInternal rmh,
- RuntimeAssembly asm,
- SecurityAction action)
-#pragma warning restore 618
- {
- // 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.)
- 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
-
-#pragma warning disable 618
- internal static bool CheckSetHelper(PermissionSet grants,
- PermissionSet refused,
- PermissionSet demands,
- RuntimeMethodHandleInternal rmh,
- Object assemblyOrString,
- SecurityAction action,
- bool throwException)
-#pragma warning restore 618
- {
- Debug.Assert(demands != null, "Should not reach here with a null demand set");
-
- IPermission permThatFailed = null;
- if (grants != null)
- grants.CheckDecoded(demands);
- if (refused != null)
- refused.CheckDecoded(demands);
-
- bool bThreadSecurity = SecurityManager._SetThreadSecurity(false);
-
- try
- {
-
- // Check grant set
- if (!demands.CheckDemand(grants, out permThatFailed))
- {
- if (throwException)
- ThrowSecurityException(assemblyOrString, grants, refused, rmh, action, demands, permThatFailed);
- else
- return false;
- }
-
- // Check refused set
- if (!demands.CheckDeny(refused, out permThatFailed))
- {
- if (throwException)
- ThrowSecurityException(assemblyOrString, grants, refused, rmh, action, demands, permThatFailed);
- else
- return false;
- }
- }
- catch (SecurityException)
- {
- throw;
- }
- catch (Exception)
- {
- // Any exception besides a security exception in this code means that
- // a permission was unable to properly handle what we asked of it.
- // We will define this to mean that the demand failed.
- if (throwException)
- ThrowSecurityException(assemblyOrString, grants, refused, rmh, action, demands, permThatFailed);
- else
- return false;
- }
- finally
- {
- if (bThreadSecurity)
- SecurityManager._SetThreadSecurity(true);
- }
- return true;
- }
-#if FEATURE_COMPRESSEDSTACK
- internal static void CheckHelper(CompressedStack cs,
- PermissionSet grantedSet,
- PermissionSet refusedSet,
- CodeAccessPermission demand,
- PermissionToken permToken,
- RuntimeMethodHandleInternal rmh,
- RuntimeAssembly asm,
- SecurityAction action)
- {
- if (cs != null)
- cs.CheckDemand(demand, permToken, rmh);
- else
- CheckHelper(grantedSet, refusedSet, demand, permToken, rmh, (Object)asm, action, true);
- }
-#else // FEATURE_COMPRESSEDSTACK
-#pragma warning disable 618
- internal static void CheckHelper(Object notUsed,
- PermissionSet grantedSet,
- PermissionSet refusedSet,
- CodeAccessPermission demand,
- PermissionToken permToken,
- RuntimeMethodHandleInternal rmh,
- RuntimeAssembly asm,
- SecurityAction action)
-#pragma warning restore 618
- {
- // 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.)
- 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
-#pragma warning disable 618
- internal static bool CheckHelper(PermissionSet grantedSet,
- PermissionSet refusedSet,
- CodeAccessPermission demand,
- PermissionToken permToken,
- RuntimeMethodHandleInternal rmh,
- Object assemblyOrString,
- SecurityAction action,
- bool throwException)
-#pragma warning restore 618
- {
- // We should never get here with a null demand
- Debug.Assert(demand != null, "Should not reach here with a null demand");
-
- if (permToken == null)
- permToken = PermissionToken.GetToken(demand);
-
- if (grantedSet != null)
- grantedSet.CheckDecoded(permToken.m_index);
- if (refusedSet != null)
- refusedSet.CheckDecoded(permToken.m_index);
-
- // If PermissionSet is null, then module does not have Permissions... Fail check.
-
- bool bThreadSecurity = SecurityManager._SetThreadSecurity(false);
-
- try
- {
- if (grantedSet == null)
- {
- if (throwException)
- ThrowSecurityException(assemblyOrString, grantedSet, refusedSet, rmh, action, demand, demand);
- else
- return false;
- }
-
- else if (!grantedSet.IsUnrestricted())
- {
- // 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.
-
- Debug.Assert(demand != null,"demand != null");
-
- // Find the permission of matching type in the permission set.
-
- CodeAccessPermission grantedPerm =
- (CodeAccessPermission)grantedSet.GetPermission(permToken);
-
- // Make sure the demand has been granted
- if (!demand.CheckDemand( grantedPerm ))
- {
- if (throwException)
- ThrowSecurityException(assemblyOrString, grantedSet, refusedSet, rmh, action, demand, demand);
- else
- return false;
- }
- }
-
- // Make the sure the permission is not refused.
-
- if (refusedSet != null)
- {
- CodeAccessPermission refusedPerm =
- (CodeAccessPermission)refusedSet.GetPermission(permToken);
- if (refusedPerm != null)
- {
- if (!refusedPerm.CheckDeny(demand))
- {
- #if _DEBUG
- if (debug)
- DEBUG_OUT( "Permission found in refused set" );
- #endif
- if (throwException)
- ThrowSecurityException(assemblyOrString, grantedSet, refusedSet, rmh, action, demand, demand);
- else
- return false;
-
- }
- }
-
- if (refusedSet.IsUnrestricted())
- {
- if (throwException)
- ThrowSecurityException(assemblyOrString, grantedSet, refusedSet, rmh, action, demand, demand);
- else
- return false;
- }
- }
- }
- catch (SecurityException)
- {
- throw;
- }
- catch (Exception)
- {
- // Any exception besides a security exception in this code means that
- // a permission was unable to properly handle what we asked of it.
- // We will define this to mean that the demand failed.
- if (throwException)
- ThrowSecurityException(assemblyOrString, grantedSet, refusedSet, rmh, action, demand, demand);
- else
- return false;
- }
- finally
- {
- if (bThreadSecurity)
- SecurityManager._SetThreadSecurity(true);
- }
-
- DEBUG_OUT( "Check passed" );
- return true;
- }
-
- internal static void Check(CodeAccessPermission cap, ref StackCrawlMark stackMark)
- {
- }
-
-
- internal static void Check(PermissionSet permSet, ref StackCrawlMark stackMark)
- {
- }
-
- [MethodImplAttribute(MethodImplOptions.InternalCall)]
- internal static extern FrameSecurityDescriptor CheckNReturnSO(PermissionToken permToken,
- CodeAccessPermission demand,
- ref StackCrawlMark stackMark,
- int create );
-
- internal static void Assert(CodeAccessPermission cap, ref StackCrawlMark stackMark)
- {
- }
-
- internal static void Deny(CodeAccessPermission cap, ref StackCrawlMark stackMark)
- {
- }
-
- internal static void PermitOnly(CodeAccessPermission cap, ref StackCrawlMark stackMark)
- {
- }
-
-#if FEATURE_PLS
- // Update the PLS used for optimization in the AppDomain: called from the VM
- private static PermissionListSet UpdateAppDomainPLS(PermissionListSet adPLS, PermissionSet grantedPerms, PermissionSet refusedPerms) {
- if (adPLS == null) {
- adPLS = new PermissionListSet();
- adPLS.UpdateDomainPLS(grantedPerms, refusedPerms);
- return adPLS;
- } else {
- PermissionListSet newPLS = new PermissionListSet();
- newPLS.UpdateDomainPLS(adPLS);
- newPLS.UpdateDomainPLS(grantedPerms, refusedPerms);
- return newPLS;
- }
- }
-#endif //FEATURE_PLS
- }
-}
diff --git a/src/mscorlib/src/System/Security/FrameSecurityDescriptor.cs b/src/mscorlib/src/System/Security/FrameSecurityDescriptor.cs
deleted file mode 100644
index 0ef5afd282..0000000000
--- a/src/mscorlib/src/System/Security/FrameSecurityDescriptor.cs
+++ /dev/null
@@ -1,537 +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.Security {
- using System.Text;
- using System.Runtime.CompilerServices;
- using System.Threading;
- using System;
- using System.Collections;
- using System.Security.Permissions;
- 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;
-#endif
- //FrameSecurityDescriptor.cs
- //
- // Internal use only.
- // DO NOT DOCUMENT
- //
-
- [Serializable]
- internal class FrameSecurityDescriptor
- {
-
- /* EE has native FrameSecurityDescriptorObject definition in object.h
- Make sure to update that structure as well, if you make any changes here.
- */
- private PermissionSet m_assertions; // imperative asserts
- private PermissionSet m_denials; // imperative denials
- private PermissionSet m_restriction; // imperative permitonlys
- private PermissionSet m_DeclarativeAssertions;
- private PermissionSet m_DeclarativeDenials;
- private PermissionSet m_DeclarativeRestrictions;
-
-#if !FEATURE_PAL
- // 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
- [NonSerialized]
- private SafeAccessTokenHandle m_callerToken;
- [NonSerialized]
- private SafeAccessTokenHandle m_impToken;
-#endif
-
- private bool m_AssertFT;
- private bool m_assertAllPossible;
-#pragma warning disable 169
- private bool m_declSecComputed; // set from the VM to indicate that the declarative A/PO/D on this frame has been populated
-#pragma warning restore 169
-
-
-
- [MethodImplAttribute(MethodImplOptions.InternalCall)]
- private static extern void IncrementOverridesCount();
- [MethodImplAttribute(MethodImplOptions.InternalCall)]
- private static extern void DecrementOverridesCount();
- [MethodImplAttribute(MethodImplOptions.InternalCall)]
- private static extern void IncrementAssertCount();
- [MethodImplAttribute(MethodImplOptions.InternalCall)]
- private static extern void DecrementAssertCount();
-
-
- // Default constructor.
- internal FrameSecurityDescriptor()
- {
- //m_flags = 0;
- }
- //-----------------------------------------------------------+
- // H E L P E R
- //-----------------------------------------------------------+
-
- private PermissionSet CreateSingletonSet(IPermission perm)
- {
- PermissionSet permSet = new PermissionSet(false);
- permSet.AddPermission(perm.Copy());
- return permSet;
- }
-
- //-----------------------------------------------------------+
- // A S S E R T
- //-----------------------------------------------------------+
-
- internal bool HasImperativeAsserts()
- {
- // we store declarative actions in both fields, so check if they are different
- return (m_assertions != null);
- }
- internal bool HasImperativeDenials()
- {
- // we store declarative actions in both fields, so check if they are different
- return (m_denials != null);
- }
- internal bool HasImperativeRestrictions()
- {
- // we store declarative actions in both fields, so check if they are different
- return (m_restriction != null);
- }
- internal void SetAssert(IPermission perm)
- {
- m_assertions = CreateSingletonSet(perm);
- IncrementAssertCount();
- }
-
- internal void SetAssert(PermissionSet permSet)
- {
- m_assertions = permSet.Copy();
- m_AssertFT = m_AssertFT || m_assertions.IsUnrestricted();
- IncrementAssertCount();
- }
-
- internal PermissionSet GetAssertions(bool fDeclarative)
- {
- return (fDeclarative) ? m_DeclarativeAssertions : m_assertions;
- }
-
- internal void SetAssertAllPossible()
- {
- m_assertAllPossible = true;
- IncrementAssertCount();
- }
-
- internal bool GetAssertAllPossible()
- {
- return m_assertAllPossible;
- }
-
- //-----------------------------------------------------------+
- // D E N Y
- //-----------------------------------------------------------+
-
- internal void SetDeny(IPermission perm)
- {
- m_denials = CreateSingletonSet(perm);
- IncrementOverridesCount();
- }
-
- internal void SetDeny(PermissionSet permSet)
- {
- m_denials = permSet.Copy();
- IncrementOverridesCount();
- }
-
- internal PermissionSet GetDenials(bool fDeclarative)
- {
- return (fDeclarative) ? m_DeclarativeDenials: m_denials;
- }
-
- //-----------------------------------------------------------+
- // R E S T R I C T
- //-----------------------------------------------------------+
-
- internal void SetPermitOnly(IPermission perm)
- {
- m_restriction = CreateSingletonSet(perm);
- IncrementOverridesCount();
- }
-
- internal void SetPermitOnly(PermissionSet permSet)
- {
- // permSet must not be null
- m_restriction = permSet.Copy();
- IncrementOverridesCount();
- }
-
- internal PermissionSet GetPermitOnly(bool fDeclarative)
- {
-
- return (fDeclarative) ? m_DeclarativeRestrictions : m_restriction;
- }
-#if !FEATURE_PAL
- //-----------------------------------------------------------+
- // SafeAccessTokenHandle (Impersonation + EH purposes)
- //-----------------------------------------------------------+
- internal void SetTokenHandles (SafeAccessTokenHandle callerToken, SafeAccessTokenHandle impToken)
- {
- m_callerToken = callerToken;
- m_impToken = impToken;
- }
-#endif
- //-----------------------------------------------------------+
- // R E V E R T
- //-----------------------------------------------------------+
-
- internal void RevertAssert()
- {
- if (m_assertions != null)
- {
- m_assertions = null;
- DecrementAssertCount();
- }
-
-
- if (m_DeclarativeAssertions != null)
- {
- m_AssertFT = m_DeclarativeAssertions.IsUnrestricted();
- }
- else
- {
- m_AssertFT = false;
- }
- }
-
- internal void RevertAssertAllPossible()
- {
- if (m_assertAllPossible)
- {
- m_assertAllPossible = false;
- DecrementAssertCount();
- }
- }
-
- internal void RevertDeny()
- {
- if (HasImperativeDenials())
- {
- DecrementOverridesCount();
- m_denials = null;
- }
- }
-
- internal void RevertPermitOnly()
- {
- if (HasImperativeRestrictions())
- {
- DecrementOverridesCount();
- m_restriction= null;;
- }
- }
-
- internal void RevertAll()
- {
- RevertAssert();
- RevertAssertAllPossible();
- RevertDeny();
- RevertPermitOnly();
- }
-
-
- //-----------------------------------------------------------+
- // Demand Evaluation
- //-----------------------------------------------------------+
-
-
- // This will get called when we hit a FSD while evaluating a demand on the call stack or compressedstack
- internal bool CheckDemand(CodeAccessPermission demand, PermissionToken permToken, RuntimeMethodHandleInternal rmh)
- {
- // imperative security
- bool fContinue = CheckDemand2(demand, permToken, rmh, false);
- if (fContinue == SecurityRuntime.StackContinue)
- {
- // declarative security
- fContinue = CheckDemand2(demand, permToken, rmh, true);
- }
- return fContinue;
- }
-
- internal bool CheckDemand2(CodeAccessPermission demand, PermissionToken permToken, RuntimeMethodHandleInternal rmh, bool fDeclarative)
- {
- PermissionSet permSet;
-
- // If the demand is null, there is no need to continue
- Debug.Assert(demand != null && !demand.CheckDemand(null), "Empty demands should have been filtered out by this point");
-
- // decode imperative
- if (GetPermitOnly(fDeclarative) != null)
- GetPermitOnly(fDeclarative).CheckDecoded(demand, permToken);
-
- if (GetDenials(fDeclarative) != null)
- GetDenials(fDeclarative).CheckDecoded(demand, permToken);
-
- if (GetAssertions(fDeclarative) != null)
- GetAssertions(fDeclarative).CheckDecoded(demand, permToken);
-
- // NOTE: See notes about exceptions and exception handling in FrameDescSetHelper
-
- bool bThreadSecurity = SecurityManager._SetThreadSecurity(false);
-
- // Check Reduction
-
- try
- {
- permSet = GetPermitOnly(fDeclarative);
- if (permSet != null)
- {
- CodeAccessPermission perm = (CodeAccessPermission)permSet.GetPermission(demand);
-
- // If the permit only set does not contain the demanded permission, throw a security exception
- if (perm == null)
- {
- if (!permSet.IsUnrestricted())
- throw new SecurityException(String.Format(CultureInfo.InvariantCulture, Environment.GetResourceString("Security_Generic"), demand.GetType().AssemblyQualifiedName), null, permSet, SecurityRuntime.GetMethodInfo(rmh), demand, demand);
- }
- else
- {
- bool bNeedToThrow = true;
-
- try
- {
- bNeedToThrow = !demand.CheckPermitOnly(perm);
- }
- catch (ArgumentException)
- {
- }
-
- if (bNeedToThrow)
- throw new SecurityException(String.Format(CultureInfo.InvariantCulture, Environment.GetResourceString("Security_Generic"), demand.GetType().AssemblyQualifiedName), null, permSet, SecurityRuntime.GetMethodInfo(rmh), demand, demand);
- }
- }
-
- // Check Denials
-
- permSet = GetDenials(fDeclarative);
- if (permSet != null)
- {
- CodeAccessPermission perm = (CodeAccessPermission)permSet.GetPermission(demand);
-
- // If an unrestricted set was denied and the demand implements IUnrestricted
- if (permSet.IsUnrestricted())
- throw new SecurityException(String.Format(CultureInfo.InvariantCulture, Environment.GetResourceString("Security_Generic"), demand.GetType().AssemblyQualifiedName), permSet, null, SecurityRuntime.GetMethodInfo(rmh), demand, demand);
-
- // If the deny set does contain the demanded permission, throw a security exception
- bool bNeedToThrow = true;
- try
- {
- bNeedToThrow = !demand.CheckDeny(perm);
- }
- catch (ArgumentException)
- {
- }
- if (bNeedToThrow)
- throw new SecurityException(String.Format(CultureInfo.InvariantCulture, Environment.GetResourceString("Security_Generic"), demand.GetType().AssemblyQualifiedName), permSet, null, SecurityRuntime.GetMethodInfo(rmh), demand, demand);
- }
-
- if (GetAssertAllPossible())
- {
- return SecurityRuntime.StackHalt;
- }
-
- permSet = GetAssertions(fDeclarative);
- // Check Assertions
- if (permSet != null)
- {
-
- CodeAccessPermission perm = (CodeAccessPermission)permSet.GetPermission(demand);
-
- // If the assert set does contain the demanded permission, halt the stackwalk
-
- try
- {
- if (permSet.IsUnrestricted() || demand.CheckAssert(perm))
- {
- return SecurityRuntime.StackHalt;
- }
- }
- catch (ArgumentException)
- {
- }
- }
-
- }
- finally
- {
- if (bThreadSecurity)
- SecurityManager._SetThreadSecurity(true);
- }
-
- return SecurityRuntime.StackContinue;
- }
-
- internal bool CheckSetDemand(PermissionSet demandSet,
- out PermissionSet alteredDemandSet,
- RuntimeMethodHandleInternal rmh)
- {
- // imperative security
- PermissionSet altPset1 = null, altPset2 = null;
- bool fContinue = CheckSetDemand2(demandSet, out altPset1, rmh, false);
- if (altPset1 != null)
- {
- demandSet = altPset1;
- }
-
- if (fContinue == SecurityRuntime.StackContinue)
- {
- // declarative security
- fContinue = CheckSetDemand2(demandSet, out altPset2, rmh, true);
- }
- // Return the most recent altered set
- // If both declarative and imperative asserts modified the demand set: return altPset2
- // Else if imperative asserts modified the demand set: return altPset1
- // else no alteration: return null
- if (altPset2 != null)
- alteredDemandSet = altPset2;
- else if (altPset1 != null)
- alteredDemandSet = altPset1;
- else
- alteredDemandSet = null;
-
- return fContinue;
- }
-
- internal bool CheckSetDemand2(PermissionSet demandSet,
- out PermissionSet alteredDemandSet,
- RuntimeMethodHandleInternal rmh, bool fDeclarative)
- {
- PermissionSet permSet;
-
- // In the common case we are not going to alter the demand set, so just to
- // be safe we'll set it to null up front.
- alteredDemandSet = null;
-
- // There's some oddness in here to deal with exceptions. The general idea behind
- // this is that we need some way of dealing with custom permissions that may not
- // handle all possible scenarios of Union(), Intersect(), and IsSubsetOf() properly
- // (they don't support it, throw null reference exceptions, etc.).
-
- // An empty demand always succeeds.
- if (demandSet == null || demandSet.IsEmpty())
- return SecurityRuntime.StackHalt;
-
- if (GetPermitOnly(fDeclarative) != null)
- GetPermitOnly(fDeclarative).CheckDecoded( demandSet );
- if (GetDenials(fDeclarative) != null)
- GetDenials(fDeclarative).CheckDecoded( demandSet );
- if (GetAssertions(fDeclarative) != null)
- GetAssertions(fDeclarative).CheckDecoded( demandSet );
-
-
- bool bThreadSecurity = SecurityManager._SetThreadSecurity(false);
-
- try
- {
- // In the case of permit only, we define an exception to be failure of the check
- // and therefore we throw a security exception.
-
- permSet = GetPermitOnly(fDeclarative);
- if (permSet != null)
- {
- IPermission permFailed = null;
- bool bNeedToThrow = true;
-
- try
- {
- bNeedToThrow = !demandSet.CheckPermitOnly(permSet, out permFailed);
- }
- catch (ArgumentException)
- {
- }
- if (bNeedToThrow)
- throw new SecurityException(Environment.GetResourceString("Security_GenericNoType"), null, permSet, SecurityRuntime.GetMethodInfo(rmh), demandSet, permFailed);
- }
-
- // In the case of denial, we define an exception to be failure of the check
- // and therefore we throw a security exception.
-
- permSet = GetDenials(fDeclarative);
-
-
- if (permSet != null)
- {
- IPermission permFailed = null;
-
- bool bNeedToThrow = true;
-
- try
- {
- bNeedToThrow = !demandSet.CheckDeny(permSet, out permFailed);
- }
- catch (ArgumentException)
- {
- }
-
- if (bNeedToThrow)
- throw new SecurityException(Environment.GetResourceString("Security_GenericNoType"), permSet, null, SecurityRuntime.GetMethodInfo(rmh), demandSet, permFailed);
- }
-
- // The assert case is more complex. Since asserts have the ability to "bleed through"
- // (where part of a demand is handled by an assertion, but the rest is passed on to
- // continue the stackwalk), we need to be more careful in handling the "failure" case.
- // Therefore, if an exception is thrown in performing any operation, we make sure to keep
- // that permission in the demand set thereby continuing the demand for that permission
- // walking down the stack.
-
- if (GetAssertAllPossible())
- {
- return SecurityRuntime.StackHalt;
- }
-
- permSet = GetAssertions(fDeclarative);
- if (permSet != null)
- {
- // If this frame asserts a superset of the demand set we're done
-
- if (demandSet.CheckAssertion( permSet ))
- return SecurityRuntime.StackHalt;
-
- // Determine whether any of the demand set asserted. We do this by
- // copying the demand set and removing anything in it that is asserted.
-
- if (!permSet.IsUnrestricted())
- {
- PermissionSet.RemoveAssertedPermissionSet(demandSet, permSet, out alteredDemandSet);
- }
- }
-
- }
- finally
- {
- if (bThreadSecurity)
- SecurityManager._SetThreadSecurity(true);
- }
-
- return SecurityRuntime.StackContinue;
- }
- }
-
-#if FEATURE_COMPRESSEDSTACK
- // Used by the stack compressor to communicate a DynamicResolver to managed code during a stackwalk.
- // The JIT will not actually place these on frames.
- internal class FrameSecurityDescriptorWithResolver : FrameSecurityDescriptor
- {
- private System.Reflection.Emit.DynamicResolver m_resolver;
-
- public System.Reflection.Emit.DynamicResolver Resolver
- {
- get
- {
- return m_resolver;
- }
- }
- }
-#endif // FEATURE_COMPRESSEDSTACK
-}
diff --git a/src/mscorlib/src/System/Security/HostProtectionException.cs b/src/mscorlib/src/System/Security/HostProtectionException.cs
deleted file mode 100644
index b08fccd1b3..0000000000
--- a/src/mscorlib/src/System/Security/HostProtectionException.cs
+++ /dev/null
@@ -1,135 +0,0 @@
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-// See the LICENSE file in the project root for more information.
-
-//
-
-/*=============================================================================
-**
-**
-** Purpose: Exception class for HostProtection
-**
-**
-=============================================================================*/
-
-namespace System.Security
-{
- using System.Security;
- using System;
- using System.Runtime.Serialization;
- using System.Security.Permissions;
- using System.Reflection;
- using System.Text;
- using System.Diagnostics.Contracts;
-
- [System.Runtime.InteropServices.ComVisible(true)]
- [Serializable]
- public class HostProtectionException : SystemException
- {
- private HostProtectionResource m_protected;
- private HostProtectionResource m_demanded;
-
- private const String ProtectedResourcesName = "ProtectedResources";
- private const String DemandedResourcesName = "DemandedResources";
-
- public HostProtectionException() : base()
- {
- m_protected = HostProtectionResource.None;
- m_demanded = HostProtectionResource.None;
- }
-
- public HostProtectionException(string message) : base(message)
- {
- m_protected = HostProtectionResource.None;
- m_demanded = HostProtectionResource.None;
- }
-
- public HostProtectionException(string message, Exception e) : base(message, e)
- {
- m_protected = HostProtectionResource.None;
- m_demanded = HostProtectionResource.None;
- }
-
- protected HostProtectionException(SerializationInfo info, StreamingContext context) : base(info, context)
- {
- if (info==null)
- throw new ArgumentNullException(nameof(info));
- Contract.EndContractBlock();
-
- m_protected = (HostProtectionResource)info.GetValue(ProtectedResourcesName, typeof(HostProtectionResource));
- m_demanded = (HostProtectionResource)info.GetValue(DemandedResourcesName, typeof(HostProtectionResource));
- }
-
- public HostProtectionException(string message, HostProtectionResource protectedResources, HostProtectionResource demandedResources)
- : base(message)
- {
- SetErrorCode(__HResults.COR_E_HOSTPROTECTION);
- m_protected = protectedResources;
- m_demanded = demandedResources;
- }
-
- // Called from the VM to create a HP Exception
- private HostProtectionException(HostProtectionResource protectedResources, HostProtectionResource demandedResources)
- : base(SecurityException.GetResString("HostProtection_HostProtection"))
- {
- SetErrorCode(__HResults.COR_E_HOSTPROTECTION);
- m_protected = protectedResources;
- m_demanded = demandedResources;
- }
-
-
- public HostProtectionResource ProtectedResources
- {
- get
- {
- return m_protected;
- }
- }
-
- public HostProtectionResource DemandedResources
- {
- get
- {
- return m_demanded;
- }
- }
-
- private String ToStringHelper(String resourceString, Object attr)
- {
- if (attr == null)
- return String.Empty;
- StringBuilder sb = new StringBuilder();
- sb.Append(Environment.NewLine);
- sb.Append(Environment.NewLine);
- sb.Append(Environment.GetResourceString( resourceString ));
- sb.Append(Environment.NewLine);
- sb.Append(attr);
- return sb.ToString();
- }
-
- public override String ToString()
- {
- String protectedResStrValue = ToStringHelper("HostProtection_ProtectedResources", ProtectedResources);
- StringBuilder sb = new StringBuilder();
- sb.Append(base.ToString());
-
- sb.Append(protectedResStrValue);
- sb.Append(ToStringHelper("HostProtection_DemandedResources", DemandedResources));
-
- return sb.ToString();
-
- }
-
- public override void GetObjectData(SerializationInfo info, StreamingContext context)
- {
- if (info==null)
- throw new ArgumentNullException(nameof(info));
- Contract.EndContractBlock();
-
- base.GetObjectData( info, context );
-
- info.AddValue(ProtectedResourcesName, ProtectedResources, typeof(HostProtectionResource));
- info.AddValue(DemandedResourcesName, DemandedResources, typeof(HostProtectionResource));
- }
- }
-}
diff --git a/src/mscorlib/src/System/Security/HostSecurityManager.cs b/src/mscorlib/src/System/Security/HostSecurityManager.cs
deleted file mode 100644
index 53137983d3..0000000000
--- a/src/mscorlib/src/System/Security/HostSecurityManager.cs
+++ /dev/null
@@ -1,90 +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 HostSecurityManager gives a hosting application the chance to
-// participate in the security decisions in the AppDomain.
-//
-
-namespace System.Security
-{
- using System.Collections;
- using System.Reflection;
- using System.Security;
- using System.Security.Permissions;
- using System.Security.Policy;
- using System.Runtime.Versioning;
- using System.Diagnostics.Contracts;
-
-
- [Serializable]
- [Flags]
- [System.Runtime.InteropServices.ComVisible(true)]
- public enum HostSecurityManagerOptions {
- None = 0x0000,
- HostAppDomainEvidence = 0x0001,
- [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.")]
- HostPolicyLevel = 0x0002,
- HostAssemblyEvidence = 0x0004,
- HostDetermineApplicationTrust = 0x0008,
- HostResolvePolicy = 0x0010,
- AllFlags = 0x001F
- }
-
- [Serializable]
- [System.Runtime.InteropServices.ComVisible(true)]
- public class HostSecurityManager {
- public HostSecurityManager () {}
-
- // The host can choose which events he wants to participate in. This property can be set when
- // the host only cares about a subset of the capabilities exposed through the HostSecurityManager.
- public virtual HostSecurityManagerOptions Flags {
- get {
- // We use AllFlags as the default.
- return HostSecurityManagerOptions.AllFlags;
- }
- }
-
- public virtual Evidence ProvideAppDomainEvidence (Evidence inputEvidence) {
- // The default implementation does not modify the input evidence.
- return inputEvidence;
- }
-
- public virtual Evidence ProvideAssemblyEvidence (Assembly loadedAssembly, Evidence inputEvidence) {
- // The default implementation does not modify the input evidence.
- return inputEvidence;
- }
-
- /// <summary>
- /// Determine what types of evidence the host might be able to supply for the AppDomain if requested
- /// </summary>
- /// <returns></returns>
- public virtual Type[] GetHostSuppliedAppDomainEvidenceTypes() {
- return null;
- }
-
- /// <summary>
- /// Determine what types of evidence the host might be able to supply for an assembly if requested
- /// </summary>
- public virtual Type[] GetHostSuppliedAssemblyEvidenceTypes(Assembly assembly) {
- return null;
- }
-
- /// <summary>
- /// Ask the host to supply a specific type of evidence for the AppDomain
- /// </summary>
- public virtual EvidenceBase GenerateAppDomainEvidence(Type evidenceType) {
- return null;
- }
-
- /// <summary>
- /// Ask the host to supply a specific type of evidence for an assembly
- /// </summary>
- public virtual EvidenceBase GenerateAssemblyEvidence(Type evidenceType, Assembly assembly) {
- return null;
- }
- }
-}
diff --git a/src/mscorlib/src/System/Security/IEvidenceFactory.cs b/src/mscorlib/src/System/Security/IEvidenceFactory.cs
deleted file mode 100644
index 592ab533be..0000000000
--- a/src/mscorlib/src/System/Security/IEvidenceFactory.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.Security
-{
- [System.Runtime.InteropServices.ComVisible(true)]
- public interface IEvidenceFactory
- {
- }
-}
diff --git a/src/mscorlib/src/System/Security/IPermission.cs b/src/mscorlib/src/System/Security/IPermission.cs
deleted file mode 100644
index 5477261fd7..0000000000
--- a/src/mscorlib/src/System/Security/IPermission.cs
+++ /dev/null
@@ -1,84 +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.
-
-//
-//
-// Defines the interface that all Permission objects must support.
-//
-
-namespace System.Security
-{
-
-[System.Runtime.InteropServices.ComVisible(true)]
- public interface IPermission : ISecurityEncodable
- {
- // NOTE: The constants that used to be defined here were moved to
- // PermissionsEnum.cs due to CLS restrictions.
-
- // The integrity of the security system depends on a means to
- // copy objects so that references to sensitive objects are not
- // exposed outside of the runtime. Thus, all permissions must
- // implement Copy.
- //
- // Makes an exact copy of the Permission.
- IPermission Copy();
-
- /*
- * Methods to support the Installation, Registration, others... PolicyEngine
- */
-
- // Policy decisions and runtime mechanisms (for example, Deny)
- // require a means to retrieve shared state between two
- // permissions. If there is no shared state between two
- // instances, then the method should return null.
- //
- // Could think of the method as GetCommonState,
- // but leave it as Intersect to avoid gratuitous name changes.
- //
- // Returns a new permission with the permission-defined intersection
- // of the two permissions. The intersection is generally defined as
- // privilege parameters that are included by both 'this' and 'target'.
- // Returns null if 'target' is null or is of wrong type.
- //
- IPermission Intersect(IPermission target);
-
- // The runtime policy manager also requires a means of combining the
- // state contained within two permissions of the same type in a logical OR
- // construct. (The Union of two permission of different type is not defined,
- // except when one of the two is a CompoundPermission of internal type equal
- // to the type of the other permission.)
- //
-
- IPermission Union(IPermission target);
-
- // IsSubsetOf defines a standard mechanism for determining
- // relative safety between two permission demands of the same type.
- // If one demand x demands no more than some other demand y, then
- // x.IsSubsetOf(y) should return true. In this case, if the
- // demand for y is satisfied, then it is possible to assume that
- // the demand for x would also be satisfied under the same
- // circumstances. On the other hand, if x demands something that y
- // does not, then x.IsSubsetOf(y) should return false; the fact
- // that x is satisfied by the current security context does not
- // also imply that the demand for y will also be satisfied.
- //
- // Returns true if 'this' Permission allows no more access than the
- // argument.
- //
- bool IsSubsetOf(IPermission target);
-
- // The Demand method is the fundamental part of the IPermission
- // interface from a component developer's perspective. The
- // permission represents the demand that the developer wants
- // satisfied, and Demand is the means to invoke the demand.
- // For each type of permission, the mechanism to verify the
- // demand will be different. However, to the developer, all
- // permissions invoke that mechanism through the Demand interface.
- // 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).
- [DynamicSecurityMethodAttribute()]
- void Demand();
-
- }
-}
diff --git a/src/mscorlib/src/System/Security/ISecurityEncodable.cs b/src/mscorlib/src/System/Security/ISecurityEncodable.cs
deleted file mode 100644
index 689b3e4b5f..0000000000
--- a/src/mscorlib/src/System/Security/ISecurityEncodable.cs
+++ /dev/null
@@ -1,17 +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.
-
-//
-//
-// All encodable security classes that support encoding need to
-// implement this interface
-//
-
-namespace System.Security
-{
- [System.Runtime.InteropServices.ComVisible(true)]
- public interface ISecurityEncodable
- {
- }
-}
diff --git a/src/mscorlib/src/System/Security/ISecurityPolicyEncodable.cs b/src/mscorlib/src/System/Security/ISecurityPolicyEncodable.cs
deleted file mode 100644
index 567e41e891..0000000000
--- a/src/mscorlib/src/System/Security/ISecurityPolicyEncodable.cs
+++ /dev/null
@@ -1,17 +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.
-
-//
-//
-// All encodable security classes that support encoding need to
-// implement this interface
-//
-
-namespace System.Security
-{
- [System.Runtime.InteropServices.ComVisible(true)]
- public interface ISecurityPolicyEncodable
- {
- }
-}
diff --git a/src/mscorlib/src/System/Security/IStackWalk.cs b/src/mscorlib/src/System/Security/IStackWalk.cs
deleted file mode 100644
index 902fc35b61..0000000000
--- a/src/mscorlib/src/System/Security/IStackWalk.cs
+++ /dev/null
@@ -1,23 +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.Security
-{
-
-[System.Runtime.InteropServices.ComVisible(true)]
- public interface IStackWalk
- {
- [DynamicSecurityMethodAttribute()]
- void Assert();
-
- [DynamicSecurityMethodAttribute()]
- void Demand();
-
- [DynamicSecurityMethodAttribute()]
- void Deny();
-
- [DynamicSecurityMethodAttribute()]
- void PermitOnly();
- }
-}
diff --git a/src/mscorlib/src/System/Security/NamedPermissionSet.cs b/src/mscorlib/src/System/Security/NamedPermissionSet.cs
deleted file mode 100644
index 1bc166fde8..0000000000
--- a/src/mscorlib/src/System/Security/NamedPermissionSet.cs
+++ /dev/null
@@ -1,75 +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.
-
-//
-//
-// Extends PermissionSet to allow an associated name and description
-//
-
-namespace System.Security
-{
- using System;
- using System.Security.Permissions;
-
- [Serializable]
- [System.Runtime.InteropServices.ComVisible(true)]
- public sealed class NamedPermissionSet : PermissionSet
- {
- 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"))
- return CreateFullTrustSet();
- else if (name.Equals("Nothing"))
- return CreateNothingSet();
- else if (name.Equals("Execution"))
- return CreateExecutionSet();
- else if (name.Equals("SkipVerification"))
- return CreateSkipVerificationSet();
- else if (name.Equals("Internet"))
- return CreateInternetSet();
- else
- return null;
- }
-
- private static PermissionSet CreateFullTrustSet() {
- return new PermissionSet(PermissionState.Unrestricted);
- }
-
- private static PermissionSet CreateNothingSet() {
- return new PermissionSet(PermissionState.None);
- }
-
- private static PermissionSet CreateExecutionSet() {
- PermissionSet permSet = new PermissionSet(PermissionState.None);
-#pragma warning disable 618
- permSet.AddPermission(new SecurityPermission(SecurityPermissionFlag.Execution));
-#pragma warning restore 618
- return permSet;
- }
-
- private static PermissionSet CreateSkipVerificationSet() {
- PermissionSet permSet = new PermissionSet(PermissionState.None);
-#pragma warning disable 618
- permSet.AddPermission(new SecurityPermission(SecurityPermissionFlag.SkipVerification));
-#pragma warning restore 618
- return permSet;
- }
-
- private static PermissionSet CreateInternetSet() {
- PermissionSet permSet = new PermissionSet(PermissionState.None);
- permSet.AddPermission(new FileDialogPermission(FileDialogPermissionAccess.Open));
-#pragma warning disable 618
- permSet.AddPermission(new SecurityPermission(SecurityPermissionFlag.Execution));
-#pragma warning restore 618
- permSet.AddPermission(new UIPermission(UIPermissionWindow.SafeTopLevelWindows, UIPermissionClipboard.OwnClipboard));
- return permSet;
-
-
- }
- }
-}
diff --git a/src/mscorlib/src/System/Security/PermissionListSet.cs b/src/mscorlib/src/System/Security/PermissionListSet.cs
deleted file mode 100644
index 093542ad4e..0000000000
--- a/src/mscorlib/src/System/Security/PermissionListSet.cs
+++ /dev/null
@@ -1,535 +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: Holds state about A/G/R permissionsets in a callstack or appdomain
-** (Replacement for PermissionListSet)
-**
-=============================================================================*/
-
-namespace System.Security
-{
- using System.Globalization;
- using System.Reflection;
- using System.Runtime.InteropServices;
- using System.Security;
- using System.Security.Permissions;
- using System.Threading;
- using System.Collections;
- using System.Collections.Generic;
- using System.Diagnostics;
- using System.Diagnostics.Contracts;
-
- [Serializable]
- sealed internal class PermissionListSet
- {
- // Only internal (public) methods are creation methods and demand evaluation methods.
- // Scroll down to the end to see them.
- private PermissionSetTriple m_firstPermSetTriple;
- private ArrayList m_permSetTriples;
-#if FEATURE_COMPRESSEDSTACK
- private ArrayList m_zoneList;
- private ArrayList m_originList;
-#endif // FEATURE_COMPRESSEDSTACK
-
- internal PermissionListSet() {}
-
- private void EnsureTriplesListCreated()
- {
- if (m_permSetTriples == null)
- {
- m_permSetTriples = new ArrayList();
- if (m_firstPermSetTriple != null)
- {
- m_permSetTriples.Add(m_firstPermSetTriple);
- m_firstPermSetTriple = null;
- }
- }
- }
-
-#if FEATURE_PLS
- internal void UpdateDomainPLS (PermissionListSet adPLS) {
- if (adPLS != null && adPLS.m_firstPermSetTriple != null)
- UpdateDomainPLS(adPLS.m_firstPermSetTriple.GrantSet, adPLS.m_firstPermSetTriple.RefusedSet);
- }
-
- internal void UpdateDomainPLS (PermissionSet grantSet, PermissionSet deniedSet) {
- Debug.Assert(m_permSetTriples == null, "m_permSetTriples != null");
- if (m_firstPermSetTriple == null)
- m_firstPermSetTriple = new PermissionSetTriple();
-
- // update the grant and denied sets
- m_firstPermSetTriple.UpdateGrant(grantSet);
- m_firstPermSetTriple.UpdateRefused(deniedSet);
- }
-#endif // FEATURE_PLS
-
- private void Terminate(PermissionSetTriple currentTriple)
- {
- UpdateTripleListAndCreateNewTriple(currentTriple, null);
- }
-
- private void Terminate(PermissionSetTriple currentTriple, PermissionListSet pls)
- {
-#if FEATURE_COMPRESSEDSTACK
- this.UpdateZoneAndOrigin(pls);
-#endif // FEATURE_COMPRESSEDSTACK
- this.UpdatePermissions(currentTriple, pls);
- this.UpdateTripleListAndCreateNewTriple(currentTriple, null);
- }
-
- private bool Update(PermissionSetTriple currentTriple, PermissionListSet pls)
- {
-#if FEATURE_COMPRESSEDSTACK
- this.UpdateZoneAndOrigin(pls);
-#endif // FEATURE_COMPRESSEDSTACK
- return this.UpdatePermissions(currentTriple, pls);
- }
-
- private bool Update(PermissionSetTriple currentTriple, FrameSecurityDescriptor fsd)
- {
-#if FEATURE_COMPRESSEDSTACK
- FrameSecurityDescriptorWithResolver fsdWithResolver = fsd as FrameSecurityDescriptorWithResolver;
- if (fsdWithResolver != null)
- {
- return Update2(currentTriple, fsdWithResolver);
- }
-#endif // FEATURE_COMPRESSEDSTACK
-
- // check imperative
- bool fHalt = Update2(currentTriple, fsd, false);
- if (!fHalt)
- {
- // then declarative
- fHalt = Update2(currentTriple, fsd, true);
- }
- return fHalt;
- }
-
-#if FEATURE_COMPRESSEDSTACK
- private bool Update2(PermissionSetTriple currentTriple, FrameSecurityDescriptorWithResolver fsdWithResolver)
- {
- System.Reflection.Emit.DynamicResolver resolver = fsdWithResolver.Resolver;
- CompressedStack dynamicCompressedStack = resolver.GetSecurityContext();
- dynamicCompressedStack.CompleteConstruction(null);
- return this.Update(currentTriple, dynamicCompressedStack.PLS);
- }
-#endif // FEATURE_COMPRESSEDSTACK
-
- private bool Update2(PermissionSetTriple currentTriple, FrameSecurityDescriptor fsd, bool fDeclarative)
- {
- // Deny
- PermissionSet deniedPset = fsd.GetDenials(fDeclarative);
- if (deniedPset != null)
- {
- currentTriple.UpdateRefused(deniedPset);
- }
-
- // permit only
- PermissionSet permitOnlyPset = fsd.GetPermitOnly(fDeclarative);
- if (permitOnlyPset != null)
- {
- currentTriple.UpdateGrant(permitOnlyPset);
- }
-
- // Assert all possible
- if (fsd.GetAssertAllPossible())
- {
- // If we have no grant set, it means that the only assembly we've seen on the stack so
- // far is mscorlib. Since mscorlib will always be fully trusted, the grant set of the
- // compressed stack is also FullTrust.
- if (currentTriple.GrantSet == null)
- currentTriple.GrantSet = PermissionSet.s_fullTrust;
-
- UpdateTripleListAndCreateNewTriple(currentTriple, m_permSetTriples);
- currentTriple.GrantSet = PermissionSet.s_fullTrust;
- currentTriple.UpdateAssert(fsd.GetAssertions(fDeclarative));
- return true;
- }
-
- // Assert
- PermissionSet assertPset = fsd.GetAssertions(fDeclarative);
- if (assertPset != null)
- {
- if (assertPset.IsUnrestricted())
- {
- // If we have no grant set, it means that the only assembly we've seen on the stack so
- // far is mscorlib. Since mscorlib will always be fully trusted, the grant set of the
- // compressed stack is also FullTrust.
- if (currentTriple.GrantSet == null)
- currentTriple.GrantSet = PermissionSet.s_fullTrust;
-
- UpdateTripleListAndCreateNewTriple(currentTriple, m_permSetTriples);
- currentTriple.GrantSet = PermissionSet.s_fullTrust;
- currentTriple.UpdateAssert(assertPset);
- return true;
- }
-
- PermissionSetTriple retTriple = currentTriple.UpdateAssert(assertPset);
- if (retTriple != null)
- {
- EnsureTriplesListCreated();
- m_permSetTriples.Add(retTriple);
- }
- }
-
- return false;
- }
- private void Update(PermissionSetTriple currentTriple, PermissionSet in_g, PermissionSet in_r)
- {
-#if FEATURE_COMPRESSEDSTACK
- ZoneIdentityPermission z;
- UrlIdentityPermission u;
- currentTriple.UpdateGrant(in_g, out z, out u);
- currentTriple.UpdateRefused(in_r);
- AppendZoneOrigin(z, u);
-#else // !FEATURE_COMPRESEDSTACK
- currentTriple.UpdateGrant(in_g);
- currentTriple.UpdateRefused(in_r);
-#endif // FEATURE_COMPRESSEDSTACK
- }
-
- // Called from the VM for HG CS construction
- private void Update(PermissionSet in_g)
- {
- if (m_firstPermSetTriple == null)
- m_firstPermSetTriple = new PermissionSetTriple();
- Update(m_firstPermSetTriple, in_g, null);
- }
-
-#if FEATURE_COMPRESSEDSTACK
- private void UpdateZoneAndOrigin(PermissionListSet pls)
- {
- if (pls != null)
- {
- if (this.m_zoneList == null && pls.m_zoneList != null && pls.m_zoneList.Count > 0)
- this.m_zoneList = new ArrayList();
- UpdateArrayList(this.m_zoneList, pls.m_zoneList);
- if (this.m_originList == null && pls.m_originList != null && pls.m_originList.Count > 0)
- this.m_originList = new ArrayList();
- UpdateArrayList(this.m_originList, pls.m_originList);
- }
- }
-#endif // FEATURE_COMPRESSEDSTACK
-
- private bool UpdatePermissions(PermissionSetTriple currentTriple, PermissionListSet pls)
- {
- if (pls != null)
- {
- if (pls.m_permSetTriples != null)
- {
- // DCS has an AGR List. So we need to add the AGR List
- UpdateTripleListAndCreateNewTriple(currentTriple,pls.m_permSetTriples);
- }
- else
- {
- // Common case: One AGR set
-
- PermissionSetTriple tmp_psTriple = pls.m_firstPermSetTriple;
- PermissionSetTriple retTriple;
- // First try and update currentTriple. Return value indicates if we can stop construction
- if (currentTriple.Update(tmp_psTriple, out retTriple))
- return true;
- // If we got a non-null retTriple, what it means is that compression failed,
- // and we now have 2 triples to deal with: retTriple and currentTriple.
- // retTriple has to be appended first. then currentTriple.
- if (retTriple != null)
- {
- EnsureTriplesListCreated();
- // we just created a new triple...add the previous one (returned) to the list
- m_permSetTriples.Add(retTriple);
- }
- }
- }
- else
- {
- // pls can be null only outside the loop in CreateCompressedState
- UpdateTripleListAndCreateNewTriple(currentTriple, null);
- }
-
-
- return false;
-
- }
-
-
- private void UpdateTripleListAndCreateNewTriple(PermissionSetTriple currentTriple, ArrayList tripleList)
- {
- if (!currentTriple.IsEmpty())
- {
- if (m_firstPermSetTriple == null && m_permSetTriples == null)
- {
- m_firstPermSetTriple = new PermissionSetTriple(currentTriple);
- }
- else
- {
- EnsureTriplesListCreated();
- m_permSetTriples.Add(new PermissionSetTriple(currentTriple));
- }
- currentTriple.Reset();
- }
- if (tripleList != null)
- {
- EnsureTriplesListCreated();
- m_permSetTriples.AddRange(tripleList);
- }
- }
-
- private static void UpdateArrayList(ArrayList current, ArrayList newList)
- {
- if (newList == null)
- return;
-
- for(int i=0;i < newList.Count; i++)
- {
- if (!current.Contains(newList[i]))
- current.Add(newList[i]);
- }
-
- }
-
-#if FEATURE_COMPRESSEDSTACK
- private void AppendZoneOrigin(ZoneIdentityPermission z, UrlIdentityPermission u)
- {
-
- if (z != null)
- {
- if (m_zoneList == null)
- m_zoneList = new ArrayList();
- z.AppendZones(m_zoneList);
- }
-
- if (u != null)
- {
- if (m_originList == null)
- m_originList = new ArrayList();
- u.AppendOrigin(m_originList);
- }
- }
-
-[System.Runtime.InteropServices.ComVisible(true)]
- // public(internal) interface begins...
- // Creation functions
- static internal PermissionListSet CreateCompressedState(CompressedStack cs, CompressedStack innerCS)
- {
- // function that completes the construction of the compressed stack if not done so already (bottom half for demand evaluation)
-
- bool bHaltConstruction = false;
- if (cs.CompressedStackHandle == null)
- return null; // FT case or Security off
-
- PermissionListSet pls = new PermissionListSet();
- PermissionSetTriple currentTriple = new PermissionSetTriple();
- int numDomains = CompressedStack.GetDCSCount(cs.CompressedStackHandle);
- for (int i=numDomains-1; (i >= 0 && !bHaltConstruction) ; i--)
- {
- DomainCompressedStack dcs = CompressedStack.GetDomainCompressedStack(cs.CompressedStackHandle, i);
- if (dcs == null)
- continue; // we hit a FT Domain
- if (dcs.PLS == null)
- {
- // We failed on some DCS
- throw new SecurityException(String.Format(CultureInfo.InvariantCulture, Environment.GetResourceString("Security_Generic")));
- }
- pls.UpdateZoneAndOrigin(dcs.PLS);
- pls.Update(currentTriple, dcs.PLS);
- bHaltConstruction = dcs.ConstructionHalted;
- }
- if (!bHaltConstruction)
- {
- PermissionListSet tmp_pls = null;
- // Construction did not halt.
- if (innerCS != null)
- {
- innerCS.CompleteConstruction(null);
- tmp_pls = innerCS.PLS;
- }
- pls.Terminate(currentTriple, tmp_pls);
- }
- else
- {
- pls.Terminate(currentTriple);
- }
-
- return pls;
- }
-
- static internal PermissionListSet CreateCompressedState(IntPtr unmanagedDCS, out bool bHaltConstruction)
- {
- PermissionListSet pls = new PermissionListSet();
- PermissionSetTriple currentTriple = new PermissionSetTriple();
-
- PermissionSet tmp_g, tmp_r;
- // Construct the descriptor list
- int descCount = DomainCompressedStack.GetDescCount(unmanagedDCS);
- bHaltConstruction = false;
- for(int i=0; (i < descCount && !bHaltConstruction); i++)
- {
- FrameSecurityDescriptor fsd;
- Assembly assembly;
- if (DomainCompressedStack.GetDescriptorInfo(unmanagedDCS, i, out tmp_g, out tmp_r, out assembly, out fsd))
- {
- // Got an FSD
- bHaltConstruction = pls.Update(currentTriple, fsd);
- }
- else
- {
- pls.Update(currentTriple, tmp_g, tmp_r);
- }
-
- }
- if (!bHaltConstruction)
- {
- // domain
- if (!DomainCompressedStack.IgnoreDomain(unmanagedDCS))
- {
- DomainCompressedStack.GetDomainPermissionSets(unmanagedDCS, out tmp_g, out tmp_r);
- pls.Update(currentTriple, tmp_g, tmp_r);
- }
- }
- pls.Terminate(currentTriple);
-
-
- // return the created object
- return pls;
-
- }
- static internal PermissionListSet CreateCompressedState_HG()
- {
- PermissionListSet pls = new PermissionListSet();
- CompressedStack.GetHomogeneousPLS(pls);
- return pls;
- }
-#endif // #if FEATURE_COMPRESSEDSTACK
- // Private Demand evaluation functions - only called from the VM
- internal bool CheckDemandNoThrow(CodeAccessPermission demand)
- {
- // AppDomain permissions - no asserts. So there should only be one triple to work with
- Debug.Assert(m_permSetTriples == null && m_firstPermSetTriple != null, "More than one PermissionSetTriple encountered in AD PermissionListSet");
-
-
-
- PermissionToken permToken = null;
- if (demand != null)
- permToken = PermissionToken.GetToken(demand);
-
- return m_firstPermSetTriple.CheckDemandNoThrow(demand, permToken);
-
-
- }
- internal bool CheckSetDemandNoThrow(PermissionSet pSet)
- {
- // AppDomain permissions - no asserts. So there should only be one triple to work with
- Debug.Assert(m_permSetTriples == null && m_firstPermSetTriple != null, "More than one PermissionSetTriple encountered in AD PermissionListSet");
-
-
- return m_firstPermSetTriple.CheckSetDemandNoThrow(pSet);
- }
-
- // Demand evauation functions
- internal bool CheckDemand(CodeAccessPermission demand, PermissionToken permToken, RuntimeMethodHandleInternal rmh)
- {
- bool bRet = SecurityRuntime.StackContinue;
- if (m_permSetTriples != null)
- {
- for (int i=0; (i < m_permSetTriples.Count && bRet != SecurityRuntime.StackHalt) ; i++)
- {
- PermissionSetTriple psTriple = (PermissionSetTriple)m_permSetTriples[i];
- bRet = psTriple.CheckDemand(demand, permToken, rmh);
- }
- }
- else if (m_firstPermSetTriple != null)
- {
- bRet = m_firstPermSetTriple.CheckDemand(demand, permToken, rmh);
- }
-
- return bRet;
- }
-
- internal bool CheckSetDemand(PermissionSet pset , RuntimeMethodHandleInternal rmh)
- {
- PermissionSet unused;
- CheckSetDemandWithModification(pset, out unused, rmh);
- return SecurityRuntime.StackHalt; // CS demand check always terminates the stackwalk
- }
-
- internal bool CheckSetDemandWithModification(PermissionSet pset, out PermissionSet alteredDemandSet, RuntimeMethodHandleInternal rmh)
- {
- bool bRet = SecurityRuntime.StackContinue;
- PermissionSet demandSet = pset;
- alteredDemandSet = null;
- if (m_permSetTriples != null)
- {
- for (int i=0; (i < m_permSetTriples.Count && bRet != SecurityRuntime.StackHalt) ; i++)
- {
- PermissionSetTriple psTriple = (PermissionSetTriple)m_permSetTriples[i];
- bRet = psTriple.CheckSetDemand(demandSet, out alteredDemandSet, rmh);
- if (alteredDemandSet != null)
- demandSet = alteredDemandSet;
- }
- }
- else if (m_firstPermSetTriple != null)
- {
- bRet = m_firstPermSetTriple.CheckSetDemand(demandSet, out alteredDemandSet, rmh);
- }
-
- return bRet;
- }
-
- /// <summary>
- /// 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>
- private bool CheckFlags(int flags)
- {
- Debug.Assert(flags != 0, "Invalid permission flag demand");
-
- bool check = true;
-
- if (m_permSetTriples != null)
- {
- for (int i = 0; i < m_permSetTriples.Count && check && flags != 0; i++)
- {
- check &= ((PermissionSetTriple)m_permSetTriples[i]).CheckFlags(ref flags);
- }
- }
- else if (m_firstPermSetTriple != null)
- {
- check = m_firstPermSetTriple.CheckFlags(ref flags);
- }
-
- return check;
- }
-
- /// <summary>
- /// Demand which succeeds if either a set of special permissions or a permission set is granted
- /// to the call stack
- /// </summary>
- /// <param name="flags">set of flags to check (See PermissionType)</param>
- /// <param name="grantSet">alternate permission set to check</param>
- internal void DemandFlagsOrGrantSet(int flags, PermissionSet grantSet)
- {
- if (CheckFlags(flags))
- return;
-
- CheckSetDemand(grantSet, RuntimeMethodHandleInternal.EmptyHandle);
- }
-
-#if FEATURE_COMPRESSEDSTACK
- internal void GetZoneAndOrigin(ArrayList zoneList, ArrayList originList, PermissionToken zoneToken, PermissionToken originToken)
- {
- if (m_zoneList != null)
- zoneList.AddRange(m_zoneList);
- if (m_originList != null)
- originList.AddRange(m_originList);
- }
-#endif
- }
-
-}
diff --git a/src/mscorlib/src/System/Security/PermissionSet.cs b/src/mscorlib/src/System/Security/PermissionSet.cs
deleted file mode 100644
index 11ca02a81e..0000000000
--- a/src/mscorlib/src/System/Security/PermissionSet.cs
+++ /dev/null
@@ -1,1605 +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.Security {
- using System;
- using System.Threading;
- using System.Security.Util;
- using System.Collections;
- using System.IO;
- using System.Security.Permissions;
- using System.Runtime.CompilerServices;
- using System.Security.Policy;
-#if FEATURE_SERIALIZATION
- using System.Runtime.Serialization.Formatters.Binary;
-#endif // FEATURE_SERIALIZATION
- using BindingFlags = System.Reflection.BindingFlags;
- using System.Runtime.Serialization;
- using System.Text;
- using System.Globalization;
- using System.Runtime.Versioning;
- using System.Diagnostics;
- using System.Diagnostics.Contracts;
-
- [Serializable]
- internal enum SpecialPermissionSetFlag
- {
- // These also appear in clr/src/vm/permset.h
- Regular = 0,
- NoSet = 1,
- EmptySet = 2,
- SkipVerification = 3
- }
-
-#if FEATURE_SERIALIZATION
- [Serializable]
-#endif
- [System.Runtime.InteropServices.ComVisible(true)]
- public class PermissionSet : ISecurityEncodable, ICollection, IStackWalk
-#if FEATURE_SERIALIZATION
- , IDeserializationCallback
-#endif
- {
-#if _DEBUG
- internal static readonly bool debug;
-#endif
-
- [System.Diagnostics.Conditional( "_DEBUG" )]
- private static void DEBUG_WRITE(String str) {
- #if _DEBUG
- if (debug) Console.WriteLine(str);
- #endif
- }
-
- [System.Diagnostics.Conditional( "_DEBUG" )]
- private static void DEBUG_COND_WRITE(bool exp, String str)
- {
- #if _DEBUG
- if (debug && (exp)) Console.WriteLine(str);
- #endif
- }
-
- [System.Diagnostics.Conditional( "_DEBUG" )]
- private static void DEBUG_PRINTSTACK(Exception e)
- {
- #if _DEBUG
- if (debug) Console.WriteLine((e).StackTrace);
- #endif
- }
-
- // These members are accessed from EE using their hardcoded offset.
- // Please update the PermissionSetObject in object.h if you make any changes
- // to the fields here. !dumpobj will show the field layout
-
- // First the fields that are serialized x-appdomain (for perf reasons)
- private bool m_Unrestricted;
- [OptionalField(VersionAdded = 2)]
- private bool m_allPermissionsDecoded = false;
-
- [OptionalField(VersionAdded = 2)]
- internal TokenBasedSet m_permSet = null;
-
- // This is a workaround so that SQL can operate under default policy without actually
- // granting permissions in assemblies that they disallow.
-
- [OptionalField(VersionAdded = 2)]
- private bool m_ignoreTypeLoadFailures = false;
-
- // This field will be populated only for non X-AD scenarios where we create a XML-ised string of the PermissionSet
- [OptionalField(VersionAdded = 2)]
- private String m_serializedPermissionSet;
-
- [NonSerialized] private bool m_CheckedForNonCas;
- [NonSerialized] private bool m_ContainsCas;
- [NonSerialized] private bool m_ContainsNonCas;
-
- // only used during non X-AD serialization to save the m_permSet value (which we dont want serialized)
- [NonSerialized] private TokenBasedSet m_permSetSaved;
-
- // Following 4 fields are used only for serialization compat purposes: DO NOT USE THESE EVER!
-#pragma warning disable 169
- private bool readableonly;
- private TokenBasedSet m_unrestrictedPermSet;
- private TokenBasedSet m_normalPermSet;
-
- [OptionalField(VersionAdded = 2)]
- private bool m_canUnrestrictedOverride;
-#pragma warning restore 169
- // END: Serialization-only fields
-
- internal static readonly PermissionSet s_fullTrust = new PermissionSet( true );
-
-#if _DEBUG
- [OnSerialized]
- private void OnSerialized(StreamingContext context)
- {
- Debug.Assert(false, "PermissionSet does not support serialization on CoreCLR");
- }
-#endif // _DEBUG
-
- internal PermissionSet()
- {
- Reset();
- m_Unrestricted = true;
- }
-
- internal PermissionSet(bool fUnrestricted)
- : this()
- {
- SetUnrestricted(fUnrestricted);
- }
-
- public PermissionSet(PermissionState state)
- : this()
- {
- if (state == PermissionState.Unrestricted)
- {
- SetUnrestricted( true );
- }
- else if (state == PermissionState.None)
- {
- SetUnrestricted( false );
- }
- else
- {
- throw new ArgumentException(Environment.GetResourceString("Argument_InvalidPermissionState"));
- }
- }
-
- public PermissionSet(PermissionSet permSet)
- : this()
- {
- if (permSet == null)
- {
- Reset();
- return;
- }
-
- m_Unrestricted = permSet.m_Unrestricted;
- m_CheckedForNonCas = permSet.m_CheckedForNonCas;
- m_ContainsCas = permSet.m_ContainsCas;
- m_ContainsNonCas = permSet.m_ContainsNonCas;
- m_ignoreTypeLoadFailures = permSet.m_ignoreTypeLoadFailures;
-
- if (permSet.m_permSet != null)
- {
- m_permSet = new TokenBasedSet(permSet.m_permSet);
-
- // now deep copy all permissions in set
- for (int i = m_permSet.GetStartingIndex(); i <= m_permSet.GetMaxUsedIndex(); i++)
- {
- Object obj = m_permSet.GetItem(i);
- IPermission perm = obj as IPermission;
-
- if (perm != null)
- {
- m_permSet.SetItem(i, perm.Copy());
- }
- }
- }
- }
-
- public virtual void CopyTo(Array array, int index)
- {
- if (array == null)
- throw new ArgumentNullException( nameof(array) );
- Contract.EndContractBlock();
-
- PermissionSetEnumeratorInternal enumerator = new PermissionSetEnumeratorInternal(this);
-
- while (enumerator.MoveNext())
- {
- array.SetValue(enumerator.Current , index++ );
- }
- }
-
-
- // private constructor that doesn't create any token based sets
- private PermissionSet( Object trash, Object junk )
- {
- m_Unrestricted = false;
- }
-
-
- // Returns an object appropriate for synchronizing access to this
- // Array.
- public virtual Object SyncRoot
- { get { return this; } }
-
- // Is this Array synchronized (i.e., thread-safe)? If you want a synchronized
- // collection, you can use SyncRoot as an object to synchronize your
- // collection with. You could also call GetSynchronized()
- // to get a synchronized wrapper around the Array.
- public virtual bool IsSynchronized
- { get { return false; } }
-
- // Is this Collection ReadOnly?
- public virtual bool IsReadOnly
- { get {return false; } }
-
- // Reinitializes all state in PermissionSet - DO NOT null-out m_serializedPermissionSet
- internal void Reset()
- {
- m_Unrestricted = false;
- m_allPermissionsDecoded = true;
- m_permSet = null;
-
- m_ignoreTypeLoadFailures = false;
-
- m_CheckedForNonCas = false;
- m_ContainsCas = false;
- m_ContainsNonCas = false;
- m_permSetSaved = null;
-
-
- }
-
- internal void CheckSet()
- {
- if (this.m_permSet == null)
- this.m_permSet = new TokenBasedSet();
- }
-
- public bool IsEmpty()
- {
- if (m_Unrestricted)
- return false;
-
- if (m_permSet == null || m_permSet.FastIsEmpty())
- return true;
-
- PermissionSetEnumeratorInternal enumerator = new PermissionSetEnumeratorInternal(this);
-
- while (enumerator.MoveNext())
- {
- IPermission perm = (IPermission)enumerator.Current;
-
- if (!perm.IsSubsetOf( null ))
- {
- return false;
- }
- }
-
- return true;
- }
-
- internal bool FastIsEmpty()
- {
- if (m_Unrestricted)
- return false;
-
- if (m_permSet == null || m_permSet.FastIsEmpty())
- return true;
-
- return false;
- }
-
- public virtual int Count
- {
- get
- {
- int count = 0;
-
- if (m_permSet != null)
- count += m_permSet.GetCount();
-
- return count;
- }
- }
-
- internal IPermission GetPermission(int index)
- {
- if (m_permSet == null)
- return null;
- Object obj = m_permSet.GetItem( index );
- if (obj == null)
- return null;
- return obj as IPermission;
- }
-
- internal IPermission GetPermission(PermissionToken permToken)
- {
- if (permToken == null)
- return null;
-
- return GetPermission( permToken.m_index );
- }
-
- internal IPermission GetPermission( IPermission perm )
- {
- if (perm == null)
- return null;
-
- return GetPermission(PermissionToken.GetToken( perm ));
- }
-
- public IPermission SetPermission(IPermission perm)
- {
- return SetPermissionImpl(perm);
- }
-
- // SetPermission overwrites a permission in a permissionset.
- protected virtual IPermission SetPermissionImpl(IPermission perm)
- {
- // can't get token if perm is null
- if (perm == null)
- return null;
-
- PermissionToken permToken = PermissionToken.GetToken(perm);
-
- if ((permToken.m_type & PermissionTokenType.IUnrestricted) != 0)
- {
- // SetPermission Makes the Permission "Restricted"
- m_Unrestricted = false;
- }
-
- CheckSet();
-
- IPermission currPerm = GetPermission( permToken.m_index );
-
- m_CheckedForNonCas = false;
-
- // Should we copy here?
- m_permSet.SetItem( permToken.m_index, perm );
- return perm;
- }
-
- public IPermission AddPermission(IPermission perm)
- {
- return AddPermissionImpl(perm);
- }
-
- protected virtual IPermission AddPermissionImpl(IPermission perm)
- {
- // can't get token if perm is null
- if (perm == null)
- return null;
-
- m_CheckedForNonCas = false;
-
- // If the permission set is unrestricted, then return an unrestricted instance
- // of perm.
-
- PermissionToken permToken = PermissionToken.GetToken(perm);
-
- if (this.IsUnrestricted() && ((permToken.m_type & PermissionTokenType.IUnrestricted) != 0))
- {
- Type perm_type = perm.GetType();
- Object[] objs = new Object[1];
- objs[0] = PermissionState.Unrestricted;
- return (IPermission) Activator.CreateInstance(perm_type, BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public, null, objs, null );
- }
-
- CheckSet();
- IPermission currPerm = GetPermission(permToken.m_index);
-
- // If a Permission exists in this slot, then union it with perm
- // Otherwise, just add perm.
-
- if (currPerm != null) {
- IPermission ip_union = currPerm.Union(perm);
- m_permSet.SetItem( permToken.m_index, ip_union );
- return ip_union;
- } else {
- // Should we copy here?
- m_permSet.SetItem( permToken.m_index, perm );
- return perm;
- }
-
- }
-
- private IPermission RemovePermission( int index )
- {
- IPermission perm = GetPermission(index);
- if (perm == null)
- return null;
- return (IPermission)m_permSet.RemoveItem( index ); // this cast is safe because the call to GetPermission will guarantee it is an IPermission
- }
-
- // Make this internal soon.
- internal void SetUnrestricted(bool unrestricted)
- {
- m_Unrestricted = unrestricted;
- if (unrestricted)
- {
- // if this is to be an unrestricted permset, null the m_permSet member
- m_permSet = null;
- }
- }
-
- public bool IsUnrestricted()
- {
- return m_Unrestricted;
- }
-
- internal enum IsSubsetOfType
- {
- Normal,
- CheckDemand,
- CheckPermitOnly,
- CheckAssertion,
- }
-
- internal bool IsSubsetOfHelper(PermissionSet target, IsSubsetOfType type, out IPermission firstPermThatFailed, bool ignoreNonCas)
- {
- #if _DEBUG
- if (debug)
- DEBUG_WRITE("IsSubsetOf\n" +
- "Other:\n" +
- (target == null ? "<null>" : target.ToString()) +
- "\nMe:\n" +
- ToString());
- #endif
-
- firstPermThatFailed = null;
- if (target == null || target.FastIsEmpty())
- {
- if(this.IsEmpty())
- return true;
- else
- {
- firstPermThatFailed = GetFirstPerm();
- return false;
- }
- }
- else if (this.IsUnrestricted() && !target.IsUnrestricted())
- return false;
- else if (this.m_permSet == null)
- return true;
- else
- {
- target.CheckSet();
-
- for (int i = m_permSet.GetStartingIndex(); i <= this.m_permSet.GetMaxUsedIndex(); ++i)
- {
- IPermission thisPerm = this.GetPermission(i);
- if (thisPerm == null || thisPerm.IsSubsetOf(null))
- continue;
-
- IPermission targetPerm = target.GetPermission(i);
-#if _DEBUG
- PermissionToken token = (PermissionToken)PermissionToken.s_tokenSet.GetItem( i );
- Debug.Assert(targetPerm == null || (token.m_type & PermissionTokenType.DontKnow) == 0, "Token not properly initialized");
-#endif
-
- if (target.m_Unrestricted)
- continue;
-
- // targetPerm can be null here, but that is fine since it thisPerm is a subset
- // of empty/null then we can continue in the loop.
- CodeAccessPermission cap = thisPerm as CodeAccessPermission;
- if(cap == null)
- {
- if (!ignoreNonCas && !thisPerm.IsSubsetOf( targetPerm ))
- {
- firstPermThatFailed = thisPerm;
- return false;
- }
- }
- else
- {
- firstPermThatFailed = thisPerm;
- switch(type)
- {
- case IsSubsetOfType.Normal:
- if (!thisPerm.IsSubsetOf( targetPerm ))
- return false;
- break;
- case IsSubsetOfType.CheckDemand:
- if (!cap.CheckDemand( (CodeAccessPermission)targetPerm ))
- return false;
- break;
- case IsSubsetOfType.CheckPermitOnly:
- if (!cap.CheckPermitOnly( (CodeAccessPermission)targetPerm ))
- return false;
- break;
- case IsSubsetOfType.CheckAssertion:
- if (!cap.CheckAssert( (CodeAccessPermission)targetPerm ))
- return false;
- break;
- }
- firstPermThatFailed = null;
- }
- }
- }
-
- return true;
- }
-
- public bool IsSubsetOf(PermissionSet target)
- {
- IPermission perm;
- return IsSubsetOfHelper(target, IsSubsetOfType.Normal, out perm, false);
- }
-
- internal bool CheckDemand(PermissionSet target, out IPermission firstPermThatFailed)
- {
- return IsSubsetOfHelper(target, IsSubsetOfType.CheckDemand, out firstPermThatFailed, true);
- }
-
- internal bool CheckPermitOnly(PermissionSet target, out IPermission firstPermThatFailed)
- {
- return IsSubsetOfHelper(target, IsSubsetOfType.CheckPermitOnly, out firstPermThatFailed, true);
- }
-
- internal bool CheckAssertion(PermissionSet target)
- {
- IPermission perm;
- return IsSubsetOfHelper(target, IsSubsetOfType.CheckAssertion, out perm, true);
- }
-
- internal bool CheckDeny(PermissionSet deniedSet, out IPermission firstPermThatFailed)
- {
- firstPermThatFailed = null;
- if (deniedSet == null || deniedSet.FastIsEmpty() || this.FastIsEmpty())
- return true;
-
- if(this.m_Unrestricted && deniedSet.m_Unrestricted)
- return false;
-
- CodeAccessPermission permThis, permThat;
- PermissionSetEnumeratorInternal enumThis = new PermissionSetEnumeratorInternal(this);
-
- while (enumThis.MoveNext())
- {
- permThis = enumThis.Current as CodeAccessPermission;
- if(permThis == null || permThis.IsSubsetOf(null))
- continue; // ignore non-CAS permissions in the grant set.
- if (deniedSet.m_Unrestricted)
- {
- firstPermThatFailed = permThis;
- return false;
- }
- permThat = (CodeAccessPermission)deniedSet.GetPermission(enumThis.GetCurrentIndex());
- if (!permThis.CheckDeny(permThat))
- {
- firstPermThatFailed = permThis;
- return false;
- }
- }
- if(this.m_Unrestricted)
- {
- PermissionSetEnumeratorInternal enumThat = new PermissionSetEnumeratorInternal(deniedSet);
- while (enumThat.MoveNext())
- {
- if(enumThat.Current is IPermission)
- return false;
- }
- }
- return true;
- }
-
- internal void CheckDecoded( CodeAccessPermission demandedPerm, PermissionToken tokenDemandedPerm )
- {
- Debug.Assert( demandedPerm != null, "Expected non-null value" );
-
- if (this.m_allPermissionsDecoded || this.m_permSet == null)
- return;
-
- if (tokenDemandedPerm == null)
- tokenDemandedPerm = PermissionToken.GetToken( demandedPerm );
-
- Debug.Assert( tokenDemandedPerm != null, "Unable to find token for demanded permission" );
-
- CheckDecoded( tokenDemandedPerm.m_index );
- }
-
- internal void CheckDecoded( int index )
- {
- if (this.m_allPermissionsDecoded || this.m_permSet == null)
- return;
-
- GetPermission(index);
- }
-
- internal void CheckDecoded(PermissionSet demandedSet)
- {
- Debug.Assert(demandedSet != null, "Expected non-null value");
-
- if (this.m_allPermissionsDecoded || this.m_permSet == null)
- return;
-
- PermissionSetEnumeratorInternal enumerator = demandedSet.GetEnumeratorInternal();
-
- while (enumerator.MoveNext())
- {
- CheckDecoded(enumerator.GetCurrentIndex());
- }
- }
-
- internal void InplaceIntersect( PermissionSet other )
- {
- Exception savedException = null;
-
- m_CheckedForNonCas = false;
-
- if (this == other)
- return;
-
- if (other == null || other.FastIsEmpty())
- {
- // If the other is empty or null, make this empty.
- Reset();
- return;
- }
-
- if (this.FastIsEmpty())
- return;
-
- int maxMax = this.m_permSet == null ? -1 : this.m_permSet.GetMaxUsedIndex();
- int otherMax = other.m_permSet == null ? -1 : other.m_permSet.GetMaxUsedIndex();
-
- if (this.IsUnrestricted() && maxMax < otherMax)
- {
- maxMax = otherMax;
- this.CheckSet();
- }
-
- if (other.IsUnrestricted())
- {
- other.CheckSet();
- }
-
- for (int i = 0; i <= maxMax; ++i)
- {
- Object thisObj = this.m_permSet.GetItem( i );
- IPermission thisPerm = thisObj as IPermission;
-
- Object otherObj = other.m_permSet.GetItem( i );
- IPermission otherPerm = otherObj as IPermission;
-
- if (thisObj == null && otherObj == null)
- continue;
-
- if (thisObj == null)
- {
- // There is no object in <this>, so intersection is empty except for IUnrestrictedPermissions
- if (this.IsUnrestricted())
- {
- {
- PermissionToken token = (PermissionToken)PermissionToken.s_tokenSet.GetItem( i );
- if ((token.m_type & PermissionTokenType.IUnrestricted) != 0)
- {
- this.m_permSet.SetItem( i, otherPerm.Copy() );
- Debug.Assert( PermissionToken.s_tokenSet.GetItem( i ) != null, "PermissionToken should already be assigned" );
- }
- }
- }
- }
- else if (otherObj == null)
- {
- if (other.IsUnrestricted())
- {
- {
- PermissionToken token = (PermissionToken)PermissionToken.s_tokenSet.GetItem( i );
- if ((token.m_type & PermissionTokenType.IUnrestricted) == 0)
- this.m_permSet.SetItem( i, null );
- }
- }
- else
- {
- this.m_permSet.SetItem( i, null );
- }
- }
- else
- {
- try
- {
- IPermission intersectPerm;
- if (thisPerm == null)
- intersectPerm = otherPerm;
- else if(otherPerm == null)
- intersectPerm = thisPerm;
- else
- intersectPerm = thisPerm.Intersect( otherPerm );
- this.m_permSet.SetItem( i, intersectPerm );
- }
- catch (Exception e)
- {
- if (savedException == null)
- savedException = e;
- }
- }
- }
-
- this.m_Unrestricted = this.m_Unrestricted && other.m_Unrestricted;
-
- if (savedException != null)
- throw savedException;
- }
-
- public PermissionSet Intersect(PermissionSet other)
- {
- if (other == null || other.FastIsEmpty() || this.FastIsEmpty())
- {
- return null;
- }
-
- int thisMax = this.m_permSet == null ? -1 : this.m_permSet.GetMaxUsedIndex();
- int otherMax = other.m_permSet == null ? -1 : other.m_permSet.GetMaxUsedIndex();
- int minMax = thisMax < otherMax ? thisMax : otherMax;
-
- if (this.IsUnrestricted() && minMax < otherMax)
- {
- minMax = otherMax;
- this.CheckSet();
- }
-
- if (other.IsUnrestricted() && minMax < thisMax)
- {
- minMax = thisMax;
- other.CheckSet();
- }
-
- PermissionSet pset = new PermissionSet( false );
-
- if (minMax > -1)
- {
- pset.m_permSet = new TokenBasedSet();
- }
-
- for (int i = 0; i <= minMax; ++i)
- {
- Object thisObj = this.m_permSet.GetItem( i );
- IPermission thisPerm = thisObj as IPermission;
- Object otherObj = other.m_permSet.GetItem( i );
- IPermission otherPerm = otherObj as IPermission;
-
- if (thisObj == null && otherObj == null)
- continue;
-
- if (thisObj == null)
- {
- if (this.m_Unrestricted)
- {
- 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() );
- Debug.Assert( PermissionToken.s_tokenSet.GetItem( i ) != null, "PermissionToken should already be assigned" );
- }
- }
- }
- }
- else if (otherObj == null)
- {
- if (other.m_Unrestricted)
- {
- 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() );
- Debug.Assert( PermissionToken.s_tokenSet.GetItem( i ) != null, "PermissionToken should already be assigned" );
- }
- }
- }
- }
- else
- {
- IPermission intersectPerm;
- if (thisPerm == null)
- intersectPerm = otherPerm;
- else if(otherPerm == null)
- intersectPerm = thisPerm;
- else
- intersectPerm = thisPerm.Intersect( otherPerm );
- pset.m_permSet.SetItem( i, intersectPerm );
- Debug.Assert( intersectPerm == null || PermissionToken.s_tokenSet.GetItem( i ) != null, "PermissionToken should already be assigned" );
- }
- }
-
- pset.m_Unrestricted = this.m_Unrestricted && other.m_Unrestricted;
- if (pset.FastIsEmpty())
- return null;
- else
- return pset;
- }
-
- internal void InplaceUnion( PermissionSet other )
- {
- // Unions the "other" PermissionSet into this one. It can be optimized to do less copies than
- // need be done by the traditional union (and we don't have to create a new PermissionSet).
-
- if (this == other)
- return;
-
- // Quick out conditions, union doesn't change this PermissionSet
- if (other == null || other.FastIsEmpty())
- return;
-
- m_CheckedForNonCas = false;
-
- this.m_Unrestricted = this.m_Unrestricted || other.m_Unrestricted;
-
- if (this.m_Unrestricted)
- {
- // if the result of Union is unrestricted permset, null the m_permSet member
- this.m_permSet = null;
- return;
- }
-
-
- // If we reach here, result of Union is not unrestricted
- // We have to union "normal" permission no matter what now.
- int maxMax = -1;
- if (other.m_permSet != null)
- {
- maxMax = other.m_permSet.GetMaxUsedIndex();
- this.CheckSet();
- }
- // Save exceptions until the end
- Exception savedException = null;
-
- for (int i = 0; i <= maxMax; ++i)
- {
- Object thisObj = this.m_permSet.GetItem( i );
- IPermission thisPerm = thisObj as IPermission;
-
- Object otherObj = other.m_permSet.GetItem( i );
- IPermission otherPerm = otherObj as IPermission;
-
- if (thisObj == null && otherObj == null)
- continue;
-
- if (thisObj == null)
- {
- if (otherPerm != null)
- {
- PermissionToken token = (PermissionToken)PermissionToken.s_tokenSet.GetItem( i );
- if (((token.m_type & PermissionTokenType.IUnrestricted) == 0) || !this.m_Unrestricted)
- {
- this.m_permSet.SetItem( i, otherPerm.Copy() );
- }
- }
- }
- else if (otherObj == null)
- {
- continue;
- }
- else
- {
- try
- {
- IPermission unionPerm;
- if(thisPerm == null)
- unionPerm = otherPerm;
- else if(otherPerm == null)
- unionPerm = thisPerm;
- else
- unionPerm = thisPerm.Union( otherPerm );
- this.m_permSet.SetItem( i, unionPerm );
- }
- catch (Exception e)
- {
- if (savedException == null)
- savedException = e;
- }
- }
- }
-
- if (savedException != null)
- throw savedException;
- }
-
- public PermissionSet Union(PermissionSet other)
- {
- // if other is null or empty, return a clone of myself
- if (other == null || other.FastIsEmpty())
- {
- return this.Copy();
- }
-
- if (this.FastIsEmpty())
- {
- return other.Copy();
- }
-
- int maxMax = -1;
-
- PermissionSet pset = new PermissionSet();
- pset.m_Unrestricted = this.m_Unrestricted || other.m_Unrestricted;
- if (pset.m_Unrestricted)
- {
- // if the result of Union is unrestricted permset, just return
- return pset;
- }
-
- // degenerate case where we look at both this.m_permSet and other.m_permSet
- this.CheckSet();
- other.CheckSet();
- maxMax = this.m_permSet.GetMaxUsedIndex() > other.m_permSet.GetMaxUsedIndex() ? this.m_permSet.GetMaxUsedIndex() : other.m_permSet.GetMaxUsedIndex();
- pset.m_permSet = new TokenBasedSet();
-
-
-
- for (int i = 0; i <= maxMax; ++i)
- {
- Object thisObj = this.m_permSet.GetItem( i );
- IPermission thisPerm = thisObj as IPermission;
-
- Object otherObj = other.m_permSet.GetItem( i );
- IPermission otherPerm = otherObj as IPermission;
-
- if (thisObj == null && otherObj == null)
- continue;
-
- if (thisObj == null)
- {
- 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() );
- Debug.Assert( PermissionToken.s_tokenSet.GetItem( i ) != null, "PermissionToken should already be assigned" );
- }
- }
- }
- else if (otherObj == null)
- {
- 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() );
- Debug.Assert( PermissionToken.s_tokenSet.GetItem( i ) != null, "PermissionToken should already be assigned" );
- }
- }
- }
- else
- {
- IPermission unionPerm;
- if(thisPerm == null)
- unionPerm = otherPerm;
- else if(otherPerm == null)
- unionPerm = thisPerm;
- else
- unionPerm = thisPerm.Union( otherPerm );
- pset.m_permSet.SetItem( i, unionPerm );
- Debug.Assert( unionPerm == null || PermissionToken.s_tokenSet.GetItem( i ) != null, "PermissionToken should already be assigned" );
- }
- }
-
- return pset;
- }
-
- // Treating the current permission set as a grant set, and the input set as
- // a set of permissions to be denied, try to cancel out as many permissions
- // from both sets as possible. For a first cut, any granted permission that
- // is a safe subset of the corresponding denied permission can result in
- // that permission being removed from both sides.
-
- internal void MergeDeniedSet(PermissionSet denied)
- {
- if (denied == null || denied.FastIsEmpty() || this.FastIsEmpty())
- return;
-
- m_CheckedForNonCas = false;
-
- // Check for the unrestricted case: FastIsEmpty() will return false if the PSet is unrestricted, but has no items
- if (this.m_permSet == null || denied.m_permSet == null)
- return; //nothing can be removed
-
- int maxIndex = denied.m_permSet.GetMaxUsedIndex() > this.m_permSet.GetMaxUsedIndex() ? this.m_permSet.GetMaxUsedIndex() : denied.m_permSet.GetMaxUsedIndex();
- for (int i = 0; i <= maxIndex; ++i) {
- IPermission deniedPerm = denied.m_permSet.GetItem(i) as IPermission;
- if (deniedPerm == null)
- continue;
-
- IPermission thisPerm = this.m_permSet.GetItem(i) as IPermission;
-
- if (thisPerm == null && !this.m_Unrestricted) {
- denied.m_permSet.SetItem(i, null);
- continue;
- }
-
- if (thisPerm != null && deniedPerm != null) {
- if (thisPerm.IsSubsetOf(deniedPerm)) {
- this.m_permSet.SetItem(i, null);
- denied.m_permSet.SetItem(i, null);
- }
- }
- }
- }
-
- // Returns true if perm is contained in this
- internal bool Contains(IPermission perm)
- {
- if (perm == null)
- return true;
- if (m_Unrestricted)
- return true;
- if (FastIsEmpty())
- return false;
-
- PermissionToken token = PermissionToken.GetToken(perm);
- Object thisObj = this.m_permSet.GetItem( token.m_index );
- if (thisObj == null)
- return perm.IsSubsetOf( null );
-
- IPermission thisPerm = GetPermission(token.m_index);
- if (thisPerm != null)
- return perm.IsSubsetOf( thisPerm );
- else
- return perm.IsSubsetOf( null );
- }
-
- [System.Runtime.InteropServices.ComVisible(false)]
- public override bool Equals( Object obj )
- {
- // Note: this method is designed to accept both PermissionSet and NamedPermissionSets.
- // It will compare them based on the values in the base type, thereby ignoring the
- // name and description of the named permission set.
-
- PermissionSet other = obj as PermissionSet;
-
- if (other == null)
- return false;
-
- if (this.m_Unrestricted != other.m_Unrestricted)
- return false;
-
- CheckSet();
- other.CheckSet();
-
- DecodeAllPermissions();
- other.DecodeAllPermissions();
-
- int maxIndex = Math.Max( this.m_permSet.GetMaxUsedIndex(), other.m_permSet.GetMaxUsedIndex() );
-
- for (int i = 0; i <= maxIndex; ++i)
- {
- IPermission thisPerm = (IPermission)this.m_permSet.GetItem( i );
- IPermission otherPerm = (IPermission)other.m_permSet.GetItem( i );
-
- if (thisPerm == null && otherPerm == null)
- {
- continue;
- }
- else if (thisPerm == null)
- {
- if (!otherPerm.IsSubsetOf( null ))
- return false;
- }
- else if (otherPerm == null)
- {
- if (!thisPerm.IsSubsetOf( null ))
- return false;
- }
- else
- {
- if (!thisPerm.Equals( otherPerm ))
- return false;
- }
- }
-
- return true;
- }
-
- [System.Runtime.InteropServices.ComVisible(false)]
- public override int GetHashCode()
- {
- int accumulator;
-
- accumulator = this.m_Unrestricted ? -1 : 0;
-
- if (this.m_permSet != null)
- {
- DecodeAllPermissions();
-
- int maxIndex = this.m_permSet.GetMaxUsedIndex();
-
- for (int i = m_permSet.GetStartingIndex(); i <= maxIndex; ++i)
- {
- IPermission perm = (IPermission)this.m_permSet.GetItem( i );
- if (perm != null)
- {
- accumulator = accumulator ^ perm.GetHashCode();
- }
- }
- }
-
- return accumulator;
- }
-
- // 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).
- [DynamicSecurityMethodAttribute()]
- [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
- public void Demand()
- {
- if (this.FastIsEmpty())
- return; // demanding the empty set always passes.
-
- ContainsNonCodeAccessPermissions();
-
- if (m_ContainsCas)
- {
- StackCrawlMark stackMark = StackCrawlMark.LookForMyCallersCaller;
- CodeAccessSecurityEngine.Check(GetCasOnlySet(), ref stackMark);
- }
- if (m_ContainsNonCas)
- {
- DemandNonCAS();
- }
- }
-
- internal void DemandNonCAS()
- {
- ContainsNonCodeAccessPermissions();
-
- if (m_ContainsNonCas)
- {
- if (this.m_permSet != null)
- {
- CheckSet();
- for (int i = m_permSet.GetStartingIndex(); i <= this.m_permSet.GetMaxUsedIndex(); ++i)
- {
- IPermission currPerm = GetPermission(i);
- if (currPerm != null && !(currPerm is CodeAccessPermission))
- currPerm.Demand();
- }
- }
- }
- }
-
- // Metadata for this method should be flaged with REQ_SQ so that
- // EE can allocate space on the stack frame for FrameSecurityDescriptor
-
- [DynamicSecurityMethodAttribute()]
- [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
- public void Assert()
- {
- StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
- SecurityRuntime.Assert(this, ref stackMark);
- }
-
- // Metadata for this method should be flaged with REQ_SQ so that
- // EE can allocate space on the stack frame for FrameSecurityDescriptor
-
- [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.")]
- public void Deny()
- {
- StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
- SecurityRuntime.Deny(this, ref stackMark);
- }
-
- // Metadata for this method should be flaged with REQ_SQ so that
- // EE can allocate space on the stack frame for FrameSecurityDescriptor
-
- [DynamicSecurityMethodAttribute()]
- [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
- public void PermitOnly()
- {
- StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
- SecurityRuntime.PermitOnly(this, ref stackMark);
- }
-
- internal IPermission GetFirstPerm()
- {
- IEnumerator enumerator = GetEnumerator();
- if(!enumerator.MoveNext())
- return null;
- return enumerator.Current as IPermission;
- }
-
- // Returns a deep copy
- public virtual PermissionSet Copy()
- {
- return new PermissionSet(this);
- }
-
- internal PermissionSet CopyWithNoIdentityPermissions()
- {
- // 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.
- return new PermissionSet(this);
- }
-
- public IEnumerator GetEnumerator()
- {
- return GetEnumeratorImpl();
- }
-
- protected virtual IEnumerator GetEnumeratorImpl()
- {
- return new PermissionSetEnumerator(this);
- }
-
- internal PermissionSetEnumeratorInternal GetEnumeratorInternal()
- {
- return new PermissionSetEnumeratorInternal(this);
- }
-
- private void NormalizePermissionSet()
- {
- // This function guarantees that all the permissions are placed at
- // the proper index within the token based sets. This becomes necessary
- // since these indices are dynamically allocated based on usage order.
-
- PermissionSet permSetTemp = new PermissionSet(false);
-
- permSetTemp.m_Unrestricted = this.m_Unrestricted;
-
- // Move all the normal permissions to the new permission set
-
- if (this.m_permSet != null)
- {
- for (int i = m_permSet.GetStartingIndex(); i <= this.m_permSet.GetMaxUsedIndex(); ++i)
- {
- Object obj = this.m_permSet.GetItem(i);
- IPermission perm = obj as IPermission;
- if (perm != null)
- permSetTemp.SetPermission( perm );
- }
- }
-
- this.m_permSet = permSetTemp.m_permSet;
- }
-
- private void DecodeAllPermissions()
- {
- if (m_permSet == null)
- {
- m_allPermissionsDecoded = true;
- return;
- }
-
- int maxIndex = m_permSet.GetMaxUsedIndex();
- for (int i = 0; i <= maxIndex; ++i)
- {
- // GetPermission has the side-effect of decoding the permission in the slot
- GetPermission(i);
- }
-
- m_allPermissionsDecoded = true;
- }
-
- internal void FilterHostProtectionPermissions(HostProtectionResource fullTrustOnly, HostProtectionResource inaccessible)
- {
- HostProtectionPermission.protectedResources = fullTrustOnly;
- HostProtectionPermission hpp = (HostProtectionPermission)GetPermission(HostProtectionPermission.GetTokenIndex());
- if(hpp == null)
- return;
-
- HostProtectionPermission newHpp = (HostProtectionPermission)hpp.Intersect(new HostProtectionPermission(fullTrustOnly));
- if (newHpp == null)
- {
- RemovePermission(HostProtectionPermission.GetTokenIndex());
- }
- else if (newHpp.Resources != hpp.Resources)
- {
- SetPermission(newHpp);
- }
- }
-
- // Determines whether the permission set contains any non-code access
- // security permissions.
- public bool ContainsNonCodeAccessPermissions()
- {
- if (m_CheckedForNonCas)
- return m_ContainsNonCas;
-
- lock (this)
- {
- if (m_CheckedForNonCas)
- return m_ContainsNonCas;
-
- m_ContainsCas = false;
- m_ContainsNonCas = false;
-
- if (IsUnrestricted())
- m_ContainsCas = true;
-
- if (this.m_permSet != null)
- {
- PermissionSetEnumeratorInternal enumerator = new PermissionSetEnumeratorInternal(this);
-
- while (enumerator.MoveNext() && (!m_ContainsCas || !m_ContainsNonCas))
- {
- IPermission perm = enumerator.Current as IPermission;
-
- if (perm != null)
- {
- if (perm is CodeAccessPermission)
- m_ContainsCas = true;
- else
- m_ContainsNonCas = true;
- }
- }
- }
-
- m_CheckedForNonCas = true;
- }
-
- return m_ContainsNonCas;
- }
-
- // Returns a permission set containing only CAS-permissions. If possible
- // this is just the input set, otherwise a new set is allocated.
- private PermissionSet GetCasOnlySet()
- {
- if (!m_ContainsNonCas)
- return this;
-
- if (IsUnrestricted())
- return this;
-
- PermissionSet pset = new PermissionSet(false);
-
- PermissionSetEnumeratorInternal enumerator = new PermissionSetEnumeratorInternal(this);
-
- while (enumerator.MoveNext())
- {
- IPermission perm = (IPermission)enumerator.Current;
-
- if (perm is CodeAccessPermission)
- pset.AddPermission(perm);
- }
-
- pset.m_CheckedForNonCas = true;
- pset.m_ContainsCas = !pset.IsEmpty();
- pset.m_ContainsNonCas = false;
-
- return pset;
- }
-
- // 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)
- {
- Debug.Assert(casPset == null || !casPset.IsReadOnly);
- Debug.Assert(nonCasPset == null || !nonCasPset.IsReadOnly);
-
- if (perm == null)
- return;
-
- if (!separateCasFromNonCas || perm is CodeAccessPermission)
- {
- if(casPset == null)
- casPset = new PermissionSet(false);
- IPermission oldPerm = casPset.GetPermission(perm);
- IPermission unionPerm = casPset.AddPermission(perm);
- if (oldPerm != null && !oldPerm.IsSubsetOf( unionPerm ))
- throw new NotSupportedException( Environment.GetResourceString( "NotSupported_DeclarativeUnion" ) );
- }
- else
- {
- if(nonCasPset == null)
- nonCasPset = new PermissionSet(false);
- IPermission oldPerm = nonCasPset.GetPermission(perm);
- IPermission unionPerm = nonCasPset.AddPermission( perm );
- if (oldPerm != null && !oldPerm.IsSubsetOf( unionPerm ))
- throw new NotSupportedException( Environment.GetResourceString( "NotSupported_DeclarativeUnion" ) );
- }
- }
-
- // Converts an array of SecurityAttributes to a PermissionSet
- private static byte[] CreateSerialized(Object[] attrs,
- bool serialize,
- ref byte[] nonCasBlob,
- out PermissionSet casPset,
- HostProtectionResource fullTrustOnlyResources,
- bool allowEmptyPermissionSets)
- {
- // Create two new (empty) sets.
- casPset = null;
- PermissionSet nonCasPset = null;
-
- // Most security attributes generate a single permission. The
- // PermissionSetAttribute class generates an entire permission set we
- // need to merge, however.
- for (int i = 0; i < attrs.Length; i++)
- {
-#pragma warning disable 618
- 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)
- {
- PermissionSet pset = ((PermissionSetAttribute)attrs[i]).CreatePermissionSet();
- if (pset == null)
- throw new ArgumentException( Environment.GetResourceString( "Argument_UnableToGeneratePermissionSet" ) );
-
- PermissionSetEnumeratorInternal enumerator = new PermissionSetEnumeratorInternal(pset);
-
- while (enumerator.MoveNext())
- {
- IPermission perm = (IPermission)enumerator.Current;
- MergePermission(perm, serialize, ref casPset, ref nonCasPset);
- }
-
- if(casPset == null)
- casPset = new PermissionSet(false);
- if (pset.IsUnrestricted())
- casPset.SetUnrestricted(true);
- }
- else
- {
-#pragma warning disable 618
- IPermission perm = ((SecurityAttribute)attrs[i]).CreatePermission();
-#pragma warning restore 618
- MergePermission(perm, serialize, ref casPset, ref nonCasPset);
- }
- }
- 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
- // declarative permission sets being NULL if they do not exist. When filtering the permission
- // set if we end up with an empty set, we can the permission set NULL rather than returning the
- // empty set in order to enable those optimizations.
- //
-
- if(casPset != null)
- {
- casPset.FilterHostProtectionPermissions(fullTrustOnlyResources, HostProtectionResource.None);
- casPset.ContainsNonCodeAccessPermissions(); // make sure all declarative PermissionSets are checked for non-CAS so we can just check the flag from native code
- if (allowEmptyPermissionSets && casPset.IsEmpty())
- casPset = null;
- }
- if(nonCasPset != null)
- {
- nonCasPset.FilterHostProtectionPermissions(fullTrustOnlyResources, HostProtectionResource.None);
- nonCasPset.ContainsNonCodeAccessPermissions(); // make sure all declarative PermissionSets are checked for non-CAS so we can just check the flag from native code
- if (allowEmptyPermissionSets && nonCasPset.IsEmpty())
- nonCasPset = null;
- }
-
- Debug.Assert(!serialize, "Cannot serialize permission sets on CoreCLR");
- return null;
- }
-
-#if FEATURE_SERIALIZATION
- /// <internalonly/>
- void IDeserializationCallback.OnDeserialization(Object sender)
- {
- NormalizePermissionSet();
- m_CheckedForNonCas = false;
- }
-#endif
-
- [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
- public static void RevertAssert()
- {
- StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
- SecurityRuntime.RevertAssert(ref stackMark);
- }
-
- internal static PermissionSet RemoveRefusedPermissionSet(PermissionSet assertSet, PermissionSet refusedSet, out bool bFailedToCompress)
- {
- Debug.Assert((assertSet == null || !assertSet.IsUnrestricted()), "Cannot be unrestricted here");
- PermissionSet retPs = null;
- bFailedToCompress = false;
- if (assertSet == null)
- return null;
- if (refusedSet != null)
- {
- if (refusedSet.IsUnrestricted())
- return null; // we're refusing everything...cannot assert anything now.
-
- PermissionSetEnumeratorInternal enumerator = new PermissionSetEnumeratorInternal(refusedSet);
- while (enumerator.MoveNext())
- {
- CodeAccessPermission refusedPerm = (CodeAccessPermission)enumerator.Current;
- int i = enumerator.GetCurrentIndex();
- if (refusedPerm != null)
- {
- CodeAccessPermission perm
- = (CodeAccessPermission)assertSet.GetPermission(i);
- try
- {
- if (refusedPerm.Intersect(perm) != null)
- {
- if (refusedPerm.Equals(perm))
- {
- if (retPs == null)
- retPs = assertSet.Copy();
-
- retPs.RemovePermission(i);
- }
- else
- {
- // Asserting a permission, part of which is already denied/refused
- // cannot compress this assert
- bFailedToCompress = true;
- return assertSet;
- }
- }
- }
- catch (ArgumentException)
- {
- // Any exception during removing a refused set from assert set => we play it safe and not assert that perm
- if (retPs == null)
- retPs = assertSet.Copy();
- retPs.RemovePermission(i);
- }
- }
- }
- }
- if (retPs != null)
- return retPs;
- return assertSet;
- }
-
- internal static void RemoveAssertedPermissionSet(PermissionSet demandSet, PermissionSet assertSet, out PermissionSet alteredDemandSet)
- {
- Debug.Assert(!assertSet.IsUnrestricted(), "Cannot call this function if assertSet is unrestricted");
- alteredDemandSet = null;
-
- PermissionSetEnumeratorInternal enumerator = new PermissionSetEnumeratorInternal(demandSet);
- while (enumerator.MoveNext())
- {
- CodeAccessPermission demandDerm = (CodeAccessPermission)enumerator.Current;
- int i = enumerator.GetCurrentIndex();
- if (demandDerm != null)
- {
- CodeAccessPermission assertPerm
- = (CodeAccessPermission)assertSet.GetPermission(i);
- try
- {
- if (demandDerm.CheckAssert(assertPerm))
- {
- if (alteredDemandSet == null)
- alteredDemandSet = demandSet.Copy();
-
- alteredDemandSet.RemovePermission(i);
- }
- }
- catch (ArgumentException)
- {
- }
- }
- }
- return;
- }
-
- internal static bool IsIntersectingAssertedPermissions(PermissionSet assertSet1, PermissionSet assertSet2)
- {
- bool isIntersecting = false;
- if (assertSet1 != null && assertSet2 != null)
- {
- PermissionSetEnumeratorInternal enumerator = new PermissionSetEnumeratorInternal(assertSet2);
- while (enumerator.MoveNext())
- {
- CodeAccessPermission perm2 = (CodeAccessPermission)enumerator.Current;
- int i = enumerator.GetCurrentIndex();
- if (perm2 != null)
- {
- CodeAccessPermission perm1
- = (CodeAccessPermission)assertSet1.GetPermission(i);
- try
- {
- if (perm1 != null && !perm1.Equals(perm2))
- {
- isIntersecting = true; // Same type of permission, but with different flags or something - cannot union them
- }
- }
- catch (ArgumentException)
- {
- isIntersecting = true; //assume worst case
- }
- }
- }
- }
- return isIntersecting;
-
- }
-
- // This is a workaround so that SQL can operate under default policy without actually
- // granting permissions in assemblies that they disallow.
-
- internal bool IgnoreTypeLoadFailures
- {
- set { m_ignoreTypeLoadFailures = value; }
- }
- }
-}
diff --git a/src/mscorlib/src/System/Security/PermissionSetEnumerator.cs b/src/mscorlib/src/System/Security/PermissionSetEnumerator.cs
deleted file mode 100644
index 7b234e9cf4..0000000000
--- a/src/mscorlib/src/System/Security/PermissionSetEnumerator.cs
+++ /dev/null
@@ -1,89 +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.Security
-{
- //PermissionSetEnumerator.cs
-
- using System;
- using System.Collections;
- using TokenBasedSetEnumerator = System.Security.Util.TokenBasedSetEnumerator;
- using TokenBasedSet = System.Security.Util.TokenBasedSet;
-
- internal class PermissionSetEnumerator : IEnumerator
- {
- PermissionSetEnumeratorInternal enm;
-
- public Object Current
- {
- get
- {
- return enm.Current;
- }
- }
-
- public bool MoveNext()
- {
- return enm.MoveNext();
- }
-
- public void Reset()
- {
- enm.Reset();
- }
-
- internal PermissionSetEnumerator(PermissionSet permSet)
- {
- enm = new PermissionSetEnumeratorInternal(permSet);
- }
- }
-
- internal struct PermissionSetEnumeratorInternal
- {
- private PermissionSet m_permSet;
- private TokenBasedSetEnumerator enm;
-
- public Object Current
- {
- get
- {
- return enm.Current;
- }
- }
-
- internal PermissionSetEnumeratorInternal(PermissionSet permSet)
- {
- m_permSet = permSet;
- enm = new TokenBasedSetEnumerator(permSet.m_permSet);
- }
-
- public int GetCurrentIndex()
- {
- return enm.Index;
- }
-
- public void Reset()
- {
- enm.Reset();
- }
-
- public bool MoveNext()
- {
- while (enm.MoveNext())
- {
- Object obj = enm.Current;
- IPermission perm = obj as IPermission;
- if (perm != null)
- {
- enm.Current = perm;
- return true;
- }
- }
- return false;
- }
- }
-}
-
diff --git a/src/mscorlib/src/System/Security/PermissionSetTriple.cs b/src/mscorlib/src/System/Security/PermissionSetTriple.cs
deleted file mode 100644
index 56eb22996e..0000000000
--- a/src/mscorlib/src/System/Security/PermissionSetTriple.cs
+++ /dev/null
@@ -1,270 +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: Container class for holding an AppDomain's Grantset and Refused sets.
-** Also used for CompressedStacks which brings in the third PermissionSet.
-** Hence, the name PermissionSetTriple.
-**
-=============================================================================*/
-
-namespace System.Security
-{
- using IEnumerator = System.Collections.IEnumerator;
- using System.Security;
- using System.Security.Permissions;
- using System.Runtime.InteropServices;
- using System.Diagnostics;
- using System.Diagnostics.Contracts;
-
-
- [Serializable]
- sealed internal class PermissionSetTriple
- {
- static private volatile PermissionToken s_zoneToken;
- static private volatile PermissionToken s_urlToken;
- internal PermissionSet AssertSet;
- internal PermissionSet GrantSet;
- internal PermissionSet RefusedSet;
- internal PermissionSetTriple()
- {
- Reset();
- }
- internal PermissionSetTriple(PermissionSetTriple triple)
- {
- this.AssertSet = triple.AssertSet;
- this.GrantSet = triple.GrantSet;
- this.RefusedSet = triple.RefusedSet;
- }
- internal void Reset()
- {
- AssertSet = null;
- GrantSet = null;
- RefusedSet = null;
- }
- internal bool IsEmpty()
- {
- return (AssertSet == null && GrantSet == null && RefusedSet == null);
- }
-
- private PermissionToken ZoneToken
- {
- get
- {
- if (s_zoneToken == null)
- s_zoneToken = PermissionToken.GetToken(typeof(ZoneIdentityPermission));
- return s_zoneToken;
- }
- }
- private PermissionToken UrlToken
- {
- get
- {
- if (s_urlToken == null)
- s_urlToken = PermissionToken.GetToken(typeof(UrlIdentityPermission));
- return s_urlToken;
- }
- }
- internal bool Update(PermissionSetTriple psTriple, out PermissionSetTriple retTriple)
- {
- retTriple = null;
- retTriple = UpdateAssert(psTriple.AssertSet);
- // Special case: unrestricted assert. Note: dcs.Assert.IsUnrestricted => dcs.Grant.IsUnrestricted
- if (psTriple.AssertSet != null && psTriple.AssertSet.IsUnrestricted())
- {
- return true; // stop construction
- }
- UpdateGrant(psTriple.GrantSet);
- UpdateRefused(psTriple.RefusedSet);
- return false;
- }
-
- internal PermissionSetTriple UpdateAssert(PermissionSet in_a)
- {
- PermissionSetTriple retTriple = null;
- if (in_a != 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;
-
- PermissionSet retPs;
- if (GrantSet != null)
- retPs = in_a.Intersect(GrantSet); // Restrict the assert to what we've already been granted
- else
- {
- GrantSet = new PermissionSet(true);
- retPs = in_a.Copy(); // Currently unrestricted Grant: assert the whole assert set
- }
- bool bFailedToCompress = false;
- // removes anything that is already in the refused set from the assert set
- if (RefusedSet != null)
- {
- retPs = PermissionSet.RemoveRefusedPermissionSet(retPs, RefusedSet, out bFailedToCompress);
- }
- if (!bFailedToCompress)
- bFailedToCompress = PermissionSet.IsIntersectingAssertedPermissions(retPs, AssertSet);
- if (bFailedToCompress)
- {
- retTriple = new PermissionSetTriple(this);
- this.Reset();
- this.GrantSet = retTriple.GrantSet.Copy();
- }
-
- if (AssertSet == null)
- AssertSet = retPs;
- else
- AssertSet.InplaceUnion(retPs);
-
- }
- return retTriple;
- }
- internal void UpdateGrant(PermissionSet in_g, out ZoneIdentityPermission z,out UrlIdentityPermission u)
- {
- z = null;
- u = null;
- if (in_g != null)
- {
- if (GrantSet == null)
- GrantSet = in_g.Copy();
- else
- GrantSet.InplaceIntersect(in_g);
-
- z = (ZoneIdentityPermission)in_g.GetPermission(ZoneToken);
- u = (UrlIdentityPermission)in_g.GetPermission(UrlToken);
- }
- }
-
- internal void UpdateGrant(PermissionSet in_g)
- {
- if (in_g != null)
- {
- if (GrantSet == null)
- GrantSet = in_g.Copy();
- else
- GrantSet.InplaceIntersect(in_g);
- }
- }
- internal void UpdateRefused(PermissionSet in_r)
- {
- if (in_r != null)
- {
- if (RefusedSet == null)
- RefusedSet = in_r.Copy();
- else
- RefusedSet.InplaceUnion(in_r);
- }
- }
-
-
- static bool CheckAssert(PermissionSet pSet, CodeAccessPermission demand, PermissionToken permToken)
- {
- if (pSet != null)
- {
- pSet.CheckDecoded(demand, permToken);
-
- CodeAccessPermission perm = (CodeAccessPermission)pSet.GetPermission(demand);
-
- // If the assert set does contain the demanded permission, halt the stackwalk
-
- try
- {
- if (pSet.IsUnrestricted() || demand.CheckAssert(perm))
- {
- return SecurityRuntime.StackHalt;
- }
- }
- catch (ArgumentException)
- {
- }
- }
- return SecurityRuntime.StackContinue;
- }
-
- static bool CheckAssert(PermissionSet assertPset, PermissionSet demandSet, out PermissionSet newDemandSet)
- {
- newDemandSet = null;
- if (assertPset!= null)
- {
- assertPset.CheckDecoded(demandSet);
- // If this frame asserts a superset of the demand set we're done
-
- if (demandSet.CheckAssertion(assertPset))
- return SecurityRuntime.StackHalt;
- PermissionSet.RemoveAssertedPermissionSet(demandSet, assertPset, out newDemandSet);
- }
- return SecurityRuntime.StackContinue;
- }
-
-
- internal bool CheckDemand(CodeAccessPermission demand, PermissionToken permToken, RuntimeMethodHandleInternal rmh)
- {
- if (CheckAssert(AssertSet, demand, permToken) == SecurityRuntime.StackHalt)
- return SecurityRuntime.StackHalt;
-
-#pragma warning disable 618
- CodeAccessSecurityEngine.CheckHelper(GrantSet, RefusedSet, demand, permToken, rmh, null, SecurityAction.Demand, true);
-#pragma warning restore 618
-
- return SecurityRuntime.StackContinue;
- }
- internal bool CheckSetDemand(PermissionSet demandSet , out PermissionSet alteredDemandset, RuntimeMethodHandleInternal rmh)
- {
- alteredDemandset = null;
-
- if (CheckAssert(AssertSet, demandSet, out alteredDemandset) == SecurityRuntime.StackHalt)
- return SecurityRuntime.StackHalt;
- if (alteredDemandset != null)
- demandSet = alteredDemandset; // note that this does not modify demandSet external to this function.
-#pragma warning disable 618
- CodeAccessSecurityEngine.CheckSetHelper(GrantSet, RefusedSet, demandSet, rmh, null, SecurityAction.Demand, true);
-#pragma warning restore 618
-
- return SecurityRuntime.StackContinue;
-
- }
-
- internal bool CheckDemandNoThrow(CodeAccessPermission demand, PermissionToken permToken)
- {
- 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
- }
- internal bool CheckSetDemandNoThrow(PermissionSet demandSet)
- {
- Debug.Assert(AssertSet == null, "AssertSet not null");
-
-#pragma warning disable 618
- return CodeAccessSecurityEngine.CheckSetHelper(GrantSet, RefusedSet, demandSet, RuntimeMethodHandleInternal.EmptyHandle, null, SecurityAction.Demand, false);
-#pragma warning restore 618
- }
- /// <summary>
- /// Check to see if the triple satisfies a demand for the permission represented by the flag.
- /// </summary>
- /// <remarks>
- /// 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>
- internal bool CheckFlags(ref int flags)
- {
- if (AssertSet != null)
- {
- // remove any permissions which were asserted for
- int assertFlags = SecurityManager.GetSpecialFlags(AssertSet, null);
- if ((flags & assertFlags) != 0)
- flags = flags & ~assertFlags;
- }
-
- return (SecurityManager.GetSpecialFlags(GrantSet, RefusedSet) & flags) == flags;
- }
- }
-}
-
-
diff --git a/src/mscorlib/src/System/Security/PermissionToken.cs b/src/mscorlib/src/System/Security/PermissionToken.cs
deleted file mode 100644
index 5c6a322c1c..0000000000
--- a/src/mscorlib/src/System/Security/PermissionToken.cs
+++ /dev/null
@@ -1,383 +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.Security
-{
- using System;
- using System.Security.Util;
- using System.Security.Permissions;
- using System.Reflection;
- using System.Collections;
- using System.Threading;
- using System.Globalization;
- using System.Runtime.CompilerServices;
- using System.Diagnostics;
- using System.Diagnostics.Contracts;
-
- [Flags]
- internal enum PermissionTokenType
- {
- Normal = 0x1,
- IUnrestricted = 0x2,
- DontKnow = 0x4,
- BuiltIn = 0x8
- }
-
- [Serializable]
- internal sealed class PermissionTokenKeyComparer : IEqualityComparer
- {
- private Comparer _caseSensitiveComparer;
- private TextInfo _info;
-
- public PermissionTokenKeyComparer()
- {
- _caseSensitiveComparer = new Comparer(CultureInfo.InvariantCulture);
- _info = CultureInfo.InvariantCulture.TextInfo;
- }
-
- public int Compare(Object a, Object b)
- {
- String strA = a as String;
- String strB = b as String;
-
- // if it's not a string then we just call the object comparer
- if (strA == null || strB == null)
- return _caseSensitiveComparer.Compare(a, b);
-
- int i = _caseSensitiveComparer.Compare(a,b);
- if (i == 0)
- return 0;
-
- if (SecurityManager.IsSameType(strA, strB))
- return 0;
-
- return i;
- }
-
- public new bool Equals( Object a, Object b )
- {
- if (a == b) return true;
- if (a == null || b == null) return false;
- return Compare( a, b ) == 0;
- }
-
- // 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(nameof(obj));
- Contract.EndContractBlock();
-
- String str = obj as String;
-
- if (str == null)
- return obj.GetHashCode();
-
- int iComma = str.IndexOf( ',' );
- if (iComma == -1)
- iComma = str.Length;
-
- int accumulator = 0;
- for (int i = 0; i < iComma; ++i)
- {
- accumulator = (accumulator << 7) ^ str[i] ^ (accumulator >> 25);
- }
-
- return accumulator;
- }
- }
-
- [Serializable]
- internal sealed class PermissionToken : ISecurityEncodable
- {
- private static readonly PermissionTokenFactory s_theTokenFactory;
- private const string c_mscorlibName = System.CoreLib.Name;
- internal int m_index;
- internal volatile PermissionTokenType m_type;
- static internal TokenBasedSet s_tokenSet = new TokenBasedSet();
-
- internal static bool IsMscorlibClassName (string className) {
- 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
- // an mscorlib.dll type so we should return true so the type can be matched with the
- // right index in the TokenBasedSet.
- int index = className.IndexOf(',');
- if (index == -1)
- return true;
-
- index = className.LastIndexOf(']');
- if (index == -1)
- index = 0;
-
- // 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 (className[i] == 's' || className[i] == 'S')
- {
- if (String.Compare(className, i, c_mscorlibName, 0, c_mscorlibName.Length, StringComparison.OrdinalIgnoreCase) == 0)
- return true;
- }
- }
- return false;
- }
-
- static PermissionToken()
- {
- s_theTokenFactory = new PermissionTokenFactory( 4 );
- }
-
- internal PermissionToken()
- {
- }
-
- internal PermissionToken(int index, PermissionTokenType type, String strTypeName)
- {
- m_index = index;
- m_type = type;
- }
-
- public static PermissionToken GetToken(Type cls)
- {
- if (cls == null)
- return null;
-
- return s_theTokenFactory.GetToken(cls, null);
- }
-
- public static PermissionToken GetToken(IPermission perm)
- {
- if (perm == null)
- return null;
-
- IBuiltInPermission ibPerm = perm as IBuiltInPermission;
-
- if (ibPerm != null)
- return s_theTokenFactory.BuiltInGetToken( ibPerm.GetTokenIndex(), perm, null );
- else
- return s_theTokenFactory.GetToken(perm.GetType(), perm);
- }
-
- public static PermissionToken FindTokenByIndex( int i )
- {
- return s_theTokenFactory.FindTokenByIndex( i );
- }
-
- public static bool IsTokenProperlyAssigned( IPermission perm, PermissionToken token )
- {
- PermissionToken heldToken = GetToken( perm );
- if (heldToken.m_index != token.m_index)
- return false;
-
- if (token.m_type != heldToken.m_type)
- return false;
-
- if (perm.GetType().Module.Assembly == Assembly.GetExecutingAssembly() &&
- heldToken.m_index >= BuiltInPermissionIndex.NUM_BUILTIN_NORMAL + BuiltInPermissionIndex.NUM_BUILTIN_UNRESTRICTED)
- return false;
-
- return true;
- }
- }
-
- // Package access only
- internal class PermissionTokenFactory
- {
- private volatile int m_size;
- private volatile int m_index;
- private volatile Hashtable m_tokenTable; // Cache of tokens by class string name
- private volatile Hashtable m_handleTable; // Cache of tokens by type handle (IntPtr)
- private volatile Hashtable m_indexTable; // Cache of tokens by index
-
-
- // We keep an array of tokens for our built-in permissions.
- // This is ordered in terms of unrestricted perms first, normals
- // second. Of course, all the ordering is based on the individual
- // permissions sticking to the deal, so we do some simple boundary
- // checking but mainly leave it to faith.
-
- private volatile PermissionToken[] m_builtIn;
-
- private const String s_unrestrictedPermissionInferfaceName = "System.Security.Permissions.IUnrestrictedPermission";
-
- internal PermissionTokenFactory( int size )
- {
- m_builtIn = new PermissionToken[BuiltInPermissionIndex.NUM_BUILTIN_NORMAL + BuiltInPermissionIndex.NUM_BUILTIN_UNRESTRICTED];
-
- m_size = size;
- m_index = BuiltInPermissionIndex.NUM_BUILTIN_NORMAL + BuiltInPermissionIndex.NUM_BUILTIN_UNRESTRICTED;
- m_tokenTable = null;
- m_handleTable = new Hashtable(size);
- m_indexTable = new Hashtable(size);
- }
-
- internal PermissionToken FindTokenByIndex( int i )
- {
- PermissionToken token;
-
- if (i < BuiltInPermissionIndex.NUM_BUILTIN_NORMAL + BuiltInPermissionIndex.NUM_BUILTIN_UNRESTRICTED)
- {
- token = BuiltInGetToken( i, null, null );
- }
- else
- {
- token = (PermissionToken)m_indexTable[i];
- }
-
- return token;
- }
-
- internal PermissionToken GetToken(Type cls, IPermission perm)
- {
- Debug.Assert( cls != null, "Must pass in valid type" );
-
- IntPtr typePtr = cls.TypeHandle.Value;
- object tok = m_handleTable[typePtr];
- if (tok == null)
- {
- String typeStr = cls.AssemblyQualifiedName;
- tok = m_tokenTable != null ? m_tokenTable[typeStr] : null; // Assumes asynchronous lookups are safe
-
- if (tok == null)
- {
- lock (this)
- {
- if (m_tokenTable != null)
- {
- tok = m_tokenTable[typeStr]; // Make sure it wasn't just added
- }
- else
- m_tokenTable = new Hashtable(m_size, 1.0f, new PermissionTokenKeyComparer());
-
- if (tok == null)
- {
- if (perm != null)
- {
- tok = new PermissionToken( m_index++, PermissionTokenType.IUnrestricted, typeStr );
- }
- else
- {
- if (cls.GetInterface(s_unrestrictedPermissionInferfaceName) != null)
- tok = new PermissionToken( m_index++, PermissionTokenType.IUnrestricted, typeStr );
- else
- tok = new PermissionToken( m_index++, PermissionTokenType.Normal, typeStr );
- }
- m_tokenTable.Add(typeStr, tok);
- m_indexTable.Add(m_index - 1, tok);
- PermissionToken.s_tokenSet.SetItem( ((PermissionToken)tok).m_index, tok );
- }
-
- if (!m_handleTable.Contains(typePtr))
- m_handleTable.Add( typePtr, tok );
- }
- }
- else
- {
- lock (this)
- {
- if (!m_handleTable.Contains(typePtr))
- m_handleTable.Add( typePtr, tok );
- }
- }
- }
-
- if ((((PermissionToken)tok).m_type & PermissionTokenType.DontKnow) != 0)
- {
- if (perm != null)
- {
- Debug.Assert( !(perm is IBuiltInPermission), "This should not be called for built-ins" );
- ((PermissionToken)tok).m_type = PermissionTokenType.IUnrestricted;
- }
- else
- {
- 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;
- }
- }
-
- return (PermissionToken)tok;
- }
-
- internal PermissionToken GetToken(String typeStr)
- {
- Object tok = null;
- tok = m_tokenTable != null ? m_tokenTable[typeStr] : null; // Assumes asynchronous lookups are safe
- if (tok == null)
- {
- lock (this)
- {
- if (m_tokenTable != null)
- {
- tok = m_tokenTable[typeStr]; // Make sure it wasn't just added
- }
- else
- m_tokenTable = new Hashtable(m_size, 1.0f, new PermissionTokenKeyComparer());
-
- if (tok == null)
- {
- tok = new PermissionToken( m_index++, PermissionTokenType.DontKnow, typeStr );
- m_tokenTable.Add(typeStr, tok);
- m_indexTable.Add(m_index - 1, tok);
- PermissionToken.s_tokenSet.SetItem(((PermissionToken)tok).m_index, tok);
- }
- }
- }
-
- return (PermissionToken)tok;
- }
-
- internal PermissionToken BuiltInGetToken( int index, IPermission perm, Type cls )
- {
- PermissionToken token = Volatile.Read(ref m_builtIn[index]);
-
- if (token == null)
- {
- lock (this)
- {
- token = m_builtIn[index];
-
- if (token == null)
- {
- PermissionTokenType permType = PermissionTokenType.DontKnow;
-
- if (perm != null)
- {
- permType = PermissionTokenType.IUnrestricted;
- }
- else if (cls != null)
- {
- permType = PermissionTokenType.IUnrestricted;
- }
-
- token = new PermissionToken( index, permType | PermissionTokenType.BuiltIn, null );
- Volatile.Write(ref m_builtIn[index], token);
- PermissionToken.s_tokenSet.SetItem( token.m_index, token );
- }
- }
- }
-
- if ((token.m_type & PermissionTokenType.DontKnow) != 0)
- {
- token.m_type = PermissionTokenType.BuiltIn;
-
- if (perm != null)
- {
- token.m_type |= PermissionTokenType.IUnrestricted;
- }
- else if (cls != null)
- {
- token.m_type |= PermissionTokenType.IUnrestricted;
- }
- else
- {
- token.m_type |= PermissionTokenType.DontKnow;
- }
- }
-
- return token;
- }
- }
-}
diff --git a/src/mscorlib/src/System/Security/Permissions/EnvironmentPermission.cs b/src/mscorlib/src/System/Security/Permissions/EnvironmentPermission.cs
deleted file mode 100644
index 567fe513c0..0000000000
--- a/src/mscorlib/src/System/Security/Permissions/EnvironmentPermission.cs
+++ /dev/null
@@ -1,347 +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.Security.Permissions {
- using System.Security;
- using System;
- using SecurityElement = System.Security.SecurityElement;
- using System.Security.Util;
- using System.IO;
- using System.Globalization;
- using System.Diagnostics.Contracts;
-
- [Serializable]
- [Flags]
- [System.Runtime.InteropServices.ComVisible(true)]
- public enum EnvironmentPermissionAccess
- {
- NoAccess = 0x00,
- Read = 0x01,
- Write = 0x02,
- AllAccess = 0x03,
- }
-
- [Serializable]
- internal class EnvironmentStringExpressionSet : StringExpressionSet
- {
- public EnvironmentStringExpressionSet()
- : base( true, null, false )
- {
- }
-
- public EnvironmentStringExpressionSet( String str )
- : base( true, str, false )
- {
- }
-
- protected override StringExpressionSet CreateNewEmpty()
- {
- return new EnvironmentStringExpressionSet();
- }
-
- protected override bool StringSubsetString( String left, String right, bool ignoreCase )
- {
- return (ignoreCase?(String.Compare( left, right, StringComparison.OrdinalIgnoreCase) == 0):
- (String.Compare( left, right, StringComparison.Ordinal) == 0));
- }
-
- protected override String ProcessWholeString( String str )
- {
- return str;
- }
-
- protected override String ProcessSingleString( String str )
- {
- return str;
- }
-
- public override string ToString()
- {
- // SafeCritical: we're not storing path information in the strings, so exposing them out is fine ...
- // they're just the same strings that came in to the .ctor.
- return base.UnsafeToString();
- }
- }
-
-[System.Runtime.InteropServices.ComVisible(true)]
- [Serializable]
- sealed public class EnvironmentPermission : CodeAccessPermission, IUnrestrictedPermission, IBuiltInPermission
- {
- private StringExpressionSet m_read;
- private StringExpressionSet m_write;
- private bool m_unrestricted;
-
- public EnvironmentPermission(PermissionState state)
- {
- if (state == PermissionState.Unrestricted)
- m_unrestricted = true;
- else if (state == PermissionState.None)
- m_unrestricted = false;
- else
- throw new ArgumentException(Environment.GetResourceString("Argument_InvalidPermissionState"));
- }
-
- public EnvironmentPermission( EnvironmentPermissionAccess flag, String pathList )
- {
- SetPathList( flag, pathList );
- }
-
- public void SetPathList( EnvironmentPermissionAccess flag, String pathList )
- {
- VerifyFlag( flag );
-
- m_unrestricted = false;
-
- if ((flag & EnvironmentPermissionAccess.Read) != 0)
- m_read = null;
-
- if ((flag & EnvironmentPermissionAccess.Write) != 0)
- m_write = null;
-
- AddPathList( flag, pathList );
- }
-
- public void AddPathList( EnvironmentPermissionAccess flag, String pathList )
- {
- VerifyFlag( flag );
-
- if (FlagIsSet( flag, EnvironmentPermissionAccess.Read ))
- {
- if (m_read == null)
- m_read = new EnvironmentStringExpressionSet();
- m_read.AddExpressions( pathList );
- }
-
- if (FlagIsSet( flag, EnvironmentPermissionAccess.Write ))
- {
- if (m_write == null)
- m_write = new EnvironmentStringExpressionSet();
- m_write.AddExpressions( pathList );
- }
-
- }
-
- public String GetPathList( EnvironmentPermissionAccess flag )
- {
- VerifyFlag( flag );
- ExclusiveFlag( flag );
-
- if (FlagIsSet( flag, EnvironmentPermissionAccess.Read ))
- {
- if (m_read == null)
- {
- return "";
- }
- return m_read.ToString();
- }
-
- if (FlagIsSet( flag, EnvironmentPermissionAccess.Write ))
- {
- if (m_write == null)
- {
- return "";
- }
- return m_write.ToString();
- }
-
- /* not reached */
-
- return "";
- }
-
-
- private void VerifyFlag( EnvironmentPermissionAccess flag )
- {
- if ((flag & ~EnvironmentPermissionAccess.AllAccess) != 0)
- throw new ArgumentException(Environment.GetResourceString("Arg_EnumIllegalVal", (int)flag));
- Contract.EndContractBlock();
- }
-
- private void ExclusiveFlag( EnvironmentPermissionAccess flag )
- {
- if (flag == EnvironmentPermissionAccess.NoAccess)
- {
- throw new ArgumentException( Environment.GetResourceString("Arg_EnumNotSingleFlag") );
- }
-
- if (((int)flag & ((int)flag-1)) != 0)
- {
- throw new ArgumentException( Environment.GetResourceString("Arg_EnumNotSingleFlag") );
- }
- Contract.EndContractBlock();
- }
-
-
- private bool FlagIsSet( EnvironmentPermissionAccess flag, EnvironmentPermissionAccess question )
- {
- return (flag & question) != 0;
- }
-
- private bool IsEmpty()
- {
- return (!m_unrestricted &&
- (this.m_read == null || this.m_read.IsEmpty()) &&
- (this.m_write == null || this.m_write.IsEmpty()));
- }
-
- //------------------------------------------------------
- //
- // CODEACCESSPERMISSION IMPLEMENTATION
- //
- //------------------------------------------------------
-
- public bool IsUnrestricted()
- {
- return m_unrestricted;
- }
-
- //------------------------------------------------------
- //
- // IPERMISSION IMPLEMENTATION
- //
- //------------------------------------------------------
-
- public override bool IsSubsetOf(IPermission target)
- {
- if (target == null)
- {
- return this.IsEmpty();
- }
-
- try
- {
- EnvironmentPermission operand = (EnvironmentPermission)target;
- if (operand.IsUnrestricted())
- return true;
- else if (this.IsUnrestricted())
- return false;
- else
- return ((this.m_read == null || this.m_read.IsSubsetOf( operand.m_read )) &&
- (this.m_write == null || this.m_write.IsSubsetOf( operand.m_write )));
- }
- catch (InvalidCastException)
- {
- throw new
- ArgumentException(
- Environment.GetResourceString("Argument_WrongType", this.GetType().FullName)
- );
- }
- }
-
- public override IPermission Intersect(IPermission target)
- {
- if (target == null)
- {
- return null;
- }
- else if (!VerifyType(target))
- {
- throw new
- ArgumentException(
- Environment.GetResourceString("Argument_WrongType", this.GetType().FullName)
- );
- }
- else if (this.IsUnrestricted())
- {
- return target.Copy();
- }
-
- EnvironmentPermission operand = (EnvironmentPermission)target;
-
- if (operand.IsUnrestricted())
- {
- return this.Copy();
- }
-
- StringExpressionSet intersectRead = this.m_read == null ? null : this.m_read.Intersect( operand.m_read );
- StringExpressionSet intersectWrite = this.m_write == null ? null : this.m_write.Intersect( operand.m_write );
-
- if ((intersectRead == null || intersectRead.IsEmpty()) &&
- (intersectWrite == null || intersectWrite.IsEmpty()))
- {
- return null;
- }
-
- EnvironmentPermission intersectPermission = new EnvironmentPermission(PermissionState.None);
- intersectPermission.m_unrestricted = false;
- intersectPermission.m_read = intersectRead;
- intersectPermission.m_write = intersectWrite;
-
- return intersectPermission;
- }
-
- public override IPermission Union(IPermission other)
- {
- if (other == null)
- {
- return this.Copy();
- }
- else if (!VerifyType(other))
- {
- throw new
- ArgumentException(
- Environment.GetResourceString("Argument_WrongType", this.GetType().FullName)
- );
- }
-
- EnvironmentPermission operand = (EnvironmentPermission)other;
-
- if (this.IsUnrestricted() || operand.IsUnrestricted())
- {
- return new EnvironmentPermission( PermissionState.Unrestricted );
- }
-
- StringExpressionSet unionRead = this.m_read == null ? operand.m_read : this.m_read.Union( operand.m_read );
- StringExpressionSet unionWrite = this.m_write == null ? operand.m_write : this.m_write.Union( operand.m_write );
-
- if ((unionRead == null || unionRead.IsEmpty()) &&
- (unionWrite == null || unionWrite.IsEmpty()))
- {
- return null;
- }
-
- EnvironmentPermission unionPermission = new EnvironmentPermission(PermissionState.None);
- unionPermission.m_unrestricted = false;
- unionPermission.m_read = unionRead;
- unionPermission.m_write = unionWrite;
-
- return unionPermission;
- }
-
- public override IPermission Copy()
- {
- EnvironmentPermission copy = new EnvironmentPermission(PermissionState.None);
- if (this.m_unrestricted)
- {
- copy.m_unrestricted = true;
- }
- else
- {
- copy.m_unrestricted = false;
- if (this.m_read != null)
- {
- copy.m_read = this.m_read.Copy();
- }
- if (this.m_write != null)
- {
- copy.m_write = this.m_write.Copy();
- }
-
- }
- return copy;
- }
-
- /// <internalonly/>
- int IBuiltInPermission.GetTokenIndex()
- {
- return EnvironmentPermission.GetTokenIndex();
- }
-
- internal static int GetTokenIndex()
- {
- return BuiltInPermissionIndex.EnvironmentPermissionIndex;
- }
- }
-
-}
diff --git a/src/mscorlib/src/System/Security/Permissions/FileDialogPermission.cs b/src/mscorlib/src/System/Security/Permissions/FileDialogPermission.cs
deleted file mode 100644
index 98a7d54c68..0000000000
--- a/src/mscorlib/src/System/Security/Permissions/FileDialogPermission.cs
+++ /dev/null
@@ -1,158 +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.Security.Permissions {
- using System;
- using System.Text;
- using System.Security;
- using System.Security.Util;
- using System.IO;
- using System.Runtime.Serialization;
- using System.Reflection;
- using System.Collections;
- using System.Globalization;
- using System.Diagnostics.Contracts;
-
-[Serializable]
-[Flags]
-[System.Runtime.InteropServices.ComVisible(true)]
- public enum FileDialogPermissionAccess {
- None = 0x00,
-
- Open = 0x01,
-
- Save = 0x02,
-
- OpenSave = Open | Save
-
- }
-
- [Serializable]
-[System.Runtime.InteropServices.ComVisible(true)]
- public sealed class FileDialogPermission : CodeAccessPermission, IUnrestrictedPermission, IBuiltInPermission {
- FileDialogPermissionAccess access;
-
- public FileDialogPermission(PermissionState state) {
- if (state == PermissionState.Unrestricted) {
- SetUnrestricted(true);
- }
- else if (state == PermissionState.None) {
- SetUnrestricted(false);
- Reset();
- }
- else {
- throw new ArgumentException(Environment.GetResourceString("Argument_InvalidPermissionState"));
- }
- }
-
- public FileDialogPermission(FileDialogPermissionAccess access) {
- VerifyAccess(access);
- this.access = access;
- }
-
- public FileDialogPermissionAccess Access {
- get {
- return access;
- }
-
- set {
- VerifyAccess(value);
- access = value;
- }
- }
-
- public override IPermission Copy() {
- return new FileDialogPermission(this.access);
- }
-
- /// <internalonly/>
- int IBuiltInPermission.GetTokenIndex() {
- return FileDialogPermission.GetTokenIndex();
- }
-
- internal static int GetTokenIndex() {
- return BuiltInPermissionIndex.FileDialogPermissionIndex;
- }
-
- public override IPermission Intersect(IPermission target) {
- if (target == null) {
- return null;
- }
- else if (!VerifyType(target)) {
- throw new ArgumentException(Environment.GetResourceString("Argument_WrongType", this.GetType().FullName));
- }
-
- FileDialogPermission operand = (FileDialogPermission)target;
-
- FileDialogPermissionAccess intersectAccess = access & operand.Access;
-
- if (intersectAccess == FileDialogPermissionAccess.None)
- return null;
- else
- return new FileDialogPermission(intersectAccess);
- }
-
- public override bool IsSubsetOf(IPermission target) {
- if (target == null) {
- // Only safe subset if this is empty
- return access == FileDialogPermissionAccess.None;
- }
-
- try {
- FileDialogPermission operand = (FileDialogPermission)target;
- if (operand.IsUnrestricted()) {
- return true;
- }
- else if (this.IsUnrestricted()) {
- return false;
- }
- else {
- int open = (int)(access & FileDialogPermissionAccess.Open);
- int save = (int)(access & FileDialogPermissionAccess.Save);
- int openTarget = (int)(operand.Access & FileDialogPermissionAccess.Open);
- int saveTarget = (int)(operand.Access & FileDialogPermissionAccess.Save);
-
- return open <= openTarget && save <= saveTarget;
- }
- }
- catch (InvalidCastException) {
- throw new ArgumentException(Environment.GetResourceString("Argument_WrongType", this.GetType().FullName));
- }
-
- }
-
- public bool IsUnrestricted() {
- return access == FileDialogPermissionAccess.OpenSave;
- }
-
- void Reset() {
- access = FileDialogPermissionAccess.None;
- }
-
- void SetUnrestricted( bool unrestricted ) {
- if (unrestricted) {
- access = FileDialogPermissionAccess.OpenSave;
- }
- }
-
- public override IPermission Union(IPermission target) {
- if (target == null) {
- return this.Copy();
- }
- else if (!VerifyType(target)) {
- throw new ArgumentException(Environment.GetResourceString("Argument_WrongType", this.GetType().FullName));
- }
-
- FileDialogPermission operand = (FileDialogPermission)target;
- return new FileDialogPermission(access | operand.Access);
- }
-
- static void VerifyAccess(FileDialogPermissionAccess access) {
- if ((access & ~FileDialogPermissionAccess.OpenSave) != 0 ) {
- throw new ArgumentException(Environment.GetResourceString("Arg_EnumIllegalVal", (int)access));
- }
- Contract.EndContractBlock();
- }
- }
-}
diff --git a/src/mscorlib/src/System/Security/Permissions/FileIOPermission.cs b/src/mscorlib/src/System/Security/Permissions/FileIOPermission.cs
deleted file mode 100644
index 34b9f1ef80..0000000000
--- a/src/mscorlib/src/System/Security/Permissions/FileIOPermission.cs
+++ /dev/null
@@ -1,1216 +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.Security.Permissions
-{
- using System;
- using System.Runtime.CompilerServices;
- using System.Runtime.InteropServices;
- using System.Security.AccessControl;
- using System.Security.Util;
- using System.IO;
- using System.Collections;
- using System.Globalization;
- using System.Runtime.Serialization;
- using System.Runtime.Versioning;
- using System.Diagnostics;
- using System.Diagnostics.Contracts;
-
- [Serializable]
- [Flags]
- [System.Runtime.InteropServices.ComVisible(true)]
- public enum FileIOPermissionAccess
- {
- NoAccess = 0x00,
- Read = 0x01,
- Write = 0x02,
- Append = 0x04,
- PathDiscovery = 0x08,
- AllAccess = 0x0F,
- }
-
- [System.Runtime.InteropServices.ComVisible(true)]
- [Serializable]
- sealed public class FileIOPermission : CodeAccessPermission, IUnrestrictedPermission, IBuiltInPermission
- {
- private FileIOAccess m_read;
- private FileIOAccess m_write;
- private FileIOAccess m_append;
- private FileIOAccess m_pathDiscovery;
- [OptionalField(VersionAdded = 2)]
- private FileIOAccess m_viewAcl;
- [OptionalField(VersionAdded = 2)]
- private FileIOAccess m_changeAcl;
- private bool m_unrestricted;
-
- public FileIOPermission(PermissionState state)
- {
- if (state == PermissionState.Unrestricted)
- {
- m_unrestricted = true;
- }
- else if (state == PermissionState.None)
- {
- m_unrestricted = false;
- }
- else
- {
- throw new ArgumentException(Environment.GetResourceString("Argument_InvalidPermissionState"));
- }
- }
-
- public FileIOPermission( FileIOPermissionAccess access, String path )
- {
- VerifyAccess( access );
-
- String[] pathList = new String[] { path };
- AddPathList( access, pathList, false, true, false );
- }
-
- public FileIOPermission( FileIOPermissionAccess access, String[] pathList )
- {
- VerifyAccess( access );
-
- AddPathList( access, pathList, false, true, false );
- }
-
- internal FileIOPermission( FileIOPermissionAccess access, String[] pathList, bool checkForDuplicates, bool needFullPath )
- {
- VerifyAccess( access );
-
- AddPathList( access, pathList, checkForDuplicates, needFullPath, true );
- }
-
- public void SetPathList( FileIOPermissionAccess access, String path )
- {
- String[] pathList;
- if(path == null)
- pathList = new String[] {};
- else
- pathList = new String[] { path };
- SetPathList( access, pathList, false );
- }
-
- public void SetPathList( FileIOPermissionAccess access, String[] pathList )
- {
- SetPathList( access, pathList, true );
- }
-
- internal void SetPathList( FileIOPermissionAccess access,
- String[] pathList, bool checkForDuplicates )
- {
- SetPathList( access, AccessControlActions.None, pathList, checkForDuplicates );
- }
-
- internal void SetPathList( FileIOPermissionAccess access, AccessControlActions control, String[] pathList, bool checkForDuplicates )
- {
- VerifyAccess( access );
-
- if ((access & FileIOPermissionAccess.Read) != 0)
- m_read = null;
-
- if ((access & FileIOPermissionAccess.Write) != 0)
- m_write = null;
-
- if ((access & FileIOPermissionAccess.Append) != 0)
- m_append = null;
-
- if ((access & FileIOPermissionAccess.PathDiscovery) != 0)
- m_pathDiscovery = null;
-
- m_viewAcl = null;
- m_changeAcl = null;
- m_unrestricted = false;
-
- AddPathList( access, pathList, checkForDuplicates, true, true );
- }
-
- public void AddPathList( FileIOPermissionAccess access, String path )
- {
- String[] pathList;
- if(path == null)
- pathList = new String[] {};
- else
- pathList = new String[] { path };
- AddPathList( access, pathList, false, true, false );
- }
-
- public void AddPathList( FileIOPermissionAccess access, String[] pathList )
- {
- AddPathList( access, pathList, true, true, true );
- }
-
- internal void AddPathList( FileIOPermissionAccess access, String[] pathListOrig, bool checkForDuplicates, bool needFullPath, bool copyPathList )
- {
- AddPathList( access, AccessControlActions.None, pathListOrig, checkForDuplicates, needFullPath, copyPathList );
- }
-
- internal void AddPathList(FileIOPermissionAccess access, AccessControlActions control, String[] pathListOrig, bool checkForDuplicates, bool needFullPath, bool copyPathList)
- {
- if (pathListOrig == null)
- {
- throw new ArgumentNullException( "pathList" );
- }
- if (pathListOrig.Length == 0)
- {
- throw new ArgumentException( Environment.GetResourceString("Argument_EmptyPath" ));
- }
- Contract.EndContractBlock();
-
- VerifyAccess(access);
-
- if (m_unrestricted)
- return;
-
- String[] pathList = pathListOrig;
- if(copyPathList)
- {
- // Make a copy of pathList (in case its value changes after we check for illegal chars)
- pathList = new String[pathListOrig.Length];
- Array.Copy(pathListOrig, pathList, pathListOrig.Length);
- }
-
- ArrayList pathArrayList = StringExpressionSet.CreateListFromExpressions(pathList, needFullPath);
-
- // If we need the full path the standard illegal characters will be checked in StringExpressionSet.
- CheckIllegalCharacters(pathList, onlyCheckExtras: needFullPath);
-
- // StringExpressionSet will do minor normalization, trimming spaces and replacing alternate
- // directory separators. It will make an attemt to expand short file names and will check
- // for standard colon placement.
- //
- // If needFullPath is true it will call NormalizePath- which performs short name expansion
- // and does the normal validity checks.
-
- if ((access & FileIOPermissionAccess.Read) != 0)
- {
- if (m_read == null)
- {
- m_read = new FileIOAccess();
- }
- m_read.AddExpressions( pathArrayList, checkForDuplicates);
- }
-
- if ((access & FileIOPermissionAccess.Write) != 0)
- {
- if (m_write == null)
- {
- m_write = new FileIOAccess();
- }
- m_write.AddExpressions( pathArrayList, checkForDuplicates);
- }
-
- if ((access & FileIOPermissionAccess.Append) != 0)
- {
- if (m_append == null)
- {
- m_append = new FileIOAccess();
- }
- m_append.AddExpressions( pathArrayList, checkForDuplicates);
- }
-
- if ((access & FileIOPermissionAccess.PathDiscovery) != 0)
- {
- if (m_pathDiscovery == null)
- {
- m_pathDiscovery = new FileIOAccess( true );
- }
- m_pathDiscovery.AddExpressions( pathArrayList, checkForDuplicates);
- }
- }
-
- public String[] GetPathList( FileIOPermissionAccess access )
- {
- VerifyAccess( access );
- ExclusiveAccess( access );
-
- if (AccessIsSet( access, FileIOPermissionAccess.Read ))
- {
- if (m_read == null)
- {
- return null;
- }
- return m_read.ToStringArray();
- }
-
- if (AccessIsSet( access, FileIOPermissionAccess.Write ))
- {
- if (m_write == null)
- {
- return null;
- }
- return m_write.ToStringArray();
- }
-
- if (AccessIsSet( access, FileIOPermissionAccess.Append ))
- {
- if (m_append == null)
- {
- return null;
- }
- return m_append.ToStringArray();
- }
-
- if (AccessIsSet( access, FileIOPermissionAccess.PathDiscovery ))
- {
- if (m_pathDiscovery == null)
- {
- return null;
- }
- return m_pathDiscovery.ToStringArray();
- }
-
- // not reached
-
- return null;
- }
-
- public FileIOPermissionAccess AllLocalFiles
- {
- get
- {
- if (m_unrestricted)
- return FileIOPermissionAccess.AllAccess;
-
- FileIOPermissionAccess access = FileIOPermissionAccess.NoAccess;
-
- if (m_read != null && m_read.AllLocalFiles)
- {
- access |= FileIOPermissionAccess.Read;
- }
-
- if (m_write != null && m_write.AllLocalFiles)
- {
- access |= FileIOPermissionAccess.Write;
- }
-
- if (m_append != null && m_append.AllLocalFiles)
- {
- access |= FileIOPermissionAccess.Append;
- }
-
- if (m_pathDiscovery != null && m_pathDiscovery.AllLocalFiles)
- {
- access |= FileIOPermissionAccess.PathDiscovery;
- }
-
- return access;
- }
-
- set
- {
- if ((value & FileIOPermissionAccess.Read) != 0)
- {
- if (m_read == null)
- m_read = new FileIOAccess();
-
- m_read.AllLocalFiles = true;
- }
- else
- {
- if (m_read != null)
- m_read.AllLocalFiles = false;
- }
-
- if ((value & FileIOPermissionAccess.Write) != 0)
- {
- if (m_write == null)
- m_write = new FileIOAccess();
-
- m_write.AllLocalFiles = true;
- }
- else
- {
- if (m_write != null)
- m_write.AllLocalFiles = false;
- }
-
- if ((value & FileIOPermissionAccess.Append) != 0)
- {
- if (m_append == null)
- m_append = new FileIOAccess();
-
- m_append.AllLocalFiles = true;
- }
- else
- {
- if (m_append != null)
- m_append.AllLocalFiles = false;
- }
-
- if ((value & FileIOPermissionAccess.PathDiscovery) != 0)
- {
- if (m_pathDiscovery == null)
- m_pathDiscovery = new FileIOAccess( true );
-
- m_pathDiscovery.AllLocalFiles = true;
- }
- else
- {
- if (m_pathDiscovery != null)
- m_pathDiscovery.AllLocalFiles = false;
- }
-
- }
- }
-
- public FileIOPermissionAccess AllFiles
- {
- get
- {
- if (m_unrestricted)
- return FileIOPermissionAccess.AllAccess;
-
- FileIOPermissionAccess access = FileIOPermissionAccess.NoAccess;
-
- if (m_read != null && m_read.AllFiles)
- {
- access |= FileIOPermissionAccess.Read;
- }
-
- if (m_write != null && m_write.AllFiles)
- {
- access |= FileIOPermissionAccess.Write;
- }
-
- if (m_append != null && m_append.AllFiles)
- {
- access |= FileIOPermissionAccess.Append;
- }
-
- if (m_pathDiscovery != null && m_pathDiscovery.AllFiles)
- {
- access |= FileIOPermissionAccess.PathDiscovery;
- }
-
- return access;
- }
-
- set
- {
- if (value == FileIOPermissionAccess.AllAccess)
- {
- m_unrestricted = true;
- return;
- }
-
- if ((value & FileIOPermissionAccess.Read) != 0)
- {
- if (m_read == null)
- m_read = new FileIOAccess();
-
- m_read.AllFiles = true;
- }
- else
- {
- if (m_read != null)
- m_read.AllFiles = false;
- }
-
- if ((value & FileIOPermissionAccess.Write) != 0)
- {
- if (m_write == null)
- m_write = new FileIOAccess();
-
- m_write.AllFiles = true;
- }
- else
- {
- if (m_write != null)
- m_write.AllFiles = false;
- }
-
- if ((value & FileIOPermissionAccess.Append) != 0)
- {
- if (m_append == null)
- m_append = new FileIOAccess();
-
- m_append.AllFiles = true;
- }
- else
- {
- if (m_append != null)
- m_append.AllFiles = false;
- }
-
- if ((value & FileIOPermissionAccess.PathDiscovery) != 0)
- {
- if (m_pathDiscovery == null)
- m_pathDiscovery = new FileIOAccess( true );
-
- m_pathDiscovery.AllFiles = true;
- }
- else
- {
- if (m_pathDiscovery != null)
- m_pathDiscovery.AllFiles = false;
- }
-
- }
- }
-
- [Pure]
- private static void VerifyAccess( FileIOPermissionAccess access )
- {
- if ((access & ~FileIOPermissionAccess.AllAccess) != 0)
- throw new ArgumentException(Environment.GetResourceString("Arg_EnumIllegalVal", (int)access));
- }
-
- [Pure]
- private static void ExclusiveAccess( FileIOPermissionAccess access )
- {
- if (access == FileIOPermissionAccess.NoAccess)
- {
- throw new ArgumentException( Environment.GetResourceString("Arg_EnumNotSingleFlag") );
- }
-
- if (((int) access & ((int)access-1)) != 0)
- {
- throw new ArgumentException( Environment.GetResourceString("Arg_EnumNotSingleFlag") );
- }
- }
-
- private static void CheckIllegalCharacters(String[] str, bool onlyCheckExtras)
- {
-#if !PLATFORM_UNIX
- for (int i = 0; i < str.Length; ++i)
- {
- // FileIOPermission doesn't allow for normalizing across various volume names. This means "C:\" and
- // "\\?\C:\" won't be considered correctly. In addition there are many other aliases for the volume
- // besides "C:" such as (in one concrete example) "\\?\Harddisk0Partition2\", "\\?\HarddiskVolume6\",
- // "\\?\Volume{d1655348-0000-0000-0000-f01500000000}\", etc.
- //
- // We'll continue to explicitly block extended syntax here by disallowing wildcards no matter where
- // they occur in the string (e.g. \\?\ isn't ok)
- if (CheckExtraPathCharacters(str[i]))
- throw new ArgumentException(Environment.GetResourceString("Argument_InvalidPathChars"));
-
- if (!onlyCheckExtras)
- PathInternal.CheckInvalidPathChars(str[i]);
- }
-#else
- // There are no "extras" on Unix
- if (onlyCheckExtras)
- return;
-
- for (int i = 0; i < str.Length; ++i)
- {
- PathInternal.CheckInvalidPathChars(str[i]);
- }
-#endif
- }
-
-#if !PLATFORM_UNIX
- /// <summary>
- /// Check for ?,* and null, ignoring extended syntax.
- /// </summary>
- [MethodImpl(MethodImplOptions.AggressiveInlining)]
- private unsafe static bool CheckExtraPathCharacters(string path)
- {
- char currentChar;
- for (int i = 0; i < path.Length; i++)
- {
- currentChar = path[i];
-
- // We also check for null here as StringExpressionSet will trim it out. (Ensuring we still throw as we always have.)
- if (currentChar == '*' || currentChar == '?' || currentChar == '\0') return true;
- }
- return false;
- }
-#endif
-
- private static bool AccessIsSet( FileIOPermissionAccess access, FileIOPermissionAccess question )
- {
- return (access & question) != 0;
- }
-
- private bool IsEmpty()
- {
- return (!m_unrestricted &&
- (this.m_read == null || this.m_read.IsEmpty()) &&
- (this.m_write == null || this.m_write.IsEmpty()) &&
- (this.m_append == null || this.m_append.IsEmpty()) &&
- (this.m_pathDiscovery == null || this.m_pathDiscovery.IsEmpty()) &&
- (this.m_viewAcl == null || this.m_viewAcl.IsEmpty()) &&
- (this.m_changeAcl == null || this.m_changeAcl.IsEmpty()));
- }
-
- //------------------------------------------------------
- //
- // CODEACCESSPERMISSION IMPLEMENTATION
- //
- //------------------------------------------------------
-
- public bool IsUnrestricted()
- {
- return m_unrestricted;
- }
-
- //------------------------------------------------------
- //
- // IPERMISSION IMPLEMENTATION
- //
- //------------------------------------------------------
-
- public override bool IsSubsetOf(IPermission target)
- {
- if (target == null)
- {
- return this.IsEmpty();
- }
-
- FileIOPermission operand = target as FileIOPermission;
- if (operand == null)
- throw new ArgumentException(Environment.GetResourceString("Argument_WrongType", this.GetType().FullName));
-
- if (operand.IsUnrestricted())
- return true;
- else if (this.IsUnrestricted())
- return false;
- else
- return ((this.m_read == null || this.m_read.IsSubsetOf( operand.m_read )) &&
- (this.m_write == null || this.m_write.IsSubsetOf( operand.m_write )) &&
- (this.m_append == null || this.m_append.IsSubsetOf( operand.m_append )) &&
- (this.m_pathDiscovery == null || this.m_pathDiscovery.IsSubsetOf( operand.m_pathDiscovery )) &&
- (this.m_viewAcl == null || this.m_viewAcl.IsSubsetOf( operand.m_viewAcl )) &&
- (this.m_changeAcl == null || this.m_changeAcl.IsSubsetOf( operand.m_changeAcl )));
- }
-
- public override IPermission Intersect(IPermission target)
- {
- if (target == null)
- {
- return null;
- }
-
- FileIOPermission operand = target as FileIOPermission;
-
- if (operand == null)
- {
- throw new ArgumentException(Environment.GetResourceString("Argument_WrongType", this.GetType().FullName));
- }
- else if (this.IsUnrestricted())
- {
- return target.Copy();
- }
-
- if (operand.IsUnrestricted())
- {
- return this.Copy();
- }
-
- FileIOAccess intersectRead = this.m_read == null ? null : this.m_read.Intersect( operand.m_read );
- FileIOAccess intersectWrite = this.m_write == null ? null : this.m_write.Intersect( operand.m_write );
- FileIOAccess intersectAppend = this.m_append == null ? null : this.m_append.Intersect( operand.m_append );
- FileIOAccess intersectPathDiscovery = this.m_pathDiscovery == null ? null : this.m_pathDiscovery.Intersect( operand.m_pathDiscovery );
- FileIOAccess intersectViewAcl = this.m_viewAcl == null ? null : this.m_viewAcl.Intersect( operand.m_viewAcl );
- FileIOAccess intersectChangeAcl = this.m_changeAcl == null ? null : this.m_changeAcl.Intersect( operand.m_changeAcl );
-
- if ((intersectRead == null || intersectRead.IsEmpty()) &&
- (intersectWrite == null || intersectWrite.IsEmpty()) &&
- (intersectAppend == null || intersectAppend.IsEmpty()) &&
- (intersectPathDiscovery == null || intersectPathDiscovery.IsEmpty()) &&
- (intersectViewAcl == null || intersectViewAcl.IsEmpty()) &&
- (intersectChangeAcl == null || intersectChangeAcl.IsEmpty()))
- {
- return null;
- }
-
- FileIOPermission intersectPermission = new FileIOPermission(PermissionState.None);
- intersectPermission.m_unrestricted = false;
- intersectPermission.m_read = intersectRead;
- intersectPermission.m_write = intersectWrite;
- intersectPermission.m_append = intersectAppend;
- intersectPermission.m_pathDiscovery = intersectPathDiscovery;
- intersectPermission.m_viewAcl = intersectViewAcl;
- intersectPermission.m_changeAcl = intersectChangeAcl;
-
- return intersectPermission;
- }
-
- public override IPermission Union(IPermission other)
- {
- if (other == null)
- {
- return this.Copy();
- }
-
- FileIOPermission operand = other as FileIOPermission;
-
- if (operand == null)
- {
- throw new ArgumentException(Environment.GetResourceString("Argument_WrongType", this.GetType().FullName));
- }
-
- if (this.IsUnrestricted() || operand.IsUnrestricted())
- {
- return new FileIOPermission( PermissionState.Unrestricted );
- }
-
- FileIOAccess unionRead = this.m_read == null ? operand.m_read : this.m_read.Union( operand.m_read );
- FileIOAccess unionWrite = this.m_write == null ? operand.m_write : this.m_write.Union( operand.m_write );
- FileIOAccess unionAppend = this.m_append == null ? operand.m_append : this.m_append.Union( operand.m_append );
- FileIOAccess unionPathDiscovery = this.m_pathDiscovery == null ? operand.m_pathDiscovery : this.m_pathDiscovery.Union( operand.m_pathDiscovery );
- FileIOAccess unionViewAcl = this.m_viewAcl == null ? operand.m_viewAcl : this.m_viewAcl.Union( operand.m_viewAcl );
- FileIOAccess unionChangeAcl = this.m_changeAcl == null ? operand.m_changeAcl : this.m_changeAcl.Union( operand.m_changeAcl );
-
- if ((unionRead == null || unionRead.IsEmpty()) &&
- (unionWrite == null || unionWrite.IsEmpty()) &&
- (unionAppend == null || unionAppend.IsEmpty()) &&
- (unionPathDiscovery == null || unionPathDiscovery.IsEmpty()) &&
- (unionViewAcl == null || unionViewAcl.IsEmpty()) &&
- (unionChangeAcl == null || unionChangeAcl.IsEmpty()))
- {
- return null;
- }
-
- FileIOPermission unionPermission = new FileIOPermission(PermissionState.None);
- unionPermission.m_unrestricted = false;
- unionPermission.m_read = unionRead;
- unionPermission.m_write = unionWrite;
- unionPermission.m_append = unionAppend;
- unionPermission.m_pathDiscovery = unionPathDiscovery;
- unionPermission.m_viewAcl = unionViewAcl;
- unionPermission.m_changeAcl = unionChangeAcl;
-
- return unionPermission;
- }
-
- public override IPermission Copy()
- {
- FileIOPermission copy = new FileIOPermission(PermissionState.None);
- if (this.m_unrestricted)
- {
- copy.m_unrestricted = true;
- }
- else
- {
- copy.m_unrestricted = false;
- if (this.m_read != null)
- {
- copy.m_read = this.m_read.Copy();
- }
- if (this.m_write != null)
- {
- copy.m_write = this.m_write.Copy();
- }
- if (this.m_append != null)
- {
- copy.m_append = this.m_append.Copy();
- }
- if (this.m_pathDiscovery != null)
- {
- copy.m_pathDiscovery = this.m_pathDiscovery.Copy();
- }
- if (this.m_viewAcl != null)
- {
- copy.m_viewAcl = this.m_viewAcl.Copy();
- }
- if (this.m_changeAcl != null)
- {
- copy.m_changeAcl = this.m_changeAcl.Copy();
- }
- }
- return copy;
- }
-
- /// <internalonly/>
- int IBuiltInPermission.GetTokenIndex()
- {
- return FileIOPermission.GetTokenIndex();
- }
-
- internal static int GetTokenIndex()
- {
- return BuiltInPermissionIndex.FileIOPermissionIndex;
- }
-
- [System.Runtime.InteropServices.ComVisible(false)]
- public override bool Equals(Object obj)
- {
- FileIOPermission perm = obj as FileIOPermission;
- if(perm == null)
- return false;
-
- if(m_unrestricted && perm.m_unrestricted)
- return true;
- if(m_unrestricted != perm.m_unrestricted)
- return false;
-
- if(m_read == null)
- {
- if(perm.m_read != null && !perm.m_read.IsEmpty())
- return false;
- }
- else if(!m_read.Equals(perm.m_read))
- return false;
-
- if(m_write == null)
- {
- if(perm.m_write != null && !perm.m_write.IsEmpty())
- return false;
- }
- else if(!m_write.Equals(perm.m_write))
- return false;
-
- if(m_append == null)
- {
- if(perm.m_append != null && !perm.m_append.IsEmpty())
- return false;
- }
- else if(!m_append.Equals(perm.m_append))
- return false;
-
- if(m_pathDiscovery == null)
- {
- if(perm.m_pathDiscovery != null && !perm.m_pathDiscovery.IsEmpty())
- return false;
- }
- else if(!m_pathDiscovery.Equals(perm.m_pathDiscovery))
- return false;
-
- if(m_viewAcl == null)
- {
- if(perm.m_viewAcl != null && !perm.m_viewAcl.IsEmpty())
- return false;
- }
- else if(!m_viewAcl.Equals(perm.m_viewAcl))
- return false;
-
- if(m_changeAcl == null)
- {
- if(perm.m_changeAcl != null && !perm.m_changeAcl.IsEmpty())
- return false;
- }
- else if(!m_changeAcl.Equals(perm.m_changeAcl))
- return false;
-
- return true;
- }
-
- [System.Runtime.InteropServices.ComVisible(false)]
- public override int GetHashCode()
- {
- // This implementation is only to silence a compiler warning.
- return base.GetHashCode();
- }
-
- /// <summary>
- /// Call this method if you don't need a the FileIOPermission for anything other than calling Demand() once.
- ///
- /// This method tries to verify full access before allocating a FileIOPermission object.
- /// If full access is there, then we still have to emulate the checks that creating the
- /// FileIOPermission object would have performed.
- ///
- /// IMPORTANT: This method should only be used after calling GetFullPath on the path to verify
- /// </summary>
- internal static void QuickDemand(FileIOPermissionAccess access, string fullPath, bool checkForDuplicates = false, bool needFullPath = false)
- {
- EmulateFileIOPermissionChecks(fullPath);
- }
-
- /// <summary>
- /// Call this method if you don't need a the FileIOPermission for anything other than calling Demand() once.
- ///
- /// This method tries to verify full access before allocating a FileIOPermission object.
- /// If full access is there, then we still have to emulate the checks that creating the
- /// FileIOPermission object would have performed.
- ///
- /// IMPORTANT: This method should only be used after calling GetFullPath on the path to verify
- ///
- /// </summary>
- internal static void QuickDemand(FileIOPermissionAccess access, string[] fullPathList, bool checkForDuplicates = false, bool needFullPath = true)
- {
- foreach (string fullPath in fullPathList)
- {
- EmulateFileIOPermissionChecks(fullPath);
- }
- }
-
- internal static void QuickDemand(PermissionState state)
- {
- // Should be a no-op without CAS
- }
-
- /// <summary>
- /// Perform the additional path checks that would normally happen when creating a FileIOPermission object.
- /// </summary>
- /// <param name="fullPath">A path that has already gone through GetFullPath or Normalize</param>
- internal static void EmulateFileIOPermissionChecks(string fullPath)
- {
- // 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.
-
-#if !PLATFORM_UNIX
- // Checking for colon / invalid characters on device paths blocks legitimate access to objects such as named pipes.
- 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.)
- if (PathInternal.HasWildCardCharacters(fullPath))
- {
- throw new ArgumentException(Environment.GetResourceString("Argument_InvalidPathChars"));
- }
-
- if (PathInternal.HasInvalidVolumeSeparator(fullPath))
- {
- throw new NotSupportedException(Environment.GetResourceString("Argument_PathFormatNotSupported"));
- }
- }
-#endif // !PLATFORM_UNIX
- }
- }
-
- [Serializable]
- internal sealed class FileIOAccess
- {
-#if !FEATURE_CASE_SENSITIVE_FILESYSTEM
- private bool m_ignoreCase = true;
-#else
- private bool m_ignoreCase = false;
-#endif // !FEATURE_CASE_SENSITIVE_FILESYSTEM
-
- private StringExpressionSet m_set;
- private bool m_allFiles;
- private bool m_allLocalFiles;
- private bool m_pathDiscovery;
-
- private const String m_strAllFiles = "*AllFiles*";
- private const String m_strAllLocalFiles = "*AllLocalFiles*";
-
- public FileIOAccess()
- {
- m_set = new StringExpressionSet( m_ignoreCase, true );
- m_allFiles = false;
- m_allLocalFiles = false;
- m_pathDiscovery = false;
- }
-
- public FileIOAccess( bool pathDiscovery )
- {
- m_set = new StringExpressionSet( m_ignoreCase, true );
- m_allFiles = false;
- m_allLocalFiles = false;
- m_pathDiscovery = pathDiscovery;
- }
-
- public FileIOAccess( String value )
- {
- if (value == null)
- {
- m_set = new StringExpressionSet( m_ignoreCase, true );
- m_allFiles = false;
- m_allLocalFiles = false;
- }
- else if (value.Length >= m_strAllFiles.Length && String.Compare( m_strAllFiles, value, StringComparison.Ordinal) == 0)
- {
- m_set = new StringExpressionSet( m_ignoreCase, true );
- m_allFiles = true;
- m_allLocalFiles = false;
- }
- else if (value.Length >= m_strAllLocalFiles.Length && String.Compare( m_strAllLocalFiles, 0, value, 0, m_strAllLocalFiles.Length, StringComparison.Ordinal) == 0)
- {
- m_set = new StringExpressionSet( m_ignoreCase, value.Substring( m_strAllLocalFiles.Length ), true );
- m_allFiles = false;
- m_allLocalFiles = true;
- }
- else
- {
- m_set = new StringExpressionSet( m_ignoreCase, value, true );
- m_allFiles = false;
- m_allLocalFiles = false;
- }
- m_pathDiscovery = false;
- }
-
- public FileIOAccess( bool allFiles, bool allLocalFiles, bool pathDiscovery )
- {
- m_set = new StringExpressionSet( m_ignoreCase, true );
- m_allFiles = allFiles;
- m_allLocalFiles = allLocalFiles;
- m_pathDiscovery = pathDiscovery;
- }
-
- public FileIOAccess( StringExpressionSet set, bool allFiles, bool allLocalFiles, bool pathDiscovery )
- {
- m_set = set;
- m_set.SetThrowOnRelative( true );
- m_allFiles = allFiles;
- m_allLocalFiles = allLocalFiles;
- m_pathDiscovery = pathDiscovery;
- }
-
- private FileIOAccess( FileIOAccess operand )
- {
- m_set = operand.m_set.Copy();
- m_allFiles = operand.m_allFiles;
- m_allLocalFiles = operand.m_allLocalFiles;
- m_pathDiscovery = operand.m_pathDiscovery;
- }
-
- public void AddExpressions(ArrayList values, bool checkForDuplicates)
- {
- m_allFiles = false;
- m_set.AddExpressions(values, checkForDuplicates);
- }
-
- public bool AllFiles
- {
- get
- {
- return m_allFiles;
- }
-
- set
- {
- m_allFiles = value;
- }
- }
-
- public bool AllLocalFiles
- {
- get
- {
- return m_allLocalFiles;
- }
-
- set
- {
- m_allLocalFiles = value;
- }
- }
-
- public bool PathDiscovery
- {
- set
- {
- m_pathDiscovery = value;
- }
- }
-
- public bool IsEmpty()
- {
- return !m_allFiles && !m_allLocalFiles && (m_set == null || m_set.IsEmpty());
- }
-
- public FileIOAccess Copy()
- {
- return new FileIOAccess( this );
- }
-
- public FileIOAccess Union( FileIOAccess operand )
- {
- if (operand == null)
- {
- return this.IsEmpty() ? null : this.Copy();
- }
-
- Debug.Assert( this.m_pathDiscovery == operand.m_pathDiscovery, "Path discovery settings must match" );
-
- if (this.m_allFiles || operand.m_allFiles)
- {
- return new FileIOAccess( true, false, this.m_pathDiscovery );
- }
-
- return new FileIOAccess( this.m_set.Union( operand.m_set ), false, this.m_allLocalFiles || operand.m_allLocalFiles, this.m_pathDiscovery );
- }
-
- public FileIOAccess Intersect( FileIOAccess operand )
- {
- if (operand == null)
- {
- return null;
- }
-
- Debug.Assert( this.m_pathDiscovery == operand.m_pathDiscovery, "Path discovery settings must match" );
-
- if (this.m_allFiles)
- {
- if (operand.m_allFiles)
- {
- return new FileIOAccess( true, false, this.m_pathDiscovery );
- }
- else
- {
- return new FileIOAccess( operand.m_set.Copy(), false, operand.m_allLocalFiles, this.m_pathDiscovery );
- }
- }
- else if (operand.m_allFiles)
- {
- return new FileIOAccess( this.m_set.Copy(), false, this.m_allLocalFiles, this.m_pathDiscovery );
- }
-
- StringExpressionSet intersectionSet = new StringExpressionSet( m_ignoreCase, true );
-
- if (this.m_allLocalFiles)
- {
- String[] expressions = operand.m_set.UnsafeToStringArray();
-
- if (expressions != null)
- {
- for (int i = 0; i < expressions.Length; ++i)
- {
- String root = GetRoot( expressions[i] );
- if (root != null && IsLocalDrive( GetRoot( root ) ) )
- {
- intersectionSet.AddExpressions( new String[] { expressions[i] }, true, false );
- }
- }
- }
- }
-
- if (operand.m_allLocalFiles)
- {
- String[] expressions = this.m_set.UnsafeToStringArray();
-
- if (expressions != null)
- {
- for (int i = 0; i < expressions.Length; ++i)
- {
- String root = GetRoot( expressions[i] );
- if (root != null && IsLocalDrive(GetRoot(root)))
- {
- intersectionSet.AddExpressions( new String[] { expressions[i] }, true, false );
- }
- }
- }
- }
-
- String[] regularIntersection = this.m_set.Intersect( operand.m_set ).UnsafeToStringArray();
-
- if (regularIntersection != null)
- intersectionSet.AddExpressions( regularIntersection, !intersectionSet.IsEmpty(), false );
-
- return new FileIOAccess( intersectionSet, false, this.m_allLocalFiles && operand.m_allLocalFiles, this.m_pathDiscovery );
- }
-
- public bool IsSubsetOf( FileIOAccess operand )
- {
- if (operand == null)
- {
- return this.IsEmpty();
- }
-
- if (operand.m_allFiles)
- {
- return true;
- }
-
- 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 )))
- {
- if (operand.m_allLocalFiles)
- {
- String[] expressions = m_set.UnsafeToStringArray();
-
- for (int i = 0; i < expressions.Length; ++i)
- {
- String root = GetRoot( expressions[i] );
- if (root == null || !IsLocalDrive(GetRoot(root)))
- {
- return false;
- }
- }
- }
- else
- {
- return false;
- }
- }
-
- return true;
- }
-
- private static String GetRoot( String path )
- {
-#if !PLATFORM_UNIX
- String str = path.Substring( 0, 3 );
- if (str.EndsWith( ":\\", StringComparison.Ordinal))
-#else
- String str = path.Substring( 0, 1 );
- if(str == "/")
-#endif // !PLATFORM_UNIX
- {
- return str;
- }
- else
- {
- return null;
- }
- }
-
- public override String ToString()
- {
- // SafeCritical: all string expression sets are constructed with the throwOnRelative bit set, so
- // we're only exposing out the same paths that we took as input.
- if (m_allFiles)
- {
- return m_strAllFiles;
- }
- else
- {
- if (m_allLocalFiles)
- {
- String retstr = m_strAllLocalFiles;
-
- String tempStr = m_set.UnsafeToString();
-
- if (tempStr != null && tempStr.Length > 0)
- retstr += ";" + tempStr;
-
- return retstr;
- }
- else
- {
- return m_set.UnsafeToString();
- }
- }
- }
-
- public String[] ToStringArray()
- {
- // SafeCritical: all string expression sets are constructed with the throwOnRelative bit set, so
- // we're only exposing out the same paths that we took as input.
- return m_set.UnsafeToStringArray();
- }
-
- [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
- [SuppressUnmanagedCodeSecurity]
- internal static extern bool IsLocalDrive(String path);
-
- public override bool Equals(Object obj)
- {
- FileIOAccess operand = obj as FileIOAccess;
- if(operand == null)
- return (IsEmpty() && obj == null);
- Debug.Assert( this.m_pathDiscovery == operand.m_pathDiscovery, "Path discovery settings must match" );
- if(m_pathDiscovery)
- {
- if(this.m_allFiles && operand.m_allFiles)
- return true;
- if(this.m_allLocalFiles == operand.m_allLocalFiles &&
- m_set.IsSubsetOf(operand.m_set) &&
- operand.m_set.IsSubsetOf(m_set)) // Watch Out: This calls StringExpressionSet.IsSubsetOf, unlike below
- return true;
- return false;
- }
- else
- {
- if(!this.IsSubsetOf(operand)) // Watch Out: This calls FileIOAccess.IsSubsetOf, unlike above
- return false;
- if(!operand.IsSubsetOf(this))
- return false;
- return true;
- }
- }
-
- public override int GetHashCode()
- {
- // This implementation is only to silence a compiler warning.
- return base.GetHashCode();
- }
- }
-}
diff --git a/src/mscorlib/src/System/Security/Permissions/GACIdentityPermission.cs b/src/mscorlib/src/System/Security/Permissions/GACIdentityPermission.cs
deleted file mode 100644
index f93f26daa9..0000000000
--- a/src/mscorlib/src/System/Security/Permissions/GACIdentityPermission.cs
+++ /dev/null
@@ -1,103 +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.Security.Permissions
-{
- using System;
- using System.Globalization;
-
- [AttributeUsage(AttributeTargets.Method | AttributeTargets.Constructor | AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Assembly, AllowMultiple = true, Inherited = false )]
- [System.Runtime.InteropServices.ComVisible(true)]
- [Serializable]
-#pragma warning disable 618
- sealed public class GacIdentityPermissionAttribute : CodeAccessSecurityAttribute
-#pragma warning restore 618
- {
-#pragma warning disable 618
- public GacIdentityPermissionAttribute( SecurityAction action )
-#pragma warning restore 618
- : base( action )
- {
- }
-
- public override IPermission CreatePermission()
- {
- return new GacIdentityPermission();
- }
- }
-
-
- [System.Runtime.InteropServices.ComVisible(true)]
- [Serializable]
- sealed public class GacIdentityPermission : CodeAccessPermission, IBuiltInPermission
- {
- //------------------------------------------------------
- //
- // PUBLIC CONSTRUCTORS
- //
- //------------------------------------------------------
-
- public GacIdentityPermission(PermissionState state)
- {
- if (state != PermissionState.Unrestricted && state != PermissionState.None)
- {
- throw new ArgumentException(Environment.GetResourceString("Argument_InvalidPermissionState"));
- }
- }
-
- public GacIdentityPermission()
- {
- }
-
- //------------------------------------------------------
- //
- // IPERMISSION IMPLEMENTATION
- //
- //------------------------------------------------------
-
-
- public override IPermission Copy()
- {
- return new GacIdentityPermission();
- }
-
- public override bool IsSubsetOf(IPermission target)
- {
- if (target == null)
- return false;
- if (!(target is GacIdentityPermission))
- throw new ArgumentException(Environment.GetResourceString("Argument_WrongType", this.GetType().FullName));
- return true;
- }
-
- public override IPermission Intersect(IPermission target)
- {
- if (target == null)
- return null;
- if (!(target is GacIdentityPermission))
- throw new ArgumentException(Environment.GetResourceString("Argument_WrongType", this.GetType().FullName));
- return this.Copy();
- }
-
- public override IPermission Union(IPermission target)
- {
- if (target == null)
- return this.Copy();
- if (!(target is GacIdentityPermission))
- throw new ArgumentException(Environment.GetResourceString("Argument_WrongType", this.GetType().FullName));
- return this.Copy();
- }
-
- /// <internalonly/>
- int IBuiltInPermission.GetTokenIndex()
- {
- return GacIdentityPermission.GetTokenIndex();
- }
-
- internal static int GetTokenIndex()
- {
- return BuiltInPermissionIndex.GacIdentityPermissionIndex;
- }
- }
-}
diff --git a/src/mscorlib/src/System/Security/Permissions/HostProtectionPermission.cs b/src/mscorlib/src/System/Security/Permissions/HostProtectionPermission.cs
deleted file mode 100644
index c4facbb67e..0000000000
--- a/src/mscorlib/src/System/Security/Permissions/HostProtectionPermission.cs
+++ /dev/null
@@ -1,265 +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.Security.Permissions
-{
- using System;
- using System.IO;
- using System.Security.Util;
- using System.Text;
- using System.Threading;
- using System.Runtime.Remoting;
- using System.Security;
- using System.Runtime.Serialization;
- using System.Reflection;
- using System.Globalization;
- using System.Diagnostics.Contracts;
-
- // Keep this enum in sync with tools\ngen\ngen.cpp and inc\mscoree.idl
-
-[Serializable]
- [Flags]
- [System.Runtime.InteropServices.ComVisible(true)]
- public enum HostProtectionResource
- {
- None = 0x0,
- //--------------------------------
- Synchronization = 0x1,
- SharedState = 0x2,
- ExternalProcessMgmt = 0x4,
- SelfAffectingProcessMgmt = 0x8,
- ExternalThreading = 0x10,
- SelfAffectingThreading = 0x20,
- SecurityInfrastructure = 0x40,
- UI = 0x80,
- MayLeakOnAbort = 0x100,
- //---------------------------------
- All = 0x1ff,
- }
-
- [AttributeUsage(AttributeTargets.Method | AttributeTargets.Constructor | AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Assembly | AttributeTargets.Delegate, AllowMultiple = true, Inherited = false )]
- [System.Runtime.InteropServices.ComVisible(true)]
- [Serializable]
- // 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]
-#pragma warning disable 618
- sealed public class HostProtectionAttribute : CodeAccessSecurityAttribute
-#pragma warning restore 618
- {
- private HostProtectionResource m_resources = HostProtectionResource.None;
-
- public HostProtectionAttribute()
-#pragma warning disable 618
- : base( SecurityAction.LinkDemand )
-#pragma warning restore 618
- {
- }
-
-#pragma warning disable 618
- public HostProtectionAttribute( SecurityAction action )
-#pragma warning restore 618
- : base( action )
- {
-#pragma warning disable 618
- if (action != SecurityAction.LinkDemand)
-#pragma warning restore 618
- throw new ArgumentException(Environment.GetResourceString("Argument_InvalidFlag"));
- Contract.EndContractBlock();
- }
-
- public HostProtectionResource Resources {
- get { return m_resources; }
- set { m_resources = value; }
- }
-
- public bool Synchronization {
- get { return (m_resources & HostProtectionResource.Synchronization) != 0; }
- set { m_resources = (value ? m_resources | HostProtectionResource.Synchronization : m_resources & ~HostProtectionResource.Synchronization); }
- }
-
- public bool SharedState {
- get { return (m_resources & HostProtectionResource.SharedState) != 0; }
- set { m_resources = (value ? m_resources | HostProtectionResource.SharedState : m_resources & ~HostProtectionResource.SharedState); }
- }
-
- public bool ExternalProcessMgmt {
- get { return (m_resources & HostProtectionResource.ExternalProcessMgmt) != 0; }
- set { m_resources = (value ? m_resources | HostProtectionResource.ExternalProcessMgmt : m_resources & ~HostProtectionResource.ExternalProcessMgmt); }
- }
-
- public bool SelfAffectingProcessMgmt {
- get { return (m_resources & HostProtectionResource.SelfAffectingProcessMgmt) != 0; }
- set { m_resources = (value ? m_resources | HostProtectionResource.SelfAffectingProcessMgmt : m_resources & ~HostProtectionResource.SelfAffectingProcessMgmt); }
- }
-
- public bool ExternalThreading {
- get { return (m_resources & HostProtectionResource.ExternalThreading) != 0; }
- set { m_resources = (value ? m_resources | HostProtectionResource.ExternalThreading : m_resources & ~HostProtectionResource.ExternalThreading); }
- }
-
- public bool SelfAffectingThreading {
- get { return (m_resources & HostProtectionResource.SelfAffectingThreading) != 0; }
- set { m_resources = (value ? m_resources | HostProtectionResource.SelfAffectingThreading : m_resources & ~HostProtectionResource.SelfAffectingThreading); }
- }
-
-[System.Runtime.InteropServices.ComVisible(true)]
- public bool SecurityInfrastructure {
- get { return (m_resources & HostProtectionResource.SecurityInfrastructure) != 0; }
- set { m_resources = (value ? m_resources | HostProtectionResource.SecurityInfrastructure : m_resources & ~HostProtectionResource.SecurityInfrastructure); }
- }
-
- public bool UI {
- get { return (m_resources & HostProtectionResource.UI) != 0; }
- set { m_resources = (value ? m_resources | HostProtectionResource.UI : m_resources & ~HostProtectionResource.UI); }
- }
-
- public bool MayLeakOnAbort {
- get { return (m_resources & HostProtectionResource.MayLeakOnAbort) != 0; }
- set { m_resources = (value ? m_resources | HostProtectionResource.MayLeakOnAbort : m_resources & ~HostProtectionResource.MayLeakOnAbort); }
- }
-
- public override IPermission CreatePermission()
- {
- if (m_unrestricted)
- {
- return new HostProtectionPermission( PermissionState.Unrestricted );
- }
- else
- {
- return new HostProtectionPermission( m_resources );
- }
- }
- }
-
- [Serializable]
- sealed internal class HostProtectionPermission : CodeAccessPermission, IUnrestrictedPermission, IBuiltInPermission
- {
- //------------------------------------------------------
- //
- // GLOBALS
- //
- //------------------------------------------------------
-
- // This value is set by PermissionSet.FilterHostProtectionPermissions. It is only used for
- // constructing a HostProtectionException object. Changing it will not affect HostProtection.
- internal static volatile HostProtectionResource protectedResources = HostProtectionResource.None;
-
- //------------------------------------------------------
- //
- // MEMBERS
- //
- //------------------------------------------------------
- private HostProtectionResource m_resources;
-
- //------------------------------------------------------
- //
- // CONSTRUCTORS
- //
- //------------------------------------------------------
- public HostProtectionPermission(PermissionState state)
- {
- if (state == PermissionState.Unrestricted)
- Resources = HostProtectionResource.All;
- else if (state == PermissionState.None)
- Resources = HostProtectionResource.None;
- else
- throw new ArgumentException(Environment.GetResourceString("Argument_InvalidPermissionState"));
- }
-
- public HostProtectionPermission(HostProtectionResource resources)
- {
- Resources = resources;
- }
-
- //------------------------------------------------------
- //
- // IPermission interface implementation
- //
- //------------------------------------------------------
- public bool IsUnrestricted()
- {
- return Resources == HostProtectionResource.All;
- }
-
- //------------------------------------------------------
- //
- // Properties
- //
- //------------------------------------------------------
- public HostProtectionResource Resources
- {
- set
- {
- if(value < HostProtectionResource.None || value > HostProtectionResource.All)
- throw new ArgumentException(Environment.GetResourceString("Arg_EnumIllegalVal", (int)value));
- Contract.EndContractBlock();
- m_resources = value;
- }
-
- get
- {
- return m_resources;
- }
- }
-
- //------------------------------------------------------
- //
- // IPermission interface implementation
- //
- //------------------------------------------------------
- public override bool IsSubsetOf(IPermission target)
- {
- if (target == null)
- return m_resources == HostProtectionResource.None;
- if(this.GetType() != target.GetType())
- throw new ArgumentException( Environment.GetResourceString("Argument_WrongType", this.GetType().FullName) );
- return ((uint)this.m_resources & (uint)((HostProtectionPermission)target).m_resources) == (uint)this.m_resources;
- }
-
- public override IPermission Union(IPermission target)
- {
- if (target == null)
- return(this.Copy());
- if(this.GetType() != target.GetType())
- throw new ArgumentException( Environment.GetResourceString("Argument_WrongType", this.GetType().FullName) );
- HostProtectionResource newResources = (HostProtectionResource)((uint)this.m_resources | (uint)((HostProtectionPermission)target).m_resources);
- return new HostProtectionPermission(newResources);
- }
-
- public override IPermission Intersect(IPermission target)
- {
- if (target == null)
- return null;
- if(this.GetType() != target.GetType())
- throw new ArgumentException( Environment.GetResourceString("Argument_WrongType", this.GetType().FullName) );
- HostProtectionResource newResources = (HostProtectionResource)((uint)this.m_resources & (uint)((HostProtectionPermission)target).m_resources);
- if(newResources == HostProtectionResource.None)
- return null;
- return new HostProtectionPermission(newResources);
- }
-
- public override IPermission Copy()
- {
- return new HostProtectionPermission(m_resources);
- }
-
- //------------------------------------------------------
- //
- // OBJECT OVERRIDES
- //
- //------------------------------------------------------
-
- /// <internalonly/>
- int IBuiltInPermission.GetTokenIndex()
- {
- return HostProtectionPermission.GetTokenIndex();
- }
-
- internal static int GetTokenIndex()
- {
- return BuiltInPermissionIndex.HostProtectionPermissionIndex;
- }
- }
-}
diff --git a/src/mscorlib/src/System/Security/Permissions/IBuiltInPermission.cs b/src/mscorlib/src/System/Security/Permissions/IBuiltInPermission.cs
deleted file mode 100644
index 58b26bd9c4..0000000000
--- a/src/mscorlib/src/System/Security/Permissions/IBuiltInPermission.cs
+++ /dev/null
@@ -1,63 +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.Security.Permissions
-{
- internal interface IBuiltInPermission
- {
- int GetTokenIndex();
- }
-
- internal static class BuiltInPermissionIndex
- {
- internal const int NUM_BUILTIN_UNRESTRICTED = 10;
- internal const int NUM_BUILTIN_NORMAL = 7;
-
- // Unrestricted permissions
-
- internal const int EnvironmentPermissionIndex = 0;
- internal const int FileDialogPermissionIndex = 1;
- internal const int FileIOPermissionIndex = 2;
- internal const int IsolatedStorageFilePermissionIndex = 3;
- internal const int ReflectionPermissionIndex = 4;
- internal const int RegistryPermissionIndex = 5;
- internal const int SecurityPermissionIndex = 6;
- internal const int UIPermissionIndex = 7;
- internal const int PrincipalPermissionIndex = 8;
- internal const int HostProtectionPermissionIndex = 9;
-
- // Normal permissions
- internal const int PublisherIdentityPermissionIndex = 0 + NUM_BUILTIN_UNRESTRICTED;
- internal const int SiteIdentityPermissionIndex = 1 + NUM_BUILTIN_UNRESTRICTED;
- internal const int StrongNameIdentityPermissionIndex = 2 + NUM_BUILTIN_UNRESTRICTED;
- internal const int UrlIdentityPermissionIndex = 3 + NUM_BUILTIN_UNRESTRICTED;
- internal const int ZoneIdentityPermissionIndex = 4 + NUM_BUILTIN_UNRESTRICTED;
- internal const int GacIdentityPermissionIndex = 5 + NUM_BUILTIN_UNRESTRICTED;
- internal const int KeyContainerPermissionIndex = 6 + NUM_BUILTIN_UNRESTRICTED;
- }
-
- [Serializable]
- internal enum BuiltInPermissionFlag
- {
- // Unrestricted permissions
-
- EnvironmentPermission = 0x1,
- FileDialogPermission = 0x2,
- FileIOPermission = 0x4,
- IsolatedStorageFilePermission = 0x8,
- ReflectionPermission = 0x10,
- RegistryPermission = 0x20,
- SecurityPermission = 0x40,
- UIPermission = 0x80,
- PrincipalPermission = 0x100,
-
- // Normal permissions
- PublisherIdentityPermission = 0x200,
- SiteIdentityPermission = 0x400,
- StrongNameIdentityPermission = 0x800,
- UrlIdentityPermission = 0x1000,
- ZoneIdentityPermission = 0x2000,
- KeyContainerPermission = 0x4000,
- }
-}
diff --git a/src/mscorlib/src/System/Security/Permissions/IUnrestrictedPermission.cs b/src/mscorlib/src/System/Security/Permissions/IUnrestrictedPermission.cs
deleted file mode 100644
index 782df8012c..0000000000
--- a/src/mscorlib/src/System/Security/Permissions/IUnrestrictedPermission.cs
+++ /dev/null
@@ -1,13 +0,0 @@
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-// See the LICENSE file in the project root for more information.
-
-namespace System.Security.Permissions {
-
- using System;
-[System.Runtime.InteropServices.ComVisible(true)]
- public interface IUnrestrictedPermission
- {
- bool IsUnrestricted();
- }
-}
diff --git a/src/mscorlib/src/System/Security/Permissions/IsolatedStorageFilePermission.cs b/src/mscorlib/src/System/Security/Permissions/IsolatedStorageFilePermission.cs
deleted file mode 100644
index 42bc648c72..0000000000
--- a/src/mscorlib/src/System/Security/Permissions/IsolatedStorageFilePermission.cs
+++ /dev/null
@@ -1,163 +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 permission is used to controls/administer access to
-// IsolatedStorageFile
-//
-
-namespace System.Security.Permissions {
-
- using System.Globalization;
-
- [Serializable]
-[System.Runtime.InteropServices.ComVisible(true)]
- sealed public class IsolatedStorageFilePermission : IsolatedStoragePermission, IBuiltInPermission
- {
- public IsolatedStorageFilePermission(PermissionState state)
- : base(state) { }
-
- internal IsolatedStorageFilePermission(IsolatedStorageContainment UsageAllowed,
- long ExpirationDays, bool PermanentData)
- : base(UsageAllowed, ExpirationDays, PermanentData) { }
-
- //------------------------------------------------------
- //
- // IPERMISSION IMPLEMENTATION
- //
- //------------------------------------------------------
-
- public override IPermission Union(IPermission target)
- {
- if (target == null)
- {
- return this.Copy();
- }
- else if (!VerifyType(target))
- {
- throw new
- ArgumentException(
- Environment.GetResourceString("Argument_WrongType", this.GetType().FullName)
- );
- }
-
- IsolatedStorageFilePermission operand = (IsolatedStorageFilePermission)target;
-
- if (this.IsUnrestricted() || operand.IsUnrestricted())
- {
- return new IsolatedStorageFilePermission( PermissionState.Unrestricted );
- }
- else
- {
- IsolatedStorageFilePermission union;
- union = new IsolatedStorageFilePermission( PermissionState.None );
- union.m_userQuota = max(m_userQuota,operand.m_userQuota);
- union.m_machineQuota = max(m_machineQuota,operand.m_machineQuota);
- union.m_expirationDays = max(m_expirationDays,operand.m_expirationDays);
- union.m_permanentData = m_permanentData || operand.m_permanentData;
- union.m_allowed = (IsolatedStorageContainment)max((long)m_allowed,(long)operand.m_allowed);
- return union;
- }
- }
-
- public override bool IsSubsetOf(IPermission target)
- {
- if (target == null)
- {
- return ((m_userQuota == 0) &&
- (m_machineQuota == 0) &&
- (m_expirationDays == 0) &&
- (m_permanentData == false) &&
- (m_allowed == IsolatedStorageContainment.None));
- }
-
- try
- {
- IsolatedStorageFilePermission operand = (IsolatedStorageFilePermission)target;
-
- if (operand.IsUnrestricted())
- return true;
-
- return ((operand.m_userQuota >= m_userQuota) &&
- (operand.m_machineQuota >= m_machineQuota) &&
- (operand.m_expirationDays >= m_expirationDays) &&
- (operand.m_permanentData || !m_permanentData) &&
- (operand.m_allowed >= m_allowed));
- }
- catch (InvalidCastException)
- {
- throw new
- ArgumentException(
- Environment.GetResourceString("Argument_WrongType", this.GetType().FullName)
- );
- }
-
- }
-
- public override IPermission Intersect(IPermission target)
- {
- if (target == null)
- return null;
- else if (!VerifyType(target))
- {
- throw new
- ArgumentException(
- Environment.GetResourceString("Argument_WrongType", this.GetType().FullName)
- );
- }
-
- IsolatedStorageFilePermission operand = (IsolatedStorageFilePermission)target;
-
- if(operand.IsUnrestricted())
- return Copy();
- else if(IsUnrestricted())
- return target.Copy();
-
- IsolatedStorageFilePermission intersection;
- intersection = new IsolatedStorageFilePermission( PermissionState.None );
- intersection.m_userQuota = min(m_userQuota,operand.m_userQuota);
- intersection.m_machineQuota = min(m_machineQuota,operand.m_machineQuota);
- intersection.m_expirationDays = min(m_expirationDays,operand.m_expirationDays);
- intersection.m_permanentData = m_permanentData && operand.m_permanentData;
- intersection.m_allowed = (IsolatedStorageContainment)min((long)m_allowed,(long)operand.m_allowed);
-
- if ((intersection.m_userQuota == 0) &&
- (intersection.m_machineQuota == 0) &&
- (intersection.m_expirationDays == 0) &&
- (intersection.m_permanentData == false) &&
- (intersection.m_allowed == IsolatedStorageContainment.None))
- return null;
-
- return intersection;
- }
-
- public override IPermission Copy()
- {
- IsolatedStorageFilePermission copy ;
- copy = new IsolatedStorageFilePermission(PermissionState.Unrestricted);
- if(!IsUnrestricted()){
- copy.m_userQuota = m_userQuota;
- copy.m_machineQuota = m_machineQuota;
- copy.m_expirationDays = m_expirationDays;
- copy.m_permanentData = m_permanentData;
- copy.m_allowed = m_allowed;
- }
- return copy;
- }
-
-
- /// <internalonly/>
- int IBuiltInPermission.GetTokenIndex()
- {
- return IsolatedStorageFilePermission.GetTokenIndex();
- }
-
- internal static int GetTokenIndex()
- {
- return BuiltInPermissionIndex.IsolatedStorageFilePermissionIndex;
- }
- }
-}
-
diff --git a/src/mscorlib/src/System/Security/Permissions/IsolatedStoragePermission.cs b/src/mscorlib/src/System/Security/Permissions/IsolatedStoragePermission.cs
deleted file mode 100644
index 9f09a37098..0000000000
--- a/src/mscorlib/src/System/Security/Permissions/IsolatedStoragePermission.cs
+++ /dev/null
@@ -1,183 +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.Security.Permissions {
-
- using System;
- using System.IO;
- using System.Security;
- using System.Security.Util;
- using System.Globalization;
-
- [Serializable]
-[System.Runtime.InteropServices.ComVisible(true)]
- public enum IsolatedStorageContainment {
- None = 0x00,
- DomainIsolationByUser = 0x10,
- ApplicationIsolationByUser = 0x15,
- AssemblyIsolationByUser = 0x20,
- DomainIsolationByMachine = 0x30,
- AssemblyIsolationByMachine = 0x40,
- ApplicationIsolationByMachine = 0x45,
- DomainIsolationByRoamingUser = 0x50,
- AssemblyIsolationByRoamingUser = 0x60,
- ApplicationIsolationByRoamingUser = 0x65,
- AdministerIsolatedStorageByUser = 0x70,
- //AdministerIsolatedStorageByMachine = 0x80,
- UnrestrictedIsolatedStorage = 0xF0
- };
-
-
- [Serializable]
- [System.Runtime.InteropServices.ComVisible(true)]
- abstract public class IsolatedStoragePermission
- : CodeAccessPermission, IUnrestrictedPermission
- {
-
- //------------------------------------------------------
- //
- // PRIVATE STATE DATA
- //
- //------------------------------------------------------
-
- /// <internalonly/>
- internal long m_userQuota;
- /// <internalonly/>
- internal long m_machineQuota;
- /// <internalonly/>
- internal long m_expirationDays;
- /// <internalonly/>
- internal bool m_permanentData;
- /// <internalonly/>
- internal IsolatedStorageContainment m_allowed;
-
- //------------------------------------------------------
- //
- // CONSTRUCTORS
- //
- //------------------------------------------------------
-
- protected IsolatedStoragePermission(PermissionState state)
- {
- if (state == PermissionState.Unrestricted)
- {
- m_userQuota = Int64.MaxValue;
- m_machineQuota = Int64.MaxValue;
- m_expirationDays = Int64.MaxValue ;
- m_permanentData = true;
- m_allowed = IsolatedStorageContainment.UnrestrictedIsolatedStorage;
- }
- else if (state == PermissionState.None)
- {
- m_userQuota = 0;
- m_machineQuota = 0;
- m_expirationDays = 0;
- m_permanentData = false;
- m_allowed = IsolatedStorageContainment.None;
- }
- else
- {
- throw new ArgumentException(Environment.GetResourceString("Argument_InvalidPermissionState"));
- }
- }
-
- internal IsolatedStoragePermission(IsolatedStorageContainment UsageAllowed,
- long ExpirationDays, bool PermanentData)
-
- {
- m_userQuota = 0; // typical demand won't include quota
- m_machineQuota = 0; // typical demand won't include quota
- m_expirationDays = ExpirationDays;
- m_permanentData = PermanentData;
- m_allowed = UsageAllowed;
- }
-
- internal IsolatedStoragePermission(IsolatedStorageContainment UsageAllowed,
- long ExpirationDays, bool PermanentData, long UserQuota)
-
- {
- m_machineQuota = 0;
- m_userQuota = UserQuota;
- m_expirationDays = ExpirationDays;
- m_permanentData = PermanentData;
- m_allowed = UsageAllowed;
- }
-
-
- //------------------------------------------------------
- //
- // PUBLIC ACCESSOR METHODS
- //
- //------------------------------------------------------
-
- // 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;
- }
- }
-
-
- //------------------------------------------------------
- //
- // CODEACCESSPERMISSION IMPLEMENTATION
- //
- //------------------------------------------------------
-
- public bool IsUnrestricted()
- {
- return m_allowed == IsolatedStorageContainment.UnrestrictedIsolatedStorage;
- }
-
-
- //------------------------------------------------------
- //
- // INTERNAL METHODS
- //
- //------------------------------------------------------
- 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;}
- }
-}
diff --git a/src/mscorlib/src/System/Security/Permissions/PermissionAttributes.cs b/src/mscorlib/src/System/Security/Permissions/PermissionAttributes.cs
deleted file mode 100644
index b6ac8ece3c..0000000000
--- a/src/mscorlib/src/System/Security/Permissions/PermissionAttributes.cs
+++ /dev/null
@@ -1,880 +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.Security.Permissions
-{
-
- using System.Security.Util;
- using System.IO;
- using System.Security.Policy;
- using System.Text;
- using System.Threading;
- using System.Runtime.InteropServices;
- using System.Runtime.Remoting;
- using System.Runtime.Serialization;
-#if FEATURE_X509
- using System.Security.Cryptography.X509Certificates;
-#endif
- using System.Runtime.Versioning;
- using System.Diagnostics.Contracts;
-
- [Serializable]
- [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.")]
- public enum SecurityAction
- {
- // Demand permission of all caller
- Demand = 2,
-
- // Assert permission so callers don't need
- Assert = 3,
-
- // Deny permissions so checks will fail
- [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.")]
- Deny = 4,
-
- // Reduce permissions so check will fail
- PermitOnly = 5,
-
- // Demand permission of caller
- LinkDemand = 6,
-
- // Demand permission of a subclass
- InheritanceDemand = 7,
-
- // Request minimum permissions to run
- [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.")]
- RequestMinimum = 8,
-
- // Request optional additional permissions
- [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.")]
- RequestOptional = 9,
-
- // Refuse to be granted these permissions
- [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.")]
- RequestRefuse = 10,
- }
-
- [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.")]
- public abstract class SecurityAttribute : System.Attribute
- {
- /// <internalonly/>
- internal SecurityAction m_action;
- /// <internalonly/>
- internal bool m_unrestricted;
-
- protected SecurityAttribute( SecurityAction action )
- {
- m_action = action;
- }
-
- public SecurityAction Action
- {
- get { return m_action; }
- set { m_action = value; }
- }
-
- public bool Unrestricted
- {
- get { return m_unrestricted; }
- set { m_unrestricted = value; }
- }
-
- abstract public IPermission CreatePermission();
-
- internal static unsafe IntPtr FindSecurityAttributeTypeHandle(String typeName)
- {
- PermissionSet.s_fullTrust.Assert();
- Type t = Type.GetType(typeName, false, false);
- if(t == null)
- return IntPtr.Zero;
- IntPtr typeHandle = t.TypeHandle.Value;
- return typeHandle;
- }
- }
-
- [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.")]
- public abstract class CodeAccessSecurityAttribute : SecurityAttribute
- {
- protected CodeAccessSecurityAttribute( SecurityAction action )
- : base( action )
- {
- }
- }
-
- [AttributeUsage(AttributeTargets.Method | AttributeTargets.Constructor | AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Assembly, AllowMultiple = true, Inherited = false )]
-[System.Runtime.InteropServices.ComVisible(true)]
- [Serializable]
-#pragma warning disable 618
- sealed public class EnvironmentPermissionAttribute : CodeAccessSecurityAttribute
-#pragma warning restore 618
- {
- private String m_read = null;
- private String m_write = null;
-
-#pragma warning disable 618
- public EnvironmentPermissionAttribute( SecurityAction action )
-#pragma warning restore 618
- : base( action )
- {
- }
-
- public String Read {
- get { return m_read; }
- set { m_read = value; }
- }
-
- public String Write {
- get { return m_write; }
- set { m_write = value; }
- }
-
- public String All {
- get { throw new NotSupportedException( Environment.GetResourceString( "NotSupported_GetMethod" ) ); }
- set { m_write = value; m_read = value; }
- }
-
- public override IPermission CreatePermission()
- {
- if (m_unrestricted)
- {
- return new EnvironmentPermission(PermissionState.Unrestricted);
- }
- else
- {
- EnvironmentPermission perm = new EnvironmentPermission(PermissionState.None);
- if (m_read != null)
- perm.SetPathList( EnvironmentPermissionAccess.Read, m_read );
- if (m_write != null)
- perm.SetPathList( EnvironmentPermissionAccess.Write, m_write );
- return perm;
- }
- }
- }
-
- [AttributeUsage(AttributeTargets.Method | AttributeTargets.Constructor | AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Assembly, AllowMultiple = true, Inherited = false )]
-[System.Runtime.InteropServices.ComVisible(true)]
- [Serializable]
-#pragma warning disable 618
- sealed public class FileDialogPermissionAttribute : CodeAccessSecurityAttribute
-#pragma warning restore 618
- {
- private FileDialogPermissionAccess m_access;
-
-#pragma warning disable 618
- public FileDialogPermissionAttribute( SecurityAction action )
-#pragma warning restore 618
- : base( action )
- {
- }
-
- public bool Open
- {
- get { return (m_access & FileDialogPermissionAccess.Open) != 0; }
- set { m_access = value ? m_access | FileDialogPermissionAccess.Open : m_access & ~FileDialogPermissionAccess.Open; }
- }
-
- public bool Save
- {
- get { return (m_access & FileDialogPermissionAccess.Save) != 0; }
- set { m_access = value ? m_access | FileDialogPermissionAccess.Save : m_access & ~FileDialogPermissionAccess.Save; }
- }
-
- public override IPermission CreatePermission()
- {
- if (m_unrestricted)
- {
- return new FileDialogPermission( PermissionState.Unrestricted );
- }
- else
- {
- return new FileDialogPermission( m_access );
- }
- }
- }
-
-
- [AttributeUsage(AttributeTargets.Method | AttributeTargets.Constructor | AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Assembly, AllowMultiple = true, Inherited = false )]
-[System.Runtime.InteropServices.ComVisible(true)]
- [Serializable]
-#pragma warning disable 618
- sealed public class FileIOPermissionAttribute : CodeAccessSecurityAttribute
-#pragma warning restore 618
- {
- private String m_read = null;
- private String m_write = null;
- private String m_append = null;
- private String m_pathDiscovery = null;
- private String m_viewAccess = null;
- private String m_changeAccess = null;
- [OptionalField(VersionAdded = 2)] private FileIOPermissionAccess m_allLocalFiles = FileIOPermissionAccess.NoAccess;
- [OptionalField(VersionAdded = 2)] private FileIOPermissionAccess m_allFiles = FileIOPermissionAccess.NoAccess;
-
-#pragma warning disable 618
- public FileIOPermissionAttribute( SecurityAction action )
-#pragma warning restore 618
- : base( action )
- {
- }
-
- public String Read {
- get { return m_read; }
- set { m_read = value; }
- }
-
- public String Write {
- get { return m_write; }
- set { m_write = value; }
- }
-
- public String Append {
- get { return m_append; }
- set { m_append = value; }
- }
-
- public String PathDiscovery {
- get { return m_pathDiscovery; }
- set { m_pathDiscovery = value; }
- }
-
- public String ViewAccessControl {
- get { return m_viewAccess; }
- set { m_viewAccess = value; }
- }
-
- public String ChangeAccessControl {
- get { return m_changeAccess; }
- set { m_changeAccess = value; }
- }
-
- [Obsolete("Please use the ViewAndModify property instead.")]
- public String All {
- set { m_read = value; m_write = value; m_append = value; m_pathDiscovery = value; }
- get { throw new NotSupportedException( Environment.GetResourceString( "NotSupported_GetMethod" ) ); }
- }
-
- // Read, Write, Append, PathDiscovery, but no ACL-related permissions
- public String ViewAndModify {
- get { throw new NotSupportedException( Environment.GetResourceString( "NotSupported_GetMethod" ) ); }
- set { m_read = value; m_write = value; m_append = value; m_pathDiscovery = value; }
- }
-
- public FileIOPermissionAccess AllFiles {
- get { return m_allFiles; }
- set { m_allFiles = value; }
- }
-
- public FileIOPermissionAccess AllLocalFiles {
- get { return m_allLocalFiles; }
- set { m_allLocalFiles = value; }
- }
-
- public override IPermission CreatePermission()
- {
- if (m_unrestricted)
- {
- return new FileIOPermission(PermissionState.Unrestricted);
- }
- else
- {
- FileIOPermission perm = new FileIOPermission(PermissionState.None);
- if (m_read != null)
- perm.SetPathList( FileIOPermissionAccess.Read, m_read );
- if (m_write != null)
- perm.SetPathList( FileIOPermissionAccess.Write, m_write );
- if (m_append != null)
- perm.SetPathList( FileIOPermissionAccess.Append, m_append );
- if (m_pathDiscovery != null)
- perm.SetPathList( FileIOPermissionAccess.PathDiscovery, m_pathDiscovery );
-
- perm.AllFiles = m_allFiles;
- perm.AllLocalFiles = m_allLocalFiles;
- return perm;
- }
- }
- }
-
- [AttributeUsage(AttributeTargets.Method | AttributeTargets.Constructor | AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Assembly, AllowMultiple = true, Inherited = false )]
- [Serializable]
-[System.Runtime.InteropServices.ComVisible(true)]
-#pragma warning disable 618
- public sealed class KeyContainerPermissionAttribute : CodeAccessSecurityAttribute {
-#pragma warning restore 618
- KeyContainerPermissionFlags m_flags = KeyContainerPermissionFlags.NoFlags;
- private string m_keyStore;
- private string m_providerName;
- private int m_providerType = -1;
- private string m_keyContainerName;
- private int m_keySpec = -1;
-
-#pragma warning disable 618
- public KeyContainerPermissionAttribute(SecurityAction action) : base(action) {}
-#pragma warning restore 618
-
- public string KeyStore {
- get { return m_keyStore; }
- set { m_keyStore = value; }
- }
-
- public string ProviderName {
- get { return m_providerName; }
- set { m_providerName = value; }
- }
-
- public int ProviderType {
- get { return m_providerType; }
- set { m_providerType = value; }
- }
-
- public string KeyContainerName {
- get { return m_keyContainerName; }
- set { m_keyContainerName = value; }
- }
-
- public int KeySpec {
- get { return m_keySpec; }
- set { m_keySpec = value; }
- }
-
- public KeyContainerPermissionFlags Flags {
- get { return m_flags; }
- set { m_flags = value; }
- }
-
- public override IPermission CreatePermission() {
- if (m_unrestricted) {
- return new KeyContainerPermission(PermissionState.Unrestricted);
- } else {
- if (KeyContainerPermissionAccessEntry.IsUnrestrictedEntry(m_keyStore, m_providerName, m_providerType, m_keyContainerName, m_keySpec))
- return new KeyContainerPermission(m_flags);
-
- // create a KeyContainerPermission with a single access entry.
- KeyContainerPermission cp = new KeyContainerPermission(KeyContainerPermissionFlags.NoFlags);
- KeyContainerPermissionAccessEntry accessEntry = new KeyContainerPermissionAccessEntry(m_keyStore, m_providerName, m_providerType, m_keyContainerName, m_keySpec, m_flags);
- cp.AccessEntries.Add(accessEntry);
- return cp;
- }
- }
- }
-
- [AttributeUsage(AttributeTargets.Method | AttributeTargets.Constructor | AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Assembly, AllowMultiple = true, Inherited = false )]
-[System.Runtime.InteropServices.ComVisible(true)]
- [Serializable]
-#pragma warning disable 618
- sealed public class ReflectionPermissionAttribute : CodeAccessSecurityAttribute
-#pragma warning restore 618
- {
- private ReflectionPermissionFlag m_flag = ReflectionPermissionFlag.NoFlags;
-
-#pragma warning disable 618
- public ReflectionPermissionAttribute( SecurityAction action )
-#pragma warning restore 618
- : base( action )
- {
- }
-
- public ReflectionPermissionFlag Flags {
- get { return m_flag; }
- set { m_flag = value; }
- }
-
- [Obsolete("This API has been deprecated. http://go.microsoft.com/fwlink/?linkid=14202")]
- public bool TypeInformation {
-#pragma warning disable 618
- get { return (m_flag & ReflectionPermissionFlag.TypeInformation) != 0; }
- set { m_flag = value ? m_flag | ReflectionPermissionFlag.TypeInformation : m_flag & ~ReflectionPermissionFlag.TypeInformation; }
-#pragma warning restore 618
- }
-
- public bool MemberAccess {
- get { return (m_flag & ReflectionPermissionFlag.MemberAccess) != 0; }
- set { m_flag = value ? m_flag | ReflectionPermissionFlag.MemberAccess : m_flag & ~ReflectionPermissionFlag.MemberAccess; }
- }
-
- [Obsolete("This permission is no longer used by the CLR.")]
- public bool ReflectionEmit {
-#pragma warning disable 618
- get { return (m_flag & ReflectionPermissionFlag.ReflectionEmit) != 0; }
- set { m_flag = value ? m_flag | ReflectionPermissionFlag.ReflectionEmit : m_flag & ~ReflectionPermissionFlag.ReflectionEmit; }
-#pragma warning restore 618
- }
-
- public bool RestrictedMemberAccess
- {
- get { return (m_flag & ReflectionPermissionFlag.RestrictedMemberAccess) != 0; }
- set { m_flag = value ? m_flag | ReflectionPermissionFlag.RestrictedMemberAccess : m_flag & ~ReflectionPermissionFlag.RestrictedMemberAccess; }
- }
-
- public override IPermission CreatePermission()
- {
- if (m_unrestricted)
- {
- return new ReflectionPermission( PermissionState.Unrestricted );
- }
- else
- {
- return new ReflectionPermission( m_flag );
- }
- }
- }
-
- [AttributeUsage(AttributeTargets.Method | AttributeTargets.Constructor | AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Assembly, AllowMultiple = true, Inherited = false )]
-[System.Runtime.InteropServices.ComVisible(true)]
- [Serializable]
-#pragma warning disable 618
- sealed public class RegistryPermissionAttribute : CodeAccessSecurityAttribute
-#pragma warning restore 618
- {
- private String m_read = null;
- private String m_write = null;
- private String m_create = null;
- private String m_viewAcl = null;
- private String m_changeAcl = null;
-
-#pragma warning disable 618
- public RegistryPermissionAttribute( SecurityAction action )
-#pragma warning restore 618
- : base( action )
- {
- }
-
- public String Read {
- get { return m_read; }
- set { m_read = value; }
- }
-
- public String Write {
- get { return m_write; }
- set { m_write = value; }
- }
-
- public String Create {
- get { return m_create; }
- set { m_create = value; }
- }
-
- public String ViewAccessControl {
- get { return m_viewAcl; }
- set { m_viewAcl = value; }
- }
-
- public String ChangeAccessControl {
- get { return m_changeAcl; }
- set { m_changeAcl = value; }
- }
-
- // Read, Write, & Create, but no ACL's
- public String ViewAndModify {
- get { throw new NotSupportedException( Environment.GetResourceString( "NotSupported_GetMethod" ) ); }
- set { m_read = value; m_write = value; m_create = value; }
- }
-
- [Obsolete("Please use the ViewAndModify property instead.")]
- public String All {
- get { throw new NotSupportedException( Environment.GetResourceString( "NotSupported_GetMethod" ) ); }
- set { m_read = value; m_write = value; m_create = value; }
- }
-
- public override IPermission CreatePermission()
- {
- if (m_unrestricted)
- {
- return new RegistryPermission( PermissionState.Unrestricted );
- }
- else
- {
- RegistryPermission perm = new RegistryPermission(PermissionState.None);
- if (m_read != null)
- perm.SetPathList( RegistryPermissionAccess.Read, m_read );
- if (m_write != null)
- perm.SetPathList( RegistryPermissionAccess.Write, m_write );
- if (m_create != null)
- perm.SetPathList( RegistryPermissionAccess.Create, m_create );
- return perm;
- }
- }
- }
-
- [AttributeUsage(AttributeTargets.Method | AttributeTargets.Constructor | AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Assembly, AllowMultiple = true, Inherited = false )]
- [System.Runtime.InteropServices.ComVisible(true)]
- [Serializable]
- // The csharp compiler requires these types to be public, but they are not used elsewhere.
- [Obsolete("SecurityPermissionAttribute is no longer accessible to application code.")]
- sealed public class SecurityPermissionAttribute : CodeAccessSecurityAttribute
- {
- private SecurityPermissionFlag m_flag = SecurityPermissionFlag.NoFlags;
-
- public SecurityPermissionAttribute( SecurityAction action )
- : base( action )
- {
- }
-
- public SecurityPermissionFlag Flags {
- get { return m_flag; }
- set { m_flag = value; }
- }
-
- public bool Assertion {
- get { return (m_flag & SecurityPermissionFlag.Assertion) != 0; }
- set { m_flag = value ? m_flag | SecurityPermissionFlag.Assertion : m_flag & ~SecurityPermissionFlag.Assertion; }
- }
-
- public bool UnmanagedCode {
- get { return (m_flag & SecurityPermissionFlag.UnmanagedCode) != 0; }
- set { m_flag = value ? m_flag | SecurityPermissionFlag.UnmanagedCode : m_flag & ~SecurityPermissionFlag.UnmanagedCode; }
- }
-
- public bool SkipVerification {
- get { return (m_flag & SecurityPermissionFlag.SkipVerification) != 0; }
- set { m_flag = value ? m_flag | SecurityPermissionFlag.SkipVerification : m_flag & ~SecurityPermissionFlag.SkipVerification; }
- }
-
- public bool Execution {
- get { return (m_flag & SecurityPermissionFlag.Execution) != 0; }
- set { m_flag = value ? m_flag | SecurityPermissionFlag.Execution : m_flag & ~SecurityPermissionFlag.Execution; }
- }
-
- public bool ControlThread {
- get { return (m_flag & SecurityPermissionFlag.ControlThread) != 0; }
- set { m_flag = value ? m_flag | SecurityPermissionFlag.ControlThread : m_flag & ~SecurityPermissionFlag.ControlThread; }
- }
-
- public bool ControlEvidence {
- get { return (m_flag & SecurityPermissionFlag.ControlEvidence) != 0; }
- set { m_flag = value ? m_flag | SecurityPermissionFlag.ControlEvidence : m_flag & ~SecurityPermissionFlag.ControlEvidence; }
- }
-
- public bool ControlPolicy {
- get { return (m_flag & SecurityPermissionFlag.ControlPolicy) != 0; }
- set { m_flag = value ? m_flag | SecurityPermissionFlag.ControlPolicy : m_flag & ~SecurityPermissionFlag.ControlPolicy; }
- }
-
- public bool SerializationFormatter {
- get { return (m_flag & SecurityPermissionFlag.SerializationFormatter) != 0; }
- set { m_flag = value ? m_flag | SecurityPermissionFlag.SerializationFormatter : m_flag & ~SecurityPermissionFlag.SerializationFormatter; }
- }
-
- public bool ControlDomainPolicy {
- get { return (m_flag & SecurityPermissionFlag.ControlDomainPolicy) != 0; }
- set { m_flag = value ? m_flag | SecurityPermissionFlag.ControlDomainPolicy : m_flag & ~SecurityPermissionFlag.ControlDomainPolicy; }
- }
-
- public bool ControlPrincipal {
- get { return (m_flag & SecurityPermissionFlag.ControlPrincipal) != 0; }
- set { m_flag = value ? m_flag | SecurityPermissionFlag.ControlPrincipal : m_flag & ~SecurityPermissionFlag.ControlPrincipal; }
- }
-
- public bool ControlAppDomain {
- get { return (m_flag & SecurityPermissionFlag.ControlAppDomain) != 0; }
- set { m_flag = value ? m_flag | SecurityPermissionFlag.ControlAppDomain : m_flag & ~SecurityPermissionFlag.ControlAppDomain; }
- }
-
- public bool RemotingConfiguration {
- get { return (m_flag & SecurityPermissionFlag.RemotingConfiguration) != 0; }
- set { m_flag = value ? m_flag | SecurityPermissionFlag.RemotingConfiguration : m_flag & ~SecurityPermissionFlag.RemotingConfiguration; }
- }
-
- [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; }
- }
-
- public bool BindingRedirects {
- get { return (m_flag & SecurityPermissionFlag.BindingRedirects) != 0; }
- set { m_flag = value ? m_flag | SecurityPermissionFlag.BindingRedirects : m_flag & ~SecurityPermissionFlag.BindingRedirects; }
- }
-
- public override IPermission CreatePermission()
- {
- if (m_unrestricted)
- {
- return new SecurityPermission( PermissionState.Unrestricted );
- }
- else
- {
- return new SecurityPermission( m_flag );
- }
- }
- }
-
- [AttributeUsage(AttributeTargets.Method | AttributeTargets.Constructor | AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Assembly, AllowMultiple = true, Inherited = false )]
-[System.Runtime.InteropServices.ComVisible(true)]
- [Serializable]
-#pragma warning disable 618
- sealed public class UIPermissionAttribute : CodeAccessSecurityAttribute
-#pragma warning restore 618
- {
- private UIPermissionWindow m_windowFlag = UIPermissionWindow.NoWindows;
- private UIPermissionClipboard m_clipboardFlag = UIPermissionClipboard.NoClipboard;
-
-#pragma warning disable 618
- public UIPermissionAttribute( SecurityAction action )
-#pragma warning restore 618
- : base( action )
- {
- }
-
- public UIPermissionWindow Window {
- get { return m_windowFlag; }
- set { m_windowFlag = value; }
- }
-
- public UIPermissionClipboard Clipboard {
- get { return m_clipboardFlag; }
- set { m_clipboardFlag = value; }
- }
-
- public override IPermission CreatePermission()
- {
- if (m_unrestricted)
- {
- return new UIPermission( PermissionState.Unrestricted );
- }
- else
- {
- return new UIPermission( m_windowFlag, m_clipboardFlag );
- }
- }
- }
-
- [AttributeUsage(AttributeTargets.Method | AttributeTargets.Constructor | AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Assembly, AllowMultiple = true, Inherited = false )]
-[System.Runtime.InteropServices.ComVisible(true)]
- [Serializable]
-#pragma warning disable 618
- sealed public class ZoneIdentityPermissionAttribute : CodeAccessSecurityAttribute
-#pragma warning restore 618
- {
- private SecurityZone m_flag = SecurityZone.NoZone;
-
-#pragma warning disable 618
- public ZoneIdentityPermissionAttribute( SecurityAction action )
-#pragma warning restore 618
- : base( action )
- {
- }
-
- public SecurityZone Zone {
- get { return m_flag; }
- set { m_flag = value; }
- }
-
- public override IPermission CreatePermission()
- {
- if (m_unrestricted)
- {
- return new ZoneIdentityPermission(PermissionState.Unrestricted);
- }
- else
- {
- return new ZoneIdentityPermission( m_flag );
- }
- }
- }
-
- [AttributeUsage(AttributeTargets.Method | AttributeTargets.Constructor | AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Assembly, AllowMultiple = true, Inherited = false )]
-[System.Runtime.InteropServices.ComVisible(true)]
- [Serializable]
-#pragma warning disable 618
- sealed public class StrongNameIdentityPermissionAttribute : CodeAccessSecurityAttribute
-#pragma warning restore 618
- {
- private String m_name = null;
- private String m_version = null;
- private String m_blob = null;
-
-#pragma warning disable 618
- public StrongNameIdentityPermissionAttribute( SecurityAction action )
-#pragma warning restore 618
- : base( action )
- {
- }
-
- public String Name
- {
- get { return m_name; }
- set { m_name = value; }
- }
-
- public String Version
- {
- get { return m_version; }
- set { m_version = value; }
- }
-
- public String PublicKey
- {
- get { return m_blob; }
- set { m_blob = value; }
- }
-
- public override IPermission CreatePermission()
- {
- if (m_unrestricted)
- {
- return new StrongNameIdentityPermission( PermissionState.Unrestricted );
- }
- else
- {
- if (m_blob == null && m_name == null && m_version == null)
- return new StrongNameIdentityPermission( PermissionState.None );
-
- if (m_blob == null)
- throw new ArgumentException( Environment.GetResourceString("ArgumentNull_Key"));
-
- StrongNamePublicKeyBlob blob = new StrongNamePublicKeyBlob( m_blob );
-
- if (m_version == null || m_version.Equals(String.Empty))
- return new StrongNameIdentityPermission( blob, m_name, null );
- else
- return new StrongNameIdentityPermission( blob, m_name, new Version( m_version ) );
- }
- }
- }
-
-
- [AttributeUsage(AttributeTargets.Method | AttributeTargets.Constructor | AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Assembly, AllowMultiple = true, Inherited = false )]
-[System.Runtime.InteropServices.ComVisible(true)]
- [Serializable]
-#pragma warning disable 618
- sealed public class SiteIdentityPermissionAttribute : CodeAccessSecurityAttribute
-#pragma warning restore 618
- {
- private String m_site = null;
-
-#pragma warning disable 618
- public SiteIdentityPermissionAttribute( SecurityAction action )
-#pragma warning restore 618
- : base( action )
- {
- }
-
- public String Site {
- get { return m_site; }
- set { m_site = value; }
- }
-
- public override IPermission CreatePermission()
- {
- if (m_unrestricted)
- {
- return new SiteIdentityPermission( PermissionState.Unrestricted );
- }
- else
- {
- if (m_site == null)
- return new SiteIdentityPermission( PermissionState.None );
-
- return new SiteIdentityPermission( m_site );
- }
- }
- }
-
- [AttributeUsage(AttributeTargets.Method | AttributeTargets.Constructor | AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Assembly, AllowMultiple = true, Inherited = false )]
-[System.Runtime.InteropServices.ComVisible(true)]
-#pragma warning disable 618
- [Serializable] sealed public class UrlIdentityPermissionAttribute : CodeAccessSecurityAttribute
-#pragma warning restore 618
- {
- private String m_url = null;
-
-#pragma warning disable 618
- public UrlIdentityPermissionAttribute( SecurityAction action )
-#pragma warning restore 618
- : base( action )
- {
- }
-
- public String Url {
- get { return m_url; }
- set { m_url = value; }
- }
-
- public override IPermission CreatePermission()
- {
- if (m_unrestricted)
- {
- return new UrlIdentityPermission( PermissionState.Unrestricted );
- }
- else
- {
- if (m_url == null)
- return new UrlIdentityPermission( PermissionState.None );
-
- return new UrlIdentityPermission( m_url );
- }
- }
- }
-
- [AttributeUsage(AttributeTargets.Method | AttributeTargets.Constructor | AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Assembly, AllowMultiple = true, Inherited = false )]
-[System.Runtime.InteropServices.ComVisible(true)]
- [Serializable]
-#pragma warning disable 618
- sealed public class PermissionSetAttribute : CodeAccessSecurityAttribute
-#pragma warning restore 618
- {
- private String m_file;
- private String m_name;
- private bool m_unicode;
- private String m_xml;
- private String m_hex;
-
-#pragma warning disable 618
- public PermissionSetAttribute( SecurityAction action )
-#pragma warning restore 618
- : base( action )
- {
- m_unicode = false;
- }
-
- public String File {
- get { return m_file; }
- set { m_file = value; }
- }
-
- public bool UnicodeEncoded {
- get { return m_unicode; }
- set { m_unicode = value; }
- }
-
- public String Name {
- get { return m_name; }
- set { m_name = value; }
- }
-
- public String XML {
- get { return m_xml; }
- set { m_xml = value; }
- }
-
- public String Hex {
- get { return m_hex; }
- set { m_hex = value; }
- }
-
- public override IPermission CreatePermission()
- {
- return null;
- }
-
- public PermissionSet CreatePermissionSet()
- {
- if (m_unrestricted)
- return new PermissionSet( PermissionState.Unrestricted );
- else if (m_name != null)
- return NamedPermissionSet.GetBuiltInSet( m_name );
- else
- return new PermissionSet( PermissionState.None );
- }
- }
-}
diff --git a/src/mscorlib/src/System/Security/Permissions/PermissionState.cs b/src/mscorlib/src/System/Security/Permissions/PermissionState.cs
deleted file mode 100644
index ea0f1a0ac2..0000000000
--- a/src/mscorlib/src/System/Security/Permissions/PermissionState.cs
+++ /dev/null
@@ -1,21 +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.
-
-//
-// The Runtime policy manager. Maintains a set of IdentityMapper objects that map
-// inbound evidence to groups. Resolves an identity into a set of permissions
-//
-
-namespace System.Security.Permissions {
-
- using System;
- [Serializable]
-[System.Runtime.InteropServices.ComVisible(true)]
- public enum PermissionState
- {
- Unrestricted = 1,
- None = 0,
- }
-
-}
diff --git a/src/mscorlib/src/System/Security/Permissions/ReflectionPermission.cs b/src/mscorlib/src/System/Security/Permissions/ReflectionPermission.cs
deleted file mode 100644
index 1c9dd7696c..0000000000
--- a/src/mscorlib/src/System/Security/Permissions/ReflectionPermission.cs
+++ /dev/null
@@ -1,274 +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.Security.Permissions
-{
- using System;
- using System.IO;
- using System.Security.Util;
- using System.Text;
- using System.Runtime.InteropServices;
- using System.Runtime.Remoting;
- using System.Security;
- using System.Reflection;
- using System.Globalization;
- using System.Diagnostics.Contracts;
-
- [ComVisible(true)]
- [Flags]
- [Serializable]
- public enum ReflectionPermissionFlag
- {
- NoFlags = 0x00,
- [Obsolete("This API has been deprecated. http://go.microsoft.com/fwlink/?linkid=14202")]
- TypeInformation = 0x01,
- MemberAccess = 0x02,
- [Obsolete("This permission is no longer used by the CLR.")]
- ReflectionEmit = 0x04,
- [ComVisible(false)]
- RestrictedMemberAccess = 0x08,
- [Obsolete("This permission has been deprecated. Use PermissionState.Unrestricted to get full access.")]
- AllFlags = 0x07
- }
-
- [ComVisible(true)]
- [Serializable]
- sealed public class ReflectionPermission
- : CodeAccessPermission, IUnrestrictedPermission, IBuiltInPermission
- {
- // ReflectionPermissionFlag.AllFlags doesn't contain the new value RestrictedMemberAccess,
- // but we cannot change its value now because that will break apps that have that old value baked in.
- // We should use this const that truely contains "all" flags instead of ReflectionPermissionFlag.AllFlags.
-#pragma warning disable 618
- internal const ReflectionPermissionFlag AllFlagsAndMore = ReflectionPermissionFlag.AllFlags | ReflectionPermissionFlag.RestrictedMemberAccess;
-#pragma warning restore 618
-
- private ReflectionPermissionFlag m_flags;
-
- //
- // Public Constructors
- //
-
- public ReflectionPermission(PermissionState state)
- {
- if (state == PermissionState.Unrestricted)
- {
- SetUnrestricted( true );
- }
- else if (state == PermissionState.None)
- {
- SetUnrestricted( false );
- }
- else
- {
- throw new ArgumentException(Environment.GetResourceString("Argument_InvalidPermissionState"));
- }
- }
-
- // Parameters:
- //
- public ReflectionPermission(ReflectionPermissionFlag flag)
- {
- VerifyAccess(flag);
-
- SetUnrestricted(false);
- m_flags = flag;
- }
-
- //------------------------------------------------------
- //
- // PRIVATE AND PROTECTED MODIFIERS
- //
- //------------------------------------------------------
-
-
- private void SetUnrestricted(bool unrestricted)
- {
- if (unrestricted)
- {
- m_flags = ReflectionPermission.AllFlagsAndMore;
- }
- else
- {
- Reset();
- }
- }
-
-
- private void Reset()
- {
- m_flags = ReflectionPermissionFlag.NoFlags;
- }
-
-
- public ReflectionPermissionFlag Flags
- {
- set
- {
- VerifyAccess(value);
-
- m_flags = value;
- }
-
- get
- {
- return m_flags;
- }
- }
-
-
- #if ZERO // Do not remove this code, useful for debugging
- public override String ToString()
- {
- StringBuilder sb = new StringBuilder();
- sb.Append("ReflectionPermission(");
- if (IsUnrestricted())
- {
- sb.Append("Unrestricted");
- }
- else
- {
- if (GetFlag(ReflectionPermissionFlag.TypeInformation))
- sb.Append("TypeInformation; ");
- if (GetFlag(ReflectionPermissionFlag.MemberAccess))
- sb.Append("MemberAccess; ");
-#pragma warning disable 618
- if (GetFlag(ReflectionPermissionFlag.ReflectionEmit))
- sb.Append("ReflectionEmit; ");
-#pragma warning restore 618
- }
-
- sb.Append(")");
- return sb.ToString();
- }
- #endif
-
-
- //
- // CodeAccessPermission implementation
- //
-
- public bool IsUnrestricted()
- {
- return m_flags == ReflectionPermission.AllFlagsAndMore;
- }
-
- //
- // IPermission implementation
- //
-
- public override IPermission Union(IPermission other)
- {
- if (other == null)
- {
- return this.Copy();
- }
- else if (!VerifyType(other))
- {
- throw new
- ArgumentException(
- Environment.GetResourceString("Argument_WrongType", this.GetType().FullName)
- );
- }
-
- ReflectionPermission operand = (ReflectionPermission)other;
-
- if (this.IsUnrestricted() || operand.IsUnrestricted())
- {
- return new ReflectionPermission( PermissionState.Unrestricted );
- }
- else
- {
- ReflectionPermissionFlag flag_union = (ReflectionPermissionFlag)(m_flags | operand.m_flags);
- return(new ReflectionPermission(flag_union));
- }
- }
-
-
-
- public override bool IsSubsetOf(IPermission target)
- {
- if (target == null)
- {
- return m_flags == ReflectionPermissionFlag.NoFlags;
- }
-
- try
- {
- ReflectionPermission operand = (ReflectionPermission)target;
- if (operand.IsUnrestricted())
- return true;
- else if (this.IsUnrestricted())
- return false;
- else
- return (((int)this.m_flags) & ~((int)operand.m_flags)) == 0;
- }
- catch (InvalidCastException)
- {
- throw new
- ArgumentException(
- Environment.GetResourceString("Argument_WrongType", this.GetType().FullName)
- );
- }
-
- }
-
- public override IPermission Intersect(IPermission target)
- {
- if (target == null)
- return null;
- else if (!VerifyType(target))
- {
- throw new
- ArgumentException(
- Environment.GetResourceString("Argument_WrongType", this.GetType().FullName)
- );
- }
-
- ReflectionPermission operand = (ReflectionPermission)target;
-
- ReflectionPermissionFlag newFlags = operand.m_flags & this.m_flags;
-
- if (newFlags == ReflectionPermissionFlag.NoFlags)
- return null;
- else
- return new ReflectionPermission( newFlags );
- }
-
- public override IPermission Copy()
- {
- if (this.IsUnrestricted())
- {
- return new ReflectionPermission(PermissionState.Unrestricted);
- }
- else
- {
- return new ReflectionPermission((ReflectionPermissionFlag)m_flags);
- }
- }
-
-
- //
- // IEncodable Interface
-
- private
- void VerifyAccess(ReflectionPermissionFlag type)
- {
- if ((type & ~ReflectionPermission.AllFlagsAndMore) != 0)
- throw new ArgumentException(Environment.GetResourceString("Arg_EnumIllegalVal", (int)type));
- Contract.EndContractBlock();
- }
-
- /// <internalonly/>
- int IBuiltInPermission.GetTokenIndex()
- {
- return ReflectionPermission.GetTokenIndex();
- }
-
- internal static int GetTokenIndex()
- {
- return BuiltInPermissionIndex.ReflectionPermissionIndex;
- }
- }
-}
diff --git a/src/mscorlib/src/System/Security/Permissions/RegistryPermission.cs b/src/mscorlib/src/System/Security/Permissions/RegistryPermission.cs
deleted file mode 100644
index c0c51e94a2..0000000000
--- a/src/mscorlib/src/System/Security/Permissions/RegistryPermission.cs
+++ /dev/null
@@ -1,363 +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.Security.Permissions
-{
- using System;
- using SecurityElement = System.Security.SecurityElement;
- using System.Security.AccessControl;
- using System.Security.Util;
- using System.IO;
- using System.Globalization;
- using System.Runtime.Serialization;
-
-[Serializable]
- [Flags]
-[System.Runtime.InteropServices.ComVisible(true)]
- public enum RegistryPermissionAccess
- {
- NoAccess = 0x00,
- Read = 0x01,
- Write = 0x02,
- Create = 0x04,
- AllAccess = 0x07,
- }
-
-[System.Runtime.InteropServices.ComVisible(true)]
- [Serializable]
- sealed public class RegistryPermission : CodeAccessPermission, IUnrestrictedPermission, IBuiltInPermission
- {
- private StringExpressionSet m_read;
- private StringExpressionSet m_write;
- private StringExpressionSet m_create;
- [OptionalField(VersionAdded = 2)]
- private StringExpressionSet m_viewAcl;
- [OptionalField(VersionAdded = 2)]
- private StringExpressionSet m_changeAcl;
- private bool m_unrestricted;
-
-
- public RegistryPermission(PermissionState state)
- {
- if (state == PermissionState.Unrestricted)
- {
- m_unrestricted = true;
- }
- else if (state == PermissionState.None)
- {
- m_unrestricted = false;
- }
- else
- {
- throw new ArgumentException(Environment.GetResourceString("Argument_InvalidPermissionState"));
- }
- }
-
- public RegistryPermission( RegistryPermissionAccess access, String pathList )
- {
- SetPathList( access, pathList );
- }
-
- public void SetPathList( RegistryPermissionAccess access, String pathList )
- {
- VerifyAccess( access );
-
- m_unrestricted = false;
-
- if ((access & RegistryPermissionAccess.Read) != 0)
- m_read = null;
-
- if ((access & RegistryPermissionAccess.Write) != 0)
- m_write = null;
-
- if ((access & RegistryPermissionAccess.Create) != 0)
- m_create = null;
-
- AddPathList( access, pathList );
- }
-
- public void AddPathList( RegistryPermissionAccess access, String pathList )
- {
- AddPathList( access, AccessControlActions.None, pathList );
- }
-
- public void AddPathList( RegistryPermissionAccess access, AccessControlActions control, String pathList )
- {
- VerifyAccess( access );
-
- if ((access & RegistryPermissionAccess.Read) != 0)
- {
- if (m_read == null)
- m_read = new StringExpressionSet();
- m_read.AddExpressions( pathList );
- }
-
- if ((access & RegistryPermissionAccess.Write) != 0)
- {
- if (m_write == null)
- m_write = new StringExpressionSet();
- m_write.AddExpressions( pathList );
- }
-
- if ((access & RegistryPermissionAccess.Create) != 0)
- {
- if (m_create == null)
- m_create = new StringExpressionSet();
- m_create.AddExpressions( pathList );
- }
- }
-
- public String GetPathList( RegistryPermissionAccess access )
- {
- // SafeCritical: these are registry paths, which means we're not leaking file system information here
- VerifyAccess( access );
- ExclusiveAccess( access );
-
- if ((access & RegistryPermissionAccess.Read) != 0)
- {
- if (m_read == null)
- {
- return "";
- }
- return m_read.UnsafeToString();
- }
-
- if ((access & RegistryPermissionAccess.Write) != 0)
- {
- if (m_write == null)
- {
- return "";
- }
- return m_write.UnsafeToString();
- }
-
- if ((access & RegistryPermissionAccess.Create) != 0)
- {
- if (m_create == null)
- {
- return "";
- }
- return m_create.UnsafeToString();
- }
-
- /* not reached */
-
- return "";
- }
-
- private void VerifyAccess( RegistryPermissionAccess access )
- {
- if ((access & ~RegistryPermissionAccess.AllAccess) != 0)
- throw new ArgumentException(Environment.GetResourceString("Arg_EnumIllegalVal", (int)access));
- }
-
- private void ExclusiveAccess( RegistryPermissionAccess access )
- {
- if (access == RegistryPermissionAccess.NoAccess)
- {
- throw new ArgumentException( Environment.GetResourceString("Arg_EnumNotSingleFlag") );
- }
-
- if (((int) access & ((int)access-1)) != 0)
- {
- throw new ArgumentException( Environment.GetResourceString("Arg_EnumNotSingleFlag") );
- }
- }
-
- private bool IsEmpty()
- {
- return (!m_unrestricted &&
- (this.m_read == null || this.m_read.IsEmpty()) &&
- (this.m_write == null || this.m_write.IsEmpty()) &&
- (this.m_create == null || this.m_create.IsEmpty()) &&
- (this.m_viewAcl == null || this.m_viewAcl.IsEmpty()) &&
- (this.m_changeAcl == null || this.m_changeAcl.IsEmpty()));
- }
-
- //------------------------------------------------------
- //
- // CODEACCESSPERMISSION IMPLEMENTATION
- //
- //------------------------------------------------------
-
- public bool IsUnrestricted()
- {
- return m_unrestricted;
- }
-
- //------------------------------------------------------
- //
- // IPERMISSION IMPLEMENTATION
- //
- //------------------------------------------------------
-
- public override bool IsSubsetOf(IPermission target)
- {
- if (target == null)
- {
- return this.IsEmpty();
- }
-
- RegistryPermission operand = target as RegistryPermission;
- if (operand == null)
- throw new ArgumentException(Environment.GetResourceString("Argument_WrongType", this.GetType().FullName));
-
- if (operand.IsUnrestricted())
- return true;
- else if (this.IsUnrestricted())
- return false;
- else
- return ((this.m_read == null || this.m_read.IsSubsetOf( operand.m_read )) &&
- (this.m_write == null || this.m_write.IsSubsetOf( operand.m_write )) &&
- (this.m_create == null || this.m_create.IsSubsetOf( operand.m_create )) &&
- (this.m_viewAcl == null || this.m_viewAcl.IsSubsetOf( operand.m_viewAcl )) &&
- (this.m_changeAcl == null || this.m_changeAcl.IsSubsetOf( operand.m_changeAcl )));
- }
-
- public override IPermission Intersect(IPermission target)
- {
- if (target == null)
- {
- return null;
- }
- else if (!VerifyType(target))
- {
- throw new
- ArgumentException(
- Environment.GetResourceString("Argument_WrongType", this.GetType().FullName)
- );
- }
- else if (this.IsUnrestricted())
- {
- return target.Copy();
- }
-
- RegistryPermission operand = (RegistryPermission)target;
- if (operand.IsUnrestricted())
- {
- return this.Copy();
- }
-
-
- StringExpressionSet intersectRead = this.m_read == null ? null : this.m_read.Intersect( operand.m_read );
- StringExpressionSet intersectWrite = this.m_write == null ? null : this.m_write.Intersect( operand.m_write );
- StringExpressionSet intersectCreate = this.m_create == null ? null : this.m_create.Intersect( operand.m_create );
- StringExpressionSet intersectViewAcl = this.m_viewAcl == null ? null : this.m_viewAcl.Intersect( operand.m_viewAcl );
- StringExpressionSet intersectChangeAcl = this.m_changeAcl == null ? null : this.m_changeAcl.Intersect( operand.m_changeAcl );
-
- if ((intersectRead == null || intersectRead.IsEmpty()) &&
- (intersectWrite == null || intersectWrite.IsEmpty()) &&
- (intersectCreate == null || intersectCreate.IsEmpty()) &&
- (intersectViewAcl == null || intersectViewAcl.IsEmpty()) &&
- (intersectChangeAcl == null || intersectChangeAcl.IsEmpty()))
- {
- return null;
- }
-
- RegistryPermission intersectPermission = new RegistryPermission(PermissionState.None);
- intersectPermission.m_unrestricted = false;
- intersectPermission.m_read = intersectRead;
- intersectPermission.m_write = intersectWrite;
- intersectPermission.m_create = intersectCreate;
- intersectPermission.m_viewAcl = intersectViewAcl;
- intersectPermission.m_changeAcl = intersectChangeAcl;
-
- return intersectPermission;
- }
-
- public override IPermission Union(IPermission other)
- {
- if (other == null)
- {
- return this.Copy();
- }
- else if (!VerifyType(other))
- {
- throw new
- ArgumentException(
- Environment.GetResourceString("Argument_WrongType", this.GetType().FullName)
- );
- }
-
- RegistryPermission operand = (RegistryPermission)other;
-
- if (this.IsUnrestricted() || operand.IsUnrestricted())
- {
- return new RegistryPermission( PermissionState.Unrestricted );
- }
-
- StringExpressionSet unionRead = this.m_read == null ? operand.m_read : this.m_read.Union( operand.m_read );
- StringExpressionSet unionWrite = this.m_write == null ? operand.m_write : this.m_write.Union( operand.m_write );
- StringExpressionSet unionCreate = this.m_create == null ? operand.m_create : this.m_create.Union( operand.m_create );
- StringExpressionSet unionViewAcl = this.m_viewAcl == null ? operand.m_viewAcl : this.m_viewAcl.Union( operand.m_viewAcl );
- StringExpressionSet unionChangeAcl = this.m_changeAcl == null ? operand.m_changeAcl : this.m_changeAcl.Union( operand.m_changeAcl );
-
- if ((unionRead == null || unionRead.IsEmpty()) &&
- (unionWrite == null || unionWrite.IsEmpty()) &&
- (unionCreate == null || unionCreate.IsEmpty()) &&
- (unionViewAcl == null || unionViewAcl.IsEmpty()) &&
- (unionChangeAcl == null || unionChangeAcl.IsEmpty()))
- {
- return null;
- }
-
- RegistryPermission unionPermission = new RegistryPermission(PermissionState.None);
- unionPermission.m_unrestricted = false;
- unionPermission.m_read = unionRead;
- unionPermission.m_write = unionWrite;
- unionPermission.m_create = unionCreate;
- unionPermission.m_viewAcl = unionViewAcl;
- unionPermission.m_changeAcl = unionChangeAcl;
-
- return unionPermission;
- }
-
-
- public override IPermission Copy()
- {
- RegistryPermission copy = new RegistryPermission(PermissionState.None);
- if (this.m_unrestricted)
- {
- copy.m_unrestricted = true;
- }
- else
- {
- copy.m_unrestricted = false;
- if (this.m_read != null)
- {
- copy.m_read = this.m_read.Copy();
- }
- if (this.m_write != null)
- {
- copy.m_write = this.m_write.Copy();
- }
- if (this.m_create != null)
- {
- copy.m_create = this.m_create.Copy();
- }
- if (this.m_viewAcl != null)
- {
- copy.m_viewAcl = this.m_viewAcl.Copy();
- }
- if (this.m_changeAcl != null)
- {
- copy.m_changeAcl = this.m_changeAcl.Copy();
- }
- }
- return copy;
- }
-
- /// <internalonly/>
- int IBuiltInPermission.GetTokenIndex()
- {
- return RegistryPermission.GetTokenIndex();
- }
-
- internal static int GetTokenIndex()
- {
- return BuiltInPermissionIndex.RegistryPermissionIndex;
- }
-
- }
-}
diff --git a/src/mscorlib/src/System/Security/Permissions/SecurityPermission.cs b/src/mscorlib/src/System/Security/Permissions/SecurityPermission.cs
deleted file mode 100644
index cf3002989d..0000000000
--- a/src/mscorlib/src/System/Security/Permissions/SecurityPermission.cs
+++ /dev/null
@@ -1,270 +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.Security.Permissions
-{
- using System;
- using System.IO;
- using System.Security.Util;
- using System.Text;
- using System.Threading;
- using System.Runtime.Remoting;
- using System.Security;
- using System.Runtime.Serialization;
- using System.Reflection;
- using System.Globalization;
- using System.Diagnostics.Contracts;
-
- [Serializable]
- [Flags]
- [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.")]
- public enum SecurityPermissionFlag
- {
- NoFlags = 0x00,
- /* The following enum value is used in the EE (ASSERT_PERMISSION in security.cpp)
- * Should this value change, make corresponding changes there
- */
- Assertion = 0x01,
- UnmanagedCode = 0x02, // Update vm\Security.h if you change this !
- SkipVerification = 0x04, // Update vm\Security.h if you change this !
- Execution = 0x08,
- ControlThread = 0x10,
- ControlEvidence = 0x20,
- ControlPolicy = 0x40,
- SerializationFormatter = 0x80,
- ControlDomainPolicy = 0x100,
- ControlPrincipal = 0x200,
- ControlAppDomain = 0x400,
- RemotingConfiguration = 0x800,
- Infrastructure = 0x1000,
- BindingRedirects = 0x2000,
- AllFlags = 0x3fff,
- }
-
-[System.Runtime.InteropServices.ComVisible(true)]
- [Serializable]
- sealed public class SecurityPermission
- : CodeAccessPermission, IUnrestrictedPermission, IBuiltInPermission
- {
-#pragma warning disable 618
- private SecurityPermissionFlag m_flags;
-#pragma warning restore 618
-
- //
- // Public Constructors
- //
-
- public SecurityPermission(PermissionState state)
- {
- if (state == PermissionState.Unrestricted)
- {
- SetUnrestricted( true );
- }
- else if (state == PermissionState.None)
- {
- SetUnrestricted( false );
- Reset();
- }
- else
- {
- throw new ArgumentException(Environment.GetResourceString("Argument_InvalidPermissionState"));
- }
- }
-
-
- // SecurityPermission
- //
-#pragma warning disable 618
- public SecurityPermission(SecurityPermissionFlag flag)
-#pragma warning restore 618
- {
- VerifyAccess(flag);
-
- SetUnrestricted(false);
- m_flags = flag;
- }
-
-
- //------------------------------------------------------
- //
- // PRIVATE AND PROTECTED MODIFIERS
- //
- //------------------------------------------------------
-
-
- private void SetUnrestricted(bool unrestricted)
- {
- if (unrestricted)
- {
-#pragma warning disable 618
- m_flags = SecurityPermissionFlag.AllFlags;
-#pragma warning restore 618
- }
- }
-
- private void Reset()
- {
-#pragma warning disable 618
- m_flags = SecurityPermissionFlag.NoFlags;
-#pragma warning restore 618
- }
-
-
-#pragma warning disable 618
- public SecurityPermissionFlag Flags
-#pragma warning restore 618
- {
- set
- {
- VerifyAccess(value);
-
- m_flags = value;
- }
-
- get
- {
- return m_flags;
- }
- }
-
- //
- // CodeAccessPermission methods
- //
-
- /*
- * IPermission interface implementation
- */
-
- public override bool IsSubsetOf(IPermission target)
- {
- if (target == null)
- {
- return m_flags == 0;
- }
-
- SecurityPermission operand = target as SecurityPermission;
- if (operand != null)
- {
- return (((int)this.m_flags) & ~((int)operand.m_flags)) == 0;
- }
- else
- {
- throw new
- ArgumentException(
- Environment.GetResourceString("Argument_WrongType", this.GetType().FullName)
- );
- }
-
- }
-
- public override IPermission Union(IPermission target) {
- if (target == null) return(this.Copy());
- if (!VerifyType(target)) {
- throw new
- ArgumentException(
- Environment.GetResourceString("Argument_WrongType", this.GetType().FullName)
- );
- }
- SecurityPermission sp_target = (SecurityPermission) target;
- if (sp_target.IsUnrestricted() || IsUnrestricted()) {
- return(new SecurityPermission(PermissionState.Unrestricted));
- }
-#pragma warning disable 618
- SecurityPermissionFlag flag_union = (SecurityPermissionFlag)(m_flags | sp_target.m_flags);
-#pragma warning restore 618
- return(new SecurityPermission(flag_union));
- }
-
- public override IPermission Intersect(IPermission target)
- {
- if (target == null)
- return null;
- else if (!VerifyType(target))
- {
- throw new
- ArgumentException(
- Environment.GetResourceString("Argument_WrongType", this.GetType().FullName)
- );
- }
-
- SecurityPermission operand = (SecurityPermission)target;
-#pragma warning disable 618
- SecurityPermissionFlag isectFlags = SecurityPermissionFlag.NoFlags;
-#pragma warning restore 618
-
- if (operand.IsUnrestricted())
- {
- if (this.IsUnrestricted())
- return new SecurityPermission(PermissionState.Unrestricted);
- else
-#pragma warning disable 618
- isectFlags = (SecurityPermissionFlag)this.m_flags;
-#pragma warning restore 618
- }
- else if (this.IsUnrestricted())
- {
-#pragma warning disable 618
- isectFlags = (SecurityPermissionFlag)operand.m_flags;
-#pragma warning restore 618
- }
- else
- {
-#pragma warning disable 618
- isectFlags = (SecurityPermissionFlag)m_flags & (SecurityPermissionFlag)operand.m_flags;
-#pragma warning restore 618
- }
-
- if (isectFlags == 0)
- return null;
- else
- return new SecurityPermission(isectFlags);
- }
-
- public override IPermission Copy()
- {
- if (IsUnrestricted())
- return new SecurityPermission(PermissionState.Unrestricted);
- else
-#pragma warning disable 618
- return new SecurityPermission((SecurityPermissionFlag)m_flags);
-#pragma warning restore 618
- }
-
- public bool IsUnrestricted()
- {
-#pragma warning disable 618
- return m_flags == SecurityPermissionFlag.AllFlags;
-#pragma warning restore 618
- }
-
- private
-#pragma warning disable 618
- void VerifyAccess(SecurityPermissionFlag type)
-#pragma warning restore 618
- {
-#pragma warning disable 618
- if ((type & ~SecurityPermissionFlag.AllFlags) != 0)
-#pragma warning restore 618
- throw new ArgumentException(Environment.GetResourceString("Arg_EnumIllegalVal", (int)type));
- Contract.EndContractBlock();
- }
-
- //
- // Object Overrides
- //
-
- /// <internalonly/>
- int IBuiltInPermission.GetTokenIndex()
- {
- return SecurityPermission.GetTokenIndex();
- }
-
- internal static int GetTokenIndex()
- {
- return BuiltInPermissionIndex.SecurityPermissionIndex;
- }
- }
-}
diff --git a/src/mscorlib/src/System/Security/Permissions/SiteIdentityPermission.cs b/src/mscorlib/src/System/Security/Permissions/SiteIdentityPermission.cs
deleted file mode 100644
index ff38d515a1..0000000000
--- a/src/mscorlib/src/System/Security/Permissions/SiteIdentityPermission.cs
+++ /dev/null
@@ -1,251 +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.Security.Permissions
-{
- using System;
- using SiteString = System.Security.Util.SiteString;
- using System.Text;
- using System.Collections;
- using System.Collections.Generic;
- using System.Globalization;
- using System.Runtime.Serialization;
-
- [System.Runtime.InteropServices.ComVisible(true)]
-#if FEATURE_SERIALIZATION
- [Serializable]
-#endif
- sealed public class SiteIdentityPermission : CodeAccessPermission, IBuiltInPermission
- {
- //------------------------------------------------------
- //
- // PRIVATE STATE DATA
- //
- //------------------------------------------------------
- [OptionalField(VersionAdded = 2)]
- private bool m_unrestricted;
- [OptionalField(VersionAdded = 2)]
- private SiteString[] m_sites;
-
- //------------------------------------------------------
- //
- // PUBLIC CONSTRUCTORS
- //
- //------------------------------------------------------
-
-
- public SiteIdentityPermission(PermissionState state)
- {
- if (state == PermissionState.Unrestricted)
- {
- m_unrestricted = true;
- }
- else if (state == PermissionState.None)
- {
- m_unrestricted = false;
- }
- else
- {
- throw new ArgumentException(Environment.GetResourceString("Argument_InvalidPermissionState"));
- }
- }
-
- public SiteIdentityPermission( String site )
- {
- Site = site;
- }
-
- //------------------------------------------------------
- //
- // PUBLIC ACCESSOR METHODS
- //
- //------------------------------------------------------
-
- public String Site
- {
- set
- {
- m_unrestricted = false;
- m_sites = new SiteString[1];
- m_sites[0] = new SiteString( value );
- }
-
- get
- {
- if(m_sites == null)
- return "";
- if(m_sites.Length == 1)
- return m_sites[0].ToString();
- throw new NotSupportedException(Environment.GetResourceString("NotSupported_AmbiguousIdentity"));
- }
- }
-
- //------------------------------------------------------
- //
- // PRIVATE AND PROTECTED HELPERS FOR ACCESSORS AND CONSTRUCTORS
- //
- //------------------------------------------------------
-
- //------------------------------------------------------
- //
- // CODEACCESSPERMISSION IMPLEMENTATION
- //
- //------------------------------------------------------
-
- //------------------------------------------------------
- //
- // IPERMISSION IMPLEMENTATION
- //
- //------------------------------------------------------
- public override IPermission Copy()
- {
- SiteIdentityPermission perm = new SiteIdentityPermission( PermissionState.None );
- perm.m_unrestricted = this.m_unrestricted;
- if (this.m_sites != null)
- {
- perm.m_sites = new SiteString[this.m_sites.Length];
- int n;
- for(n = 0; n < this.m_sites.Length; n++)
- perm.m_sites[n] = (SiteString)this.m_sites[n].Copy();
- }
- return perm;
- }
-
- public override bool IsSubsetOf(IPermission target)
- {
- if (target == null)
- {
- if(m_unrestricted)
- return false;
- if(m_sites == null)
- return true;
- if(m_sites.Length == 0)
- return true;
- return false;
- }
- SiteIdentityPermission that = target as SiteIdentityPermission;
- if(that == null)
- throw new ArgumentException(Environment.GetResourceString("Argument_WrongType", this.GetType().FullName));
- if(that.m_unrestricted)
- return true;
- if(m_unrestricted)
- return false;
- if(this.m_sites != null)
- {
- foreach(SiteString ssThis in this.m_sites)
- {
- bool bOK = false;
- if(that.m_sites != null)
- {
- foreach(SiteString ssThat in that.m_sites)
- {
- if(ssThis.IsSubsetOf(ssThat))
- {
- bOK = true;
- break;
- }
- }
- }
- if(!bOK)
- return false;
- }
- }
- return true;
- }
-
- public override IPermission Intersect(IPermission target)
- {
- if (target == null)
- return null;
- SiteIdentityPermission that = target as SiteIdentityPermission;
- if(that == null)
- throw new ArgumentException(Environment.GetResourceString("Argument_WrongType", this.GetType().FullName));
- if(this.m_unrestricted && that.m_unrestricted)
- {
- SiteIdentityPermission res = new SiteIdentityPermission(PermissionState.None);
- res.m_unrestricted = true;
- return res;
- }
- if(this.m_unrestricted)
- return that.Copy();
- if(that.m_unrestricted)
- return this.Copy();
- if(this.m_sites == null || that.m_sites == null || this.m_sites.Length == 0 || that.m_sites.Length == 0)
- return null;
- List<SiteString> alSites = new List<SiteString>();
- foreach(SiteString ssThis in this.m_sites)
- {
- foreach(SiteString ssThat in that.m_sites)
- {
- SiteString ssInt = (SiteString)ssThis.Intersect(ssThat);
- if(ssInt != null)
- alSites.Add(ssInt);
- }
- }
- if(alSites.Count == 0)
- return null;
- SiteIdentityPermission result = new SiteIdentityPermission(PermissionState.None);
- result.m_sites = alSites.ToArray();
- return result;
- }
-
- public override IPermission Union(IPermission target)
- {
- if (target == null)
- {
- if((this.m_sites == null || this.m_sites.Length == 0) && !this.m_unrestricted)
- return null;
- return this.Copy();
- }
- SiteIdentityPermission that = target as SiteIdentityPermission;
- if(that == null)
- throw new ArgumentException(Environment.GetResourceString("Argument_WrongType", this.GetType().FullName));
- if(this.m_unrestricted || that.m_unrestricted)
- {
- SiteIdentityPermission res = new SiteIdentityPermission(PermissionState.None);
- res.m_unrestricted = true;
- return res;
- }
- if (this.m_sites == null || this.m_sites.Length == 0)
- {
- if(that.m_sites == null || that.m_sites.Length == 0)
- return null;
- return that.Copy();
- }
- if(that.m_sites == null || that.m_sites.Length == 0)
- return this.Copy();
- List<SiteString> alSites = new List<SiteString>();
- foreach(SiteString ssThis in this.m_sites)
- alSites.Add(ssThis);
- foreach(SiteString ssThat in that.m_sites)
- {
- bool bDupe = false;
- foreach(SiteString ss in alSites)
- {
- if(ssThat.Equals(ss))
- {
- bDupe = true;
- break;
- }
- }
- if(!bDupe)
- alSites.Add(ssThat);
- }
- SiteIdentityPermission result = new SiteIdentityPermission(PermissionState.None);
- result.m_sites = alSites.ToArray();
- return result;
- }
-
- /// <internalonly/>
- int IBuiltInPermission.GetTokenIndex()
- {
- return SiteIdentityPermission.GetTokenIndex();
- }
-
- internal static int GetTokenIndex()
- {
- return BuiltInPermissionIndex.SiteIdentityPermissionIndex;
- }
- }
-}
diff --git a/src/mscorlib/src/System/Security/Permissions/StrongNameIdentityPermission.cs b/src/mscorlib/src/System/Security/Permissions/StrongNameIdentityPermission.cs
deleted file mode 100644
index f09d84de34..0000000000
--- a/src/mscorlib/src/System/Security/Permissions/StrongNameIdentityPermission.cs
+++ /dev/null
@@ -1,401 +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.Security.Permissions
-{
- using System;
- using System.Security.Util;
- using System.IO;
- using String = System.String;
- using Version = System.Version;
- using System.Security.Policy;
- using System.Collections;
- using System.Collections.Generic;
- using System.Globalization;
- using System.Diagnostics.Contracts;
-
- // The only difference between this class and System.Security.Policy.StrongName is that this one
- // allows m_name to be null. We should merge this class with System.Security.Policy.StrongName
- [Serializable]
- sealed internal class StrongName2
- {
- public StrongNamePublicKeyBlob m_publicKeyBlob;
- public String m_name;
- public Version m_version;
-
- public StrongName2(StrongNamePublicKeyBlob publicKeyBlob, String name, Version version)
- {
- m_publicKeyBlob = publicKeyBlob;
- m_name = name;
- m_version = version;
- }
-
- public StrongName2 Copy()
- {
- return new StrongName2(m_publicKeyBlob, m_name, m_version);
- }
-
- public bool IsSubsetOf(StrongName2 target)
- {
- // This StrongName2 is a subset of the target if it's public key blob is null no matter what
- if (this.m_publicKeyBlob == null)
- return true;
-
- // Subsets are always false if the public key blobs do not match
- if (!this.m_publicKeyBlob.Equals( target.m_publicKeyBlob ))
- return false;
-
- // We use null in strings to represent the "Anything" state.
- // Therefore, the logic to detect an individual subset is:
- //
- // 1. If the this string is null ("Anything" is a subset of any other).
- // 2. If the this string and target string are the same (equality is sufficient for a subset).
- //
- // The logic is reversed here to discover things that are not subsets.
- if (this.m_name != null)
- {
- if (target.m_name == null || !System.Security.Policy.StrongName.CompareNames( target.m_name, this.m_name ))
- return false;
- }
-
- if ((Object) this.m_version != null)
- {
- if ((Object) target.m_version == null ||
- target.m_version.CompareTo( this.m_version ) != 0)
- {
- return false;
- }
- }
-
- return true;
- }
-
- public StrongName2 Intersect(StrongName2 target)
- {
- if (target.IsSubsetOf( this ))
- return target.Copy();
- else if (this.IsSubsetOf( target ))
- return this.Copy();
- else
- return null;
- }
-
- public bool Equals(StrongName2 target)
- {
- if (!target.IsSubsetOf(this))
- return false;
- if (!this.IsSubsetOf(target))
- return false;
- return true;
- }
- }
-
-
-
-[System.Runtime.InteropServices.ComVisible(true)]
- [Serializable]
- sealed public class StrongNameIdentityPermission : CodeAccessPermission, IBuiltInPermission
- {
- //------------------------------------------------------
- //
- // PRIVATE STATE DATA
- //
- //------------------------------------------------------
-
- private bool m_unrestricted;
- private StrongName2[] m_strongNames;
-
- //------------------------------------------------------
- //
- // PUBLIC CONSTRUCTORS
- //
- //------------------------------------------------------
-
-
- public StrongNameIdentityPermission(PermissionState state)
- {
- if (state == PermissionState.Unrestricted)
- {
- m_unrestricted = true;
- }
- else if (state == PermissionState.None)
- {
- m_unrestricted = false;
- }
- else
- {
- throw new ArgumentException(Environment.GetResourceString("Argument_InvalidPermissionState"));
- }
- }
-
- public StrongNameIdentityPermission( StrongNamePublicKeyBlob blob, String name, Version version )
- {
- if (blob == null)
- throw new ArgumentNullException( nameof(blob) );
- if (name != null && name.Equals( "" ))
- throw new ArgumentException( Environment.GetResourceString( "Argument_EmptyStrongName" ) );
- Contract.EndContractBlock();
- m_unrestricted = false;
- m_strongNames = new StrongName2[1];
- m_strongNames[0] = new StrongName2(blob, name, version);
- }
-
-
- //------------------------------------------------------
- //
- // PUBLIC ACCESSOR METHODS
- //
- //------------------------------------------------------
-
- public StrongNamePublicKeyBlob PublicKey
- {
- set
- {
- if (value == null)
- throw new ArgumentNullException( nameof(PublicKey) );
- Contract.EndContractBlock();
- m_unrestricted = false;
- if(m_strongNames != null && m_strongNames.Length == 1)
- m_strongNames[0].m_publicKeyBlob = value;
- else
- {
- m_strongNames = new StrongName2[1];
- m_strongNames[0] = new StrongName2(value, "", new Version());
- }
- }
-
- get
- {
- if(m_strongNames == null || m_strongNames.Length == 0)
- return null;
- if(m_strongNames.Length > 1)
- throw new NotSupportedException(Environment.GetResourceString("NotSupported_AmbiguousIdentity"));
- return m_strongNames[0].m_publicKeyBlob;
- }
- }
-
- public String Name
- {
- set
- {
- if (value != null && value.Length == 0)
- throw new ArgumentException( Environment.GetResourceString("Argument_EmptyName" ));
- Contract.EndContractBlock();
- m_unrestricted = false;
- if(m_strongNames != null && m_strongNames.Length == 1)
- m_strongNames[0].m_name = value;
- else
- {
- m_strongNames = new StrongName2[1];
- m_strongNames[0] = new StrongName2(null, value, new Version());
- }
- }
-
- get
- {
- if(m_strongNames == null || m_strongNames.Length == 0)
- return "";
- if(m_strongNames.Length > 1)
- throw new NotSupportedException(Environment.GetResourceString("NotSupported_AmbiguousIdentity"));
- return m_strongNames[0].m_name;
- }
- }
-
- public Version Version
- {
- set
- {
- m_unrestricted = false;
- if(m_strongNames != null && m_strongNames.Length == 1)
- m_strongNames[0].m_version = value;
- else
- {
- m_strongNames = new StrongName2[1];
- m_strongNames[0] = new StrongName2(null, "", value);
- }
- }
-
- get
- {
- if(m_strongNames == null || m_strongNames.Length == 0)
- return new Version();
- if(m_strongNames.Length > 1)
- throw new NotSupportedException(Environment.GetResourceString("NotSupported_AmbiguousIdentity"));
- return m_strongNames[0].m_version;
- }
- }
-
- //------------------------------------------------------
- //
- // PRIVATE AND PROTECTED HELPERS FOR ACCESSORS AND CONSTRUCTORS
- //
- //------------------------------------------------------
-
- //------------------------------------------------------
- //
- // CODEACCESSPERMISSION IMPLEMENTATION
- //
- //------------------------------------------------------
-
- //------------------------------------------------------
- //
- // IPERMISSION IMPLEMENTATION
- //
- //------------------------------------------------------
-
-
- public override IPermission Copy()
- {
- StrongNameIdentityPermission perm = new StrongNameIdentityPermission(PermissionState.None);
- perm.m_unrestricted = this.m_unrestricted;
- if(this.m_strongNames != null)
- {
- perm.m_strongNames = new StrongName2[this.m_strongNames.Length];
- int n;
- for(n = 0; n < this.m_strongNames.Length; n++)
- perm.m_strongNames[n] = this.m_strongNames[n].Copy();
- }
- return perm;
- }
-
- public override bool IsSubsetOf(IPermission target)
- {
- if (target == null)
- {
- if(m_unrestricted)
- return false;
- if(m_strongNames == null)
- return true;
- if(m_strongNames.Length == 0)
- return true;
- return false;
- }
- StrongNameIdentityPermission that = target as StrongNameIdentityPermission;
- if(that == null)
- throw new ArgumentException(Environment.GetResourceString("Argument_WrongType", this.GetType().FullName));
- if(that.m_unrestricted)
- return true;
- if(m_unrestricted)
- return false;
- if(this.m_strongNames != null)
- {
- foreach(StrongName2 snThis in m_strongNames)
- {
- bool bOK = false;
- if(that.m_strongNames != null)
- {
- foreach(StrongName2 snThat in that.m_strongNames)
- {
- if(snThis.IsSubsetOf(snThat))
- {
- bOK = true;
- break;
- }
- }
- }
- if(!bOK)
- return false;
- }
- }
- return true;
- }
-
-
-
- public override IPermission Intersect(IPermission target)
- {
- if (target == null)
- return null;
- StrongNameIdentityPermission that = target as StrongNameIdentityPermission;
- if(that == null)
- throw new ArgumentException(Environment.GetResourceString("Argument_WrongType", this.GetType().FullName));
- if(this.m_unrestricted && that.m_unrestricted)
- {
- StrongNameIdentityPermission res = new StrongNameIdentityPermission(PermissionState.None);
- res.m_unrestricted = true;
- return res;
- }
- if(this.m_unrestricted)
- return that.Copy();
- if(that.m_unrestricted)
- return this.Copy();
- if(this.m_strongNames == null || that.m_strongNames == null || this.m_strongNames.Length == 0 || that.m_strongNames.Length == 0)
- return null;
- List<StrongName2> alStrongNames = new List<StrongName2>();
- foreach(StrongName2 snThis in this.m_strongNames)
- {
- foreach(StrongName2 snThat in that.m_strongNames)
- {
- StrongName2 snInt = (StrongName2)snThis.Intersect(snThat);
- if(snInt != null)
- alStrongNames.Add(snInt);
- }
- }
- if(alStrongNames.Count == 0)
- return null;
- StrongNameIdentityPermission result = new StrongNameIdentityPermission(PermissionState.None);
- result.m_strongNames = alStrongNames.ToArray();
- return result;
- }
-
- public override IPermission Union(IPermission target)
- {
- if (target == null)
- {
- if((this.m_strongNames == null || this.m_strongNames.Length == 0) && !this.m_unrestricted)
- return null;
- return this.Copy();
- }
- StrongNameIdentityPermission that = target as StrongNameIdentityPermission;
- if(that == null)
- throw new ArgumentException(Environment.GetResourceString("Argument_WrongType", this.GetType().FullName));
- if(this.m_unrestricted || that.m_unrestricted)
- {
- StrongNameIdentityPermission res = new StrongNameIdentityPermission(PermissionState.None);
- res.m_unrestricted = true;
- return res;
- }
- if (this.m_strongNames == null || this.m_strongNames.Length == 0)
- {
- if(that.m_strongNames == null || that.m_strongNames.Length == 0)
- return null;
- return that.Copy();
- }
- if(that.m_strongNames == null || that.m_strongNames.Length == 0)
- return this.Copy();
- List<StrongName2> alStrongNames = new List<StrongName2>();
- foreach(StrongName2 snThis in this.m_strongNames)
- alStrongNames.Add(snThis);
- foreach(StrongName2 snThat in that.m_strongNames)
- {
- bool bDupe = false;
- foreach(StrongName2 sn in alStrongNames)
- {
- if(snThat.Equals(sn))
- {
- bDupe = true;
- break;
- }
- }
- if(!bDupe)
- alStrongNames.Add(snThat);
- }
- StrongNameIdentityPermission result = new StrongNameIdentityPermission(PermissionState.None);
- result.m_strongNames = alStrongNames.ToArray();
- return result;
- }
-
- /// <internalonly/>
- int IBuiltInPermission.GetTokenIndex()
- {
- return StrongNameIdentityPermission.GetTokenIndex();
- }
-
- internal static int GetTokenIndex()
- {
- return BuiltInPermissionIndex.StrongNameIdentityPermissionIndex;
- }
-
- }
-}
diff --git a/src/mscorlib/src/System/Security/Permissions/StrongNamePublicKeyBlob.cs b/src/mscorlib/src/System/Security/Permissions/StrongNamePublicKeyBlob.cs
deleted file mode 100644
index 823eaba938..0000000000
--- a/src/mscorlib/src/System/Security/Permissions/StrongNamePublicKeyBlob.cs
+++ /dev/null
@@ -1,94 +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.Security.Permissions
-{
- using System;
- using System.Security.Util;
- using System.Diagnostics.Contracts;
-
- [System.Runtime.InteropServices.ComVisible(true)]
- [Serializable] sealed public class StrongNamePublicKeyBlob
- {
- internal byte[] PublicKey;
-
- internal StrongNamePublicKeyBlob()
- {
- }
-
- public StrongNamePublicKeyBlob( byte[] publicKey )
- {
- if (publicKey == null)
- throw new ArgumentNullException( nameof(PublicKey) );
- Contract.EndContractBlock();
-
- this.PublicKey = new byte[publicKey.Length];
- Array.Copy( publicKey, 0, this.PublicKey, 0, publicKey.Length );
- }
-
- internal StrongNamePublicKeyBlob( String publicKey )
- {
- this.PublicKey = Hex.DecodeHexString( publicKey );
- }
-
- private static bool CompareArrays( byte[] first, byte[] second )
- {
- if (first.Length != second.Length)
- {
- return false;
- }
-
- int count = first.Length;
- for (int i = 0; i < count; ++i)
- {
- if (first[i] != second[i])
- return false;
- }
-
- return true;
- }
-
-
- internal bool Equals( StrongNamePublicKeyBlob blob )
- {
- if (blob == null)
- return false;
- else
- return CompareArrays( this.PublicKey, blob.PublicKey );
- }
-
- public override bool Equals( Object obj )
- {
- if (obj == null || !(obj is StrongNamePublicKeyBlob))
- return false;
-
- return this.Equals( (StrongNamePublicKeyBlob)obj );
- }
-
- static private int GetByteArrayHashCode( byte[] baData )
- {
- if (baData == null)
- return 0;
-
- int accumulator = 0;
-
- for (int i = 0; i < baData.Length; ++i)
- {
- accumulator = (accumulator << 8) ^ (int)baData[i] ^ (accumulator >> 24);
- }
-
- return accumulator;
- }
-
- public override int GetHashCode()
- {
- return GetByteArrayHashCode( PublicKey );
- }
-
- public override String ToString()
- {
- return Hex.EncodeHexString( PublicKey );
- }
- }
-}
diff --git a/src/mscorlib/src/System/Security/Permissions/UIPermission.cs b/src/mscorlib/src/System/Security/Permissions/UIPermission.cs
deleted file mode 100644
index 4abe801e41..0000000000
--- a/src/mscorlib/src/System/Security/Permissions/UIPermission.cs
+++ /dev/null
@@ -1,327 +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.Security.Permissions
-{
- using System;
- using System.Security;
- using System.Security.Util;
- using System.IO;
- using System.Runtime.Serialization;
- using System.Reflection;
- using System.Collections;
- using System.Globalization;
- using System.Diagnostics.Contracts;
-
- [Serializable]
-[System.Runtime.InteropServices.ComVisible(true)]
- public enum UIPermissionWindow
- {
- // No window use allowed at all.
- NoWindows = 0x0,
-
- // Only allow safe subwindow use (for embedded components).
- SafeSubWindows = 0x01,
-
- // Safe top-level window use only (see specification for details).
- SafeTopLevelWindows = 0x02,
-
- // All windows and all event may be used.
- AllWindows = 0x03,
-
- }
-
- [Serializable]
-[System.Runtime.InteropServices.ComVisible(true)]
- public enum UIPermissionClipboard
- {
- // No clipboard access is allowed.
- NoClipboard = 0x0,
-
- // Paste from the same app domain only.
- OwnClipboard = 0x1,
-
- // Any clipboard access is allowed.
- AllClipboard = 0x2,
-
- }
-
-
-[System.Runtime.InteropServices.ComVisible(true)]
- [Serializable]
- sealed public class UIPermission
- : CodeAccessPermission, IUnrestrictedPermission, IBuiltInPermission
- {
- //------------------------------------------------------
- //
- // PRIVATE STATE DATA
- //
- //------------------------------------------------------
-
- private UIPermissionWindow m_windowFlag;
- private UIPermissionClipboard m_clipboardFlag;
-
- //------------------------------------------------------
- //
- // PUBLIC CONSTRUCTORS
- //
- //------------------------------------------------------
-
- public UIPermission(PermissionState state)
- {
- if (state == PermissionState.Unrestricted)
- {
- SetUnrestricted( true );
- }
- else if (state == PermissionState.None)
- {
- SetUnrestricted( false );
- Reset();
- }
- else
- {
- throw new ArgumentException(Environment.GetResourceString("Argument_InvalidPermissionState"));
- }
- }
-
- public UIPermission(UIPermissionWindow windowFlag, UIPermissionClipboard clipboardFlag )
- {
- VerifyWindowFlag( windowFlag );
- VerifyClipboardFlag( clipboardFlag );
-
- m_windowFlag = windowFlag;
- m_clipboardFlag = clipboardFlag;
- }
-
- public UIPermission(UIPermissionWindow windowFlag )
- {
- VerifyWindowFlag( windowFlag );
-
- m_windowFlag = windowFlag;
- }
-
- public UIPermission(UIPermissionClipboard clipboardFlag )
- {
- VerifyClipboardFlag( clipboardFlag );
-
- m_clipboardFlag = clipboardFlag;
- }
-
-
- //------------------------------------------------------
- //
- // PUBLIC ACCESSOR METHODS
- //
- //------------------------------------------------------
-
- public UIPermissionWindow Window
- {
- set
- {
- VerifyWindowFlag(value);
-
- m_windowFlag = value;
- }
-
- get
- {
- return m_windowFlag;
- }
- }
-
- public UIPermissionClipboard Clipboard
- {
- set
- {
- VerifyClipboardFlag(value);
-
- m_clipboardFlag = value;
- }
-
- get
- {
- return m_clipboardFlag;
- }
- }
-
- //------------------------------------------------------
- //
- // PRIVATE AND PROTECTED HELPERS FOR ACCESSORS AND CONSTRUCTORS
- //
- //------------------------------------------------------
-
- private static void VerifyWindowFlag(UIPermissionWindow flag)
- {
- if (flag < UIPermissionWindow.NoWindows || flag > UIPermissionWindow.AllWindows)
- {
- throw new ArgumentException(Environment.GetResourceString("Arg_EnumIllegalVal", (int)flag));
- }
- Contract.EndContractBlock();
- }
-
- private static void VerifyClipboardFlag(UIPermissionClipboard flag)
- {
- if (flag < UIPermissionClipboard.NoClipboard || flag > UIPermissionClipboard.AllClipboard)
- {
- throw new ArgumentException(Environment.GetResourceString("Arg_EnumIllegalVal", (int)flag));
- }
- Contract.EndContractBlock();
- }
-
- private void Reset()
- {
- m_windowFlag = UIPermissionWindow.NoWindows;
- m_clipboardFlag = UIPermissionClipboard.NoClipboard;
- }
-
- private void SetUnrestricted( bool unrestricted )
- {
- if (unrestricted)
- {
- m_windowFlag = UIPermissionWindow.AllWindows;
- m_clipboardFlag = UIPermissionClipboard.AllClipboard;
- }
- }
-
-#if false
- //------------------------------------------------------
- //
- // OBJECT METHOD OVERRIDES
- //
- //------------------------------------------------------
- public String ToString()
- {
- #if _DEBUG
- StringBuilder sb = new StringBuilder();
- sb.Append("UIPermission(");
- if (IsUnrestricted())
- {
- sb.Append("Unrestricted");
- }
- else
- {
- sb.Append(m_stateNameTableWindow[m_windowFlag]);
- sb.Append(", ");
- sb.Append(m_stateNameTableClipboard[m_clipboardFlag]);
- }
-
- sb.Append(")");
- return sb.ToString();
- #else
- return super.ToString();
- #endif
- }
-#endif
-
- //------------------------------------------------------
- //
- // CODEACCESSPERMISSION IMPLEMENTATION
- //
- //------------------------------------------------------
-
- public bool IsUnrestricted()
- {
- return m_windowFlag == UIPermissionWindow.AllWindows && m_clipboardFlag == UIPermissionClipboard.AllClipboard;
- }
-
- //------------------------------------------------------
- //
- // IPERMISSION IMPLEMENTATION
- //
- //------------------------------------------------------
-
- public override bool IsSubsetOf(IPermission target)
- {
- if (target == null)
- {
- // Only safe subset if this is empty
- return m_windowFlag == UIPermissionWindow.NoWindows && m_clipboardFlag == UIPermissionClipboard.NoClipboard;
- }
-
- try
- {
- UIPermission operand = (UIPermission)target;
- if (operand.IsUnrestricted())
- return true;
- else if (this.IsUnrestricted())
- return false;
- else
- return this.m_windowFlag <= operand.m_windowFlag && this.m_clipboardFlag <= operand.m_clipboardFlag;
- }
- catch (InvalidCastException)
- {
- throw new
- ArgumentException(
- Environment.GetResourceString("Argument_WrongType", this.GetType().FullName)
- );
- }
-
- }
-
- public override IPermission Intersect(IPermission target)
- {
- if (target == null)
- {
- return null;
- }
- else if (!VerifyType(target))
- {
- throw new
- ArgumentException(
- Environment.GetResourceString("Argument_WrongType", this.GetType().FullName)
- );
- }
-
- UIPermission operand = (UIPermission)target;
- UIPermissionWindow isectWindowFlags = m_windowFlag < operand.m_windowFlag ? m_windowFlag : operand.m_windowFlag;
- UIPermissionClipboard isectClipboardFlags = m_clipboardFlag < operand.m_clipboardFlag ? m_clipboardFlag : operand.m_clipboardFlag;
- if (isectWindowFlags == UIPermissionWindow.NoWindows && isectClipboardFlags == UIPermissionClipboard.NoClipboard)
- return null;
- else
- return new UIPermission(isectWindowFlags, isectClipboardFlags);
- }
-
- public override IPermission Union(IPermission target)
- {
- if (target == null)
- {
- return this.Copy();
- }
- else if (!VerifyType(target))
- {
- throw new
- ArgumentException(
- Environment.GetResourceString("Argument_WrongType", this.GetType().FullName)
- );
- }
-
- UIPermission operand = (UIPermission)target;
- UIPermissionWindow isectWindowFlags = m_windowFlag > operand.m_windowFlag ? m_windowFlag : operand.m_windowFlag;
- UIPermissionClipboard isectClipboardFlags = m_clipboardFlag > operand.m_clipboardFlag ? m_clipboardFlag : operand.m_clipboardFlag;
- if (isectWindowFlags == UIPermissionWindow.NoWindows && isectClipboardFlags == UIPermissionClipboard.NoClipboard)
- return null;
- else
- return new UIPermission(isectWindowFlags, isectClipboardFlags);
- }
-
- public override IPermission Copy()
- {
- return new UIPermission(this.m_windowFlag, this.m_clipboardFlag);
- }
-
- /// <internalonly/>
- int IBuiltInPermission.GetTokenIndex()
- {
- return UIPermission.GetTokenIndex();
- }
-
- internal static int GetTokenIndex()
- {
- return BuiltInPermissionIndex.UIPermissionIndex;
- }
-
- }
-
-
-}
diff --git a/src/mscorlib/src/System/Security/Permissions/URLIdentityPermission.cs b/src/mscorlib/src/System/Security/Permissions/URLIdentityPermission.cs
deleted file mode 100644
index 0883bf8979..0000000000
--- a/src/mscorlib/src/System/Security/Permissions/URLIdentityPermission.cs
+++ /dev/null
@@ -1,284 +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.Security.Permissions
-{
- using System;
- using System.Security.Util;
- using System.IO;
- using System.Text;
- using System.Collections;
- using System.Collections.Generic;
- using System.Globalization;
- using System.Runtime.Serialization;
- using System.Diagnostics.Contracts;
-
- [System.Runtime.InteropServices.ComVisible(true)]
-#if FEATURE_SERIALIZATION
- [Serializable]
-#endif
- sealed public class UrlIdentityPermission : CodeAccessPermission, IBuiltInPermission
- {
- //------------------------------------------------------
- //
- // PRIVATE STATE DATA
- //
- //------------------------------------------------------
-
- [OptionalField(VersionAdded = 2)]
- private bool m_unrestricted;
- [OptionalField(VersionAdded = 2)]
- private URLString[] m_urls;
-
- //------------------------------------------------------
- //
- // PUBLIC CONSTRUCTORS
- //
- //------------------------------------------------------
-
-
- public UrlIdentityPermission(PermissionState state)
- {
- if (state == PermissionState.Unrestricted)
- {
- m_unrestricted = true;
- }
- else if (state == PermissionState.None)
- {
- m_unrestricted = false;
- }
- else
- {
- throw new ArgumentException(Environment.GetResourceString("Argument_InvalidPermissionState"));
- }
- }
-
- public UrlIdentityPermission( String site )
- {
- if (site == null)
- throw new ArgumentNullException( nameof(site) );
- Contract.EndContractBlock();
- Url = site;
- }
-
- internal UrlIdentityPermission( URLString site )
- {
- m_unrestricted = false;
- m_urls = new URLString[1];
- m_urls[0] = site;
- }
-
- // Internal function to append all the urls in m_urls to the input originList
- internal void AppendOrigin(ArrayList originList)
- {
- if (m_urls == null)
- originList.Add("");
- else
- {
- int n;
- for(n = 0; n < this.m_urls.Length; n++)
- originList.Add(m_urls[n].ToString());
- }
- }
-
- //------------------------------------------------------
- //
- // PUBLIC ACCESSOR METHODS
- //
- //------------------------------------------------------
-
- public String Url
- {
- set
- {
- m_unrestricted = false;
- if(value == null || value.Length == 0)
- m_urls = null;
- else
- {
- m_urls = new URLString[1];
- m_urls[0] = new URLString( value );
- }
- }
-
- get
- {
- if(m_urls == null)
- return "";
- if(m_urls.Length == 1)
- return m_urls[0].ToString();
- throw new NotSupportedException(Environment.GetResourceString("NotSupported_AmbiguousIdentity"));
- }
- }
-
- //------------------------------------------------------
- //
- // PRIVATE AND PROTECTED HELPERS FOR ACCESSORS AND CONSTRUCTORS
- //
- //------------------------------------------------------
-
- //------------------------------------------------------
- //
- // CODEACCESSPERMISSION IMPLEMENTATION
- //
- //------------------------------------------------------
-
- //------------------------------------------------------
- //
- // IPERMISSION IMPLEMENTATION
- //
- //------------------------------------------------------
-
-
- public override IPermission Copy()
- {
- UrlIdentityPermission perm = new UrlIdentityPermission( PermissionState.None );
- perm.m_unrestricted = this.m_unrestricted;
- if (this.m_urls != null)
- {
- perm.m_urls = new URLString[this.m_urls.Length];
- int n;
- for(n = 0; n < this.m_urls.Length; n++)
- perm.m_urls[n] = (URLString)this.m_urls[n].Copy();
- }
- return perm;
- }
-
- public override bool IsSubsetOf(IPermission target)
- {
- if (target == null)
- {
- if(m_unrestricted)
- return false;
- if(m_urls == null)
- return true;
- if(m_urls.Length == 0)
- return true;
- return false;
- }
- UrlIdentityPermission that = target as UrlIdentityPermission;
- if(that == null)
- throw new ArgumentException(Environment.GetResourceString("Argument_WrongType", this.GetType().FullName));
- if(that.m_unrestricted)
- return true;
- if(m_unrestricted)
- return false;
- if(this.m_urls != null)
- {
- foreach(URLString usThis in this.m_urls)
- {
- bool bOK = false;
- if(that.m_urls != null)
- {
- foreach(URLString usThat in that.m_urls)
- {
- if(usThis.IsSubsetOf(usThat))
- {
- bOK = true;
- break;
- }
- }
- }
- if(!bOK)
- return false;
- }
- }
- return true;
- }
-
- public override IPermission Intersect(IPermission target)
- {
- if (target == null)
- return null;
- UrlIdentityPermission that = target as UrlIdentityPermission;
- if(that == null)
- throw new ArgumentException(Environment.GetResourceString("Argument_WrongType", this.GetType().FullName));
- if(this.m_unrestricted && that.m_unrestricted)
- {
- UrlIdentityPermission res = new UrlIdentityPermission(PermissionState.None);
- res.m_unrestricted = true;
- return res;
- }
- if(this.m_unrestricted)
- return that.Copy();
- if(that.m_unrestricted)
- return this.Copy();
- if(this.m_urls == null || that.m_urls == null || this.m_urls.Length == 0 || that.m_urls.Length == 0)
- return null;
- List<URLString> alUrls = new List<URLString>();
- foreach(URLString usThis in this.m_urls)
- {
- foreach(URLString usThat in that.m_urls)
- {
- URLString usInt = (URLString)usThis.Intersect(usThat);
- if(usInt != null)
- alUrls.Add(usInt);
- }
- }
- if(alUrls.Count == 0)
- return null;
- UrlIdentityPermission result = new UrlIdentityPermission(PermissionState.None);
- result.m_urls = alUrls.ToArray();
- return result;
- }
-
- public override IPermission Union(IPermission target)
- {
- if (target == null)
- {
- if((this.m_urls == null || this.m_urls.Length == 0) && !this.m_unrestricted)
- return null;
- return this.Copy();
- }
- UrlIdentityPermission that = target as UrlIdentityPermission;
- if(that == null)
- throw new ArgumentException(Environment.GetResourceString("Argument_WrongType", this.GetType().FullName));
- if(this.m_unrestricted || that.m_unrestricted)
- {
- UrlIdentityPermission res = new UrlIdentityPermission(PermissionState.None);
- res.m_unrestricted = true;
- return res;
- }
- if (this.m_urls == null || this.m_urls.Length == 0)
- {
- if(that.m_urls == null || that.m_urls.Length == 0)
- return null;
- return that.Copy();
- }
- if(that.m_urls == null || that.m_urls.Length == 0)
- return this.Copy();
- List<URLString> alUrls = new List<URLString>();
- foreach(URLString usThis in this.m_urls)
- alUrls.Add(usThis);
- foreach(URLString usThat in that.m_urls)
- {
- bool bDupe = false;
- foreach(URLString us in alUrls)
- {
- if(usThat.Equals(us))
- {
- bDupe = true;
- break;
- }
- }
- if(!bDupe)
- alUrls.Add(usThat);
- }
- UrlIdentityPermission result = new UrlIdentityPermission(PermissionState.None);
- result.m_urls = alUrls.ToArray();
- return result;
- }
-
- /// <internalonly/>
- int IBuiltInPermission.GetTokenIndex()
- {
- return UrlIdentityPermission.GetTokenIndex();
- }
-
- internal static int GetTokenIndex()
- {
- return BuiltInPermissionIndex.UrlIdentityPermissionIndex;
- }
- }
-}
diff --git a/src/mscorlib/src/System/Security/Permissions/ZoneIdentityPermission.cs b/src/mscorlib/src/System/Security/Permissions/ZoneIdentityPermission.cs
deleted file mode 100644
index 9023c7eece..0000000000
--- a/src/mscorlib/src/System/Security/Permissions/ZoneIdentityPermission.cs
+++ /dev/null
@@ -1,208 +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.Security.Permissions
-{
- using System;
- using System.Globalization;
- using System.Runtime.Serialization;
- using System.Collections;
- using System.Collections.Generic;
- using System.Diagnostics.Contracts;
-
- [System.Runtime.InteropServices.ComVisible(true)]
-#if FEATURE_SERIALIZATION
- [Serializable]
-#endif
- sealed public class ZoneIdentityPermission : CodeAccessPermission, IBuiltInPermission
- {
- //------------------------------------------------------
- //
- // PRIVATE STATE DATA
- //
- //------------------------------------------------------
-
- // Zone Enum Flag
- // ----- ----- -----
- // NoZone -1 0x00
- // MyComputer 0 0x01 (1 << 0)
- // Intranet 1 0x02 (1 << 1)
- // Trusted 2 0x04 (1 << 2)
- // Internet 3 0x08 (1 << 3)
- // Untrusted 4 0x10 (1 << 4)
-
- private const uint AllZones = 0x1f;
- [OptionalField(VersionAdded = 2)]
- private uint m_zones;
-
- //------------------------------------------------------
- //
- // PUBLIC CONSTRUCTORS
- //
- //------------------------------------------------------
-
- public ZoneIdentityPermission(PermissionState state)
- {
- if (state == PermissionState.Unrestricted)
- {
- m_zones = AllZones;
- }
- else if (state == PermissionState.None)
- {
- m_zones = 0;
- }
- else
- {
- throw new ArgumentException(Environment.GetResourceString("Argument_InvalidPermissionState"));
- }
- }
-
- public ZoneIdentityPermission( SecurityZone zone )
- {
- this.SecurityZone = zone;
- }
-
- internal ZoneIdentityPermission( uint zones )
- {
- m_zones = (zones & AllZones);
- }
-
- // Internal function to append all the Zone in this permission to the input ArrayList
- internal void AppendZones(ArrayList zoneList)
- {
- int nEnum = 0;
- uint nFlag;
- for(nFlag = 1; nFlag < AllZones; nFlag <<= 1)
- {
- if((m_zones & nFlag) != 0)
- {
- zoneList.Add((SecurityZone)nEnum);
- }
- nEnum++;
- }
- }
-
- //------------------------------------------------------
- //
- // PUBLIC ACCESSOR METHODS
- //
- //------------------------------------------------------
-
- public SecurityZone SecurityZone
- {
- set
- {
- VerifyZone( value );
- if(value == SecurityZone.NoZone)
- m_zones = 0;
- else
- m_zones = (uint)1 << (int)value;
- }
-
- get
- {
- SecurityZone z = SecurityZone.NoZone;
- int nEnum = 0;
- uint nFlag;
- for(nFlag = 1; nFlag < AllZones; nFlag <<= 1)
- {
- if((m_zones & nFlag) != 0)
- {
- if(z == SecurityZone.NoZone)
- z = (SecurityZone)nEnum;
- else
- return SecurityZone.NoZone;
- }
- nEnum++;
- }
- return z;
- }
- }
-
- //------------------------------------------------------
- //
- // PRIVATE AND PROTECTED HELPERS FOR ACCESSORS AND CONSTRUCTORS
- //
- //------------------------------------------------------
-
- private static void VerifyZone( SecurityZone zone )
- {
- if (zone < SecurityZone.NoZone || zone > SecurityZone.Untrusted)
- {
- throw new ArgumentException( Environment.GetResourceString("Argument_IllegalZone") );
- }
- Contract.EndContractBlock();
- }
-
-
- //------------------------------------------------------
- //
- // CODEACCESSPERMISSION IMPLEMENTATION
- //
- //------------------------------------------------------
-
- //------------------------------------------------------
- //
- // IPERMISSION IMPLEMENTATION
- //
- //------------------------------------------------------
-
-
- public override IPermission Copy()
- {
- return new ZoneIdentityPermission(this.m_zones);
- }
-
- public override bool IsSubsetOf(IPermission target)
- {
- if (target == null)
- return this.m_zones == 0;
-
- ZoneIdentityPermission that = target as ZoneIdentityPermission;
- if (that == null)
- throw new ArgumentException(Environment.GetResourceString("Argument_WrongType", this.GetType().FullName));
- return (this.m_zones & that.m_zones) == this.m_zones;
- }
-
- public override IPermission Intersect(IPermission target)
- {
- if (target == null)
- return null;
-
- ZoneIdentityPermission that = target as ZoneIdentityPermission;
- if (that == null)
- throw new ArgumentException(Environment.GetResourceString("Argument_WrongType", this.GetType().FullName));
- uint newZones = this.m_zones & that.m_zones;
- if(newZones == 0)
- return null;
- return new ZoneIdentityPermission(newZones);
- }
-
- public override IPermission Union(IPermission target)
- {
- if (target == null)
- return this.m_zones != 0 ? this.Copy() : null;
-
- ZoneIdentityPermission that = target as ZoneIdentityPermission;
- if (that == null)
- throw new ArgumentException(Environment.GetResourceString("Argument_WrongType", this.GetType().FullName));
- return new ZoneIdentityPermission(this.m_zones | that.m_zones);
- }
-
- /// <internalonly/>
- int IBuiltInPermission.GetTokenIndex()
- {
- return ZoneIdentityPermission.GetTokenIndex();
- }
-
- internal static int GetTokenIndex()
- {
- return BuiltInPermissionIndex.ZoneIdentityPermissionIndex;
- }
-
- }
-}
diff --git a/src/mscorlib/src/System/Security/Permissions/keycontainerpermission.cs b/src/mscorlib/src/System/Security/Permissions/keycontainerpermission.cs
deleted file mode 100644
index d4f1c273c6..0000000000
--- a/src/mscorlib/src/System/Security/Permissions/keycontainerpermission.cs
+++ /dev/null
@@ -1,634 +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.Security.Permissions {
- using System;
- using System.Collections;
- using System.Collections.Generic;
-#if FEATURE_CRYPTO
- using System.Security.Cryptography;
-#endif
- using System.Security.Util;
- using System.Globalization;
- using System.Diagnostics;
- using System.Diagnostics.Contracts;
-
-[Serializable]
- [Flags]
- [System.Runtime.InteropServices.ComVisible(true)]
- public enum KeyContainerPermissionFlags {
- NoFlags = 0x0000,
-
- Create = 0x0001,
- Open = 0x0002,
- Delete = 0x0004,
-
- Import = 0x0010,
- Export = 0x0020,
-
- Sign = 0x0100,
- Decrypt = 0x0200,
-
- ViewAcl = 0x1000,
- ChangeAcl = 0x2000,
-
- AllFlags = 0x3337
- }
-
- [Serializable]
- [System.Runtime.InteropServices.ComVisible(true)]
- public sealed class KeyContainerPermissionAccessEntry {
- private string m_keyStore;
- private string m_providerName;
- private int m_providerType;
- private string m_keyContainerName;
- private int m_keySpec;
- private KeyContainerPermissionFlags m_flags;
-
- internal KeyContainerPermissionAccessEntry(KeyContainerPermissionAccessEntry accessEntry) :
- this (accessEntry.KeyStore, accessEntry.ProviderName, accessEntry.ProviderType, accessEntry.KeyContainerName,
- accessEntry.KeySpec, accessEntry.Flags) {
- }
-
- public KeyContainerPermissionAccessEntry(string keyContainerName, KeyContainerPermissionFlags flags) :
- this (null, null, -1, keyContainerName, -1, flags) {
- }
-
-#if FEATURE_CRYPTO
- public KeyContainerPermissionAccessEntry(CspParameters parameters, KeyContainerPermissionFlags flags) :
- this((parameters.Flags & CspProviderFlags.UseMachineKeyStore) == CspProviderFlags.UseMachineKeyStore ? "Machine" : "User",
- parameters.ProviderName,
- parameters.ProviderType,
- parameters.KeyContainerName,
- parameters.KeyNumber,
- flags) {
- }
-#endif
-
- public KeyContainerPermissionAccessEntry(string keyStore, string providerName, int providerType,
- string keyContainerName, int keySpec, KeyContainerPermissionFlags flags) {
- m_providerName = (providerName == null ? "*" : providerName);
- m_providerType = providerType;
- m_keyContainerName = (keyContainerName == null ? "*" : keyContainerName);
- m_keySpec = keySpec;
- KeyStore = keyStore;
- Flags = flags;
- }
-
- public string KeyStore {
- get {
- return m_keyStore;
- }
- set {
- // Unrestricted entries are invalid; they should not be allowed.
- if (IsUnrestrictedEntry(value, this.ProviderName, this.ProviderType, this.KeyContainerName, this.KeySpec))
- throw new ArgumentException(Environment.GetResourceString("Arg_InvalidAccessEntry"));
-
- if (value == null) {
- m_keyStore = "*";
- } else {
- if (value != "User" && value != "Machine" && value != "*")
- throw new ArgumentException(Environment.GetResourceString("Argument_InvalidKeyStore", value), nameof(value));
- m_keyStore = value;
- }
- }
- }
-
- public string ProviderName {
- get {
- return m_providerName;
- }
- set {
- // Unrestricted entries are invalid; they should not be allowed.
- if (IsUnrestrictedEntry(this.KeyStore, value, this.ProviderType, this.KeyContainerName, this.KeySpec))
- throw new ArgumentException(Environment.GetResourceString("Arg_InvalidAccessEntry"));
-
- if (value == null)
- m_providerName = "*";
- else
- m_providerName = value;
- }
- }
-
- public int ProviderType {
- get {
- return m_providerType;
- }
- set {
- // Unrestricted entries are invalid; they should not be allowed.
- if (IsUnrestrictedEntry(this.KeyStore, this.ProviderName, value, this.KeyContainerName, this.KeySpec))
- throw new ArgumentException(Environment.GetResourceString("Arg_InvalidAccessEntry"));
-
- m_providerType = value;
- }
- }
-
- public string KeyContainerName {
- get {
- return m_keyContainerName;
- }
- set {
- // Unrestricted entries are invalid; they should not be allowed.
- if (IsUnrestrictedEntry(this.KeyStore, this.ProviderName, this.ProviderType, value, this.KeySpec))
- throw new ArgumentException(Environment.GetResourceString("Arg_InvalidAccessEntry"));
-
- if (value == null)
- m_keyContainerName = "*";
- else
- m_keyContainerName = value;
- }
- }
-
- public int KeySpec {
- get {
- return m_keySpec;
- }
- set {
- // Unrestricted entries are invalid; they should not be allowed.
- if (IsUnrestrictedEntry(this.KeyStore, this.ProviderName, this.ProviderType, this.KeyContainerName, value))
- throw new ArgumentException(Environment.GetResourceString("Arg_InvalidAccessEntry"));
-
- m_keySpec = value;
- }
- }
-
- public KeyContainerPermissionFlags Flags {
- get {
- return m_flags;
- }
- set {
- KeyContainerPermission.VerifyFlags(value);
- m_flags = value;
- }
- }
-
- public override bool Equals (Object o) {
- KeyContainerPermissionAccessEntry accessEntry = o as KeyContainerPermissionAccessEntry;
- if (accessEntry == null)
- return false;
-
- if (accessEntry.m_keyStore != m_keyStore) return false;
- if (accessEntry.m_providerName != m_providerName) return false;
- if (accessEntry.m_providerType != m_providerType) return false;
- if (accessEntry.m_keyContainerName != m_keyContainerName) return false;
- if (accessEntry.m_keySpec != m_keySpec) return false;
-
- return true;
- }
-
- public override int GetHashCode () {
- int hash = 0;
-
- hash |= (this.m_keyStore.GetHashCode() & 0x000000FF) << 24;
- hash |= (this.m_providerName.GetHashCode() & 0x000000FF) << 16;
- hash |= (this.m_providerType & 0x0000000F) << 12;
- hash |= (this.m_keyContainerName.GetHashCode() & 0x000000FF) << 4;
- hash |= (this.m_keySpec & 0x0000000F);
-
- return hash;
- }
-
- internal bool IsSubsetOf (KeyContainerPermissionAccessEntry target) {
- if (target.m_keyStore != "*" && this.m_keyStore != target.m_keyStore)
- return false;
- if (target.m_providerName != "*" && this.m_providerName != target.m_providerName)
- return false;
- if (target.m_providerType != -1 && this.m_providerType != target.m_providerType)
- return false;
- if (target.m_keyContainerName != "*" && this.m_keyContainerName != target.m_keyContainerName)
- return false;
- if (target.m_keySpec != -1 && this.m_keySpec != target.m_keySpec)
- return false;
-
- return true;
- }
-
- internal static bool IsUnrestrictedEntry (string keyStore, string providerName, int providerType,
- string keyContainerName, int keySpec) {
- if (keyStore != "*" && keyStore != null) return false;
- if (providerName != "*" && providerName != null) return false;
- if (providerType != -1) return false;
- if (keyContainerName != "*" && keyContainerName != null) return false;
- if (keySpec != -1) return false;
-
- return true;
- }
- }
-
- [Serializable]
- [System.Runtime.InteropServices.ComVisible(true)]
- public sealed class KeyContainerPermissionAccessEntryCollection : ICollection {
- private ArrayList m_list;
- private KeyContainerPermissionFlags m_globalFlags;
-
- private KeyContainerPermissionAccessEntryCollection () {}
- internal KeyContainerPermissionAccessEntryCollection (KeyContainerPermissionFlags globalFlags) {
- m_list = new ArrayList();
- m_globalFlags = globalFlags;
- }
-
- public KeyContainerPermissionAccessEntry this[int index] {
- get {
- if (index < 0)
- throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_EnumNotStarted"));
- if (index >= Count)
- throw new ArgumentOutOfRangeException(nameof(index), Environment.GetResourceString("ArgumentOutOfRange_Index"));
- Contract.EndContractBlock();
-
- return (KeyContainerPermissionAccessEntry)m_list[index];
- }
- }
-
- public int Count {
- get {
- return m_list.Count;
- }
- }
-
- public int Add (KeyContainerPermissionAccessEntry accessEntry) {
- if (accessEntry == null)
- throw new ArgumentNullException(nameof(accessEntry));
- Contract.EndContractBlock();
-
- int index = m_list.IndexOf(accessEntry);
- if (index == -1) {
- if (accessEntry.Flags != m_globalFlags) {
- return m_list.Add(accessEntry);
- }
- else
- return -1;
- } else {
- // We pick up the intersection of the 2 flags. This is the secure choice
- // so we are opting for it.
- ((KeyContainerPermissionAccessEntry)m_list[index]).Flags &= accessEntry.Flags;
- return index;
- }
- }
-
- public void Clear () {
- m_list.Clear();
- }
-
- public int IndexOf (KeyContainerPermissionAccessEntry accessEntry) {
- return m_list.IndexOf(accessEntry);
- }
-
- public void Remove (KeyContainerPermissionAccessEntry accessEntry) {
- if (accessEntry == null)
- throw new ArgumentNullException(nameof(accessEntry));
- Contract.EndContractBlock();
- m_list.Remove(accessEntry);
- }
-
- public KeyContainerPermissionAccessEntryEnumerator GetEnumerator () {
- return new KeyContainerPermissionAccessEntryEnumerator(this);
- }
-
- /// <internalonly/>
- IEnumerator IEnumerable.GetEnumerator () {
- return new KeyContainerPermissionAccessEntryEnumerator(this);
- }
-
- /// <internalonly/>
- void ICollection.CopyTo (Array array, int index) {
- if (array == null)
- 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(nameof(index), Environment.GetResourceString("ArgumentOutOfRange_Index"));
- if (index + this.Count > array.Length)
- throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen"));
- Contract.EndContractBlock();
-
- for (int i=0; i < this.Count; i++) {
- array.SetValue(this[i], index);
- index++;
- }
- }
-
- public void CopyTo (KeyContainerPermissionAccessEntry[] array, int index) {
- ((ICollection)this).CopyTo(array, index);
- }
-
- public bool IsSynchronized {
- get {
- return false;
- }
- }
-
- public Object SyncRoot {
- get {
- return this;
- }
- }
- }
-
- [Serializable]
- [System.Runtime.InteropServices.ComVisible(true)]
- public sealed class KeyContainerPermissionAccessEntryEnumerator : IEnumerator {
- private KeyContainerPermissionAccessEntryCollection m_entries;
- private int m_current;
-
- private KeyContainerPermissionAccessEntryEnumerator () {}
- internal KeyContainerPermissionAccessEntryEnumerator (KeyContainerPermissionAccessEntryCollection entries) {
- m_entries = entries;
- m_current = -1;
- }
-
- public KeyContainerPermissionAccessEntry Current {
- get {
- return m_entries[m_current];
- }
- }
-
- /// <internalonly/>
- Object IEnumerator.Current {
- get {
- return (Object) m_entries[m_current];
- }
- }
-
- public bool MoveNext() {
- if (m_current == ((int) m_entries.Count - 1))
- return false;
- m_current++;
- return true;
- }
-
- public void Reset() {
- m_current = -1;
- }
- }
-
- [Serializable]
- [System.Runtime.InteropServices.ComVisible(true)]
- public sealed class KeyContainerPermission : CodeAccessPermission, IUnrestrictedPermission, IBuiltInPermission {
- private KeyContainerPermissionFlags m_flags;
- private KeyContainerPermissionAccessEntryCollection m_accessEntries;
-
- public KeyContainerPermission (PermissionState state) {
- if (state == PermissionState.Unrestricted)
- m_flags = KeyContainerPermissionFlags.AllFlags;
- else if (state == PermissionState.None)
- m_flags = KeyContainerPermissionFlags.NoFlags;
- else
- throw new ArgumentException(Environment.GetResourceString("Argument_InvalidPermissionState"));
- m_accessEntries = new KeyContainerPermissionAccessEntryCollection(m_flags);
- }
-
- public KeyContainerPermission (KeyContainerPermissionFlags flags) {
- VerifyFlags(flags);
- m_flags = flags;
- m_accessEntries = new KeyContainerPermissionAccessEntryCollection(m_flags);
- }
-
- public KeyContainerPermission (KeyContainerPermissionFlags flags, KeyContainerPermissionAccessEntry[] accessList) {
- if (accessList == null)
- throw new ArgumentNullException(nameof(accessList));
- Contract.EndContractBlock();
-
- VerifyFlags(flags);
- m_flags = flags;
- m_accessEntries = new KeyContainerPermissionAccessEntryCollection(m_flags);
- for (int index = 0; index < accessList.Length; index++) {
- m_accessEntries.Add(accessList[index]);
- }
- }
-
- public KeyContainerPermissionFlags Flags {
- get {
- return m_flags;
- }
- }
-
- public KeyContainerPermissionAccessEntryCollection AccessEntries {
- get {
- return m_accessEntries;
- }
- }
-
- public bool IsUnrestricted () {
- if (m_flags != KeyContainerPermissionFlags.AllFlags)
- return false;
-
- foreach (KeyContainerPermissionAccessEntry accessEntry in AccessEntries) {
- if ((accessEntry.Flags & KeyContainerPermissionFlags.AllFlags) != KeyContainerPermissionFlags.AllFlags)
- return false;
- }
-
- return true;
- }
-
- private bool IsEmpty () {
- if (this.Flags == KeyContainerPermissionFlags.NoFlags) {
- foreach (KeyContainerPermissionAccessEntry accessEntry in AccessEntries) {
- if (accessEntry.Flags != KeyContainerPermissionFlags.NoFlags)
- return false;
- }
- return true;
- }
- return false;
- }
-
- //
- // IPermission implementation
- //
-
- public override bool IsSubsetOf (IPermission target) {
- if (target == null)
- return IsEmpty();
-
- if (!VerifyType(target))
- throw new ArgumentException(Environment.GetResourceString("Argument_WrongType", this.GetType().FullName));
-
- KeyContainerPermission operand = (KeyContainerPermission) target;
-
- // since there are containers that are neither in the access list of the source, nor in the
- // access list of the target, the source flags must be a subset of the target flags.
- if ((this.m_flags & operand.m_flags) != this.m_flags)
- return false;
-
- // Any entry in the source should have "applicable" flags in the destination that actually
- // are less restrictive than the flags in the source.
-
- foreach (KeyContainerPermissionAccessEntry accessEntry in AccessEntries) {
- KeyContainerPermissionFlags targetFlags = GetApplicableFlags(accessEntry, operand);
- if ((accessEntry.Flags & targetFlags) != accessEntry.Flags)
- return false;
- }
-
- // Any entry in the target should have "applicable" flags in the source that actually
- // are more restrictive than the flags in the target.
-
- foreach (KeyContainerPermissionAccessEntry accessEntry in operand.AccessEntries) {
- KeyContainerPermissionFlags sourceFlags = GetApplicableFlags(accessEntry, this);
- if ((sourceFlags & accessEntry.Flags) != sourceFlags)
- return false;
- }
-
- return true;
- }
-
- public override IPermission Intersect (IPermission target) {
- if (target == null)
- return null;
-
- if (!VerifyType(target))
- throw new ArgumentException(Environment.GetResourceString("Argument_WrongType", this.GetType().FullName));
-
- KeyContainerPermission operand = (KeyContainerPermission) target;
- if (this.IsEmpty() || operand.IsEmpty())
- return null;
-
- KeyContainerPermissionFlags flags_intersect = operand.m_flags & this.m_flags;
- KeyContainerPermission cp = new KeyContainerPermission(flags_intersect);
- foreach (KeyContainerPermissionAccessEntry accessEntry in AccessEntries) {
- cp.AddAccessEntryAndIntersect(accessEntry, operand);
- }
- foreach (KeyContainerPermissionAccessEntry accessEntry in operand.AccessEntries) {
- cp.AddAccessEntryAndIntersect(accessEntry, this);
- }
- return cp.IsEmpty() ? null : cp;
- }
-
- public override IPermission Union (IPermission target) {
- if (target == null)
- return this.Copy();
-
- if (!VerifyType(target))
- throw new ArgumentException(Environment.GetResourceString("Argument_WrongType", this.GetType().FullName));
-
- KeyContainerPermission operand = (KeyContainerPermission) target;
- if (this.IsUnrestricted() || operand.IsUnrestricted())
- return new KeyContainerPermission(PermissionState.Unrestricted);
-
- KeyContainerPermissionFlags flags_union = (KeyContainerPermissionFlags) (m_flags | operand.m_flags);
- KeyContainerPermission cp = new KeyContainerPermission(flags_union);
- foreach (KeyContainerPermissionAccessEntry accessEntry in AccessEntries) {
- cp.AddAccessEntryAndUnion(accessEntry, operand);
- }
- foreach (KeyContainerPermissionAccessEntry accessEntry in operand.AccessEntries) {
- cp.AddAccessEntryAndUnion(accessEntry, this);
- }
- return cp.IsEmpty() ? null : cp;
- }
-
- public override IPermission Copy () {
- if (this.IsEmpty())
- return null;
-
- KeyContainerPermission cp = new KeyContainerPermission((KeyContainerPermissionFlags)m_flags);
- foreach (KeyContainerPermissionAccessEntry accessEntry in AccessEntries) {
- cp.AccessEntries.Add(accessEntry);
- }
- return cp;
- }
-
- /// <internalonly/>
- int IBuiltInPermission.GetTokenIndex () {
- return KeyContainerPermission.GetTokenIndex();
- }
-
- //
- // private methods
- //
-
- private void AddAccessEntries(SecurityElement securityElement) {
- if (securityElement.InternalChildren != null && securityElement.InternalChildren.Count != 0) {
- IEnumerator elemEnumerator = securityElement.Children.GetEnumerator();
- while (elemEnumerator.MoveNext()) {
- SecurityElement current = (SecurityElement) elemEnumerator.Current;
- if (current != null) {
- if (String.Equals(current.Tag, "AccessEntry")) {
- int iMax = current.m_lAttributes.Count;
- 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;
- string keyContainerName = null;
- int keySpec = -1;
- KeyContainerPermissionFlags flags = KeyContainerPermissionFlags.NoFlags;
- for (int i = 0; i < iMax; i += 2) {
- String strAttrName = (String) current.m_lAttributes[i];
- String strAttrValue = (String) current.m_lAttributes[i+1];
- if (String.Equals(strAttrName, "KeyStore"))
- keyStore = strAttrValue;
- if (String.Equals(strAttrName, "ProviderName"))
- providerName = strAttrValue;
- else if (String.Equals(strAttrName, "ProviderType"))
- providerType = Convert.ToInt32(strAttrValue, null);
- else if (String.Equals(strAttrName, "KeyContainerName"))
- keyContainerName = strAttrValue;
- else if (String.Equals(strAttrName, "KeySpec"))
- keySpec = Convert.ToInt32(strAttrValue, null);
- else if (String.Equals(strAttrName, "Flags")) {
- flags = (KeyContainerPermissionFlags) Enum.Parse(typeof(KeyContainerPermissionFlags), strAttrValue);
- }
- }
- KeyContainerPermissionAccessEntry accessEntry = new KeyContainerPermissionAccessEntry(keyStore, providerName, providerType, keyContainerName, keySpec, flags);
- AccessEntries.Add(accessEntry);
- }
- }
- }
- }
- }
-
- private void AddAccessEntryAndUnion (KeyContainerPermissionAccessEntry accessEntry, KeyContainerPermission target) {
- KeyContainerPermissionAccessEntry newAccessEntry = new KeyContainerPermissionAccessEntry(accessEntry);
- newAccessEntry.Flags |= GetApplicableFlags(accessEntry, target);
- AccessEntries.Add(newAccessEntry);
- }
-
- private void AddAccessEntryAndIntersect (KeyContainerPermissionAccessEntry accessEntry, KeyContainerPermission target) {
- KeyContainerPermissionAccessEntry newAccessEntry = new KeyContainerPermissionAccessEntry(accessEntry);
- newAccessEntry.Flags &= GetApplicableFlags(accessEntry, target);
- AccessEntries.Add(newAccessEntry);
- }
-
- //
- // private/internal static methods.
- //
-
- internal static void VerifyFlags (KeyContainerPermissionFlags flags) {
- if ((flags & ~KeyContainerPermissionFlags.AllFlags) != 0)
- throw new ArgumentException(Environment.GetResourceString("Arg_EnumIllegalVal", (int)flags));
- Contract.EndContractBlock();
- }
-
- private static KeyContainerPermissionFlags GetApplicableFlags (KeyContainerPermissionAccessEntry accessEntry, KeyContainerPermission target) {
- KeyContainerPermissionFlags flags = KeyContainerPermissionFlags.NoFlags;
- bool applyDefaultFlags = true;
-
- // If the entry exists in the target, return the flag of the target entry.
- int index = target.AccessEntries.IndexOf(accessEntry);
- if (index != -1) {
- flags = ((KeyContainerPermissionAccessEntry)target.AccessEntries[index]).Flags;
- return flags;
- }
-
- // Intersect the flags in all the target entries that apply to the current access entry,
- foreach (KeyContainerPermissionAccessEntry targetAccessEntry in target.AccessEntries) {
- if (accessEntry.IsSubsetOf(targetAccessEntry)) {
- if (applyDefaultFlags == false) {
- flags &= targetAccessEntry.Flags;
- } else {
- flags = targetAccessEntry.Flags;
- applyDefaultFlags = false;
- }
- }
- }
-
- // If no target entry applies to the current entry, the default global flag applies.
- if (applyDefaultFlags)
- flags = target.Flags;
-
- return flags;
- }
-
- private static int GetTokenIndex() {
- return BuiltInPermissionIndex.KeyContainerPermissionIndex;
- }
- }
-}
diff --git a/src/mscorlib/src/System/Security/Policy/ApplicationTrust.cs b/src/mscorlib/src/System/Security/Policy/ApplicationTrust.cs
deleted file mode 100644
index 3d4e35adf4..0000000000
--- a/src/mscorlib/src/System/Security/Policy/ApplicationTrust.cs
+++ /dev/null
@@ -1,126 +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.
-
-//
-// This class encapsulates security decisions about an application.
-//
-
-namespace System.Security.Policy
-{
- using System.Collections;
- using System.Collections.Generic;
- using System.Globalization;
- using System.IO;
- using System.Runtime.InteropServices;
-#if FEATURE_SERIALIZATION
- using System.Runtime.Serialization;
- using System.Runtime.Serialization.Formatters.Binary;
-#endif // FEATURE_SERIALIZATION
- using System.Runtime.Versioning;
- using System.Security.Permissions;
- using System.Security.Util;
- using System.Text;
- using System.Threading;
- using System.Diagnostics.Contracts;
-
- [System.Runtime.InteropServices.ComVisible(true)]
- public enum ApplicationVersionMatch {
- MatchExactVersion,
- MatchAllVersions
- }
-
- [System.Runtime.InteropServices.ComVisible(true)]
- [Serializable]
- public sealed class ApplicationTrust : EvidenceBase, ISecurityEncodable
- {
- private PolicyStatement m_psDefaultGrant;
- private IList<StrongName> m_fullTrustAssemblies;
-
- // Permission special flags for the default grant set in this ApplicationTrust. This should be
- // updated in sync with any updates to the default grant set.
- //
- // In the general case, these values cannot be trusted - we only store a reference to the
- // DefaultGrantSet, and return the reference directly, which means that code can update the
- // permission set without our knowledge. That would lead to the flags getting out of sync with the
- // grant set.
- //
- // However, we only care about these flags when we're creating a homogenous AppDomain, and in that
- // case we control the ApplicationTrust object end-to-end, and know that the permission set will not
- // change after the flags are calculated.
- [NonSerialized]
- private int m_grantSetSpecialFlags;
-
- public ApplicationTrust () : this (new PermissionSet(PermissionState.None))
- {
- }
-
- internal ApplicationTrust (PermissionSet defaultGrantSet)
- {
- InitDefaultGrantSet(defaultGrantSet);
-
- m_fullTrustAssemblies = new List<StrongName>().AsReadOnly();
- }
-
- public ApplicationTrust(PermissionSet defaultGrantSet, IEnumerable<StrongName> fullTrustAssemblies) {
- if (fullTrustAssemblies == null) {
- throw new ArgumentNullException(nameof(fullTrustAssemblies));
- }
-
- InitDefaultGrantSet(defaultGrantSet);
-
- List<StrongName> fullTrustList = new List<StrongName>();
- foreach (StrongName strongName in fullTrustAssemblies) {
- if (strongName == null) {
- throw new ArgumentException(Environment.GetResourceString("Argument_NullFullTrustAssembly"), nameof(fullTrustAssemblies));
- }
-
- fullTrustList.Add(new StrongName(strongName.PublicKey, strongName.Name, strongName.Version));
- }
-
- m_fullTrustAssemblies = fullTrustList.AsReadOnly();
- }
-
- // Sets up the default grant set for all constructors. Extracted to avoid the cost of
- // IEnumerable virtual dispatches on startup when there are no fullTrustAssemblies (CoreCLR)
- private void InitDefaultGrantSet(PermissionSet defaultGrantSet) {
- if (defaultGrantSet == null) {
- throw new ArgumentNullException(nameof(defaultGrantSet));
- }
-
- // Creating a PolicyStatement copies the incoming permission set, so we don't have to worry
- // about the PermissionSet parameter changing underneath us after we've calculated the
- // permisison flags in the DefaultGrantSet setter.
- DefaultGrantSet = new PolicyStatement(defaultGrantSet);
- }
-
- public PolicyStatement DefaultGrantSet {
- get {
- if (m_psDefaultGrant == null)
- return new PolicyStatement(new PermissionSet(PermissionState.None));
- return m_psDefaultGrant;
- }
- set {
- if (value == null) {
- m_psDefaultGrant = null;
- m_grantSetSpecialFlags = 0;
- }
- else {
- m_psDefaultGrant = value;
- m_grantSetSpecialFlags = SecurityManager.GetSpecialFlags(m_psDefaultGrant.PermissionSet, null);
- }
- }
- }
-
- public IList<StrongName> FullTrustAssemblies {
- get {
- return m_fullTrustAssemblies;
- }
- }
-
- public override EvidenceBase Clone()
- {
- return base.Clone();
- }
- }
-}
diff --git a/src/mscorlib/src/System/Security/Policy/Evidence.cs b/src/mscorlib/src/System/Security/Policy/Evidence.cs
deleted file mode 100644
index 22479dff6c..0000000000
--- a/src/mscorlib/src/System/Security/Policy/Evidence.cs
+++ /dev/null
@@ -1,38 +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.Security.Policy
-{
- using System.Runtime.InteropServices;
-#if FEATURE_SERIALIZATION
- using System.Runtime.Serialization;
- using System.Runtime.Serialization.Formatters.Binary;
-#endif // FEATURE_SERIALIZATION
-
- /// <summary>
- /// The Evidence class keeps track of information that can be used to make security decisions about
- /// an assembly or an AppDomain. There are two types of evidence, one is supplied by the CLR or a
- /// host, the other supplied by the assembly itself.
- ///
- /// We keep a dictionary that maps each type of possbile evidence to an EvidenceTypeDescriptor which
- /// contains the evidence objects themselves if they exist as well as some extra metadata about that
- /// type of evidence. This dictionary is fully populated with keys for host evidence at all times and
- /// for assembly evidence the first time the application evidence is touched. This means that if a
- /// Type key does not exist in the dictionary, then that particular type of evidence will never be
- /// given to the assembly or AppDomain in question as host evidence. The only exception is if the
- /// user later manually adds host evidence via the AddHostEvidence API.
- ///
- /// Assembly supplied evidence is created up front, however host supplied evidence may be lazily
- /// created. In the lazy creation case, the Type will map to either an EvidenceTypeDescriptor that does
- /// not contain any evidence data or null. As requests come in for that evidence, we'll populate the
- /// EvidenceTypeDescriptor appropriately.
- /// </summary>
-#if FEATURE_SERIALIZATION
- [Serializable]
-#endif
- [ComVisible(true)]
- public sealed class Evidence
- {
- }
-}
diff --git a/src/mscorlib/src/System/Security/Policy/EvidenceBase.cs b/src/mscorlib/src/System/Security/Policy/EvidenceBase.cs
deleted file mode 100644
index 7fef1ded3c..0000000000
--- a/src/mscorlib/src/System/Security/Policy/EvidenceBase.cs
+++ /dev/null
@@ -1,178 +0,0 @@
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-// See the LICENSE file in the project root for more information.
-
-//
-
-using System;
-using System.Collections;
-using System.Collections.Generic;
-using System.Diagnostics;
-using System.Diagnostics.Contracts;
-using System.IO;
-using System.Runtime.InteropServices;
-#if FEATURE_SERIALIZATION
-using System.Runtime.Serialization.Formatters.Binary;
-#endif // FEATURE_SERIALIZATION
-using System.Security.Permissions;
-
-namespace System.Security.Policy
-{
- /// <summary>
- /// Base class from which all objects to be used as Evidence must derive
- /// </summary>
- [ComVisible(true)]
- [Serializable]
- public abstract class EvidenceBase
- {
- protected EvidenceBase()
- {
-#if FEATURE_SERIALIZATION
- // All objects to be used as evidence must be serializable. Make sure that any derived types
- // are marked serializable to enforce this, since the attribute does not inherit down to derived
- // classes.
- if (!GetType().IsSerializable)
- {
- throw new InvalidOperationException(Environment.GetResourceString("Policy_EvidenceMustBeSerializable"));
- }
-#endif // FEATURE_SERIALIZATION
- }
-
- /// <remarks>
- /// Since legacy evidence objects would be cloned by being serialized, the default implementation
- /// of EvidenceBase will do the same.
- /// </remarks>
- public virtual EvidenceBase Clone()
- {
-#if FEATURE_SERIALIZATION
- using (MemoryStream memoryStream = new MemoryStream())
- {
- BinaryFormatter formatter = new BinaryFormatter();
- formatter.Serialize(memoryStream, this);
-
- memoryStream.Position = 0;
- return formatter.Deserialize(memoryStream) as EvidenceBase;
- }
-#else // !FEATURE_SERIALIZATION
- throw new NotImplementedException();
-#endif // FEATURE_SERIALIZATION
- }
- }
-
- /// <summary>
- /// Interface for types which wrap Whidbey evidence objects for compatibility with v4 evidence rules
- /// </summary>
- internal interface ILegacyEvidenceAdapter
- {
- object EvidenceObject { get; }
- Type EvidenceType { get; }
- }
-
- /// <summary>
- /// Wrapper class to hold legacy evidence objects which do not derive from EvidenceBase, and allow
- /// them to be held in the Evidence collection which expects to maintain lists of EvidenceBase only
- /// </summary>
- [Serializable]
- internal sealed class LegacyEvidenceWrapper : EvidenceBase, ILegacyEvidenceAdapter
- {
- private object m_legacyEvidence;
-
- internal LegacyEvidenceWrapper(object legacyEvidence)
- {
- 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;
- }
-
- public object EvidenceObject
- {
- get { return m_legacyEvidence; }
- }
-
- public Type EvidenceType
- {
- get { return m_legacyEvidence.GetType(); }
- }
-
- public override bool Equals(object obj)
- {
- return m_legacyEvidence.Equals(obj);
- }
-
- public override int GetHashCode()
- {
- return m_legacyEvidence.GetHashCode();
- }
-
- public override EvidenceBase Clone()
- {
- return base.Clone();
- }
- }
-
- /// <summary>
- /// Pre-v4 versions of the runtime allow multiple pieces of evidence that all have the same type.
- /// This type wraps those evidence objects into a single type of list, allowing legacy code to continue
- /// to work with the Evidence collection that does not expect multiple evidences of the same type.
- ///
- /// This may not be limited to LegacyEvidenceWrappers, since it's valid for legacy code to add multiple
- /// objects of built-in evidence to an Evidence collection. The built-in evidence now derives from
- /// EvienceObject, so when the legacy code runs on v4, it may end up attempting to add multiple
- /// Hash evidences for intsance.
- /// </summary>
- [Serializable]
- internal sealed class LegacyEvidenceList : EvidenceBase, IEnumerable<EvidenceBase>, ILegacyEvidenceAdapter
- {
- private List<EvidenceBase> m_legacyEvidenceList = new List<EvidenceBase>();
-
- public object EvidenceObject
- {
- get
- {
- // We'll choose the first item in the list to represent us if we're forced to return only
- // one object. This can occur if multiple pieces of evidence are added via the legacy APIs,
- // and then the new APIs are used to retrieve that evidence.
- return m_legacyEvidenceList.Count > 0 ? m_legacyEvidenceList[0] : null;
- }
- }
-
- public Type EvidenceType
- {
- get
- {
- 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;
- }
- }
-
- public void Add(EvidenceBase evidence)
- {
- 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");
- Debug.Assert(evidence.GetType() != typeof(LegacyEvidenceList),
- "Attempt to add a legacy evidence list to another legacy evidence list");
-
- m_legacyEvidenceList.Add(evidence);
- }
-
- public IEnumerator<EvidenceBase> GetEnumerator()
- {
- return m_legacyEvidenceList.GetEnumerator();
- }
-
- IEnumerator System.Collections.IEnumerable.GetEnumerator()
- {
- return m_legacyEvidenceList.GetEnumerator();
- }
-
- 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
deleted file mode 100644
index 8deb145102..0000000000
--- a/src/mscorlib/src/System/Security/Policy/EvidenceTypeDescriptor.cs
+++ /dev/null
@@ -1,160 +0,0 @@
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-// See the LICENSE file in the project root for more information.
-using System;
-using System.Diagnostics;
-using System.Diagnostics.Contracts;
-using System.Runtime.Serialization;
-
-namespace System.Security.Policy
-{
- /// <summary>
- /// Descriptor stored in the Evidence collection to detail the information we have about a type of
- /// evidence. This descriptor also stores any evidence that's been generated of the specific type.
- /// </summary>
- [Serializable]
- internal sealed class EvidenceTypeDescriptor
- {
- [NonSerialized]
- private bool m_hostCanGenerate;
-
- [NonSerialized]
- private bool m_generated;
-
- private EvidenceBase m_hostEvidence;
- private EvidenceBase m_assemblyEvidence;
-
- // EvidenceTypeDescriptors are stored in Evidence indexed by the type they describe, so this
- // information is redundant. We keep it around in checked builds to help debugging, but we can drop
- // it from retial builds.
-#if _DEBUG
- [NonSerialized]
- private Type m_evidenceType;
-#endif // _DEBUG
-
- public EvidenceTypeDescriptor()
- {
- }
-
- /// <summary>
- /// Make a deep copy of a type descriptor
- /// </summary>
- private EvidenceTypeDescriptor(EvidenceTypeDescriptor descriptor)
- {
- Debug.Assert(descriptor != null);
-
- m_hostCanGenerate = descriptor.m_hostCanGenerate;
-
- if (descriptor.m_assemblyEvidence != null)
- {
- m_assemblyEvidence = descriptor.m_assemblyEvidence.Clone() as EvidenceBase;
- }
- if (descriptor.m_hostEvidence != null)
- {
- m_hostEvidence = descriptor.m_hostEvidence.Clone() as EvidenceBase;
- }
-
-#if _DEBUG
- m_evidenceType = descriptor.m_evidenceType;
-#endif // _DEBUG
- }
-
- /// <summary>
- /// Evidence of this type supplied by the assembly
- /// </summary>
- public EvidenceBase AssemblyEvidence
- {
- get { return m_assemblyEvidence; }
-
- set
- {
- Debug.Assert(value != null);
-#if _DEBUG
- Debug.Assert(CheckEvidenceType(value), "Incorrect type of AssemblyEvidence set");
-#endif
- m_assemblyEvidence = value;
- }
- }
-
- /// <summary>
- /// Flag indicating that we've already attempted to generate this type of evidence
- /// </summary>
- public bool Generated
- {
- get { return m_generated; }
-
- set
- {
- Debug.Assert(value, "Attempt to clear the Generated flag");
- m_generated = value;
- }
- }
-
- /// <summary>
- /// Has the HostSecurityManager has told us that it can potentially generate evidence of this type
- /// </summary>
- public bool HostCanGenerate
- {
- get { return m_hostCanGenerate; }
-
- set
- {
- Debug.Assert(value, "Attempt to clear HostCanGenerate flag");
- m_hostCanGenerate = value;
- }
- }
-
- /// <summary>
- /// Evidence of this type supplied by the CLR or the host
- /// </summary>
- public EvidenceBase HostEvidence
- {
- get { return m_hostEvidence; }
-
- set
- {
- Debug.Assert(value != null);
-#if _DEBUG
- Debug.Assert(CheckEvidenceType(value), "Incorrect type of HostEvidence set");
-#endif
- m_hostEvidence = value;
- }
- }
-
-#if _DEBUG
- /// <summary>
- /// Verify that evidence being stored in this descriptor is of the correct type
- /// </summary>
- private bool CheckEvidenceType(EvidenceBase evidence)
- {
- Debug.Assert(evidence != null);
-
- ILegacyEvidenceAdapter legacyAdapter = evidence as ILegacyEvidenceAdapter;
- Type storedType = legacyAdapter == null ? evidence.GetType() : legacyAdapter.EvidenceType;
-
- return m_evidenceType == null || m_evidenceType.IsAssignableFrom(storedType);
- }
-#endif // _DEBUG
-
- /// <summary>
- /// Make a deep copy of this descriptor
- /// </summary>
- public EvidenceTypeDescriptor Clone()
- {
- return new EvidenceTypeDescriptor(this);
- }
-
-#if _DEBUG
- /// <summary>
- /// Set the type that this evidence descriptor refers to.
- /// </summary>
- internal void SetEvidenceType(Type evidenceType)
- {
- Debug.Assert(evidenceType != null);
- Debug.Assert(m_evidenceType == null, "Attempt to reset evidence type");
-
- m_evidenceType = evidenceType;
- }
-#endif // _DEBUG
- }
-}
diff --git a/src/mscorlib/src/System/Security/Policy/IDelayEvaluatedEvidence.cs b/src/mscorlib/src/System/Security/Policy/IDelayEvaluatedEvidence.cs
deleted file mode 100644
index 8f8c07c9e4..0000000000
--- a/src/mscorlib/src/System/Security/Policy/IDelayEvaluatedEvidence.cs
+++ /dev/null
@@ -1,34 +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.Security.Policy {
- /// <summary>
- /// Interface for evidence objects that support being "unverified". For instance, StrongName
- /// evidence for a strong name signature which was not yet verified. This interface is used to
- /// keep track of weather or not the evidence object was needed to compute a grant set. If it was,
- /// then we can force verificaiton of the evidence object -- if not we can save time by not doing
- /// any verification on it. (Since we didn't use it for policy resolution, it wouldn't have
- /// mattered if the evidence was not present in the first place).
- /// </summary>
- internal interface IDelayEvaluatedEvidence {
- /// <summary>
- /// Is this evidence object verified yet?
- /// </summary>
- bool IsVerified
- {
- get;
- }
-
- /// <summary>
- /// Was this evidence object used during the course of policy evaluation?
- /// </summary>
- bool WasUsed { get; }
-
- /// <summary>
- /// Mark the object as used
- /// </summary>
- void MarkUsed();
- }
-}
diff --git a/src/mscorlib/src/System/Security/Policy/IIdentityPermissionFactory.cs b/src/mscorlib/src/System/Security/Policy/IIdentityPermissionFactory.cs
deleted file mode 100644
index a46f39602d..0000000000
--- a/src/mscorlib/src/System/Security/Policy/IIdentityPermissionFactory.cs
+++ /dev/null
@@ -1,20 +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.
-
-//
-//
-// All Identities will implement this interface.
-//
-
-namespace System.Security.Policy {
- using System.Runtime.Remoting;
- using System;
- using System.Security.Util;
-[System.Runtime.InteropServices.ComVisible(true)]
- public interface IIdentityPermissionFactory
- {
- IPermission CreateIdentityPermission( Evidence evidence );
- }
-
-}
diff --git a/src/mscorlib/src/System/Security/Policy/IRuntimeEvidenceFactory.cs b/src/mscorlib/src/System/Security/Policy/IRuntimeEvidenceFactory.cs
deleted file mode 100644
index 98467fe367..0000000000
--- a/src/mscorlib/src/System/Security/Policy/IRuntimeEvidenceFactory.cs
+++ /dev/null
@@ -1,36 +0,0 @@
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-// See the LICENSE file in the project root for more information.
-
-//
-
-using System;
-using System.Collections.Generic;
-
-namespace System.Security.Policy
-{
- /// <summary>
- /// IRuntimeEvidenceFactory is implemented by runtime types which the CLR knows how to delay
- /// generate evidence for. It is used by the Evidence class to get evidence on demand when we first
- /// need it.
- /// </summary>
- internal interface IRuntimeEvidenceFactory
- {
- /// <summary>
- /// Object which the evidence generated by this factory is used for
- /// </summary>
- IEvidenceFactory Target { get; }
-
- /// <summary>
- /// Get the collection of evidence objects supplied by the factory itself, rather than by the
- /// runtime.
- /// </summary>
- IEnumerable<EvidenceBase> GetFactorySuppliedEvidence();
-
- /// <summary>
- /// Generate a specific type of evidence for this object, returning null if the specified type of
- /// evidence cannot be generated.
- /// </summary>
- EvidenceBase GenerateEvidence(Type evidenceType);
- }
-}
diff --git a/src/mscorlib/src/System/Security/Policy/PolicyException.cs b/src/mscorlib/src/System/Security/Policy/PolicyException.cs
deleted file mode 100644
index 68e87f780d..0000000000
--- a/src/mscorlib/src/System/Security/Policy/PolicyException.cs
+++ /dev/null
@@ -1,50 +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.
-
-//
-//
-// Use this class to throw a PolicyException
-//
-
-namespace System.Security.Policy {
-
- using System;
- using System.Runtime.Serialization;
- [Serializable]
-[System.Runtime.InteropServices.ComVisible(true)]
- public class PolicyException : SystemException
- {
- public PolicyException()
-
- : base(Environment.GetResourceString( "Policy_Default" )) {
- HResult = __HResults.CORSEC_E_POLICY_EXCEPTION;
- }
-
- public PolicyException(String message)
-
- : base(message) {
- HResult = __HResults.CORSEC_E_POLICY_EXCEPTION;
- }
-
- public PolicyException(String message, Exception exception)
-
- : base(message, exception) {
- HResult = __HResults.CORSEC_E_POLICY_EXCEPTION;
- }
-
- protected PolicyException(SerializationInfo info, StreamingContext context) : base (info, context) {}
-
- internal PolicyException(String message, int hresult) : base (message)
- {
- HResult = hresult;
- }
-
- internal PolicyException(String message, int hresult, Exception exception) : base (message, exception)
- {
- HResult = hresult;
- }
-
- }
-
-}
diff --git a/src/mscorlib/src/System/Security/Policy/PolicyStatement.cs b/src/mscorlib/src/System/Security/Policy/PolicyStatement.cs
deleted file mode 100644
index 9b58ece9f1..0000000000
--- a/src/mscorlib/src/System/Security/Policy/PolicyStatement.cs
+++ /dev/null
@@ -1,246 +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.
-
-//
-// Represents the policy associated with some piece of evidence
-//
-using System.Diagnostics.Contracts;
-namespace System.Security.Policy {
-
- using System;
- using System.Security;
- using System.Security.Util;
- using Math = System.Math;
- using System.Collections;
- using System.Collections.Generic;
- using System.Security.Permissions;
- using System.Text;
- using System.Globalization;
-[Serializable]
- [Flags]
-[System.Runtime.InteropServices.ComVisible(true)]
- public enum PolicyStatementAttribute
- {
- Nothing = 0x0,
- Exclusive = 0x01,
- LevelFinal = 0x02,
- All = 0x03,
- }
-
- [Serializable]
- [System.Runtime.InteropServices.ComVisible(true)]
- sealed public class PolicyStatement : ISecurityPolicyEncodable, ISecurityEncodable
- {
- // The PermissionSet associated with this policy
- internal PermissionSet m_permSet;
-
- // The bitfield of inheritance properties associated with this policy
- internal PolicyStatementAttribute m_attributes;
-
- internal PolicyStatement()
- {
- m_permSet = null;
- m_attributes = PolicyStatementAttribute.Nothing;
- }
-
- public PolicyStatement( PermissionSet permSet )
- : this( permSet, PolicyStatementAttribute.Nothing )
- {
- }
-
- public PolicyStatement( PermissionSet permSet, PolicyStatementAttribute attributes )
- {
- if (permSet == null)
- {
- m_permSet = new PermissionSet( false );
- }
- else
- {
- m_permSet = permSet.Copy();
- }
- if (ValidProperties( attributes ))
- {
- m_attributes = attributes;
- }
- }
-
- private PolicyStatement( PermissionSet permSet, PolicyStatementAttribute attributes, bool copy )
- {
- if (permSet != null)
- {
- if (copy)
- m_permSet = permSet.Copy();
- else
- m_permSet = permSet;
- }
- else
- {
- m_permSet = new PermissionSet( false );
- }
-
- m_attributes = attributes;
- }
-
- public PermissionSet PermissionSet
- {
- get
- {
- lock (this)
- {
- return m_permSet.Copy();
- }
- }
-
- set
- {
- lock (this)
- {
- if (value == null)
- {
- m_permSet = new PermissionSet( false );
- }
- else
- {
- m_permSet = value.Copy();
- }
- }
- }
- }
-
- internal void SetPermissionSetNoCopy( PermissionSet permSet )
- {
- m_permSet = permSet;
- }
-
- internal PermissionSet GetPermissionSetNoCopy()
- {
- lock (this)
- {
- return m_permSet;
- }
- }
-
- public PolicyStatementAttribute Attributes
- {
- get
- {
- return m_attributes;
- }
-
- set
- {
- if (ValidProperties( value ))
- {
- m_attributes = value;
- }
- }
- }
-
- public PolicyStatement Copy()
- {
- // The PolicyStatement .ctor will copy the permission set
- return new PolicyStatement(m_permSet, Attributes, true);
- }
-
- public String AttributeString
- {
- get
- {
- StringBuilder sb = new StringBuilder();
-
- bool first = true;
-
- if (GetFlag((int) PolicyStatementAttribute.Exclusive ))
- {
- sb.Append( "Exclusive" );
- first = false;
- }
- if (GetFlag((int) PolicyStatementAttribute.LevelFinal ))
- {
- if (!first)
- sb.Append( " " );
- sb.Append( "LevelFinal" );
- }
-
- return sb.ToString();
- }
- }
-
- private static bool ValidProperties( PolicyStatementAttribute attributes )
- {
- if ((attributes & ~(PolicyStatementAttribute.All)) == 0)
- {
- return true;
- }
- else
- {
- throw new ArgumentException( Environment.GetResourceString( "Argument_InvalidFlag" ) );
- }
- }
-
- private bool GetFlag( int flag )
- {
- return (flag & (int)m_attributes) != 0;
- }
-
- /// <summary>
- /// Union a child policy statement into this policy statement
- /// </summary>
- internal void InplaceUnion(PolicyStatement childPolicy)
- {
- BCLDebug.Assert(childPolicy != null, "childPolicy != null");
-
- if (((Attributes & childPolicy.Attributes) & PolicyStatementAttribute.Exclusive) == PolicyStatementAttribute.Exclusive)
- {
- throw new PolicyException(Environment.GetResourceString( "Policy_MultipleExclusive" ));
- }
-
- // 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
- // is exclusive then it is the only code group which should have an effect on the resulting
- // grant set and therefore our grant should be ignored.
- if ((childPolicy.Attributes & PolicyStatementAttribute.Exclusive) == PolicyStatementAttribute.Exclusive)
- {
- m_permSet = childPolicy.GetPermissionSetNoCopy();
- Attributes = childPolicy.Attributes;
- }
- else
- {
- m_permSet.InplaceUnion(childPolicy.GetPermissionSetNoCopy());
- Attributes = Attributes | childPolicy.Attributes;
- }
- }
-
- [System.Runtime.InteropServices.ComVisible(false)]
- public override bool Equals( Object obj )
- {
- PolicyStatement other = obj as PolicyStatement;
-
- if (other == null)
- return false;
-
- if (this.m_attributes != other.m_attributes)
- return false;
-
- if (!Object.Equals( this.m_permSet, other.m_permSet ))
- return false;
-
- return true;
- }
-
- [System.Runtime.InteropServices.ComVisible(false)]
- public override int GetHashCode()
- {
- int accumulator = (int)this.m_attributes;
-
- if (m_permSet != null)
- accumulator = accumulator ^ m_permSet.GetHashCode();
-
- return accumulator;
- }
-
- }
-}
-
diff --git a/src/mscorlib/src/System/Security/Policy/Site.cs b/src/mscorlib/src/System/Security/Policy/Site.cs
deleted file mode 100644
index 14a95e1666..0000000000
--- a/src/mscorlib/src/System/Security/Policy/Site.cs
+++ /dev/null
@@ -1,105 +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.
-
-//
-
-//
-//
-// Site is an IIdentity representing internet sites.
-//
-
-using System;
-using System.Diagnostics;
-using System.Diagnostics.Contracts;
-using System.Globalization;
-using System.Security.Permissions;
-using System.Security.Util;
-
-namespace System.Security.Policy
-{
- [Serializable]
- [System.Runtime.InteropServices.ComVisible(true)]
- public sealed class Site : EvidenceBase, IIdentityPermissionFactory
- {
- private SiteString m_name;
-
- public Site(String name)
- {
- if (name == null)
- throw new ArgumentNullException(nameof(name));
- Contract.EndContractBlock();
-
- m_name = new SiteString( name );
- }
-
- private Site(SiteString name)
- {
- Debug.Assert(name != null);
- m_name = name;
- }
-
- public static Site CreateFromUrl( String url )
- {
- return new Site(ParseSiteFromUrl(url));
- }
-
- private static SiteString ParseSiteFromUrl( String name )
- {
- URLString urlString = new URLString( name );
-
- if (String.Compare( urlString.Scheme, "file", StringComparison.OrdinalIgnoreCase) == 0)
- throw new ArgumentException( Environment.GetResourceString( "Argument_InvalidSite" ) );
-
- return new SiteString( new URLString( name ).Host );
- }
-
- public String Name
- {
- get { return m_name.ToString(); }
- }
-
- internal SiteString GetSiteString()
- {
- return m_name;
- }
-
- public IPermission CreateIdentityPermission( Evidence evidence )
- {
- return new SiteIdentityPermission( Name );
- }
-
- public override bool Equals(Object o)
- {
- Site other = o as Site;
- if (other == null)
- {
- return false;
- }
-
- return String.Equals(Name, other.Name, StringComparison.OrdinalIgnoreCase);
- }
-
- public override int GetHashCode()
- {
- return Name.GetHashCode();
- }
-
- public override EvidenceBase Clone()
- {
- return new Site(m_name);
- }
-
- public Object Copy()
- {
- return Clone();
- }
-
- // INormalizeForIsolatedStorage is not implemented for startup perf
- // equivalent to INormalizeForIsolatedStorage.Normalize()
- internal Object Normalize()
- {
- return m_name.ToString().ToUpper(CultureInfo.InvariantCulture);
- }
- }
-}
diff --git a/src/mscorlib/src/System/Security/Policy/StrongName.cs b/src/mscorlib/src/System/Security/Policy/StrongName.cs
deleted file mode 100644
index 999b478ba7..0000000000
--- a/src/mscorlib/src/System/Security/Policy/StrongName.cs
+++ /dev/null
@@ -1,171 +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.
-
-//
-
-//
-//
-// StrongName is an IIdentity representing strong names.
-//
-
-namespace System.Security.Policy {
- using System.IO;
- using System.Reflection;
- using System.Security.Util;
- using System.Security.Permissions;
- using System.Diagnostics.Contracts;
- using CultureInfo = System.Globalization.CultureInfo;
-
- [Serializable]
- [System.Runtime.InteropServices.ComVisible(true)]
- public sealed class StrongName : EvidenceBase, IIdentityPermissionFactory, IDelayEvaluatedEvidence
- {
- private StrongNamePublicKeyBlob m_publicKeyBlob;
- private String m_name;
- private Version m_version;
-
- // Delay evaluated evidence is for policy resolution only, so it doesn't make sense to save that
- // state away and then try to evaluate the strong name later.
- [NonSerialized]
- private RuntimeAssembly m_assembly = null;
-
- [NonSerialized]
- private bool m_wasUsed = false;
-
- internal StrongName() {}
-
- public StrongName( StrongNamePublicKeyBlob blob, String name, Version version ) : this(blob, name, version, null)
- {
- }
-
- internal StrongName(StrongNamePublicKeyBlob blob, String name, Version version, Assembly assembly)
- {
- if (name == null)
- throw new ArgumentNullException(nameof(name));
- if (String.IsNullOrEmpty(name))
- throw new ArgumentException(Environment.GetResourceString("Argument_EmptyStrongName"));
-
- if (blob == null)
- throw new ArgumentNullException(nameof(blob));
-
- if (version == null)
- throw new ArgumentNullException(nameof(version));
- Contract.EndContractBlock();
-
- RuntimeAssembly rtAssembly = assembly as RuntimeAssembly;
- if (assembly != null && rtAssembly == null)
- throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeAssembly"), nameof(assembly));
-
- m_publicKeyBlob = blob;
- m_name = name;
- m_version = version;
- m_assembly = rtAssembly;
- }
-
- public StrongNamePublicKeyBlob PublicKey
- {
- get
- {
- return m_publicKeyBlob;
- }
- }
-
- public String Name
- {
- get
- {
- return m_name;
- }
- }
-
- public Version Version
- {
- get
- {
- return m_version;
- }
- }
-
- bool IDelayEvaluatedEvidence.IsVerified
- {
- get
- {
- return true;
- }
- }
-
- bool IDelayEvaluatedEvidence.WasUsed
- {
- get { return m_wasUsed; }
- }
-
- void IDelayEvaluatedEvidence.MarkUsed()
- {
- m_wasUsed = true;
- }
-
- internal static bool CompareNames( String asmName, String mcName )
- {
- if (mcName.Length > 0 && mcName[mcName.Length-1] == '*' && mcName.Length - 1 <= asmName.Length)
- return String.Compare( mcName, 0, asmName, 0, mcName.Length - 1, StringComparison.OrdinalIgnoreCase) == 0;
- else
- return String.Compare( mcName, asmName, StringComparison.OrdinalIgnoreCase) == 0;
- }
-
- public IPermission CreateIdentityPermission( Evidence evidence )
- {
- return new StrongNameIdentityPermission( m_publicKeyBlob, m_name, m_version );
- }
-
- public override EvidenceBase Clone()
- {
- return new StrongName(m_publicKeyBlob, m_name, m_version);
- }
-
- public Object Copy()
- {
- return Clone();
- }
-
- public override bool Equals( Object o )
- {
- StrongName that = (o as StrongName);
- return (that != null) &&
- Equals( this.m_publicKeyBlob, that.m_publicKeyBlob ) &&
- Equals( this.m_name, that.m_name ) &&
- Equals( this.m_version, that.m_version );
- }
-
- public override int GetHashCode()
- {
- if (m_publicKeyBlob != null)
- {
- return m_publicKeyBlob.GetHashCode();
- }
- else if (m_name != null || m_version != null)
- {
- return (m_name == null ? 0 : m_name.GetHashCode()) + (m_version == null ? 0 : m_version.GetHashCode());
- }
- else
- {
- return typeof( StrongName ).GetHashCode();
- }
- }
-
- // INormalizeForIsolatedStorage is not implemented for startup perf
- // equivalent to INormalizeForIsolatedStorage.Normalize()
- internal Object Normalize()
- {
- MemoryStream ms = new MemoryStream();
- BinaryWriter bw = new BinaryWriter(ms);
-
- bw.Write(m_publicKeyBlob.PublicKey);
- bw.Write(m_version.Major);
- bw.Write(m_name);
-
- ms.Position = 0;
- return ms;
- }
- }
-}
diff --git a/src/mscorlib/src/System/Security/Policy/URL.cs b/src/mscorlib/src/System/Security/Policy/URL.cs
deleted file mode 100644
index 3541124ac6..0000000000
--- a/src/mscorlib/src/System/Security/Policy/URL.cs
+++ /dev/null
@@ -1,98 +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.
-
-//
-
-//
-//
-// Url is an IIdentity representing url internet sites.
-//
-
-namespace System.Security.Policy {
- using System.IO;
- using System.Security.Util;
- using UrlIdentityPermission = System.Security.Permissions.UrlIdentityPermission;
- using System.Runtime.Serialization;
- using System.Diagnostics;
- using System.Diagnostics.Contracts;
-
- [Serializable]
- [System.Runtime.InteropServices.ComVisible(true)]
- public sealed class Url : EvidenceBase, IIdentityPermissionFactory
- {
- private URLString m_url;
-
- internal Url( String name, bool parsed )
- {
- if (name == null)
- throw new ArgumentNullException( nameof(name) );
- Contract.EndContractBlock();
-
- m_url = new URLString( name, parsed );
- }
-
- public Url( String name )
- {
- if (name == null)
- throw new ArgumentNullException( nameof(name) );
- Contract.EndContractBlock();
-
- m_url = new URLString( name );
- }
-
- private Url(Url url)
- {
- Debug.Assert(url != null);
- m_url = url.m_url;
- }
-
- public String Value
- {
- get { return m_url.ToString(); }
- }
-
- internal URLString GetURLString()
- {
- return m_url;
- }
-
- public IPermission CreateIdentityPermission( Evidence evidence )
- {
- return new UrlIdentityPermission( m_url );
- }
-
- public override bool Equals(Object o)
- {
- Url other = o as Url;
- if (other == null)
- {
- return false;
- }
-
- return other.m_url.Equals(m_url);
- }
-
- public override int GetHashCode()
- {
- return this.m_url.GetHashCode();
- }
-
- public override EvidenceBase Clone()
- {
- return new Url(this);
- }
-
- public Object Copy()
- {
- return Clone();
- }
-
- // INormalizeForIsolatedStorage is not implemented for startup perf
- // equivalent to INormalizeForIsolatedStorage.Normalize()
- internal Object Normalize()
- {
- return m_url.NormalizeUrl();
- }
- }
-}
diff --git a/src/mscorlib/src/System/Security/Policy/Zone.cs b/src/mscorlib/src/System/Security/Policy/Zone.cs
deleted file mode 100644
index a9f5d84aeb..0000000000
--- a/src/mscorlib/src/System/Security/Policy/Zone.cs
+++ /dev/null
@@ -1,93 +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.
-
-//
-
-//
-//
-// Zone is an IIdentity representing Internet/Intranet/MyComputer etc.
-//
-
-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
- {
- private SecurityZone m_zone;
-
- private static readonly String[] s_names =
- {"MyComputer", "Intranet", "Trusted", "Internet", "Untrusted", "NoZone"};
-
- public Zone(SecurityZone zone)
- {
- if (zone < SecurityZone.NoZone || zone > SecurityZone.Untrusted)
- throw new ArgumentException( Environment.GetResourceString( "Argument_IllegalZone" ) );
- Contract.EndContractBlock();
-
- m_zone = zone;
- }
-
- private Zone(Zone zone)
- {
- Debug.Assert(zone != null);
- m_zone = zone.m_zone;
- }
-
- public IPermission CreateIdentityPermission( Evidence evidence )
- {
- return new ZoneIdentityPermission( SecurityZone );
- }
-
- public SecurityZone SecurityZone
- {
- get
- {
- return m_zone;
- }
- }
-
- public override bool Equals(Object o)
- {
- Zone other = o as Zone;
- if (other == null)
- {
- return false;
- }
-
- return SecurityZone == other.SecurityZone;
- }
-
- public override int GetHashCode()
- {
- return (int)SecurityZone;
- }
-
- public override EvidenceBase Clone()
- {
- return new Zone(this);
- }
-
- public Object Copy()
- {
- return Clone();
- }
-
- // INormalizeForIsolatedStorage is not implemented for startup perf
- // equivalent to INormalizeForIsolatedStorage.Normalize()
- internal Object Normalize()
- {
- return s_names[(int)SecurityZone];
- }
- }
-}
diff --git a/src/mscorlib/src/System/Security/Principal/IIdentity.cs b/src/mscorlib/src/System/Security/Principal/IIdentity.cs
deleted file mode 100644
index 2bda6c6e3d..0000000000
--- a/src/mscorlib/src/System/Security/Principal/IIdentity.cs
+++ /dev/null
@@ -1,29 +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.
-
-//
-
-//
-//
-// All identities will implement this interface
-//
-
-namespace System.Security.Principal
-{
- using System.Runtime.Remoting;
- using System;
- using System.Security.Util;
-
-[System.Runtime.InteropServices.ComVisible(true)]
- public interface IIdentity {
- // Access to the name string
- string Name { get; }
-
- // Access to Authentication 'type' info
- string AuthenticationType { get; }
-
- // Determine if this represents the unauthenticated identity
- bool IsAuthenticated { get; }
- }
-}
diff --git a/src/mscorlib/src/System/Security/Principal/IPrincipal.cs b/src/mscorlib/src/System/Security/Principal/IPrincipal.cs
deleted file mode 100644
index 449cfb50b2..0000000000
--- a/src/mscorlib/src/System/Security/Principal/IPrincipal.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.
-
-//
-
-//
-//
-// All roles will implement this interface
-//
-
-namespace System.Security.Principal
-{
- using System.Runtime.Remoting;
- using System;
- using System.Security.Util;
-
-[System.Runtime.InteropServices.ComVisible(true)]
- public interface IPrincipal {
- // Retrieve the identity object
- IIdentity Identity { get; }
-
- // Perform a check for a specific role
- bool IsInRole (string role);
- }
-}
diff --git a/src/mscorlib/src/System/Security/Principal/TokenImpersonationLevel.cs b/src/mscorlib/src/System/Security/Principal/TokenImpersonationLevel.cs
deleted file mode 100644
index 9eec46f774..0000000000
--- a/src/mscorlib/src/System/Security/Principal/TokenImpersonationLevel.cs
+++ /dev/null
@@ -1,15 +0,0 @@
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-// See the LICENSE file in the project root for more information.
-
-namespace System.Security.Principal
-{
- public enum TokenImpersonationLevel
- {
- None = 0,
- Anonymous = 1,
- Identification = 2,
- Impersonation = 3,
- Delegation = 4
- }
-}
diff --git a/src/mscorlib/src/System/Security/SafeSecurityHandles.cs b/src/mscorlib/src/System/Security/SafeSecurityHandles.cs
deleted file mode 100644
index 9a84164460..0000000000
--- a/src/mscorlib/src/System/Security/SafeSecurityHandles.cs
+++ /dev/null
@@ -1,148 +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 Microsoft.Win32.SafeHandles {
- using System;
- using System.Runtime.CompilerServices;
- using System.Runtime.InteropServices;
- using System.Runtime.ConstrainedExecution;
- using System.Runtime.Versioning;
- using System.Security;
-
- // Introduce this handle to replace internal SafeTokenHandle,
- // which is mainly used to hold Windows thread or process access token
- public sealed class SafeAccessTokenHandle : SafeHandle
- {
- private SafeAccessTokenHandle()
- : base(IntPtr.Zero, true)
- { }
-
- // 0 is an Invalid Handle
- public SafeAccessTokenHandle(IntPtr handle)
- : base(IntPtr.Zero, true)
- {
- SetHandle(handle);
- }
-
- public static SafeAccessTokenHandle InvalidHandle
- {
- get { return new SafeAccessTokenHandle(IntPtr.Zero); }
- }
-
- public override bool IsInvalid
- {
- get { return handle == IntPtr.Zero || handle == new IntPtr(-1); }
- }
-
- protected override bool ReleaseHandle()
- {
- return Win32Native.CloseHandle(handle);
- }
- }
-
- internal sealed class SafeLsaLogonProcessHandle : SafeHandleZeroOrMinusOneIsInvalid {
- private SafeLsaLogonProcessHandle() : base (true) {}
-
- // 0 is an Invalid Handle
- internal SafeLsaLogonProcessHandle(IntPtr handle) : base (true) {
- SetHandle(handle);
- }
-
- internal static SafeLsaLogonProcessHandle InvalidHandle {
- get { return new SafeLsaLogonProcessHandle(IntPtr.Zero); }
- }
-
- override protected bool ReleaseHandle()
- {
- // LsaDeregisterLogonProcess returns an NTSTATUS
- return Win32Native.LsaDeregisterLogonProcess(handle) >= 0;
- }
- }
-
- internal sealed class SafeLsaMemoryHandle : SafeBuffer {
- private SafeLsaMemoryHandle() : base(true) {}
-
- // 0 is an Invalid Handle
- internal SafeLsaMemoryHandle(IntPtr handle) : base (true) {
- SetHandle(handle);
- }
-
- internal static SafeLsaMemoryHandle InvalidHandle {
- get { return new SafeLsaMemoryHandle( IntPtr.Zero ); }
- }
-
- override protected bool ReleaseHandle()
- {
- return Win32Native.LsaFreeMemory(handle) == 0;
- }
- }
-
- internal sealed class SafeLsaPolicyHandle : SafeHandleZeroOrMinusOneIsInvalid {
- private SafeLsaPolicyHandle() : base(true) {}
-
- // 0 is an Invalid Handle
- internal SafeLsaPolicyHandle(IntPtr handle) : base (true) {
- SetHandle(handle);
- }
-
- internal static SafeLsaPolicyHandle InvalidHandle {
- get { return new SafeLsaPolicyHandle( IntPtr.Zero ); }
- }
-
- override protected bool ReleaseHandle()
- {
- return Win32Native.LsaClose(handle) == 0;
- }
- }
-
- internal sealed class SafeLsaReturnBufferHandle : SafeBuffer {
- private SafeLsaReturnBufferHandle() : base (true) {}
-
- // 0 is an Invalid Handle
- internal SafeLsaReturnBufferHandle(IntPtr handle) : base (true) {
- SetHandle(handle);
- }
-
- internal static SafeLsaReturnBufferHandle InvalidHandle {
- get { return new SafeLsaReturnBufferHandle(IntPtr.Zero); }
- }
-
- override protected bool ReleaseHandle()
- {
- // LsaFreeReturnBuffer returns an NTSTATUS
- return Win32Native.LsaFreeReturnBuffer(handle) >= 0;
- }
- }
-
- internal sealed class SafeProcessHandle : SafeHandleZeroOrMinusOneIsInvalid {
- private SafeProcessHandle() : base (true) {}
-
- // 0 is an Invalid Handle
- internal SafeProcessHandle(IntPtr handle) : base (true) {
- SetHandle(handle);
- }
-
- internal static SafeProcessHandle InvalidHandle {
- get { return new SafeProcessHandle(IntPtr.Zero); }
- }
-
- override protected bool ReleaseHandle()
- {
- return Win32Native.CloseHandle(handle);
- }
- }
-
- internal sealed class SafeThreadHandle : SafeHandleZeroOrMinusOneIsInvalid {
- private SafeThreadHandle() : base (true) {}
-
- // 0 is an Invalid Handle
- internal SafeThreadHandle(IntPtr handle) : base (true) {
- SetHandle(handle);
- }
-
- 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
deleted file mode 100644
index 674c04196f..0000000000
--- a/src/mscorlib/src/System/Security/SecurityContext.cs
+++ /dev/null
@@ -1,486 +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: Capture security context for a thread
-**
-**
-===========================================================*/
-namespace System.Security
-{
- using Microsoft.Win32;
- using Microsoft.Win32.SafeHandles;
- using System.Threading;
- using System.Runtime.Remoting;
- using System.Collections;
- using System.Runtime.Serialization;
- using System.Security.Permissions;
- using System.Runtime.InteropServices;
- using System.Runtime.CompilerServices;
-#if FEATURE_CORRUPTING_EXCEPTIONS
- using System.Runtime.ExceptionServices;
-#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
- public enum SecurityContextSource
- {
- CurrentAppDomain = 0,
- CurrentAssembly
- }
-
- internal enum SecurityContextDisableFlow
- {
- Nothing = 0,
- WI = 0x1,
- All = 0x3FFF
- }
-
-#if FEATURE_COMPRESSEDSTACK
- internal struct SecurityContextSwitcher: IDisposable
- {
- internal SecurityContext.Reader prevSC; // prev SC that we restore on an Undo
- 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;
-
- public void Dispose()
- {
- Undo();
- }
-
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
-#if FEATURE_CORRUPTING_EXCEPTIONS
- [HandleProcessCorruptedStateExceptions]
-#endif // FEATURE_CORRUPTING_EXCEPTIONS
- internal bool UndoNoThrow()
- {
- try
- {
- Undo();
- }
- catch
- {
- return false;
- }
- return true;
- }
-
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
-#if FEATURE_CORRUPTING_EXCEPTIONS
- [HandleProcessCorruptedStateExceptions]
-#endif // FEATURE_CORRUPTING_EXCEPTIONS
- public void Undo()
- {
- if (currSC == null)
- {
- return; // mutiple Undo()s called on this switcher object
- }
-
- if (currEC != null)
- {
- 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();
- }
- else
- {
- // caller must have already restored the ExecutionContext
- Debug.Assert(Thread.CurrentThread.GetExecutionContextReader().SecurityContext.IsSame(prevSC));
- }
-
- currSC = null; // this will prevent the switcher object being used again
-
- bool bNoException = true;
-
- bNoException &= cssw.UndoNoThrow();
-
-
- if (!bNoException)
- {
- // Failfast since we can't continue safely...
- System.Environment.FailFast(Environment.GetResourceString("ExecutionContext_UndoFailed"));
- }
-
- }
- }
-
- public sealed class SecurityContext : IDisposable
- {
- /*=========================================================================
- ** Data accessed from managed code that needs to be defined in
- ** SecurityContextObject to maintain alignment between the two classes.
- ** DON'T CHANGE THESE UNLESS YOU MODIFY SecurityContextObject in vm\object.h
- =========================================================================*/
-
- private ExecutionContext _executionContext;
- private volatile CompressedStack _compressedStack;
- static private volatile SecurityContext _fullTrustSC;
-
- internal volatile bool isNewCapture = false;
- internal volatile SecurityContextDisableFlow _disableFlow = SecurityContextDisableFlow.Nothing;
-
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
- internal SecurityContext()
- {
- }
-
- internal struct Reader
- {
- SecurityContext m_sc;
-
- public Reader(SecurityContext sc) { m_sc = sc; }
-
- public SecurityContext DangerousGetRawSecurityContext() { return m_sc; }
-
- public bool IsNull { get { return m_sc == null; } }
- public bool IsSame(SecurityContext sc) { return m_sc == sc; }
- public bool IsSame(SecurityContext.Reader sc) { return m_sc == sc.m_sc; }
-
- [MethodImpl(MethodImplOptions.AggressiveInlining)]
- public bool IsFlowSuppressed(SecurityContextDisableFlow flags)
- {
- return (m_sc == null) ? false : ((m_sc._disableFlow & flags) == flags);
- }
-
- public CompressedStack CompressedStack { get { return IsNull ? null : m_sc.CompressedStack; } }
-
- public WindowsIdentity WindowsIdentity
- {
- [MethodImpl(MethodImplOptions.AggressiveInlining)]
- get { return IsNull ? null : m_sc.WindowsIdentity; }
- }
- }
-
-
- static internal SecurityContext FullTrustSecurityContext
- {
- get
- {
- if (_fullTrustSC == null)
- _fullTrustSC = CreateFullTrustSecurityContext();
- return _fullTrustSC;
- }
- }
-
- // link the security context to an ExecutionContext
- internal ExecutionContext ExecutionContext
- {
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
- set
- {
- _executionContext = value;
- }
- }
-
- internal CompressedStack CompressedStack
- {
- get
- {
- return _compressedStack;
- }
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
- set
- {
- _compressedStack = value;
- }
- }
-
- public void Dispose()
- {
- }
-
- public static AsyncFlowControl SuppressFlow()
- {
- return SuppressFlow(SecurityContextDisableFlow.All);
- }
-
- public static AsyncFlowControl SuppressFlowWindowsIdentity()
- {
- return SuppressFlow(SecurityContextDisableFlow.WI);
- }
-
- internal static AsyncFlowControl SuppressFlow(SecurityContextDisableFlow flags)
- {
- if (IsFlowSuppressed(flags))
- {
- throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_CannotSupressFlowMultipleTimes"));
- }
-
- ExecutionContext ec = Thread.CurrentThread.GetMutableExecutionContext();
- if (ec.SecurityContext == null)
- ec.SecurityContext = new SecurityContext();
- AsyncFlowControl afc = new AsyncFlowControl();
- afc.Setup(flags);
- return afc;
- }
-
- public static void RestoreFlow()
- {
- SecurityContext sc = Thread.CurrentThread.GetMutableExecutionContext().SecurityContext;
- if (sc == null || sc._disableFlow == SecurityContextDisableFlow.Nothing)
- {
- throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_CannotRestoreUnsupressedFlow"));
- }
- sc._disableFlow = SecurityContextDisableFlow.Nothing;
- }
-
- public static bool IsFlowSuppressed()
- {
- return SecurityContext.IsFlowSuppressed(SecurityContextDisableFlow.All);
- }
-
- internal static bool IsFlowSuppressed(SecurityContextDisableFlow flags)
- {
- return Thread.CurrentThread.GetExecutionContextReader().SecurityContext.IsFlowSuppressed(flags);
- }
-
- // This method is special from a security perspective - the VM will not allow a stack walk to
- // 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.
- [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)
- {
- if (securityContext == null )
- {
- throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_NullContext"));
- }
- Contract.EndContractBlock();
-
- StackCrawlMark stackMark = StackCrawlMark.LookForMe;
-
- if (!securityContext.isNewCapture)
- {
- throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_NotNewCaptureContext"));
- }
-
- securityContext.isNewCapture = false;
-
- ExecutionContext.Reader ec = Thread.CurrentThread.GetExecutionContextReader();
-
- // Optimization: do the callback directly if both the current and target contexts are equal to the
- // default full-trust security context
- if ( SecurityContext.CurrentlyInDefaultFTSecurityContext(ec)
- && securityContext.IsDefaultFTSecurityContext())
- {
- callback(state);
-
- if (GetCurrentWI(Thread.CurrentThread.GetExecutionContextReader()) != null)
- {
- // If we enter here it means the callback did an impersonation
- // that we need to revert.
- // We don't need to revert any other security state since it is stack-based
- // and automatically goes away when the callback returns.
- WindowsIdentity.SafeRevertToSelf(ref stackMark);
- // Ensure we have reverted to the state we entered in.
- Debug.Assert(GetCurrentWI(Thread.CurrentThread.GetExecutionContextReader()) == null);
- }
- }
- else
- {
- RunInternal(securityContext, callback, state);
- }
-
- }
- internal static void RunInternal(SecurityContext securityContext, ContextCallback callBack, Object state)
- {
- if (cleanupCode == null)
- {
- tryCode = new RuntimeHelpers.TryCode(runTryCode);
- cleanupCode = new RuntimeHelpers.CleanupCode(runFinallyCode);
- }
- SecurityContextRunData runData = new SecurityContextRunData(securityContext, callBack, state);
- RuntimeHelpers.ExecuteCodeWithGuaranteedCleanup(tryCode, cleanupCode, runData);
-
- }
-
- internal class SecurityContextRunData
- {
- internal SecurityContext sc;
- internal ContextCallback callBack;
- internal Object state;
- internal SecurityContextSwitcher scsw;
- internal SecurityContextRunData(SecurityContext securityContext, ContextCallback cb, Object state)
- {
- this.sc = securityContext;
- this.callBack = cb;
- this.state = state;
- this.scsw = new SecurityContextSwitcher();
- }
- }
-
- static internal void runTryCode(Object userData)
- {
- SecurityContextRunData rData = (SecurityContextRunData) userData;
- rData.scsw = SetSecurityContext(rData.sc, Thread.CurrentThread.GetExecutionContextReader().SecurityContext, modifyCurrentExecutionContext: true);
- rData.callBack(rData.state);
-
- }
-
- [PrePrepareMethod]
- static internal void runFinallyCode(Object userData, bool exceptionThrown)
- {
- SecurityContextRunData rData = (SecurityContextRunData) userData;
- rData.scsw.Undo();
- }
-
- static volatile internal RuntimeHelpers.TryCode tryCode;
- static volatile internal RuntimeHelpers.CleanupCode cleanupCode;
-
-
-
- // Internal API that gets called from public SetSecurityContext and from SetExecutionContext
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
- [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)
- {
- StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
- return SetSecurityContext(sc, prevSecurityContext, modifyCurrentExecutionContext, ref stackMark);
- }
-
-#if FEATURE_CORRUPTING_EXCEPTIONS
- [HandleProcessCorruptedStateExceptions]
-#endif // FEATURE_CORRUPTING_EXCEPTIONS
- internal static SecurityContextSwitcher SetSecurityContext(SecurityContext sc, SecurityContext.Reader prevSecurityContext, bool modifyCurrentExecutionContext, ref StackCrawlMark stackMark)
- {
- // Save the flow state at capture and reset it in the SC.
- SecurityContextDisableFlow _capturedFlowState = sc._disableFlow;
- sc._disableFlow = SecurityContextDisableFlow.Nothing;
-
- //Set up the switcher object
- SecurityContextSwitcher scsw = new SecurityContextSwitcher();
- scsw.currSC = sc;
- scsw.prevSC = prevSecurityContext;
-
- if (modifyCurrentExecutionContext)
- {
- // save the current Execution Context
- ExecutionContext currEC = Thread.CurrentThread.GetMutableExecutionContext();
- scsw.currEC = currEC;
- currEC.SecurityContext = sc;
- }
-
- if (sc != null)
- {
- RuntimeHelpers.PrepareConstrainedRegions();
- try
- {
- scsw.cssw = CompressedStack.SetCompressedStack(sc.CompressedStack, prevSecurityContext.CompressedStack);
- }
- catch
- {
- scsw.UndoNoThrow();
- throw;
- }
- }
- return scsw;
- }
-
- /// <internalonly/>
- public SecurityContext CreateCopy()
- {
- if (!isNewCapture)
- {
- throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_NotNewCaptureContext"));
- }
-
- SecurityContext sc = new SecurityContext();
- sc.isNewCapture = true;
- sc._disableFlow = _disableFlow;
-
- if (_compressedStack != null)
- sc._compressedStack = _compressedStack.CreateCopy();
-
- return sc;
- }
-
- /// <internalonly/>
- internal SecurityContext CreateMutableCopy()
- {
- Debug.Assert(!this.isNewCapture);
-
- SecurityContext sc = new SecurityContext();
- sc._disableFlow = this._disableFlow;
-
- if (this._compressedStack != null)
- sc._compressedStack = this._compressedStack.CreateCopy();
-
- return sc;
- }
-
- [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
- public static SecurityContext Capture( )
- {
- // check to see if Flow is suppressed
- if (IsFlowSuppressed())
- return null;
-
- StackCrawlMark stackMark= StackCrawlMark.LookForMyCaller;
- SecurityContext sc = SecurityContext.Capture(Thread.CurrentThread.GetExecutionContextReader(), ref stackMark);
- if (sc == null)
- sc = CreateFullTrustSecurityContext();
- return sc;
- }
-
- // create a clone from a non-existing SecurityContext
- [MethodImpl(MethodImplOptions.AggressiveInlining)]
- static internal SecurityContext Capture(ExecutionContext.Reader currThreadEC, ref StackCrawlMark stackMark)
- {
- // check to see if Flow is suppressed
- if (currThreadEC.SecurityContext.IsFlowSuppressed(SecurityContextDisableFlow.All))
- return null;
-
- // If we're in FT right now, return null
- if (CurrentlyInDefaultFTSecurityContext(currThreadEC))
- return null;
-
- return CaptureCore(currThreadEC, ref stackMark);
- }
-
- static private SecurityContext CaptureCore(ExecutionContext.Reader currThreadEC, ref StackCrawlMark stackMark)
- {
- SecurityContext sc = new SecurityContext();
- sc.isNewCapture = true;
-
- // Force create CompressedStack
- sc.CompressedStack = CompressedStack.GetCompressedStack(ref stackMark);
- return sc;
- }
-
- static internal SecurityContext CreateFullTrustSecurityContext()
- {
- SecurityContext sc = new SecurityContext();
- sc.isNewCapture = true;
-
- // Force create CompressedStack
- sc.CompressedStack = new CompressedStack(null);
- return sc;
- }
-
- internal bool IsDefaultFTSecurityContext()
- {
- return (CompressedStack == null || CompressedStack.CompressedStackHandle == null);
- }
- static internal bool CurrentlyInDefaultFTSecurityContext(ExecutionContext threadEC)
- {
- return (IsDefaultThreadSecurityInfo());
- }
-
- [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
deleted file mode 100644
index f57665b278..0000000000
--- a/src/mscorlib/src/System/Security/SecurityElement.cs
+++ /dev/null
@@ -1,875 +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.Security
-{
- using System;
- using System.Collections;
- using System.Collections.Generic;
- using System.Security.Util;
- using System.Text;
- using System.Globalization;
- using System.IO;
- using System.Security.Permissions;
- using System.Diagnostics;
- using System.Diagnostics.Contracts;
-
- internal enum SecurityElementType
- {
- Regular = 0,
- Format = 1,
- Comment = 2
- }
-
-
- internal interface ISecurityElementFactory
- {
- SecurityElement CreateSecurityElement();
-
- Object Copy();
-
- String GetTag();
-
- String Attribute( String attributeName );
- }
-
- [Serializable]
-[System.Runtime.InteropServices.ComVisible(true)]
- sealed public class SecurityElement : ISecurityElementFactory
- {
- internal String m_strTag;
- internal String m_strText;
- private ArrayList m_lChildren;
- internal ArrayList m_lAttributes;
- internal SecurityElementType m_type = SecurityElementType.Regular;
-
- private static readonly char[] s_tagIllegalCharacters = new char[] { ' ', '<', '>' };
- private static readonly char[] s_textIllegalCharacters = new char[] { '<', '>' };
- private static readonly char[] s_valueIllegalCharacters = new char[] { '<', '>', '\"' };
- private const String s_strIndent = " ";
-
- private const int c_AttributesTypical = 4 * 2; // 4 attributes, times 2 strings per attribute
- private const int c_ChildrenTypical = 1;
-
- private static readonly String[] s_escapeStringPairs = new String[]
- {
- // these must be all once character escape sequences or a new escaping algorithm is needed
- "<", "&lt;",
- ">", "&gt;",
- "\"", "&quot;",
- "\'", "&apos;",
- "&", "&amp;"
- };
-
- private static readonly char[] s_escapeChars = new char[] { '<', '>', '\"', '\'', '&' };
-
- //-------------------------- Constructors ---------------------------
-
- internal SecurityElement()
- {
- }
-
-////// ISecurityElementFactory implementation
-
- SecurityElement ISecurityElementFactory.CreateSecurityElement()
- {
- return this;
- }
-
- String ISecurityElementFactory.GetTag()
- {
- return ((SecurityElement)this).Tag;
- }
-
- Object ISecurityElementFactory.Copy()
- {
- return ((SecurityElement)this).Copy();
- }
-
- String ISecurityElementFactory.Attribute( String attributeName )
- {
- return ((SecurityElement)this).Attribute( attributeName );
- }
-
- public SecurityElement( String tag )
- {
- if (tag == null)
- throw new ArgumentNullException( nameof(tag) );
-
- if (!IsValidTag( tag ))
- throw new ArgumentException( String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "Argument_InvalidElementTag" ), tag ) );
- Contract.EndContractBlock();
-
- m_strTag = tag;
- m_strText = null;
- }
-
- public SecurityElement( String tag, String text )
- {
- if (tag == null)
- throw new ArgumentNullException( nameof(tag) );
-
- if (!IsValidTag( tag ))
- throw new ArgumentException( String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "Argument_InvalidElementTag" ), tag ) );
-
- if (text != null && !IsValidText( text ))
- throw new ArgumentException( String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "Argument_InvalidElementText" ), text ) );
- Contract.EndContractBlock();
-
- m_strTag = tag;
- m_strText = text;
- }
-
- //-------------------------- Properties -----------------------------
-
- public String Tag
- {
- [Pure]
- get
- {
- return m_strTag;
- }
-
- set
- {
- if (value == null)
- throw new ArgumentNullException( nameof(Tag) );
-
- if (!IsValidTag( value ))
- throw new ArgumentException( String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "Argument_InvalidElementTag" ), value ) );
- Contract.EndContractBlock();
-
- m_strTag = value;
- }
- }
-
- public Hashtable Attributes
- {
- get
- {
- if (m_lAttributes == null || m_lAttributes.Count == 0)
- {
- return null;
- }
- else
- {
- Hashtable hashtable = new Hashtable( m_lAttributes.Count/2 );
-
- int iMax = m_lAttributes.Count;
- 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)
- {
- hashtable.Add( m_lAttributes[i], m_lAttributes[i+1]);
- }
-
- return hashtable;
- }
- }
-
- set
- {
- if (value == null || value.Count == 0)
- {
- m_lAttributes = null;
- }
- else
- {
- ArrayList list = new ArrayList(value.Count);
-
- System.Collections.IDictionaryEnumerator enumerator = (System.Collections.IDictionaryEnumerator)value.GetEnumerator();
-
- while (enumerator.MoveNext())
- {
- String attrName = (String)enumerator.Key;
- String attrValue = (String)enumerator.Value;
-
- if (!IsValidAttributeName( attrName ))
- throw new ArgumentException( String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "Argument_InvalidElementName" ), (String)enumerator.Current ) );
-
- if (!IsValidAttributeValue( attrValue ))
- throw new ArgumentException( String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "Argument_InvalidElementValue" ), (String)enumerator.Value ) );
-
- list.Add(attrName);
- list.Add(attrValue);
- }
-
- m_lAttributes = list;
- }
- }
- }
-
- public String Text
- {
- get
- {
- return Unescape( m_strText );
- }
-
- set
- {
- if (value == null)
- {
- m_strText = null;
- }
- else
- {
- if (!IsValidText( value ))
- throw new ArgumentException( String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "Argument_InvalidElementTag" ), value ) );
-
- m_strText = value;
- }
- }
- }
-
- public ArrayList Children
- {
- get
- {
- ConvertSecurityElementFactories();
- return m_lChildren;
- }
-
- set
- {
- if (value != null)
- {
- IEnumerator enumerator = value.GetEnumerator();
-
- while (enumerator.MoveNext())
- {
- if (enumerator.Current == null)
- throw new ArgumentException( Environment.GetResourceString( "ArgumentNull_Child" ) );
- }
- }
-
- m_lChildren = value;
- }
- }
-
- internal void ConvertSecurityElementFactories()
- {
- if (m_lChildren == null)
- return;
-
- for (int i = 0; i < m_lChildren.Count; ++i)
- {
- ISecurityElementFactory iseFactory = m_lChildren[i] as ISecurityElementFactory;
- if (iseFactory != null && !(m_lChildren[i] is SecurityElement))
- m_lChildren[i] = iseFactory.CreateSecurityElement();
- }
- }
-
- internal ArrayList InternalChildren
- {
- get
- {
- // Beware! This array list can contain SecurityElements and other ISecurityElementFactories.
- // If you want to get a consistent SecurityElement view, call get_Children.
- return m_lChildren;
- }
- }
-
- //-------------------------- Public Methods -----------------------------
-
- internal void AddAttributeSafe( String name, String value )
- {
- if (m_lAttributes == null)
- {
- m_lAttributes = new ArrayList( c_AttributesTypical );
- }
- else
- {
- int iMax = m_lAttributes.Count;
- 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)
- {
- String strAttrName = (String)m_lAttributes[i];
-
- if (String.Equals(strAttrName, name))
- throw new ArgumentException( Environment.GetResourceString( "Argument_AttributeNamesMustBeUnique" ) );
- }
- }
-
- m_lAttributes.Add(name);
- m_lAttributes.Add(value);
- }
-
- public void AddAttribute( String name, String value )
- {
- if (name == null)
- throw new ArgumentNullException( nameof(name) );
-
- if (value == null)
- throw new ArgumentNullException( nameof(value) );
-
- if (!IsValidAttributeName( name ))
- throw new ArgumentException( String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "Argument_InvalidElementName" ), name ) );
-
- if (!IsValidAttributeValue( value ))
- throw new ArgumentException( String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "Argument_InvalidElementValue" ), value ) );
- Contract.EndContractBlock();
-
- AddAttributeSafe( name, value );
- }
-
- public void AddChild( SecurityElement child )
- {
- if (child == null)
- throw new ArgumentNullException( nameof(child) );
- Contract.EndContractBlock();
-
- if (m_lChildren == null)
- m_lChildren = new ArrayList( c_ChildrenTypical );
-
- m_lChildren.Add( child );
- }
-
- internal void AddChild( ISecurityElementFactory child )
- {
- if (child == null)
- throw new ArgumentNullException( nameof(child) );
- Contract.EndContractBlock();
-
- if (m_lChildren == null)
- m_lChildren = new ArrayList( c_ChildrenTypical );
-
- m_lChildren.Add( child );
- }
-
- internal void AddChildNoDuplicates( ISecurityElementFactory child )
- {
- if (child == null)
- throw new ArgumentNullException( nameof(child) );
- Contract.EndContractBlock();
-
- if (m_lChildren == null)
- {
- m_lChildren = new ArrayList( c_ChildrenTypical );
- m_lChildren.Add( child );
- }
- else
- {
- for (int i = 0; i < m_lChildren.Count; ++i)
- {
- if (m_lChildren[i] == child)
- return;
- }
- m_lChildren.Add( child );
- }
- }
-
- public bool Equal( SecurityElement other )
- {
- if (other == null)
- return false;
-
- // Check if the tags are the same
- if (!String.Equals(m_strTag, other.m_strTag))
- return false;
-
- // Check if the text is the same
- if (!String.Equals(m_strText, other.m_strText))
- return false;
-
- // Check if the attributes are the same and appear in the same
- // order.
-
- // Maybe we can get away by only checking the number of attributes
- if (m_lAttributes == null || other.m_lAttributes == null)
- {
- if (m_lAttributes != other.m_lAttributes)
- return false;
- }
- else
- {
- int iMax = m_lAttributes.Count;
- 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;
-
- for (int i = 0; i < iMax; i++)
- {
- String lhs = (String)m_lAttributes[i];
- String rhs = (String)other.m_lAttributes[i];
-
- if (!String.Equals(lhs, rhs))
- return false;
- }
- }
-
- // Finally we must check the child and make sure they are
- // equal and in the same order
-
- // Maybe we can get away by only checking the number of children
- if (m_lChildren == null || other.m_lChildren == null)
- {
- if (m_lChildren != other.m_lChildren)
- return false;
- }
- else
- {
- if (m_lChildren.Count != other.m_lChildren.Count)
- return false;
-
- this.ConvertSecurityElementFactories();
- other.ConvertSecurityElementFactories();
-
- // Okay, we'll need to go through each one of them
- IEnumerator lhs = m_lChildren.GetEnumerator();
- IEnumerator rhs = other.m_lChildren.GetEnumerator();
-
- SecurityElement e1, e2;
- while (lhs.MoveNext())
- {
- rhs.MoveNext();
- e1 = (SecurityElement)lhs.Current;
- e2 = (SecurityElement)rhs.Current;
- if (e1 == null || !e1.Equal(e2))
- return false;
- }
- }
- return true;
- }
-
- [System.Runtime.InteropServices.ComVisible(false)]
- public SecurityElement Copy()
- {
- SecurityElement element = new SecurityElement( this.m_strTag, this.m_strText );
- element.m_lChildren = this.m_lChildren == null ? null : new ArrayList( this.m_lChildren );
- element.m_lAttributes = this.m_lAttributes == null ? null : new ArrayList(this.m_lAttributes);
-
- return element;
- }
-
- [Pure]
- public static bool IsValidTag( String tag )
- {
- if (tag == null)
- return false;
-
- return tag.IndexOfAny( s_tagIllegalCharacters ) == -1;
- }
-
- [Pure]
- public static bool IsValidText( String text )
- {
- if (text == null)
- return false;
-
- return text.IndexOfAny( s_textIllegalCharacters ) == -1;
- }
-
- [Pure]
- public static bool IsValidAttributeName( String name )
- {
- return IsValidTag( name );
- }
-
- [Pure]
- public static bool IsValidAttributeValue( String value )
- {
- if (value == null)
- return false;
-
- return value.IndexOfAny( s_valueIllegalCharacters ) == -1;
- }
-
- private static String GetEscapeSequence( char c )
- {
- int iMax = s_escapeStringPairs.Length;
- 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)
- {
- String strEscSeq = s_escapeStringPairs[i];
- String strEscValue = s_escapeStringPairs[i+1];
-
- if (strEscSeq[0] == c)
- return strEscValue;
- }
-
- Debug.Assert( false, "Unable to find escape sequence for this character" );
- return c.ToString();
- }
-
- public static String Escape( String str )
- {
- if (str == null)
- return null;
-
- StringBuilder sb = null;
-
- int strLen = str.Length;
- int index; // Pointer into the string that indicates the location of the current '&' character
- int newIndex = 0; // Pointer into the string that indicates the start index of the "remaining" string (that still needs to be processed).
-
-
- do
- {
- index = str.IndexOfAny( s_escapeChars, newIndex );
-
- if (index == -1)
- {
- if (sb == null)
- return str;
- else
- {
- sb.Append( str, newIndex, strLen - newIndex );
- return sb.ToString();
- }
- }
- else
- {
- if (sb == null)
- sb = new StringBuilder();
-
- sb.Append( str, newIndex, index - newIndex );
- sb.Append( GetEscapeSequence( str[index] ) );
-
- newIndex = ( index + 1 );
- }
- }
- while (true);
-
- // no normal exit is possible
- }
-
- private static String GetUnescapeSequence( String str, int index, out int newIndex )
- {
- int maxCompareLength = str.Length - index;
-
- int iMax = s_escapeStringPairs.Length;
- 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)
- {
- String strEscSeq = s_escapeStringPairs[i];
- String strEscValue = s_escapeStringPairs[i+1];
-
- int length = strEscValue.Length;
-
- if (length <= maxCompareLength && String.Compare( strEscValue, 0, str, index, length, StringComparison.Ordinal) == 0)
- {
- newIndex = index + strEscValue.Length;
- return strEscSeq;
- }
- }
-
- newIndex = index + 1;
- return str[index].ToString();
- }
-
-
- private static String Unescape( String str )
- {
- if (str == null)
- return null;
-
- StringBuilder sb = null;
-
- int strLen = str.Length;
- int index; // Pointer into the string that indicates the location of the current '&' character
- int newIndex = 0; // Pointer into the string that indicates the start index of the "remainging" string (that still needs to be processed).
-
- do
- {
- index = str.IndexOf( '&', newIndex );
-
- if (index == -1)
- {
- if (sb == null)
- return str;
- else
- {
- sb.Append( str, newIndex, strLen - newIndex );
- return sb.ToString();
- }
- }
- else
- {
- if (sb == null)
- sb = new StringBuilder();
-
- sb.Append(str, newIndex, index - newIndex);
- sb.Append( GetUnescapeSequence( str, index, out newIndex ) ); // updates the newIndex too
-
- }
- }
- while (true);
-
- // C# reports a warning if I leave this in, but I still kinda want to just in case.
- // Debug.Assert( false, "If you got here, the execution engine or compiler is really confused" );
- // return str;
- }
-
- private delegate void ToStringHelperFunc( Object obj, String str );
-
- private static void ToStringHelperStringBuilder( Object obj, String str )
- {
- ((StringBuilder)obj).Append( str );
- }
-
- public override String ToString ()
- {
- StringBuilder sb = new StringBuilder();
-
- ToString( "", sb, new ToStringHelperFunc( ToStringHelperStringBuilder ) );
-
- return sb.ToString();
- }
-
- private void ToString( String indent, Object obj, ToStringHelperFunc func )
- {
- // First add the indent
-
- // func( obj, indent );
-
- // Add in the opening bracket and the tag.
-
- func( obj, "<" );
-
- switch (m_type)
- {
- case SecurityElementType.Format:
- func( obj, "?" );
- break;
-
- case SecurityElementType.Comment:
- func( obj, "!" );
- break;
-
- default:
- break;
- }
-
- func( obj, m_strTag );
-
- // If there are any attributes, plop those in.
-
- if (m_lAttributes != null && m_lAttributes.Count > 0)
- {
- func( obj, " " );
-
- int iMax = m_lAttributes.Count;
- 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)
- {
- String strAttrName = (String)m_lAttributes[i];
- String strAttrValue = (String)m_lAttributes[i+1];
-
- func( obj, strAttrName );
- func( obj, "=\"" );
- func( obj, strAttrValue );
- func( obj, "\"" );
-
- if (i != m_lAttributes.Count - 2)
- {
- if (m_type == SecurityElementType.Regular)
- {
- func( obj, Environment.NewLine );
- }
- else
- {
- func( obj, " " );
- }
- }
- }
- }
-
- if (m_strText == null && (m_lChildren == null || m_lChildren.Count == 0))
- {
- // If we are a single tag with no children, just add the end of tag text.
-
- switch (m_type)
- {
- case SecurityElementType.Comment:
- func( obj, ">" );
- break;
-
- case SecurityElementType.Format:
- func( obj, " ?>" );
- break;
-
- default:
- func( obj, "/>" );
- break;
- }
- func( obj, Environment.NewLine );
- }
- else
- {
- // Close the current tag.
-
- func( obj, ">" );
-
- // Output the text
-
- func( obj, m_strText );
-
- // Output any children.
-
- if (m_lChildren != null)
- {
- this.ConvertSecurityElementFactories();
-
- func( obj, Environment.NewLine );
-
- // String childIndent = indent + s_strIndent;
-
- for (int i = 0; i < m_lChildren.Count; ++i)
- {
- ((SecurityElement)m_lChildren[i]).ToString( "", obj, func );
- }
-
- // In the case where we have children, the close tag will not be on the same line as the
- // opening tag, so we need to indent.
-
- // func( obj, indent );
- }
-
- // Output the closing tag
-
- func( obj, "</" );
- func( obj, m_strTag );
- func( obj, ">" );
- func( obj, Environment.NewLine );
- }
- }
-
-
-
- public String Attribute( String name )
- {
- if (name == null)
- throw new ArgumentNullException( nameof(name) );
- Contract.EndContractBlock();
-
- // Note: we don't check for validity here because an
- // if an invalid name is passed we simply won't find it.
-
- if (m_lAttributes == null)
- return null;
-
- // Go through all the attribute and see if we know about
- // the one we are asked for
-
- int iMax = m_lAttributes.Count;
- 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)
- {
- String strAttrName = (String)m_lAttributes[i];
-
- if (String.Equals(strAttrName, name))
- {
- String strAttrValue = (String)m_lAttributes[i+1];
-
- return Unescape(strAttrValue);
- }
- }
-
- // In the case where we didn't find it, we are expected to
- // return null
- return null;
- }
-
- public SecurityElement SearchForChildByTag( String tag )
- {
- // Go through all the children and see if we can
- // find the one are are asked for (matching tags)
-
- if (tag == null)
- throw new ArgumentNullException( nameof(tag) );
- Contract.EndContractBlock();
-
- // Note: we don't check for a valid tag here because
- // an invalid tag simply won't be found.
-
- if (m_lChildren == null)
- return null;
-
- IEnumerator enumerator = m_lChildren.GetEnumerator();
-
- while (enumerator.MoveNext())
- {
- SecurityElement current = (SecurityElement)enumerator.Current;
-
- if (current != null && String.Equals(current.Tag, tag))
- return current;
- }
- return null;
- }
-
- internal String SearchForTextOfLocalName(String strLocalName)
- {
- // Search on each child in order and each
- // child's child, depth-first
-
- if (strLocalName == null)
- throw new ArgumentNullException( nameof(strLocalName) );
- Contract.EndContractBlock();
-
- // Note: we don't check for a valid tag here because
- // an invalid tag simply won't be found.
-
- // First we check this.
-
- if (m_strTag == null) return null;
- if (m_strTag.Equals( strLocalName ) || m_strTag.EndsWith( ":" + strLocalName, StringComparison.Ordinal ))
- return Unescape( m_strText );
- if (m_lChildren == null)
- return null;
-
- IEnumerator enumerator = m_lChildren.GetEnumerator();
-
- while (enumerator.MoveNext())
- {
- String current = ((SecurityElement)enumerator.Current).SearchForTextOfLocalName( strLocalName );
-
- if (current != null)
- return current;
- }
- return null;
- }
-
- public String SearchForTextOfTag( String tag )
- {
- // Search on each child in order and each
- // child's child, depth-first
-
- if (tag == null)
- throw new ArgumentNullException( nameof(tag) );
- Contract.EndContractBlock();
-
- // Note: we don't check for a valid tag here because
- // an invalid tag simply won't be found.
-
- // First we check this.
-
- if (String.Equals(m_strTag, tag))
- return Unescape( m_strText );
- if (m_lChildren == null)
- return null;
-
- IEnumerator enumerator = m_lChildren.GetEnumerator();
-
- this.ConvertSecurityElementFactories();
-
- while (enumerator.MoveNext())
- {
- String current = ((SecurityElement)enumerator.Current).SearchForTextOfTag( tag );
-
- if (current != null)
- return current;
- }
- return null;
- }
- }
-}
diff --git a/src/mscorlib/src/System/Security/SecurityException.cs b/src/mscorlib/src/System/Security/SecurityException.cs
index c76674cdb9..8811be82ff 100644
--- a/src/mscorlib/src/System/Security/SecurityException.cs
+++ b/src/mscorlib/src/System/Security/SecurityException.cs
@@ -18,30 +18,23 @@ namespace System.Security
using System.Security;
using System;
using System.Runtime.Serialization;
- using System.Security.Permissions;
using System.Reflection;
using System.Text;
using System.Security.Policy;
using System.IO;
-#if FEATURE_SERIALIZATION
- using System.Runtime.Serialization.Formatters.Binary;
-#endif // FEATURE_SERIALIZATION
using System.Globalization;
- using System.Security.Util;
using System.Diagnostics.Contracts;
- [System.Runtime.InteropServices.ComVisible(true)]
[Serializable]
public class SecurityException : SystemException
{
internal static string GetResString(string sResourceName)
{
- PermissionSet.s_fullTrust.Assert();
return Environment.GetResourceString(sResourceName);
}
#pragma warning disable 618
- internal static Exception MakeSecurityException(AssemblyName asmName, Evidence asmEvidence, PermissionSet granted, PermissionSet refused, RuntimeMethodHandleInternal rmh, SecurityAction action, Object demand, IPermission permThatFailed)
+ internal static Exception MakeSecurityException(AssemblyName asmName, Evidence asmEvidence, RuntimeMethodHandleInternal rmh, Object demand)
#pragma warning restore 618
{
return new SecurityException(GetResString("Arg_SecurityException"));
@@ -66,16 +59,6 @@ namespace System.Security
SetErrorCode(System.__HResults.COR_E_SECURITY);
}
- 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(){}
-
protected SecurityException(SerializationInfo info, StreamingContext context) : base(info, context)
{
if (info == null)
@@ -88,22 +71,6 @@ namespace System.Security
return base.ToString();
}
- private bool CanAccessSensitiveInfo()
- {
- bool retVal = false;
- try
- {
-#pragma warning disable 618
- new SecurityPermission(SecurityPermissionFlag.ControlEvidence | SecurityPermissionFlag.ControlPolicy).Demand();
-#pragma warning restore 618
- retVal = true;
- }
- catch (SecurityException)
- {
- }
- return retVal;
- }
-
public override void GetObjectData(SerializationInfo info, StreamingContext context)
{
if (info == null)
diff --git a/src/mscorlib/src/System/Security/SecurityManager.cs b/src/mscorlib/src/System/Security/SecurityManager.cs
deleted file mode 100644
index 933fe0be3d..0000000000
--- a/src/mscorlib/src/System/Security/SecurityManager.cs
+++ /dev/null
@@ -1,157 +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.
-
-//
-// The SecurityManager class provides a general purpose API for interacting
-// with the security system.
-//
-
-namespace System.Security
-{
- using System;
- using System.Security.Permissions;
- using System.Runtime.InteropServices;
- using System.Runtime.CompilerServices;
-
- [Serializable]
- [System.Runtime.InteropServices.ComVisible(true)]
- public enum PolicyLevelType
- {
- User = 0,
- Machine = 1,
- Enterprise = 2,
- AppDomain = 3
- }
-
- [System.Runtime.InteropServices.ComVisible(true)]
- static public class SecurityManager
- {
- private static int[][] s_BuiltInPermissionIndexMap = {
- new int[] { BuiltInPermissionIndex.EnvironmentPermissionIndex, (int) PermissionType.EnvironmentPermission },
- new int[] { BuiltInPermissionIndex.FileDialogPermissionIndex, (int) PermissionType.FileDialogPermission },
- new int[] { BuiltInPermissionIndex.FileIOPermissionIndex, (int) PermissionType.FileIOPermission },
- new int[] { BuiltInPermissionIndex.ReflectionPermissionIndex, (int) PermissionType.ReflectionPermission },
- new int[] { BuiltInPermissionIndex.SecurityPermissionIndex, (int) PermissionType.SecurityPermission },
- new int[] { BuiltInPermissionIndex.UIPermissionIndex, (int) PermissionType.UIPermission }
- };
-
- private static CodeAccessPermission[] s_UnrestrictedSpecialPermissionMap = {
- new EnvironmentPermission(PermissionState.Unrestricted),
- new FileDialogPermission(PermissionState.Unrestricted),
- new FileIOPermission(PermissionState.Unrestricted),
- new ReflectionPermission(PermissionState.Unrestricted),
- new SecurityPermission(PermissionState.Unrestricted),
- new UIPermission(PermissionState.Unrestricted)
- };
-
- internal static int GetSpecialFlags (PermissionSet grantSet, PermissionSet deniedSet) {
- if ((grantSet != null && grantSet.IsUnrestricted()) && (deniedSet == null || deniedSet.IsEmpty())) {
- return -1;
- }
- else {
- SecurityPermission securityPermission = null;
-#pragma warning disable 618
- SecurityPermissionFlag securityPermissionFlags = SecurityPermissionFlag.NoFlags;
-#pragma warning restore 618
- ReflectionPermission reflectionPermission = null;
- ReflectionPermissionFlag reflectionPermissionFlags = ReflectionPermissionFlag.NoFlags;
-
- CodeAccessPermission[] specialPermissions = new CodeAccessPermission[6];
- if (grantSet != null) {
- if (grantSet.IsUnrestricted()) {
-#pragma warning disable 618
- securityPermissionFlags = SecurityPermissionFlag.AllFlags;
-#pragma warning restore 618
- reflectionPermissionFlags = ReflectionPermission.AllFlagsAndMore;
- for (int i = 0; i < specialPermissions.Length; i++) {
- specialPermissions[i] = s_UnrestrictedSpecialPermissionMap[i];
- }
- }
- else {
- securityPermission = grantSet.GetPermission(BuiltInPermissionIndex.SecurityPermissionIndex) as SecurityPermission;
- if (securityPermission != null)
- securityPermissionFlags = securityPermission.Flags;
- reflectionPermission = grantSet.GetPermission(BuiltInPermissionIndex.ReflectionPermissionIndex) as ReflectionPermission;
- if (reflectionPermission != null)
- reflectionPermissionFlags = reflectionPermission.Flags;
- for (int i = 0; i < specialPermissions.Length; i++) {
- specialPermissions[i] = grantSet.GetPermission(s_BuiltInPermissionIndexMap[i][0]) as CodeAccessPermission;
- }
- }
- }
-
- if (deniedSet != null) {
- if (deniedSet.IsUnrestricted()) {
-#pragma warning disable 618
- securityPermissionFlags = SecurityPermissionFlag.NoFlags;
-#pragma warning restore 618
- reflectionPermissionFlags = ReflectionPermissionFlag.NoFlags;
- for (int i = 0; i < s_BuiltInPermissionIndexMap.Length; i++) {
- specialPermissions[i] = null;
- }
- }
- else {
- securityPermission = deniedSet.GetPermission(BuiltInPermissionIndex.SecurityPermissionIndex) as SecurityPermission;
- if (securityPermission != null)
- securityPermissionFlags &= ~securityPermission.Flags;
- reflectionPermission = deniedSet.GetPermission(BuiltInPermissionIndex.ReflectionPermissionIndex) as ReflectionPermission;
- if (reflectionPermission != null)
- reflectionPermissionFlags &= ~reflectionPermission.Flags;
- for (int i = 0; i < s_BuiltInPermissionIndexMap.Length; i++) {
- CodeAccessPermission deniedSpecialPermission = deniedSet.GetPermission(s_BuiltInPermissionIndexMap[i][0]) as CodeAccessPermission;
- if (deniedSpecialPermission != null && !deniedSpecialPermission.IsSubsetOf(null))
- specialPermissions[i] = null; // we don't care about the exact value here.
- }
- }
- }
- int flags = MapToSpecialFlags(securityPermissionFlags, reflectionPermissionFlags);
- if (flags != -1) {
- for (int i = 0; i < specialPermissions.Length; i++) {
- if (specialPermissions[i] != null && ((IUnrestrictedPermission) specialPermissions[i]).IsUnrestricted())
- flags |= (1 << (int) s_BuiltInPermissionIndexMap[i][1]);
- }
- }
- return flags;
- }
- }
-
-#pragma warning disable 618
- private static int MapToSpecialFlags (SecurityPermissionFlag securityPermissionFlags, ReflectionPermissionFlag reflectionPermissionFlags) {
- int flags = 0;
- if ((securityPermissionFlags & SecurityPermissionFlag.UnmanagedCode) == SecurityPermissionFlag.UnmanagedCode)
- flags |= (1 << (int) PermissionType.SecurityUnmngdCodeAccess);
- if ((securityPermissionFlags & SecurityPermissionFlag.SkipVerification) == SecurityPermissionFlag.SkipVerification)
- flags |= (1 << (int) PermissionType.SecuritySkipVerification);
- if ((securityPermissionFlags & SecurityPermissionFlag.Assertion) == SecurityPermissionFlag.Assertion)
- flags |= (1 << (int) PermissionType.SecurityAssert);
- if ((securityPermissionFlags & SecurityPermissionFlag.SerializationFormatter) == SecurityPermissionFlag.SerializationFormatter)
- flags |= (1 << (int) PermissionType.SecuritySerialization);
- if ((securityPermissionFlags & SecurityPermissionFlag.BindingRedirects) == SecurityPermissionFlag.BindingRedirects)
- flags |= (1 << (int) PermissionType.SecurityBindingRedirects);
- if ((securityPermissionFlags & SecurityPermissionFlag.ControlEvidence) == SecurityPermissionFlag.ControlEvidence)
- flags |= (1 << (int) PermissionType.SecurityControlEvidence);
- if ((securityPermissionFlags & SecurityPermissionFlag.ControlPrincipal) == SecurityPermissionFlag.ControlPrincipal)
- flags |= (1 << (int) PermissionType.SecurityControlPrincipal);
-
- if ((reflectionPermissionFlags & ReflectionPermissionFlag.RestrictedMemberAccess) == ReflectionPermissionFlag.RestrictedMemberAccess)
- flags |= (1 << (int)PermissionType.ReflectionRestrictedMemberAccess);
- if ((reflectionPermissionFlags & ReflectionPermissionFlag.MemberAccess) == ReflectionPermissionFlag.MemberAccess)
- flags |= (1 << (int) PermissionType.ReflectionMemberAccess);
-
- return flags;
- }
-#pragma warning restore 618
-
- [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
- [SuppressUnmanagedCodeSecurity]
- internal static extern bool IsSameType(String strLeft, String strRight);
-
- [MethodImplAttribute(MethodImplOptions.InternalCall)]
- internal static extern bool _SetThreadSecurity(bool bThreadSecurity);
-
- [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
deleted file mode 100644
index d037fe939d..0000000000
--- a/src/mscorlib/src/System/Security/SecurityRuntime.cs
+++ /dev/null
@@ -1,159 +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.Security
-{
- using System;
- using System.Globalization;
- using System.Threading;
- using System.Reflection;
- using System.Collections;
- using System.Runtime.CompilerServices;
- using System.Security.Permissions;
- using System.Runtime.Versioning;
- using System.Diagnostics.Contracts;
-
- internal class SecurityRuntime
- {
- private SecurityRuntime(){}
-
- // Returns the security object for the caller of the method containing
- // 'stackMark' on its frame.
- //
- // THE RETURNED OBJECT IS THE LIVE RUNTIME OBJECT. BE CAREFUL WITH IT!
- //
- // Internal only, do not doc.
- //
- [MethodImplAttribute(MethodImplOptions.InternalCall)]
- internal static extern
- FrameSecurityDescriptor GetSecurityObjectForFrame(ref StackCrawlMark stackMark,
- bool create);
-
- // Constants used to return status to native
- internal const bool StackContinue = true;
- internal const bool StackHalt = false;
-
- // this method is a big perf hit, so don't call unnecessarily
- internal static MethodInfo GetMethodInfo(RuntimeMethodHandleInternal rmh)
- {
- if (rmh.IsNullHandle())
- return null;
-
-#if _DEBUG
- try
- {
-#endif
- // Assert here because reflection will check grants and if we fail the check,
- // there will be an infinite recursion that overflows the stack.
- PermissionSet.s_fullTrust.Assert();
- return (System.RuntimeType.GetMethodBase(RuntimeMethodHandle.GetDeclaringType(rmh), rmh) as MethodInfo);
-#if _DEBUG
- }
- catch(Exception)
- {
- return null;
- }
-#endif
- }
-
- private static bool FrameDescSetHelper(FrameSecurityDescriptor secDesc,
- PermissionSet demandSet,
- out PermissionSet alteredDemandSet,
- RuntimeMethodHandleInternal rmh)
- {
- return secDesc.CheckSetDemand(demandSet, out alteredDemandSet, rmh);
- }
-
- private static bool FrameDescHelper(FrameSecurityDescriptor secDesc,
- IPermission demandIn,
- PermissionToken permToken,
- RuntimeMethodHandleInternal rmh)
- {
- return secDesc.CheckDemand((CodeAccessPermission) demandIn, permToken, rmh);
- }
-
-#if FEATURE_COMPRESSEDSTACK
- private static bool CheckDynamicMethodSetHelper(System.Reflection.Emit.DynamicResolver dynamicResolver,
- PermissionSet demandSet,
- out PermissionSet alteredDemandSet,
- RuntimeMethodHandleInternal rmh)
- {
- System.Threading.CompressedStack creationStack = dynamicResolver.GetSecurityContext();
- bool result;
- try
- {
- result = creationStack.CheckSetDemandWithModificationNoHalt(demandSet, out alteredDemandSet, rmh);
- }
- catch (SecurityException ex)
- {
- throw new SecurityException(Environment.GetResourceString("Security_AnonymouslyHostedDynamicMethodCheckFailed"), ex);
- }
-
- return result;
- }
-
- private static bool CheckDynamicMethodHelper(System.Reflection.Emit.DynamicResolver dynamicResolver,
- IPermission demandIn,
- PermissionToken permToken,
- RuntimeMethodHandleInternal rmh)
- {
- System.Threading.CompressedStack creationStack = dynamicResolver.GetSecurityContext();
- bool result;
- try
- {
- result = creationStack.CheckDemandNoHalt((CodeAccessPermission)demandIn, permToken, rmh);
- }
- catch (SecurityException ex)
- {
- throw new SecurityException(Environment.GetResourceString("Security_AnonymouslyHostedDynamicMethodCheckFailed"), ex);
- }
- return result;
- }
-#endif // FEATURE_COMPRESSEDSTACK
-
- //
- // API for PermissionSets
- //
-
- internal static void Assert(PermissionSet permSet, ref StackCrawlMark stackMark)
- {
- }
-
- internal static void AssertAllPossible(ref StackCrawlMark stackMark)
- {
- }
-
- internal static void Deny(PermissionSet permSet, ref StackCrawlMark stackMark)
- {
- }
-
- internal static void PermitOnly(PermissionSet permSet, ref StackCrawlMark stackMark)
- {
- }
-
- //
- // Revert API
- //
-
- internal static void RevertAssert(ref StackCrawlMark stackMark)
- {
- }
-
- internal static void RevertDeny(ref StackCrawlMark stackMark)
- {
- }
-
- internal static void RevertPermitOnly(ref StackCrawlMark stackMark)
- {
- }
-
- internal static void RevertAll(ref StackCrawlMark stackMark)
- {
- }
- }
-}
-
-
diff --git a/src/mscorlib/src/System/Security/SecurityState.cs b/src/mscorlib/src/System/Security/SecurityState.cs
index 3c7f8bf49f..55dcce07c0 100644
--- a/src/mscorlib/src/System/Security/SecurityState.cs
+++ b/src/mscorlib/src/System/Security/SecurityState.cs
@@ -3,7 +3,6 @@
// See the LICENSE file in the project root for more information.
using System;
using System.Security;
-using System.Security.Permissions;
namespace System.Security
{
diff --git a/src/mscorlib/src/System/Security/SecurityZone.cs b/src/mscorlib/src/System/Security/SecurityZone.cs
deleted file mode 100644
index a74b637846..0000000000
--- a/src/mscorlib/src/System/Security/SecurityZone.cs
+++ /dev/null
@@ -1,29 +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.
-
-//
-//
-// Enumeration of the zones code can come from
-//
-
-namespace System.Security
-{
- using System;
- using System.Runtime.InteropServices;
-
- // The quick cache code depends on the values in this enumeration. Any change to this enumeration should
- // be reflected in PolicyManager.GenerateQuickCache as well.
- [ComVisible(true)]
- [Serializable]
- public enum SecurityZone
- {
- MyComputer = 0,
- Intranet = 1,
- Trusted = 2,
- Internet = 3,
- Untrusted = 4,
-
- NoZone = -1, // No Zone Information
- }
-}
diff --git a/src/mscorlib/src/System/Security/Util/Config.cs b/src/mscorlib/src/System/Security/Util/Config.cs
deleted file mode 100644
index afc9b8c336..0000000000
--- a/src/mscorlib/src/System/Security/Util/Config.cs
+++ /dev/null
@@ -1,83 +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.Security.Util {
- using System;
- using System.Security.Util;
- using System.Security.Policy;
- using System.Security.Permissions;
- using System.Collections;
- using System.IO;
- using System.Reflection;
- using System.Globalization;
- using System.Text;
-#if FEATURE_SERIALIZATION
- using System.Runtime.Serialization.Formatters.Binary;
-#endif // FEATURE_SERIALIZATION
- using System.Threading;
- using System.Runtime.CompilerServices;
- using System.Runtime.InteropServices;
- using System.Runtime.Versioning;
-
- // Duplicated in vm\COMSecurityConfig.h
-[Serializable]
-[Flags]
- internal enum QuickCacheEntryType
- {
- FullTrustZoneMyComputer = 0x1000000,
- FullTrustZoneIntranet = 0x2000000,
- FullTrustZoneInternet = 0x4000000,
- FullTrustZoneTrusted = 0x8000000,
- FullTrustZoneUntrusted = 0x10000000,
- FullTrustAll = 0x20000000,
- }
-
- internal static class Config {
- private static volatile string m_machineConfig;
- private static volatile string m_userConfig;
-
- private static void GetFileLocales()
- {
- if (m_machineConfig == null)
- {
- string machineConfig = null;
- GetMachineDirectory(JitHelpers.GetStringHandleOnStack(ref machineConfig));
- m_machineConfig = machineConfig;
- }
- if (m_userConfig == null)
- {
- string userConfig = null;
- GetUserDirectory(JitHelpers.GetStringHandleOnStack(ref userConfig));
- m_userConfig = userConfig;
- }
- }
-
- internal static string MachineDirectory
- {
- get
- {
- GetFileLocales();
- return m_machineConfig;
- }
- }
-
- internal static string UserDirectory
- {
- get
- {
- GetFileLocales();
- return m_userConfig;
- }
- }
-
- [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode), SuppressUnmanagedCodeSecurity]
- private static extern void GetMachineDirectory(StringHandleOnStack retDirectory);
-
- [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode), SuppressUnmanagedCodeSecurity]
- private static extern void GetUserDirectory(StringHandleOnStack retDirectory);
-
- [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
deleted file mode 100644
index 4ca1cf678b..0000000000
--- a/src/mscorlib/src/System/Security/Util/Hex.cs
+++ /dev/null
@@ -1,126 +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.
-
-/*
- *
- * Operations to convert to and from Hex
- *
- */
-
-namespace System.Security.Util
-{
- using System;
- using System.Security;
- using System.Diagnostics.Contracts;
- internal static class Hex
- {
- // converts number to hex digit. Does not do any range checks.
- static char HexDigit(int num) {
- return (char)((num < 10) ? (num + '0') : (num + ('A' - 10)));
- }
-
- public static String EncodeHexString(byte[] sArray)
- {
- String result = null;
-
- if(sArray != null) {
- char[] hexOrder = new char[sArray.Length * 2];
-
- int digit;
- for(int i = 0, j = 0; i < sArray.Length; i++) {
- digit = (int)((sArray[i] & 0xf0) >> 4);
- hexOrder[j++] = HexDigit(digit);
- digit = (int)(sArray[i] & 0x0f);
- hexOrder[j++] = HexDigit(digit);
- }
- result = new String(hexOrder);
- }
- return result;
- }
-
- internal static string EncodeHexStringFromInt(byte[] sArray) {
- String result = null;
- if(sArray != null) {
- char[] hexOrder = new char[sArray.Length * 2];
-
- int i = sArray.Length;
- int digit, j=0;
- while (i-- > 0) {
- digit = (sArray[i] & 0xf0) >> 4;
- hexOrder[j++] = HexDigit(digit);
- digit = sArray[i] & 0x0f;
- hexOrder[j++] = HexDigit(digit);
- }
- result = new String(hexOrder);
- }
- return result;
- }
-
- public static int ConvertHexDigit(Char val)
- {
- if (val <= '9' && val >= '0')
- return (val - '0');
- else if (val >= 'a' && val <= 'f')
- return ((val - 'a') + 10);
- else if (val >= 'A' && val <= 'F')
- return ((val - 'A') + 10);
- else
- throw new ArgumentException( Environment.GetResourceString( "ArgumentOutOfRange_Index" ) );
- }
-
-
- public static byte[] DecodeHexString(String hexString)
- {
- if (hexString == null)
- throw new ArgumentNullException( nameof(hexString) );
- Contract.EndContractBlock();
-
- bool spaceSkippingMode = false;
-
- int i = 0;
- int length = hexString.Length;
-
- if ((length >= 2) &&
- (hexString[0] == '0') &&
- ( (hexString[1] == 'x') || (hexString[1] == 'X') ))
- {
- length = hexString.Length - 2;
- i = 2;
- }
-
- // Hex strings must always have 2N or (3N - 1) entries.
-
- if (length % 2 != 0 && length % 3 != 2)
- {
- throw new ArgumentException( Environment.GetResourceString( "Argument_InvalidHexFormat" ) );
- }
-
- byte[] sArray;
-
- if (length >=3 && hexString[i + 2] == ' ')
- {
- spaceSkippingMode = true;
-
- // Each hex digit will take three spaces, except the first (hence the plus 1).
- sArray = new byte[length / 3 + 1];
- }
- else
- {
- // Each hex digit will take two spaces
- sArray = new byte[length / 2];
- }
-
- int digit;
- int rawdigit;
- for (int j = 0; i < hexString.Length; i += 2, j++) {
- rawdigit = ConvertHexDigit(hexString[i]);
- digit = ConvertHexDigit(hexString[i+1]);
- sArray[j] = (byte) (digit | (rawdigit << 4));
- if (spaceSkippingMode)
- i++;
- }
- return(sArray);
- }
- }
-}
diff --git a/src/mscorlib/src/System/Security/Util/StringExpressionSet.cs b/src/mscorlib/src/System/Security/Util/StringExpressionSet.cs
deleted file mode 100644
index 8a12235106..0000000000
--- a/src/mscorlib/src/System/Security/Util/StringExpressionSet.cs
+++ /dev/null
@@ -1,752 +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.Security.Util {
- using System.Text;
- using System;
- using System.Collections;
- using System.Collections.Generic;
- using System.Runtime.CompilerServices;
- using System.Runtime.InteropServices;
- using System.Globalization;
- using System.Runtime.Versioning;
- using System.IO;
- using System.Diagnostics;
- using System.Diagnostics.Contracts;
-
- [Serializable]
- internal class StringExpressionSet
- {
- // This field, as well as the expressions fields below are critical since they may contain
- // canonicalized full path data potentially built out of relative data passed as input to the
- // StringExpressionSet. Full trust code using the string expression set needs to ensure that before
- // exposing this data out to partial trust, they protect against this. Possibilities include:
- //
- // 1. Using the throwOnRelative flag
- // 2. Ensuring that the partial trust code has permission to see full path data
- // 3. Not using this set for paths (eg EnvironmentStringExpressionSet)
- //
- protected ArrayList m_list;
- protected bool m_ignoreCase;
- protected String m_expressions;
- protected String[] m_expressionsArray;
-
- protected bool m_throwOnRelative;
-
- protected static readonly char[] m_separators = { ';' };
- protected static readonly char[] m_trimChars = { ' ' };
-#if !PLATFORM_UNIX
- protected static readonly char m_directorySeparator = '\\';
- protected static readonly char m_alternateDirectorySeparator = '/';
-#else
- protected static readonly char m_directorySeparator = '/';
- protected static readonly char m_alternateDirectorySeparator = '\\';
-#endif // !PLATFORM_UNIX
-
- public StringExpressionSet()
- : this( true, null, false )
- {
- }
-
- public StringExpressionSet( String str )
- : this( true, str, false )
- {
- }
-
- public StringExpressionSet( bool ignoreCase, bool throwOnRelative )
- : this( ignoreCase, null, throwOnRelative )
- {
- }
-
- public StringExpressionSet( bool ignoreCase, String str, bool throwOnRelative )
- {
- m_list = null;
- m_ignoreCase = ignoreCase;
- m_throwOnRelative = throwOnRelative;
- if (str == null)
- m_expressions = null;
- else
- AddExpressions( str );
- }
-
- protected virtual StringExpressionSet CreateNewEmpty()
- {
- return new StringExpressionSet();
- }
-
- public virtual StringExpressionSet Copy()
- {
- // SafeCritical: just copying this value around, not leaking it
-
- StringExpressionSet copy = CreateNewEmpty();
- if (this.m_list != null)
- copy.m_list = new ArrayList(this.m_list);
-
- copy.m_expressions = this.m_expressions;
- copy.m_ignoreCase = this.m_ignoreCase;
- copy.m_throwOnRelative = this.m_throwOnRelative;
- return copy;
- }
-
- public void SetThrowOnRelative( bool throwOnRelative )
- {
- this.m_throwOnRelative = throwOnRelative;
- }
-
- private static String StaticProcessWholeString( String str )
- {
- return str.Replace( m_alternateDirectorySeparator, m_directorySeparator );
- }
-
- private static String StaticProcessSingleString( String str )
- {
- return str.Trim( m_trimChars );
- }
-
- protected virtual String ProcessWholeString( String str )
- {
- return StaticProcessWholeString(str);
- }
-
- protected virtual String ProcessSingleString( String str )
- {
- return StaticProcessSingleString(str);
- }
-
- public void AddExpressions( String str )
- {
- if (str == null)
- throw new ArgumentNullException( nameof(str) );
- Contract.EndContractBlock();
- if (str.Length == 0)
- return;
-
- str = ProcessWholeString( str );
-
- if (m_expressions == null)
- m_expressions = str;
- else
- m_expressions = m_expressions + m_separators[0] + str;
-
- m_expressionsArray = null;
-
- // We have to parse the string and compute the list here.
- // The logic in this class tries to delay this parsing but
- // since operations like IsSubsetOf are called during
- // demand evaluation, it is not safe to delay this step
- // as that would cause concurring threads to update the object
- // at the same time. The CheckList operation should ideally be
- // removed from this class, but for the sake of keeping the
- // changes to a minimum here, we simply make sure m_list
- // cannot be null by parsing m_expressions eagerly.
-
- String[] arystr = Split( str );
-
- if (m_list == null)
- m_list = new ArrayList();
-
- for (int index = 0; index < arystr.Length; ++index)
- {
- if (arystr[index] != null && !arystr[index].Equals( "" ))
- {
- String temp = ProcessSingleString( arystr[index] );
- int indexOfNull = temp.IndexOf( '\0' );
-
- if (indexOfNull != -1)
- temp = temp.Substring( 0, indexOfNull );
-
- if (temp != null && !temp.Equals( "" ))
- {
- if (m_throwOnRelative)
- {
- if (PathInternal.IsPartiallyQualified(temp))
- {
- throw new ArgumentException( Environment.GetResourceString( "Argument_AbsolutePathRequired" ) );
- }
-
- temp = CanonicalizePath( temp );
- }
-
- m_list.Add( temp );
- }
- }
- }
-
- Reduce();
- }
-
- public void AddExpressions( String[] str, bool checkForDuplicates, bool needFullPath )
- {
- AddExpressions(CreateListFromExpressions(str, needFullPath), checkForDuplicates);
- }
-
- public void AddExpressions( ArrayList exprArrayList, bool checkForDuplicates)
- {
- Debug.Assert( m_throwOnRelative, "This should only be called when throw on relative is set" );
-
- m_expressionsArray = null;
- m_expressions = null;
-
- if (m_list != null)
- m_list.AddRange(exprArrayList);
- else
- m_list = new ArrayList(exprArrayList);
-
- if (checkForDuplicates)
- Reduce();
- }
-
-
- internal static ArrayList CreateListFromExpressions(String[] str, bool needFullPath)
- {
- if (str == null)
- {
- 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( nameof(str) );
-
- // Replace alternate directory separators
- String oneString = StaticProcessWholeString( str[index] );
-
- if (oneString != null && oneString.Length != 0)
- {
- // Trim leading and trailing spaces
- String temp = StaticProcessSingleString( oneString);
-
- int indexOfNull = temp.IndexOf( '\0' );
-
- if (indexOfNull != -1)
- temp = temp.Substring( 0, indexOfNull );
-
- if (temp != null && temp.Length != 0)
- {
- if (PathInternal.IsPartiallyQualified(temp))
- {
- throw new ArgumentException(Environment.GetResourceString( "Argument_AbsolutePathRequired" ) );
- }
-
- temp = CanonicalizePath( temp, needFullPath );
-
- retArrayList.Add( temp );
- }
- }
- }
-
- return retArrayList;
- }
-
- protected void CheckList()
- {
- if (m_list == null && m_expressions != null)
- {
- CreateList();
- }
- }
-
- protected String[] Split( String expressions )
- {
- if (m_throwOnRelative)
- {
- List<String> tempList = new List<String>();
-
- String[] quoteSplit = expressions.Split( '\"' );
-
- for (int i = 0; i < quoteSplit.Length; ++i)
- {
- if (i % 2 == 0)
- {
- String[] semiSplit = quoteSplit[i].Split( ';' );
-
- for (int j = 0; j < semiSplit.Length; ++j)
- {
- if (semiSplit[j] != null && !semiSplit[j].Equals( "" ))
- tempList.Add( semiSplit[j] );
- }
- }
- else
- {
- tempList.Add( quoteSplit[i] );
- }
- }
-
- String[] finalArray = new String[tempList.Count];
-
- IEnumerator enumerator = tempList.GetEnumerator();
-
- int index = 0;
- while (enumerator.MoveNext())
- {
- finalArray[index++] = (String)enumerator.Current;
- }
-
- return finalArray;
- }
- else
- {
- return expressions.Split( m_separators );
- }
- }
-
-
- protected void CreateList()
- {
- String[] expressionsArray = Split( m_expressions );
-
- m_list = new ArrayList();
-
- for (int index = 0; index < expressionsArray.Length; ++index)
- {
- if (expressionsArray[index] != null && !expressionsArray[index].Equals( "" ))
- {
- String temp = ProcessSingleString( expressionsArray[index] );
-
- int indexOfNull = temp.IndexOf( '\0' );
-
- if (indexOfNull != -1)
- temp = temp.Substring( 0, indexOfNull );
-
- if (temp != null && !temp.Equals( "" ))
- {
- if (m_throwOnRelative)
- {
- if (PathInternal.IsPartiallyQualified(temp))
- {
- throw new ArgumentException( Environment.GetResourceString( "Argument_AbsolutePathRequired" ) );
- }
-
- temp = CanonicalizePath( temp );
- }
-
- m_list.Add( temp );
- }
- }
- }
- }
-
- public bool IsEmpty()
- {
- // SafeCritical: we're just showing that the expressions are empty, the sensitive portion is their
- // contents - not the existence of the contents
- if (m_list == null)
- {
- return m_expressions == null;
- }
- else
- {
- return m_list.Count == 0;
- }
- }
-
- public bool IsSubsetOf( StringExpressionSet ses )
- {
- if (this.IsEmpty())
- return true;
-
- if (ses == null || ses.IsEmpty())
- return false;
-
- CheckList();
- ses.CheckList();
-
- for (int index = 0; index < this.m_list.Count; ++index)
- {
- if (!StringSubsetStringExpression( (String)this.m_list[index], ses, m_ignoreCase ))
- {
- return false;
- }
- }
- return true;
- }
-
- public bool IsSubsetOfPathDiscovery( StringExpressionSet ses )
- {
- if (this.IsEmpty())
- return true;
-
- if (ses == null || ses.IsEmpty())
- return false;
-
- CheckList();
- ses.CheckList();
-
- for (int index = 0; index < this.m_list.Count; ++index)
- {
- if (!StringSubsetStringExpressionPathDiscovery( (String)this.m_list[index], ses, m_ignoreCase ))
- {
- return false;
- }
- }
- return true;
- }
-
-
- public StringExpressionSet Union( StringExpressionSet ses )
- {
- // If either set is empty, the union represents a copy of the other.
-
- if (ses == null || ses.IsEmpty())
- return this.Copy();
-
- if (this.IsEmpty())
- return ses.Copy();
-
- CheckList();
- ses.CheckList();
-
- // Perform the union
- // note: insert smaller set into bigger set to reduce needed comparisons
-
- StringExpressionSet bigger = ses.m_list.Count > this.m_list.Count ? ses : this;
- StringExpressionSet smaller = ses.m_list.Count <= this.m_list.Count ? ses : this;
-
- StringExpressionSet unionSet = bigger.Copy();
-
- unionSet.Reduce();
-
- for (int index = 0; index < smaller.m_list.Count; ++index)
- {
- unionSet.AddSingleExpressionNoDuplicates( (String)smaller.m_list[index] );
- }
-
- unionSet.GenerateString();
-
- return unionSet;
- }
-
-
- public StringExpressionSet Intersect( StringExpressionSet ses )
- {
- // If either set is empty, the intersection is empty
-
- if (this.IsEmpty() || ses == null || ses.IsEmpty())
- return CreateNewEmpty();
-
- CheckList();
- ses.CheckList();
-
- // Do the intersection for real
-
- StringExpressionSet intersectSet = CreateNewEmpty();
-
- for (int this_index = 0; this_index < this.m_list.Count; ++this_index)
- {
- for (int ses_index = 0; ses_index < ses.m_list.Count; ++ses_index)
- {
- if (StringSubsetString( (String)this.m_list[this_index], (String)ses.m_list[ses_index], m_ignoreCase ))
- {
- if (intersectSet.m_list == null)
- {
- intersectSet.m_list = new ArrayList();
- }
- intersectSet.AddSingleExpressionNoDuplicates( (String)this.m_list[this_index] );
- }
- else if (StringSubsetString( (String)ses.m_list[ses_index], (String)this.m_list[this_index], m_ignoreCase ))
- {
- if (intersectSet.m_list == null)
- {
- intersectSet.m_list = new ArrayList();
- }
- intersectSet.AddSingleExpressionNoDuplicates( (String)ses.m_list[ses_index] );
- }
- }
- }
-
- intersectSet.GenerateString();
-
- return intersectSet;
- }
-
- protected void GenerateString()
- {
- // SafeCritical - moves critical data around, but doesn't expose it out
- if (m_list != null)
- {
- StringBuilder sb = new StringBuilder();
-
- IEnumerator enumerator = this.m_list.GetEnumerator();
- bool first = true;
-
- while (enumerator.MoveNext())
- {
- if (!first)
- sb.Append( m_separators[0] );
- else
- first = false;
-
- String currentString = (String)enumerator.Current;
- if (currentString != null)
- {
- int indexOfSeparator = currentString.IndexOf( m_separators[0] );
-
- if (indexOfSeparator != -1)
- sb.Append( '\"' );
-
- sb.Append( currentString );
-
- if (indexOfSeparator != -1)
- sb.Append( '\"' );
- }
- }
-
- m_expressions = sb.ToString();
- }
- else
- {
- m_expressions = null;
- }
- }
-
- // We don't override ToString since that API must be either transparent or safe citical. If the
- // 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.
- public string UnsafeToString()
- {
- CheckList();
-
- Reduce();
-
- GenerateString();
-
- return m_expressions;
- }
-
- public String[] UnsafeToStringArray()
- {
- if (m_expressionsArray == null && m_list != null)
- {
- m_expressionsArray = (String[])m_list.ToArray(typeof(String));
- }
-
- return m_expressionsArray;
- }
-
-
- //-------------------------------
- // protected static helper functions
- //-------------------------------
-
- private bool StringSubsetStringExpression( String left, StringExpressionSet right, bool ignoreCase )
- {
- for (int index = 0; index < right.m_list.Count; ++index)
- {
- if (StringSubsetString( left, (String)right.m_list[index], ignoreCase ))
- {
- return true;
- }
- }
- return false;
- }
-
- private static bool StringSubsetStringExpressionPathDiscovery( String left, StringExpressionSet right, bool ignoreCase )
- {
- for (int index = 0; index < right.m_list.Count; ++index)
- {
- if (StringSubsetStringPathDiscovery( left, (String)right.m_list[index], ignoreCase ))
- {
- return true;
- }
- }
- return false;
- }
-
-
- protected virtual bool StringSubsetString( String left, String right, bool ignoreCase )
- {
- StringComparison strComp = (ignoreCase ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal);
- if (right == null || left == null || right.Length == 0 || left.Length == 0 ||
- right.Length > left.Length)
- {
- return false;
- }
- else if (right.Length == left.Length)
- {
- // if they are equal in length, just do a normal compare
- return String.Compare( right, left, strComp) == 0;
- }
- else if (left.Length - right.Length == 1 && left[left.Length-1] == m_directorySeparator)
- {
- return String.Compare( left, 0, right, 0, right.Length, strComp) == 0;
- }
- else if (right[right.Length-1] == m_directorySeparator)
- {
- // right is definitely a directory, just do a substring compare
- return String.Compare( right, 0, left, 0, right.Length, strComp) == 0;
- }
- else if (left[right.Length] == m_directorySeparator)
- {
- // left is hinting at being a subdirectory on right, do substring compare to make find out
- return String.Compare( right, 0, left, 0, right.Length, strComp) == 0;
- }
- else
- {
- return false;
- }
- }
-
- protected static bool StringSubsetStringPathDiscovery( String left, String right, bool ignoreCase )
- {
- StringComparison strComp = (ignoreCase ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal);
- if (right == null || left == null || right.Length == 0 || left.Length == 0)
- {
- return false;
- }
- else if (right.Length == left.Length)
- {
- // if they are equal in length, just do a normal compare
- return String.Compare( right, left, strComp) == 0;
- }
- else
- {
- String shortString, longString;
-
- if (right.Length < left.Length)
- {
- shortString = right;
- longString = left;
- }
- else
- {
- shortString = left;
- longString = right;
- }
-
- if (String.Compare( shortString, 0, longString, 0, shortString.Length, strComp) != 0)
- {
- return false;
- }
-
-#if !PLATFORM_UNIX
- if (shortString.Length == 3 &&
- shortString.EndsWith( ":\\", StringComparison.Ordinal ) &&
- ((shortString[0] >= 'A' && shortString[0] <= 'Z') ||
- (shortString[0] >= 'a' && shortString[0] <= 'z')))
-#else
- if (shortString.Length == 1 && shortString[0]== m_directorySeparator)
-#endif // !PLATFORM_UNIX
- return true;
-
- return longString[shortString.Length] == m_directorySeparator;
- }
- }
-
-
- //-------------------------------
- // protected helper functions
- //-------------------------------
-
- protected void AddSingleExpressionNoDuplicates( String expression )
- {
- // SafeCritical: We're not exposing out the string sets, just allowing modification of them
- int index = 0;
-
- m_expressionsArray = null;
- m_expressions = null;
-
- if (this.m_list == null)
- this.m_list = new ArrayList();
-
- while (index < this.m_list.Count)
- {
- if (StringSubsetString( (String)this.m_list[index], expression, m_ignoreCase ))
- {
- this.m_list.RemoveAt( index );
- }
- else if (StringSubsetString( expression, (String)this.m_list[index], m_ignoreCase ))
- {
- return;
- }
- else
- {
- index++;
- }
- }
- this.m_list.Add( expression );
- }
-
- protected void Reduce()
- {
- CheckList();
-
- if (this.m_list == null)
- return;
-
- int j;
-
- for (int i = 0; i < this.m_list.Count - 1; i++)
- {
- j = i + 1;
-
- while (j < this.m_list.Count)
- {
- if (StringSubsetString( (String)this.m_list[j], (String)this.m_list[i], m_ignoreCase ))
- {
- this.m_list.RemoveAt( j );
- }
- else if (StringSubsetString( (String)this.m_list[i], (String)this.m_list[j], m_ignoreCase ))
- {
- // write the value at j into position i, delete the value at position j and keep going.
- this.m_list[i] = this.m_list[j];
- this.m_list.RemoveAt( j );
- j = i + 1;
- }
- else
- {
- j++;
- }
- }
- }
- }
-
- [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
- [SuppressUnmanagedCodeSecurity]
- internal static extern void GetLongPathName( String path, StringHandleOnStack retLongPath );
-
- internal static String CanonicalizePath( String path )
- {
- return CanonicalizePath( path, true );
- }
-
- internal static string CanonicalizePath(string path, bool needFullPath)
- {
- if (needFullPath)
- {
- string newPath = Path.GetFullPath(path);
- if (path.EndsWith(m_directorySeparator + ".", StringComparison.Ordinal))
- {
- if (newPath.EndsWith(m_directorySeparator))
- {
- newPath += ".";
- }
- else
- {
- newPath += m_directorySeparator + ".";
- }
- }
- path = newPath;
- }
-#if !PLATFORM_UNIX
- else if (path.IndexOf('~') != -1)
- {
- // GetFullPathInternal() will expand 8.3 file names
- string longPath = null;
- GetLongPathName(path, JitHelpers.GetStringHandleOnStack(ref longPath));
- path = (longPath != null) ? longPath : path;
- }
-
- // This blocks usage of alternate data streams and some extended syntax paths (\\?\C:\). Checking after
- // normalization allows valid paths such as " C:\" to be considered ok (as it will become "C:\").
- if (path.IndexOf(':', 2) != -1)
- throw new NotSupportedException(Environment.GetResourceString("Argument_PathFormatNotSupported"));
-#endif // !PLATFORM_UNIX
-
- return path;
- }
- }
-}
diff --git a/src/mscorlib/src/System/Security/Util/TokenBasedSet.cs b/src/mscorlib/src/System/Security/Util/TokenBasedSet.cs
deleted file mode 100644
index 8589fa7c42..0000000000
--- a/src/mscorlib/src/System/Security/Util/TokenBasedSet.cs
+++ /dev/null
@@ -1,443 +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.Security.Util
-{
- using System;
- using System.Collections;
- using System.Security.Permissions;
- using System.Runtime.Serialization;
- using System.Threading;
- using System.Diagnostics;
- using System.Diagnostics.Contracts;
- using System.Diagnostics.CodeAnalysis;
-
-#if FEATURE_SERIALIZATION
- [Serializable]
-#endif
- internal class TokenBasedSet
- {
-
-
- // Following 3 fields are used only for serialization compat purposes: DO NOT USE THESE EVER!
-#pragma warning disable 414
- private int m_initSize = 24;
- private int m_increment = 8;
-#pragma warning restore 414
- private Object[] m_objSet;
- // END -> Serialization only fields
-
- [OptionalField(VersionAdded = 2)]
- private volatile Object m_Obj;
- [OptionalField(VersionAdded = 2)]
- private volatile Object[] m_Set;
-
- private int m_cElt;
- private volatile int m_maxIndex;
-
-
- [OnDeserialized]
- private void OnDeserialized(StreamingContext ctx)
- {
- OnDeserializedInternal();
- }
- private void OnDeserializedInternal()
- {
- if (m_objSet != null) //v1.x case
- {
- if (m_cElt == 1)
- m_Obj = m_objSet[m_maxIndex];
- else
- m_Set = m_objSet;
- m_objSet = null;
- }
- // Nothing to do for the v2.0 and beyond case
- }
-
- [OnSerializing]
- private void OnSerializing(StreamingContext ctx)
- {
-
- if ((ctx.State & ~(StreamingContextStates.Clone|StreamingContextStates.CrossAppDomain)) != 0)
- {
- //Nothing special for the v2 and beyond case
-
- // for the v1.x case, we need to create m_objSet if necessary
- if (m_cElt == 1)
- {
- m_objSet = new Object[m_maxIndex+1];
- m_objSet[m_maxIndex] = m_Obj;
- }
- else if (m_cElt > 0)
- {
- // Array case:
- m_objSet = m_Set;
- }
-
- }
- }
- [OnSerialized]
- private void OnSerialized(StreamingContext ctx)
- {
- if ((ctx.State & ~(StreamingContextStates.Clone|StreamingContextStates.CrossAppDomain)) != 0)
- {
- m_objSet = null;
-
- }
- }
-
-
- internal bool MoveNext(ref TokenBasedSetEnumerator e)
- {
- switch (m_cElt)
- {
- case 0:
- return false;
-
- case 1:
- if (e.Index == -1)
- {
- e.Index = m_maxIndex;
- e.Current = m_Obj;
- return true;
- }
- else
- {
- e.Index = (short)(m_maxIndex+1);
- e.Current = null;
- return false;
- }
-
- default:
- while (++e.Index <= m_maxIndex)
- {
- e.Current = Volatile.Read(ref m_Set[e.Index]);
-
- if (e.Current != null)
- return true;
- }
-
- e.Current = null;
- return false;
- }
- }
-
- internal TokenBasedSet()
- {
- Reset();
- }
-
- [SuppressMessage("Microsoft.Concurrency", "CA8001", Justification = "Reviewed for thread safety")]
- internal TokenBasedSet(TokenBasedSet tbSet)
- {
- if (tbSet == null)
- {
- Reset();
- return;
- }
-
- if (tbSet.m_cElt > 1)
- {
- Object[] aObj = tbSet.m_Set;
- int aLen = aObj.Length;
-
- Object[] aNew = new Object[aLen];
- System.Array.Copy(aObj, 0, aNew, 0, aLen);
-
- m_Set = aNew;
- }
- else
- {
- m_Obj = tbSet.m_Obj;
- }
-
- m_cElt = tbSet.m_cElt;
- m_maxIndex = tbSet.m_maxIndex;
- }
-
- internal void Reset()
- {
- m_Obj = null;
- m_Set = null;
- m_cElt = 0;
- m_maxIndex = -1;
- }
-
- internal void SetItem(int index, Object item)
- {
- Object[] aObj = null;
-
- if (item == null)
- {
- RemoveItem(index);
- return;
- }
-
- switch (m_cElt)
- {
- case 0:
- // on the first item, we don't create an array, we merely remember it's index and value
- // this this the 99% case
- m_cElt = 1;
- m_maxIndex = (short)index;
- m_Obj = item;
- break;
-
- case 1:
- // we have to decide if a 2nd item has indeed been added and create the array
- // if it has
- if (index == m_maxIndex)
- {
- // replacing the one existing item
- m_Obj = item;
- }
- else
- {
- // adding a second distinct permission
- Object objSaved = m_Obj;
- int iMax = Math.Max(m_maxIndex, index);
-
- aObj = new Object[iMax+1];
- aObj[m_maxIndex] = objSaved;
- aObj[index] = item;
- m_maxIndex = (short)iMax;
- m_cElt = 2;
- m_Set = aObj;
- m_Obj = null;
- }
- break;
-
- default:
- // this is the general case code for when there is really an array
-
- aObj = m_Set;
-
- // we are now adding an item, check if we need to grow
-
- if (index >= aObj.Length)
- {
- Object[] newset = new Object[index+1];
- System.Array.Copy(aObj, 0, newset, 0, m_maxIndex+1);
- m_maxIndex = (short)index;
- newset[index] = item;
- m_Set = newset;
- m_cElt++;
- }
- else
- {
- if (aObj[index] == null)
- m_cElt++;
-
- aObj[index] = item;
-
- if (index > m_maxIndex)
- m_maxIndex = (short)index;
- }
- break;
- }
- }
-
- [SuppressMessage("Microsoft.Concurrency", "CA8001", Justification = "Reviewed for thread-safety")]
- internal Object GetItem(int index)
- {
- switch (m_cElt)
- {
- case 0:
- return null;
-
- case 1:
- if (index == m_maxIndex)
- return m_Obj;
- else
- return null;
- default:
- if (index < m_Set.Length)
- return Volatile.Read(ref m_Set[index]);
- else
- return null;
- }
- }
-
- internal Object RemoveItem(int index)
- {
- Object ret = null;
-
- switch (m_cElt)
- {
- case 0:
- ret = null;
- break;
-
- case 1:
- if (index != m_maxIndex)
- {
- // removing a permission we don't have ignore it
- ret = null;
- }
- else
- {
- // removing the permission we have at the moment
- ret = m_Obj;
- Reset();
- }
- break;
-
- default:
- // this is the general case code for when there is really an array
-
- // we are removing an item
- if (index < m_Set.Length && (ret = Volatile.Read(ref m_Set[index])) != null)
- {
- // ok we really deleted something at this point
-
- Volatile.Write(ref m_Set[index], null);
- m_cElt--;
-
- if (index == m_maxIndex)
- ResetMaxIndex(m_Set);
-
- // collapse the array
- if (m_cElt == 1)
- {
- m_Obj = Volatile.Read(ref m_Set[m_maxIndex]);
- m_Set = null;
- }
- }
- break;
- }
-
- return ret;
- }
-
- private void ResetMaxIndex(Object[] aObj)
- {
- int i;
-
- // Start at the end of the array, and
- // scan backwards for the first non-null
- // slot. That is the new maxIndex.
- for (i = aObj.Length - 1; i >= 0; i--)
- {
- if (aObj[i] != null)
- {
- m_maxIndex = (short)i;
- return;
- }
- }
-
- m_maxIndex = -1;
- }
- internal int GetStartingIndex()
- {
- if (m_cElt <= 1)
- return m_maxIndex;
- return 0;
- }
- internal int GetCount()
- {
- return m_cElt;
- }
-
- internal int GetMaxUsedIndex()
- {
- return m_maxIndex;
- }
-
- internal bool FastIsEmpty()
- {
- return m_cElt == 0;
- }
-
- // Used to merge two distinct TokenBasedSets (used currently only in PermissionSet Deserialization)
- internal TokenBasedSet SpecialUnion(TokenBasedSet other)
- {
- // This gets called from PermissionSet.OnDeserialized and it's possible that the TokenBasedSets have
- // not been subjected to VTS callbacks yet
- OnDeserializedInternal();
- TokenBasedSet unionSet = new TokenBasedSet();
- int maxMax;
- if (other != null)
- {
- other.OnDeserializedInternal();
- maxMax = this.GetMaxUsedIndex() > other.GetMaxUsedIndex() ? this.GetMaxUsedIndex() : other.GetMaxUsedIndex();
- }
- else
- maxMax = this.GetMaxUsedIndex();
-
- for (int i = 0; i <= maxMax; ++i)
- {
- Object thisObj = this.GetItem( i );
- IPermission thisPerm = thisObj as IPermission;
-
- Object otherObj = (other != null)?other.GetItem( i ):null;
- IPermission otherPerm = otherObj as IPermission;
-
- if (thisObj == null && otherObj == null)
- continue;
-
- if (thisObj == null)
- {
- PermissionToken token = PermissionToken.GetToken(otherPerm);
-
- if (token == null)
- {
- throw new SerializationException(Environment.GetResourceString("Serialization_InsufficientState"));
- }
-
- unionSet.SetItem(token.m_index, otherPerm);
- }
- else if (otherObj == null)
- {
- PermissionToken token = PermissionToken.GetToken(thisPerm);
- if (token == null)
- {
- throw new SerializationException(Environment.GetResourceString("Serialization_InsufficientState"));
- }
- unionSet.SetItem( token.m_index, thisPerm);
- }
- else
- {
- Debug.Assert( (thisObj == null || otherObj == null), "Permission cannot be in both TokenBasedSets" );
- }
- }
- return unionSet;
- }
-
- internal void SpecialSplit(ref TokenBasedSet unrestrictedPermSet, ref TokenBasedSet normalPermSet, bool ignoreTypeLoadFailures)
- {
- int maxIndex = GetMaxUsedIndex();
-
- for (int i = GetStartingIndex(); i <= maxIndex; ++i)
- {
- Object obj = GetItem( i );
- if (obj != null)
- {
- IPermission perm = obj as IPermission;
- PermissionToken token = PermissionToken.GetToken(perm);
-
- if (perm == null || token == null)
- continue;
-
- if (perm is IUnrestrictedPermission)
- {
- // Add to unrestrictedPermSet
- if (unrestrictedPermSet == null)
- unrestrictedPermSet = new TokenBasedSet();
- unrestrictedPermSet.SetItem(token.m_index, perm);
- }
- else
- {
- // Add to normalPermSet
- if (normalPermSet == null)
- normalPermSet = new TokenBasedSet();
- normalPermSet.SetItem(token.m_index, perm);
- }
-
- }
-
- }
-
- }
- }
-}
diff --git a/src/mscorlib/src/System/Security/Util/TokenBasedSetEnumerator.cs b/src/mscorlib/src/System/Security/Util/TokenBasedSetEnumerator.cs
deleted file mode 100644
index 9c868d3c53..0000000000
--- a/src/mscorlib/src/System/Security/Util/TokenBasedSetEnumerator.cs
+++ /dev/null
@@ -1,36 +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.Security.Util
-{
- using System;
- using System.Collections;
-
- internal struct TokenBasedSetEnumerator
- {
- public Object Current;
- public int Index;
-
- private TokenBasedSet _tb;
-
- public bool MoveNext()
- {
- return _tb != null ? _tb.MoveNext(ref this) : false;
- }
-
- public void Reset()
- {
- Index = -1;
- Current = null;
- }
-
- public TokenBasedSetEnumerator(TokenBasedSet tb)
- {
- Index = -1;
- Current = null;
- _tb = tb;
- }
- }
-}
-
diff --git a/src/mscorlib/src/System/Security/Util/URLString.cs b/src/mscorlib/src/System/Security/Util/URLString.cs
index 83f9ce483f..4ec353876a 100644
--- a/src/mscorlib/src/System/Security/Util/URLString.cs
+++ b/src/mscorlib/src/System/Security/Util/URLString.cs
@@ -22,368 +22,8 @@ namespace System.Security.Util {
using System.IO;
using System.Diagnostics.Contracts;
-#if FEATURE_SERIALIZATION
- [Serializable]
-#endif
- internal sealed class URLString : SiteString
+ internal static class URLString
{
- private String m_protocol;
- [OptionalField(VersionAdded = 2)]
- private String m_userpass;
- private SiteString m_siteString;
- private int m_port;
-#if !PLATFORM_UNIX
- private LocalSiteString m_localSite;
-#endif // !PLATFORM_UNIX
- private DirectoryString m_directory;
-
- private const String m_defaultProtocol = "file";
-
- [OptionalField(VersionAdded = 2)]
- private bool m_parseDeferred;
- [OptionalField(VersionAdded = 2)]
- private String m_urlOriginal;
- [OptionalField(VersionAdded = 2)]
- private bool m_parsedOriginal;
-
- [OptionalField(VersionAdded = 3)]
- private bool m_isUncShare;
-
- // legacy field from v1.x, not used in v2 and beyond. Retained purely for serialization compatibility.
- private String m_fullurl;
-
-
- [OnDeserialized]
- public void OnDeserialized(StreamingContext ctx)
- {
-
- if (m_urlOriginal == null)
- {
- // pre-v2 deserialization. Need to fix-up fields here
- m_parseDeferred = false;
- m_parsedOriginal = false; // Dont care what this value is - never used
- m_userpass = "";
- m_urlOriginal = m_fullurl;
- m_fullurl = null;
- }
- }
- [OnSerializing]
- private void OnSerializing(StreamingContext ctx)
- {
-
- if ((ctx.State & ~(StreamingContextStates.Clone|StreamingContextStates.CrossAppDomain)) != 0)
- {
- DoDeferredParse();
- m_fullurl = m_urlOriginal;
- }
- }
- [OnSerialized]
- private void OnSerialized(StreamingContext ctx)
- {
- if ((ctx.State & ~(StreamingContextStates.Clone|StreamingContextStates.CrossAppDomain)) != 0)
- {
- m_fullurl = null;
- }
- }
-
- public URLString()
- {
- m_protocol = "";
- m_userpass = "";
- m_siteString = new SiteString();
- m_port = -1;
-#if !PLATFORM_UNIX
- m_localSite = null;
-#endif // !PLATFORM_UNIX
- m_directory = new DirectoryString();
- m_parseDeferred = false;
- }
-
- private void DoDeferredParse()
- {
- if (m_parseDeferred)
- {
- ParseString(m_urlOriginal, m_parsedOriginal);
- m_parseDeferred = false;
- }
- }
-
- public URLString(string url) : this(url, false, false) {}
- public URLString(string url, bool parsed) : this(url, parsed, false) {}
-
- internal URLString(string url, bool parsed, bool doDeferredParsing)
- {
- m_port = -1;
- m_userpass = "";
- DoFastChecks(url);
- m_urlOriginal = url;
- m_parsedOriginal = parsed;
- m_parseDeferred = true;
- if (doDeferredParsing)
- DoDeferredParse();
- }
-
- // Converts %XX and %uYYYY to the actual characters (I.e. Unesacpes any escape characters present in the URL)
- private String UnescapeURL(String url)
- {
- StringBuilder intermediate = StringBuilderCache.Acquire(url.Length);
- int Rindex = 0; // index into temp that gives the rest of the string to be processed
- int index;
- int braIndex = -1;
- int ketIndex = -1;
- braIndex = url.IndexOf('[',Rindex);
- if (braIndex != -1)
- ketIndex = url.IndexOf(']', braIndex);
-
- do
- {
- index = url.IndexOf( '%', Rindex);
-
- if (index == -1)
- {
- intermediate = intermediate.Append(url, Rindex, (url.Length - Rindex));
- break;
- }
- // if we hit a '%' in the middle of an IPv6 address, dont process that
- if (index > braIndex && index < ketIndex)
- {
- intermediate = intermediate.Append(url, Rindex, (ketIndex - Rindex+1));
- Rindex = ketIndex+1;
- continue;
- }
-
- if (url.Length - index < 2) // Check that there is at least 1 char after the '%'
- throw new ArgumentException( Environment.GetResourceString( "Argument_InvalidUrl" ) );
-
- if (url[index+1] == 'u' || url[index+1] == 'U')
- {
- if (url.Length - index < 6) // example: "%u004d" is 6 chars long
- throw new ArgumentException( Environment.GetResourceString( "Argument_InvalidUrl" ) );
-
- // We have a unicode character specified in hex
-
- try
- {
- char c = (char)(Hex.ConvertHexDigit( url[index+2] ) << 12 |
- Hex.ConvertHexDigit( url[index+3] ) << 8 |
- Hex.ConvertHexDigit( url[index+4] ) << 4 |
- Hex.ConvertHexDigit( url[index+5] ));
- intermediate = intermediate.Append(url, Rindex, index - Rindex);
- intermediate = intermediate.Append(c);
- }
- catch(ArgumentException) // Hex.ConvertHexDigit can throw an "out of range" ArgumentException
- {
- throw new ArgumentException( Environment.GetResourceString( "Argument_InvalidUrl" ) );
- }
-
- Rindex = index + 6 ; //update the 'seen' length
- }
- else
- {
- // we have a hex character.
-
- if (url.Length - index < 3) // example: "%4d" is 3 chars long
- throw new ArgumentException( Environment.GetResourceString( "Argument_InvalidUrl" ) );
-
- try
- {
- char c = (char)(Hex.ConvertHexDigit( url[index+1] ) << 4 | Hex.ConvertHexDigit( url[index+2] ));
-
- intermediate = intermediate.Append(url, Rindex, index - Rindex);
- intermediate = intermediate.Append(c);
- }
- catch(ArgumentException) // Hex.ConvertHexDigit can throw an "out of range" ArgumentException
- {
- throw new ArgumentException( Environment.GetResourceString( "Argument_InvalidUrl" ) );
- }
-
- Rindex = index + 3; // update the 'seen' length
- }
-
- }
- while (true);
- return StringBuilderCache.GetStringAndRelease(intermediate);
- }
-
- // Helper Function for ParseString:
- // Search for the end of the protocol info and grab the actual protocol string
- // ex. http://www.microsoft.com/complus would have a protocol string of http
- private String ParseProtocol(String url)
- {
- String temp;
- int index = url.IndexOf( ':' );
-
- if (index == 0)
- {
- throw new ArgumentException( Environment.GetResourceString( "Argument_InvalidUrl" ) );
- }
- else if (index == -1)
- {
- m_protocol = m_defaultProtocol;
- temp = url;
- }
- else if (url.Length > index + 1)
- {
- if (index == m_defaultProtocol.Length &&
- String.Compare(url, 0, m_defaultProtocol, 0, index, StringComparison.OrdinalIgnoreCase) == 0)
- {
- m_protocol = m_defaultProtocol;
- temp = url.Substring( index + 1 );
-
- // Since an explicit file:// URL could be immediately followed by a host name, we will be
- // conservative and assume that it is on a share rather than a potentally relative local
- // URL.
- m_isUncShare = true;
- }
- else if (url[index+1] != '\\')
- {
-#if !PLATFORM_UNIX
- if (url.Length > index + 2 &&
- url[index+1] == '/' &&
- url[index+2] == '/')
-#else
- if (url.Length > index + 1 &&
- url[index+1] == '/' ) // UNIX style "file:/home/me" is allowed, so account for that
-#endif // !PLATFORM_UNIX
- {
- m_protocol = url.Substring( 0, index );
-
- for (int i = 0; i < m_protocol.Length; ++i)
- {
- char c = m_protocol[i];
-
- if ((c >= 'a' && c <= 'z') ||
- (c >= 'A' && c <= 'Z') ||
- (c >= '0' && c <= '9') ||
- (c == '+') ||
- (c == '.') ||
- (c == '-'))
- {
- continue;
- }
- else
- {
- throw new ArgumentException( Environment.GetResourceString( "Argument_InvalidUrl" ) );
- }
- }
-#if !PLATFORM_UNIX
- temp = url.Substring( index + 3 );
-#else
- // In UNIX, we don't know how many characters we'll have to skip past.
- // Skip past \, /, and :
- //
- for ( int j=index ; j<url.Length ; j++ )
- {
- if ( url[j] != '\\' && url[j] != '/' && url[j] != ':' )
- {
- index = j;
- break;
- }
- }
-
- temp = url.Substring( index );
-#endif // !PLATFORM_UNIX
- }
- else
- {
- throw new ArgumentException( Environment.GetResourceString( "Argument_InvalidUrl" ) );
- }
- }
- else
- {
- m_protocol = m_defaultProtocol;
- temp = url;
- }
- }
- else
- {
- throw new ArgumentException( Environment.GetResourceString( "Argument_InvalidUrl" ) );
- }
-
- return temp;
- }
-
- private String ParsePort(String url)
- {
- String temp = url;
- char[] separators = new char[] { ':', '/' };
- int Rindex = 0;
- int userpassIndex = temp.IndexOf('@');
- if (userpassIndex != -1) {
- if (temp.IndexOf('/',0,userpassIndex) == -1) {
- // this is a user:pass type of string
- m_userpass = temp.Substring(0,userpassIndex);
- Rindex = userpassIndex + 1;
- }
- }
-
- int braIndex = -1;
- int ketIndex = -1;
- int portIndex = -1;
- braIndex = url.IndexOf('[',Rindex);
- if (braIndex != -1)
- ketIndex = url.IndexOf(']', braIndex);
- if (ketIndex != -1)
- {
- // IPv6 address...ignore the IPv6 block when searching for the port
- portIndex = temp.IndexOfAny(separators,ketIndex);
- }
- else
- {
- portIndex = temp.IndexOfAny(separators,Rindex);
- }
-
-
-
- if (portIndex != -1 && temp[portIndex] == ':')
- {
- // make sure it really is a port, and has a number after the :
- if ( temp[portIndex+1] >= '0' && temp[portIndex+1] <= '9' )
- {
- int tempIndex = temp.IndexOf( '/', Rindex);
-
- if (tempIndex == -1)
- {
- m_port = Int32.Parse( temp.Substring(portIndex + 1), CultureInfo.InvariantCulture );
-
- if (m_port < 0)
- throw new ArgumentException( Environment.GetResourceString( "Argument_InvalidUrl" ) );
-
- temp = temp.Substring( Rindex, portIndex - Rindex );
- }
- else if (tempIndex > portIndex)
- {
- m_port = Int32.Parse( temp.Substring(portIndex + 1, tempIndex - portIndex - 1), CultureInfo.InvariantCulture );
- temp = temp.Substring( Rindex, portIndex - Rindex ) + temp.Substring( tempIndex );
- }
- else
- throw new ArgumentException( Environment.GetResourceString( "Argument_InvalidUrl" ) );
- }
- else
- throw new ArgumentException( Environment.GetResourceString( "Argument_InvalidUrl" ) );
- }
- else {
- // Chop of the user/pass portion if any
- temp = temp.Substring(Rindex);
- }
-
- return temp;
- }
-
- // This does three things:
- // 1. It makes the following modifications to the start of the string:
- // a. \\?\ and \\?/ => <empty>
- // b. \\.\ and \\./ => <empty>
- // 2. If isFileUrl is true, converts all slashes to front slashes and strips leading
- // front slashes. See comment by code.
- // 3. Throws a PathTooLongException if the length of the resulting URL is >= MAX_PATH.
- // This is done to prevent security issues due to canonicalization truncations.
- // Remove this method when the Path class supports "\\?\"
- internal static string PreProcessForExtendedPathRemoval(string url, bool isFileUrl)
- {
- return PreProcessForExtendedPathRemoval(checkPathLength: true, url: url, isFileUrl: isFileUrl);
- }
-
internal static string PreProcessForExtendedPathRemoval(bool checkPathLength, string url, bool isFileUrl)
{
bool isUncShare = false;
@@ -417,7 +57,8 @@ namespace System.Security.Util {
}
else
{
- if (isFileUrl) {
+ if (isFileUrl)
+ {
// We need to handle an indefinite number of leading front slashes for file URLs since we could
// get something like:
// file://\\?\
@@ -449,14 +90,14 @@ namespace System.Security.Util {
{
int slashCount = 0;
bool seenFirstBackslash = false;
-
+
while (slashCount < modifiedUrl.Length && (modifiedUrl[slashCount] == '/' || modifiedUrl[slashCount] == '\\'))
{
// Look for sets of consecutive backslashes. We can't just look for these at the start
// of the string, since file:// might come first. Instead, once we see the first \, look
// for a second one following it.
if (!seenFirstBackslash && modifiedUrl[slashCount] == '\\')
- {
+ {
seenFirstBackslash = true;
if (slashCount + 1 < modifiedUrl.Length && modifiedUrl[slashCount + 1] == '\\')
isUncShare = true;
@@ -493,873 +134,5 @@ namespace System.Security.Util {
throw new PathTooLongException(Environment.GetResourceString("IO.PathTooLong"));
}
}
-
- // Do any misc massaging of data in the URL
- private String PreProcessURL(String url, bool isFileURL)
- {
-
-#if !PLATFORM_UNIX
- if (isFileURL) {
- // Remove when the Path class supports "\\?\"
- url = PreProcessForExtendedPathRemoval(url, true, ref m_isUncShare);
- }
- else {
- url = url.Replace('\\', '/');
- }
- return url;
-#else
- // Remove superfluous '/'
- // For UNIX, the file path would look something like:
- // file:///home/johndoe/here
- // file:/home/johndoe/here
- // file:../johndoe/here
- // file:~/johndoe/here
- String temp = url;
- int nbSlashes = 0;
- while(nbSlashes<temp.Length && '/'==temp[nbSlashes])
- nbSlashes++;
-
- // if we get a path like file:///directory/name we need to convert
- // this to /directory/name.
- if(nbSlashes > 2)
- temp = temp.Substring(nbSlashes-1, temp.Length - (nbSlashes-1));
- else if (2 == nbSlashes) /* it's a relative path */
- temp = temp.Substring(nbSlashes, temp.Length - nbSlashes);
- return temp;
-#endif // !PLATFORM_UNIX
-
- }
-
- private void ParseFileURL(String url)
- {
-
- String temp = url;
-#if !PLATFORM_UNIX
- int index = temp.IndexOf( '/');
-
- if (index != -1 &&
- ((index == 2 &&
- temp[index-1] != ':' &&
- temp[index-1] != '|') ||
- index != 2) &&
- index != temp.Length - 1)
- {
- // Also, if it is a UNC share, we want m_localSite to
- // be of the form "computername/share", so if the first
- // fileEnd character found is a slash, do some more parsing
- // to find the proper end character.
-
- int tempIndex = temp.IndexOf( '/', index+1);
-
- if (tempIndex != -1)
- index = tempIndex;
- else
- index = -1;
- }
-
- String localSite;
- if (index == -1)
- localSite = temp;
- else
- localSite = temp.Substring(0,index);
-
- if (localSite.Length == 0)
- throw new ArgumentException( Environment.GetResourceString( "Argument_InvalidUrl" ) );
-
- int i;
- bool spacesAllowed;
-
- if (localSite[0] == '\\' && localSite[1] == '\\')
- {
- spacesAllowed = true;
- i = 2;
- }
- else
- {
- i = 0;
- spacesAllowed = false;
- }
-
- bool useSmallCharToUpper = true;
-
- for (; i < localSite.Length; ++i)
- {
- char c = localSite[i];
-
- if ((c >= 'A' && c <= 'Z') ||
- (c >= 'a' && c <= 'z') ||
- (c >= '0' && c <= '9') ||
- (c == '-') || (c == '/') ||
- (c == ':') || (c == '|') ||
- (c == '.') || (c == '*') ||
- (c == '$') || (spacesAllowed && c == ' '))
- {
- continue;
- }
- else
- {
- useSmallCharToUpper = false;
- break;
- }
- }
-
- if (useSmallCharToUpper)
- localSite = String.SmallCharToUpper( localSite );
- else
- localSite = localSite.ToUpper(CultureInfo.InvariantCulture);
-
- m_localSite = new LocalSiteString( localSite );
-
- if (index == -1)
- {
- if (localSite[localSite.Length-1] == '*')
- m_directory = new DirectoryString( "*", false );
- else
- m_directory = new DirectoryString();
- }
- else
- {
- String directoryString = temp.Substring( index + 1 );
- if (directoryString.Length == 0)
- {
- m_directory = new DirectoryString();
- }
- else
- {
- m_directory = new DirectoryString( directoryString, true);
- }
- }
-#else // !PLATFORM_UNIX
- m_directory = new DirectoryString( temp, true);
-#endif // !PLATFORM_UNIX
-
- m_siteString = null;
- return;
- }
-
- private void ParseNonFileURL(String url)
- {
- String temp = url;
- int index = temp.IndexOf('/');
-
- if (index == -1)
- {
-#if !PLATFORM_UNIX
- m_localSite = null; // for drive letter
-#endif // !PLATFORM_UNIX
- m_siteString = new SiteString( temp );
- m_directory = new DirectoryString();
- }
- else
- {
-#if !PLATFORM_UNIX
- String site = temp.Substring( 0, index );
- m_localSite = null;
- m_siteString = new SiteString( site );
-
- String directoryString = temp.Substring( index + 1 );
-
- if (directoryString.Length == 0)
- {
- m_directory = new DirectoryString();
- }
- else
- {
- m_directory = new DirectoryString( directoryString, false );
- }
-#else
- String directoryString = temp.Substring( index + 1 );
- String site = temp.Substring( 0, index );
- m_directory = new DirectoryString( directoryString, false );
- m_siteString = new SiteString( site );
-#endif //!PLATFORM_UNIX
- }
- return;
- }
-
- void DoFastChecks( String url )
- {
- if (url == null)
- {
- throw new ArgumentNullException( nameof(url) );
- }
- Contract.EndContractBlock();
-
- if (url.Length == 0)
- {
- throw new FormatException(Environment.GetResourceString("Format_StringZeroLength"));
- }
- }
-
- // NOTE:
- // 1. We support URLs that follow the common Internet scheme syntax
- // (<scheme>://user:pass@<host>:<port>/<url-path>) and all windows file URLs.
- // 2. In the general case we parse of the site and create a SiteString out of it
- // (which supports our wildcarding scheme). In the case of files we don't support
- // wildcarding and furthermore SiteString doesn't like ':' and '|' which can appear
- // in file urls so we just keep that info in a separate string and set the
- // SiteString to null.
- //
- // ex. http://www.microsoft.com/complus -> m_siteString = "www.microsoft.com" m_localSite = null
- // ex. file:///c:/complus/mscorlib.dll -> m_siteString = null m_localSite = "c:"
- // ex. file:///c|/complus/mscorlib.dll -> m_siteString = null m_localSite = "c:"
- void ParseString( String url, bool parsed )
- {
- // If there are any escaped hex or unicode characters in the url, translate those
- // into the proper character.
-
- if (!parsed)
- {
- url = UnescapeURL(url);
- }
-
- // Identify the protocol and strip the protocol info from the string, if present.
- String temp = ParseProtocol(url);
-
- bool fileProtocol = (String.Compare( m_protocol, "file", StringComparison.OrdinalIgnoreCase) == 0);
-
- // handle any special preocessing...removing extra characters, etc.
- temp = PreProcessURL(temp, fileProtocol);
-
- if (fileProtocol)
- {
- ParseFileURL(temp);
- }
- else
- {
- // Check if there is a port number and parse that out.
- temp = ParsePort(temp);
- ParseNonFileURL(temp);
- // Note: that we allow DNS and Netbios names for non-file protocols (since sitestring will check
- // that the hostname satisfies these two protocols. DNS-only checking can theoretically be added
- // here but that would break all the programs that use '_' (which is fairly common, yet illegal).
- // If this needs to be done at any point, add a call to m_siteString.IsLegalDNSName().
- }
-
-
- }
-
- public String Scheme
- {
- get
- {
- DoDeferredParse();
-
- return m_protocol;
- }
- }
-
- public String Host
- {
- get
- {
- DoDeferredParse();
-
- if (m_siteString != null)
- {
- return m_siteString.ToString();
- }
- else
- {
-#if !PLATFORM_UNIX
- return m_localSite.ToString();
-#else
- return "";
-#endif // !PLATFORM_UNIX
- }
- }
- }
-
- public String Port
- {
- get
- {
- DoDeferredParse();
-
- if (m_port == -1)
- return null;
- else
- return m_port.ToString(CultureInfo.InvariantCulture);
- }
- }
-
- public String Directory
- {
- get
- {
- DoDeferredParse();
-
- return m_directory.ToString();
- }
- }
-
- /// <summary>
- /// Make a best guess at determining if this is URL refers to a file with a relative path. Since
- /// this is a guess to help out users of UrlMembershipCondition who may accidentally supply a
- /// relative URL, we'd rather err on the side of absolute than relative. (We'd rather accept some
- /// meaningless membership conditions rather than reject meaningful ones).
- ///
- /// In order to be a relative file URL, the URL needs to have a protocol of file, and not be on a
- /// UNC share.
- ///
- /// If both of the above are true, then the heuristics we'll use to detect an absolute URL are:
- /// 1. A host name which is:
- /// a. greater than one character and ends in a colon (representing the drive letter) OR
- /// b. ends with a * (so we match any file with the given prefix if any)
- /// 2. Has a directory name (cannot be simply file://c:)
- /// </summary>
- public bool IsRelativeFileUrl
- {
- get
- {
- DoDeferredParse();
-
- if (String.Equals(m_protocol, "file", StringComparison.OrdinalIgnoreCase) && !m_isUncShare)
- {
-#if !PLATFORM_UNIX
- string host = m_localSite != null ? m_localSite.ToString() : null;
- // If the host name ends with the * character, treat this as an absolute URL since the *
- // could represent the rest of the full path.
- if (host.EndsWith('*'))
- return false;
-#endif // !PLATFORM_UNIX
- string directory = m_directory != null ? m_directory.ToString() : null;
-
-#if !PLATFORM_UNIX
- return host == null || host.Length < 2 || !host.EndsWith(':') ||
- String.IsNullOrEmpty(directory);
-#else
- return String.IsNullOrEmpty(directory);
-#endif // !PLATFORM_UNIX
-
- }
-
- // Since this is not a local URL, it cannot be relative
- return false;
- }
- }
-
- public String GetFileName()
- {
- DoDeferredParse();
-
-#if !PLATFORM_UNIX
- if (String.Compare( m_protocol, "file", StringComparison.OrdinalIgnoreCase) != 0)
- return null;
-
- String intermediateDirectory = this.Directory.Replace( '/', '\\' );
-
- String directory = this.Host.Replace( '/', '\\' );
-
- int directorySlashIndex = directory.IndexOf( '\\' );
- if (directorySlashIndex == -1)
- {
- if (directory.Length != 2 ||
- !(directory[1] == ':' || directory[1] == '|'))
- {
- directory = "\\\\" + directory;
- }
- }
- else if (directorySlashIndex != 2 ||
- (directorySlashIndex == 2 && directory[1] != ':' && directory[1] != '|'))
- {
- directory = "\\\\" + directory;
- }
-
- directory += "\\" + intermediateDirectory;
-
- return directory;
-#else
- // In Unix, directory contains the full pathname
- // (this is what we get in Win32)
- if (String.Compare( m_protocol, "file", StringComparison.OrdinalIgnoreCase ) != 0)
- return null;
-
- return this.Directory;
-#endif // !PLATFORM_UNIX
- }
-
-
- public String GetDirectoryName()
- {
- DoDeferredParse();
-
-#if !PLATFORM_UNIX
- if (String.Compare( m_protocol, "file", StringComparison.OrdinalIgnoreCase ) != 0)
- return null;
-
- String intermediateDirectory = this.Directory.Replace( '/', '\\' );
-
- int slashIndex = 0;
- for (int i = intermediateDirectory.Length; i > 0; i--)
- {
- if (intermediateDirectory[i-1] == '\\')
- {
- slashIndex = i;
- break;
- }
- }
-
- String directory = this.Host.Replace( '/', '\\' );
-
- int directorySlashIndex = directory.IndexOf( '\\' );
- if (directorySlashIndex == -1)
- {
- if (directory.Length != 2 ||
- !(directory[1] == ':' || directory[1] == '|'))
- {
- directory = "\\\\" + directory;
- }
- }
- else if (directorySlashIndex > 2 ||
- (directorySlashIndex == 2 && directory[1] != ':' && directory[1] != '|'))
- {
- directory = "\\\\" + directory;
- }
-
- directory += "\\";
-
- if (slashIndex > 0)
- {
- directory += intermediateDirectory.Substring( 0, slashIndex );
- }
-
- return directory;
-#else
- if (String.Compare( m_protocol, "file", StringComparison.OrdinalIgnoreCase) != 0)
- return null;
-
- String directory = this.Directory.ToString();
- int slashIndex = 0;
- for (int i = directory.Length; i > 0; i--)
- {
- if (directory[i-1] == '/')
- {
- slashIndex = i;
- break;
- }
- }
-
- if (slashIndex > 0)
- {
- directory = directory.Substring( 0, slashIndex );
- }
-
- return directory;
-#endif // !PLATFORM_UNIX
- }
-
- public override SiteString Copy()
- {
- return new URLString( m_urlOriginal, m_parsedOriginal );
- }
-
- public override bool IsSubsetOf( SiteString site )
- {
- if (site == null)
- {
- return false;
- }
-
- URLString url = site as URLString;
-
- if (url == null)
- {
- return false;
- }
-
- DoDeferredParse();
- url.DoDeferredParse();
-
- URLString normalUrl1 = this.SpecialNormalizeUrl();
- URLString normalUrl2 = url.SpecialNormalizeUrl();
-
- if (String.Compare( normalUrl1.m_protocol, normalUrl2.m_protocol, StringComparison.OrdinalIgnoreCase) == 0 &&
- normalUrl1.m_directory.IsSubsetOf( normalUrl2.m_directory ))
- {
-#if !PLATFORM_UNIX
- if (normalUrl1.m_localSite != null)
- {
- // We do a little extra processing in here for local files since we allow
- // both <drive_letter>: and <drive_letter>| forms of urls.
-
- return normalUrl1.m_localSite.IsSubsetOf( normalUrl2.m_localSite );
- }
- else
-#endif // !PLATFORM_UNIX
- {
- if (normalUrl1.m_port != normalUrl2.m_port)
- return false;
-
- return normalUrl2.m_siteString != null && normalUrl1.m_siteString.IsSubsetOf( normalUrl2.m_siteString );
- }
- }
- else
- {
- return false;
- }
- }
-
- public override String ToString()
- {
- return m_urlOriginal;
- }
-
- public override bool Equals(Object o)
- {
- DoDeferredParse();
-
- if (o == null || !(o is URLString))
- return false;
- else
- return this.Equals( (URLString)o );
- }
-
- public override int GetHashCode()
- {
- DoDeferredParse();
-
- TextInfo info = CultureInfo.InvariantCulture.TextInfo;
- int accumulator = 0;
-
- if (this.m_protocol != null)
- accumulator = info.GetCaseInsensitiveHashCode( this.m_protocol );
-
-#if !PLATFORM_UNIX
- if (this.m_localSite != null)
- {
- accumulator = accumulator ^ this.m_localSite.GetHashCode();
- }
- else
- {
- accumulator = accumulator ^ this.m_siteString.GetHashCode();
- }
- accumulator = accumulator ^ this.m_directory.GetHashCode();
-#else
- accumulator = accumulator ^ info.GetCaseInsensitiveHashCode(this.m_urlOriginal);
-#endif // !PLATFORM_UNIX
-
-
-
- return accumulator;
- }
-
- public bool Equals( URLString url )
- {
- return CompareUrls( this, url );
- }
-
- public static bool CompareUrls( URLString url1, URLString url2 )
- {
- if (url1 == null && url2 == null)
- return true;
-
- if (url1 == null || url2 == null)
- return false;
-
- url1.DoDeferredParse();
- url2.DoDeferredParse();
-
- URLString normalUrl1 = url1.SpecialNormalizeUrl();
- URLString normalUrl2 = url2.SpecialNormalizeUrl();
-
- // Compare protocol (case insensitive)
-
- if (String.Compare( normalUrl1.m_protocol, normalUrl2.m_protocol, StringComparison.OrdinalIgnoreCase) != 0)
- return false;
-
- // Do special processing for file urls
-
- if (String.Compare( normalUrl1.m_protocol, "file", StringComparison.OrdinalIgnoreCase) == 0)
- {
-#if !PLATFORM_UNIX
- if (!normalUrl1.m_localSite.IsSubsetOf( normalUrl2.m_localSite ) ||
- !normalUrl2.m_localSite.IsSubsetOf( normalUrl1.m_localSite ))
- return false;
-#else
- return url1.IsSubsetOf( url2 ) &&
- url2.IsSubsetOf( url1 );
-#endif // !PLATFORM_UNIX
- }
- else
- {
- if (String.Compare( normalUrl1.m_userpass, normalUrl2.m_userpass, StringComparison.Ordinal) != 0)
- return false;
-
- if (!normalUrl1.m_siteString.IsSubsetOf( normalUrl2.m_siteString ) ||
- !normalUrl2.m_siteString.IsSubsetOf( normalUrl1.m_siteString ))
- return false;
-
- if (url1.m_port != url2.m_port)
- return false;
- }
-
- if (!normalUrl1.m_directory.IsSubsetOf( normalUrl2.m_directory ) ||
- !normalUrl2.m_directory.IsSubsetOf( normalUrl1.m_directory ))
- return false;
-
- return true;
- }
-
- internal String NormalizeUrl()
- {
- DoDeferredParse();
- StringBuilder builtUrl = StringBuilderCache.Acquire();
-
- if (String.Compare( m_protocol, "file", StringComparison.OrdinalIgnoreCase) == 0)
- {
-#if !PLATFORM_UNIX
- builtUrl = builtUrl.AppendFormat("FILE:///{0}/{1}", m_localSite.ToString(), m_directory.ToString());
-#else
- builtUrl = builtUrl.AppendFormat("FILE:///{0}", m_directory.ToString());
-#endif // !PLATFORM_UNIX
- }
- else
- {
- builtUrl = builtUrl.AppendFormat("{0}://{1}{2}", m_protocol, m_userpass, m_siteString.ToString());
-
- if (m_port != -1)
- builtUrl = builtUrl.AppendFormat("{0}",m_port);
-
- builtUrl = builtUrl.AppendFormat("/{0}", m_directory.ToString());
- }
-
- return StringBuilderCache.GetStringAndRelease(builtUrl).ToUpper(CultureInfo.InvariantCulture);
- }
-
-#if !PLATFORM_UNIX
- internal URLString SpecialNormalizeUrl()
- {
- // Under WinXP, file protocol urls can be mapped to
- // drives that aren't actually file protocol underneath
- // due to drive mounting. This code attempts to figure
- // out what a drive is mounted to and create the
- // url is maps to.
-
- DoDeferredParse();
- if (String.Compare( m_protocol, "file", StringComparison.OrdinalIgnoreCase) != 0)
- {
- return this;
- }
- else
- {
- String localSite = m_localSite.ToString();
-
- if (localSite.Length == 2 &&
- (localSite[1] == '|' ||
- localSite[1] == ':'))
- {
- String deviceName = null;
- GetDeviceName(localSite, JitHelpers.GetStringHandleOnStack(ref deviceName));
-
- if (deviceName != null)
- {
- if (deviceName.IndexOf( "://", StringComparison.Ordinal ) != -1)
- {
- URLString u = new URLString( deviceName + "/" + this.m_directory.ToString() );
- u.DoDeferredParse(); // Presumably the caller of SpecialNormalizeUrl wants a fully parsed URL
- return u;
- }
- else
- {
- URLString u = new URLString( "file://" + deviceName + "/" + this.m_directory.ToString() );
- u.DoDeferredParse();// Presumably the caller of SpecialNormalizeUrl wants a fully parsed URL
- return u;
- }
- }
- else
- return this;
- }
- else
- {
- return this;
- }
- }
- }
-
- [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
- [SuppressUnmanagedCodeSecurity]
- private static extern void GetDeviceName( String driveLetter, StringHandleOnStack retDeviceName );
-
-#else
- internal URLString SpecialNormalizeUrl()
- {
- return this;
- }
-#endif // !PLATFORM_UNIX
-
- }
-
-
- [Serializable]
- internal class DirectoryString : SiteString
- {
- private bool m_checkForIllegalChars;
-
- private new static char[] m_separators = { '/' };
-
- // From KB #Q177506, file/folder illegal characters are \ / : * ? " < > |
- protected static char[] m_illegalDirectoryCharacters = { '\\', ':', '*', '?', '"', '<', '>', '|' };
-
- public DirectoryString()
- {
- m_site = "";
- m_separatedSite = new ArrayList();
- }
-
- public DirectoryString( String directory, bool checkForIllegalChars )
- {
- m_site = directory;
- m_checkForIllegalChars = checkForIllegalChars;
- m_separatedSite = CreateSeparatedString(directory);
- }
-
- private ArrayList CreateSeparatedString(String directory)
- {
- if (directory == null || directory.Length == 0)
- {
- throw new ArgumentException(Environment.GetResourceString("Argument_InvalidDirectoryOnUrl"));
- }
- Contract.EndContractBlock();
-
- ArrayList list = new ArrayList();
- String[] separatedArray = directory.Split(m_separators);
-
- for (int index = 0; index < separatedArray.Length; ++index)
- {
- if (separatedArray[index] == null || separatedArray[index].Equals( "" ))
- {
- // this case is fine, we just ignore it the extra separators.
- }
- else if (separatedArray[index].Equals( "*" ))
- {
- if (index != separatedArray.Length-1)
- {
- throw new ArgumentException(Environment.GetResourceString("Argument_InvalidDirectoryOnUrl"));
- }
- list.Add( separatedArray[index] );
- }
- else if (m_checkForIllegalChars && separatedArray[index].IndexOfAny( m_illegalDirectoryCharacters ) != -1)
- {
- throw new ArgumentException(Environment.GetResourceString("Argument_InvalidDirectoryOnUrl"));
- }
- else
- {
- list.Add( separatedArray[index] );
- }
- }
-
- return list;
- }
-
- public virtual bool IsSubsetOf( DirectoryString operand )
- {
- return this.IsSubsetOf( operand, true );
- }
-
- public virtual bool IsSubsetOf( DirectoryString operand, bool ignoreCase )
- {
- if (operand == null)
- {
- return false;
- }
- else if (operand.m_separatedSite.Count == 0)
- {
- return this.m_separatedSite.Count == 0 || this.m_separatedSite.Count > 0 && String.Compare((String)this.m_separatedSite[0], "*", StringComparison.Ordinal) == 0;
- }
- else if (this.m_separatedSite.Count == 0)
- {
- return String.Compare((String)operand.m_separatedSite[0], "*", StringComparison.Ordinal) == 0;
- }
- else
- {
- return base.IsSubsetOf( operand, ignoreCase );
- }
- }
- }
-
-#if !PLATFORM_UNIX
- [Serializable]
- internal class LocalSiteString : SiteString
- {
- private new static char[] m_separators = { '/' };
-
- public LocalSiteString( String site )
- {
- m_site = site.Replace( '|', ':');
-
- if (m_site.Length > 2 && m_site.IndexOf( ':' ) != -1)
- throw new ArgumentException(Environment.GetResourceString("Argument_InvalidDirectoryOnUrl"));
-
- m_separatedSite = CreateSeparatedString(m_site);
- }
-
- private ArrayList CreateSeparatedString(String directory)
- {
- if (directory == null || directory.Length == 0)
- {
- throw new ArgumentException(Environment.GetResourceString("Argument_InvalidDirectoryOnUrl"));
- }
- Contract.EndContractBlock();
-
- ArrayList list = new ArrayList();
- String[] separatedArray = directory.Split(m_separators);
-
- for (int index = 0; index < separatedArray.Length; ++index)
- {
- if (separatedArray[index] == null || separatedArray[index].Equals( "" ))
- {
- if (index < 2 &&
- directory[index] == '/')
- {
- list.Add( "//" );
- }
- else if (index != separatedArray.Length-1)
- {
- throw new ArgumentException(Environment.GetResourceString("Argument_InvalidDirectoryOnUrl"));
- }
- }
- else if (separatedArray[index].Equals( "*" ))
- {
- if (index != separatedArray.Length-1)
- {
- throw new ArgumentException(Environment.GetResourceString("Argument_InvalidDirectoryOnUrl"));
- }
- list.Add( separatedArray[index] );
- }
- else
- {
- list.Add( separatedArray[index] );
- }
- }
-
- return list;
- }
-
- public virtual bool IsSubsetOf( LocalSiteString operand )
- {
- return this.IsSubsetOf( operand, true );
- }
-
- public virtual bool IsSubsetOf( LocalSiteString operand, bool ignoreCase )
- {
- if (operand == null)
- {
- return false;
- }
- else if (operand.m_separatedSite.Count == 0)
- {
- return this.m_separatedSite.Count == 0 || this.m_separatedSite.Count > 0 && String.Compare((String)this.m_separatedSite[0], "*", StringComparison.Ordinal) == 0;
- }
- else if (this.m_separatedSite.Count == 0)
- {
- return String.Compare((String)operand.m_separatedSite[0], "*", StringComparison.Ordinal) == 0;
- }
- else
- {
- return base.IsSubsetOf( operand, ignoreCase );
- }
- }
}
-#endif // !PLATFORM_UNIX
}
diff --git a/src/mscorlib/src/System/Security/Util/XMLUtil.cs b/src/mscorlib/src/System/Security/Util/XMLUtil.cs
deleted file mode 100644
index 3a1aaa3b09..0000000000
--- a/src/mscorlib/src/System/Security/Util/XMLUtil.cs
+++ /dev/null
@@ -1,435 +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: Helpers for XML input & output
-**
-===========================================================*/
-namespace System.Security.Util {
-
- using System;
- using System.Security;
- using System.Security.Permissions;
- using System.Security.Policy;
- using System.Runtime.InteropServices;
- using System.Runtime.Remoting;
- using System.IO;
- using System.Text;
- using System.Runtime.CompilerServices;
- using PermissionState = System.Security.Permissions.PermissionState;
- using BindingFlags = System.Reflection.BindingFlags;
- using Assembly = System.Reflection.Assembly;
- using System.Threading;
- using System.Globalization;
- using System.Reflection;
- using System.Diagnostics;
- using System.Diagnostics.Contracts;
-
- internal static class XMLUtil
- {
- //
- // Warning: Element constructors have side-effects on their
- // third argument.
- //
-
- private const String BuiltInPermission = "System.Security.Permissions.";
-
- public static SecurityElement
- NewPermissionElement (IPermission ip)
- {
- return NewPermissionElement (ip.GetType ().FullName) ;
- }
-
- public static SecurityElement
- NewPermissionElement (String name)
- {
- SecurityElement ecr = new SecurityElement( "Permission" );
- ecr.AddAttribute( "class", name );
- return ecr;
- }
-
- public static void
- AddClassAttribute( SecurityElement element, Type type, String typename )
- {
- // Replace any quotes with apostrophes so that we can include quoted materials
- // within classnames. Notably the assembly name member 'loc' uses a quoted string.
-
- // NOTE: this makes assumptions as to what reflection is expecting for a type string
- // it will need to be updated if reflection changes what it wants.
-
- if ( typename == null )
- typename = 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( '\"', '\'' ) );
- }
-
- internal static bool ParseElementForAssemblyIdentification(SecurityElement el,
- out String className,
- out String assemblyName, // for example "WindowsBase"
- out String assemblyVersion)
- {
-
- className = null;
- assemblyName = null;
- assemblyVersion = null;
-
- String fullClassName = el.Attribute( "class" );
-
- if (fullClassName == null)
- {
- return false;
- }
- if (fullClassName.IndexOf('\'') >= 0)
- {
- fullClassName = fullClassName.Replace( '\'', '\"' );
- }
-
- int commaIndex = fullClassName.IndexOf( ',' );
- int namespaceClassNameLength;
-
- // If the classname is tagged with assembly information, find where
- // the assembly information begins.
-
- if (commaIndex == -1)
- {
- return false;
- }
-
- namespaceClassNameLength = commaIndex;
- className = fullClassName.Substring(0, namespaceClassNameLength);
- String assemblyFullName = fullClassName.Substring(commaIndex + 1);
- AssemblyName an = new AssemblyName(assemblyFullName);
- assemblyName = an.Name;
- assemblyVersion = an.Version.ToString();
- return true;
- }
- private static bool
- ParseElementForObjectCreation( SecurityElement el,
- String requiredNamespace,
- out String className,
- out int classNameStart,
- out int classNameLength )
- {
- className = null;
- classNameStart = 0;
- classNameLength = 0;
-
- int requiredNamespaceLength = requiredNamespace.Length;
-
- String fullClassName = el.Attribute( "class" );
-
- if (fullClassName == null)
- {
- throw new ArgumentException( Environment.GetResourceString( "Argument_NoClass" ) );
- }
-
- if (fullClassName.IndexOf('\'') >= 0)
- {
- fullClassName = fullClassName.Replace( '\'', '\"' );
- }
-
- if (!PermissionToken.IsMscorlibClassName( fullClassName ))
- {
- return false;
- }
-
- int commaIndex = fullClassName.IndexOf( ',' );
- int namespaceClassNameLength;
-
- // If the classname is tagged with assembly information, find where
- // the assembly information begins.
-
- if (commaIndex == -1)
- {
- namespaceClassNameLength = fullClassName.Length;
- }
- else
- {
- namespaceClassNameLength = commaIndex;
- }
-
- // Only if the length of the class name is greater than the namespace info
- // on our requiredNamespace do we continue
- // with our check.
-
- if (namespaceClassNameLength > requiredNamespaceLength)
- {
- // Make sure we are in the required namespace.
- if (fullClassName.StartsWith(requiredNamespace, StringComparison.Ordinal))
- {
- className = fullClassName;
- classNameLength = namespaceClassNameLength - requiredNamespaceLength;
- classNameStart = requiredNamespaceLength;
- return true;
- }
- }
-
- return false;
- }
-
- public static IPermission
- CreatePermission (SecurityElement el, PermissionState permState, bool ignoreTypeLoadFailures)
- {
- if (el == null || !(el.Tag.Equals("Permission") || el.Tag.Equals("IPermission")) )
- throw new ArgumentException( String.Format( null, Environment.GetResourceString( "Argument_WrongElementType" ), "<Permission>" ) ) ;
- Contract.EndContractBlock();
-
- String className;
- int classNameLength;
- int classNameStart;
-
- if (!ParseElementForObjectCreation( el,
- BuiltInPermission,
- out className,
- out classNameStart,
- out classNameLength ))
- {
- goto USEREFLECTION;
- }
-
- // We have a built in permission, figure out which it is.
-
- // UIPermission
- // FileIOPermission
- // SecurityPermission
- // PrincipalPermission
- // ReflectionPermission
- // FileDialogPermission
- // EnvironmentPermission
- // GacIdentityPermission
- // UrlIdentityPermission
- // SiteIdentityPermission
- // ZoneIdentityPermission
- // KeyContainerPermission
- // UnsafeForHostPermission
- // HostProtectionPermission
- // StrongNameIdentityPermission
- // RegistryPermission
- // PublisherIdentityPermission
-
- switch (classNameLength)
- {
- case 12:
- // UIPermission
- if (String.Compare(className, classNameStart, "UIPermission", 0, classNameLength, StringComparison.Ordinal) == 0)
- return new UIPermission( permState );
- else
- goto USEREFLECTION;
-
- case 16:
- // FileIOPermission
- if (String.Compare(className, classNameStart, "FileIOPermission", 0, classNameLength, StringComparison.Ordinal) == 0)
- return new FileIOPermission( permState );
- else
- goto USEREFLECTION;
-
- case 18:
- // RegistryPermission
- // SecurityPermission
- if (className[classNameStart] == 'R')
- {
- if (String.Compare(className, classNameStart, "RegistryPermission", 0, classNameLength, StringComparison.Ordinal) == 0)
- return new RegistryPermission( permState );
- else
- goto USEREFLECTION;
- }
- else
- {
- if (String.Compare(className, classNameStart, "SecurityPermission", 0, classNameLength, StringComparison.Ordinal) == 0)
- return new SecurityPermission( permState );
- else
- goto USEREFLECTION;
- }
- case 20:
- // ReflectionPermission
- // FileDialogPermission
- if (className[classNameStart] == 'R')
- {
- if (String.Compare(className, classNameStart, "ReflectionPermission", 0, classNameLength, StringComparison.Ordinal) == 0)
- return new ReflectionPermission( permState );
- else
- goto USEREFLECTION;
- }
- else
- {
- if (String.Compare(className, classNameStart, "FileDialogPermission", 0, classNameLength, StringComparison.Ordinal) == 0)
- return new FileDialogPermission( permState );
- else
- goto USEREFLECTION;
- }
-
- case 21:
- // EnvironmentPermission
- // UrlIdentityPermission
- // GacIdentityPermission
- if (className[classNameStart] == 'E')
- {
- if (String.Compare(className, classNameStart, "EnvironmentPermission", 0, classNameLength, StringComparison.Ordinal) == 0)
- return new EnvironmentPermission( permState );
- else
- goto USEREFLECTION;
- }
- else if (className[classNameStart] == 'U')
- {
- if (String.Compare(className, classNameStart, "UrlIdentityPermission", 0, classNameLength, StringComparison.Ordinal) == 0)
- return new UrlIdentityPermission( permState );
- else
- goto USEREFLECTION;
- }
- else
- {
- if (String.Compare(className, classNameStart, "GacIdentityPermission", 0, classNameLength, StringComparison.Ordinal) == 0)
- return new GacIdentityPermission( permState );
- else
- goto USEREFLECTION;
- }
- case 22:
- // SiteIdentityPermission
- // ZoneIdentityPermission
- // KeyContainerPermission
- if (className[classNameStart] == 'S')
- {
- if (String.Compare(className, classNameStart, "SiteIdentityPermission", 0, classNameLength, StringComparison.Ordinal) == 0)
- return new SiteIdentityPermission( permState );
- else
- goto USEREFLECTION;
- }
- else if (className[classNameStart] == 'Z')
- {
- if (String.Compare(className, classNameStart, "ZoneIdentityPermission", 0, classNameLength, StringComparison.Ordinal) == 0)
- return new ZoneIdentityPermission( permState );
- else
- goto USEREFLECTION;
- }
- else
- {
- if (String.Compare(className, classNameStart, "KeyContainerPermission", 0, classNameLength, StringComparison.Ordinal) == 0)
- return new KeyContainerPermission( permState );
- else
- goto USEREFLECTION;
- }
- case 24:
- // HostProtectionPermission
- if (String.Compare(className, classNameStart, "HostProtectionPermission", 0, classNameLength, StringComparison.Ordinal) == 0)
- return new HostProtectionPermission( permState );
- else
- goto USEREFLECTION;
- case 28:
- // StrongNameIdentityPermission
- if (String.Compare(className, classNameStart, "StrongNameIdentityPermission", 0, classNameLength, StringComparison.Ordinal) == 0)
- return new StrongNameIdentityPermission( permState );
- else
- goto USEREFLECTION;
- default:
- goto USEREFLECTION;
- }
-
-USEREFLECTION:
-
- Object[] objs = new Object[1];
- objs[0] = permState;
-
- Type permClass = null;
- IPermission perm = null;
-
- new ReflectionPermission(ReflectionPermissionFlag.MemberAccess).Assert();
- permClass = GetClassFromElement(el, ignoreTypeLoadFailures);
- if (permClass == null)
- return null;
- if (!(typeof(IPermission).IsAssignableFrom(permClass)))
- throw new ArgumentException( Environment.GetResourceString("Argument_NotAPermissionType") );
-
- perm = (IPermission) Activator.CreateInstance(permClass, BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public, null, objs, null );
-
- return perm;
- }
-
- internal static Type
- GetClassFromElement (SecurityElement el, bool ignoreTypeLoadFailures)
- {
- String className = el.Attribute( "class" );
-
- if (className == null)
- {
- if (ignoreTypeLoadFailures)
- return null;
- else
- throw new ArgumentException( String.Format( null, Environment.GetResourceString("Argument_InvalidXMLMissingAttr"), "class") );
- }
-
- if (ignoreTypeLoadFailures)
- {
- try
- {
- return Type.GetType(className, false, false);
- }
- catch (SecurityException)
- {
- return null;
- }
- }
- else
- return Type.GetType(className, true, false);
- }
-
- public static bool
- IsPermissionElement (IPermission ip,
- SecurityElement el)
- {
- if (!el.Tag.Equals ("Permission") && !el.Tag.Equals ("IPermission"))
- return false;
-
- return true;
- }
-
- public static bool
- IsUnrestricted (SecurityElement el)
- {
- String sUnrestricted = el.Attribute( "Unrestricted" );
-
- if (sUnrestricted == null)
- return false;
-
- return sUnrestricted.Equals( "true" ) || sUnrestricted.Equals( "TRUE" ) || sUnrestricted.Equals( "True" );
- }
-
-
- public static String BitFieldEnumToString( Type type, Object value )
- {
- int iValue = (int)value;
-
- if (iValue == 0)
- return Enum.GetName( type, 0 );
-
- StringBuilder result = StringBuilderCache.Acquire();
- bool first = true;
- int flag = 0x1;
-
- for (int i = 1; i < 32; ++i)
- {
- if ((flag & iValue) != 0)
- {
- String sFlag = Enum.GetName( type, flag );
-
- if (sFlag == null)
- continue;
-
- if (!first)
- {
- result.Append( ", " );
- }
-
- result.Append( sFlag );
- first = false;
- }
-
- flag = flag << 1;
- }
-
- return StringBuilderCache.GetStringAndRelease(result);
- }
- }
-}
diff --git a/src/mscorlib/src/System/Security/Util/sitestring.cs b/src/mscorlib/src/System/Security/Util/sitestring.cs
deleted file mode 100644
index 28f23742ec..0000000000
--- a/src/mscorlib/src/System/Security/Util/sitestring.cs
+++ /dev/null
@@ -1,289 +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.Security.Util {
- using System;
- using System.Collections;
- using System.Globalization;
- using System.Diagnostics.Contracts;
-
- [Serializable]
- internal class SiteString
- {
- protected String m_site;
- protected ArrayList m_separatedSite;
-
- protected static char[] m_separators = { '.' };
-
- protected internal SiteString()
- {
- // Only call this in derived classes when you know what you're doing.
- }
-
- public SiteString( String site )
- {
- m_separatedSite = CreateSeparatedSite( site );
- m_site = site;
- }
-
- private SiteString(String site, ArrayList separatedSite)
- {
- m_separatedSite = separatedSite;
- m_site = site;
- }
-
- private static ArrayList CreateSeparatedSite(String site)
- {
- if (site == null || site.Length == 0)
- {
- throw new ArgumentException( Environment.GetResourceString("Argument_InvalidSite" ));
- }
- Contract.EndContractBlock();
-
- ArrayList list = new ArrayList();
- int braIndex = -1;
- int ketIndex = -1;
- braIndex = site.IndexOf('[');
- if (braIndex == 0)
- ketIndex = site.IndexOf(']', braIndex+1);
-
- if (ketIndex != -1)
- {
- // Found an IPv6 address. Special case that
- String ipv6Addr = site.Substring(braIndex+1, ketIndex-braIndex-1);
- list.Add(ipv6Addr);
- return list;
- }
-
- // Regular hostnames or IPv4 addresses
- // We dont need to do this for IPv4 addresses, but it's easier to do it anyway
- String[] separatedArray = site.Split( m_separators );
-
- for (int index = separatedArray.Length-1; index > -1; --index)
- {
- if (separatedArray[index] == null)
- {
- throw new ArgumentException( Environment.GetResourceString("Argument_InvalidSite" ));
- }
- else if (separatedArray[index].Equals( "" ))
- {
- if (index != separatedArray.Length-1)
- {
- throw new ArgumentException( Environment.GetResourceString("Argument_InvalidSite" ));
- }
- }
- else if (separatedArray[index].Equals( "*" ))
- {
- if (index != 0)
- {
- throw new ArgumentException( Environment.GetResourceString("Argument_InvalidSite" ));
- }
- list.Add( separatedArray[index] );
- }
- else if (!AllLegalCharacters( separatedArray[index] ))
- {
- throw new ArgumentException( Environment.GetResourceString("Argument_InvalidSite" ));
- }
- else
- {
- list.Add( separatedArray[index] );
- }
- }
-
- return list;
- }
-
- // KB# Q188997 - http://support.microsoft.com/default.aspx?scid=KB;EN-US;Q188997& gives the list of allowed characters in
- // a NETBIOS name. DNS names are a subset of that (alphanumeric or '-').
- private static bool AllLegalCharacters( String str )
- {
- for (int i = 0; i < str.Length; ++i)
- {
- char c = str[i];
-
- if (IsLegalDNSChar(c) ||
- IsNetbiosSplChar(c))
- {
- continue;
- }
- else
- {
- return false;
- }
- }
-
- return true;
- }
-
- private static bool IsLegalDNSChar(char c)
- {
- if ((c >= 'a' && c <= 'z') ||
- (c >= 'A' && c <= 'Z') ||
- (c >= '0' && c <= '9') ||
- (c == '-'))
- return true;
- else
- return false;
- }
- private static bool IsNetbiosSplChar(char c)
- {
- // ! @ # $ % ^ & ( ) - _ ' { } . ~ are OK
- switch (c) {
- case '-':
- case '_':
- case '@':
- case '!':
- case '#':
- case '$':
- case '%':
- case '^':
- case '&':
- case '(':
- case ')':
- case '\'':
- case '{':
- case '}':
- case '.':
- case '~':
- return true;
- default:
- return false;
- }
- }
-
- public override String ToString()
- {
- return m_site;
- }
-
- public override bool Equals(Object o)
- {
- if (o == null || !(o is SiteString))
- return false;
- else
- return this.Equals( (SiteString)o, true );
- }
-
- public override int GetHashCode()
- {
- TextInfo info = CultureInfo.InvariantCulture.TextInfo;
-
- return info.GetCaseInsensitiveHashCode( this.m_site );
- }
-
- internal bool Equals( SiteString ss, bool ignoreCase )
- {
- if (this.m_site == null)
- return ss.m_site == null;
- if (ss.m_site == null)
- return false;
- return this.IsSubsetOf(ss, ignoreCase) && ss.IsSubsetOf(this, ignoreCase);
- }
-
-
- public virtual SiteString Copy()
- {
- return new SiteString( m_site, m_separatedSite );
- }
-
- public virtual bool IsSubsetOf( SiteString operand )
- {
- return this.IsSubsetOf( operand, true );
- }
-
- public virtual bool IsSubsetOf( SiteString operand, bool ignoreCase )
- {
- StringComparison strComp = (ignoreCase? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal);
- if (operand == null)
- {
- return false;
- }
- else if (this.m_separatedSite.Count == operand.m_separatedSite.Count &&
- this.m_separatedSite.Count == 0)
- {
- return true;
- }
- else if (this.m_separatedSite.Count < operand.m_separatedSite.Count - 1)
- {
- return false;
- }
- else if (this.m_separatedSite.Count > operand.m_separatedSite.Count &&
- operand.m_separatedSite.Count > 0 &&
- !operand.m_separatedSite[operand.m_separatedSite.Count - 1].Equals("*"))
- {
- return false;
- }
- else if (String.Compare( this.m_site, operand.m_site, strComp) == 0)
- {
- return true;
- }
-
- for (int index = 0; index < operand.m_separatedSite.Count - 1; ++index)
- {
- if (String.Compare((String)this.m_separatedSite[index], (String)operand.m_separatedSite[index], strComp) != 0)
- {
- return false;
- }
- }
-
- if (this.m_separatedSite.Count < operand.m_separatedSite.Count)
- {
- return operand.m_separatedSite[operand.m_separatedSite.Count - 1].Equals("*");
- }
- else if (this.m_separatedSite.Count == operand.m_separatedSite.Count)
- {
- // last item must be the same or operand must have a * in its last item
- return (String.Compare((String)this.m_separatedSite[this.m_separatedSite.Count - 1],
- (String)operand.m_separatedSite[this.m_separatedSite.Count - 1],
- strComp ) == 0 ||
- operand.m_separatedSite[operand.m_separatedSite.Count - 1].Equals("*"));
-
- }
- else
- return true;
- }
-
-
-
- public virtual SiteString Intersect( SiteString operand )
- {
- if (operand == null)
- {
- return null;
- }
- else if (this.IsSubsetOf( operand ))
- {
- return this.Copy();
- }
- else if (operand.IsSubsetOf( this ))
- {
- return operand.Copy();
- }
- else
- {
- return null;
- }
- }
-
- public virtual SiteString Union( SiteString operand )
- {
- if (operand == null)
- {
- return this;
- }
- else if (this.IsSubsetOf( operand ))
- {
- return operand.Copy();
- }
- else if (operand.IsSubsetOf( this ))
- {
- return this.Copy();
- }
- else
- {
- return null;
- }
- }
- }
-}
diff --git a/src/mscorlib/src/System/Security/VerificationException.cs b/src/mscorlib/src/System/Security/VerificationException.cs
index b0823cac01..5defbd6603 100644
--- a/src/mscorlib/src/System/Security/VerificationException.cs
+++ b/src/mscorlib/src/System/Security/VerificationException.cs
@@ -9,7 +9,6 @@ namespace System.Security {
using System;
using System.Runtime.Serialization;
- [System.Runtime.InteropServices.ComVisible(true)]
[Serializable]
public class VerificationException : SystemException {
public VerificationException()
diff --git a/src/mscorlib/src/System/Security/securestring.cs b/src/mscorlib/src/System/Security/securestring.cs
deleted file mode 100644
index 548126f4d0..0000000000
--- a/src/mscorlib/src/System/Security/securestring.cs
+++ /dev/null
@@ -1,751 +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.Security {
- using System.Security.Cryptography;
- using System.Runtime.InteropServices;
-#if FEATURE_CORRUPTING_EXCEPTIONS
- using System.Runtime.ExceptionServices;
-#endif // FEATURE_CORRUPTING_EXCEPTIONS
- using System.Text;
- using Microsoft.Win32;
- using System.Runtime.CompilerServices;
- using System.Security.Permissions;
- using System.Runtime.ConstrainedExecution;
- using System.Runtime.Versioning;
- using Microsoft.Win32.SafeHandles;
- using System.Diagnostics;
- using System.Diagnostics.Contracts;
-
- public sealed class SecureString: IDisposable {
- [System.Security.SecurityCritical] // auto-generated
- private SafeBSTRHandle m_buffer;
- [ContractPublicPropertyName("Length")]
- private int m_length;
- private bool m_readOnly;
- private bool m_encrypted;
-
- static bool supportedOnCurrentPlatform = EncryptionSupported();
-
- const int BlockSize = (int)Win32Native.CRYPTPROTECTMEMORY_BLOCK_SIZE /2; // a char is two bytes
- const int MaxLength = 65536;
- const uint ProtectionScope = Win32Native.CRYPTPROTECTMEMORY_SAME_PROCESS;
-
- [System.Security.SecuritySafeCritical] // auto-generated
- static SecureString()
- {
- }
-
- [System.Security.SecurityCritical] // auto-generated
- unsafe static bool EncryptionSupported() {
- // check if the enrypt/decrypt function is supported on current OS
- bool supported = true;
- try {
- Win32Native.SystemFunction041(
- SafeBSTRHandle.Allocate(null , (int)Win32Native.CRYPTPROTECTMEMORY_BLOCK_SIZE),
- Win32Native.CRYPTPROTECTMEMORY_BLOCK_SIZE,
- Win32Native.CRYPTPROTECTMEMORY_SAME_PROCESS);
- }
- catch (EntryPointNotFoundException) {
- supported = false;
- }
- return supported;
- }
-
- [System.Security.SecurityCritical] // auto-generated
- internal SecureString(SecureString str) {
- AllocateBuffer(str.BufferLength);
- SafeBSTRHandle.Copy(str.m_buffer, this.m_buffer);
- m_length = str.m_length;
- m_encrypted = str.m_encrypted;
- }
-
-
- [System.Security.SecuritySafeCritical] // auto-generated
- public SecureString() {
- CheckSupportedOnCurrentPlatform();
-
- // allocate the minimum block size for calling protectMemory
- AllocateBuffer(BlockSize);
- m_length = 0;
- }
-
-
- [System.Security.SecurityCritical] // auto-generated
-#if FEATURE_CORRUPTING_EXCEPTIONS
- [HandleProcessCorruptedStateExceptions]
-#endif // FEATURE_CORRUPTING_EXCEPTIONS
- private unsafe void InitializeSecureString(char* value, int length)
- {
- CheckSupportedOnCurrentPlatform();
-
- AllocateBuffer(length);
- m_length = length;
-
- byte* bufferPtr = null;
- RuntimeHelpers.PrepareConstrainedRegions();
- try
- {
- m_buffer.AcquirePointer(ref bufferPtr);
- Buffer.Memcpy(bufferPtr, (byte*)value, length * 2);
- }
- catch (Exception) {
- ProtectMemory();
- throw;
- }
- finally
- {
- if (bufferPtr != null)
- m_buffer.ReleasePointer();
- }
-
- ProtectMemory();
- }
-
- [System.Security.SecurityCritical] // auto-generated
- [CLSCompliant(false)]
- public unsafe SecureString(char* value, int length) {
- if( value == null) {
- throw new ArgumentNullException(nameof(value));
- }
-
- if( length < 0) {
- throw new ArgumentOutOfRangeException(nameof(length), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
- }
-
- if( length > MaxLength) {
- throw new ArgumentOutOfRangeException(nameof(length), Environment.GetResourceString("ArgumentOutOfRange_Length"));
- }
- Contract.EndContractBlock();
-
- // Refactored since HandleProcessCorruptedStateExceptionsAttribute applies to methods only (yet).
- InitializeSecureString(value, length);
- }
-
- public int Length {
- [System.Security.SecuritySafeCritical] // auto-generated
- [MethodImplAttribute(MethodImplOptions.Synchronized)]
- get {
- EnsureNotDisposed();
- return m_length;
- }
- }
-
- [System.Security.SecuritySafeCritical] // auto-generated
- [MethodImplAttribute(MethodImplOptions.Synchronized)]
-#if FEATURE_CORRUPTING_EXCEPTIONS
- [HandleProcessCorruptedStateExceptions]
-#endif // FEATURE_CORRUPTING_EXCEPTIONS
- public void AppendChar(char c) {
- EnsureNotDisposed();
- EnsureNotReadOnly();
-
- EnsureCapacity(m_length + 1);
-
- RuntimeHelpers.PrepareConstrainedRegions();
- try {
- UnProtectMemory();
- m_buffer.Write<char>((uint)m_length * sizeof(char), c);
- m_length++;
- }
- catch (Exception) {
- ProtectMemory();
- throw;
- }
- finally {
- ProtectMemory();
- }
- }
-
- // clears the current contents. Only available if writable
- [System.Security.SecuritySafeCritical] // auto-generated
- [MethodImplAttribute(MethodImplOptions.Synchronized)]
- public void Clear() {
- EnsureNotDisposed();
- EnsureNotReadOnly();
-
- m_length = 0;
- m_buffer.ClearBuffer();
- m_encrypted = false;
- }
-
- // Do a deep-copy of the SecureString
- [System.Security.SecuritySafeCritical] // auto-generated
- [MethodImplAttribute(MethodImplOptions.Synchronized)]
- public SecureString Copy() {
- EnsureNotDisposed();
- return new SecureString(this);
- }
-
- [System.Security.SecuritySafeCritical] // auto-generated
- [MethodImplAttribute(MethodImplOptions.Synchronized)]
- public void Dispose() {
- if(m_buffer != null && !m_buffer.IsInvalid) {
- m_buffer.Close();
- m_buffer = null;
- }
- }
-
- [System.Security.SecuritySafeCritical] // auto-generated
- [MethodImplAttribute(MethodImplOptions.Synchronized)]
-#if FEATURE_CORRUPTING_EXCEPTIONS
- [HandleProcessCorruptedStateExceptions]
-#endif // FEATURE_CORRUPTING_EXCEPTIONS
- public void InsertAt( int index, char c ) {
- if( index < 0 || index > m_length) {
- throw new ArgumentOutOfRangeException(nameof(index), Environment.GetResourceString("ArgumentOutOfRange_IndexString"));
- }
- Contract.EndContractBlock();
-
- EnsureNotDisposed();
- EnsureNotReadOnly();
-
- EnsureCapacity(m_length + 1);
-
- unsafe {
- byte* bufferPtr = null;
- RuntimeHelpers.PrepareConstrainedRegions();
- try {
- UnProtectMemory();
- m_buffer.AcquirePointer(ref bufferPtr);
- char* pBuffer = (char*)bufferPtr;
-
- for (int i = m_length; i > index; i--) {
- pBuffer[i] = pBuffer[i - 1];
- }
- pBuffer[index] = c;
- ++m_length;
- }
- catch (Exception) {
- ProtectMemory();
- throw;
- }
- finally {
- ProtectMemory();
- if (bufferPtr != null)
- m_buffer.ReleasePointer();
- }
- }
- }
-
- [System.Security.SecuritySafeCritical] // auto-generated
- [MethodImplAttribute(MethodImplOptions.Synchronized)]
- public bool IsReadOnly() {
- EnsureNotDisposed();
- return m_readOnly;
- }
-
- [System.Security.SecuritySafeCritical] // auto-generated
- [MethodImplAttribute(MethodImplOptions.Synchronized)]
- public void MakeReadOnly() {
- EnsureNotDisposed();
- m_readOnly = true;
- }
-
- [System.Security.SecuritySafeCritical] // auto-generated
- [MethodImplAttribute(MethodImplOptions.Synchronized)]
-#if FEATURE_CORRUPTING_EXCEPTIONS
- [HandleProcessCorruptedStateExceptions]
-#endif // FEATURE_CORRUPTING_EXCEPTIONS
- public void RemoveAt( int index ) {
- EnsureNotDisposed();
- EnsureNotReadOnly();
-
- if( index < 0 || index >= m_length) {
- throw new ArgumentOutOfRangeException(nameof(index), Environment.GetResourceString("ArgumentOutOfRange_IndexString"));
- }
-
- unsafe
- {
- byte* bufferPtr = null;
- RuntimeHelpers.PrepareConstrainedRegions();
- try
- {
- UnProtectMemory();
- m_buffer.AcquirePointer(ref bufferPtr);
- char* pBuffer = (char*)bufferPtr;
-
- for (int i = index; i < m_length - 1; i++)
- {
- pBuffer[i] = pBuffer[i + 1];
- }
- pBuffer[--m_length] = (char)0;
- }
- catch (Exception) {
- ProtectMemory();
- throw;
- }
- finally
- {
- ProtectMemory();
- if (bufferPtr != null)
- m_buffer.ReleasePointer();
- }
- }
- }
-
- [System.Security.SecuritySafeCritical] // auto-generated
- [MethodImplAttribute(MethodImplOptions.Synchronized)]
-#if FEATURE_CORRUPTING_EXCEPTIONS
- [HandleProcessCorruptedStateExceptions]
-#endif // FEATURE_CORRUPTING_EXCEPTIONS
- public void SetAt( int index, char c ) {
- if( index < 0 || index >= m_length) {
- throw new ArgumentOutOfRangeException(nameof(index), Environment.GetResourceString("ArgumentOutOfRange_IndexString"));
- }
- Contract.EndContractBlock();
- Debug.Assert(index <= Int32.MaxValue / sizeof(char));
-
- EnsureNotDisposed();
- EnsureNotReadOnly();
-
- RuntimeHelpers.PrepareConstrainedRegions();
- try {
- UnProtectMemory();
- m_buffer.Write<char>((uint)index * sizeof(char), c);
- }
- catch (Exception) {
- ProtectMemory();
- throw;
- }
- finally {
- ProtectMemory();
- }
- }
-
- private int BufferLength {
- [System.Security.SecurityCritical] // auto-generated
- get {
- Debug.Assert(m_buffer != null, "Buffer is not initialized!");
- return m_buffer.Length;
- }
- }
-
- [System.Security.SecurityCritical] // auto-generated
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
- private void AllocateBuffer(int size) {
- uint alignedSize = GetAlignedSize(size);
-
- m_buffer = SafeBSTRHandle.Allocate(null, alignedSize);
- if (m_buffer.IsInvalid) {
- throw new OutOfMemoryException();
- }
- }
-
- private void CheckSupportedOnCurrentPlatform() {
- if( !supportedOnCurrentPlatform) {
- throw new NotSupportedException(Environment.GetResourceString("Arg_PlatformSecureString"));
- }
- Contract.EndContractBlock();
- }
-
- [System.Security.SecurityCritical] // auto-generated
- private void EnsureCapacity(int capacity) {
- if( capacity > MaxLength) {
- throw new ArgumentOutOfRangeException(nameof(capacity), Environment.GetResourceString("ArgumentOutOfRange_Capacity"));
- }
- Contract.EndContractBlock();
-
- if( capacity <= m_buffer.Length) {
- return;
- }
-
- SafeBSTRHandle newBuffer = SafeBSTRHandle.Allocate(null, GetAlignedSize(capacity));
-
- if (newBuffer.IsInvalid) {
- throw new OutOfMemoryException();
- }
-
- SafeBSTRHandle.Copy(m_buffer, newBuffer);
- m_buffer.Close();
- m_buffer = newBuffer;
- }
-
- [System.Security.SecurityCritical] // auto-generated
- private void EnsureNotDisposed() {
- if( m_buffer == null) {
- throw new ObjectDisposedException(null);
- }
- Contract.EndContractBlock();
- }
-
- private void EnsureNotReadOnly() {
- if( m_readOnly) {
- throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_ReadOnly"));
- }
- Contract.EndContractBlock();
- }
-
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
- private static uint GetAlignedSize( int size) {
- 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
- alignedSize += BlockSize;
- }
- return alignedSize;
- }
-
- [System.Security.SecurityCritical] // auto-generated
- private unsafe int GetAnsiByteCount() {
- const uint CP_ACP = 0;
- const uint WC_NO_BEST_FIT_CHARS = 0x00000400;
-
- uint flgs = WC_NO_BEST_FIT_CHARS;
- uint DefaultCharUsed = (uint)'?';
-
- byte* bufferPtr = null;
- RuntimeHelpers.PrepareConstrainedRegions();
- try {
- m_buffer.AcquirePointer(ref bufferPtr);
-
- return Win32Native.WideCharToMultiByte(
- CP_ACP,
- flgs,
- (char*) bufferPtr,
- m_length,
- null,
- 0,
- IntPtr.Zero,
- new IntPtr((void*)&DefaultCharUsed));
- }
- finally {
- if (bufferPtr != null)
- m_buffer.ReleasePointer();
- }
- }
-
- [System.Security.SecurityCritical] // auto-generated
- private unsafe void GetAnsiBytes( byte * ansiStrPtr, int byteCount) {
- const uint CP_ACP = 0;
- const uint WC_NO_BEST_FIT_CHARS = 0x00000400;
-
- uint flgs = WC_NO_BEST_FIT_CHARS;
- uint DefaultCharUsed = (uint)'?';
-
- byte* bufferPtr = null;
- RuntimeHelpers.PrepareConstrainedRegions();
- try {
- m_buffer.AcquirePointer(ref bufferPtr);
-
- Win32Native.WideCharToMultiByte(
- CP_ACP,
- flgs,
- (char*) bufferPtr,
- m_length,
- ansiStrPtr,
- byteCount - 1,
- IntPtr.Zero,
- new IntPtr((void*)&DefaultCharUsed));
-
- *(ansiStrPtr + byteCount - 1) = (byte)0;
- }
- finally {
- if (bufferPtr != null)
- m_buffer.ReleasePointer();
- }
- }
-
- [System.Security.SecurityCritical] // auto-generated
- [ReliabilityContract(Consistency.MayCorruptInstance, Cer.MayFail)]
- private void ProtectMemory() {
- 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;
- }
-
- RuntimeHelpers.PrepareConstrainedRegions();
- try {
- }
- finally {
- // RtlEncryptMemory return an NTSTATUS
- int status = Win32Native.SystemFunction040(m_buffer, (uint)m_buffer.Length * 2, ProtectionScope);
- if (status < 0) { // non-negative numbers indicate success
-#if FEATURE_CORECLR
- throw new CryptographicException(Win32Native.RtlNtStatusToDosError(status));
-#else
- throw new CryptographicException(Win32Native.LsaNtStatusToWinError(status));
-#endif
- }
- m_encrypted = true;
- }
- }
-
- [System.Security.SecurityCritical] // auto-generated
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
- [MethodImplAttribute(MethodImplOptions.Synchronized)]
-#if FEATURE_CORRUPTING_EXCEPTIONS
- [HandleProcessCorruptedStateExceptions]
-#endif // FEATURE_CORRUPTING_EXCEPTIONS
- internal unsafe IntPtr ToBSTR() {
- EnsureNotDisposed();
- int length = m_length;
- IntPtr ptr = IntPtr.Zero;
- IntPtr result = IntPtr.Zero;
- byte* bufferPtr = null;
-
- RuntimeHelpers.PrepareConstrainedRegions();
- try {
- RuntimeHelpers.PrepareConstrainedRegions();
- try {
- }
- finally {
- ptr = Win32Native.SysAllocStringLen(null, length);
- }
-
- if (ptr == IntPtr.Zero) {
- throw new OutOfMemoryException();
- }
-
- UnProtectMemory();
- m_buffer.AcquirePointer(ref bufferPtr);
- Buffer.Memcpy((byte*) ptr.ToPointer(), bufferPtr, length *2);
- result = ptr;
- }
- catch (Exception) {
- ProtectMemory();
- throw;
- }
- finally {
- ProtectMemory();
- if( result == IntPtr.Zero) {
- // If we failed for any reason, free the new buffer
- if (ptr != IntPtr.Zero) {
- Win32Native.ZeroMemory(ptr, (UIntPtr)(length * 2));
- Win32Native.SysFreeString(ptr);
- }
- }
- if (bufferPtr != null)
- m_buffer.ReleasePointer();
- }
- return result;
- }
-
- [System.Security.SecurityCritical] // auto-generated
- [MethodImplAttribute(MethodImplOptions.Synchronized)]
-#if FEATURE_CORRUPTING_EXCEPTIONS
- [HandleProcessCorruptedStateExceptions]
-#endif // FEATURE_CORRUPTING_EXCEPTIONS
- internal unsafe IntPtr ToUniStr(bool allocateFromHeap) {
- EnsureNotDisposed();
- int length = m_length;
- IntPtr ptr = IntPtr.Zero;
- IntPtr result = IntPtr.Zero;
- byte* bufferPtr = null;
-
- RuntimeHelpers.PrepareConstrainedRegions();
- try {
- RuntimeHelpers.PrepareConstrainedRegions();
- try {
- }
- finally {
- if( allocateFromHeap) {
- ptr = Marshal.AllocHGlobal((length + 1) * 2);
- }
- else {
- ptr = Marshal.AllocCoTaskMem((length + 1) * 2);
- }
- }
-
- if (ptr == IntPtr.Zero) {
- throw new OutOfMemoryException();
- }
-
- UnProtectMemory();
- m_buffer.AcquirePointer(ref bufferPtr);
- Buffer.Memcpy((byte*) ptr.ToPointer(), bufferPtr, length *2);
- char * endptr = (char *) ptr.ToPointer();
- *(endptr + length) = '\0';
- result = ptr;
- }
- catch (Exception) {
- ProtectMemory();
- throw;
- }
- finally {
- ProtectMemory();
-
- if( result == IntPtr.Zero) {
- // If we failed for any reason, free the new buffer
- if (ptr != IntPtr.Zero) {
- Win32Native.ZeroMemory(ptr, (UIntPtr)(length * 2));
- if( allocateFromHeap) {
- Marshal.FreeHGlobal(ptr);
- }
- else {
- Marshal.FreeCoTaskMem(ptr);
- }
- }
- }
-
- if (bufferPtr != null)
- m_buffer.ReleasePointer();
- }
- return result;
- }
-
- [System.Security.SecurityCritical] // auto-generated
- [MethodImplAttribute(MethodImplOptions.Synchronized)]
-#if FEATURE_CORRUPTING_EXCEPTIONS
- [HandleProcessCorruptedStateExceptions]
-#endif // FEATURE_CORRUPTING_EXCEPTIONS
- internal unsafe IntPtr ToAnsiStr(bool allocateFromHeap) {
- EnsureNotDisposed();
-
- IntPtr ptr = IntPtr.Zero;
- IntPtr result = IntPtr.Zero;
- int byteCount = 0;
- RuntimeHelpers.PrepareConstrainedRegions();
- try {
- // GetAnsiByteCount uses the string data, so the calculation must happen after we are decrypted.
- UnProtectMemory();
-
- // allocating an extra char for terminating zero
- byteCount = GetAnsiByteCount() + 1;
-
- RuntimeHelpers.PrepareConstrainedRegions();
- try {
- }
- finally {
- if( allocateFromHeap) {
- ptr = Marshal.AllocHGlobal(byteCount);
- }
- else {
- ptr = Marshal.AllocCoTaskMem(byteCount);
- }
- }
-
- if (ptr == IntPtr.Zero) {
- throw new OutOfMemoryException();
- }
-
- GetAnsiBytes((byte *)ptr.ToPointer(), byteCount);
- result = ptr;
- }
- catch (Exception) {
- ProtectMemory();
- throw;
- }
- finally {
- ProtectMemory();
- if( result == IntPtr.Zero) {
- // If we failed for any reason, free the new buffer
- if (ptr != IntPtr.Zero) {
- Win32Native.ZeroMemory(ptr, (UIntPtr)byteCount);
- if( allocateFromHeap) {
- Marshal.FreeHGlobal(ptr);
- }
- else {
- Marshal.FreeCoTaskMem(ptr);
- }
- }
- }
-
- }
- return result;
- }
-
- [System.Security.SecurityCritical] // auto-generated
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
- private void UnProtectMemory() {
- 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;
- }
-
- RuntimeHelpers.PrepareConstrainedRegions();
- try {
- }
- finally {
- if (m_encrypted) {
- // RtlEncryptMemory return an NTSTATUS
- int status = Win32Native.SystemFunction041(m_buffer, (uint)m_buffer.Length * 2, ProtectionScope);
- if (status < 0)
- { // non-negative numbers indicate success
-#if FEATURE_CORECLR
- throw new CryptographicException(Win32Native.RtlNtStatusToDosError(status));
-#else
- throw new CryptographicException(Win32Native.LsaNtStatusToWinError(status));
-#endif
- }
- m_encrypted = false;
- }
- }
- }
- }
-
- [System.Security.SecurityCritical] // auto-generated
- [SuppressUnmanagedCodeSecurityAttribute()]
- internal sealed class SafeBSTRHandle : SafeBuffer {
- internal SafeBSTRHandle () : base(true) {}
-
- internal static SafeBSTRHandle Allocate(String src, uint len)
- {
- SafeBSTRHandle bstr = SysAllocStringLen(src, len);
- bstr.Initialize(len * sizeof(char));
- return bstr;
- }
-
- [DllImport(Win32Native.OLEAUT32, CharSet = CharSet.Unicode)]
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
- private static extern SafeBSTRHandle SysAllocStringLen(String src, uint len); // BSTR
-
- [System.Security.SecurityCritical]
- override protected bool ReleaseHandle()
- {
- Win32Native.ZeroMemory(handle, (UIntPtr) (Win32Native.SysStringLen(handle) * 2));
- Win32Native.SysFreeString(handle);
- return true;
- }
-
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
- internal unsafe void ClearBuffer() {
- byte* bufferPtr = null;
- RuntimeHelpers.PrepareConstrainedRegions();
- try
- {
- AcquirePointer(ref bufferPtr);
- Win32Native.ZeroMemory((IntPtr)bufferPtr, (UIntPtr) (Win32Native.SysStringLen((IntPtr)bufferPtr) * 2));
- }
- finally
- {
- if (bufferPtr != null)
- ReleasePointer();
- }
- }
-
-
- internal unsafe int Length {
- get {
- return (int) Win32Native.SysStringLen(this);
- }
- }
-
- internal unsafe static void Copy(SafeBSTRHandle source, SafeBSTRHandle target) {
- byte* sourcePtr = null, targetPtr = null;
- RuntimeHelpers.PrepareConstrainedRegions();
- try
- {
- source.AcquirePointer(ref sourcePtr);
- target.AcquirePointer(ref targetPtr);
-
- 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);
- }
- finally
- {
- if (sourcePtr != null)
- source.ReleasePointer();
- if (targetPtr != null)
- target.ReleasePointer();
- }
- }
- }
-}
-
diff --git a/src/mscorlib/src/System/SerializableAttribute.cs b/src/mscorlib/src/System/SerializableAttribute.cs
index bceca6800a..1c99654eec 100644
--- a/src/mscorlib/src/System/SerializableAttribute.cs
+++ b/src/mscorlib/src/System/SerializableAttribute.cs
@@ -16,7 +16,6 @@ namespace System {
using System.Reflection;
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Enum | AttributeTargets.Delegate, Inherited = false)]
-[System.Runtime.InteropServices.ComVisible(true)]
public sealed class SerializableAttribute : Attribute
{
internal static Attribute GetCustomAttribute(RuntimeType type)
diff --git a/src/mscorlib/src/System/SharedStatics.cs b/src/mscorlib/src/System/SharedStatics.cs
index cbc5c354a1..d9364335f5 100644
--- a/src/mscorlib/src/System/SharedStatics.cs
+++ b/src/mscorlib/src/System/SharedStatics.cs
@@ -16,7 +16,6 @@ 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;
@@ -36,40 +35,9 @@ namespace System
}
private volatile String _Remoting_Identity_IDGuid;
- public static String Remoting_Identity_IDGuid
- {
- get
- {
- if (_sharedStatics._Remoting_Identity_IDGuid == null)
- {
- bool tookLock = false;
- RuntimeHelpers.PrepareConstrainedRegions();
- try {
- Monitor.Enter(_sharedStatics, ref tookLock);
-
- if (_sharedStatics._Remoting_Identity_IDGuid == null)
- {
- _sharedStatics._Remoting_Identity_IDGuid = Guid.NewGuid().ToString().Replace('-', '_');
- }
- }
- finally {
- if (tookLock)
- Monitor.Exit(_sharedStatics);
- }
- }
-
- Debug.Assert(_sharedStatics._Remoting_Identity_IDGuid != null,
- "_sharedStatics._Remoting_Identity_IDGuid != null");
- return _sharedStatics._Remoting_Identity_IDGuid;
- }
- }
// Note this may not need to be process-wide.
private int _Remoting_Identity_IDSeqNum;
- internal static int Remoting_Identity_GetNextSeqNum()
- {
- return Interlocked.Increment(ref _sharedStatics._Remoting_Identity_IDSeqNum);
- }
// This is the total amount of memory currently "reserved" via
@@ -77,7 +45,6 @@ namespace System
// Stored as a long because we need to use Interlocked.Add.
private long _memFailPointReservedMemory;
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
internal static long AddMemoryFailPointReservation(long size)
{
// Size can legitimately be negative - see Dispose.
diff --git a/src/mscorlib/src/System/Single.cs b/src/mscorlib/src/System/Single.cs
index 481c088617..657d7aef32 100644
--- a/src/mscorlib/src/System/Single.cs
+++ b/src/mscorlib/src/System/Single.cs
@@ -21,7 +21,6 @@ namespace System {
[Serializable]
[System.Runtime.InteropServices.StructLayout(LayoutKind.Sequential)]
-[System.Runtime.InteropServices.ComVisible(true)]
public struct Single : IComparable, IFormattable, IConvertible
, IComparable<Single>, IEquatable<Single>
{
@@ -58,7 +57,6 @@ namespace System {
}
[Pure]
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
[System.Runtime.Versioning.NonVersionable]
public unsafe static bool IsNaN(float f) {
return (*(int*)(&f) & 0x7FFFFFFF) > 0x7F800000;
diff --git a/src/mscorlib/src/System/Span.cs b/src/mscorlib/src/System/Span.cs
index 9fa55c63d7..c77a1994c9 100644
--- a/src/mscorlib/src/System/Span.cs
+++ b/src/mscorlib/src/System/Span.cs
@@ -2,17 +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.
-using System.Collections.Generic;
using System.Diagnostics;
using System.Runtime.CompilerServices;
+using EditorBrowsableState = System.ComponentModel.EditorBrowsableState;
+using EditorBrowsableAttribute = System.ComponentModel.EditorBrowsableAttribute;
#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
+ /// Span represents a contiguous region of arbitrary memory. 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>
@@ -29,14 +29,13 @@ namespace System
/// <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>
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
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();
- }
+ if (default(T) == null && array.GetType() != typeof(T[]))
+ ThrowHelper.ThrowArrayTypeMismatchException();
_pointer = new ByReference<T>(ref JitHelpers.GetArrayData(array));
_length = array.Length;
@@ -54,14 +53,13 @@ namespace System
/// <exception cref="System.ArgumentOutOfRangeException">
/// Thrown when the specified <paramref name="start"/> is not in the range (&lt;0 or &gt;=Length).
/// </exception>
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
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 (default(T) == null && array.GetType() != typeof(T[]))
+ ThrowHelper.ThrowArrayTypeMismatchException();
if ((uint)start > (uint)array.Length)
ThrowHelper.ThrowArgumentOutOfRangeException();
@@ -82,14 +80,13 @@ namespace System
/// <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>
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
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 (default(T) == null && array.GetType() != typeof(T[]))
+ ThrowHelper.ThrowArrayTypeMismatchException();
if ((uint)start > (uint)array.Length || (uint)length > (uint)(array.Length - start))
ThrowHelper.ThrowArgumentOutOfRangeException();
@@ -112,6 +109,7 @@ namespace System
/// Thrown when the specified <paramref name="length"/> is negative.
/// </exception>
[CLSCompliant(false)]
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
public unsafe Span(void* pointer, int length)
{
if (JitHelpers.ContainsReferences<T>())
@@ -137,6 +135,7 @@ namespace System
/// <exception cref="System.ArgumentOutOfRangeException">
/// Thrown when the specified <paramref name="length"/> is negative.
/// </exception>
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Span<T> DangerousCreate(object obj, ref T objectData, int length)
{
if (obj == null)
@@ -146,13 +145,13 @@ namespace System
return new Span<T>(ref objectData, length);
}
-
- /// <summary>
- /// An internal helper for creating spans.
- /// </summary>
+ // Constructor for internal use only.
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
internal Span(ref T ptr, int length)
{
+ Debug.Assert(length >= 0);
+
_pointer = new ByReference<T>(ref ptr);
_length = length;
}
@@ -167,36 +166,128 @@ namespace System
}
/// <summary>
- /// Gets the number of elements contained in the <see cref="Span{T}"/>
+ /// The number of items in the span.
/// </summary>
public int Length => _length;
/// <summary>
- /// Returns whether the <see cref="Span{T}"/> is empty.
+ /// Returns true if Length is 0.
/// </summary>
public bool IsEmpty => _length == 0;
/// <summary>
- /// Fetches the element at the specified index.
+ /// Returns a reference to specified element of the Span.
/// </summary>
+ /// <param name="index"></param>
+ /// <returns></returns>
/// <exception cref="System.IndexOutOfRangeException">
- /// Thrown when the specified <paramref name="index"/> is not in range (&lt;0 or &gt;&eq;Length).
+ /// Thrown when index less than 0 or index greater than or equal to Length
/// </exception>
+
+ // TODO: https://github.com/dotnet/corefx/issues/13681
+ // Until we get over the hurdle of C# 7 tooling, this indexer will return "T" and have a setter rather than a "ref T". (The doc comments
+ // continue to reflect the original intent of returning "ref T")
public T this[int index]
{
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
get
{
if ((uint)index >= (uint)_length)
ThrowHelper.ThrowIndexOutOfRangeException();
- return Unsafe.Add(ref DangerousGetPinnableReference(), index);
+ return Unsafe.Add(ref _pointer.Value, index);
}
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
set
{
if ((uint)index >= (uint)_length)
ThrowHelper.ThrowIndexOutOfRangeException();
- Unsafe.Add(ref DangerousGetPinnableReference(), index) = value;
+ Unsafe.Add(ref _pointer.Value, index) = value;
+ }
+ }
+
+ /// <summary>
+ /// Returns a reference to specified element of the Span.
+ /// </summary>
+ /// <param name="index"></param>
+ /// <returns></returns>
+ /// <exception cref="System.IndexOutOfRangeException">
+ /// Thrown when index less than 0 or index greater than or equal to Length
+ /// </exception>
+
+ // TODO: https://github.com/dotnet/corefx/issues/13681
+ // Until we get over the hurdle of C# 7 tooling, this temporary method will simulate the intended "ref T" indexer for those
+ // who need bypass the workaround for performance.
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public ref T GetItem(int index)
+ {
+ if ((uint)index >= ((uint)_length))
+ ThrowHelper.ThrowIndexOutOfRangeException();
+
+ return ref Unsafe.Add(ref _pointer.Value, index);
+ }
+
+ /// <summary>
+ /// Clears the contents of this span.
+ /// </summary>
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public void Clear()
+ {
+ // TODO: Optimize - https://github.com/dotnet/coreclr/issues/9161
+ for (int i = 0; i < _length; i++)
+ {
+ this[i] = default(T);
+ }
+ }
+
+ /// <summary>
+ /// Fills the contents of this span with the given value.
+ /// </summary>
+ public void Fill(T value)
+ {
+ int length = _length;
+
+ if (length == 0)
+ return;
+
+ if (Unsafe.SizeOf<T>() == 1)
+ {
+ byte fill = Unsafe.As<T, byte>(ref value);
+ ref byte r = ref Unsafe.As<T, byte>(ref _pointer.Value);
+ Unsafe.InitBlockUnaligned(ref r, fill, (uint)length);
+ }
+ else
+ {
+ ref T r = ref DangerousGetPinnableReference();
+
+ // TODO: Create block fill for value types of power of two sizes e.g. 2,4,8,16
+
+ // Simple loop unrolling
+ int i = 0;
+ for (; i < (length & ~7); i += 8)
+ {
+ Unsafe.Add<T>(ref r, i + 0) = value;
+ Unsafe.Add<T>(ref r, i + 1) = value;
+ Unsafe.Add<T>(ref r, i + 2) = value;
+ Unsafe.Add<T>(ref r, i + 3) = value;
+ Unsafe.Add<T>(ref r, i + 4) = value;
+ Unsafe.Add<T>(ref r, i + 5) = value;
+ Unsafe.Add<T>(ref r, i + 6) = value;
+ Unsafe.Add<T>(ref r, i + 7) = value;
+ }
+ if (i < (length & ~3))
+ {
+ Unsafe.Add<T>(ref r, i + 0) = value;
+ Unsafe.Add<T>(ref r, i + 1) = value;
+ Unsafe.Add<T>(ref r, i + 2) = value;
+ Unsafe.Add<T>(ref r, i + 3) = value;
+ i += 4;
+ }
+ for (; i < length; i++)
+ {
+ Unsafe.Add<T>(ref r, i) = value;
+ }
}
}
@@ -228,7 +319,7 @@ namespace System
if ((uint)_length > (uint)destination.Length)
return false;
- SpanHelper.CopyTo<T>(ref destination.DangerousGetPinnableReference(), ref DangerousGetPinnableReference(), _length);
+ SpanHelper.CopyTo<T>(ref destination._pointer.Value, ref _pointer.Value, _length);
return true;
}
@@ -238,7 +329,7 @@ namespace System
/// </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());
+ return left._length == right._length && Unsafe.AreSame<T>(ref left._pointer.Value, ref right._pointer.Value);
}
/// <summary>
@@ -254,6 +345,7 @@ namespace System
/// </exception>
/// </summary>
[Obsolete("Equals() on Span will always throw an exception. Use == instead.")]
+ [EditorBrowsable(EditorBrowsableState.Never)]
public override bool Equals(object obj)
{
ThrowHelper.ThrowNotSupportedException_CannotCallEqualsOnSpan();
@@ -268,6 +360,7 @@ namespace System
/// </exception>
/// </summary>
[Obsolete("GetHashCode() on Span will always throw an exception.")]
+ [EditorBrowsable(EditorBrowsableState.Never)]
public override int GetHashCode()
{
ThrowHelper.ThrowNotSupportedException_CannotCallGetHashCodeOnSpan();
@@ -283,27 +376,27 @@ namespace System
/// <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);
+ 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);
+ public static implicit operator ReadOnlySpan<T>(Span<T> span) => new ReadOnlySpan<T>(ref span._pointer.Value, 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).
+ /// 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
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
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);
+ return new Span<T>(ref Unsafe.Add(ref _pointer.Value, start), _length - start);
}
/// <summary>
@@ -312,15 +405,15 @@ namespace System
/// <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).
+ /// Thrown when the specified <paramref name="start"/> or end 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
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
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);
+ return new Span<T>(ref Unsafe.Add(ref _pointer.Value, start), length);
}
/// <summary>
@@ -328,13 +421,14 @@ namespace System
/// allocates, so should generally be avoided, however it is sometimes
/// necessary to bridge the gap with APIs written in terms of arrays.
/// </summary>
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
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);
+ SpanHelper.CopyTo<T>(ref JitHelpers.GetArrayData(destination), ref _pointer.Value, _length);
return destination;
}
@@ -344,7 +438,7 @@ namespace System
public static Span<T> Empty => default(Span<T>);
}
- public static class SpanExtensions
+ public static class Span
{
/// <summary>
/// Casts a Span of one primitive type <typeparamref name="T"/> to Span of bytes.
@@ -433,6 +527,64 @@ namespace System
ref Unsafe.As<TFrom, TTo>(ref source.DangerousGetPinnableReference()),
checked((int)((long)source.Length * Unsafe.SizeOf<TFrom>() / Unsafe.SizeOf<TTo>())));
}
+
+ /// <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>
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ 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>
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ 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>
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ 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);
+ }
}
internal static class SpanHelper
diff --git a/src/mscorlib/src/System/StackOverflowException.cs b/src/mscorlib/src/System/StackOverflowException.cs
index 4a20527f61..0a875e7373 100644
--- a/src/mscorlib/src/System/StackOverflowException.cs
+++ b/src/mscorlib/src/System/StackOverflowException.cs
@@ -11,30 +11,31 @@
**
=============================================================================*/
-namespace System {
-
- using System;
- using System.Runtime.Serialization;
- [System.Runtime.InteropServices.ComVisible(true)]
+using System.Runtime.Serialization;
+
+namespace System
+{
[Serializable]
- public sealed class StackOverflowException : SystemException {
- public StackOverflowException()
- : base(Environment.GetResourceString("Arg_StackOverflowException")) {
- SetErrorCode(__HResults.COR_E_STACKOVERFLOW);
- }
-
- public StackOverflowException(String message)
- : base(message) {
- SetErrorCode(__HResults.COR_E_STACKOVERFLOW);
+ public sealed class StackOverflowException : SystemException
+ {
+ public StackOverflowException()
+ : base(SR.Arg_StackOverflowException)
+ {
+ HResult = __HResults.COR_E_STACKOVERFLOW;
}
-
- public StackOverflowException(String message, Exception innerException)
- : base(message, innerException) {
- SetErrorCode(__HResults.COR_E_STACKOVERFLOW);
+
+ public StackOverflowException(String message)
+ : base(message)
+ {
+ HResult = __HResults.COR_E_STACKOVERFLOW;
}
- internal StackOverflowException(SerializationInfo info, StreamingContext context) : base (info, context) {
+ public StackOverflowException(String message, Exception innerException)
+ : base(message, innerException)
+ {
+ HResult = __HResults.COR_E_STACKOVERFLOW;
}
-
+
+ internal StackOverflowException(SerializationInfo info, StreamingContext context) : base(info, context) { }
}
}
diff --git a/src/mscorlib/src/System/String.Comparison.cs b/src/mscorlib/src/System/String.Comparison.cs
index 07f2f9de22..2ac1d78997 100644
--- a/src/mscorlib/src/System/String.Comparison.cs
+++ b/src/mscorlib/src/System/String.Comparison.cs
@@ -73,7 +73,6 @@ namespace System
// Search/Query methods
//
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
private unsafe static bool EqualsHelper(String strA, String strB)
{
Contract.Requires(strA != null);
@@ -134,7 +133,6 @@ namespace System
}
}
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
private unsafe static bool StartsWithOrdinalHelper(String str, String startsWith)
{
Contract.Requires(str != null);
@@ -716,7 +714,6 @@ namespace System
}
[Pure]
- [ComVisible(false)]
public Boolean EndsWith(String value, StringComparison comparisonType) {
if( (Object)value == null) {
throw new ArgumentNullException(nameof(value));
@@ -793,7 +790,6 @@ namespace System
}
// Determines whether two strings match.
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
public override bool Equals(Object obj)
{
if (this == null) // this is necessary to guard against reverse-pinvokes and
@@ -814,7 +810,6 @@ namespace System
// Determines whether two strings match.
[Pure]
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
public bool Equals(String value)
{
if (this == null) // this is necessary to guard against reverse-pinvokes and
@@ -984,7 +979,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.
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
public override int GetHashCode()
{
#if FEATURE_RANDOMIZED_STRING_HASHING
@@ -999,12 +993,10 @@ namespace System
// 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).
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
internal int GetLegacyNonRandomizedHashCode() {
unsafe {
fixed (char* src = &m_firstChar) {
@@ -1069,7 +1061,6 @@ namespace System
}
[Pure]
- [ComVisible(false)]
public Boolean StartsWith(String value, StringComparison comparisonType) {
if( (Object)value == null) {
throw new ArgumentNullException(nameof(value));
diff --git a/src/mscorlib/src/System/String.Manipulation.cs b/src/mscorlib/src/System/String.Manipulation.cs
index 194b4f8c59..e06141d669 100644
--- a/src/mscorlib/src/System/String.Manipulation.cs
+++ b/src/mscorlib/src/System/String.Manipulation.cs
@@ -14,10 +14,6 @@ namespace System
{
public partial class String
{
- private const int TrimHead = 0;
- private const int TrimTail = 1;
- private const int TrimBoth = 2;
-
unsafe private static void FillStringChecked(String dest, int destPos, String src)
{
Contract.Requires(dest != null);
@@ -176,7 +172,6 @@ namespace System
return result;
}
- [ComVisible(false)]
public static string Concat<T>(IEnumerable<T> values)
{
if (values == null)
@@ -227,7 +222,6 @@ namespace System
}
- [ComVisible(false)]
public static string Concat(IEnumerable<string> values)
{
if (values == null)
@@ -575,7 +569,6 @@ namespace System
return Join(separator, value, 0, value.Length);
}
- [ComVisible(false)]
public unsafe static string Join(string separator, params object[] values)
{
separator = separator ?? string.Empty;
@@ -586,7 +579,6 @@ namespace System
}
}
- [ComVisible(false)]
public unsafe static string Join<T>(string separator, IEnumerable<T> values)
{
separator = separator ?? string.Empty;
@@ -597,7 +589,6 @@ namespace System
}
}
- [ComVisible(false)]
public static string Join(string separator, IEnumerable<string> values)
{
if (values == null)
@@ -1043,16 +1034,14 @@ namespace System
return ReplaceInternal(oldValue, newValue);
}
- [ComVisible(false)]
- public String[] Split(char separator, StringSplitOptions options = StringSplitOptions.None) {
+ public unsafe String[] Split(char separator, StringSplitOptions options = StringSplitOptions.None) {
Contract.Ensures(Contract.Result<String[]>() != null);
- return SplitInternal(separator, Int32.MaxValue, options);
+ return SplitInternal(&separator, 1, int.MaxValue, options);
}
- [ComVisible(false)]
- public String[] Split(char separator, int count, StringSplitOptions options = StringSplitOptions.None) {
+ public unsafe String[] Split(char separator, int count, StringSplitOptions options = StringSplitOptions.None) {
Contract.Ensures(Contract.Result<String[]>() != null);
- return SplitInternal(separator, count, options);
+ return SplitInternal(&separator, 1, count, options);
}
// Creates an array of strings by splitting this string at each
@@ -1085,24 +1074,17 @@ namespace System
return SplitInternal(separator, count, StringSplitOptions.None);
}
- [ComVisible(false)]
public String[] Split(char[] separator, StringSplitOptions options) {
Contract.Ensures(Contract.Result<String[]>() != null);
return SplitInternal(separator, Int32.MaxValue, options);
}
- [ComVisible(false)]
public String[] Split(char[] separator, int count, StringSplitOptions options)
{
Contract.Ensures(Contract.Result<String[]>() != null);
return SplitInternal(separator, count, options);
}
- private unsafe String[] SplitInternal(char separator, int count, StringSplitOptions options)
- {
- return SplitInternal(&separator, 1, count, options);
- }
-
private unsafe String[] SplitInternal(char[] separator, int count, StringSplitOptions options)
{
fixed (char* pSeparators = separator)
@@ -1153,25 +1135,21 @@ namespace System
}
}
- [ComVisible(false)]
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 = StringSplitOptions.None) {
Contract.Ensures(Contract.Result<String[]>() != null);
return SplitInternal(separator ?? String.Empty, null, count, options);
}
- [ComVisible(false)]
public String [] Split(String[] separator, StringSplitOptions options) {
Contract.Ensures(Contract.Result<String[]>() != null);
return SplitInternal(null, separator, Int32.MaxValue, options);
}
- [ComVisible(false)]
public String[] Split(String[] separator, Int32 count, StringSplitOptions options) {
Contract.Ensures(Contract.Result<String[]>() != null);
return SplitInternal(null, separator, count, options);
@@ -1536,116 +1514,177 @@ namespace System
Contract.EndContractBlock();
return this.ToUpper(CultureInfo.InvariantCulture);
}
-
- // Removes a set of characters from the end of this string.
+
+ // Trims the whitespace from both ends of the string. Whitespace is defined by
+ // Char.IsWhiteSpace.
+ //
[Pure]
- public String Trim(params char[] trimChars) {
- if (null==trimChars || trimChars.Length == 0) {
- return TrimHelper(TrimBoth);
+ public string Trim()
+ {
+ Contract.Ensures(Contract.Result<string>() != null);
+ Contract.EndContractBlock();
+
+ return TrimWhiteSpaceHelper(TrimType.Both);
+ }
+
+ // Removes a set of characters from the beginning and end of this string.
+ public unsafe string Trim(char trimChar) => TrimHelper(&trimChar, 1, TrimType.Both);
+
+ // Removes a set of characters from the beginning and end of this string.
+ [Pure]
+ public unsafe string Trim(params char[] trimChars)
+ {
+ if (trimChars == null || trimChars.Length == 0)
+ {
+ return TrimWhiteSpaceHelper(TrimType.Both);
+ }
+ fixed (char* pTrimChars = &trimChars[0])
+ {
+ return TrimHelper(pTrimChars, trimChars.Length, TrimType.Both);
}
- return TrimHelper(trimChars,TrimBoth);
}
-
+
+ // Removes a set of characters from the beginning of this string.
+ public string TrimStart() => TrimWhiteSpaceHelper(TrimType.Head);
+
// Removes a set of characters from the beginning of this string.
- public String TrimStart(params char[] trimChars) {
- if (null==trimChars || trimChars.Length == 0) {
- return TrimHelper(TrimHead);
+ public unsafe string TrimStart(char trimChar) => TrimHelper(&trimChar, 1, TrimType.Head);
+
+ // Removes a set of characters from the beginning of this string.
+ public unsafe string TrimStart(params char[] trimChars)
+ {
+ if (trimChars == null || trimChars.Length == 0)
+ {
+ return TrimWhiteSpaceHelper(TrimType.Head);
}
- return TrimHelper(trimChars,TrimHead);
- }
-
-
- // Removes a set of characters from the end of this string.
- public String TrimEnd(params char[] trimChars) {
- if (null==trimChars || trimChars.Length == 0) {
- return TrimHelper(TrimTail);
+ fixed (char* pTrimChars = &trimChars[0])
+ {
+ return TrimHelper(pTrimChars, trimChars.Length, TrimType.Head);
}
- return TrimHelper(trimChars,TrimTail);
}
- // Trims the whitespace from both ends of the string. Whitespace is defined by
- // Char.IsWhiteSpace.
- //
- [Pure]
- public String Trim() {
- Contract.Ensures(Contract.Result<String>() != null);
- Contract.EndContractBlock();
+ // Removes a set of characters from the end of this string.
+ public string TrimEnd() => TrimWhiteSpaceHelper(TrimType.Tail);
- return TrimHelper(TrimBoth);
+ // Removes a set of characters from the end of this string.
+ public unsafe string TrimEnd(char trimChar) => TrimHelper(&trimChar, 1, TrimType.Tail);
+
+ // Removes a set of characters from the end of this string.
+ public unsafe string TrimEnd(params char[] trimChars)
+ {
+ if (trimChars == null || trimChars.Length == 0)
+ {
+ return TrimWhiteSpaceHelper(TrimType.Tail);
+ }
+ fixed (char* pTrimChars = &trimChars[0])
+ {
+ return TrimHelper(pTrimChars, trimChars.Length, TrimType.Tail);
+ }
}
-
- 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
- int end = this.Length-1;
- int start=0;
-
- //Trim specified characters.
- if (trimType !=TrimTail) {
- for (start=0; start < this.Length; start++) {
- if (!Char.IsWhiteSpace(this[start])) break;
+ private string TrimWhiteSpaceHelper(TrimType 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.
+ int end = Length - 1;
+ int start = 0;
+
+ // Trim specified characters.
+ if (trimType != TrimType.Tail)
+ {
+ for (start = 0; start < Length; start++)
+ {
+ if (!char.IsWhiteSpace(this[start]))
+ {
+ break;
+ }
}
}
-
- if (trimType !=TrimHead) {
- for (end= Length -1; end >= start; end--) {
- if (!Char.IsWhiteSpace(this[end])) break;
+
+ if (trimType != TrimType.Head)
+ {
+ for (end = Length - 1; end >= start; end--)
+ {
+ if (!char.IsWhiteSpace(this[end]))
+ {
+ break;
+ }
}
}
return CreateTrimmedString(start, end);
}
-
-
- 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
- int end = this.Length-1;
- int start=0;
-
- //Trim specified characters.
- if (trimType !=TrimTail) {
- for (start=0; start < this.Length; start++) {
+
+ private unsafe string TrimHelper(char* trimChars, int trimCharsLength, TrimType trimType)
+ {
+ Debug.Assert(trimChars != null);
+ Debug.Assert(trimCharsLength > 0);
+
+ // end will point to the first non-trimmed character on the right.
+ // start will point to the first non-trimmed character on the left.
+ int end = Length - 1;
+ int start = 0;
+
+ // Trim specified characters.
+ if (trimType != TrimType.Tail)
+ {
+ for (start = 0; start < Length; start++)
+ {
int i = 0;
char ch = this[start];
- for( i = 0; i < trimChars.Length; i++) {
- if( trimChars[i] == ch) break;
+ for (i = 0; i < trimCharsLength; i++)
+ {
+ if (trimChars[i] == ch)
+ {
+ break;
+ }
}
- if( i == trimChars.Length) { // the character is not white space
- break;
+ if (i == trimCharsLength)
+ {
+ // The character is not in trimChars, so stop trimming.
+ break;
}
}
}
-
- if (trimType !=TrimHead) {
- for (end= Length -1; end >= start; end--) {
- int i = 0;
- char ch = this[end];
- for(i = 0; i < trimChars.Length; i++) {
- if( trimChars[i] == ch) break;
+
+ if (trimType != TrimType.Head)
+ {
+ for (end = Length - 1; end >= start; end--)
+ {
+ int i = 0;
+ char ch = this[end];
+ for (i = 0; i < trimCharsLength; i++)
+ {
+ if (trimChars[i] == ch)
+ {
+ break;
+ }
+ }
+ if (i == trimCharsLength)
+ {
+ // The character is not in trimChars, so stop trimming.
+ break;
}
- if( i == trimChars.Length) { // the character is not white space
- break;
- }
}
}
return CreateTrimmedString(start, end);
}
+ private string CreateTrimmedString(int start, int end)
+ {
+ int len = end - start + 1;
+ return
+ len == Length ? this :
+ len == 0 ? string.Empty :
+ InternalSubString(start, len);
+ }
- private String CreateTrimmedString(int start, int end) {
- int len = end -start + 1;
- if (len == this.Length) {
- // Don't allocate a new string as the trimmed string has not changed.
- return this;
- }
-
- if( len == 0) {
- return String.Empty;
- }
- return InternalSubString(start, len);
+ private enum TrimType
+ {
+ Head = 0,
+ Tail = 1,
+ Both = 2
}
}
}
diff --git a/src/mscorlib/src/System/String.cs b/src/mscorlib/src/System/String.cs
index f9162ff528..175e396633 100644
--- a/src/mscorlib/src/System/String.cs
+++ b/src/mscorlib/src/System/String.cs
@@ -37,7 +37,6 @@ namespace System {
// implemented as a part of String. As with arrays, character positions
// (indices) are zero-based.
- [ComVisible(true)]
[Serializable]
public sealed partial class String : IComparable, ICloneable, IConvertible, IEnumerable
, IComparable<String>, IEnumerable<char>, IEquatable<String>
@@ -331,18 +330,12 @@ namespace System {
// These just wrap calls to Normalization class
public bool IsNormalized()
{
-#if !FEATURE_NORM_IDNA_ONLY
// Default to Form C
return IsNormalized(NormalizationForm.FormC);
-#else
- // Default to Form IDNA
- return IsNormalized((NormalizationForm)ExtendedNormalizationForms.FormIdna);
-#endif
}
public bool IsNormalized(NormalizationForm normalizationForm)
{
-#if !FEATURE_NORM_IDNA_ONLY
if (this.IsFastSort())
{
// If its FastSort && one of the 4 main forms, then its already normalized
@@ -352,24 +345,17 @@ namespace System {
normalizationForm == NormalizationForm.FormKD )
return true;
}
-#endif // !FEATURE_NORM_IDNA_ONLY
return Normalization.IsNormalized(this, normalizationForm);
}
public String Normalize()
{
-#if !FEATURE_NORM_IDNA_ONLY
// Default to Form C
return Normalize(NormalizationForm.FormC);
-#else
- // Default to Form IDNA
- return Normalize((NormalizationForm)ExtendedNormalizationForms.FormIdna);
-#endif
}
public String Normalize(NormalizationForm normalizationForm)
{
-#if !FEATURE_NORM_IDNA_ONLY
if (this.IsAscii())
{
// If its FastSort && one of the 4 main forms, then its already normalized
@@ -379,7 +365,6 @@ namespace System {
normalizationForm == NormalizationForm.FormKD )
return this;
}
-#endif // !FEATURE_NORM_IDNA_ONLY
return Normalization.Normalize(this, normalizationForm);
}
@@ -801,12 +786,14 @@ namespace System {
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern bool IsAscii();
+#if FEATURE_COMINTEROP
// Set extra byte for odd-sized strings that came from interop as BSTR.
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern void SetTrailByte(byte data);
// Try to retrieve the extra byte - returns false if not present.
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern bool TryGetTrailByte(out byte data);
+#endif
public CharEnumerator GetEnumerator() {
Contract.Ensures(Contract.Result<CharEnumerator>() != null);
@@ -842,10 +829,8 @@ namespace System {
}
}
-#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 02e8d71d0e..cf65c48c2b 100644
--- a/src/mscorlib/src/System/StringComparer.cs
+++ b/src/mscorlib/src/System/StringComparer.cs
@@ -13,7 +13,6 @@ namespace System {
[Serializable]
- [System.Runtime.InteropServices.ComVisible(true)]
public abstract class StringComparer : IComparer, IEqualityComparer, IComparer<string>, IEqualityComparer<string>{
private static readonly StringComparer _invariantCulture = new CultureAwareComparer(CultureInfo.InvariantCulture, false);
private static readonly StringComparer _invariantCultureIgnoreCase = new CultureAwareComparer(CultureInfo.InvariantCulture, true);
@@ -162,11 +161,6 @@ namespace System {
_ignoreCase = ignoreCase;
}
- internal CultureAwareComparer(CompareInfo compareInfo, bool ignoreCase) {
- _compareInfo = compareInfo;
- _ignoreCase = ignoreCase;
- }
-
public override int Compare(string x, string y) {
if (Object.ReferenceEquals(x, y)) return 0;
if (x == null) return -1;
@@ -211,9 +205,6 @@ namespace System {
}
#if FEATURE_RANDOMIZED_STRING_HASHING
- IEqualityComparer IWellKnownStringEqualityComparer.GetRandomizedEqualityComparer() {
- return new CultureAwareRandomizedComparer(_compareInfo, _ignoreCase);
- }
IEqualityComparer IWellKnownStringEqualityComparer.GetEqualityComparerForSerialization() {
return this;
@@ -222,77 +213,6 @@ namespace System {
}
-#if FEATURE_RANDOMIZED_STRING_HASHING
- internal sealed class CultureAwareRandomizedComparer : StringComparer, IWellKnownStringEqualityComparer {
-
- private CompareInfo _compareInfo;
- private bool _ignoreCase;
- private long _entropy;
-
- internal CultureAwareRandomizedComparer(CompareInfo compareInfo, bool ignoreCase) {
- _compareInfo = compareInfo;
- _ignoreCase = ignoreCase;
- _entropy = HashHelpers.GetEntropy();
- }
-
- public override int Compare(string x, string y) {
- if (Object.ReferenceEquals(x, y)) return 0;
- if (x == null) return -1;
- if (y == null) return 1;
- return _compareInfo.Compare(x, y, _ignoreCase? CompareOptions.IgnoreCase : CompareOptions.None);
- }
-
- public override bool Equals(string x, string y) {
- if (Object.ReferenceEquals(x ,y)) return true;
- if (x == null || y == null) return false;
-
- return (_compareInfo.Compare(x, y, _ignoreCase? CompareOptions.IgnoreCase : CompareOptions.None) == 0);
- }
-
- public override int GetHashCode(string obj) {
- if( obj == null) {
- throw new ArgumentNullException(nameof(obj));
- }
- Contract.EndContractBlock();
-
- CompareOptions options = CompareOptions.None;
-
- if( _ignoreCase) {
- options |= CompareOptions.IgnoreCase;
- }
-
-#if FEATURE_COREFX_GLOBALIZATION
- return _compareInfo.GetHashCodeOfStringCore(obj, options, true, _entropy);
-#else
- return _compareInfo.GetHashCodeOfString(obj, options, true, _entropy);
-#endif
- }
-
- // Equals method for the comparer itself.
- public override bool Equals(Object obj){
- CultureAwareRandomizedComparer comparer = obj as CultureAwareRandomizedComparer;
- if( comparer == null) {
- return false;
- }
- return (this._ignoreCase == comparer._ignoreCase) && (this._compareInfo.Equals(comparer._compareInfo)) && (this._entropy == comparer._entropy);
- }
-
- public override int GetHashCode() {
- int hashCode = _compareInfo.GetHashCode() ;
- return ((_ignoreCase ? (~hashCode) : hashCode) ^ ((int) (_entropy & 0x7FFFFFFF)));
- }
-
- IEqualityComparer IWellKnownStringEqualityComparer.GetRandomizedEqualityComparer() {
- return new CultureAwareRandomizedComparer(_compareInfo, _ignoreCase);
- }
-
- // We want to serialize the old comparer.
- IEqualityComparer IWellKnownStringEqualityComparer.GetEqualityComparerForSerialization() {
- return new CultureAwareComparer(_compareInfo, _ignoreCase);
- }
- }
-#endif
-
// Provide x more optimal implementation of ordinal comparison.
[Serializable]
internal sealed class OrdinalComparer : StringComparer
@@ -360,9 +280,6 @@ namespace System {
}
#if FEATURE_RANDOMIZED_STRING_HASHING
- IEqualityComparer IWellKnownStringEqualityComparer.GetRandomizedEqualityComparer() {
- return new OrdinalRandomizedComparer(_ignoreCase);
- }
IEqualityComparer IWellKnownStringEqualityComparer.GetEqualityComparerForSerialization() {
return this;
@@ -371,89 +288,11 @@ namespace System {
}
-
#if FEATURE_RANDOMIZED_STRING_HASHING
- internal sealed class OrdinalRandomizedComparer : StringComparer, IWellKnownStringEqualityComparer {
- private bool _ignoreCase;
- private long _entropy;
-
- internal OrdinalRandomizedComparer(bool ignoreCase) {
- _ignoreCase = ignoreCase;
- _entropy = HashHelpers.GetEntropy();
- }
-
- public override int Compare(string x, string y) {
- if (Object.ReferenceEquals(x, y)) return 0;
- if (x == null) return -1;
- if (y == null) return 1;
-
- if( _ignoreCase) {
- return String.Compare(x, y, StringComparison.OrdinalIgnoreCase);
- }
-
- return String.CompareOrdinal(x, y);
- }
-
- public override bool Equals(string x, string y) {
- if (Object.ReferenceEquals(x ,y)) return true;
- if (x == null || y == null) return false;
-
- if( _ignoreCase) {
- if( x.Length != y.Length) {
- return false;
- }
- return (String.Compare(x, y, StringComparison.OrdinalIgnoreCase) == 0);
- }
- return x.Equals(y);
- }
-
- public override int GetHashCode(string obj) {
- if( obj == null) {
- throw new ArgumentNullException(nameof(obj));
- }
- Contract.EndContractBlock();
-
- if( _ignoreCase) {
-#if FEATURE_COREFX_GLOBALIZATION
- return CultureInfo.InvariantCulture.CompareInfo.GetHashCodeOfStringCore(obj, CompareOptions.IgnoreCase, true, _entropy);
-#else
- return TextInfo.GetHashCodeOrdinalIgnoreCase(obj, true, _entropy);
-#endif
- }
-
- return String.InternalMarvin32HashString(obj, obj.Length, _entropy);
- }
-
- // Equals method for the comparer itself.
- public override bool Equals(Object obj){
- OrdinalRandomizedComparer comparer = obj as OrdinalRandomizedComparer;
- if( comparer == null) {
- return false;
- }
- return (this._ignoreCase == comparer._ignoreCase) && (this._entropy == comparer._entropy);
- }
-
- public override int GetHashCode() {
- string name = "OrdinalRandomizedComparer";
- int hashCode = name.GetHashCode();
- return ((_ignoreCase ? (~hashCode) : hashCode) ^ ((int) (_entropy & 0x7FFFFFFF)));
- }
-
- IEqualityComparer IWellKnownStringEqualityComparer.GetRandomizedEqualityComparer() {
- return new OrdinalRandomizedComparer(_ignoreCase);
- }
-
- // We want to serialize the old comparer.
- IEqualityComparer IWellKnownStringEqualityComparer.GetEqualityComparerForSerialization() {
- return new OrdinalComparer(_ignoreCase);
- }
- }
// This interface is implemented by string comparers in the framework that can opt into
// randomized hashing behaviors.
internal interface IWellKnownStringEqualityComparer {
- // Get an IEqualityComparer that has the same equality comparision rules as "this" but uses Randomized Hashing.
- IEqualityComparer GetRandomizedEqualityComparer();
// Get an IEqaulityComparer that can be serailzied (e.g., it exists in older versions).
IEqualityComparer GetEqualityComparerForSerialization();
}
diff --git a/src/mscorlib/src/System/StringComparison.cs b/src/mscorlib/src/System/StringComparison.cs
index aa83e396b6..c654f7200f 100644
--- a/src/mscorlib/src/System/StringComparison.cs
+++ b/src/mscorlib/src/System/StringComparison.cs
@@ -13,11 +13,12 @@
**
**
===========================================================*/
-namespace System{
-
+
+namespace System
+{
[Serializable]
-[System.Runtime.InteropServices.ComVisible(true)]
- public enum StringComparison {
+ public enum StringComparison
+ {
CurrentCulture = 0,
CurrentCultureIgnoreCase = 1,
InvariantCulture = 2,
diff --git a/src/mscorlib/src/System/StringSplitOptions.cs b/src/mscorlib/src/System/StringSplitOptions.cs
index ae95aae9f8..43b626a010 100644
--- a/src/mscorlib/src/System/StringSplitOptions.cs
+++ b/src/mscorlib/src/System/StringSplitOptions.cs
@@ -2,15 +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.
-using System.Runtime.InteropServices;
-
namespace System
{
- [ComVisible(false)]
[Flags]
public enum StringSplitOptions
{
None = 0,
RemoveEmptyEntries = 1
}
-}
+} \ No newline at end of file
diff --git a/src/mscorlib/src/System/StubHelpers.cs b/src/mscorlib/src/System/StubHelpers.cs
index 26a227628a..2d5926b923 100644
--- a/src/mscorlib/src/System/StubHelpers.cs
+++ b/src/mscorlib/src/System/StubHelpers.cs
@@ -19,7 +19,6 @@ namespace System.StubHelpers {
using System.Diagnostics;
using System.Diagnostics.Contracts;
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
internal static class AnsiCharMarshaler
{
// The length of the returned array is an approximation based on the length of the input string and the system
@@ -27,7 +26,8 @@ namespace System.StubHelpers {
unsafe static internal byte[] DoAnsiConversion(string str, bool fBestFit, bool fThrowOnUnmappableChar, out int cbLength)
{
byte[] buffer = new byte[(str.Length + 1) * Marshal.SystemMaxDBCSCharSize];
- fixed (byte *bufferPtr = buffer)
+ BCLDebug.Assert(buffer.Length != 0);
+ fixed (byte *bufferPtr = &buffer[0])
{
cbLength = str.ConvertToAnsi(bufferPtr, buffer.Length, fBestFit, fThrowOnUnmappableChar);
}
@@ -53,7 +53,6 @@ namespace System.StubHelpers {
}
} // class AnsiCharMarshaler
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
internal static class CSTRMarshaler
{
static internal unsafe IntPtr ConvertToNative(int flags, string strManaged, IntPtr pNativeBuffer)
@@ -121,7 +120,6 @@ namespace System.StubHelpers {
}
} // class CSTRMarshaler
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
internal static class UTF8Marshaler
{
const int MAX_UTF8_CHAR_SIZE = 3;
@@ -178,7 +176,6 @@ namespace System.StubHelpers {
}
}
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
internal static class UTF8BufferMarshaler
{
static internal unsafe IntPtr ConvertToNative(StringBuilder sb, IntPtr pNativeBuffer, int flags)
@@ -218,7 +215,7 @@ namespace System.StubHelpers {
// null argument.
char[] cCharBuffer = new char[numChar + 1];
cCharBuffer[numChar] = '\0';
- fixed (char* pBuffer = cCharBuffer)
+ fixed (char* pBuffer = &cCharBuffer[0])
{
numChar = Encoding.UTF8.GetChars((byte*)pNative, nbBytes, pBuffer, numChar);
// replace string builder internal buffer
@@ -229,7 +226,6 @@ namespace System.StubHelpers {
#if FEATURE_COMINTEROP
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
internal static class BSTRMarshaler
{
static internal unsafe IntPtr ConvertToNative(string strManaged, IntPtr pNativeBuffer)
@@ -357,7 +353,6 @@ namespace System.StubHelpers {
#endif // FEATURE_COMINTEROP
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
internal static class VBByValStrMarshaler
{
static internal unsafe IntPtr ConvertToNative(string strManaged, bool fBestFit, bool fThrowOnUnmappableChar, ref int cch)
@@ -423,7 +418,6 @@ namespace System.StubHelpers {
#if FEATURE_COMINTEROP
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
internal static class AnsiBSTRMarshaler
{
static internal unsafe IntPtr ConvertToNative(int flags, string strManaged)
@@ -475,7 +469,6 @@ namespace System.StubHelpers {
#endif // FEATURE_COMINTEROP
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
internal static class WSTRBufferMarshaler
{
static internal IntPtr ConvertToNative(string strManaged)
@@ -506,7 +499,6 @@ namespace System.StubHelpers {
public Int64 UniversalTime;
};
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
internal static class DateTimeOffsetMarshaler {
// Numer of ticks counted between 0001-01-01, 00:00:00 and 1601-01-01, 00:00:00.
@@ -534,7 +526,6 @@ namespace System.StubHelpers {
#if FEATURE_COMINTEROP
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
internal static class HStringMarshaler
{
// Slow-path, which requires making a copy of the managed string into the resulting HSTRING
@@ -597,7 +588,6 @@ namespace System.StubHelpers {
}
} // class HStringMarshaler
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
internal static class ObjectMarshaler
{
[MethodImplAttribute(MethodImplOptions.InternalCall)]
@@ -612,7 +602,6 @@ namespace System.StubHelpers {
#endif // FEATURE_COMINTEROP
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
internal static class ValueClassMarshaler
{
[MethodImplAttribute(MethodImplOptions.InternalCall)]
@@ -625,7 +614,6 @@ namespace System.StubHelpers {
static internal extern void ClearNative(IntPtr dst, IntPtr pMT);
} // class ValueClassMarshaler
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
internal static class DateMarshaler
{
[MethodImplAttribute(MethodImplOptions.InternalCall)]
@@ -637,7 +625,6 @@ namespace System.StubHelpers {
} // class DateMarshaler
#if FEATURE_COMINTEROP
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
[FriendAccessAllowed]
internal static class InterfaceMarshaler
{
@@ -657,7 +644,6 @@ namespace System.StubHelpers {
#endif // FEATURE_COMINTEROP
#if FEATURE_COMINTEROP
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
internal static class UriMarshaler
{
[MethodImplAttribute(MethodImplOptions.InternalCall)]
@@ -713,7 +699,6 @@ namespace System.StubHelpers {
}
#endif // FEATURE_COMINTEROP
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
internal static class MngdNativeArrayMarshaler
{
[MethodImplAttribute(MethodImplOptions.InternalCall)]
@@ -740,7 +725,6 @@ namespace System.StubHelpers {
} // class MngdNativeArrayMarshaler
#if FEATURE_COMINTEROP
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
internal static class MngdSafeArrayMarshaler
{
[MethodImplAttribute(MethodImplOptions.InternalCall)]
@@ -762,7 +746,6 @@ namespace System.StubHelpers {
static internal extern void ClearNative(IntPtr pMarshalState, ref object pManagedHome, IntPtr pNativeHome);
} // class MngdSafeArrayMarshaler
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
internal static class MngdHiddenLengthArrayMarshaler
{
[MethodImplAttribute(MethodImplOptions.InternalCall)]
@@ -923,7 +906,6 @@ namespace System.StubHelpers {
#endif // FEATURE_COMINTEROP
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
internal static class MngdRefCustomMarshaler
{
[MethodImplAttribute(MethodImplOptions.InternalCall)]
@@ -942,7 +924,6 @@ namespace System.StubHelpers {
static internal extern void ClearManaged(IntPtr pMarshalState, ref object pManagedHome, IntPtr pNativeHome);
} // class MngdRefCustomMarshaler
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
internal struct AsAnyMarshaler
{
private const ushort VTHACK_ANSICHAR = 253;
@@ -1282,7 +1263,6 @@ namespace System.StubHelpers {
} // struct AsAnyMarshaler
#if FEATURE_COMINTEROP
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
internal static class NullableMarshaler
{
static internal IntPtr ConvertToNative<T>(ref Nullable<T> pManaged) where T : struct
@@ -1344,7 +1324,6 @@ namespace System.StubHelpers {
internal static extern System.Type GetTypeFromWinRTTypeName(string typeName, out bool isPrimitive);
}
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
internal static class SystemTypeMarshaler
{
internal static unsafe void ConvertToNative(System.Type managedType, TypeNameNative *pNativeType)
@@ -1431,7 +1410,6 @@ namespace System.StubHelpers {
} // class SystemTypeMarshaler
// For converting WinRT's Windows.Foundation.HResult into System.Exception and vice versa.
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
internal static class HResultExceptionMarshaler
{
static internal unsafe int ConvertToNative(Exception ex)
@@ -1469,7 +1447,6 @@ namespace System.StubHelpers {
}
} // class HResultExceptionMarshaler
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
internal static class KeyValuePairMarshaler
{
internal static IntPtr ConvertToNative<K, V>([In] ref KeyValuePair<K, V> pair)
@@ -1534,7 +1511,6 @@ namespace System.StubHelpers {
public bool m_owned;
} // class CleanupWorkListElement
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
internal sealed class CleanupWorkList
{
private List<CleanupWorkListElement> m_list = new List<CleanupWorkListElement>();
@@ -1545,7 +1521,6 @@ namespace System.StubHelpers {
m_list.Add(elem);
}
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
public void Destroy()
{
for (int i = m_list.Count - 1; i >= 0; i--)
@@ -1556,7 +1531,6 @@ namespace System.StubHelpers {
}
} // class CleanupWorkList
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
[SuppressUnmanagedCodeSecurityAttribute()]
internal static class StubHelpers
{
@@ -1593,7 +1567,6 @@ namespace System.StubHelpers {
return SafeHandleAddRef(handle, ref element.m_owned);
}
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
static internal void DestroyCleanupList(ref CleanupWorkList pCleanupWorkList)
{
if (pCleanupWorkList != null)
@@ -1655,7 +1628,6 @@ namespace System.StubHelpers {
}
// Releases the SH (to be called from finally block).
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
static internal void SafeHandleRelease(SafeHandle pHandle)
{
if (pHandle == null)
diff --git a/src/mscorlib/src/System/SystemException.cs b/src/mscorlib/src/System/SystemException.cs
index 8a54124e3e..f4779a2cd4 100644
--- a/src/mscorlib/src/System/SystemException.cs
+++ b/src/mscorlib/src/System/SystemException.cs
@@ -2,30 +2,31 @@
// 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;
- using System.Runtime.Serialization;
+using System.Runtime.Serialization;
+
+namespace System
+{
[Serializable]
- [System.Runtime.InteropServices.ComVisible(true)]
public class SystemException : Exception
{
- public SystemException()
- : base(Environment.GetResourceString("Arg_SystemException")) {
- SetErrorCode(__HResults.COR_E_SYSTEM);
- }
-
- public SystemException(String message)
- : base(message) {
- SetErrorCode(__HResults.COR_E_SYSTEM);
+ public SystemException()
+ : base(SR.Arg_SystemException)
+ {
+ HResult = __HResults.COR_E_SYSTEM;
}
-
- public SystemException(String message, Exception innerException)
- : base(message, innerException) {
- SetErrorCode(__HResults.COR_E_SYSTEM);
+
+ public SystemException(String message)
+ : base(message)
+ {
+ HResult = __HResults.COR_E_SYSTEM;
}
- protected SystemException(SerializationInfo info, StreamingContext context) : base(info, context) {
+ public SystemException(String message, Exception innerException)
+ : base(message, innerException)
+ {
+ HResult = __HResults.COR_E_SYSTEM;
}
+
+ protected SystemException(SerializationInfo info, StreamingContext context) : base(info, context) { }
}
}
diff --git a/src/mscorlib/src/System/Text/ASCIIEncoding.cs b/src/mscorlib/src/System/Text/ASCIIEncoding.cs
index fc7589f2d8..07b7f3e890 100644
--- a/src/mscorlib/src/System/Text/ASCIIEncoding.cs
+++ b/src/mscorlib/src/System/Text/ASCIIEncoding.cs
@@ -6,7 +6,6 @@ namespace System.Text
{
using System;
using System.Runtime.Serialization;
- using System.Security.Permissions;
using System.Diagnostics;
using System.Diagnostics.Contracts;
@@ -22,7 +21,6 @@ namespace System.Text
//
[Serializable]
-[System.Runtime.InteropServices.ComVisible(true)]
public class ASCIIEncoding : Encoding
{
// Used by Encoding.ASCII for lazy initialization
@@ -72,7 +70,6 @@ namespace System.Text
}
[CLSCompliant(false)]
- [System.Runtime.InteropServices.ComVisible(false)]
public override unsafe int GetByteCount(char* chars, int count)
{
return EncodingForwarder.GetByteCount(this, chars, count);
@@ -100,7 +97,6 @@ namespace System.Text
}
[CLSCompliant(false)]
- [System.Runtime.InteropServices.ComVisible(false)]
public override unsafe int GetBytes(char* chars, int charCount, byte* bytes, int byteCount)
{
return EncodingForwarder.GetBytes(this, chars, charCount, bytes, byteCount);
@@ -115,7 +111,6 @@ namespace System.Text
}
[CLSCompliant(false)]
- [System.Runtime.InteropServices.ComVisible(false)]
public override unsafe int GetCharCount(byte* bytes, int count)
{
return EncodingForwarder.GetCharCount(this, bytes, count);
@@ -128,7 +123,6 @@ namespace System.Text
}
[CLSCompliant(false)]
- [System.Runtime.InteropServices.ComVisible(false)]
public unsafe override int GetChars(byte* bytes, int byteCount, char* chars, int charCount)
{
return EncodingForwarder.GetChars(this, bytes, byteCount, chars, charCount);
@@ -741,7 +735,6 @@ namespace System.Text
// True if and only if the encoding only uses single byte code points. (Ie, ASCII, 1252, etc)
- [System.Runtime.InteropServices.ComVisible(false)]
public override bool IsSingleByte
{
get
@@ -750,14 +743,12 @@ namespace System.Text
}
}
- [System.Runtime.InteropServices.ComVisible(false)]
public override Decoder GetDecoder()
{
return new DecoderNLS(this);
}
- [System.Runtime.InteropServices.ComVisible(false)]
public override Encoder GetEncoder()
{
return new EncoderNLS(this);
diff --git a/src/mscorlib/src/System/Text/BaseCodePageEncoding.cs b/src/mscorlib/src/System/Text/BaseCodePageEncoding.cs
deleted file mode 100644
index 0a42237dc1..0000000000
--- a/src/mscorlib/src/System/Text/BaseCodePageEncoding.cs
+++ /dev/null
@@ -1,332 +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_CODEPAGES_FILE
-namespace System.Text
-{
- using System;
- using System.Diagnostics;
- using System.Diagnostics.Contracts;
- using System.Globalization;
- using System.Runtime.InteropServices;
- using System.Security;
- using System.Collections;
- using System.Runtime.CompilerServices;
- using System.Runtime.Serialization;
- using System.Runtime.Versioning;
- using System.Security.Permissions;
- using Microsoft.Win32.SafeHandles;
-
- // Our input file data structures look like:
- //
- // Header Structure Looks Like:
- // struct NLSPlusHeader
- // {
- // WORD[16] filename; // 32 bytes
- // WORD[4] version; // 8 bytes = 40 // I.e: 3, 2, 0, 0
- // WORD count; // 2 bytes = 42 // Number of code page index's that'll follow
- // }
- //
- // Each code page section looks like:
- // struct NLSCodePageIndex
- // {
- // WORD[16] codePageName; // 32 bytes
- // WORD codePage; // +2 bytes = 34
- // WORD byteCount; // +2 bytes = 36
- // DWORD offset; // +4 bytes = 40 // Bytes from beginning of FILE.
- // }
- //
- // Each code page then has its own header
- // struct NLSCodePage
- // {
- // WORD[16] codePageName; // 32 bytes
- // WORD[4] version; // 8 bytes = 40 // I.e: 3.2.0.0
- // WORD codePage; // 2 bytes = 42
- // WORD byteCount; // 2 bytes = 44 // 1 or 2 byte code page (SBCS or DBCS)
- // WORD unicodeReplace; // 2 bytes = 46 // default replacement unicode character
- // WORD byteReplace; // 2 bytes = 48 // default replacement byte(s)
- // BYTE[] data; // data section
- // }
-
- [Serializable]
- internal abstract class BaseCodePageEncoding : EncodingNLS, ISerializable
- {
- // Static & Const stuff
- internal const String CODE_PAGE_DATA_FILE_NAME = "codepages.nlp";
- [NonSerialized]
- protected int dataTableCodePage;
-
- // Variables to help us allocate/mark our memory section correctly
- [NonSerialized]
- protected bool bFlagDataTable = true;
- [NonSerialized]
- protected int iExtraBytes = 0;
-
- // Our private unicode to bytes best fit array and visa versa.
- [NonSerialized]
- protected char[] arrayUnicodeBestFit = null;
- [NonSerialized]
- protected char[] arrayBytesBestFit = null;
-
- // This is used to help ISCII, EUCJP and ISO2022 figure out they're MlangEncodings
- [NonSerialized]
- protected bool m_bUseMlangTypeForSerialization = false;
-
- static BaseCodePageEncoding()
- {
- }
-
- //
- // This is the header for the native data table that we load from CODE_PAGE_DATA_FILE_NAME.
- //
- // Explicit layout is used here since a syntax like char[16] can not be used in sequential layout.
- [StructLayout(LayoutKind.Explicit)]
- internal unsafe struct CodePageDataFileHeader
- {
- [FieldOffset(0)]
- internal char TableName; // WORD[16]
- [FieldOffset(0x20)]
- internal ushort Version; // WORD[4]
- [FieldOffset(0x28)]
- internal short CodePageCount; // WORD
- [FieldOffset(0x2A)]
- internal short unused1; // Add a unused WORD so that CodePages is aligned with DWORD boundary.
- // Otherwise, 64-bit version will fail.
- [FieldOffset(0x2C)]
- internal CodePageIndex CodePages; // Start of code page index
- }
-
- [StructLayout(LayoutKind.Explicit, Pack=2)]
- internal unsafe struct CodePageIndex
- {
- [FieldOffset(0)]
- internal char CodePageName; // WORD[16]
- [FieldOffset(0x20)]
- internal short CodePage; // WORD
- [FieldOffset(0x22)]
- internal short ByteCount; // WORD
- [FieldOffset(0x24)]
- internal int Offset; // DWORD
- }
-
- [StructLayout(LayoutKind.Explicit)]
- internal unsafe struct CodePageHeader
- {
- [FieldOffset(0)]
- internal char CodePageName; // WORD[16]
- [FieldOffset(0x20)]
- internal ushort VersionMajor; // WORD
- [FieldOffset(0x22)]
- internal ushort VersionMinor; // WORD
- [FieldOffset(0x24)]
- internal ushort VersionRevision;// WORD
- [FieldOffset(0x26)]
- internal ushort VersionBuild; // WORD
- [FieldOffset(0x28)]
- internal short CodePage; // WORD
- [FieldOffset(0x2a)]
- internal short ByteCount; // WORD // 1 or 2 byte code page (SBCS or DBCS)
- [FieldOffset(0x2c)]
- internal char UnicodeReplace; // WORD // default replacement unicode character
- [FieldOffset(0x2e)]
- internal ushort ByteReplace; // WORD // default replacement bytes
- [FieldOffset(0x30)]
- internal short FirstDataWord; // WORD[]
- }
-
- // Initialize our global stuff
- unsafe static CodePageDataFileHeader* m_pCodePageFileHeader =
- (CodePageDataFileHeader*)GlobalizationAssembly.GetGlobalizationResourceBytePtr(
- typeof(CharUnicodeInfo).Assembly, CODE_PAGE_DATA_FILE_NAME);
-
- // Real variables
- [NonSerialized]
- unsafe protected CodePageHeader* pCodePage = null;
-
- // Safe handle wrapper around section map view
- [NonSerialized]
- protected SafeViewOfFileHandle safeMemorySectionHandle = null;
-
- // Safe handle wrapper around mapped file handle
- [NonSerialized]
- protected SafeFileMappingHandle safeFileMappingHandle = null;
-
- internal BaseCodePageEncoding(int codepage) : this(codepage, codepage)
- {
- }
-
- internal BaseCodePageEncoding(int codepage, int dataCodePage) :
- base(codepage == 0? Microsoft.Win32.Win32Native.GetACP(): codepage)
- {
- // Remember number of code page that we'll be using the table for.
- dataTableCodePage = dataCodePage;
- LoadCodePageTables();
- }
-
- // Constructor called by serialization.
- internal BaseCodePageEncoding(SerializationInfo info, StreamingContext context) : base(0)
- {
- // We cannot ever call this, we've proxied ourselved to CodePageEncoding
- throw new ArgumentNullException("this");
- }
-
- // ISerializable implementation
- void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
- {
- // Make sure to get the base stuff too This throws if info is null
- SerializeEncoding(info, context);
- Debug.Assert(info!=null, "[BaseCodePageEncoding.GetObjectData] Expected null info to throw");
-
- // Just need Everett maxCharSize (BaseCodePageEncoding) or m_maxByteSize (MLangBaseCodePageEncoding)
- info.AddValue(m_bUseMlangTypeForSerialization ? "m_maxByteSize" : "maxCharSize",
- this.IsSingleByte ? 1 : 2);
-
- // Use this class or MLangBaseCodePageEncoding as our deserializer.
- info.SetType(m_bUseMlangTypeForSerialization ? typeof(MLangCodePageEncoding) :
- typeof(CodePageEncoding));
- }
-
- // We need to load tables for our code page
- private unsafe void LoadCodePageTables()
- {
- CodePageHeader* pCodePage = FindCodePage(dataTableCodePage);
-
- // Make sure we have one
- if (pCodePage == null)
- {
- // Didn't have one
- throw new NotSupportedException(
- Environment.GetResourceString("NotSupported_NoCodepageData", CodePage));
- }
-
- // Remember our code page
- this.pCodePage = pCodePage;
-
- // We had it, so load it
- LoadManagedCodePage();
- }
-
- // Look up the code page pointer
- 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
- // binary or anything so its not monsterously fast.
- for (int i = 0; i < m_pCodePageFileHeader->CodePageCount; i++)
- {
- CodePageIndex* pCodePageIndex = (&(m_pCodePageFileHeader->CodePages)) + i;
-
- if (pCodePageIndex->CodePage == codePage)
- {
- // Found it!
- CodePageHeader* pCodePage =
- (CodePageHeader*)((byte*)m_pCodePageFileHeader + pCodePageIndex->Offset);
- return pCodePage;
- }
- }
-
- // Couldn't find it
- return null;
- }
-
- // Get our code page byte count
- internal static unsafe int GetCodePageByteSize(int codePage)
- {
- // Get our code page info
- CodePageHeader* pCodePage = FindCodePage(codePage);
-
- // If null return 0
- if (pCodePage == null)
- return 0;
-
- 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
- protected abstract unsafe void LoadManagedCodePage();
-
- // Allocate memory to load our code page
- protected unsafe byte* GetSharedMemory(int iSize)
- {
- // Build our name
- String strName = GetMemorySectionName();
-
- IntPtr mappedFileHandle;
-
- // This gets shared memory for our map. If its can't, it gives us clean memory.
- Byte *pMemorySection = EncodingTable.nativeCreateOpenFileMapping(strName, iSize, out mappedFileHandle);
- Debug.Assert(pMemorySection != null,
- "[BaseCodePageEncoding.GetSharedMemory] Expected non-null memory section to be opened");
-
- // If that failed, we have to die.
- if (pMemorySection == null)
- throw new OutOfMemoryException(
- Environment.GetResourceString("Arg_OutOfMemoryException"));
-
- // if we have null file handle. this means memory was allocated after
- // failing to open the mapped file.
-
- if (mappedFileHandle != IntPtr.Zero)
- {
- safeMemorySectionHandle = new SafeViewOfFileHandle((IntPtr) pMemorySection, true);
- safeFileMappingHandle = new SafeFileMappingHandle(mappedFileHandle, true);
- }
-
- return pMemorySection;
- }
-
- protected unsafe virtual String GetMemorySectionName()
- {
- int iUseCodePage = this.bFlagDataTable ? dataTableCodePage : CodePage;
-
- String strName = String.Format(CultureInfo.InvariantCulture, "NLS_CodePage_{0}_{1}_{2}_{3}_{4}",
- iUseCodePage, this.pCodePage->VersionMajor, this.pCodePage->VersionMinor,
- this.pCodePage->VersionRevision, this.pCodePage->VersionBuild);
-
- return strName;
- }
-
- protected abstract unsafe void ReadBestFitTable();
-
- internal override char[] GetBestFitUnicodeToBytesData()
- {
- // Read in our best fit table if necessary
- if (arrayUnicodeBestFit == null) ReadBestFitTable();
-
- Debug.Assert(arrayUnicodeBestFit != null,
- "[BaseCodePageEncoding.GetBestFitUnicodeToBytesData]Expected non-null arrayUnicodeBestFit");
-
- // Normally we don't have any best fit data.
- return arrayUnicodeBestFit;
- }
-
- internal override char[] GetBestFitBytesToUnicodeData()
- {
- // Read in our best fit table if necessary
- if (arrayBytesBestFit == null) ReadBestFitTable();
-
- Debug.Assert(arrayBytesBestFit != null,
- "[BaseCodePageEncoding.GetBestFitBytesToUnicodeData]Expected non-null arrayBytesBestFit");
-
- // Normally we don't have any best fit data.
- return arrayBytesBestFit;
- }
-
- // During the AppDomain shutdown the Encoding class may already finalized and the memory section
- // 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.
- internal unsafe void CheckMemorySection()
- {
- if (safeMemorySectionHandle != null && safeMemorySectionHandle.DangerousGetHandle() == IntPtr.Zero)
- {
- LoadManagedCodePage();
- }
- }
- }
-}
-
-#endif // FEATURE_CODEPAGES_FILE
diff --git a/src/mscorlib/src/System/Text/CodePageEncoding.cs b/src/mscorlib/src/System/Text/CodePageEncoding.cs
deleted file mode 100644
index 7805c6580a..0000000000
--- a/src/mscorlib/src/System/Text/CodePageEncoding.cs
+++ /dev/null
@@ -1,136 +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.
-
-
-// WARNING:
-//
-// This is just an IObjectReference proxy for the Code Page Encodings.
-namespace System.Text
-{
- using System;
- using System.Runtime.Serialization;
- using System.Security.Permissions;
- using System.Diagnostics;
- using System.Diagnostics.Contracts;
-
- /*=================================CodePageEncoding==================================
- ** This class is here only to deserialize the Code Page classes from Everett (V1.1) into
- ** Appropriate Whidbey (V2.0) objects. We also serialize the Whidbey classes
- ** using this proxy since we pretty much need one anyway and that solves Whidbey
- ** to Everett compatibility as well.
- ==============================================================================*/
-
- [Serializable]
- internal sealed class CodePageEncoding : IObjectReference, ISerializable
- {
- // Temp stuff
- [NonSerialized]
- private int m_codePage;
- [NonSerialized]
- private bool m_isReadOnly;
- [NonSerialized]
- private bool m_deserializedFromEverett = false;
-
- [NonSerialized]
- private EncoderFallback encoderFallback = null;
- [NonSerialized]
- private DecoderFallback decoderFallback = null;
-
- // Might need this when GetRealObjecting
- [NonSerialized]
- private Encoding realEncoding = null;
-
- // Constructor called by serialization.
- internal CodePageEncoding(SerializationInfo info, StreamingContext context)
- {
- // Any info?
- if (info==null) throw new ArgumentNullException(nameof(info));
- Contract.EndContractBlock();
-
- // All versions have a code page
- this.m_codePage = (int)info.GetValue("m_codePage", typeof(int));
-
- // See if we have a code page
- try
- {
- //
- // Try Whidbey V2.0 Fields
- //
- this.m_isReadOnly = (bool)info.GetValue("m_isReadOnly", typeof(bool));
-
- this.encoderFallback = (EncoderFallback)info.GetValue("encoderFallback", typeof(EncoderFallback));
- this.decoderFallback = (DecoderFallback)info.GetValue("decoderFallback", typeof(DecoderFallback));
- }
- catch (SerializationException)
- {
- //
- // Didn't have Whidbey things, must be Everett
- //
- this.m_deserializedFromEverett = true;
-
- // May as well be read only
- this.m_isReadOnly = true;
- }
- }
-
- // Just get it from GetEncoding
- public Object GetRealObject(StreamingContext context)
- {
- // Get our encoding (Note: This has default fallbacks for readonly and everett cases)
- this.realEncoding = Encoding.GetEncoding(this.m_codePage);
-
- // If its read only then it uses default fallbacks, otherwise pick up the new ones
- // Otherwise we want to leave the new one read only
- if (!this.m_deserializedFromEverett && !this.m_isReadOnly)
- {
- this.realEncoding = (Encoding)this.realEncoding.Clone();
- this.realEncoding.EncoderFallback = this.encoderFallback;
- this.realEncoding.DecoderFallback = this.decoderFallback;
- }
-
- return this.realEncoding;
- }
-
- // ISerializable implementation
- void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
- {
- // We cannot ever call this.
- Debug.Assert(false, "Didn't expect to make it to CodePageEncoding ISerializable.GetObjectData");
- throw new ArgumentException(Environment.GetResourceString("Arg_ExecutionEngineException"));
- }
-
- // Same problem with the Decoder, this only happens with Everett Decoders
- [Serializable]
- internal sealed class Decoder : IObjectReference, ISerializable
- {
- // Might need this when GetRealObjecting
- [NonSerialized]
- private Encoding realEncoding = null;
-
- // Constructor called by serialization, have to handle deserializing from Everett
- internal Decoder(SerializationInfo info, StreamingContext context)
- {
- // Any info?
- if (info==null) throw new ArgumentNullException(nameof(info));
- Contract.EndContractBlock();
-
- this.realEncoding = (Encoding)info.GetValue("encoding", typeof(Encoding));
- }
-
- // Just get it from GetDecider
- public Object GetRealObject(StreamingContext context)
- {
- return this.realEncoding.GetDecoder();
- }
-
- // ISerializable implementation, get data for this object
- void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
- {
- // We cannot ever call this.
- 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
deleted file mode 100644
index 28b85d591e..0000000000
--- a/src/mscorlib/src/System/Text/DBCSCodePageEncoding.cs
+++ /dev/null
@@ -1,1194 +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_CODEPAGES_FILE // requires BaseCodePageEncooding
-namespace System.Text
-{
- using System;
- using System.Diagnostics;
- using System.Diagnostics.Contracts;
- using System.Text;
- using System.Threading;
- using System.Runtime.Serialization;
- using System.Security;
- using System.Security.Permissions;
-
- // DBCSCodePageEncoding
- //
- [Serializable]
- internal class DBCSCodePageEncoding : BaseCodePageEncoding, ISerializable
- {
- // Pointers to our memory section parts
- [NonSerialized]
- protected unsafe char* mapBytesToUnicode = null; // char 65536
- [NonSerialized]
- protected unsafe ushort* mapUnicodeToBytes = null; // byte 65536
- [NonSerialized]
- protected unsafe int* mapCodePageCached = null; // to remember which CP is cached
-
- [NonSerialized]
- protected const char UNKNOWN_CHAR_FLAG=(char)0x0;
- [NonSerialized]
- protected const char UNICODE_REPLACEMENT_CHAR=(char)0xFFFD;
- [NonSerialized]
- protected const char LEAD_BYTE_CHAR=(char)0xFFFE; // For lead bytes
-
- // Note that even though we provide bytesUnknown and byteCountUnknown,
- // They aren't actually used because of the fallback mechanism. (char is though)
- [NonSerialized]
- ushort bytesUnknown;
- [NonSerialized]
- int byteCountUnknown;
- [NonSerialized]
- protected char charUnknown = (char)0;
-
- public DBCSCodePageEncoding(int codePage) : this(codePage, codePage)
- {
- }
-
- internal DBCSCodePageEncoding(int codePage, int dataCodePage) : base(codePage, dataCodePage)
- {
- }
-
- // Constructor called by serialization.
- // Note: We use the base GetObjectData however
- internal DBCSCodePageEncoding(SerializationInfo info, StreamingContext context) : base(0)
- {
- // Actually this can't ever get called, CodePageEncoding is our proxy
- Debug.Assert(false, "Didn't expect to make it to DBCSCodePageEncoding serialization constructor");
- throw new ArgumentNullException("this");
- }
-
- // MBCS data section:
- //
- // We treat each multibyte pattern as 2 bytes in our table. If its a single byte, then the high byte
- // for that position will be 0. When the table is loaded, leading bytes are flagged with 0xFFFE, so
- // when reading the table look up with each byte. If the result is 0xFFFE, then use 2 bytes to read
- // further data. FFFF is a special value indicating that the unicode code is the same as the
- // character code (this helps us support code points < 0x20). FFFD is used as replacement character.
- //
- // Normal table:
- // WCHAR* - Starting with MB code point 0.
- // FFFF indicates we are to use the multibyte value for our code point.
- // FFFE is the lead byte mark. (This should only appear in positions < 0x100)
- // FFFD is the replacement (unknown character) mark.
- // 2-20 means to advance the pointer 2-0x20 characters.
- // 1 means that to advance to the multibyte position contained in the next char.
- // 0 nothing special (I don't think its possible.)
- //
- // Table ends when multibyte position has advanced to 0xFFFF.
- //
- // Bytes->Unicode Best Fit table:
- // WCHAR* - Same as normal table, except first wchar is byte position to start at.
- //
- // Unicode->Bytes Best Fit Table:
- // WCHAR* - Same as normal table, except first wchar is char position to start at and
- // we loop through unicode code points and the table has the byte points that
- // corrospond to those unicode code points.
- // We have a managed code page entry, so load our tables
- //
- protected override unsafe void LoadManagedCodePage()
- {
- // Should be loading OUR code page
- 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
- if (pCodePage->ByteCount != 2)
- throw new NotSupportedException(
- Environment.GetResourceString("NotSupported_NoCodepageData", CodePage));
- // Remember our unknown bytes & chars
- bytesUnknown = pCodePage->ByteReplace;
- charUnknown = pCodePage->UnicodeReplace;
-
- // Need to make sure the fallback buffer's fallback char is correct
- if (this.DecoderFallback.IsMicrosoftBestFitFallback)
- {
- ((InternalDecoderBestFitFallback)(this.DecoderFallback)).cReplacement = charUnknown;
- }
-
- // Is our replacement bytesUnknown a single or double byte character?
- byteCountUnknown = 1;
- if (bytesUnknown > 0xff)
- byteCountUnknown++;
-
- // We use fallback encoder, which uses ?, which so far all of our tables do as well
- 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)
- // Plus 4 byte to remember CP # when done loading it. (Don't want to get IA64 or anything out of alignment)
- byte *pMemorySection = GetSharedMemory(65536 * 2 * 2 + 4 + this.iExtraBytes);
-
- mapBytesToUnicode = (char*)pMemorySection;
- mapUnicodeToBytes = (ushort*)(pMemorySection + 65536 * 2);
- mapCodePageCached = (int*)(pMemorySection + 65536 * 2 * 2 + this.iExtraBytes);
-
- // If its cached (& filled in) we don't have to do anything else
- if (*mapCodePageCached != 0)
- {
- 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.");
-
- // Special case for GB18030 because it mangles its own code page after this function
- if ((*mapCodePageCached != this.dataTableCodePage && this.bFlagDataTable) ||
- (*mapCodePageCached != this.CodePage && !this.bFlagDataTable))
- throw new OutOfMemoryException(
- Environment.GetResourceString("Arg_OutOfMemoryException"));
-
- // If its cached (& filled in) we don't have to do anything else
- return;
- }
-
- // Need to read our data file and fill in our section.
- // WARNING: Multiple code pieces could do this at once (so we don't have to lock machine-wide)
- // so be careful here. Only stick legal values in here, don't stick temporary values.
-
- // Move to the beginning of the data section
- char* pData = (char*)&(pCodePage->FirstDataWord);
-
- // We start at bytes position 0
- int bytePosition = 0;
- int useBytes = 0;
-
- while (bytePosition < 0x10000)
- {
- // Get the next byte
- char input = *pData;
- pData++;
-
- // build our table:
- if (input == 1)
- {
- // Use next data as our byte position
- bytePosition = (int)(*pData);
- pData++;
- continue;
- }
- else if (input < 0x20 && input > 0)
- {
- // Advance input characters
- bytePosition += input;
- continue;
- }
- else if (input == 0xFFFF)
- {
- // Same as our bytePosition
- useBytes = bytePosition;
- input = unchecked((char)bytePosition);
- }
- else if (input == LEAD_BYTE_CHAR) // 0xfffe
- {
- // Lead byte mark
- Debug.Assert(bytePosition < 0x100, "[DBCSCodePageEncoding.LoadManagedCodePage]expected lead byte to be < 0x100");
- useBytes = bytePosition;
- // input stays 0xFFFE
- }
- else if (input == UNICODE_REPLACEMENT_CHAR)
- {
- // Replacement char is already done
- bytePosition++;
- continue;
- }
- else
- {
- // Use this character
- useBytes = bytePosition;
- // input == input;
- }
-
- // We may need to clean up the selected character & position
- if (CleanUpBytes(ref useBytes))
- {
- // Use this selected character at the selected position, don't do this if not supposed to.
- if (input != LEAD_BYTE_CHAR)
- {
- // Don't do this for lead byte marks.
- mapUnicodeToBytes[input] = unchecked((ushort)useBytes);
- }
- mapBytesToUnicode[useBytes] = input;
- }
- bytePosition++;
- }
-
- // See if we have any clean up junk to do
- CleanUpEndBytes(mapBytesToUnicode);
-
- // We're done with our mapped section, set our flag so others don't have to rebuild table.
- // We only do this if we're flagging(using) the data table as our primary mechanism
- if (this.bFlagDataTable)
- *mapCodePageCached = this.dataTableCodePage;
- }
-
- // Any special processing for this code page
- protected virtual bool CleanUpBytes(ref int bytes)
- {
- return true;
- }
-
- // Any special processing for this code page
- protected virtual unsafe void CleanUpEndBytes(char* chars)
- {
- }
-
- // 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;
- }
- }
-
- // Read in our best fit table
- protected unsafe override void ReadBestFitTable()
- {
- // Lock so we don't confuse ourselves.
- lock(InternalSyncObject)
- {
- // If we got a best fit array already then don't do this
- if (arrayUnicodeBestFit == null)
- {
- //
- // Read in Best Fit table.
- //
-
- // First we have to advance past original character mapping table
- // Move to the beginning of the data section
- char* pData = (char*)&(pCodePage->FirstDataWord);
-
- // We start at bytes position 0
- int bytesPosition = 0;
-
- while (bytesPosition < 0x10000)
- {
- // Get the next byte
- char input = *pData;
- pData++;
-
- // build our table:
- if (input == 1)
- {
- // Use next data as our byte position
- bytesPosition = (int)(*pData);
- pData++;
- }
- else if (input < 0x20 && input > 0)
- {
- // Advance input characters
- bytesPosition += input;
- }
- else
- {
- // All other cases add 1 to bytes position
- bytesPosition++;
- }
- }
-
- // Now bytesPosition is at start of bytes->unicode best fit table
- char* pBytes2Unicode = pData;
-
- // Now pData should be pointing to first word of bytes -> unicode best fit table
- // (which we're also not using at the moment)
- int iBestFitCount = 0;
- bytesPosition = *pData;
- pData++;
-
- while (bytesPosition < 0x10000)
- {
- // Get the next byte
- char input = *pData;
- pData++;
-
- // build our table:
- if (input == 1)
- {
- // Use next data as our byte position
- bytesPosition = (int)(*pData);
- pData++;
- }
- else if (input < 0x20 && input > 0)
- {
- // Advance input characters
- bytesPosition += input;
- }
- else
- {
- // Use this character (unless its unknown, unk just skips 1)
- if (input != UNICODE_REPLACEMENT_CHAR)
- {
- int correctedChar = bytesPosition;
- if (CleanUpBytes(ref correctedChar))
- {
- // Sometimes correction makes them same as no best fit, skip those.
- if (mapBytesToUnicode[correctedChar] != input)
- {
- iBestFitCount++;
- }
- }
- }
-
- // Position gets incremented in any case.
- bytesPosition++;
- }
-
- }
-
- // Now we know how big the best fit table has to be
- char[] arrayTemp = new char[iBestFitCount * 2];
-
- // Now we know how many best fits we have, so go back & read them in
- iBestFitCount = 0;
- pData = pBytes2Unicode;
- bytesPosition = *pData;
- pData++;
- bool bOutOfOrder = false;
-
- // Read it all in again
- while (bytesPosition < 0x10000)
- {
- // Get the next byte
- char input = *pData;
- pData++;
-
- // build our table:
- if (input == 1)
- {
- // Use next data as our byte position
- bytesPosition = (int)(*pData);
- pData++;
- }
- else if (input < 0x20 && input > 0)
- {
- // Advance input characters
- bytesPosition += input;
- }
- else
- {
- // Use this character (unless its unknown, unk just skips 1)
- if (input != UNICODE_REPLACEMENT_CHAR)
- {
- int correctedChar = bytesPosition;
- if (CleanUpBytes(ref correctedChar))
- {
- // Sometimes correction makes them same as no best fit, skip those.
- if (mapBytesToUnicode[correctedChar] != input)
- {
- if (correctedChar != bytesPosition)
- bOutOfOrder = true;
-
- arrayTemp[iBestFitCount++] = unchecked((char)correctedChar);
- arrayTemp[iBestFitCount++] = input;
- }
- }
- }
-
- // Position gets incremented in any case.
- bytesPosition++;
- }
- }
-
- // If they're out of order we need to sort them.
- if (bOutOfOrder)
- {
- 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)
- {
- int iSmallest = i;
- char cSmallest = arrayTemp[i];
-
- for (int j = i + 2; j < arrayTemp.Length; j+=2)
- {
- // Find smallest one for front
- if (cSmallest > arrayTemp[j])
- {
- cSmallest = arrayTemp[j];
- iSmallest = j;
- }
- }
-
- // If smallest one is something else, switch them
- if (iSmallest != i)
- {
- char temp = arrayTemp[iSmallest];
- arrayTemp[iSmallest] = arrayTemp[i];
- arrayTemp[i] = temp;
- temp = arrayTemp[iSmallest+1];
- arrayTemp[iSmallest+1] = arrayTemp[i+1];
- arrayTemp[i+1] = temp;
- }
- }
- }
-
- // Remember our array
- arrayBytesBestFit = arrayTemp;
-
- // Now were at beginning of Unicode -> Bytes best fit table, need to count them
- char* pUnicode2Bytes = pData;
- int unicodePosition = *(pData++);
- iBestFitCount = 0;
-
- while (unicodePosition < 0x10000)
- {
- // Get the next byte
- char input = *pData;
- pData++;
-
- // build our table:
- if (input == 1)
- {
- // Use next data as our byte position
- unicodePosition = (int)*pData;
- pData++;
- }
- else if (input < 0x20 && input > 0)
- {
- // Advance input characters
- unicodePosition += input;
- }
- else
- {
- // Same as our unicodePosition or use this character
- if (input > 0)
- iBestFitCount++;
- unicodePosition++;
- }
- }
-
- // Allocate our table
- arrayTemp = new char[iBestFitCount*2];
-
- // Now do it again to fill the array with real values
- pData = pUnicode2Bytes;
- unicodePosition = *(pData++);
- iBestFitCount = 0;
-
- while (unicodePosition < 0x10000)
- {
- // Get the next byte
- char input = *pData;
- pData++;
-
- // build our table:
- if (input == 1)
- {
- // Use next data as our byte position
- unicodePosition = (int)*pData;
- pData++;
- }
- else if (input < 0x20 && input > 0)
- {
- // Advance input characters
- unicodePosition += input;
- }
- else
- {
- if (input > 0)
- {
- // Use this character, may need to clean it up
- int correctedChar = (int)input;
- if (CleanUpBytes(ref correctedChar))
- {
- arrayTemp[iBestFitCount++] = unchecked((char)unicodePosition);
- // Have to map it to Unicode because best fit will need unicode value of best fit char.
- arrayTemp[iBestFitCount++] = mapBytesToUnicode[correctedChar];
-
- // This won't work if it won't round trip.
- // 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.
- // 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));
- }
- }
- unicodePosition++;
- }
- }
-
- // Remember our array
- arrayUnicodeBestFit = arrayTemp;
- }
-
- }
- }
-
- // GetByteCount
- // Note: We start by assuming that the output will be the same as count. Having
- // an encoder or fallback may change that assumption
- 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
- 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.
- Debug.Assert(encoderFallback != null, "[DBCSCodePageEncoding.GetByteCount]Attempting to use null fallback");
-
- CheckMemorySection();
-
- // Get any left over characters
- char charLeftOver = (char)0;
- if (encoder != null)
- {
- charLeftOver = encoder.charLeftOver;
-
- // Only count if encoder.m_throwOnOverflow
- if (encoder.InternalHasFallbackBuffer && encoder.FallbackBuffer.Remaining > 0)
- throw new ArgumentException(Environment.GetResourceString("Argument_EncoderFallbackNotEmpty",
- this.EncodingName, encoder.Fallback.GetType()));
- }
-
- // prepare our end
- int byteCount = 0;
- char* charEnd = chars + count;
-
- // For fallback we will need a fallback buffer
- EncoderFallbackBuffer fallbackBuffer = null;
-
- // We may have a left over character from last time, try and process it.
- if (charLeftOver > 0)
- {
- 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.
- // Get Fallback
- fallbackBuffer = encoder.FallbackBuffer;
- fallbackBuffer.InternalInitialize(chars, charEnd, encoder, false);
- // This will fallback a pair if *chars is a low surrogate
- fallbackBuffer.InternalFallback(charLeftOver, ref chars);
- }
-
- // Now we may have fallback char[] already (from the encoder)
-
- // We have to use fallback method.
- char ch;
- while ((ch = (fallbackBuffer == null) ? '\0' : fallbackBuffer.InternalGetNextChar()) != 0 ||
- chars < charEnd)
- {
- // First unwind any fallback
- if (ch == 0)
- {
- // No fallback, just get next char
- ch = *chars;
- chars++;
- }
-
- // get byte for this char
- ushort sTemp = mapUnicodeToBytes[ch];
-
- // Check for fallback, this'll catch surrogate pairs too.
- if (sTemp == 0 && ch != (char)0)
- {
- if (fallbackBuffer == null)
- {
- // Initialize the buffer
- if (encoder == null)
- fallbackBuffer = this.encoderFallback.CreateFallbackBuffer();
- else
- fallbackBuffer = encoder.FallbackBuffer;
- fallbackBuffer.InternalInitialize(charEnd - count, charEnd, encoder, false);
- }
-
- // Get Fallback
- fallbackBuffer.InternalFallback(ch, ref chars);
- continue;
- }
-
- // We'll use this one
- byteCount++;
- if (sTemp >= 0x100)
- byteCount++;
- }
-
- return (int)byteCount;
- }
-
- 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
- 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.
- Debug.Assert(encoderFallback != null, "[DBCSCodePageEncoding.GetBytes]Attempting to use null encoder fallback");
-
- CheckMemorySection();
-
- // For fallback we will need a fallback buffer
- EncoderFallbackBuffer fallbackBuffer = null;
-
- // prepare our end
- char* charEnd = chars + charCount;
- char* charStart = chars;
- byte* byteStart = bytes;
- byte* byteEnd = bytes + byteCount;
-
- // Get any left over characters
- char charLeftOver = (char)0;
- if (encoder != null)
- {
- charLeftOver = encoder.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)
- fallbackBuffer = encoder.FallbackBuffer;
- fallbackBuffer.InternalInitialize(chars, charEnd, encoder, true);
-
- // If we're not converting we must not have a fallback buffer
- if (encoder.m_throwOnOverflow && fallbackBuffer.Remaining > 0)
- throw new ArgumentException(Environment.GetResourceString("Argument_EncoderFallbackNotEmpty",
- this.EncodingName, encoder.Fallback.GetType()));
-
- // We may have a left over character from last time, try and process it.
- if (charLeftOver > 0)
- {
- 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.
- // Get Fallback
- fallbackBuffer.InternalFallback(charLeftOver, ref chars);
- }
- }
-
- // Now we may have fallback char[] already from the encoder
-
- // Go ahead and do it, including the fallback.
- char ch;
- while ((ch = (fallbackBuffer == null) ? '\0' : fallbackBuffer.InternalGetNextChar()) != 0 ||
- chars < charEnd)
- {
- // First unwind any fallback
- if (ch == 0)
- {
- // No fallback, just get next char
- ch = *chars;
- chars++;
- }
-
- // get byte for this char
- ushort sTemp = mapUnicodeToBytes[ch];
-
- // Check for fallback, this'll catch surrogate pairs too.
- if (sTemp == 0 && ch != (char)0)
- {
- if (fallbackBuffer == null)
- {
- // Initialize the buffer
- 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);
- }
-
- // Get Fallback
- fallbackBuffer.InternalFallback(ch, ref chars);
- continue;
- }
-
- // We'll use this one (or two)
- // Bounds check
-
- // Go ahead and add it, lead byte 1st if necessary
- if (sTemp >= 0x100)
- {
- if (bytes + 1 >= byteEnd)
- {
- // didn't use this char, we'll throw or use buffer
- if (fallbackBuffer == null || fallbackBuffer.bFallingBack == false)
- {
- Debug.Assert(chars > charStart,
- "[DBCSCodePageEncoding.GetBytes]Expected chars to have advanced (double byte case)");
- chars--; // don't use last char
- }
- else
- fallbackBuffer.MovePrevious(); // don't use last fallback
- ThrowBytesOverflow(encoder, chars == charStart); // throw ?
- break; // don't throw, stop
- }
-
- *bytes = unchecked((byte)(sTemp >> 8));
- bytes++;
- }
- // Single byte
- else if (bytes >= byteEnd)
- {
- // didn't use this char, we'll throw or use buffer
- if (fallbackBuffer == null || fallbackBuffer.bFallingBack == false)
- {
- Debug.Assert(chars > charStart,
- "[DBCSCodePageEncoding.GetBytes]Expected chars to have advanced (single byte case)");
- chars--; // don't use last char
- }
- else
- fallbackBuffer.MovePrevious(); // don't use last fallback
- ThrowBytesOverflow(encoder, chars == charStart); // throw ?
- break; // don't throw, stop
- }
-
- *bytes = unchecked((byte)(sTemp & 0xff));
- bytes++;
- }
-
- // encoder stuff if we have one
- if (encoder != null)
- {
- // Fallback stuck it in encoder if necessary, but we have to clear MustFlush cases
- if (fallbackBuffer != null && !fallbackBuffer.bUsedEncoder)
- // Clear it in case of MustFlush
- encoder.charLeftOver = (char)0;
-
- // Set our chars used count
- encoder.m_charsUsed = (int)(chars - charStart);
- }
-
- // 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)
-// Debug.Assert((encoder == null || encoder.m_throwOnOverflow) &&
-// (fallbackBuffer == null || fallbackBuffer.Remaining == 0),
-// "[DBCSEncoding.GetBytes]Expected empty fallback buffer at end if not converting");
-
- return (int)(bytes - byteStart);
- }
-
- // This is internal and called by something else,
- internal override unsafe int GetCharCount(byte* bytes, int count, DecoderNLS baseDecoder)
- {
- // Just assert, we're called internally so these should be safe, checked already
- Debug.Assert(bytes != null, "[DBCSCodePageEncoding.GetCharCount]bytes is null");
- Debug.Assert(count >= 0, "[DBCSCodePageEncoding.GetCharCount]byteCount is negative");
-
- CheckMemorySection();
-
- // Fix our decoder
- DBCSDecoder decoder = (DBCSDecoder)baseDecoder;
-
- // Get our fallback
- DecoderFallbackBuffer fallbackBuffer = null;
-
- // We'll need to know where the end is
- byte* byteEnd = bytes + count;
- int charCount = count; // Assume 1 char / byte
-
- // Shouldn't have anything in fallback buffer for GetCharCount
- // (don't have to check m_throwOnOverflow for count)
- Debug.Assert(decoder == null ||
- !decoder.InternalHasFallbackBuffer || decoder.FallbackBuffer.Remaining == 0,
- "[DBCSCodePageEncoding.GetCharCount]Expected empty fallback buffer at start");
-
- // If we have a left over byte, use it
- if (decoder != null && decoder.bLeftOver > 0)
- {
- // We have a left over byte?
- if (count == 0)
- {
- // No input though
- if (!decoder.MustFlush)
- {
- // Don't have to flush
- return 0;
- }
-
-
- Debug.Assert(fallbackBuffer == null,
- "[DBCSCodePageEncoding.GetCharCount]Expected empty fallback buffer");
- fallbackBuffer = decoder.FallbackBuffer;
- fallbackBuffer.InternalInitialize(bytes, null);
-
- byte[] byteBuffer = new byte[] { unchecked((byte)decoder.bLeftOver) };
- return fallbackBuffer.InternalFallback(byteBuffer, bytes);
- }
-
- // Get our full info
- int iBytes = decoder.bLeftOver << 8;
- iBytes |= (*bytes);
- bytes++;
-
- // This is either 1 known char or fallback
- // Already counted 1 char
- // Look up our bytes
- char cDecoder = mapBytesToUnicode[iBytes];
- if (cDecoder == 0 && iBytes != 0)
- {
- // Deallocate preallocated one
- charCount--;
-
- // We'll need a fallback
- Debug.Assert(fallbackBuffer == null,
- "[DBCSCodePageEncoding.GetCharCount]Expected empty fallback buffer for unknown pair");
- fallbackBuffer = decoder.FallbackBuffer;
- fallbackBuffer.InternalInitialize(byteEnd - count, null);
-
- // Do fallback, we know there're 2 bytes
- byte[] byteBuffer = new byte[] { unchecked((byte)(iBytes >> 8)), unchecked((byte)iBytes) };
- charCount += fallbackBuffer.InternalFallback(byteBuffer, bytes);
- }
- // else we already reserved space for this one.
- }
-
- // Loop, watch out for fallbacks
- while (bytes < byteEnd)
- {
- // Faster if don't use *bytes++;
- int iBytes = *bytes;
- bytes++;
- char c = mapBytesToUnicode[iBytes];
-
- // See if it was a double byte character
- if (c == LEAD_BYTE_CHAR)
- {
- // Its a lead byte
- charCount--; // deallocate preallocated lead byte
- if (bytes < byteEnd)
- {
- // Have another to use, so use it
- iBytes <<= 8;
- iBytes |= *bytes;
- bytes++;
- c = mapBytesToUnicode[iBytes];
- }
- else
- {
- // No input left
- if (decoder == null || decoder.MustFlush)
- {
- // have to flush anyway, set to unknown so we use fallback in a 'sec
- charCount++; // reallocate deallocated lead byte
- c = UNKNOWN_CHAR_FLAG;
- }
- else
- {
- // We'll stick it in decoder
- break;
- }
- }
- }
-
- // See if it was unknown.
- // Unknown and known chars already allocated, but fallbacks aren't
- if (c == UNKNOWN_CHAR_FLAG && iBytes != 0)
- {
- if (fallbackBuffer == null)
- {
- if (decoder == null)
- fallbackBuffer = this.DecoderFallback.CreateFallbackBuffer();
- else
- fallbackBuffer = decoder.FallbackBuffer;
- fallbackBuffer.InternalInitialize(byteEnd - count, null);
- }
-
- // Do fallback
- charCount--; // Get rid of preallocated extra char
- byte[] byteBuffer = null;
- if (iBytes < 0x100)
- byteBuffer = new byte[] { unchecked((byte)iBytes) };
- else
- byteBuffer = new byte[] { unchecked((byte)(iBytes >> 8)), unchecked((byte)iBytes) };
- charCount += fallbackBuffer.InternalFallback(byteBuffer, bytes);
- }
- }
-
- // Shouldn't have anything in fallback buffer for GetChars
- Debug.Assert(decoder == null || !decoder.m_throwOnOverflow ||
- !decoder.InternalHasFallbackBuffer || decoder.FallbackBuffer.Remaining == 0,
- "[DBCSCodePageEncoding.GetCharCount]Expected empty fallback buffer at end");
-
- // Return our count
- return charCount;
- }
-
- 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
- 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();
-
- // Fix our decoder
- DBCSDecoder decoder = (DBCSDecoder)baseDecoder;
-
- // We'll need to know where the end is
- byte* byteStart = bytes;
- byte* byteEnd = bytes + byteCount;
- char* charStart = chars;
- char* charEnd = chars + charCount;
- bool bUsedDecoder = false;
-
- // Get our fallback
- DecoderFallbackBuffer fallbackBuffer = null;
-
- // Shouldn't have anything in fallback buffer for GetChars
- Debug.Assert(decoder == null || !decoder.m_throwOnOverflow ||
- !decoder.InternalHasFallbackBuffer || decoder.FallbackBuffer.Remaining == 0,
- "[DBCSCodePageEncoding.GetChars]Expected empty fallback buffer at start");
-
- // If we have a left over byte, use it
- if (decoder != null && decoder.bLeftOver > 0)
- {
- // We have a left over byte?
- if (byteCount == 0)
- {
- // No input though
- if (!decoder.MustFlush)
- {
- // Don't have to flush
- return 0;
- }
-
- // Well, we're flushing, so use '?' or fallback
- // fallback leftover byte
- Debug.Assert(fallbackBuffer == null,
- "[DBCSCodePageEncoding.GetChars]Expected empty fallback");
- fallbackBuffer = decoder.FallbackBuffer;
- fallbackBuffer.InternalInitialize(bytes, charEnd);
-
- // If no room its hopeless, this was 1st fallback
- byte[] byteBuffer = new byte[] { unchecked((byte)decoder.bLeftOver) };
- if (!fallbackBuffer.InternalFallback(byteBuffer, bytes, ref chars))
- ThrowCharsOverflow(decoder, true);
-
- decoder.bLeftOver = 0;
-
- // Done, return it
- return (int)(chars-charStart);
- }
-
- // Get our full info
- int iBytes = decoder.bLeftOver << 8;
- iBytes |= (*bytes);
- bytes++;
-
- // Look up our bytes
- char cDecoder = mapBytesToUnicode[iBytes];
- if (cDecoder == UNKNOWN_CHAR_FLAG && iBytes != 0)
- {
- Debug.Assert(fallbackBuffer == null,
- "[DBCSCodePageEncoding.GetChars]Expected empty fallback for two bytes");
- fallbackBuffer = decoder.FallbackBuffer;
- fallbackBuffer.InternalInitialize(byteEnd - byteCount, charEnd);
-
- byte[] byteBuffer = new byte[] { unchecked((byte)(iBytes >> 8)), unchecked((byte)iBytes) };
- if (!fallbackBuffer.InternalFallback(byteBuffer, bytes, ref chars))
- ThrowCharsOverflow(decoder, true);
- }
- else
- {
- // Do we have output room?, hopeless if not, this is first char
- if (chars >= charEnd)
- ThrowCharsOverflow(decoder, true);
-
- *(chars++) = cDecoder;
- }
- }
-
- // Loop, paying attention to our fallbacks.
- while (bytes < byteEnd)
- {
- // Faster if don't use *bytes++;
- int iBytes = *bytes;
- bytes++;
- char c = mapBytesToUnicode[iBytes];
-
- // See if it was a double byte character
- if (c == LEAD_BYTE_CHAR)
- {
- // Its a lead byte
- if (bytes < byteEnd)
- {
- // Have another to use, so use it
- iBytes <<= 8;
- iBytes |= *bytes;
- bytes++;
- c = mapBytesToUnicode[iBytes];
- }
- else
- {
- // No input left
- if (decoder == null || decoder.MustFlush)
- {
- // have to flush anyway, set to unknown so we use fallback in a 'sec
- c = UNKNOWN_CHAR_FLAG;
- }
- else
- {
- // Stick it in decoder
- bUsedDecoder = true;
- decoder.bLeftOver = (byte)iBytes;
- break;
- }
- }
- }
-
- // See if it was unknown
- if (c == UNKNOWN_CHAR_FLAG && iBytes != 0)
- {
- if (fallbackBuffer == null)
- {
- if (decoder == null)
- fallbackBuffer = this.DecoderFallback.CreateFallbackBuffer();
- else
- fallbackBuffer = decoder.FallbackBuffer;
- fallbackBuffer.InternalInitialize(byteEnd - byteCount, charEnd);
- }
-
- // Do fallback
- byte[] byteBuffer = null;
- if (iBytes < 0x100)
- byteBuffer = new byte[] { unchecked((byte)iBytes) };
- else
- byteBuffer = new byte[] { unchecked((byte)(iBytes >> 8)), unchecked((byte)iBytes) };
- if (!fallbackBuffer.InternalFallback(byteBuffer, bytes, ref chars))
- {
- // May or may not throw, but we didn't get these byte(s)
- 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
- ThrowCharsOverflow(decoder, bytes == byteStart); // throw?
- break; // don't throw, but stop loop
- }
- }
- else
- {
- // Do we have buffer room?
- if (chars >= charEnd)
- {
- // May or may not throw, but we didn't get these byte(s)
- Debug.Assert(bytes > byteStart,
- "[DBCSCodePageEncoding.GetChars]Expected bytes to have advanced for lead byte");
- bytes--; // unused byte
- if (iBytes >= 0x100)
- {
- Debug.Assert(bytes > byteStart,
- "[DBCSCodePageEncoding.GetChars]Expected bytes to have advanced for trail byte");
- bytes--; // 2nd unused byte
- }
- ThrowCharsOverflow(decoder, bytes == byteStart); // throw?
- break; // don't throw, but stop loop
- }
-
- *(chars++) = c;
- }
- }
-
- // We already stuck it in encoder if necessary, but we have to clear cases where nothing new got into decoder
- if (decoder != null)
- {
- // Clear it in case of MustFlush
- if (bUsedDecoder == false)
- {
- decoder.bLeftOver = 0;
- }
-
- // Remember our count
- decoder.m_bytesUsed = (int)(bytes - byteStart);
- }
-
- // Shouldn't have anything in fallback buffer for GetChars
- Debug.Assert(decoder == null || !decoder.m_throwOnOverflow ||
- !decoder.InternalHasFallbackBuffer || decoder.FallbackBuffer.Remaining == 0,
- "[DBCSCodePageEncoding.GetChars]Expected empty fallback buffer at end");
-
- // Return length of our output
- return (int)(chars - charStart);
- }
-
- public override int GetMaxByteCount(int charCount)
- {
- if (charCount < 0)
- throw new ArgumentOutOfRangeException(nameof(charCount),
- Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
- Contract.EndContractBlock();
-
- // Characters would be # of characters + 1 in case high surrogate is ? * max fallback
- long byteCount = (long)charCount + 1;
-
- if (EncoderFallback.MaxCharCount > 1)
- byteCount *= EncoderFallback.MaxCharCount;
-
- // 2 to 1 is worst case. Already considered surrogate fallback
- byteCount *= 2;
-
- if (byteCount > 0x7fffffff)
- throw new ArgumentOutOfRangeException(nameof(charCount), Environment.GetResourceString("ArgumentOutOfRange_GetByteCountOverflow"));
-
- return (int)byteCount;
- }
-
- public override int GetMaxCharCount(int byteCount)
- {
- if (byteCount < 0)
- throw new ArgumentOutOfRangeException(nameof(byteCount),
- Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
- Contract.EndContractBlock();
-
- // DBCS is pretty much the same, but could have hanging high byte making extra ? and fallback for unknown
- long charCount = ((long)byteCount + 1);
-
- // 1 to 1 for most characters. Only surrogates with fallbacks have less, unknown fallbacks could be longer.
- if (DecoderFallback.MaxCharCount > 1)
- charCount *= DecoderFallback.MaxCharCount;
-
- if (charCount > 0x7fffffff)
- throw new ArgumentOutOfRangeException(nameof(byteCount), Environment.GetResourceString("ArgumentOutOfRange_GetCharCountOverflow"));
-
- return (int)charCount;
- }
-
- public override Decoder GetDecoder()
- {
- return new DBCSDecoder(this);
- }
-
- [Serializable]
- internal class DBCSDecoder : DecoderNLS
- {
- // Need a place for the last left over byte
- internal byte bLeftOver = 0;
-
- public DBCSDecoder(DBCSCodePageEncoding encoding) : base(encoding)
- {
- // Base calls reset
- }
-
- public override void Reset()
- {
- this.bLeftOver = 0;
- if (m_fallbackBuffer != null)
- m_fallbackBuffer.Reset();
- }
-
- // Anything left in our decoder?
- internal override bool HasState
- {
- get
- {
- return (this.bLeftOver != 0);
- }
- }
- }
- }
-}
-#endif // FEATURE_CODEPAGES_FILE
-
diff --git a/src/mscorlib/src/System/Text/Decoder.cs b/src/mscorlib/src/System/Text/Decoder.cs
index 0ebbacddcf..a9fea82a39 100644
--- a/src/mscorlib/src/System/Text/Decoder.cs
+++ b/src/mscorlib/src/System/Text/Decoder.cs
@@ -20,7 +20,6 @@ namespace System.Text
// class are typically obtained through calls to the GetDecoder method
// of Encoding objects.
//
- [System.Runtime.InteropServices.ComVisible(true)]
[Serializable]
public abstract class Decoder
{
@@ -39,7 +38,6 @@ namespace System.Text
// We don't call default reset because default reset probably isn't good if we aren't initialized.
}
- [System.Runtime.InteropServices.ComVisible(false)]
public DecoderFallback Fallback
{
get
@@ -65,7 +63,6 @@ namespace System.Text
// Note: we don't test for threading here because async access to Encoders and Decoders
// doesn't work anyway.
- [System.Runtime.InteropServices.ComVisible(false)]
public DecoderFallbackBuffer FallbackBuffer
{
get
@@ -99,7 +96,6 @@ namespace System.Text
//
// Virtual implimentation has to call GetChars with flush and a big enough buffer to clear a 0 byte string
// We avoid GetMaxCharCount() because a) we can't call the base encoder and b) it might be really big.
- [System.Runtime.InteropServices.ComVisible(false)]
public virtual void Reset()
{
byte[] byteTemp = Array.Empty<byte>();
@@ -117,7 +113,6 @@ namespace System.Text
//
public abstract int GetCharCount(byte[] bytes, int index, int count);
- [System.Runtime.InteropServices.ComVisible(false)]
public virtual int GetCharCount(byte[] bytes, int index, int count, bool flush)
{
return GetCharCount(bytes, index, count);
@@ -126,7 +121,6 @@ namespace System.Text
// We expect this to be the workhorse for NLS Encodings, but for existing
// ones we need a working (if slow) default implimentation)
[CLSCompliant(false)]
- [System.Runtime.InteropServices.ComVisible(false)]
public virtual unsafe int GetCharCount(byte* bytes, int count, bool flush)
{
// Validate input parameters
@@ -190,7 +184,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.
[CLSCompliant(false)]
- [System.Runtime.InteropServices.ComVisible(false)]
public virtual unsafe int GetChars(byte* bytes, int byteCount,
char* chars, int charCount, bool flush)
{
@@ -248,7 +241,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.Runtime.InteropServices.ComVisible(false)]
public virtual 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)
@@ -306,7 +298,6 @@ namespace System.Text
// 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)
[CLSCompliant(false)]
- [System.Runtime.InteropServices.ComVisible(false)]
public virtual unsafe void Convert(byte* bytes, int byteCount,
char* chars, int charCount, bool flush,
out int bytesUsed, out int charsUsed, out bool completed)
diff --git a/src/mscorlib/src/System/Text/DecoderFallback.cs b/src/mscorlib/src/System/Text/DecoderFallback.cs
index 42483a724d..bfd4a2852d 100644
--- a/src/mscorlib/src/System/Text/DecoderFallback.cs
+++ b/src/mscorlib/src/System/Text/DecoderFallback.cs
@@ -75,14 +75,6 @@ namespace System.Text
// Maximum number of characters that this instance of this fallback could return
public abstract int MaxCharCount { get; }
-
- internal bool IsMicrosoftBestFitFallback
- {
- get
- {
- return bIsMicrosoftBestFitFallback;
- }
- }
}
diff --git a/src/mscorlib/src/System/Text/DecoderNLS.cs b/src/mscorlib/src/System/Text/DecoderNLS.cs
index e44c43adef..79474f8d8c 100644
--- a/src/mscorlib/src/System/Text/DecoderNLS.cs
+++ b/src/mscorlib/src/System/Text/DecoderNLS.cs
@@ -5,7 +5,6 @@
namespace System.Text
{
using System.Runtime.Serialization;
- using System.Security.Permissions;
using System.Text;
using System;
using System.Diagnostics.Contracts;
@@ -98,7 +97,7 @@ namespace System.Text
bytes = new byte[1];
// Just call pointer version
- fixed (byte* pBytes = bytes)
+ fixed (byte* pBytes = &bytes[0])
return GetCharCount(pBytes + index, count, flush);
}
@@ -159,8 +158,8 @@ namespace System.Text
chars = new char[1];
// Just call pointer version
- fixed (byte* pBytes = bytes)
- fixed (char* pChars = chars)
+ fixed (byte* pBytes = &bytes[0])
+ fixed (char* pChars = &chars[0])
// Remember that charCount is # to decode, not size of array
return GetChars(pBytes + byteIndex, byteCount,
pChars + charIndex, charCount, flush);
@@ -223,9 +222,9 @@ namespace System.Text
chars = new char[1];
// Just call the pointer version (public overrides can't do this)
- fixed (byte* pBytes = bytes)
+ fixed (byte* pBytes = &bytes[0])
{
- fixed (char* pChars = chars)
+ fixed (char* pChars = &chars[0])
{
Convert(pBytes + byteIndex, byteCount, pChars + charIndex, charCount, flush,
out bytesUsed, out charsUsed, out completed);
diff --git a/src/mscorlib/src/System/Text/EUCJPEncoding.cs b/src/mscorlib/src/System/Text/EUCJPEncoding.cs
deleted file mode 100644
index 44345b22b9..0000000000
--- a/src/mscorlib/src/System/Text/EUCJPEncoding.cs
+++ /dev/null
@@ -1,183 +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_CODEPAGES_FILE // requires BaseCodePageEncooding
-namespace System.Text
-{
- using System.Text;
- using System.Globalization;
-
- // EUCJPEncoding
- //
- // EUC-JP Encoding (51932)
- //
- // EUC-JP has the following code points:
- // 00-7F - ASCII
- // 80-8D & 90-9F - Control. (Like Unicode, except for 8e and 8f)
- // A1-FE, A1-FE - 2 byte JIS X 0208 range.
- // 8E, A1-DF - 2 byte half-width Katakana
- // 8F, A1-FE, A1-FE - 3 byte JIX X 0212 range. WE DON'T USE JIS 0212!!!
- //
- // New thoughts:
- // Fixing windows 20932 code page so that all characters can be looked up there.
- //
- // Old thoughts:
- // Windows NLS uses a special CP20932 for EUC-JP, but it is not used by mlang. Windows
- // Maps the 3 byte ranges to the 2 byte CP20932 by masking the 2nd byte with & 0x7F.
- // MLang uses the native windows 932 code page, which is more reliable, however the code points
- // don't line up as nicely as the 20932 code page, however it doesn't have JIS X 0212 support.
- //
- // So what we do is:
- // 1. For ASCII, leave it alone
- // 2. For half-width Katakana, use the leading byte and convert with 20936 code page.
- // 3. For JIS X 0208, Use the leading & trailing bytes with 20936 code page
- // 4. For JIS X 0212, Remove the lead byte, & 0xFF7F, and use the CP20936 table to convert.
- //
- // Regarding Normalization:
- // Forms KC & KD are precluded because of things like halfwidth Katakana that has compatibility mappings
- // Form D is precluded because of 0x00a8, which changes to space + dierises.
- //
- // I think that IsAlwaysNormalized should probably return true for form C (but not certain)
- //
- // NOTE: We don't use JIS 0212 so we are basically a DBCS code page, we just have to modify
- // the 932 table we're basing this on.
- //
-
- using System;
-
- [Serializable]
- internal class EUCJPEncoding : DBCSCodePageEncoding
- {
- // This pretends to be CP 932 as far as memory tables are concerned.
- public EUCJPEncoding() : base(51932, 932)
- {
- this.m_bUseMlangTypeForSerialization = true;
- }
-
- protected unsafe override String GetMemorySectionName()
- {
- int iUseCodePage = this.bFlagDataTable ? dataTableCodePage : CodePage;
-
- String strName = String.Format(CultureInfo.InvariantCulture, "CodePage_{0}_{1}_{2}_{3}_{4}_EUCJP",
- iUseCodePage, this.pCodePage->VersionMajor, this.pCodePage->VersionMinor,
- this.pCodePage->VersionRevision, this.pCodePage->VersionBuild);
-
- return strName;
- }
-
- // Clean up characters for EUC-JP code pages, etc.
- protected override bool CleanUpBytes(ref int bytes)
- {
- if (bytes >= 0x100)
- {
- // map extended char (0xfa40-0xfc4b) to a special range
- // (ported from mlang)
- if (bytes >= 0xfa40 && bytes <= 0xfc4b)
- {
- if ( bytes >= 0xfa40 && bytes <= 0xfa5b )
- {
- if ( bytes <= 0xfa49 )
- bytes = bytes - 0x0b51 ;
- else if ( bytes >= 0xfa4a && bytes <= 0xfa53 )
- bytes = bytes - 0x072f6 ;
- else if ( bytes >= 0xfa54 && bytes <= 0xfa57 )
- bytes = bytes - 0x0b5b ;
- else if ( bytes == 0xfa58 )
- bytes = 0x878a ;
- else if ( bytes == 0xfa59 )
- bytes = 0x8782 ;
- else if ( bytes == 0xfa5a )
- bytes = 0x8784 ;
- else if ( bytes == 0xfa5b )
- bytes = 0x879a ;
- }
- else if ( bytes >= 0xfa5c && bytes <= 0xfc4b )
- {
- byte tc = unchecked((byte)bytes);
- if ( tc < 0x5c )
- bytes = bytes - 0x0d5f;
- else if ( tc >= 0x80 && tc <= 0x9B )
- bytes = bytes - 0x0d1d;
- else
- bytes = bytes - 0x0d1c;
- }
- }
-
- // Convert 932 code page to 20932 like code page range
- // (also ported from mlang)
- byte bLead = unchecked((byte)(bytes >> 8));
- byte bTrail = unchecked((byte)bytes);
-
- bLead -= ((bLead > (byte)0x9f) ? (byte)0xb1 : (byte)0x71);
- bLead = (byte)((bLead << 1) + 1);
- if (bTrail > (byte)0x9e)
- {
- bTrail -= (byte)0x7e;
- bLead++;
- }
- else
- {
- if (bTrail > (byte)0x7e)
- bTrail--;
- bTrail -= (byte)0x1f;
- }
-
- bytes = ((int)bLead) << 8 | (int)bTrail | 0x8080;
-
- // // Don't step on our katakana special plane, if katakana space return false.
- // if (bytes >= 0x8E00 && bytes <= 0x8EFF)
- // return false;
-
- // Don't step out of our allocated lead byte area.
- // All DBCS lead and trail bytes should be >= 0xa1 and <= 0xfe
- if ((bytes & 0xFF00) < 0xa100 || (bytes & 0xFF00) > 0xfe00 ||
- (bytes & 0xFF) < 0xa1 || (bytes & 0xFF) > 0xfe)
- return false;
-
- // WARNING: Our funky mapping allows illegal values, which we continue to use
- // so that we're compatible with Everett.
- }
- else
- {
- // For 51932 1/2 Katakana gets a 0x8E lead byte
- // Adjust 1/2 Katakana
- if (bytes >= 0xa1 && bytes <= 0xdf)
- {
- bytes |= 0x8E00;
- return true;
- }
-
- // 0x81-0x9f and 0xe0-0xfc CP 932
- // 0x8e and 0xa1-0xfe CP 20932 (we don't use 8e though)
- // b0-df is 1/2 Katakana
- // So 81-9f & e0-fc are 932 lead bytes, a1-fe are our lead bytes
- // so ignore everything above 0x80 except 0xa0 and 0xff
- if (bytes >= 0x81 && bytes != 0xa0 && bytes != 0xff)
- {
- // We set diffent lead bytes later, so just return false
- return false;
- }
- }
-
- return true;
- }
-
- protected override unsafe void CleanUpEndBytes(char* chars)
- {
- // Need to special case CP 51932
- // 0x81-0x9f and 0xe0-0xfc CP 932
- // 0x8e and 0xa1-0xfe CP 20932
- // 0x10 and 0x21-0x9? Us (remapping 932)
- // b0-df is 1/2 Katakana (trail byte)
-
- // A1-FE are DBCS code points
- for (int i = 0xA1; i <= 0xFE; i++)
- chars[i] = LEAD_BYTE_CHAR;
-
- // And 8E is lead byte for Katakana (already set)
- chars[0x8e] = LEAD_BYTE_CHAR;
- }
- }
-}
-#endif // FEATURE_CODEPAGES_FILE
diff --git a/src/mscorlib/src/System/Text/Encoder.cs b/src/mscorlib/src/System/Text/Encoder.cs
index b9d4581276..f766f98142 100644
--- a/src/mscorlib/src/System/Text/Encoder.cs
+++ b/src/mscorlib/src/System/Text/Encoder.cs
@@ -20,7 +20,6 @@ namespace System.Text
// class are typically obtained through calls to the GetEncoder method
// of Encoding objects.
//
- [System.Runtime.InteropServices.ComVisible(true)]
[Serializable]
public abstract class Encoder
{
@@ -39,7 +38,6 @@ namespace System.Text
// We don't call default reset because default reset probably isn't good if we aren't initialized.
}
- [System.Runtime.InteropServices.ComVisible(false)]
public EncoderFallback Fallback
{
get
@@ -65,7 +63,6 @@ namespace System.Text
// Note: we don't test for threading here because async access to Encoders and Decoders
// doesn't work anyway.
- [System.Runtime.InteropServices.ComVisible(false)]
public EncoderFallbackBuffer FallbackBuffer
{
get
@@ -99,7 +96,6 @@ namespace System.Text
//
// Virtual implimentation has to call GetBytes with flush and a big enough buffer to clear a 0 char string
// We avoid GetMaxByteCount() because a) we can't call the base encoder and b) it might be really big.
- [System.Runtime.InteropServices.ComVisible(false)]
public virtual void Reset()
{
char[] charTemp = {};
@@ -122,7 +118,6 @@ namespace System.Text
// 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.
[CLSCompliant(false)]
- [System.Runtime.InteropServices.ComVisible(false)]
public virtual unsafe int GetByteCount(char* chars, int count, bool flush)
{
// Validate input parameters
@@ -183,7 +178,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.
[CLSCompliant(false)]
- [System.Runtime.InteropServices.ComVisible(false)]
public virtual unsafe int GetBytes(char* chars, int charCount,
byte* bytes, int byteCount, bool flush)
{
@@ -240,7 +234,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.Runtime.InteropServices.ComVisible(false)]
public virtual 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)
@@ -299,7 +292,6 @@ namespace System.Text
// 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)
[CLSCompliant(false)]
- [System.Runtime.InteropServices.ComVisible(false)]
public virtual unsafe void Convert(char* chars, int charCount,
byte* bytes, int byteCount, bool flush,
out int charsUsed, out int bytesUsed, out bool completed)
diff --git a/src/mscorlib/src/System/Text/EncoderBestFitFallback.cs b/src/mscorlib/src/System/Text/EncoderBestFitFallback.cs
index c5f82a299b..9be095bbd8 100644
--- a/src/mscorlib/src/System/Text/EncoderBestFitFallback.cs
+++ b/src/mscorlib/src/System/Text/EncoderBestFitFallback.cs
@@ -123,7 +123,7 @@ namespace System.Text
0xD800, 0xDBFF));
if (!Char.IsLowSurrogate(charUnknownLow))
- throw new ArgumentOutOfRangeException("CharUnknownLow",
+ throw new ArgumentOutOfRangeException(nameof(charUnknownLow),
Environment.GetResourceString("ArgumentOutOfRange_Range",
0xDC00, 0xDFFF));
Contract.EndContractBlock();
diff --git a/src/mscorlib/src/System/Text/EncoderExceptionFallback.cs b/src/mscorlib/src/System/Text/EncoderExceptionFallback.cs
index 051f50ac7c..6735e7a5f8 100644
--- a/src/mscorlib/src/System/Text/EncoderExceptionFallback.cs
+++ b/src/mscorlib/src/System/Text/EncoderExceptionFallback.cs
@@ -68,7 +68,7 @@ namespace System.Text
}
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/EncoderNLS.cs b/src/mscorlib/src/System/Text/EncoderNLS.cs
index 2add017d68..95901e01f4 100644
--- a/src/mscorlib/src/System/Text/EncoderNLS.cs
+++ b/src/mscorlib/src/System/Text/EncoderNLS.cs
@@ -5,7 +5,6 @@
namespace System.Text
{
using System.Runtime.Serialization;
- using System.Security.Permissions;
using System.Text;
using System;
using System.Diagnostics.Contracts;
@@ -98,7 +97,7 @@ namespace System.Text
// Just call the pointer version
int result = -1;
- fixed (char* pChars = chars)
+ fixed (char* pChars = &chars[0])
{
result = GetByteCount(pChars + index, count, flush);
}
@@ -151,8 +150,8 @@ namespace System.Text
bytes = new byte[1];
// Just call pointer version
- fixed (char* pChars = chars)
- fixed (byte* pBytes = bytes)
+ fixed (char* pChars = &chars[0])
+ fixed (byte* pBytes = &bytes[0])
// Remember that charCount is # to decode, not size of array.
return GetBytes(pChars + charIndex, charCount,
@@ -212,9 +211,9 @@ namespace System.Text
bytes = new byte[1];
// Just call the pointer version (can't do this for non-msft encoders)
- fixed (char* pChars = chars)
+ fixed (char* pChars = &chars[0])
{
- fixed (byte* pBytes = bytes)
+ fixed (byte* pBytes = &bytes[0])
{
Convert(pChars + charIndex, charCount, pBytes + byteIndex, byteCount, flush,
out charsUsed, out bytesUsed, out completed);
diff --git a/src/mscorlib/src/System/Text/EncoderReplacementFallback.cs b/src/mscorlib/src/System/Text/EncoderReplacementFallback.cs
index 604cddf9bb..b0657ff18d 100644
--- a/src/mscorlib/src/System/Text/EncoderReplacementFallback.cs
+++ b/src/mscorlib/src/System/Text/EncoderReplacementFallback.cs
@@ -153,7 +153,7 @@ namespace System.Text
0xD800, 0xDBFF));
if (!Char.IsLowSurrogate(charUnknownLow))
- throw new ArgumentOutOfRangeException("CharUnknownLow",
+ throw new ArgumentOutOfRangeException(nameof(charUnknownLow),
Environment.GetResourceString("ArgumentOutOfRange_Range",
0xDC00, 0xDFFF));
Contract.EndContractBlock();
diff --git a/src/mscorlib/src/System/Text/Encoding.cs b/src/mscorlib/src/System/Text/Encoding.cs
index 658bdbb133..8cb01e41fa 100644
--- a/src/mscorlib/src/System/Text/Encoding.cs
+++ b/src/mscorlib/src/System/Text/Encoding.cs
@@ -12,7 +12,6 @@ namespace System.Text
using System.Runtime.Serialization;
using System.Globalization;
using System.Security;
- using System.Security.Permissions;
using System.Threading;
using System.Text;
using System.Diagnostics;
@@ -83,7 +82,6 @@ namespace System.Text
// generally executes faster.
//
- [System.Runtime.InteropServices.ComVisible(true)]
[Serializable]
public abstract class Encoding : ICloneable
{
@@ -372,23 +370,6 @@ namespace System.Text
return dstEncoding.GetBytes(srcEncoding.GetChars(bytes, index, count));
}
-#if FEATURE_CODEPAGES_FILE
- // 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;
- }
- }
-
- // On Desktop, encoding instances that aren't cached in a static field are cached in
- // a hash table by codepage.
- private static volatile Hashtable encodings;
-#endif
public static void RegisterProvider(EncodingProvider provider)
{
@@ -441,45 +422,6 @@ namespace System.Text
"Argument_CodepageNotSupported", codepage), nameof(codepage));
}
-#if FEATURE_CODEPAGES_FILE
- object key = codepage; // Box once
-
- // See if we have a hash table with our encoding in it already.
- if (encodings != null) {
- result = (Encoding)encodings[key];
- }
-
- if (result == null)
- {
- // Don't conflict with ourselves
- lock (InternalSyncObject)
- {
- // Need a new hash table
- // in case another thread beat us to creating the Dictionary
- if (encodings == null) {
- encodings = new Hashtable();
- }
-
- // Double check that we don't have one in the table (in case another thread beat us here)
- if ((result = (Encoding)encodings[key]) != null)
- return result;
-
- if (codepage == CodePageWindows1252)
- {
- result = new SBCSCodePageEncoding(codepage);
- }
- else
- {
- result = GetEncodingCodePage(codepage) ?? GetEncodingRare(codepage);
- }
-
- Debug.Assert(result != null, "result != null");
-
- encodings.Add(key, result);
- }
- }
- return result;
-#else
// Is it a valid code page?
if (EncodingTable.GetCodePageDataItem(codepage) == null)
{
@@ -488,7 +430,6 @@ namespace System.Text
}
return UTF8;
-#endif // FEATURE_CODEPAGES_FILE
}
[Pure]
@@ -510,86 +451,6 @@ namespace System.Text
return fallbackEncoding;
}
-#if FEATURE_CODEPAGES_FILE
- private static Encoding GetEncodingRare(int codepage)
- {
- 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)
- {
- case ISCIIAssemese:
- case ISCIIBengali:
- case ISCIIDevanagari:
- case ISCIIGujarathi:
- case ISCIIKannada:
- case ISCIIMalayalam:
- case ISCIIOriya:
- case ISCIIPanjabi:
- case ISCIITamil:
- case ISCIITelugu:
- result = new ISCIIEncoding(codepage);
- break;
- // GB2312-80 uses same code page for 20936 and mac 10008
- case CodePageMacGB2312:
- // case CodePageGB2312:
- // result = new DBCSCodePageEncoding(codepage, EUCCN);
- result = new DBCSCodePageEncoding(CodePageMacGB2312, CodePageGB2312);
- break;
-
- // Mac Korean 10003 and 20949 are the same
- case CodePageMacKorean:
- result = new DBCSCodePageEncoding(CodePageMacKorean, CodePageDLLKorean);
- break;
- // GB18030 Code Pages
- case GB18030:
- result = new GB18030Encoding();
- break;
- // ISO2022 Code Pages
- case ISOKorean:
- // case ISOSimplifiedCN
- case ChineseHZ:
- case ISO2022JP: // JIS JP, full-width Katakana mode (no half-width Katakana)
- case ISO2022JPESC: // JIS JP, esc sequence to do Katakana.
- case ISO2022JPSISO: // JIS JP with Shift In/ Shift Out Katakana support
- result = new ISO2022Encoding(codepage);
- break;
- // Duplicate EUC-CN (51936) just calls a base code page 936,
- // so does ISOSimplifiedCN (50227), which's gotta be broken
- case DuplicateEUCCN:
- case ISOSimplifiedCN:
- result = new DBCSCodePageEncoding(codepage, EUCCN); // Just maps to 936
- break;
- case EUCJP:
- result = new EUCJPEncoding();
- break;
- case EUCKR:
- result = new DBCSCodePageEncoding(codepage, CodePageDLLKorean); // Maps to 20949
- break;
- case ENC50229:
- throw new NotSupportedException(Environment.GetResourceString("NotSupported_CodePage50229"));
- case ISO_8859_8I:
- result = new SBCSCodePageEncoding(codepage, ISO_8859_8_Visual); // Hebrew maps to a different code page
- break;
- default:
- // Not found, already tried codepage table code pages in GetEncoding()
- throw new NotSupportedException(
- Environment.GetResourceString("NotSupported_NoCodepageData", codepage));
- }
- return result;
- }
-
- private static Encoding GetEncodingCodePage(int CodePage)
- {
- // Single Byte or Double Byte Code Page? (0 if not found)
- int i = BaseCodePageEncoding.GetCodePageByteSize(CodePage);
- if (i == 1) return new SBCSCodePageEncoding(CodePage);
- else if (i == 2) return new DBCSCodePageEncoding(CodePage);
-
- // Return null if we didn't find one.
- return null;
- }
-#endif // FEATURE_CODEPAGES_FILE
// Returns an Encoding object for a given name or a given code page value.
//
[Pure]
@@ -764,7 +625,6 @@ namespace System.Text
// True if and only if the encoding only uses single byte code points. (Ie, ASCII, 1252, etc)
- [System.Runtime.InteropServices.ComVisible(false)]
public virtual bool IsSingleByte
{
get
@@ -774,7 +634,6 @@ namespace System.Text
}
- [System.Runtime.InteropServices.ComVisible(false)]
public EncoderFallback EncoderFallback
{
get
@@ -796,7 +655,6 @@ namespace System.Text
}
- [System.Runtime.InteropServices.ComVisible(false)]
public DecoderFallback DecoderFallback
{
get
@@ -818,7 +676,6 @@ namespace System.Text
}
- [System.Runtime.InteropServices.ComVisible(false)]
public virtual Object Clone()
{
Encoding newEncoding = (Encoding)this.MemberwiseClone();
@@ -829,7 +686,6 @@ namespace System.Text
}
- [System.Runtime.InteropServices.ComVisible(false)]
public bool IsReadOnly
{
get
@@ -918,7 +774,6 @@ namespace System.Text
// a 3rd party encoding.
[Pure]
[CLSCompliant(false)]
- [System.Runtime.InteropServices.ComVisible(false)]
public virtual unsafe int GetByteCount(char* chars, int count)
{
// Validate input parameters
@@ -1080,7 +935,6 @@ namespace System.Text
// when we copy the buffer so that we don't overflow byteCount either.
[CLSCompliant(false)]
- [System.Runtime.InteropServices.ComVisible(false)]
public virtual unsafe int GetBytes(char* chars, int charCount,
byte* bytes, int byteCount)
{
@@ -1149,7 +1003,6 @@ namespace System.Text
// ones we need a working (if slow) default implimentation)
[Pure]
[CLSCompliant(false)]
- [System.Runtime.InteropServices.ComVisible(false)]
public virtual unsafe int GetCharCount(byte* bytes, int count)
{
// Validate input parameters
@@ -1236,7 +1089,6 @@ namespace System.Text
// when we copy the buffer so that we don't overflow charCount either.
[CLSCompliant(false)]
- [System.Runtime.InteropServices.ComVisible(false)]
public virtual unsafe int GetChars(byte* bytes, int byteCount,
char* chars, int charCount)
{
@@ -1291,7 +1143,6 @@ namespace System.Text
[CLSCompliant(false)]
- [System.Runtime.InteropServices.ComVisible(false)]
public unsafe string GetString(byte* bytes, int byteCount)
{
if (bytes == null)
@@ -1320,18 +1171,12 @@ namespace System.Text
// IsAlwaysNormalized
// Returns true if the encoding is always normalized for the specified encoding form
[Pure]
- [System.Runtime.InteropServices.ComVisible(false)]
public bool IsAlwaysNormalized()
{
-#if !FEATURE_NORM_IDNA_ONLY
return this.IsAlwaysNormalized(NormalizationForm.FormC);
-#else
- return this.IsAlwaysNormalized((NormalizationForm)ExtendedNormalizationForms.FormIdna);
-#endif
}
[Pure]
- [System.Runtime.InteropServices.ComVisible(false)]
public virtual bool IsAlwaysNormalized(NormalizationForm form)
{
// Assume false unless the encoding knows otherwise
@@ -1364,23 +1209,10 @@ namespace System.Text
Encoding enc;
-#if FEATURE_CODEPAGES_FILE
- int codePage = Win32Native.GetACP();
-
- // For US English, we can save some startup working set by not calling
- // GetEncoding(int codePage) since JITting GetEncoding will force us to load
- // all the Encoding classes for ASCII, UTF7 & UTF8, & UnicodeEncoding.
-
- if (codePage == 1252)
- enc = new SBCSCodePageEncoding(codePage);
- else
- enc = GetEncoding(codePage);
-#else // FEATURE_CODEPAGES_FILE
// For silverlight we use UTF8 since ANSI isn't available
enc = UTF8;
-#endif // FEATURE_CODEPAGES_FILE
// This method should only ever return one Encoding instance
return Interlocked.CompareExchange(ref defaultEncoding, enc, null) ?? enc;
@@ -1882,20 +1714,6 @@ namespace System.Text
return AddChar(ch,1);
}
-
- internal unsafe bool AddChar(char ch1, char ch2, int numBytes)
- {
- // Need room for 2 chars
- if (chars >= charEnd - 1)
- {
- // Throw maybe
- bytes-=numBytes; // Didn't encode these bytes
- enc.ThrowCharsOverflow(decoder, bytes <= byteStart); // Throw?
- return false; // No throw, but no store either
- }
- return AddChar(ch1, numBytes) && AddChar(ch2, numBytes);
- }
-
internal unsafe void AdjustBytes(int count)
{
bytes += count;
@@ -1909,12 +1727,6 @@ namespace System.Text
}
}
- // Do we have count more bytes?
- internal unsafe bool EvenMoreData(int count)
- {
- return (bytes <= byteEnd - count);
- }
-
// 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.
internal unsafe byte GetNextByte()
@@ -1942,24 +1754,6 @@ namespace System.Text
return Fallback(byteBuffer);
}
- internal unsafe bool Fallback(byte byte1, byte byte2)
- {
- // Build our buffer
- byte[] byteBuffer = new byte[] { byte1, byte2 };
-
- // Do the fallback and add the data.
- return Fallback(byteBuffer);
- }
-
- internal unsafe bool Fallback(byte byte1, byte byte2, byte byte3, byte byte4)
- {
- // Build our buffer
- byte[] byteBuffer = new byte[] { byte1, byte2, byte3, byte4 };
-
- // Do the fallback and add the data.
- return Fallback(byteBuffer);
- }
-
internal unsafe bool Fallback(byte[] byteBuffer)
{
// Do the fallback and add the data.
@@ -2067,26 +1861,6 @@ namespace System.Text
return (AddByte(b1, 1 + moreBytesExpected) && AddByte(b2, moreBytesExpected));
}
- internal unsafe bool AddByte(byte b1, byte b2, byte b3)
- {
- return AddByte(b1, b2, b3, (int)0);
- }
-
- internal unsafe bool AddByte(byte b1, byte b2, byte b3, int moreBytesExpected)
- {
- return (AddByte(b1, 2 + moreBytesExpected) &&
- AddByte(b2, 1 + moreBytesExpected) &&
- AddByte(b3, moreBytesExpected));
- }
-
- internal unsafe bool AddByte(byte b1, byte b2, byte b3, byte b4)
- {
- return (AddByte(b1, 3) &&
- AddByte(b2, 2) &&
- AddByte(b3, 1) &&
- AddByte(b4, 0));
- }
-
internal unsafe void MovePrevious(bool bThrow)
{
if (fallbackBuffer.bFallingBack)
@@ -2104,12 +1878,6 @@ namespace System.Text
enc.ThrowBytesOverflow(encoder, bytes == byteStart); // Throw? (and reset fallback if not converting)
}
- internal unsafe bool Fallback(char charFallback)
- {
- // Do the fallback
- return fallbackBuffer.InternalFallback(charFallback, ref chars);
- }
-
internal unsafe bool MoreData
{
get
diff --git a/src/mscorlib/src/System/Text/EncodingForwarder.cs b/src/mscorlib/src/System/Text/EncodingForwarder.cs
index 9a8dd26627..50ccbd9333 100644
--- a/src/mscorlib/src/System/Text/EncodingForwarder.cs
+++ b/src/mscorlib/src/System/Text/EncodingForwarder.cs
@@ -130,7 +130,7 @@ namespace System.Text
if (bytes.Length == 0)
bytes = new byte[1];
- fixed (char* pChars = s) fixed (byte* pBytes = bytes)
+ fixed (char* pChars = s) fixed (byte* pBytes = &bytes[0])
{
return encoding.GetBytes(pChars + charIndex, charCount, pBytes + byteIndex, byteCount, encoder: null);
}
@@ -170,7 +170,7 @@ namespace System.Text
bytes = new byte[1];
// Just call the (internal) pointer version
- fixed (char* pChars = chars) fixed (byte* pBytes = bytes)
+ fixed (char* pChars = chars) fixed (byte* pBytes = &bytes[0])
{
return encoding.GetBytes(pChars + charIndex, charCount, pBytes + byteIndex, byteCount, encoder: null);
}
@@ -266,7 +266,7 @@ namespace System.Text
if (chars.Length == 0)
chars = new char[1];
- fixed (byte* pBytes = bytes) fixed (char* pChars = chars)
+ fixed (byte* pBytes = bytes) fixed (char* pChars = &chars[0])
{
return encoding.GetChars(pBytes + byteIndex, byteCount, pChars + charIndex, charCount, decoder: null);
}
diff --git a/src/mscorlib/src/System/Text/EncodingNLS.cs b/src/mscorlib/src/System/Text/EncodingNLS.cs
index fbddf37e88..cb6ed8a52c 100644
--- a/src/mscorlib/src/System/Text/EncodingNLS.cs
+++ b/src/mscorlib/src/System/Text/EncodingNLS.cs
@@ -15,7 +15,6 @@ namespace System.Text
// This class overrides Encoding with the things we need for our NLS Encodings
- [System.Runtime.InteropServices.ComVisible(true)]
[Serializable]
internal abstract class EncodingNLS : Encoding
{
diff --git a/src/mscorlib/src/System/Text/EncodingProvider.cs b/src/mscorlib/src/System/Text/EncodingProvider.cs
index a7f745a753..734d1ac761 100644
--- a/src/mscorlib/src/System/Text/EncodingProvider.cs
+++ b/src/mscorlib/src/System/Text/EncodingProvider.cs
@@ -8,7 +8,6 @@ namespace System.Text
using System.Collections;
using System.Collections.Generic;
- [System.Runtime.InteropServices.ComVisible(true)]
public abstract class EncodingProvider
{
public EncodingProvider() { }
diff --git a/src/mscorlib/src/System/Text/GB18030Encoding.cs b/src/mscorlib/src/System/Text/GB18030Encoding.cs
deleted file mode 100644
index 8ed52a6ab8..0000000000
--- a/src/mscorlib/src/System/Text/GB18030Encoding.cs
+++ /dev/null
@@ -1,1365 +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.
-
-
-//
-// Ported to managed code from c_gb18030.c and related gb18030 dll files
-//
-//
-// Abstract:
-//
-// Managed implementation of GB18030-2000 (code page 54936) ported from implimentation in c_g18030.dll
-// This file contains functions to convert GB18030-2000 (code page 54936) into Unicode, and vice versa.
-//
-// Notes:
-// GB18030-2000 (aka GBK2K) is designed to be mostly compatible with GBK (codepage 936),
-// while supports the full range of Unicode code points (BMP + 16 supplementary planes).
-//
-// The structure for GB18030 is:
-// * Single byte:
-// 0x00 ~ 0x7f
-// * Two-byte:
-// 0x81 ~ 0xfe, 0x40 ~ 0x7e (leading byte, trailing byte)
-// 0x81 ~ 0xfe, 0x80 ~ 0xfe (leading byte, trailing byte)
-// * Four-byte:
-// 0x81 ~ 0xfe, 0x30 ~ 0x39, 0x81 ~ 0xfe, 0x30 ~ 0x39.
-// The surrogare pair will be encoded from 0x90, 0x30, 0x81, 0x30
-//
-// The BMP range is fully supported in GB18030 using 1-byte, 2-byte and 4-byte sequences.
-// In valid 4-byte GB18030, there are two gaps that can not be mapped to Unicode characters.
-// 0x84, 0x31, 0xa5, 0x30 (just after the GB18030 bytes for U+FFFF(*)) ~ 0x8f, 0x39, 0xfe, 0x39 (just before the first GB18030 bytes for U+D800,U+DC00)
-// 0xe3, 0x32, 0x9a, 0x36 (just after the GB18030 bytes for U+DBFF U+DFFF(**)) ~ 0xfe, 0x39, 0xfe, 0x39
-//
-//
-// Note1: U+FFFF = 0x84, 0x31, 0xa4, 0x39
-// Note2: U+DBFF U+DFFF = 0xe3, 0x32, 0x9a, 0x35
-//
-// Tables used in GB18030Encoding:
-//
-// Our data is similar to the 936 Code Page, so we start from there to build our tables. We build the
-// normal double byte mapUnicodeToBytes and mapBytesToUnicode tables by applying differences from 936.
-// We also build a map4BytesToUnicode table and a mapUnicodeTo4BytesFlags
-//
-// * mapUnicodeTo4BytesFlags
-// This is an array of bytes, so we have to do a / 8 and << %8 to check the appropriate bit (see Is4Byte())
-// If the bit is set its true.
-//
-// true - If set/true this is a 4 byte code. The value in mapUnicodeToBytes will be the 4 byte offset
-// false - If cleared/false this is a 1 or 2 byte code. The value in mapUnicodeToBytes will be the 2 bytes.
-//
-// * mapUnicodeToBytes
-// Contains either the 2 byte value of double byte GB18030 or the 4 byte offset for 4 byte GB18030,
-// depending on the value of the flag in mapUnicodeTo4BytesFlags
-//
-// * mapBytesToUnicode
-// mapBytesToUnicode maps 2 byte GB 18030 to Unicode like other DBCS code pages.
-//
-// * map4BytesToUnicode
-// map4BytesToUnicode is indexed by the 4 byte offset and contains the unicode value for each 4 byte offset
-//
-//
-// 4 Byte sequences
-// We generally use the offset for the 4 byte sequence, such as:
-//
-// The index value is the offset of the 4-byte GB18030.
-//
-// 4-byte GB18030 Index value
-// ============== ===========
-// 81,30,81,30 0
-// 81,30,81,31 1
-// 81,30,81,32 2
-// ... ...
-//
-// The value of map4BytesToUnicode cotains the Unicode codepoint for the offset of the
-// corresponding 4-byte GB18030.
-//
-// E.g. map4BytesToUnicode[0] = 0x0080. This means that GB18030 0x81, 0x30, 0x81, 0x30 will be converted to Unicode U+0800.
-//
-// 4 Byte Surrogate Sequences
-// Those work similarly to the normal 4 byte sequences, but start at a different offset
-//
-// We don't override IsAlwaysNormalized because GB18030 covers all of the unicode space, so isn't guaranteed to be normal.
-//
-#if FEATURE_CODEPAGES_FILE // requires BaseCodePageEncooding
-namespace System.Text
-{
- using System;
- using System.Diagnostics;
- using System.Diagnostics.Contracts;
- using System.Text;
- using System.Runtime.InteropServices;
- using System.Security;
- using System.Runtime.CompilerServices;
- using System.Runtime.Serialization;
- using System.Runtime.Versioning;
- using System.Security.Permissions;
- using System.Globalization;
-
- /*=================================GB18030Encoding============================
- **
- ** This is used to support GB18030-2000 encoding (code page 54936).
- **
- ==============================================================================*/
-
- [Serializable]
- internal sealed class GB18030Encoding : DBCSCodePageEncoding, ISerializable
- {
- // This is the table of 4 byte conversions.
- private const int GBLast4ByteCode = 0x99FB;
- [NonSerialized]
- unsafe internal char* map4BytesToUnicode = null; // new char[GBLast4ByteCode + 1]; // Need to map all 4 byte sequences to Unicode
- [NonSerialized]
- 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;
-
- // First and last character of surrogate range as offset from 4 byte GB18030 GB81308130
- private const int GBSurrogateOffset = 0x2E248; // GB90308130
- private const int GBLastSurrogateOffset = 0x12E247; // GBE3329A35
-
- // We have to load the 936 code page tables, so impersonate 936 as our base
- internal GB18030Encoding() : base(GB18030, 936)
- {
- }
-
- // Constructor called by serialization.
- internal GB18030Encoding(SerializationInfo info, StreamingContext context) :
- base(GB18030, 936)
- {
- // Set up our base, also throws if info was empty
- DeserializeEncoding(info, context);
- 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
- void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
- {
- // Make sure to get the base stuff too This throws if info is null
- SerializeEncoding(info, context);
- Debug.Assert(info!=null, "[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.
- protected override unsafe void LoadManagedCodePage()
- {
- // Use base code page loading algorithm.
- // We need to use our main CP as our flag.
- this.bFlagDataTable = false;
- this.iExtraBytes = (GBLast4ByteCode + 1) * 2 + 0x10000 / 8;
-
- // Load most of our code page
- base.LoadManagedCodePage();
-
- // Point to our new data sections
- byte *pMemorySection = (byte *) safeMemorySectionHandle.DangerousGetHandle();
- mapUnicodeTo4BytesFlags = pMemorySection + 65536 * 2 * 2;
- map4BytesToUnicode = (char*)(pMemorySection + 65536 * 2 * 2 + 0x10000 / 8);
-
- // Need to check our pointer to see if we're loaded, return if we're built already
- if (*mapCodePageCached == this.CodePage)
- return;
-
- // Once we've done our base LoadManagedCodePage, we'll have to add our fixes
- char unicodeCount = (char)0;
- ushort count4Byte = 0;
- for (int index = 0; index < tableUnicodeToGBDiffs.Length; index++)
- {
- ushort data = tableUnicodeToGBDiffs[index];
-
- // Check high bit
- if ((data & 0x8000) != 0)
- {
- // Make be exact value
- if (data > 0x9000 && data != 0xD1A6)
- {
- // It was an exact value (gb18040[data] = unicode)
- mapBytesToUnicode[data] = unicodeCount;
- mapUnicodeToBytes[unicodeCount] = data;
- unicodeCount++;
- }
- else
- {
- // It was a CP 936 compatible data, that table's already loaded, just increment our pointer
- unicodeCount += unchecked((char)(data & 0x7FFF));
- }
- }
- else
- {
- // It was GB 18030 4 byte data, next <data> characters are 4 byte sequences.
- while (data > 0)
- {
- Debug.Assert(count4Byte <= GBLast4ByteCode,
- "[GB18030Encoding.LoadManagedCodePage] Found too many 4 byte codes in data table.");
-
- // Set the 4 byte -> Unicode value
- map4BytesToUnicode[count4Byte] = unicodeCount;
- // Set the unicode -> 4 bytes value, including flag that its a 4 byte sequence
- mapUnicodeToBytes[unicodeCount] = count4Byte;
- // Set the flag saying its a 4 byte sequence
- mapUnicodeTo4BytesFlags[unicodeCount / 8] |= unchecked((byte)(1 << (unicodeCount % 8)));
- unicodeCount++;
- count4Byte++;
- data--;
- }
-
- }
- }
-
- // unicodeCount should've wrapped back to 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
- 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.
- *mapCodePageCached = this.CodePage;
- }
-
- internal override void SetDefaultFallbacks()
- {
- // For GB18030Encoding just use default replacement fallbacks because its only for bad surrogates
- this.encoderFallback = EncoderFallback.ReplacementFallback;
- this.decoderFallback = DecoderFallback.ReplacementFallback;
- }
-
- // 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
- internal unsafe bool Is4Byte(char charTest)
- {
- // See what kind it is
- byte b4Byte = mapUnicodeTo4BytesFlags[charTest / 8];
- return (b4Byte != 0 && (b4Byte & (1 << (charTest % 8))) != 0);
- }
-
- // GetByteCount
- internal override unsafe int GetByteCount(char* chars, int count, EncoderNLS encoder)
- {
- // Just call GetBytes() with null bytes
- return GetBytes(chars, count, null, 0, encoder);
- }
-
- 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
-// 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.
- Debug.Assert(encoderFallback != null, "[GB18030Encoding.GetBytes]Attempting to use null encoder fallback");
-
- // Get any left over characters
- char charLeftOver = (char)0;
- if (encoder != null)
- charLeftOver = encoder.charLeftOver;
-
- // prepare our helpers
- Encoding.EncodingByteBuffer buffer = new Encoding.EncodingByteBuffer(
- this, encoder, bytes, byteCount, chars, charCount);
-
- // Try again if we were MustFlush
- TryAgain:
-
- // Go ahead and do it, including the fallback.
- while (buffer.MoreData)
- {
- // Get next char
- char ch = buffer.GetNextChar();
-
- // Have to check for charLeftOver
- if (charLeftOver != 0)
- {
- 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.
- if (!Char.IsLowSurrogate(ch))
- {
- // No low surrogate, fallback high surrogate & try this one again
- buffer.MovePrevious(false); // (Ignoring this character, don't thow)
- if (!buffer.Fallback(charLeftOver))
- {
- charLeftOver = (char)0;
- break;
- }
- charLeftOver = (char)0;
- continue;
- }
- else
- {
- // Next is a surrogate, add it as surrogate pair
-
- // Need 4 bytes for surrogates
- // Get our offset
- int offset = ((charLeftOver - 0xd800) << 10) + (ch - 0xdc00);
-
- byte byte4 = (byte)((offset % 0x0a) + 0x30);
- offset /= 0x0a;
- byte byte3 = (byte)((offset % 0x7e) + 0x81);
- offset /= 0x7e;
- byte byte2 = (byte)((offset % 0x0a) + 0x30);
- offset /= 0x0a;
- Debug.Assert(offset < 0x6f,
- "[GB18030Encoding.GetBytes](1) Expected offset < 0x6f, not 0x" + offset.ToString("X2", CultureInfo.InvariantCulture));
-
- charLeftOver = (char)0;
- if (!buffer.AddByte((byte)(offset + 0x90),byte2,byte3,byte4))
- {
- // Didn't work, need to back up for both surrogates (AddByte already backed up one)
- buffer.MovePrevious(false); // (don't throw)
- break;
- }
- }
- charLeftOver = '\0';
- }
- // ASCII's easiest
- else if (ch <= 0x7f)
- {
- // Need a byte
- if (!buffer.AddByte((byte)ch))
- break;
- }
- // See if its a surrogate pair
- else if (Char.IsHighSurrogate(ch))
- {
- // Remember it for next time
- charLeftOver = ch;
- }
- else if (Char.IsLowSurrogate(ch))
- {
- // Low surrogates should've been found already
- if (!buffer.Fallback(ch))
- break;
- }
- else
- {
- // Not surrogate or ASCII, get value
- ushort iBytes = mapUnicodeToBytes[ch];
-
- // See what kind it is
- if (Is4Byte(ch))
- {
- //
- // This Unicode character will be converted to four-byte GB18030.
- //
- // Need 4 bytes
- byte byte4 = (byte)((iBytes % 0x0a) + 0x30);
- iBytes /= 0x0a;
- byte byte3 = (byte)((iBytes % 0x7e) + 0x81);
- iBytes /= 0x7e;
- byte byte2 = (byte)((iBytes % 0x0a) + 0x30);
- iBytes /= 0x0a;
- 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;
- }
- else
- {
- // Its 2 byte, use it
- if (!buffer.AddByte(unchecked((byte)(iBytes >> 8)), unchecked((byte)(iBytes & 0xff))))
- break;
- }
- }
- }
-
- // Do we need to flush our charLeftOver?
- if ((encoder == null || encoder.MustFlush) && (charLeftOver > 0))
- {
- // Fall it back
- buffer.Fallback(charLeftOver);
- charLeftOver = (char)0;
- goto TryAgain;
- }
-
- // Fallback stuck it in encoder if necessary, but we have to clear MustFlash cases
- // (Check bytes != null, don't clear it if we're just counting)
- if (encoder != null)
- {
- // Remember our charLeftOver
- if (bytes != null)
- encoder.charLeftOver = charLeftOver;
-
- encoder.m_charsUsed = buffer.CharsUsed;
- }
-
- // Return our length
- return buffer.Count;
- }
-
- // Helper methods
- internal bool IsGBLeadByte(short ch)
- {
- // return true if we're in the lead byte range
- return ((ch) >= 0x81 && (ch) <= 0xfe);
- }
-
- internal bool IsGBTwoByteTrailing(short ch)
- {
- // Return true if we are in range for the trailing byte of a 2 byte sequence
- return (((ch) >= 0x40 && (ch) <= 0x7e) ||
- ((ch) >= 0x80 && (ch) <= 0xfe));
- }
-
- internal bool IsGBFourByteTrailing(short ch)
- {
- // Return true if we are in range for the trailing byte of a 4 byte sequence
- return ((ch) >= 0x30 && (ch) <= 0x39);
- }
-
- internal int GetFourBytesOffset(short offset1, short offset2, short offset3, short offset4)
- {
- return ((offset1 - 0x81) * 0x0a * 0x7e * 0x0a +
- (offset2 - 0x30) * 0x7e * 0x0a +
- (offset3 - 0x81) * 0x0a +
- offset4 - 0x30);
- }
-
- // This is internal and called by something else,
- 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);
- }
-
- 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
- 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;
-
- // Get our info.
- Encoding.EncodingCharBuffer buffer = new Encoding.EncodingCharBuffer(
- this, decoder, chars, charCount, bytes, byteCount);
-
- // Need temp bytes because we can't muss up decoder
- short byte1 = -1;
- short byte2 = -1;
- short byte3 = -1;
- short byte4 = -1;
-
- // See if there was anything to get out of the decoder
- if (decoder != null && decoder.bLeftOver1 != -1)
- {
- // Need temp bytes because we can't muss up decoder
- byte1 = decoder.bLeftOver1;
- byte2 = decoder.bLeftOver2;
- byte3 = decoder.bLeftOver3;
- byte4 = decoder.bLeftOver4;
-
- // Loop because we might have too many in buffer
- // This could happen if we are working on a 4 byte sequence, but it isn't valid.
- while (byte1 != -1)
- {
- // If its not a lead byte, use ? or its value, then scoot them down & try again
- // This could happen if we previously had a bad 4 byte sequence and this is a trail byte
- if (!IsGBLeadByte(byte1))
- {
- // This is either a ? or ASCII, need 1 char output
- if (byte1 <= 0x7f)
- {
- if (!buffer.AddChar((char)byte1)) // Its ASCII
- break;
- }
- else
- {
- if (!buffer.Fallback((byte)byte1)) // Not a valid byte
- break;
- }
-
- byte1 = byte2;
- byte2 = byte3;
- byte3 = byte4;
- byte4 = -1;
- continue;
- }
-
- // Read in more bytes as needed
- while (byte2 == -1 ||
- (IsGBFourByteTrailing(byte2) && byte4 == -1))
- {
- // Do we have room?
- if (!buffer.MoreData)
- {
- // No input left to read, do we have to flush?
- if (!decoder.MustFlush)
- {
- // Don't stick stuff in decoder when counting
- if (chars != null)
- {
- // Don't have to flush, won't have any chars
- // Decoder is correct, just return
- decoder.bLeftOver1 = byte1;
- decoder.bLeftOver2 = byte2;
- decoder.bLeftOver3 = byte3;
- decoder.bLeftOver4 = byte4;
- }
-
- decoder.m_bytesUsed = buffer.BytesUsed;
- return buffer.Count;
- }
-
- // We'll have to flush, add a ? and scoot them down to try again
- // We could be trying for a 4 byte sequence but byte 3 could be ascii and should be spit out
- // Breaking will do this because we have zeros
- break;
- }
-
- // Read them in
- if (byte2 == -1) byte2 = buffer.GetNextByte();
- else if (byte3 == -1) byte3 = buffer.GetNextByte();
- else byte4 = buffer.GetNextByte();
- }
-
- // Now we have our 2 or 4 bytes
- if (IsGBTwoByteTrailing(byte2))
- {
- //
- // The trailing byte is a GB18030 two-byte sequence trailing byte.
- //
- int iTwoBytes = byte1 << 8;
- iTwoBytes |= unchecked((byte)byte2);
- if (!buffer.AddChar(this.mapBytesToUnicode[iTwoBytes], 2))
- break;
-
- // We're done with it
- byte1 = -1;
- byte2 = -1;
- }
- else if (IsGBFourByteTrailing(byte2) &&
- IsGBLeadByte(byte3) &&
- IsGBFourByteTrailing(byte4))
- {
- //
- // Four-byte GB18030
- //
-
- int sFourBytesOffset = GetFourBytesOffset(
- byte1, byte2, byte3, byte4);
-
- // What kind is it?
- if (sFourBytesOffset <= GBLast4ByteCode)
- {
- //
- // The Unicode will be in the BMP range.
- //
- if (!buffer.AddChar(map4BytesToUnicode[sFourBytesOffset], 4))
- break;
- }
- else if (sFourBytesOffset >= GBSurrogateOffset &&
- sFourBytesOffset <= GBLastSurrogateOffset)
- {
- //
- // This will be converted to a surrogate pair, need another char
- //
-
- // Use our surrogate
- sFourBytesOffset -= GBSurrogateOffset;
- if (!buffer.AddChar(unchecked((char)(0xd800 + (sFourBytesOffset / 0x400))),
- unchecked((char)(0xdc00 + (sFourBytesOffset % 0x400))), 4))
- break;
- }
- else
- {
- // Real GB18030 codepoint, but can't be mapped to unicode
- // We already checked our buffer space.
- // Do fallback here if we impliment decoderfallbacks.
- if (!buffer.Fallback((byte)byte1, (byte)byte2, (byte)byte3, (byte)byte4))
- break;
- }
-
- // We're done with this one
- byte1 = -1;
- byte2 = -1;
- byte3 = -1;
- byte4 = -1;
- }
- else
- {
- // Not a valid sequence, use '?' for 1st byte & scoot them all down 1
- if (!buffer.Fallback((byte)byte1))
- break;
-
- // Move all bytes down 1
- byte1 = byte2;
- byte2 = byte3;
- byte3 = byte4;
- byte4 = -1;
- }
- }
- }
-
- // Loop, just do '?' replacement because we don't have fallbacks for decodings.
- while (buffer.MoreData)
- {
- byte ch = buffer.GetNextByte();
-
- // ASCII case is easy
- if (ch <= 0x7f)
- {
- // ASCII, have room?
- if (!buffer.AddChar((char)ch))
- break; // No room in convert buffer, so stop
- }
- // See if its a lead byte
- else if (IsGBLeadByte(ch))
- {
- // ch is a lead byte, have room for more?
- if (buffer.MoreData)
- {
- byte ch2 = buffer.GetNextByte();
- if (IsGBTwoByteTrailing(ch2))
- {
- //
- // The trailing byte is a GB18030 two-byte sequence trailing byte.
- //
-
- //
- // Two-byte GB18030
- //
- int iTwoBytes = ch << 8;
- iTwoBytes |= ch2;
- if (!buffer.AddChar(this.mapBytesToUnicode[iTwoBytes], 2))
- break;
- }
- else if (IsGBFourByteTrailing(ch2))
- {
- // Do we have room for Four Byte Sequence? (already have 1 byte)
- if (buffer.EvenMoreData(2))
- {
- // Is it a valid 4 byte sequence?
- byte ch3 = buffer.GetNextByte();
- byte ch4 = buffer.GetNextByte();
- if (IsGBLeadByte(ch3) &&
- IsGBFourByteTrailing(ch4))
- {
- //
- // Four-byte GB18030
- //
- int sFourBytesOffset = GetFourBytesOffset(ch, ch2, ch3, ch4);
-
- // What kind is it?
- // We'll be at least 1 BMP char or a '?' char.
-
- if (sFourBytesOffset <= GBLast4ByteCode)
- {
- //
- // The Unicode will be in the BMP range.
- //
- if (!buffer.AddChar(map4BytesToUnicode[sFourBytesOffset],4))
- break;
- }
- else if (sFourBytesOffset >= GBSurrogateOffset &&
- sFourBytesOffset <= GBLastSurrogateOffset)
- {
- //
- // This will be converted to a surrogate pair, need another char
- //
-
- // Use our surrogate
- sFourBytesOffset -= GBSurrogateOffset;
- if (!buffer.AddChar(unchecked((char)(0xd800 + (sFourBytesOffset / 0x400))),
- unchecked((char)(0xdc00 + (sFourBytesOffset % 0x400))),4))
- break;
- }
- else
- {
- // Real GB18030 codepoint, but can't be mapped to unicode
- if (!buffer.Fallback(ch, ch2, ch3, ch4))
- break;
- }
- }
- else
- {
- // Not a valid 2 or 4 byte sequence, use '?' for ch and try other 3 again
- buffer.AdjustBytes(-3);
- if (!buffer.Fallback(ch))
- break;
- }
- }
- else
- {
- // No room for 4 bytes, have 2 already, may be one more
- // Lead byte but no place to stick it
- if (decoder != null && !decoder.MustFlush)
- {
- // (make sure not to set decoder if counting, so check chars)
- if (chars != null)
- {
- // We'll be able to stick the remainder in the decoder
- byte1 = ch;
- byte2 = ch2;
-
- if (buffer.MoreData)
- byte3 = buffer.GetNextByte();
- else
- byte3 = -1;
-
- byte4=-1;
- }
- break;
- }
-
- // Won't go in decoder, we'll use '?' for it.
- if (!buffer.Fallback(ch, ch2))
- break;
- }
- }
- else
- {
- // Unknown byte sequence, fall back lead byte and try 2nd one again
- buffer.AdjustBytes(-1);
- if (!buffer.Fallback(ch))
- break;
- }
- }
- else
- {
- // Lead byte but don't know about trail byte
- // (make sure not to set decoder if counting, so check bytes)
- if (decoder != null && !decoder.MustFlush)
- {
- // We'll be able to stick it in the decoder
- // (don't actually do it when counting though)
- if (chars != null)
- {
- byte1 = ch;
- byte2 = -1;
- byte3 = -1;
- byte4 = -1;
- }
- break;
- }
-
- if (!buffer.Fallback(ch))
- break;
- }
- }
- else
- {
- // Not ASCII and not a lead byte, we'll use '?' for it if we have room
- if (!buffer.Fallback(ch))
- break;
- }
- }
-
- // Need to flush the decoder if necessary
- // (make sure not to set decoder if counting, so check bytes)
- if (decoder != null)
- {
- if (chars != null)
- {
- decoder.bLeftOver1 = byte1;
- decoder.bLeftOver2 = byte2;
- decoder.bLeftOver3 = byte3;
- decoder.bLeftOver4 = byte4;
- }
- decoder.m_bytesUsed = buffer.BytesUsed;
- }
-
- // Return the # of characters we found
- return buffer.Count;
- }
-
- public override int GetMaxByteCount(int charCount)
- {
- if (charCount < 0)
- throw new ArgumentOutOfRangeException(nameof(charCount),
- Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
- Contract.EndContractBlock();
-
- // Characters would be # of characters + 1 in case high surrogate is ? * max fallback
- long byteCount = (long)charCount + 1;
-
- if (EncoderFallback.MaxCharCount > 1)
- byteCount *= EncoderFallback.MaxCharCount;
-
- // We could have 4 bytes for each char, no extra for surrogates because 18030 can do whole unicode range.
- byteCount *= 4;
-
- if (byteCount > 0x7fffffff)
- throw new ArgumentOutOfRangeException(nameof(charCount), Environment.GetResourceString("ArgumentOutOfRange_GetByteCountOverflow"));
-
- return (int)byteCount;
- }
-
- public override int GetMaxCharCount(int byteCount)
- {
- if (byteCount < 0)
- throw new ArgumentOutOfRangeException(nameof(byteCount),
- Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
- Contract.EndContractBlock();
-
- // Just return length, we could have a single char for each byte + whatever extra our decoder could do to us.
- // If decoder is messed up it could spit out 3 ?s.
- long charCount = ((long)byteCount) + 3;
-
- // Take fallback size into consideration
- if (DecoderFallback.MaxCharCount > 1)
- charCount *= DecoderFallback.MaxCharCount;
-
- if (charCount > 0x7fffffff)
- throw new ArgumentOutOfRangeException(nameof(byteCount), Environment.GetResourceString("ArgumentOutOfRange_GetCharCountOverflow"));
-
- return (int)charCount;
- }
-
- public override Decoder GetDecoder()
- {
- return new GB18030Decoder(this);
- }
-
- [Serializable]
- internal sealed class GB18030Decoder : System.Text.DecoderNLS, ISerializable
- {
- internal short bLeftOver1 = -1;
- internal short bLeftOver2 = -1;
- internal short bLeftOver3 = -1;
- internal short bLeftOver4 = -1;
-
- internal GB18030Decoder(EncodingNLS encoding) : base(encoding)
- {
- // DecoderNLS Calls reset
- }
-
- // Constructor called by serialization, have to handle deserializing from Everett
- internal GB18030Decoder(SerializationInfo info, StreamingContext context)
- {
- // Any info?
- if (info==null) throw new ArgumentNullException(nameof(info));
- Contract.EndContractBlock();
-
- try
- {
- //
- // Try Whidbey V2.0 Fields
- //
- this.m_encoding = (Encoding)info.GetValue("m_encoding", typeof(Encoding));
- this.m_fallback = (DecoderFallback)info.GetValue("m_fallback", typeof(DecoderFallback));
- this.bLeftOver1 = (short)info.GetValue("bLeftOver1", typeof(short));
- this.bLeftOver2 = (short)info.GetValue("bLeftOver2", typeof(short));
- this.bLeftOver3 = (short)info.GetValue("bLeftOver3", typeof(short));
- this.bLeftOver4 = (short)info.GetValue("bLeftOver4", typeof(short));
- }
- catch (SerializationException)
- {
- // Didn't have Whidbey stuff, try Everett (DecoderNLS already called Reset())
- this.m_encoding = new GB18030Encoding();
- }
- }
-
- // ISerializable implementation, get data for this object
- void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
- {
- // Any info?
- if (info==null) throw new ArgumentNullException(nameof(info));
- Contract.EndContractBlock();
-
- // Save Whidbey data
- // Just need Everett maxCharSize (BaseCodePageEncoding) or m_maxByteSize (MLangBaseCodePageEncoding)
- info.AddValue("m_encoding", this.m_encoding);
- info.AddValue("m_fallback", this.m_fallback);
- info.AddValue("bLeftOver1", this.bLeftOver1);
- info.AddValue("bLeftOver2", this.bLeftOver2);
- info.AddValue("bLeftOver3", this.bLeftOver3);
- info.AddValue("bLeftOver4", this.bLeftOver4);
-
- // Everett needs different data (this is just empty for Everett)
- info.AddValue("m_leftOverBytes", (int)0);
- info.AddValue("leftOver", new byte[8]);
- }
-
- public override void Reset()
- {
- bLeftOver1 = -1;
- bLeftOver2 = -1;
- bLeftOver3 = -1;
- bLeftOver4 = -1;
- if (m_fallbackBuffer != null)
- m_fallbackBuffer.Reset();
- }
-
- // Anything left in our decoder?
- internal override bool HasState
- {
- get
- {
- return (this.bLeftOver1 >= 0);
- }
- }
- }
-
- // tableUnicodeToGBDiffs
- //
- // This compressed data enumerates the differences between gb18030 and the 936 code page as follows:
- //
- // <count> & 0x8000 == 0x8000 The next count <count> characters are identical to 936 characters.
- // <count> & 0x8000 == 0x0000 The next count <count> characters are 4 byte gb18030 characters.
- // Except for:
- // <count> >= 0x9000 && <count> != 0xD1A6 This character is this 2 byte GB18030 value.
- //
- readonly ushort[] tableUnicodeToGBDiffs =
- {
- 0x8080, // U+0000 - U+007F ( 128 chars) use CP 936 conversion.
- 0x0024, // U+0080 - U+00A3 ( 36 chars) are GB18030 81 30 81 30 - 81 30 84 35 (offset 0000 - 0023)
- 0x8001, // U+00A4 - U+00A4 ( 1 chars) use CP 936 conversion.
- 0x0002, // U+00A5 - U+00A6 ( 2 chars) are GB18030 81 30 84 36 - 81 30 84 37 (offset 0024 - 0025)
- 0x8002, // U+00A7 - U+00A8 ( 2 chars) use CP 936 conversion.
- 0x0007, // U+00A9 - U+00AF ( 7 chars) are GB18030 81 30 84 38 - 81 30 85 34 (offset 0026 - 002C)
- 0x8002, // U+00B0 - U+00B1 ( 2 chars) use CP 936 conversion.
- 0x0005, // U+00B2 - U+00B6 ( 5 chars) are GB18030 81 30 85 35 - 81 30 85 39 (offset 002D - 0031)
- 0x8001, // U+00B7 - U+00B7 ( 1 chars) use CP 936 conversion.
- 0x001F, // U+00B8 - U+00D6 ( 31 chars) are GB18030 81 30 86 30 - 81 30 89 30 (offset 0032 - 0050)
- 0x8001, // U+00D7 - U+00D7 ( 1 chars) use CP 936 conversion.
- 0x0008, // U+00D8 - U+00DF ( 8 chars) are GB18030 81 30 89 31 - 81 30 89 38 (offset 0051 - 0058)
- 0x8002, // U+00E0 - U+00E1 ( 2 chars) use CP 936 conversion.
- 0x0006, // U+00E2 - U+00E7 ( 6 chars) are GB18030 81 30 89 39 - 81 30 8A 34 (offset 0059 - 005E)
- 0x8003, // U+00E8 - U+00EA ( 3 chars) use CP 936 conversion.
- 0x0001, // U+00EB - U+00EB ( 1 chars) are GB18030 81 30 8A 35 - 81 30 8A 35 (offset 005F - 005F)
- 0x8002, // U+00EC - U+00ED ( 2 chars) use CP 936 conversion.
- 0x0004, // U+00EE - U+00F1 ( 4 chars) are GB18030 81 30 8A 36 - 81 30 8A 39 (offset 0060 - 0063)
- 0x8002, // U+00F2 - U+00F3 ( 2 chars) use CP 936 conversion.
- 0x0003, // U+00F4 - U+00F6 ( 3 chars) are GB18030 81 30 8B 30 - 81 30 8B 32 (offset 0064 - 0066)
- 0x8001, // U+00F7 - U+00F7 ( 1 chars) use CP 936 conversion.
- 0x0001, // U+00F8 - U+00F8 ( 1 chars) are GB18030 81 30 8B 33 - 81 30 8B 33 (offset 0067 - 0067)
- 0x8002, // U+00F9 - U+00FA ( 2 chars) use CP 936 conversion.
- 0x0001, // U+00FB - U+00FB ( 1 chars) are GB18030 81 30 8B 34 - 81 30 8B 34 (offset 0068 - 0068)
- 0x8001, // U+00FC - U+00FC ( 1 chars) use CP 936 conversion.
- 0x0004, // U+00FD - U+0100 ( 4 chars) are GB18030 81 30 8B 35 - 81 30 8B 38 (offset 0069 - 006C)
- 0x8001, // U+0101 - U+0101 ( 1 chars) use CP 936 conversion.
- 0x0011, // U+0102 - U+0112 ( 17 chars) are GB18030 81 30 8B 39 - 81 30 8D 35 (offset 006D - 007D)
- 0x8001, // U+0113 - U+0113 ( 1 chars) use CP 936 conversion.
- 0x0007, // U+0114 - U+011A ( 7 chars) are GB18030 81 30 8D 36 - 81 30 8E 32 (offset 007E - 0084)
- 0x8001, // U+011B - U+011B ( 1 chars) use CP 936 conversion.
- 0x000F, // U+011C - U+012A ( 15 chars) are GB18030 81 30 8E 33 - 81 30 8F 37 (offset 0085 - 0093)
- 0x8001, // U+012B - U+012B ( 1 chars) use CP 936 conversion.
- 0x0018, // U+012C - U+0143 ( 24 chars) are GB18030 81 30 8F 38 - 81 30 92 31 (offset 0094 - 00AB)
- 0x8001, // U+0144 - U+0144 ( 1 chars) use CP 936 conversion.
- 0x0003, // U+0145 - U+0147 ( 3 chars) are GB18030 81 30 92 32 - 81 30 92 34 (offset 00AC - 00AE)
- 0x8001, // U+0148 - U+0148 ( 1 chars) use CP 936 conversion.
- 0x0004, // U+0149 - U+014C ( 4 chars) are GB18030 81 30 92 35 - 81 30 92 38 (offset 00AF - 00B2)
- 0x8001, // U+014D - U+014D ( 1 chars) use CP 936 conversion.
- 0x001D, // U+014E - U+016A ( 29 chars) are GB18030 81 30 92 39 - 81 30 95 37 (offset 00B3 - 00CF)
- 0x8001, // U+016B - U+016B ( 1 chars) use CP 936 conversion.
- 0x0062, // U+016C - U+01CD ( 98 chars) are GB18030 81 30 95 38 - 81 30 9F 35 (offset 00D0 - 0131)
- 0x8001, // U+01CE - U+01CE ( 1 chars) use CP 936 conversion.
- 0x0001, // U+01CF - U+01CF ( 1 chars) are GB18030 81 30 9F 36 - 81 30 9F 36 (offset 0132 - 0132)
- 0x8001, // U+01D0 - U+01D0 ( 1 chars) use CP 936 conversion.
- 0x0001, // U+01D1 - U+01D1 ( 1 chars) are GB18030 81 30 9F 37 - 81 30 9F 37 (offset 0133 - 0133)
- 0x8001, // U+01D2 - U+01D2 ( 1 chars) use CP 936 conversion.
- 0x0001, // U+01D3 - U+01D3 ( 1 chars) are GB18030 81 30 9F 38 - 81 30 9F 38 (offset 0134 - 0134)
- 0x8001, // U+01D4 - U+01D4 ( 1 chars) use CP 936 conversion.
- 0x0001, // U+01D5 - U+01D5 ( 1 chars) are GB18030 81 30 9F 39 - 81 30 9F 39 (offset 0135 - 0135)
- 0x8001, // U+01D6 - U+01D6 ( 1 chars) use CP 936 conversion.
- 0x0001, // U+01D7 - U+01D7 ( 1 chars) are GB18030 81 30 A0 30 - 81 30 A0 30 (offset 0136 - 0136)
- 0x8001, // U+01D8 - U+01D8 ( 1 chars) use CP 936 conversion.
- 0x0001, // U+01D9 - U+01D9 ( 1 chars) are GB18030 81 30 A0 31 - 81 30 A0 31 (offset 0137 - 0137)
- 0x8001, // U+01DA - U+01DA ( 1 chars) use CP 936 conversion.
- 0x0001, // U+01DB - U+01DB ( 1 chars) are GB18030 81 30 A0 32 - 81 30 A0 32 (offset 0138 - 0138)
- 0x8001, // U+01DC - U+01DC ( 1 chars) use CP 936 conversion.
- 0x001C, // U+01DD - U+01F8 ( 28 chars) are GB18030 81 30 A0 33 - 81 30 A3 30 (offset 0139 - 0154)
- 0xA8BF, // U+01F9 is non-936 GB18030 value A8 BF.
- 0x0057, // U+01FA - U+0250 ( 87 chars) are GB18030 81 30 A3 31 - 81 30 AB 37 (offset 0155 - 01AB)
- 0x8001, // U+0251 - U+0251 ( 1 chars) use CP 936 conversion.
- 0x000F, // U+0252 - U+0260 ( 15 chars) are GB18030 81 30 AB 38 - 81 30 AD 32 (offset 01AC - 01BA)
- 0x8001, // U+0261 - U+0261 ( 1 chars) use CP 936 conversion.
- 0x0065, // U+0262 - U+02C6 ( 101 chars) are GB18030 81 30 AD 33 - 81 30 B7 33 (offset 01BB - 021F)
- 0x8001, // U+02C7 - U+02C7 ( 1 chars) use CP 936 conversion.
- 0x0001, // U+02C8 - U+02C8 ( 1 chars) are GB18030 81 30 B7 34 - 81 30 B7 34 (offset 0220 - 0220)
- 0x8003, // U+02C9 - U+02CB ( 3 chars) use CP 936 conversion.
- 0x000D, // U+02CC - U+02D8 ( 13 chars) are GB18030 81 30 B7 35 - 81 30 B8 37 (offset 0221 - 022D)
- 0x8001, // U+02D9 - U+02D9 ( 1 chars) use CP 936 conversion.
- 0x00B7, // U+02DA - U+0390 ( 183 chars) are GB18030 81 30 B8 38 - 81 30 CB 30 (offset 022E - 02E4)
- 0x8011, // U+0391 - U+03A1 ( 17 chars) use CP 936 conversion.
- 0x0001, // U+03A2 - U+03A2 ( 1 chars) are GB18030 81 30 CB 31 - 81 30 CB 31 (offset 02E5 - 02E5)
- 0x8007, // U+03A3 - U+03A9 ( 7 chars) use CP 936 conversion.
- 0x0007, // U+03AA - U+03B0 ( 7 chars) are GB18030 81 30 CB 32 - 81 30 CB 38 (offset 02E6 - 02EC)
- 0x8011, // U+03B1 - U+03C1 ( 17 chars) use CP 936 conversion.
- 0x0001, // U+03C2 - U+03C2 ( 1 chars) are GB18030 81 30 CB 39 - 81 30 CB 39 (offset 02ED - 02ED)
- 0x8007, // U+03C3 - U+03C9 ( 7 chars) use CP 936 conversion.
- 0x0037, // U+03CA - U+0400 ( 55 chars) are GB18030 81 30 CC 30 - 81 30 D1 34 (offset 02EE - 0324)
- 0x8001, // U+0401 - U+0401 ( 1 chars) use CP 936 conversion.
- 0x000E, // U+0402 - U+040F ( 14 chars) are GB18030 81 30 D1 35 - 81 30 D2 38 (offset 0325 - 0332)
- 0x8040, // U+0410 - U+044F ( 64 chars) use CP 936 conversion.
- 0x0001, // U+0450 - U+0450 ( 1 chars) are GB18030 81 30 D2 39 - 81 30 D2 39 (offset 0333 - 0333)
- 0x8001, // U+0451 - U+0451 ( 1 chars) use CP 936 conversion.
- 0x1BBE, // U+0452 - U+200F ( 7102 chars) are GB18030 81 30 D3 30 - 81 36 A5 31 (offset 0334 - 1EF1)
- 0x8001, // U+2010 - U+2010 ( 1 chars) use CP 936 conversion.
- 0x0002, // U+2011 - U+2012 ( 2 chars) are GB18030 81 36 A5 32 - 81 36 A5 33 (offset 1EF2 - 1EF3)
- 0x8004, // U+2013 - U+2016 ( 4 chars) use CP 936 conversion.
- 0x0001, // U+2017 - U+2017 ( 1 chars) are GB18030 81 36 A5 34 - 81 36 A5 34 (offset 1EF4 - 1EF4)
- 0x8002, // U+2018 - U+2019 ( 2 chars) use CP 936 conversion.
- 0x0002, // U+201A - U+201B ( 2 chars) are GB18030 81 36 A5 35 - 81 36 A5 36 (offset 1EF5 - 1EF6)
- 0x8002, // U+201C - U+201D ( 2 chars) use CP 936 conversion.
- 0x0007, // U+201E - U+2024 ( 7 chars) are GB18030 81 36 A5 37 - 81 36 A6 33 (offset 1EF7 - 1EFD)
- 0x8002, // U+2025 - U+2026 ( 2 chars) use CP 936 conversion.
- 0x0009, // U+2027 - U+202F ( 9 chars) are GB18030 81 36 A6 34 - 81 36 A7 32 (offset 1EFE - 1F06)
- 0x8001, // U+2030 - U+2030 ( 1 chars) use CP 936 conversion.
- 0x0001, // U+2031 - U+2031 ( 1 chars) are GB18030 81 36 A7 33 - 81 36 A7 33 (offset 1F07 - 1F07)
- 0x8002, // U+2032 - U+2033 ( 2 chars) use CP 936 conversion.
- 0x0001, // U+2034 - U+2034 ( 1 chars) are GB18030 81 36 A7 34 - 81 36 A7 34 (offset 1F08 - 1F08)
- 0x8001, // U+2035 - U+2035 ( 1 chars) use CP 936 conversion.
- 0x0005, // U+2036 - U+203A ( 5 chars) are GB18030 81 36 A7 35 - 81 36 A7 39 (offset 1F09 - 1F0D)
- 0x8001, // U+203B - U+203B ( 1 chars) use CP 936 conversion.
- 0x0070, // U+203C - U+20AB ( 112 chars) are GB18030 81 36 A8 30 - 81 36 B3 31 (offset 1F0E - 1F7D)
- 0xA2E3, // U+20AC is non-936 GB18030 value A2 E3.
- 0x0056, // U+20AD - U+2102 ( 86 chars) are GB18030 81 36 B3 32 - 81 36 BB 37 (offset 1F7E - 1FD3)
- 0x8001, // U+2103 - U+2103 ( 1 chars) use CP 936 conversion.
- 0x0001, // U+2104 - U+2104 ( 1 chars) are GB18030 81 36 BB 38 - 81 36 BB 38 (offset 1FD4 - 1FD4)
- 0x8001, // U+2105 - U+2105 ( 1 chars) use CP 936 conversion.
- 0x0003, // U+2106 - U+2108 ( 3 chars) are GB18030 81 36 BB 39 - 81 36 BC 31 (offset 1FD5 - 1FD7)
- 0x8001, // U+2109 - U+2109 ( 1 chars) use CP 936 conversion.
- 0x000C, // U+210A - U+2115 ( 12 chars) are GB18030 81 36 BC 32 - 81 36 BD 33 (offset 1FD8 - 1FE3)
- 0x8001, // U+2116 - U+2116 ( 1 chars) use CP 936 conversion.
- 0x000A, // U+2117 - U+2120 ( 10 chars) are GB18030 81 36 BD 34 - 81 36 BE 33 (offset 1FE4 - 1FED)
- 0x8001, // U+2121 - U+2121 ( 1 chars) use CP 936 conversion.
- 0x003E, // U+2122 - U+215F ( 62 chars) are GB18030 81 36 BE 34 - 81 36 C4 35 (offset 1FEE - 202B)
- 0x800C, // U+2160 - U+216B ( 12 chars) use CP 936 conversion.
- 0x0004, // U+216C - U+216F ( 4 chars) are GB18030 81 36 C4 36 - 81 36 C4 39 (offset 202C - 202F)
- 0x800A, // U+2170 - U+2179 ( 10 chars) use CP 936 conversion.
- 0x0016, // U+217A - U+218F ( 22 chars) are GB18030 81 36 C5 30 - 81 36 C7 31 (offset 2030 - 2045)
- 0x8004, // U+2190 - U+2193 ( 4 chars) use CP 936 conversion.
- 0x0002, // U+2194 - U+2195 ( 2 chars) are GB18030 81 36 C7 32 - 81 36 C7 33 (offset 2046 - 2047)
- 0x8004, // U+2196 - U+2199 ( 4 chars) use CP 936 conversion.
- 0x006E, // U+219A - U+2207 ( 110 chars) are GB18030 81 36 C7 34 - 81 36 D2 33 (offset 2048 - 20B5)
- 0x8001, // U+2208 - U+2208 ( 1 chars) use CP 936 conversion.
- 0x0006, // U+2209 - U+220E ( 6 chars) are GB18030 81 36 D2 34 - 81 36 D2 39 (offset 20B6 - 20BB)
- 0x8001, // U+220F - U+220F ( 1 chars) use CP 936 conversion.
- 0x0001, // U+2210 - U+2210 ( 1 chars) are GB18030 81 36 D3 30 - 81 36 D3 30 (offset 20BC - 20BC)
- 0x8001, // U+2211 - U+2211 ( 1 chars) use CP 936 conversion.
- 0x0003, // U+2212 - U+2214 ( 3 chars) are GB18030 81 36 D3 31 - 81 36 D3 33 (offset 20BD - 20BF)
- 0x8001, // U+2215 - U+2215 ( 1 chars) use CP 936 conversion.
- 0x0004, // U+2216 - U+2219 ( 4 chars) are GB18030 81 36 D3 34 - 81 36 D3 37 (offset 20C0 - 20C3)
- 0x8001, // U+221A - U+221A ( 1 chars) use CP 936 conversion.
- 0x0002, // U+221B - U+221C ( 2 chars) are GB18030 81 36 D3 38 - 81 36 D3 39 (offset 20C4 - 20C5)
- 0x8004, // U+221D - U+2220 ( 4 chars) use CP 936 conversion.
- 0x0002, // U+2221 - U+2222 ( 2 chars) are GB18030 81 36 D4 30 - 81 36 D4 31 (offset 20C6 - 20C7)
- 0x8001, // U+2223 - U+2223 ( 1 chars) use CP 936 conversion.
- 0x0001, // U+2224 - U+2224 ( 1 chars) are GB18030 81 36 D4 32 - 81 36 D4 32 (offset 20C8 - 20C8)
- 0x8001, // U+2225 - U+2225 ( 1 chars) use CP 936 conversion.
- 0x0001, // U+2226 - U+2226 ( 1 chars) are GB18030 81 36 D4 33 - 81 36 D4 33 (offset 20C9 - 20C9)
- 0x8005, // U+2227 - U+222B ( 5 chars) use CP 936 conversion.
- 0x0002, // U+222C - U+222D ( 2 chars) are GB18030 81 36 D4 34 - 81 36 D4 35 (offset 20CA - 20CB)
- 0x8001, // U+222E - U+222E ( 1 chars) use CP 936 conversion.
- 0x0005, // U+222F - U+2233 ( 5 chars) are GB18030 81 36 D4 36 - 81 36 D5 30 (offset 20CC - 20D0)
- 0x8004, // U+2234 - U+2237 ( 4 chars) use CP 936 conversion.
- 0x0005, // U+2238 - U+223C ( 5 chars) are GB18030 81 36 D5 31 - 81 36 D5 35 (offset 20D1 - 20D5)
- 0x8001, // U+223D - U+223D ( 1 chars) use CP 936 conversion.
- 0x000A, // U+223E - U+2247 ( 10 chars) are GB18030 81 36 D5 36 - 81 36 D6 35 (offset 20D6 - 20DF)
- 0x8001, // U+2248 - U+2248 ( 1 chars) use CP 936 conversion.
- 0x0003, // U+2249 - U+224B ( 3 chars) are GB18030 81 36 D6 36 - 81 36 D6 38 (offset 20E0 - 20E2)
- 0x8001, // U+224C - U+224C ( 1 chars) use CP 936 conversion.
- 0x0005, // U+224D - U+2251 ( 5 chars) are GB18030 81 36 D6 39 - 81 36 D7 33 (offset 20E3 - 20E7)
- 0x8001, // U+2252 - U+2252 ( 1 chars) use CP 936 conversion.
- 0x000D, // U+2253 - U+225F ( 13 chars) are GB18030 81 36 D7 34 - 81 36 D8 36 (offset 20E8 - 20F4)
- 0x8002, // U+2260 - U+2261 ( 2 chars) use CP 936 conversion.
- 0x0002, // U+2262 - U+2263 ( 2 chars) are GB18030 81 36 D8 37 - 81 36 D8 38 (offset 20F5 - 20F6)
- 0x8004, // U+2264 - U+2267 ( 4 chars) use CP 936 conversion.
- 0x0006, // U+2268 - U+226D ( 6 chars) are GB18030 81 36 D8 39 - 81 36 D9 34 (offset 20F7 - 20FC)
- 0x8002, // U+226E - U+226F ( 2 chars) use CP 936 conversion.
- 0x0025, // U+2270 - U+2294 ( 37 chars) are GB18030 81 36 D9 35 - 81 36 DD 31 (offset 20FD - 2121)
- 0x8001, // U+2295 - U+2295 ( 1 chars) use CP 936 conversion.
- 0x0003, // U+2296 - U+2298 ( 3 chars) are GB18030 81 36 DD 32 - 81 36 DD 34 (offset 2122 - 2124)
- 0x8001, // U+2299 - U+2299 ( 1 chars) use CP 936 conversion.
- 0x000B, // U+229A - U+22A4 ( 11 chars) are GB18030 81 36 DD 35 - 81 36 DE 35 (offset 2125 - 212F)
- 0x8001, // U+22A5 - U+22A5 ( 1 chars) use CP 936 conversion.
- 0x0019, // U+22A6 - U+22BE ( 25 chars) are GB18030 81 36 DE 36 - 81 36 E1 30 (offset 2130 - 2148)
- 0x8001, // U+22BF - U+22BF ( 1 chars) use CP 936 conversion.
- 0x0052, // U+22C0 - U+2311 ( 82 chars) are GB18030 81 36 E1 31 - 81 36 E9 32 (offset 2149 - 219A)
- 0x8001, // U+2312 - U+2312 ( 1 chars) use CP 936 conversion.
- 0x014D, // U+2313 - U+245F ( 333 chars) are GB18030 81 36 E9 33 - 81 37 8C 35 (offset 219B - 22E7)
- 0x800A, // U+2460 - U+2469 ( 10 chars) use CP 936 conversion.
- 0x000A, // U+246A - U+2473 ( 10 chars) are GB18030 81 37 8C 36 - 81 37 8D 35 (offset 22E8 - 22F1)
- 0x8028, // U+2474 - U+249B ( 40 chars) use CP 936 conversion.
- 0x0064, // U+249C - U+24FF ( 100 chars) are GB18030 81 37 8D 36 - 81 37 97 35 (offset 22F2 - 2355)
- 0x804C, // U+2500 - U+254B ( 76 chars) use CP 936 conversion.
- 0x0004, // U+254C - U+254F ( 4 chars) are GB18030 81 37 97 36 - 81 37 97 39 (offset 2356 - 2359)
- 0x8024, // U+2550 - U+2573 ( 36 chars) use CP 936 conversion.
- 0x000D, // U+2574 - U+2580 ( 13 chars) are GB18030 81 37 98 30 - 81 37 99 32 (offset 235A - 2366)
- 0x800F, // U+2581 - U+258F ( 15 chars) use CP 936 conversion.
- 0x0003, // U+2590 - U+2592 ( 3 chars) are GB18030 81 37 99 33 - 81 37 99 35 (offset 2367 - 2369)
- 0x8003, // U+2593 - U+2595 ( 3 chars) use CP 936 conversion.
- 0x000A, // U+2596 - U+259F ( 10 chars) are GB18030 81 37 99 36 - 81 37 9A 35 (offset 236A - 2373)
- 0x8002, // U+25A0 - U+25A1 ( 2 chars) use CP 936 conversion.
- 0x0010, // U+25A2 - U+25B1 ( 16 chars) are GB18030 81 37 9A 36 - 81 37 9C 31 (offset 2374 - 2383)
- 0x8002, // U+25B2 - U+25B3 ( 2 chars) use CP 936 conversion.
- 0x0008, // U+25B4 - U+25BB ( 8 chars) are GB18030 81 37 9C 32 - 81 37 9C 39 (offset 2384 - 238B)
- 0x8002, // U+25BC - U+25BD ( 2 chars) use CP 936 conversion.
- 0x0008, // U+25BE - U+25C5 ( 8 chars) are GB18030 81 37 9D 30 - 81 37 9D 37 (offset 238C - 2393)
- 0x8002, // U+25C6 - U+25C7 ( 2 chars) use CP 936 conversion.
- 0x0003, // U+25C8 - U+25CA ( 3 chars) are GB18030 81 37 9D 38 - 81 37 9E 30 (offset 2394 - 2396)
- 0x8001, // U+25CB - U+25CB ( 1 chars) use CP 936 conversion.
- 0x0002, // U+25CC - U+25CD ( 2 chars) are GB18030 81 37 9E 31 - 81 37 9E 32 (offset 2397 - 2398)
- 0x8002, // U+25CE - U+25CF ( 2 chars) use CP 936 conversion.
- 0x0012, // U+25D0 - U+25E1 ( 18 chars) are GB18030 81 37 9E 33 - 81 37 A0 30 (offset 2399 - 23AA)
- 0x8004, // U+25E2 - U+25E5 ( 4 chars) use CP 936 conversion.
- 0x001F, // U+25E6 - U+2604 ( 31 chars) are GB18030 81 37 A0 31 - 81 37 A3 31 (offset 23AB - 23C9)
- 0x8002, // U+2605 - U+2606 ( 2 chars) use CP 936 conversion.
- 0x0002, // U+2607 - U+2608 ( 2 chars) are GB18030 81 37 A3 32 - 81 37 A3 33 (offset 23CA - 23CB)
- 0x8001, // U+2609 - U+2609 ( 1 chars) use CP 936 conversion.
- 0x0036, // U+260A - U+263F ( 54 chars) are GB18030 81 37 A3 34 - 81 37 A8 37 (offset 23CC - 2401)
- 0x8001, // U+2640 - U+2640 ( 1 chars) use CP 936 conversion.
- 0x0001, // U+2641 - U+2641 ( 1 chars) are GB18030 81 37 A8 38 - 81 37 A8 38 (offset 2402 - 2402)
- 0x8001, // U+2642 - U+2642 ( 1 chars) use CP 936 conversion.
- 0x083E, // U+2643 - U+2E80 ( 2110 chars) are GB18030 81 37 A8 39 - 81 38 FD 38 (offset 2403 - 2C40)
- 0xFE50, // U+2E81 is non-936 GB18030 value FE 50.
- 0x0002, // U+2E82 - U+2E83 ( 2 chars) are GB18030 81 38 FD 39 - 81 38 FE 30 (offset 2C41 - 2C42)
- 0xFE54, // U+2E84 is non-936 GB18030 value FE 54.
- 0x0003, // U+2E85 - U+2E87 ( 3 chars) are GB18030 81 38 FE 31 - 81 38 FE 33 (offset 2C43 - 2C45)
- 0xFE57, // U+2E88 is non-936 GB18030 value FE 57.
- 0x0002, // U+2E89 - U+2E8A ( 2 chars) are GB18030 81 38 FE 34 - 81 38 FE 35 (offset 2C46 - 2C47)
- 0xFE58, // U+2E8B is non-936 GB18030 value FE 58.
- 0xFE5D, // U+2E8C is non-936 GB18030 value FE 5D.
- 0x000A, // U+2E8D - U+2E96 ( 10 chars) are GB18030 81 38 FE 36 - 81 39 81 35 (offset 2C48 - 2C51)
- 0xFE5E, // U+2E97 is non-936 GB18030 value FE 5E.
- 0x000F, // U+2E98 - U+2EA6 ( 15 chars) are GB18030 81 39 81 36 - 81 39 83 30 (offset 2C52 - 2C60)
- 0xFE6B, // U+2EA7 is non-936 GB18030 value FE 6B.
- 0x0002, // U+2EA8 - U+2EA9 ( 2 chars) are GB18030 81 39 83 31 - 81 39 83 32 (offset 2C61 - 2C62)
- 0xFE6E, // U+2EAA is non-936 GB18030 value FE 6E.
- 0x0003, // U+2EAB - U+2EAD ( 3 chars) are GB18030 81 39 83 33 - 81 39 83 35 (offset 2C63 - 2C65)
- 0xFE71, // U+2EAE is non-936 GB18030 value FE 71.
- 0x0004, // U+2EAF - U+2EB2 ( 4 chars) are GB18030 81 39 83 36 - 81 39 83 39 (offset 2C66 - 2C69)
- 0xFE73, // U+2EB3 is non-936 GB18030 value FE 73.
- 0x0002, // U+2EB4 - U+2EB5 ( 2 chars) are GB18030 81 39 84 30 - 81 39 84 31 (offset 2C6A - 2C6B)
- 0xFE74, // U+2EB6 is non-936 GB18030 value FE 74.
- 0xFE75, // U+2EB7 is non-936 GB18030 value FE 75.
- 0x0003, // U+2EB8 - U+2EBA ( 3 chars) are GB18030 81 39 84 32 - 81 39 84 34 (offset 2C6C - 2C6E)
- 0xFE79, // U+2EBB is non-936 GB18030 value FE 79.
- 0x000E, // U+2EBC - U+2EC9 ( 14 chars) are GB18030 81 39 84 35 - 81 39 85 38 (offset 2C6F - 2C7C)
- 0xFE84, // U+2ECA is non-936 GB18030 value FE 84.
- 0x0125, // U+2ECB - U+2FEF ( 293 chars) are GB18030 81 39 85 39 - 81 39 A3 31 (offset 2C7D - 2DA1)
- 0xA98A, // U+2FF0 is non-936 GB18030 value A9 8A.
- 0xA98B, // U+2FF1 is non-936 GB18030 value A9 8B.
- 0xA98C, // U+2FF2 is non-936 GB18030 value A9 8C.
- 0xA98D, // U+2FF3 is non-936 GB18030 value A9 8D.
- 0xA98E, // U+2FF4 is non-936 GB18030 value A9 8E.
- 0xA98F, // U+2FF5 is non-936 GB18030 value A9 8F.
- 0xA990, // U+2FF6 is non-936 GB18030 value A9 90.
- 0xA991, // U+2FF7 is non-936 GB18030 value A9 91.
- 0xA992, // U+2FF8 is non-936 GB18030 value A9 92.
- 0xA993, // U+2FF9 is non-936 GB18030 value A9 93.
- 0xA994, // U+2FFA is non-936 GB18030 value A9 94.
- 0xA995, // U+2FFB is non-936 GB18030 value A9 95.
- 0x0004, // U+2FFC - U+2FFF ( 4 chars) are GB18030 81 39 A3 32 - 81 39 A3 35 (offset 2DA2 - 2DA5)
- 0x8004, // U+3000 - U+3003 ( 4 chars) use CP 936 conversion.
- 0x0001, // U+3004 - U+3004 ( 1 chars) are GB18030 81 39 A3 36 - 81 39 A3 36 (offset 2DA6 - 2DA6)
- 0x8013, // U+3005 - U+3017 ( 19 chars) use CP 936 conversion.
- 0x0005, // U+3018 - U+301C ( 5 chars) are GB18030 81 39 A3 37 - 81 39 A4 31 (offset 2DA7 - 2DAB)
- 0x8002, // U+301D - U+301E ( 2 chars) use CP 936 conversion.
- 0x0002, // U+301F - U+3020 ( 2 chars) are GB18030 81 39 A4 32 - 81 39 A4 33 (offset 2DAC - 2DAD)
- 0x8009, // U+3021 - U+3029 ( 9 chars) use CP 936 conversion.
- 0x0014, // U+302A - U+303D ( 20 chars) are GB18030 81 39 A4 34 - 81 39 A6 33 (offset 2DAE - 2DC1)
- 0xA989, // U+303E is non-936 GB18030 value A9 89.
- 0x0002, // U+303F - U+3040 ( 2 chars) are GB18030 81 39 A6 34 - 81 39 A6 35 (offset 2DC2 - 2DC3)
- 0x8053, // U+3041 - U+3093 ( 83 chars) use CP 936 conversion.
- 0x0007, // U+3094 - U+309A ( 7 chars) are GB18030 81 39 A6 36 - 81 39 A7 32 (offset 2DC4 - 2DCA)
- 0x8004, // U+309B - U+309E ( 4 chars) use CP 936 conversion.
- 0x0002, // U+309F - U+30A0 ( 2 chars) are GB18030 81 39 A7 33 - 81 39 A7 34 (offset 2DCB - 2DCC)
- 0x8056, // U+30A1 - U+30F6 ( 86 chars) use CP 936 conversion.
- 0x0005, // U+30F7 - U+30FB ( 5 chars) are GB18030 81 39 A7 35 - 81 39 A7 39 (offset 2DCD - 2DD1)
- 0x8003, // U+30FC - U+30FE ( 3 chars) use CP 936 conversion.
- 0x0006, // U+30FF - U+3104 ( 6 chars) are GB18030 81 39 A8 30 - 81 39 A8 35 (offset 2DD2 - 2DD7)
- 0x8025, // U+3105 - U+3129 ( 37 chars) use CP 936 conversion.
- 0x00F6, // U+312A - U+321F ( 246 chars) are GB18030 81 39 A8 36 - 81 39 C1 31 (offset 2DD8 - 2ECD)
- 0x800A, // U+3220 - U+3229 ( 10 chars) use CP 936 conversion.
- 0x0007, // U+322A - U+3230 ( 7 chars) are GB18030 81 39 C1 32 - 81 39 C1 38 (offset 2ECE - 2ED4)
- 0x8001, // U+3231 - U+3231 ( 1 chars) use CP 936 conversion.
- 0x0071, // U+3232 - U+32A2 ( 113 chars) are GB18030 81 39 C1 39 - 81 39 CD 31 (offset 2ED5 - 2F45)
- 0x8001, // U+32A3 - U+32A3 ( 1 chars) use CP 936 conversion.
- 0x00EA, // U+32A4 - U+338D ( 234 chars) are GB18030 81 39 CD 32 - 81 39 E4 35 (offset 2F46 - 302F)
- 0x8002, // U+338E - U+338F ( 2 chars) use CP 936 conversion.
- 0x000C, // U+3390 - U+339B ( 12 chars) are GB18030 81 39 E4 36 - 81 39 E5 37 (offset 3030 - 303B)
- 0x8003, // U+339C - U+339E ( 3 chars) use CP 936 conversion.
- 0x0002, // U+339F - U+33A0 ( 2 chars) are GB18030 81 39 E5 38 - 81 39 E5 39 (offset 303C - 303D)
- 0x8001, // U+33A1 - U+33A1 ( 1 chars) use CP 936 conversion.
- 0x0022, // U+33A2 - U+33C3 ( 34 chars) are GB18030 81 39 E6 30 - 81 39 E9 33 (offset 303E - 305F)
- 0x8001, // U+33C4 - U+33C4 ( 1 chars) use CP 936 conversion.
- 0x0009, // U+33C5 - U+33CD ( 9 chars) are GB18030 81 39 E9 34 - 81 39 EA 32 (offset 3060 - 3068)
- 0x8001, // U+33CE - U+33CE ( 1 chars) use CP 936 conversion.
- 0x0002, // U+33CF - U+33D0 ( 2 chars) are GB18030 81 39 EA 33 - 81 39 EA 34 (offset 3069 - 306A)
- 0x8002, // U+33D1 - U+33D2 ( 2 chars) use CP 936 conversion.
- 0x0002, // U+33D3 - U+33D4 ( 2 chars) are GB18030 81 39 EA 35 - 81 39 EA 36 (offset 306B - 306C)
- 0x8001, // U+33D5 - U+33D5 ( 1 chars) use CP 936 conversion.
- 0x0071, // U+33D6 - U+3446 ( 113 chars) are GB18030 81 39 EA 37 - 81 39 F5 39 (offset 306D - 30DD)
- 0xFE56, // U+3447 is non-936 GB18030 value FE 56.
- 0x002B, // U+3448 - U+3472 ( 43 chars) are GB18030 81 39 F6 30 - 81 39 FA 32 (offset 30DE - 3108)
- 0xFE55, // U+3473 is non-936 GB18030 value FE 55.
- 0x012A, // U+3474 - U+359D ( 298 chars) are GB18030 81 39 FA 33 - 82 30 9A 30 (offset 3109 - 3232)
- 0xFE5A, // U+359E is non-936 GB18030 value FE 5A.
- 0x006F, // U+359F - U+360D ( 111 chars) are GB18030 82 30 9A 31 - 82 30 A5 31 (offset 3233 - 32A1)
- 0xFE5C, // U+360E is non-936 GB18030 value FE 5C.
- 0x000B, // U+360F - U+3619 ( 11 chars) are GB18030 82 30 A5 32 - 82 30 A6 32 (offset 32A2 - 32AC)
- 0xFE5B, // U+361A is non-936 GB18030 value FE 5B.
- 0x02FD, // U+361B - U+3917 ( 765 chars) are GB18030 82 30 A6 33 - 82 30 F2 37 (offset 32AD - 35A9)
- 0xFE60, // U+3918 is non-936 GB18030 value FE 60.
- 0x0055, // U+3919 - U+396D ( 85 chars) are GB18030 82 30 F2 38 - 82 30 FB 32 (offset 35AA - 35FE)
- 0xFE5F, // U+396E is non-936 GB18030 value FE 5F.
- 0x0060, // U+396F - U+39CE ( 96 chars) are GB18030 82 30 FB 33 - 82 31 86 38 (offset 35FF - 365E)
- 0xFE62, // U+39CF is non-936 GB18030 value FE 62.
- 0xFE65, // U+39D0 is non-936 GB18030 value FE 65.
- 0x000E, // U+39D1 - U+39DE ( 14 chars) are GB18030 82 31 86 39 - 82 31 88 32 (offset 365F - 366C)
- 0xFE63, // U+39DF is non-936 GB18030 value FE 63.
- 0x0093, // U+39E0 - U+3A72 ( 147 chars) are GB18030 82 31 88 33 - 82 31 96 39 (offset 366D - 36FF)
- 0xFE64, // U+3A73 is non-936 GB18030 value FE 64.
- 0x00DA, // U+3A74 - U+3B4D ( 218 chars) are GB18030 82 31 97 30 - 82 31 AC 37 (offset 3700 - 37D9)
- 0xFE68, // U+3B4E is non-936 GB18030 value FE 68.
- 0x011F, // U+3B4F - U+3C6D ( 287 chars) are GB18030 82 31 AC 38 - 82 31 C9 34 (offset 37DA - 38F8)
- 0xFE69, // U+3C6E is non-936 GB18030 value FE 69.
- 0x0071, // U+3C6F - U+3CDF ( 113 chars) are GB18030 82 31 C9 35 - 82 31 D4 37 (offset 38F9 - 3969)
- 0xFE6A, // U+3CE0 is non-936 GB18030 value FE 6A.
- 0x0375, // U+3CE1 - U+4055 ( 885 chars) are GB18030 82 31 D4 38 - 82 32 AF 32 (offset 396A - 3CDE)
- 0xFE6F, // U+4056 is non-936 GB18030 value FE 6F.
- 0x0108, // U+4057 - U+415E ( 264 chars) are GB18030 82 32 AF 33 - 82 32 C9 36 (offset 3CDF - 3DE6)
- 0xFE70, // U+415F is non-936 GB18030 value FE 70.
- 0x01D7, // U+4160 - U+4336 ( 471 chars) are GB18030 82 32 C9 37 - 82 32 F8 37 (offset 3DE7 - 3FBD)
- 0xFE72, // U+4337 is non-936 GB18030 value FE 72.
- 0x0074, // U+4338 - U+43AB ( 116 chars) are GB18030 82 32 F8 38 - 82 33 86 33 (offset 3FBE - 4031)
- 0xFE78, // U+43AC is non-936 GB18030 value FE 78.
- 0x0004, // U+43AD - U+43B0 ( 4 chars) are GB18030 82 33 86 34 - 82 33 86 37 (offset 4032 - 4035)
- 0xFE77, // U+43B1 is non-936 GB18030 value FE 77.
- 0x002B, // U+43B2 - U+43DC ( 43 chars) are GB18030 82 33 86 38 - 82 33 8B 30 (offset 4036 - 4060)
- 0xFE7A, // U+43DD is non-936 GB18030 value FE 7A.
- 0x00F8, // U+43DE - U+44D5 ( 248 chars) are GB18030 82 33 8B 31 - 82 33 A3 38 (offset 4061 - 4158)
- 0xFE7B, // U+44D6 is non-936 GB18030 value FE 7B.
- 0x0175, // U+44D7 - U+464B ( 373 chars) are GB18030 82 33 A3 39 - 82 33 C9 31 (offset 4159 - 42CD)
- 0xFE7D, // U+464C is non-936 GB18030 value FE 7D.
- 0x0014, // U+464D - U+4660 ( 20 chars) are GB18030 82 33 C9 32 - 82 33 CB 31 (offset 42CE - 42E1)
- 0xFE7C, // U+4661 is non-936 GB18030 value FE 7C.
- 0x00C1, // U+4662 - U+4722 ( 193 chars) are GB18030 82 33 CB 32 - 82 33 DE 34 (offset 42E2 - 43A2)
- 0xFE80, // U+4723 is non-936 GB18030 value FE 80.
- 0x0005, // U+4724 - U+4728 ( 5 chars) are GB18030 82 33 DE 35 - 82 33 DE 39 (offset 43A3 - 43A7)
- 0xFE81, // U+4729 is non-936 GB18030 value FE 81.
- 0x0052, // U+472A - U+477B ( 82 chars) are GB18030 82 33 DF 30 - 82 33 E7 31 (offset 43A8 - 43F9)
- 0xFE82, // U+477C is non-936 GB18030 value FE 82.
- 0x0010, // U+477D - U+478C ( 16 chars) are GB18030 82 33 E7 32 - 82 33 E8 37 (offset 43FA - 4409)
- 0xFE83, // U+478D is non-936 GB18030 value FE 83.
- 0x01B9, // U+478E - U+4946 ( 441 chars) are GB18030 82 33 E8 38 - 82 34 96 38 (offset 440A - 45C2)
- 0xFE85, // U+4947 is non-936 GB18030 value FE 85.
- 0x0032, // U+4948 - U+4979 ( 50 chars) are GB18030 82 34 96 39 - 82 34 9B 38 (offset 45C3 - 45F4)
- 0xFE86, // U+497A is non-936 GB18030 value FE 86.
- 0x0002, // U+497B - U+497C ( 2 chars) are GB18030 82 34 9B 39 - 82 34 9C 30 (offset 45F5 - 45F6)
- 0xFE87, // U+497D is non-936 GB18030 value FE 87.
- 0x0004, // U+497E - U+4981 ( 4 chars) are GB18030 82 34 9C 31 - 82 34 9C 34 (offset 45F7 - 45FA)
- 0xFE88, // U+4982 is non-936 GB18030 value FE 88.
- 0xFE89, // U+4983 is non-936 GB18030 value FE 89.
- 0x0001, // U+4984 - U+4984 ( 1 chars) are GB18030 82 34 9C 35 - 82 34 9C 35 (offset 45FB - 45FB)
- 0xFE8A, // U+4985 is non-936 GB18030 value FE 8A.
- 0xFE8B, // U+4986 is non-936 GB18030 value FE 8B.
- 0x0014, // U+4987 - U+499A ( 20 chars) are GB18030 82 34 9C 36 - 82 34 9E 35 (offset 45FC - 460F)
- 0xFE8D, // U+499B is non-936 GB18030 value FE 8D.
- 0x0003, // U+499C - U+499E ( 3 chars) are GB18030 82 34 9E 36 - 82 34 9E 38 (offset 4610 - 4612)
- 0xFE8C, // U+499F is non-936 GB18030 value FE 8C.
- 0x0016, // U+49A0 - U+49B5 ( 22 chars) are GB18030 82 34 9E 39 - 82 34 A1 30 (offset 4613 - 4628)
- 0xFE8F, // U+49B6 is non-936 GB18030 value FE 8F.
- 0xFE8E, // U+49B7 is non-936 GB18030 value FE 8E.
- 0x02BF, // U+49B8 - U+4C76 ( 703 chars) are GB18030 82 34 A1 31 - 82 34 E7 33 (offset 4629 - 48E7)
- 0xFE96, // U+4C77 is non-936 GB18030 value FE 96.
- 0x0027, // U+4C78 - U+4C9E ( 39 chars) are GB18030 82 34 E7 34 - 82 34 EB 32 (offset 48E8 - 490E)
- 0xFE93, // U+4C9F is non-936 GB18030 value FE 93.
- 0xFE94, // U+4CA0 is non-936 GB18030 value FE 94.
- 0xFE95, // U+4CA1 is non-936 GB18030 value FE 95.
- 0xFE97, // U+4CA2 is non-936 GB18030 value FE 97.
- 0xFE92, // U+4CA3 is non-936 GB18030 value FE 92.
- 0x006F, // U+4CA4 - U+4D12 ( 111 chars) are GB18030 82 34 EB 33 - 82 34 F6 33 (offset 490F - 497D)
- 0xFE98, // U+4D13 is non-936 GB18030 value FE 98.
- 0xFE99, // U+4D14 is non-936 GB18030 value FE 99.
- 0xFE9A, // U+4D15 is non-936 GB18030 value FE 9A.
- 0xFE9B, // U+4D16 is non-936 GB18030 value FE 9B.
- 0xFE9C, // U+4D17 is non-936 GB18030 value FE 9C.
- 0xFE9D, // U+4D18 is non-936 GB18030 value FE 9D.
- 0xFE9E, // U+4D19 is non-936 GB18030 value FE 9E.
- 0x0094, // U+4D1A - U+4DAD ( 148 chars) are GB18030 82 34 F6 34 - 82 35 87 31 (offset 497E - 4A11)
- 0xFE9F, // U+4DAE is non-936 GB18030 value FE 9F.
- 0x0051, // U+4DAF - U+4DFF ( 81 chars) are GB18030 82 35 87 32 - 82 35 8F 32 (offset 4A12 - 4A62)
- 0xD1A6, // U+4E00 - U+9FA5 (20902 chars) use CP 936 conversion.
- 0x385A, // U+9FA6 - U+D7FF (14426 chars) are GB18030 82 35 8F 33 - 83 36 C7 38 (offset 4A63 - 82BC)
- 0x8F6C, // U+D800 - U+E76B ( 3948 chars) use CP 936 conversion.
- 0x0001, // U+E76C - U+E76C ( 1 chars) are GB18030 83 36 C7 39 - 83 36 C7 39 (offset 82BD - 82BD)
- 0x805B, // U+E76D - U+E7C7 ( 91 chars) use CP 936 conversion.
- 0x0001, // U+E7C8 - U+E7C8 ( 1 chars) are GB18030 83 36 C8 30 - 83 36 C8 30 (offset 82BE - 82BE)
- 0x801E, // U+E7C9 - U+E7E6 ( 30 chars) use CP 936 conversion.
- 0x000D, // U+E7E7 - U+E7F3 ( 13 chars) are GB18030 83 36 C8 31 - 83 36 C9 33 (offset 82BF - 82CB)
- 0x8021, // U+E7F4 - U+E814 ( 33 chars) use CP 936 conversion.
- 0x0001, // U+E815 - U+E815 ( 1 chars) are GB18030 83 36 C9 34 - 83 36 C9 34 (offset 82CC - 82CC)
- 0x8003, // U+E816 - U+E818 ( 3 chars) use CP 936 conversion.
- 0x0005, // U+E819 - U+E81D ( 5 chars) are GB18030 83 36 C9 35 - 83 36 C9 39 (offset 82CD - 82D1)
- 0x8001, // U+E81E - U+E81E ( 1 chars) use CP 936 conversion.
- 0x0007, // U+E81F - U+E825 ( 7 chars) are GB18030 83 36 CA 30 - 83 36 CA 36 (offset 82D2 - 82D8)
- 0x8001, // U+E826 - U+E826 ( 1 chars) use CP 936 conversion.
- 0x0004, // U+E827 - U+E82A ( 4 chars) are GB18030 83 36 CA 37 - 83 36 CB 30 (offset 82D9 - 82DC)
- 0x8002, // U+E82B - U+E82C ( 2 chars) use CP 936 conversion.
- 0x0004, // U+E82D - U+E830 ( 4 chars) are GB18030 83 36 CB 31 - 83 36 CB 34 (offset 82DD - 82E0)
- 0x8002, // U+E831 - U+E832 ( 2 chars) use CP 936 conversion.
- 0x0008, // U+E833 - U+E83A ( 8 chars) are GB18030 83 36 CB 35 - 83 36 CC 32 (offset 82E1 - 82E8)
- 0x8001, // U+E83B - U+E83B ( 1 chars) use CP 936 conversion.
- 0x0007, // U+E83C - U+E842 ( 7 chars) are GB18030 83 36 CC 33 - 83 36 CC 39 (offset 82E9 - 82EF)
- 0x8001, // U+E843 - U+E843 ( 1 chars) use CP 936 conversion.
- 0x0010, // U+E844 - U+E853 ( 16 chars) are GB18030 83 36 CD 30 - 83 36 CE 35 (offset 82F0 - 82FF)
- 0x8002, // U+E854 - U+E855 ( 2 chars) use CP 936 conversion.
- 0x000E, // U+E856 - U+E863 ( 14 chars) are GB18030 83 36 CE 36 - 83 36 CF 39 (offset 8300 - 830D)
- 0x8001, // U+E864 - U+E864 ( 1 chars) use CP 936 conversion.
- 0x10C7, // U+E865 - U+F92B ( 4295 chars) are GB18030 83 36 D0 30 - 84 30 85 34 (offset 830E - 93D4)
- 0x8001, // U+F92C - U+F92C ( 1 chars) use CP 936 conversion.
- 0x004C, // U+F92D - U+F978 ( 76 chars) are GB18030 84 30 85 35 - 84 30 8D 30 (offset 93D5 - 9420)
- 0x8001, // U+F979 - U+F979 ( 1 chars) use CP 936 conversion.
- 0x001B, // U+F97A - U+F994 ( 27 chars) are GB18030 84 30 8D 31 - 84 30 8F 37 (offset 9421 - 943B)
- 0x8001, // U+F995 - U+F995 ( 1 chars) use CP 936 conversion.
- 0x0051, // U+F996 - U+F9E6 ( 81 chars) are GB18030 84 30 8F 38 - 84 30 97 38 (offset 943C - 948C)
- 0x8001, // U+F9E7 - U+F9E7 ( 1 chars) use CP 936 conversion.
- 0x0009, // U+F9E8 - U+F9F0 ( 9 chars) are GB18030 84 30 97 39 - 84 30 98 37 (offset 948D - 9495)
- 0x8001, // U+F9F1 - U+F9F1 ( 1 chars) use CP 936 conversion.
- 0x001A, // U+F9F2 - U+FA0B ( 26 chars) are GB18030 84 30 98 38 - 84 30 9B 33 (offset 9496 - 94AF)
- 0x8004, // U+FA0C - U+FA0F ( 4 chars) use CP 936 conversion.
- 0x0001, // U+FA10 - U+FA10 ( 1 chars) are GB18030 84 30 9B 34 - 84 30 9B 34 (offset 94B0 - 94B0)
- 0x8001, // U+FA11 - U+FA11 ( 1 chars) use CP 936 conversion.
- 0x0001, // U+FA12 - U+FA12 ( 1 chars) are GB18030 84 30 9B 35 - 84 30 9B 35 (offset 94B1 - 94B1)
- 0x8002, // U+FA13 - U+FA14 ( 2 chars) use CP 936 conversion.
- 0x0003, // U+FA15 - U+FA17 ( 3 chars) are GB18030 84 30 9B 36 - 84 30 9B 38 (offset 94B2 - 94B4)
- 0x8001, // U+FA18 - U+FA18 ( 1 chars) use CP 936 conversion.
- 0x0006, // U+FA19 - U+FA1E ( 6 chars) are GB18030 84 30 9B 39 - 84 30 9C 34 (offset 94B5 - 94BA)
- 0x8003, // U+FA1F - U+FA21 ( 3 chars) use CP 936 conversion.
- 0x0001, // U+FA22 - U+FA22 ( 1 chars) are GB18030 84 30 9C 35 - 84 30 9C 35 (offset 94BB - 94BB)
- 0x8002, // U+FA23 - U+FA24 ( 2 chars) use CP 936 conversion.
- 0x0002, // U+FA25 - U+FA26 ( 2 chars) are GB18030 84 30 9C 36 - 84 30 9C 37 (offset 94BC - 94BD)
- 0x8003, // U+FA27 - U+FA29 ( 3 chars) use CP 936 conversion.
- 0x0406, // U+FA2A - U+FE2F ( 1030 chars) are GB18030 84 30 9C 38 - 84 31 85 37 (offset 94BE - 98C3)
- 0x8002, // U+FE30 - U+FE31 ( 2 chars) use CP 936 conversion.
- 0x0001, // U+FE32 - U+FE32 ( 1 chars) are GB18030 84 31 85 38 - 84 31 85 38 (offset 98C4 - 98C4)
- 0x8012, // U+FE33 - U+FE44 ( 18 chars) use CP 936 conversion.
- 0x0004, // U+FE45 - U+FE48 ( 4 chars) are GB18030 84 31 85 39 - 84 31 86 32 (offset 98C5 - 98C8)
- 0x800A, // U+FE49 - U+FE52 ( 10 chars) use CP 936 conversion.
- 0x0001, // U+FE53 - U+FE53 ( 1 chars) are GB18030 84 31 86 33 - 84 31 86 33 (offset 98C9 - 98C9)
- 0x8004, // U+FE54 - U+FE57 ( 4 chars) use CP 936 conversion.
- 0x0001, // U+FE58 - U+FE58 ( 1 chars) are GB18030 84 31 86 34 - 84 31 86 34 (offset 98CA - 98CA)
- 0x800E, // U+FE59 - U+FE66 ( 14 chars) use CP 936 conversion.
- 0x0001, // U+FE67 - U+FE67 ( 1 chars) are GB18030 84 31 86 35 - 84 31 86 35 (offset 98CB - 98CB)
- 0x8004, // U+FE68 - U+FE6B ( 4 chars) use CP 936 conversion.
- 0x0095, // U+FE6C - U+FF00 ( 149 chars) are GB18030 84 31 86 36 - 84 31 95 34 (offset 98CC - 9960)
- 0x805E, // U+FF01 - U+FF5E ( 94 chars) use CP 936 conversion.
- 0x0081, // U+FF5F - U+FFDF ( 129 chars) are GB18030 84 31 95 35 - 84 31 A2 33 (offset 9961 - 99E1)
- 0x8006, // U+FFE0 - U+FFE5 ( 6 chars) use CP 936 conversion.
- 0x001A, // U+FFE6 - U+FFFF ( 26 chars) are GB18030 84 31 A2 34 - 84 31 A4 39 (offset 99E2 - 99FB)
- };
- }
-}
-#endif // FEATURE_CODEPAGES_FILE
-
diff --git a/src/mscorlib/src/System/Text/ISCIIEncoding.cs b/src/mscorlib/src/System/Text/ISCIIEncoding.cs
deleted file mode 100644
index 751b8217c0..0000000000
--- a/src/mscorlib/src/System/Text/ISCIIEncoding.cs
+++ /dev/null
@@ -1,2621 +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.
-
-// ISCIIEncoding
-//
-// Ported from windows c_iscii. If you find bugs here, there're likely similar
-// bugs in the windows version
-namespace System.Text
-{
- using System;
- using System.Diagnostics;
- using System.Diagnostics.Contracts;
- using System.Globalization;
- using System.Runtime.Serialization;
- using System.Security.Permissions;
-
- // Encodes text into and out of the ISCII encodings.
- // ISCII contains characters to encode indic scripts by mapping indic scripts
- // to the same code page. This works because they are all related scripts.
- // ISCII provides a "font" selection method to switch between the appropriate
- // fonts to display the other scripts. All ISCII characters are above the
- // ASCII range to provide ASCII compatibility.
- //
- // IsAlwaysNormalized() isn't overridden
- // We don't override IsAlwaysNormalized() because it is false for all forms (like base implimentation)
- // Forms C & KC have things like 0933 + 093C == composed 0934, so they aren't normalized
- // Forms D & KD have things like 0934, which decomposes to 0933 + 093C, so not normal.
- // Form IDNA has the above problems plus case mapping, so false (like most encodings)
- //
-
- [Serializable]
- internal class ISCIIEncoding : EncodingNLS, ISerializable
- {
- // Constants
- private const int CodeDefault = 0; // 0x40 Default
- private const int CodeRoman = 1; // 0x41 Roman Transliteration (not supported)
- private const int CodeDevanagari = 2; // 0x42 57002
- private const int CodeBengali = 3; // 0x43 57003
- private const int CodeTamil = 4; // 0x44 57004
- private const int CodeTelugu = 5; // 0x45 57005
- private const int CodeAssamese = 6; // 0x46 57006 Assamese (Bengali)
- private const int CodeOriya = 7; // 0x47 57007
- private const int CodeKannada = 8; // 0x48 57008
- private const int CodeMalayalam = 9; // 0x49 57009
- private const int CodeGujarati = 10; // 0x4a 57010
- private const int CodePunjabi = 11; // 0x4b 57011 Punjabi (Gurmukhi)
-
- // Ranges
- private const int MultiByteBegin = 0xa0; // Beginning of MultiByte space in ISCII
- private const int IndicBegin = 0x0901; // Beginining of Unicode Indic script code points
- private const int IndicEnd = 0x0d6f; // End of Unicode Indic Script code points
-
- // ISCII Control Values
- private const byte ControlATR = 0xef; // Attribute (ATR) code
- private const byte ControlCodePageStart = 0x40; // Start of code page range
-
- // Interesting ISCII characters
- private const byte Virama = 0xe8;
- private const byte Nukta = 0xe9;
- private const byte DevenagariExt = 0xf0;
-
- // Interesting Unicode characters
- private const char ZWNJ = (char)0x200c;
- private const char ZWJ = (char)0x200d;
-
- // Code Page
- private int defaultCodePage;
-
- public ISCIIEncoding(int codePage) : base(codePage)
- {
- // Set our code page (subtracting windows code page # offset)
- defaultCodePage = codePage - 57000;
-
- // Legal windows code pages are between Devanagari and Punjabi
- 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), nameof(codePage));
- }
-
- // Constructor called by serialization.
- internal ISCIIEncoding(SerializationInfo info, StreamingContext context) : base(0)
- {
- // Actually this can't ever get called, MLangCodePageEncoding is our proxy
- // (In Everett this was done by MLang)
- Debug.Assert(false, "Didn't expect to make it to ISCIIEncoding serialization constructor");
- throw new ArgumentException(Environment.GetResourceString("Arg_ExecutionEngineException"));
- }
-
- // ISerializable implementation
- void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
- {
- // Make sure to get the base stuff too This throws if info is null
- SerializeEncoding(info, context);
- Debug.Assert(info!=null, "[ISCIIEncoding.GetObjectData] Expected null info to throw");
-
- // Just need Everett MLangCodePageEncoding maxCharSize
- info.AddValue("m_maxByteSize", 2);
-
- // Always have this as our helper
- info.SetType(typeof(MLangCodePageEncoding));
- }
-
- // Our MaxByteCount is 4 times the input size. That could be because
- // the first input character could be in the wrong code page ("font") and
- // then that character could also be encoded in 2 code points
- public override int GetMaxByteCount(int charCount)
- {
- if (charCount < 0)
- throw new ArgumentOutOfRangeException(nameof(charCount),
- Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
- Contract.EndContractBlock();
-
- // Characters would be # of characters + 1 in case high surrogate is ? * max fallback
- long byteCount = (long)charCount + 1;
-
- if (EncoderFallback.MaxCharCount > 1)
- byteCount *= EncoderFallback.MaxCharCount;
-
- // 4 Time input because 1st input could require code page change and also that char could require 2 code points
- byteCount *= 4;
-
- if (byteCount > 0x7fffffff)
- throw new ArgumentOutOfRangeException(nameof(charCount), Environment.GetResourceString("ArgumentOutOfRange_GetByteCountOverflow"));
-
- return (int)byteCount;
- }
-
- // Our MaxCharCount is the same as the byteCount. There are a few sequences
- // where 2 (or more) bytes could become 2 chars, but thats still 1 to 1.
- public override int GetMaxCharCount(int byteCount)
- {
- if (byteCount < 0)
- throw new ArgumentOutOfRangeException(nameof(byteCount),
- Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
- Contract.EndContractBlock();
-
- // Our MaxCharCount is the same as the byteCount. There are a few sequences
- // where 2 (or more) bytes could become 2 chars, but thats still 1 to 1.
- // Also could have 1 in decoder if we're waiting to see if next char's a nukta.
- long charCount = ((long)byteCount + 1);
-
- // Some code points are undefined so we could fall back.
- if (DecoderFallback.MaxCharCount > 1)
- charCount *= DecoderFallback.MaxCharCount;
-
- if (charCount > 0x7fffffff)
- throw new ArgumentOutOfRangeException(nameof(byteCount), Environment.GetResourceString("ArgumentOutOfRange_GetCharCountOverflow"));
-
- return (int)charCount;
- }
-
- // Our workhorse version
- internal override unsafe int GetByteCount(char* chars, int count, EncoderNLS baseEncoder)
- {
- // Use null pointer to ask GetBytes for count
- return GetBytes(chars, count, null, 0, baseEncoder);
- }
-
- // Workhorse
- internal override unsafe int GetBytes(char *chars, int charCount,
- byte* bytes, int byteCount, EncoderNLS baseEncoder)
- {
- // Allow null bytes for counting
- 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;
-
- // prepare our helpers
- Encoding.EncodingByteBuffer buffer = new Encoding.EncodingByteBuffer(
- this, encoder, bytes, byteCount, chars, charCount);
-
- int currentCodePage = this.defaultCodePage;
- bool bLastVirama = false;
-
- // Use encoder info if available
- if (encoder != null)
- {
- // Remember our old state
- currentCodePage = encoder.currentCodePage;
- bLastVirama = encoder.bLastVirama;
-
- // If we have a high surrogate left over, then fall it back
- if (encoder.charLeftOver > 0)
- {
- buffer.Fallback(encoder.charLeftOver);
- bLastVirama = false; // Redundant
- }
- }
-
- while (buffer.MoreData)
- {
- // Get our data
- char ch = buffer.GetNextChar();
-
- // See if its a Multi Byte Character
- if (ch < MultiByteBegin)
- {
- // Its a boring low character, add it.
- if (!buffer.AddByte((byte)ch))
- break;
- bLastVirama = false;
- continue;
- }
-
- // See if its outside of the Indic script Range range
- if ((ch < IndicBegin) || (ch > IndicEnd))
- {
- // See if its a ZWJ or ZWNJ and if we has bLastVirama;
- if (bLastVirama && (ch == ZWNJ || ch == ZWJ))
- {
- // It was a bLastVirama and ZWNJ || ZWJ
- if (ch == ZWNJ)
- {
- if (!buffer.AddByte(Virama))
- break;
- }
- else // ZWJ
- {
- if (!buffer.AddByte(Nukta))
- break;
- }
-
- // bLastVirama now counts as false
- bLastVirama = false;
- continue;
- }
-
- // Have to do our fallback
- //
- // Note that this will fallback 2 chars if this is a high surrogate.
- // Throws if recursive (knows because we called InternalGetNextChar)
- buffer.Fallback(ch);
- bLastVirama = false;
- continue;
- }
-
- // Its in the Unicode Indic script range
- int indicInfo = UnicodeToIndicChar[ch - IndicBegin];
- byte byteIndic = (byte)indicInfo;
- int indicScript = (0x000f & (indicInfo >> 8));
- int indicTwoBytes = (0xf000 & indicInfo);
-
- // If IndicInfo is 0 then have to do fallback
- if (indicInfo == 0)
- {
- // Its some Unicode character we don't have indic for.
- // Have to do our fallback
- // Add Fallback Count
- // Note that chars was preincremented, and GetEncoderFallbackString might add an extra
- // if chars != charEnd and there's a surrogate.
- // Throws if recursive (knows because we called InternalGetNextChar)
- buffer.Fallback(ch);
-
- bLastVirama = false;
- continue;
- }
-
- // See if our code page ("font" in ISCII spec) has to change
- // (This if doesn't add character, just changes character set)
- Debug.Assert(indicScript!=0, "[ISCIIEncoding.GetBytes]expected an indic script value");
- if (indicScript != currentCodePage)
- {
- // It changed, spit out the ATR
- if (!buffer.AddByte(ControlATR, (byte)(indicScript | ControlCodePageStart)))
- break;
-
- // Now spit out the new code page (& remember it) (do this afterwards in case AddByte failed)
- currentCodePage = indicScript;
-
- // We only know how to map from Unicode to pages from Devanagari to Punjabi (2 to 11)
- Debug.Assert(currentCodePage >= CodeDevanagari && currentCodePage <= CodePunjabi,
- "[ISCIIEncoding.GetBytes]Code page (" + currentCodePage + " shouldn't appear in ISCII from Unicode table!");
- }
-
- // Safe to add our byte now
- if (!buffer.AddByte(byteIndic, indicTwoBytes != 0 ? 1:0))
- break;
-
- // Remember if this one was a Virama
- bLastVirama = (byteIndic == Virama);
-
- // Some characters need extra bytes
- if (indicTwoBytes != 0)
- {
- // This one needs another byte
- Debug.Assert((indicTwoBytes >> 12) > 0 && (indicTwoBytes >> 12) <= 3,
- "[ISCIIEncoding.GetBytes]Expected indicTwoBytes from 1-3, not " + (indicTwoBytes >> 12));
-
- // Already did buffer checking, but...
- if (!buffer.AddByte(SecondIndicByte[indicTwoBytes >> 12]))
- break;
- }
- }
-
- // May need to switch back to our default code page
- if (currentCodePage != defaultCodePage && (encoder == null || encoder.MustFlush))
- {
- // It changed, spit out the ATR
- if (buffer.AddByte(ControlATR, (byte)(defaultCodePage | ControlCodePageStart)))
- currentCodePage = defaultCodePage;
- else
- // If not successful, convert will maintain state for next time, also
- // AddByte will have decremented our char count, however we need it to remain the same
- buffer.GetNextChar();
- bLastVirama = false;
- }
-
- // Make sure we remember our state if necessary
- // Note that we don't care about flush because Virama and code page
- // changes are legal at the end.
- // Don't set encoder if we're just counting
- if (encoder != null && bytes != null)
- {
- // Clear Encoder if necessary.
- if (!buffer.fallbackBuffer.bUsedEncoder)
- {
- encoder.charLeftOver = (char)0;
- }
-
- // Remember our code page/virama state
- encoder.currentCodePage = currentCodePage;
- encoder.bLastVirama = bLastVirama;
-
- // How many chars were used?
- encoder.m_charsUsed = buffer.CharsUsed;
- }
-
- // Return our length
- return buffer.Count;
- }
-
- // Workhorse
- internal override unsafe int GetCharCount(byte* bytes, int count, DecoderNLS baseDecoder)
- {
- // Just call GetChars with null chars saying we want count
- return GetChars(bytes, count, null, 0, baseDecoder);
- }
-
- // For decoding, the following interesting rules apply:
- // Virama followed by another Virama or Nukta becomes Virama + ZWNJ or Virama + ZWJ
- // ATR is followed by a byte to switch code pages ("fonts")
- // Devenagari F0, B8 -> \u0952
- // Devenagari F0, BF -> \u0970
- // Some characters followed by E9 become a different character instead.
- 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
- 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;
-
- // Get our info.
- Encoding.EncodingCharBuffer buffer = new Encoding.EncodingCharBuffer(
- this, decoder, chars, charCount, bytes, byteCount);
-
- int currentCodePage = this.defaultCodePage;
- bool bLastATR = false;
- bool bLastVirama = false;
- bool bLastDevenagariStressAbbr = false;
- char cLastCharForNextNukta = '\0';
- char cLastCharForNoNextNukta = '\0';
-
- // See if there's anything in our decoder
- if (decoder != null)
- {
- currentCodePage = decoder.currentCodePage;
- bLastATR = decoder.bLastATR;
- bLastVirama = decoder.bLastVirama;
- bLastDevenagariStressAbbr = decoder.bLastDevenagariStressAbbr;
- cLastCharForNextNukta = decoder.cLastCharForNextNukta;
- cLastCharForNoNextNukta = decoder.cLastCharForNoNextNukta;
- }
-
- bool bLastSpecial = bLastVirama | bLastATR | bLastDevenagariStressAbbr |
- (cLastCharForNextNukta != '\0');
-
- // Get our current code page index (some code pages are dups)
- int currentCodePageIndex = -1;
- Debug.Assert(currentCodePage >= CodeDevanagari && currentCodePage <= CodePunjabi,
- "[ISCIIEncoding.GetChars]Decoder code page must be >= Devanagari and <= Punjabi, not " + currentCodePage);
-
- if (currentCodePage >= CodeDevanagari && currentCodePage <= CodePunjabi)
- {
- currentCodePageIndex = IndicMappingIndex[currentCodePage];
- }
-
- // Loop through our input
- while (buffer.MoreData)
- {
- byte b = buffer.GetNextByte();
-
- // See if last one was special
- if (bLastSpecial)
- {
- // Now it won't be
- bLastSpecial = false;
-
- // One and only one of our flags should be set
- Debug.Assert(((bLastVirama ? 1 : 0) + (bLastATR ? 1 : 0) +
- (bLastDevenagariStressAbbr ? 1 : 0) +
- ((cLastCharForNextNukta > 0) ? 1 : 0)) == 1,
- String.Format(CultureInfo.InvariantCulture,
- "[ISCIIEncoding.GetChars]Special cases require 1 and only 1 special case flag: LastATR {0} Dev. {1} Nukta {2}",
- bLastATR, bLastDevenagariStressAbbr, cLastCharForNextNukta));
- // If the last one was an ATR, then we'll have to do ATR stuff
- if (bLastATR)
- {
- // We only support Devanagari - Punjabi
- if (b >= (0x40 | CodeDevanagari) && b <= (0x40 | CodePunjabi))
- {
- // Remember the code page
- currentCodePage = b & 0xf;
- currentCodePageIndex = IndicMappingIndex[currentCodePage];
- // No longer last ATR
- bLastATR = false;
- continue;
- }
-
- // Change back to default?
- if (b == 0x40)
- {
- currentCodePage = this.defaultCodePage;
- currentCodePageIndex = -1;
-
- if (currentCodePage >= CodeDevanagari && currentCodePage <= CodePunjabi)
- {
- currentCodePageIndex = IndicMappingIndex[currentCodePage];
- }
- // No longer last ATR
- bLastATR = false;
- continue;
- }
-
- // We don't support Roman
- if (b == 0x41)
- {
- currentCodePage = this.defaultCodePage;
- currentCodePageIndex = -1;
-
- if (currentCodePage >= CodeDevanagari && currentCodePage <= CodePunjabi)
- {
- currentCodePageIndex = IndicMappingIndex[currentCodePage];
- }
-
- // Even though we don't know how to support Roman, windows didn't add a ? so we don't either.
- // No longer last ATR
- bLastATR = false;
- continue;
- }
-
- // Other code pages & ATR codes not supported, fallback the ATR
- // If fails, decrements the buffer, which is OK, we remember ATR state.
- if (!buffer.Fallback(ControlATR))
- break;
-
- // No longer last ATR (fell back)
- bLastATR = false;
-
- // we know we can't have any of these other modes
- 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
- }
- else if (bLastVirama)
- {
- // If last was Virama, then we might need ZWNJ or ZWJ instead
- if (b == Virama)
- {
- // If no room, then stop
- if (!buffer.AddChar(ZWNJ))
- break;
- bLastVirama = false;
- continue;
- }
- if (b == Nukta)
- {
- // If no room, then stop
- if (!buffer.AddChar(ZWJ))
- break;
- bLastVirama = false;
- continue;
- }
-
- // No longer in this mode, fall through to handle character
- // (Virama itself was added when flag was set last iteration)
- bLastVirama = false;
-
- // We know we can't have any of these other modes
- 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)
- {
- // Last byte was an 0xf0 (ext).
- // If current is b8 or bf, then we have 952 or 970. Otherwise fallback
- if (b == 0xb8)
- {
- // It was a 0xb8
- if (!buffer.AddChar('\x0952')) // Devanagari stress sign anudatta
- break;
- bLastDevenagariStressAbbr = false;
- continue;
- }
-
- if (b == 0xbf)
- {
- // It was a 0xbf
- if (!buffer.AddChar('\x0970')) // Devanagari abbr. sign
- break;
- bLastDevenagariStressAbbr = false;
- continue;
- }
-
- // Wasn't an expected pattern, do fallback for f0 (ext)
- // if fails, fallback will back up our buffer
- if (!buffer.Fallback(DevenagariExt))
- break;
-
- // Keep processing this byte (turn off mode)
- // (last character was added when mode was set)
- bLastDevenagariStressAbbr = false;
-
- 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
- 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
- if (b == Nukta)
- {
- // We combine nukta with previous char
- if (!buffer.AddChar(cLastCharForNextNukta))
- break;
-
- // Done already
- cLastCharForNextNukta = cLastCharForNoNextNukta = '\0';
- continue;
- }
-
- // No Nukta, just add last character and keep processing current byte
- if (!buffer.AddChar(cLastCharForNoNextNukta))
- break;
-
- // Keep processing this byte, turn off mode.
- cLastCharForNextNukta = cLastCharForNoNextNukta = '\0';
-
- 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.
- Debug.Assert (!bLastSpecial && !bLastDevenagariStressAbbr && !bLastVirama && !bLastATR &&
- cLastCharForNextNukta == '\0',
- "[ISCIIEncoding.GetChars]No special state for last code point should exist at this point.");
-
- // If its a simple byte, just add it
- if (b < MultiByteBegin)
- {
- if (!buffer.AddChar((char)b))
- break;
- continue;
- }
-
- // See if its an ATR marker
- if (b == ControlATR)
- {
- bLastATR = bLastSpecial = true;
- continue;
- }
-
- Debug.Assert (currentCodePageIndex != -1, "[ISCIIEncoding.GetChars]Expected valid currentCodePageIndex != -1");
- char ch = IndicMapping[currentCodePageIndex, 0, b - MultiByteBegin];
- char cAlt = IndicMapping[currentCodePageIndex, 1, b - MultiByteBegin];
-
- // If no 2nd char, just add it, also lonely Nuktas get added as well.
- if (cAlt == 0 || b == Nukta)
- {
- // If it was an unknown character do fallback
-
- // ? if not known.
- if (ch == 0)
- {
- // Fallback the unknown byte
- if (!buffer.Fallback(b))
- break;
- }
- else
- {
- // Add the known character
- if (!buffer.AddChar(ch))
- break;
- }
- continue;
- }
-
- // if b == Virama set last Virama so we can do ZWJ or ZWNJ next time if needed.
- if (b == Virama)
- {
- // Add Virama
- if (!buffer.AddChar(ch))
- break;
- bLastVirama = bLastSpecial = true;
- continue;
- }
-
- // See if its one that changes with a Nukta
- if ((cAlt & 0xF000) == 0)
- {
- // It could change if next char is a nukta
- bLastSpecial = true;
- cLastCharForNextNukta = cAlt;
- cLastCharForNoNextNukta = ch;
- continue;
- }
-
- // We must be the Devenagari special case for F0, B8 & F0, BF
- 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));
- bLastDevenagariStressAbbr = bLastSpecial = true;
-
- }
-
- // If we don't have a decoder, or if we had to flush, then we need to get rid
- // of last ATR, LastNoNextNukta and LastDevenagariExt.
- if (decoder == null || decoder.MustFlush)
- {
- // If these fail (because of Convert with insufficient buffer), then they'll turn off MustFlush as well.
- if (bLastATR)
- {
- // Have to add ATR fallback
- if (buffer.Fallback(ControlATR))
- bLastATR = false;
- else
- // If not successful, convert will maintain state for next time, also
- // AddChar will have decremented our byte count, however we need it to remain the same
- buffer.GetNextByte();
- }
- else if (bLastDevenagariStressAbbr)
- {
- // Have to do fallback for DevenagariExt
- if (buffer.Fallback(DevenagariExt))
- bLastDevenagariStressAbbr = false;
- else
- // If not successful, convert will maintain state for next time, also
- // AddChar will have decremented our byte count, however we need it to remain the same
- buffer.GetNextByte();
- }
- else if (cLastCharForNoNextNukta != '\0')
- {
- // Have to add our last char because there was no next nukta
- if (buffer.AddChar(cLastCharForNoNextNukta))
- cLastCharForNoNextNukta = cLastCharForNextNukta = '\0';
- else
- // If not successful, convert will maintain state for next time, also
- // AddChar will have decremented our byte count, however we need it to remain the same
- buffer.GetNextByte();
- }
- // LastVirama is unimportant for flushing decoder.
- }
-
- // Remember any left over stuff
- // (only remember if we aren't counting)
- if (decoder != null && chars != null)
- {
- // If not flushing or have state (from convert) then need to remember state
- if (!decoder.MustFlush ||
- cLastCharForNoNextNukta != '\0' || bLastATR || bLastDevenagariStressAbbr)
- {
- // Either not flushing or had state (from convert)
- Debug.Assert(!decoder.MustFlush || !decoder.m_throwOnOverflow,
- "[ISCIIEncoding.GetChars]Expected no state or not converting or not flushing");
- decoder.currentCodePage = currentCodePage;
- decoder.bLastVirama = bLastVirama;
- decoder.bLastATR = bLastATR;
- decoder.bLastDevenagariStressAbbr = bLastDevenagariStressAbbr;
- decoder.cLastCharForNextNukta = cLastCharForNextNukta;
- decoder.cLastCharForNoNextNukta = cLastCharForNoNextNukta;
- }
- else
- {
- decoder.currentCodePage = this.defaultCodePage;
- decoder.bLastVirama = false;
- decoder.bLastATR = false;
- decoder.bLastDevenagariStressAbbr = false;
- decoder.cLastCharForNextNukta = '\0';
- decoder.cLastCharForNoNextNukta = '\0';
- }
- decoder.m_bytesUsed = buffer.BytesUsed;
- }
- // Otherwise we already did fallback and added extra things
-
- // Return the # of characters we found
- return buffer.Count;
- }
-
- public override Decoder GetDecoder()
- {
- return new ISCIIDecoder(this);
- }
-
- public override Encoder GetEncoder()
- {
- return new ISCIIEncoder(this);
- }
-
- public override int GetHashCode()
- {
- //Not great distribution, but this is relatively unlikely to be used as the key in a hashtable.
- return defaultCodePage + this.EncoderFallback.GetHashCode() + this.DecoderFallback.GetHashCode();
- }
-
- [Serializable]
- internal class ISCIIEncoder : EncoderNLS
- {
- // Need to remember the default code page (for HasState)
- internal int defaultCodePage = 0;
-
- // Need a place for the current code page
- internal int currentCodePage = 0;
-
- // Was the last character a virama? (Because ZWJ and ZWNJ are different then)
- internal bool bLastVirama = false;
-
- public ISCIIEncoder(Encoding encoding) : base(encoding)
- {
- this.currentCodePage = this.defaultCodePage = encoding.CodePage - 57000;
-
- // base calls reset
- }
-
- // Warning: If you're decoding mixed encoding files or something, this could be confusing
- // We don't always force back to base encoding mapping, so if you reset where do you restart?
- public override void Reset()
- {
- bLastVirama = false;
- charLeftOver = (char)0;
- if (m_fallbackBuffer != null)
- m_fallbackBuffer.Reset();
- }
-
- // Anything left in our encoder?
- // Encoder not only has to get rid of left over characters, but it has to switch back to the current code page.
- internal override bool HasState
- {
- get
- {
- return (this.charLeftOver != (char)0 || this.currentCodePage != this.defaultCodePage);
- }
- }
- }
-
- [Serializable]
- internal class ISCIIDecoder : DecoderNLS
- {
- // Need a place to store any our current code page and last ATR flag
- internal int currentCodePage = 0;
- internal bool bLastATR = false;
- internal bool bLastVirama = false;
- internal bool bLastDevenagariStressAbbr = false;
- internal char cLastCharForNextNukta = '\0';
- internal char cLastCharForNoNextNukta = '\0';
-
- public ISCIIDecoder(Encoding encoding) : base(encoding)
- {
- this.currentCodePage = encoding.CodePage - 57000;
-
- // base calls reset
- }
-
- // Warning: If you're decoding mixed encoding files or something, this could be confusing
- // We don't always force back to base encoding mapping, so if you reset where do you restart?
- public override void Reset()
- {
- bLastATR = false;
- bLastVirama = false;
- bLastDevenagariStressAbbr = false;
- cLastCharForNextNukta = '\0';
- cLastCharForNoNextNukta = '\0';
- if (m_fallbackBuffer != null)
- m_fallbackBuffer.Reset();
- }
-
- // Anything left in our decoder?
- internal override bool HasState
- {
- get
- {
- return (this.cLastCharForNextNukta != '\0' || this.cLastCharForNoNextNukta != '\0' ||
- this.bLastATR || this.bLastDevenagariStressAbbr);
- }
- }
- }
-
- //
- // ISCII Tables
- //
- // From Windows ISCII\tables.c
- //
-
- ////////////////////////////////////////////////////////////////////////////
- //
- // Char to Byte
- //
- // 0xXYZZ Where Y is the code page "font" part and ZZ is the byte character
- // The high X bits also reference the SecondIndicByte table if an
- // extra byte is needed.
- // 0x0000 For undefined characters
- //
- // This is valid for values IndicBegin to IndicEnd
- //
- // WARNING: When this was copied from windows, the ? characters (0x003F) were
- // searched/replaced with 0x0000.
- //
- ////////////////////////////////////////////////////////////////////////////
-
- static int[] UnicodeToIndicChar =
- {
- 0x02a1, // U+0901 : Devanagari Sign Candrabindu
- 0x02a2, // U+0902 : Devanagari Sign Anusvara
- 0x02a3, // U+0903 : Devanagari Sign Visarga
- 0x0000, // U+0904 : Undefined
- 0x02a4, // U+0905 : Devanagari Letter A
- 0x02a5, // U+0906 : Devanagari Letter Aa
- 0x02a6, // U+0907 : Devanagari Letter I
- 0x02a7, // U+0908 : Devanagari Letter Ii
- 0x02a8, // U+0909 : Devanagari Letter U
- 0x02a9, // U+090a : Devanagari Letter Uu
- 0x02aa, // U+090b : Devanagari Letter Vocalic R
- 0x12a6, // U+090c : Devanagari Letter Vocalic L
- 0x02ae, // U+090d : Devanagari Letter Candra E
- 0x02ab, // U+090e : Devanagari Letter Short E
- 0x02ac, // U+090f : Devanagari Letter E
- 0x02ad, // U+0910 : Devanagari Letter Ai
- 0x02b2, // U+0911 : Devanagari Letter Candra O
- 0x02af, // U+0912 : Devanagari Letter Short O
- 0x02b0, // U+0913 : Devanagari Letter O
- 0x02b1, // U+0914 : Devanagari Letter Au
- 0x02b3, // U+0915 : Devanagari Letter Ka
- 0x02b4, // U+0916 : Devanagari Letter Kha
- 0x02b5, // U+0917 : Devanagari Letter Ga
- 0x02b6, // U+0918 : Devanagari Letter Gha
- 0x02b7, // U+0919 : Devanagari Letter Nga
- 0x02b8, // U+091a : Devanagari Letter Ca
- 0x02b9, // U+091b : Devanagari Letter Cha
- 0x02ba, // U+091c : Devanagari Letter Ja
- 0x02bb, // U+091d : Devanagari Letter Jha
- 0x02bc, // U+091e : Devanagari Letter Nya
- 0x02bd, // U+091f : Devanagari Letter Tta
- 0x02be, // U+0920 : Devanagari Letter Ttha
- 0x02bf, // U+0921 : Devanagari Letter Dda
- 0x02c0, // U+0922 : Devanagari Letter Ddha
- 0x02c1, // U+0923 : Devanagari Letter Nna
- 0x02c2, // U+0924 : Devanagari Letter Ta
- 0x02c3, // U+0925 : Devanagari Letter Tha
- 0x02c4, // U+0926 : Devanagari Letter Da
- 0x02c5, // U+0927 : Devanagari Letter Dha
- 0x02c6, // U+0928 : Devanagari Letter Na
- 0x02c7, // U+0929 : Devanagari Letter Nnna
- 0x02c8, // U+092a : Devanagari Letter Pa
- 0x02c9, // U+092b : Devanagari Letter Pha
- 0x02ca, // U+092c : Devanagari Letter Ba
- 0x02cb, // U+092d : Devanagari Letter Bha
- 0x02cc, // U+092e : Devanagari Letter Ma
- 0x02cd, // U+092f : Devanagari Letter Ya
- 0x02cf, // U+0930 : Devanagari Letter Ra
- 0x02d0, // U+0931 : Devanagari Letter Rra
- 0x02d1, // U+0932 : Devanagari Letter La
- 0x02d2, // U+0933 : Devanagari Letter Lla
- 0x02d3, // U+0934 : Devanagari Letter Llla
- 0x02d4, // U+0935 : Devanagari Letter Va
- 0x02d5, // U+0936 : Devanagari Letter Sha
- 0x02d6, // U+0937 : Devanagari Letter Ssa
- 0x02d7, // U+0938 : Devanagari Letter Sa
- 0x02d8, // U+0939 : Devanagari Letter Ha
- 0x0000, // U+093a : Undefined
- 0x0000, // U+093b : Undefined
- 0x02e9, // U+093c : Devanagari Sign Nukta
- 0x12ea, // U+093d : Devanagari Sign Avagraha
- 0x02da, // U+093e : Devanagari Vowel Sign Aa
- 0x02db, // U+093f : Devanagari Vowel Sign I
- 0x02dc, // U+0940 : Devanagari Vowel Sign Ii
- 0x02dd, // U+0941 : Devanagari Vowel Sign U
- 0x02de, // U+0942 : Devanagari Vowel Sign Uu
- 0x02df, // U+0943 : Devanagari Vowel Sign Vocalic R
- 0x12df, // U+0944 : Devanagari Vowel Sign Vocalic Rr
- 0x02e3, // U+0945 : Devanagari Vowel Sign Candra E
- 0x02e0, // U+0946 : Devanagari Vowel Sign Short E
- 0x02e1, // U+0947 : Devanagari Vowel Sign E
- 0x02e2, // U+0948 : Devanagari Vowel Sign Ai
- 0x02e7, // U+0949 : Devanagari Vowel Sign Candra O
- 0x02e4, // U+094a : Devanagari Vowel Sign Short O
- 0x02e5, // U+094b : Devanagari Vowel Sign O
- 0x02e6, // U+094c : Devanagari Vowel Sign Au
- 0x02e8, // U+094d : Devanagari Sign Virama
- 0x0000, // U+094e : Undefined
- 0x0000, // U+094f : Undefined
- 0x12a1, // U+0950 : Devanagari Om
- 0x0000, // U+0951 : Devanagari Stress Sign Udatta
- 0x22f0, // U+0952 : Devanagari Stress Sign Anudatta
- 0x0000, // U+0953 : Devanagari Grave Accent
- 0x0000, // U+0954 : Devanagari Acute Accent
- 0x0000, // U+0955 : Undefined
- 0x0000, // U+0956 : Undefined
- 0x0000, // U+0957 : Undefined
- 0x12b3, // U+0958 : Devanagari Letter Qa
- 0x12b4, // U+0959 : Devanagari Letter Khha
- 0x12b5, // U+095a : Devanagari Letter Ghha
- 0x12ba, // U+095b : Devanagari Letter Za
- 0x12bf, // U+095c : Devanagari Letter Dddha
- 0x12c0, // U+095d : Devanagari Letter Rha
- 0x12c9, // U+095e : Devanagari Letter Fa
- 0x02ce, // U+095f : Devanagari Letter Yya
- 0x12aa, // U+0960 : Devanagari Letter Vocalic Rr
- 0x12a7, // U+0961 : Devanagari Letter Vocalic Ll
- 0x12db, // U+0962 : Devanagari Vowel Sign Vocalic L
- 0x12dc, // U+0963 : Devanagari Vowel Sign Vocalic Ll
- 0x02ea, // U+0964 : Devanagari Danda
- 0x0000, // U+0965 : Devanagari Double Danda
- 0x02f1, // U+0966 : Devanagari Digit Zero
- 0x02f2, // U+0967 : Devanagari Digit One
- 0x02f3, // U+0968 : Devanagari Digit Two
- 0x02f4, // U+0969 : Devanagari Digit Three
- 0x02f5, // U+096a : Devanagari Digit Four
- 0x02f6, // U+096b : Devanagari Digit Five
- 0x02f7, // U+096c : Devanagari Digit Six
- 0x02f8, // U+096d : Devanagari Digit Seven
- 0x02f9, // U+096e : Devanagari Digit Eight
- 0x02fa, // U+096f : Devanagari Digit Nine
- 0x32f0, // U+0970 : Devanagari Abbreviation Sign
- 0x0000, // U+0971 : Undefined
- 0x0000, // U+0972 : Undefined
- 0x0000, // U+0973 : Undefined
- 0x0000, // U+0974 : Undefined
- 0x0000, // U+0975 : Undefined
- 0x0000, // U+0976 : Undefined
- 0x0000, // U+0977 : Undefined
- 0x0000, // U+0978 : Undefined
- 0x0000, // U+0979 : Undefined
- 0x0000, // U+097a : Undefined
- 0x0000, // U+097b : Undefined
- 0x0000, // U+097c : Undefined
- 0x0000, // U+097d : Undefined
- 0x0000, // U+097e : Undefined
- 0x0000, // U+097f : Undefined
- 0x0000, // U+0980 : Undefined
- 0x03a1, // U+0981 : Bengali Sign Candrabindu
- 0x03a2, // U+0982 : Bengali Sign Anusvara
- 0x03a3, // U+0983 : Bengali Sign Visarga
- 0x0000, // U+0984 : Undefined
- 0x03a4, // U+0985 : Bengali Letter A
- 0x03a5, // U+0986 : Bengali Letter Aa
- 0x03a6, // U+0987 : Bengali Letter I
- 0x03a7, // U+0988 : Bengali Letter Ii
- 0x03a8, // U+0989 : Bengali Letter U
- 0x03a9, // U+098a : Bengali Letter Uu
- 0x03aa, // U+098b : Bengali Letter Vocalic R
- 0x13a6, // U+098c : Bengali Letter Vocalic L
- 0x0000, // U+098d : Undefined
- 0x0000, // U+098e : Undefined
- 0x03ab, // U+098f : Bengali Letter E
- 0x03ad, // U+0990 : Bengali Letter Ai
- 0x0000, // U+0991 : Undefined
- 0x0000, // U+0992 : Undefined
- 0x03af, // U+0993 : Bengali Letter O
- 0x03b1, // U+0994 : Bengali Letter Au
- 0x03b3, // U+0995 : Bengali Letter Ka
- 0x03b4, // U+0996 : Bengali Letter Kha
- 0x03b5, // U+0997 : Bengali Letter Ga
- 0x03b6, // U+0998 : Bengali Letter Gha
- 0x03b7, // U+0999 : Bengali Letter Nga
- 0x03b8, // U+099a : Bengali Letter Ca
- 0x03b9, // U+099b : Bengali Letter Cha
- 0x03ba, // U+099c : Bengali Letter Ja
- 0x03bb, // U+099d : Bengali Letter Jha
- 0x03bc, // U+099e : Bengali Letter Nya
- 0x03bd, // U+099f : Bengali Letter Tta
- 0x03be, // U+09a0 : Bengali Letter Ttha
- 0x03bf, // U+09a1 : Bengali Letter Dda
- 0x03c0, // U+09a2 : Bengali Letter Ddha
- 0x03c1, // U+09a3 : Bengali Letter Nna
- 0x03c2, // U+09a4 : Bengali Letter Ta
- 0x03c3, // U+09a5 : Bengali Letter Tha
- 0x03c4, // U+09a6 : Bengali Letter Da
- 0x03c5, // U+09a7 : Bengali Letter Dha
- 0x03c6, // U+09a8 : Bengali Letter Na
- 0x0000, // U+09a9 : Undefined
- 0x03c8, // U+09aa : Bengali Letter Pa
- 0x03c9, // U+09ab : Bengali Letter Pha
- 0x03ca, // U+09ac : Bengali Letter Ba
- 0x03cb, // U+09ad : Bengali Letter Bha
- 0x03cc, // U+09ae : Bengali Letter Ma
- 0x03cd, // U+09af : Bengali Letter Ya
- 0x03cf, // U+09b0 : Bengali Letter Ra
- 0x0000, // U+09b1 : Undefined
- 0x03d1, // U+09b2 : Bengali Letter La
- 0x0000, // U+09b3 : Undefined
- 0x0000, // U+09b4 : Undefined
- 0x0000, // U+09b5 : Undefined
- 0x03d5, // U+09b6 : Bengali Letter Sha
- 0x03d6, // U+09b7 : Bengali Letter Ssa
- 0x03d7, // U+09b8 : Bengali Letter Sa
- 0x03d8, // U+09b9 : Bengali Letter Ha
- 0x0000, // U+09ba : Undefined
- 0x0000, // U+09bb : Undefined
- 0x03e9, // U+09bc : Bengali Sign Nukta
- 0x0000, // U+09bd : Undefined
- 0x03da, // U+09be : Bengali Vowel Sign Aa
- 0x03db, // U+09bf : Bengali Vowel Sign I
- 0x03dc, // U+09c0 : Bengali Vowel Sign Ii
- 0x03dd, // U+09c1 : Bengali Vowel Sign U
- 0x03de, // U+09c2 : Bengali Vowel Sign Uu
- 0x03df, // U+09c3 : Bengali Vowel Sign Vocalic R
- 0x13df, // U+09c4 : Bengali Vowel Sign Vocalic Rr
- 0x0000, // U+09c5 : Undefined
- 0x0000, // U+09c6 : Undefined
- 0x03e0, // U+09c7 : Bengali Vowel Sign E
- 0x03e2, // U+09c8 : Bengali Vowel Sign Ai
- 0x0000, // U+09c9 : Undefined
- 0x0000, // U+09ca : Undefined
- 0x03e4, // U+09cb : Bengali Vowel Sign O
- 0x03e6, // U+09cc : Bengali Vowel Sign Au
- 0x03e8, // U+09cd : Bengali Sign Virama
- 0x0000, // U+09ce : Undefined
- 0x0000, // U+09cf : Undefined
- 0x0000, // U+09d0 : Undefined
- 0x0000, // U+09d1 : Undefined
- 0x0000, // U+09d2 : Undefined
- 0x0000, // U+09d3 : Undefined
- 0x0000, // U+09d4 : Undefined
- 0x0000, // U+09d5 : Undefined
- 0x0000, // U+09d6 : Undefined
- 0x0000, // U+09d7 : Bengali Au Length Mark
- 0x0000, // U+09d8 : Undefined
- 0x0000, // U+09d9 : Undefined
- 0x0000, // U+09da : Undefined
- 0x0000, // U+09db : Undefined
- 0x13bf, // U+09dc : Bengali Letter Rra
- 0x13c0, // U+09dd : Bengali Letter Rha
- 0x0000, // U+09de : Undefined
- 0x03ce, // U+09df : Bengali Letter Yya
- 0x13aa, // U+09e0 : Bengali Letter Vocalic Rr
- 0x13a7, // U+09e1 : Bengali Letter Vocalic Ll
- 0x13db, // U+09e2 : Bengali Vowel Sign Vocalic L
- 0x13dc, // U+09e3 : Bengali Vowel Sign Vocalic Ll
- 0x0000, // U+09e4 : Undefined
- 0x0000, // U+09e5 : Undefined
- 0x03f1, // U+09e6 : Bengali Digit Zero
- 0x03f2, // U+09e7 : Bengali Digit One
- 0x03f3, // U+09e8 : Bengali Digit Two
- 0x03f4, // U+09e9 : Bengali Digit Three
- 0x03f5, // U+09ea : Bengali Digit Four
- 0x03f6, // U+09eb : Bengali Digit Five
- 0x03f7, // U+09ec : Bengali Digit Six
- 0x03f8, // U+09ed : Bengali Digit Seven
- 0x03f9, // U+09ee : Bengali Digit Eight
- 0x03fa, // U+09ef : Bengali Digit Nine
- 0x0000, // U+09f0 : Bengali Letter Ra With Middle Diagonal
- 0x0000, // U+09f1 : Bengali Letter Ra With Lower Diagonal
- 0x0000, // U+09f2 : Bengali Rupee Mark
- 0x0000, // U+09f3 : Bengali Rupee Sign
- 0x0000, // U+09f4 : Bengali Currency Numerator One
- 0x0000, // U+09f5 : Bengali Currency Numerator Two
- 0x0000, // U+09f6 : Bengali Currency Numerator Three
- 0x0000, // U+09f7 : Bengali Currency Numerator Four
- 0x0000, // U+09f8 : Bengali Currency Numerator One Less Than The Denominator
- 0x0000, // U+09f9 : Bengali Currency Denominator Sixteen
- 0x0000, // U+09fa : Bengali Isshar
- 0x0000, // U+09fb : Undefined
- 0x0000, // U+09fc : Undefined
- 0x0000, // U+09fd : Undefined
- 0x0000, // U+09fe : Undefined
- 0x0000, // U+09ff : Undefined
- 0x0000, // U+0a00 : Undefined
- 0x0000, // U+0a01 : Undefined
- 0x0ba2, // U+0a02 : Gurmukhi Sign Bindi
- 0x0000, // U+0a03 : Undefined
- 0x0000, // U+0a04 : Undefined
- 0x0ba4, // U+0a05 : Gurmukhi Letter A
- 0x0ba5, // U+0a06 : Gurmukhi Letter Aa
- 0x0ba6, // U+0a07 : Gurmukhi Letter I
- 0x0ba7, // U+0a08 : Gurmukhi Letter Ii
- 0x0ba8, // U+0a09 : Gurmukhi Letter U
- 0x0ba9, // U+0a0a : Gurmukhi Letter Uu
- 0x0000, // U+0a0b : Undefined
- 0x0000, // U+0a0c : Undefined
- 0x0000, // U+0a0d : Undefined
- 0x0000, // U+0a0e : Undefined
- 0x0bab, // U+0a0f : Gurmukhi Letter Ee
- 0x0bad, // U+0a10 : Gurmukhi Letter Ai
- 0x0000, // U+0a11 : Undefined
- 0x0000, // U+0a12 : Undefined
- 0x0bb0, // U+0a13 : Gurmukhi Letter Oo
- 0x0bb1, // U+0a14 : Gurmukhi Letter Au
- 0x0bb3, // U+0a15 : Gurmukhi Letter Ka
- 0x0bb4, // U+0a16 : Gurmukhi Letter Kha
- 0x0bb5, // U+0a17 : Gurmukhi Letter Ga
- 0x0bb6, // U+0a18 : Gurmukhi Letter Gha
- 0x0bb7, // U+0a19 : Gurmukhi Letter Nga
- 0x0bb8, // U+0a1a : Gurmukhi Letter Ca
- 0x0bb9, // U+0a1b : Gurmukhi Letter Cha
- 0x0bba, // U+0a1c : Gurmukhi Letter Ja
- 0x0bbb, // U+0a1d : Gurmukhi Letter Jha
- 0x0bbc, // U+0a1e : Gurmukhi Letter Nya
- 0x0bbd, // U+0a1f : Gurmukhi Letter Tta
- 0x0bbe, // U+0a20 : Gurmukhi Letter Ttha
- 0x0bbf, // U+0a21 : Gurmukhi Letter Dda
- 0x0bc0, // U+0a22 : Gurmukhi Letter Ddha
- 0x0bc1, // U+0a23 : Gurmukhi Letter Nna
- 0x0bc2, // U+0a24 : Gurmukhi Letter Ta
- 0x0bc3, // U+0a25 : Gurmukhi Letter Tha
- 0x0bc4, // U+0a26 : Gurmukhi Letter Da
- 0x0bc5, // U+0a27 : Gurmukhi Letter Dha
- 0x0bc6, // U+0a28 : Gurmukhi Letter Na
- 0x0000, // U+0a29 : Undefined
- 0x0bc8, // U+0a2a : Gurmukhi Letter Pa
- 0x0bc9, // U+0a2b : Gurmukhi Letter Pha
- 0x0bca, // U+0a2c : Gurmukhi Letter Ba
- 0x0bcb, // U+0a2d : Gurmukhi Letter Bha
- 0x0bcc, // U+0a2e : Gurmukhi Letter Ma
- 0x0bcd, // U+0a2f : Gurmukhi Letter Ya
- 0x0bcf, // U+0a30 : Gurmukhi Letter Ra
- 0x0000, // U+0a31 : Undefined
- 0x0bd1, // U+0a32 : Gurmukhi Letter La
- 0x0bd2, // U+0a33 : Gurmukhi Letter Lla
- 0x0000, // U+0a34 : Undefined
- 0x0bd4, // U+0a35 : Gurmukhi Letter Va
- 0x0bd5, // U+0a36 : Gurmukhi Letter Sha
- 0x0000, // U+0a37 : Undefined
- 0x0bd7, // U+0a38 : Gurmukhi Letter Sa
- 0x0bd8, // U+0a39 : Gurmukhi Letter Ha
- 0x0000, // U+0a3a : Undefined
- 0x0000, // U+0a3b : Undefined
- 0x0be9, // U+0a3c : Gurmukhi Sign Nukta
- 0x0000, // U+0a3d : Undefined
- 0x0bda, // U+0a3e : Gurmukhi Vowel Sign Aa
- 0x0bdb, // U+0a3f : Gurmukhi Vowel Sign I
- 0x0bdc, // U+0a40 : Gurmukhi Vowel Sign Ii
- 0x0bdd, // U+0a41 : Gurmukhi Vowel Sign U
- 0x0bde, // U+0a42 : Gurmukhi Vowel Sign Uu
- 0x0000, // U+0a43 : Undefined
- 0x0000, // U+0a44 : Undefined
- 0x0000, // U+0a45 : Undefined
- 0x0000, // U+0a46 : Undefined
- 0x0be0, // U+0a47 : Gurmukhi Vowel Sign Ee
- 0x0be2, // U+0a48 : Gurmukhi Vowel Sign Ai
- 0x0000, // U+0a49 : Undefined
- 0x0000, // U+0a4a : Undefined
- 0x0be4, // U+0a4b : Gurmukhi Vowel Sign Oo
- 0x0be6, // U+0a4c : Gurmukhi Vowel Sign Au
- 0x0be8, // U+0a4d : Gurmukhi Sign Virama
- 0x0000, // U+0a4e : Undefined
- 0x0000, // U+0a4f : Undefined
- 0x0000, // U+0a50 : Undefined
- 0x0000, // U+0a51 : Undefined
- 0x0000, // U+0a52 : Undefined
- 0x0000, // U+0a53 : Undefined
- 0x0000, // U+0a54 : Undefined
- 0x0000, // U+0a55 : Undefined
- 0x0000, // U+0a56 : Undefined
- 0x0000, // U+0a57 : Undefined
- 0x0000, // U+0a58 : Undefined
- 0x1bb4, // U+0a59 : Gurmukhi Letter Khha
- 0x1bb5, // U+0a5a : Gurmukhi Letter Ghha
- 0x1bba, // U+0a5b : Gurmukhi Letter Za
- 0x1bc0, // U+0a5c : Gurmukhi Letter Rra
- 0x0000, // U+0a5d : Undefined
- 0x1bc9, // U+0a5e : Gurmukhi Letter Fa
- 0x0000, // U+0a5f : Undefined
- 0x0000, // U+0a60 : Undefined
- 0x0000, // U+0a61 : Undefined
- 0x0000, // U+0a62 : Undefined
- 0x0000, // U+0a63 : Undefined
- 0x0000, // U+0a64 : Undefined
- 0x0000, // U+0a65 : Undefined
- 0x0bf1, // U+0a66 : Gurmukhi Digit Zero
- 0x0bf2, // U+0a67 : Gurmukhi Digit One
- 0x0bf3, // U+0a68 : Gurmukhi Digit Two
- 0x0bf4, // U+0a69 : Gurmukhi Digit Three
- 0x0bf5, // U+0a6a : Gurmukhi Digit Four
- 0x0bf6, // U+0a6b : Gurmukhi Digit Five
- 0x0bf7, // U+0a6c : Gurmukhi Digit Six
- 0x0bf8, // U+0a6d : Gurmukhi Digit Seven
- 0x0bf9, // U+0a6e : Gurmukhi Digit Eight
- 0x0bfa, // U+0a6f : Gurmukhi Digit Nine
- 0x0000, // U+0a70 : Gurmukhi Tippi
- 0x0000, // U+0a71 : Gurmukhi Addak
- 0x0000, // U+0a72 : Gurmukhi Iri
- 0x0000, // U+0a73 : Gurmukhi Ura
- 0x0000, // U+0a74 : Gurmukhi Ek Onkar
- 0x0000, // U+0a75 : Undefined
- 0x0000, // U+0a76 : Undefined
- 0x0000, // U+0a77 : Undefined
- 0x0000, // U+0a78 : Undefined
- 0x0000, // U+0a79 : Undefined
- 0x0000, // U+0a7a : Undefined
- 0x0000, // U+0a7b : Undefined
- 0x0000, // U+0a7c : Undefined
- 0x0000, // U+0a7d : Undefined
- 0x0000, // U+0a7e : Undefined
- 0x0000, // U+0a7f : Undefined
- 0x0000, // U+0a80 : Undefined
- 0x0aa1, // U+0a81 : Gujarati Sign Candrabindu
- 0x0aa2, // U+0a82 : Gujarati Sign Anusvara
- 0x0aa3, // U+0a83 : Gujarati Sign Visarga
- 0x0000, // U+0a84 : Undefined
- 0x0aa4, // U+0a85 : Gujarati Letter A
- 0x0aa5, // U+0a86 : Gujarati Letter Aa
- 0x0aa6, // U+0a87 : Gujarati Letter I
- 0x0aa7, // U+0a88 : Gujarati Letter Ii
- 0x0aa8, // U+0a89 : Gujarati Letter U
- 0x0aa9, // U+0a8a : Gujarati Letter Uu
- 0x0aaa, // U+0a8b : Gujarati Letter Vocalic R
- 0x0000, // U+0a8c : Undefined
- 0x0aae, // U+0a8d : Gujarati Vowel Candra E
- 0x0000, // U+0a8e : Undefined
- 0x0aab, // U+0a8f : Gujarati Letter E
- 0x0aad, // U+0a90 : Gujarati Letter Ai
- 0x0ab2, // U+0a91 : Gujarati Vowel Candra O
- 0x0000, // U+0a92 : Undefined
- 0x0ab0, // U+0a93 : Gujarati Letter O
- 0x0ab1, // U+0a94 : Gujarati Letter Au
- 0x0ab3, // U+0a95 : Gujarati Letter Ka
- 0x0ab4, // U+0a96 : Gujarati Letter Kha
- 0x0ab5, // U+0a97 : Gujarati Letter Ga
- 0x0ab6, // U+0a98 : Gujarati Letter Gha
- 0x0ab7, // U+0a99 : Gujarati Letter Nga
- 0x0ab8, // U+0a9a : Gujarati Letter Ca
- 0x0ab9, // U+0a9b : Gujarati Letter Cha
- 0x0aba, // U+0a9c : Gujarati Letter Ja
- 0x0abb, // U+0a9d : Gujarati Letter Jha
- 0x0abc, // U+0a9e : Gujarati Letter Nya
- 0x0abd, // U+0a9f : Gujarati Letter Tta
- 0x0abe, // U+0aa0 : Gujarati Letter Ttha
- 0x0abf, // U+0aa1 : Gujarati Letter Dda
- 0x0ac0, // U+0aa2 : Gujarati Letter Ddha
- 0x0ac1, // U+0aa3 : Gujarati Letter Nna
- 0x0ac2, // U+0aa4 : Gujarati Letter Ta
- 0x0ac3, // U+0aa5 : Gujarati Letter Tha
- 0x0ac4, // U+0aa6 : Gujarati Letter Da
- 0x0ac5, // U+0aa7 : Gujarati Letter Dha
- 0x0ac6, // U+0aa8 : Gujarati Letter Na
- 0x0000, // U+0aa9 : Undefined
- 0x0ac8, // U+0aaa : Gujarati Letter Pa
- 0x0ac9, // U+0aab : Gujarati Letter Pha
- 0x0aca, // U+0aac : Gujarati Letter Ba
- 0x0acb, // U+0aad : Gujarati Letter Bha
- 0x0acc, // U+0aae : Gujarati Letter Ma
- 0x0acd, // U+0aaf : Gujarati Letter Ya
- 0x0acf, // U+0ab0 : Gujarati Letter Ra
- 0x0000, // U+0ab1 : Undefined
- 0x0ad1, // U+0ab2 : Gujarati Letter La
- 0x0ad2, // U+0ab3 : Gujarati Letter Lla
- 0x0000, // U+0ab4 : Undefined
- 0x0ad4, // U+0ab5 : Gujarati Letter Va
- 0x0ad5, // U+0ab6 : Gujarati Letter Sha
- 0x0ad6, // U+0ab7 : Gujarati Letter Ssa
- 0x0ad7, // U+0ab8 : Gujarati Letter Sa
- 0x0ad8, // U+0ab9 : Gujarati Letter Ha
- 0x0000, // U+0aba : Undefined
- 0x0000, // U+0abb : Undefined
- 0x0ae9, // U+0abc : Gujarati Sign Nukta
- 0x1aea, // U+0abd : Gujarati Sign Avagraha
- 0x0ada, // U+0abe : Gujarati Vowel Sign Aa
- 0x0adb, // U+0abf : Gujarati Vowel Sign I
- 0x0adc, // U+0ac0 : Gujarati Vowel Sign Ii
- 0x0add, // U+0ac1 : Gujarati Vowel Sign U
- 0x0ade, // U+0ac2 : Gujarati Vowel Sign Uu
- 0x0adf, // U+0ac3 : Gujarati Vowel Sign Vocalic R
- 0x1adf, // U+0ac4 : Gujarati Vowel Sign Vocalic Rr
- 0x0ae3, // U+0ac5 : Gujarati Vowel Sign Candra E
- 0x0000, // U+0ac6 : Undefined
- 0x0ae0, // U+0ac7 : Gujarati Vowel Sign E
- 0x0ae2, // U+0ac8 : Gujarati Vowel Sign Ai
- 0x0ae7, // U+0ac9 : Gujarati Vowel Sign Candra O
- 0x0000, // U+0aca : Undefined
- 0x0ae4, // U+0acb : Gujarati Vowel Sign O
- 0x0ae6, // U+0acc : Gujarati Vowel Sign Au
- 0x0ae8, // U+0acd : Gujarati Sign Virama
- 0x0000, // U+0ace : Undefined
- 0x0000, // U+0acf : Undefined
- 0x1aa1, // U+0ad0 : Gujarati Om
- 0x0000, // U+0ad1 : Undefined
- 0x0000, // U+0ad2 : Undefined
- 0x0000, // U+0ad3 : Undefined
- 0x0000, // U+0ad4 : Undefined
- 0x0000, // U+0ad5 : Undefined
- 0x0000, // U+0ad6 : Undefined
- 0x0000, // U+0ad7 : Undefined
- 0x0000, // U+0ad8 : Undefined
- 0x0000, // U+0ad9 : Undefined
- 0x0000, // U+0ada : Undefined
- 0x0000, // U+0adb : Undefined
- 0x0000, // U+0adc : Undefined
- 0x0000, // U+0add : Undefined
- 0x0000, // U+0ade : Undefined
- 0x0000, // U+0adf : Undefined
- 0x1aaa, // U+0ae0 : Gujarati Letter Vocalic Rr
- 0x0000, // U+0ae1 : Undefined
- 0x0000, // U+0ae2 : Undefined
- 0x0000, // U+0ae3 : Undefined
- 0x0000, // U+0ae4 : Undefined
- 0x0000, // U+0ae5 : Undefined
- 0x0af1, // U+0ae6 : Gujarati Digit Zero
- 0x0af2, // U+0ae7 : Gujarati Digit One
- 0x0af3, // U+0ae8 : Gujarati Digit Two
- 0x0af4, // U+0ae9 : Gujarati Digit Three
- 0x0af5, // U+0aea : Gujarati Digit Four
- 0x0af6, // U+0aeb : Gujarati Digit Five
- 0x0af7, // U+0aec : Gujarati Digit Six
- 0x0af8, // U+0aed : Gujarati Digit Seven
- 0x0af9, // U+0aee : Gujarati Digit Eight
- 0x0afa, // U+0aef : Gujarati Digit Nine
- 0x0000, // U+0af0 : Undefined
- 0x0000, // U+0af1 : Undefined
- 0x0000, // U+0af2 : Undefined
- 0x0000, // U+0af3 : Undefined
- 0x0000, // U+0af4 : Undefined
- 0x0000, // U+0af5 : Undefined
- 0x0000, // U+0af6 : Undefined
- 0x0000, // U+0af7 : Undefined
- 0x0000, // U+0af8 : Undefined
- 0x0000, // U+0af9 : Undefined
- 0x0000, // U+0afa : Undefined
- 0x0000, // U+0afb : Undefined
- 0x0000, // U+0afc : Undefined
- 0x0000, // U+0afd : Undefined
- 0x0000, // U+0afe : Undefined
- 0x0000, // U+0aff : Undefined
- 0x0000, // U+0b00 : Undefined
- 0x07a1, // U+0b01 : Oriya Sign Candrabindu
- 0x07a2, // U+0b02 : Oriya Sign Anusvara
- 0x07a3, // U+0b03 : Oriya Sign Visarga
- 0x0000, // U+0b04 : Undefined
- 0x07a4, // U+0b05 : Oriya Letter A
- 0x07a5, // U+0b06 : Oriya Letter Aa
- 0x07a6, // U+0b07 : Oriya Letter I
- 0x07a7, // U+0b08 : Oriya Letter Ii
- 0x07a8, // U+0b09 : Oriya Letter U
- 0x07a9, // U+0b0a : Oriya Letter Uu
- 0x07aa, // U+0b0b : Oriya Letter Vocalic R
- 0x17a6, // U+0b0c : Oriya Letter Vocalic L
- 0x0000, // U+0b0d : Undefined
- 0x0000, // U+0b0e : Undefined
- 0x07ab, // U+0b0f : Oriya Letter E
- 0x07ad, // U+0b10 : Oriya Letter Ai
- 0x0000, // U+0b11 : Undefined
- 0x0000, // U+0b12 : Undefined
- 0x07b0, // U+0b13 : Oriya Letter O
- 0x07b1, // U+0b14 : Oriya Letter Au
- 0x07b3, // U+0b15 : Oriya Letter Ka
- 0x07b4, // U+0b16 : Oriya Letter Kha
- 0x07b5, // U+0b17 : Oriya Letter Ga
- 0x07b6, // U+0b18 : Oriya Letter Gha
- 0x07b7, // U+0b19 : Oriya Letter Nga
- 0x07b8, // U+0b1a : Oriya Letter Ca
- 0x07b9, // U+0b1b : Oriya Letter Cha
- 0x07ba, // U+0b1c : Oriya Letter Ja
- 0x07bb, // U+0b1d : Oriya Letter Jha
- 0x07bc, // U+0b1e : Oriya Letter Nya
- 0x07bd, // U+0b1f : Oriya Letter Tta
- 0x07be, // U+0b20 : Oriya Letter Ttha
- 0x07bf, // U+0b21 : Oriya Letter Dda
- 0x07c0, // U+0b22 : Oriya Letter Ddha
- 0x07c1, // U+0b23 : Oriya Letter Nna
- 0x07c2, // U+0b24 : Oriya Letter Ta
- 0x07c3, // U+0b25 : Oriya Letter Tha
- 0x07c4, // U+0b26 : Oriya Letter Da
- 0x07c5, // U+0b27 : Oriya Letter Dha
- 0x07c6, // U+0b28 : Oriya Letter Na
- 0x0000, // U+0b29 : Undefined
- 0x07c8, // U+0b2a : Oriya Letter Pa
- 0x07c9, // U+0b2b : Oriya Letter Pha
- 0x07ca, // U+0b2c : Oriya Letter Ba
- 0x07cb, // U+0b2d : Oriya Letter Bha
- 0x07cc, // U+0b2e : Oriya Letter Ma
- 0x07cd, // U+0b2f : Oriya Letter Ya
- 0x07cf, // U+0b30 : Oriya Letter Ra
- 0x0000, // U+0b31 : Undefined
- 0x07d1, // U+0b32 : Oriya Letter La
- 0x07d2, // U+0b33 : Oriya Letter Lla
- 0x0000, // U+0b34 : Undefined
- 0x0000, // U+0b35 : Undefined
- 0x07d5, // U+0b36 : Oriya Letter Sha
- 0x07d6, // U+0b37 : Oriya Letter Ssa
- 0x07d7, // U+0b38 : Oriya Letter Sa
- 0x07d8, // U+0b39 : Oriya Letter Ha
- 0x0000, // U+0b3a : Undefined
- 0x0000, // U+0b3b : Undefined
- 0x07e9, // U+0b3c : Oriya Sign Nukta
- 0x17ea, // U+0b3d : Oriya Sign Avagraha
- 0x07da, // U+0b3e : Oriya Vowel Sign Aa
- 0x07db, // U+0b3f : Oriya Vowel Sign I
- 0x07dc, // U+0b40 : Oriya Vowel Sign Ii
- 0x07dd, // U+0b41 : Oriya Vowel Sign U
- 0x07de, // U+0b42 : Oriya Vowel Sign Uu
- 0x07df, // U+0b43 : Oriya Vowel Sign Vocalic R
- 0x0000, // U+0b44 : Undefined
- 0x0000, // U+0b45 : Undefined
- 0x0000, // U+0b46 : Undefined
- 0x07e0, // U+0b47 : Oriya Vowel Sign E
- 0x07e2, // U+0b48 : Oriya Vowel Sign Ai
- 0x0000, // U+0b49 : Undefined
- 0x0000, // U+0b4a : Undefined
- 0x07e4, // U+0b4b : Oriya Vowel Sign O
- 0x07e6, // U+0b4c : Oriya Vowel Sign Au
- 0x07e8, // U+0b4d : Oriya Sign Virama
- 0x0000, // U+0b4e : Undefined
- 0x0000, // U+0b4f : Undefined
- 0x0000, // U+0b50 : Undefined
- 0x0000, // U+0b51 : Undefined
- 0x0000, // U+0b52 : Undefined
- 0x0000, // U+0b53 : Undefined
- 0x0000, // U+0b54 : Undefined
- 0x0000, // U+0b55 : Undefined
- 0x0000, // U+0b56 : Oriya Ai Length Mark
- 0x0000, // U+0b57 : Oriya Au Length Mark
- 0x0000, // U+0b58 : Undefined
- 0x0000, // U+0b59 : Undefined
- 0x0000, // U+0b5a : Undefined
- 0x0000, // U+0b5b : Undefined
- 0x17bf, // U+0b5c : Oriya Letter Rra
- 0x17c0, // U+0b5d : Oriya Letter Rha
- 0x0000, // U+0b5e : Undefined
- 0x07ce, // U+0b5f : Oriya Letter Yya
- 0x17aa, // U+0b60 : Oriya Letter Vocalic Rr
- 0x17a7, // U+0b61 : Oriya Letter Vocalic Ll
- 0x0000, // U+0b62 : Undefined
- 0x0000, // U+0b63 : Undefined
- 0x0000, // U+0b64 : Undefined
- 0x0000, // U+0b65 : Undefined
- 0x07f1, // U+0b66 : Oriya Digit Zero
- 0x07f2, // U+0b67 : Oriya Digit One
- 0x07f3, // U+0b68 : Oriya Digit Two
- 0x07f4, // U+0b69 : Oriya Digit Three
- 0x07f5, // U+0b6a : Oriya Digit Four
- 0x07f6, // U+0b6b : Oriya Digit Five
- 0x07f7, // U+0b6c : Oriya Digit Six
- 0x07f8, // U+0b6d : Oriya Digit Seven
- 0x07f9, // U+0b6e : Oriya Digit Eight
- 0x07fa, // U+0b6f : Oriya Digit Nine
- 0x0000, // U+0b70 : Oriya Isshar
- 0x0000, // U+0b71 : Undefined
- 0x0000, // U+0b72 : Undefined
- 0x0000, // U+0b73 : Undefined
- 0x0000, // U+0b74 : Undefined
- 0x0000, // U+0b75 : Undefined
- 0x0000, // U+0b76 : Undefined
- 0x0000, // U+0b77 : Undefined
- 0x0000, // U+0b78 : Undefined
- 0x0000, // U+0b79 : Undefined
- 0x0000, // U+0b7a : Undefined
- 0x0000, // U+0b7b : Undefined
- 0x0000, // U+0b7c : Undefined
- 0x0000, // U+0b7d : Undefined
- 0x0000, // U+0b7e : Undefined
- 0x0000, // U+0b7f : Undefined
- 0x0000, // U+0b80 : Undefined
- 0x0000, // U+0b81 : Undefined
- 0x04a2, // U+0b82 : Tamil Sign Anusvara
- 0x04a3, // U+0b83 : Tamil Sign Visarga
- 0x0000, // U+0b84 : Undefined
- 0x04a4, // U+0b85 : Tamil Letter A
- 0x04a5, // U+0b86 : Tamil Letter Aa
- 0x04a6, // U+0b87 : Tamil Letter I
- 0x04a7, // U+0b88 : Tamil Letter Ii
- 0x04a8, // U+0b89 : Tamil Letter U
- 0x04a9, // U+0b8a : Tamil Letter Uu
- 0x0000, // U+0b8b : Undefined
- 0x0000, // U+0b8c : Undefined
- 0x0000, // U+0b8d : Undefined
- 0x0000, // U+0b8e : Tamil Letter E
- 0x04ab, // U+0b8f : Tamil Letter Ee
- 0x04ad, // U+0b90 : Tamil Letter Ai
- 0x0000, // U+0b91 : Undefined
- 0x04af, // U+0b92 : Tamil Letter O
- 0x04b0, // U+0b93 : Tamil Letter Oo
- 0x04b1, // U+0b94 : Tamil Letter Au
- 0x04b3, // U+0b95 : Tamil Letter Ka
- 0x0000, // U+0b96 : Undefined
- 0x0000, // U+0b97 : Undefined
- 0x0000, // U+0b98 : Undefined
- 0x04b7, // U+0b99 : Tamil Letter Nga
- 0x04b8, // U+0b9a : Tamil Letter Ca
- 0x0000, // U+0b9b : Undefined
- 0x04ba, // U+0b9c : Tamil Letter Ja
- 0x0000, // U+0b9d : Undefined
- 0x04bc, // U+0b9e : Tamil Letter Nya
- 0x04bd, // U+0b9f : Tamil Letter Tta
- 0x0000, // U+0ba0 : Undefined
- 0x0000, // U+0ba1 : Undefined
- 0x0000, // U+0ba2 : Undefined
- 0x04c1, // U+0ba3 : Tamil Letter Nna
- 0x04c2, // U+0ba4 : Tamil Letter Ta
- 0x0000, // U+0ba5 : Undefined
- 0x0000, // U+0ba6 : Undefined
- 0x0000, // U+0ba7 : Undefined
- 0x04c6, // U+0ba8 : Tamil Letter Na
- 0x04c7, // U+0ba9 : Tamil Letter Nnna
- 0x04c8, // U+0baa : Tamil Letter Pa
- 0x0000, // U+0bab : Undefined
- 0x0000, // U+0bac : Undefined
- 0x0000, // U+0bad : Undefined
- 0x04cc, // U+0bae : Tamil Letter Ma
- 0x04cd, // U+0baf : Tamil Letter Ya
- 0x04cf, // U+0bb0 : Tamil Letter Ra
- 0x04d0, // U+0bb1 : Tamil Letter Rra
- 0x04d1, // U+0bb2 : Tamil Letter La
- 0x04d2, // U+0bb3 : Tamil Letter Lla
- 0x04d3, // U+0bb4 : Tamil Letter Llla
- 0x04d4, // U+0bb5 : Tamil Letter Va
- 0x0000, // U+0bb6 : Undefined
- 0x04d5, // U+0bb7 : Tamil Letter Ssa
- 0x04d7, // U+0bb8 : Tamil Letter Sa
- 0x04d8, // U+0bb9 : Tamil Letter Ha
- 0x0000, // U+0bba : Undefined
- 0x0000, // U+0bbb : Undefined
- 0x0000, // U+0bbc : Undefined
- 0x0000, // U+0bbd : Undefined
- 0x04da, // U+0bbe : Tamil Vowel Sign Aa
- 0x04db, // U+0bbf : Tamil Vowel Sign I
- 0x04dc, // U+0bc0 : Tamil Vowel Sign Ii
- 0x04dd, // U+0bc1 : Tamil Vowel Sign U
- 0x04de, // U+0bc2 : Tamil Vowel Sign Uu
- 0x0000, // U+0bc3 : Undefined
- 0x0000, // U+0bc4 : Undefined
- 0x0000, // U+0bc5 : Undefined
- 0x04e0, // U+0bc6 : Tamil Vowel Sign E
- 0x04e1, // U+0bc7 : Tamil Vowel Sign Ee
- 0x04e2, // U+0bc8 : Tamil Vowel Sign Ai
- 0x0000, // U+0bc9 : Undefined
- 0x04e4, // U+0bca : Tamil Vowel Sign O
- 0x04e5, // U+0bcb : Tamil Vowel Sign Oo
- 0x04e6, // U+0bcc : Tamil Vowel Sign Au
- 0x04e8, // U+0bcd : Tamil Sign Virama
- 0x0000, // U+0bce : Undefined
- 0x0000, // U+0bcf : Undefined
- 0x0000, // U+0bd0 : Undefined
- 0x0000, // U+0bd1 : Undefined
- 0x0000, // U+0bd2 : Undefined
- 0x0000, // U+0bd3 : Undefined
- 0x0000, // U+0bd4 : Undefined
- 0x0000, // U+0bd5 : Undefined
- 0x0000, // U+0bd6 : Undefined
- 0x0000, // U+0bd7 : Tamil Au Length Mark
- 0x0000, // U+0bd8 : Undefined
- 0x0000, // U+0bd9 : Undefined
- 0x0000, // U+0bda : Undefined
- 0x0000, // U+0bdb : Undefined
- 0x0000, // U+0bdc : Undefined
- 0x0000, // U+0bdd : Undefined
- 0x0000, // U+0bde : Undefined
- 0x0000, // U+0bdf : Undefined
- 0x0000, // U+0be0 : Undefined
- 0x0000, // U+0be1 : Undefined
- 0x0000, // U+0be2 : Undefined
- 0x0000, // U+0be3 : Undefined
- 0x0000, // U+0be4 : Undefined
- 0x0000, // U+0be5 : Undefined
- 0x0000, // U+0be6 : Undefined
- 0x04f2, // U+0be7 : Tamil Digit One
- 0x04f3, // U+0be8 : Tamil Digit Two
- 0x04f4, // U+0be9 : Tamil Digit Three
- 0x04f5, // U+0bea : Tamil Digit Four
- 0x04f6, // U+0beb : Tamil Digit Five
- 0x04f7, // U+0bec : Tamil Digit Six
- 0x04f8, // U+0bed : Tamil Digit Seven
- 0x04f9, // U+0bee : Tamil Digit Eight
- 0x04fa, // U+0bef : Tamil Digit Nine
- 0x0000, // U+0bf0 : Tamil Number Ten
- 0x0000, // U+0bf1 : Tamil Number One Hundred
- 0x0000, // U+0bf2 : Tamil Number One Thousand
- 0x0000, // U+0bf3 : Undefined
- 0x0000, // U+0bf4 : Undefined
- 0x0000, // U+0bf5 : Undefined
- 0x0000, // U+0bf6 : Undefined
- 0x0000, // U+0bf7 : Undefined
- 0x0000, // U+0bf8 : Undefined
- 0x0000, // U+0bf9 : Undefined
- 0x0000, // U+0bfa : Undefined
- 0x0000, // U+0bfb : Undefined
- 0x0000, // U+0bfc : Undefined
- 0x0000, // U+0bfd : Undefined
- 0x0000, // U+0bfe : Undefined
- 0x0000, // U+0bff : Undefined
- 0x0000, // U+0c00 : Undefined
- 0x05a1, // U+0c01 : Telugu Sign Candrabindu
- 0x05a2, // U+0c02 : Telugu Sign Anusvara
- 0x05a3, // U+0c03 : Telugu Sign Visarga
- 0x0000, // U+0c04 : Undefined
- 0x05a4, // U+0c05 : Telugu Letter A
- 0x05a5, // U+0c06 : Telugu Letter Aa
- 0x05a6, // U+0c07 : Telugu Letter I
- 0x05a7, // U+0c08 : Telugu Letter Ii
- 0x05a8, // U+0c09 : Telugu Letter U
- 0x05a9, // U+0c0a : Telugu Letter Uu
- 0x05aa, // U+0c0b : Telugu Letter Vocalic R
- 0x15a6, // U+0c0c : Telugu Letter Vocalic L
- 0x0000, // U+0c0d : Undefined
- 0x05ab, // U+0c0e : Telugu Letter E
- 0x05ac, // U+0c0f : Telugu Letter Ee
- 0x05ad, // U+0c10 : Telugu Letter Ai
- 0x0000, // U+0c11 : Undefined
- 0x05af, // U+0c12 : Telugu Letter O
- 0x05b0, // U+0c13 : Telugu Letter Oo
- 0x05b1, // U+0c14 : Telugu Letter Au
- 0x05b3, // U+0c15 : Telugu Letter Ka
- 0x05b4, // U+0c16 : Telugu Letter Kha
- 0x05b5, // U+0c17 : Telugu Letter Ga
- 0x05b6, // U+0c18 : Telugu Letter Gha
- 0x05b7, // U+0c19 : Telugu Letter Nga
- 0x05b8, // U+0c1a : Telugu Letter Ca
- 0x05b9, // U+0c1b : Telugu Letter Cha
- 0x05ba, // U+0c1c : Telugu Letter Ja
- 0x05bb, // U+0c1d : Telugu Letter Jha
- 0x05bc, // U+0c1e : Telugu Letter Nya
- 0x05bd, // U+0c1f : Telugu Letter Tta
- 0x05be, // U+0c20 : Telugu Letter Ttha
- 0x05bf, // U+0c21 : Telugu Letter Dda
- 0x05c0, // U+0c22 : Telugu Letter Ddha
- 0x05c1, // U+0c23 : Telugu Letter Nna
- 0x05c2, // U+0c24 : Telugu Letter Ta
- 0x05c3, // U+0c25 : Telugu Letter Tha
- 0x05c4, // U+0c26 : Telugu Letter Da
- 0x05c5, // U+0c27 : Telugu Letter Dha
- 0x05c6, // U+0c28 : Telugu Letter Na
- 0x0000, // U+0c29 : Undefined
- 0x05c8, // U+0c2a : Telugu Letter Pa
- 0x05c9, // U+0c2b : Telugu Letter Pha
- 0x05ca, // U+0c2c : Telugu Letter Ba
- 0x05cb, // U+0c2d : Telugu Letter Bha
- 0x05cc, // U+0c2e : Telugu Letter Ma
- 0x05cd, // U+0c2f : Telugu Letter Ya
- 0x05cf, // U+0c30 : Telugu Letter Ra
- 0x05d0, // U+0c31 : Telugu Letter Rra
- 0x05d1, // U+0c32 : Telugu Letter La
- 0x05d2, // U+0c33 : Telugu Letter Lla
- 0x0000, // U+0c34 : Undefined
- 0x05d4, // U+0c35 : Telugu Letter Va
- 0x05d5, // U+0c36 : Telugu Letter Sha
- 0x05d6, // U+0c37 : Telugu Letter Ssa
- 0x05d7, // U+0c38 : Telugu Letter Sa
- 0x05d8, // U+0c39 : Telugu Letter Ha
- 0x0000, // U+0c3a : Undefined
- 0x0000, // U+0c3b : Undefined
- 0x0000, // U+0c3c : Undefined
- 0x0000, // U+0c3d : Undefined
- 0x05da, // U+0c3e : Telugu Vowel Sign Aa
- 0x05db, // U+0c3f : Telugu Vowel Sign I
- 0x05dc, // U+0c40 : Telugu Vowel Sign Ii
- 0x05dd, // U+0c41 : Telugu Vowel Sign U
- 0x05de, // U+0c42 : Telugu Vowel Sign Uu
- 0x05df, // U+0c43 : Telugu Vowel Sign Vocalic R
- 0x15df, // U+0c44 : Telugu Vowel Sign Vocalic Rr
- 0x0000, // U+0c45 : Undefined
- 0x05e0, // U+0c46 : Telugu Vowel Sign E
- 0x05e1, // U+0c47 : Telugu Vowel Sign Ee
- 0x05e2, // U+0c48 : Telugu Vowel Sign Ai
- 0x0000, // U+0c49 : Undefined
- 0x05e4, // U+0c4a : Telugu Vowel Sign O
- 0x05e5, // U+0c4b : Telugu Vowel Sign Oo
- 0x05e6, // U+0c4c : Telugu Vowel Sign Au
- 0x05e8, // U+0c4d : Telugu Sign Virama
- 0x0000, // U+0c4e : Undefined
- 0x0000, // U+0c4f : Undefined
- 0x0000, // U+0c50 : Undefined
- 0x0000, // U+0c51 : Undefined
- 0x0000, // U+0c52 : Undefined
- 0x0000, // U+0c53 : Undefined
- 0x0000, // U+0c54 : Undefined
- 0x0000, // U+0c55 : Telugu Length Mark
- 0x0000, // U+0c56 : Telugu Ai Length Mark
- 0x0000, // U+0c57 : Undefined
- 0x0000, // U+0c58 : Undefined
- 0x0000, // U+0c59 : Undefined
- 0x0000, // U+0c5a : Undefined
- 0x0000, // U+0c5b : Undefined
- 0x0000, // U+0c5c : Undefined
- 0x0000, // U+0c5d : Undefined
- 0x0000, // U+0c5e : Undefined
- 0x0000, // U+0c5f : Undefined
- 0x15aa, // U+0c60 : Telugu Letter Vocalic Rr
- 0x15a7, // U+0c61 : Telugu Letter Vocalic Ll
- 0x0000, // U+0c62 : Undefined
- 0x0000, // U+0c63 : Undefined
- 0x0000, // U+0c64 : Undefined
- 0x0000, // U+0c65 : Undefined
- 0x05f1, // U+0c66 : Telugu Digit Zero
- 0x05f2, // U+0c67 : Telugu Digit One
- 0x05f3, // U+0c68 : Telugu Digit Two
- 0x05f4, // U+0c69 : Telugu Digit Three
- 0x05f5, // U+0c6a : Telugu Digit Four
- 0x05f6, // U+0c6b : Telugu Digit Five
- 0x05f7, // U+0c6c : Telugu Digit Six
- 0x05f8, // U+0c6d : Telugu Digit Seven
- 0x05f9, // U+0c6e : Telugu Digit Eight
- 0x05fa, // U+0c6f : Telugu Digit Nine
- 0x0000, // U+0c70 : Undefined
- 0x0000, // U+0c71 : Undefined
- 0x0000, // U+0c72 : Undefined
- 0x0000, // U+0c73 : Undefined
- 0x0000, // U+0c74 : Undefined
- 0x0000, // U+0c75 : Undefined
- 0x0000, // U+0c76 : Undefined
- 0x0000, // U+0c77 : Undefined
- 0x0000, // U+0c78 : Undefined
- 0x0000, // U+0c79 : Undefined
- 0x0000, // U+0c7a : Undefined
- 0x0000, // U+0c7b : Undefined
- 0x0000, // U+0c7c : Undefined
- 0x0000, // U+0c7d : Undefined
- 0x0000, // U+0c7e : Undefined
- 0x0000, // U+0c7f : Undefined
- 0x0000, // U+0c80 : Undefined
- 0x0000, // U+0c81 : Undefined
- 0x08a2, // U+0c82 : Kannada Sign Anusvara
- 0x08a3, // U+0c83 : Kannada Sign Visarga
- 0x0000, // U+0c84 : Undefined
- 0x08a4, // U+0c85 : Kannada Letter A
- 0x08a5, // U+0c86 : Kannada Letter Aa
- 0x08a6, // U+0c87 : Kannada Letter I
- 0x08a7, // U+0c88 : Kannada Letter Ii
- 0x08a8, // U+0c89 : Kannada Letter U
- 0x08a9, // U+0c8a : Kannada Letter Uu
- 0x08aa, // U+0c8b : Kannada Letter Vocalic R
- 0x18a6, // U+0c8c : Kannada Letter Vocalic L
- 0x0000, // U+0c8d : Undefined
- 0x08ab, // U+0c8e : Kannada Letter E
- 0x08ac, // U+0c8f : Kannada Letter Ee
- 0x08ad, // U+0c90 : Kannada Letter Ai
- 0x0000, // U+0c91 : Undefined
- 0x08af, // U+0c92 : Kannada Letter O
- 0x08b0, // U+0c93 : Kannada Letter Oo
- 0x08b1, // U+0c94 : Kannada Letter Au
- 0x08b3, // U+0c95 : Kannada Letter Ka
- 0x08b4, // U+0c96 : Kannada Letter Kha
- 0x08b5, // U+0c97 : Kannada Letter Ga
- 0x08b6, // U+0c98 : Kannada Letter Gha
- 0x08b7, // U+0c99 : Kannada Letter Nga
- 0x08b8, // U+0c9a : Kannada Letter Ca
- 0x08b9, // U+0c9b : Kannada Letter Cha
- 0x08ba, // U+0c9c : Kannada Letter Ja
- 0x08bb, // U+0c9d : Kannada Letter Jha
- 0x08bc, // U+0c9e : Kannada Letter Nya
- 0x08bd, // U+0c9f : Kannada Letter Tta
- 0x08be, // U+0ca0 : Kannada Letter Ttha
- 0x08bf, // U+0ca1 : Kannada Letter Dda
- 0x08c0, // U+0ca2 : Kannada Letter Ddha
- 0x08c1, // U+0ca3 : Kannada Letter Nna
- 0x08c2, // U+0ca4 : Kannada Letter Ta
- 0x08c3, // U+0ca5 : Kannada Letter Tha
- 0x08c4, // U+0ca6 : Kannada Letter Da
- 0x08c5, // U+0ca7 : Kannada Letter Dha
- 0x08c6, // U+0ca8 : Kannada Letter Na
- 0x0000, // U+0ca9 : Undefined
- 0x08c8, // U+0caa : Kannada Letter Pa
- 0x08c9, // U+0cab : Kannada Letter Pha
- 0x08ca, // U+0cac : Kannada Letter Ba
- 0x08cb, // U+0cad : Kannada Letter Bha
- 0x08cc, // U+0cae : Kannada Letter Ma
- 0x08cd, // U+0caf : Kannada Letter Ya
- 0x08cf, // U+0cb0 : Kannada Letter Ra
- 0x08d0, // U+0cb1 : Kannada Letter Rra
- 0x08d1, // U+0cb2 : Kannada Letter La
- 0x08d2, // U+0cb3 : Kannada Letter Lla
- 0x0000, // U+0cb4 : Undefined
- 0x08d4, // U+0cb5 : Kannada Letter Va
- 0x08d5, // U+0cb6 : Kannada Letter Sha
- 0x08d6, // U+0cb7 : Kannada Letter Ssa
- 0x08d7, // U+0cb8 : Kannada Letter Sa
- 0x08d8, // U+0cb9 : Kannada Letter Ha
- 0x0000, // U+0cba : Undefined
- 0x0000, // U+0cbb : Undefined
- 0x0000, // U+0cbc : Undefined
- 0x0000, // U+0cbd : Undefined
- 0x08da, // U+0cbe : Kannada Vowel Sign Aa
- 0x08db, // U+0cbf : Kannada Vowel Sign I
- 0x08dc, // U+0cc0 : Kannada Vowel Sign Ii
- 0x08dd, // U+0cc1 : Kannada Vowel Sign U
- 0x08de, // U+0cc2 : Kannada Vowel Sign Uu
- 0x08df, // U+0cc3 : Kannada Vowel Sign Vocalic R
- 0x18df, // U+0cc4 : Kannada Vowel Sign Vocalic Rr
- 0x0000, // U+0cc5 : Undefined
- 0x08e0, // U+0cc6 : Kannada Vowel Sign E
- 0x08e1, // U+0cc7 : Kannada Vowel Sign Ee
- 0x08e2, // U+0cc8 : Kannada Vowel Sign Ai
- 0x0000, // U+0cc9 : Undefined
- 0x08e4, // U+0cca : Kannada Vowel Sign O
- 0x08e5, // U+0ccb : Kannada Vowel Sign Oo
- 0x08e6, // U+0ccc : Kannada Vowel Sign Au
- 0x08e8, // U+0ccd : Kannada Sign Virama
- 0x0000, // U+0cce : Undefined
- 0x0000, // U+0ccf : Undefined
- 0x0000, // U+0cd0 : Undefined
- 0x0000, // U+0cd1 : Undefined
- 0x0000, // U+0cd2 : Undefined
- 0x0000, // U+0cd3 : Undefined
- 0x0000, // U+0cd4 : Undefined
- 0x0000, // U+0cd5 : Kannada Length Mark
- 0x0000, // U+0cd6 : Kannada Ai Length Mark
- 0x0000, // U+0cd7 : Undefined
- 0x0000, // U+0cd8 : Undefined
- 0x0000, // U+0cd9 : Undefined
- 0x0000, // U+0cda : Undefined
- 0x0000, // U+0cdb : Undefined
- 0x0000, // U+0cdc : Undefined
- 0x0000, // U+0cdd : Undefined
- 0x18c9, // U+0cde : Kannada Letter Fa
- 0x0000, // U+0cdf : Undefined
- 0x18aa, // U+0ce0 : Kannada Letter Vocalic Rr
- 0x18a7, // U+0ce1 : Kannada Letter Vocalic Ll
- 0x0000, // U+0ce2 : Undefined
- 0x0000, // U+0ce3 : Undefined
- 0x0000, // U+0ce4 : Undefined
- 0x0000, // U+0ce5 : Undefined
- 0x08f1, // U+0ce6 : Kannada Digit Zero
- 0x08f2, // U+0ce7 : Kannada Digit One
- 0x08f3, // U+0ce8 : Kannada Digit Two
- 0x08f4, // U+0ce9 : Kannada Digit Three
- 0x08f5, // U+0cea : Kannada Digit Four
- 0x08f6, // U+0ceb : Kannada Digit Five
- 0x08f7, // U+0cec : Kannada Digit Six
- 0x08f8, // U+0ced : Kannada Digit Seven
- 0x08f9, // U+0cee : Kannada Digit Eight
- 0x08fa, // U+0cef : Kannada Digit Nine
- 0x0000, // U+0cf0 : Undefined
- 0x0000, // U+0cf1 : Undefined
- 0x0000, // U+0cf2 : Undefined
- 0x0000, // U+0cf3 : Undefined
- 0x0000, // U+0cf4 : Undefined
- 0x0000, // U+0cf5 : Undefined
- 0x0000, // U+0cf6 : Undefined
- 0x0000, // U+0cf7 : Undefined
- 0x0000, // U+0cf8 : Undefined
- 0x0000, // U+0cf9 : Undefined
- 0x0000, // U+0cfa : Undefined
- 0x0000, // U+0cfb : Undefined
- 0x0000, // U+0cfc : Undefined
- 0x0000, // U+0cfd : Undefined
- 0x0000, // U+0cfe : Undefined
- 0x0000, // U+0cff : Undefined
- 0x0000, // U+0d00 : Undefined
- 0x0000, // U+0d01 : Undefined
- 0x09a2, // U+0d02 : Malayalam Sign Anusvara
- 0x09a3, // U+0d03 : Malayalam Sign Visarga
- 0x0000, // U+0d04 : Undefined
- 0x09a4, // U+0d05 : Malayalam Letter A
- 0x09a5, // U+0d06 : Malayalam Letter Aa
- 0x09a6, // U+0d07 : Malayalam Letter I
- 0x09a7, // U+0d08 : Malayalam Letter Ii
- 0x09a8, // U+0d09 : Malayalam Letter U
- 0x09a9, // U+0d0a : Malayalam Letter Uu
- 0x09aa, // U+0d0b : Malayalam Letter Vocalic R
- 0x19a6, // U+0d0c : Malayalam Letter Vocalic L
- 0x0000, // U+0d0d : Undefined
- 0x09ab, // U+0d0e : Malayalam Letter E
- 0x09ac, // U+0d0f : Malayalam Letter Ee
- 0x09ad, // U+0d10 : Malayalam Letter Ai
- 0x0000, // U+0d11 : Undefined
- 0x09af, // U+0d12 : Malayalam Letter O
- 0x09b0, // U+0d13 : Malayalam Letter Oo
- 0x09b1, // U+0d14 : Malayalam Letter Au
- 0x09b3, // U+0d15 : Malayalam Letter Ka
- 0x09b4, // U+0d16 : Malayalam Letter Kha
- 0x09b5, // U+0d17 : Malayalam Letter Ga
- 0x09b6, // U+0d18 : Malayalam Letter Gha
- 0x09b7, // U+0d19 : Malayalam Letter Nga
- 0x09b8, // U+0d1a : Malayalam Letter Ca
- 0x09b9, // U+0d1b : Malayalam Letter Cha
- 0x09ba, // U+0d1c : Malayalam Letter Ja
- 0x09bb, // U+0d1d : Malayalam Letter Jha
- 0x09bc, // U+0d1e : Malayalam Letter Nya
- 0x09bd, // U+0d1f : Malayalam Letter Tta
- 0x09be, // U+0d20 : Malayalam Letter Ttha
- 0x09bf, // U+0d21 : Malayalam Letter Dda
- 0x09c0, // U+0d22 : Malayalam Letter Ddha
- 0x09c1, // U+0d23 : Malayalam Letter Nna
- 0x09c2, // U+0d24 : Malayalam Letter Ta
- 0x09c3, // U+0d25 : Malayalam Letter Tha
- 0x09c4, // U+0d26 : Malayalam Letter Da
- 0x09c5, // U+0d27 : Malayalam Letter Dha
- 0x09c6, // U+0d28 : Malayalam Letter Na
- 0x0000, // U+0d29 : Undefined
- 0x09c8, // U+0d2a : Malayalam Letter Pa
- 0x09c9, // U+0d2b : Malayalam Letter Pha
- 0x09ca, // U+0d2c : Malayalam Letter Ba
- 0x09cb, // U+0d2d : Malayalam Letter Bha
- 0x09cc, // U+0d2e : Malayalam Letter Ma
- 0x09cd, // U+0d2f : Malayalam Letter Ya
- 0x09cf, // U+0d30 : Malayalam Letter Ra
- 0x09d0, // U+0d31 : Malayalam Letter Rra
- 0x09d1, // U+0d32 : Malayalam Letter La
- 0x09d2, // U+0d33 : Malayalam Letter Lla
- 0x09d3, // U+0d34 : Malayalam Letter Llla
- 0x09d4, // U+0d35 : Malayalam Letter Va
- 0x09d5, // U+0d36 : Malayalam Letter Sha
- 0x09d6, // U+0d37 : Malayalam Letter Ssa
- 0x09d7, // U+0d38 : Malayalam Letter Sa
- 0x09d8, // U+0d39 : Malayalam Letter Ha
- 0x0000, // U+0d3a : Undefined
- 0x0000, // U+0d3b : Undefined
- 0x0000, // U+0d3c : Undefined
- 0x0000, // U+0d3d : Undefined
- 0x09da, // U+0d3e : Malayalam Vowel Sign Aa
- 0x09db, // U+0d3f : Malayalam Vowel Sign I
- 0x09dc, // U+0d40 : Malayalam Vowel Sign Ii
- 0x09dd, // U+0d41 : Malayalam Vowel Sign U
- 0x09de, // U+0d42 : Malayalam Vowel Sign Uu
- 0x09df, // U+0d43 : Malayalam Vowel Sign Vocalic R
- 0x0000, // U+0d44 : Undefined
- 0x0000, // U+0d45 : Undefined
- 0x09e0, // U+0d46 : Malayalam Vowel Sign E
- 0x09e1, // U+0d47 : Malayalam Vowel Sign Ee
- 0x09e2, // U+0d48 : Malayalam Vowel Sign Ai
- 0x0000, // U+0d49 : Undefined
- 0x09e4, // U+0d4a : Malayalam Vowel Sign O
- 0x09e5, // U+0d4b : Malayalam Vowel Sign Oo
- 0x09e6, // U+0d4c : Malayalam Vowel Sign Au
- 0x09e8, // U+0d4d : Malayalam Sign Virama
- 0x0000, // U+0d4e : Undefined
- 0x0000, // U+0d4f : Undefined
- 0x0000, // U+0d50 : Undefined
- 0x0000, // U+0d51 : Undefined
- 0x0000, // U+0d52 : Undefined
- 0x0000, // U+0d53 : Undefined
- 0x0000, // U+0d54 : Undefined
- 0x0000, // U+0d55 : Undefined
- 0x0000, // U+0d56 : Undefined
- 0x0000, // U+0d57 : Malayalam Au Length Mark
- 0x0000, // U+0d58 : Undefined
- 0x0000, // U+0d59 : Undefined
- 0x0000, // U+0d5a : Undefined
- 0x0000, // U+0d5b : Undefined
- 0x0000, // U+0d5c : Undefined
- 0x0000, // U+0d5d : Undefined
- 0x0000, // U+0d5e : Undefined
- 0x0000, // U+0d5f : Undefined
- 0x19aa, // U+0d60 : Malayalam Letter Vocalic Rr
- 0x19a7, // U+0d61 : Malayalam Letter Vocalic Ll
- 0x0000, // U+0d62 : Undefined
- 0x0000, // U+0d63 : Undefined
- 0x0000, // U+0d64 : Undefined
- 0x0000, // U+0d65 : Undefined
- 0x09f1, // U+0d66 : Malayalam Digit Zero
- 0x09f2, // U+0d67 : Malayalam Digit One
- 0x09f3, // U+0d68 : Malayalam Digit Two
- 0x09f4, // U+0d69 : Malayalam Digit Three
- 0x09f5, // U+0d6a : Malayalam Digit Four
- 0x09f6, // U+0d6b : Malayalam Digit Five
- 0x09f7, // U+0d6c : Malayalam Digit Six
- 0x09f8, // U+0d6d : Malayalam Digit Seven
- 0x09f9, // U+0d6e : Malayalam Digit Eight
- 0x09fa // U+0d6f : Malayalam Digit Nine
- };
-
- ////////////////////////////////////////////////////////////////////////////
- // SecondIndicByte
- //
- // This is used if the UnicodeToIndic table 4 high bits are set, this is
- // the value of the second Indic byte when applicable.
- ////////////////////////////////////////////////////////////////////////////
- static byte[] SecondIndicByte =
- {
- 0x00,
- 0xe9,
- 0xb8, // U+0952 == 0xf0_0xb8
- 0xbf // U+0970 == 0xf0_0xbf
- };
-
- ////////////////////////////////////////////////////////////////////////////
- // IndicMapping
- //
- // This table maps the 10 indic code pages to their unicode counterparts.
- // There are 0x60 characters in each table. The tables are in pairs of 2
- // (1st char, 2nd char) and there are 10 tables (1 for each code page "font")
- ////////////////////////////////////////////////////////////////////////////
- static int[] IndicMappingIndex =
- {
- -1, // 0 DEF 0X40 Default // Not a real code page
- -1, // 1 RMN 0X41 Roman // Transliteration not supported
- 0, // 2 DEV 0X42 Devanagari
- 1, // 3 BNG 0X43 Bengali
- 2, // 4 TML 0X44 Tamil
- 3, // 5 TLG 0X45 Telugu
- 1, // 6 ASM 0X46 Assamese (Bengali) - Reuses table 1
- 4, // 7 ORI 0X47 Oriya
- 5, // 8 KND 0X48 Kannada
- 6, // 9 MLM 0X49 Malayalam
- 7, // 10 GJR 0X4A Gujarati
- 8 // 11 PNJ 0X4B Punjabi (Gurmukhi)
- };
-
- ////////////////////////////////////////////////////////////////////////////
- // IndicMapping
- //
- // This table contains 9 tables for the 10 indic code pages to their unicode counterparts.
- // There are 0x60 characters in each table. The tables are in pairs of 2
- // (1st char, 2nd char) and there are 10 tables (1 for each code page "font")
- //
- // The first index is the table index (from the IndicMappingIndex table),
- // the 2nd the byte index, the third the character index.
- //
- // For byte 0 a 0x0000 value indicates an unknown character
- // For byte 1 a 0 value indicates no special attributes.
- // For byte 1, 200C & 200D are Virama, Nukta special cases
- // For byte 1, B8BF is Devanagari stress & abbreviation sign special cases
- //
- // WARNING: When copying these from windows, ? 0x003F were changed to 0x0000.
- //
- ////////////////////////////////////////////////////////////////////////////
- // char[codePageMapIndex][byte][character]
- static char[,,] IndicMapping =
- {
- {
- ////////////////////////////////////////////////////////////////////////////
- //
- // Devanagari Table 0, Code Page (2, 0x42, 57002)
- //
- ////////////////////////////////////////////////////////////////////////////
-
- // Default Unicode Char
- {
- // a0, a1, a2, a3, a4, a5, a6, a7,
- '\x0000', '\x0901', '\x0902', '\x0903', '\x0905', '\x0906', '\x0907', '\x0908',
- // a8, a9, aa, ab, ac, ad, ae, af,
- '\x0909', '\x090a', '\x090b', '\x090e', '\x090f', '\x0910', '\x090d', '\x0912',
- // b0, b1, b2, b3, b4, b5, b6, b7,
- '\x0913', '\x0914', '\x0911', '\x0915', '\x0916', '\x0917', '\x0918', '\x0919',
- // b8, b9, ba, bb, bc, bd, be, bf,
- '\x091a', '\x091b', '\x091c', '\x091d', '\x091e', '\x091f', '\x0920', '\x0921',
- // c0, c1, c2, c3, c4, c5, c6, c7,
- '\x0922', '\x0923', '\x0924', '\x0925', '\x0926', '\x0927', '\x0928', '\x0929',
- // c8, c9, ca, cb, cc, cd, ce, cf,
- '\x092a', '\x092b', '\x092c', '\x092d', '\x092e', '\x092f', '\x095f', '\x0930',
- // d0, d1, d2, d3, d4, d5, d6, d7,
- '\x0931', '\x0932', '\x0933', '\x0934', '\x0935', '\x0936', '\x0937', '\x0938',
- // d8, d9, da, db, dc, dd, de, df,
- '\x0939', '\x0000', '\x093e', '\x093f', '\x0940', '\x0941', '\x0942', '\x0943',
- // e0, e1, e2, e3, e4, e5, e6, e7,
- '\x0946', '\x0947', '\x0948', '\x0945', '\x094a', '\x094b', '\x094c', '\x0949',
- // e8, e9, ea, eb, ec, ed, ee, ef,
- '\x094d', '\x093c', '\x0964', '\x0000', '\x0000', '\x0000', '\x0000', '\x0000',
- // f0, f1, f2, f3, f4, f5, f6, f7,
- '\x0000', '\x0966', '\x0967', '\x0968', '\x0969', '\x096a', '\x096b', '\x096c',
- // f8, f9, fa, fb, fc, fd, fe, ff
- '\x096d', '\x096e', '\x096f', '\x0000', '\x0000', '\x0000', '\x0000', '\x0000'
- },
-
- // Alternate Unicode Char & Flags
- {
- // a0, a1, a2, a3, a4, a5, a6, a7,
- '\x0', '\x0950', '\x0', '\x0', '\x0', '\x0', '\x090c', '\x0961',
- // a8, a9, aa, ab, ac, ad, ae, af,
- '\x0', '\x0', '\x0960', '\x0', '\x0', '\x0', '\x0', '\x0',
- // b0, b1, b2, b3, b4, b5, b6, b7,
- '\x0', '\x0', '\x0', '\x0958', '\x0959', '\x095a', '\x0', '\x0',
- // b8, b9, ba, bb, bc, bd, be, bf,
- '\x0', '\x0', '\x095b', '\x0', '\x0', '\x0', '\x0', '\x095c',
- // c0, c1, c2, c3, c4, c5, c6, c7,
- '\x095d', '\x0', '\x0', '\x0', '\x0', '\x0', '\x0', '\x0',
- // c8, c9, ca, cb, cc, cd, ce, cf,
- '\x0', '\x095e', '\x0', '\x0', '\x0', '\x0', '\x0', '\x0',
- // d0, d1, d2, d3, d4, d5, d6, d7,
- '\x0', '\x0', '\x0', '\x0', '\x0', '\x0', '\x0', '\x0',
- // d8, d9, da, db, dc, dd, de, df,
- '\x0', '\x0', '\x0', '\x0962', '\x0963', '\x0', '\x0', '\x0944',
- // e0, e1, e2, e3, e4, e5, e6, e7,
- '\x0', '\x0', '\x0', '\x0', '\x0', '\x0', '\x0', '\x0',
- // e8, e9, ea, eb, ec, ed, ee, ef,
- '\x200C', '\x200D', '\x093d', '\x0', '\x0', '\x0', '\x0', '\x0',
- // f0, f1, f2, f3, f4, f5, f6, f7,
- '\xB8BF', '\x0', '\x0', '\x0', '\x0', '\x0', '\x0', '\x0',
- // f8, f9, fa, fb, fc, fd, fe, ff
- '\x0', '\x0', '\x0', '\x0', '\x0', '\x0', '\x0', '\x0'
- }
- },
-
- {
- ////////////////////////////////////////////////////////////////////////////
- //
- // Bengali & Assemese Table 1', Code Pages (3, '43', 57003 & 6', '46', 57006)
- //
- ////////////////////////////////////////////////////////////////////////////
-
- // Default Unicode Char
- {
- // a0, a1, a2, a3, a4, a5, a6, a7,
- '\x0000', '\x0981', '\x0982', '\x0983', '\x0985', '\x0986', '\x0987', '\x0988',
- // a8, a9, aa, ab, ac, ad, ae, af,
- '\x0989', '\x098a', '\x098b', '\x098f', '\x098f', '\x0990', '\x0990', '\x0993',
- // b0, b1, b2, b3, b4, b5, b6, b7,
- '\x0993', '\x0994', '\x0994', '\x0995', '\x0996', '\x0997', '\x0998', '\x0999',
- // b8, b9, ba, bb, bc, bd, be, bf,
- '\x099a', '\x099b', '\x099c', '\x099d', '\x099e', '\x099f', '\x09a0', '\x09a1',
- // c0, c1, c2, c3, c4, c5, c6, c7,
- '\x09a2', '\x09a3', '\x09a4', '\x09a5', '\x09a6', '\x09a7', '\x09a8', '\x09a8',
- // c8, c9, ca, cb, cc, cd, ce, cf,
- '\x09aa', '\x09ab', '\x09ac', '\x09ad', '\x09ae', '\x09af', '\x09df', '\x09b0',
- // d0, d1, d2, d3, d4, d5, d6, d7,
- '\x09b0', '\x09b2', '\x09b2', '\x09b2', '\x09ac', '\x09b6', '\x09b7', '\x09b8',
- // d8, d9, da, db, dc, dd, de, df,
- '\x09b9', '\x0000', '\x09be', '\x09bf', '\x09c0', '\x09c1', '\x09c2', '\x09c3',
- // e0, e1, e2, e3, e4, e5, e6, e7,
- '\x09c7', '\x09c7', '\x09c8', '\x09c8', '\x09cb', '\x09cb', '\x09cc', '\x09cc',
- // e8, e9, ea, eb, ec, ed, ee, ef,
- '\x09cd', '\x09bc', '\x002e', '\x0000', '\x0000', '\x0000', '\x0000', '\x0000',
- // f0, f1, f2, f3, f4, f5, f6, f7,
- '\x0000', '\x09e6', '\x09e7', '\x09e8', '\x09e9', '\x09ea', '\x09eb', '\x09ec',
- // f8, f9, fa, fb, fc, fd, fe, ff
- '\x09ed', '\x09ee', '\x09ef', '\x0000', '\x0000', '\x0000', '\x0000', '\x0000'
- },
-
- // Alternate Unicode Char & Flags
- {
- // a0, a1, a2, a3, a4, a5, a6, a7,
- '\x0', '\x0', '\x0', '\x0', '\x0', '\x0', '\x098c', '\x09e1',
- // a8, a9, aa, ab, ac, ad, ae, af,
- '\x0', '\x0', '\x09e0', '\x0', '\x0', '\x0', '\x0', '\x0',
- // b0, b1, b2, b3, b4, b5, b6, b7,
- '\x0', '\x0', '\x0', '\x0', '\x0', '\x0', '\x0', '\x0',
- // b8, b9, ba, bb, bc, bd, be, bf,
- '\x0', '\x0', '\x0', '\x0', '\x0', '\x0', '\x0', '\x09dc',
- // c0, c1, c2, c3, c4, c5, c6, c7,
- '\x09dd', '\x0', '\x0', '\x0', '\x0', '\x0', '\x0', '\x0',
- // c8, c9, ca, cb, cc, cd, ce, cf,
- '\x0', '\x0', '\x0', '\x0', '\x0', '\x0', '\x0', '\x0',
- // d0, d1, d2, d3, d4, d5, d6, d7,
- '\x0', '\x0', '\x0', '\x0', '\x0', '\x0', '\x0', '\x0',
- // d8, d9, da, db, dc, dd, de, df,
- '\x0', '\x0', '\x0', '\x09e2', '\x09e3', '\x0', '\x0', '\x09c4',
- // e0, e1, e2, e3, e4, e5, e6, e7,
- '\x0', '\x0', '\x0', '\x0', '\x0', '\x0', '\x0', '\x0',
- // e8, e9, ea, eb, ec, ed, ee, ef,
- '\x200C', '\x200D', '\x0', '\x0', '\x0', '\x0', '\x0', '\x0',
- // f0, f1, f2, f3, f4, f5, f6, f7,
- '\x0', '\x0', '\x0', '\x0', '\x0', '\x0', '\x0', '\x0',
- // f8, f9, fa, fb, fc, fd, fe, ff
- '\x0', '\x0', '\x0', '\x0', '\x0', '\x0', '\x0', '\x0'
- }
- },
-
- {
- ////////////////////////////////////////////////////////////////////////////
- //
- // Tamil Table 2', Code Page (4, '44', 57004)
- //
- ////////////////////////////////////////////////////////////////////////////
-
- // Default Unicode Char
- {
- // a0, a1, a2, a3, a4, a5, a6, a7,
- '\x0000', '\x0000', '\x0b82', '\x0b83', '\x0b85', '\x0b86', '\x0b87', '\x0b88',
- // a8, a9, aa, ab, ac, ad, ae, af,
- '\x0b89', '\x0b8a', '\x0000', '\x0b8f', '\x0b8f', '\x0b90', '\x0b90', '\x0b92',
- // b0, b1, b2, b3, b4, b5, b6, b7,
- '\x0b93', '\x0b94', '\x0b94', '\x0b95', '\x0b95', '\x0b95', '\x0b95', '\x0b99',
- // b8, b9, ba, bb, bc, bd, be, bf,
- '\x0b9a', '\x0b9a', '\x0b9c', '\x0b9c', '\x0b9e', '\x0b9f', '\x0b9f', '\x0b9f',
- // c0, c1, c2, c3, c4, c5, c6, c7,
- '\x0b9f', '\x0ba3', '\x0ba4', '\x0ba4', '\x0ba4', '\x0ba4', '\x0ba8', '\x0ba9',
- // c8, c9, ca, cb, cc, cd, ce, cf,
- '\x0baa', '\x0baa', '\x0baa', '\x0baa', '\x0bae', '\x0baf', '\x0baf', '\x0bb0',
- // d0, d1, d2, d3, d4, d5, d6, d7,
- '\x0bb1', '\x0bb2', '\x0bb3', '\x0bb4', '\x0bb5', '\x0bb7', '\x0bb7', '\x0bb8',
- // d8, d9, da, db, dc, dd, de, df,
- '\x0bb9', '\x0000', '\x0bbe', '\x0bbf', '\x0bc0', '\x0bc1', '\x0bc2', '\x0000',
- // e0, e1, e2, e3, e4, e5, e6, e7,
- '\x0bc6', '\x0bc7', '\x0bc8', '\x0bc8', '\x0bca', '\x0bcb', '\x0bcc', '\x0bcc',
- // e8, e9, ea, eb, ec, ed, ee, ef,
- '\x0bcd', '\x0000', '\x002e', '\x0000', '\x0000', '\x0000', '\x0000', '\x0000',
- // f0, f1, f2, f3, f4, f5, f6, f7,
- '\x0000', '\x0030', '\x0be7', '\x0be8', '\x0be9', '\x0bea', '\x0beb', '\x0bec',
- // f8, f9, fa, fb, fc, fd, fe, ff
- '\x0bed', '\x0bee', '\x0bef', '\x0000', '\x0000', '\x0000', '\x0000', '\x0000'
- },
-
- // Alternate Unicode Char & Flags
- {
- // a0, a1, a2, a3, a4, a5, a6, a7,
- '\x0', '\x0', '\x0', '\x0', '\x0', '\x0', '\x0', '\x0',
- // a8, a9, aa, ab, ac, ad, ae, af,
- '\x0', '\x0', '\x0', '\x0', '\x0', '\x0', '\x0', '\x0',
- // b0, b1, b2, b3, b4, b5, b6, b7,
- '\x0', '\x0', '\x0', '\x0', '\x0', '\x0', '\x0', '\x0',
- // b8, b9, ba, bb, bc, bd, be, bf,
- '\x0', '\x0', '\x0', '\x0', '\x0', '\x0', '\x0', '\x0',
- // c0, c1, c2, c3, c4, c5, c6, c7,
- '\x0', '\x0', '\x0', '\x0', '\x0', '\x0', '\x0', '\x0',
- // c8, c9, ca, cb, cc, cd, ce, cf,
- '\x0', '\x0', '\x0', '\x0', '\x0', '\x0', '\x0', '\x0',
- // d0, d1, d2, d3, d4, d5, d6, d7,
- '\x0', '\x0', '\x0', '\x0', '\x0', '\x0', '\x0', '\x0',
- // d8, d9, da, db, dc, dd, de, df,
- '\x0', '\x0', '\x0', '\x0', '\x0', '\x0', '\x0', '\x0',
- // e0, e1, e2, e3, e4, e5, e6, e7,
- '\x0', '\x0', '\x0', '\x0', '\x0', '\x0', '\x0', '\x0',
- // e8, e9, ea, eb, ec, ed, ee, ef,
- '\x200C', '\x200D', '\x0', '\x0', '\x0', '\x0', '\x0', '\x0',
- // f0, f1, f2, f3, f4, f5, f6, f7,
- '\x0', '\x0', '\x0', '\x0', '\x0', '\x0', '\x0', '\x0',
- // f8, f9, fa, fb, fc, fd, fe, ff
- '\x0', '\x0', '\x0', '\x0', '\x0', '\x0', '\x0', '\x0'
- }
- },
-
- {
- ////////////////////////////////////////////////////////////////////////////
- //
- // Telugu Table 3', Code Page (5, '45', 57005)
- //
- ////////////////////////////////////////////////////////////////////////////
-
- // Default Unicode Char
- {
- // a0, a1, a2, a3, a4, a5, a6, a7,
- '\x0000', '\x0c01', '\x0c02', '\x0c03', '\x0c05', '\x0c06', '\x0c07', '\x0c08',
- // a8, a9, aa, ab, ac, ad, ae, af,
- '\x0c09', '\x0c0a', '\x0c0b', '\x0c0e', '\x0c0f', '\x0c10', '\x0c10', '\x0c12',
- // b0, b1, b2, b3, b4, b5, b6, b7,
- '\x0c13', '\x0c14', '\x0c14', '\x0c15', '\x0c16', '\x0c17', '\x0c18', '\x0c19',
- // b8, b9, ba, bb, bc, bd, be, bf,
- '\x0c1a', '\x0c1b', '\x0c1c', '\x0c1d', '\x0c1e', '\x0c1f', '\x0c20', '\x0c21',
- // c0, c1, c2, c3, c4, c5, c6, c7,
- '\x0c22', '\x0c23', '\x0c24', '\x0c25', '\x0c26', '\x0c27', '\x0c28', '\x0c28',
- // c8, c9, ca, cb, cc, cd, ce, cf,
- '\x0c2a', '\x0c2b', '\x0c2c', '\x0c2d', '\x0c2e', '\x0c2f', '\x0c2f', '\x0c30',
- // d0, d1, d2, d3, d4, d5, d6, d7,
- '\x0c31', '\x0c32', '\x0c33', '\x0c33', '\x0c35', '\x0c36', '\x0c37', '\x0c38',
- // d8, d9, da, db, dc, dd, de, df,
- '\x0c39', '\x0000', '\x0c3e', '\x0c3f', '\x0c40', '\x0c41', '\x0c42', '\x0c43',
- // e0, e1, e2, e3, e4, e5, e6, e7,
- '\x0c46', '\x0c47', '\x0c48', '\x0c48', '\x0c4a', '\x0c4b', '\x0c4c', '\x0c4c',
- // e8, e9, ea, eb, ec, ed, ee, ef,
- '\x0c4d', '\x0000', '\x002e', '\x0000', '\x0000', '\x0000', '\x0000', '\x0000',
- // f0, f1, f2, f3, f4, f5, f6, f7,
- '\x0000', '\x0c66', '\x0c67', '\x0c68', '\x0c69', '\x0c6a', '\x0c6b', '\x0c6c',
- // f8, f9, fa, fb, fc, fd, fe, ff
- '\x0c6d', '\x0c6e', '\x0c6f', '\x0000', '\x0000', '\x0000', '\x0000', '\x0000'
- },
-
- // Alternate Unicode Char & Flags
- {
- // a0, a1, a2, a3, a4, a5, a6, a7,
- '\x0', '\x0', '\x0', '\x0', '\x0', '\x0', '\x0c0c', '\x0c61',
- // a8, a9, aa, ab, ac, ad, ae, af,
- '\x0', '\x0', '\x0c60', '\x0', '\x0', '\x0', '\x0', '\x0',
- // b0, b1, b2, b3, b4, b5, b6, b7,
- '\x0', '\x0', '\x0', '\x0', '\x0', '\x0', '\x0', '\x0',
- // b8, b9, ba, bb, bc, bd, be, bf,
- '\x0', '\x0', '\x0', '\x0', '\x0', '\x0', '\x0', '\x0',
- // c0, c1, c2, c3, c4, c5, c6, c7,
- '\x0', '\x0', '\x0', '\x0', '\x0', '\x0', '\x0', '\x0',
- // c8, c9, ca, cb, cc, cd, ce, cf,
- '\x0', '\x0', '\x0', '\x0', '\x0', '\x0', '\x0', '\x0',
- // d0, d1, d2, d3, d4, d5, d6, d7,
- '\x0', '\x0', '\x0', '\x0', '\x0', '\x0', '\x0', '\x0',
- // d8, d9, da, db, dc, dd, de, df,
- '\x0', '\x0', '\x0', '\x0', '\x0', '\x0', '\x0', '\x0c44',
- // e0, e1, e2, e3, e4, e5, e6, e7,
- '\x0', '\x0', '\x0', '\x0', '\x0', '\x0', '\x0', '\x0',
- // e8, e9, ea, eb, ec, ed, ee, ef,
- '\x200C', '\x200D', '\x0', '\x0', '\x0', '\x0', '\x0', '\x0',
- // f0, f1, f2, f3, f4, f5, f6, f7,
- '\x0', '\x0', '\x0', '\x0', '\x0', '\x0', '\x0', '\x0',
- // f8, f9, fa, fb, fc, fd, fe, ff
- '\x0', '\x0', '\x0', '\x0', '\x0', '\x0', '\x0', '\x0'
- }
- },
-
- {
- ////////////////////////////////////////////////////////////////////////////
- //
- // Oriya Table 4', Code Page (7, '47', 57007)
- //
- ////////////////////////////////////////////////////////////////////////////
-
- // Default Unicode Char
- {
- // a0, a1, a2, a3, a4, a5, a6, a7,
- '\x0000', '\x0b01', '\x0b02', '\x0b03', '\x0b05', '\x0b06', '\x0b07', '\x0b08',
- // a8, a9, aa, ab, ac, ad, ae, af,
- '\x0b09', '\x0b0a', '\x0b0b', '\x0b0f', '\x0b0f', '\x0b10', '\x0b10', '\x0b10',
- // b0, b1, b2, b3, b4, b5, b6, b7,
- '\x0b13', '\x0b14', '\x0b14', '\x0b15', '\x0b16', '\x0b17', '\x0b18', '\x0b19',
- // b8, b9, ba, bb, bc, bd, be, bf,
- '\x0b1a', '\x0b1b', '\x0b1c', '\x0b1d', '\x0b1e', '\x0b1f', '\x0b20', '\x0b21',
- // c0, c1, c2, c3, c4, c5, c6, c7,
- '\x0b22', '\x0b23', '\x0b24', '\x0b25', '\x0b26', '\x0b27', '\x0b28', '\x0b28',
- // c8, c9, ca, cb, cc, cd, ce, cf,
- '\x0b2a', '\x0b2b', '\x0b2c', '\x0b2d', '\x0b2e', '\x0b2f', '\x0b5f', '\x0b30',
- // d0, d1, d2, d3, d4, d5, d6, d7,
- '\x0b30', '\x0b32', '\x0b33', '\x0b33', '\x0b2c', '\x0b36', '\x0b37', '\x0b38',
- // d8, d9, da, db, dc, dd, de, df,
- '\x0b39', '\x0000', '\x0b3e', '\x0b3f', '\x0b40', '\x0b41', '\x0b42', '\x0b43',
- // e0, e1, e2, e3, e4, e5, e6, e7,
- '\x0b47', '\x0b47', '\x0b48', '\x0b48', '\x0b4b', '\x0b4b', '\x0b4c', '\x0b4c',
- // e8, e9, ea, eb, ec, ed, ee, ef,
- '\x0b4d', '\x0b3c', '\x002e', '\x0000', '\x0000', '\x0000', '\x0000', '\x0000',
- // f0, f1, f2, f3, f4, f5, f6, f7,
- '\x0000', '\x0b66', '\x0b67', '\x0b68', '\x0b69', '\x0b6a', '\x0b6b', '\x0b6c',
- // f8, f9, fa, fb, fc, fd, fe, ff
- '\x0b6d', '\x0b6e', '\x0b6f', '\x0000', '\x0000', '\x0000', '\x0000', '\x0000'
- },
-
- // Alternate Unicode Char & Flags
- {
- // a0, a1, a2, a3, a4, a5, a6, a7,
- '\x0', '\x0', '\x0', '\x0', '\x0', '\x0', '\x0c0c', '\x0c61',
- // a8, a9, aa, ab, ac, ad, ae, af,
- '\x0', '\x0', '\x0c60', '\x0', '\x0', '\x0', '\x0', '\x0',
- // b0, b1, b2, b3, b4, b5, b6, b7,
- '\x0', '\x0', '\x0', '\x0', '\x0', '\x0', '\x0', '\x0',
- // b8, b9, ba, bb, bc, bd, be, bf,
- '\x0', '\x0', '\x0', '\x0', '\x0', '\x0', '\x0', '\x0b5c',
- // c0, c1, c2, c3, c4, c5, c6, c7,
- '\x0b5d', '\x0', '\x0', '\x0', '\x0', '\x0', '\x0', '\x0',
- // c8, c9, ca, cb, cc, cd, ce, cf,
- '\x0', '\x0', '\x0', '\x0', '\x0', '\x0', '\x0', '\x0',
- // d0, d1, d2, d3, d4, d5, d6, d7,
- '\x0', '\x0', '\x0', '\x0', '\x0', '\x0', '\x0', '\x0',
- // d8, d9, da, db, dc, dd, de, df,
- '\x0', '\x0', '\x0', '\x0', '\x0', '\x0', '\x0', '\x0c44',
- // e0, e1, e2, e3, e4, e5, e6, e7,
- '\x0', '\x0', '\x0', '\x0', '\x0', '\x0', '\x0', '\x0',
- // e8, e9, ea, eb, ec, ed, ee, ef,
- '\x200C', '\x200D', '\x0b3d', '\x0', '\x0', '\x0', '\x0', '\x0',
- // f0, f1, f2, f3, f4, f5, f6, f7,
- '\x0', '\x0', '\x0', '\x0', '\x0', '\x0', '\x0', '\x0',
- // f8, f9, fa, fb, fc, fd, fe, ff
- '\x0', '\x0', '\x0', '\x0', '\x0', '\x0', '\x0', '\x0'
- }
- },
-
- {
- ////////////////////////////////////////////////////////////////////////////
- //
- // Kannada Table 5', Code Page (8, '48', 57008)
- //
- ////////////////////////////////////////////////////////////////////////////
-
- // Default Unicode Char
- {
- // a0, a1, a2, a3, a4, a5, a6, a7,
- '\x0000', '\x0000', '\x0c82', '\x0c83', '\x0c85', '\x0c86', '\x0c87', '\x0c88',
- // a8, a9, aa, ab, ac, ad, ae, af,
- '\x0c89', '\x0c8a', '\x0c8b', '\x0c8e', '\x0c8f', '\x0c90', '\x0c90', '\x0c92',
- // b0, b1, b2, b3, b4, b5, b6, b7,
- '\x0c93', '\x0c94', '\x0c94', '\x0c95', '\x0c96', '\x0c97', '\x0c98', '\x0c99',
- // b8, b9, ba, bb, bc, bd, be, bf,
- '\x0c9a', '\x0c9b', '\x0c9c', '\x0c9d', '\x0c9e', '\x0c9f', '\x0ca0', '\x0ca1',
- // c0, c1, c2, c3, c4, c5, c6, c7,
- '\x0ca2', '\x0ca3', '\x0ca4', '\x0ca5', '\x0ca6', '\x0ca7', '\x0ca8', '\x0ca8',
- // c8, c9, ca, cb, cc, cd, ce, cf,
- '\x0caa', '\x0cab', '\x0cac', '\x0cad', '\x0cae', '\x0caf', '\x0caf', '\x0cb0',
- // d0, d1, d2, d3, d4, d5, d6, d7,
- '\x0cb1', '\x0cb2', '\x0cb3', '\x0cb3', '\x0cb5', '\x0cb6', '\x0cb7', '\x0cb8',
- // d8, d9, da, db, dc, dd, de, df,
- '\x0cb9', '\x0000', '\x0cbe', '\x0cbf', '\x0cc0', '\x0cc1', '\x0cc2', '\x0cc3',
- // e0, e1, e2, e3, e4, e5, e6, e7,
- '\x0cc6', '\x0cc7', '\x0cc8', '\x0cc8', '\x0cca', '\x0ccb', '\x0ccc', '\x0ccc',
- // e8, e9, ea, eb, ec, ed, ee, ef,
- '\x0ccd', '\x0000', '\x002e', '\x0000', '\x0000', '\x0000', '\x0000', '\x0000',
- // f0, f1, f2, f3, f4, f5, f6, f7,
- '\x0000', '\x0ce6', '\x0ce7', '\x0ce8', '\x0ce9', '\x0cea', '\x0ceb', '\x0cec',
- // f8, f9, fa, fb, fc, fd, fe, ff
- '\x0ced', '\x0cee', '\x0cef', '\x0000', '\x0000', '\x0000', '\x0000', '\x0000'
- },
-
- // Alternate Unicode Char & Flags
- {
- // a0, a1, a2, a3, a4, a5, a6, a7,
- '\x0', '\x0', '\x0', '\x0', '\x0', '\x0', '\x0c8c', '\x0ce1',
- // a8, a9, aa, ab, ac, ad, ae, af,
- '\x0', '\x0', '\x0ce0', '\x0', '\x0', '\x0', '\x0', '\x0',
- // b0, b1, b2, b3, b4, b5, b6, b7,
- '\x0', '\x0', '\x0', '\x0', '\x0', '\x0', '\x0', '\x0',
- // b8, b9, ba, bb, bc, bd, be, bf,
- '\x0', '\x0', '\x0', '\x0', '\x0', '\x0', '\x0', '\x0',
- // c0, c1, c2, c3, c4, c5, c6, c7,
- '\x0', '\x0', '\x0', '\x0', '\x0', '\x0', '\x0', '\x0',
- // c8, c9, ca, cb, cc, cd, ce, cf,
- '\x0', '\x0cde', '\x0', '\x0', '\x0', '\x0', '\x0', '\x0',
- // d0, d1, d2, d3, d4, d5, d6, d7,
- '\x0', '\x0', '\x0', '\x0', '\x0', '\x0', '\x0', '\x0',
- // d8, d9, da, db, dc, dd, de, df,
- '\x0', '\x0', '\x0', '\x0', '\x0', '\x0', '\x0', '\x0cc4',
- // e0, e1, e2, e3, e4, e5, e6, e7,
- '\x0', '\x0', '\x0', '\x0', '\x0', '\x0', '\x0', '\x0',
- // e8, e9, ea, eb, ec, ed, ee, ef,
- '\x200C', '\x200D', '\x0', '\x0', '\x0', '\x0', '\x0', '\x0',
- // f0, f1, f2, f3, f4, f5, f6, f7,
- '\x0', '\x0', '\x0', '\x0', '\x0', '\x0', '\x0', '\x0',
- // f8, f9, fa, fb, fc, fd, fe, ff
- '\x0', '\x0', '\x0', '\x0', '\x0', '\x0', '\x0', '\x0'
- }
- },
-
- {
- ////////////////////////////////////////////////////////////////////////////
- //
- // Malayalam Table 6', Code Page (9, '49', 57009)
- //
- ////////////////////////////////////////////////////////////////////////////
-
- // Default Unicode Char
- {
- // a0, a1, a2, a3, a4, a5, a6, a7,
- '\x0000', '\x0000', '\x0d02', '\x0d03', '\x0d05', '\x0d06', '\x0d07', '\x0d08',
- // a8, a9, aa, ab, ac, ad, ae, af,
- '\x0d09', '\x0d0a', '\x0d0b', '\x0d0e', '\x0d0f', '\x0d10', '\x0d10', '\x0d12',
- // b0, b1, b2, b3, b4, b5, b6, b7,
- '\x0d13', '\x0d14', '\x0d14', '\x0d15', '\x0d16', '\x0d17', '\x0d18', '\x0d19',
- // b8, b9, ba, bb, bc, bd, be, bf,
- '\x0d1a', '\x0d1b', '\x0d1c', '\x0d1d', '\x0d1e', '\x0d1f', '\x0d20', '\x0d21',
- // c0, c1, c2, c3, c4, c5, c6, c7,
- '\x0d22', '\x0d23', '\x0d24', '\x0d25', '\x0d26', '\x0d27', '\x0d28', '\x0d28',
- // c8, c9, ca, cb, cc, cd, ce, cf,
- '\x0d2a', '\x0d2b', '\x0d2c', '\x0d2d', '\x0d2e', '\x0d2f', '\x0d2f', '\x0d30',
- // d0, d1, d2, d3, d4, d5, d6, d7,
- '\x0d31', '\x0d32', '\x0d33', '\x0d34', '\x0d35', '\x0d36', '\x0d37', '\x0d38',
- // d8, d9, da, db, dc, dd, de, df,
- '\x0d39', '\x0000', '\x0d3e', '\x0d3f', '\x0d40', '\x0d41', '\x0d42', '\x0d43',
- // e0, e1, e2, e3, e4, e5, e6, e7,
- '\x0d46', '\x0d47', '\x0d48', '\x0d48', '\x0d4a', '\x0d4b', '\x0d4c', '\x0d4c',
- // e8, e9, ea, eb, ec, ed, ee, ef,
- '\x0d4d', '\x0000', '\x002e', '\x0000', '\x0000', '\x0000', '\x0000', '\x0000',
- // f0, f1, f2, f3, f4, f5, f6, f7,
- '\x0000', '\x0d66', '\x0d67', '\x0d68', '\x0d69', '\x0d6a', '\x0d6b', '\x0d6c',
- // f8, f9, fa, fb, fc, fd, fe, ff
- '\x0d6d', '\x0d6e', '\x0d6f', '\x0000', '\x0000', '\x0000', '\x0000', '\x0000'
- },
-
- // Alternate Unicode Char & Flags
- {
- // a0, a1, a2, a3, a4, a5, a6, a7,
- '\x0', '\x0', '\x0', '\x0', '\x0', '\x0', '\x0d0c', '\x0d61',
- // a8, a9, aa, ab, ac, ad, ae, af,
- '\x0', '\x0', '\x0d60', '\x0', '\x0', '\x0', '\x0', '\x0',
- // b0, b1, b2, b3, b4, b5, b6, b7,
- '\x0', '\x0', '\x0', '\x0', '\x0', '\x0', '\x0', '\x0',
- // b8, b9, ba, bb, bc, bd, be, bf,
- '\x0', '\x0', '\x0', '\x0', '\x0', '\x0', '\x0', '\x0',
- // c0, c1, c2, c3, c4, c5, c6, c7,
- '\x0', '\x0', '\x0', '\x0', '\x0', '\x0', '\x0', '\x0',
- // c8, c9, ca, cb, cc, cd, ce, cf,
- '\x0', '\x0', '\x0', '\x0', '\x0', '\x0', '\x0', '\x0',
- // d0, d1, d2, d3, d4, d5, d6, d7,
- '\x0', '\x0', '\x0', '\x0', '\x0', '\x0', '\x0', '\x0',
- // d8, d9, da, db, dc, dd, de, df,
- '\x0', '\x0', '\x0', '\x0', '\x0', '\x0', '\x0', '\x0',
- // e0, e1, e2, e3, e4, e5, e6, e7,
- '\x0', '\x0', '\x0', '\x0', '\x0', '\x0', '\x0', '\x0',
- // e8, e9, ea, eb, ec, ed, ee, ef,
- '\x200C', '\x200D', '\x0', '\x0', '\x0', '\x0', '\x0', '\x0',
- // f0, f1, f2, f3, f4, f5, f6, f7,
- '\x0', '\x0', '\x0', '\x0', '\x0', '\x0', '\x0', '\x0',
- // f8, f9, fa, fb, fc, fd, fe, ff
- '\x0', '\x0', '\x0', '\x0', '\x0', '\x0', '\x0', '\x0'
- }
- },
-
- {
- ////////////////////////////////////////////////////////////////////////////
- //
- // Gujarati Table 7', Code Page (10', '4a', 57010)
- //
- ////////////////////////////////////////////////////////////////////////////
-
- // Default Unicode Char
- {
- // a0, a1, a2, a3, a4, a5, a6, a7,
- '\x0000', '\x0a81', '\x0a82', '\x0a83', '\x0a85', '\x0a86', '\x0a87', '\x0a88',
- // a8, a9, aa, ab, ac, ad, ae, af,
- '\x0a89', '\x0a8a', '\x0a8b', '\x0a8f', '\x0a8f', '\x0a90', '\x0a8d', '\x0a8d',
- // b0, b1, b2, b3, b4, b5, b6, b7,
- '\x0a93', '\x0a94', '\x0a91', '\x0a95', '\x0a96', '\x0a97', '\x0a98', '\x0a99',
- // b8, b9, ba, bb, bc, bd, be, bf,
- '\x0a9a', '\x0a9b', '\x0a9c', '\x0a9d', '\x0a9e', '\x0a9f', '\x0aa0', '\x0aa1',
- // c0, c1, c2, c3, c4, c5, c6, c7,
- '\x0aa2', '\x0aa3', '\x0aa4', '\x0aa5', '\x0aa6', '\x0aa7', '\x0aa8', '\x0aa8',
- // c8, c9, ca, cb, cc, cd, ce, cf,
- '\x0aaa', '\x0aab', '\x0aac', '\x0aad', '\x0aae', '\x0aaf', '\x0aaf', '\x0ab0',
- // d0, d1, d2, d3, d4, d5, d6, d7,
- '\x0ab0', '\x0ab2', '\x0ab3', '\x0ab3', '\x0ab5', '\x0ab6', '\x0ab7', '\x0ab8',
- // d8, d9, da, db, dc, dd, de, df,
- '\x0ab9', '\x0000', '\x0abe', '\x0abf', '\x0ac0', '\x0ac1', '\x0ac2', '\x0ac3',
- // e0, e1, e2, e3, e4, e5, e6, e7,
- '\x0ac7', '\x0ac7', '\x0ac8', '\x0ac5', '\x0acb', '\x0acb', '\x0acc', '\x0ac9',
- // e8, e9, ea, eb, ec, ed, ee, ef,
- '\x0acd', '\x0abc', '\x002e', '\x0000', '\x0000', '\x0000', '\x0000', '\x0000',
- // f0, f1, f2, f3, f4, f5, f6, f7,
- '\x0000', '\x0ae6', '\x0ae7', '\x0ae8', '\x0ae9', '\x0aea', '\x0aeb', '\x0aec',
- // f8, f9, fa, fb, fc, fd, fe, ff
- '\x0aed', '\x0aee', '\x0aef', '\x0000', '\x0000', '\x0000', '\x0000', '\x0000'
- },
-
- // Alternate Unicode Char & Flags
- {
- // a0, a1, a2, a3, a4, a5, a6, a7,
- '\x0', '\x0ad0', '\x0', '\x0', '\x0', '\x0', '\x0', '\x0',
- // a8, a9, aa, ab, ac, ad, ae, af,
- '\x0', '\x0', '\x0ae0', '\x0', '\x0', '\x0', '\x0', '\x0',
- // b0, b1, b2, b3, b4, b5, b6, b7,
- '\x0', '\x0', '\x0', '\x0', '\x0', '\x0', '\x0', '\x0',
- // b8, b9, ba, bb, bc, bd, be, bf,
- '\x0', '\x0', '\x0', '\x0', '\x0', '\x0', '\x0', '\x0',
- // c0, c1, c2, c3, c4, c5, c6, c7,
- '\x0', '\x0', '\x0', '\x0', '\x0', '\x0', '\x0', '\x0',
- // c8, c9, ca, cb, cc, cd, ce, cf,
- '\x0', '\x0', '\x0', '\x0', '\x0', '\x0', '\x0', '\x0',
- // d0, d1, d2, d3, d4, d5, d6, d7,
- '\x0', '\x0', '\x0', '\x0', '\x0', '\x0', '\x0', '\x0',
- // d8, d9, da, db, dc, dd, de, df,
- '\x0', '\x0', '\x0', '\x0', '\x0', '\x0', '\x0', '\x0ac4',
- // e0, e1, e2, e3, e4, e5, e6, e7,
- '\x0', '\x0', '\x0', '\x0', '\x0', '\x0', '\x0', '\x0',
- // e8, e9, ea, eb, ec, ed, ee, ef,
- '\x200C', '\x200D', '\x0abd', '\x0', '\x0', '\x0', '\x0', '\x0',
- // f0, f1, f2, f3, f4, f5, f6, f7,
- '\x0', '\x0', '\x0', '\x0', '\x0', '\x0', '\x0', '\x0',
- // f8, f9, fa, fb, fc, fd, fe, ff
- '\x0', '\x0', '\x0', '\x0', '\x0', '\x0', '\x0', '\x0'
- }
- },
-
- {
- ////////////////////////////////////////////////////////////////////////////
- //
- // Punjabi (Gurmukhi) Table 8', Code Page (11', '4b', 57011)
- //
- ////////////////////////////////////////////////////////////////////////////
-
- // Default Unicode Char
- {
- // a0, a1, a2, a3, a4, a5, a6, a7,
- '\x0000', '\x0000', '\x0a02', '\x0000', '\x0a05', '\x0a06', '\x0a07', '\x0a08',
- // a8, a9, aa, ab, ac, ad, ae, af,
- '\x0a09', '\x0a0a', '\x0000', '\x0a0f', '\x0a0f', '\x0a10', '\x0a10', '\x0a10',
- // b0, b1, b2, b3, b4, b5, b6, b7,
- '\x0a13', '\x0a14', '\x0a14', '\x0a15', '\x0a16', '\x0a17', '\x0a18', '\x0a19',
- // b8, b9, ba, bb, bc, bd, be, bf,
- '\x0a1a', '\x0a1b', '\x0a1c', '\x0a1d', '\x0a1e', '\x0a1f', '\x0a20', '\x0a21',
- // c0, c1, c2, c3, c4, c5, c6, c7,
- '\x0a22', '\x0a23', '\x0a24', '\x0a25', '\x0a26', '\x0a27', '\x0a28', '\x0a28',
- // c8, c9, ca, cb, cc, cd, ce, cf,
- '\x0a2a', '\x0a2b', '\x0a2c', '\x0a2d', '\x0a2e', '\x0a2f', '\x0a2f', '\x0a30',
- // d0, d1, d2, d3, d4, d5, d6, d7,
- '\x0a30', '\x0a32', '\x0a33', '\x0a33', '\x0a35', '\x0a36', '\x0a36', '\x0a38',
- // d8, d9, da, db, dc, dd, de, df,
- '\x0a39', '\x0000', '\x0a3e', '\x0a3f', '\x0a40', '\x0a41', '\x0a42', '\x0000',
- // e0, e1, e2, e3, e4, e5, e6, e7,
- '\x0a47', '\x0a47', '\x0a48', '\x0a48', '\x0a4b', '\x0a4b', '\x0a4c', '\x0a4c',
- // e8, e9, ea, eb, ec, ed, ee, ef,
- '\x0a4d', '\x0a3c', '\x002e', '\x0000', '\x0000', '\x0000', '\x0000', '\x0000',
- // f0, f1, f2, f3, f4, f5, f6, f7,
- '\x0000', '\x0a66', '\x0a67', '\x0a68', '\x0a69', '\x0a6a', '\x0a6b', '\x0a6c',
- // f8, f9, fa, fb, fc, fd, fe, ff
- '\x0a6d', '\x0a6e', '\x0a6f', '\x0000', '\x0000', '\x0000', '\x0000', '\x0000'
- },
-
- // Alternate Unicode Char & Flags
- {
- // a0, a1, a2, a3, a4, a5, a6, a7,
- '\x0', '\x0', '\x0', '\x0', '\x0', '\x0', '\x0', '\x0',
- // a8, a9, aa, ab, ac, ad, ae, af,
- '\x0', '\x0', '\x0', '\x0', '\x0', '\x0', '\x0', '\x0',
- // b0, b1, b2, b3, b4, b5, b6, b7,
- '\x0', '\x0', '\x0', '\x0', '\x0a59', '\x0a5a', '\x0', '\x0',
- // b8, b9, ba, bb, bc, bd, be, bf,
- '\x0', '\x0', '\x0a5b', '\x0', '\x0', '\x0', '\x0', '\x0',
- // c0, c1, c2, c3, c4, c5, c6, c7,
- '\x0a5c', '\x0', '\x0', '\x0', '\x0', '\x0', '\x0', '\x0',
- // c8, c9, ca, cb, cc, cd, ce, cf,
- '\x0', '\x0a5e', '\x0', '\x0', '\x0', '\x0', '\x0', '\x0',
- // d0, d1, d2, d3, d4, d5, d6, d7,
- '\x0', '\x0', '\x0', '\x0', '\x0', '\x0', '\x0', '\x0',
- // d8, d9, da, db, dc, dd, de, df,
- '\x0', '\x0', '\x0', '\x0', '\x0', '\x0', '\x0', '\x0',
- // e0, e1, e2, e3, e4, e5, e6, e7,
- '\x0', '\x0', '\x0', '\x0', '\x0', '\x0', '\x0', '\x0',
- // e8, e9, ea, eb, ec, ed, ee, ef,
- '\x200C', '\x200D', '\x0', '\x0', '\x0', '\x0', '\x0', '\x0',
- // f0, f1, f2, f3, f4, f5, f6, f7,
- '\x0', '\x0', '\x0', '\x0', '\x0', '\x0', '\x0', '\x0',
- // f8, f9, fa, fb, fc, fd, fe, ff
- '\x0', '\x0', '\x0', '\x0', '\x0', '\x0', '\x0', '\x0'
- }
- }
- };
- }
-
-}
diff --git a/src/mscorlib/src/System/Text/ISO2022Encoding.cs b/src/mscorlib/src/System/Text/ISO2022Encoding.cs
deleted file mode 100644
index fca579fe56..0000000000
--- a/src/mscorlib/src/System/Text/ISO2022Encoding.cs
+++ /dev/null
@@ -1,1983 +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.
-
-
-//
-//
-// Notes:
-//
-// IsAlwaysNormalized ???
-// Regarding Normalization for ISO-2022-JP (50220, 50221, 50222), its the same rules as EUCJP
-// Forms KC & KD are precluded because of things like halfwidth Katakana that has compatibility mappings
-// Form D is precluded because of 0x00a8, which changes to space + dierises.
-//
-// Note: I think that IsAlwaysNormalized should probably return true for form C for Japanese 20932 based CPs.
-//
-// For ISO-2022-KR
-// Never normalized, C & D (& therefore KC & KD) are precluded because of Hangul syllables and combined characters.
-//
-// IsAlwaysNormalized ???
-// Regarding Normalization for ISO-2022-CN (50227, 50229) & HZ-GB2312 (52936) I think is similar to the Japanese case.
-// Forms KC & KD are precluded because of things like halfwidth Katakana that has compatibility mappings
-// Form D is precluded because of 0x00a8, which changes to space + dierises.
-//
-// Note: I think that IsAlwaysNormalized should probably return true for form C for Chinese 20936 based CPs.
-//
-#if FEATURE_CODEPAGES_FILE // requires BaseCodePageEncooding
-namespace System.Text
-{
- using System.Globalization;
- using System.Diagnostics;
- using System.Diagnostics.Contracts;
- using System.Text;
- using System.Runtime.InteropServices;
- using System;
- using System.Security;
- using System.Runtime.CompilerServices;
- using System.Runtime.Serialization;
-
-
- /*=================================ISO2022Encoding============================
- **
- ** This is used to support ISO 2022 encodings that use shift/escape sequences.
- **
- ==============================================================================*/
-
- [Serializable]
- internal class ISO2022Encoding : DBCSCodePageEncoding
- {
- const byte SHIFT_OUT = (byte)0x0E;
- const byte SHIFT_IN = (byte)0x0F;
- const byte ESCAPE = 0x1B;
- const byte LEADBYTE_HALFWIDTH = 0x10;
-
- // 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.
- internal ISO2022Encoding(int codePage) : base(codePage, tableBaseCodePages[codePage % 10])
- {
- this.m_bUseMlangTypeForSerialization = true;
- }
-
- // Constructor called by serialization.
- // Note: We use the base GetObjectData however
- internal ISO2022Encoding(SerializationInfo info, StreamingContext context) : base(info, context)
- {
- // Actually this can't ever get called, CodePageEncoding is our proxy
- Debug.Assert(false, "Didn't expect to make it to DBCSCodePageEncoding serialization constructor");
- throw new ArgumentException(Environment.GetResourceString("Arg_ExecutionEngineException"));
- }
-
- static int[] tableBaseCodePages =
- {
- 932, // 50220 ISO-2022-JP, No halfwidth Katakana, convert to full width
- 932, // 50221 ISO-2022-JP, Use escape sequence for half width Katakana
- 932, // 50222 ISO-2022-JP, Use shift-in/shift-out for half width Katakana
- 0,
- 0,
- 949, // 50225 ISO-2022-KR, Korean
- 936, // 52936 HZ-GB2312, 936 might be better source
- 0, //20936, // 50227 ISO-2022-CN, Note: This is just the same as CP 936 in Everett.
- 0,
- // 50229 is currently unsupported, CP 20000 is currently not built in .nlp file
- 0, //20000, // 50229 ISO-2022-CN, ModeCNS11643_1
- 0, //20000, // 50229 ISO-2022-CN, ModeCNS11643_2
- 0 // ModeASCII
- };
-
- internal enum ISO2022Modes
- {
- ModeHalfwidthKatakana = 0,
- ModeJIS0208 = 1,
- ModeKR = 5,
- ModeHZ = 6,
- ModeGB2312 = 7,
- ModeCNS11643_1 = 9,
- ModeCNS11643_2 = 10,
- ModeASCII = 11,
-
- ModeIncompleteEscape = -1,
- ModeInvalidEscape = -2,
- ModeNOOP = -3
- }
-
- protected unsafe override String GetMemorySectionName()
- {
- int iUseCodePage = this.bFlagDataTable ? dataTableCodePage : CodePage;
-
- String strFormat;
-
- switch (this.CodePage)
- {
- case 50220:
- case 50221:
- case 50222:
- strFormat = "CodePage_{0}_{1}_{2}_{3}_{4}_ISO2022JP";
- break;
- case 50225:
- strFormat = "CodePage_{0}_{1}_{2}_{3}_{4}_ISO2022KR";
- break;
- case 52936:
- strFormat = "CodePage_{0}_{1}_{2}_{3}_{4}_HZ";
- break;
- default:
- Debug.Assert(false, "[ISO2022Encoding.GetMemorySectionName] Don't expect to get here for code page " + this.CodePage);
- strFormat = "CodePage_{0}_{1}_{2}_{3}_{4}";
- break;
- }
-
- String strName = String.Format(CultureInfo.InvariantCulture, strFormat,
- iUseCodePage, this.pCodePage->VersionMajor, this.pCodePage->VersionMinor,
- this.pCodePage->VersionRevision, this.pCodePage->VersionBuild);
-
- return strName;
- }
-
- // Clean up characters for ISO2022 code pages, etc.
- // ISO2022 (50220, 50221, 50222)
- // GB-HZ (52936)
- protected override bool CleanUpBytes(ref int bytes)
- {
- switch (this.CodePage)
- {
- // 932 based code pages
- case 50220:
- case 50221:
- case 50222:
- {
- if (bytes >= 0x100)
- {
- // map extended char (0xfa40-0xfc4b) to a special range
- // (ported from mlang)
- if (bytes >= 0xfa40 && bytes <= 0xfc4b)
- {
- if ( bytes >= 0xfa40 && bytes <= 0xfa5b )
- {
- if ( bytes <= 0xfa49 )
- bytes = bytes - 0x0b51 ;
- else if ( bytes >= 0xfa4a && bytes <= 0xfa53 )
- bytes = bytes - 0x072f6 ;
- else if ( bytes >= 0xfa54 && bytes <= 0xfa57 )
- bytes = bytes - 0x0b5b ;
- else if ( bytes == 0xfa58 )
- bytes = 0x878a ;
- else if ( bytes == 0xfa59 )
- bytes = 0x8782 ;
- else if ( bytes == 0xfa5a )
- bytes = 0x8784 ;
- else if ( bytes == 0xfa5b )
- bytes = 0x879a ;
- }
- else if ( bytes >= 0xfa5c && bytes <= 0xfc4b )
- {
- byte tc = unchecked((byte)bytes);
- if ( tc < 0x5c )
- bytes = bytes - 0x0d5f;
- else if ( tc >= 0x80 && tc <= 0x9B )
- bytes = bytes - 0x0d1d;
- else
- bytes = bytes - 0x0d1c;
- }
- }
-
- // Convert 932 code page to 20932 like code page range
- // (also ported from mlang)
- byte bLead = unchecked((byte)(bytes >> 8));
- byte bTrail = unchecked((byte)bytes);
-
- bLead -= ((bLead > (byte)0x9f) ? (byte)0xb1 : (byte)0x71);
- bLead = (byte)((bLead << 1) + 1);
- if (bTrail > (byte)0x9e)
- {
- bTrail -= (byte)0x7e;
- bLead++;
- }
- else
- {
- if (bTrail > (byte)0x7e)
- bTrail--;
- bTrail -= (byte)0x1f;
- }
-
- bytes = ((int)bLead) << 8 | (int)bTrail;
-
- // Don't step out of our allocated lead byte area.
- // All DBCS lead and trail bytes should be >= 0x21 and <= 0x7e
- // This is commented out because Everett/Mlang had illegal PUA
- // mappings to ISO2022 code pages that we're maintaining.
-// if ((bytes & 0xFF00) < 0x2100 || (bytes & 0xFF00) > 0x7e00 ||
- // (bytes & 0xFF) < 0x21 || (bytes & 0xFF) > 0x7e)
- // return false;
- }
- else
- {
- // Adjust 1/2 Katakana
- if (bytes >= 0xa1 && bytes <= 0xdf)
- bytes += (LEADBYTE_HALFWIDTH << 8) - 0x80;
-
- // 0x81-0x9f and 0xe0-0xfc CP 932
- // 0x8e and 0xa1-0xfe CP 20932 (we don't use 8e though)
- // b0-df is 1/2 Katakana
- if (bytes >= 0x81 &&
- (bytes <= 0x9f ||
- (bytes >= 0xe0 && bytes <= 0xfc)))
- {
- // Don't do lead bytes, we use escape sequences instead.
- return false;
- }
- }
- break;
- }
- case 50225:
- {
- // For 50225 since we don't rely on lead byte marks, return false and don't add them,
- // esp. since we're only a 7 bit code page.
- if (bytes >= 0x80 && bytes <= 0xff)
- return false;
-
- // Ignore characters out of range (a1-7f)
- if (bytes >= 0x100 &&
- ((bytes & 0xff) < 0xa1 || (bytes & 0xff) == 0xff ||
- (bytes & 0xff00) < 0xa100 || (bytes & 0xff00) == 0xff00))
- return false;
-
- // May as well get them into our 7 bit range
- bytes &= 0x7f7f;
-
- break;
- }
- case 52936:
- {
- // Since we don't rely on lead byte marks for 52936, get rid of them so we
- // don't end up with extra wierd fffe mappings.
- if (bytes >= 0x81 && bytes <= 0xfe)
- return false;
-
- break;
- }
- }
-
- return true;
- }
-
- // GetByteCount
- 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
- 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);
- }
-
- 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
- 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.
- Debug.Assert(encoderFallback != null, "[ISO2022Encoding.GetBytes]Attempting to use null encoder fallback");
-
- // Fix our encoder
- ISO2022Encoder encoder = (ISO2022Encoder)baseEncoder;
-
- // Our return value
- int iCount = 0;
-
- switch(CodePage)
- {
- case 50220:
- case 50221:
- case 50222:
- iCount = GetBytesCP5022xJP( chars, charCount, bytes, byteCount, encoder );
- break;
- case 50225:
- iCount = GetBytesCP50225KR( chars, charCount, bytes, byteCount, encoder );
- break;
-// Everett had 50227 the same as 936
-/* case 50227:
- iCount = GetBytesCP50227CN( chars, charCount, bytes, byteCount, encoder );
- break;
-*/
- case 52936:
- iCount = GetBytesCP52936( chars, charCount, bytes, byteCount, encoder );
- break;
- }
-
- return iCount;
- }
-
- // This is internal and called by something else,
- internal override unsafe int GetCharCount(byte* bytes, int count, DecoderNLS baseDecoder)
- {
- // Just assert, we're called internally so these should be safe, checked already
- 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);
- }
-
- 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
- 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;
- int iCount = 0;
-
- switch (CodePage)
- {
- case 50220:
- case 50221:
- case 50222:
- iCount = GetCharsCP5022xJP( bytes, byteCount, chars, charCount, decoder);
- break;
- case 50225:
- iCount = GetCharsCP50225KR( bytes, byteCount, chars, charCount, decoder);
- break;
- // Currently 50227 is the same as 936
-// case 50227:
- // iCount = GetCharsCP50227CN( bytes, byteCount, chars, charCount, decoder);
- // break;
- case 52936:
- iCount = GetCharsCP52936( bytes, byteCount, chars, charCount, decoder);
- break;
- default:
- Debug.Assert(false, "[ISO2022Encoding.GetChars] had unexpected code page");
- break;
- }
-
- return iCount;
- }
-
- // ISO 2022 Code pages for JP.
- // 50220 - No halfwidth Katakana, convert to full width
- // 50221 - Use escape sequence for half width Katakana
- // 50222 - Use shift-in/shift-out for half width Katakana
- //
- // These are the JIS code pages, superset of ISO-2022 / ISO-2022-JP-1
- // 0E Shift Out (following bytes are Katakana)
- // 0F Shift In (back to "normal" behavior)
- // 21-7E Byte ranges (1 or 2 bytes)
- // <ESC> $ @ To Double Byte 0208 Mode (actually older code page, but subset of 0208)
- // <ESC> $ B To Double Byte 0208 Mode (duplicate)
- // <ESC> $ ( D To Double Byte 0212 Mode (previously we misinterpreted this)
- // <ESC> $ I To half width Katakana
- // <ESC> ( J To JIS-Roman
- // <ESC> ( H To JIS-Roman (swedish character set)
- // <ESC> ( B To ASCII
- // <ESC> & @ Alternate lead in to <ESC> $ B so just ignore it.
- //
- // So in Katakana mode we add 0x8e as a lead byte and use CP 20932 to convert it
- // In ASCII mode we just spit out the single byte.
- // In Roman mode we should change 0x5c (\) -> Yen sign and 0x7e (~) to Overline, however
- // we didn't in mLang, otherwise roman is like ASCII.
- // In 0208 double byte mode we have to |= with 0x8080 and use CP 20932 to convert it.
- // In 0212 double byte mode we have to |= with 0x8000 and use CP 20932 to convert it.
- //
- // Note that JIS Shift In/Shift Out is different than the other ISO2022 encodings. For JIS
- // Shift out always shifts to half-width Katakana. Chinese encodings use designator sequences
- // instead of escape sequences and shift out to the designated sequence or back in to ASCII.
- //
- // When decoding JIS 0208, MLang used a '*' (0x2a) character in JIS 0208 mode to map the trailing byte
- // to halfwidth katakana. I found no description of that behavior, however that block of 0208 is
- // undefined, so we maintain that behavior when decoding. We will never generate characters using
- // that technique, but the decoder will process them.
- //
- private unsafe int GetBytesCP5022xJP(char* chars, int charCount,
- byte* bytes, int byteCount, ISO2022Encoder encoder)
- {
- // prepare our helpers
- Encoding.EncodingByteBuffer buffer = new Encoding.EncodingByteBuffer(
- this, encoder, bytes, byteCount, chars, charCount);
-
- // Get our mode
- ISO2022Modes currentMode = ISO2022Modes.ModeASCII; // Mode
- ISO2022Modes shiftInMode = ISO2022Modes.ModeASCII; // Mode that shift in will go back to (only used by CP 50222)
-
- // Check our encoder
- if (encoder != null)
- {
- char charLeftOver = encoder.charLeftOver;
-
- currentMode = encoder.currentMode;
- shiftInMode = encoder.shiftInOutMode;
-
- // We may have a left over character from last time, try and process it.
- if (charLeftOver > 0)
- {
- 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);
- }
- }
-
- while (buffer.MoreData)
- {
- // Get our char
- char ch = buffer.GetNextChar();
-
- // Get our bytes
- ushort iBytes = mapUnicodeToBytes[ch];
-
- StartConvert:
- // Check for halfwidth bytes
- byte bLeadByte = (byte)(iBytes >> 8);
- byte bTrailByte = (byte)(iBytes & 0xff);
-
- if (bLeadByte == LEADBYTE_HALFWIDTH)
- {
- // Its Halfwidth Katakana
- if (CodePage == 50220)
- {
- // CodePage 50220 doesn't use halfwidth Katakana, convert to fullwidth
- // See if its out of range, fallback if so, throws if recursive fallback
- if (bTrailByte < 0x21 || bTrailByte >= 0x21 + HalfToFullWidthKanaTable.Length)
- {
- buffer.Fallback(ch);
- continue;
- }
-
- // Get the full width katakana char to use.
- iBytes = unchecked((ushort)(HalfToFullWidthKanaTable[bTrailByte - 0x21] & 0x7F7F));
-
- // May have to do all sorts of fun stuff for mode, go back to start convert
- goto StartConvert;
- }
-
- // Can use halfwidth Katakana, make sure we're in right mode
-
- // Make sure we're in right mode
- if (currentMode != ISO2022Modes.ModeHalfwidthKatakana)
- {
- // 50222 or 50221, either shift in/out or escape to get to Katakana mode
- if (CodePage == 50222)
- {
- // Shift Out
- if (!buffer.AddByte(SHIFT_OUT))
- break; // convert out of space, stop
-
- // Don't change modes until after AddByte in case it fails for convert
- // We get to shift out to Katakana, make sure we'll go back to the right mode
- // (This ends up always being ASCII)
- shiftInMode = currentMode;
- currentMode = ISO2022Modes.ModeHalfwidthKatakana;
- }
- else
- {
- // 50221 does halfwidth katakana by escape sequence
- Debug.Assert(CodePage == 50221, "[ISO2022Encoding.GetBytesCP5022xJP]Expected Code Page 50221");
-
- // Add our escape sequence
- if (!buffer.AddByte(ESCAPE, unchecked((byte)'('), unchecked((byte)'I')))
- break; // convert out of space, stop
-
- currentMode = ISO2022Modes.ModeHalfwidthKatakana;
- }
- }
-
- // We know we're in Katakana mode now, so add it.
- // Go ahead and add the Katakana byte. Our table tail bytes are 0x80 too big.
- if (!buffer.AddByte(unchecked((byte)(bTrailByte & 0x7F))))
- break; // convert out of space, stop
-
- // Done with this one
- continue;
- }
- else if (bLeadByte != 0)
- {
- //
- // It's a double byte character.
- //
-
- // If we're CP 50222 we may have to shift in from Katakana mode first
- if (CodePage == 50222 && currentMode == ISO2022Modes.ModeHalfwidthKatakana)
- {
- // Shift In
- if (!buffer.AddByte(SHIFT_IN))
- break; // convert out of space, stop
-
- // Need to shift in from katakana. (Still might not be right, but won't be shifted out anyway)
- currentMode = shiftInMode;
- }
-
- // Make sure we're in the right mode (JIS 0208 or JIS 0212)
- // Note: Right now we don't use JIS 0212. Also this table'd be wrong
-
- // Its JIS extension 0208
- if (currentMode != ISO2022Modes.ModeJIS0208)
- {
- // Escape sequence, we can fail after this, mode will be correct for convert
- if (!buffer.AddByte(ESCAPE, unchecked((byte)'$'), unchecked((byte)'B')))
- break; // Convert out of space, stop
-
- currentMode = ISO2022Modes.ModeJIS0208;
- }
-
- // Add our double bytes
- if (!buffer.AddByte(unchecked((byte)(bLeadByte)), unchecked((byte)(bTrailByte))))
- break; // Convert out of space, stop
- continue;
- }
- else if (iBytes != 0 || ch == 0)
- {
- // Single byte Char
- // If we're CP 50222 we may have to shift in from Katakana mode first
- if (CodePage == 50222 && currentMode == ISO2022Modes.ModeHalfwidthKatakana)
- {
- // Shift IN
- if (!buffer.AddByte(SHIFT_IN))
- break; // convert ran out of room
-
- // Need to shift in from katakana. (Still might not be right, but won't be shifted out anyway)
- currentMode = shiftInMode;
- }
-
- // Its a single byte character, switch to ASCII if we have to
- if (currentMode != ISO2022Modes.ModeASCII)
- {
- if (!buffer.AddByte(ESCAPE,unchecked((byte)'('), unchecked((byte)'B')))
- break; // convert ran out of room
-
- currentMode = ISO2022Modes.ModeASCII;
- }
-
- // Add the ASCII char
- if (!buffer.AddByte(bTrailByte))
- break; // convert had no room left
- continue;
- }
-
- // Its unknown, do fallback, throws if recursive (knows because we called InternalGetNextChar)
- buffer.Fallback(ch);
- }
-
- // Switch back to ASCII if MustFlush or no encoder
- if (currentMode != ISO2022Modes.ModeASCII &&
- (encoder == null || encoder.MustFlush))
- {
- // If we're CP 50222 we may have to shift in from Katakana mode first
- if (CodePage == 50222 && currentMode == ISO2022Modes.ModeHalfwidthKatakana)
- {
- // Shift IN, only shift mode if necessary.
- if (buffer.AddByte(SHIFT_IN))
- // Need to shift in from katakana. (Still might not be right, but won't be shifted out anyway)
- currentMode = shiftInMode;
- else
- // If not successful, convert will maintain state for next time, also
- // AddByte will have decremented our char count, however we need it to remain the same
- buffer.GetNextChar();
- }
-
- // switch back to ASCII to finish neatly
- if (currentMode != ISO2022Modes.ModeASCII &&
- (CodePage != 50222 || currentMode != ISO2022Modes.ModeHalfwidthKatakana))
- {
- // only shift if it was successful
- if (buffer.AddByte(ESCAPE, unchecked((byte)'('), unchecked((byte)'B')))
- currentMode = ISO2022Modes.ModeASCII;
- else
- // If not successful, convert will maintain state for next time, also
- // AddByte will have decremented our char count, however we need it to remain the same
- buffer.GetNextChar();
- }
- }
-
- // Remember our encoder state
- if (bytes != null && encoder != null)
- {
- // This is ASCII if we had to flush
- encoder.currentMode = currentMode;
- encoder.shiftInOutMode = shiftInMode;
-
- if (!buffer.fallbackBuffer.bUsedEncoder)
- {
- encoder.charLeftOver = (char)0;
- }
-
- encoder.m_charsUsed = buffer.CharsUsed;
- }
-
- // Return our length
- return buffer.Count;
- }
-
- // ISO 2022 Code pages for Korean - CP 50225
- //
- // CP 50225 has Shift In/Shift Out codes, and a single designator sequence that is supposed
- // to appear once in the file, at the beginning of a line, before any multibyte code points.
- // So we stick the designator at the beginning of the output.
- //
- // These are the KR code page codes for ISO-2022-KR
- // 0E Shift Out (following bytes are double byte)
- // 0F Shift In (back to ASCII behavior)
- // 21-7E Byte ranges (1 or 2 bytes)
- // <ESC> $)C Double byte ISO-2022-KR designator
- //
- // Note that this encoding is a little different than other encodings. The <esc>$)C sequence
- // should only appear once per file. (Actually I saw another spec/rfc that said at the beginning
- // of each line, but it shouldn't really matter.)
- //
- // During decoding Mlang accepted ' ', '\t, and '\n' as their respective characters, even if
- // it was in double byte mode. We maintain that behavior, although I couldn't find a reference or
- // reason for that behavior. We never generate data using that shortcut.
- //
- // 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.
- //
- private unsafe int GetBytesCP50225KR(char* chars, int charCount,
- byte* bytes, int byteCount, ISO2022Encoder encoder)
- {
- // prepare our helpers
- Encoding.EncodingByteBuffer buffer = new Encoding.EncodingByteBuffer(
- this, encoder, bytes, byteCount, chars, charCount);
-
- // Get our mode
- ISO2022Modes currentMode = ISO2022Modes.ModeASCII; // Mode
- ISO2022Modes shiftOutMode = ISO2022Modes.ModeASCII; // ModeKR if already stamped lead bytes
-
- // Check our encoder
- if (encoder != null)
- {
- // May have leftover stuff
- char charLeftOver = encoder.charLeftOver;
- currentMode = encoder.currentMode;
- shiftOutMode = encoder.shiftInOutMode;
-
- // We may have a l left over character from last time, try and process it.
- if (charLeftOver > 0)
- {
- 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);
- }
- }
-
- while (buffer.MoreData)
- {
- // Get our data
- char ch = buffer.GetNextChar();
-
- // Get our bytes
- ushort iBytes = mapUnicodeToBytes[ch];
-
- // Check for double byte bytes
- byte bLeadByte = (byte)(iBytes >> 8);
- byte bTrailByte = (byte)(iBytes & 0xff);
-
- if (bLeadByte != 0)
- {
- //
- // It's a double byte character.
- //
-
- // If we haven't done our Korean designator, then do so, if we have any input
- if (shiftOutMode != ISO2022Modes.ModeKR)
- {
- // Add our code page designator sequence
- if (!buffer.AddByte(ESCAPE, unchecked((byte)'$'), unchecked((byte)')'), unchecked((byte)'C')))
- break; // No room during convert.
-
- shiftOutMode = ISO2022Modes.ModeKR;
- }
-
- // May have to switch to ModeKR first
- if (currentMode != ISO2022Modes.ModeKR)
- {
- if (!buffer.AddByte(SHIFT_OUT))
- break; // No convert room
-
- currentMode = ISO2022Modes.ModeKR;
- }
-
- // Add the bytes
- if (!buffer.AddByte(bLeadByte, bTrailByte))
- break; // no convert room
- continue;
- }
- else if (iBytes != 0 || ch == 0)
- {
- // Its a single byte character, switch to ASCII if we have to
- if (currentMode != ISO2022Modes.ModeASCII)
- {
- if (!buffer.AddByte(SHIFT_IN))
- break;
-
- currentMode = ISO2022Modes.ModeASCII;
- }
-
- // Add the ASCII char
- if (!buffer.AddByte(bTrailByte))
- break;
- continue;
- }
-
- // Its unknown, do fallback, throws if recursive (knows because we called InternalGetNextChar)
- buffer.Fallback(ch);
- }
-
- // Switch back to ASCII if MustFlush or no encoder
- if (currentMode != ISO2022Modes.ModeASCII &&
- (encoder == null || encoder.MustFlush))
- {
- // Get back to ASCII to be safe. Only do it if it success.
- if (buffer.AddByte(SHIFT_IN))
- currentMode = ISO2022Modes.ModeASCII;
- else
- // If not successful, convert will maintain state for next time, also
- // AddByte will have decremented our char count, however we need it to remain the same
- buffer.GetNextChar();
- }
-
- // Remember our encoder state
- if (bytes != null && encoder != null)
- {
- // If we didn't use the encoder, then there's no chars left over
- if (!buffer.fallbackBuffer.bUsedEncoder)
- {
- encoder.charLeftOver = (char)0;
- }
-
- // This is ASCII if we had to flush
- encoder.currentMode = currentMode;
-
- // We don't use shift out mode, but if we've flushed we need to reset it so it doesn't
- // get output again.
- if (!encoder.MustFlush || encoder.charLeftOver != (char)0)
- {
- // We should be not flushing or converting
- Debug.Assert(!encoder.MustFlush || !encoder.m_throwOnOverflow,
- "[ISO2022Encoding.GetBytesCP50225KR]Expected no left over data or not flushing or not converting");
- encoder.shiftInOutMode = shiftOutMode;
- }
- else
- encoder.shiftInOutMode = ISO2022Modes.ModeASCII;
-
- encoder.m_charsUsed = buffer.CharsUsed;
- }
-
- // Return our length
- return buffer.Count;
- }
-
- // CP52936 is HZ Encoding
- // HZ Encoding has 4 shift sequences:
- // ~~ '~' (\u7e)
- // ~} shift into 1 byte mode,
- // ~{ shift into 2 byte GB 2312-80
- // ~<NL> Maintain 2 byte mode across new lines (ignore both ~ and <NL> characters)
- // (This is for mailers that restrict to 70 or 80 or whatever character lines)
- //
- // According to comment in mlang, lead & trail byte ranges are described in RFC 1843
- // RFC 1843 => valid HZ code range: leading byte 0x21 - 0x77, 2nd byte 0x21 - 0x7e
- // Our 936 code points are or'd with 0x8080, so lead byte 0xa1 - 0xf7, trail byte 0xa1 - 0xfe
- //
- // This encoding is designed for transmission by e-mail and news. No bytes should have high bit set.
- // (all bytes <= 0x7f)
- private unsafe int GetBytesCP52936(char* chars, int charCount,
- byte* bytes, int byteCount, ISO2022Encoder encoder)
- {
- // prepare our helpers
- Encoding.EncodingByteBuffer buffer = new Encoding.EncodingByteBuffer(
- this, encoder, bytes, byteCount, chars, charCount);
-
- // Mode
- ISO2022Modes currentMode = ISO2022Modes.ModeASCII;
-
- // Check our encoder
- if (encoder != null)
- {
- char charLeftOver = encoder.charLeftOver;
- currentMode = encoder.currentMode;
-
- // We may have a left over character from last time, try and process it.
- if (charLeftOver > 0)
- {
- 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);
- }
- }
-
- while (buffer.MoreData)
- {
- // Get our char
- char ch = buffer.GetNextChar();
-
- // Get our bytes
- ushort sChar = mapUnicodeToBytes[ch];
- if (sChar == 0 && ch != 0)
- {
- // Wasn't a legal byte sequence, its a surrogate or fallback
- // Throws if recursive (knows because we called InternalGetNextChar)
- buffer.Fallback(ch);
-
- // Done with our char, now process fallback
- continue;
- }
-
- // Check for halfwidth bytes
- byte bLeadByte = (byte)(sChar >> 8);
- byte bTrailByte = (byte)(sChar & 0xff);
-
- // If its a double byte, it has to fit in the lead byte 0xa1 - 0xf7, trail byte 0xa1 - 0xfe range
- // (including the 0x8080 that our codepage or's to the value)
- if ((bLeadByte != 0 &&
- (bLeadByte < 0xa1 || bLeadByte > 0xf7 || bTrailByte < 0xa1 || bTrailByte > 0xfe)) ||
- (bLeadByte == 0 && bTrailByte > 0x80 && bTrailByte != 0xff))
- {
- // Illegal character, in 936 code page, but not in HZ subset, get fallback for it
- buffer.Fallback(ch);
- continue;
- }
-
- // sChar is now either ASCII or has an 0x8080 mask
- if (bLeadByte != 0)
- {
- // Its a double byte mode
- if (currentMode != ISO2022Modes.ModeHZ)
- {
- // Need to add the double byte mode marker
- if (!buffer.AddByte((byte)'~', (byte)'{', 2))
- break; // Stop if no buffer space in convert
-
- currentMode = ISO2022Modes.ModeHZ;
- }
-
- // Go ahead and add the 2 bytes
- if (!buffer.AddByte(unchecked((byte)(bLeadByte & 0x7f)), unchecked((byte)(bTrailByte & 0x7f))))
- break; // Stop if no buffer space in convert
- }
- else
- {
- // Its supposed to be ASCII
- if (currentMode != ISO2022Modes.ModeASCII)
- {
- // Need to add the ASCII mode marker
- // Will have 1 more byte (or 2 if ~)
- if (!buffer.AddByte((byte)'~', (byte)'}', bTrailByte == '~' ? 2:1))
- break;
-
- currentMode = ISO2022Modes.ModeASCII;
- }
-
- // If its a '~' we'll need an extra one
- if (bTrailByte == '~')
- {
- // Need to add the extra ~
- if (!buffer.AddByte((byte)'~', 1))
- break;
- }
-
- // Need to add the character
- if (!buffer.AddByte(bTrailByte))
- break;
- }
- }
-
- // Add ASCII shift out if we're at end of decoder
- if (currentMode != ISO2022Modes.ModeASCII &&
- (encoder == null || encoder.MustFlush))
- {
- // Need to add the ASCII mode marker
- // Only turn off other mode if this works
- if (buffer.AddByte((byte)'~',(byte)'}'))
- currentMode = ISO2022Modes.ModeASCII;
- else
- // If not successful, convert will maintain state for next time, also
- // AddByte will have decremented our char count, however we need it to remain the same
- buffer.GetNextChar();
- }
-
- // Need to remember our mode
- if (encoder != null && bytes != null)
- {
- // This is ASCII if we had to flush
- encoder.currentMode = currentMode;
-
- if (!buffer.fallbackBuffer.bUsedEncoder)
- {
- encoder.charLeftOver = (char)0;
- }
-
- encoder.m_charsUsed = buffer.CharsUsed;
- }
-
- // Return our length
- return buffer.Count;
- }
-
- private unsafe int GetCharsCP5022xJP(byte* bytes, int byteCount,
- char* chars, int charCount, ISO2022Decoder decoder)
- {
- // Get our info.
- Encoding.EncodingCharBuffer buffer = new Encoding.EncodingCharBuffer(
- this, decoder, chars, charCount, bytes, byteCount);
-
- // No mode information yet
- ISO2022Modes currentMode = ISO2022Modes.ModeASCII; // Our current Mode
- ISO2022Modes shiftInMode = ISO2022Modes.ModeASCII; // Mode that we'll shift in to
- byte[] escapeBytes = new byte[4];
- int escapeCount = 0;
-
- if (decoder != null)
- {
- currentMode = decoder.currentMode;
- shiftInMode = decoder.shiftInOutMode;
-
- // See if we have leftover decoder buffer to use
- // Load our bytesLeftOver
- escapeCount = decoder.bytesLeftOverCount;
-
- // Don't want to mess up decoder if we're counting or throw an exception
- for (int i = 0; i < escapeCount; i++)
- escapeBytes[i] = decoder.bytesLeftOver[i];
- }
-
- // Do this until the end
- while (buffer.MoreData || escapeCount > 0)
- {
- byte ch;
-
- if (escapeCount > 0)
- {
- // Get more escape sequences if necessary
- if (escapeBytes[0] == ESCAPE)
- {
- // Stop if no more input
- if (!buffer.MoreData)
- {
- if (decoder != null && !decoder.MustFlush)
- break;
- }
- else
- {
- // Add it to the sequence we can check
- escapeBytes[escapeCount++] = buffer.GetNextByte();
-
- // We have an escape sequence
- ISO2022Modes modeReturn =
- CheckEscapeSequenceJP(escapeBytes, escapeCount);
-
- if (modeReturn != ISO2022Modes.ModeInvalidEscape)
- {
- if (modeReturn != ISO2022Modes.ModeIncompleteEscape)
- {
- // Processed escape correctly
- escapeCount = 0;
-
- // We're now this mode
- currentMode = shiftInMode = modeReturn;
- }
-
- // Either way, continue to get next escape or real byte
- continue;
- }
- }
-
- // If ModeInvalidEscape, or no input & must flush, then fall through to add escape.
- }
-
- // Read next escape byte and move them down one.
- ch = DecrementEscapeBytes(ref escapeBytes, ref escapeCount);
- }
- else
- {
- // Get our next byte
- ch = buffer.GetNextByte();
-
- if (ch == ESCAPE)
- {
- // We'll have an escape sequence, use it if we don't have one buffered already
- if (escapeCount == 0)
- {
- // Start this new escape sequence
- escapeBytes[0] = ch;
- escapeCount = 1;
- continue;
- }
-
- // Flush the previous escape sequence, then reuse this escape byte
- buffer.AdjustBytes(-1);
- }
- }
-
- if (ch == SHIFT_OUT)
- {
- shiftInMode = currentMode;
- currentMode = ISO2022Modes.ModeHalfwidthKatakana;
- continue;
- }
- else if (ch == SHIFT_IN)
- {
- currentMode = shiftInMode;
- continue;
- }
-
- // Get our full character
- ushort iBytes = ch;
- bool b2Bytes = false;
-
- if (currentMode == ISO2022Modes.ModeJIS0208)
- {
- //
- // To handle errors, we need to check:
- // 1. if trailbyte is there
- // 2. if code is valid
- //
- if (escapeCount > 0)
- {
- // Let another escape fall through
- if (escapeBytes[0] != ESCAPE)
- {
- // Move them down one & get the next data
- iBytes <<= 8;
- iBytes |= DecrementEscapeBytes(ref escapeBytes, ref escapeCount);
- b2Bytes = true;
- }
- }
- else if (buffer.MoreData)
- {
- iBytes <<= 8;
- iBytes |= buffer.GetNextByte();
- b2Bytes = true;
- }
- else
- {
- // Not enough input, use decoder if possible
- if (decoder == null || decoder.MustFlush)
- {
- // No decoder, do fallback for this byte
- buffer.Fallback(ch);
- break;
- }
-
- // Stick it in the decoder if we're not counting
- if (chars != null)
- {
- escapeBytes[0] = ch;
- escapeCount = 1;
- }
- break;
- }
-
- // MLang treated JIS 0208 '*' lead byte like a single halfwidth katakana
- // escape, so use 0x8e00 as katakana lead byte and keep same trail byte.
- // 0x2a lead byte range is normally unused in JIS 0208, so shouldn't have
- // any wierd compatibility issues.
- if ((b2Bytes == true) && ((iBytes & 0xff00) == 0x2a00))
- {
- iBytes = (ushort)(iBytes & 0xff);
- iBytes |= (LEADBYTE_HALFWIDTH << 8); // Put us in the halfwidth katakana range
- }
- }
- else if (iBytes >= 0xA1 && iBytes <= 0xDF)
- {
- // Everett accidentally mapped Katakana like shift-jis (932),
- // even though this is a 7 bit code page. We keep that mapping
- iBytes |= (LEADBYTE_HALFWIDTH << 8); // Map to halfwidth katakana range
- iBytes &= 0xff7f; // remove extra 0x80
- }
- else if (currentMode == ISO2022Modes.ModeHalfwidthKatakana )
- {
- // Add 0x10 lead byte that our encoding expects for Katakana:
- iBytes |= (LEADBYTE_HALFWIDTH << 8);
- }
-
- // We have an iBytes to try to convert.
- char c = mapBytesToUnicode[iBytes];
-
- // See if it was unknown
- if (c == UNKNOWN_CHAR_FLAG && iBytes != 0)
- {
- // Have to do fallback
- if (b2Bytes)
- {
- if (!buffer.Fallback((byte)(iBytes >> 8), (byte)iBytes))
- break;
- }
- else
- {
- if (!buffer.Fallback(ch))
- break;
- }
- }
- else
- {
- // If we were JIS 0208, then we consumed an extra byte
- if (!buffer.AddChar(c, b2Bytes ? 2:1))
- break;
- }
- }
-
- // Make sure our decoder state matches our mode, if not counting
- if (chars != null && decoder != null)
- {
- // Remember it if we don't flush
- if (!decoder.MustFlush || escapeCount != 0)
- {
- // Either not flushing or had state (from convert)
- Debug.Assert(!decoder.MustFlush || !decoder.m_throwOnOverflow,
- "[ISO2022Encoding.GetCharsCP5022xJP]Expected no state or not converting or not flushing");
-
- decoder.currentMode = currentMode;
- decoder.shiftInOutMode = shiftInMode;
-
- // Remember escape buffer
- decoder.bytesLeftOverCount = escapeCount;
- decoder.bytesLeftOver = escapeBytes;
- }
- else
- {
- // We flush, clear buffer
- decoder.currentMode = ISO2022Modes.ModeASCII;
- decoder.shiftInOutMode = ISO2022Modes.ModeASCII;
- decoder.bytesLeftOverCount = 0;
- // Slightly different if counting/not counting
- }
-
- decoder.m_bytesUsed = buffer.BytesUsed;
- }
-
- // Return # of characters we found
- return buffer.Count;
- }
-
- // We know we have an escape sequence, so check it starting with the byte after the escape
- private ISO2022Modes CheckEscapeSequenceJP( byte[] bytes, int escapeCount )
- {
- // Have an escape sequence
- if (bytes[0] != ESCAPE)
- return ISO2022Modes.ModeInvalidEscape;
-
- if (escapeCount < 3)
- return ISO2022Modes.ModeIncompleteEscape;
-
- if (bytes[1] == '(')
- {
- if (bytes[2] == 'B') // <esc>(B
- {
- return ISO2022Modes.ModeASCII;
- }
- else if (bytes[2] == 'H') // <esc>(H
- {
- // Actually this is supposed to be Swedish
- // We treat it like ASCII though.
- return ISO2022Modes.ModeASCII;
- }
- else if (bytes[2] == 'J') // <esc>(J
- {
- // Actually this is supposed to be Roman
- // 2 characters are different, but historically we treat it as ascii
- return ISO2022Modes.ModeASCII;
- }
- else if (bytes[2] == 'I') // <esc>(I
- {
- return ISO2022Modes.ModeHalfwidthKatakana;
- }
- }
- else if (bytes[1] == '$')
- {
- if (bytes[2] == '@' || // <esc>$@
- bytes[2] == 'B') // <esc>$B
- {
- return ISO2022Modes.ModeJIS0208;
- }
- else
- {
- // Looking for <esc>$(D
- if (escapeCount < 4)
- return ISO2022Modes.ModeIncompleteEscape;
-
- if (bytes[2] == '(' && bytes[3] == 'D') // <esc>$(D
- {
- // Mlang treated 0208 like 0212 even though that's wrong
- return ISO2022Modes.ModeJIS0208;
- }
- }
- }
- else if (bytes[1] == '&')
- {
- if (bytes[2] == '@') // <esc>&@
- {
- // Ignore ESC & @ (prefix to <esc>$B)
- return ISO2022Modes.ModeNOOP;
- }
- }
-
- // If we get here we fell through and have an invalid/unknown escape sequence
- return ISO2022Modes.ModeInvalidEscape;
- }
-
- private byte DecrementEscapeBytes(ref byte[] bytes, ref int count)
- {
- Debug.Assert(count > 0, "[ISO2022Encoding.DecrementEscapeBytes]count > 0");
-
- // Decrement our count
- count--;
-
- // Remember the first one
- byte returnValue = bytes[0];
-
- // Move them down one.
- for (int i = 0; i < count; i++)
- {
- bytes[i] = bytes[i+1];
- }
-
- // Clear out the last byte
- bytes[count] = 0;
-
- // Return the old 1st byte
- return returnValue;
- }
-
- // Note that in DBCS mode mlang passed through ' ', '\t' and '\n' as SBCS characters
- // probably to allow mailer formatting without too much extra work.
- private unsafe int GetCharsCP50225KR(byte* bytes, int byteCount,
- char* chars, int charCount, ISO2022Decoder decoder)
- {
- // Get our info.
- Encoding.EncodingCharBuffer buffer = new Encoding.EncodingCharBuffer(
- this, decoder, chars, charCount, bytes, byteCount);
-
- // No mode information yet
- ISO2022Modes currentMode = ISO2022Modes.ModeASCII; // Our current Mode
-
- byte[] escapeBytes = new byte[4];
- int escapeCount = 0;
-
- if (decoder != null)
- {
- currentMode = decoder.currentMode;
-
- // See if we have leftover decoder buffer to use
- // Load our bytesLeftOver
- escapeCount = decoder.bytesLeftOverCount;
-
- // Don't want to mess up decoder if we're counting or throw an exception
- for (int i = 0; i < escapeCount; i++)
- escapeBytes[i] = decoder.bytesLeftOver[i];
- }
-
- // Do this until the end, just do '?' replacement because we don't have fallbacks for decodings.
- while (buffer.MoreData || escapeCount > 0)
- {
- byte ch;
-
- if (escapeCount > 0)
- {
- // Get more escape sequences if necessary
- if (escapeBytes[0] == ESCAPE)
- {
- // Stop if no more input
- if (!buffer.MoreData)
- {
- if (decoder != null && !decoder.MustFlush)
- break;
- }
- else
- {
- // Add it to the sequence we can check
- escapeBytes[escapeCount++] = buffer.GetNextByte();
-
- // We have an escape sequence
- ISO2022Modes modeReturn =
- CheckEscapeSequenceKR(escapeBytes, escapeCount);
-
- if (modeReturn != ISO2022Modes.ModeInvalidEscape)
- {
- if (modeReturn != ISO2022Modes.ModeIncompleteEscape)
- {
- // Processed escape correctly, no effect (we know about KR mode)
- escapeCount = 0;
- }
-
- // Either way, continue to get next escape or real byte
- continue;
- }
- }
-
- // If ModeInvalidEscape, or no input & must flush, then fall through to add escape.
- }
-
- // Still have something left over in escape buffer
- // Get it and move them down one
- ch = DecrementEscapeBytes(ref escapeBytes, ref escapeCount);
- }
- else
- {
- // Get our next byte
- ch = buffer.GetNextByte();
-
- if (ch == ESCAPE)
- {
- // We'll have an escape sequence, use it if we don't have one buffered already
- if (escapeCount == 0)
- {
- // Start this new escape sequence
- escapeBytes[0] = ch;
- escapeCount = 1;
- continue;
- }
-
- // Flush previous escape sequence, then reuse this escape byte
- buffer.AdjustBytes(-1);
- }
- }
-
- if (ch == SHIFT_OUT)
- {
- currentMode = ISO2022Modes.ModeKR;
- continue;
- }
- else if (ch == SHIFT_IN)
- {
- currentMode = ISO2022Modes.ModeASCII;
- continue;
- }
-
- // Get our full character
- ushort iBytes = ch;
- bool b2Bytes = false;
-
- // MLANG was passing through ' ', '\t' and '\n', so we do so as well, but I don't see that in the RFC.
- if (currentMode == ISO2022Modes.ModeKR && ch != ' ' && ch != '\t' && ch != '\n')
- {
- //
- // To handle errors, we need to check:
- // 1. if trailbyte is there
- // 2. if code is valid
- //
- if (escapeCount > 0)
- {
- // Let another escape fall through
- if (escapeBytes[0] != ESCAPE)
- {
- // Move them down one & get the next data
- iBytes <<= 8;
- iBytes |= DecrementEscapeBytes(ref escapeBytes, ref escapeCount);
- b2Bytes = true;
- }
- }
- else if (buffer.MoreData)
- {
- iBytes <<= 8;
- iBytes |= buffer.GetNextByte();
- b2Bytes = true;
- }
- else
- {
- // Not enough input, use decoder if possible
- if (decoder == null || decoder.MustFlush)
- {
- // No decoder, do fallback for lonely 1st byte
- buffer.Fallback(ch);
- break;
- }
-
- // Stick it in the decoder if we're not counting
- if (chars != null)
- {
- escapeBytes[0] = ch;
- escapeCount = 1;
- }
- break;
- }
- }
-
- // We have a iBytes to try to convert.
- char c = mapBytesToUnicode[iBytes];
-
- // See if it was unknown
- if (c == UNKNOWN_CHAR_FLAG && iBytes != 0)
- {
- // Have to do fallback
- if (b2Bytes)
- {
- if (!buffer.Fallback((byte)(iBytes >> 8), (byte)iBytes))
- break;
- }
- else
- {
- if (!buffer.Fallback(ch))
- break;
- }
- }
- else
- {
- if (!buffer.AddChar(c, b2Bytes ? 2:1))
- break;
- }
- }
-
- // Make sure our decoder state matches our mode, if not counting
- if (chars != null && decoder != null)
- {
- // Remember it if we don't flush
- if (!decoder.MustFlush || escapeCount != 0)
- {
- // Either not flushing or had state (from convert)
- Debug.Assert(!decoder.MustFlush || !decoder.m_throwOnOverflow,
- "[ISO2022Encoding.GetCharsCP50225KR]Expected no state or not converting or not flushing");
-
- decoder.currentMode = currentMode;
-
- // Remember escape buffer
- decoder.bytesLeftOverCount = escapeCount;
- decoder.bytesLeftOver = escapeBytes;
- }
- else
- {
- // We flush, clear buffer
- decoder.currentMode = ISO2022Modes.ModeASCII;
- decoder.shiftInOutMode = ISO2022Modes.ModeASCII;
- decoder.bytesLeftOverCount = 0;
- }
-
- decoder.m_bytesUsed = buffer.BytesUsed;
- }
-
- // Return # of characters we found
- return buffer.Count;
- }
-
- // We know we have an escape sequence, so check it starting with the byte after the escape
- private ISO2022Modes CheckEscapeSequenceKR( byte[] bytes, int escapeCount )
- {
- // Have an escape sequence
- if (bytes[0] != ESCAPE)
- return ISO2022Modes.ModeInvalidEscape;
-
- if (escapeCount < 4)
- return ISO2022Modes.ModeIncompleteEscape;
-
- if (bytes[1] == '$' && bytes[2] == ')' && bytes[3] == 'C') // <esc>$)C
- return ISO2022Modes.ModeKR;
-
- // If we get here we fell through and have an invalid/unknown escape sequence
- return ISO2022Modes.ModeInvalidEscape;
- }
-
- // CP52936 is HZ Encoding
- // HZ Encoding has 4 shift sequences:
- // ~~ '~' (\u7e)
- // ~} shift into 1 byte mode,
- // ~{ shift into 2 byte GB 2312-80
- // ~<NL> Maintain 2 byte mode across new lines (ignore both ~ and <NL> characters)
- // (This is for mailers that restrict to 70 or 80 or whatever character lines)
- //
- // According to comment in mlang, lead & trail byte ranges are described in RFC 1843
- // RFC 1843 => valid HZ code range: leading byte 0x21 - 0x77, 2nd byte 0x21 - 0x7e
- // Our 936 code points are or'd with 0x8080, so lead byte 0xa1 - 0xf7, trail byte 0xa1 - 0xfe
- //
- // This encoding is designed for transmission by e-mail and news. No bytes should have high bit set.
- // (all bytes <= 0x7f)
- private unsafe int GetCharsCP52936(byte* bytes, int byteCount,
- char* chars, int charCount, ISO2022Decoder decoder)
- {
- 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(
- this, decoder, chars, charCount, bytes, byteCount);
-
- // No mode information yet
- ISO2022Modes currentMode = ISO2022Modes.ModeASCII;
- int byteLeftOver = -1;
- bool bUsedDecoder = false;
-
- if (decoder != null)
- {
- currentMode = decoder.currentMode;
- // See if we have leftover decoder buffer to use
- // Don't want to mess up decoder if we're counting or throw an exception
- if (decoder.bytesLeftOverCount != 0 )
- {
- // Load our bytesLeftOver
- byteLeftOver = decoder.bytesLeftOver[0];
- }
- }
-
- // Do this until the end, just do '?' replacement because we don't have fallbacks for decodings.
- while (buffer.MoreData || byteLeftOver >= 0)
- {
- byte ch;
-
- // May have a left over byte
- if (byteLeftOver >= 0)
- {
- ch = (byte)byteLeftOver;
- byteLeftOver = -1;
- }
- else
- {
- ch = buffer.GetNextByte();
- }
-
- // We're in escape mode
- if (ch == '~')
- {
- // Next char is type of switch
- if (!buffer.MoreData)
- {
- // We don't have anything left, it'll be in decoder or a ?
- // don't fail if we are allowing overflows
- if (decoder == null || decoder.MustFlush)
- {
- // We'll be a '?'
- buffer.Fallback(ch);
- // break if we fail & break if we don't (because !MoreData)
- // Add succeeded, continue
- break;
- }
-
- // Stick it in decoder
- if (decoder != null)
- decoder.ClearMustFlush();
-
- if (chars != null)
- {
- decoder.bytesLeftOverCount = 1;
- decoder.bytesLeftOver[0] = (byte)'~';
- bUsedDecoder = true;
- }
- break;
- }
-
- // What type is it?, get 2nd byte
- ch = buffer.GetNextByte();
-
- if (ch == '~' && currentMode == ISO2022Modes.ModeASCII)
- {
- // Its just a ~~ replacement for ~, add it
- if (!buffer.AddChar((char)ch, 2))
- // Add failed, break for converting
- break;
-
- // Add succeeded, continue
- continue;
- }
- else if (ch == '{')
- {
- // Switching to Double Byte mode
- currentMode = ISO2022Modes.ModeHZ;
- continue;
- }
- else if (ch == '}')
- {
- // Switching to ASCII mode
- currentMode = ISO2022Modes.ModeASCII;
- continue;
- }
- else if (ch == '\n')
- {
- // Ignore ~\n sequence
- continue;
- }
- else
- {
- // Unknown escape, back up and try the '~' as a "normal" byte or lead byte
- buffer.AdjustBytes(-1);
- ch = (byte)'~';
- }
- }
-
- // go ahead and add our data
- if (currentMode != ISO2022Modes.ModeASCII)
- {
- // Should be ModeHZ
- Debug.Assert(currentMode == ISO2022Modes.ModeHZ, "[ISO2022Encoding.GetCharsCP52936]Expected ModeHZ");
- char cm;
-
- // Everett allowed characters < 0x20 to be passed as if they were ASCII
- if (ch < 0x20)
- {
- // Emit it as ASCII
- goto STOREASCII;
- }
-
- // Its multibyte, should have another byte
- if (!buffer.MoreData)
- {
- // No bytes left
- // don't fail if we are allowing overflows
- if (decoder == null || decoder.MustFlush)
- {
- // Not enough bytes, fallback lead byte
- buffer.Fallback(ch);
-
- // Break if we fail & break because !MoreData
- break;
- }
-
- if (decoder != null)
- decoder.ClearMustFlush();
-
- // Stick it in decoder
- if (chars != null)
- {
- decoder.bytesLeftOverCount = 1;
- decoder.bytesLeftOver[0] = ch;
- bUsedDecoder = true;
- }
- break;
- }
-
- // Everett uses space as an escape character for single SBCS bytes
- byte ch2 = buffer.GetNextByte();
- ushort iBytes = (ushort)(ch << 8 | ch2);
-
- if (ch == ' ' && ch2 != 0)
- {
- // Get next char and treat it like ASCII (Everett treated space like an escape
- // allowing the next char to be just ascii)
- cm = (char)ch2;
- goto STOREMULTIBYTE;
- }
-
- // Bytes should be in range: lead byte 0x21-0x77, trail byte: 0x21 - 0x7e
- if ((ch < 0x21 || ch > 0x77 || ch2 < 0x21 || ch2 > 0x7e) &&
- // Everett allowed high bit mappings for same characters (but only if both bits set)
- (ch < 0xa1 || ch > 0xf7 || ch2 < 0xa1 || ch2 > 0xfe))
- {
- // For some reason Everett allowed XX20 to become unicode 3000... (ideo sp)
- if (ch2 == 0x20 && 0x21 <= ch && ch <= 0x7d)
- {
- iBytes = 0x2121;
- goto MULTIBYTE;
- }
-
- // Illegal char, use fallback. If lead byte is 0 have to do it special and do it first
- if (!buffer.Fallback((byte)(iBytes>>8), (byte)(iBytes)))
- break;
- continue;
- }
-
- MULTIBYTE:
- iBytes |= 0x8080;
- // Look up the multibyte char to stick it in our data
-
- // We have a iBytes to try to convert.
- cm = mapBytesToUnicode[iBytes];
-
- STOREMULTIBYTE:
-
- // See if it was unknown
- if (cm == UNKNOWN_CHAR_FLAG && iBytes != 0)
- {
- // Fall back the unknown stuff
- if (!buffer.Fallback((byte)(iBytes>>8), (byte)(iBytes)))
- break;
- continue;
- }
-
- if (!buffer.AddChar(cm, 2))
- break; // convert ran out of buffer, stop
- continue;
- }
-
- // Just ASCII
- // We allow some chars > 7f because everett did, so we have to look them up.
- STOREASCII:
- char c = mapBytesToUnicode[ch];
-
- // Check if it was unknown
- if ((c == UNKNOWN_CHAR_FLAG || c == 0) && (ch != 0))
- {
- // fallback the unkown bytes
- if (!buffer.Fallback((byte)ch))
- break;
- continue;
- }
-
- // Go ahead and add our ASCII character
- if (!buffer.AddChar(c))
- break; // convert ran out of buffer, stop
- }
-
- // Need to remember our state, IF we're not counting
- if (chars != null && decoder != null)
- {
- if (!bUsedDecoder)
- {
- // If we didn't use it, clear the byte left over
- decoder.bytesLeftOverCount = 0;
- }
-
- if (decoder.MustFlush && decoder.bytesLeftOverCount == 0)
- {
- decoder.currentMode = ISO2022Modes.ModeASCII;
- }
- else
- {
- // Either not flushing or had state (from convert)
- Debug.Assert(!decoder.MustFlush || !decoder.m_throwOnOverflow,
- "[ISO2022Encoding.GetCharsCP52936]Expected no state or not converting or not flushing");
-
- decoder.currentMode = currentMode;
- }
- decoder.m_bytesUsed = buffer.BytesUsed;
- }
-
- // Return # of characters we found
- return buffer.Count;
- }
-
- // Note: These all end up with 1/2 bytes of average byte count, so unless we're 1 we're always
- // charCount/2 bytes too big.
- public override int GetMaxByteCount(int charCount)
- {
- if (charCount < 0)
- throw new ArgumentOutOfRangeException(nameof(charCount),
- Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
- Contract.EndContractBlock();
-
- // Characters would be # of characters + 1 in case high surrogate is ? * max fallback
- long byteCount = (long)charCount + 1;
-
- if (EncoderFallback.MaxCharCount > 1)
- byteCount *= EncoderFallback.MaxCharCount;
-
- // Start with just generic DBCS values (sort of).
- int perChar = 2;
- int extraStart = 0;
- int extraEnd = 0;
-
- switch (CodePage)
- {
- case 50220:
- case 50221:
- // 2 bytes per char + 3 bytes switch to JIS 0208 or 1 byte + 3 bytes switch to 1 byte CP
- perChar = 5; // 5 max (4.5 average)
- extraEnd = 3; // 3 bytes to shift back to ASCII
- break;
- case 50222:
- // 2 bytes per char + 3 bytes switch to JIS 0208 or 1 byte + 3 bytes switch to 1 byte CP
- perChar = 5; // 5 max (4.5 average)
- extraEnd = 4; // 1 byte to shift from Katakana -> DBCS, 3 bytes to shift back to ASCII from DBCS
- break;
- case 50225:
- // 2 bytes per char + 1 byte SO, or 1 byte per char + 1 byte SI.
- perChar = 3; // 3 max, (2.5 average)
- extraStart = 4; // EUC-KR marker appears at beginning of file.
- extraEnd = 1; // 1 byte to shift back to ascii if necessary.
- break;
- case 52936:
- // 2 bytes per char + 2 byte shift, or 1 byte + 1 byte shift
- // Worst case: left over surrogate with no low surrogate is extra ?, could have to switch to ASCII, then could have HZ and flush to ASCII mode
- perChar = 4; // 4 max, (3.5 average if every other char is HZ/ASCII)
- extraEnd = 2; // 2 if we have to shift back to ASCII
- break;
- }
-
- // Return our surrogate and End plus perChar for each char.
- byteCount *= perChar;
- byteCount += extraStart + extraEnd;
-
- if (byteCount > 0x7fffffff)
- throw new ArgumentOutOfRangeException(nameof(charCount), Environment.GetResourceString("ArgumentOutOfRange_GetByteCountOverflow"));
-
- return (int)byteCount;
- }
-
- public override int GetMaxCharCount(int byteCount)
- {
- if (byteCount < 0)
- throw new ArgumentOutOfRangeException(nameof(byteCount),
- Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
- Contract.EndContractBlock();
-
- int perChar = 1;
- int extraDecoder = 1;
-
- switch (CodePage)
- {
- case 50220:
- case 50221:
- case 50222:
- case 50225:
- perChar = 1; // Worst case all ASCII
- extraDecoder = 3; // Could have left over 3 chars of 4 char escape sequence, that all become ?
- break;
- case 52936:
- perChar = 1; // Worst case all ASCII
- extraDecoder = 1; // sequences are 2 chars, so if next one is illegal, then previous 1 could be ?
- break;
- }
-
- // Figure out our length, perchar * char + whatever extra our decoder could do to us.
- long charCount = ((long)byteCount * perChar) + extraDecoder;
-
- // Just in case we have to fall back unknown ones.
- if (DecoderFallback.MaxCharCount > 1)
- charCount *= DecoderFallback.MaxCharCount;
-
- if (charCount > 0x7fffffff)
- throw new ArgumentOutOfRangeException(nameof(byteCount), Environment.GetResourceString("ArgumentOutOfRange_GetCharCountOverflow"));
-
- return (int)charCount;
- }
-
- public override Encoder GetEncoder()
- {
- return new ISO2022Encoder(this);
- }
-
- public override Decoder GetDecoder()
- {
- return new ISO2022Decoder(this);
- }
-
- [Serializable]
- internal class ISO2022Encoder : System.Text.EncoderNLS
- {
- internal ISO2022Modes currentMode;
- internal ISO2022Modes shiftInOutMode;
-
- internal ISO2022Encoder(EncodingNLS encoding) : base(encoding)
- {
- // base calls reset
- }
-
- public override void Reset()
- {
- // Reset
- currentMode = ISO2022Modes.ModeASCII;
- shiftInOutMode = ISO2022Modes.ModeASCII;
- charLeftOver = (char)0;
- if (m_fallbackBuffer != null)
- m_fallbackBuffer.Reset();
- }
-
- // Anything left in our encoder?
- internal override bool HasState
- {
- get
- {
- // Don't check shift-out mode, it may be ascii (JP) or not (KR)
- return (this.charLeftOver != (char)0 ||
- currentMode != ISO2022Modes.ModeASCII);
- }
- }
- }
-
- [Serializable]
- internal class ISO2022Decoder : System.Text.DecoderNLS
- {
- internal byte[] bytesLeftOver;
- internal int bytesLeftOverCount;
- internal ISO2022Modes currentMode;
- internal ISO2022Modes shiftInOutMode;
-
- internal ISO2022Decoder(EncodingNLS encoding) : base(encoding)
- {
- // base calls reset
- }
-
- public override void Reset()
- {
- // Reset
- bytesLeftOverCount = 0;
- bytesLeftOver = new byte[4];
- currentMode = ISO2022Modes.ModeASCII;
- shiftInOutMode = ISO2022Modes.ModeASCII;
- if (m_fallbackBuffer != null)
- m_fallbackBuffer.Reset();
- }
-
- // Anything left in our decoder?
- internal override bool HasState
- {
- get
- {
- // If have bytes left over or not shifted back to ASCII then have problem
- return (this.bytesLeftOverCount != 0 ||
- currentMode != ISO2022Modes.ModeASCII);
- }
- }
- }
-
- static ushort[] HalfToFullWidthKanaTable =
- {
- 0xa1a3, // 0x8ea1 : Halfwidth Ideographic Period
- 0xa1d6, // 0x8ea2 : Halfwidth Opening Corner Bracket
- 0xa1d7, // 0x8ea3 : Halfwidth Closing Corner Bracket
- 0xa1a2, // 0x8ea4 : Halfwidth Ideographic Comma
- 0xa1a6, // 0x8ea5 : Halfwidth Katakana Middle Dot
- 0xa5f2, // 0x8ea6 : Halfwidth Katakana Wo
- 0xa5a1, // 0x8ea7 : Halfwidth Katakana Small A
- 0xa5a3, // 0x8ea8 : Halfwidth Katakana Small I
- 0xa5a5, // 0x8ea9 : Halfwidth Katakana Small U
- 0xa5a7, // 0x8eaa : Halfwidth Katakana Small E
- 0xa5a9, // 0x8eab : Halfwidth Katakana Small O
- 0xa5e3, // 0x8eac : Halfwidth Katakana Small Ya
- 0xa5e5, // 0x8ead : Halfwidth Katakana Small Yu
- 0xa5e7, // 0x8eae : Halfwidth Katakana Small Yo
- 0xa5c3, // 0x8eaf : Halfwidth Katakana Small Tu
- 0xa1bc, // 0x8eb0 : Halfwidth Katakana-Hiragana Prolonged Sound Mark
- 0xa5a2, // 0x8eb1 : Halfwidth Katakana A
- 0xa5a4, // 0x8eb2 : Halfwidth Katakana I
- 0xa5a6, // 0x8eb3 : Halfwidth Katakana U
- 0xa5a8, // 0x8eb4 : Halfwidth Katakana E
- 0xa5aa, // 0x8eb5 : Halfwidth Katakana O
- 0xa5ab, // 0x8eb6 : Halfwidth Katakana Ka
- 0xa5ad, // 0x8eb7 : Halfwidth Katakana Ki
- 0xa5af, // 0x8eb8 : Halfwidth Katakana Ku
- 0xa5b1, // 0x8eb9 : Halfwidth Katakana Ke
- 0xa5b3, // 0x8eba : Halfwidth Katakana Ko
- 0xa5b5, // 0x8ebb : Halfwidth Katakana Sa
- 0xa5b7, // 0x8ebc : Halfwidth Katakana Si
- 0xa5b9, // 0x8ebd : Halfwidth Katakana Su
- 0xa5bb, // 0x8ebe : Halfwidth Katakana Se
- 0xa5bd, // 0x8ebf : Halfwidth Katakana So
- 0xa5bf, // 0x8ec0 : Halfwidth Katakana Ta
- 0xa5c1, // 0x8ec1 : Halfwidth Katakana Ti
- 0xa5c4, // 0x8ec2 : Halfwidth Katakana Tu
- 0xa5c6, // 0x8ec3 : Halfwidth Katakana Te
- 0xa5c8, // 0x8ec4 : Halfwidth Katakana To
- 0xa5ca, // 0x8ec5 : Halfwidth Katakana Na
- 0xa5cb, // 0x8ec6 : Halfwidth Katakana Ni
- 0xa5cc, // 0x8ec7 : Halfwidth Katakana Nu
- 0xa5cd, // 0x8ec8 : Halfwidth Katakana Ne
- 0xa5ce, // 0x8ec9 : Halfwidth Katakana No
- 0xa5cf, // 0x8eca : Halfwidth Katakana Ha
- 0xa5d2, // 0x8ecb : Halfwidth Katakana Hi
- 0xa5d5, // 0x8ecc : Halfwidth Katakana Hu
- 0xa5d8, // 0x8ecd : Halfwidth Katakana He
- 0xa5db, // 0x8ece : Halfwidth Katakana Ho
- 0xa5de, // 0x8ecf : Halfwidth Katakana Ma
- 0xa5df, // 0x8ed0 : Halfwidth Katakana Mi
- 0xa5e0, // 0x8ed1 : Halfwidth Katakana Mu
- 0xa5e1, // 0x8ed2 : Halfwidth Katakana Me
- 0xa5e2, // 0x8ed3 : Halfwidth Katakana Mo
- 0xa5e4, // 0x8ed4 : Halfwidth Katakana Ya
- 0xa5e6, // 0x8ed5 : Halfwidth Katakana Yu
- 0xa5e8, // 0x8ed6 : Halfwidth Katakana Yo
- 0xa5e9, // 0x8ed7 : Halfwidth Katakana Ra
- 0xa5ea, // 0x8ed8 : Halfwidth Katakana Ri
- 0xa5eb, // 0x8ed9 : Halfwidth Katakana Ru
- 0xa5ec, // 0x8eda : Halfwidth Katakana Re
- 0xa5ed, // 0x8edb : Halfwidth Katakana Ro
- 0xa5ef, // 0x8edc : Halfwidth Katakana Wa
- 0xa5f3, // 0x8edd : Halfwidth Katakana N
- 0xa1ab, // 0x8ede : Halfwidth Katakana Voiced Sound Mark
- 0xa1ac // 0x8edf : Halfwidth Katakana Semi-Voiced Sound Mark
- };
- }
-}
-#endif // FEATURE_CODEPAGES_FILE
-
diff --git a/src/mscorlib/src/System/Text/Latin1Encoding.cs b/src/mscorlib/src/System/Text/Latin1Encoding.cs
index 56a6c1f949..26009bf6c0 100644
--- a/src/mscorlib/src/System/Text/Latin1Encoding.cs
+++ b/src/mscorlib/src/System/Text/Latin1Encoding.cs
@@ -13,7 +13,6 @@ namespace System.Text
using System.Collections;
using System.Runtime.CompilerServices;
using System.Runtime.Serialization;
- using System.Security.Permissions;
//
@@ -488,7 +487,6 @@ namespace System.Text
}
}
-#if !FEATURE_NORM_IDNA_ONLY
public override bool IsAlwaysNormalized(NormalizationForm form)
{
// Latin-1 contains precomposed characters, so normal for Form C.
@@ -498,7 +496,6 @@ namespace System.Text
// Only true for form C.
return (form == NormalizationForm.FormC);
}
-#endif // !FEATURE_NORM_IDNA_ONLY
// Since our best fit table is small we'll hard code it
internal override char[] GetBestFitUnicodeToBytesData()
{
diff --git a/src/mscorlib/src/System/Text/MLangCodePageEncoding.cs b/src/mscorlib/src/System/Text/MLangCodePageEncoding.cs
deleted file mode 100644
index a82db91b98..0000000000
--- a/src/mscorlib/src/System/Text/MLangCodePageEncoding.cs
+++ /dev/null
@@ -1,172 +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.
-
-
-// WARNING:
-//
-// This is just an IObjectReference proxy for the former MLang Encodings (V1.1)
-// We keep the old name now even for the Whidbey V2.0 IObjectReference because it also
-// works with the Everett V1.1 version.
-namespace System.Text
-{
- using System;
- using System.Runtime.Serialization;
- using System.Security.Permissions;
- using System.Diagnostics;
- using System.Diagnostics.Contracts;
-
- /*=================================MLangCodePageEncoding==================================
- ** This class is here only to deserialize the MLang classes from Everett (V1.1) into
- ** Appropriate Whidbey (V2.0) objects. We also serialize the Whidbey classes
- ** using this proxy since we pretty much need one anyway and that solves Whidbey
- ** to Everett compatibility as well.
- ==============================================================================*/
-
- [Serializable]
- internal sealed class MLangCodePageEncoding : IObjectReference, ISerializable
- {
- // Temp stuff
- [NonSerialized]
- private int m_codePage;
- [NonSerialized]
- private bool m_isReadOnly;
- [NonSerialized]
- private bool m_deserializedFromEverett = false;
-
- [NonSerialized]
- private EncoderFallback encoderFallback = null;
- [NonSerialized]
- private DecoderFallback decoderFallback = null;
-
- // Might need this when GetRealObjecting
- [NonSerialized]
- private Encoding realEncoding = null;
-
- // Constructor called by serialization.
- internal MLangCodePageEncoding(SerializationInfo info, StreamingContext context)
- {
- // Any info?
- if (info==null) throw new ArgumentNullException(nameof(info));
- Contract.EndContractBlock();
-
- // All versions have a code page
- this.m_codePage = (int)info.GetValue("m_codePage", typeof(int));
-
- // See if we have a code page
- try
- {
- //
- // Try Whidbey V2.0 Fields
- //
- this.m_isReadOnly = (bool)info.GetValue("m_isReadOnly", typeof(bool));
-
- this.encoderFallback = (EncoderFallback)info.GetValue("encoderFallback", typeof(EncoderFallback));
- this.decoderFallback = (DecoderFallback)info.GetValue("decoderFallback", typeof(DecoderFallback));
- }
- catch (SerializationException)
- {
- //
- // Didn't have Whidbey things, must be Everett
- //
- this.m_deserializedFromEverett = true;
-
- // May as well be read only
- this.m_isReadOnly = true;
- }
- }
-
- // Just get it from GetEncoding
- public Object GetRealObject(StreamingContext context)
- {
- // Get our encoding (Note: This has default fallbacks for readonly and everett cases)
- this.realEncoding = Encoding.GetEncoding(this.m_codePage);
-
- // If its read only then it uses default fallbacks, otherwise pick up the new ones
- // Otherwise we want to leave the new one read only
- if (!this.m_deserializedFromEverett && !this.m_isReadOnly)
- {
- this.realEncoding = (Encoding)this.realEncoding.Clone();
- this.realEncoding.EncoderFallback = this.encoderFallback;
- this.realEncoding.DecoderFallback = this.decoderFallback;
- }
-
- return this.realEncoding;
- }
-
- // ISerializable implementation
- void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
- {
- // We cannot ever call this.
- Debug.Assert(false, "Didn't expect to make it to MLangCodePageEncoding ISerializable.GetObjectData");
- throw new ArgumentException(Environment.GetResourceString("Arg_ExecutionEngineException"));
- }
-
-// Same problem with the Encoder, this only happens with Everett Encoders
- [Serializable]
- internal sealed class MLangEncoder : IObjectReference, ISerializable
- {
- // Might need this when GetRealObjecting
- [NonSerialized]
- private Encoding realEncoding = null;
-
- // Constructor called by serialization, have to handle deserializing from Everett
- internal MLangEncoder(SerializationInfo info, StreamingContext context)
- {
- // Any 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
- public Object GetRealObject(StreamingContext context)
- {
- return this.realEncoding.GetEncoder();
- }
-
- // ISerializable implementation, get data for this object
- void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
- {
- // We cannot ever call this.
- Debug.Assert(false, "Didn't expect to make it to MLangCodePageEncoding.MLangEncoder.GetObjectData");
- throw new ArgumentException(Environment.GetResourceString("Arg_ExecutionEngineException"));
- }
- }
-
-
- // Same problem with the Decoder, this only happens with Everett Decoders
- [Serializable]
- internal sealed class MLangDecoder : IObjectReference, ISerializable
- {
- // Might need this when GetRealObjecting
- [NonSerialized]
- private Encoding realEncoding = null;
-
- // Constructor called by serialization, have to handle deserializing from Everett
- internal MLangDecoder(SerializationInfo info, StreamingContext context)
- {
- // Any 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
- public Object GetRealObject(StreamingContext context)
- {
- return this.realEncoding.GetDecoder();
- }
-
- // ISerializable implementation, get data for this object
- void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
- {
- // We cannot ever call this.
- 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.Windows.cs b/src/mscorlib/src/System/Text/Normalization.Windows.cs
index b2faf0db68..3bcba08934 100644
--- a/src/mscorlib/src/System/Text/Normalization.Windows.cs
+++ b/src/mscorlib/src/System/Text/Normalization.Windows.cs
@@ -21,19 +21,15 @@ namespace System.Text
//
// 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;
@@ -77,7 +73,6 @@ namespace System.Text
{
switch ((ExtendedNormalizationForms)form)
{
-#if !FEATURE_NORM_IDNA_ONLY
case ExtendedNormalizationForms.FormC:
if (NFC) return;
InitializeForm(form, "normnfc.nlp");
@@ -101,7 +96,6 @@ namespace System.Text
InitializeForm(form, "normnfkd.nlp");
NFKD = true;
break;
-#endif // !FEATURE_NORM_IDNA_ONLY
case ExtendedNormalizationForms.FormIdna:
if (IDNA) return;
@@ -109,7 +103,6 @@ namespace System.Text
IDNA = true;
break;
-#if !FEATURE_NORM_IDNA_ONLY
case ExtendedNormalizationForms.FormCDisallowUnassigned:
if (NFCDisallowUnassigned) return;
InitializeForm(form, "normnfc.nlp");
@@ -133,7 +126,6 @@ namespace System.Text
InitializeForm(form, "normnfkd.nlp");
NFKDDisallowUnassigned = true;
break;
-#endif // !FEATURE_NORM_IDNA_ONLY
case ExtendedNormalizationForms.FormIdnaDisallowUnassigned:
if (IDNADisallowUnassigned) return;
diff --git a/src/mscorlib/src/System/Text/Normalization.cs b/src/mscorlib/src/System/Text/Normalization.cs
index e7e733a587..c81149d59a 100644
--- a/src/mscorlib/src/System/Text/Normalization.cs
+++ b/src/mscorlib/src/System/Text/Normalization.cs
@@ -5,32 +5,25 @@
namespace System.Text
{
// This is the enumeration for Normalization Forms
-[System.Runtime.InteropServices.ComVisible(true)]
public enum NormalizationForm
{
-#if !FEATURE_NORM_IDNA_ONLY
FormC = 1,
FormD = 2,
FormKC = 5,
FormKD = 6
-#endif // !FEATURE_NORM_IDNA_ONLY
}
internal enum ExtendedNormalizationForms
{
-#if !FEATURE_NORM_IDNA_ONLY
FormC = 1,
FormD = 2,
FormKC = 5,
FormKD = 6,
-#endif // !FEATURE_NORM_IDNA_ONLY
FormIdna = 0xd,
-#if !FEATURE_NORM_IDNA_ONLY
FormCDisallowUnassigned = 0x101,
FormDDisallowUnassigned = 0x102,
FormKCDisallowUnassigned = 0x105,
FormKDDisallowUnassigned = 0x106,
-#endif // !FEATURE_NORM_IDNA_ONLY
FormIdnaDisallowUnassigned = 0x10d
}
}
diff --git a/src/mscorlib/src/System/Text/SBCSCodePageEncoding.cs b/src/mscorlib/src/System/Text/SBCSCodePageEncoding.cs
deleted file mode 100644
index 8b07149fb7..0000000000
--- a/src/mscorlib/src/System/Text/SBCSCodePageEncoding.cs
+++ /dev/null
@@ -1,1009 +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_CODEPAGES_FILE // requires BaseCodePageEncooding
-namespace System.Text
-{
- using System;
- using System.Diagnostics;
- using System.Diagnostics.Contracts;
- using System.Text;
- using System.Threading;
- using System.Globalization;
- using System.Runtime.Serialization;
- using System.Security;
- using System.Security.Permissions;
-
- // SBCSCodePageEncoding
- [Serializable]
- internal class SBCSCodePageEncoding : BaseCodePageEncoding, ISerializable
- {
- // Pointers to our memory section parts
- [NonSerialized]
- unsafe char* mapBytesToUnicode = null; // char 256
- [NonSerialized]
- unsafe byte* mapUnicodeToBytes = null; // byte 65536
- [NonSerialized]
- unsafe int* mapCodePageCached = null; // to remember which CP is cached
-
- const char UNKNOWN_CHAR=(char)0xFFFD;
-
- // byteUnknown is used for default fallback only
- [NonSerialized]
- byte byteUnknown;
- [NonSerialized]
- char charUnknown;
-
- public SBCSCodePageEncoding(int codePage) : this(codePage, codePage)
- {
- }
-
- internal SBCSCodePageEncoding(int codePage, int dataCodePage) : base(codePage, dataCodePage)
- {
- }
-
- // Constructor called by serialization.
- // Note: We use the base GetObjectData however
- internal SBCSCodePageEncoding(SerializationInfo info, StreamingContext context) : base(0)
- {
- // Actually this can't ever get called, CodePageEncoding is our proxy
- Debug.Assert(false, "Didn't expect to make it to SBCSCodePageEncoding serialization constructor");
- throw new ArgumentNullException("this");
- }
-
- // We have a managed code page entry, so load our tables
- // SBCS data section looks like:
- //
- // char[256] - what each byte maps to in unicode. No support for surrogates. 0 is undefined code point
- // (except 0 for byte 0 is expected to be a real 0)
- //
- // byte/char* - Data for best fit (unicode->bytes), again no best fit for Unicode
- // 1st WORD is Unicode // of 1st character position
- // Next bytes are best fit byte for that position. Position is incremented after each byte
- // 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!
- protected override unsafe void LoadManagedCodePage()
- {
- // Should be loading OUR code page
- 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
- if (pCodePage->ByteCount != 1)
- throw new NotSupportedException(
- Environment.GetResourceString("NotSupported_NoCodepageData", CodePage));
-
- // Remember our unknown bytes & chars
- byteUnknown = (byte)pCodePage->ByteReplace;
- charUnknown = pCodePage->UnicodeReplace;
-
- // Get our mapped section 65536 bytes for unicode->bytes, 256 * 2 bytes for bytes->unicode
- // Plus 4 byte to remember CP # when done loading it. (Don't want to get IA64 or anything out of alignment)
- byte *pMemorySection = GetSharedMemory(65536*1 + 256*2 + 4 + iExtraBytes);
-
- mapBytesToUnicode = (char*)pMemorySection;
- mapUnicodeToBytes = (byte*)(pMemorySection + 256 * 2);
- mapCodePageCached = (int*)(pMemorySection + 256 * 2 + 65536 * 1 + iExtraBytes);
-
- // If its cached (& filled in) we don't have to do anything else
- if (*mapCodePageCached != 0)
- {
- 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);
-
- if (*mapCodePageCached != this.dataTableCodePage)
- throw new OutOfMemoryException(
- Environment.GetResourceString("Arg_OutOfMemoryException"));
-
- // If its cached (& filled in) we don't have to do anything else
- return;
- }
-
- // Need to read our data file and fill in our section.
- // WARNING: Multiple code pieces could do this at once (so we don't have to lock machine-wide)
- // so be careful here. Only stick legal values in here, don't stick temporary values.
-
- // Read our data file and set mapBytesToUnicode and mapUnicodeToBytes appropriately
- // First table is just all 256 mappings
- char* pTemp = (char*)&(pCodePage->FirstDataWord);
- for (int b = 0; b < 256; b++)
- {
- // Don't want to force 0's to map Unicode wrong. 0 byte == 0 unicode already taken care of
- if (pTemp[b] != 0 || b == 0)
- {
- mapBytesToUnicode[b] = pTemp[b];
-
- if (pTemp[b] != UNKNOWN_CHAR)
- mapUnicodeToBytes[pTemp[b]] = (byte)b;
- }
- else
- {
- mapBytesToUnicode[b] = UNKNOWN_CHAR;
- }
- }
-
- // We're done with our mapped section, set our flag so others don't have to rebuild table.
- *mapCodePageCached = this.dataTableCodePage;
- }
-
- // 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;
- }
- }
-
- // Read in our best fit table
- protected unsafe override void ReadBestFitTable()
- {
- // Lock so we don't confuse ourselves.
- lock(InternalSyncObject)
- {
- // If we got a best fit array already, then don't do this
- if (arrayUnicodeBestFit == null)
- {
- //
- // Read in Best Fit table.
- //
-
- // First check the SBCS->Unicode best fit table, which starts right after the
- // 256 word data table. This table looks like word, word where 1st word is byte and 2nd
- // word is replacement for that word. It ends when byte == 0.
- byte* pData = (byte*)&(pCodePage->FirstDataWord);
- pData += 512;
-
- // Need new best fit array
- char[] arrayTemp = new char[256];
- for (int i = 0; i < 256; i++)
- arrayTemp[i] = mapBytesToUnicode[i];
-
- // See if our words are zero
- ushort byteTemp;
- while ((byteTemp = *((ushort*)pData)) != 0)
- {
-
- 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;
-
- arrayTemp[byteTemp] = *((char*)pData);
- pData += 2;
- }
-
- // Remember our new array
- arrayBytesBestFit = arrayTemp;
-
- // It was on 0, it needs to be on next byte
- pData+=2;
- byte* pUnicodeToSBCS = pData;
-
- // Now count our characters from our Unicode->SBCS best fit table,
- // which is right after our 256 byte data table
- int iBestFitCount = 0;
-
- // Now do the UnicodeToBytes Best Fit mapping (this is the one we normally think of when we say "best fit")
- // pData should be pointing at the first data point for Bytes->Unicode table
- int unicodePosition = *((ushort*)pData);
- pData += 2;
-
- while (unicodePosition < 0x10000)
- {
- // Get the next byte
- byte input = *pData;
- pData++;
-
- // build our table:
- if (input == 1)
- {
- // Use next 2 bytes as our byte position
- unicodePosition = *((ushort*)pData);
- pData+=2;
- }
- else if (input < 0x20 && input > 0 && input != 0x1e)
- {
- // Advance input characters
- unicodePosition += input;
- }
- else
- {
- // Use this character if it isn't zero
- if (input > 0)
- iBestFitCount++;
-
- // skip this unicode position in any case
- unicodePosition++;
- }
- }
-
- // Make an array for our best fit data
- arrayTemp = new char[iBestFitCount*2];
-
- // Now actually read in the data
- // reset pData should be pointing at the first data point for Bytes->Unicode table
- pData = pUnicodeToSBCS;
- unicodePosition = *((ushort*)pData);
- pData += 2;
- iBestFitCount = 0;
-
- while (unicodePosition < 0x10000)
- {
- // Get the next byte
- byte input = *pData;
- pData++;
-
- // build our table:
- if (input == 1)
- {
- // Use next 2 bytes as our byte position
- unicodePosition = *((ushort*)pData);
- pData+=2;
- }
- else if (input < 0x20 && input > 0 && input != 0x1e)
- {
- // Advance input characters
- unicodePosition += input;
- }
- else
- {
- // Check for escape for glyph range
- if (input == 0x1e)
- {
- // Its an escape, so just read next byte directly
- input = *pData;
- pData++;
- }
-
- // 0 means just skip me
- if (input > 0)
- {
- // Use this character
- arrayTemp[iBestFitCount++] = (char)unicodePosition;
- // Have to map it to Unicode because best fit will need unicode value of best fit char.
- arrayTemp[iBestFitCount++] = mapBytesToUnicode[input];
-
- // This won't work if it won't round trip.
- 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));
- }
- unicodePosition++;
- }
- }
-
- // Remember it
- arrayUnicodeBestFit = arrayTemp;
- }
- }
- }
-
- // GetByteCount
- // Note: We start by assuming that the output will be the same as count. Having
- // an encoder or fallback may change that assumption
- 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
- 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.
- Debug.Assert(encoderFallback != null, "[SBCSCodePageEncoding.GetByteCount]Attempting to use null fallback");
-
- CheckMemorySection();
-
- // Need to test fallback
- EncoderReplacementFallback fallback = null;
-
- // Get any left over characters
- char charLeftOver = (char)0;
- if (encoder != null)
- {
- charLeftOver = encoder.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
- Debug.Assert(!encoder.m_throwOnOverflow || !encoder.InternalHasFallbackBuffer ||
- encoder.FallbackBuffer.Remaining == 0,
- "[SBCSCodePageEncoding.GetByteCount]Expected empty fallback buffer at start");
- }
- else
- {
- // If we aren't using default fallback then we may have a complicated count.
- fallback = this.EncoderFallback as EncoderReplacementFallback;
- }
-
- if ((fallback != null && fallback.MaxCharCount == 1)/* || bIsBestFit*/)
- {
- // Replacement fallback encodes surrogate pairs as two ?? (or two whatever), so return size is always
- // same as input size.
- // Note that no existing SBCS code pages map code points to supplimentary characters, so this is easy.
-
- // We could however have 1 extra byte if the last call had an encoder and a funky fallback and
- // if we don't use the funky fallback this time.
-
- // Do we have an extra char left over from last time?
- if (charLeftOver > 0)
- count++;
-
- return (count);
- }
-
- // It had a funky fallback, so its more complicated
- // Need buffer maybe later
- EncoderFallbackBuffer fallbackBuffer = null;
-
- // prepare our end
- int byteCount = 0;
- char* charEnd = chars + count;
-
- // We may have a left over character from last time, try and process it.
- if (charLeftOver > 0)
- {
- // Since left over char was a surrogate, it'll have to be fallen back.
- // Get Fallback
- Debug.Assert(encoder != null, "[SBCSCodePageEncoding.GetByteCount]Expect to have encoder if we have a charLeftOver");
- fallbackBuffer = encoder.FallbackBuffer;
- fallbackBuffer.InternalInitialize(chars, charEnd, encoder, false);
-
- // This will fallback a pair if *chars is a low surrogate
- fallbackBuffer.InternalFallback(charLeftOver, ref chars);
- }
-
- // Now we may have fallback char[] already from the encoder
-
- // Go ahead and do it, including the fallback.
- char ch;
- while ((ch = (fallbackBuffer == null) ? '\0' : fallbackBuffer.InternalGetNextChar()) != 0 ||
- chars < charEnd)
- {
- // First unwind any fallback
- if (ch == 0)
- {
- // No fallback, just get next char
- ch = *chars;
- chars++;
- }
-
- // get byte for this char
- byte bTemp = mapUnicodeToBytes[ch];
-
- // Check for fallback, this'll catch surrogate pairs too.
- if (bTemp == 0 && ch != (char)0)
- {
- if (fallbackBuffer == null)
- {
- // Create & init fallback buffer
- if (encoder == null)
- fallbackBuffer = this.encoderFallback.CreateFallbackBuffer();
- else
- fallbackBuffer = encoder.FallbackBuffer;
-
- // chars has moved so we need to remember figure it out so Exception fallback
- // index will be correct
- fallbackBuffer.InternalInitialize(charEnd - count, charEnd, encoder, false);
- }
-
- // Get Fallback
- fallbackBuffer.InternalFallback(ch, ref chars);
- continue;
- }
-
- // We'll use this one
- byteCount++;
- }
-
- Debug.Assert(fallbackBuffer == null || fallbackBuffer.Remaining == 0,
- "[SBCSEncoding.GetByteCount]Expected Empty fallback buffer at end");
-
- return (int)byteCount;
- }
-
- 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
- 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.
- Debug.Assert(encoderFallback != null, "[SBCSCodePageEncoding.GetBytes]Attempting to use null encoder fallback");
-
- CheckMemorySection();
-
- // Need to test fallback
- EncoderReplacementFallback fallback = null;
-
- // Get any left over characters
- char charLeftOver = (char)0;
- if (encoder != null)
- {
- charLeftOver = encoder.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
- 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 &&
-// encoder.FallbackBuffer.Remaining > 0)
-// throw new ArgumentException(Environment.GetResourceString("Argument_EncoderFallbackNotEmpty",
-// this.EncodingName, encoder.Fallback.GetType()));
- }
- else
- {
- // If we aren't using default fallback then we may have a complicated count.
- fallback = this.EncoderFallback as EncoderReplacementFallback;
- }
-
- // prepare our end
- char* charEnd = chars + charCount;
- byte* byteStart = bytes;
- char* charStart = chars;
-
- // See if we do the fast default or slightly slower fallback
- if (fallback != null && fallback.MaxCharCount == 1)
- {
- // Make sure our fallback character is valid first
- byte bReplacement = mapUnicodeToBytes[fallback.DefaultString[0]];
-
- // Check for replacements in range, otherwise fall back to slow version.
- if (bReplacement != 0)
- {
- // We should have exactly as many output bytes as input bytes, unless there's a left
- // over character, in which case we may need one more.
-
- // If we had a left over character will have to add a ? (This happens if they had a funky
- // fallback last time, but not this time.) (We can't spit any out though
- // because with fallback encoder each surrogate is treated as a seperate code point)
- if (charLeftOver > 0)
- {
- // Have to have room
- // Throw even if doing no throw version because this is just 1 char,
- // so buffer will never be big enough
- if (byteCount == 0)
- ThrowBytesOverflow(encoder, true);
-
- // This'll make sure we still have more room and also make sure our return value is correct.
- *(bytes++) = bReplacement;
- byteCount--; // We used one of the ones we were counting.
- }
-
- // This keeps us from overrunning our output buffer
- if (byteCount < charCount)
- {
- // Throw or make buffer smaller?
- ThrowBytesOverflow(encoder, byteCount < 1);
-
- // Just use what we can
- charEnd = chars + byteCount;
- }
-
- // Simple way
- while (chars < charEnd)
- {
- char ch2 = *chars;
- chars++;
-
- byte bTemp = mapUnicodeToBytes[ch2];
-
- // Check for fallback
- if (bTemp == 0 && ch2 != (char)0)
- *bytes = bReplacement;
- else
- *bytes = bTemp;
-
- bytes++;
- }
-
- // Clear encoder
- if (encoder != null)
- {
- encoder.charLeftOver = (char)0;
- encoder.m_charsUsed = (int)(chars-charStart);
- }
- return (int)(bytes - byteStart);
- }
- }
-
- // Slower version, have to do real fallback.
-
- // For fallback we may need a fallback buffer, we know we aren't default fallback
- EncoderFallbackBuffer fallbackBuffer = null;
-
- // prepare our end
- byte* byteEnd = bytes + byteCount;
-
- // We may have a left over character from last time, try and process it.
- if (charLeftOver > 0)
- {
- // Since left over char was a surrogate, it'll have to be fallen back.
- // Get Fallback
- Debug.Assert(encoder != null, "[SBCSCodePageEncoding.GetBytes]Expect to have encoder if we have a charLeftOver");
- fallbackBuffer = encoder.FallbackBuffer;
- fallbackBuffer.InternalInitialize(chars, charEnd, encoder, true);
-
- // This will fallback a pair if *chars is a low surrogate
- fallbackBuffer.InternalFallback(charLeftOver, ref chars);
- if (fallbackBuffer.Remaining > byteEnd - bytes)
- {
- // Throw it, if we don't have enough for this we never will
- ThrowBytesOverflow(encoder, true);
- }
- }
-
- // Now we may have fallback char[] already from the encoder fallback above
-
- // Go ahead and do it, including the fallback.
- char ch;
- while ((ch = (fallbackBuffer == null) ? '\0' : fallbackBuffer.InternalGetNextChar()) != 0 ||
- chars < charEnd)
- {
- // First unwind any fallback
- if (ch == 0)
- {
- // No fallback, just get next char
- ch = *chars;
- chars++;
- }
-
- // get byte for this char
- byte bTemp = mapUnicodeToBytes[ch];
-
- // Check for fallback, this'll catch surrogate pairs too.
- if (bTemp == 0 && ch != (char)0)
- {
- // Get Fallback
- if ( fallbackBuffer == null )
- {
- // Create & init fallback buffer
- if (encoder == null)
- fallbackBuffer = this.encoderFallback.CreateFallbackBuffer();
- else
- fallbackBuffer = encoder.FallbackBuffer;
- // chars has moved so we need to remember figure it out so Exception fallback
- // index will be correct
- fallbackBuffer.InternalInitialize(charEnd - charCount, charEnd, encoder, true);
- }
-
- // Make sure we have enough room. Each fallback char will be 1 output char
- // (or recursion exception will be thrown)
- fallbackBuffer.InternalFallback(ch, ref chars);
- if (fallbackBuffer.Remaining > byteEnd - bytes)
- {
- // Didn't use this char, reset it
- Debug.Assert(chars > charStart,
- "[SBCSCodePageEncoding.GetBytes]Expected chars to have advanced (fallback)");
- chars--;
- fallbackBuffer.InternalReset();
-
- // Throw it & drop this data
- ThrowBytesOverflow(encoder, chars == charStart);
- break;
- }
- continue;
- }
-
- // We'll use this one
- // Bounds check
- if (bytes >= byteEnd)
- {
- // didn't use this char, we'll throw or use buffer
- Debug.Assert(fallbackBuffer == null || fallbackBuffer.bFallingBack == false,
- "[SBCSCodePageEncoding.GetBytes]Expected to NOT be falling back");
- if (fallbackBuffer == null || fallbackBuffer.bFallingBack == false)
- {
- Debug.Assert(chars > charStart,
- "[SBCSCodePageEncoding.GetBytes]Expected chars to have advanced (normal)");
- chars--; // don't use last char
- }
- ThrowBytesOverflow(encoder, chars == charStart); // throw ?
- break; // don't throw, stop
- }
-
- // Go ahead and add it
- *bytes = bTemp;
- bytes++;
- }
-
- // encoder stuff if we have one
- if (encoder != null)
- {
- // Fallback stuck it in encoder if necessary, but we have to clear MustFlush cases
- if (fallbackBuffer != null && !fallbackBuffer.bUsedEncoder)
- // Clear it in case of MustFlush
- encoder.charLeftOver = (char)0;
-
- // Set our chars used count
- encoder.m_charsUsed = (int)(chars - charStart);
- }
-
- // Expect Empty fallback buffer for SBCS
- 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,
- internal override unsafe int GetCharCount(byte* bytes, int count, DecoderNLS decoder)
- {
- // Just assert, we're called internally so these should be safe, checked already
- Debug.Assert(bytes != null, "[SBCSCodePageEncoding.GetCharCount]bytes is null");
- Debug.Assert(count >= 0, "[SBCSCodePageEncoding.GetCharCount]byteCount is negative");
-
- CheckMemorySection();
-
- // See if we have best fit
- bool bUseBestFit = false;
-
- // Only need decoder fallback buffer if not using default replacement fallback or best fit fallback.
- DecoderReplacementFallback fallback = null;
-
- if (decoder == null)
- {
- fallback = this.DecoderFallback as DecoderReplacementFallback;
- bUseBestFit = this.DecoderFallback.IsMicrosoftBestFitFallback;
- }
- else
- {
- fallback = decoder.Fallback as DecoderReplacementFallback;
- bUseBestFit = decoder.Fallback.IsMicrosoftBestFitFallback;
- Debug.Assert(!decoder.m_throwOnOverflow || !decoder.InternalHasFallbackBuffer ||
- decoder.FallbackBuffer.Remaining == 0,
- "[SBCSCodePageEncoding.GetChars]Expected empty fallback buffer at start");
- }
-
- if (bUseBestFit || (fallback != null && fallback.MaxCharCount == 1))
- {
- // Just return length, SBCS stay the same length because they don't map to surrogate
- // pairs and we don't have a decoder fallback.
- return count;
- }
-
- // Might need one of these later
- DecoderFallbackBuffer fallbackBuffer = null;
-
- // Have to do it the hard way.
- // Assume charCount will be == count
- int charCount = count;
- byte[] byteBuffer = new byte[1];
-
- // Do it our fast way
- byte* byteEnd = bytes + count;
-
- // Quick loop
- while (bytes < byteEnd)
- {
- // Faster if don't use *bytes++;
- char c;
- c = mapBytesToUnicode[*bytes];
- bytes++;
-
- // If unknown we have to do fallback count
- if (c == UNKNOWN_CHAR)
- {
- // Must have a fallback buffer
- if (fallbackBuffer == null)
- {
- // Need to adjust count so we get real start
- if (decoder == null)
- fallbackBuffer = this.DecoderFallback.CreateFallbackBuffer();
- else
- fallbackBuffer = decoder.FallbackBuffer;
- fallbackBuffer.InternalInitialize(byteEnd - count, null);
- }
-
- // Use fallback buffer
- byteBuffer[0] = *(bytes - 1);
- charCount--; // We'd already reserved one for *(bytes-1)
- charCount += fallbackBuffer.InternalFallback(byteBuffer, bytes);
- }
- }
-
- // Fallback buffer must be empty
- Debug.Assert(fallbackBuffer == null || fallbackBuffer.Remaining == 0,
- "[SBCSEncoding.GetCharCount]Expected Empty fallback buffer at end");
-
- // Converted sequence is same length as input
- return charCount;
- }
-
- 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
- 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();
-
- // See if we have best fit
- bool bUseBestFit = false;
-
- // Do it fast way if using ? replacement or best fit fallbacks
- byte* byteEnd = bytes + byteCount;
- byte* byteStart = bytes;
- char* charStart = chars;
-
- // Only need decoder fallback buffer if not using default replacement fallback or best fit fallback.
- DecoderReplacementFallback fallback = null;
-
- if (decoder == null)
- {
- fallback = this.DecoderFallback as DecoderReplacementFallback;
- bUseBestFit = this.DecoderFallback.IsMicrosoftBestFitFallback;
- }
- else
- {
- fallback = decoder.Fallback as DecoderReplacementFallback;
- bUseBestFit = decoder.Fallback.IsMicrosoftBestFitFallback;
- Debug.Assert(!decoder.m_throwOnOverflow || !decoder.InternalHasFallbackBuffer ||
- decoder.FallbackBuffer.Remaining == 0,
- "[SBCSCodePageEncoding.GetChars]Expected empty fallback buffer at start");
- }
-
- if (bUseBestFit || (fallback != null && fallback.MaxCharCount == 1))
- {
- // Try it the fast way
- char replacementChar;
- if (fallback == null)
- replacementChar = '?'; // Best fit alwasy has ? for fallback for SBCS
- else
- replacementChar = fallback.DefaultString[0];
-
- // Need byteCount chars, otherwise too small buffer
- if (charCount < byteCount)
- {
- // Need at least 1 output byte, throw if must throw
- ThrowCharsOverflow(decoder, charCount < 1);
-
- // Not throwing, use what we can
- byteEnd = bytes + charCount;
- }
-
- // Quick loop, just do '?' replacement because we don't have fallbacks for decodings.
- while (bytes < byteEnd)
- {
- char c;
- if (bUseBestFit)
- {
- if (arrayBytesBestFit == null)
- {
- ReadBestFitTable();
- }
- c = arrayBytesBestFit[*bytes];
- }
- else
- c = mapBytesToUnicode[*bytes];
- bytes++;
-
- if (c == UNKNOWN_CHAR)
- // This is an invalid byte in the ASCII encoding.
- *chars = replacementChar;
- else
- *chars = c;
- chars++;
- }
-
- // bytes & chars used are the same
- if (decoder != null)
- decoder.m_bytesUsed = (int)(bytes - byteStart);
- return (int)(chars - charStart);
- }
-
- // Slower way's going to need a fallback buffer
- DecoderFallbackBuffer fallbackBuffer = null;
- byte[] byteBuffer = new byte[1];
- char* charEnd = chars + charCount;
-
- // Not quite so fast loop
- while (bytes < byteEnd)
- {
- // Faster if don't use *bytes++;
- char c = mapBytesToUnicode[*bytes];
- bytes++;
-
- // See if it was unknown
- if (c == UNKNOWN_CHAR)
- {
- // Make sure we have a fallback buffer
- if (fallbackBuffer == null)
- {
- if (decoder == null)
- fallbackBuffer = this.DecoderFallback.CreateFallbackBuffer();
- else
- fallbackBuffer = decoder.FallbackBuffer;
- fallbackBuffer.InternalInitialize(byteEnd - byteCount, charEnd);
- }
-
- // Use fallback buffer
- 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.
- if (!fallbackBuffer.InternalFallback(byteBuffer, bytes, ref chars))
- {
- // May or may not throw, but we didn't get this byte
- bytes--; // unused byte
- fallbackBuffer.InternalReset(); // Didn't fall this back
- ThrowCharsOverflow(decoder, bytes == byteStart); // throw?
- break; // don't throw, but stop loop
- }
- }
- else
- {
- // Make sure we have buffer space
- if (chars >= charEnd)
- {
- Debug.Assert(bytes > byteStart,
- "[SBCSCodePageEncoding.GetChars]Expected bytes to have advanced already (known byte)");
- bytes--; // unused byte
- ThrowCharsOverflow(decoder, bytes == byteStart); // throw?
- break; // don't throw, but stop loop
- }
-
- *(chars) = c;
- chars++;
- }
- }
-
- // Might have had decoder fallback stuff.
- if (decoder != null)
- decoder.m_bytesUsed = (int)(bytes - byteStart);
-
- // Expect Empty fallback buffer for GetChars
- Debug.Assert(fallbackBuffer == null || fallbackBuffer.Remaining == 0,
- "[SBCSEncoding.GetChars]Expected Empty fallback buffer at end");
-
- return (int)(chars - charStart);
- }
-
- public override int GetMaxByteCount(int charCount)
- {
- if (charCount < 0)
- throw new ArgumentOutOfRangeException(nameof(charCount),
- Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
- Contract.EndContractBlock();
-
- // Characters would be # of characters + 1 in case high surrogate is ? * max fallback
- long byteCount = (long)charCount + 1;
-
- if (EncoderFallback.MaxCharCount > 1)
- byteCount *= EncoderFallback.MaxCharCount;
-
- // 1 to 1 for most characters. Only surrogates with fallbacks have less.
-
- if (byteCount > 0x7fffffff)
- throw new ArgumentOutOfRangeException(nameof(charCount), Environment.GetResourceString("ArgumentOutOfRange_GetByteCountOverflow"));
- return (int)byteCount;
- }
-
- public override int GetMaxCharCount(int byteCount)
- {
- if (byteCount < 0)
- throw new ArgumentOutOfRangeException(nameof(byteCount),
- Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
- Contract.EndContractBlock();
-
- // Just return length, SBCS stay the same length because they don't map to surrogate
- long charCount = (long)byteCount;
-
- // 1 to 1 for most characters. Only surrogates with fallbacks have less, unknown fallbacks could be longer.
- if (DecoderFallback.MaxCharCount > 1)
- charCount *= DecoderFallback.MaxCharCount;
-
- if (charCount > 0x7fffffff)
- throw new ArgumentOutOfRangeException(nameof(byteCount), Environment.GetResourceString("ArgumentOutOfRange_GetCharCountOverflow"));
-
- return (int)charCount;
- }
-
- // True if and only if the encoding only uses single byte code points. (Ie, ASCII, 1252, etc)
- public override bool IsSingleByte
- {
- get
- {
- return true;
- }
- }
-
- [System.Runtime.InteropServices.ComVisible(false)]
- public override bool IsAlwaysNormalized(NormalizationForm form)
- {
- // Most of these code pages could be decomposed or have compatibility mappings for KC, KD, & D
- // additionally the allow unassigned forms and IDNA wouldn't work either, so C is our choice.
- if (form == NormalizationForm.FormC)
- {
- // Form C is only true for some code pages. They have to have all 256 code points assigned
- // and not map to unassigned or combinable code points.
- switch (CodePage)
- {
- // Return true for some code pages.
- case 1252: // (Latin I - ANSI)
- case 1250: // (Eastern Europe - ANSI)
- case 1251: // (Cyrillic - ANSI)
- case 1254: // (Turkish - ANSI)
- case 1256: // (Arabic - ANSI)
- case 28591: // (ISO 8859-1 Latin I)
- case 437: // (United States - OEM)
- case 737: // (Greek (aka 437G) - OEM)
- case 775: // (Baltic - OEM)
- case 850: // (Multilingual (Latin I) - OEM)
- case 852: // (Slovak (Latin II) - OEM)
- case 855: // (Cyrillic - OEM)
- case 858: // (Multilingual (Latin I) - OEM + Euro)
- case 860: // (Portuguese - OEM)
- case 861: // (Icelandic - OEM)
- case 862: // (Hebrew - OEM)
- case 863: // (Canadian French - OEM)
- case 865: // (Nordic - OEM)
- case 866: // (Russian - OEM)
- case 869: // (Modern Greek - OEM)
- case 10007: // (Cyrillic - MAC)
- case 10017: // (Ukraine - MAC)
- case 10029: // (Latin II - MAC)
- case 28592: // (ISO 8859-2 Eastern Europe)
- case 28594: // (ISO 8859-4 Baltic)
- case 28595: // (ISO 8859-5 Cyrillic)
- case 28599: // (ISO 8859-9 Latin Alphabet No.5)
- case 28603: // (ISO/IEC 8859-13:1998 (Lithuanian))
- case 28605: // (ISO 8859-15 Latin 9 (IBM923=IBM819+Euro))
- case 037: // (IBM EBCDIC U.S./Canada)
- case 500: // (IBM EBCDIC International)
- case 870: // (IBM EBCDIC Latin-2 Multilingual/ROECE)
- case 1026: // (IBM EBCDIC Latin-5 Turkey)
- case 1047: // (IBM Latin-1/Open System)
- case 1140: // (IBM EBCDIC U.S./Canada (037+Euro))
- case 1141: // (IBM EBCDIC Germany (20273(IBM273)+Euro))
- case 1142: // (IBM EBCDIC Denmark/Norway (20277(IBM277+Euro))
- case 1143: // (IBM EBCDIC Finland/Sweden (20278(IBM278)+Euro))
- case 1144: // (IBM EBCDIC Italy (20280(IBM280)+Euro))
- case 1145: // (IBM EBCDIC Latin America/Spain (20284(IBM284)+Euro))
- case 1146: // (IBM EBCDIC United Kingdom (20285(IBM285)+Euro))
- case 1147: // (IBM EBCDIC France (20297(IBM297+Euro))
- case 1148: // (IBM EBCDIC International (500+Euro))
- case 1149: // (IBM EBCDIC Icelandic (20871(IBM871+Euro))
- case 20273: // (IBM EBCDIC Germany)
- case 20277: // (IBM EBCDIC Denmark/Norway)
- case 20278: // (IBM EBCDIC Finland/Sweden)
- case 20280: // (IBM EBCDIC Italy)
- case 20284: // (IBM EBCDIC Latin America/Spain)
- case 20285: // (IBM EBCDIC United Kingdom)
- case 20297: // (IBM EBCDIC France)
- case 20871: // (IBM EBCDIC Icelandic)
- case 20880: // (IBM EBCDIC Cyrillic)
- case 20924: // (IBM Latin-1/Open System (IBM924=IBM1047+Euro))
- case 21025: // (IBM EBCDIC Cyrillic (Serbian, Bulgarian))
- case 720: // (Arabic - Transparent ASMO)
- case 20866: // (Russian - KOI8)
- case 21866: // (Ukrainian - KOI8-U)
- return true;
- }
- }
-
- // False for IDNA and unknown
- return false;
- }
- }
-}
-#endif // FEATURE_CODEPAGES_FILE
diff --git a/src/mscorlib/src/System/Text/StringBuilder.cs b/src/mscorlib/src/System/Text/StringBuilder.cs
index f20146fe00..72247c333e 100644
--- a/src/mscorlib/src/System/Text/StringBuilder.cs
+++ b/src/mscorlib/src/System/Text/StringBuilder.cs
@@ -41,7 +41,6 @@ namespace System.Text {
// Console.WriteLine(sb1);
// Console.WriteLine(sb2);
//
- [System.Runtime.InteropServices.ComVisible(true)]
[Serializable]
public sealed class StringBuilder : ISerializable
{
@@ -593,7 +592,7 @@ namespace System.Text {
throw new ArgumentOutOfRangeException(nameof(startIndex), Environment.GetResourceString("ArgumentOutOfRange_GenericPositive"));
}
if (charCount<0) {
- throw new ArgumentOutOfRangeException("count", Environment.GetResourceString("ArgumentOutOfRange_GenericPositive"));
+ throw new ArgumentOutOfRangeException(nameof(charCount), Environment.GetResourceString("ArgumentOutOfRange_GenericPositive"));
}
Contract.Ensures(Contract.Result<StringBuilder>() != null);
Contract.EndContractBlock();
@@ -605,7 +604,7 @@ namespace System.Text {
throw new ArgumentNullException(nameof(value));
}
if (charCount > value.Length - startIndex) {
- throw new ArgumentOutOfRangeException("count", Environment.GetResourceString("ArgumentOutOfRange_Index"));
+ throw new ArgumentOutOfRangeException(nameof(charCount), Environment.GetResourceString("ArgumentOutOfRange_Index"));
}
if (charCount==0) {
@@ -715,20 +714,17 @@ namespace System.Text {
}
}
- [System.Runtime.InteropServices.ComVisible(false)]
public StringBuilder AppendLine() {
Contract.Ensures(Contract.Result<StringBuilder>() != null);
return Append(Environment.NewLine);
}
- [System.Runtime.InteropServices.ComVisible(false)]
public StringBuilder AppendLine(string value) {
Contract.Ensures(Contract.Result<StringBuilder>() != null);
Append(value);
return Append(Environment.NewLine);
}
- [System.Runtime.InteropServices.ComVisible(false)]
public void CopyTo(int sourceIndex, char[] destination, int destinationIndex, int count) {
if (destination == null) {
throw new ArgumentNullException(nameof(destination));
@@ -848,7 +844,7 @@ namespace System.Text {
}
if (length > Length - startIndex) {
- throw new ArgumentOutOfRangeException("index", Environment.GetResourceString("ArgumentOutOfRange_Index"));
+ throw new ArgumentOutOfRangeException(nameof(length), Environment.GetResourceString("ArgumentOutOfRange_Index"));
}
Contract.Ensures(Contract.Result<StringBuilder>() != null);
Contract.EndContractBlock();
@@ -1205,7 +1201,7 @@ namespace System.Text {
}
if (charCount < 0) {
- throw new ArgumentOutOfRangeException("count", Environment.GetResourceString("ArgumentOutOfRange_GenericPositive"));
+ throw new ArgumentOutOfRangeException(nameof(charCount), Environment.GetResourceString("ArgumentOutOfRange_GenericPositive"));
}
if (startIndex > value.Length - charCount) {
diff --git a/src/mscorlib/src/System/Text/SurrogateEncoder.cs b/src/mscorlib/src/System/Text/SurrogateEncoder.cs
deleted file mode 100644
index bbfa180f29..0000000000
--- a/src/mscorlib/src/System/Text/SurrogateEncoder.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.
-
-
-// WARNING:
-//
-// This is just an IObjectReference proxy for the former V1.1 Surrogate Encoder
-// All this does is make an encoder of the correct type, it DOES NOT maintain state.
-namespace System.Text
-{
- using System;
- using System.Runtime.Serialization;
- using System.Security.Permissions;
- using System.Diagnostics;
- using System.Diagnostics.Contracts;
-
- /*=================================SurrogateEncoder==================================
- ** This class is here only to deserialize the SurrogateEncoder class from Everett (V1.1) into
- ** Appropriate Whidbey (V2.0) objects.
- ==============================================================================*/
-
- [Serializable]
- internal sealed class SurrogateEncoder : IObjectReference, ISerializable
- {
- // Might need this when GetRealObjecting
- [NonSerialized]
- private Encoding realEncoding = null;
-
- // Constructor called by serialization.
- internal SurrogateEncoder(SerializationInfo info, StreamingContext context)
- {
- // Any info?
- if (info==null) throw new ArgumentNullException(nameof(info));
- Contract.EndContractBlock();
-
- // All versions have a code page
- this.realEncoding = (Encoding)info.GetValue("m_encoding", typeof(Encoding));
- }
-
- // Just get it from GetEncoding
- public Object GetRealObject(StreamingContext context)
- {
- // Need to get our Encoding's Encoder
- return this.realEncoding.GetEncoder();
- }
-
- // ISerializable implementation
- void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
- {
- // We cannot ever call this.
- 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/UTF7Encoding.cs b/src/mscorlib/src/System/Text/UTF7Encoding.cs
index 624ca735f6..9418d2e768 100644
--- a/src/mscorlib/src/System/Text/UTF7Encoding.cs
+++ b/src/mscorlib/src/System/Text/UTF7Encoding.cs
@@ -10,13 +10,11 @@ namespace System.Text
{
using System;
using System.Runtime.Serialization;
- using System.Security.Permissions;
using System.Diagnostics;
using System.Diagnostics.Contracts;
[Serializable]
- [System.Runtime.InteropServices.ComVisible(true)]
public class UTF7Encoding : Encoding
{
private const String base64Chars =
@@ -127,7 +125,6 @@ namespace System.Text
- [System.Runtime.InteropServices.ComVisible(false)]
public override bool Equals(Object value)
{
UTF7Encoding that = value as UTF7Encoding;
@@ -142,7 +139,6 @@ namespace System.Text
// Compared to all the other encodings, variations of UTF7 are unlikely
- [System.Runtime.InteropServices.ComVisible(false)]
public override int GetHashCode()
{
return this.CodePage + this.EncoderFallback.GetHashCode() + this.DecoderFallback.GetHashCode();
@@ -170,20 +166,17 @@ namespace System.Text
return EncodingForwarder.GetByteCount(this, chars, index, count);
}
- [System.Runtime.InteropServices.ComVisible(false)]
public override int GetByteCount(String s)
{
return EncodingForwarder.GetByteCount(this, s);
}
[CLSCompliant(false)]
- [System.Runtime.InteropServices.ComVisible(false)]
public override unsafe int GetByteCount(char* chars, int count)
{
return EncodingForwarder.GetByteCount(this, chars, count);
}
- [System.Runtime.InteropServices.ComVisible(false)]
public override int GetBytes(String s, int charIndex, int charCount,
byte[] bytes, int byteIndex)
{
@@ -206,7 +199,6 @@ namespace System.Text
}
[CLSCompliant(false)]
- [System.Runtime.InteropServices.ComVisible(false)]
public override unsafe int GetBytes(char* chars, int charCount, byte* bytes, int byteCount)
{
return EncodingForwarder.GetBytes(this, chars, charCount, bytes, byteCount);
@@ -221,7 +213,6 @@ namespace System.Text
}
[CLSCompliant(false)]
- [System.Runtime.InteropServices.ComVisible(false)]
public override unsafe int GetCharCount(byte* bytes, int count)
{
return EncodingForwarder.GetCharCount(this, bytes, count);
@@ -234,7 +225,6 @@ namespace System.Text
}
[CLSCompliant(false)]
- [System.Runtime.InteropServices.ComVisible(false)]
public unsafe override int GetChars(byte* bytes, int byteCount, char* chars, int charCount)
{
return EncodingForwarder.GetChars(this, bytes, byteCount, chars, charCount);
@@ -243,7 +233,6 @@ namespace System.Text
// Returns a string containing the decoded representation of a range of
// bytes in a byte array.
- [System.Runtime.InteropServices.ComVisible(false)]
public override String GetString(byte[] bytes, int index, int count)
{
return EncodingForwarder.GetString(this, bytes, index, count);
diff --git a/src/mscorlib/src/System/Text/UTF8Encoding.cs b/src/mscorlib/src/System/Text/UTF8Encoding.cs
index ba19649b56..191bbfef56 100644
--- a/src/mscorlib/src/System/Text/UTF8Encoding.cs
+++ b/src/mscorlib/src/System/Text/UTF8Encoding.cs
@@ -20,7 +20,6 @@ namespace System.Text
using System;
using System.Globalization;
using System.Runtime.Serialization;
- using System.Security.Permissions;
using System.Diagnostics;
using System.Diagnostics.Contracts;
@@ -37,7 +36,6 @@ namespace System.Text
// switch the byte orderings.
[Serializable]
-[System.Runtime.InteropServices.ComVisible(true)]
public class UTF8Encoding : Encoding
{
/*
@@ -131,7 +129,6 @@ namespace System.Text
}
[CLSCompliant(false)]
- [System.Runtime.InteropServices.ComVisible(false)]
public override unsafe int GetByteCount(char* chars, int count)
{
return EncodingForwarder.GetByteCount(this, chars, count);
@@ -159,7 +156,6 @@ namespace System.Text
}
[CLSCompliant(false)]
- [System.Runtime.InteropServices.ComVisible(false)]
public override unsafe int GetBytes(char* chars, int charCount, byte* bytes, int byteCount)
{
return EncodingForwarder.GetBytes(this, chars, charCount, bytes, byteCount);
@@ -174,7 +170,6 @@ namespace System.Text
}
[CLSCompliant(false)]
- [System.Runtime.InteropServices.ComVisible(false)]
public override unsafe int GetCharCount(byte* bytes, int count)
{
return EncodingForwarder.GetCharCount(this, bytes, count);
@@ -187,7 +182,6 @@ namespace System.Text
}
[CLSCompliant(false)]
- [System.Runtime.InteropServices.ComVisible(false)]
public unsafe override int GetChars(byte* bytes, int byteCount, char* chars, int charCount)
{
return EncodingForwarder.GetChars(this, bytes, byteCount, chars, charCount);
@@ -196,7 +190,6 @@ namespace System.Text
// Returns a string containing the decoded representation of a range of
// bytes in a byte array.
- [System.Runtime.InteropServices.ComVisible(false)]
public override String GetString(byte[] bytes, int index, int count)
{
return EncodingForwarder.GetString(this, bytes, index, count);
diff --git a/src/mscorlib/src/System/Text/UnicodeEncoding.cs b/src/mscorlib/src/System/Text/UnicodeEncoding.cs
index 25255c3230..d8ef18ab05 100644
--- a/src/mscorlib/src/System/Text/UnicodeEncoding.cs
+++ b/src/mscorlib/src/System/Text/UnicodeEncoding.cs
@@ -11,13 +11,11 @@ namespace System.Text
using System;
using System.Globalization;
using System.Runtime.Serialization;
- using System.Security.Permissions;
using System.Diagnostics;
using System.Diagnostics.Contracts;
[Serializable]
- [System.Runtime.InteropServices.ComVisible(true)]
public class UnicodeEncoding : Encoding
{
// Used by Encoding.BigEndianUnicode/Unicode for lazy initialization
@@ -111,7 +109,6 @@ namespace System.Text
}
[CLSCompliant(false)]
- [System.Runtime.InteropServices.ComVisible(false)]
public override unsafe int GetByteCount(char* chars, int count)
{
return EncodingForwarder.GetByteCount(this, chars, count);
@@ -139,7 +136,6 @@ namespace System.Text
}
[CLSCompliant(false)]
- [System.Runtime.InteropServices.ComVisible(false)]
public override unsafe int GetBytes(char* chars, int charCount, byte* bytes, int byteCount)
{
return EncodingForwarder.GetBytes(this, chars, charCount, bytes, byteCount);
@@ -154,7 +150,6 @@ namespace System.Text
}
[CLSCompliant(false)]
- [System.Runtime.InteropServices.ComVisible(false)]
public override unsafe int GetCharCount(byte* bytes, int count)
{
return EncodingForwarder.GetCharCount(this, bytes, count);
@@ -167,7 +162,6 @@ namespace System.Text
}
[CLSCompliant(false)]
- [System.Runtime.InteropServices.ComVisible(false)]
public unsafe override int GetChars(byte* bytes, int byteCount, char* chars, int charCount)
{
return EncodingForwarder.GetChars(this, bytes, byteCount, chars, charCount);
@@ -176,7 +170,6 @@ namespace System.Text
// Returns a string containing the decoded representation of a range of
// bytes in a byte array.
- [System.Runtime.InteropServices.ComVisible(false)]
public override String GetString(byte[] bytes, int index, int count)
{
return EncodingForwarder.GetString(this, bytes, index, count);
@@ -1659,7 +1652,6 @@ namespace System.Text
}
- [System.Runtime.InteropServices.ComVisible(false)]
public override System.Text.Encoder GetEncoder()
{
return new EncoderNLS(this);
diff --git a/src/mscorlib/src/System/ThreadAttributes.cs b/src/mscorlib/src/System/ThreadAttributes.cs
index bbd859c3af..6248736107 100644
--- a/src/mscorlib/src/System/ThreadAttributes.cs
+++ b/src/mscorlib/src/System/ThreadAttributes.cs
@@ -4,16 +4,13 @@
/*=============================================================================
**
-**
-**
** Purpose: For Threads-related custom attributes.
**
-**
=============================================================================*/
-namespace System {
- [AttributeUsage (AttributeTargets.Method)]
-[System.Runtime.InteropServices.ComVisible(true)]
+namespace System
+{
+ [AttributeUsage(AttributeTargets.Method)]
public sealed class STAThreadAttribute : Attribute
{
public STAThreadAttribute()
@@ -21,8 +18,7 @@ namespace System {
}
}
- [AttributeUsage (AttributeTargets.Method)]
-[System.Runtime.InteropServices.ComVisible(true)]
+ [AttributeUsage(AttributeTargets.Method)]
public sealed class MTAThreadAttribute : Attribute
{
public MTAThreadAttribute()
diff --git a/src/mscorlib/src/System/ThreadStaticAttribute.cs b/src/mscorlib/src/System/ThreadStaticAttribute.cs
index 58842eef0b..3755e65a7b 100644
--- a/src/mscorlib/src/System/ThreadStaticAttribute.cs
+++ b/src/mscorlib/src/System/ThreadStaticAttribute.cs
@@ -12,14 +12,14 @@
**
**
===========================================================*/
-namespace System {
-
- using System;
-[Serializable]
+using System;
+
+namespace System
+{
+ [Serializable]
[AttributeUsage(AttributeTargets.Field, Inherited = false)]
-[System.Runtime.InteropServices.ComVisible(true)]
- public class ThreadStaticAttribute : Attribute
+ public class ThreadStaticAttribute : Attribute
{
public ThreadStaticAttribute()
{
diff --git a/src/mscorlib/src/System/Threading/ApartmentState.cs b/src/mscorlib/src/System/Threading/ApartmentState.cs
index 844f85e9e7..1edf0af98a 100644
--- a/src/mscorlib/src/System/Threading/ApartmentState.cs
+++ b/src/mscorlib/src/System/Threading/ApartmentState.cs
@@ -15,7 +15,6 @@
namespace System.Threading {
[Serializable]
-[System.Runtime.InteropServices.ComVisible(true)]
public enum ApartmentState
{
/*=========================================================================
diff --git a/src/mscorlib/src/System/Threading/AsyncLocal.cs b/src/mscorlib/src/System/Threading/AsyncLocal.cs
index 6ed1545ac7..8c4319bd2c 100644
--- a/src/mscorlib/src/System/Threading/AsyncLocal.cs
+++ b/src/mscorlib/src/System/Threading/AsyncLocal.cs
@@ -127,8 +127,6 @@ namespace System.Threading
{
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
{
diff --git a/src/mscorlib/src/System/Threading/AutoResetEvent.cs b/src/mscorlib/src/System/Threading/AutoResetEvent.cs
index 78a6fa1234..fc6b2301ca 100644
--- a/src/mscorlib/src/System/Threading/AutoResetEvent.cs
+++ b/src/mscorlib/src/System/Threading/AutoResetEvent.cs
@@ -14,10 +14,8 @@
namespace System.Threading {
using System;
- using System.Security.Permissions;
using System.Runtime.InteropServices;
- [System.Runtime.InteropServices.ComVisible(true)]
public sealed class AutoResetEvent : EventWaitHandle
{
public AutoResetEvent(bool initialState) : base(initialState,EventResetMode.AutoReset){ }
diff --git a/src/mscorlib/src/System/Threading/CancellationToken.cs b/src/mscorlib/src/System/Threading/CancellationToken.cs
index 5b78f20900..b68ba4c046 100644
--- a/src/mscorlib/src/System/Threading/CancellationToken.cs
+++ b/src/mscorlib/src/System/Threading/CancellationToken.cs
@@ -9,7 +9,6 @@
using System;
using System.Runtime.InteropServices;
-using System.Security.Permissions;
using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Runtime;
@@ -38,7 +37,6 @@ namespace System.Threading
/// All members of this struct are thread-safe and may be used concurrently from multiple threads.
/// </para>
/// </remarks>
- [ComVisible(false)]
[DebuggerDisplay("IsCancellationRequested = {IsCancellationRequested}")]
public struct CancellationToken
{
@@ -317,11 +315,8 @@ namespace System.Threading
}
// the real work..
- [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(nameof(callback));
@@ -341,8 +336,7 @@ namespace System.Threading
if (useSynchronizationContext)
capturedSyncContext = SynchronizationContext.Current;
if (useExecutionContext)
- capturedExecutionContext = ExecutionContext.Capture(
- ref stackMark, ExecutionContext.CaptureOptions.OptimizeDefaultCase); // ideally we'd also use IgnoreSyncCtx, but that could break compat
+ capturedExecutionContext = ExecutionContext.Capture();
}
// Register the callback with the source.
diff --git a/src/mscorlib/src/System/Threading/CancellationTokenRegistration.cs b/src/mscorlib/src/System/Threading/CancellationTokenRegistration.cs
index ac27fe30e6..89e98fa3c8 100644
--- a/src/mscorlib/src/System/Threading/CancellationTokenRegistration.cs
+++ b/src/mscorlib/src/System/Threading/CancellationTokenRegistration.cs
@@ -6,7 +6,6 @@
////////////////////////////////////////////////////////////////////////////////
using System.Diagnostics.Contracts;
-using System.Security.Permissions;
using System.Runtime.CompilerServices;
namespace System.Threading
diff --git a/src/mscorlib/src/System/Threading/CancellationTokenSource.cs b/src/mscorlib/src/System/Threading/CancellationTokenSource.cs
index fe9e0dec76..1e70d6f30f 100644
--- a/src/mscorlib/src/System/Threading/CancellationTokenSource.cs
+++ b/src/mscorlib/src/System/Threading/CancellationTokenSource.cs
@@ -10,7 +10,6 @@ using System;
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 +34,6 @@ namespace System.Threading
/// concurrently from multiple threads.
/// </para>
/// </remarks>
- [ComVisible(false)]
public class CancellationTokenSource : IDisposable
{
@@ -864,12 +862,19 @@ namespace System.Threading
/// <param name="token2">The second <see cref="T:System.Threading.CancellationToken">CancellationToken</see> to observe.</param>
/// <returns>A <see cref="T:System.Threading.CancellationTokenSource">CancellationTokenSource</see> that is linked
/// to the source tokens.</returns>
- public static CancellationTokenSource CreateLinkedTokenSource(CancellationToken token1, CancellationToken token2)
- {
- return token1.CanBeCanceled || token2.CanBeCanceled ?
- new LinkedCancellationTokenSource(token1, token2) :
- new CancellationTokenSource();
- }
+ public static CancellationTokenSource CreateLinkedTokenSource(CancellationToken token1, CancellationToken token2) =>
+ !token1.CanBeCanceled ? CreateLinkedTokenSource(token2) :
+ token2.CanBeCanceled ? new Linked2CancellationTokenSource(token1, token2) :
+ (CancellationTokenSource)new Linked1CancellationTokenSource(token1);
+
+ /// <summary>
+ /// Creates a <see cref="CancellationTokenSource"/> that will be in the canceled state
+ /// when any of the source tokens are in the canceled state.
+ /// </summary>
+ /// <param name="token">The first <see cref="T:System.Threading.CancellationToken">CancellationToken</see> to observe.</param>
+ /// <returns>A <see cref="CancellationTokenSource"/> that is linked to the source tokens.</returns>
+ internal static CancellationTokenSource CreateLinkedTokenSource(CancellationToken token) =>
+ token.CanBeCanceled ? new Linked1CancellationTokenSource(token) : new CancellationTokenSource();
/// <summary>
/// Creates a <see cref="T:System.Threading.CancellationTokenSource">CancellationTokenSource</see> that will be in the canceled state
@@ -884,14 +889,19 @@ namespace System.Threading
if (tokens == null)
throw new ArgumentNullException(nameof(tokens));
- if (tokens.Length == 0)
- throw new ArgumentException(Environment.GetResourceString("CancellationToken_CreateLinkedToken_TokensIsEmpty"));
-
- // a defensive copy is not required as the array has value-items that have only a single IntPtr field,
- // hence each item cannot be null itself, and reads of the payloads cannot be torn.
- Contract.EndContractBlock();
-
- return new LinkedCancellationTokenSource(tokens);
+ switch (tokens.Length)
+ {
+ case 0:
+ throw new ArgumentException(Environment.GetResourceString("CancellationToken_CreateLinkedToken_TokensIsEmpty"));
+ case 1:
+ return CreateLinkedTokenSource(tokens[0]);
+ case 2:
+ return CreateLinkedTokenSource(tokens[0], tokens[1]);
+ default:
+ // a defensive copy is not required as the array has value-items that have only a single reference field,
+ // hence each item cannot be null itself, and reads of the payloads cannot be torn.
+ return new LinkedNCancellationTokenSource(tokens);
+ }
}
@@ -907,35 +917,50 @@ namespace System.Threading
}
}
- private sealed class LinkedCancellationTokenSource : CancellationTokenSource
+ private sealed class Linked1CancellationTokenSource : CancellationTokenSource
{
- private static readonly Action<object> s_linkedTokenCancelDelegate =
- s => ((CancellationTokenSource)s).NotifyCancellation(throwOnFirstException: false); // skip ThrowIfDisposed() check in Cancel()
- private CancellationTokenRegistration[] m_linkingRegistrations;
+ private readonly CancellationTokenRegistration _reg1;
- internal LinkedCancellationTokenSource(CancellationToken token1, CancellationToken token2)
+ internal Linked1CancellationTokenSource(CancellationToken token1)
{
- bool token2CanBeCanceled = token2.CanBeCanceled;
+ _reg1 = token1.InternalRegisterWithoutEC(LinkedNCancellationTokenSource.s_linkedTokenCancelDelegate, this);
+ }
- if (token1.CanBeCanceled)
- {
- m_linkingRegistrations = new CancellationTokenRegistration[token2CanBeCanceled ? 2 : 1]; // there will be at least 1 and at most 2 linkings
- m_linkingRegistrations[0] = token1.InternalRegisterWithoutEC(s_linkedTokenCancelDelegate, this);
- }
+ protected override void Dispose(bool disposing)
+ {
+ if (!disposing || m_disposed) return;
+ _reg1.Dispose();
+ base.Dispose(disposing);
+ }
+ }
- if (token2CanBeCanceled)
- {
- int index = 1;
- if (m_linkingRegistrations == null)
- {
- m_linkingRegistrations = new CancellationTokenRegistration[1]; // this will be the only linking
- index = 0;
- }
- m_linkingRegistrations[index] = token2.InternalRegisterWithoutEC(s_linkedTokenCancelDelegate, this);
- }
+ private sealed class Linked2CancellationTokenSource : CancellationTokenSource
+ {
+ private readonly CancellationTokenRegistration _reg1;
+ private readonly CancellationTokenRegistration _reg2;
+
+ internal Linked2CancellationTokenSource(CancellationToken token1, CancellationToken token2)
+ {
+ _reg1 = token1.InternalRegisterWithoutEC(LinkedNCancellationTokenSource.s_linkedTokenCancelDelegate, this);
+ _reg2 = token2.InternalRegisterWithoutEC(LinkedNCancellationTokenSource.s_linkedTokenCancelDelegate, this);
}
- internal LinkedCancellationTokenSource(params CancellationToken[] tokens)
+ protected override void Dispose(bool disposing)
+ {
+ if (!disposing || m_disposed) return;
+ _reg1.Dispose();
+ _reg2.Dispose();
+ base.Dispose(disposing);
+ }
+ }
+
+ private sealed class LinkedNCancellationTokenSource : CancellationTokenSource
+ {
+ internal static readonly Action<object> s_linkedTokenCancelDelegate =
+ s => ((CancellationTokenSource)s).NotifyCancellation(throwOnFirstException: false); // skip ThrowIfDisposed() check in Cancel()
+ private CancellationTokenRegistration[] m_linkingRegistrations;
+
+ internal LinkedNCancellationTokenSource(params CancellationToken[] tokens)
{
m_linkingRegistrations = new CancellationTokenRegistration[tokens.Length];
@@ -968,7 +993,6 @@ namespace System.Threading
base.Dispose(disposing);
}
-
}
}
diff --git a/src/mscorlib/src/System/Threading/CountdownEvent.cs b/src/mscorlib/src/System/Threading/CountdownEvent.cs
index d86a2ccfb8..af055e347e 100644
--- a/src/mscorlib/src/System/Threading/CountdownEvent.cs
+++ b/src/mscorlib/src/System/Threading/CountdownEvent.cs
@@ -11,7 +11,6 @@
// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
using System;
-using System.Security.Permissions;
using System.Runtime.InteropServices;
using System.Threading;
using System.Diagnostics;
@@ -30,7 +29,6 @@ namespace System.Threading
/// completed, and Reset, which should only be used when no other threads are
/// accessing the event.
/// </remarks>
- [ComVisible(false)]
[DebuggerDisplay("Initial Count={InitialCount}, Current Count={CurrentCount}")]
public class CountdownEvent : IDisposable
{
diff --git a/src/mscorlib/src/System/Threading/EventWaitHandle.cs b/src/mscorlib/src/System/Threading/EventWaitHandle.cs
index 4b1611c6aa..0268948a5c 100644
--- a/src/mscorlib/src/System/Threading/EventWaitHandle.cs
+++ b/src/mscorlib/src/System/Threading/EventWaitHandle.cs
@@ -15,10 +15,10 @@
namespace System.Security.AccessControl
{
- public class EventWaitHandleSecurity
+ internal class EventWaitHandleSecurity
{
}
- public enum EventWaitHandleRights
+ internal enum EventWaitHandleRights
{
}
}
@@ -28,7 +28,6 @@ namespace System.Threading
using System;
using System.Threading;
using System.Runtime.CompilerServices;
- using System.Security.Permissions;
using System.IO;
using Microsoft.Win32;
using Microsoft.Win32.SafeHandles;
@@ -89,7 +88,7 @@ namespace System.Threading
{
}
- public unsafe EventWaitHandle(bool initialState, EventResetMode mode, string name, out bool createdNew, EventWaitHandleSecurity eventSecurity)
+ internal unsafe EventWaitHandle(bool initialState, EventResetMode mode, string name, out bool createdNew, EventWaitHandleSecurity eventSecurity)
{
if(name != null)
{
@@ -146,7 +145,7 @@ namespace System.Threading
return OpenExisting(name, (EventWaitHandleRights)0);
}
- public static EventWaitHandle OpenExisting(string name, EventWaitHandleRights rights)
+ internal static EventWaitHandle OpenExisting(string name, EventWaitHandleRights rights)
{
EventWaitHandle result;
switch (OpenExistingWorker(name, rights, out result))
@@ -171,11 +170,6 @@ namespace System.Threading
return OpenExistingWorker(name, (EventWaitHandleRights)0, out result) == OpenExistingResult.Success;
}
- public static bool TryOpenExisting(string name, EventWaitHandleRights rights, out EventWaitHandle result)
- {
- return OpenExistingWorker(name, rights, out result) == OpenExistingResult.Success;
- }
-
private static OpenExistingResult OpenExistingWorker(string name, EventWaitHandleRights rights, out EventWaitHandle result)
{
#if PLATFORM_UNIX
diff --git a/src/mscorlib/src/System/Threading/ExecutionContext.cs b/src/mscorlib/src/System/Threading/ExecutionContext.cs
index 5ea9942f65..47a55a3bb9 100644
--- a/src/mscorlib/src/System/Threading/ExecutionContext.cs
+++ b/src/mscorlib/src/System/Threading/ExecutionContext.cs
@@ -19,7 +19,6 @@ namespace System.Threading
using System.Reflection;
using System.Runtime.ExceptionServices;
using System.Runtime.Serialization;
- using System.Security.Permissions;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
using System.Runtime.ConstrainedExecution;
@@ -27,7 +26,6 @@ namespace System.Threading
using System.Diagnostics.Contracts;
using System.Diagnostics.CodeAnalysis;
- [System.Runtime.InteropServices.ComVisible(true)]
public delegate void ContextCallback(Object state);
internal struct ExecutionContextSwitcher
@@ -55,7 +53,7 @@ namespace System.Threading
[Serializable]
public sealed class ExecutionContext : IDisposable, ISerializable
{
- private static readonly ExecutionContext Default = new ExecutionContext();
+ internal static readonly ExecutionContext Default = new ExecutionContext();
private readonly IAsyncLocalValueMap m_localValues;
private readonly IAsyncLocal[] m_localChangeNotifications;
@@ -93,16 +91,10 @@ namespace System.Threading
public static ExecutionContext Capture()
{
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;
+ return
+ executionContext == null ? Default :
+ executionContext.m_isFlowSuppressed ? null :
+ executionContext;
}
private ExecutionContext ShallowClone(bool isFlowSuppressed)
@@ -301,38 +293,6 @@ namespace System.Threading
}
}
- #region Wrappers for CLR compat, to avoid ifdefs all over the BCL
-
- [Flags]
- internal enum CaptureOptions
- {
- None = 0x00,
- IgnoreSyncCtx = 0x01,
- OptimizeDefaultCase = 0x02,
- }
-
- internal static ExecutionContext Capture(ref StackCrawlMark stackMark, CaptureOptions captureOptions)
- {
- return Capture();
- }
-
- [FriendAccessAllowed]
- internal static ExecutionContext FastCapture()
- {
- return Capture();
- }
-
- [FriendAccessAllowed]
- internal static void Run(ExecutionContext executionContext, ContextCallback callback, Object state, bool preserveSyncCtx)
- {
- Run(executionContext, callback, state);
- }
-
- internal bool IsDefaultFTContext(bool ignoreSyncCtx)
- {
- return this == Default;
- }
-
public ExecutionContext CreateCopy()
{
return this; // since CoreCLR's ExecutionContext is immutable, we don't need to create copies.
@@ -342,18 +302,6 @@ namespace System.Threading
{
// For CLR compat only
}
-
- internal static ExecutionContext PreAllocatedDefault
- {
- get { return ExecutionContext.Default; }
- }
-
- internal bool IsPreAllocatedDefault
- {
- get { return this == ExecutionContext.Default; }
- }
-
- #endregion
}
public struct AsyncFlowControl : IDisposable
diff --git a/src/mscorlib/src/System/Threading/IObjectHandle.cs b/src/mscorlib/src/System/Threading/IObjectHandle.cs
deleted file mode 100644
index 464f06e52d..0000000000
--- a/src/mscorlib/src/System/Threading/IObjectHandle.cs
+++ /dev/null
@@ -1,31 +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.
-
-/*============================================================
-**
-**
-**
-** IObjectHandle defines the interface for unwrapping objects.
-** Objects that are marshal by value object can be returned through
-** an indirection allowing the caller to control when the
-** object is loaded into their domain. The caller can unwrap
-** the object from the indirection through this interface.
-**
-**
-===========================================================*/
-namespace System.Runtime.Remoting {
-
- using System;
- using System.Runtime.InteropServices;
-
- [ InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown),
- GuidAttribute("C460E2B4-E199-412a-8456-84DC3E4838C3") ]
- [System.Runtime.InteropServices.ComVisible(true)]
- public interface IObjectHandle {
- // Unwrap the object. Implementers of this interface
- // typically have an indirect referece to another object.
- Object Unwrap();
- }
-}
-
diff --git a/src/mscorlib/src/System/Threading/Interlocked.cs b/src/mscorlib/src/System/Threading/Interlocked.cs
index 8a0b527fc0..131d51a65b 100644
--- a/src/mscorlib/src/System/Threading/Interlocked.cs
+++ b/src/mscorlib/src/System/Threading/Interlocked.cs
@@ -6,7 +6,6 @@
namespace System.Threading
{
using System;
- using System.Security.Permissions;
using System.Runtime.CompilerServices;
using System.Runtime.ConstrainedExecution;
using System.Runtime.Versioning;
@@ -25,13 +24,11 @@ namespace System.Threading
* long
*****************************/
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
public static int Increment(ref int location)
{
return Add(ref location, 1);
}
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
public static long Increment(ref long location)
{
return Add(ref location, 1);
@@ -43,7 +40,6 @@ namespace System.Threading
* long
*****************************/
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
public static int Decrement(ref int location)
{
return Add(ref location, -1);
@@ -65,7 +61,6 @@ namespace System.Threading
*****************************/
[MethodImplAttribute(MethodImplOptions.InternalCall)]
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
public static extern int Exchange(ref int location1, int value);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
@@ -78,15 +73,11 @@ namespace System.Threading
public static extern double Exchange(ref double location1, double value);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
public static extern Object Exchange(ref Object location1, Object value);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
public static extern IntPtr Exchange(ref IntPtr location1, IntPtr value);
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
- [System.Runtime.InteropServices.ComVisible(false)]
public static T Exchange<T>(ref T location1, T value) where T : class
{
_Exchange(__makeref(location1), __makeref(value));
@@ -98,7 +89,6 @@ namespace System.Threading
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
private static extern void _Exchange(TypedReference location1, TypedReference value);
/******************************
@@ -112,7 +102,6 @@ namespace System.Threading
*****************************/
[MethodImplAttribute(MethodImplOptions.InternalCall)]
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
public static extern int CompareExchange(ref int location1, int value, int comparand);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
@@ -125,11 +114,9 @@ namespace System.Threading
public static extern double CompareExchange(ref double location1, double value, double comparand);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
public static extern Object CompareExchange(ref Object location1, Object value, Object comparand);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
public static extern IntPtr CompareExchange(ref IntPtr location1, IntPtr value, IntPtr comparand);
/*****************************************************************
@@ -156,8 +143,6 @@ namespace System.Threading
* for details.
*****************************************************************/
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
- [System.Runtime.InteropServices.ComVisible(false)]
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'
@@ -166,12 +151,10 @@ namespace System.Threading
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
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)]
internal static extern int CompareExchange(ref int location1, int value, int comparand, ref bool succeeded);
/******************************
@@ -181,19 +164,16 @@ namespace System.Threading
*****************************/
[MethodImplAttribute(MethodImplOptions.InternalCall)]
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
internal static extern int ExchangeAdd(ref int location1, int value);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern long ExchangeAdd(ref long location1, long value);
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
public static int Add(ref int location1, int value)
{
return ExchangeAdd(ref location1, value) + value;
}
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
public static long Add(ref long location1, long value)
{
return ExchangeAdd(ref location1, value) + value;
diff --git a/src/mscorlib/src/System/Threading/LazyInitializer.cs b/src/mscorlib/src/System/Threading/LazyInitializer.cs
index 238cc89dbd..af32673d03 100644
--- a/src/mscorlib/src/System/Threading/LazyInitializer.cs
+++ b/src/mscorlib/src/System/Threading/LazyInitializer.cs
@@ -11,7 +11,6 @@
// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
-using System.Security.Permissions;
using System.Diagnostics;
using System.Diagnostics.Contracts;
namespace System.Threading
diff --git a/src/mscorlib/src/System/Threading/LockCookie.cs b/src/mscorlib/src/System/Threading/LockCookie.cs
deleted file mode 100644
index c1fbfd828e..0000000000
--- a/src/mscorlib/src/System/Threading/LockCookie.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: Defines the lock that implements
-** single-writer/multiple-reader semantics
-**
-**
-===========================================================*/
-
-namespace System.Threading {
-
- using System;
- [System.Runtime.InteropServices.ComVisible(true)]
- public struct LockCookie
- {
- private int _dwFlags;
- private int _dwWriterSeqNum;
- private int _wReaderAndWriterLevel;
- private int _dwThreadID;
-
- public override int GetHashCode()
- {
- return _dwFlags + _dwWriterSeqNum + _wReaderAndWriterLevel + _dwThreadID;
- }
-
- public override bool Equals(Object obj)
- {
- if (obj is LockCookie)
- return Equals((LockCookie)obj);
- else
- return false;
- }
-
- public bool Equals(LockCookie obj)
- {
- return obj._dwFlags == _dwFlags && obj._dwWriterSeqNum == _dwWriterSeqNum &&
- obj._wReaderAndWriterLevel == _wReaderAndWriterLevel && obj._dwThreadID == _dwThreadID;
- }
-
- public static bool operator ==(LockCookie a, LockCookie b)
- {
- return a.Equals(b);
- }
-
- public static bool operator !=(LockCookie a, LockCookie b)
- {
- return !(a == b);
- }
- }
-}
-
diff --git a/src/mscorlib/src/System/Threading/LockRecursionException.cs b/src/mscorlib/src/System/Threading/LockRecursionException.cs
index ab95e70c7e..40f04b00b4 100644
--- a/src/mscorlib/src/System/Threading/LockRecursionException.cs
+++ b/src/mscorlib/src/System/Threading/LockRecursionException.cs
@@ -19,7 +19,6 @@ namespace System.Threading
using System.Runtime.CompilerServices;
[Serializable]
- [System.Security.Permissions.HostProtection(MayLeakOnAbort = true)]
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 00041567df..a8e012fb43 100644
--- a/src/mscorlib/src/System/Threading/ManualResetEvent.cs
+++ b/src/mscorlib/src/System/Threading/ManualResetEvent.cs
@@ -14,10 +14,8 @@
namespace System.Threading {
using System;
- using System.Security.Permissions;
using System.Runtime.InteropServices;
-[System.Runtime.InteropServices.ComVisible(true)]
public sealed class ManualResetEvent : EventWaitHandle
{
public ManualResetEvent(bool initialState) : base(initialState,EventResetMode.ManualReset){}
diff --git a/src/mscorlib/src/System/Threading/ManualResetEventSlim.cs b/src/mscorlib/src/System/Threading/ManualResetEventSlim.cs
index 509af5bfa0..2d57b4102b 100644
--- a/src/mscorlib/src/System/Threading/ManualResetEventSlim.cs
+++ b/src/mscorlib/src/System/Threading/ManualResetEventSlim.cs
@@ -13,7 +13,6 @@
// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
using System;
-using System.Security.Permissions;
using System.Threading;
using System.Runtime.InteropServices;
using System.Diagnostics;
@@ -45,7 +44,6 @@ namespace System.Threading
/// completed, and Reset, which should only be used when no other threads are
/// accessing the event.
/// </remarks>
- [ComVisible(false)]
[DebuggerDisplay("Set = {IsSet}")]
public class ManualResetEventSlim : IDisposable
{
diff --git a/src/mscorlib/src/System/Threading/Monitor.cs b/src/mscorlib/src/System/Threading/Monitor.cs
index 94dec13d05..fdbc384243 100644
--- a/src/mscorlib/src/System/Threading/Monitor.cs
+++ b/src/mscorlib/src/System/Threading/Monitor.cs
@@ -17,7 +17,6 @@
namespace System.Threading {
using System;
- using System.Security.Permissions;
using System.Runtime;
using System.Runtime.Remoting;
using System.Threading;
@@ -27,7 +26,6 @@ namespace System.Threading {
using System.Diagnostics;
using System.Diagnostics.Contracts;
- [System.Runtime.InteropServices.ComVisible(true)]
public static class Monitor
{
/*=========================================================================
@@ -76,7 +74,6 @@ namespace System.Threading {
** own the lock.
=========================================================================*/
[MethodImplAttribute(MethodImplOptions.InternalCall)]
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
public static extern void Exit(Object obj);
/*=========================================================================
diff --git a/src/mscorlib/src/System/Threading/Mutex.cs b/src/mscorlib/src/System/Threading/Mutex.cs
index 506abb7a07..dcb821307a 100644
--- a/src/mscorlib/src/System/Threading/Mutex.cs
+++ b/src/mscorlib/src/System/Threading/Mutex.cs
@@ -16,7 +16,6 @@ namespace System.Threading
using System;
using System.Threading;
using System.Runtime.CompilerServices;
- using System.Security.Permissions;
using System.IO;
using Microsoft.Win32;
using Microsoft.Win32.SafeHandles;
@@ -27,23 +26,20 @@ namespace System.Threading
using System.Diagnostics;
using System.Diagnostics.Contracts;
- [ComVisible(true)]
public sealed class Mutex : WaitHandle
{
static bool dummyBool;
- public class MutexSecurity
+ internal class MutexSecurity
{
}
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
public Mutex(bool initiallyOwned, String name, out bool createdNew)
: this(initiallyOwned, name, out createdNew, (MutexSecurity)null)
{
}
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
- public unsafe Mutex(bool initiallyOwned, String name, out bool createdNew, MutexSecurity mutexSecurity)
+ internal unsafe Mutex(bool initiallyOwned, String name, out bool createdNew, MutexSecurity mutexSecurity)
{
if (name == string.Empty)
{
@@ -62,26 +58,6 @@ namespace System.Threading
CreateMutexWithGuaranteedCleanup(initiallyOwned, name, out createdNew, secAttrs);
}
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
- internal Mutex(bool initiallyOwned, String name, out bool createdNew, Win32Native.SECURITY_ATTRIBUTES secAttrs)
- {
- if (name == string.Empty)
- {
- // Empty name is treated as an unnamed mutex. Set to null, and we will check for null from now on.
- name = null;
- }
-#if !PLATFORM_UNIX
- if (name != null && System.IO.Path.MaxPath < name.Length)
- {
- throw new ArgumentException(Environment.GetResourceString("Argument_WaitHandleNameTooLong", Path.MaxPath), nameof(name));
- }
-#endif
- Contract.EndContractBlock();
-
- CreateMutexWithGuaranteedCleanup(initiallyOwned, name, out createdNew, secAttrs);
- }
-
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
internal void CreateMutexWithGuaranteedCleanup(bool initiallyOwned, String name, out bool createdNew, Win32Native.SECURITY_ATTRIBUTES secAttrs)
{
RuntimeHelpers.CleanupCode cleanupCode = new RuntimeHelpers.CleanupCode(MutexCleanupCode);
@@ -104,7 +80,6 @@ namespace System.Threading
Win32Native.SECURITY_ATTRIBUTES m_secAttrs;
Mutex m_mutex;
- [PrePrepareMethod]
internal MutexTryCodeHelper(bool initiallyOwned,MutexCleanupInfo cleanupInfo, String name, Win32Native.SECURITY_ATTRIBUTES secAttrs, Mutex mutex)
{
Debug.Assert(name == null || name.Length != 0);
@@ -116,7 +91,6 @@ namespace System.Threading
m_mutex = mutex;
}
- [PrePrepareMethod]
internal void MutexTryCode(object userData)
{
SafeWaitHandle mutexHandle = null;
@@ -153,7 +127,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", PathInternal.MaxComponentLength), "name");
+ throw new ArgumentException(Environment.GetResourceString("Argument_WaitHandleNameTooLong", Interop.Sys.MaxName), "name");
#endif
case Win32Native.ERROR_INVALID_HANDLE:
@@ -170,7 +144,6 @@ namespace System.Threading
}
}
- [PrePrepareMethod]
private void MutexCleanupCode(Object userData, bool exceptionThrown)
{
MutexCleanupInfo cleanupInfo = (MutexCleanupInfo) userData;
@@ -198,21 +171,17 @@ namespace System.Threading
}
}
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
public Mutex(bool initiallyOwned, String name) : this(initiallyOwned, name, out dummyBool) {
}
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
public Mutex(bool initiallyOwned) : this(initiallyOwned, null, out dummyBool)
{
}
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
public Mutex() : this(false, null, out dummyBool)
{
}
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
private Mutex(SafeWaitHandle handle)
{
SetHandleInternal(handle);
@@ -224,11 +193,11 @@ namespace System.Threading
return OpenExisting(name, (MutexRights) 0);
}
- public enum MutexRights
+ internal enum MutexRights
{
}
- public static Mutex OpenExisting(string name, MutexRights rights)
+ internal static Mutex OpenExisting(string name, MutexRights rights)
{
Mutex result;
switch (OpenExistingWorker(name, rights, out result))
@@ -253,11 +222,6 @@ namespace System.Threading
return OpenExistingWorker(name, (MutexRights)0, out result) == OpenExistingResult.Success;
}
- public static bool TryOpenExisting(string name, MutexRights rights, out Mutex result)
- {
- return OpenExistingWorker(name, rights, out result) == OpenExistingResult.Success;
- }
-
private static OpenExistingResult OpenExistingWorker(string name, MutexRights rights, out Mutex result)
{
if (name == null)
@@ -294,7 +258,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", PathInternal.MaxComponentLength), nameof(name));
+ throw new ArgumentException(Environment.GetResourceString("Argument_WaitHandleNameTooLong", Interop.Sys.MaxName), nameof(name));
}
#endif
@@ -316,7 +280,6 @@ 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).
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
public void ReleaseMutex()
{
if (Win32Native.ReleaseMutex(safeWaitHandle))
@@ -324,11 +287,10 @@ namespace System.Threading
}
else
{
- throw new Exception(Environment.GetResourceString("Arg_SynchronizationLockException"));
+ throw new ApplicationException(Environment.GetResourceString("Arg_SynchronizationLockException"));
}
}
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
static int CreateMutexHandle(bool initiallyOwned, String name, Win32Native.SECURITY_ATTRIBUTES securityAttribute, out SafeWaitHandle mutexHandle)
{
int errorCode;
diff --git a/src/mscorlib/src/System/Threading/Overlapped.cs b/src/mscorlib/src/System/Threading/Overlapped.cs
index 2b192c7b3a..d3caff5e74 100644
--- a/src/mscorlib/src/System/Threading/Overlapped.cs
+++ b/src/mscorlib/src/System/Threading/Overlapped.cs
@@ -31,7 +31,6 @@ namespace System.Threading
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security;
- using System.Security.Permissions;
using System.Runtime.ConstrainedExecution;
using System.Diagnostics;
using System.Diagnostics.Contracts;
@@ -44,7 +43,6 @@ namespace System.Threading
// The first five matches OVERLAPPED structure.
// The remaining are reserved at the end
[System.Runtime.InteropServices.StructLayout(LayoutKind.Sequential)]
- [System.Runtime.InteropServices.ComVisible(true)]
public struct NativeOverlapped
{
public IntPtr InternalLow;
@@ -71,13 +69,11 @@ namespace System.Threading
{
}
- internal _IOCompletionCallback(IOCompletionCallback ioCompletionCallback, ref StackCrawlMark stackMark)
+ internal _IOCompletionCallback(IOCompletionCallback ioCompletionCallback)
{
_ioCompletionCallback = ioCompletionCallback;
// clone the exection context
- _executionContext = ExecutionContext.Capture(
- ref stackMark,
- ExecutionContext.CaptureOptions.IgnoreSyncCtx | ExecutionContext.CaptureOptions.OptimizeDefaultCase);
+ _executionContext = ExecutionContext.Capture();
}
// Context callback: same sig for SendOrPostCallback and ContextCallback
static internal ContextCallback _ccb = new ContextCallback(IOCompletionCallback_Context);
@@ -103,26 +99,23 @@ namespace System.Threading
overlapped = OverlappedData.GetOverlappedFromNative(pOVERLAP).m_overlapped;
helper = overlapped.iocbHelper;
- if (helper == null || helper._executionContext == null || helper._executionContext.IsDefaultFTContext(true))
- {
- // We got here because of UnsafePack (or) Pack with EC flow supressed
- IOCompletionCallback callback = overlapped.UserCallback;
- callback( errorCode, numBytes, pOVERLAP);
- }
- else
- {
- // We got here because of Pack
- helper._errorCode = errorCode;
- helper._numBytes = numBytes;
- helper._pOVERLAP = pOVERLAP;
- using (ExecutionContext executionContext = helper._executionContext.CreateCopy())
- ExecutionContext.Run(executionContext, _ccb, helper, true);
- }
-
- //Quickly check the VM again, to see if a packet has arrived.
-
+ if (helper == null || helper._executionContext == null || helper._executionContext == ExecutionContext.Default)
+ {
+ // We got here because of UnsafePack (or) Pack with EC flow supressed
+ IOCompletionCallback callback = overlapped.UserCallback;
+ callback( errorCode, numBytes, pOVERLAP);
+ }
+ else
+ {
+ // We got here because of Pack
+ helper._errorCode = errorCode;
+ helper._numBytes = numBytes;
+ helper._pOVERLAP = pOVERLAP;
+ ExecutionContext.Run(helper._executionContext, _ccb, helper);
+ }
+
+ //Quickly check the VM again, to see if a packet has arrived.
OverlappedData.CheckVMForIOPacket(out pOVERLAP, out errorCode, out numBytes);
-
} while (pOVERLAP != null);
}
@@ -174,17 +167,15 @@ namespace System.Threading
m_nativeOverlapped.InternalHigh = (IntPtr)0;
}
- [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
unsafe internal NativeOverlapped* Pack(IOCompletionCallback iocb, Object userData)
{
if (!m_pinSelf.IsNull()) {
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_Overlapped_Pack"));
}
- StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
if (iocb != null)
{
- m_iocbHelper = new _IOCompletionCallback(iocb, ref stackMark);
+ m_iocbHelper = new _IOCompletionCallback(iocb);
m_iocb = iocb;
}
else
@@ -229,7 +220,6 @@ namespace System.Threading
return AllocateNativeOverlapped();
}
- [ComVisible(false)]
internal IntPtr UserHandle
{
get { return m_nativeOverlapped.EventHandle; }
@@ -255,7 +245,6 @@ namespace System.Threading
#region class Overlapped
/// <internalonly/>
- [System.Runtime.InteropServices.ComVisible(true)]
public class Overlapped
{
private OverlappedData m_overlappedData;
@@ -307,7 +296,6 @@ namespace System.Threading
set { m_overlappedData.UserHandle = new IntPtr(value); }
}
- [ComVisible(false)]
public IntPtr EventHandleIntPtr
{
get { return m_overlappedData.UserHandle; }
@@ -336,7 +324,7 @@ namespace System.Threading
return Pack (iocb, null);
}
- [CLSCompliant(false),ComVisible(false)]
+ [CLSCompliant(false)]
unsafe public NativeOverlapped* Pack(IOCompletionCallback iocb, Object userData)
{
return m_overlappedData.Pack(iocb, userData);
@@ -349,7 +337,7 @@ namespace System.Threading
return UnsafePack (iocb, null);
}
- [CLSCompliant(false), ComVisible(false)]
+ [CLSCompliant(false)]
unsafe public NativeOverlapped* UnsafePack(IOCompletionCallback iocb, Object userData)
{
return m_overlappedData.UnsafePack(iocb, userData);
diff --git a/src/mscorlib/src/System/Threading/ParameterizedThreadStart.cs b/src/mscorlib/src/System/Threading/ParameterizedThreadStart.cs
index 45d24fef49..32b63153c4 100644
--- a/src/mscorlib/src/System/Threading/ParameterizedThreadStart.cs
+++ b/src/mscorlib/src/System/Threading/ParameterizedThreadStart.cs
@@ -15,7 +15,6 @@
namespace System.Threading {
- using System.Security.Permissions;
using System.Threading;
using System.Runtime.InteropServices;
diff --git a/src/mscorlib/src/System/Threading/ReaderWriterLock.cs b/src/mscorlib/src/System/Threading/ReaderWriterLock.cs
deleted file mode 100644
index e35ac7685b..0000000000
--- a/src/mscorlib/src/System/Threading/ReaderWriterLock.cs
+++ /dev/null
@@ -1,276 +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 lock that implements
-** single-writer/multiple-reader semantics
-**
-**
-===========================================================*/
-
-#if FEATURE_RWLOCK
-namespace System.Threading {
- using System.Threading;
- using System.Security.Permissions;
- using System.Runtime.Remoting;
- using System;
- using System.Runtime.CompilerServices;
- using System.Runtime.InteropServices;
- using System.Runtime.ConstrainedExecution;
- using System.Runtime.Versioning;
- using System.Diagnostics.Contracts;
-
- [ComVisible(true)]
- public sealed class ReaderWriterLock: CriticalFinalizerObject
- {
- /*
- * Constructor
- */
- public ReaderWriterLock()
- {
- PrivateInitialize();
- }
-
- /*
- * Destructor
- */
- ~ReaderWriterLock()
- {
- PrivateDestruct();
- }
-
- /*
- * Property that returns TRUE if the reader lock is held
- * by the current thread
- */
- public bool IsReaderLockHeld {
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
- get {
- return(PrivateGetIsReaderLockHeld());
- }
- }
-
- /*
- * Property that returns TRUE if the writer lock is held
- * by the current thread
- */
- public bool IsWriterLockHeld {
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
- get {
- return(PrivateGetIsWriterLockHeld());
- }
- }
-
- /*
- * Property that returns the current writer sequence number.
- * The caller should be a reader or writer for getting
- * meaningful results
- */
- public int WriterSeqNum {
- get {
- return(PrivateGetWriterSeqNum());
- }
- }
-
- /*
- * Acquires reader lock. The thread will block if a different
- * thread has writer lock.
- */
- [MethodImplAttribute(MethodImplOptions.InternalCall)]
- private extern void AcquireReaderLockInternal(int millisecondsTimeout);
-
- public void AcquireReaderLock(int millisecondsTimeout)
- {
- AcquireReaderLockInternal(millisecondsTimeout);
- }
-
-
- public void AcquireReaderLock(TimeSpan timeout)
- {
- long tm = (long)timeout.TotalMilliseconds;
- if (tm < -1 || tm > (long) Int32.MaxValue)
- throw new ArgumentOutOfRangeException(nameof(timeout), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegOrNegative1"));
- AcquireReaderLockInternal((int)tm);
- }
-
- /*
- * Acquires writer lock. The thread will block if a different
- * thread has reader lock. It will dead lock if this thread
- * has reader lock. Use UpgardeToWriterLock when you are not
- * sure if the thread has reader lock
- */
- [MethodImplAttribute(MethodImplOptions.InternalCall)]
- private extern void AcquireWriterLockInternal(int millisecondsTimeout);
-
- public void AcquireWriterLock(int millisecondsTimeout)
- {
- AcquireWriterLockInternal(millisecondsTimeout);
- }
-
- public void AcquireWriterLock(TimeSpan timeout)
- {
- long tm = (long)timeout.TotalMilliseconds;
- if (tm < -1 || tm > (long) Int32.MaxValue)
- throw new ArgumentOutOfRangeException(nameof(timeout), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegOrNegative1"));
- AcquireWriterLockInternal((int)tm);
- }
-
-
- /*
- * Releases reader lock.
- */
- [MethodImplAttribute(MethodImplOptions.InternalCall)]
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
- private extern void ReleaseReaderLockInternal();
-
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
- public void ReleaseReaderLock()
- {
- ReleaseReaderLockInternal();
- }
-
- /*
- * Releases writer lock.
- */
- [MethodImplAttribute(MethodImplOptions.InternalCall)]
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
- private extern void ReleaseWriterLockInternal();
-
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
- public void ReleaseWriterLock()
- {
- ReleaseWriterLockInternal();
- }
-
- /*
- * Upgardes the thread to a writer. If the thread has is a
- * reader, it is possible that the reader lock was
- * released before writer lock was acquired.
- */
- public LockCookie UpgradeToWriterLock(int millisecondsTimeout)
- {
- LockCookie result = new LockCookie ();
- FCallUpgradeToWriterLock (ref result, millisecondsTimeout);
- return result;
- }
-
- [MethodImplAttribute(MethodImplOptions.InternalCall)]
- private extern void FCallUpgradeToWriterLock(ref LockCookie result, int millisecondsTimeout);
-
- public LockCookie UpgradeToWriterLock(TimeSpan timeout)
- {
- long tm = (long)timeout.TotalMilliseconds;
- if (tm < -1 || tm > (long) Int32.MaxValue)
- throw new ArgumentOutOfRangeException(nameof(timeout), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegOrNegative1"));
- return UpgradeToWriterLock((int)tm);
- }
-
- /*
- * Restores the lock status of the thread to the one it was
- * in when it called UpgradeToWriterLock.
- */
- [MethodImplAttribute(MethodImplOptions.InternalCall)]
- private extern void DowngradeFromWriterLockInternal(ref LockCookie lockCookie);
-
- public void DowngradeFromWriterLock(ref LockCookie lockCookie)
- {
- DowngradeFromWriterLockInternal(ref lockCookie);
- }
-
- /*
- * Releases the lock irrespective of the number of times the thread
- * acquired the lock
- */
- public LockCookie ReleaseLock()
- {
- LockCookie result = new LockCookie ();
- FCallReleaseLock (ref result);
- return result;
- }
-
- [MethodImplAttribute(MethodImplOptions.InternalCall)]
- private extern void FCallReleaseLock(ref LockCookie result);
-
- /*
- * Restores the lock status of the thread to the one it was
- * in when it called ReleaseLock.
- */
- [MethodImplAttribute(MethodImplOptions.InternalCall)]
- private extern void RestoreLockInternal(ref LockCookie lockCookie);
-
- public void RestoreLock(ref LockCookie lockCookie)
- {
- RestoreLockInternal(ref lockCookie);
- }
-
- /*
- * Internal helper that returns TRUE if the reader lock is held
- * by the current thread
- */
- [MethodImplAttribute(MethodImplOptions.InternalCall)]
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
- private extern bool PrivateGetIsReaderLockHeld();
-
- /*
- * Internal helper that returns TRUE if the writer lock is held
- * by the current thread
- */
- [MethodImplAttribute(MethodImplOptions.InternalCall)]
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
- private extern bool PrivateGetIsWriterLockHeld();
-
- /*
- * Internal helper that returns the current writer sequence
- * number. The caller should be a reader or writer for getting
- * meaningful results
- */
- [MethodImplAttribute(MethodImplOptions.InternalCall)]
- private extern int PrivateGetWriterSeqNum();
-
- /*
- * Returns true if there were intermediate writes since the
- * sequence number was obtained. The caller should be
- * a reader or writer for getting meaningful results
- */
- [MethodImplAttribute(MethodImplOptions.InternalCall)]
- public extern bool AnyWritersSince(int seqNum);
-
- // Initialize state kept inside the lock
- [MethodImplAttribute(MethodImplOptions.InternalCall)]
- private extern void PrivateInitialize();
-
- // Destruct resource associated with the lock
- [MethodImplAttribute(MethodImplOptions.InternalCall)]
- private extern void PrivateDestruct();
-
- // State
-#pragma warning disable 169
-#pragma warning disable 414 // These fields are not used from managed.
- private IntPtr _hWriterEvent;
- private IntPtr _hReaderEvent;
- private IntPtr _hObjectHandle;
- private int _dwState = 0;
- private int _dwULockID = 0;
- private int _dwLLockID = 0;
- private int _dwWriterID = 0;
- private int _dwWriterSeqNum = 0;
- private short _wWriterLevel;
-#if RWLOCK_STATISTICS
- // WARNING: You must explicitly #define RWLOCK_STATISTICS when you
- // build in both the VM and BCL directories if you want this.
- private int _dwReaderEntryCount = 0;
- private int _dwReaderContentionCount = 0;
- private int _dwWriterEntryCount = 0;
- private int _dwWriterContentionCount = 0;
- private int _dwEventsReleasedCount = 0;
-#endif // RWLOCK_STATISTICS
-#pragma warning restore 414
-#pragma warning restore 169
- }
-}
-#endif //FEATURE_RWLOCK
diff --git a/src/mscorlib/src/System/Threading/SemaphoreSlim.cs b/src/mscorlib/src/System/Threading/SemaphoreSlim.cs
index 92d760d77d..c3b43d9585 100644
--- a/src/mscorlib/src/System/Threading/SemaphoreSlim.cs
+++ b/src/mscorlib/src/System/Threading/SemaphoreSlim.cs
@@ -16,7 +16,6 @@ using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Security;
-using System.Security.Permissions;
using System.Runtime.InteropServices;
using System.Diagnostics.Contracts;
using System.Threading.Tasks;
@@ -39,7 +38,6 @@ namespace System.Threading
/// completed.
/// </para>
/// </remarks>
- [ComVisible(false)]
[DebuggerDisplay("Current Count = {m_currentCount}")]
public class SemaphoreSlim : IDisposable
{
@@ -315,7 +313,7 @@ namespace System.Threading
if (millisecondsTimeout < -1)
{
throw new ArgumentOutOfRangeException(
- "totalMilliSeconds", millisecondsTimeout, GetResourceString("SemaphoreSlim_Wait_TimeoutWrong"));
+ nameof(millisecondsTimeout), millisecondsTimeout, GetResourceString("SemaphoreSlim_Wait_TimeoutWrong"));
}
cancellationToken.ThrowIfCancellationRequested();
@@ -609,7 +607,7 @@ namespace System.Threading
if (millisecondsTimeout < -1)
{
throw new ArgumentOutOfRangeException(
- "totalMilliSeconds", millisecondsTimeout, GetResourceString("SemaphoreSlim_Wait_TimeoutWrong"));
+ nameof(millisecondsTimeout), millisecondsTimeout, GetResourceString("SemaphoreSlim_Wait_TimeoutWrong"));
}
// Bail early for cancellation
diff --git a/src/mscorlib/src/System/Threading/SpinLock.cs b/src/mscorlib/src/System/Threading/SpinLock.cs
index 1d90890d6e..eee73ce2bf 100644
--- a/src/mscorlib/src/System/Threading/SpinLock.cs
+++ b/src/mscorlib/src/System/Threading/SpinLock.cs
@@ -9,19 +9,14 @@
// repeatedly checking until the lock becomes available. As the thread remains active performing a non-useful task,
// the use of such a lock is a kind of busy waiting and consumes CPU resources without performing real work.
//
-//
// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
-using System;
-using System.Security.Permissions;
+
+using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
-using System.Runtime.ConstrainedExecution;
-using System.Diagnostics;
-using System.Diagnostics.Contracts;
namespace System.Threading
{
-
/// <summary>
/// Provides a mutual exclusion lock primitive where a thread trying to acquire the lock waits in a loop
/// repeatedly checking until the lock becomes available.
@@ -54,7 +49,6 @@ namespace System.Threading
/// concurrently.
/// </para>
/// </remarks>
- [ComVisible(false)]
[DebuggerTypeProxy(typeof(SystemThreading_SpinLockDebugView))]
[DebuggerDisplay("IsHeld = {IsHeld}")]
public struct SpinLock
@@ -106,6 +100,14 @@ namespace System.Threading
// The waiters count is calculated by m_owner & WAITERS_MASK 01111....110
private static int MAXIMUM_WAITERS = WAITERS_MASK;
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ private int CompareExchange(ref int location, int value, int comparand, ref bool success)
+ {
+ int result = Interlocked.CompareExchange(ref location, value, comparand);
+ success = (result == comparand);
+ return result;
+ }
+
/// <summary>
/// Initializes a new instance of the <see cref="T:System.Threading.SpinLock"/>
/// structure with the option to track thread IDs to improve debugging.
@@ -158,9 +160,8 @@ namespace System.Threading
int observedOwner = m_owner;
if (lockTaken || //invalid parameter
(observedOwner & ID_DISABLED_AND_ANONYMOUS_OWNED) != LOCK_ID_DISABLE_MASK || //thread tracking is enabled or the lock is already acquired
- Interlocked.CompareExchange(ref m_owner, observedOwner | LOCK_ANONYMOUS_OWNED, observedOwner, ref lockTaken) != observedOwner) //acquiring the lock failed
+ CompareExchange(ref m_owner, observedOwner | LOCK_ANONYMOUS_OWNED, observedOwner, ref lockTaken) != observedOwner) //acquiring the lock failed
ContinueTryEnter(Timeout.Infinite, ref lockTaken); // Then try the slow path if any of the above conditions is met
-
}
/// <summary>
@@ -183,7 +184,22 @@ namespace System.Threading
/// </exception>
public void TryEnter(ref bool lockTaken)
{
- TryEnter(0, ref lockTaken);
+ int observedOwner = m_owner;
+ if (((observedOwner & LOCK_ID_DISABLE_MASK) == 0) | lockTaken)
+ {
+ // Thread tracking enabled or invalid arg. Take slow path.
+ ContinueTryEnter(0, ref lockTaken);
+ }
+ else if ((observedOwner & LOCK_ANONYMOUS_OWNED) != 0)
+ {
+ // Lock already held by someone
+ lockTaken = false;
+ }
+ else
+ {
+ // Lock wasn't held; try to acquire it.
+ CompareExchange(ref m_owner, observedOwner | LOCK_ANONYMOUS_OWNED, observedOwner, ref lockTaken);
+ }
}
/// <summary>
@@ -219,7 +235,7 @@ namespace System.Threading
if (totalMilliseconds < -1 || totalMilliseconds > int.MaxValue)
{
throw new System.ArgumentOutOfRangeException(
- nameof(timeout), timeout, Environment.GetResourceString("SpinLock_TryEnter_ArgumentOutOfRange"));
+ nameof(timeout), timeout, SR.SpinLock_TryEnter_ArgumentOutOfRange);
}
// Call reliable enter with the int-based timeout milliseconds
@@ -254,7 +270,7 @@ namespace System.Threading
if (millisecondsTimeout < -1 || //invalid parameter
lockTaken || //invalid parameter
(observedOwner & ID_DISABLED_AND_ANONYMOUS_OWNED) != LOCK_ID_DISABLE_MASK || //thread tracking is enabled or the lock is already acquired
- Interlocked.CompareExchange(ref m_owner, observedOwner | LOCK_ANONYMOUS_OWNED, observedOwner, ref lockTaken) != observedOwner) // acquiring the lock failed
+ CompareExchange(ref m_owner, observedOwner | LOCK_ANONYMOUS_OWNED, observedOwner, ref lockTaken) != observedOwner) // acquiring the lock failed
ContinueTryEnter(millisecondsTimeout, ref lockTaken); // The call the slow pth
}
@@ -271,13 +287,13 @@ namespace System.Threading
if (lockTaken)
{
lockTaken = false;
- throw new System.ArgumentException(Environment.GetResourceString("SpinLock_TryReliableEnter_ArgumentException"));
+ throw new System.ArgumentException(SR.SpinLock_TryReliableEnter_ArgumentException);
}
if (millisecondsTimeout < -1)
{
throw new ArgumentOutOfRangeException(
- nameof(millisecondsTimeout), millisecondsTimeout, Environment.GetResourceString("SpinLock_TryEnter_ArgumentOutOfRange"));
+ nameof(millisecondsTimeout), millisecondsTimeout, SR.SpinLock_TryEnter_ArgumentOutOfRange);
}
uint startTime = 0;
@@ -311,7 +327,7 @@ namespace System.Threading
observedOwner = m_owner;
if ((observedOwner & LOCK_ANONYMOUS_OWNED) == LOCK_UNOWNED)
{
- if (Interlocked.CompareExchange(ref m_owner, observedOwner | 1, observedOwner, ref lockTaken) == observedOwner)
+ if (CompareExchange(ref m_owner, observedOwner | 1, observedOwner, ref lockTaken) == observedOwner)
{
// Aquired lock
return;
@@ -331,7 +347,7 @@ namespace System.Threading
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
{
if ((observedOwner & WAITERS_MASK) != MAXIMUM_WAITERS)
- turn = (Interlocked.Add(ref m_owner, 2) & WAITERS_MASK) >> 1 ;
+ turn = (Interlocked.Add(ref m_owner, 2) & WAITERS_MASK) >> 1;
}
//***Step 2. Spinning
@@ -353,7 +369,7 @@ namespace System.Threading
: (observedOwner - 2) | 1; // otherwise decrement the waiters and set the lock bit
Debug.Assert((newOwner & WAITERS_MASK) >= 0);
- if (Interlocked.CompareExchange(ref m_owner, newOwner, observedOwner, ref lockTaken) == observedOwner)
+ if (CompareExchange(ref m_owner, newOwner, observedOwner, ref lockTaken) == observedOwner)
{
return;
}
@@ -381,7 +397,7 @@ namespace System.Threading
: (observedOwner - 2) | 1; // otherwise decrement the waiters and set the lock bit
Debug.Assert((newOwner & WAITERS_MASK) >= 0);
- if (Interlocked.CompareExchange(ref m_owner, newOwner, observedOwner, ref lockTaken) == observedOwner)
+ if (CompareExchange(ref m_owner, newOwner, observedOwner, ref lockTaken) == observedOwner)
{
return;
}
@@ -431,7 +447,6 @@ namespace System.Threading
}
spinner.SpinOnce();
}
-
}
/// <summary>
@@ -444,11 +459,11 @@ namespace System.Threading
int lockUnowned = 0;
// We are using thread IDs to mark ownership. Snap the thread ID and check for recursion.
// We also must or the ID enablement bit, to ensure we propagate when we CAS it in.
- int m_newOwner = Thread.CurrentThread.ManagedThreadId;
+ int m_newOwner = Environment.CurrentManagedThreadId;
if (m_owner == m_newOwner)
{
// We don't allow lock recursion.
- throw new LockRecursionException(Environment.GetResourceString("SpinLock_TryEnter_LockRecursionException"));
+ throw new LockRecursionException(SR.SpinLock_TryEnter_LockRecursionException);
}
@@ -457,7 +472,6 @@ namespace System.Threading
// Loop until the lock has been successfully acquired or, if specified, the timeout expires.
do
{
-
// We failed to get the lock, either from the fast route or the last iteration
// and the timeout hasn't expired; spin once and try again.
spinner.SpinOnce();
@@ -466,7 +480,7 @@ namespace System.Threading
if (m_owner == lockUnowned)
{
- if (Interlocked.CompareExchange(ref m_owner, m_newOwner, lockUnowned, ref lockTaken) == lockUnowned)
+ if (CompareExchange(ref m_owner, m_newOwner, lockUnowned, ref lockTaken) == lockUnowned)
{
return;
}
@@ -491,7 +505,6 @@ namespace System.Threading
/// <exception cref="SynchronizationLockException">
/// Thread ownership tracking is enabled, and the current thread is not the owner of this lock.
/// </exception>
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
public void Exit()
{
//This is the fast path for the thread tracking is disabled, otherwise go to the slow path
@@ -517,15 +530,14 @@ namespace System.Threading
/// <exception cref="SynchronizationLockException">
/// Thread ownership tracking is enabled, and the current thread is not the owner of this lock.
/// </exception>
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
public void Exit(bool useMemoryBarrier)
{
// This is the fast path for the thread tracking is diabled and not to use memory barrier, otherwise go to the slow path
// The reason not to add else statement if the usememorybarrier is that it will add more barnching in the code and will prevent
- // method inlining, so this is optimized for useMemoryBarrier=false and Exit() overload optimized for useMemoryBarrier=true
- if ((m_owner & LOCK_ID_DISABLE_MASK) != 0 && !useMemoryBarrier)
+ // method inlining, so this is optimized for useMemoryBarrier=false and Exit() overload optimized for useMemoryBarrier=true.
+ int tmpOwner = m_owner;
+ if ((tmpOwner & LOCK_ID_DISABLE_MASK) != 0 & !useMemoryBarrier)
{
- int tmpOwner = m_owner;
m_owner = tmpOwner & (~LOCK_ANONYMOUS_OWNED);
}
else
@@ -545,7 +557,7 @@ namespace System.Threading
if (threadTrackingEnabled && !IsHeldByCurrentThread)
{
throw new System.Threading.SynchronizationLockException(
- Environment.GetResourceString("SpinLock_Exit_SynchronizationLockException"));
+ SR.SpinLock_Exit_SynchronizationLockException);
}
if (useMemoryBarrier)
@@ -554,7 +566,6 @@ namespace System.Threading
Interlocked.Exchange(ref m_owner, LOCK_UNOWNED);
else
Interlocked.Decrement(ref m_owner);
-
}
else
{
@@ -565,9 +576,7 @@ namespace System.Threading
int tmpOwner = m_owner;
m_owner = tmpOwner & (~LOCK_ANONYMOUS_OWNED);
}
-
}
-
}
/// <summary>
@@ -575,7 +584,6 @@ namespace System.Threading
/// </summary>
public bool IsHeld
{
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
get
{
if (IsThreadOwnerTrackingEnabled)
@@ -601,21 +609,19 @@ namespace System.Threading
/// </exception>
public bool IsHeldByCurrentThread
{
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
get
{
if (!IsThreadOwnerTrackingEnabled)
{
- throw new InvalidOperationException(Environment.GetResourceString("SpinLock_IsHeldByCurrentThread"));
+ throw new InvalidOperationException(SR.SpinLock_IsHeldByCurrentThread);
}
- return ((m_owner & (~LOCK_ID_DISABLE_MASK)) == Thread.CurrentThread.ManagedThreadId);
+ return ((m_owner & (~LOCK_ID_DISABLE_MASK)) == Environment.CurrentManagedThreadId);
}
}
/// <summary>Gets whether thread ownership tracking is enabled for this instance.</summary>
public bool IsThreadOwnerTrackingEnabled
{
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
get { return (m_owner & LOCK_ID_DISABLE_MASK) == 0; }
}
diff --git a/src/mscorlib/src/System/Threading/SpinWait.cs b/src/mscorlib/src/System/Threading/SpinWait.cs
index 1b31407e0f..8431f6564f 100644
--- a/src/mscorlib/src/System/Threading/SpinWait.cs
+++ b/src/mscorlib/src/System/Threading/SpinWait.cs
@@ -12,7 +12,6 @@
using System;
using System.Runtime.ConstrainedExecution;
-using System.Security.Permissions;
using System.Threading;
using System.Diagnostics;
using System.Diagnostics.Contracts;
diff --git a/src/mscorlib/src/System/Threading/SynchronizationContext.cs b/src/mscorlib/src/System/Threading/SynchronizationContext.cs
index 5531597229..f4b3c79409 100644
--- a/src/mscorlib/src/System/Threading/SynchronizationContext.cs
+++ b/src/mscorlib/src/System/Threading/SynchronizationContext.cs
@@ -13,12 +13,9 @@
namespace System.Threading
{
using Microsoft.Win32.SafeHandles;
- using System.Security.Permissions;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
-#if FEATURE_CORRUPTING_EXCEPTIONS
using System.Runtime.ExceptionServices;
-#endif // FEATURE_CORRUPTING_EXCEPTIONS
using System.Runtime;
using System.Runtime.Versioning;
using System.Runtime.ConstrainedExecution;
@@ -29,14 +26,12 @@ namespace System.Threading
using System.Diagnostics.CodeAnalysis;
-#if FEATURE_SYNCHRONIZATIONCONTEXT_WAIT
[Flags]
enum SynchronizationContextProperties
{
None = 0,
RequireWaitNotification = 0x1
};
-#endif
#if FEATURE_COMINTEROP && FEATURE_APPX
//
@@ -52,15 +47,12 @@ namespace System.Threading
public class SynchronizationContext
{
-#if FEATURE_SYNCHRONIZATIONCONTEXT_WAIT
SynchronizationContextProperties _props = SynchronizationContextProperties.None;
-#endif
public SynchronizationContext()
{
}
-#if FEATURE_SYNCHRONIZATIONCONTEXT_WAIT
// helper delegate to statically bind to Wait method
private delegate int WaitDelegate(IntPtr[] waitHandles, bool waitAll, int millisecondsTimeout);
@@ -109,7 +101,6 @@ namespace System.Threading
{
return ((_props & SynchronizationContextProperties.RequireWaitNotification) != 0);
}
-#endif
public virtual void Send(SendOrPostCallback d, Object state)
@@ -137,10 +128,8 @@ namespace System.Threading
{
}
-#if FEATURE_SYNCHRONIZATIONCONTEXT_WAIT
// 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);
@@ -148,8 +137,6 @@ namespace System.Threading
// 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)
@@ -164,22 +151,14 @@ namespace System.Threading
// Static helper to which the above method can delegate to in order to get the default
// COM behavior.
[CLSCompliant(false)]
- [PrePrepareMethod]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
private static extern int WaitHelperNative(IntPtr[] waitHandles, bool waitAll, int millisecondsTimeout);
-#endif
public static void SetSynchronizationContext(SynchronizationContext syncContext)
{
Thread.CurrentThread.SynchronizationContext = syncContext;
}
- public static void SetThreadStaticContext(SynchronizationContext syncContext)
- {
- Thread.CurrentThread.SynchronizationContext = syncContext;
- }
-
public static SynchronizationContext Current
{
get
@@ -260,11 +239,9 @@ namespace System.Threading
return new SynchronizationContext();
}
-#if FEATURE_SYNCHRONIZATIONCONTEXT_WAIT
private static int InvokeWaitMethodHelper(SynchronizationContext syncContext, IntPtr[] waitHandles, bool waitAll, int millisecondsTimeout)
{
return syncContext.Wait(waitHandles, waitAll, millisecondsTimeout);
}
-#endif
}
}
diff --git a/src/mscorlib/src/System/Threading/SynchronizationLockException.cs b/src/mscorlib/src/System/Threading/SynchronizationLockException.cs
index 0610a6063d..de42c1f232 100644
--- a/src/mscorlib/src/System/Threading/SynchronizationLockException.cs
+++ b/src/mscorlib/src/System/Threading/SynchronizationLockException.cs
@@ -17,7 +17,6 @@ namespace System.Threading {
using System;
using System.Runtime.Serialization;
- [System.Runtime.InteropServices.ComVisible(true)]
[Serializable]
public class SynchronizationLockException : SystemException {
public SynchronizationLockException()
diff --git a/src/mscorlib/src/System/Threading/Tasks/BeginEndAwaitableAdapter.cs b/src/mscorlib/src/System/Threading/Tasks/BeginEndAwaitableAdapter.cs
deleted file mode 100644
index 71eb787c5e..0000000000
--- a/src/mscorlib/src/System/Threading/Tasks/BeginEndAwaitableAdapter.cs
+++ /dev/null
@@ -1,157 +0,0 @@
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-// See the LICENSE file in the project root for more information.
-
-using System;
-using System.Diagnostics;
-using System.Diagnostics.Contracts;
-using System.IO;
-using System.Runtime.CompilerServices;
-using System.Security;
-using System.Threading;
-using System.Threading.Tasks;
-
-namespace System.Threading.Tasks {
-
-/// <summary>
-/// Provides an adapter to make Begin/End pairs awaitable.
-/// In general, Task.Factory.FromAsync should be used for this purpose.
-/// However, for cases where absolute minimal overhead is required, this type
-/// may be used to making APM pairs awaitable while minimizing overhead.
-/// (APM = Asynchronous Programming Model or the Begin/End pattern.)
-/// </summary>
-/// <remarks>
-/// This instance may be reused repeatedly. However, it must only be used
-/// by a single APM invocation at a time. It's state will automatically be reset
-/// when the await completes.
-/// </remarks>
-/// <example>
-/// Usage sample:
-/// <code>
-/// static async Task CopyStreamAsync(Stream source, Stream dest) {
-///
-/// BeginEndAwaitableAdapter adapter = new BeginEndAwaitableAdapter();
-/// Byte[] buffer = new Byte[0x1000];
-///
-/// while (true) {
-///
-/// source.BeginRead(buffer, 0, buffer.Length, BeginEndAwaitableAdapter.Callback, adapter);
-/// Int32 numRead = source.EndRead(await adapter);
-/// if (numRead == 0)
-/// break;
-///
-/// dest.BeginWrite(buffer, 0, numRead, BeginEndAwaitableAdapter.Callback, adapter);
-/// dest.EndWrite(await adapter);
-/// }
-/// }
-/// </code>
-/// </example>
-internal sealed class BeginEndAwaitableAdapter : ICriticalNotifyCompletion {
-
- /// <summary>A sentinel marker used to communicate between OnCompleted and the APM callback
- /// that the callback has already run, and thus OnCompleted needs to execute the callback.</summary>
- private readonly static Action CALLBACK_RAN = () => { };
-
- /// <summary>The IAsyncResult for the APM operation.</summary>
- private IAsyncResult _asyncResult;
-
- /// <summary>The continuation delegate provided to the awaiter.</summary>
- private Action _continuation;
-
-
- /// <summary>A callback to be passed as the AsyncCallback to an APM pair.
- /// It expects that an BeginEndAwaitableAdapter instance was supplied to the APM Begin method as the object state.</summary>
- public readonly static AsyncCallback Callback = (asyncResult) => {
-
- 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;
-
- // Store the IAsyncResult into it so that it's available to the awaiter
- adapter._asyncResult = asyncResult;
-
- // If the _continuation has already been set to the actual continuation by OnCompleted, then invoke the continuation.
- // Set _continuation to the CALLBACK_RAN sentinel so that IsCompleted returns true and OnCompleted sees the sentinel
- // and knows to invoke the callback.
- // Due to some known incorrect implementations of IAsyncResult in the Framework where CompletedSynchronously is lazily
- // set to true if it is first invoked after IsCompleted is true, we cannot rely here on CompletedSynchronously for
- // synchronization between the caller and the callback, and thus do not use CompletedSynchronously at all.
- Action continuation = Interlocked.Exchange(ref adapter._continuation, CALLBACK_RAN);
- if (continuation != null) {
-
- Debug.Assert(continuation != CALLBACK_RAN);
- continuation();
- }
- };
-
-
- /// <summary>Gets an awaiter.</summary>
- /// <returns>Returns itself as the awaiter.</returns>
- public BeginEndAwaitableAdapter GetAwaiter() {
-
- return this;
- }
-
-
- /// <summary>Gets whether the awaited APM operation completed.</summary>
- public bool IsCompleted {
- get {
-
- // We are completed if the callback was called and it set the continuation to the CALLBACK_RAN sentinel.
- // If the operation completes asynchronously, there's still a chance we'll see CALLBACK_RAN here, in which
- // case we're still good to keep running synchronously.
- return (_continuation == CALLBACK_RAN);
- }
- }
-
- /// <summary>Schedules the continuation to run when the operation completes.</summary>
- /// <param name="continuation">The continuation.</param>
- public void UnsafeOnCompleted(Action continuation) {
-
- Debug.Assert(continuation != null);
- OnCompleted(continuation);
- }
-
-
- /// <summary>Schedules the continuation to run when the operation completes.</summary>
- /// <param name="continuation">The continuation.</param>
- public void OnCompleted(Action continuation) {
-
- 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,
- // it was already set to the CALLBACK_RAN-sentinel by the Callback, in which case we hit a very rare race condition
- // where the operation didn't complete synchronously but completed asynchronously between our
- // calls to IsCompleted and OnCompleted... in that case, just schedule a task to run the continuation.
- if (_continuation == CALLBACK_RAN
- || Interlocked.CompareExchange(ref _continuation, continuation, null) == CALLBACK_RAN) {
-
- Task.Run(continuation); // must run async at this point, or else we'd risk stack diving
- }
- }
-
-
- /// <summary>Gets the IAsyncResult for the APM operation after the operation completes, and then resets the adapter.</summary>
- /// <returns>The IAsyncResult for the operation.</returns>
- public IAsyncResult GetResult() {
-
- Debug.Assert(_asyncResult != null && _asyncResult.IsCompleted);
-
- // Get the IAsyncResult
- IAsyncResult result = _asyncResult;
-
- // Reset the adapter
- _asyncResult = null;
- _continuation = null;
-
- // Return the result
- return result;
- }
-
-} // class BeginEndAwaitableAdapter
-
-} // namespace
diff --git a/src/mscorlib/src/System/Threading/Tasks/ConcurrentExclusiveSchedulerPair.cs b/src/mscorlib/src/System/Threading/Tasks/ConcurrentExclusiveSchedulerPair.cs
index c7a96b0394..a87406a493 100644
--- a/src/mscorlib/src/System/Threading/Tasks/ConcurrentExclusiveSchedulerPair.cs
+++ b/src/mscorlib/src/System/Threading/Tasks/ConcurrentExclusiveSchedulerPair.cs
@@ -20,7 +20,6 @@ using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Diagnostics.Contracts;
using System.Security;
-using System.Security.Permissions;
namespace System.Threading.Tasks
{
diff --git a/src/mscorlib/src/System/Threading/Tasks/FutureFactory.cs b/src/mscorlib/src/System/Threading/Tasks/FutureFactory.cs
index c98e219e86..137afa11f5 100644
--- a/src/mscorlib/src/System/Threading/Tasks/FutureFactory.cs
+++ b/src/mscorlib/src/System/Threading/Tasks/FutureFactory.cs
@@ -12,7 +12,6 @@
using System;
using System.Security;
-using System.Security.Permissions;
using System.Runtime.CompilerServices;
using System.Threading;
using System.Diagnostics;
@@ -277,13 +276,11 @@ namespace System.Threading.Tasks
/// However, unless creation and scheduling must be separated, StartNew is the recommended approach
/// for both simplicity and performance.
/// </remarks>
- [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var have to be marked non-inlineable
public Task<TResult> StartNew(Func<TResult> function)
{
- StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
Task currTask = Task.InternalCurrent;
return Task<TResult>.StartNew(currTask, function, m_defaultCancellationToken,
- m_defaultCreationOptions, InternalTaskOptions.None, GetDefaultScheduler(currTask), ref stackMark);
+ m_defaultCreationOptions, InternalTaskOptions.None, GetDefaultScheduler(currTask));
}
/// <summary>
@@ -306,13 +303,11 @@ namespace System.Threading.Tasks
/// However, unless creation and scheduling must be separated, StartNew is the recommended approach
/// for both simplicity and performance.
/// </remarks>
- [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var have to be marked non-inlineable
public Task<TResult> StartNew(Func<TResult> function, CancellationToken cancellationToken)
{
- StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
Task currTask = Task.InternalCurrent;
return Task<TResult>.StartNew(currTask, function, cancellationToken,
- m_defaultCreationOptions, InternalTaskOptions.None, GetDefaultScheduler(currTask), ref stackMark);
+ m_defaultCreationOptions, InternalTaskOptions.None, GetDefaultScheduler(currTask));
}
/// <summary>
@@ -337,13 +332,11 @@ namespace System.Threading.Tasks
/// However, unless creation and scheduling must be separated, StartNew is the recommended approach
/// for both simplicity and performance.
/// </remarks>
- [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var have to be marked non-inlineable
public Task<TResult> StartNew(Func<TResult> function, TaskCreationOptions creationOptions)
{
- StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
Task currTask = Task.InternalCurrent;
return Task<TResult>.StartNew(currTask, function, m_defaultCancellationToken,
- creationOptions, InternalTaskOptions.None, GetDefaultScheduler(currTask), ref stackMark);
+ creationOptions, InternalTaskOptions.None, GetDefaultScheduler(currTask));
}
/// <summary>
@@ -379,13 +372,11 @@ namespace System.Threading.Tasks
/// However, unless creation and scheduling must be separated, StartNew is the recommended approach
/// for both simplicity and performance.
/// </remarks>
- [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var have to be marked non-inlineable
public Task<TResult> StartNew(Func<TResult> function, CancellationToken cancellationToken, TaskCreationOptions creationOptions, TaskScheduler scheduler)
{
- StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
return Task<TResult>.StartNew(
Task.InternalCurrentIfAttached(creationOptions), function, cancellationToken,
- creationOptions, InternalTaskOptions.None, scheduler, ref stackMark);
+ creationOptions, InternalTaskOptions.None, scheduler);
}
/// <summary>
@@ -406,13 +397,11 @@ namespace System.Threading.Tasks
/// However, unless creation and scheduling must be separated, StartNew is the recommended approach
/// for both simplicity and performance.
/// </remarks>
- [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var have to be marked non-inlineable
public Task<TResult> StartNew(Func<Object, TResult> function, Object state)
{
- StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
Task currTask = Task.InternalCurrent;
return Task<TResult>.StartNew(currTask, function, state, m_defaultCancellationToken,
- m_defaultCreationOptions, InternalTaskOptions.None, GetDefaultScheduler(currTask), ref stackMark);
+ m_defaultCreationOptions, InternalTaskOptions.None, GetDefaultScheduler(currTask));
}
/// <summary>
@@ -437,13 +426,11 @@ namespace System.Threading.Tasks
/// However, unless creation and scheduling must be separated, StartNew is the recommended approach
/// for both simplicity and performance.
/// </remarks>
- [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var have to be marked non-inlineable
public Task<TResult> StartNew(Func<Object, TResult> function, Object state, CancellationToken cancellationToken)
{
- StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
Task currTask = Task.InternalCurrent;
return Task<TResult>.StartNew(currTask, function, state, cancellationToken,
- m_defaultCreationOptions, InternalTaskOptions.None, GetDefaultScheduler(currTask), ref stackMark);
+ m_defaultCreationOptions, InternalTaskOptions.None, GetDefaultScheduler(currTask));
}
/// <summary>
@@ -470,13 +457,11 @@ namespace System.Threading.Tasks
/// However, unless creation and scheduling must be separated, StartNew is the recommended approach
/// for both simplicity and performance.
/// </remarks>
- [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var have to be marked non-inlineable
public Task<TResult> StartNew(Func<Object, TResult> function, Object state, TaskCreationOptions creationOptions)
{
- StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
Task currTask = Task.InternalCurrent;
return Task<TResult>.StartNew(currTask, function, state, m_defaultCancellationToken,
- creationOptions, InternalTaskOptions.None, GetDefaultScheduler(currTask), ref stackMark);
+ creationOptions, InternalTaskOptions.None, GetDefaultScheduler(currTask));
}
/// <summary>
@@ -514,12 +499,10 @@ namespace System.Threading.Tasks
/// However, unless creation and scheduling must be separated, StartNew is the recommended approach
/// for both simplicity and performance.
/// </remarks>
- [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var have to be marked non-inlineable
public Task<TResult> StartNew(Func<Object, TResult> function, Object state, CancellationToken cancellationToken, TaskCreationOptions creationOptions, TaskScheduler scheduler)
{
- StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
return Task<TResult>.StartNew(Task.InternalCurrentIfAttached(creationOptions), function, state, cancellationToken,
- creationOptions, InternalTaskOptions.None, scheduler, ref stackMark);
+ creationOptions, InternalTaskOptions.None, scheduler);
}
//
@@ -604,11 +587,9 @@ namespace System.Threading.Tasks
/// <paramref name="endMethod"/> argument is null.</exception>
/// <returns>A <see cref="T:System.Threading.Tasks.Task{TResult}">Task</see> that represents the
/// asynchronous operation.</returns>
- [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var have to be marked non-inlineable
public Task<TResult> FromAsync(IAsyncResult asyncResult, Func<IAsyncResult, TResult> endMethod)
{
- StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
- return FromAsyncImpl(asyncResult, endMethod, null, m_defaultCreationOptions, DefaultScheduler, ref stackMark);
+ return FromAsyncImpl(asyncResult, endMethod, null, m_defaultCreationOptions, DefaultScheduler);
}
/// <summary>
@@ -630,14 +611,12 @@ namespace System.Threading.Tasks
/// value.</exception>
/// <returns>A <see cref="T:System.Threading.Tasks.Task{TResult}">Task</see> that represents the
/// asynchronous operation.</returns>
- [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var have to be marked non-inlineable
public Task<TResult> FromAsync(
IAsyncResult asyncResult,
Func<IAsyncResult, TResult> endMethod,
TaskCreationOptions creationOptions)
{
- StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
- return FromAsyncImpl(asyncResult, endMethod, null, creationOptions, DefaultScheduler, ref stackMark);
+ return FromAsyncImpl(asyncResult, endMethod, null, creationOptions, DefaultScheduler);
}
@@ -665,27 +644,23 @@ namespace System.Threading.Tasks
/// value.</exception>
/// <returns>A <see cref="T:System.Threading.Tasks.Task{TResult}">Task</see> that represents the
/// asynchronous operation.</returns>
- [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var have to be marked non-inlineable
public Task<TResult> FromAsync(
IAsyncResult asyncResult,
Func<IAsyncResult, TResult> endMethod,
TaskCreationOptions creationOptions,
TaskScheduler scheduler)
{
- StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
- return FromAsyncImpl(asyncResult, endMethod, null, creationOptions, scheduler, ref stackMark);
+ return FromAsyncImpl(asyncResult, endMethod, null, creationOptions, scheduler);
}
- // internal overload that supports StackCrawlMark
- // We also need this logic broken out into a static method so that the similar TaskFactory.FromAsync()
+ // We need this logic broken out into a static method so that the similar TaskFactory.FromAsync()
// method can access the logic w/o declaring a TaskFactory<TResult> instance.
internal static Task<TResult> FromAsyncImpl(
IAsyncResult asyncResult,
Func<IAsyncResult, TResult> endFunction,
Action<IAsyncResult> endAction,
TaskCreationOptions creationOptions,
- TaskScheduler scheduler,
- ref StackCrawlMark stackMark)
+ TaskScheduler scheduler)
{
if (asyncResult == null)
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.asyncResult);
@@ -714,12 +689,12 @@ namespace System.Threading.Tasks
// Just specify this task as detached. No matter what happens, we want endMethod
// to be called -- even if the parent is canceled. So we don't want to flow
// RespectParentCancellation.
- Task t = new Task(delegate
+ Task t = new Task(new Action<object>(delegate
{
FromAsyncCoreLogic(asyncResult, endFunction, endAction, promise, requiresSynchronization:true);
- },
+ }),
(object)null, null,
- default(CancellationToken), TaskCreationOptions.None, InternalTaskOptions.None, null, ref stackMark);
+ default(CancellationToken), TaskCreationOptions.None, InternalTaskOptions.None, null);
if (AsyncCausalityTracer.LoggingOn)
AsyncCausalityTracer.TraceOperationCreation(CausalityTraceLevel.Verbose, t.Id, "TaskFactory.FromAsync Callback", 0);
@@ -1428,14 +1403,12 @@ namespace System.Threading.Tasks
/// <paramref name="tasks"/> array contains a null value.</exception>
/// <exception cref="T:System.ArgumentException">The exception that is thrown when the
/// <paramref name="tasks"/> array is empty.</exception>
- [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var have to be marked non-inlineable
public Task<TResult> ContinueWhenAll(Task[] tasks, Func<Task[], TResult> continuationFunction)
{
if (continuationFunction == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.continuationFunction);
Contract.EndContractBlock();
- StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
- return ContinueWhenAllImpl(tasks, continuationFunction, null, m_defaultContinuationOptions, m_defaultCancellationToken, DefaultScheduler, ref stackMark);
+ return ContinueWhenAllImpl(tasks, continuationFunction, null, m_defaultContinuationOptions, m_defaultCancellationToken, DefaultScheduler);
}
/// <summary>
@@ -1459,14 +1432,12 @@ namespace System.Threading.Tasks
/// <exception cref="T:System.ObjectDisposedException">The provided <see cref="System.Threading.CancellationToken">CancellationToken</see>
/// has already been disposed.
/// </exception>
- [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var have to be marked non-inlineable
public Task<TResult> ContinueWhenAll(Task[] tasks, Func<Task[], TResult> continuationFunction, CancellationToken cancellationToken)
{
if (continuationFunction == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.continuationFunction);
Contract.EndContractBlock();
- StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
- return ContinueWhenAllImpl(tasks, continuationFunction, null, m_defaultContinuationOptions, cancellationToken, DefaultScheduler, ref stackMark);
+ return ContinueWhenAllImpl(tasks, continuationFunction, null, m_defaultContinuationOptions, cancellationToken, DefaultScheduler);
}
/// <summary>
@@ -1496,14 +1467,12 @@ namespace System.Threading.Tasks
/// which constrain for which <see cref="System.Threading.Tasks.TaskStatus">TaskStatus</see> states a continuation
/// will be executed, are illegal with ContinueWhenAll.
/// </remarks>
- [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var have to be marked non-inlineable
public Task<TResult> ContinueWhenAll(Task[] tasks, Func<Task[], TResult> continuationFunction, TaskContinuationOptions continuationOptions)
{
if (continuationFunction == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.continuationFunction);
Contract.EndContractBlock();
- StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
- return ContinueWhenAllImpl(tasks, continuationFunction, null, continuationOptions, m_defaultCancellationToken, DefaultScheduler, ref stackMark);
+ return ContinueWhenAllImpl(tasks, continuationFunction, null, continuationOptions, m_defaultCancellationToken, DefaultScheduler);
}
/// <summary>
@@ -1543,15 +1512,13 @@ namespace System.Threading.Tasks
/// which constrain for which <see cref="System.Threading.Tasks.TaskStatus">TaskStatus</see> states a continuation
/// will be executed, are illegal with ContinueWhenAll.
/// </remarks>
- [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var have to be marked non-inlineable
public Task<TResult> ContinueWhenAll(Task[] tasks, Func<Task[], TResult> continuationFunction,
CancellationToken cancellationToken, TaskContinuationOptions continuationOptions, TaskScheduler scheduler)
{
if (continuationFunction == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.continuationFunction);
Contract.EndContractBlock();
- StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
- return ContinueWhenAllImpl(tasks, continuationFunction, null, continuationOptions, cancellationToken, scheduler, ref stackMark);
+ return ContinueWhenAllImpl(tasks, continuationFunction, null, continuationOptions, cancellationToken, scheduler);
}
/// <summary>
@@ -1571,14 +1538,12 @@ namespace System.Threading.Tasks
/// <paramref name="tasks"/> array contains a null value.</exception>
/// <exception cref="T:System.ArgumentException">The exception that is thrown when the
/// <paramref name="tasks"/> array is empty.</exception>
- [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var have to be marked non-inlineable
public Task<TResult> ContinueWhenAll<TAntecedentResult>(Task<TAntecedentResult>[] tasks, Func<Task<TAntecedentResult>[], TResult> continuationFunction)
{
if (continuationFunction == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.continuationFunction);
Contract.EndContractBlock();
- StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
- return ContinueWhenAllImpl<TAntecedentResult>(tasks, continuationFunction, null, m_defaultContinuationOptions, m_defaultCancellationToken, DefaultScheduler, ref stackMark);
+ return ContinueWhenAllImpl<TAntecedentResult>(tasks, continuationFunction, null, m_defaultContinuationOptions, m_defaultCancellationToken, DefaultScheduler);
}
/// <summary>
@@ -1603,15 +1568,13 @@ namespace System.Threading.Tasks
/// <exception cref="T:System.ObjectDisposedException">The provided <see cref="System.Threading.CancellationToken">CancellationToken</see>
/// has already been disposed.
/// </exception>
- [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var have to be marked non-inlineable
public Task<TResult> ContinueWhenAll<TAntecedentResult>(Task<TAntecedentResult>[] tasks, Func<Task<TAntecedentResult>[], TResult> continuationFunction,
CancellationToken cancellationToken)
{
if (continuationFunction == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.continuationFunction);
Contract.EndContractBlock();
- StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
- return ContinueWhenAllImpl<TAntecedentResult>(tasks, continuationFunction, null, m_defaultContinuationOptions, cancellationToken, DefaultScheduler, ref stackMark);
+ return ContinueWhenAllImpl<TAntecedentResult>(tasks, continuationFunction, null, m_defaultContinuationOptions, cancellationToken, DefaultScheduler);
}
/// <summary>
@@ -1642,15 +1605,13 @@ namespace System.Threading.Tasks
/// which constrain for which <see cref="System.Threading.Tasks.TaskStatus">TaskStatus</see> states a continuation
/// will be executed, are illegal with ContinueWhenAll.
/// </remarks>
- [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var have to be marked non-inlineable
public Task<TResult> ContinueWhenAll<TAntecedentResult>(Task<TAntecedentResult>[] tasks, Func<Task<TAntecedentResult>[], TResult> continuationFunction,
TaskContinuationOptions continuationOptions)
{
if (continuationFunction == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.continuationFunction);
Contract.EndContractBlock();
- StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
- return ContinueWhenAllImpl<TAntecedentResult>(tasks, continuationFunction, null, continuationOptions, m_defaultCancellationToken, DefaultScheduler, ref stackMark);
+ return ContinueWhenAllImpl<TAntecedentResult>(tasks, continuationFunction, null, continuationOptions, m_defaultCancellationToken, DefaultScheduler);
}
/// <summary>
@@ -1691,15 +1652,13 @@ namespace System.Threading.Tasks
/// which constrain for which <see cref="System.Threading.Tasks.TaskStatus">TaskStatus</see> states a continuation
/// will be executed, are illegal with ContinueWhenAll.
/// </remarks>
- [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var have to be marked non-inlineable
public Task<TResult> ContinueWhenAll<TAntecedentResult>(Task<TAntecedentResult>[] tasks, Func<Task<TAntecedentResult>[], TResult> continuationFunction,
CancellationToken cancellationToken, TaskContinuationOptions continuationOptions, TaskScheduler scheduler)
{
if (continuationFunction == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.continuationFunction);
Contract.EndContractBlock();
- StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
- return ContinueWhenAllImpl<TAntecedentResult>(tasks, continuationFunction, null, continuationOptions, cancellationToken, scheduler, ref stackMark);
+ return ContinueWhenAllImpl<TAntecedentResult>(tasks, continuationFunction, null, continuationOptions, cancellationToken, scheduler);
}
@@ -1707,7 +1666,7 @@ namespace System.Threading.Tasks
// Note: if you make any changes to this method, please do the same to the non-generic version too.
internal static Task<TResult> ContinueWhenAllImpl<TAntecedentResult>(Task<TAntecedentResult>[] tasks,
Func<Task<TAntecedentResult>[], TResult> continuationFunction, Action<Task<TAntecedentResult>[]> continuationAction,
- TaskContinuationOptions continuationOptions, CancellationToken cancellationToken, TaskScheduler scheduler, ref StackCrawlMark stackMark)
+ TaskContinuationOptions continuationOptions, CancellationToken cancellationToken, TaskScheduler scheduler)
{
// check arguments
TaskFactory.CheckMultiTaskContinuationOptions(continuationOptions);
@@ -1737,7 +1696,7 @@ namespace System.Threading.Tasks
return starter.ContinueWith<TResult>(
// use a cached delegate
GenericDelegateCache<TAntecedentResult, TResult>.CWAllFuncDelegate,
- continuationFunction, scheduler, cancellationToken, continuationOptions, ref stackMark);
+ continuationFunction, scheduler, cancellationToken, continuationOptions);
}
else
{
@@ -1746,7 +1705,7 @@ namespace System.Threading.Tasks
return starter.ContinueWith<TResult>(
// use a cached delegate
GenericDelegateCache<TAntecedentResult, TResult>.CWAllActionDelegate,
- continuationAction, scheduler, cancellationToken, continuationOptions, ref stackMark);
+ continuationAction, scheduler, cancellationToken, continuationOptions);
}
}
@@ -1754,7 +1713,7 @@ namespace System.Threading.Tasks
// Note: if you make any changes to this method, please do the same to the generic version too.
internal static Task<TResult> ContinueWhenAllImpl(Task[] tasks,
Func<Task[], TResult> continuationFunction, Action<Task[]> continuationAction,
- TaskContinuationOptions continuationOptions, CancellationToken cancellationToken, TaskScheduler scheduler, ref StackCrawlMark stackMark)
+ TaskContinuationOptions continuationOptions, CancellationToken cancellationToken, TaskScheduler scheduler)
{
// check arguments
TaskFactory.CheckMultiTaskContinuationOptions(continuationOptions);
@@ -1790,7 +1749,7 @@ namespace System.Threading.Tasks
completedTasks.NotifyDebuggerOfWaitCompletionIfNecessary();
return ((Func<Task[], TResult>)state)(completedTasks.Result);
},
- continuationFunction, scheduler, cancellationToken, continuationOptions, ref stackMark);
+ continuationFunction, scheduler, cancellationToken, continuationOptions);
}
else
{
@@ -1804,7 +1763,7 @@ namespace System.Threading.Tasks
completedTasks.NotifyDebuggerOfWaitCompletionIfNecessary();
((Action<Task[]>)state)(completedTasks.Result); return default(TResult);
},
- continuationAction, scheduler, cancellationToken, continuationOptions, ref stackMark);
+ continuationAction, scheduler, cancellationToken, continuationOptions);
}
}
@@ -1828,14 +1787,12 @@ namespace System.Threading.Tasks
/// <paramref name="tasks"/> array contains a null value.</exception>
/// <exception cref="T:System.ArgumentException">The exception that is thrown when the
/// <paramref name="tasks"/> array is empty.</exception>
- [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var have to be marked non-inlineable
public Task<TResult> ContinueWhenAny(Task[] tasks, Func<Task, TResult> continuationFunction)
{
if (continuationFunction == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.continuationFunction);
Contract.EndContractBlock();
- StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
- return ContinueWhenAnyImpl(tasks, continuationFunction, null, m_defaultContinuationOptions, m_defaultCancellationToken, DefaultScheduler, ref stackMark);
+ return ContinueWhenAnyImpl(tasks, continuationFunction, null, m_defaultContinuationOptions, m_defaultCancellationToken, DefaultScheduler);
}
/// <summary>
@@ -1859,14 +1816,12 @@ namespace System.Threading.Tasks
/// <exception cref="T:System.ObjectDisposedException">The provided <see cref="System.Threading.CancellationToken">CancellationToken</see>
/// has already been disposed.
/// </exception>
- [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var have to be marked non-inlineable
public Task<TResult> ContinueWhenAny(Task[] tasks, Func<Task, TResult> continuationFunction, CancellationToken cancellationToken)
{
if (continuationFunction == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.continuationFunction);
Contract.EndContractBlock();
- StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
- return ContinueWhenAnyImpl(tasks, continuationFunction, null, m_defaultContinuationOptions, cancellationToken, DefaultScheduler, ref stackMark);
+ return ContinueWhenAnyImpl(tasks, continuationFunction, null, m_defaultContinuationOptions, cancellationToken, DefaultScheduler);
}
/// <summary>
@@ -1896,14 +1851,12 @@ namespace System.Threading.Tasks
/// which constrain for which <see cref="System.Threading.Tasks.TaskStatus">TaskStatus</see> states a continuation
/// will be executed, are illegal with ContinueWhenAny.
/// </remarks>
- [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var have to be marked non-inlineable
public Task<TResult> ContinueWhenAny(Task[] tasks, Func<Task, TResult> continuationFunction, TaskContinuationOptions continuationOptions)
{
if (continuationFunction == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.continuationFunction);
Contract.EndContractBlock();
- StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
- return ContinueWhenAnyImpl(tasks, continuationFunction, null, continuationOptions, m_defaultCancellationToken, DefaultScheduler, ref stackMark);
+ return ContinueWhenAnyImpl(tasks, continuationFunction, null, continuationOptions, m_defaultCancellationToken, DefaultScheduler);
}
/// <summary>
@@ -1943,15 +1896,13 @@ namespace System.Threading.Tasks
/// which constrain for which <see cref="System.Threading.Tasks.TaskStatus">TaskStatus</see> states a continuation
/// will be executed, are illegal with ContinueWhenAny.
/// </remarks>
- [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var have to be marked non-inlineable
public Task<TResult> ContinueWhenAny(Task[] tasks, Func<Task, TResult> continuationFunction,
CancellationToken cancellationToken, TaskContinuationOptions continuationOptions, TaskScheduler scheduler)
{
if (continuationFunction == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.continuationFunction);
Contract.EndContractBlock();
- StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
- return ContinueWhenAnyImpl(tasks, continuationFunction, null, continuationOptions, cancellationToken, scheduler, ref stackMark);
+ return ContinueWhenAnyImpl(tasks, continuationFunction, null, continuationOptions, cancellationToken, scheduler);
}
/// <summary>
@@ -1971,14 +1922,12 @@ namespace System.Threading.Tasks
/// <paramref name="tasks"/> array contains a null value.</exception>
/// <exception cref="T:System.ArgumentException">The exception that is thrown when the
/// <paramref name="tasks"/> array is empty.</exception>
- [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var have to be marked non-inlineable
public Task<TResult> ContinueWhenAny<TAntecedentResult>(Task<TAntecedentResult>[] tasks, Func<Task<TAntecedentResult>, TResult> continuationFunction)
{
if (continuationFunction == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.continuationFunction);
Contract.EndContractBlock();
- StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
- return ContinueWhenAnyImpl<TAntecedentResult>(tasks, continuationFunction, null, m_defaultContinuationOptions, m_defaultCancellationToken, DefaultScheduler, ref stackMark);
+ return ContinueWhenAnyImpl<TAntecedentResult>(tasks, continuationFunction, null, m_defaultContinuationOptions, m_defaultCancellationToken, DefaultScheduler);
}
/// <summary>
@@ -2003,15 +1952,13 @@ namespace System.Threading.Tasks
/// <exception cref="T:System.ObjectDisposedException">The provided <see cref="System.Threading.CancellationToken">CancellationToken</see>
/// has already been disposed.
/// </exception>
- [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var have to be marked non-inlineable
public Task<TResult> ContinueWhenAny<TAntecedentResult>(Task<TAntecedentResult>[] tasks, Func<Task<TAntecedentResult>, TResult> continuationFunction,
CancellationToken cancellationToken)
{
if (continuationFunction == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.continuationFunction);
Contract.EndContractBlock();
- StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
- return ContinueWhenAnyImpl<TAntecedentResult>(tasks, continuationFunction, null, m_defaultContinuationOptions, cancellationToken, DefaultScheduler, ref stackMark);
+ return ContinueWhenAnyImpl<TAntecedentResult>(tasks, continuationFunction, null, m_defaultContinuationOptions, cancellationToken, DefaultScheduler);
}
/// <summary>
@@ -2042,15 +1989,13 @@ namespace System.Threading.Tasks
/// which constrain for which <see cref="System.Threading.Tasks.TaskStatus">TaskStatus</see> states a continuation
/// will be executed, are illegal with ContinueWhenAny.
/// </remarks>
- [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var have to be marked non-inlineable
public Task<TResult> ContinueWhenAny<TAntecedentResult>(Task<TAntecedentResult>[] tasks, Func<Task<TAntecedentResult>, TResult> continuationFunction,
TaskContinuationOptions continuationOptions)
{
if (continuationFunction == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.continuationFunction);
Contract.EndContractBlock();
- StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
- return ContinueWhenAnyImpl<TAntecedentResult>(tasks, continuationFunction, null, continuationOptions, m_defaultCancellationToken, DefaultScheduler, ref stackMark);
+ return ContinueWhenAnyImpl<TAntecedentResult>(tasks, continuationFunction, null, continuationOptions, m_defaultCancellationToken, DefaultScheduler);
}
/// <summary>
@@ -2091,22 +2036,20 @@ namespace System.Threading.Tasks
/// which constrain for which <see cref="System.Threading.Tasks.TaskStatus">TaskStatus</see> states a continuation
/// will be executed, are illegal with ContinueWhenAny.
/// </remarks>
- [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var have to be marked non-inlineable
public Task<TResult> ContinueWhenAny<TAntecedentResult>(Task<TAntecedentResult>[] tasks, Func<Task<TAntecedentResult>, TResult> continuationFunction,
CancellationToken cancellationToken, TaskContinuationOptions continuationOptions, TaskScheduler scheduler)
{
if (continuationFunction == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.continuationFunction);
Contract.EndContractBlock();
- StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
- return ContinueWhenAnyImpl<TAntecedentResult>(tasks, continuationFunction, null, continuationOptions, cancellationToken, scheduler, ref stackMark);
+ return ContinueWhenAnyImpl<TAntecedentResult>(tasks, continuationFunction, null, continuationOptions, cancellationToken, scheduler);
}
// Core implementation of ContinueWhenAny, non-generic version
// Note: if you make any changes to this method, be sure to do the same to the generic version
internal static Task<TResult> ContinueWhenAnyImpl(Task[] tasks,
Func<Task, TResult> continuationFunction, Action<Task> continuationAction,
- TaskContinuationOptions continuationOptions, CancellationToken cancellationToken, TaskScheduler scheduler, ref StackCrawlMark stackMark)
+ TaskContinuationOptions continuationOptions, CancellationToken cancellationToken, TaskScheduler scheduler)
{
// check arguments
TaskFactory.CheckMultiTaskContinuationOptions(continuationOptions);
@@ -2136,7 +2079,7 @@ namespace System.Threading.Tasks
//the following delegate avoids closure capture as much as possible
//completedTask.Result is the winning task; state == continuationAction
(completedTask, state) => { return ((Func<Task, TResult>)state)(completedTask.Result); },
- continuationFunction, scheduler, cancellationToken, continuationOptions, ref stackMark);
+ continuationFunction, scheduler, cancellationToken, continuationOptions);
}
else
{
@@ -2145,7 +2088,7 @@ namespace System.Threading.Tasks
//the following delegate avoids closure capture as much as possible
//completedTask.Result is the winning task; state == continuationAction
(completedTask, state) => { ((Action<Task>)state)(completedTask.Result); return default(TResult); },
- continuationAction, scheduler, cancellationToken, continuationOptions, ref stackMark);
+ continuationAction, scheduler, cancellationToken, continuationOptions);
}
}
@@ -2154,7 +2097,7 @@ namespace System.Threading.Tasks
// Note: if you make any changes to this method, be sure to do the same to the non-generic version
internal static Task<TResult> ContinueWhenAnyImpl<TAntecedentResult>(Task<TAntecedentResult>[] tasks,
Func<Task<TAntecedentResult>, TResult> continuationFunction, Action<Task<TAntecedentResult>> continuationAction,
- TaskContinuationOptions continuationOptions, CancellationToken cancellationToken, TaskScheduler scheduler, ref StackCrawlMark stackMark)
+ TaskContinuationOptions continuationOptions, CancellationToken cancellationToken, TaskScheduler scheduler)
{
// check arguments
TaskFactory.CheckMultiTaskContinuationOptions(continuationOptions);
@@ -2182,7 +2125,7 @@ namespace System.Threading.Tasks
return starter.ContinueWith<TResult>(
// Use a cached delegate
GenericDelegateCache<TAntecedentResult, TResult>.CWAnyFuncDelegate,
- continuationFunction, scheduler, cancellationToken, continuationOptions, ref stackMark);
+ continuationFunction, scheduler, cancellationToken, continuationOptions);
}
else
{
@@ -2190,7 +2133,7 @@ namespace System.Threading.Tasks
return starter.ContinueWith<TResult>(
// Use a cached delegate
GenericDelegateCache<TAntecedentResult,TResult>.CWAnyActionDelegate,
- continuationAction, scheduler, cancellationToken, continuationOptions, ref stackMark);
+ continuationAction, scheduler, cancellationToken, continuationOptions);
}
}
}
diff --git a/src/mscorlib/src/System/Threading/Tasks/IAsyncCausalityTracerStatics.cs b/src/mscorlib/src/System/Threading/Tasks/IAsyncCausalityTracerStatics.cs
index b8155d017e..32efd771a0 100644
--- a/src/mscorlib/src/System/Threading/Tasks/IAsyncCausalityTracerStatics.cs
+++ b/src/mscorlib/src/System/Threading/Tasks/IAsyncCausalityTracerStatics.cs
@@ -19,16 +19,16 @@ namespace Windows.Foundation.Diagnostics
[Guid("50850B26-267E-451B-A890-AB6A370245EE")]
[WindowsRuntimeImport]
internal interface IAsyncCausalityTracerStatics
- {
- void TraceOperationCreation(CausalityTraceLevel traceLevel, CausalitySource source, Guid platformId, ulong operationId, string operationName, ulong relatedContext);
- void TraceOperationCompletion(CausalityTraceLevel traceLevel, CausalitySource source, Guid platformId, ulong operationId, AsyncCausalityStatus status);
- void TraceOperationRelation(CausalityTraceLevel traceLevel, CausalitySource source, Guid platformId, ulong operationId, CausalityRelation relation);
- void TraceSynchronousWorkStart(CausalityTraceLevel traceLevel, CausalitySource source, Guid platformId, ulong operationId, CausalitySynchronousWork work);
- void TraceSynchronousWorkCompletion(CausalityTraceLevel traceLevel, CausalitySource source, CausalitySynchronousWork work);
+ {
+ void TraceOperationCreation(CausalityTraceLevel traceLevel, CausalitySource source, Guid platformId, ulong operationId, string operationName, ulong relatedContext);
+ void TraceOperationCompletion(CausalityTraceLevel traceLevel, CausalitySource source, Guid platformId, ulong operationId, AsyncCausalityStatus status);
+ void TraceOperationRelation(CausalityTraceLevel traceLevel, CausalitySource source, Guid platformId, ulong operationId, CausalityRelation relation);
+ void TraceSynchronousWorkStart(CausalityTraceLevel traceLevel, CausalitySource source, Guid platformId, ulong operationId, CausalitySynchronousWork work);
+ void TraceSynchronousWorkCompletion(CausalityTraceLevel traceLevel, CausalitySource source, CausalitySynchronousWork work);
//These next 2 functions could've been represented as an event except that the EventRegistrationToken wasn't being propagated to WinRT
EventRegistrationToken add_TracingStatusChanged(System.EventHandler<TracingStatusChangedEventArgs> eventHandler);
void remove_TracingStatusChanged(EventRegistrationToken token);
- }
+ }
[ComImport]
[Guid("410B7711-FF3B-477F-9C9A-D2EFDA302DC3")]
diff --git a/src/mscorlib/src/System/Threading/Tasks/Parallel.cs b/src/mscorlib/src/System/Threading/Tasks/Parallel.cs
deleted file mode 100644
index 7808943870..0000000000
--- a/src/mscorlib/src/System/Threading/Tasks/Parallel.cs
+++ /dev/null
@@ -1,3593 +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 helper class that contains parallel versions of various looping constructs. This
-// internally uses the task parallel library, but takes care to expose very little
-// evidence of this infrastructure being used.
-//
-// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
-
-using System;
-using System.Diagnostics;
-using System.Collections;
-using System.Collections.Generic;
-using System.Collections.Concurrent;
-using System.Security.Permissions;
-using System.Threading;
-using System.Threading.Tasks;
-using System.Diagnostics.Contracts;
-
-
-namespace System.Threading.Tasks
-{
- /// <summary>
- /// Stores options that configure the operation of methods on the
- /// <see cref="T:System.Threading.Tasks.Parallel">Parallel</see> class.
- /// </summary>
- /// <remarks>
- /// By default, methods on the Parallel class attempt to utilize all available processors, are non-cancelable, and target
- /// the default TaskScheduler (TaskScheduler.Default). <see cref="ParallelOptions"/> enables
- /// overriding these defaults.
- /// </remarks>
- public class ParallelOptions
- {
- private TaskScheduler m_scheduler;
- private int m_maxDegreeOfParallelism;
- private CancellationToken m_cancellationToken;
-
- /// <summary>
- /// Initializes a new instance of the <see cref="ParallelOptions"/> class.
- /// </summary>
- /// <remarks>
- /// This constructor initializes the instance with default values. <see cref="MaxDegreeOfParallelism"/>
- /// is initialized to -1, signifying that there is no upper bound set on how much parallelism should
- /// be employed. <see cref="CancellationToken"/> is initialized to a non-cancelable token,
- /// and <see cref="TaskScheduler"/> is initialized to the default scheduler (TaskScheduler.Default).
- /// All of these defaults may be overwritten using the property set accessors on the instance.
- /// </remarks>
- public ParallelOptions()
- {
- m_scheduler = TaskScheduler.Default;
- m_maxDegreeOfParallelism = -1;
- m_cancellationToken = CancellationToken.None;
- }
-
- /// <summary>
- /// Gets or sets the <see cref="T:System.Threading.Tasks.TaskScheduler">TaskScheduler</see>
- /// associated with this <see cref="ParallelOptions"/> instance. Setting this property to null
- /// indicates that the current scheduler should be used.
- /// </summary>
- public TaskScheduler TaskScheduler
- {
- get { return m_scheduler; }
- set { m_scheduler = value; }
- }
-
- // Convenience property used by TPL logic
- internal TaskScheduler EffectiveTaskScheduler
- {
- get
- {
- if (m_scheduler == null) return TaskScheduler.Current;
- else return m_scheduler;
- }
- }
-
- /// <summary>
- /// Gets or sets the maximum degree of parallelism enabled by this ParallelOptions instance.
- /// </summary>
- /// <remarks>
- /// The <see cref="MaxDegreeOfParallelism"/> limits the number of concurrent operations run by <see
- /// cref="T:System.Threading.Tasks.Parallel">Parallel</see> method calls that are passed this
- /// ParallelOptions instance to the set value, if it is positive. If <see
- /// cref="MaxDegreeOfParallelism"/> is -1, then there is no limit placed on the number of concurrently
- /// running operations.
- /// </remarks>
- /// <exception cref="T:System.ArgumentOutOfRangeException">
- /// The exception that is thrown when this <see cref="MaxDegreeOfParallelism"/> is set to 0 or some
- /// value less than -1.
- /// </exception>
- public int MaxDegreeOfParallelism
- {
- get { return m_maxDegreeOfParallelism; }
- set
- {
- if ((value == 0) || (value < -1))
- throw new ArgumentOutOfRangeException(nameof(MaxDegreeOfParallelism));
- m_maxDegreeOfParallelism = value;
- }
- }
-
- /// <summary>
- /// Gets or sets the <see cref="T:System.Threading.CancellationToken">CancellationToken</see>
- /// associated with this <see cref="ParallelOptions"/> instance.
- /// </summary>
- /// <remarks>
- /// Providing a <see cref="T:System.Threading.CancellationToken">CancellationToken</see>
- /// to a <see cref="T:System.Threading.Tasks.Parallel">Parallel</see> method enables the operation to be
- /// exited early. Code external to the operation may cancel the token, and if the operation observes the
- /// token being set, it may exit early by throwing an
- /// <see cref="T:System.OperationCanceledException"/>.
- /// </remarks>
- public CancellationToken CancellationToken
- {
- get { return m_cancellationToken; }
- set { m_cancellationToken = value; }
- }
-
- internal int EffectiveMaxConcurrencyLevel
- {
- get
- {
- int rval = MaxDegreeOfParallelism;
- int schedulerMax = EffectiveTaskScheduler.MaximumConcurrencyLevel;
- if ((schedulerMax > 0) && (schedulerMax != Int32.MaxValue))
- {
- rval = (rval == -1) ? schedulerMax : Math.Min(schedulerMax, rval);
- }
- return rval;
- }
- }
- }
-
- /// <summary>
- /// Provides support for parallel loops and regions.
- /// </summary>
- /// <remarks>
- /// 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>
- public static class Parallel
- {
- // static counter for generating unique Fork/Join Context IDs to be used in ETW events
- internal static int s_forkJoinContextID;
-
- // We use a stride for loops to amortize the frequency of interlocked operations.
- internal const int DEFAULT_LOOP_STRIDE = 16;
-
- // Static variable to hold default parallel options
- internal static ParallelOptions s_defaultParallelOptions = new ParallelOptions();
-
- /// <summary>
- /// Executes each of the provided actions, possibly in parallel.
- /// </summary>
- /// <param name="actions">An array of <see cref="T:System.Action">Actions</see> to execute.</param>
- /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the
- /// <paramref name="actions"/> argument is null.</exception>
- /// <exception cref="T:System.ArgumentException">The exception that is thrown when the
- /// <paramref name="actions"/> array contains a null element.</exception>
- /// <exception cref="T:System.AggregateException">The exception that is thrown when any
- /// action in the <paramref name="actions"/> array throws an exception.</exception>
- /// <remarks>
- /// This method can be used to execute a set of operations, potentially in parallel.
- /// No guarantees are made about the order in which the operations execute or whether
- /// they execute in parallel. This method does not return until each of the
- /// provided operations has completed, regardless of whether completion
- /// occurs due to normal or exceptional termination.
- /// </remarks>
- public static void Invoke(params Action[] actions)
- {
- Invoke(s_defaultParallelOptions, actions);
- }
-
- /// <summary>
- /// Executes each of the provided actions, possibly in parallel.
- /// </summary>
- /// <param name="parallelOptions">A <see cref="T:System.Threading.Tasks.ParallelOptions">ParallelOptions</see>
- /// instance that configures the behavior of this operation.</param>
- /// <param name="actions">An array of <see cref="T:System.Action">Actions</see> to execute.</param>
- /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the
- /// <paramref name="actions"/> argument is null.</exception>
- /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the
- /// <paramref name="parallelOptions"/> argument is null.</exception>
- /// <exception cref="T:System.ArgumentException">The exception that is thrown when the
- /// <paramref name="actions"/> array contains a null element.</exception>
- /// <exception cref="T:System.OperationCanceledException">The exception that is thrown when
- /// the <see cref="T:System.Threading.CancellationToken">CancellationToken</see> in the
- /// <paramref name="parallelOptions"/> is set.</exception>
- /// <exception cref="T:System.AggregateException">The exception that is thrown when any
- /// action in the <paramref name="actions"/> array throws an exception.</exception>
- /// <exception cref="T:System.ObjectDisposedException">The exception that is thrown when the
- /// the <see cref="T:System.Threading.CancellationTokenSource">CancellationTokenSource</see> associated with the
- /// the <see cref="T:System.Threading.CancellationToken">CancellationToken</see> in the
- /// <paramref name="parallelOptions"/> has been disposed.</exception>
- /// <remarks>
- /// This method can be used to execute a set of operations, potentially in parallel.
- /// No guarantees are made about the order in which the operations execute or whether
- /// the they execute in parallel. This method does not return until each of the
- /// provided operations has completed, regardless of whether completion
- /// occurs due to normal or exceptional termination.
- /// </remarks>
- public static void Invoke(ParallelOptions parallelOptions, params Action[] actions)
- {
- if (actions == null)
- {
- throw new ArgumentNullException(nameof(actions));
- }
- if (parallelOptions == null)
- {
- throw new ArgumentNullException(nameof(parallelOptions));
- }
-
- // Throw an ODE if we're passed a disposed CancellationToken.
- if (parallelOptions.CancellationToken.CanBeCanceled
- && AppContextSwitches.ThrowExceptionIfDisposedCancellationTokenSource)
- {
- parallelOptions.CancellationToken.ThrowIfSourceDisposed();
- }
- // Quit early if we're already canceled -- avoid a bunch of work.
- if (parallelOptions.CancellationToken.IsCancellationRequested)
- throw new OperationCanceledException(parallelOptions.CancellationToken);
-
- // We must validate that the actions array contains no null elements, and also
- // make a defensive copy of the actions array.
- Action[] actionsCopy = new Action[actions.Length];
- for (int i = 0; i < actionsCopy.Length; i++)
- {
- actionsCopy[i] = actions[i];
- if (actionsCopy[i] == null)
- {
- throw new ArgumentException(Environment.GetResourceString("Parallel_Invoke_ActionNull"));
- }
- }
-
- // ETW event for Parallel Invoke Begin
- int forkJoinContextID = 0;
- Task callerTask = null;
- if (TplEtwProvider.Log.IsEnabled())
- {
- forkJoinContextID = Interlocked.Increment(ref s_forkJoinContextID);
- callerTask = Task.InternalCurrent;
- TplEtwProvider.Log.ParallelInvokeBegin((callerTask != null ? callerTask.m_taskScheduler.Id : TaskScheduler.Current.Id), (callerTask != null ? callerTask.Id : 0),
- forkJoinContextID, TplEtwProvider.ForkJoinOperationType.ParallelInvoke,
- actionsCopy.Length);
- }
-
-#if DEBUG
- actions = null; // Ensure we don't accidentally use this below.
-#endif
-
- // If we have no work to do, we are done.
- if (actionsCopy.Length < 1) return;
-
- // In the algorithm below, if the number of actions is greater than this, we automatically
- // use Parallel.For() to handle the actions, rather than the Task-per-Action strategy.
- const int SMALL_ACTIONCOUNT_LIMIT = 10;
-
- try
- {
- // If we've gotten this far, it's time to process the actions.
- if ((actionsCopy.Length > SMALL_ACTIONCOUNT_LIMIT) ||
- (parallelOptions.MaxDegreeOfParallelism != -1 && parallelOptions.MaxDegreeOfParallelism < actionsCopy.Length))
- {
- // Used to hold any exceptions encountered during action processing
- ConcurrentQueue<Exception> exceptionQ = null; // will be lazily initialized if necessary
-
- // This is more efficient for a large number of actions, or for enforcing MaxDegreeOfParallelism.
- try
- {
- // Launch a self-replicating task to handle the execution of all actions.
- // The use of a self-replicating task allows us to use as many cores
- // as are available, and no more. The exception to this rule is
- // that, in the case of a blocked action, the ThreadPool may inject
- // extra threads, which means extra tasks can run.
- int actionIndex = 0;
- ParallelForReplicatingTask rootTask = new ParallelForReplicatingTask(parallelOptions, delegate
- {
- // Each for-task will pull an action at a time from the list
- int myIndex = Interlocked.Increment(ref actionIndex); // = index to use + 1
- while (myIndex <= actionsCopy.Length)
- {
- // Catch and store any exceptions. If we don't catch them, the self-replicating
- // task will exit, and that may cause other SR-tasks to exit.
- // And (absent cancellation) we want all actions to execute.
- try
- {
- actionsCopy[myIndex - 1]();
- }
- catch (Exception e)
- {
- LazyInitializer.EnsureInitialized<ConcurrentQueue<Exception>>(ref exceptionQ, () => { return new ConcurrentQueue<Exception>(); });
- exceptionQ.Enqueue(e);
- }
-
- // Check for cancellation. If it is encountered, then exit the delegate.
- if (parallelOptions.CancellationToken.IsCancellationRequested)
- throw new OperationCanceledException(parallelOptions.CancellationToken);
-
- // You're still in the game. Grab your next action index.
- myIndex = Interlocked.Increment(ref actionIndex);
- }
- }, TaskCreationOptions.None, InternalTaskOptions.SelfReplicating);
-
- rootTask.RunSynchronously(parallelOptions.EffectiveTaskScheduler);
- rootTask.Wait();
- }
- catch (Exception e)
- {
- LazyInitializer.EnsureInitialized<ConcurrentQueue<Exception>>(ref exceptionQ, () => { return new ConcurrentQueue<Exception>(); });
-
- // Since we're consuming all action exceptions, there are very few reasons that
- // we would see an exception here. Two that come to mind:
- // (1) An OCE thrown by one or more actions (AggregateException thrown)
- // (2) An exception thrown from the ParallelForReplicatingTask constructor
- // (regular exception thrown).
- // We'll need to cover them both.
- AggregateException ae = e as AggregateException;
- if (ae != null)
- {
- // Strip off outer container of an AggregateException, because downstream
- // logic needs OCEs to be at the top level.
- foreach (Exception exc in ae.InnerExceptions) exceptionQ.Enqueue(exc);
- }
- else
- {
- exceptionQ.Enqueue(e);
- }
- }
-
- // If we have encountered any exceptions, then throw.
- if ((exceptionQ != null) && (exceptionQ.Count > 0))
- {
- ThrowIfReducableToSingleOCE(exceptionQ, parallelOptions.CancellationToken);
- throw new AggregateException(exceptionQ);
- }
- }
- else
- {
- // This is more efficient for a small number of actions and no DOP support
-
- // Initialize our array of tasks, one per action.
- Task[] tasks = new Task[actionsCopy.Length];
-
- // One more check before we begin...
- if (parallelOptions.CancellationToken.IsCancellationRequested)
- throw new OperationCanceledException(parallelOptions.CancellationToken);
-
- // Launch all actions as tasks
- for (int i = 1; i < tasks.Length; i++)
- {
- tasks[i] = Task.Factory.StartNew(actionsCopy[i], parallelOptions.CancellationToken, TaskCreationOptions.None,
- InternalTaskOptions.None, parallelOptions.EffectiveTaskScheduler);
- }
-
- // Optimization: Use current thread to run something before we block waiting for all tasks.
- tasks[0] = new Task(actionsCopy[0]);
- tasks[0].RunSynchronously(parallelOptions.EffectiveTaskScheduler);
-
- // Now wait for the tasks to complete. This will not unblock until all of
- // them complete, and it will throw an exception if one or more of them also
- // threw an exception. We let such exceptions go completely unhandled.
- try
- {
- if (tasks.Length <= 4)
- {
- // for 4 or less tasks, the sequential waitall version is faster
- Task.FastWaitAll(tasks);
- }
- else
- {
- // otherwise we revert to the regular WaitAll which delegates the multiple wait to the cooperative event.
- Task.WaitAll(tasks);
- }
- }
- catch (AggregateException aggExp)
- {
- // see if we can combine it into a single OCE. If not propagate the original exception
- ThrowIfReducableToSingleOCE(aggExp.InnerExceptions, parallelOptions.CancellationToken);
- throw;
- }
- finally
- {
- for (int i = 0; i < tasks.Length; i++)
- {
- if (tasks[i].IsCompleted) tasks[i].Dispose();
- }
- }
- }
- }
- finally
- {
- // ETW event for Parallel Invoke End
- if (TplEtwProvider.Log.IsEnabled())
- {
- TplEtwProvider.Log.ParallelInvokeEnd((callerTask != null ? callerTask.m_taskScheduler.Id : TaskScheduler.Current.Id), (callerTask != null ? callerTask.Id : 0),
- forkJoinContextID);
- }
- }
- }
-
- /// <summary>
- /// Executes a for loop in which iterations may run in parallel.
- /// </summary>
- /// <param name="fromInclusive">The start index, inclusive.</param>
- /// <param name="toExclusive">The end index, exclusive.</param>
- /// <param name="body">The delegate that is invoked once per iteration.</param>
- /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the <paramref name="body"/>
- /// argument is null.</exception>
- /// <exception cref="T:System.AggregateException">The exception that is thrown to contain an exception
- /// thrown from one of the specified delegates.</exception>
- /// <returns>A <see cref="T:System.Threading.Tasks.ParallelLoopResult">ParallelLoopResult</see> structure
- /// that contains information on what portion of the loop completed.</returns>
- /// <remarks>
- /// The <paramref name="body"/> delegate is invoked once for each value in the iteration range:
- /// [fromInclusive, toExclusive). It is provided with the iteration count (an Int32) as a parameter.
- /// </remarks>
- public static ParallelLoopResult For(int fromInclusive, int toExclusive, Action<int> body)
- {
- if (body == null)
- {
- throw new ArgumentNullException(nameof(body));
- }
-
- return ForWorker<object>(
- fromInclusive, toExclusive,
- s_defaultParallelOptions,
- body, null, null, null, null);
- }
-
- /// <summary>
- /// Executes a for loop in which iterations may run in parallel.
- /// </summary>
- /// <param name="fromInclusive">The start index, inclusive.</param>
- /// <param name="toExclusive">The end index, exclusive.</param>
- /// <param name="body">The delegate that is invoked once per iteration.</param>
- /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the <paramref name="body"/>
- /// argument is null.</exception>
- /// <exception cref="T:System.AggregateException">The exception that is thrown to contain an exception
- /// thrown from one of the specified delegates.</exception>
- /// <returns>A <see cref="T:System.Threading.Tasks.ParallelLoopResult">ParallelLoopResult</see> structure
- /// that contains information on what portion of the loop completed.</returns>
- /// <remarks>
- /// The <paramref name="body"/> delegate is invoked once for each value in the iteration range:
- /// [fromInclusive, toExclusive). It is provided with the iteration count (an Int64) as a parameter.
- /// </remarks>
- public static ParallelLoopResult For(long fromInclusive, long toExclusive, Action<long> body)
- {
- if (body == null)
- {
- throw new ArgumentNullException(nameof(body));
- }
-
- return ForWorker64<object>(
- fromInclusive, toExclusive, s_defaultParallelOptions,
- body, null, null, null, null);
- }
-
- /// <summary>
- /// Executes a for loop in which iterations may run in parallel.
- /// </summary>
- /// <param name="fromInclusive">The start index, inclusive.</param>
- /// <param name="toExclusive">The end index, exclusive.</param>
- /// <param name="parallelOptions">A <see cref="T:System.Threading.Tasks.ParallelOptions">ParallelOptions</see>
- /// instance that configures the behavior of this operation.</param>
- /// <param name="body">The delegate that is invoked once per iteration.</param>
- /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the <paramref name="body"/>
- /// argument is null.</exception>
- /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the
- /// <paramref name="parallelOptions"/> argument is null.</exception>
- /// <exception cref="T:System.OperationCanceledException">The exception that is thrown when the
- /// <see cref="T:System.Threading.CancellationToken">CancellationToken</see> in the <paramref name="parallelOptions"/>
- /// argument is set.</exception>
- /// <exception cref="T:System.AggregateException">The exception that is thrown to contain an exception
- /// thrown from one of the specified delegates.</exception>
- /// <exception cref="T:System.ObjectDisposedException">The exception that is thrown when the
- /// the <see cref="T:System.Threading.CancellationTokenSource">CancellationTokenSource</see> associated with the
- /// the <see cref="T:System.Threading.CancellationToken">CancellationToken</see> in the
- /// <paramref name="parallelOptions"/> has been disposed.</exception>
- /// <returns>A <see cref="T:System.Threading.Tasks.ParallelLoopResult">ParallelLoopResult</see> structure
- /// that contains information on what portion of the loop completed.</returns>
- /// <remarks>
- /// The <paramref name="body"/> delegate is invoked once for each value in the iteration range:
- /// [fromInclusive, toExclusive). It is provided with the iteration count (an Int32) as a parameter.
- /// </remarks>
- public static ParallelLoopResult For(int fromInclusive, int toExclusive, ParallelOptions parallelOptions, Action<int> body)
- {
- if (body == null)
- {
- throw new ArgumentNullException(nameof(body));
- }
- if (parallelOptions == null)
- {
- throw new ArgumentNullException(nameof(parallelOptions));
- }
-
- return ForWorker<object>(
- fromInclusive, toExclusive, parallelOptions,
- body, null, null, null, null);
- }
-
- /// <summary>
- /// Executes a for loop in which iterations may run in parallel.
- /// </summary>
- /// <param name="fromInclusive">The start index, inclusive.</param>
- /// <param name="toExclusive">The end index, exclusive.</param>
- /// <param name="parallelOptions">A <see cref="T:System.Threading.Tasks.ParallelOptions">ParallelOptions</see>
- /// instance that configures the behavior of this operation.</param>
- /// <param name="body">The delegate that is invoked once per iteration.</param>
- /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the <paramref name="body"/>
- /// argument is null.</exception>
- /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the
- /// <paramref name="parallelOptions"/> argument is null.</exception>
- /// <exception cref="T:System.OperationCanceledException">The exception that is thrown when the
- /// <see cref="T:System.Threading.CancellationToken">CancellationToken</see> in the <paramref name="parallelOptions"/>
- /// argument is set.</exception>
- /// <exception cref="T:System.AggregateException">The exception that is thrown to contain an exception
- /// thrown from one of the specified delegates.</exception>
- /// <exception cref="T:System.ObjectDisposedException">The exception that is thrown when the
- /// the <see cref="T:System.Threading.CancellationTokenSource">CancellationTokenSource</see> associated with the
- /// the <see cref="T:System.Threading.CancellationToken">CancellationToken</see> in the
- /// <paramref name="parallelOptions"/> has been disposed.</exception>
- /// <returns>A <see cref="T:System.Threading.Tasks.ParallelLoopResult">ParallelLoopResult</see> structure
- /// that contains information on what portion of the loop completed.</returns>
- /// <remarks>
- /// The <paramref name="body"/> delegate is invoked once for each value in the iteration range:
- /// [fromInclusive, toExclusive). It is provided with the iteration count (an Int64) as a parameter.
- /// </remarks>
- public static ParallelLoopResult For(long fromInclusive, long toExclusive, ParallelOptions parallelOptions, Action<long> body)
- {
- if (body == null)
- {
- throw new ArgumentNullException(nameof(body));
- }
- if (parallelOptions == null)
- {
- throw new ArgumentNullException(nameof(parallelOptions));
- }
-
- return ForWorker64<object>(
- fromInclusive, toExclusive, parallelOptions,
- body, null, null, null, null);
- }
-
- /// <summary>
- /// Executes a for loop in which iterations may run in parallel.
- /// </summary>
- /// <param name="fromInclusive">The start index, inclusive.</param>
- /// <param name="toExclusive">The end index, exclusive.</param>
- /// <param name="body">The delegate that is invoked once per iteration.</param>
- /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the <paramref name="body"/>
- /// argument is null.</exception>
- /// <exception cref="T:System.AggregateException">The exception that is thrown to contain an exception
- /// thrown from one of the specified delegates.</exception>
- /// <returns>A <see cref="T:System.Threading.Tasks.ParallelLoopResult">ParallelLoopResult</see> structure
- /// that contains information on what portion of the loop completed.</returns>
- /// <remarks>
- /// <para>
- /// The <paramref name="body"/> delegate is invoked once for each value in the iteration range:
- /// [fromInclusive, toExclusive). It is provided with the following parameters: the iteration count (an Int32),
- /// and a <see cref="System.Threading.Tasks.ParallelLoopState">ParallelLoopState</see> instance that may be
- /// used to break out of the loop prematurely.
- /// </para>
- /// <para>
- /// Calling <see cref="System.Threading.Tasks.ParallelLoopState.Break()">ParallelLoopState.Break()</see>
- /// informs the For operation that iterations after the current one need not
- /// execute. However, all iterations before the current one will still need to be executed if they have not already.
- /// Therefore, calling Break is similar to using a break operation within a
- /// conventional for loop in a language like C#, but it is not a perfect substitute: for example, there is no guarantee that iterations
- /// after the current one will definitely not execute.
- /// </para>
- /// <para>
- /// If executing all iterations before the current one is not necessary,
- /// <see cref="System.Threading.Tasks.ParallelLoopState.Stop()">ParallelLoopState.Stop()</see>
- /// should be preferred to using Break. Calling Stop informs the For loop that it may abandon all remaining
- /// iterations, regardless of whether they're for interations above or below the current,
- /// since all required work has already been completed. As with Break, however, there are no guarantees regarding
- /// which other iterations will not execute.
- /// </para>
- /// <para>
- /// When a loop is ended prematurely, the <see cref="T:ParallelLoopState"/> that's returned will contain
- /// relevant information about the loop's completion.
- /// </para>
- /// </remarks>
- public static ParallelLoopResult For(int fromInclusive, int toExclusive, Action<int, ParallelLoopState> body)
- {
- if (body == null)
- {
- throw new ArgumentNullException(nameof(body));
- }
-
- return ForWorker<object>(
- fromInclusive, toExclusive, s_defaultParallelOptions,
- null, body, null, null, null);
- }
-
- /// <summary>
- /// Executes a for loop in which iterations may run in parallel.
- /// </summary>
- /// <param name="fromInclusive">The start index, inclusive.</param>
- /// <param name="toExclusive">The end index, exclusive.</param>
- /// <param name="body">The delegate that is invoked once per iteration.</param>
- /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the <paramref name="body"/>
- /// argument is null.</exception>
- /// <exception cref="T:System.AggregateException">The exception that is thrown to contain an exception
- /// thrown from one of the specified delegates.</exception>
- /// <returns>A <see cref="T:System.Threading.Tasks.ParallelLoopResult">ParallelLoopResult</see> structure
- /// that contains information on what portion of the loop completed.</returns>
- /// <remarks>
- /// The <paramref name="body"/> delegate is invoked once for each value in the iteration range:
- /// [fromInclusive, toExclusive). It is provided with the following parameters: the iteration count (an Int64),
- /// and a <see cref="System.Threading.Tasks.ParallelLoopState">ParallelLoopState</see> instance that may be
- /// used to break out of the loop prematurely.
- /// </remarks>
- public static ParallelLoopResult For(long fromInclusive, long toExclusive, Action<long, ParallelLoopState> body)
- {
- if (body == null)
- {
- throw new ArgumentNullException(nameof(body));
- }
-
- return ForWorker64<object>(
- fromInclusive, toExclusive, s_defaultParallelOptions,
- null, body, null, null, null);
- }
-
- /// <summary>
- /// Executes a for loop in which iterations may run in parallel.
- /// </summary>
- /// <param name="fromInclusive">The start index, inclusive.</param>
- /// <param name="toExclusive">The end index, exclusive.</param>
- /// <param name="parallelOptions">A <see cref="T:System.Threading.Tasks.ParallelOptions">ParallelOptions</see>
- /// instance that configures the behavior of this operation.</param>
- /// <param name="body">The delegate that is invoked once per iteration.</param>
- /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the <paramref name="body"/>
- /// argument is null.</exception>
- /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the
- /// <paramref name="parallelOptions"/> argument is null.</exception>
- /// <exception cref="T:System.OperationCanceledException">The exception that is thrown when the
- /// <see cref="T:System.Threading.CancellationToken">CancellationToken</see> in the <paramref name="parallelOptions"/>
- /// argument is set.</exception>
- /// <exception cref="T:System.AggregateException">The exception that is thrown to contain an exception
- /// thrown from one of the specified delegates.</exception>
- /// <exception cref="T:System.ObjectDisposedException">The exception that is thrown when the
- /// the <see cref="T:System.Threading.CancellationTokenSource">CancellationTokenSource</see> associated with the
- /// the <see cref="T:System.Threading.CancellationToken">CancellationToken</see> in the
- /// <paramref name="parallelOptions"/> has been disposed.</exception>
- /// <returns>A <see cref="T:System.Threading.Tasks.ParallelLoopResult">ParallelLoopResult</see> structure
- /// that contains information on what portion of the loop completed.</returns>
- /// <remarks>
- /// The <paramref name="body"/> delegate is invoked once for each value in the iteration range:
- /// [fromInclusive, toExclusive). It is provided with the following parameters: the iteration count (an Int32),
- /// and a <see cref="System.Threading.Tasks.ParallelLoopState">ParallelLoopState</see> instance that may be
- /// used to break out of the loop prematurely.
- /// </remarks>
- public static ParallelLoopResult For(int fromInclusive, int toExclusive, ParallelOptions parallelOptions, Action<int, ParallelLoopState> body)
- {
- if (body == null)
- {
- throw new ArgumentNullException(nameof(body));
- }
- if (parallelOptions == null)
- {
- throw new ArgumentNullException(nameof(parallelOptions));
- }
-
- return ForWorker<object>(
- fromInclusive, toExclusive, parallelOptions,
- null, body, null, null, null);
- }
-
- /// <summary>
- /// Executes a for loop in which iterations may run in parallel.
- /// </summary>
- /// <param name="fromInclusive">The start index, inclusive.</param>
- /// <param name="toExclusive">The end index, exclusive.</param>
- /// <param name="parallelOptions">A <see cref="T:System.Threading.Tasks.ParallelOptions">ParallelOptions</see>
- /// instance that configures the behavior of this operation.</param>
- /// <param name="body">The delegate that is invoked once per iteration.</param>
- /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the <paramref name="body"/>
- /// argument is null.</exception>
- /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the
- /// <paramref name="parallelOptions"/> argument is null.</exception>
- /// <exception cref="T:System.OperationCanceledException">The exception that is thrown when the
- /// <see cref="T:System.Threading.CancellationToken">CancellationToken</see> in the <paramref name="parallelOptions"/>
- /// argument is set.</exception>
- /// <exception cref="T:System.AggregateException">The exception that is thrown to contain an exception
- /// thrown from one of the specified delegates.</exception>
- /// <exception cref="T:System.ObjectDisposedException">The exception that is thrown when the
- /// the <see cref="T:System.Threading.CancellationTokenSource">CancellationTokenSource</see> associated with the
- /// the <see cref="T:System.Threading.CancellationToken">CancellationToken</see> in the
- /// <paramref name="parallelOptions"/> has been disposed.</exception>
- /// <returns>A <see cref="T:System.Threading.Tasks.ParallelLoopResult">ParallelLoopResult</see> structure
- /// that contains information on what portion of the loop completed.</returns>
- /// <remarks>
- /// The <paramref name="body"/> delegate is invoked once for each value in the iteration range:
- /// [fromInclusive, toExclusive). It is provided with the following parameters: the iteration count (an Int64),
- /// and a <see cref="System.Threading.Tasks.ParallelLoopState">ParallelLoopState</see> instance that may be
- /// used to break out of the loop prematurely.
- /// </remarks>
- public static ParallelLoopResult For(long fromInclusive, long toExclusive, ParallelOptions parallelOptions,
- Action<long, ParallelLoopState> body)
- {
- if (body == null)
- {
- throw new ArgumentNullException(nameof(body));
- }
- if (parallelOptions == null)
- {
- throw new ArgumentNullException(nameof(parallelOptions));
- }
-
- return ForWorker64<object>(
- fromInclusive, toExclusive, parallelOptions,
- null, body, null, null, null);
- }
-
- /// <summary>
- /// Executes a for loop in which iterations may run in parallel.
- /// </summary>
- /// <typeparam name="TLocal">The type of the thread-local data.</typeparam>
- /// <param name="fromInclusive">The start index, inclusive.</param>
- /// <param name="toExclusive">The end index, exclusive.</param>
- /// <param name="localInit">The function delegate that returns the initial state of the local data
- /// for each thread.</param>
- /// <param name="body">The delegate that is invoked once per iteration.</param>
- /// <param name="localFinally">The delegate that performs a final action on the local state of each
- /// thread.</param>
- /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the <paramref name="body"/>
- /// argument is null.</exception>
- /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the
- /// <paramref name="localInit"/> argument is null.</exception>
- /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the
- /// <paramref name="localFinally"/> argument is null.</exception>
- /// <exception cref="T:System.AggregateException">The exception that is thrown to contain an exception
- /// thrown from one of the specified delegates.</exception>
- /// <returns>A <see cref="T:System.Threading.Tasks.ParallelLoopResult">ParallelLoopResult</see> structure
- /// that contains information on what portion of the loop completed.</returns>
- /// <remarks>
- /// <para>
- /// The <paramref name="body"/> delegate is invoked once for each value in the iteration range:
- /// [fromInclusive, toExclusive). It is provided with the following parameters: the iteration count (an Int32),
- /// a <see cref="System.Threading.Tasks.ParallelLoopState">ParallelLoopState</see> instance that may be
- /// used to break out of the loop prematurely, and some local state that may be shared amongst iterations
- /// that execute on the same thread.
- /// </para>
- /// <para>
- /// The <paramref name="localInit"/> delegate is invoked once for each thread that participates in the loop's
- /// execution and returns the initial local state for each of those threads. These initial states are passed to the first
- /// <paramref name="body"/> invocations on each thread. Then, every subsequent body invocation returns a possibly
- /// modified state value that is passed to the next body invocation. Finally, the last body invocation on each thread returns a state value
- /// that is passed to the <paramref name="localFinally"/> delegate. The localFinally delegate is invoked once per thread to perform a final
- /// action on each thread's local state.
- /// </para>
- /// </remarks>
- public static ParallelLoopResult For<TLocal>(
- int fromInclusive, int toExclusive,
- Func<TLocal> localInit,
- Func<int, ParallelLoopState, TLocal, TLocal> body,
- Action<TLocal> localFinally)
- {
- if (body == null)
- {
- throw new ArgumentNullException(nameof(body));
- }
- if (localInit == null)
- {
- throw new ArgumentNullException(nameof(localInit));
- }
- if (localFinally == null)
- {
- throw new ArgumentNullException(nameof(localFinally));
- }
-
- return ForWorker(
- fromInclusive, toExclusive, s_defaultParallelOptions,
- null, null, body, localInit, localFinally);
- }
-
- /// <summary>
- /// Executes a for loop in which iterations may run in parallel. Supports 64-bit indices.
- /// </summary>
- /// <typeparam name="TLocal">The type of the thread-local data.</typeparam>
- /// <param name="fromInclusive">The start index, inclusive.</param>
- /// <param name="toExclusive">The end index, exclusive.</param>
- /// <param name="localInit">The function delegate that returns the initial state of the local data
- /// for each thread.</param>
- /// <param name="body">The delegate that is invoked once per iteration.</param>
- /// <param name="localFinally">The delegate that performs a final action on the local state of each
- /// thread.</param>
- /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the <paramref name="body"/>
- /// argument is null.</exception>
- /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the
- /// <paramref name="localInit"/> argument is null.</exception>
- /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the
- /// <paramref name="localFinally"/> argument is null.</exception>
- /// <exception cref="T:System.AggregateException">The exception that is thrown to contain an exception
- /// thrown from one of the specified delegates.</exception>
- /// <returns>A <see cref="T:System.Threading.Tasks.ParallelLoopResult">ParallelLoopResult</see> structure
- /// that contains information on what portion of the loop completed.</returns>
- /// <remarks>
- /// <para>
- /// The <paramref name="body"/> delegate is invoked once for each value in the iteration range:
- /// [fromInclusive, toExclusive). It is provided with the following parameters: the iteration count (an Int64),
- /// a <see cref="System.Threading.Tasks.ParallelLoopState">ParallelLoopState</see> instance that may be
- /// used to break out of the loop prematurely, and some local state that may be shared amongst iterations
- /// that execute on the same thread.
- /// </para>
- /// <para>
- /// The <paramref name="localInit"/> delegate is invoked once for each thread that participates in the loop's
- /// execution and returns the initial local state for each of those threads. These initial states are passed to the first
- /// <paramref name="body"/> invocations on each thread. Then, every subsequent body invocation returns a possibly
- /// modified state value that is passed to the next body invocation. Finally, the last body invocation on each thread returns a state value
- /// that is passed to the <paramref name="localFinally"/> delegate. The localFinally delegate is invoked once per thread to perform a final
- /// action on each thread's local state.
- /// </para>
- /// </remarks>
- public static ParallelLoopResult For<TLocal>(
- long fromInclusive, long toExclusive,
- Func<TLocal> localInit,
- Func<long, ParallelLoopState, TLocal, TLocal> body,
- Action<TLocal> localFinally)
- {
- if (body == null)
- {
- throw new ArgumentNullException(nameof(body));
- }
- if (localInit == null)
- {
- throw new ArgumentNullException(nameof(localInit));
- }
- if (localFinally == null)
- {
- throw new ArgumentNullException(nameof(localFinally));
- }
-
- return ForWorker64(
- fromInclusive, toExclusive, s_defaultParallelOptions,
- null, null, body, localInit, localFinally);
- }
-
- /// <summary>
- /// Executes a for loop in which iterations may run in parallel.
- /// </summary>
- /// <typeparam name="TLocal">The type of the thread-local data.</typeparam>
- /// <param name="fromInclusive">The start index, inclusive.</param>
- /// <param name="toExclusive">The end index, exclusive.</param>
- /// <param name="parallelOptions">A <see cref="T:System.Threading.Tasks.ParallelOptions">ParallelOptions</see>
- /// instance that configures the behavior of this operation.</param>
- /// <param name="localInit">The function delegate that returns the initial state of the local data
- /// for each thread.</param>
- /// <param name="body">The delegate that is invoked once per iteration.</param>
- /// <param name="localFinally">The delegate that performs a final action on the local state of each
- /// thread.</param>
- /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the <paramref name="body"/>
- /// argument is null.</exception>
- /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the
- /// <paramref name="localInit"/> argument is null.</exception>
- /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the
- /// <paramref name="localFinally"/> argument is null.</exception>
- /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the
- /// <paramref name="parallelOptions"/> argument is null.</exception>
- /// <exception cref="T:System.OperationCanceledException">The exception that is thrown when the
- /// <see cref="T:System.Threading.CancellationToken">CancellationToken</see> in the <paramref name="parallelOptions"/>
- /// argument is set.</exception>
- /// <exception cref="T:System.AggregateException">The exception that is thrown to contain an exception
- /// thrown from one of the specified delegates.</exception>
- /// <exception cref="T:System.ObjectDisposedException">The exception that is thrown when the
- /// the <see cref="T:System.Threading.CancellationTokenSource">CancellationTokenSource</see> associated with the
- /// the <see cref="T:System.Threading.CancellationToken">CancellationToken</see> in the
- /// <paramref name="parallelOptions"/> has been disposed.</exception>
- /// <returns>A <see cref="T:System.Threading.Tasks.ParallelLoopResult">ParallelLoopResult</see> structure
- /// that contains information on what portion of the loop completed.</returns>
- /// <remarks>
- /// <para>
- /// The <paramref name="body"/> delegate is invoked once for each value in the iteration range:
- /// [fromInclusive, toExclusive). It is provided with the following parameters: the iteration count (an Int32),
- /// a <see cref="System.Threading.Tasks.ParallelLoopState">ParallelLoopState</see> instance that may be
- /// used to break out of the loop prematurely, and some local state that may be shared amongst iterations
- /// that execute on the same thread.
- /// </para>
- /// <para>
- /// The <paramref name="localInit"/> delegate is invoked once for each thread that participates in the loop's
- /// execution and returns the initial local state for each of those threads. These initial states are passed to the first
- /// <paramref name="body"/> invocations on each thread. Then, every subsequent body invocation returns a possibly
- /// modified state value that is passed to the next body invocation. Finally, the last body invocation on each thread returns a state value
- /// that is passed to the <paramref name="localFinally"/> delegate. The localFinally delegate is invoked once per thread to perform a final
- /// action on each thread's local state.
- /// </para>
- /// </remarks>
- public static ParallelLoopResult For<TLocal>(
- int fromInclusive, int toExclusive, ParallelOptions parallelOptions,
- Func<TLocal> localInit,
- Func<int, ParallelLoopState, TLocal, TLocal> body,
- Action<TLocal> localFinally)
- {
- if (body == null)
- {
- throw new ArgumentNullException(nameof(body));
- }
- if (localInit == null)
- {
- throw new ArgumentNullException(nameof(localInit));
- }
- if (localFinally == null)
- {
- throw new ArgumentNullException(nameof(localFinally));
- }
- if (parallelOptions == null)
- {
- throw new ArgumentNullException(nameof(parallelOptions));
- }
-
- return ForWorker(
- fromInclusive, toExclusive, parallelOptions,
- null, null, body, localInit, localFinally);
- }
-
- /// <summary>
- /// Executes a for loop in which iterations may run in parallel.
- /// </summary>
- /// <typeparam name="TLocal">The type of the thread-local data.</typeparam>
- /// <param name="fromInclusive">The start index, inclusive.</param>
- /// <param name="toExclusive">The end index, exclusive.</param>
- /// <param name="parallelOptions">A <see cref="T:System.Threading.Tasks.ParallelOptions">ParallelOptions</see>
- /// instance that configures the behavior of this operation.</param>
- /// <param name="localInit">The function delegate that returns the initial state of the local data
- /// for each thread.</param>
- /// <param name="body">The delegate that is invoked once per iteration.</param>
- /// <param name="localFinally">The delegate that performs a final action on the local state of each
- /// thread.</param>
- /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the <paramref name="body"/>
- /// argument is null.</exception>
- /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the
- /// <paramref name="localInit"/> argument is null.</exception>
- /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the
- /// <paramref name="localFinally"/> argument is null.</exception>
- /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the
- /// <paramref name="parallelOptions"/> argument is null.</exception>
- /// <exception cref="T:System.OperationCanceledException">The exception that is thrown when the
- /// <see cref="T:System.Threading.CancellationToken">CancellationToken</see> in the <paramref name="parallelOptions"/>
- /// argument is set.</exception>
- /// <exception cref="T:System.AggregateException">The exception that is thrown to contain an exception
- /// thrown from one of the specified delegates.</exception>
- /// <exception cref="T:System.ObjectDisposedException">The exception that is thrown when the
- /// the <see cref="T:System.Threading.CancellationTokenSource">CancellationTokenSource</see> associated with the
- /// the <see cref="T:System.Threading.CancellationToken">CancellationToken</see> in the
- /// <paramref name="parallelOptions"/> has been disposed.</exception>
- /// <returns>A <see cref="T:System.Threading.Tasks.ParallelLoopResult">ParallelLoopResult</see> structure
- /// that contains information on what portion of the loop completed.</returns>
- /// <remarks>
- /// <para>
- /// The <paramref name="body"/> delegate is invoked once for each value in the iteration range:
- /// [fromInclusive, toExclusive). It is provided with the following parameters: the iteration count (an Int64),
- /// a <see cref="System.Threading.Tasks.ParallelLoopState">ParallelLoopState</see> instance that may be
- /// used to break out of the loop prematurely, and some local state that may be shared amongst iterations
- /// that execute on the same thread.
- /// </para>
- /// <para>
- /// The <paramref name="localInit"/> delegate is invoked once for each thread that participates in the loop's
- /// execution and returns the initial local state for each of those threads. These initial states are passed to the first
- /// <paramref name="body"/> invocations on each thread. Then, every subsequent body invocation returns a possibly
- /// modified state value that is passed to the next body invocation. Finally, the last body invocation on each thread returns a state value
- /// that is passed to the <paramref name="localFinally"/> delegate. The localFinally delegate is invoked once per thread to perform a final
- /// action on each thread's local state.
- /// </para>
- /// </remarks>
- public static ParallelLoopResult For<TLocal>(
- long fromInclusive, long toExclusive, ParallelOptions parallelOptions,
- Func<TLocal> localInit,
- Func<long, ParallelLoopState, TLocal, TLocal> body,
- Action<TLocal> localFinally)
- {
- if (body == null)
- {
- throw new ArgumentNullException(nameof(body));
- }
- if (localInit == null)
- {
- throw new ArgumentNullException(nameof(localInit));
- }
- if (localFinally == null)
- {
- throw new ArgumentNullException(nameof(localFinally));
- }
- if (parallelOptions == null)
- {
- throw new ArgumentNullException(nameof(parallelOptions));
- }
-
-
- return ForWorker64(
- fromInclusive, toExclusive, parallelOptions,
- null, null, body, localInit, localFinally);
- }
-
-
-
-
-
-
-
- /// <summary>
- /// Performs the major work of the parallel for loop. It assumes that argument validation has already
- /// been performed by the caller. This function's whole purpose in life is to enable as much reuse of
- /// common implementation details for the various For overloads we offer. Without it, we'd end up
- /// with lots of duplicate code. It handles: (1) simple for loops, (2) for loops that depend on
- /// ParallelState, and (3) for loops with thread local data.
- ///
- /// </summary>
- /// <typeparam name="TLocal">The type of the local data.</typeparam>
- /// <param name="fromInclusive">The loop's start index, inclusive.</param>
- /// <param name="toExclusive">The loop's end index, exclusive.</param>
- /// <param name="parallelOptions">A ParallelOptions instance.</param>
- /// <param name="body">The simple loop body.</param>
- /// <param name="bodyWithState">The loop body for ParallelState overloads.</param>
- /// <param name="bodyWithLocal">The loop body for thread local state overloads.</param>
- /// <param name="localInit">A selector function that returns new thread local state.</param>
- /// <param name="localFinally">A cleanup function to destroy thread local state.</param>
- /// <remarks>Only one of the body arguments may be supplied (i.e. they are exclusive).</remarks>
- /// <returns>A <see cref="T:System.Threading.Tasks.ParallelLoopResult"/> structure.</returns>
- private static ParallelLoopResult ForWorker<TLocal>(
- int fromInclusive, int toExclusive,
- ParallelOptions parallelOptions,
- Action<int> body,
- Action<int, ParallelLoopState> bodyWithState,
- Func<int, ParallelLoopState, TLocal, TLocal> bodyWithLocal,
- Func<TLocal> localInit, Action<TLocal> localFinally)
- {
- Debug.Assert(((body == null ? 0 : 1) + (bodyWithState == null ? 0 : 1) + (bodyWithLocal == null ? 0 : 1)) == 1,
- "expected exactly one body function to be supplied");
- 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.
- ParallelLoopResult result = new ParallelLoopResult();
-
- // We just return immediately if 'to' is smaller (or equal to) 'from'.
- if (toExclusive <= fromInclusive)
- {
- result.m_completed = true;
- return result;
- }
-
- // For all loops we need a shared flag even though we don't have a body with state,
- // because the shared flag contains the exceptional bool, which triggers other workers
- // to exit their loops if one worker catches an exception
- ParallelLoopStateFlags32 sharedPStateFlags = new ParallelLoopStateFlags32();
-
- TaskCreationOptions creationOptions = TaskCreationOptions.None;
- InternalTaskOptions internalOptions = InternalTaskOptions.SelfReplicating;
-
- // Before getting started, do a quick peek to see if we have been canceled already
- if (parallelOptions.CancellationToken.IsCancellationRequested)
- {
- throw new OperationCanceledException(parallelOptions.CancellationToken);
- }
-
- // initialize ranges with passed in loop arguments and expected number of workers
- int numExpectedWorkers = (parallelOptions.EffectiveMaxConcurrencyLevel == -1) ?
- PlatformHelper.ProcessorCount :
- parallelOptions.EffectiveMaxConcurrencyLevel;
- RangeManager rangeManager = new RangeManager(fromInclusive, toExclusive, 1, numExpectedWorkers);
-
- // Keep track of any cancellations
- OperationCanceledException oce = null;
-
- CancellationTokenRegistration ctr = new CancellationTokenRegistration();
-
- // if cancellation is enabled, we need to register a callback to stop the loop when it gets signaled
- if (parallelOptions.CancellationToken.CanBeCanceled)
- {
- ctr = parallelOptions.CancellationToken.InternalRegisterWithoutEC((o) =>
- {
- // Cause processing to stop
- sharedPStateFlags.Cancel();
- // Record our cancellation
- oce = new OperationCanceledException(parallelOptions.CancellationToken);
- }, null);
- }
-
- // ETW event for Parallel For begin
- int forkJoinContextID = 0;
- Task callingTask = null;
- if (TplEtwProvider.Log.IsEnabled())
- {
- forkJoinContextID = Interlocked.Increment(ref s_forkJoinContextID);
- callingTask = Task.InternalCurrent;
- TplEtwProvider.Log.ParallelLoopBegin((callingTask != null ? callingTask.m_taskScheduler.Id : TaskScheduler.Current.Id), (callingTask != null ? callingTask.Id : 0),
- forkJoinContextID, TplEtwProvider.ForkJoinOperationType.ParallelFor,
- fromInclusive, toExclusive);
- }
-
- ParallelForReplicatingTask rootTask = null;
-
- try
- {
- // this needs to be in try-block because it can throw in BuggyScheduler.MaxConcurrencyLevel
- rootTask = new ParallelForReplicatingTask(
- parallelOptions,
- delegate
- {
- //
- // first thing we do upon enterying the task is to register as a new "RangeWorker" with the
- // shared RangeManager instance.
- //
- // If this call returns a RangeWorker struct which wraps the state needed by this task
- //
- // We need to call FindNewWork32() on it to see whether there's a chunk available.
- //
-
-
- // Cache some information about the current task
- Task currentWorkerTask = Task.InternalCurrent;
- bool bIsRootTask = (currentWorkerTask == rootTask);
-
- RangeWorker currentWorker = new RangeWorker();
- Object savedStateFromPreviousReplica = currentWorkerTask.SavedStateFromPreviousReplica;
-
- if (savedStateFromPreviousReplica is RangeWorker)
- currentWorker = (RangeWorker)savedStateFromPreviousReplica;
- else
- currentWorker = rangeManager.RegisterNewWorker();
-
-
-
- // These are the local index values to be used in the sequential loop.
- // Their values filled in by FindNewWork32
- int nFromInclusiveLocal;
- int nToExclusiveLocal;
-
- if (currentWorker.FindNewWork32(out nFromInclusiveLocal, out nToExclusiveLocal) == false ||
- sharedPStateFlags.ShouldExitLoop(nFromInclusiveLocal) == true)
- {
- return; // no need to run
- }
-
- // ETW event for ParallelFor Worker Fork
- if (TplEtwProvider.Log.IsEnabled())
- {
- TplEtwProvider.Log.ParallelFork((currentWorkerTask != null ? currentWorkerTask.m_taskScheduler.Id : TaskScheduler.Current.Id), (currentWorkerTask != null ? currentWorkerTask.Id : 0),
- forkJoinContextID);
- }
-
- TLocal localValue = default(TLocal);
- bool bLocalValueInitialized = false; // Tracks whether localInit ran without exceptions, so that we can skip localFinally if it wasn't
-
- try
- {
- // Create a new state object that references the shared "stopped" and "exceptional" flags
- // If needed, it will contain a new instance of thread-local state by invoking the selector.
- ParallelLoopState32 state = null;
-
- if (bodyWithState != null)
- {
- Debug.Assert(sharedPStateFlags != null);
- state = new ParallelLoopState32(sharedPStateFlags);
- }
- else if (bodyWithLocal != null)
- {
- Debug.Assert(sharedPStateFlags != null);
- state = new ParallelLoopState32(sharedPStateFlags);
- if (localInit != null)
- {
- localValue = localInit();
- bLocalValueInitialized = true;
- }
- }
-
- // initialize a loop timer which will help us decide whether we should exit early
- LoopTimer loopTimer = new LoopTimer(rootTask.ActiveChildCount);
-
- // Now perform the loop itself.
- do
- {
- if (body != null)
- {
- for (int j = nFromInclusiveLocal;
- j < nToExclusiveLocal && (sharedPStateFlags.LoopStateFlags == ParallelLoopStateFlags.PLS_NONE // fast path check as SEL() doesn't inline
- || !sharedPStateFlags.ShouldExitLoop()); // the no-arg version is used since we have no state
- j += 1)
- {
-
- body(j);
- }
- }
- else if (bodyWithState != null)
- {
- for (int j = nFromInclusiveLocal;
- j < nToExclusiveLocal && (sharedPStateFlags.LoopStateFlags == ParallelLoopStateFlags.PLS_NONE // fast path check as SEL() doesn't inline
- || !sharedPStateFlags.ShouldExitLoop(j));
- j += 1)
- {
-
- state.CurrentIteration = j;
- bodyWithState(j, state);
- }
- }
- else
- {
- for (int j = nFromInclusiveLocal;
- j < nToExclusiveLocal && (sharedPStateFlags.LoopStateFlags == ParallelLoopStateFlags.PLS_NONE // fast path check as SEL() doesn't inline
- || !sharedPStateFlags.ShouldExitLoop(j));
- j += 1)
- {
- state.CurrentIteration = j;
- localValue = bodyWithLocal(j, state, localValue);
- }
- }
-
- // Cooperative multitasking workaround for AppDomain fairness.
- // Check if allowed loop time is exceeded, if so save current state and return. The self replicating task logic
- // will detect this, and queue up a replacement task. Note that we don't do this on the root task.
- if (!bIsRootTask && loopTimer.LimitExceeded())
- {
- currentWorkerTask.SavedStateForNextReplica = (object)currentWorker;
- break;
- }
-
- }
- // Exit if we can't find new work, or if the loop was stoppped.
- while (currentWorker.FindNewWork32(out nFromInclusiveLocal, out nToExclusiveLocal) &&
- ((sharedPStateFlags.LoopStateFlags == ParallelLoopStateFlags.PLS_NONE) ||
- !sharedPStateFlags.ShouldExitLoop(nFromInclusiveLocal)));
- }
- catch
- {
- // if we catch an exception in a worker, we signal the other workers to exit the loop, and we rethrow
- sharedPStateFlags.SetExceptional();
- throw;
- }
- finally
- {
- // If a cleanup function was specified, call it. Otherwise, if the type is
- // IDisposable, we will invoke Dispose on behalf of the user.
- if (localFinally != null && bLocalValueInitialized)
- {
- localFinally(localValue);
- }
-
- // ETW event for ParallelFor Worker Join
- if (TplEtwProvider.Log.IsEnabled())
- {
- TplEtwProvider.Log.ParallelJoin((currentWorkerTask != null ? currentWorkerTask.m_taskScheduler.Id : TaskScheduler.Current.Id), (currentWorkerTask != null ? currentWorkerTask.Id : 0),
- forkJoinContextID);
- }
- }
- },
- creationOptions, internalOptions);
-
- rootTask.RunSynchronously(parallelOptions.EffectiveTaskScheduler); // might throw TSE
- rootTask.Wait();
-
- // If we made a cancellation registration, we need to clean it up now before observing the OCE
- // Otherwise we could be caught in the middle of a callback, and observe PLS_STOPPED, but oce = null
- if (parallelOptions.CancellationToken.CanBeCanceled)
- {
- ctr.Dispose();
- }
-
- // If we got through that with no exceptions, and we were canceled, then
- // throw our cancellation exception
- if (oce != null) throw oce;
- }
- catch (AggregateException aggExp)
- {
- // if we made a cancellation registration, and rootTask.Wait threw, we need to clean it up here
- if (parallelOptions.CancellationToken.CanBeCanceled)
- {
- ctr.Dispose();
- }
-
- // see if we can combine it into a single OCE. If not propagate the original exception
- ThrowIfReducableToSingleOCE(aggExp.InnerExceptions, parallelOptions.CancellationToken);
- throw;
- }
- catch (TaskSchedulerException)
- {
- // if we made a cancellation registration, and rootTask.RunSynchronously threw, we need to clean it up here
- if (parallelOptions.CancellationToken.CanBeCanceled)
- {
- ctr.Dispose();
- }
- throw;
- }
- finally
- {
- int sb_status = sharedPStateFlags.LoopStateFlags;
- result.m_completed = (sb_status == ParallelLoopStateFlags.PLS_NONE);
- if ((sb_status & ParallelLoopStateFlags.PLS_BROKEN) != 0)
- {
- result.m_lowestBreakIteration = sharedPStateFlags.LowestBreakIteration;
- }
-
- if ((rootTask != null) && rootTask.IsCompleted) rootTask.Dispose();
-
- // ETW event for Parallel For End
- if (TplEtwProvider.Log.IsEnabled())
- {
- int nTotalIterations = 0;
-
- // calculate how many iterations we ran in total
- if (sb_status == ParallelLoopStateFlags.PLS_NONE)
- nTotalIterations = toExclusive - fromInclusive;
- else if ((sb_status & ParallelLoopStateFlags.PLS_BROKEN) != 0)
- nTotalIterations = sharedPStateFlags.LowestBreakIteration - fromInclusive;
- else
- nTotalIterations = -1; //PLS_STOPPED! We can't determine this if we were stopped..
-
- TplEtwProvider.Log.ParallelLoopEnd((callingTask != null ? callingTask.m_taskScheduler.Id : TaskScheduler.Current.Id), (callingTask != null ? callingTask.Id : 0),
- forkJoinContextID, nTotalIterations);
- }
- }
-
- return result;
- }
-
- /// <summary>
- /// Performs the major work of the 64-bit parallel for loop. It assumes that argument validation has already
- /// been performed by the caller. This function's whole purpose in life is to enable as much reuse of
- /// common implementation details for the various For overloads we offer. Without it, we'd end up
- /// with lots of duplicate code. It handles: (1) simple for loops, (2) for loops that depend on
- /// ParallelState, and (3) for loops with thread local data.
- ///
- /// </summary>
- /// <typeparam name="TLocal">The type of the local data.</typeparam>
- /// <param name="fromInclusive">The loop's start index, inclusive.</param>
- /// <param name="toExclusive">The loop's end index, exclusive.</param>
- /// <param name="parallelOptions">A ParallelOptions instance.</param>
- /// <param name="body">The simple loop body.</param>
- /// <param name="bodyWithState">The loop body for ParallelState overloads.</param>
- /// <param name="bodyWithLocal">The loop body for thread local state overloads.</param>
- /// <param name="localInit">A selector function that returns new thread local state.</param>
- /// <param name="localFinally">A cleanup function to destroy thread local state.</param>
- /// <remarks>Only one of the body arguments may be supplied (i.e. they are exclusive).</remarks>
- /// <returns>A <see cref="T:System.Threading.Tasks.ParallelLoopResult"/> structure.</returns>
- private static ParallelLoopResult ForWorker64<TLocal>(
- long fromInclusive, long toExclusive,
- ParallelOptions parallelOptions,
- Action<long> body,
- Action<long, ParallelLoopState> bodyWithState,
- Func<long, ParallelLoopState, TLocal, TLocal> bodyWithLocal,
- Func<TLocal> localInit, Action<TLocal> localFinally)
- {
- Debug.Assert(((body == null ? 0 : 1) + (bodyWithState == null ? 0 : 1) + (bodyWithLocal == null ? 0 : 1)) == 1,
- "expected exactly one body function to be supplied");
- 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.
- ParallelLoopResult result = new ParallelLoopResult();
-
- // We just return immediately if 'to' is smaller (or equal to) 'from'.
- if (toExclusive <= fromInclusive)
- {
- result.m_completed = true;
- return result;
- }
-
- // For all loops we need a shared flag even though we don't have a body with state,
- // because the shared flag contains the exceptional bool, which triggers other workers
- // to exit their loops if one worker catches an exception
- ParallelLoopStateFlags64 sharedPStateFlags = new ParallelLoopStateFlags64();
-
- TaskCreationOptions creationOptions = TaskCreationOptions.None;
- InternalTaskOptions internalOptions = InternalTaskOptions.SelfReplicating;
-
- // Before getting started, do a quick peek to see if we have been canceled already
- if (parallelOptions.CancellationToken.IsCancellationRequested)
- {
- throw new OperationCanceledException(parallelOptions.CancellationToken);
- }
-
- // initialize ranges with passed in loop arguments and expected number of workers
- int numExpectedWorkers = (parallelOptions.EffectiveMaxConcurrencyLevel == -1) ?
- PlatformHelper.ProcessorCount :
- parallelOptions.EffectiveMaxConcurrencyLevel;
- RangeManager rangeManager = new RangeManager(fromInclusive, toExclusive, 1, numExpectedWorkers);
-
- // Keep track of any cancellations
- OperationCanceledException oce = null;
-
- CancellationTokenRegistration ctr = new CancellationTokenRegistration();
-
- // if cancellation is enabled, we need to register a callback to stop the loop when it gets signaled
- if (parallelOptions.CancellationToken.CanBeCanceled)
- {
- ctr = parallelOptions.CancellationToken.InternalRegisterWithoutEC((o) =>
- {
- // Cause processing to stop
- sharedPStateFlags.Cancel();
- // Record our cancellation
- oce = new OperationCanceledException(parallelOptions.CancellationToken);
- }, null);
- }
-
- // ETW event for Parallel For begin
- Task callerTask = null;
- int forkJoinContextID = 0;
- if (TplEtwProvider.Log.IsEnabled())
- {
- forkJoinContextID = Interlocked.Increment(ref s_forkJoinContextID);
- callerTask = Task.InternalCurrent;
- TplEtwProvider.Log.ParallelLoopBegin((callerTask != null ? callerTask.m_taskScheduler.Id : TaskScheduler.Current.Id), (callerTask != null ? callerTask.Id : 0),
- forkJoinContextID, TplEtwProvider.ForkJoinOperationType.ParallelFor,
- fromInclusive, toExclusive);
- }
-
- ParallelForReplicatingTask rootTask = null;
-
- try
- {
- // this needs to be in try-block because it can throw in BuggyScheduler.MaxConcurrencyLevel
- rootTask = new ParallelForReplicatingTask(
- parallelOptions,
- delegate
- {
- //
- // first thing we do upon enterying the task is to register as a new "RangeWorker" with the
- // shared RangeManager instance.
- //
- // If this call returns a RangeWorker struct which wraps the state needed by this task
- //
- // We need to call FindNewWork() on it to see whether there's a chunk available.
- //
-
- // Cache some information about the current task
- Task currentWorkerTask = Task.InternalCurrent;
- bool bIsRootTask = (currentWorkerTask == rootTask);
-
- RangeWorker currentWorker = new RangeWorker();
- Object savedStateFromPreviousReplica = currentWorkerTask.SavedStateFromPreviousReplica;
-
- if (savedStateFromPreviousReplica is RangeWorker)
- currentWorker = (RangeWorker)savedStateFromPreviousReplica;
- else
- currentWorker = rangeManager.RegisterNewWorker();
-
-
- // These are the local index values to be used in the sequential loop.
- // Their values filled in by FindNewWork
- long nFromInclusiveLocal;
- long nToExclusiveLocal;
-
- if (currentWorker.FindNewWork(out nFromInclusiveLocal, out nToExclusiveLocal) == false ||
- sharedPStateFlags.ShouldExitLoop(nFromInclusiveLocal) == true)
- {
- return; // no need to run
- }
-
- // ETW event for ParallelFor Worker Fork
- if (TplEtwProvider.Log.IsEnabled())
- {
- TplEtwProvider.Log.ParallelFork((currentWorkerTask != null ? currentWorkerTask.m_taskScheduler.Id : TaskScheduler.Current.Id), (currentWorkerTask != null ? currentWorkerTask.Id : 0),
- forkJoinContextID);
- }
-
- TLocal localValue = default(TLocal);
- bool bLocalValueInitialized = false; // Tracks whether localInit ran without exceptions, so that we can skip localFinally if it wasn't
-
- try
- {
-
- // Create a new state object that references the shared "stopped" and "exceptional" flags
- // If needed, it will contain a new instance of thread-local state by invoking the selector.
- ParallelLoopState64 state = null;
-
- if (bodyWithState != null)
- {
- Debug.Assert(sharedPStateFlags != null);
- state = new ParallelLoopState64(sharedPStateFlags);
- }
- else if (bodyWithLocal != null)
- {
- Debug.Assert(sharedPStateFlags != null);
- state = new ParallelLoopState64(sharedPStateFlags);
-
- // If a thread-local selector was supplied, invoke it. Otherwise, use the default.
- if (localInit != null)
- {
- localValue = localInit();
- bLocalValueInitialized = true;
- }
- }
-
- // initialize a loop timer which will help us decide whether we should exit early
- LoopTimer loopTimer = new LoopTimer(rootTask.ActiveChildCount);
-
- // Now perform the loop itself.
- do
- {
- if (body != null)
- {
- for (long j = nFromInclusiveLocal;
- j < nToExclusiveLocal && (sharedPStateFlags.LoopStateFlags == ParallelLoopStateFlags.PLS_NONE // fast path check as SEL() doesn't inline
- || !sharedPStateFlags.ShouldExitLoop()); // the no-arg version is used since we have no state
- j += 1)
- {
- body(j);
- }
- }
- else if (bodyWithState != null)
- {
- for (long j = nFromInclusiveLocal;
- j < nToExclusiveLocal && (sharedPStateFlags.LoopStateFlags == ParallelLoopStateFlags.PLS_NONE // fast path check as SEL() doesn't inline
- || !sharedPStateFlags.ShouldExitLoop(j));
- j += 1)
- {
- state.CurrentIteration = j;
- bodyWithState(j, state);
- }
- }
- else
- {
- for (long j = nFromInclusiveLocal;
- j < nToExclusiveLocal && (sharedPStateFlags.LoopStateFlags == ParallelLoopStateFlags.PLS_NONE // fast path check as SEL() doesn't inline
- || !sharedPStateFlags.ShouldExitLoop(j));
- j += 1)
- {
- state.CurrentIteration = j;
- localValue = bodyWithLocal(j, state, localValue);
- }
- }
-
- // Cooperative multitasking workaround for AppDomain fairness.
- // Check if allowed loop time is exceeded, if so save current state and return. The self replicating task logic
- // will detect this, and queue up a replacement task. Note that we don't do this on the root task.
- if (!bIsRootTask && loopTimer.LimitExceeded())
- {
- currentWorkerTask.SavedStateForNextReplica = (object)currentWorker;
- break;
- }
- }
- // Exit if we can't find new work, or if the loop was stoppped.
- while (currentWorker.FindNewWork(out nFromInclusiveLocal, out nToExclusiveLocal) &&
- ((sharedPStateFlags.LoopStateFlags == ParallelLoopStateFlags.PLS_NONE) ||
- !sharedPStateFlags.ShouldExitLoop(nFromInclusiveLocal)));
- }
- catch
- {
- // if we catch an exception in a worker, we signal the other workers to exit the loop, and we rethrow
- sharedPStateFlags.SetExceptional();
- throw;
- }
- finally
- {
- // If a cleanup function was specified, call it. Otherwise, if the type is
- // IDisposable, we will invoke Dispose on behalf of the user.
- if (localFinally != null && bLocalValueInitialized)
- {
- localFinally(localValue);
- }
-
- // ETW event for ParallelFor Worker Join
- if (TplEtwProvider.Log.IsEnabled())
- {
- TplEtwProvider.Log.ParallelJoin((currentWorkerTask != null ? currentWorkerTask.m_taskScheduler.Id : TaskScheduler.Current.Id), (currentWorkerTask != null ? currentWorkerTask.Id : 0),
- forkJoinContextID);
- }
- }
- },
- creationOptions, internalOptions);
-
- rootTask.RunSynchronously(parallelOptions.EffectiveTaskScheduler); // might throw TSE
- rootTask.Wait();
-
- // If we made a cancellation registration, we need to clean it up now before observing the OCE
- // Otherwise we could be caught in the middle of a callback, and observe PLS_STOPPED, but oce = null
- if (parallelOptions.CancellationToken.CanBeCanceled)
- {
- ctr.Dispose();
- }
-
- // If we got through that with no exceptions, and we were canceled, then
- // throw our cancellation exception
- if (oce != null) throw oce;
- }
- catch (AggregateException aggExp)
- {
- // if we made a cancellation registration, and rootTask.Wait threw, we need to clean it up here
- if (parallelOptions.CancellationToken.CanBeCanceled)
- {
- ctr.Dispose();
- }
-
- // see if we can combine it into a single OCE. If not propagate the original exception
- ThrowIfReducableToSingleOCE(aggExp.InnerExceptions, parallelOptions.CancellationToken);
- throw;
- }
- catch (TaskSchedulerException)
- {
- // if we made a cancellation registration, and rootTask.RunSynchronously threw, we need to clean it up here
- if (parallelOptions.CancellationToken.CanBeCanceled)
- {
- ctr.Dispose();
- }
- throw;
- }
- finally
- {
- int sb_status = sharedPStateFlags.LoopStateFlags;
- result.m_completed = (sb_status == ParallelLoopStateFlags.PLS_NONE);
- if ((sb_status & ParallelLoopStateFlags.PLS_BROKEN) != 0)
- {
- result.m_lowestBreakIteration = sharedPStateFlags.LowestBreakIteration;
- }
-
- if ((rootTask != null) && rootTask.IsCompleted) rootTask.Dispose();
-
- // ETW event for Parallel For End
- if (TplEtwProvider.Log.IsEnabled())
- {
- long nTotalIterations = 0;
-
- // calculate how many iterations we ran in total
- if (sb_status == ParallelLoopStateFlags.PLS_NONE)
- nTotalIterations = toExclusive - fromInclusive;
- else if ((sb_status & ParallelLoopStateFlags.PLS_BROKEN) != 0)
- nTotalIterations = sharedPStateFlags.LowestBreakIteration - fromInclusive;
- else
- nTotalIterations = -1; //PLS_STOPPED! We can't determine this if we were stopped..
-
- TplEtwProvider.Log.ParallelLoopEnd((callerTask != null ? callerTask.m_taskScheduler.Id : TaskScheduler.Current.Id), (callerTask != null ? callerTask.Id : 0),
- forkJoinContextID, nTotalIterations);
- }
- }
-
- return result;
- }
-
-
- /// <summary>
- /// Executes a for each operation on an <see cref="T:System.Collections.IEnumerable{TSource}"/>
- /// in which iterations may run in parallel.
- /// </summary>
- /// <typeparam name="TSource">The type of the data in the source.</typeparam>
- /// <param name="source">An enumerable data source.</param>
- /// <param name="body">The delegate that is invoked once per iteration.</param>
- /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the <paramref name="source"/>
- /// argument is null.</exception>
- /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the <paramref name="body"/>
- /// argument is null.</exception>
- /// <exception cref="T:System.AggregateException">The exception that is thrown to contain an exception
- /// thrown from one of the specified delegates.</exception>
- /// <returns>A <see cref="T:System.Threading.Tasks.ParallelLoopResult">ParallelLoopResult</see> structure
- /// that contains information on what portion of the loop completed.</returns>
- /// <remarks>
- /// The <paramref name="body"/> delegate is invoked once for each element in the <paramref name="source"/>
- /// enumerable. It is provided with the current element as a parameter.
- /// </remarks>
- public static ParallelLoopResult ForEach<TSource>(IEnumerable<TSource> source, Action<TSource> body)
- {
- if (source == null)
- {
- throw new ArgumentNullException(nameof(source));
- }
- if (body == null)
- {
- throw new ArgumentNullException(nameof(body));
- }
-
- return ForEachWorker<TSource, object>(
- source, s_defaultParallelOptions, body, null, null, null, null, null, null);
- }
-
- /// <summary>
- /// Executes a for each operation on an <see cref="T:System.Collections.IEnumerable{TSource}"/>
- /// in which iterations may run in parallel.
- /// </summary>
- /// <typeparam name="TSource">The type of the data in the source.</typeparam>
- /// <param name="source">An enumerable data source.</param>
- /// <param name="parallelOptions">A <see cref="T:System.Threading.Tasks.ParallelOptions">ParallelOptions</see>
- /// instance that configures the behavior of this operation.</param>
- /// <param name="body">The delegate that is invoked once per iteration.</param>
- /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the <paramref name="source"/>
- /// argument is null.</exception>
- /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the
- /// <paramref name="parallelOptions"/> argument is null.</exception>
- /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the <paramref name="body"/>
- /// argument is null.</exception>
- /// <exception cref="T:System.OperationCanceledException">The exception that is thrown when the
- /// <see cref="T:System.Threading.CancellationToken">CancellationToken</see> in the <paramref name="parallelOptions"/>
- /// argument is set</exception>
- /// <exception cref="T:System.AggregateException">The exception that is thrown to contain an exception
- /// thrown from one of the specified delegates.</exception>
- /// <exception cref="T:System.ObjectDisposedException">The exception that is thrown when the
- /// the <see cref="T:System.Threading.CancellationTokenSource">CancellationTokenSource</see> associated with the
- /// the <see cref="T:System.Threading.CancellationToken">CancellationToken</see> in the
- /// <paramref name="parallelOptions"/> has been disposed.</exception>
- /// <returns>A <see cref="T:System.Threading.Tasks.ParallelLoopResult">ParallelLoopResult</see> structure
- /// that contains information on what portion of the loop completed.</returns>
- /// <remarks>
- /// The <paramref name="body"/> delegate is invoked once for each element in the <paramref name="source"/>
- /// enumerable. It is provided with the current element as a parameter.
- /// </remarks>
- public static ParallelLoopResult ForEach<TSource>(IEnumerable<TSource> source, ParallelOptions parallelOptions, Action<TSource> body)
- {
- if (source == null)
- {
- throw new ArgumentNullException(nameof(source));
- }
- if (body == null)
- {
- throw new ArgumentNullException(nameof(body));
- }
- if (parallelOptions == null)
- {
- throw new ArgumentNullException(nameof(parallelOptions));
- }
-
- return ForEachWorker<TSource, object>(
- source, parallelOptions, body, null, null, null, null, null, null);
- }
-
- /// <summary>
- /// Executes a for each operation on an <see cref="T:System.Collections.IEnumerable{TSource}"/>
- /// in which iterations may run in parallel.
- /// </summary>
- /// <typeparam name="TSource">The type of the data in the source.</typeparam>
- /// <param name="source">An enumerable data source.</param>
- /// <param name="body">The delegate that is invoked once per iteration.</param>
- /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the <paramref name="source"/>
- /// argument is null.</exception>
- /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the <paramref name="body"/>
- /// argument is null.</exception>
- /// <exception cref="T:System.AggregateException">The exception that is thrown to contain an exception
- /// thrown from one of the specified delegates.</exception>
- /// <returns>A <see cref="T:System.Threading.Tasks.ParallelLoopResult">ParallelLoopResult</see> structure
- /// that contains information on what portion of the loop completed.</returns>
- /// <remarks>
- /// The <paramref name="body"/> delegate is invoked once for each element in the <paramref name="source"/>
- /// enumerable. It is provided with the following parameters: the current element,
- /// and a <see cref="System.Threading.Tasks.ParallelLoopState">ParallelLoopState</see> instance that may be
- /// used to break out of the loop prematurely.
- /// </remarks>
- public static ParallelLoopResult ForEach<TSource>(IEnumerable<TSource> source, Action<TSource, ParallelLoopState> body)
- {
- if (source == null)
- {
- throw new ArgumentNullException(nameof(source));
- }
- if (body == null)
- {
- throw new ArgumentNullException(nameof(body));
- }
-
- return ForEachWorker<TSource, object>(
- source, s_defaultParallelOptions, null, body, null, null, null, null, null);
- }
-
- /// <summary>
- /// Executes a for each operation on an <see cref="T:System.Collections.IEnumerable{TSource}"/>
- /// in which iterations may run in parallel.
- /// </summary>
- /// <typeparam name="TSource">The type of the data in the source.</typeparam>
- /// <param name="source">An enumerable data source.</param>
- /// <param name="parallelOptions">A <see cref="T:System.Threading.Tasks.ParallelOptions">ParallelOptions</see>
- /// instance that configures the behavior of this operation.</param>
- /// <param name="body">The delegate that is invoked once per iteration.</param>
- /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the <paramref name="source"/>
- /// argument is null.</exception>
- /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the
- /// <paramref name="parallelOptions"/> argument is null.</exception>
- /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the <paramref name="body"/>
- /// argument is null.</exception>
- /// <exception cref="T:System.OperationCanceledException">The exception that is thrown when the
- /// <see cref="T:System.Threading.CancellationToken">CancellationToken</see> in the <paramref name="parallelOptions"/>
- /// argument is set</exception>
- /// <exception cref="T:System.AggregateException">The exception that is thrown to contain an exception
- /// thrown from one of the specified delegates.</exception>
- /// <exception cref="T:System.ObjectDisposedException">The exception that is thrown when the
- /// the <see cref="T:System.Threading.CancellationTokenSource">CancellationTokenSource</see> associated with the
- /// the <see cref="T:System.Threading.CancellationToken">CancellationToken</see> in the
- /// <paramref name="parallelOptions"/> has been disposed.</exception>
- /// <returns>A <see cref="T:System.Threading.Tasks.ParallelLoopResult">ParallelLoopResult</see> structure
- /// that contains information on what portion of the loop completed.</returns>
- /// <remarks>
- /// The <paramref name="body"/> delegate is invoked once for each element in the <paramref name="source"/>
- /// enumerable. It is provided with the following parameters: the current element,
- /// and a <see cref="System.Threading.Tasks.ParallelLoopState">ParallelLoopState</see> instance that may be
- /// used to break out of the loop prematurely.
- /// </remarks>
- public static ParallelLoopResult ForEach<TSource>(IEnumerable<TSource> source, ParallelOptions parallelOptions, Action<TSource, ParallelLoopState> body)
- {
- if (source == null)
- {
- throw new ArgumentNullException(nameof(source));
- }
- if (body == null)
- {
- throw new ArgumentNullException(nameof(body));
- }
- if (parallelOptions == null)
- {
- throw new ArgumentNullException(nameof(parallelOptions));
- }
-
- return ForEachWorker<TSource, object>(
- source, parallelOptions, null, body, null, null, null, null, null);
- }
-
- /// <summary>
- /// Executes a for each operation on an <see cref="T:System.Collections.IEnumerable{TSource}"/>
- /// in which iterations may run in parallel.
- /// </summary>
- /// <typeparam name="TSource">The type of the data in the source.</typeparam>
- /// <param name="source">An enumerable data source.</param>
- /// <param name="body">The delegate that is invoked once per iteration.</param>
- /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the <paramref name="source"/>
- /// argument is null.</exception>
- /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the <paramref name="body"/>
- /// argument is null.</exception>
- /// <exception cref="T:System.AggregateException">The exception that is thrown to contain an exception
- /// thrown from one of the specified delegates.</exception>
- /// <returns>A <see cref="T:System.Threading.Tasks.ParallelLoopResult">ParallelLoopResult</see> structure
- /// that contains information on what portion of the loop completed.</returns>
- /// <remarks>
- /// The <paramref name="body"/> delegate is invoked once for each element in the <paramref name="source"/>
- /// enumerable. It is provided with the following parameters: the current element,
- /// a <see cref="System.Threading.Tasks.ParallelLoopState">ParallelLoopState</see> instance that may be
- /// used to break out of the loop prematurely, and the current element's index (an Int64).
- /// </remarks>
- public static ParallelLoopResult ForEach<TSource>(IEnumerable<TSource> source, Action<TSource, ParallelLoopState, long> body)
- {
- if (source == null)
- {
- throw new ArgumentNullException(nameof(source));
- }
- if (body == null)
- {
- throw new ArgumentNullException(nameof(body));
- }
-
- return ForEachWorker<TSource, object>(
- source, s_defaultParallelOptions, null, null, body, null, null, null, null);
- }
-
- /// <summary>
- /// Executes a for each operation on an <see cref="T:System.Collections.IEnumerable{TSource}"/>
- /// in which iterations may run in parallel.
- /// </summary>
- /// <typeparam name="TSource">The type of the data in the source.</typeparam>
- /// <param name="source">An enumerable data source.</param>
- /// <param name="parallelOptions">A <see cref="T:System.Threading.Tasks.ParallelOptions">ParallelOptions</see>
- /// instance that configures the behavior of this operation.</param>
- /// <param name="body">The delegate that is invoked once per iteration.</param>
- /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the <paramref name="source"/>
- /// argument is null.</exception>
- /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the
- /// <paramref name="parallelOptions"/> argument is null.</exception>
- /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the <paramref name="body"/>
- /// argument is null.</exception>
- /// <exception cref="T:System.OperationCanceledException">The exception that is thrown when the
- /// <see cref="T:System.Threading.CancellationToken">CancellationToken</see> in the <paramref name="parallelOptions"/>
- /// argument is set</exception>
- /// <exception cref="T:System.AggregateException">The exception that is thrown to contain an exception
- /// thrown from one of the specified delegates.</exception>
- /// <exception cref="T:System.ObjectDisposedException">The exception that is thrown when the
- /// the <see cref="T:System.Threading.CancellationTokenSource">CancellationTokenSource</see> associated with the
- /// the <see cref="T:System.Threading.CancellationToken">CancellationToken</see> in the
- /// <paramref name="parallelOptions"/> has been disposed.</exception>
- /// <returns>A <see cref="T:System.Threading.Tasks.ParallelLoopResult">ParallelLoopResult</see> structure
- /// that contains information on what portion of the loop completed.</returns>
- /// <remarks>
- /// The <paramref name="body"/> delegate is invoked once for each element in the <paramref name="source"/>
- /// enumerable. It is provided with the following parameters: the current element,
- /// a <see cref="System.Threading.Tasks.ParallelLoopState">ParallelLoopState</see> instance that may be
- /// used to break out of the loop prematurely, and the current element's index (an Int64).
- /// </remarks>
- public static ParallelLoopResult ForEach<TSource>(IEnumerable<TSource> source, ParallelOptions parallelOptions, Action<TSource, ParallelLoopState, long> body)
- {
- if (source == null)
- {
- throw new ArgumentNullException(nameof(source));
- }
- if (body == null)
- {
- throw new ArgumentNullException(nameof(body));
- }
- if (parallelOptions == null)
- {
- throw new ArgumentNullException(nameof(parallelOptions));
- }
-
- return ForEachWorker<TSource, object>(
- source, parallelOptions, null, null, body, null, null, null, null);
- }
-
- /// <summary>
- /// Executes a for each operation on an <see cref="T:System.Collections.IEnumerable{TSource}"/>
- /// in which iterations may run in parallel.
- /// </summary>
- /// <typeparam name="TSource">The type of the data in the source.</typeparam>
- /// <typeparam name="TLocal">The type of the thread-local data.</typeparam>
- /// <param name="source">An enumerable data source.</param>
- /// <param name="localInit">The function delegate that returns the initial state of the local data
- /// for each thread.</param>
- /// <param name="body">The delegate that is invoked once per iteration.</param>
- /// <param name="localFinally">The delegate that performs a final action on the local state of each
- /// thread.</param>
- /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the <paramref name="source"/>
- /// argument is null.</exception>
- /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the <paramref name="body"/>
- /// argument is null.</exception>
- /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the
- /// <paramref name="localInit"/> argument is null.</exception>
- /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the
- /// <paramref name="localFinally"/> argument is null.</exception>
- /// <exception cref="T:System.AggregateException">The exception that is thrown to contain an exception
- /// thrown from one of the specified delegates.</exception>
- /// <returns>A <see cref="T:System.Threading.Tasks.ParallelLoopResult">ParallelLoopResult</see> structure
- /// that contains information on what portion of the loop completed.</returns>
- /// <remarks>
- /// <para>
- /// The <paramref name="body"/> delegate is invoked once for each element in the <paramref name="source"/>
- /// enumerable. It is provided with the following parameters: the current element,
- /// a <see cref="System.Threading.Tasks.ParallelLoopState">ParallelLoopState</see> instance that may be
- /// used to break out of the loop prematurely, and some local state that may be shared amongst iterations
- /// that execute on the same thread.
- /// </para>
- /// <para>
- /// The <paramref name="localInit"/> delegate is invoked once for each thread that participates in the loop's
- /// execution and returns the initial local state for each of those threads. These initial states are passed to the first
- /// <paramref name="body"/> invocations on each thread. Then, every subsequent body invocation returns a possibly
- /// modified state value that is passed to the next body invocation. Finally, the last body invocation on each thread returns a state value
- /// that is passed to the <paramref name="localFinally"/> delegate. The localFinally delegate is invoked once per thread to perform a final
- /// action on each thread's local state.
- /// </para>
- /// </remarks>
- public static ParallelLoopResult ForEach<TSource, TLocal>(IEnumerable<TSource> source, Func<TLocal> localInit,
- Func<TSource, ParallelLoopState, TLocal, TLocal> body, Action<TLocal> localFinally)
- {
- if (source == null)
- {
- throw new ArgumentNullException(nameof(source));
- }
- if (body == null)
- {
- throw new ArgumentNullException(nameof(body));
- }
- if (localInit == null)
- {
- throw new ArgumentNullException(nameof(localInit));
- }
- if (localFinally == null)
- {
- throw new ArgumentNullException(nameof(localFinally));
- }
-
- return ForEachWorker<TSource, TLocal>(
- source, s_defaultParallelOptions, null, null, null, body, null, localInit, localFinally);
- }
-
- /// <summary>
- /// Executes a for each operation on an <see cref="T:System.Collections.IEnumerable{TSource}"/>
- /// in which iterations may run in parallel.
- /// </summary>
- /// <typeparam name="TSource">The type of the data in the source.</typeparam>
- /// <typeparam name="TLocal">The type of the thread-local data.</typeparam>
- /// <param name="source">An enumerable data source.</param>
- /// <param name="parallelOptions">A <see cref="T:System.Threading.Tasks.ParallelOptions">ParallelOptions</see>
- /// instance that configures the behavior of this operation.</param>
- /// <param name="localInit">The function delegate that returns the initial state of the local data
- /// for each thread.</param>
- /// <param name="body">The delegate that is invoked once per iteration.</param>
- /// <param name="localFinally">The delegate that performs a final action on the local state of each
- /// thread.</param>
- /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the <paramref name="source"/>
- /// argument is null.</exception>
- /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the
- /// <paramref name="parallelOptions"/> argument is null.</exception>
- /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the <paramref name="body"/>
- /// argument is null.</exception>
- /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the
- /// <paramref name="localInit"/> argument is null.</exception>
- /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the
- /// <paramref name="localFinally"/> argument is null.</exception>
- /// <exception cref="T:System.OperationCanceledException">The exception that is thrown when the
- /// <see cref="T:System.Threading.CancellationToken">CancellationToken</see> in the <paramref name="parallelOptions"/>
- /// argument is set</exception>
- /// <exception cref="T:System.AggregateException">The exception that is thrown to contain an exception
- /// thrown from one of the specified delegates.</exception>
- /// <exception cref="T:System.ObjectDisposedException">The exception that is thrown when the
- /// the <see cref="T:System.Threading.CancellationTokenSource">CancellationTokenSource</see> associated with the
- /// the <see cref="T:System.Threading.CancellationToken">CancellationToken</see> in the
- /// <paramref name="parallelOptions"/> has been disposed.</exception>
- /// <returns>A <see cref="T:System.Threading.Tasks.ParallelLoopResult">ParallelLoopResult</see> structure
- /// that contains information on what portion of the loop completed.</returns>
- /// <remarks>
- /// <para>
- /// The <paramref name="body"/> delegate is invoked once for each element in the <paramref name="source"/>
- /// enumerable. It is provided with the following parameters: the current element,
- /// a <see cref="System.Threading.Tasks.ParallelLoopState">ParallelLoopState</see> instance that may be
- /// used to break out of the loop prematurely, and some local state that may be shared amongst iterations
- /// that execute on the same thread.
- /// </para>
- /// <para>
- /// The <paramref name="localInit"/> delegate is invoked once for each thread that participates in the loop's
- /// execution and returns the initial local state for each of those threads. These initial states are passed to the first
- /// <paramref name="body"/> invocations on each thread. Then, every subsequent body invocation returns a possibly
- /// modified state value that is passed to the next body invocation. Finally, the last body invocation on each thread returns a state value
- /// that is passed to the <paramref name="localFinally"/> delegate. The localFinally delegate is invoked once per thread to perform a final
- /// action on each thread's local state.
- /// </para>
- /// </remarks>
- public static ParallelLoopResult ForEach<TSource, TLocal>(IEnumerable<TSource> source,
- ParallelOptions parallelOptions, Func<TLocal> localInit,
- Func<TSource, ParallelLoopState, TLocal, TLocal> body, Action<TLocal> localFinally)
- {
- if (source == null)
- {
- throw new ArgumentNullException(nameof(source));
- }
- if (body == null)
- {
- throw new ArgumentNullException(nameof(body));
- }
- if (localInit == null)
- {
- throw new ArgumentNullException(nameof(localInit));
- }
- if (localFinally == null)
- {
- throw new ArgumentNullException(nameof(localFinally));
- }
- if (parallelOptions == null)
- {
- throw new ArgumentNullException(nameof(parallelOptions));
- }
-
- return ForEachWorker<TSource, TLocal>(
- source, parallelOptions, null, null, null, body, null, localInit, localFinally);
- }
-
- /// <summary>
- /// Executes a for each operation on an <see cref="T:System.Collections.IEnumerable{TSource}"/>
- /// in which iterations may run in parallel.
- /// </summary>
- /// <typeparam name="TSource">The type of the data in the source.</typeparam>
- /// <typeparam name="TLocal">The type of the thread-local data.</typeparam>
- /// <param name="source">An enumerable data source.</param>
- /// <param name="localInit">The function delegate that returns the initial state of the local data
- /// for each thread.</param>
- /// <param name="body">The delegate that is invoked once per iteration.</param>
- /// <param name="localFinally">The delegate that performs a final action on the local state of each
- /// thread.</param>
- /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the <paramref name="source"/>
- /// argument is null.</exception>
- /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the <paramref name="body"/>
- /// argument is null.</exception>
- /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the
- /// <paramref name="localInit"/> argument is null.</exception>
- /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the
- /// <paramref name="localFinally"/> argument is null.</exception>
- /// <exception cref="T:System.AggregateException">The exception that is thrown to contain an exception
- /// thrown from one of the specified delegates.</exception>
- /// <returns>A <see cref="T:System.Threading.Tasks.ParallelLoopResult">ParallelLoopResult</see> structure
- /// that contains information on what portion of the loop completed.</returns>
- /// <remarks>
- /// <para>
- /// The <paramref name="body"/> delegate is invoked once for each element in the <paramref name="source"/>
- /// enumerable. It is provided with the following parameters: the current element,
- /// a <see cref="System.Threading.Tasks.ParallelLoopState">ParallelLoopState</see> instance that may be
- /// used to break out of the loop prematurely, the current element's index (an Int64), and some local
- /// state that may be shared amongst iterations that execute on the same thread.
- /// </para>
- /// <para>
- /// The <paramref name="localInit"/> delegate is invoked once for each thread that participates in the loop's
- /// execution and returns the initial local state for each of those threads. These initial states are passed to the first
- /// <paramref name="body"/> invocations on each thread. Then, every subsequent body invocation returns a possibly
- /// modified state value that is passed to the next body invocation. Finally, the last body invocation on each thread returns a state value
- /// that is passed to the <paramref name="localFinally"/> delegate. The localFinally delegate is invoked once per thread to perform a final
- /// action on each thread's local state.
- /// </para>
- /// </remarks>
- public static ParallelLoopResult ForEach<TSource, TLocal>(IEnumerable<TSource> source, Func<TLocal> localInit,
- Func<TSource, ParallelLoopState, long, TLocal, TLocal> body, Action<TLocal> localFinally)
- {
- if (source == null)
- {
- throw new ArgumentNullException(nameof(source));
- }
- if (body == null)
- {
- throw new ArgumentNullException(nameof(body));
- }
- if (localInit == null)
- {
- throw new ArgumentNullException(nameof(localInit));
- }
- if (localFinally == null)
- {
- throw new ArgumentNullException(nameof(localFinally));
- }
-
- return ForEachWorker<TSource, TLocal>(
- source, s_defaultParallelOptions, null, null, null, null, body, localInit, localFinally);
- }
-
- /// <summary>
- /// Executes a for each operation on an <see cref="T:System.Collections.IEnumerable{TSource}"/>
- /// in which iterations may run in parallel.
- /// </summary>
- /// <typeparam name="TSource">The type of the data in the source.</typeparam>
- /// <typeparam name="TLocal">The type of the thread-local data.</typeparam>
- /// <param name="source">An enumerable data source.</param>
- /// <param name="parallelOptions">A <see cref="T:System.Threading.Tasks.ParallelOptions">ParallelOptions</see>
- /// instance that configures the behavior of this operation.</param>
- /// <param name="localInit">The function delegate that returns the initial state of the local data
- /// for each thread.</param>
- /// <param name="body">The delegate that is invoked once per iteration.</param>
- /// <param name="localFinally">The delegate that performs a final action on the local state of each
- /// thread.</param>
- /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the <paramref name="source"/>
- /// argument is null.</exception>
- /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the
- /// <paramref name="parallelOptions"/> argument is null.</exception>
- /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the <paramref name="body"/>
- /// argument is null.</exception>
- /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the
- /// <paramref name="localInit"/> argument is null.</exception>
- /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the
- /// <paramref name="localFinally"/> argument is null.</exception>
- /// <exception cref="T:System.OperationCanceledException">The exception that is thrown when the
- /// <see cref="T:System.Threading.CancellationToken">CancellationToken</see> in the <paramref name="parallelOptions"/>
- /// argument is set</exception>
- /// <exception cref="T:System.AggregateException">The exception that is thrown to contain an exception
- /// thrown from one of the specified delegates.</exception>
- /// <exception cref="T:System.ObjectDisposedException">The exception that is thrown when the
- /// the <see cref="T:System.Threading.CancellationTokenSource">CancellationTokenSource</see> associated with the
- /// the <see cref="T:System.Threading.CancellationToken">CancellationToken</see> in the
- /// <paramref name="parallelOptions"/> has been disposed.</exception>
- /// <returns>A <see cref="T:System.Threading.Tasks.ParallelLoopResult">ParallelLoopResult</see> structure
- /// that contains information on what portion of the loop completed.</returns>
- /// <remarks>
- /// <para>
- /// The <paramref name="body"/> delegate is invoked once for each element in the <paramref name="source"/>
- /// enumerable. It is provided with the following parameters: the current element,
- /// a <see cref="System.Threading.Tasks.ParallelLoopState">ParallelLoopState</see> instance that may be
- /// used to break out of the loop prematurely, the current element's index (an Int64), and some local
- /// state that may be shared amongst iterations that execute on the same thread.
- /// </para>
- /// <para>
- /// The <paramref name="localInit"/> delegate is invoked once for each thread that participates in the loop's
- /// execution and returns the initial local state for each of those threads. These initial states are passed to the first
- /// <paramref name="body"/> invocations on each thread. Then, every subsequent body invocation returns a possibly
- /// modified state value that is passed to the next body invocation. Finally, the last body invocation on each thread returns a state value
- /// that is passed to the <paramref name="localFinally"/> delegate. The localFinally delegate is invoked once per thread to perform a final
- /// action on each thread's local state.
- /// </para>
- /// </remarks>
- public static ParallelLoopResult ForEach<TSource, TLocal>(IEnumerable<TSource> source, ParallelOptions parallelOptions, Func<TLocal> localInit,
- Func<TSource, ParallelLoopState, long, TLocal, TLocal> body, Action<TLocal> localFinally)
- {
- if (source == null)
- {
- throw new ArgumentNullException(nameof(source));
- }
- if (body == null)
- {
- throw new ArgumentNullException(nameof(body));
- }
- if (localInit == null)
- {
- throw new ArgumentNullException(nameof(localInit));
- }
- if (localFinally == null)
- {
- throw new ArgumentNullException(nameof(localFinally));
- }
- if (parallelOptions == null)
- {
- throw new ArgumentNullException(nameof(parallelOptions));
- }
-
- return ForEachWorker<TSource, TLocal>(
- source, parallelOptions, null, null, null, null, body, localInit, localFinally);
- }
-
-
- /// <summary>
- /// Performs the major work of the parallel foreach loop. It assumes that argument validation has
- /// already been performed by the caller. This function's whole purpose in life is to enable as much
- /// reuse of common implementation details for the various For overloads we offer. Without it, we'd
- /// end up with lots of duplicate code. It handles: (1) simple foreach loops, (2) foreach loops that
- /// depend on ParallelState, and (3) foreach loops that access indices, (4) foreach loops with thread
- /// local data, and any necessary permutations thereof.
- ///
- /// </summary>
- /// <typeparam name="TSource">The type of the source data.</typeparam>
- /// <typeparam name="TLocal">The type of the local data.</typeparam>
- /// <param name="source">An enumerable data source.</param>
- /// <param name="parallelOptions">ParallelOptions instance to use with this ForEach-loop</param>
- /// <param name="body">The simple loop body.</param>
- /// <param name="bodyWithState">The loop body for ParallelState overloads.</param>
- /// <param name="bodyWithStateAndIndex">The loop body for ParallelState/indexed overloads.</param>
- /// <param name="bodyWithStateAndLocal">The loop body for ParallelState/thread local state overloads.</param>
- /// <param name="bodyWithEverything">The loop body for ParallelState/indexed/thread local state overloads.</param>
- /// <param name="localInit">A selector function that returns new thread local state.</param>
- /// <param name="localFinally">A cleanup function to destroy thread local state.</param>
- /// <remarks>Only one of the bodyXX arguments may be supplied (i.e. they are exclusive).</remarks>
- /// <returns>A <see cref="T:System.Threading.Tasks.ParallelLoopResult"/> structure.</returns>
- private static ParallelLoopResult ForEachWorker<TSource, TLocal>(
- IEnumerable<TSource> source,
- ParallelOptions parallelOptions,
- Action<TSource> body,
- Action<TSource, ParallelLoopState> bodyWithState,
- Action<TSource, ParallelLoopState, long> bodyWithStateAndIndex,
- Func<TSource, ParallelLoopState, TLocal, TLocal> bodyWithStateAndLocal,
- Func<TSource, ParallelLoopState, long, TLocal, TLocal> bodyWithEverything,
- Func<TLocal> localInit, Action<TLocal> localFinally)
- {
- 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");
- 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
- if (parallelOptions.CancellationToken.IsCancellationRequested)
- {
- throw new OperationCanceledException(parallelOptions.CancellationToken);
- }
-
- // If it's an array, we can use a fast-path that uses ldelems in the IL.
- TSource[] sourceAsArray = source as TSource[];
- if (sourceAsArray != null)
- {
- return ForEachWorker<TSource, TLocal>(
- sourceAsArray, parallelOptions, body, bodyWithState, bodyWithStateAndIndex, bodyWithStateAndLocal,
- bodyWithEverything, localInit, localFinally);
- }
-
- // If we can index into the list, we can use a faster code-path that doesn't result in
- // contention for the single, shared enumerator object.
- IList<TSource> sourceAsList = source as IList<TSource>;
- if (sourceAsList != null)
- {
- return ForEachWorker<TSource, TLocal>(
- sourceAsList, parallelOptions, body, bodyWithState, bodyWithStateAndIndex, bodyWithStateAndLocal,
- bodyWithEverything, localInit, localFinally);
- }
-
- // This is an honest-to-goodness IEnumerable. Wrap it in a Partitioner and defer to our
- // ForEach(Partitioner) logic.
- return PartitionerForEachWorker<TSource, TLocal>(Partitioner.Create(source), parallelOptions, body, bodyWithState,
- bodyWithStateAndIndex, bodyWithStateAndLocal, bodyWithEverything, localInit, localFinally);
-
- }
-
- /// <summary>
- /// A fast path for the more general ForEachWorker method above. This uses ldelem instructions to
- /// access the individual elements of the array, which will be faster.
- /// </summary>
- /// <typeparam name="TSource">The type of the source data.</typeparam>
- /// <typeparam name="TLocal">The type of the local data.</typeparam>
- /// <param name="array">An array data source.</param>
- /// <param name="parallelOptions">The options to use for execution.</param>
- /// <param name="body">The simple loop body.</param>
- /// <param name="bodyWithState">The loop body for ParallelState overloads.</param>
- /// <param name="bodyWithStateAndIndex">The loop body for indexed/ParallelLoopState overloads.</param>
- /// <param name="bodyWithStateAndLocal">The loop body for local/ParallelLoopState overloads.</param>
- /// <param name="bodyWithEverything">The loop body for the most generic overload.</param>
- /// <param name="localInit">A selector function that returns new thread local state.</param>
- /// <param name="localFinally">A cleanup function to destroy thread local state.</param>
- /// <returns>A <see cref="T:System.Threading.Tasks.ParallelLoopResult"/> structure.</returns>
- private static ParallelLoopResult ForEachWorker<TSource, TLocal>(
- TSource[] array,
- ParallelOptions parallelOptions,
- Action<TSource> body,
- Action<TSource, ParallelLoopState> bodyWithState,
- Action<TSource, ParallelLoopState, long> bodyWithStateAndIndex,
- Func<TSource, ParallelLoopState, TLocal, TLocal> bodyWithStateAndLocal,
- Func<TSource, ParallelLoopState, long, TLocal, TLocal> bodyWithEverything,
- Func<TLocal> localInit, Action<TLocal> localFinally)
- {
- Debug.Assert(array != null);
- Debug.Assert(parallelOptions != null, "ForEachWorker(array): parallelOptions is null");
-
- int from = array.GetLowerBound(0);
- int to = array.GetUpperBound(0) + 1;
-
- if (body != null)
- {
- return ForWorker<object>(
- from, to, parallelOptions, (i) => body(array[i]), null, null, null, null);
- }
- else if (bodyWithState != null)
- {
- return ForWorker<object>(
- from, to, parallelOptions, null, (i, state) => bodyWithState(array[i], state), null, null, null);
- }
- else if (bodyWithStateAndIndex != null)
- {
- return ForWorker<object>(
- from, to, parallelOptions, null, (i, state) => bodyWithStateAndIndex(array[i], state, i), null, null, null);
- }
- else if (bodyWithStateAndLocal != null)
- {
- return ForWorker<TLocal>(
- from, to, parallelOptions, null, null, (i, state, local) => bodyWithStateAndLocal(array[i], state, local), localInit, localFinally);
- }
- else
- {
- return ForWorker<TLocal>(
- from, to, parallelOptions, null, null, (i, state, local) => bodyWithEverything(array[i], state, i, local), localInit, localFinally);
- }
- }
-
- /// <summary>
- /// A fast path for the more general ForEachWorker method above. This uses IList&lt;T&gt;'s indexer
- /// capabilities to access the individual elements of the list rather than an enumerator.
- /// </summary>
- /// <typeparam name="TSource">The type of the source data.</typeparam>
- /// <typeparam name="TLocal">The type of the local data.</typeparam>
- /// <param name="list">A list data source.</param>
- /// <param name="parallelOptions">The options to use for execution.</param>
- /// <param name="body">The simple loop body.</param>
- /// <param name="bodyWithState">The loop body for ParallelState overloads.</param>
- /// <param name="bodyWithStateAndIndex">The loop body for indexed/ParallelLoopState overloads.</param>
- /// <param name="bodyWithStateAndLocal">The loop body for local/ParallelLoopState overloads.</param>
- /// <param name="bodyWithEverything">The loop body for the most generic overload.</param>
- /// <param name="localInit">A selector function that returns new thread local state.</param>
- /// <param name="localFinally">A cleanup function to destroy thread local state.</param>
- /// <returns>A <see cref="T:System.Threading.Tasks.ParallelLoopResult"/> structure.</returns>
- private static ParallelLoopResult ForEachWorker<TSource, TLocal>(
- IList<TSource> list,
- ParallelOptions parallelOptions,
- Action<TSource> body,
- Action<TSource, ParallelLoopState> bodyWithState,
- Action<TSource, ParallelLoopState, long> bodyWithStateAndIndex,
- Func<TSource, ParallelLoopState, TLocal, TLocal> bodyWithStateAndLocal,
- Func<TSource, ParallelLoopState, long, TLocal, TLocal> bodyWithEverything,
- Func<TLocal> localInit, Action<TLocal> localFinally)
- {
- Debug.Assert(list != null);
- Debug.Assert(parallelOptions != null, "ForEachWorker(list): parallelOptions is null");
-
- if (body != null)
- {
- return ForWorker<object>(
- 0, list.Count, parallelOptions, (i) => body(list[i]), null, null, null, null);
- }
- else if (bodyWithState != null)
- {
- return ForWorker<object>(
- 0, list.Count, parallelOptions, null, (i, state) => bodyWithState(list[i], state), null, null, null);
- }
- else if (bodyWithStateAndIndex != null)
- {
- return ForWorker<object>(
- 0, list.Count, parallelOptions, null, (i, state) => bodyWithStateAndIndex(list[i], state, i), null, null, null);
- }
- else if (bodyWithStateAndLocal != null)
- {
- return ForWorker<TLocal>(
- 0, list.Count, parallelOptions, null, null, (i, state, local) => bodyWithStateAndLocal(list[i], state, local), localInit, localFinally);
- }
- else
- {
- return ForWorker<TLocal>(
- 0, list.Count, parallelOptions, null, null, (i, state, local) => bodyWithEverything(list[i], state, i, local), localInit, localFinally);
- }
- }
-
-
-
- /// <summary>
- /// Executes a for each operation on a <see cref="T:System.Collections.Concurrent.Partitioner{TSource}">
- /// Partitioner</see> in which iterations may run in parallel.
- /// </summary>
- /// <typeparam name="TSource">The type of the elements in <paramref name="source"/>.</typeparam>
- /// <param name="source">The Partitioner that contains the original data source.</param>
- /// <param name="body">The delegate that is invoked once per iteration.</param>
- /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the <paramref name="source"/>
- /// argument is null.</exception>
- /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the <paramref name="body"/>
- /// argument is null.</exception>
- /// <exception cref="T:System.InvalidOperationException">The exception that is thrown when the
- /// SupportsDynamicPartitions property in the <paramref name="source"/> Partitioner returns
- /// false.</exception>
- /// <exception cref="T:System.InvalidOperationException">The exception that is thrown when any
- /// methods in the <paramref name="source"/> Partitioner return null.</exception>
- /// <exception cref="T:System.InvalidOperationException">The exception that is thrown when the
- /// GetPartitions() method in the <paramref name="source"/> Partitioner does not return
- /// the correct number of partitions.</exception>
- /// <exception cref="T:System.InvalidOperationException">The exception that is thrown when the
- /// GetPartitions() method in the <paramref name="source"/> Partitioner returns an IList
- /// with at least one null value.</exception>
- /// <exception cref="T:System.InvalidOperationException">The exception that is thrown when the
- /// GetDynamicPartitions() method in the <paramref name="source"/> Partitioner returns an
- /// IEnumerable whose GetEnumerator() method returns null.</exception>
- /// <exception cref="T:System.AggregateException">The exception that is thrown to contain an exception
- /// thrown from one of the specified delegates.</exception>
- /// <returns>A <see cref="T:System.Threading.Tasks.ParallelLoopResult">ParallelLoopResult</see> structure
- /// that contains information on what portion of the loop completed.</returns>
- /// <remarks>
- /// <para>
- /// The <see cref="T:System.Collections.Concurrent.Partitioner{TSource}">Partitioner</see> is used to retrieve
- /// the elements to be processed, in place of the original data source. If the current element's
- /// index is desired, the source must be an <see cref="T:System.Collections.Concurrent.OrderablePartitioner">
- /// OrderablePartitioner</see>.
- /// </para>
- /// <para>
- /// The <paramref name="body"/> delegate is invoked once for each element in the <paramref name="source"/>
- /// Partitioner. It is provided with the current element as a parameter.
- /// </para>
- /// </remarks>
- public static ParallelLoopResult ForEach<TSource>(
- Partitioner<TSource> source,
- Action<TSource> body)
- {
- if (source == null)
- {
- throw new ArgumentNullException(nameof(source));
- }
- if (body == null)
- {
- throw new ArgumentNullException(nameof(body));
- }
-
- return PartitionerForEachWorker<TSource, object>(source, s_defaultParallelOptions, body, null, null, null, null, null, null);
- }
-
- /// <summary>
- /// Executes a for each operation on a <see cref="T:System.Collections.Concurrent.Partitioner{TSource}">
- /// Partitioner</see> in which iterations may run in parallel.
- /// </summary>
- /// <typeparam name="TSource">The type of the elements in <paramref name="source"/>.</typeparam>
- /// <param name="source">The Partitioner that contains the original data source.</param>
- /// <param name="body">The delegate that is invoked once per iteration.</param>
- /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the <paramref name="source"/>
- /// argument is null.</exception>
- /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the <paramref name="body"/>
- /// argument is null.</exception>
- /// <exception cref="T:System.InvalidOperationException">The exception that is thrown when the
- /// SupportsDynamicPartitions property in the <paramref name="source"/> Partitioner returns
- /// false.</exception>
- /// <exception cref="T:System.InvalidOperationException">The exception that is thrown when any
- /// methods in the <paramref name="source"/> Partitioner return null.</exception>
- /// <exception cref="T:System.InvalidOperationException">The exception that is thrown when the
- /// GetPartitions() method in the <paramref name="source"/> Partitioner does not return
- /// the correct number of partitions.</exception>
- /// <exception cref="T:System.InvalidOperationException">The exception that is thrown when the
- /// GetPartitions() method in the <paramref name="source"/> Partitioner returns an IList
- /// with at least one null value.</exception>
- /// <exception cref="T:System.InvalidOperationException">The exception that is thrown when the
- /// GetDynamicPartitions() method in the <paramref name="source"/> Partitioner returns an
- /// IEnumerable whose GetEnumerator() method returns null.</exception>
- /// <exception cref="T:System.AggregateException">The exception that is thrown to contain an exception
- /// thrown from one of the specified delegates.</exception>
- /// <returns>A <see cref="T:System.Threading.Tasks.ParallelLoopResult">ParallelLoopResult</see> structure
- /// that contains information on what portion of the loop completed.</returns>
- /// <remarks>
- /// <para>
- /// The <see cref="T:System.Collections.Concurrent.Partitioner{TSource}">Partitioner</see> is used to retrieve
- /// the elements to be processed, in place of the original data source. If the current element's
- /// index is desired, the source must be an <see cref="T:System.Collections.Concurrent.OrderablePartitioner">
- /// OrderablePartitioner</see>.
- /// </para>
- /// <para>
- /// The <paramref name="body"/> delegate is invoked once for each element in the <paramref name="source"/>
- /// Partitioner. It is provided with the following parameters: the current element,
- /// and a <see cref="System.Threading.Tasks.ParallelLoopState">ParallelLoopState</see> instance that may be
- /// used to break out of the loop prematurely.
- /// </para>
- /// </remarks>
- public static ParallelLoopResult ForEach<TSource>(
- Partitioner<TSource> source,
- Action<TSource, ParallelLoopState> body)
- {
- if (source == null)
- {
- throw new ArgumentNullException(nameof(source));
- }
- if (body == null)
- {
- throw new ArgumentNullException(nameof(body));
- }
-
- return PartitionerForEachWorker<TSource, object>(source, s_defaultParallelOptions, null, body, null, null, null, null, null);
- }
-
- /// <summary>
- /// Executes a for each operation on a <see cref="T:System.Collections.Concurrent.OrderablePartitioner{TSource}">
- /// OrderablePartitioner</see> in which iterations may run in parallel.
- /// </summary>
- /// <typeparam name="TSource">The type of the elements in <paramref name="source"/>.</typeparam>
- /// <param name="source">The OrderablePartitioner that contains the original data source.</param>
- /// <param name="body">The delegate that is invoked once per iteration.</param>
- /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the <paramref name="source"/>
- /// argument is null.</exception>
- /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the <paramref name="body"/>
- /// argument is null.</exception>
- /// <exception cref="T:System.InvalidOperationException">The exception that is thrown when the
- /// SupportsDynamicPartitions property in the <paramref name="source"/> OrderablePartitioner returns
- /// false.</exception>
- /// <exception cref="T:System.InvalidOperationException">The exception that is thrown when the
- /// KeysNormalized property in the <paramref name="source"/> OrderablePartitioner returns
- /// false.</exception>
- /// <exception cref="T:System.InvalidOperationException">The exception that is thrown when any
- /// methods in the <paramref name="source"/> OrderablePartitioner return null.</exception>
- /// <exception cref="T:System.InvalidOperationException">The exception that is thrown when the
- /// GetPartitions() or GetOrderablePartitions() methods in the <paramref name="source"/>
- /// OrderablePartitioner do not return the correct number of partitions.</exception>
- /// <exception cref="T:System.InvalidOperationException">The exception that is thrown when the
- /// GetPartitions() or GetOrderablePartitions() methods in the <paramref name="source"/>
- /// OrderablePartitioner return an IList with at least one null value.</exception>
- /// <exception cref="T:System.InvalidOperationException">The exception that is thrown when the
- /// GetDynamicPartitions() or GetDynamicOrderablePartitions() methods in the <paramref name="source"/>
- /// OrderablePartitioner return an IEnumerable whose GetEnumerator() method returns null.</exception>
- /// <exception cref="T:System.AggregateException">The exception that is thrown to contain an exception
- /// thrown from one of the specified delegates.</exception>
- /// <returns>A <see cref="T:System.Threading.Tasks.ParallelLoopResult">ParallelLoopResult</see> structure
- /// that contains information on what portion of the loop completed.</returns>
- /// <remarks>
- /// <para>
- /// The <see cref="T:System.Collections.Concurrent.Partitioner{TSource}">Partitioner</see> is used to retrieve
- /// the elements to be processed, in place of the original data source. If the current element's
- /// index is desired, the source must be an <see cref="T:System.Collections.Concurrent.OrderablePartitioner">
- /// OrderablePartitioner</see>.
- /// </para>
- /// <para>
- /// The <paramref name="body"/> delegate is invoked once for each element in the <paramref name="source"/>
- /// Partitioner. It is provided with the following parameters: the current element,
- /// a <see cref="System.Threading.Tasks.ParallelLoopState">ParallelLoopState</see> instance that may be
- /// used to break out of the loop prematurely, and the current element's index (an Int64).
- /// </para>
- /// </remarks>
- public static ParallelLoopResult ForEach<TSource>(
- OrderablePartitioner<TSource> source,
- Action<TSource, ParallelLoopState, long> body)
- {
- if (source == null)
- {
- throw new ArgumentNullException(nameof(source));
- }
- if (body == null)
- {
- throw new ArgumentNullException(nameof(body));
- }
-
- if (!source.KeysNormalized)
- {
- throw new InvalidOperationException(Environment.GetResourceString("Parallel_ForEach_OrderedPartitionerKeysNotNormalized"));
- }
-
- return PartitionerForEachWorker<TSource, object>(source, s_defaultParallelOptions, null, null, body, null, null, null, null);
- }
-
- /// <summary>
- /// Executes a for each operation on a <see cref="T:System.Collections.Concurrent.Partitioner{TSource}">
- /// Partitioner</see> in which iterations may run in parallel.
- /// </summary>
- /// <typeparam name="TSource">The type of the elements in <paramref name="source"/>.</typeparam>
- /// <typeparam name="TLocal">The type of the thread-local data.</typeparam>
- /// <param name="source">The Partitioner that contains the original data source.</param>
- /// <param name="localInit">The function delegate that returns the initial state of the local data
- /// for each thread.</param>
- /// <param name="body">The delegate that is invoked once per iteration.</param>
- /// <param name="localFinally">The delegate that performs a final action on the local state of each
- /// thread.</param>
- /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the <paramref name="source"/>
- /// argument is null.</exception>
- /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the <paramref name="body"/>
- /// argument is null.</exception>
- /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the
- /// <paramref name="localInit"/> argument is null.</exception>
- /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the
- /// <paramref name="localFinally"/> argument is null.</exception>
- /// <exception cref="T:System.InvalidOperationException">The exception that is thrown when the
- /// SupportsDynamicPartitions property in the <paramref name="source"/> Partitioner returns
- /// false.</exception>
- /// <exception cref="T:System.InvalidOperationException">The exception that is thrown when any
- /// methods in the <paramref name="source"/> Partitioner return null.</exception>
- /// <exception cref="T:System.InvalidOperationException">The exception that is thrown when the
- /// GetPartitions() method in the <paramref name="source"/> Partitioner does not return
- /// the correct number of partitions.</exception>
- /// <exception cref="T:System.InvalidOperationException">The exception that is thrown when the
- /// GetPartitions() method in the <paramref name="source"/> Partitioner returns an IList
- /// with at least one null value.</exception>
- /// <exception cref="T:System.InvalidOperationException">The exception that is thrown when the
- /// GetDynamicPartitions() method in the <paramref name="source"/> Partitioner returns an
- /// IEnumerable whose GetEnumerator() method returns null.</exception>
- /// <exception cref="T:System.AggregateException">The exception that is thrown to contain an exception
- /// thrown from one of the specified delegates.</exception>
- /// <returns>A <see cref="T:System.Threading.Tasks.ParallelLoopResult">ParallelLoopResult</see> structure
- /// that contains information on what portion of the loop completed.</returns>
- /// <remarks>
- /// <para>
- /// The <see cref="T:System.Collections.Concurrent.Partitioner{TSource}">Partitioner</see> is used to retrieve
- /// the elements to be processed, in place of the original data source. If the current element's
- /// index is desired, the source must be an <see cref="T:System.Collections.Concurrent.OrderablePartitioner">
- /// OrderablePartitioner</see>.
- /// </para>
- /// <para>
- /// The <paramref name="body"/> delegate is invoked once for each element in the <paramref name="source"/>
- /// Partitioner. It is provided with the following parameters: the current element,
- /// a <see cref="System.Threading.Tasks.ParallelLoopState">ParallelLoopState</see> instance that may be
- /// used to break out of the loop prematurely, and some local state that may be shared amongst iterations
- /// that execute on the same thread.
- /// </para>
- /// <para>
- /// The <paramref name="localInit"/> delegate is invoked once for each thread that participates in the loop's
- /// execution and returns the initial local state for each of those threads. These initial states are passed to the first
- /// <paramref name="body"/> invocations on each thread. Then, every subsequent body invocation returns a possibly
- /// modified state value that is passed to the next body invocation. Finally, the last body invocation on each thread returns a state value
- /// that is passed to the <paramref name="localFinally"/> delegate. The localFinally delegate is invoked once per thread to perform a final
- /// action on each thread's local state.
- /// </para>
- /// </remarks>
- public static ParallelLoopResult ForEach<TSource, TLocal>(
- Partitioner<TSource> source,
- Func<TLocal> localInit,
- Func<TSource, ParallelLoopState, TLocal, TLocal> body,
- Action<TLocal> localFinally)
- {
- if (source == null)
- {
- throw new ArgumentNullException(nameof(source));
- }
- if (body == null)
- {
- throw new ArgumentNullException(nameof(body));
- }
- if (localInit == null)
- {
- throw new ArgumentNullException(nameof(localInit));
- }
- if (localFinally == null)
- {
- throw new ArgumentNullException(nameof(localFinally));
- }
-
- return PartitionerForEachWorker<TSource, TLocal>(source, s_defaultParallelOptions, null, null, null, body, null, localInit, localFinally);
- }
-
- /// <summary>
- /// Executes a for each operation on a <see cref="T:System.Collections.Concurrent.OrderablePartitioner{TSource}">
- /// OrderablePartitioner</see> in which iterations may run in parallel.
- /// </summary>
- /// <typeparam name="TSource">The type of the elements in <paramref name="source"/>.</typeparam>
- /// <typeparam name="TLocal">The type of the thread-local data.</typeparam>
- /// <param name="source">The OrderablePartitioner that contains the original data source.</param>
- /// <param name="localInit">The function delegate that returns the initial state of the local data
- /// for each thread.</param>
- /// <param name="body">The delegate that is invoked once per iteration.</param>
- /// <param name="localFinally">The delegate that performs a final action on the local state of each
- /// thread.</param>
- /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the <paramref name="source"/>
- /// argument is null.</exception>
- /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the <paramref name="body"/>
- /// argument is null.</exception>
- /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the
- /// <paramref name="localInit"/> argument is null.</exception>
- /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the
- /// <paramref name="localFinally"/> argument is null.</exception>
- /// <exception cref="T:System.InvalidOperationException">The exception that is thrown when the
- /// SupportsDynamicPartitions property in the <paramref name="source"/> OrderablePartitioner returns
- /// false.</exception>
- /// <exception cref="T:System.InvalidOperationException">The exception that is thrown when the
- /// KeysNormalized property in the <paramref name="source"/> OrderablePartitioner returns
- /// false.</exception>
- /// <exception cref="T:System.InvalidOperationException">The exception that is thrown when any
- /// methods in the <paramref name="source"/> OrderablePartitioner return null.</exception>
- /// <exception cref="T:System.InvalidOperationException">The exception that is thrown when the
- /// GetPartitions() or GetOrderablePartitions() methods in the <paramref name="source"/>
- /// OrderablePartitioner do not return the correct number of partitions.</exception>
- /// <exception cref="T:System.InvalidOperationException">The exception that is thrown when the
- /// GetPartitions() or GetOrderablePartitions() methods in the <paramref name="source"/>
- /// OrderablePartitioner return an IList with at least one null value.</exception>
- /// <exception cref="T:System.InvalidOperationException">The exception that is thrown when the
- /// GetDynamicPartitions() or GetDynamicOrderablePartitions() methods in the <paramref name="source"/>
- /// OrderablePartitioner return an IEnumerable whose GetEnumerator() method returns null.</exception>
- /// <exception cref="T:System.AggregateException">The exception that is thrown to contain an exception
- /// thrown from one of the specified delegates.</exception>
- /// <returns>A <see cref="T:System.Threading.Tasks.ParallelLoopResult">ParallelLoopResult</see> structure
- /// that contains information on what portion of the loop completed.</returns>
- /// <remarks>
- /// <para>
- /// The <see cref="T:System.Collections.Concurrent.Partitioner{TSource}">Partitioner</see> is used to retrieve
- /// the elements to be processed, in place of the original data source. If the current element's
- /// index is desired, the source must be an <see cref="T:System.Collections.Concurrent.OrderablePartitioner">
- /// OrderablePartitioner</see>.
- /// </para>
- /// <para>
- /// The <paramref name="body"/> delegate is invoked once for each element in the <paramref name="source"/>
- /// Partitioner. It is provided with the following parameters: the current element,
- /// a <see cref="System.Threading.Tasks.ParallelLoopState">ParallelLoopState</see> instance that may be
- /// used to break out of the loop prematurely, the current element's index (an Int64), and some local
- /// state that may be shared amongst iterations that execute on the same thread.
- /// </para>
- /// <para>
- /// The <paramref name="localInit"/> delegate is invoked once for each thread that participates in the loop's
- /// execution and returns the initial local state for each of those threads. These initial states are passed to the first
- /// <paramref name="body"/> invocations on each thread. Then, every subsequent body invocation returns a possibly
- /// modified state value that is passed to the next body invocation. Finally, the last body invocation on each thread returns a state value
- /// that is passed to the <paramref name="localFinally"/> delegate. The localFinally delegate is invoked once per thread to perform a final
- /// action on each thread's local state.
- /// </para>
- /// </remarks>
- public static ParallelLoopResult ForEach<TSource, TLocal>(
- OrderablePartitioner<TSource> source,
- Func<TLocal> localInit,
- Func<TSource, ParallelLoopState, long, TLocal, TLocal> body,
- Action<TLocal> localFinally)
- {
- if (source == null)
- {
- throw new ArgumentNullException(nameof(source));
- }
- if (body == null)
- {
- throw new ArgumentNullException(nameof(body));
- }
- if (localInit == null)
- {
- throw new ArgumentNullException(nameof(localInit));
- }
- if (localFinally == null)
- {
- throw new ArgumentNullException(nameof(localFinally));
- }
-
- if (!source.KeysNormalized)
- {
- throw new InvalidOperationException(Environment.GetResourceString("Parallel_ForEach_OrderedPartitionerKeysNotNormalized"));
- }
-
- return PartitionerForEachWorker<TSource, TLocal>(source, s_defaultParallelOptions, null, null, null, null, body, localInit, localFinally);
- }
-
- /// <summary>
- /// Executes a for each operation on a <see cref="T:System.Collections.Concurrent.Partitioner{TSource}">
- /// Partitioner</see> in which iterations may run in parallel.
- /// </summary>
- /// <typeparam name="TSource">The type of the elements in <paramref name="source"/>.</typeparam>
- /// <param name="source">The Partitioner that contains the original data source.</param>
- /// <param name="parallelOptions">A <see cref="T:System.Threading.Tasks.ParallelOptions">ParallelOptions</see>
- /// instance that configures the behavior of this operation.</param>
- /// <param name="body">The delegate that is invoked once per iteration.</param>
- /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the <paramref name="source"/>
- /// argument is null.</exception>
- /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the
- /// <paramref name="parallelOptions"/> argument is null.</exception>
- /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the <paramref name="body"/>
- /// argument is null.</exception>
- /// <exception cref="T:System.OperationCanceledException">The exception that is thrown when the
- /// <see cref="T:System.Threading.CancellationToken">CancellationToken</see> in the <paramref name="parallelOptions"/>
- /// argument is set</exception>
- /// <exception cref="T:System.InvalidOperationException">The exception that is thrown when the
- /// SupportsDynamicPartitions property in the <paramref name="source"/> Partitioner returns
- /// false.</exception>
- /// <exception cref="T:System.InvalidOperationException">The exception that is thrown when any
- /// methods in the <paramref name="source"/> Partitioner return null.</exception>
- /// <exception cref="T:System.InvalidOperationException">The exception that is thrown when the
- /// GetPartitions() method in the <paramref name="source"/> Partitioner does not return
- /// the correct number of partitions.</exception>
- /// <exception cref="T:System.InvalidOperationException">The exception that is thrown when the
- /// GetPartitions() method in the <paramref name="source"/> Partitioner returns an IList
- /// with at least one null value.</exception>
- /// <exception cref="T:System.InvalidOperationException">The exception that is thrown when the
- /// GetDynamicPartitions() method in the <paramref name="source"/> Partitioner returns an
- /// IEnumerable whose GetEnumerator() method returns null.</exception>
- /// <exception cref="T:System.AggregateException">The exception that is thrown to contain an exception
- /// thrown from one of the specified delegates.</exception>
- /// <exception cref="T:System.ObjectDisposedException">The exception that is thrown when the
- /// the <see cref="T:System.Threading.CancellationTokenSource">CancellationTokenSource</see> associated with the
- /// the <see cref="T:System.Threading.CancellationToken">CancellationToken</see> in the
- /// <paramref name="parallelOptions"/> has been disposed.</exception>
- /// <returns>A <see cref="T:System.Threading.Tasks.ParallelLoopResult">ParallelLoopResult</see> structure
- /// that contains information on what portion of the loop completed.</returns>
- /// <remarks>
- /// <para>
- /// The <see cref="T:System.Collections.Concurrent.Partitioner{TSource}">Partitioner</see> is used to retrieve
- /// the elements to be processed, in place of the original data source. If the current element's
- /// index is desired, the source must be an <see cref="T:System.Collections.Concurrent.OrderablePartitioner">
- /// OrderablePartitioner</see>.
- /// </para>
- /// <para>
- /// The <paramref name="body"/> delegate is invoked once for each element in the <paramref name="source"/>
- /// Partitioner. It is provided with the current element as a parameter.
- /// </para>
- /// </remarks>
- public static ParallelLoopResult ForEach<TSource>(
- Partitioner<TSource> source,
- ParallelOptions parallelOptions,
- Action<TSource> body)
- {
- if (source == null)
- {
- throw new ArgumentNullException(nameof(source));
- }
- if (body == null)
- {
- throw new ArgumentNullException(nameof(body));
- }
- if (parallelOptions == null)
- {
- throw new ArgumentNullException(nameof(parallelOptions));
- }
-
- return PartitionerForEachWorker<TSource, object>(source, parallelOptions, body, null, null, null, null, null, null);
- }
-
- /// <summary>
- /// Executes a for each operation on a <see cref="T:System.Collections.Concurrent.Partitioner{TSource}">
- /// Partitioner</see> in which iterations may run in parallel.
- /// </summary>
- /// <typeparam name="TSource">The type of the elements in <paramref name="source"/>.</typeparam>
- /// <param name="source">The Partitioner that contains the original data source.</param>
- /// <param name="parallelOptions">A <see cref="T:System.Threading.Tasks.ParallelOptions">ParallelOptions</see>
- /// instance that configures the behavior of this operation.</param>
- /// <param name="body">The delegate that is invoked once per iteration.</param>
- /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the <paramref name="source"/>
- /// argument is null.</exception>
- /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the
- /// <paramref name="parallelOptions"/> argument is null.</exception>
- /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the <paramref name="body"/>
- /// argument is null.</exception>
- /// <exception cref="T:System.OperationCanceledException">The exception that is thrown when the
- /// <see cref="T:System.Threading.CancellationToken">CancellationToken</see> in the <paramref name="parallelOptions"/>
- /// argument is set</exception>
- /// <exception cref="T:System.InvalidOperationException">The exception that is thrown when the
- /// SupportsDynamicPartitions property in the <paramref name="source"/> Partitioner returns
- /// false.</exception>
- /// <exception cref="T:System.InvalidOperationException">The exception that is thrown when any
- /// methods in the <paramref name="source"/> Partitioner return null.</exception>
- /// <exception cref="T:System.InvalidOperationException">The exception that is thrown when the
- /// GetPartitions() method in the <paramref name="source"/> Partitioner does not return
- /// the correct number of partitions.</exception>
- /// <exception cref="T:System.InvalidOperationException">The exception that is thrown when the
- /// GetPartitions() method in the <paramref name="source"/> Partitioner returns an IList
- /// with at least one null value.</exception>
- /// <exception cref="T:System.InvalidOperationException">The exception that is thrown when the
- /// GetDynamicPartitions() method in the <paramref name="source"/> Partitioner returns an
- /// IEnumerable whose GetEnumerator() method returns null.</exception>
- /// <exception cref="T:System.AggregateException">The exception that is thrown to contain an exception
- /// thrown from one of the specified delegates.</exception>
- /// <exception cref="T:System.ObjectDisposedException">The exception that is thrown when the
- /// the <see cref="T:System.Threading.CancellationTokenSource">CancellationTokenSource</see> associated with the
- /// the <see cref="T:System.Threading.CancellationToken">CancellationToken</see> in the
- /// <paramref name="parallelOptions"/> has been disposed.</exception>
- /// <returns>A <see cref="T:System.Threading.Tasks.ParallelLoopResult">ParallelLoopResult</see> structure
- /// that contains information on what portion of the loop completed.</returns>
- /// <remarks>
- /// <para>
- /// The <see cref="T:System.Collections.Concurrent.Partitioner{TSource}">Partitioner</see> is used to retrieve
- /// the elements to be processed, in place of the original data source. If the current element's
- /// index is desired, the source must be an <see cref="T:System.Collections.Concurrent.OrderablePartitioner">
- /// OrderablePartitioner</see>.
- /// </para>
- /// <para>
- /// The <paramref name="body"/> delegate is invoked once for each element in the <paramref name="source"/>
- /// Partitioner. It is provided with the following parameters: the current element,
- /// and a <see cref="System.Threading.Tasks.ParallelLoopState">ParallelLoopState</see> instance that may be
- /// used to break out of the loop prematurely.
- /// </para>
- /// </remarks>
- public static ParallelLoopResult ForEach<TSource>(
- Partitioner<TSource> source,
- ParallelOptions parallelOptions,
- Action<TSource, ParallelLoopState> body)
- {
- if (source == null)
- {
- throw new ArgumentNullException(nameof(source));
- }
- if (body == null)
- {
- throw new ArgumentNullException(nameof(body));
- }
- if (parallelOptions == null)
- {
- throw new ArgumentNullException(nameof(parallelOptions));
- }
-
- return PartitionerForEachWorker<TSource, object>(source, parallelOptions, null, body, null, null, null, null, null);
- }
-
- /// <summary>
- /// Executes a for each operation on a <see cref="T:System.Collections.Concurrent.OrderablePartitioner{TSource}">
- /// OrderablePartitioner</see> in which iterations may run in parallel.
- /// </summary>
- /// <typeparam name="TSource">The type of the elements in <paramref name="source"/>.</typeparam>
- /// <param name="source">The OrderablePartitioner that contains the original data source.</param>
- /// <param name="parallelOptions">A <see cref="T:System.Threading.Tasks.ParallelOptions">ParallelOptions</see>
- /// instance that configures the behavior of this operation.</param>
- /// <param name="body">The delegate that is invoked once per iteration.</param>
- /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the <paramref name="source"/>
- /// argument is null.</exception>
- /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the
- /// <paramref name="parallelOptions"/> argument is null.</exception>
- /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the <paramref name="body"/>
- /// argument is null.</exception>
- /// <exception cref="T:System.OperationCanceledException">The exception that is thrown when the
- /// <see cref="T:System.Threading.CancellationToken">CancellationToken</see> in the <paramref name="parallelOptions"/>
- /// argument is set</exception>
- /// <exception cref="T:System.InvalidOperationException">The exception that is thrown when the
- /// SupportsDynamicPartitions property in the <paramref name="source"/> OrderablePartitioner returns
- /// false.</exception>
- /// <exception cref="T:System.InvalidOperationException">The exception that is thrown when the
- /// KeysNormalized property in the <paramref name="source"/> OrderablePartitioner returns
- /// false.</exception>
- /// <exception cref="T:System.InvalidOperationException">The exception that is thrown when any
- /// methods in the <paramref name="source"/> OrderablePartitioner return null.</exception>
- /// <exception cref="T:System.InvalidOperationException">The exception that is thrown when the
- /// GetPartitions() or GetOrderablePartitions() methods in the <paramref name="source"/>
- /// OrderablePartitioner do not return the correct number of partitions.</exception>
- /// <exception cref="T:System.InvalidOperationException">The exception that is thrown when the
- /// GetPartitions() or GetOrderablePartitions() methods in the <paramref name="source"/>
- /// OrderablePartitioner return an IList with at least one null value.</exception>
- /// <exception cref="T:System.InvalidOperationException">The exception that is thrown when the
- /// GetDynamicPartitions() or GetDynamicOrderablePartitions() methods in the <paramref name="source"/>
- /// OrderablePartitioner return an IEnumerable whose GetEnumerator() method returns null.</exception>
- /// <exception cref="T:System.AggregateException">The exception that is thrown to contain an exception
- /// thrown from one of the specified delegates.</exception>
- /// <exception cref="T:System.ObjectDisposedException">The exception that is thrown when the
- /// the <see cref="T:System.Threading.CancellationTokenSource">CancellationTokenSource</see> associated with the
- /// the <see cref="T:System.Threading.CancellationToken">CancellationToken</see> in the
- /// <paramref name="parallelOptions"/> has been disposed.</exception>
- /// <returns>A <see cref="T:System.Threading.Tasks.ParallelLoopResult">ParallelLoopResult</see> structure
- /// that contains information on what portion of the loop completed.</returns>
- /// <remarks>
- /// <para>
- /// The <see cref="T:System.Collections.Concurrent.Partitioner{TSource}">Partitioner</see> is used to retrieve
- /// the elements to be processed, in place of the original data source. If the current element's
- /// index is desired, the source must be an <see cref="T:System.Collections.Concurrent.OrderablePartitioner">
- /// OrderablePartitioner</see>.
- /// </para>
- /// <para>
- /// The <paramref name="body"/> delegate is invoked once for each element in the <paramref name="source"/>
- /// Partitioner. It is provided with the following parameters: the current element,
- /// a <see cref="System.Threading.Tasks.ParallelLoopState">ParallelLoopState</see> instance that may be
- /// used to break out of the loop prematurely, and the current element's index (an Int64).
- /// </para>
- /// </remarks>
- public static ParallelLoopResult ForEach<TSource>(
- OrderablePartitioner<TSource> source,
- ParallelOptions parallelOptions,
- Action<TSource, ParallelLoopState, long> body)
- {
- if (source == null)
- {
- throw new ArgumentNullException(nameof(source));
- }
- if (body == null)
- {
- throw new ArgumentNullException(nameof(body));
- }
- if (parallelOptions == null)
- {
- throw new ArgumentNullException(nameof(parallelOptions));
- }
-
- if (!source.KeysNormalized)
- {
- throw new InvalidOperationException(Environment.GetResourceString("Parallel_ForEach_OrderedPartitionerKeysNotNormalized"));
- }
-
- return PartitionerForEachWorker<TSource, object>(source, parallelOptions, null, null, body, null, null, null, null);
- }
-
- /// <summary>
- /// Executes a for each operation on a <see cref="T:System.Collections.Concurrent.Partitioner{TSource}">
- /// Partitioner</see> in which iterations may run in parallel.
- /// </summary>
- /// <typeparam name="TSource">The type of the elements in <paramref name="source"/>.</typeparam>
- /// <typeparam name="TLocal">The type of the thread-local data.</typeparam>
- /// <param name="source">The Partitioner that contains the original data source.</param>
- /// <param name="parallelOptions">A <see cref="T:System.Threading.Tasks.ParallelOptions">ParallelOptions</see>
- /// instance that configures the behavior of this operation.</param>
- /// <param name="localInit">The function delegate that returns the initial state of the local data
- /// for each thread.</param>
- /// <param name="body">The delegate that is invoked once per iteration.</param>
- /// <param name="localFinally">The delegate that performs a final action on the local state of each
- /// thread.</param>
- /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the <paramref name="source"/>
- /// argument is null.</exception>
- /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the
- /// <paramref name="parallelOptions"/> argument is null.</exception>
- /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the <paramref name="body"/>
- /// argument is null.</exception>
- /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the
- /// <paramref name="localInit"/> argument is null.</exception>
- /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the
- /// <paramref name="localFinally"/> argument is null.</exception>
- /// <exception cref="T:System.OperationCanceledException">The exception that is thrown when the
- /// <see cref="T:System.Threading.CancellationToken">CancellationToken</see> in the <paramref name="parallelOptions"/>
- /// argument is set</exception>
- /// <exception cref="T:System.InvalidOperationException">The exception that is thrown when the
- /// SupportsDynamicPartitions property in the <paramref name="source"/> Partitioner returns
- /// false.</exception>
- /// <exception cref="T:System.InvalidOperationException">The exception that is thrown when any
- /// methods in the <paramref name="source"/> Partitioner return null.</exception>
- /// <exception cref="T:System.InvalidOperationException">The exception that is thrown when the
- /// GetPartitions() method in the <paramref name="source"/> Partitioner does not return
- /// the correct number of partitions.</exception>
- /// <exception cref="T:System.InvalidOperationException">The exception that is thrown when the
- /// GetPartitions() method in the <paramref name="source"/> Partitioner returns an IList
- /// with at least one null value.</exception>
- /// <exception cref="T:System.InvalidOperationException">The exception that is thrown when the
- /// GetDynamicPartitions() method in the <paramref name="source"/> Partitioner returns an
- /// IEnumerable whose GetEnumerator() method returns null.</exception>
- /// <exception cref="T:System.AggregateException">The exception that is thrown to contain an exception
- /// thrown from one of the specified delegates.</exception>
- /// <exception cref="T:System.ObjectDisposedException">The exception that is thrown when the
- /// the <see cref="T:System.Threading.CancellationTokenSource">CancellationTokenSource</see> associated with the
- /// the <see cref="T:System.Threading.CancellationToken">CancellationToken</see> in the
- /// <paramref name="parallelOptions"/> has been disposed.</exception>
- /// <returns>A <see cref="T:System.Threading.Tasks.ParallelLoopResult">ParallelLoopResult</see> structure
- /// that contains information on what portion of the loop completed.</returns>
- /// <remarks>
- /// <para>
- /// The <see cref="T:System.Collections.Concurrent.Partitioner{TSource}">Partitioner</see> is used to retrieve
- /// the elements to be processed, in place of the original data source. If the current element's
- /// index is desired, the source must be an <see cref="T:System.Collections.Concurrent.OrderablePartitioner">
- /// OrderablePartitioner</see>.
- /// </para>
- /// <para>
- /// The <paramref name="body"/> delegate is invoked once for each element in the <paramref name="source"/>
- /// Partitioner. It is provided with the following parameters: the current element,
- /// a <see cref="System.Threading.Tasks.ParallelLoopState">ParallelLoopState</see> instance that may be
- /// used to break out of the loop prematurely, and some local state that may be shared amongst iterations
- /// that execute on the same thread.
- /// </para>
- /// <para>
- /// The <paramref name="localInit"/> delegate is invoked once for each thread that participates in the loop's
- /// execution and returns the initial local state for each of those threads. These initial states are passed to the first
- /// <paramref name="body"/> invocations on each thread. Then, every subsequent body invocation returns a possibly
- /// modified state value that is passed to the next body invocation. Finally, the last body invocation on each thread returns a state value
- /// that is passed to the <paramref name="localFinally"/> delegate. The localFinally delegate is invoked once per thread to perform a final
- /// action on each thread's local state.
- /// </para>
- /// </remarks>
- public static ParallelLoopResult ForEach<TSource, TLocal>(
- Partitioner<TSource> source,
- ParallelOptions parallelOptions,
- Func<TLocal> localInit,
- Func<TSource, ParallelLoopState, TLocal, TLocal> body,
- Action<TLocal> localFinally)
- {
- if (source == null)
- {
- throw new ArgumentNullException(nameof(source));
- }
- if (body == null)
- {
- throw new ArgumentNullException(nameof(body));
- }
- if (localInit == null)
- {
- throw new ArgumentNullException(nameof(localInit));
- }
- if (localFinally == null)
- {
- throw new ArgumentNullException(nameof(localFinally));
- }
- if (parallelOptions == null)
- {
- throw new ArgumentNullException(nameof(parallelOptions));
- }
-
- return PartitionerForEachWorker<TSource, TLocal>(source, parallelOptions, null, null, null, body, null, localInit, localFinally);
- }
-
- /// <summary>
- /// Executes a for each operation on a <see cref="T:System.Collections.Concurrent.OrderablePartitioner{TSource}">
- /// OrderablePartitioner</see> in which iterations may run in parallel.
- /// </summary>
- /// <typeparam name="TSource">The type of the elements in <paramref name="source"/>.</typeparam>
- /// <typeparam name="TLocal">The type of the thread-local data.</typeparam>
- /// <param name="source">The OrderablePartitioner that contains the original data source.</param>
- /// <param name="parallelOptions">A <see cref="T:System.Threading.Tasks.ParallelOptions">ParallelOptions</see>
- /// instance that configures the behavior of this operation.</param>
- /// <param name="localInit">The function delegate that returns the initial state of the local data
- /// for each thread.</param>
- /// <param name="body">The delegate that is invoked once per iteration.</param>
- /// <param name="localFinally">The delegate that performs a final action on the local state of each
- /// thread.</param>
- /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the <paramref name="source"/>
- /// argument is null.</exception>
- /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the
- /// <paramref name="parallelOptions"/> argument is null.</exception>
- /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the <paramref name="body"/>
- /// argument is null.</exception>
- /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the
- /// <paramref name="localInit"/> argument is null.</exception>
- /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the
- /// <paramref name="localFinally"/> argument is null.</exception>
- /// <exception cref="T:System.OperationCanceledException">The exception that is thrown when the
- /// <see cref="T:System.Threading.CancellationToken">CancellationToken</see> in the <paramref name="parallelOptions"/>
- /// argument is set</exception>
- /// <exception cref="T:System.InvalidOperationException">The exception that is thrown when the
- /// SupportsDynamicPartitions property in the <paramref name="source"/> OrderablePartitioner returns
- /// false.</exception>
- /// <exception cref="T:System.InvalidOperationException">The exception that is thrown when the
- /// KeysNormalized property in the <paramref name="source"/> OrderablePartitioner returns
- /// false.</exception>
- /// <exception cref="T:System.InvalidOperationException">The exception that is thrown when any
- /// methods in the <paramref name="source"/> OrderablePartitioner return null.</exception>
- /// <exception cref="T:System.InvalidOperationException">The exception that is thrown when the
- /// GetPartitions() or GetOrderablePartitions() methods in the <paramref name="source"/>
- /// OrderablePartitioner do not return the correct number of partitions.</exception>
- /// <exception cref="T:System.InvalidOperationException">The exception that is thrown when the
- /// GetPartitions() or GetOrderablePartitions() methods in the <paramref name="source"/>
- /// OrderablePartitioner return an IList with at least one null value.</exception>
- /// <exception cref="T:System.InvalidOperationException">The exception that is thrown when the
- /// GetDynamicPartitions() or GetDynamicOrderablePartitions() methods in the <paramref name="source"/>
- /// OrderablePartitioner return an IEnumerable whose GetEnumerator() method returns null.</exception>
- /// <exception cref="T:System.AggregateException">The exception that is thrown to contain an exception
- /// thrown from one of the specified delegates.</exception>
- /// <exception cref="T:System.ObjectDisposedException">The exception that is thrown when the
- /// the <see cref="T:System.Threading.CancellationTokenSource">CancellationTokenSource</see> associated with the
- /// the <see cref="T:System.Threading.CancellationToken">CancellationToken</see> in the
- /// <paramref name="parallelOptions"/> has been disposed.</exception>
- /// <returns>A <see cref="T:System.Threading.Tasks.ParallelLoopResult">ParallelLoopResult</see> structure
- /// that contains information on what portion of the loop completed.</returns>
- /// <remarks>
- /// <para>
- /// The <see cref="T:System.Collections.Concurrent.Partitioner{TSource}">Partitioner</see> is used to retrieve
- /// the elements to be processed, in place of the original data source. If the current element's
- /// index is desired, the source must be an <see cref="T:System.Collections.Concurrent.OrderablePartitioner">
- /// OrderablePartitioner</see>.
- /// </para>
- /// <para>
- /// The <paramref name="body"/> delegate is invoked once for each element in the <paramref name="source"/>
- /// Partitioner. It is provided with the following parameters: the current element,
- /// a <see cref="System.Threading.Tasks.ParallelLoopState">ParallelLoopState</see> instance that may be
- /// used to break out of the loop prematurely, the current element's index (an Int64), and some local
- /// state that may be shared amongst iterations that execute on the same thread.
- /// </para>
- /// <para>
- /// The <paramref name="localInit"/> delegate is invoked once for each thread that participates in the loop's
- /// execution and returns the initial local state for each of those threads. These initial states are passed to the first
- /// <paramref name="body"/> invocations on each thread. Then, every subsequent body invocation returns a possibly
- /// modified state value that is passed to the next body invocation. Finally, the last body invocation on each thread returns a state value
- /// that is passed to the <paramref name="localFinally"/> delegate. The localFinally delegate is invoked once per thread to perform a final
- /// action on each thread's local state.
- /// </para>
- /// </remarks>
- public static ParallelLoopResult ForEach<TSource, TLocal>(
- OrderablePartitioner<TSource> source,
- ParallelOptions parallelOptions,
- Func<TLocal> localInit,
- Func<TSource, ParallelLoopState, long, TLocal, TLocal> body,
- Action<TLocal> localFinally)
- {
- if (source == null)
- {
- throw new ArgumentNullException(nameof(source));
- }
- if (body == null)
- {
- throw new ArgumentNullException(nameof(body));
- }
- if (localInit == null)
- {
- throw new ArgumentNullException(nameof(localInit));
- }
- if (localFinally == null)
- {
- throw new ArgumentNullException(nameof(localFinally));
- }
- if (parallelOptions == null)
- {
- throw new ArgumentNullException(nameof(parallelOptions));
- }
-
- if (!source.KeysNormalized)
- {
- throw new InvalidOperationException(Environment.GetResourceString("Parallel_ForEach_OrderedPartitionerKeysNotNormalized"));
- }
-
- return PartitionerForEachWorker<TSource, TLocal>(source, parallelOptions, null, null, null, null, body, localInit, localFinally);
- }
-
- // Main worker method for Parallel.ForEach() calls w/ Partitioners.
- private static ParallelLoopResult PartitionerForEachWorker<TSource, TLocal>(
- Partitioner<TSource> source, // Might be OrderablePartitioner
- ParallelOptions parallelOptions,
- Action<TSource> simpleBody,
- Action<TSource, ParallelLoopState> bodyWithState,
- Action<TSource, ParallelLoopState, long> bodyWithStateAndIndex,
- Func<TSource, ParallelLoopState, TLocal, TLocal> bodyWithStateAndLocal,
- Func<TSource, ParallelLoopState, long, TLocal, TLocal> bodyWithEverything,
- Func<TLocal> localInit,
- Action<TLocal> localFinally)
- {
- 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");
- 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>;
- Debug.Assert((orderedSource != null) || (bodyWithStateAndIndex == null && bodyWithEverything == null),
- "PartitionForEach: bodies with indices are only allowable for OrderablePartitioner");
-
- if (!source.SupportsDynamicPartitions)
- {
- throw new InvalidOperationException(Environment.GetResourceString("Parallel_ForEach_PartitionerNotDynamic"));
- }
-
- // Before getting started, do a quick peek to see if we have been canceled already
- if (parallelOptions.CancellationToken.IsCancellationRequested)
- {
- throw new OperationCanceledException(parallelOptions.CancellationToken);
- }
-
- // ETW event for Parallel For begin
- int forkJoinContextID = 0;
- Task callerTask = null;
- if (TplEtwProvider.Log.IsEnabled())
- {
- forkJoinContextID = Interlocked.Increment(ref s_forkJoinContextID);
- callerTask = Task.InternalCurrent;
- TplEtwProvider.Log.ParallelLoopBegin((callerTask != null ? callerTask.m_taskScheduler.Id : TaskScheduler.Current.Id), (callerTask != null ? callerTask.Id : 0),
- forkJoinContextID, TplEtwProvider.ForkJoinOperationType.ParallelForEach,
- 0, 0);
- }
-
- // For all loops we need a shared flag even though we don't have a body with state,
- // because the shared flag contains the exceptional bool, which triggers other workers
- // to exit their loops if one worker catches an exception
- ParallelLoopStateFlags64 sharedPStateFlags = new ParallelLoopStateFlags64();
-
- // Instantiate our result. Specifics will be filled in later.
- ParallelLoopResult result = new ParallelLoopResult();
-
- // Keep track of any cancellations
- OperationCanceledException oce = null;
-
- CancellationTokenRegistration ctr = new CancellationTokenRegistration();
-
- // if cancellation is enabled, we need to register a callback to stop the loop when it gets signaled
- if (parallelOptions.CancellationToken.CanBeCanceled)
- {
- ctr = parallelOptions.CancellationToken.InternalRegisterWithoutEC((o) =>
- {
- // Cause processing to stop
- sharedPStateFlags.Cancel();
- // Record our cancellation
- oce = new OperationCanceledException(parallelOptions.CancellationToken);
- }, null);
- }
-
- // Get our dynamic partitioner -- depends on whether source is castable to OrderablePartitioner
- // Also, do some error checking.
- IEnumerable<TSource> partitionerSource = null;
- IEnumerable<KeyValuePair<long, TSource>> orderablePartitionerSource = null;
- if (orderedSource != null)
- {
- orderablePartitionerSource = orderedSource.GetOrderableDynamicPartitions();
- if (orderablePartitionerSource == null)
- {
- throw new InvalidOperationException(Environment.GetResourceString("Parallel_ForEach_PartitionerReturnedNull"));
- }
- }
- else
- {
- partitionerSource = source.GetDynamicPartitions();
- if (partitionerSource == null)
- {
- throw new InvalidOperationException(Environment.GetResourceString("Parallel_ForEach_PartitionerReturnedNull"));
- }
- }
-
- ParallelForReplicatingTask rootTask = null;
-
- // This is the action that will be run by each replicable task.
- Action partitionAction = delegate
- {
- Task currentWorkerTask = Task.InternalCurrent;
-
- // ETW event for ParallelForEach Worker Fork
- if (TplEtwProvider.Log.IsEnabled())
- {
- TplEtwProvider.Log.ParallelFork((currentWorkerTask != null ? currentWorkerTask.m_taskScheduler.Id : TaskScheduler.Current.Id), (currentWorkerTask != null ? currentWorkerTask.Id : 0),
- forkJoinContextID);
- }
-
- TLocal localValue = default(TLocal);
- bool bLocalValueInitialized = false; // Tracks whether localInit ran without exceptions, so that we can skip localFinally if it wasn't
- IDisposable myPartitionToDispose = null;
-
- try
- {
- // Create a new state object that references the shared "stopped" and "exceptional" flags.
- // If needed, it will contain a new instance of thread-local state by invoking the selector.
- ParallelLoopState64 state = null;
-
- if (bodyWithState != null || bodyWithStateAndIndex != null)
- {
- state = new ParallelLoopState64(sharedPStateFlags);
- }
- else if (bodyWithStateAndLocal != null || bodyWithEverything != null)
- {
- state = new ParallelLoopState64(sharedPStateFlags);
- // If a thread-local selector was supplied, invoke it. Otherwise, stick with the default.
- if (localInit != null)
- {
- localValue = localInit();
- bLocalValueInitialized = true;
- }
- }
-
-
- bool bIsRootTask = (rootTask == currentWorkerTask);
-
- // initialize a loop timer which will help us decide whether we should exit early
- LoopTimer loopTimer = new LoopTimer(rootTask.ActiveChildCount);
-
- if (orderedSource != null)
- {
- // Use this path for OrderablePartitioner
-
-
- // first check if there's saved state from a previous replica that we might be replacing.
- // the only state to be passed down in such a transition is the enumerator
- IEnumerator<KeyValuePair<long, TSource>> myPartition = currentWorkerTask.SavedStateFromPreviousReplica as IEnumerator<KeyValuePair<long, TSource>>;
- if (myPartition == null)
- {
- // apparently we're a brand new replica, get a fresh enumerator from the partitioner
- myPartition = orderablePartitionerSource.GetEnumerator();
- if (myPartition == null)
- {
- throw new InvalidOperationException(Environment.GetResourceString("Parallel_ForEach_NullEnumerator"));
- }
- }
- myPartitionToDispose = myPartition;
-
- while (myPartition.MoveNext())
- {
- KeyValuePair<long, TSource> kvp = myPartition.Current;
- long index = kvp.Key;
- TSource value = kvp.Value;
-
- // Update our iteration index
- if (state != null) state.CurrentIteration = index;
-
- if (simpleBody != null)
- simpleBody(value);
- else if (bodyWithState != null)
- bodyWithState(value, state);
- else if (bodyWithStateAndIndex != null)
- bodyWithStateAndIndex(value, state, index);
- else if (bodyWithStateAndLocal != null)
- localValue = bodyWithStateAndLocal(value, state, localValue);
- else
- localValue = bodyWithEverything(value, state, index, localValue);
-
- if (sharedPStateFlags.ShouldExitLoop(index)) break;
-
- // Cooperative multitasking workaround for AppDomain fairness.
- // Check if allowed loop time is exceeded, if so save current state and return. The self replicating task logic
- // will detect this, and queue up a replacement task. Note that we don't do this on the root task.
- if (!bIsRootTask && loopTimer.LimitExceeded())
- {
- currentWorkerTask.SavedStateForNextReplica = myPartition;
- myPartitionToDispose = null;
- break;
- }
- }
-
- }
- else
- {
- // Use this path for Partitioner that is not OrderablePartitioner
-
- // first check if there's saved state from a previous replica that we might be replacing.
- // the only state to be passed down in such a transition is the enumerator
- IEnumerator<TSource> myPartition = currentWorkerTask.SavedStateFromPreviousReplica as IEnumerator<TSource>;
- if (myPartition == null)
- {
- // apparently we're a brand new replica, get a fresh enumerator from the partitioner
- myPartition = partitionerSource.GetEnumerator();
- if (myPartition == null)
- {
- throw new InvalidOperationException(Environment.GetResourceString("Parallel_ForEach_NullEnumerator"));
- }
- }
- myPartitionToDispose = myPartition;
-
- // I'm not going to try to maintain this
- if (state != null)
- state.CurrentIteration = 0;
-
- while (myPartition.MoveNext())
- {
- TSource t = myPartition.Current;
-
- if (simpleBody != null)
- simpleBody(t);
- else if (bodyWithState != null)
- bodyWithState(t, state);
- else if (bodyWithStateAndLocal != null)
- localValue = bodyWithStateAndLocal(t, state, localValue);
- else
- Debug.Assert(false, "PartitionerForEach: illegal body type in Partitioner handler");
-
-
- // Any break, stop or exception causes us to halt
- // We don't have the global indexing information to discriminate whether or not
- // we are before or after a break point.
- if (sharedPStateFlags.LoopStateFlags != ParallelLoopStateFlags.PLS_NONE)
- break;
-
- // Cooperative multitasking workaround for AppDomain fairness.
- // Check if allowed loop time is exceeded, if so save current state and return. The self replicating task logic
- // will detect this, and queue up a replacement task. Note that we don't do this on the root task.
- if (!bIsRootTask && loopTimer.LimitExceeded())
- {
- currentWorkerTask.SavedStateForNextReplica = myPartition;
- myPartitionToDispose = null;
- break;
- }
- }
- }
- }
- catch
- {
- // Inform other tasks of the exception, then rethrow
- sharedPStateFlags.SetExceptional();
- throw;
- }
- finally
- {
- if (localFinally != null && bLocalValueInitialized)
- {
- localFinally(localValue);
- }
-
- if (myPartitionToDispose != null)
- {
- myPartitionToDispose.Dispose();
- }
-
- // ETW event for ParallelFor Worker Join
- if (TplEtwProvider.Log.IsEnabled())
- {
- TplEtwProvider.Log.ParallelJoin((currentWorkerTask != null ? currentWorkerTask.m_taskScheduler.Id : TaskScheduler.Current.Id), (currentWorkerTask != null ? currentWorkerTask.Id : 0),
- forkJoinContextID);
- }
- }
- };
-
- try
- {
- // Create and start the self-replicating task.
- // This needs to be in try-block because it can throw in BuggyScheduler.MaxConcurrencyLevel
- rootTask = new ParallelForReplicatingTask(parallelOptions, partitionAction, TaskCreationOptions.None,
- InternalTaskOptions.SelfReplicating);
-
- // And process it's completion...
- // Moved inside try{} block because faulty scheduler may throw here.
- rootTask.RunSynchronously(parallelOptions.EffectiveTaskScheduler);
-
- rootTask.Wait();
-
- // If we made a cancellation registration, we need to clean it up now before observing the OCE
- // Otherwise we could be caught in the middle of a callback, and observe PLS_STOPPED, but oce = null
- if (parallelOptions.CancellationToken.CanBeCanceled)
- {
- ctr.Dispose();
- }
-
- // If we got through that with no exceptions, and we were canceled, then
- // throw our cancellation exception
- if (oce != null) throw oce;
- }
- catch (AggregateException aggExp)
- {
- // if we made a cancellation registration, and rootTask.Wait threw, we need to clean it up here
- if (parallelOptions.CancellationToken.CanBeCanceled)
- {
- ctr.Dispose();
- }
-
- // see if we can combine it into a single OCE. If not propagate the original exception
- ThrowIfReducableToSingleOCE(aggExp.InnerExceptions, parallelOptions.CancellationToken);
- throw;
- }
- catch (TaskSchedulerException)
- {
- // if we made a cancellation registration, and either we threw an exception constructing rootTask or
- // rootTask.RunSynchronously threw, we need to clean it up here.
- if (parallelOptions.CancellationToken.CanBeCanceled)
- {
- ctr.Dispose();
- }
- throw;
- }
- finally
- {
- int sb_status = sharedPStateFlags.LoopStateFlags;
- result.m_completed = (sb_status == ParallelLoopStateFlags.PLS_NONE);
- if ((sb_status & ParallelLoopStateFlags.PLS_BROKEN) != 0)
- {
- result.m_lowestBreakIteration = sharedPStateFlags.LowestBreakIteration;
- }
-
- if ((rootTask != null) && rootTask.IsCompleted) rootTask.Dispose();
-
- //dispose the partitioner source if it implements IDisposable
- IDisposable d = null;
- if (orderablePartitionerSource != null)
- {
- d = orderablePartitionerSource as IDisposable;
- }
- else
- {
- d = partitionerSource as IDisposable;
- }
-
- if (d != null)
- {
- d.Dispose();
- }
-
- // ETW event for Parallel For End
- if (TplEtwProvider.Log.IsEnabled())
- {
- TplEtwProvider.Log.ParallelLoopEnd((callerTask != null ? callerTask.m_taskScheduler.Id : TaskScheduler.Current.Id), (callerTask != null ? callerTask.Id : 0),
- forkJoinContextID, 0);
- }
- }
-
- return result;
- }
-
- /// <summary>
- /// Internal utility function that implements the OCE filtering behavior for all Parallel.* APIs.
- /// Throws a single OperationCancelledException object with the token if the Exception collection only contains
- /// OperationCancelledExceptions with the given CancellationToken.
- ///
- /// </summary>
- /// <param name="excCollection"> The exception collection to filter</param>
- /// <param name="ct"> The CancellationToken expected on all inner exceptions</param>
- /// <returns></returns>
- internal static void ThrowIfReducableToSingleOCE(IEnumerable<Exception> excCollection, CancellationToken ct)
- {
- bool bCollectionNotZeroLength = false;
- if (ct.IsCancellationRequested)
- {
- foreach (Exception e in excCollection)
- {
- bCollectionNotZeroLength = true;
- OperationCanceledException oce = e as OperationCanceledException;
- if (oce == null || oce.CancellationToken != ct)
- {
- // mismatch found
- return;
- }
- }
-
- // all exceptions are OCEs with this token, let's throw it
- if (bCollectionNotZeroLength) throw new OperationCanceledException(ct);
- }
- }
-
- internal struct LoopTimer
- {
- public LoopTimer(int nWorkerTaskIndex)
- {
- // This logic ensures that we have a diversity of timeouts across worker tasks (100, 150, 200, 250, 100, etc)
- // Otherwise all worker will try to timeout at precisely the same point, which is bad if the work is just about to finish
- int timeOut = s_BaseNotifyPeriodMS + (nWorkerTaskIndex % PlatformHelper.ProcessorCount) * s_NotifyPeriodIncrementMS;
-
- m_timeLimit = Environment.TickCount + timeOut;
- }
-
- public bool LimitExceeded()
- {
- 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.
- return (Environment.TickCount > m_timeLimit);
- }
-
- const int s_BaseNotifyPeriodMS = 100;
- const int s_NotifyPeriodIncrementMS = 50;
-
- private int m_timeLimit;
- }
-
- }
-
-}
diff --git a/src/mscorlib/src/System/Threading/Tasks/ParallelLoopState.cs b/src/mscorlib/src/System/Threading/Tasks/ParallelLoopState.cs
deleted file mode 100644
index 6a62cf8977..0000000000
--- a/src/mscorlib/src/System/Threading/Tasks/ParallelLoopState.cs
+++ /dev/null
@@ -1,641 +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.
-
-// =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+
-//
-// ParallelState.cs
-//
-//
-// A non-generic and generic parallel state class, used by the Parallel helper class
-// for parallel loop management.
-//
-// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
-
-using System.Diagnostics;
-using System.Security.Permissions;
-using System.Diagnostics.Contracts;
-
-// Prevents compiler warnings/errors regarding the use of ref params in Interlocked methods
-#pragma warning disable 0420
-
-namespace System.Threading.Tasks
-{
-
- /// <summary>
- /// Enables iterations of <see cref="T:System.Threading.Tasks.Parallel"/> loops to interact with
- /// other iterations.
- /// </summary>
- [DebuggerDisplay("ShouldExitCurrentIteration = {ShouldExitCurrentIteration}")]
- public class ParallelLoopState
- {
- // Derived classes will track a ParallelStateFlags32 or ParallelStateFlags64.
- // So this is slightly redundant, but it enables us to implement some
- // methods in this base class.
- private ParallelLoopStateFlags m_flagsBase;
-
- internal ParallelLoopState(ParallelLoopStateFlags fbase)
- {
- m_flagsBase = fbase;
- }
-
- /// <summary>
- /// Internal/virtual support for ShouldExitCurrentIteration.
- /// </summary>
- internal virtual bool InternalShouldExitCurrentIteration
- {
- get
- {
- Debug.Assert(false);
- throw new NotSupportedException(
- Environment.GetResourceString("ParallelState_NotSupportedException_UnsupportedMethod"));
- }
- }
-
- /// <summary>
- /// Gets whether the current iteration of the loop should exit based
- /// on requests made by this or other iterations.
- /// </summary>
- /// <remarks>
- /// When an iteration of a loop calls <see cref="Break()"/> or <see cref="Stop()"/>, or
- /// when one throws an exception, or when the loop is canceled, the <see cref="Parallel"/> class will proactively
- /// attempt to prohibit additional iterations of the loop from starting execution.
- /// However, there may be cases where it is unable to prevent additional iterations from starting.
- /// It may also be the case that a long-running iteration has already begun execution. In such
- /// cases, iterations may explicitly check the <see cref="ShouldExitCurrentIteration"/> property and
- /// cease execution if the property returns true.
- /// </remarks>
- public bool ShouldExitCurrentIteration
- {
- get
- {
- return InternalShouldExitCurrentIteration;
- }
- }
-
- /// <summary>
- /// Gets whether any iteration of the loop has called <see cref="Stop()"/>.
- /// </summary>
- public bool IsStopped
- {
- get
- {
- return ((m_flagsBase.LoopStateFlags & ParallelLoopStateFlags.PLS_STOPPED) != 0);
- }
- }
-
- /// <summary>
- /// Gets whether any iteration of the loop has thrown an exception that went unhandled by that
- /// iteration.
- /// </summary>
- public bool IsExceptional
- {
- get
- {
- return ((m_flagsBase.LoopStateFlags & ParallelLoopStateFlags.PLS_EXCEPTIONAL) != 0);
- }
- }
-
- /// <summary>
- /// Internal/virtual support for LowestBreakIteration.
- /// </summary>
- internal virtual long? InternalLowestBreakIteration
- {
- get
- {
- Debug.Assert(false);
- throw new NotSupportedException(
- Environment.GetResourceString("ParallelState_NotSupportedException_UnsupportedMethod"));
- }
- }
-
- /// <summary>
- /// Gets the lowest iteration of the loop from which <see cref="Break()"/> was called.
- /// </summary>
- /// <remarks>
- /// If no iteration of the loop called <see cref="Break()"/>, this property will return null.
- /// </remarks>
- public long? LowestBreakIteration
- {
- get
- {
- return InternalLowestBreakIteration;
- }
- }
-
- /// <summary>
- /// Communicates that the <see cref="Parallel"/> loop should cease execution at the system's earliest
- /// convenience.
- /// </summary>
- /// <exception cref="T:System.InvalidOperationException">
- /// The <see cref="Break()"/> method was previously called. <see cref="Break()"/> and <see
- /// cref="Stop()"/> may not be used in combination by iterations of the same loop.
- /// </exception>
- /// <remarks>
- /// <para>
- /// <see cref="Stop()"/> may be used to communicate to the loop that no other iterations need be run.
- /// For long-running iterations that may already be executing, <see cref="Stop()"/> causes <see cref="IsStopped"/>
- /// to return true for all other iterations of the loop, such that another iteration may check <see
- /// cref="IsStopped"/> and exit early if it's observed to be true.
- /// </para>
- /// <para>
- /// <see cref="Stop()"/> is typically employed in search-based algorithms, where once a result is found,
- /// no other iterations need be executed.
- /// </para>
- /// </remarks>
- public void Stop()
- {
- m_flagsBase.Stop();
- }
-
- // Internal/virtual support for Break().
- internal virtual void InternalBreak()
- {
- Debug.Assert(false);
- throw new NotSupportedException(
- Environment.GetResourceString("ParallelState_NotSupportedException_UnsupportedMethod"));
- }
-
- /// <summary>
- /// Communicates that the <see cref="Parallel"/> loop should cease execution at the system's earliest
- /// convenience of iterations beyond the current iteration.
- /// </summary>
- /// <exception cref="T:System.InvalidOperationException">
- /// The <see cref="Stop()"/> method was previously called. <see cref="Break()"/> and <see cref="Stop()"/>
- /// may not be used in combination by iterations of the same loop.
- /// </exception>
- /// <remarks>
- /// <para>
- /// <see cref="Break()"/> may be used to communicate to the loop that no other iterations after the
- /// current iteration need be run. For example, if <see cref="Break()"/> is called from the 100th
- /// iteration of a for loop iterating in parallel from 0 to 1000, all iterations less than 100 should
- /// still be run, but the iterations from 101 through to 1000 are not necessary.
- /// </para>
- /// <para>
- /// For long-running iterations that may already be executing, <see cref="Break()"/> causes <see
- /// cref="LowestBreakIteration"/>
- /// to be set to the current iteration's index if the current index is less than the current value of
- /// <see cref="LowestBreakIteration"/>.
- /// </para>
- /// <para>
- /// <see cref="Break()"/> is typically employed in search-based algorithms where an ordering is
- /// present in the data source.
- /// </para>
- /// </remarks>
- public void Break()
- {
- InternalBreak();
- }
-
- // Helper method to avoid repeating Break() logic between ParallelState32 and ParallelState32<TLocal>
- internal static void Break(int iteration, ParallelLoopStateFlags32 pflags)
- {
- int oldValue = ParallelLoopStateFlags.PLS_NONE;
-
- // Attempt to change state from "not stopped or broken or canceled or exceptional" to "broken".
- if (!pflags.AtomicLoopStateUpdate(ParallelLoopStateFlags.PLS_BROKEN,
- ParallelLoopStateFlags.PLS_STOPPED | ParallelLoopStateFlags.PLS_EXCEPTIONAL | ParallelLoopStateFlags.PLS_CANCELED,
- ref oldValue))
- {
-
- // If we were already stopped, we have a problem
- if ((oldValue & ParallelLoopStateFlags.PLS_STOPPED) != 0)
- {
- throw new InvalidOperationException(
- Environment.GetResourceString("ParallelState_Break_InvalidOperationException_BreakAfterStop"));
- }
- else
- {
- // Apparently we previously got cancelled or became exceptional. No action necessary
- return;
- }
- }
-
- // replace shared LowestBreakIteration with CurrentIteration, but only if CurrentIteration
- // is less than LowestBreakIteration.
- int oldLBI = pflags.m_lowestBreakIteration;
- if (iteration < oldLBI)
- {
- SpinWait wait = new SpinWait();
- while (Interlocked.CompareExchange(
- ref pflags.m_lowestBreakIteration,
- iteration,
- oldLBI) != oldLBI)
- {
- wait.SpinOnce();
- oldLBI = pflags.m_lowestBreakIteration;
- if (iteration > oldLBI) break;
- }
- }
-
- }
-
- // Helper method to avoid repeating Break() logic between ParallelState64 and ParallelState64<TLocal>
- internal static void Break(long iteration, ParallelLoopStateFlags64 pflags)
- {
- int oldValue = ParallelLoopStateFlags.PLS_NONE;
-
- // Attempt to change state from "not stopped or broken or canceled or exceptional" to "broken".
- if (!pflags.AtomicLoopStateUpdate(ParallelLoopStateFlags.PLS_BROKEN,
- ParallelLoopStateFlags.PLS_STOPPED | ParallelLoopStateFlags.PLS_EXCEPTIONAL | ParallelLoopStateFlags.PLS_CANCELED,
- ref oldValue))
- {
-
- // If we were already stopped, we have a problem
- if ((oldValue & ParallelLoopStateFlags.PLS_STOPPED) != 0)
- {
- throw new InvalidOperationException(
- Environment.GetResourceString("ParallelState_Break_InvalidOperationException_BreakAfterStop"));
- }
- else
- {
- // Apparently we previously got cancelled or became exceptional. No action necessary
- return;
- }
- }
-
- // replace shared LowestBreakIteration with CurrentIteration, but only if CurrentIteration
- // is less than LowestBreakIteration.
- long oldLBI = pflags.LowestBreakIteration;
- if (iteration < oldLBI)
- {
- SpinWait wait = new SpinWait();
- while (Interlocked.CompareExchange(
- ref pflags.m_lowestBreakIteration,
- iteration,
- oldLBI) != oldLBI)
- {
- wait.SpinOnce();
- oldLBI = pflags.LowestBreakIteration;
- if (iteration > oldLBI) break;
- }
- }
-
- }
- }
-
- internal class ParallelLoopState32 : ParallelLoopState
- {
- private ParallelLoopStateFlags32 m_sharedParallelStateFlags;
- private int m_currentIteration = 0;
-
- /// <summary>
- /// Internal constructor to ensure an instance isn't created by users.
- /// </summary>
- /// <param name="sharedParallelStateFlags">A flag shared among all threads participating
- /// in the execution of a certain loop.</param>
- internal ParallelLoopState32(ParallelLoopStateFlags32 sharedParallelStateFlags)
- : base(sharedParallelStateFlags)
- {
- m_sharedParallelStateFlags = sharedParallelStateFlags;
- }
-
- /// <summary>
- /// Tracks the current loop iteration for the owning task.
- /// This is used to compute whether or not the task should
- /// terminate early due to a Break() call.
- /// </summary>
- internal int CurrentIteration {
- get { return m_currentIteration; }
- set { m_currentIteration = value; }
- }
-
- /// <summary>
- /// Returns true if we should be exiting from the current iteration
- /// due to Stop(), Break() or exception.
- /// </summary>
- internal override bool InternalShouldExitCurrentIteration
- {
- get { return m_sharedParallelStateFlags.ShouldExitLoop(CurrentIteration); }
- }
-
- /// <summary>
- /// Returns the lowest iteration at which Break() has been called, or
- /// null if Break() has not yet been called.
- /// </summary>
- internal override long? InternalLowestBreakIteration
- {
- get {return m_sharedParallelStateFlags.NullableLowestBreakIteration; }
- }
-
- /// <summary>
- /// Communicates that parallel tasks should stop when they reach a specified iteration element.
- /// (which is CurrentIteration of the caller).
- /// </summary>
- /// <exception cref="T:System.InvalidOperationException">Break() called after Stop().</exception>
- /// <remarks>
- /// This is shared with all other concurrent threads in the system which are participating in the
- /// loop's execution. After calling Break(), no additional iterations will be executed on
- /// the current thread, and other worker threads will execute once they get beyond the calling iteration.
- /// </remarks>
- internal override void InternalBreak()
- {
- ParallelLoopState.Break(CurrentIteration, m_sharedParallelStateFlags);
- }
- }
-
- /// <summary>
- /// Allows independent iterations of a parallel loop to interact with other iterations.
- /// </summary>
- internal class ParallelLoopState64 : ParallelLoopState
- {
- private ParallelLoopStateFlags64 m_sharedParallelStateFlags;
- private long m_currentIteration = 0;
-
- /// <summary>
- /// Internal constructor to ensure an instance isn't created by users.
- /// </summary>
- /// <param name="sharedParallelStateFlags">A flag shared among all threads participating
- /// in the execution of a certain loop.</param>
- internal ParallelLoopState64(ParallelLoopStateFlags64 sharedParallelStateFlags)
- : base(sharedParallelStateFlags)
- {
- m_sharedParallelStateFlags = sharedParallelStateFlags;
- }
-
- /// <summary>
- /// Tracks the current loop iteration for the owning task.
- /// This is used to compute whether or not the task should
- /// terminate early due to a Break() call.
- /// </summary>
- internal long CurrentIteration
- {
- // No interlocks needed, because this value is only accessed in a single thread.
- get {return m_currentIteration;}
- set {m_currentIteration = value; }
- }
-
- /// <summary>
- /// Returns true if we should be exiting from the current iteration
- /// due to Stop(), Break() or exception.
- /// </summary>
- internal override bool InternalShouldExitCurrentIteration
- {
- get { return m_sharedParallelStateFlags.ShouldExitLoop(CurrentIteration); }
- }
-
- /// <summary>
- /// Returns the lowest iteration at which Break() has been called, or
- /// null if Break() has not yet been called.
- /// </summary>
- internal override long? InternalLowestBreakIteration
- {
- // We don't need to worry about torn read/write here because
- // ParallelStateFlags64.LowestBreakIteration property is protected
- // by an Interlocked.Read().
- get { return m_sharedParallelStateFlags.NullableLowestBreakIteration; }
- }
-
- /// <summary>
- /// Communicates that parallel tasks should stop when they reach a specified iteration element.
- /// (which is CurrentIteration of the caller).
- /// </summary>
- /// <exception cref="T:System.InvalidOperationException">Break() called after Stop().</exception>
- /// <remarks>
- /// Atomically sets shared StoppedBroken flag to BROKEN, then atomically sets shared
- /// LowestBreakIteration to CurrentIteration, but only if CurrentIteration is less than
- /// LowestBreakIteration.
- /// </remarks>
- internal override void InternalBreak()
- {
- ParallelLoopState.Break(CurrentIteration, m_sharedParallelStateFlags);
- }
-
- }
-
- /// <summary>
- /// State information that is common between ParallelStateFlags class
- /// and ParallelStateFlags64 class.
- /// </summary>
- internal class ParallelLoopStateFlags
- {
- internal static int PLS_NONE;
- internal static int PLS_EXCEPTIONAL = 1;
- internal static int PLS_BROKEN = 2;
- internal static int PLS_STOPPED = 4;
- internal static int PLS_CANCELED = 8;
-
- private volatile int m_LoopStateFlags = PLS_NONE;
-
- internal int LoopStateFlags
- {
- get { return m_LoopStateFlags; }
- }
-
- internal bool AtomicLoopStateUpdate(int newState, int illegalStates)
- {
- int oldState = 0;
- return AtomicLoopStateUpdate(newState, illegalStates, ref oldState);
- }
-
- internal bool AtomicLoopStateUpdate(int newState, int illegalStates, ref int oldState)
- {
- SpinWait sw = new SpinWait();
-
- do
- {
- oldState = m_LoopStateFlags;
- if ((oldState & illegalStates) != 0) return false;
- if (Interlocked.CompareExchange(ref m_LoopStateFlags, oldState | newState, oldState) == oldState)
- {
- return true;
- }
- sw.SpinOnce();
- } while (true);
-
- }
-
- internal void SetExceptional()
- {
- // we can set the exceptional flag regardless of the state of other bits.
- AtomicLoopStateUpdate(PLS_EXCEPTIONAL, PLS_NONE);
- }
-
- internal void Stop()
- {
- // disallow setting of PLS_STOPPED bit only if PLS_BROKEN was already set
- if (!AtomicLoopStateUpdate(PLS_STOPPED, PLS_BROKEN))
- {
- throw new InvalidOperationException(
- Environment.GetResourceString("ParallelState_Stop_InvalidOperationException_StopAfterBreak"));
- }
- }
-
- // Returns true if StoppedBroken is updated to PLS_CANCELED.
- internal bool Cancel()
- {
- // we can set the canceled flag regardless of the state of other bits.
- return (AtomicLoopStateUpdate(PLS_CANCELED, PLS_NONE));
- }
- }
-
- /// <summary>
- /// An internal class used to share accounting information in 32-bit versions
- /// of For()/ForEach() loops.
- /// </summary>
- internal class ParallelLoopStateFlags32 : ParallelLoopStateFlags
- {
- // Records the lowest iteration at which a Break() has been called,
- // or Int32.MaxValue if no break has been called. Used directly
- // by Break().
- internal volatile int m_lowestBreakIteration = Int32.MaxValue;
-
- // Not strictly necessary, but maintains consistency with ParallelStateFlags64
- internal int LowestBreakIteration
- {
- get { return m_lowestBreakIteration; }
- }
-
- // Does some processing to convert m_lowestBreakIteration to a long?.
- internal long? NullableLowestBreakIteration
- {
- get
- {
- if (m_lowestBreakIteration == Int32.MaxValue) return null;
- else
- {
- // protect against torn read of 64-bit value
- long rval = m_lowestBreakIteration;
- if (IntPtr.Size >= 8) return rval;
- else return Interlocked.Read(ref rval);
- }
- }
- }
-
-
- /// <summary>
- /// Lets the caller know whether or not to prematurely exit the For/ForEach loop.
- /// If this returns true, then exit the loop. Otherwise, keep going.
- /// </summary>
- /// <param name="CallerIteration">The caller's current iteration point
- /// in the loop.</param>
- /// <remarks>
- /// The loop should exit on any one of the following conditions:
- /// (1) Stop() has been called by one or more tasks.
- /// (2) An exception has been raised by one or more tasks.
- /// (3) Break() has been called by one or more tasks, and
- /// CallerIteration exceeds the (lowest) iteration at which
- /// Break() was called.
- /// (4) The loop was canceled.
- /// </remarks>
- internal bool ShouldExitLoop(int CallerIteration)
- {
- int flags = LoopStateFlags;
- return (flags != PLS_NONE && (
- ((flags & (PLS_EXCEPTIONAL | PLS_STOPPED | PLS_CANCELED)) != 0) ||
- (((flags & PLS_BROKEN) != 0) && (CallerIteration > LowestBreakIteration))));
- }
-
- // This lighter version of ShouldExitLoop will be used when the body type doesn't contain a state.
- // Since simpler bodies cannot stop or break, we can safely skip checks for those flags here.
- internal bool ShouldExitLoop()
- {
- int flags = LoopStateFlags;
- return ((flags != PLS_NONE) && ((flags & (PLS_EXCEPTIONAL | PLS_CANCELED)) != 0));
- }
- }
-
- /// <summary>
- /// An internal class used to share accounting information in 64-bit versions
- /// of For()/ForEach() loops.
- /// </summary>
- internal class ParallelLoopStateFlags64 : ParallelLoopStateFlags
- {
- // Records the lowest iteration at which a Break() has been called,
- // or Int64.MaxValue if no break has been called. Used directly
- // by Break().
- internal long m_lowestBreakIteration = Int64.MaxValue;
-
- // Performs a conditionally interlocked read of m_lowestBreakIteration.
- internal long LowestBreakIteration
- {
- get
- {
- if (IntPtr.Size >= 8) return m_lowestBreakIteration;
- else return Interlocked.Read(ref m_lowestBreakIteration);
- }
- }
-
- // Does some processing to convert m_lowestBreakIteration to a long?.
- internal long? NullableLowestBreakIteration
- {
- get
- {
- if (m_lowestBreakIteration == Int64.MaxValue) return null;
- else
- {
- if (IntPtr.Size >= 8) return m_lowestBreakIteration;
- else return Interlocked.Read(ref m_lowestBreakIteration);
- }
- }
- }
-
- /// <summary>
- /// Lets the caller know whether or not to prematurely exit the For/ForEach loop.
- /// If this returns true, then exit the loop. Otherwise, keep going.
- /// </summary>
- /// <param name="CallerIteration">The caller's current iteration point
- /// in the loop.</param>
- /// <remarks>
- /// The loop should exit on any one of the following conditions:
- /// (1) Stop() has been called by one or more tasks.
- /// (2) An exception has been raised by one or more tasks.
- /// (3) Break() has been called by one or more tasks, and
- /// CallerIteration exceeds the (lowest) iteration at which
- /// Break() was called.
- /// (4) The loop has been canceled.
- /// </remarks>
- internal bool ShouldExitLoop(long CallerIteration)
- {
- int flags = LoopStateFlags;
- return (flags != PLS_NONE && (
- ((flags & (PLS_EXCEPTIONAL | PLS_STOPPED | PLS_CANCELED)) != 0) ||
- (((flags & PLS_BROKEN) != 0) && (CallerIteration > LowestBreakIteration))));
- }
-
- // This lighter version of ShouldExitLoop will be used when the body type doesn't contain a state.
- // Since simpler bodies cannot stop or break, we can safely skip checks for those flags here.
- internal bool ShouldExitLoop()
- {
- int flags = LoopStateFlags;
- return ((flags != PLS_NONE) && ((flags & (PLS_EXCEPTIONAL | PLS_CANCELED)) != 0));
- }
- }
-
- /// <summary>
- /// Provides completion status on the execution of a <see cref="Parallel"/> loop.
- /// </summary>
- /// <remarks>
- /// If <see cref="IsCompleted"/> returns true, then the loop ran to completion, such that all iterations
- /// of the loop were executed. If <see cref="IsCompleted"/> returns false and <see
- /// cref="LowestBreakIteration"/> returns null, a call to <see
- /// cref="System.Threading.Tasks.ParallelLoopState.Stop"/> was used to end the loop prematurely. If <see
- /// cref="IsCompleted"/> returns false and <see cref="LowestBreakIteration"/> returns a non-null integral
- /// value, <see cref="System.Threading.Tasks.ParallelLoopState.Break()"/> was used to end the loop prematurely.
- /// </remarks>
- public struct ParallelLoopResult
- {
- internal bool m_completed;
- internal long? m_lowestBreakIteration;
-
- /// <summary>
- /// Gets whether the loop ran to completion, such that all iterations of the loop were executed
- /// and the loop didn't receive a request to end prematurely.
- /// </summary>
- public bool IsCompleted { get { return m_completed; } }
-
- /// <summary>
- /// Gets the index of the lowest iteration from which <see
- /// cref="System.Threading.Tasks.ParallelLoopState.Break()"/>
- /// was called.
- /// </summary>
- /// <remarks>
- /// If <see cref="System.Threading.Tasks.ParallelLoopState.Break()"/> was not employed, this property will
- /// return null.
- /// </remarks>
- public long? LowestBreakIteration { get { return m_lowestBreakIteration; } }
- }
-
-}
-
-#pragma warning restore 0420
diff --git a/src/mscorlib/src/System/Threading/Tasks/ParallelRangeManager.cs b/src/mscorlib/src/System/Threading/Tasks/ParallelRangeManager.cs
deleted file mode 100644
index 49f61a6614..0000000000
--- a/src/mscorlib/src/System/Threading/Tasks/ParallelRangeManager.cs
+++ /dev/null
@@ -1,279 +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.
-
-// =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+
-//
-//
-//
-// Implements the algorithm for distributing loop indices to parallel loop workers
-//
-// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
-
-using System;
-using System.Threading;
-using System.Diagnostics;
-using System.Diagnostics.Contracts;
-
-#pragma warning disable 0420
-
-namespace System.Threading.Tasks
-{
- /// <summary>
- /// Represents an index range
- /// </summary>
- internal struct IndexRange
- {
- // the From and To values for this range. These do not change.
- internal long m_nFromInclusive;
- internal long m_nToExclusive;
-
- // The shared index, stored as the offset from nFromInclusive. Using an offset rather than the actual
- // value saves us from overflows that can happen due to multiple workers racing to increment this.
- // All updates to this field need to be interlocked.
- internal volatile Shared<long> m_nSharedCurrentIndexOffset;
-
- // to be set to 1 by the worker that finishes this range. It's OK to do a non-interlocked write here.
- internal int m_bRangeFinished;
- }
-
-
- /// <summary>
- /// The RangeWorker struct wraps the state needed by a task that services the parallel loop
- /// </summary>
- internal struct RangeWorker
- {
- // reference to the IndexRange array allocated by the range manager
- internal readonly IndexRange[] m_indexRanges;
-
- // index of the current index range that this worker is grabbing chunks from
- internal int m_nCurrentIndexRange;
-
- // the step for this loop. Duplicated here for quick access (rather than jumping to rangemanager)
- internal long m_nStep;
-
- // increment value is the current amount that this worker will use
- // to increment the shared index of the range it's working on
- internal long m_nIncrementValue;
-
- // the increment value is doubled each time this worker finds work, and is capped at this value
- internal readonly long m_nMaxIncrementValue;
-
- /// <summary>
- /// Initializes a RangeWorker struct
- /// </summary>
- internal RangeWorker(IndexRange[] ranges, int nInitialRange, long nStep)
- {
- m_indexRanges = ranges;
- m_nCurrentIndexRange = nInitialRange;
- m_nStep = nStep;
-
- m_nIncrementValue = nStep;
-
- m_nMaxIncrementValue = Parallel.DEFAULT_LOOP_STRIDE * nStep;
- }
-
- /// <summary>
- /// Implements the core work search algorithm that will be used for this range worker.
- /// </summary>
- ///
- /// Usage pattern is:
- /// 1) the thread associated with this rangeworker calls FindNewWork
- /// 2) if we return true, the worker uses the nFromInclusiveLocal and nToExclusiveLocal values
- /// to execute the sequential loop
- /// 3) if we return false it means there is no more work left. It's time to quit.
- ///
- internal bool FindNewWork(out long nFromInclusiveLocal, out long nToExclusiveLocal)
- {
- // since we iterate over index ranges circularly, we will use the
- // count of visited ranges as our exit condition
- int numIndexRangesToVisit = m_indexRanges.Length;
-
- do
- {
- // local snap to save array access bounds checks in places where we only read fields
- IndexRange currentRange = m_indexRanges[m_nCurrentIndexRange];
-
- if (currentRange.m_bRangeFinished == 0)
- {
- if (m_indexRanges[m_nCurrentIndexRange].m_nSharedCurrentIndexOffset == null)
- {
- Interlocked.CompareExchange(ref m_indexRanges[m_nCurrentIndexRange].m_nSharedCurrentIndexOffset, new Shared<long>(0), null);
- }
-
- // this access needs to be on the array slot
- long nMyOffset = Interlocked.Add(ref m_indexRanges[m_nCurrentIndexRange].m_nSharedCurrentIndexOffset.Value,
- m_nIncrementValue) - m_nIncrementValue;
-
- if (currentRange.m_nToExclusive - currentRange.m_nFromInclusive > nMyOffset)
- {
- // we found work
-
- nFromInclusiveLocal = currentRange.m_nFromInclusive + nMyOffset;
- nToExclusiveLocal = nFromInclusiveLocal + m_nIncrementValue;
-
- // Check for going past end of range, or wrapping
- if ( (nToExclusiveLocal > currentRange.m_nToExclusive) || (nToExclusiveLocal < currentRange.m_nFromInclusive) )
- {
- nToExclusiveLocal = currentRange.m_nToExclusive;
- }
-
- // We will double our unit of increment until it reaches the maximum.
- if (m_nIncrementValue < m_nMaxIncrementValue)
- {
- m_nIncrementValue *= 2;
- if (m_nIncrementValue > m_nMaxIncrementValue)
- {
- m_nIncrementValue = m_nMaxIncrementValue;
- }
- }
-
- return true;
- }
- else
- {
- // this index range is completed, mark it so that others can skip it quickly
- Interlocked.Exchange(ref m_indexRanges[m_nCurrentIndexRange].m_bRangeFinished, 1);
- }
- }
-
- // move on to the next index range, in circular order.
- m_nCurrentIndexRange = (m_nCurrentIndexRange + 1) % m_indexRanges.Length;
- numIndexRangesToVisit--;
-
- } while (numIndexRangesToVisit > 0);
- // we've visited all index ranges possible => there's no work remaining
-
- nFromInclusiveLocal = 0;
- nToExclusiveLocal = 0;
-
- return false;
- }
-
-
- /// <summary>
- /// 32 bit integer version of FindNewWork. Assumes the ranges were initialized with 32 bit values.
- /// </summary>
- internal bool FindNewWork32(out int nFromInclusiveLocal32, out int nToExclusiveLocal32)
- {
- long nFromInclusiveLocal;
- long nToExclusiveLocal;
-
- bool bRetVal = FindNewWork(out nFromInclusiveLocal, out nToExclusiveLocal);
-
- Debug.Assert((nFromInclusiveLocal <= Int32.MaxValue) && (nFromInclusiveLocal >= Int32.MinValue) &&
- (nToExclusiveLocal <= Int32.MaxValue) && (nToExclusiveLocal >= Int32.MinValue));
-
- // convert to 32 bit before returning
- nFromInclusiveLocal32 = (int)nFromInclusiveLocal;
- nToExclusiveLocal32 = (int)nToExclusiveLocal;
-
- return bRetVal;
- }
- }
-
-
- /// <summary>
- /// Represents the entire loop operation, keeping track of workers and ranges.
- /// </summary>
- ///
- /// The usage pattern is:
- /// 1) The Parallel loop entry function (ForWorker) creates an instance of this class
- /// 2) Every thread joining to service the parallel loop calls RegisterWorker to grab a
- /// RangeWorker struct to wrap the state it will need to find and execute work,
- /// and they keep interacting with that struct until the end of the loop
- internal class RangeManager
- {
- internal readonly IndexRange[] m_indexRanges;
-
- internal int m_nCurrentIndexRangeToAssign;
- internal long m_nStep;
-
- /// <summary>
- /// Initializes a RangeManager with the given loop parameters, and the desired number of outer ranges
- /// </summary>
- internal RangeManager(long nFromInclusive, long nToExclusive, long nStep, int nNumExpectedWorkers)
- {
- m_nCurrentIndexRangeToAssign = 0;
- m_nStep = nStep;
-
- // Our signed math breaks down w/ nNumExpectedWorkers == 1. So change it to 2.
- if (nNumExpectedWorkers == 1)
- nNumExpectedWorkers = 2;
-
- //
- // calculate the size of each index range
- //
-
- ulong uSpan = (ulong)(nToExclusive - nFromInclusive);
- ulong uRangeSize = uSpan / (ulong) nNumExpectedWorkers; // rough estimate first
-
- uRangeSize -= uRangeSize % (ulong) nStep; // snap to multiples of nStep
- // otherwise index range transitions will derail us from nStep
-
- if (uRangeSize == 0)
- {
- uRangeSize = (ulong) nStep;
- }
-
- //
- // find the actual number of index ranges we will need
- //
- Debug.Assert((uSpan / uRangeSize) < Int32.MaxValue);
-
- int nNumRanges = (int)(uSpan / uRangeSize);
-
- if (uSpan % uRangeSize != 0)
- {
- nNumRanges++;
- }
-
-
- // Convert to signed so the rest of the logic works.
- // Should be fine so long as uRangeSize < Int64.MaxValue, which we guaranteed by setting #workers >= 2.
- long nRangeSize = (long)uRangeSize;
-
- // allocate the array of index ranges
- m_indexRanges = new IndexRange[nNumRanges];
-
- long nCurrentIndex = nFromInclusive;
- for (int i = 0; i < nNumRanges; i++)
- {
- // the fromInclusive of the new index range is always on nCurrentIndex
- m_indexRanges[i].m_nFromInclusive = nCurrentIndex;
- m_indexRanges[i].m_nSharedCurrentIndexOffset = null;
- m_indexRanges[i].m_bRangeFinished = 0;
-
- // now increment it to find the toExclusive value for our range
- nCurrentIndex += nRangeSize;
-
- // detect integer overflow or range overage and snap to nToExclusive
- if (nCurrentIndex < nCurrentIndex - nRangeSize ||
- nCurrentIndex > nToExclusive)
- {
- // this should only happen at the last index
- Debug.Assert(i == nNumRanges - 1);
-
- nCurrentIndex = nToExclusive;
- }
-
- // now that the end point of the new range is calculated, assign it.
- m_indexRanges[i].m_nToExclusive = nCurrentIndex;
- }
- }
-
- /// <summary>
- /// The function that needs to be called by each new worker thread servicing the parallel loop
- /// in order to get a RangeWorker struct that wraps the state for finding and executing indices
- /// </summary>
- internal RangeWorker RegisterNewWorker()
- {
- Debug.Assert(m_indexRanges != null && m_indexRanges.Length != 0);
-
- int nInitialRange = (Interlocked.Increment(ref m_nCurrentIndexRangeToAssign) - 1) % m_indexRanges.Length;
-
- return new RangeWorker(m_indexRanges, nInitialRange, m_nStep);
- }
- }
-}
-#pragma warning restore 0420
diff --git a/src/mscorlib/src/System/Threading/Tasks/ProducerConsumerQueues.cs b/src/mscorlib/src/System/Threading/Tasks/ProducerConsumerQueues.cs
index 6b9dfbbe37..545bf9a5e5 100644
--- a/src/mscorlib/src/System/Threading/Tasks/ProducerConsumerQueues.cs
+++ b/src/mscorlib/src/System/Threading/Tasks/ProducerConsumerQueues.cs
@@ -52,11 +52,6 @@ namespace System.Threading.Tasks
/// <summary>Gets the number of items in the collection.</summary>
/// <remarks>In many implementations, this method will not be thread-safe.</remarks>
int Count { get; }
-
- /// <summary>A thread-safe way to get the number of items in the collection. May synchronize access by locking the provided synchronization object.</summary>
- /// <param name="syncObj">The sync object used to lock</param>
- /// <returns>The collection count</returns>
- int GetCountSafe(object syncObj);
}
/// <summary>
@@ -80,10 +75,6 @@ namespace System.Threading.Tasks
/// <summary>Gets the number of items in the collection.</summary>
int IProducerConsumerQueue<T>.Count { get { return base.Count; } }
-
- /// <summary>A thread-safe way to get the number of items in the collection. May synchronize access by locking the provided synchronization object.</summary>
- /// <remarks>ConcurrentQueue.Count is thread safe, no need to acquire the lock.</remarks>
- int IProducerConsumerQueue<T>.GetCountSafe(object syncObj) { return base.Count; }
}
/// <summary>
@@ -260,143 +251,6 @@ namespace System.Threading.Tasks
return true;
}
- /// <summary>Attempts to peek at an item in the queue.</summary>
- /// <param name="result">The peeked item.</param>
- /// <returns>true if an item could be peeked; otherwise, false.</returns>
- public bool TryPeek(out T result)
- {
- Segment segment = m_head;
- var array = segment.m_array;
- int first = segment.m_state.m_first; // local copy to avoid multiple volatile reads
-
- // Fast path: there's obviously data available in the current segment
- if (first != segment.m_state.m_lastCopy)
- {
- result = array[first];
- return true;
- }
- // Slow path: there may not be data available in the current segment
- else return TryPeekSlow(ref segment, ref array, out result);
- }
-
- /// <summary>Attempts to peek at an item in the queue.</summary>
- /// <param name="array">The array from which the item is peeked.</param>
- /// <param name="segment">The segment from which the item is peeked.</param>
- /// <param name="result">The peeked item.</param>
- /// <returns>true if an item could be peeked; otherwise, false.</returns>
- private bool TryPeekSlow(ref Segment segment, ref T[] array, out T result)
- {
- Contract.Requires(segment != null, "Expected a non-null segment.");
- Contract.Requires(array != null, "Expected a non-null item array.");
-
- if (segment.m_state.m_last != segment.m_state.m_lastCopy)
- {
- segment.m_state.m_lastCopy = segment.m_state.m_last;
- return TryPeek(out result); // will only recur once for this peek operation
- }
-
- if (segment.m_next != null && segment.m_state.m_first == segment.m_state.m_last)
- {
- segment = segment.m_next;
- array = segment.m_array;
- m_head = segment;
- }
-
- var first = segment.m_state.m_first; // local copy to avoid extraneous volatile reads
-
- if (first == segment.m_state.m_last)
- {
- result = default(T);
- return false;
- }
-
- result = array[first];
- return true;
- }
-
- /// <summary>Attempts to dequeue an item from the queue.</summary>
- /// <param name="predicate">The predicate that must return true for the item to be dequeued. If null, all items implicitly return true.</param>
- /// <param name="result">The dequeued item.</param>
- /// <returns>true if an item could be dequeued; otherwise, false.</returns>
- public bool TryDequeueIf(Predicate<T> predicate, out T result)
- {
- Segment segment = m_head;
- var array = segment.m_array;
- int first = segment.m_state.m_first; // local copy to avoid multiple volatile reads
-
- // Fast path: there's obviously data available in the current segment
- if (first != segment.m_state.m_lastCopy)
- {
- result = array[first];
- if (predicate == null || predicate(result))
- {
- array[first] = default(T); // Clear the slot to release the element
- segment.m_state.m_first = (first + 1) & (array.Length - 1);
- return true;
- }
- else
- {
- result = default(T);
- return false;
- }
- }
- // Slow path: there may not be data available in the current segment
- else return TryDequeueIfSlow(predicate, ref segment, ref array, out result);
- }
-
- /// <summary>Attempts to dequeue an item from the queue.</summary>
- /// <param name="predicate">The predicate that must return true for the item to be dequeued. If null, all items implicitly return true.</param>
- /// <param name="array">The array from which the item was dequeued.</param>
- /// <param name="segment">The segment from which the item was dequeued.</param>
- /// <param name="result">The dequeued item.</param>
- /// <returns>true if an item could be dequeued; otherwise, false.</returns>
- private bool TryDequeueIfSlow(Predicate<T> predicate, ref Segment segment, ref T[] array, out T result)
- {
- Contract.Requires(segment != null, "Expected a non-null segment.");
- Contract.Requires(array != null, "Expected a non-null item array.");
-
- if (segment.m_state.m_last != segment.m_state.m_lastCopy)
- {
- segment.m_state.m_lastCopy = segment.m_state.m_last;
- return TryDequeueIf(predicate, out result); // will only recur once for this dequeue operation
- }
-
- if (segment.m_next != null && segment.m_state.m_first == segment.m_state.m_last)
- {
- segment = segment.m_next;
- array = segment.m_array;
- m_head = segment;
- }
-
- var first = segment.m_state.m_first; // local copy to avoid extraneous volatile reads
-
- if (first == segment.m_state.m_last)
- {
- result = default(T);
- return false;
- }
-
- result = array[first];
- if (predicate == null || predicate(result))
- {
- array[first] = default(T); // Clear the slot to release the element
- segment.m_state.m_first = (first + 1) & (segment.m_array.Length - 1);
- segment.m_state.m_lastCopy = segment.m_state.m_last; // Refresh m_lastCopy to ensure that m_first has not passed m_lastCopy
- return true;
- }
- else
- {
- result = default(T);
- return false;
- }
- }
-
- public void Clear()
- {
- T ignored;
- while (TryDequeue(out ignored)) ;
- }
-
/// <summary>Gets whether the collection is currently empty.</summary>
/// <remarks>WARNING: This should not be used concurrently without further vetting.</remarks>
public bool IsEmpty
@@ -452,17 +306,6 @@ namespace System.Threading.Tasks
}
}
- /// <summary>A thread-safe way to get the number of items in the collection. May synchronize access by locking the provided synchronization object.</summary>
- /// <remarks>The Count is not thread safe, so we need to acquire the lock.</remarks>
- int IProducerConsumerQueue<T>.GetCountSafe(object syncObj)
- {
- Debug.Assert(syncObj != null, "The syncObj parameter is null.");
- lock (syncObj)
- {
- return Count;
- }
- }
-
/// <summary>A segment in the queue containing one or more items.</summary>
[StructLayout(LayoutKind.Sequential)]
private sealed class Segment
@@ -520,23 +363,9 @@ namespace System.Threading.Tasks
Contract.Requires(queue != null, "Expected a non-null queue.");
m_queue = queue;
}
-
- /// <summary>Gets the contents of the list.</summary>
- [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)]
- public T[] Items
- {
- get
- {
- List<T> list = new List<T>();
- foreach (T item in m_queue)
- list.Add(item);
- return list.ToArray();
- }
- }
}
}
-
/// <summary>A placeholder class for common padding constants and eventually routines.</summary>
static class PaddingHelpers
{
diff --git a/src/mscorlib/src/System/Threading/Tasks/TPLETWProvider.cs b/src/mscorlib/src/System/Threading/Tasks/TPLETWProvider.cs
index 325aa91b44..12cc1daa63 100644
--- a/src/mscorlib/src/System/Threading/Tasks/TPLETWProvider.cs
+++ b/src/mscorlib/src/System/Threading/Tasks/TPLETWProvider.cs
@@ -14,7 +14,6 @@ using System;
using System.Collections.Generic;
using System.Text;
using System.Security;
-using System.Security.Permissions;
using System.Runtime.CompilerServices;
namespace System.Threading.Tasks
@@ -61,17 +60,6 @@ namespace System.Threading.Tasks
/// <summary>Prevent external instantiation. All logging should go through the Log instance.</summary>
private TplEtwProvider() { }
- /// <summary>Type of a fork/join operation.</summary>
- public enum ForkJoinOperationType
- {
- /// <summary>Parallel.Invoke.</summary>
- ParallelInvoke=1,
- /// <summary>Parallel.For.</summary>
- ParallelFor=2,
- /// <summary>Parallel.ForEach.</summary>
- ParallelForEach=3
- }
-
/// <summary>Configured behavior of a task wait operation.</summary>
public enum TaskWaitBehavior : int
{
@@ -203,195 +191,6 @@ namespace System.Threading.Tasks
//-----------------------------------------------------------------------------------
//
- // Parallel Events
- //
-
- #region ParallelLoopBegin
- /// <summary>
- /// Denotes the entry point for a Parallel.For or Parallel.ForEach loop
- /// </summary>
- /// <param name="OriginatingTaskSchedulerID">The scheduler ID.</param>
- /// <param name="OriginatingTaskID">The task ID.</param>
- /// <param name="ForkJoinContextID">The loop ID.</param>
- /// <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>
- [Event(PARALLELLOOPBEGIN_ID, Level = EventLevel.Informational, ActivityOptions=EventActivityOptions.Recursive,
- Task = TplEtwProvider.Tasks.Loop, Opcode = EventOpcode.Start)]
- public void ParallelLoopBegin(
- int OriginatingTaskSchedulerID, int OriginatingTaskID, // PFX_COMMON_EVENT_HEADER
- int ForkJoinContextID, ForkJoinOperationType OperationType, // PFX_FORKJOIN_COMMON_EVENT_HEADER
- long InclusiveFrom, long ExclusiveTo)
- {
- if (IsEnabled() && IsEnabled(EventLevel.Informational, Keywords.Parallel))
- {
- // There is no explicit WriteEvent() overload matching this event's fields. Therefore calling
- // WriteEvent() would hit the "params" overload, which leads to an object allocation every time
- // this event is fired. To prevent that problem we will call WriteEventCore(), which works with
- // a stack based EventData array populated with the event fields.
- unsafe
- {
- EventData* eventPayload = stackalloc EventData[6];
-
- eventPayload[0].Size = sizeof(int);
- eventPayload[0].DataPointer = ((IntPtr) (&OriginatingTaskSchedulerID));
- eventPayload[1].Size = sizeof(int);
- eventPayload[1].DataPointer = ((IntPtr) (&OriginatingTaskID));
- eventPayload[2].Size = sizeof(int);
- eventPayload[2].DataPointer = ((IntPtr) (&ForkJoinContextID));
- eventPayload[3].Size = sizeof(int);
- eventPayload[3].DataPointer = ((IntPtr) (&OperationType));
- eventPayload[4].Size = sizeof(long);
- eventPayload[4].DataPointer = ((IntPtr) (&InclusiveFrom));
- eventPayload[5].Size = sizeof(long);
- eventPayload[5].DataPointer = ((IntPtr) (&ExclusiveTo));
-
- WriteEventCore(PARALLELLOOPBEGIN_ID, 6, eventPayload);
- }
- }
- }
- #endregion
-
- #region ParallelLoopEnd
- /// <summary>
- /// Denotes the end of a Parallel.For or Parallel.ForEach loop.
- /// </summary>
- /// <param name="OriginatingTaskSchedulerID">The scheduler ID.</param>
- /// <param name="OriginatingTaskID">The task ID.</param>
- /// <param name="ForkJoinContextID">The loop ID.</param>
- /// <param name="TotalIterations">the total number of iterations processed.</param>
- [Event(PARALLELLOOPEND_ID, Level = EventLevel.Informational, Task = TplEtwProvider.Tasks.Loop, Opcode = EventOpcode.Stop)]
- public void ParallelLoopEnd(
- int OriginatingTaskSchedulerID, int OriginatingTaskID, // PFX_COMMON_EVENT_HEADER
- int ForkJoinContextID, long TotalIterations)
- {
- if (IsEnabled() && IsEnabled(EventLevel.Informational, Keywords.Parallel))
- {
- // There is no explicit WriteEvent() overload matching this event's fields.
- // Therefore calling WriteEvent() would hit the "params" overload, which leads to an object allocation every time this event is fired.
- // To prevent that problem we will call WriteEventCore(), which works with a stack based EventData array populated with the event fields
- unsafe
- {
- EventData* eventPayload = stackalloc EventData[4];
-
- eventPayload[0].Size = sizeof(int);
- eventPayload[0].DataPointer = ((IntPtr) (&OriginatingTaskSchedulerID));
- eventPayload[1].Size = sizeof(int);
- eventPayload[1].DataPointer = ((IntPtr) (&OriginatingTaskID));
- eventPayload[2].Size = sizeof(int);
- eventPayload[2].DataPointer = ((IntPtr) (&ForkJoinContextID));
- eventPayload[3].Size = sizeof(long);
- eventPayload[3].DataPointer = ((IntPtr) (&TotalIterations));
-
- WriteEventCore(PARALLELLOOPEND_ID, 4, eventPayload);
- }
- }
- }
- #endregion
-
- #region ParallelInvokeBegin
- /// <summary>Denotes the entry point for a Parallel.Invoke call.</summary>
- /// <param name="OriginatingTaskSchedulerID">The scheduler ID.</param>
- /// <param name="OriginatingTaskID">The task ID.</param>
- /// <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>
- [Event(PARALLELINVOKEBEGIN_ID, Level = EventLevel.Informational, ActivityOptions=EventActivityOptions.Recursive,
- Task = TplEtwProvider.Tasks.Invoke, Opcode = EventOpcode.Start)]
- public void ParallelInvokeBegin(
- int OriginatingTaskSchedulerID, int OriginatingTaskID, // PFX_COMMON_EVENT_HEADER
- int ForkJoinContextID, ForkJoinOperationType OperationType, // PFX_FORKJOIN_COMMON_EVENT_HEADER
- int ActionCount)
- {
- if (IsEnabled() && IsEnabled(EventLevel.Informational, Keywords.Parallel))
- {
- // There is no explicit WriteEvent() overload matching this event's fields.
- // Therefore calling WriteEvent() would hit the "params" overload, which leads to an object allocation every time this event is fired.
- // To prevent that problem we will call WriteEventCore(), which works with a stack based EventData array populated with the event fields
- unsafe
- {
- EventData* eventPayload = stackalloc EventData[5];
-
- eventPayload[0].Size = sizeof(int);
- eventPayload[0].DataPointer = ((IntPtr) (&OriginatingTaskSchedulerID));
- eventPayload[1].Size = sizeof(int);
- eventPayload[1].DataPointer = ((IntPtr) (&OriginatingTaskID));
- eventPayload[2].Size = sizeof(int);
- eventPayload[2].DataPointer = ((IntPtr) (&ForkJoinContextID));
- eventPayload[3].Size = sizeof(int);
- eventPayload[3].DataPointer = ((IntPtr) (&OperationType));
- eventPayload[4].Size = sizeof(int);
- eventPayload[4].DataPointer = ((IntPtr) (&ActionCount));
-
- WriteEventCore(PARALLELINVOKEBEGIN_ID, 5, eventPayload);
- }
- }
- }
- #endregion
-
- #region ParallelInvokeEnd
- /// <summary>
- /// Denotes the exit point for a Parallel.Invoke call.
- /// </summary>
- /// <param name="OriginatingTaskSchedulerID">The scheduler ID.</param>
- /// <param name="OriginatingTaskID">The task ID.</param>
- /// <param name="ForkJoinContextID">The invoke ID.</param>
- [Event(PARALLELINVOKEEND_ID, Level = EventLevel.Informational, Task = TplEtwProvider.Tasks.Invoke, Opcode = EventOpcode.Stop)]
- public void ParallelInvokeEnd(
- int OriginatingTaskSchedulerID, int OriginatingTaskID, // PFX_COMMON_EVENT_HEADER
- int ForkJoinContextID)
- {
- if (IsEnabled() && IsEnabled(EventLevel.Informational, Keywords.Parallel))
- {
- WriteEvent(PARALLELINVOKEEND_ID, OriginatingTaskSchedulerID, OriginatingTaskID, ForkJoinContextID);
- }
- }
- #endregion
-
- #region ParallelFork
- /// <summary>
- /// Denotes the start of an individual task that's part of a fork/join context.
- /// Before this event is fired, the start of the new fork/join context will be marked
- /// with another event that declares a unique context ID.
- /// </summary>
- /// <param name="OriginatingTaskSchedulerID">The scheduler ID.</param>
- /// <param name="OriginatingTaskID">The task ID.</param>
- /// <param name="ForkJoinContextID">The invoke ID.</param>
- [Event(PARALLELFORK_ID, Level = EventLevel.Verbose, ActivityOptions=EventActivityOptions.Recursive,
- Task = TplEtwProvider.Tasks.ForkJoin, Opcode = EventOpcode.Start)]
- public void ParallelFork(
- int OriginatingTaskSchedulerID, int OriginatingTaskID, // PFX_COMMON_EVENT_HEADER
- int ForkJoinContextID)
- {
- if (IsEnabled() && IsEnabled(EventLevel.Verbose, Keywords.Parallel))
- {
- WriteEvent(PARALLELFORK_ID, OriginatingTaskSchedulerID, OriginatingTaskID, ForkJoinContextID);
- }
- }
- #endregion
-
- #region ParallelJoin
- /// <summary>
- /// Denotes the end of an individual task that's part of a fork/join context.
- /// This should match a previous ParallelFork event with a matching "OriginatingTaskID"
- /// </summary>
- /// <param name="OriginatingTaskSchedulerID">The scheduler ID.</param>
- /// <param name="OriginatingTaskID">The task ID.</param>
- /// <param name="ForkJoinContextID">The invoke ID.</param>
- [Event(PARALLELJOIN_ID, Level = EventLevel.Verbose, Task = TplEtwProvider.Tasks.ForkJoin, Opcode = EventOpcode.Stop)]
- public void ParallelJoin(
- int OriginatingTaskSchedulerID, int OriginatingTaskID, // PFX_COMMON_EVENT_HEADER
- int ForkJoinContextID)
- {
- if (IsEnabled() && IsEnabled(EventLevel.Verbose, Keywords.Parallel))
- {
- WriteEvent(PARALLELJOIN_ID, OriginatingTaskSchedulerID, OriginatingTaskID, ForkJoinContextID);
- }
- }
- #endregion
-
- //-----------------------------------------------------------------------------------
- //
// Task Events
//
@@ -512,7 +311,7 @@ namespace System.Threading.Tasks
Level = EventLevel.Informational, Keywords = Keywords.TaskTransfer|Keywords.Tasks)]
public void TaskWaitBegin(
int OriginatingTaskSchedulerID, int OriginatingTaskID, // PFX_COMMON_EVENT_HEADER
- int TaskID, TaskWaitBehavior Behavior, int ContinueWithTaskID, int appDomain)
+ int TaskID, TaskWaitBehavior Behavior, int ContinueWithTaskID)
{
if (IsEnabled() && IsEnabled(EventLevel.Informational, Keywords.TaskTransfer|Keywords.Tasks))
{
@@ -534,8 +333,10 @@ namespace System.Threading.Tasks
Guid childActivityId = CreateGuidForTaskID(TaskID);
WriteEventWithRelatedActivityIdCore(TASKWAITBEGIN_ID, &childActivityId, 5, eventPayload);
}
- else
+ else
+ {
WriteEventCore(TASKWAITBEGIN_ID, 5, eventPayload);
+ }
}
}
}
@@ -688,7 +489,7 @@ namespace System.Threading.Tasks
}
}
- [NonEvent, System.Security.SecuritySafeCritical]
+ [NonEvent]
unsafe public void RunningContinuation(int TaskID, object Object) { RunningContinuation(TaskID, (long) *((void**) JitHelpers.UnsafeCastToStackPointer(ref Object))); }
[Event(20, Keywords = Keywords.Debug)]
private void RunningContinuation(int TaskID, long Object)
@@ -697,7 +498,7 @@ namespace System.Threading.Tasks
WriteEvent(20, TaskID, Object);
}
- [NonEvent, System.Security.SecuritySafeCritical]
+ [NonEvent]
unsafe public void RunningContinuationList(int TaskID, int Index, object Object) { RunningContinuationList(TaskID, Index, (long) *((void**) JitHelpers.UnsafeCastToStackPointer(ref Object))); }
[Event(21, Keywords = Keywords.Debug)]
@@ -707,9 +508,6 @@ namespace System.Threading.Tasks
WriteEvent(21, TaskID, Index, Object);
}
- [Event(22, Keywords = Keywords.Debug)]
- public void DebugMessage(string Message) { WriteEvent(22, Message); }
-
[Event(23, Keywords = Keywords.Debug)]
public void DebugFacilityMessage(string Facility, string Message) { WriteEvent(23, Facility, Message); }
diff --git a/src/mscorlib/src/System/Threading/Tasks/Task.cs b/src/mscorlib/src/System/Threading/Tasks/Task.cs
index cf081f75fd..7013c5c5e0 100644
--- a/src/mscorlib/src/System/Threading/Tasks/Task.cs
+++ b/src/mscorlib/src/System/Threading/Tasks/Task.cs
@@ -18,7 +18,6 @@ using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.ExceptionServices;
using System.Security;
-using System.Security.Permissions;
using System.Threading;
using System.Diagnostics;
using System.Diagnostics.Contracts;
@@ -147,7 +146,6 @@ namespace System.Threading.Tasks
private static StackGuard t_stackGuard; // The stack guard object for this thread
internal static int s_taskIdCounter; //static counter used to generate unique task IDs
- private readonly static TaskFactory s_factory = new TaskFactory();
private volatile int m_taskId; // this task's unique ID. initialized only if it is ever requested
@@ -365,12 +363,9 @@ namespace System.Threading.Tasks
/// </summary>
/// <param name="action">The delegate that represents the code to execute in the Task.</param>
/// <exception cref="T:System.ArgumentNullException">The <paramref name="action"/> argument is null.</exception>
- [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var have to be marked non-inlineable
public Task(Action action)
: this(action, null, null, default(CancellationToken), TaskCreationOptions.None, InternalTaskOptions.None, null)
{
- StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
- PossiblyCaptureContext(ref stackMark);
}
/// <summary>
@@ -383,12 +378,9 @@ namespace System.Threading.Tasks
/// <exception cref="T:System.ObjectDisposedException">The provided <see cref="System.Threading.CancellationToken">CancellationToken</see>
/// has already been disposed.
/// </exception>
- [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var have to be marked non-inlineable
public Task(Action action, CancellationToken cancellationToken)
: this(action, null, null, cancellationToken, TaskCreationOptions.None, InternalTaskOptions.None, null)
{
- StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
- PossiblyCaptureContext(ref stackMark);
}
/// <summary>
@@ -406,12 +398,9 @@ namespace System.Threading.Tasks
/// The <paramref name="creationOptions"/> argument specifies an invalid value for <see
/// cref="T:System.Threading.Tasks.TaskCreationOptions"/>.
/// </exception>
- [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var have to be marked non-inlineable
public Task(Action action, TaskCreationOptions creationOptions)
: this(action, null, Task.InternalCurrentIfAttached(creationOptions), default(CancellationToken), creationOptions, InternalTaskOptions.None, null)
{
- StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
- PossiblyCaptureContext(ref stackMark);
}
/// <summary>
@@ -433,12 +422,9 @@ namespace System.Threading.Tasks
/// <exception cref="T:System.ObjectDisposedException">The provided <see cref="System.Threading.CancellationToken">CancellationToken</see>
/// has already been disposed.
/// </exception>
- [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var have to be marked non-inlineable
public Task(Action action, CancellationToken cancellationToken, TaskCreationOptions creationOptions)
: this(action, null, Task.InternalCurrentIfAttached(creationOptions), cancellationToken, creationOptions, InternalTaskOptions.None, null)
{
- StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
- PossiblyCaptureContext(ref stackMark);
}
@@ -450,12 +436,9 @@ namespace System.Threading.Tasks
/// <exception cref="T:System.ArgumentNullException">
/// The <paramref name="action"/> argument is null.
/// </exception>
- [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var have to be marked non-inlineable
public Task(Action<object> action, object state)
: this(action, state, null, default(CancellationToken), TaskCreationOptions.None, InternalTaskOptions.None, null)
{
- StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
- PossiblyCaptureContext(ref stackMark);
}
/// <summary>
@@ -470,12 +453,9 @@ namespace System.Threading.Tasks
/// <exception cref="T:System.ObjectDisposedException">The provided <see cref="System.Threading.CancellationToken">CancellationToken</see>
/// has already been disposed.
/// </exception>
- [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var have to be marked non-inlineable
public Task(Action<object> action, object state, CancellationToken cancellationToken)
: this(action, state, null, cancellationToken, TaskCreationOptions.None, InternalTaskOptions.None, null)
{
- StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
- PossiblyCaptureContext(ref stackMark);
}
/// <summary>
@@ -494,12 +474,9 @@ namespace System.Threading.Tasks
/// The <paramref name="creationOptions"/> argument specifies an invalid value for <see
/// cref="T:System.Threading.Tasks.TaskCreationOptions"/>.
/// </exception>
- [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var have to be marked non-inlineable
public Task(Action<object> action, object state, TaskCreationOptions creationOptions)
: this(action, state, Task.InternalCurrentIfAttached(creationOptions), default(CancellationToken), creationOptions, InternalTaskOptions.None, null)
{
- StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
- PossiblyCaptureContext(ref stackMark);
}
/// <summary>
@@ -522,19 +499,9 @@ namespace System.Threading.Tasks
/// <exception cref="T:System.ObjectDisposedException">The provided <see cref="System.Threading.CancellationToken">CancellationToken</see>
/// has already been disposed.
/// </exception>
- [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var have to be marked non-inlineable
public Task(Action<object> action, object state, CancellationToken cancellationToken, TaskCreationOptions creationOptions)
: this(action, state, Task.InternalCurrentIfAttached(creationOptions), cancellationToken, creationOptions, InternalTaskOptions.None, null)
{
- StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
- PossiblyCaptureContext(ref stackMark);
- }
-
- internal Task(Action<object> action, object state, Task parent, CancellationToken cancellationToken,
- TaskCreationOptions creationOptions, InternalTaskOptions internalOptions, TaskScheduler scheduler, ref StackCrawlMark stackMark)
- : this(action, state, parent, cancellationToken, creationOptions, internalOptions, scheduler)
- {
- PossiblyCaptureContext(ref stackMark);
}
/// <summary>
@@ -557,10 +524,8 @@ namespace System.Threading.Tasks
}
Contract.EndContractBlock();
- // Keep a link to your parent if: (A) You are attached, or (B) you are self-replicating.
- if (parent != null &&
- ((creationOptions & TaskCreationOptions.AttachedToParent) != 0 ||
- (internalOptions & InternalTaskOptions.SelfReplicating) != 0))
+ // Keep a link to the parent if attached
+ if (parent != null && (creationOptions & TaskCreationOptions.AttachedToParent) != 0)
{
EnsureContingentPropertiesInitializedUnsafe().m_parent = parent;
}
@@ -586,6 +551,10 @@ namespace System.Threading.Tasks
m_stateObject = state;
m_taskScheduler = scheduler;
+ Debug.Assert(m_contingentProperties == null || m_contingentProperties.m_capturedContext == null,
+ "Captured an ExecutionContext when one was already captured.");
+ CapturedContext = ExecutionContext.Capture();
+
// Check for validity of options
if ((creationOptions &
~(TaskCreationOptions.AttachedToParent |
@@ -602,22 +571,13 @@ namespace System.Threading.Tasks
// Check the validity of internalOptions
int illegalInternalOptions =
(int) (internalOptions &
- ~(InternalTaskOptions.SelfReplicating |
- InternalTaskOptions.ChildReplica |
- InternalTaskOptions.PromiseTask |
+ ~(InternalTaskOptions.PromiseTask |
InternalTaskOptions.ContinuationTask |
InternalTaskOptions.LazyCancellation |
InternalTaskOptions.QueuedByRuntime));
Debug.Assert(illegalInternalOptions == 0, "TaskConstructorCore: Illegal internal options");
#endif
- // Throw exception if the user specifies both LongRunning and SelfReplicating
- if (((creationOptions & TaskCreationOptions.LongRunning) != 0) &&
- ((internalOptions & InternalTaskOptions.SelfReplicating) != 0))
- {
- ThrowHelper.ThrowInvalidOperationException(ExceptionResource.Task_ctor_LRandSR);
- }
-
// Assign options to m_stateAndOptionsFlag.
Debug.Assert(m_stateFlags == 0, "TaskConstructorCore: non-zero m_stateFlags");
Debug.Assert((((int)creationOptions) | OptionsMask) == OptionsMask, "TaskConstructorCore: options take too many bits");
@@ -648,9 +608,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)
{
- Debug.Assert((internalOptions &
- (InternalTaskOptions.ChildReplica | InternalTaskOptions.SelfReplicating | InternalTaskOptions.ContinuationTask)) == 0,
- "TaskConstructorCore: Did not expect to see cancelable token for replica/replicating or continuation task.");
+ Debug.Assert((internalOptions & InternalTaskOptions.ContinuationTask) == 0, "TaskConstructorCore: Did not expect to see cancelable token for continuation task.");
AssignCancellationToken(cancellationToken, null, null);
}
@@ -757,24 +715,6 @@ namespace System.Threading.Tasks
}
}
-
- /// <summary>
- /// Captures the ExecutionContext so long as flow isn't suppressed.
- /// </summary>
- /// <param name="stackMark">A stack crawl mark pointing to the frame of the caller.</param>
-
- internal void PossiblyCaptureContext(ref StackCrawlMark stackMark)
- {
- 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()
- // available, so we call the parameterless overload.
- CapturedContext = ExecutionContext.Capture(
- ref stackMark,
- ExecutionContext.CaptureOptions.IgnoreSyncCtx | ExecutionContext.CaptureOptions.OptimizeDefaultCase);
- }
-
// Internal property to process TaskCreationOptions access and mutation.
internal TaskCreationOptions Options
{
@@ -989,16 +929,14 @@ namespace System.Threading.Tasks
/// </summary>
internal void AddNewChild()
{
- Debug.Assert(Task.InternalCurrent == this || this.IsSelfReplicatingRoot, "Task.AddNewChild(): Called from an external context");
+ Debug.Assert(Task.InternalCurrent == this, "Task.AddNewChild(): Called from an external context");
var props = EnsureContingentPropertiesInitialized();
- if (props.m_completionCountdown == 1 && !IsSelfReplicatingRoot)
+ if (props.m_completionCountdown == 1)
{
// A count of 1 indicates so far there was only the parent, and this is the first child task
// Single kid => no fuss about who else is accessing the count. Let's save ourselves 100 cycles
- // We exclude self replicating root tasks from this optimization, because further child creation can take place on
- // other cores and with bad enough timing this write may not be visible to them.
props.m_completionCountdown++;
}
else
@@ -1264,7 +1202,7 @@ namespace System.Threading.Tasks
// Implicitly converts action to object and handles the meat of the StartNew() logic.
internal static Task InternalStartNew(
Task creatingTask, Delegate action, object state, CancellationToken cancellationToken, TaskScheduler scheduler,
- TaskCreationOptions options, InternalTaskOptions internalOptions, ref StackCrawlMark stackMark)
+ TaskCreationOptions options, InternalTaskOptions internalOptions)
{
// Validate arguments.
if (scheduler == null)
@@ -1276,7 +1214,6 @@ namespace System.Threading.Tasks
// Create and schedule the task. This throws an InvalidOperationException if already shut down.
// Here we add the InternalTaskOptions.QueuedByRuntime to the internalOptions, so that TaskConstructorCore can skip the cancellation token registration
Task t = new Task(action, state, creatingTask, cancellationToken, options, internalOptions | InternalTaskOptions.QueuedByRuntime, scheduler);
- t.PossiblyCaptureContext(ref stackMark);
t.ScheduleAndStart(false);
return t;
@@ -1615,23 +1552,10 @@ namespace System.Threading.Tasks
/// of <see cref="System.Threading.Tasks.TaskFactory"/>, as would result from using
/// the default constructor on TaskFactory.
/// </remarks>
- public static TaskFactory Factory { get { return s_factory; } }
-
- /// <summary>A task that's already been completed successfully.</summary>
- private static Task s_completedTask;
+ public static TaskFactory Factory { get; } = new TaskFactory();
/// <summary>Gets a task that's already been completed successfully.</summary>
- /// <remarks>May not always return the same instance.</remarks>
- public static Task CompletedTask
- {
- get
- {
- var completedTask = s_completedTask;
- if (completedTask == null)
- s_completedTask = completedTask = new Task(false, (TaskCreationOptions)InternalTaskOptions.DoNotDispose, default(CancellationToken)); // benign initialization race condition
- return completedTask;
- }
- }
+ public static Task CompletedTask { get; } = new Task(false, (TaskCreationOptions)InternalTaskOptions.DoNotDispose, default(CancellationToken));
/// <summary>
/// Provides an event that can be used to wait for completion.
@@ -1663,35 +1587,6 @@ namespace System.Threading.Tasks
}
}
- /// <summary>
- /// Determines whether this is the root task of a self replicating group.
- /// </summary>
- internal bool IsSelfReplicatingRoot
- {
- get
- {
- // Return true if self-replicating bit is set and child replica bit is not set
- return (Options & (TaskCreationOptions)(InternalTaskOptions.SelfReplicating | InternalTaskOptions.ChildReplica))
- == (TaskCreationOptions)InternalTaskOptions.SelfReplicating;
- }
- }
-
- /// <summary>
- /// Determines whether the task is a replica itself.
- /// </summary>
- internal bool IsChildReplica
- {
- get { return (Options & (TaskCreationOptions)InternalTaskOptions.ChildReplica) != 0; }
- }
-
- internal int ActiveChildCount
- {
- get
- {
- var props = Volatile.Read(ref m_contingentProperties);
- return props != null ? props.m_completionCountdown - 1 : 0;
- }
- }
/// <summary>
/// The property formerly known as IsFaulted.
@@ -1737,7 +1632,7 @@ namespace System.Threading.Tasks
}
else
{
- return m_contingentProperties?.m_capturedContext ?? ExecutionContext.PreAllocatedDefault;
+ return m_contingentProperties?.m_capturedContext ?? ExecutionContext.Default;
}
}
set
@@ -1747,7 +1642,7 @@ namespace System.Threading.Tasks
{
m_stateFlags |= TASK_STATE_EXECUTIONCONTEXT_IS_NULL;
}
- else if (!value.IsPreAllocatedDefault) // not the default context, then inflate the contingent properties and set it
+ else if (value != ExecutionContext.Default) // not the default context, then inflate the contingent properties and set it
{
EnsureContingentPropertiesInitializedUnsafe().m_capturedContext = value;
}
@@ -1755,32 +1650,6 @@ namespace System.Threading.Tasks
}
}
- /// <summary>
- /// Static helper function to copy specific ExecutionContext
- /// </summary>
- /// <param name="capturedContext">The captured context</param>
- /// <returns>The copied context, null if the capturedContext is null</returns>
- private static ExecutionContext CopyExecutionContext(ExecutionContext capturedContext)
- {
- if (capturedContext == null)
- return null;
- if (capturedContext.IsPreAllocatedDefault)
- return ExecutionContext.PreAllocatedDefault;
-
- return capturedContext.CreateCopy();
- }
-
-
-#if DEBUG
- /// <summary>
- /// Retrieves an identifier for the task.
- /// </summary>
- internal int InternalId
- {
- get { return GetHashCode(); }
- }
-#endif
-
/////////////
// methods
@@ -1920,7 +1789,7 @@ namespace System.Threading.Tasks
catch (ThreadAbortException tae)
{
AddException(tae);
- FinishThreadAbortedTask(true, false);
+ FinishThreadAbortedTask(delegateRan:false);
}
catch (Exception e)
{
@@ -1930,10 +1799,10 @@ namespace System.Threading.Tasks
AddException(tse);
Finish(false);
- // Now we need to mark ourselves as "handled" to avoid crashing the finalizer thread if we are called from StartNew()
- // or from the self replicating logic, because in both cases the exception is either propagated outside directly, or added
- // to an enclosing parent. However we won't do this for continuation tasks, because in that case we internally eat the exception
- // and therefore we need to make sure the user does later observe it explicitly or see it on the finalizer.
+ // Now we need to mark ourselves as "handled" to avoid crashing the finalizer thread if we are called from StartNew(),
+ // because the exception is either propagated outside directly, or added to an enclosing parent. However we won't do this for
+ // continuation tasks, because in that case we internally eat the exception and therefore we need to make sure the user does
+ // later observe it explicitly or see it on the finalizer.
if ((Options & (TaskCreationOptions)InternalTaskOptions.ContinuationTask) == 0)
{
@@ -2192,11 +2061,9 @@ namespace System.Threading.Tasks
var props = Volatile.Read(ref m_contingentProperties);
if (props == null || // no contingent properties means no children, so it's safe to complete ourselves
- (props.m_completionCountdown == 1 && !IsSelfReplicatingRoot) ||
+ (props.m_completionCountdown == 1) ||
// Count of 1 => either all children finished, or there were none. Safe to complete ourselves
// without paying the price of an Interlocked.Decrement.
- // However we need to exclude self replicating root tasks from this optimization, because
- // they can have children joining in, or finishing even after the root task delegate is done.
Interlocked.Decrement(ref props.m_completionCountdown) == 0) // Reaching this sub clause means there may be remaining active children,
// and we could be racing with one of them to call FinishStageTwo().
// So whoever does the final Interlocked.Dec is responsible to finish.
@@ -2424,19 +2291,13 @@ namespace System.Threading.Tasks
/// This makes a note in the state flags so that we avoid any costly synchronous operations in the finish codepath
/// such as inlined continuations
/// </summary>
- /// <param name="bTAEAddedToExceptionHolder">
- /// Indicates whether the ThreadAbortException was added to this task's exception holder.
- /// This should always be true except for the case of non-root self replicating task copies.
- /// </param>
/// <param name="delegateRan">Whether the delegate was executed.</param>
- internal void FinishThreadAbortedTask(bool bTAEAddedToExceptionHolder, bool delegateRan)
+ internal void FinishThreadAbortedTask(bool delegateRan)
{
- Debug.Assert(!bTAEAddedToExceptionHolder || m_contingentProperties?.m_exceptionsHolder != null,
- "FinishThreadAbortedTask() called on a task whose exception holder wasn't initialized");
+ Debug.Assert(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.
- if (bTAEAddedToExceptionHolder)
- m_contingentProperties.m_exceptionsHolder.MarkAsHandled(false);
+ m_contingentProperties.m_exceptionsHolder.MarkAsHandled(false);
// If this method has already been called for this task, or if this task has already completed, then
// return before actually calling Finish().
@@ -2447,220 +2308,33 @@ namespace System.Threading.Tasks
}
Finish(delegateRan);
-
}
/// <summary>
- /// Executes the task. This method will only be called once, and handles bookeeping associated with
- /// self-replicating tasks, in addition to performing necessary exception marshaling.
+ /// Executes the task. This method will only be called once, and handles any necessary exception marshaling.
/// </summary>
private void Execute()
{
- if (IsSelfReplicatingRoot)
+ try
{
- ExecuteSelfReplicating(this);
+ InnerInvoke();
}
- else
+ catch (ThreadAbortException tae)
{
- try
- {
- InnerInvoke();
- }
- catch (ThreadAbortException tae)
- {
- // Don't record the TAE or call FinishThreadAbortedTask for a child replica task --
- // it's already been done downstream.
- if (!IsChildReplica)
- {
- // Record this exception in the task's exception list
- HandleException(tae);
+ // Record this exception in the task's exception list
+ HandleException(tae);
- // This is a ThreadAbortException and it will be rethrown from this catch clause, causing us to
- // skip the regular Finish codepath. In order not to leave the task unfinished, we now call
- // FinishThreadAbortedTask here.
- FinishThreadAbortedTask(true, true);
- }
- }
- catch (Exception exn)
- {
- // Record this exception in the task's exception list
- HandleException(exn);
- }
+ // This is a ThreadAbortException and it will be rethrown from this catch clause, causing us to
+ // skip the regular Finish codepath. In order not to leave the task unfinished, we now call
+ // FinishThreadAbortedTask here.
+ FinishThreadAbortedTask(delegateRan: true);
}
- }
-
- // Allows (internal) deriving classes to support limited replication.
- // (By default, replication is basically unlimited).
- internal virtual bool ShouldReplicate()
- {
- return true;
- }
-
- // Allows (internal) deriving classes to instantiate the task replica as a Task super class of their choice
- // (By default, we create a regular Task instance)
- internal virtual Task CreateReplicaTask(Action<object> taskReplicaDelegate, Object stateObject, Task parentTask, TaskScheduler taskScheduler,
- TaskCreationOptions creationOptionsForReplica, InternalTaskOptions internalOptionsForReplica)
- {
- return new Task(taskReplicaDelegate, stateObject, parentTask, default(CancellationToken),
- creationOptionsForReplica, internalOptionsForReplica, parentTask.ExecutingTaskScheduler);
- }
-
- // Allows internal deriving classes to support replicas that exit prematurely and want to pass on state to the next replica
- internal virtual Object SavedStateForNextReplica
- {
- get { return null; }
-
- set { /*do nothing*/ }
- }
-
- // Allows internal deriving classes to support replicas that exit prematurely and want to pass on state to the next replica
- internal virtual Object SavedStateFromPreviousReplica
- {
- get { return null; }
-
- set { /*do nothing*/ }
- }
-
- // Allows internal deriving classes to support replicas that exit prematurely and want to hand over the child replica that they
- // had queued, so that the replacement replica can work with that child task instead of queuing up yet another one
- internal virtual Task HandedOverChildReplica
- {
- get { return null; }
-
- set { /* do nothing*/ }
- }
-
- private static void ExecuteSelfReplicating(Task root)
- {
- TaskCreationOptions creationOptionsForReplicas = root.CreationOptions | TaskCreationOptions.AttachedToParent;
- InternalTaskOptions internalOptionsForReplicas =
- InternalTaskOptions.ChildReplica | // child replica flag disables self replication for the replicas themselves.
- InternalTaskOptions.SelfReplicating | // we still want to identify this as part of a self replicating group
- InternalTaskOptions.QueuedByRuntime; // we queue and cancel these tasks internally, so don't allow CT registration to take place
-
-
- // Important Note: The child replicas we launch from here will be attached the root replica (by virtue of the root.CreateReplicaTask call)
- // because we need the root task to receive all their exceptions, and to block until all of them return
-
-
- // This variable is captured in a closure and shared among all replicas.
- bool replicasAreQuitting = false;
-
- // Set up a delegate that will form the body of the root and all recursively created replicas.
- Action<object> taskReplicaDelegate = null;
- taskReplicaDelegate = delegate
+ catch (Exception exn)
{
- Task currentTask = Task.InternalCurrent;
-
-
- // Check if a child task has been handed over by a prematurely quiting replica that we might be a replacement for.
- Task childTask = currentTask.HandedOverChildReplica;
-
- if (childTask == null)
- {
- // Apparently we are not a replacement task. This means we need to queue up a child task for replication to progress
-
- // Down-counts a counter in the root task.
- if (!root.ShouldReplicate()) return;
-
- // If any of the replicas have quit, we will do so ourselves.
- if (Volatile.Read(ref replicasAreQuitting))
- {
- return;
- }
-
- // Propagate a copy of the context from the root task. It may be null if flow was suppressed.
- ExecutionContext creatorContext = root.CapturedContext;
-
-
- childTask = root.CreateReplicaTask(taskReplicaDelegate, root.m_stateObject, root, root.ExecutingTaskScheduler,
- creationOptionsForReplicas, internalOptionsForReplicas);
-
- childTask.CapturedContext = CopyExecutionContext(creatorContext);
-
- childTask.ScheduleAndStart(false);
- }
-
-
-
- // Finally invoke the meat of the task.
- // Note that we are directly calling root.InnerInvoke() even though we are currently be in the action delegate of a child replica
- // This is because the actual work was passed down in that delegate, and the action delegate of the child replica simply contains this
- // replication control logic.
- try
- {
- // passing in currentTask only so that the parallel debugger can find it
- root.InnerInvokeWithArg(currentTask);
- }
- catch (Exception exn)
- {
- // Record this exception in the root task's exception list
- root.HandleException(exn);
-
- if (exn is ThreadAbortException)
- {
- // If this is a ThreadAbortException it will escape this catch clause, causing us to skip the regular Finish codepath
- // In order not to leave the task unfinished, we now call FinishThreadAbortedTask here
- currentTask.FinishThreadAbortedTask(false, true);
- }
- }
-
- Object savedState = currentTask.SavedStateForNextReplica;
-
- // check for premature exit
- if (savedState != null)
- {
- // the replica decided to exit early
- // we need to queue up a replacement, attach the saved state, and yield the thread right away
-
- Task replacementReplica = root.CreateReplicaTask(taskReplicaDelegate, root.m_stateObject, root, root.ExecutingTaskScheduler,
- creationOptionsForReplicas, internalOptionsForReplicas);
-
- // Propagate a copy of the context from the root task to the replacement task
- ExecutionContext creatorContext = root.CapturedContext;
- replacementReplica.CapturedContext = CopyExecutionContext(creatorContext);
-
- replacementReplica.HandedOverChildReplica = childTask;
- replacementReplica.SavedStateFromPreviousReplica = savedState;
-
- replacementReplica.ScheduleAndStart(false);
- }
- else
- {
- // The replica finished normally, which means it can't find more work to grab.
- // Time to mark replicas quitting
-
- replicasAreQuitting = true;
-
- // InternalCancel() could conceivably throw in the underlying scheduler's TryDequeue() method.
- // If it does, then make sure that we record it.
- try
- {
- childTask.InternalCancel(true);
- }
- catch (Exception e)
- {
- // Apparently TryDequeue threw an exception. Before propagating that exception, InternalCancel should have
- // attempted an atomic state transition and a call to CancellationCleanupLogic() on this task. So we know
- // the task was properly cleaned up if it was possible.
- //
- // Now all we need to do is to Record the exception in the root task.
-
- root.HandleException(e);
- }
-
- // No specific action needed if the child could not be canceled
- // because we attached it to the root task, which should therefore be receiving any exceptions from the child,
- // and root.wait will not return before this child finishes anyway.
-
- }
- };
-
- //
- // Now we execute as the root task
- //
- taskReplicaDelegate(null);
+ // Record this exception in the task's exception list
+ HandleException(exn);
+ }
}
/// <summary>
@@ -2683,7 +2357,7 @@ namespace System.Threading.Tasks
if (!IsCompleted)
{
HandleException(tae);
- FinishThreadAbortedTask(true, false);
+ FinishThreadAbortedTask(delegateRan:false);
}
}
@@ -2693,10 +2367,10 @@ 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>
+ /// in codepaths servicing user provided TaskSchedulers. The ThreadPool scheduler doesn't need this. </param>
internal bool ExecuteEntry(bool bPreventDoubleExecution)
{
- if (bPreventDoubleExecution || ((Options & (TaskCreationOptions)InternalTaskOptions.SelfReplicating) != 0))
+ if (bPreventDoubleExecution)
{
int previousState = 0;
@@ -2772,18 +2446,10 @@ namespace System.Threading.Tasks
}
else
{
- if (IsSelfReplicatingRoot || IsChildReplica)
- {
- CapturedContext = CopyExecutionContext(ec);
- }
-
// Run the task. We need a simple shim that converts the
// object back into a Task object, so that we can Execute it.
- // Lazily initialize the callback delegate; benign race condition
- var callback = s_ecCallback;
- if (callback == null) s_ecCallback = callback = new ContextCallback(ExecutionContextCallback);
- ExecutionContext.Run(ec, callback, this, true);
+ ExecutionContext.Run(ec, s_ecCallback, this);
}
if (AsyncCausalityTracer.LoggingOn)
@@ -2810,16 +2476,7 @@ namespace System.Threading.Tasks
}
}
- // Cached callback delegate that's lazily initialized due to ContextCallback being SecurityCritical
- private static ContextCallback s_ecCallback;
-
- private static void ExecutionContextCallback(object obj)
- {
- Task task = obj as Task;
- Debug.Assert(task != null, "expected a task object");
- task.Execute();
- }
-
+ private static readonly ContextCallback s_ecCallback = obj => ((Task)obj).Execute();
/// <summary>
/// The actual code which invokes the body of the task. This can be overriden in derived types.
@@ -2844,21 +2501,6 @@ namespace System.Threading.Tasks
}
/// <summary>
- /// Alternate InnerInvoke prototype to be called from ExecuteSelfReplicating() so that
- /// the Parallel Debugger can discover the actual task being invoked.
- /// Details: Here, InnerInvoke is actually being called on the rootTask object while we are actually executing the
- /// childTask. And the debugger needs to discover the childTask, so we pass that down as an argument.
- /// The NoOptimization and NoInlining flags ensure that the childTask pointer is retained, and that this
- /// function appears on the callstack.
- /// </summary>
- /// <param name="childTask"></param>
- [MethodImpl(MethodImplOptions.NoOptimization | MethodImplOptions.NoInlining)]
- internal void InnerInvokeWithArg(Task childTask)
- {
- InnerInvoke();
- }
-
- /// <summary>
/// Performs whatever handling is necessary for an unhandled exception. Normally
/// this just entails adding the exception to the holder object.
/// </summary>
@@ -2917,10 +2559,9 @@ namespace System.Threading.Tasks
/// true to attempt to marshal the continuation back to the original context captured; otherwise, false.
/// </param>
/// <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>
internal void SetContinuationForAwait(
- Action continuationAction, bool continueOnCapturedContext, bool flowExecutionContext, ref StackCrawlMark stackMark)
+ Action continuationAction, bool continueOnCapturedContext, bool flowExecutionContext)
{
Contract.Requires(continuationAction != null);
@@ -2941,7 +2582,7 @@ namespace System.Threading.Tasks
var syncCtx = SynchronizationContext.CurrentNoFlow;
if (syncCtx != null && syncCtx.GetType() != typeof(SynchronizationContext))
{
- tc = new SynchronizationContextAwaitTaskContinuation(syncCtx, continuationAction, flowExecutionContext, ref stackMark);
+ tc = new SynchronizationContextAwaitTaskContinuation(syncCtx, continuationAction, flowExecutionContext);
}
else
{
@@ -2950,7 +2591,7 @@ namespace System.Threading.Tasks
var scheduler = TaskScheduler.InternalCurrent;
if (scheduler != null && scheduler != TaskScheduler.Default)
{
- tc = new TaskSchedulerAwaitTaskContinuation(scheduler, continuationAction, flowExecutionContext, ref stackMark);
+ tc = new TaskSchedulerAwaitTaskContinuation(scheduler, continuationAction, flowExecutionContext);
}
}
}
@@ -2962,7 +2603,7 @@ namespace System.Threading.Tasks
// ExecutionContext, we need to capture it and wrap it in an AwaitTaskContinuation.
// Otherwise, we're targeting the default scheduler and we don't need to flow ExecutionContext, so
// we don't actually need a continuation object. We can just store/queue the action itself.
- tc = new AwaitTaskContinuation(continuationAction, flowExecutionContext: true, stackMark: ref stackMark);
+ tc = new AwaitTaskContinuation(continuationAction, flowExecutionContext: true);
}
// Now register the continuation, and if we couldn't register it because the task is already completing,
@@ -3190,7 +2831,7 @@ namespace System.Threading.Tasks
Task currentTask = Task.InternalCurrent;
etwLog.TaskWaitBegin(
(currentTask != null ? currentTask.m_taskScheduler.Id : TaskScheduler.Default.Id), (currentTask != null ? currentTask.Id : 0),
- this.Id, TplEtwProvider.TaskWaitBehavior.Synchronous, 0, System.Threading.Thread.GetDomainID());
+ this.Id, TplEtwProvider.TaskWaitBehavior.Synchronous, 0);
}
bool returnValue = IsCompleted;
@@ -3377,7 +3018,7 @@ namespace System.Threading.Tasks
}
}
- bool bRequiresAtomicStartTransition = (ts != null && ts.RequiresAtomicStartTransition) || ((Options & (TaskCreationOptions)InternalTaskOptions.SelfReplicating) != 0);
+ bool bRequiresAtomicStartTransition = ts != null && ts.RequiresAtomicStartTransition;
if (!bPopSucceeded && bCancelNonExecutingOnly && bRequiresAtomicStartTransition)
{
@@ -3715,11 +3356,9 @@ namespace System.Threading.Tasks
/// <exception cref="T:System.ArgumentNullException">
/// The <paramref name="continuationAction"/> argument is null.
/// </exception>
- [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var have to be marked non-inlineable
public Task ContinueWith(Action<Task> continuationAction)
{
- StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
- return ContinueWith(continuationAction, TaskScheduler.Current, default(CancellationToken), TaskContinuationOptions.None, ref stackMark);
+ return ContinueWith(continuationAction, TaskScheduler.Current, default(CancellationToken), TaskContinuationOptions.None);
}
/// <summary>
@@ -3742,11 +3381,9 @@ namespace System.Threading.Tasks
/// <exception cref="T:System.ObjectDisposedException">The provided <see cref="System.Threading.CancellationToken">CancellationToken</see>
/// has already been disposed.
/// </exception>
- [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var have to be marked non-inlineable
public Task ContinueWith(Action<Task> continuationAction, CancellationToken cancellationToken)
{
- StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
- return ContinueWith(continuationAction, TaskScheduler.Current, cancellationToken, TaskContinuationOptions.None, ref stackMark);
+ return ContinueWith(continuationAction, TaskScheduler.Current, cancellationToken, TaskContinuationOptions.None);
}
/// <summary>
@@ -3771,11 +3408,9 @@ namespace System.Threading.Tasks
/// <exception cref="T:System.ArgumentNullException">
/// The <paramref name="scheduler"/> argument is null.
/// </exception>
- [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var have to be marked non-inlineable
public Task ContinueWith(Action<Task> continuationAction, TaskScheduler scheduler)
{
- StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
- return ContinueWith(continuationAction, scheduler, default(CancellationToken), TaskContinuationOptions.None, ref stackMark);
+ return ContinueWith(continuationAction, scheduler, default(CancellationToken), TaskContinuationOptions.None);
}
/// <summary>
@@ -3806,11 +3441,9 @@ namespace System.Threading.Tasks
/// The <paramref name="continuationOptions"/> argument specifies an invalid value for <see
/// cref="T:System.Threading.Tasks.TaskContinuationOptions">TaskContinuationOptions</see>.
/// </exception>
- [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var have to be marked non-inlineable
public Task ContinueWith(Action<Task> continuationAction, TaskContinuationOptions continuationOptions)
{
- StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
- return ContinueWith(continuationAction, TaskScheduler.Current, default(CancellationToken), continuationOptions, ref stackMark);
+ return ContinueWith(continuationAction, TaskScheduler.Current, default(CancellationToken), continuationOptions);
}
/// <summary>
@@ -3851,17 +3484,15 @@ namespace System.Threading.Tasks
/// <exception cref="T:System.ObjectDisposedException">The provided <see cref="System.Threading.CancellationToken">CancellationToken</see>
/// has already been disposed.
/// </exception>
- [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var have to be marked non-inlineable
public Task ContinueWith(Action<Task> continuationAction, CancellationToken cancellationToken,
TaskContinuationOptions continuationOptions, TaskScheduler scheduler)
{
- StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
- return ContinueWith(continuationAction, scheduler, cancellationToken, continuationOptions, ref stackMark);
+ return ContinueWith(continuationAction, scheduler, cancellationToken, continuationOptions);
}
// Same as the above overload, just with a stack mark parameter.
private Task ContinueWith(Action<Task> continuationAction, TaskScheduler scheduler,
- CancellationToken cancellationToken, TaskContinuationOptions continuationOptions, ref StackCrawlMark stackMark)
+ CancellationToken cancellationToken, TaskContinuationOptions continuationOptions)
{
// Throw on continuation with null action
if (continuationAction == null)
@@ -3882,8 +3513,7 @@ namespace System.Threading.Tasks
Task continuationTask = new ContinuationTaskFromTask(
this, continuationAction, null,
- creationOptions, internalOptions,
- ref stackMark
+ creationOptions, internalOptions
);
// Register the continuation. If synchronous execution is requested, this may
@@ -3913,11 +3543,9 @@ namespace System.Threading.Tasks
/// <exception cref="T:System.ArgumentNullException">
/// The <paramref name="continuationAction"/> argument is null.
/// </exception>
- [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var have to be marked non-inlineable
public Task ContinueWith(Action<Task, Object> continuationAction, Object state)
{
- StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
- return ContinueWith(continuationAction, state, TaskScheduler.Current, default(CancellationToken), TaskContinuationOptions.None, ref stackMark);
+ return ContinueWith(continuationAction, state, TaskScheduler.Current, default(CancellationToken), TaskContinuationOptions.None);
}
/// <summary>
@@ -3941,11 +3569,9 @@ namespace System.Threading.Tasks
/// <exception cref="T:System.ObjectDisposedException">The provided <see cref="System.Threading.CancellationToken">CancellationToken</see>
/// has already been disposed.
/// </exception>
- [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var have to be marked non-inlineable
public Task ContinueWith(Action<Task, Object> continuationAction, Object state, CancellationToken cancellationToken)
{
- StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
- return ContinueWith(continuationAction, state, TaskScheduler.Current, cancellationToken, TaskContinuationOptions.None, ref stackMark);
+ return ContinueWith(continuationAction, state, TaskScheduler.Current, cancellationToken, TaskContinuationOptions.None);
}
/// <summary>
@@ -3971,11 +3597,9 @@ namespace System.Threading.Tasks
/// <exception cref="T:System.ArgumentNullException">
/// The <paramref name="scheduler"/> argument is null.
/// </exception>
- [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var have to be marked non-inlineable
public Task ContinueWith(Action<Task, Object> continuationAction, Object state, TaskScheduler scheduler)
{
- StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
- return ContinueWith(continuationAction, state, scheduler, default(CancellationToken), TaskContinuationOptions.None, ref stackMark);
+ return ContinueWith(continuationAction, state, scheduler, default(CancellationToken), TaskContinuationOptions.None);
}
/// <summary>
@@ -4007,11 +3631,9 @@ namespace System.Threading.Tasks
/// The <paramref name="continuationOptions"/> argument specifies an invalid value for <see
/// cref="T:System.Threading.Tasks.TaskContinuationOptions">TaskContinuationOptions</see>.
/// </exception>
- [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var have to be marked non-inlineable
public Task ContinueWith(Action<Task, Object> continuationAction, Object state, TaskContinuationOptions continuationOptions)
{
- StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
- return ContinueWith(continuationAction, state, TaskScheduler.Current, default(CancellationToken), continuationOptions, ref stackMark);
+ return ContinueWith(continuationAction, state, TaskScheduler.Current, default(CancellationToken), continuationOptions);
}
/// <summary>
@@ -4053,17 +3675,15 @@ namespace System.Threading.Tasks
/// <exception cref="T:System.ObjectDisposedException">The provided <see cref="System.Threading.CancellationToken">CancellationToken</see>
/// has already been disposed.
/// </exception>
- [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var have to be marked non-inlineable
public Task ContinueWith(Action<Task, Object> continuationAction, Object state, CancellationToken cancellationToken,
TaskContinuationOptions continuationOptions, TaskScheduler scheduler)
{
- StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
- return ContinueWith(continuationAction, state, scheduler, cancellationToken, continuationOptions, ref stackMark);
+ return ContinueWith(continuationAction, state, scheduler, cancellationToken, continuationOptions);
}
// Same as the above overload, just with a stack mark parameter.
private Task ContinueWith(Action<Task, Object> continuationAction, Object state, TaskScheduler scheduler,
- CancellationToken cancellationToken, TaskContinuationOptions continuationOptions, ref StackCrawlMark stackMark)
+ CancellationToken cancellationToken, TaskContinuationOptions continuationOptions)
{
// Throw on continuation with null action
if (continuationAction == null)
@@ -4084,8 +3704,7 @@ namespace System.Threading.Tasks
Task continuationTask = new ContinuationTaskFromTask(
this, continuationAction, state,
- creationOptions, internalOptions,
- ref stackMark
+ creationOptions, internalOptions
);
// Register the continuation. If synchronous execution is requested, this may
@@ -4118,12 +3737,10 @@ namespace System.Threading.Tasks
/// <exception cref="T:System.ArgumentNullException">
/// The <paramref name="continuationFunction"/> argument is null.
/// </exception>
- [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var have to be marked non-inlineable
public Task<TResult> ContinueWith<TResult>(Func<Task, TResult> continuationFunction)
{
- StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
return ContinueWith<TResult>(continuationFunction, TaskScheduler.Current, default(CancellationToken),
- TaskContinuationOptions.None, ref stackMark);
+ TaskContinuationOptions.None);
}
@@ -4150,11 +3767,9 @@ namespace System.Threading.Tasks
/// <exception cref="T:System.ObjectDisposedException">The provided <see cref="System.Threading.CancellationToken">CancellationToken</see>
/// has already been disposed.
/// </exception>
- [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var have to be marked non-inlineable
public Task<TResult> ContinueWith<TResult>(Func<Task, TResult> continuationFunction, CancellationToken cancellationToken)
{
- StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
- return ContinueWith<TResult>(continuationFunction, TaskScheduler.Current, cancellationToken, TaskContinuationOptions.None, ref stackMark);
+ return ContinueWith<TResult>(continuationFunction, TaskScheduler.Current, cancellationToken, TaskContinuationOptions.None);
}
/// <summary>
@@ -4182,11 +3797,9 @@ namespace System.Threading.Tasks
/// <exception cref="T:System.ArgumentNullException">
/// The <paramref name="scheduler"/> argument is null.
/// </exception>
- [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var have to be marked non-inlineable
public Task<TResult> ContinueWith<TResult>(Func<Task, TResult> continuationFunction, TaskScheduler scheduler)
{
- StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
- return ContinueWith<TResult>(continuationFunction, scheduler, default(CancellationToken), TaskContinuationOptions.None, ref stackMark);
+ return ContinueWith<TResult>(continuationFunction, scheduler, default(CancellationToken), TaskContinuationOptions.None);
}
/// <summary>
@@ -4220,11 +3833,9 @@ namespace System.Threading.Tasks
/// The <paramref name="continuationOptions"/> argument specifies an invalid value for <see
/// cref="T:System.Threading.Tasks.TaskContinuationOptions">TaskContinuationOptions</see>.
/// </exception>
- [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var have to be marked non-inlineable
public Task<TResult> ContinueWith<TResult>(Func<Task, TResult> continuationFunction, TaskContinuationOptions continuationOptions)
{
- StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
- return ContinueWith<TResult>(continuationFunction, TaskScheduler.Current, default(CancellationToken), continuationOptions, ref stackMark);
+ return ContinueWith<TResult>(continuationFunction, TaskScheduler.Current, default(CancellationToken), continuationOptions);
}
/// <summary>
@@ -4268,17 +3879,15 @@ namespace System.Threading.Tasks
/// <exception cref="T:System.ObjectDisposedException">The provided <see cref="System.Threading.CancellationToken">CancellationToken</see>
/// has already been disposed.
/// </exception>
- [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var have to be marked non-inlineable
public Task<TResult> ContinueWith<TResult>(Func<Task, TResult> continuationFunction, CancellationToken cancellationToken,
TaskContinuationOptions continuationOptions, TaskScheduler scheduler)
{
- StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
- return ContinueWith<TResult>(continuationFunction, scheduler, cancellationToken, continuationOptions, ref stackMark);
+ return ContinueWith<TResult>(continuationFunction, scheduler, cancellationToken, continuationOptions);
}
// Same as the above overload, just with a stack mark parameter.
private Task<TResult> ContinueWith<TResult>(Func<Task, TResult> continuationFunction, TaskScheduler scheduler,
- CancellationToken cancellationToken, TaskContinuationOptions continuationOptions, ref StackCrawlMark stackMark)
+ CancellationToken cancellationToken, TaskContinuationOptions continuationOptions)
{
// Throw on continuation with null function
if (continuationFunction == null)
@@ -4299,8 +3908,7 @@ namespace System.Threading.Tasks
Task<TResult> continuationTask = new ContinuationResultTaskFromTask<TResult>(
this, continuationFunction, null,
- creationOptions, internalOptions,
- ref stackMark
+ creationOptions, internalOptions
);
// Register the continuation. If synchronous execution is requested, this may
@@ -4333,12 +3941,10 @@ namespace System.Threading.Tasks
/// <exception cref="T:System.ArgumentNullException">
/// The <paramref name="continuationFunction"/> argument is null.
/// </exception>
- [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var have to be marked non-inlineable
public Task<TResult> ContinueWith<TResult>(Func<Task, Object, TResult> continuationFunction, Object state)
{
- StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
return ContinueWith<TResult>(continuationFunction, state, TaskScheduler.Current, default(CancellationToken),
- TaskContinuationOptions.None, ref stackMark);
+ TaskContinuationOptions.None);
}
@@ -4366,11 +3972,9 @@ namespace System.Threading.Tasks
/// <exception cref="T:System.ObjectDisposedException">The provided <see cref="System.Threading.CancellationToken">CancellationToken</see>
/// has already been disposed.
/// </exception>
- [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var have to be marked non-inlineable
public Task<TResult> ContinueWith<TResult>(Func<Task, Object, TResult> continuationFunction, Object state, CancellationToken cancellationToken)
{
- StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
- return ContinueWith<TResult>(continuationFunction, state, TaskScheduler.Current, cancellationToken, TaskContinuationOptions.None, ref stackMark);
+ return ContinueWith<TResult>(continuationFunction, state, TaskScheduler.Current, cancellationToken, TaskContinuationOptions.None);
}
/// <summary>
@@ -4399,11 +4003,9 @@ namespace System.Threading.Tasks
/// <exception cref="T:System.ArgumentNullException">
/// The <paramref name="scheduler"/> argument is null.
/// </exception>
- [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var have to be marked non-inlineable
public Task<TResult> ContinueWith<TResult>(Func<Task, Object, TResult> continuationFunction, Object state, TaskScheduler scheduler)
{
- StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
- return ContinueWith<TResult>(continuationFunction, state, scheduler, default(CancellationToken), TaskContinuationOptions.None, ref stackMark);
+ return ContinueWith<TResult>(continuationFunction, state, scheduler, default(CancellationToken), TaskContinuationOptions.None);
}
/// <summary>
@@ -4438,11 +4040,9 @@ namespace System.Threading.Tasks
/// The <paramref name="continuationOptions"/> argument specifies an invalid value for <see
/// cref="T:System.Threading.Tasks.TaskContinuationOptions">TaskContinuationOptions</see>.
/// </exception>
- [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var have to be marked non-inlineable
public Task<TResult> ContinueWith<TResult>(Func<Task, Object, TResult> continuationFunction, Object state, TaskContinuationOptions continuationOptions)
{
- StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
- return ContinueWith<TResult>(continuationFunction, state, TaskScheduler.Current, default(CancellationToken), continuationOptions, ref stackMark);
+ return ContinueWith<TResult>(continuationFunction, state, TaskScheduler.Current, default(CancellationToken), continuationOptions);
}
/// <summary>
@@ -4487,17 +4087,15 @@ namespace System.Threading.Tasks
/// <exception cref="T:System.ObjectDisposedException">The provided <see cref="System.Threading.CancellationToken">CancellationToken</see>
/// has already been disposed.
/// </exception>
- [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var have to be marked non-inlineable
public Task<TResult> ContinueWith<TResult>(Func<Task, Object, TResult> continuationFunction, Object state, CancellationToken cancellationToken,
TaskContinuationOptions continuationOptions, TaskScheduler scheduler)
{
- StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
- return ContinueWith<TResult>(continuationFunction, state, scheduler, cancellationToken, continuationOptions, ref stackMark);
+ return ContinueWith<TResult>(continuationFunction, state, scheduler, cancellationToken, continuationOptions);
}
// Same as the above overload, just with a stack mark parameter.
private Task<TResult> ContinueWith<TResult>(Func<Task, Object, TResult> continuationFunction, Object state, TaskScheduler scheduler,
- CancellationToken cancellationToken, TaskContinuationOptions continuationOptions, ref StackCrawlMark stackMark)
+ CancellationToken cancellationToken, TaskContinuationOptions continuationOptions)
{
// Throw on continuation with null function
if (continuationFunction == null)
@@ -4518,8 +4116,7 @@ namespace System.Threading.Tasks
Task<TResult> continuationTask = new ContinuationResultTaskFromTask<TResult>(
this, continuationFunction, state,
- creationOptions, internalOptions,
- ref stackMark
+ creationOptions, internalOptions
);
// Register the continuation. If synchronous execution is requested, this may
@@ -5207,49 +4804,6 @@ namespace System.Threading.Tasks
}
/// <summary>
- /// Internal WaitAll implementation which is meant to be used with small number of tasks,
- /// optimized for Parallel.Invoke and other structured primitives.
- /// </summary>
- internal static void FastWaitAll(Task[] tasks)
- {
- Contract.Requires(tasks != null);
-
- List<Exception> exceptions = null;
-
- // Collects incomplete tasks in "waitedOnTaskList" and their cooperative events in "cooperativeEventList"
- for (int i = tasks.Length - 1; i >= 0; i--)
- {
- if (!tasks[i].IsCompleted)
- {
- // Just attempting to inline here... result doesn't matter.
- // We'll do a second pass to do actual wait on each task, and to aggregate their exceptions.
- // If the task is inlined here, it will register as IsCompleted in the second pass
- // and will just give us the exception.
- tasks[i].WrappedTryRunInline();
- }
- }
-
- // Wait on the tasks.
- for (int i = tasks.Length - 1; i >= 0; i--)
- {
- var task = tasks[i];
- task.SpinThenBlockingWait(Timeout.Infinite, default(CancellationToken));
- AddExceptionsForCompletedTask(ref exceptions, task);
-
- // Note that unlike other wait code paths, we do not check
- // task.NotifyDebuggerOfWaitCompletionIfNecessary() here, because this method is currently
- // only used from contexts where the tasks couldn't have that bit set, namely
- // Parallel.Invoke. If that ever changes, such checks should be added here.
- }
-
- // If one or more threw exceptions, aggregate them.
- if (exceptions != null)
- {
- ThrowHelper.ThrowAggregateException(exceptions);
- }
- }
-
- /// <summary>
/// This internal function is only meant to be called by WaitAll()
/// If the completed task is canceled or it has other exceptions, here we will add those
/// into the passed in exception list (which will be lazily initialized here).
@@ -5582,12 +5136,10 @@ namespace System.Threading.Tasks
/// <exception cref="T:System.ArgumentNullException">
/// The <paramref name="action"/> parameter was null.
/// </exception>
- [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var have to be marked non-inlineable
public static Task Run(Action action)
{
- StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
return Task.InternalStartNew(null, action, null, default(CancellationToken), TaskScheduler.Default,
- TaskCreationOptions.DenyChildAttach, InternalTaskOptions.None, ref stackMark);
+ TaskCreationOptions.DenyChildAttach, InternalTaskOptions.None);
}
/// <summary>
@@ -5602,12 +5154,10 @@ namespace System.Threading.Tasks
/// <exception cref="T:System.ObjectDisposedException">
/// The <see cref="T:System.CancellationTokenSource"/> associated with <paramref name="cancellationToken"/> was disposed.
/// </exception>
- [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var have to be marked non-inlineable
public static Task Run(Action action, CancellationToken cancellationToken)
{
- StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
return Task.InternalStartNew(null, action, null, cancellationToken, TaskScheduler.Default,
- TaskCreationOptions.DenyChildAttach, InternalTaskOptions.None, ref stackMark);
+ TaskCreationOptions.DenyChildAttach, InternalTaskOptions.None);
}
/// <summary>
@@ -5618,12 +5168,10 @@ namespace System.Threading.Tasks
/// <exception cref="T:System.ArgumentNullException">
/// The <paramref name="function"/> parameter was null.
/// </exception>
- [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var have to be marked non-inlineable
public static Task<TResult> Run<TResult>(Func<TResult> function)
{
- StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
return Task<TResult>.StartNew(null, function, default(CancellationToken),
- TaskCreationOptions.DenyChildAttach, InternalTaskOptions.None, TaskScheduler.Default, ref stackMark);
+ TaskCreationOptions.DenyChildAttach, InternalTaskOptions.None, TaskScheduler.Default);
}
/// <summary>
@@ -5638,12 +5186,10 @@ namespace System.Threading.Tasks
/// <exception cref="T:System.ObjectDisposedException">
/// The <see cref="T:System.CancellationTokenSource"/> associated with <paramref name="cancellationToken"/> was disposed.
/// </exception>
- [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var have to be marked non-inlineable
public static Task<TResult> Run<TResult>(Func<TResult> function, CancellationToken cancellationToken)
{
- StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
return Task<TResult>.StartNew(null, function, cancellationToken,
- TaskCreationOptions.DenyChildAttach, InternalTaskOptions.None, TaskScheduler.Default, ref stackMark);
+ TaskCreationOptions.DenyChildAttach, InternalTaskOptions.None, TaskScheduler.Default);
}
/// <summary>
@@ -6693,102 +6239,6 @@ namespace System.Threading.Tasks
public TaskStatus Status { get { return m_task.Status; } }
}
- // Special purpose derivation of Task that supports limited replication through
- // overriding the ShouldReplicate() method. This is used by the Parallel.For/ForEach
- // methods.
- internal class ParallelForReplicatingTask : Task
- {
- // Member variables
- private int m_replicationDownCount; // downcounter to control replication
-
- //
- // Constructors
- //
-
- [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var have to be marked non-inlineable
- internal ParallelForReplicatingTask(
- ParallelOptions parallelOptions, Action action, TaskCreationOptions creationOptions, InternalTaskOptions internalOptions)
- : base(action, null, Task.InternalCurrent, default(CancellationToken), creationOptions, internalOptions | InternalTaskOptions.SelfReplicating, null)
- {
- // Compute the down count based on scheduler/DOP info in parallelOptions.
- m_replicationDownCount = parallelOptions.EffectiveMaxConcurrencyLevel;
-
- StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
- PossiblyCaptureContext(ref stackMark);
- }
-
-
- // Controls degree of replication. If downcounter is initialized to -1, then
- // replication will be allowed to "run wild". Otherwise, this method decrements
- // the downcounter each time it is called, calling false when it is called with
- // a zero downcounter. This method returning false effectively ends the replication
- // of the associated ParallelForReplicatingTask.
- internal override bool ShouldReplicate()
- {
- if (m_replicationDownCount == -1) return true; // "run wild"
-
- if (m_replicationDownCount > 0) // Decrement and return true if not called with 0 downcount
- {
- m_replicationDownCount--;
- return true;
- }
-
- return false; // We're done replicating
- }
-
- internal override Task CreateReplicaTask(Action<object> taskReplicaDelegate, Object stateObject, Task parentTask, TaskScheduler taskScheduler,
- TaskCreationOptions creationOptionsForReplica, InternalTaskOptions internalOptionsForReplica)
- {
- return new ParallelForReplicaTask(taskReplicaDelegate, stateObject, parentTask, taskScheduler,
- creationOptionsForReplica, internalOptionsForReplica);
- }
-
-
- }
-
- internal class ParallelForReplicaTask : Task
- {
- internal object m_stateForNextReplica; // some replicas may quit prematurely, in which case they will use this variable
- // to save state they want to be picked up by the next replica queued to the same thread
-
- internal object m_stateFromPreviousReplica; // some replicas may quit prematurely, in which case they will use this variable
- // to save state they want to be picked up by the next replica queued to the same thread
-
- internal Task m_handedOverChildReplica; // some replicas may quit prematurely, in which case they will use this variable
- // to hand over the child replica they had queued to the next task that will replace them
-
- internal ParallelForReplicaTask(Action<object> taskReplicaDelegate, Object stateObject, Task parentTask, TaskScheduler taskScheduler,
- TaskCreationOptions creationOptionsForReplica, InternalTaskOptions internalOptionsForReplica) :
- base(taskReplicaDelegate, stateObject, parentTask, default(CancellationToken), creationOptionsForReplica, internalOptionsForReplica, taskScheduler)
- {
- }
-
- // Allows internal deriving classes to support replicas that exit prematurely and want to pass on state to the next replica
- internal override Object SavedStateForNextReplica
- {
- get { return m_stateForNextReplica; }
-
- set { m_stateForNextReplica = value; }
- }
-
- // Allows internal deriving classes to support replicas that exit prematurely and want to pass on state to the next replica
- internal override Object SavedStateFromPreviousReplica
- {
- get { return m_stateFromPreviousReplica; }
-
- set { m_stateFromPreviousReplica = value; }
- }
-
- // Allows internal deriving classes to support replicas that exit prematurely and want to hand over the child replica that they
- // had queued, so that the replacement replica can work with that child task instead of queuing up yet another one
- internal override Task HandedOverChildReplica
- {
- get { return m_handedOverChildReplica; }
-
- set { m_handedOverChildReplica = value; }
- }
- }
-
/// <summary>
/// Specifies flags that control optional behavior for the creation and execution of tasks.
/// </summary>
@@ -6856,10 +6306,8 @@ namespace System.Threading.Tasks
/// <summary>Used to filter out internal vs. public task creation options.</summary>
InternalOptionsMask = 0x0000FF00,
- ChildReplica = 0x0100,
ContinuationTask = 0x0200,
PromiseTask = 0x0400,
- SelfReplicating = 0x0800,
/// <summary>
/// Store the presence of TaskContinuationOptions.LazyCancellation, since it does not directly
diff --git a/src/mscorlib/src/System/Threading/Tasks/TaskCompletionSource.cs b/src/mscorlib/src/System/Threading/Tasks/TaskCompletionSource.cs
index 320f704f09..bf9f9cbb2c 100644
--- a/src/mscorlib/src/System/Threading/Tasks/TaskCompletionSource.cs
+++ b/src/mscorlib/src/System/Threading/Tasks/TaskCompletionSource.cs
@@ -17,7 +17,6 @@ using System.Diagnostics.Contracts;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using System.Runtime.ExceptionServices;
-using System.Security.Permissions;
using System.Threading;
// Disable the "reference to volatile field not treated as volatile" error.
@@ -203,22 +202,6 @@ namespace System.Threading.Tasks
return rval;
}
- /// <summary>Attempts to transition the underlying task to the faulted state.</summary>
- /// <param name="exceptions">The collection of exception dispatch infos to bind to this task.</param>
- /// <returns>True if the operation was successful; otherwise, false.</returns>
- /// <remarks>Unlike the public methods, this method doesn't currently validate that its arguments are correct.</remarks>
- internal bool TrySetException(IEnumerable<ExceptionDispatchInfo> exceptions)
- {
- Debug.Assert(exceptions != null);
-#if DEBUG
- foreach(var edi in exceptions) Debug.Assert(edi != null, "Contents must be non-null");
-#endif
-
- bool rval = m_task.TrySetException(exceptions);
- if (!rval && !m_task.IsCompleted) SpinUntilCompleted();
- return rval;
- }
-
/// <summary>
/// Transitions the underlying
/// <see cref="T:System.Threading.Tasks.Task{TResult}"/> into the
diff --git a/src/mscorlib/src/System/Threading/Tasks/TaskContinuation.cs b/src/mscorlib/src/System/Threading/Tasks/TaskContinuation.cs
index 70b9418dbf..3c6ccd8dd4 100644
--- a/src/mscorlib/src/System/Threading/Tasks/TaskContinuation.cs
+++ b/src/mscorlib/src/System/Threading/Tasks/TaskContinuation.cs
@@ -29,13 +29,12 @@ namespace System.Threading.Tasks
private Task m_antecedent;
public ContinuationTaskFromTask(
- Task antecedent, Delegate action, object state, TaskCreationOptions creationOptions, InternalTaskOptions internalOptions, ref StackCrawlMark stackMark) :
+ Task antecedent, Delegate action, object state, TaskCreationOptions creationOptions, InternalTaskOptions internalOptions) :
base(action, state, Task.InternalCurrentIfAttached(creationOptions), default(CancellationToken), creationOptions, internalOptions, null)
{
Contract.Requires(action is Action<Task> || action is Action<Task, object>,
"Invalid delegate type in ContinuationTaskFromTask");
m_antecedent = antecedent;
- PossiblyCaptureContext(ref stackMark);
}
/// <summary>
@@ -77,13 +76,12 @@ namespace System.Threading.Tasks
private Task m_antecedent;
public ContinuationResultTaskFromTask(
- Task antecedent, Delegate function, object state, TaskCreationOptions creationOptions, InternalTaskOptions internalOptions, ref StackCrawlMark stackMark) :
+ Task antecedent, Delegate function, object state, TaskCreationOptions creationOptions, InternalTaskOptions internalOptions) :
base(function, state, Task.InternalCurrentIfAttached(creationOptions), default(CancellationToken), creationOptions, internalOptions, null)
{
Contract.Requires(function is Func<Task, TResult> || function is Func<Task, object, TResult>,
"Invalid delegate type in ContinuationResultTaskFromTask");
m_antecedent = antecedent;
- PossiblyCaptureContext(ref stackMark);
}
/// <summary>
@@ -125,13 +123,12 @@ namespace System.Threading.Tasks
private Task<TAntecedentResult> m_antecedent;
public ContinuationTaskFromResultTask(
- Task<TAntecedentResult> antecedent, Delegate action, object state, TaskCreationOptions creationOptions, InternalTaskOptions internalOptions, ref StackCrawlMark stackMark) :
+ Task<TAntecedentResult> antecedent, Delegate action, object state, TaskCreationOptions creationOptions, InternalTaskOptions internalOptions) :
base(action, state, Task.InternalCurrentIfAttached(creationOptions), default(CancellationToken), creationOptions, internalOptions, null)
{
Contract.Requires(action is Action<Task<TAntecedentResult>> || action is Action<Task<TAntecedentResult>, object>,
"Invalid delegate type in ContinuationTaskFromResultTask");
m_antecedent = antecedent;
- PossiblyCaptureContext(ref stackMark);
}
/// <summary>
@@ -173,13 +170,12 @@ namespace System.Threading.Tasks
private Task<TAntecedentResult> m_antecedent;
public ContinuationResultTaskFromResultTask(
- Task<TAntecedentResult> antecedent, Delegate function, object state, TaskCreationOptions creationOptions, InternalTaskOptions internalOptions, ref StackCrawlMark stackMark) :
+ Task<TAntecedentResult> antecedent, Delegate function, object state, TaskCreationOptions creationOptions, InternalTaskOptions internalOptions) :
base(function, state, Task.InternalCurrentIfAttached(creationOptions), default(CancellationToken), creationOptions, internalOptions, null)
{
Contract.Requires(function is Func<Task<TAntecedentResult>, TResult> || function is Func<Task<TAntecedentResult>, object, TResult>,
"Invalid delegate type in ContinuationResultTaskFromResultTask");
m_antecedent = antecedent;
- PossiblyCaptureContext(ref stackMark);
}
/// <summary>
@@ -392,10 +388,9 @@ namespace System.Threading.Tasks
/// <param name="context">The synchronization context with which to invoke the action. Must not be null.</param>
/// <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>
internal SynchronizationContextAwaitTaskContinuation(
- SynchronizationContext context, Action action, bool flowExecutionContext, ref StackCrawlMark stackMark) :
- base(action, flowExecutionContext, ref stackMark)
+ SynchronizationContext context, Action action, bool flowExecutionContext) :
+ base(action, flowExecutionContext)
{
Debug.Assert(context != null);
m_syncContext = context;
@@ -479,10 +474,9 @@ namespace System.Threading.Tasks
/// <param name="scheduler">The task scheduler with which to invoke the action. Must not be null.</param>
/// <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>
internal TaskSchedulerAwaitTaskContinuation(
- TaskScheduler scheduler, Action action, bool flowExecutionContext, ref StackCrawlMark stackMark) :
- base(action, flowExecutionContext, ref stackMark)
+ TaskScheduler scheduler, Action action, bool flowExecutionContext) :
+ base(action, flowExecutionContext)
{
Debug.Assert(scheduler != null);
m_scheduler = scheduler;
@@ -543,29 +537,13 @@ 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>
- /// <param name="stackMark">The captured stack mark with which to construct an ExecutionContext.</param>
- internal AwaitTaskContinuation(Action action, bool flowExecutionContext, ref StackCrawlMark stackMark)
- {
- Contract.Requires(action != null);
- m_action = action;
- if (flowExecutionContext)
- {
- m_capturedContext = ExecutionContext.Capture(
- ref stackMark,
- ExecutionContext.CaptureOptions.IgnoreSyncCtx | ExecutionContext.CaptureOptions.OptimizeDefaultCase);
- }
- }
-
- /// <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>
internal AwaitTaskContinuation(Action action, bool flowExecutionContext)
{
Contract.Requires(action != null);
m_action = action;
if (flowExecutionContext)
{
- m_capturedContext = ExecutionContext.FastCapture();
+ m_capturedContext = ExecutionContext.Capture();
}
}
@@ -670,11 +648,7 @@ namespace System.Threading.Tasks
// If there is an execution context, get the cached delegate and run the action under the context.
else
{
- try
- {
- ExecutionContext.Run(m_capturedContext, GetInvokeActionCallback(), m_action, true);
- }
- finally { m_capturedContext.Dispose(); }
+ ExecutionContext.Run(m_capturedContext, GetInvokeActionCallback(), m_action);
}
}
finally
@@ -689,8 +663,7 @@ namespace System.Threading.Tasks
void IThreadPoolWorkItem.ExecuteWorkItem()
{
// inline the fast path
- if (m_capturedContext == null && !TplEtwProvider.Log.IsEnabled()
- )
+ if (m_capturedContext == null && !TplEtwProvider.Log.IsEnabled())
{
m_action();
}
@@ -739,7 +712,7 @@ namespace System.Threading.Tasks
// If there's no captured context, just run the callback directly.
if (m_capturedContext == null) callback(state);
// Otherwise, use the captured context to do so.
- else ExecutionContext.Run(m_capturedContext, callback, state, true);
+ else ExecutionContext.Run(m_capturedContext, callback, state);
}
catch (Exception exc) // we explicitly do not request handling of dangerous exceptions like AVs
{
@@ -749,9 +722,6 @@ namespace System.Threading.Tasks
{
// Restore the current task information
if (prevCurrentTask != null) currentTask = prevCurrentTask;
-
- // Clean up after the execution context, which is only usable once.
- if (m_capturedContext != null) m_capturedContext.Dispose();
}
}
diff --git a/src/mscorlib/src/System/Threading/Tasks/TaskExceptionHolder.cs b/src/mscorlib/src/System/Threading/Tasks/TaskExceptionHolder.cs
index 45817dab23..ee1112a93f 100644
--- a/src/mscorlib/src/System/Threading/Tasks/TaskExceptionHolder.cs
+++ b/src/mscorlib/src/System/Threading/Tasks/TaskExceptionHolder.cs
@@ -149,23 +149,6 @@ namespace System.Threading.Tasks
/// Add an exception to the holder. This will ensure the holder is
/// in the proper state (handled/unhandled) depending on the list's contents.
/// </summary>
- /// <param name="exceptionObject">
- /// An exception object (either an Exception, an ExceptionDispatchInfo,
- /// an IEnumerable{Exception}, or an IEnumerable{ExceptionDispatchInfo})
- /// to add to the list.
- /// </param>
- /// <remarks>
- /// Must be called under lock.
- /// </remarks>
- internal void Add(object exceptionObject)
- {
- Add(exceptionObject, representsCancellation: false);
- }
-
- /// <summary>
- /// Add an exception to the holder. This will ensure the holder is
- /// in the proper state (handled/unhandled) depending on the list's contents.
- /// </summary>
/// <param name="representsCancellation">
/// Whether the exception represents a cancellation request (true) or a fault (false).
/// </param>
diff --git a/src/mscorlib/src/System/Threading/Tasks/TaskFactory.cs b/src/mscorlib/src/System/Threading/Tasks/TaskFactory.cs
index aa4c2df74b..89ba2988ca 100644
--- a/src/mscorlib/src/System/Threading/Tasks/TaskFactory.cs
+++ b/src/mscorlib/src/System/Threading/Tasks/TaskFactory.cs
@@ -15,7 +15,6 @@
using System;
using System.Collections.Generic;
using System.Security;
-using System.Security.Permissions;
using System.Runtime.CompilerServices;
using System.Threading;
using System.Diagnostics;
@@ -225,7 +224,7 @@ namespace System.Threading.Tasks
TaskCreationOptions.PreferFairness |
TaskCreationOptions.RunContinuationsAsynchronously)) != 0)
{
- throw new ArgumentOutOfRangeException(nameof(creationOptions));
+ ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.creationOptions);
}
Contract.EndContractBlock();
}
@@ -293,13 +292,11 @@ namespace System.Threading.Tasks
/// unless creation and scheduling must be separated, StartNew is the recommended
/// approach for both simplicity and performance.
/// </remarks>
- [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var have to be marked non-inlineable
public Task StartNew(Action action)
{
- StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
Task currTask = Task.InternalCurrent;
return Task.InternalStartNew(currTask, action, null, m_defaultCancellationToken, GetDefaultScheduler(currTask),
- m_defaultCreationOptions, InternalTaskOptions.None, ref stackMark);
+ m_defaultCreationOptions, InternalTaskOptions.None);
}
/// <summary>
@@ -320,13 +317,11 @@ namespace System.Threading.Tasks
/// unless creation and scheduling must be separated, StartNew is the recommended
/// approach for both simplicity and performance.
/// </remarks>
- [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var have to be marked non-inlineable
public Task StartNew(Action action, CancellationToken cancellationToken)
{
- StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
Task currTask = Task.InternalCurrent;
return Task.InternalStartNew(currTask, action, null, cancellationToken, GetDefaultScheduler(currTask),
- m_defaultCreationOptions, InternalTaskOptions.None, ref stackMark);
+ m_defaultCreationOptions, InternalTaskOptions.None);
}
/// <summary>
@@ -350,13 +345,11 @@ namespace System.Threading.Tasks
/// However, unless creation and scheduling must be separated, StartNew is the recommended approach
/// for both simplicity and performance.
/// </remarks>
- [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var have to be marked non-inlineable
public Task StartNew(Action action, TaskCreationOptions creationOptions)
{
- StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
Task currTask = Task.InternalCurrent;
return Task.InternalStartNew(currTask, action, null, m_defaultCancellationToken, GetDefaultScheduler(currTask), creationOptions,
- InternalTaskOptions.None, ref stackMark);
+ InternalTaskOptions.None);
}
/// <summary>
@@ -391,22 +384,11 @@ namespace System.Threading.Tasks
/// However, unless creation and scheduling must be separated, StartNew is the recommended approach
/// for both simplicity and performance.
/// </remarks>
- [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var have to be marked non-inlineable
public Task StartNew(Action action, CancellationToken cancellationToken, TaskCreationOptions creationOptions, TaskScheduler scheduler)
{
- StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
return Task.InternalStartNew(
Task.InternalCurrentIfAttached(creationOptions), action, null, cancellationToken, scheduler, creationOptions,
- InternalTaskOptions.None, ref stackMark);
- }
-
- // Internal version includes InternalTaskOptions for Parallel.Invoke() support.
- [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var have to be marked non-inlineable
- internal Task StartNew(Action action, CancellationToken cancellationToken, TaskCreationOptions creationOptions, InternalTaskOptions internalOptions, TaskScheduler scheduler)
- {
- StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
- return Task.InternalStartNew(
- Task.InternalCurrentIfAttached(creationOptions), action, null, cancellationToken, scheduler, creationOptions, internalOptions, ref stackMark);
+ InternalTaskOptions.None);
}
@@ -427,13 +409,11 @@ namespace System.Threading.Tasks
/// However, unless creation and scheduling must be separated, StartNew is the recommended approach
/// for both simplicity and performance.
/// </remarks>
- [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var have to be marked non-inlineable
public Task StartNew(Action<Object> action, Object state)
{
- StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
Task currTask = Task.InternalCurrent;
return Task.InternalStartNew(currTask, action, state, m_defaultCancellationToken, GetDefaultScheduler(currTask),
- m_defaultCreationOptions, InternalTaskOptions.None, ref stackMark);
+ m_defaultCreationOptions, InternalTaskOptions.None);
}
@@ -458,13 +438,11 @@ namespace System.Threading.Tasks
/// However, unless creation and scheduling must be separated, StartNew is the recommended approach
/// for both simplicity and performance.
/// </remarks>
- [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var have to be marked non-inlineable
public Task StartNew(Action<Object> action, Object state, CancellationToken cancellationToken)
{
- StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
Task currTask = Task.InternalCurrent;
return Task.InternalStartNew(currTask, action, state, cancellationToken, GetDefaultScheduler(currTask),
- m_defaultCreationOptions, InternalTaskOptions.None, ref stackMark);
+ m_defaultCreationOptions, InternalTaskOptions.None);
}
/// <summary>
@@ -490,13 +468,11 @@ namespace System.Threading.Tasks
/// However, unless creation and scheduling must be separated, StartNew is the recommended approach
/// for both simplicity and performance.
/// </remarks>
- [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var have to be marked non-inlineable
public Task StartNew(Action<Object> action, Object state, TaskCreationOptions creationOptions)
{
- StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
Task currTask = Task.InternalCurrent;
return Task.InternalStartNew(currTask, action, state, m_defaultCancellationToken, GetDefaultScheduler(currTask),
- creationOptions, InternalTaskOptions.None, ref stackMark);
+ creationOptions, InternalTaskOptions.None);
}
/// <summary>
@@ -533,14 +509,12 @@ namespace System.Threading.Tasks
/// However, unless creation and scheduling must be separated, StartNew is the recommended approach
/// for both simplicity and performance.
/// </remarks>
- [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var have to be marked non-inlineable
public Task StartNew(Action<Object> action, Object state, CancellationToken cancellationToken,
TaskCreationOptions creationOptions, TaskScheduler scheduler)
{
- StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
return Task.InternalStartNew(
Task.InternalCurrentIfAttached(creationOptions), action, state, cancellationToken, scheduler,
- creationOptions, InternalTaskOptions.None, ref stackMark);
+ creationOptions, InternalTaskOptions.None);
}
/// <summary>
@@ -562,13 +536,11 @@ namespace System.Threading.Tasks
/// However, unless creation and scheduling must be separated, StartNew is the recommended approach
/// for both simplicity and performance.
/// </remarks>
- [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var have to be marked non-inlineable
public Task<TResult> StartNew<TResult>(Func<TResult> function)
{
- StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
Task currTask = Task.InternalCurrent;
return Task<TResult>.StartNew(currTask, function, m_defaultCancellationToken,
- m_defaultCreationOptions, InternalTaskOptions.None, GetDefaultScheduler(currTask), ref stackMark);
+ m_defaultCreationOptions, InternalTaskOptions.None, GetDefaultScheduler(currTask));
}
@@ -595,13 +567,11 @@ namespace System.Threading.Tasks
/// However, unless creation and scheduling must be separated, StartNew is the recommended approach
/// for both simplicity and performance.
/// </remarks>
- [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var have to be marked non-inlineable
public Task<TResult> StartNew<TResult>(Func<TResult> function, CancellationToken cancellationToken)
{
- StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
Task currTask = Task.InternalCurrent;
return Task<TResult>.StartNew(currTask, function, cancellationToken,
- m_defaultCreationOptions, InternalTaskOptions.None, GetDefaultScheduler(currTask), ref stackMark);
+ m_defaultCreationOptions, InternalTaskOptions.None, GetDefaultScheduler(currTask));
}
/// <summary>
@@ -629,13 +599,11 @@ namespace System.Threading.Tasks
/// However, unless creation and scheduling must be separated, StartNew is the recommended approach
/// for both simplicity and performance.
/// </remarks>
- [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var have to be marked non-inlineable
public Task<TResult> StartNew<TResult>(Func<TResult> function, TaskCreationOptions creationOptions)
{
- StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
Task currTask = Task.InternalCurrent;
return Task<TResult>.StartNew(currTask, function, m_defaultCancellationToken,
- creationOptions, InternalTaskOptions.None, GetDefaultScheduler(currTask), ref stackMark);
+ creationOptions, InternalTaskOptions.None, GetDefaultScheduler(currTask));
}
/// <summary>
@@ -674,13 +642,11 @@ namespace System.Threading.Tasks
/// However, unless creation and scheduling must be separated, StartNew is the recommended approach
/// for both simplicity and performance.
/// </remarks>
- [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var have to be marked non-inlineable
public Task<TResult> StartNew<TResult>(Func<TResult> function, CancellationToken cancellationToken, TaskCreationOptions creationOptions, TaskScheduler scheduler)
{
- StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
return Task<TResult>.StartNew(
Task.InternalCurrentIfAttached(creationOptions), function, cancellationToken,
- creationOptions, InternalTaskOptions.None, scheduler, ref stackMark);
+ creationOptions, InternalTaskOptions.None, scheduler);
}
/// <summary>
@@ -704,13 +670,11 @@ namespace System.Threading.Tasks
/// However, unless creation and scheduling must be separated, StartNew is the recommended approach
/// for both simplicity and performance.
/// </remarks>
- [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var have to be marked non-inlineable
public Task<TResult> StartNew<TResult>(Func<Object, TResult> function, Object state)
{
- StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
Task currTask = Task.InternalCurrent;
return Task<TResult>.StartNew(currTask, function, state, m_defaultCancellationToken,
- m_defaultCreationOptions, InternalTaskOptions.None, GetDefaultScheduler(currTask), ref stackMark);
+ m_defaultCreationOptions, InternalTaskOptions.None, GetDefaultScheduler(currTask));
}
@@ -739,13 +703,11 @@ namespace System.Threading.Tasks
/// However, unless creation and scheduling must be separated, StartNew is the recommended approach
/// for both simplicity and performance.
/// </remarks>
- [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var have to be marked non-inlineable
public Task<TResult> StartNew<TResult>(Func<Object, TResult> function, Object state, CancellationToken cancellationToken)
{
- StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
Task currTask = Task.InternalCurrent;
return Task<TResult>.StartNew(currTask, function, state, cancellationToken,
- m_defaultCreationOptions, InternalTaskOptions.None, GetDefaultScheduler(currTask), ref stackMark);
+ m_defaultCreationOptions, InternalTaskOptions.None, GetDefaultScheduler(currTask));
}
/// <summary>
@@ -775,13 +737,11 @@ namespace System.Threading.Tasks
/// However, unless creation and scheduling must be separated, StartNew is the recommended approach
/// for both simplicity and performance.
/// </remarks>
- [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var have to be marked non-inlineable
public Task<TResult> StartNew<TResult>(Func<Object, TResult> function, Object state, TaskCreationOptions creationOptions)
{
- StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
Task currTask = Task.InternalCurrent;
return Task<TResult>.StartNew(currTask, function, state, m_defaultCancellationToken,
- creationOptions, InternalTaskOptions.None, GetDefaultScheduler(currTask), ref stackMark);
+ creationOptions, InternalTaskOptions.None, GetDefaultScheduler(currTask));
}
/// <summary>
@@ -822,14 +782,12 @@ namespace System.Threading.Tasks
/// However, unless creation and scheduling must be separated, StartNew is the recommended approach
/// for both simplicity and performance.
/// </remarks>
- [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var have to be marked non-inlineable
public Task<TResult> StartNew<TResult>(Func<Object, TResult> function, Object state, CancellationToken cancellationToken,
TaskCreationOptions creationOptions, TaskScheduler scheduler)
{
- StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
return Task<TResult>.StartNew(
Task.InternalCurrentIfAttached(creationOptions), function, state, cancellationToken,
- creationOptions, InternalTaskOptions.None, scheduler, ref stackMark);
+ creationOptions, InternalTaskOptions.None, scheduler);
}
//
@@ -850,13 +808,11 @@ namespace System.Threading.Tasks
/// <paramref name="endMethod"/> argument is null.</exception>
/// <returns>A <see cref="T:System.Threading.Tasks.Task">Task</see> that represents the asynchronous
/// operation.</returns>
- [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var have to be marked non-inlineable
public Task FromAsync(
IAsyncResult asyncResult,
Action<IAsyncResult> endMethod)
{
- StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
- return FromAsync(asyncResult, endMethod, m_defaultCreationOptions, DefaultScheduler, ref stackMark);
+ return FromAsync(asyncResult, endMethod, m_defaultCreationOptions, DefaultScheduler);
}
/// <summary>
@@ -878,14 +834,12 @@ namespace System.Threading.Tasks
/// value.</exception>
/// <returns>A <see cref="T:System.Threading.Tasks.Task">Task</see> that represents the asynchronous
/// operation.</returns>
- [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var have to be marked non-inlineable
public Task FromAsync(
IAsyncResult asyncResult,
Action<IAsyncResult> endMethod,
TaskCreationOptions creationOptions)
{
- StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
- return FromAsync(asyncResult, endMethod, creationOptions, DefaultScheduler, ref stackMark);
+ return FromAsync(asyncResult, endMethod, creationOptions, DefaultScheduler);
}
/// <summary>
@@ -911,26 +865,13 @@ namespace System.Threading.Tasks
/// value.</exception>
/// <returns>A <see cref="T:System.Threading.Tasks.Task">Task</see> that represents the asynchronous
/// operation.</returns>
- [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var have to be marked non-inlineable
public Task FromAsync(
IAsyncResult asyncResult,
Action<IAsyncResult> endMethod,
TaskCreationOptions creationOptions,
TaskScheduler scheduler)
{
- StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
- return FromAsync(asyncResult, endMethod, creationOptions, scheduler, ref stackMark);
- }
-
- // private version that supports StackCrawlMark.
- private Task FromAsync(
- IAsyncResult asyncResult,
- Action<IAsyncResult> endMethod,
- TaskCreationOptions creationOptions,
- TaskScheduler scheduler,
- ref StackCrawlMark stackMark)
- {
- return TaskFactory<VoidTaskResult>.FromAsyncImpl(asyncResult, null, endMethod, creationOptions, scheduler, ref stackMark);
+ return TaskFactory<VoidTaskResult>.FromAsyncImpl(asyncResult, null, endMethod, creationOptions, scheduler);
}
/// <summary>
@@ -1228,12 +1169,10 @@ namespace System.Threading.Tasks
/// <paramref name="endMethod"/> argument is null.</exception>
/// <returns>A <see cref="T:System.Threading.Tasks.Task{TResult}">Task</see> that represents the
/// asynchronous operation.</returns>
- [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var have to be marked non-inlineable
public Task<TResult> FromAsync<TResult>(
IAsyncResult asyncResult, Func<IAsyncResult, TResult> endMethod)
{
- StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
- return TaskFactory<TResult>.FromAsyncImpl(asyncResult, endMethod, null, m_defaultCreationOptions, DefaultScheduler, ref stackMark);
+ return TaskFactory<TResult>.FromAsyncImpl(asyncResult, endMethod, null, m_defaultCreationOptions, DefaultScheduler);
}
/// <summary>
@@ -1258,12 +1197,10 @@ namespace System.Threading.Tasks
/// value.</exception>
/// <returns>A <see cref="T:System.Threading.Tasks.Task{TResult}">Task</see> that represents the
/// asynchronous operation.</returns>
- [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var have to be marked non-inlineable
public Task<TResult> FromAsync<TResult>(
IAsyncResult asyncResult, Func<IAsyncResult, TResult> endMethod, TaskCreationOptions creationOptions)
{
- StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
- return TaskFactory<TResult>.FromAsyncImpl(asyncResult, endMethod, null, creationOptions, DefaultScheduler, ref stackMark);
+ return TaskFactory<TResult>.FromAsyncImpl(asyncResult, endMethod, null, creationOptions, DefaultScheduler);
}
/// <summary>
@@ -1292,12 +1229,10 @@ namespace System.Threading.Tasks
/// value.</exception>
/// <returns>A <see cref="T:System.Threading.Tasks.Task{TResult}">Task</see> that represents the
/// asynchronous operation.</returns>
- [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var have to be marked non-inlineable
public Task<TResult> FromAsync<TResult>(
IAsyncResult asyncResult, Func<IAsyncResult, TResult> endMethod, TaskCreationOptions creationOptions, TaskScheduler scheduler)
{
- StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
- return TaskFactory<TResult>.FromAsyncImpl(asyncResult, endMethod, null, creationOptions, scheduler, ref stackMark);
+ return TaskFactory<TResult>.FromAsyncImpl(asyncResult, endMethod, null, creationOptions, scheduler);
}
/// <summary>
@@ -1606,7 +1541,7 @@ namespace System.Threading.Tasks
TaskCreationOptions.PreferFairness |
TaskCreationOptions.LongRunning)) != 0)
{
- throw new ArgumentOutOfRangeException(nameof(creationOptions));
+ ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.creationOptions);
}
}
@@ -1798,14 +1733,12 @@ namespace System.Threading.Tasks
/// <paramref name="tasks"/> array contains a null value.</exception>
/// <exception cref="T:System.ArgumentException">The exception that is thrown when the
/// <paramref name="tasks"/> array is empty.</exception>
- [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(nameof(continuationAction));
Contract.EndContractBlock();
- StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
- return TaskFactory<VoidTaskResult>.ContinueWhenAllImpl(tasks, null, continuationAction, m_defaultContinuationOptions, m_defaultCancellationToken, DefaultScheduler, ref stackMark);
+ return TaskFactory<VoidTaskResult>.ContinueWhenAllImpl(tasks, null, continuationAction, m_defaultContinuationOptions, m_defaultCancellationToken, DefaultScheduler);
}
@@ -1830,14 +1763,12 @@ namespace System.Threading.Tasks
/// <exception cref="T:System.ObjectDisposedException">The provided <see cref="System.Threading.CancellationToken">CancellationToken</see>
/// has already been disposed.
/// </exception>
- [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(nameof(continuationAction));
Contract.EndContractBlock();
- StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
- return TaskFactory<VoidTaskResult>.ContinueWhenAllImpl(tasks, null, continuationAction, m_defaultContinuationOptions, cancellationToken, DefaultScheduler, ref stackMark);
+ return TaskFactory<VoidTaskResult>.ContinueWhenAllImpl(tasks, null, continuationAction, m_defaultContinuationOptions, cancellationToken, DefaultScheduler);
}
/// <summary>
@@ -1867,14 +1798,12 @@ namespace System.Threading.Tasks
/// which constrain for which <see cref="System.Threading.Tasks.TaskStatus">TaskStatus</see> states a continuation
/// will be executed, are illegal with ContinueWhenAll.
/// </remarks>
- [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(nameof(continuationAction));
Contract.EndContractBlock();
- StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
- return TaskFactory<VoidTaskResult>.ContinueWhenAllImpl(tasks, null, continuationAction, continuationOptions, m_defaultCancellationToken, DefaultScheduler, ref stackMark);
+ return TaskFactory<VoidTaskResult>.ContinueWhenAllImpl(tasks, null, continuationAction, continuationOptions, m_defaultCancellationToken, DefaultScheduler);
}
/// <summary>
@@ -1914,15 +1843,13 @@ namespace System.Threading.Tasks
/// which constrain for which <see cref="System.Threading.Tasks.TaskStatus">TaskStatus</see> states a continuation
/// will be executed, are illegal with ContinueWhenAll.
/// </remarks>
- [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var have to be marked non-inlineable
public Task ContinueWhenAll(Task[] tasks, Action<Task[]> continuationAction, CancellationToken cancellationToken,
TaskContinuationOptions continuationOptions, TaskScheduler scheduler)
{
if (continuationAction == null) throw new ArgumentNullException(nameof(continuationAction));
Contract.EndContractBlock();
- StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
- return TaskFactory<VoidTaskResult>.ContinueWhenAllImpl(tasks, null, continuationAction, continuationOptions, cancellationToken, scheduler, ref stackMark);
+ return TaskFactory<VoidTaskResult>.ContinueWhenAllImpl(tasks, null, continuationAction, continuationOptions, cancellationToken, scheduler);
}
/// <summary>
@@ -1942,14 +1869,12 @@ namespace System.Threading.Tasks
/// <paramref name="tasks"/> array contains a null value.</exception>
/// <exception cref="T:System.ArgumentException">The exception that is thrown when the
/// <paramref name="tasks"/> array is empty.</exception>
- [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(nameof(continuationAction));
Contract.EndContractBlock();
- StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
- return TaskFactory<VoidTaskResult>.ContinueWhenAllImpl<TAntecedentResult>(tasks, null, continuationAction, m_defaultContinuationOptions, m_defaultCancellationToken, DefaultScheduler, ref stackMark);
+ return TaskFactory<VoidTaskResult>.ContinueWhenAllImpl<TAntecedentResult>(tasks, null, continuationAction, m_defaultContinuationOptions, m_defaultCancellationToken, DefaultScheduler);
}
@@ -1975,15 +1900,13 @@ namespace System.Threading.Tasks
/// <exception cref="T:System.ObjectDisposedException">The provided <see cref="System.Threading.CancellationToken">CancellationToken</see>
/// has already been disposed.
/// </exception>
- [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,
CancellationToken cancellationToken)
{
if (continuationAction == null) throw new ArgumentNullException(nameof(continuationAction));
Contract.EndContractBlock();
- StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
- return TaskFactory<VoidTaskResult>.ContinueWhenAllImpl<TAntecedentResult>(tasks, null, continuationAction, m_defaultContinuationOptions, cancellationToken, DefaultScheduler, ref stackMark);
+ return TaskFactory<VoidTaskResult>.ContinueWhenAllImpl<TAntecedentResult>(tasks, null, continuationAction, m_defaultContinuationOptions, cancellationToken, DefaultScheduler);
}
/// <summary>
@@ -2014,15 +1937,13 @@ namespace System.Threading.Tasks
/// which constrain for which <see cref="System.Threading.Tasks.TaskStatus">TaskStatus</see> states a continuation
/// will be executed, are illegal with ContinueWhenAll.
/// </remarks>
- [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,
TaskContinuationOptions continuationOptions)
{
if (continuationAction == null) throw new ArgumentNullException(nameof(continuationAction));
Contract.EndContractBlock();
- StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
- return TaskFactory<VoidTaskResult>.ContinueWhenAllImpl<TAntecedentResult>(tasks, null, continuationAction, continuationOptions, m_defaultCancellationToken, DefaultScheduler, ref stackMark);
+ return TaskFactory<VoidTaskResult>.ContinueWhenAllImpl<TAntecedentResult>(tasks, null, continuationAction, continuationOptions, m_defaultCancellationToken, DefaultScheduler);
}
/// <summary>
@@ -2063,15 +1984,13 @@ namespace System.Threading.Tasks
/// which constrain for which <see cref="System.Threading.Tasks.TaskStatus">TaskStatus</see> states a continuation
/// will be executed, are illegal with ContinueWhenAll.
/// </remarks>
- [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,
CancellationToken cancellationToken, TaskContinuationOptions continuationOptions, TaskScheduler scheduler)
{
if (continuationAction == null) throw new ArgumentNullException(nameof(continuationAction));
Contract.EndContractBlock();
- StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
- return TaskFactory<VoidTaskResult>.ContinueWhenAllImpl<TAntecedentResult>(tasks, null, continuationAction, continuationOptions, cancellationToken, scheduler, ref stackMark);
+ return TaskFactory<VoidTaskResult>.ContinueWhenAllImpl<TAntecedentResult>(tasks, null, continuationAction, continuationOptions, cancellationToken, scheduler);
}
/// <summary>
@@ -2094,14 +2013,12 @@ namespace System.Threading.Tasks
/// <paramref name="tasks"/> array contains a null value.</exception>
/// <exception cref="T:System.ArgumentException">The exception that is thrown when the
/// <paramref name="tasks"/> array is empty.</exception>
- [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(nameof(continuationFunction));
Contract.EndContractBlock();
- StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
- return TaskFactory<TResult>.ContinueWhenAllImpl(tasks, continuationFunction, null, m_defaultContinuationOptions, m_defaultCancellationToken, DefaultScheduler, ref stackMark);
+ return TaskFactory<TResult>.ContinueWhenAllImpl(tasks, continuationFunction, null, m_defaultContinuationOptions, m_defaultCancellationToken, DefaultScheduler);
}
@@ -2130,14 +2047,12 @@ namespace System.Threading.Tasks
/// <exception cref="T:System.ObjectDisposedException">The provided <see cref="System.Threading.CancellationToken">CancellationToken</see>
/// has already been disposed.
/// </exception>
- [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(nameof(continuationFunction));
Contract.EndContractBlock();
- StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
- return TaskFactory<TResult>.ContinueWhenAllImpl(tasks, continuationFunction, null, m_defaultContinuationOptions, cancellationToken, DefaultScheduler, ref stackMark);
+ return TaskFactory<TResult>.ContinueWhenAllImpl(tasks, continuationFunction, null, m_defaultContinuationOptions, cancellationToken, DefaultScheduler);
}
/// <summary>
@@ -2171,14 +2086,12 @@ namespace System.Threading.Tasks
/// which constrain for which <see cref="System.Threading.Tasks.TaskStatus">TaskStatus</see> states a continuation
/// will be executed, are illegal with ContinueWhenAll.
/// </remarks>
- [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(nameof(continuationFunction));
Contract.EndContractBlock();
- StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
- return TaskFactory<TResult>.ContinueWhenAllImpl(tasks, continuationFunction, null, continuationOptions, m_defaultCancellationToken, DefaultScheduler, ref stackMark);
+ return TaskFactory<TResult>.ContinueWhenAllImpl(tasks, continuationFunction, null, continuationOptions, m_defaultCancellationToken, DefaultScheduler);
}
/// <summary>
@@ -2222,15 +2135,13 @@ namespace System.Threading.Tasks
/// which constrain for which <see cref="System.Threading.Tasks.TaskStatus">TaskStatus</see> states a continuation
/// will be executed, are illegal with ContinueWhenAll.
/// </remarks>
- [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,
TaskContinuationOptions continuationOptions, TaskScheduler scheduler)
{
if (continuationFunction == null) throw new ArgumentNullException(nameof(continuationFunction));
Contract.EndContractBlock();
- StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
- return TaskFactory<TResult>.ContinueWhenAllImpl(tasks, continuationFunction, null, continuationOptions, cancellationToken, scheduler, ref stackMark);
+ return TaskFactory<TResult>.ContinueWhenAllImpl(tasks, continuationFunction, null, continuationOptions, cancellationToken, scheduler);
}
@@ -2255,14 +2166,12 @@ namespace System.Threading.Tasks
/// <paramref name="tasks"/> array contains a null value.</exception>
/// <exception cref="T:System.ArgumentException">The exception that is thrown when the
/// <paramref name="tasks"/> array is empty.</exception>
- [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(nameof(continuationFunction));
Contract.EndContractBlock();
- StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
- return TaskFactory<TResult>.ContinueWhenAllImpl<TAntecedentResult>(tasks, continuationFunction, null, m_defaultContinuationOptions, m_defaultCancellationToken, DefaultScheduler, ref stackMark);
+ return TaskFactory<TResult>.ContinueWhenAllImpl<TAntecedentResult>(tasks, continuationFunction, null, m_defaultContinuationOptions, m_defaultCancellationToken, DefaultScheduler);
}
/// <summary>
@@ -2291,15 +2200,13 @@ namespace System.Threading.Tasks
/// <exception cref="T:System.ObjectDisposedException">The provided <see cref="System.Threading.CancellationToken">CancellationToken</see>
/// has already been disposed.
/// </exception>
- [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,
CancellationToken cancellationToken)
{
if (continuationFunction == null) throw new ArgumentNullException(nameof(continuationFunction));
Contract.EndContractBlock();
- StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
- return TaskFactory<TResult>.ContinueWhenAllImpl<TAntecedentResult>(tasks, continuationFunction, null, m_defaultContinuationOptions, cancellationToken, DefaultScheduler, ref stackMark);
+ return TaskFactory<TResult>.ContinueWhenAllImpl<TAntecedentResult>(tasks, continuationFunction, null, m_defaultContinuationOptions, cancellationToken, DefaultScheduler);
}
/// <summary>
@@ -2334,15 +2241,13 @@ namespace System.Threading.Tasks
/// which constrain for which <see cref="System.Threading.Tasks.TaskStatus">TaskStatus</see> states a continuation
/// will be executed, are illegal with ContinueWhenAll.
/// </remarks>
- [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,
TaskContinuationOptions continuationOptions)
{
if (continuationFunction == null) throw new ArgumentNullException(nameof(continuationFunction));
Contract.EndContractBlock();
- StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
- return TaskFactory<TResult>.ContinueWhenAllImpl<TAntecedentResult>(tasks, continuationFunction, null, continuationOptions, m_defaultCancellationToken, DefaultScheduler, ref stackMark);
+ return TaskFactory<TResult>.ContinueWhenAllImpl<TAntecedentResult>(tasks, continuationFunction, null, continuationOptions, m_defaultCancellationToken, DefaultScheduler);
}
/// <summary>
@@ -2387,15 +2292,13 @@ namespace System.Threading.Tasks
/// which constrain for which <see cref="System.Threading.Tasks.TaskStatus">TaskStatus</see> states a continuation
/// will be executed, are illegal with ContinueWhenAll.
/// </remarks>
- [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,
CancellationToken cancellationToken, TaskContinuationOptions continuationOptions, TaskScheduler scheduler)
{
if (continuationFunction == null) throw new ArgumentNullException(nameof(continuationFunction));
Contract.EndContractBlock();
- StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
- return TaskFactory<TResult>.ContinueWhenAllImpl<TAntecedentResult>(tasks, continuationFunction, null, continuationOptions, cancellationToken, scheduler, ref stackMark);
+ return TaskFactory<TResult>.ContinueWhenAllImpl<TAntecedentResult>(tasks, continuationFunction, null, continuationOptions, cancellationToken, scheduler);
}
//
@@ -2505,7 +2408,23 @@ namespace System.Threading.Tasks
checkArgsOnly = true;
}
// Otherwise, add the completion action and keep going.
- else task.AddCompletionAction(promise);
+ else
+ {
+ task.AddCompletionAction(promise);
+ if (promise.IsCompleted)
+ {
+ // One of the previous tasks that already had its continuation registered may have
+ // raced to complete with our adding the continuation to this task. The completion
+ // routine would have gone through and removed the continuation from all of the tasks
+ // with which it was already registered, but if the race causes this continuation to
+ // be added after that, it'll never be removed. As such, after adding the continuation,
+ // we check to see whether the promise has already completed, and if it has, we try to
+ // manually remove the continuation from this task. If it was already removed, it'll be
+ // a nop, and if we race to remove it, the synchronization in RemoveContinuation will
+ // keep things consistent.
+ task.RemoveContinuation(promise);
+ }
+ }
}
return promise;
@@ -2528,14 +2447,12 @@ namespace System.Threading.Tasks
/// <paramref name="tasks"/> array contains a null value.</exception>
/// <exception cref="T:System.ArgumentException">The exception that is thrown when the
/// <paramref name="tasks"/> array is empty.</exception>
- [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(nameof(continuationAction));
Contract.EndContractBlock();
- StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
- return TaskFactory<VoidTaskResult>.ContinueWhenAnyImpl(tasks, null, continuationAction, m_defaultContinuationOptions, m_defaultCancellationToken, DefaultScheduler, ref stackMark);
+ return TaskFactory<VoidTaskResult>.ContinueWhenAnyImpl(tasks, null, continuationAction, m_defaultContinuationOptions, m_defaultCancellationToken, DefaultScheduler);
}
/// <summary>
@@ -2559,14 +2476,12 @@ namespace System.Threading.Tasks
/// <exception cref="T:System.ObjectDisposedException">The provided <see cref="System.Threading.CancellationToken">CancellationToken</see>
/// has already been disposed.
/// </exception>
- [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(nameof(continuationAction));
Contract.EndContractBlock();
- StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
- return TaskFactory<VoidTaskResult>.ContinueWhenAnyImpl(tasks, null, continuationAction, m_defaultContinuationOptions, cancellationToken, DefaultScheduler, ref stackMark);
+ return TaskFactory<VoidTaskResult>.ContinueWhenAnyImpl(tasks, null, continuationAction, m_defaultContinuationOptions, cancellationToken, DefaultScheduler);
}
/// <summary>
@@ -2596,14 +2511,12 @@ namespace System.Threading.Tasks
/// which constrain for which <see cref="System.Threading.Tasks.TaskStatus">TaskStatus</see> states a continuation
/// will be executed, are illegal with ContinueWhenAny.
/// </remarks>
- [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(nameof(continuationAction));
Contract.EndContractBlock();
- StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
- return TaskFactory<VoidTaskResult>.ContinueWhenAnyImpl(tasks, null, continuationAction, continuationOptions, m_defaultCancellationToken, DefaultScheduler, ref stackMark);
+ return TaskFactory<VoidTaskResult>.ContinueWhenAnyImpl(tasks, null, continuationAction, continuationOptions, m_defaultCancellationToken, DefaultScheduler);
}
/// <summary>
@@ -2643,15 +2556,13 @@ namespace System.Threading.Tasks
/// which constrain for which <see cref="System.Threading.Tasks.TaskStatus">TaskStatus</see> states a continuation
/// will be executed, are illegal with ContinueWhenAny.
/// </remarks>
- [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var have to be marked non-inlineable
public Task ContinueWhenAny(Task[] tasks, Action<Task> continuationAction, CancellationToken cancellationToken,
TaskContinuationOptions continuationOptions, TaskScheduler scheduler)
{
if (continuationAction == null) throw new ArgumentNullException(nameof(continuationAction));
Contract.EndContractBlock();
- StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
- return TaskFactory<VoidTaskResult>.ContinueWhenAnyImpl(tasks, null, continuationAction, continuationOptions, cancellationToken, scheduler, ref stackMark);
+ return TaskFactory<VoidTaskResult>.ContinueWhenAnyImpl(tasks, null, continuationAction, continuationOptions, cancellationToken, scheduler);
}
@@ -2675,14 +2586,12 @@ namespace System.Threading.Tasks
/// <paramref name="tasks"/> array contains a null value.</exception>
/// <exception cref="T:System.ArgumentException">The exception that is thrown when the
/// <paramref name="tasks"/> array is empty.</exception>
- [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(nameof(continuationFunction));
Contract.EndContractBlock();
- StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
- return TaskFactory<TResult>.ContinueWhenAnyImpl(tasks, continuationFunction, null, m_defaultContinuationOptions, m_defaultCancellationToken, DefaultScheduler, ref stackMark);
+ return TaskFactory<TResult>.ContinueWhenAnyImpl(tasks, continuationFunction, null, m_defaultContinuationOptions, m_defaultCancellationToken, DefaultScheduler);
}
/// <summary>
@@ -2710,14 +2619,12 @@ namespace System.Threading.Tasks
/// <exception cref="T:System.ObjectDisposedException">The provided <see cref="System.Threading.CancellationToken">CancellationToken</see>
/// has already been disposed.
/// </exception>
- [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(nameof(continuationFunction));
Contract.EndContractBlock();
- StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
- return TaskFactory<TResult>.ContinueWhenAnyImpl(tasks, continuationFunction, null, m_defaultContinuationOptions, cancellationToken, DefaultScheduler, ref stackMark);
+ return TaskFactory<TResult>.ContinueWhenAnyImpl(tasks, continuationFunction, null, m_defaultContinuationOptions, cancellationToken, DefaultScheduler);
}
/// <summary>
@@ -2751,14 +2658,12 @@ namespace System.Threading.Tasks
/// which constrain for which <see cref="System.Threading.Tasks.TaskStatus">TaskStatus</see> states a continuation
/// will be executed, are illegal with ContinueWhenAny.
/// </remarks>
- [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(nameof(continuationFunction));
Contract.EndContractBlock();
- StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
- return TaskFactory<TResult>.ContinueWhenAnyImpl(tasks, continuationFunction, null,continuationOptions, m_defaultCancellationToken, DefaultScheduler, ref stackMark);
+ return TaskFactory<TResult>.ContinueWhenAnyImpl(tasks, continuationFunction, null,continuationOptions, m_defaultCancellationToken, DefaultScheduler);
}
/// <summary>
@@ -2802,15 +2707,13 @@ namespace System.Threading.Tasks
/// which constrain for which <see cref="System.Threading.Tasks.TaskStatus">TaskStatus</see> states a continuation
/// will be executed, are illegal with ContinueWhenAny.
/// </remarks>
- [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,
TaskContinuationOptions continuationOptions, TaskScheduler scheduler)
{
if (continuationFunction == null) throw new ArgumentNullException(nameof(continuationFunction));
Contract.EndContractBlock();
- StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
- return TaskFactory<TResult>.ContinueWhenAnyImpl(tasks, continuationFunction, null, continuationOptions, cancellationToken, scheduler, ref stackMark);
+ return TaskFactory<TResult>.ContinueWhenAnyImpl(tasks, continuationFunction, null, continuationOptions, cancellationToken, scheduler);
}
/// <summary>
@@ -2834,12 +2737,10 @@ namespace System.Threading.Tasks
/// <paramref name="tasks"/> array contains a null value.</exception>
/// <exception cref="T:System.ArgumentException">The exception that is thrown when the
/// <paramref name="tasks"/> array is empty.</exception>
- [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var have to be marked non-inlineable
public Task<TResult> ContinueWhenAny<TAntecedentResult, TResult>(Task<TAntecedentResult>[] tasks, Func<Task<TAntecedentResult>, TResult> continuationFunction)
{
- StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
if (continuationFunction == null) throw new ArgumentNullException(nameof(continuationFunction));
- return TaskFactory<TResult>.ContinueWhenAnyImpl<TAntecedentResult>(tasks, continuationFunction, null, m_defaultContinuationOptions, m_defaultCancellationToken, DefaultScheduler, ref stackMark);
+ return TaskFactory<TResult>.ContinueWhenAnyImpl<TAntecedentResult>(tasks, continuationFunction, null, m_defaultContinuationOptions, m_defaultCancellationToken, DefaultScheduler);
}
/// <summary>
@@ -2868,15 +2769,13 @@ namespace System.Threading.Tasks
/// <exception cref="T:System.ObjectDisposedException">The provided <see cref="System.Threading.CancellationToken">CancellationToken</see>
/// has already been disposed.
/// </exception>
- [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var have to be marked non-inlineable
public Task<TResult> ContinueWhenAny<TAntecedentResult, TResult>(Task<TAntecedentResult>[] tasks, Func<Task<TAntecedentResult>, TResult> continuationFunction,
CancellationToken cancellationToken)
{
if (continuationFunction == null) throw new ArgumentNullException(nameof(continuationFunction));
Contract.EndContractBlock();
- StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
- return TaskFactory<TResult>.ContinueWhenAnyImpl<TAntecedentResult>(tasks, continuationFunction, null, m_defaultContinuationOptions, cancellationToken, DefaultScheduler, ref stackMark);
+ return TaskFactory<TResult>.ContinueWhenAnyImpl<TAntecedentResult>(tasks, continuationFunction, null, m_defaultContinuationOptions, cancellationToken, DefaultScheduler);
}
/// <summary>
@@ -2911,15 +2810,13 @@ namespace System.Threading.Tasks
/// which constrain for which <see cref="System.Threading.Tasks.TaskStatus">TaskStatus</see> states a continuation
/// will be executed, are illegal with ContinueWhenAny.
/// </remarks>
- [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var have to be marked non-inlineable
public Task<TResult> ContinueWhenAny<TAntecedentResult, TResult>(Task<TAntecedentResult>[] tasks, Func<Task<TAntecedentResult>, TResult> continuationFunction,
TaskContinuationOptions continuationOptions)
{
if (continuationFunction == null) throw new ArgumentNullException(nameof(continuationFunction));
Contract.EndContractBlock();
- StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
- return TaskFactory<TResult>.ContinueWhenAnyImpl<TAntecedentResult>(tasks, continuationFunction, null, continuationOptions, m_defaultCancellationToken, DefaultScheduler, ref stackMark);
+ return TaskFactory<TResult>.ContinueWhenAnyImpl<TAntecedentResult>(tasks, continuationFunction, null, continuationOptions, m_defaultCancellationToken, DefaultScheduler);
}
/// <summary>
@@ -2964,15 +2861,13 @@ namespace System.Threading.Tasks
/// which constrain for which <see cref="System.Threading.Tasks.TaskStatus">TaskStatus</see> states a continuation
/// will be executed, are illegal with ContinueWhenAny.
/// </remarks>
- [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var have to be marked non-inlineable
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(nameof(continuationFunction));
Contract.EndContractBlock();
- StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
- return TaskFactory<TResult>.ContinueWhenAnyImpl<TAntecedentResult>(tasks, continuationFunction, null, continuationOptions, cancellationToken, scheduler, ref stackMark);
+ return TaskFactory<TResult>.ContinueWhenAnyImpl<TAntecedentResult>(tasks, continuationFunction, null, continuationOptions, cancellationToken, scheduler);
}
@@ -2993,14 +2888,12 @@ namespace System.Threading.Tasks
/// <paramref name="tasks"/> array contains a null value.</exception>
/// <exception cref="T:System.ArgumentException">The exception that is thrown when the
/// <paramref name="tasks"/> array is empty.</exception>
- [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(nameof(continuationAction));
Contract.EndContractBlock();
- StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
- return TaskFactory<VoidTaskResult>.ContinueWhenAnyImpl<TAntecedentResult>(tasks, null, continuationAction, m_defaultContinuationOptions, m_defaultCancellationToken, DefaultScheduler, ref stackMark);
+ return TaskFactory<VoidTaskResult>.ContinueWhenAnyImpl<TAntecedentResult>(tasks, null, continuationAction, m_defaultContinuationOptions, m_defaultCancellationToken, DefaultScheduler);
}
/// <summary>
@@ -3025,15 +2918,13 @@ namespace System.Threading.Tasks
/// <exception cref="T:System.ObjectDisposedException">The provided <see cref="System.Threading.CancellationToken">CancellationToken</see>
/// has already been disposed.
/// </exception>
- [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,
CancellationToken cancellationToken)
{
if (continuationAction == null) throw new ArgumentNullException(nameof(continuationAction));
Contract.EndContractBlock();
- StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
- return TaskFactory<VoidTaskResult>.ContinueWhenAnyImpl<TAntecedentResult>(tasks, null, continuationAction, m_defaultContinuationOptions, cancellationToken, DefaultScheduler, ref stackMark);
+ return TaskFactory<VoidTaskResult>.ContinueWhenAnyImpl<TAntecedentResult>(tasks, null, continuationAction, m_defaultContinuationOptions, cancellationToken, DefaultScheduler);
}
/// <summary>
@@ -3064,15 +2955,13 @@ namespace System.Threading.Tasks
/// which constrain for which <see cref="System.Threading.Tasks.TaskStatus">TaskStatus</see> states a continuation
/// will be executed, are illegal with ContinueWhenAny.
/// </remarks>
- [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,
TaskContinuationOptions continuationOptions)
{
if (continuationAction == null) throw new ArgumentNullException(nameof(continuationAction));
Contract.EndContractBlock();
- StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
- return TaskFactory<VoidTaskResult>.ContinueWhenAnyImpl<TAntecedentResult>(tasks, null, continuationAction, continuationOptions, m_defaultCancellationToken, DefaultScheduler, ref stackMark);
+ return TaskFactory<VoidTaskResult>.ContinueWhenAnyImpl<TAntecedentResult>(tasks, null, continuationAction, continuationOptions, m_defaultCancellationToken, DefaultScheduler);
}
/// <summary>
@@ -3113,15 +3002,13 @@ namespace System.Threading.Tasks
/// which constrain for which <see cref="System.Threading.Tasks.TaskStatus">TaskStatus</see> states a continuation
/// will be executed, are illegal with ContinueWhenAny.
/// </remarks>
- [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,
CancellationToken cancellationToken, TaskContinuationOptions continuationOptions, TaskScheduler scheduler)
{
if (continuationAction == null) throw new ArgumentNullException(nameof(continuationAction));
Contract.EndContractBlock();
- StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
- return TaskFactory<VoidTaskResult>.ContinueWhenAnyImpl<TAntecedentResult>(tasks, null, continuationAction, continuationOptions, cancellationToken, scheduler, ref stackMark);
+ return TaskFactory<VoidTaskResult>.ContinueWhenAnyImpl<TAntecedentResult>(tasks, null, continuationAction, continuationOptions, cancellationToken, scheduler);
}
// Check task array and return a defensive copy.
diff --git a/src/mscorlib/src/System/Threading/Tasks/TaskScheduler.cs b/src/mscorlib/src/System/Threading/Tasks/TaskScheduler.cs
index fad3fc06c5..d68c3fedc4 100644
--- a/src/mscorlib/src/System/Threading/Tasks/TaskScheduler.cs
+++ b/src/mscorlib/src/System/Threading/Tasks/TaskScheduler.cs
@@ -16,7 +16,6 @@ using System.Collections.Generic;
using System.Globalization;
using System.Threading;
using System.Security;
-using System.Security.Permissions;
using System.Collections.Concurrent;
using System.Diagnostics.Contracts;
using System.Diagnostics;
diff --git a/src/mscorlib/src/System/Threading/Tasks/future.cs b/src/mscorlib/src/System/Threading/Tasks/future.cs
index 0c3fec89b7..15136f12bf 100644
--- a/src/mscorlib/src/System/Threading/Tasks/future.cs
+++ b/src/mscorlib/src/System/Threading/Tasks/future.cs
@@ -16,7 +16,6 @@ using System.Runtime;
using System.Runtime.CompilerServices;
using System.Runtime.ExceptionServices;
using System.Security;
-using System.Security.Permissions;
using System.Threading;
using System.Diagnostics;
using System.Diagnostics.Contracts;
@@ -128,13 +127,10 @@ namespace System.Threading.Tasks
/// <exception cref="T:System.ArgumentException">
/// The <paramref name="function"/> argument is null.
/// </exception>
- [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var have to be marked non-inlineable
public Task(Func<TResult> function)
: this(function, null, default(CancellationToken),
TaskCreationOptions.None, InternalTaskOptions.None, null)
{
- StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
- PossiblyCaptureContext(ref stackMark);
}
@@ -152,13 +148,10 @@ namespace System.Threading.Tasks
/// <exception cref="T:System.ObjectDisposedException">The provided <see cref="System.Threading.CancellationToken">CancellationToken</see>
/// has already been disposed.
/// </exception>
- [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var have to be marked non-inlineable
public Task(Func<TResult> function, CancellationToken cancellationToken)
: this(function, null, cancellationToken,
TaskCreationOptions.None, InternalTaskOptions.None, null)
{
- StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
- PossiblyCaptureContext(ref stackMark);
}
/// <summary>
@@ -179,12 +172,9 @@ namespace System.Threading.Tasks
/// The <paramref name="creationOptions"/> argument specifies an invalid value for <see
/// cref="T:System.Threading.Tasks.TaskCreationOptions"/>.
/// </exception>
- [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var have to be marked non-inlineable
public Task(Func<TResult> function, TaskCreationOptions creationOptions)
: this(function, Task.InternalCurrentIfAttached(creationOptions), default(CancellationToken), creationOptions, InternalTaskOptions.None, null)
{
- StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
- PossiblyCaptureContext(ref stackMark);
}
/// <summary>
@@ -209,12 +199,9 @@ namespace System.Threading.Tasks
/// <exception cref="T:System.ObjectDisposedException">The provided <see cref="System.Threading.CancellationToken">CancellationToken</see>
/// has already been disposed.
/// </exception>
- [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var have to be marked non-inlineable
public Task(Func<TResult> function, CancellationToken cancellationToken, TaskCreationOptions creationOptions)
: this(function, Task.InternalCurrentIfAttached(creationOptions), cancellationToken, creationOptions, InternalTaskOptions.None, null)
{
- StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
- PossiblyCaptureContext(ref stackMark);
}
/// <summary>
@@ -228,13 +215,10 @@ namespace System.Threading.Tasks
/// <exception cref="T:System.ArgumentException">
/// The <paramref name="function"/> argument is null.
/// </exception>
- [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var have to be marked non-inlineable
public Task(Func<object, TResult> function, object state)
: this(function, state, null, default(CancellationToken),
TaskCreationOptions.None, InternalTaskOptions.None, null)
{
- StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
- PossiblyCaptureContext(ref stackMark);
}
/// <summary>
@@ -252,13 +236,10 @@ namespace System.Threading.Tasks
/// <exception cref="T:System.ObjectDisposedException">The provided <see cref="System.Threading.CancellationToken">CancellationToken</see>
/// has already been disposed.
/// </exception>
- [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var have to be marked non-inlineable
public Task(Func<object, TResult> function, object state, CancellationToken cancellationToken)
: this(function, state, null, cancellationToken,
TaskCreationOptions.None, InternalTaskOptions.None, null)
{
- StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
- PossiblyCaptureContext(ref stackMark);
}
/// <summary>
@@ -280,13 +261,10 @@ namespace System.Threading.Tasks
/// The <paramref name="creationOptions"/> argument specifies an invalid value for <see
/// cref="T:System.Threading.Tasks.TaskCreationOptions"/>.
/// </exception>
- [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var have to be marked non-inlineable
public Task(Func<object, TResult> function, object state, TaskCreationOptions creationOptions)
: this(function, state, Task.InternalCurrentIfAttached(creationOptions), default(CancellationToken),
creationOptions, InternalTaskOptions.None, null)
{
- StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
- PossiblyCaptureContext(ref stackMark);
}
@@ -313,23 +291,10 @@ namespace System.Threading.Tasks
/// <exception cref="T:System.ObjectDisposedException">The provided <see cref="System.Threading.CancellationToken">CancellationToken</see>
/// has already been disposed.
/// </exception>
- [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var have to be marked non-inlineable
public Task(Func<object, TResult> function, object state, CancellationToken cancellationToken, TaskCreationOptions creationOptions)
: this(function, state, Task.InternalCurrentIfAttached(creationOptions), cancellationToken,
creationOptions, InternalTaskOptions.None, null)
{
- StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
- PossiblyCaptureContext(ref stackMark);
- }
-
- internal Task(
- Func<TResult> valueSelector, Task parent, CancellationToken cancellationToken,
- TaskCreationOptions creationOptions, InternalTaskOptions internalOptions, TaskScheduler scheduler,
- ref StackCrawlMark stackMark) :
- this(valueSelector, parent, cancellationToken,
- creationOptions, internalOptions, scheduler)
- {
- PossiblyCaptureContext(ref stackMark);
}
/// <summary>
@@ -341,24 +306,10 @@ namespace System.Threading.Tasks
/// <param name="cancellationToken">The CancellationToken for the task.</param>
/// <param name="creationOptions">Options to control the future's behavior.</param>
/// <param name="internalOptions">Internal options to control the future's behavior.</param>
- /// <exception cref="T:System.ArgumentOutOfRangeException">The <paramref name="creationOptions"/> argument specifies
- /// a SelfReplicating <see cref="Task{TResult}"/>, which is illegal."/>.</exception>
internal Task(Func<TResult> valueSelector, Task parent, CancellationToken cancellationToken,
TaskCreationOptions creationOptions, InternalTaskOptions internalOptions, TaskScheduler scheduler) :
base(valueSelector, null, parent, cancellationToken, creationOptions, internalOptions, scheduler)
{
- if ((internalOptions & InternalTaskOptions.SelfReplicating) != 0)
- {
- ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.creationOptions, ExceptionResource.TaskT_ctor_SelfReplicating);
- }
- }
-
- internal Task(
- Func<object, TResult> valueSelector, object state, Task parent, CancellationToken cancellationToken,
- TaskCreationOptions creationOptions, InternalTaskOptions internalOptions, TaskScheduler scheduler, ref StackCrawlMark stackMark) :
- this(valueSelector, state, parent, cancellationToken, creationOptions, internalOptions, scheduler)
- {
- PossiblyCaptureContext(ref stackMark);
}
/// <summary>
@@ -371,22 +322,16 @@ namespace System.Threading.Tasks
/// <param name="scheduler">The task scheduler which will be used to execute the future.</param>
/// <param name="creationOptions">Options to control the future's behavior.</param>
/// <param name="internalOptions">Internal options to control the future's behavior.</param>
- /// <exception cref="T:System.ArgumentOutOfRangeException">The <paramref name="creationOptions"/> argument specifies
- /// a SelfReplicating <see cref="Task{TResult}"/>, which is illegal."/>.</exception>
internal Task(Delegate valueSelector, object state, Task parent, CancellationToken cancellationToken,
TaskCreationOptions creationOptions, InternalTaskOptions internalOptions, TaskScheduler scheduler) :
base(valueSelector, state, parent, cancellationToken, creationOptions, internalOptions, scheduler)
{
- if ((internalOptions & InternalTaskOptions.SelfReplicating) != 0)
- {
- ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.creationOptions, ExceptionResource.TaskT_ctor_SelfReplicating);
- }
}
// Internal method used by TaskFactory<TResult>.StartNew() methods
internal static Task<TResult> StartNew(Task parent, Func<TResult> function, CancellationToken cancellationToken,
- TaskCreationOptions creationOptions, InternalTaskOptions internalOptions, TaskScheduler scheduler, ref StackCrawlMark stackMark)
+ TaskCreationOptions creationOptions, InternalTaskOptions internalOptions, TaskScheduler scheduler)
{
if (function == null)
{
@@ -396,13 +341,9 @@ namespace System.Threading.Tasks
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.scheduler);
}
- if ((internalOptions & InternalTaskOptions.SelfReplicating) != 0)
- {
- ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.creationOptions, ExceptionResource.TaskT_ctor_SelfReplicating);
- }
// Create and schedule the future.
- Task<TResult> f = new Task<TResult>(function, parent, cancellationToken, creationOptions, internalOptions | InternalTaskOptions.QueuedByRuntime, scheduler, ref stackMark);
+ Task<TResult> f = new Task<TResult>(function, parent, cancellationToken, creationOptions, internalOptions | InternalTaskOptions.QueuedByRuntime, scheduler);
f.ScheduleAndStart(false);
return f;
@@ -410,7 +351,7 @@ namespace System.Threading.Tasks
// Internal method used by TaskFactory<TResult>.StartNew() methods
internal static Task<TResult> StartNew(Task parent, Func<object, TResult> function, object state, CancellationToken cancellationToken,
- TaskCreationOptions creationOptions, InternalTaskOptions internalOptions, TaskScheduler scheduler, ref StackCrawlMark stackMark)
+ TaskCreationOptions creationOptions, InternalTaskOptions internalOptions, TaskScheduler scheduler)
{
if (function == null)
{
@@ -420,13 +361,9 @@ namespace System.Threading.Tasks
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.scheduler);
}
- if ((internalOptions & InternalTaskOptions.SelfReplicating) != 0)
- {
- ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.creationOptions, ExceptionResource.TaskT_ctor_SelfReplicating);
- }
// Create and schedule the future.
- Task<TResult> f = new Task<TResult>(function, state, parent, cancellationToken, creationOptions, internalOptions | InternalTaskOptions.QueuedByRuntime, scheduler, ref stackMark);
+ Task<TResult> f = new Task<TResult>(function, state, parent, cancellationToken, creationOptions, internalOptions | InternalTaskOptions.QueuedByRuntime, scheduler);
f.ScheduleAndStart(false);
return f;
@@ -726,11 +663,9 @@ namespace System.Threading.Tasks
/// <exception cref="T:System.ArgumentNullException">
/// The <paramref name="continuationAction"/> argument is null.
/// </exception>
- [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var have to be marked non-inlineable
public Task ContinueWith(Action<Task<TResult>> continuationAction)
{
- StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
- return ContinueWith(continuationAction, TaskScheduler.Current, default(CancellationToken), TaskContinuationOptions.None, ref stackMark);
+ return ContinueWith(continuationAction, TaskScheduler.Current, default(CancellationToken), TaskContinuationOptions.None);
}
@@ -754,11 +689,9 @@ namespace System.Threading.Tasks
/// <exception cref="T:System.ObjectDisposedException">The provided <see cref="System.Threading.CancellationToken">CancellationToken</see>
/// has already been disposed.
/// </exception>
- [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var have to be marked non-inlineable
public Task ContinueWith(Action<Task<TResult>> continuationAction, CancellationToken cancellationToken)
{
- StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
- return ContinueWith(continuationAction, TaskScheduler.Current, cancellationToken, TaskContinuationOptions.None, ref stackMark);
+ return ContinueWith(continuationAction, TaskScheduler.Current, cancellationToken, TaskContinuationOptions.None);
}
@@ -784,11 +717,9 @@ namespace System.Threading.Tasks
/// <exception cref="T:System.ArgumentNullException">
/// The <paramref name="scheduler"/> argument is null.
/// </exception>
- [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var have to be marked non-inlineable
public Task ContinueWith(Action<Task<TResult>> continuationAction, TaskScheduler scheduler)
{
- StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
- return ContinueWith(continuationAction, scheduler, default(CancellationToken), TaskContinuationOptions.None, ref stackMark);
+ return ContinueWith(continuationAction, scheduler, default(CancellationToken), TaskContinuationOptions.None);
}
/// <summary>
@@ -819,11 +750,9 @@ namespace System.Threading.Tasks
/// The <paramref name="continuationOptions"/> argument specifies an invalid value for <see
/// cref="T:System.Threading.Tasks.TaskContinuationOptions">TaskContinuationOptions</see>.
/// </exception>
- [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var have to be marked non-inlineable
public Task ContinueWith(Action<Task<TResult>> continuationAction, TaskContinuationOptions continuationOptions)
{
- StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
- return ContinueWith(continuationAction, TaskScheduler.Current, default(CancellationToken), continuationOptions, ref stackMark);
+ return ContinueWith(continuationAction, TaskScheduler.Current, default(CancellationToken), continuationOptions);
}
/// <summary>
@@ -864,17 +793,15 @@ namespace System.Threading.Tasks
/// <exception cref="T:System.ObjectDisposedException">The provided <see cref="System.Threading.CancellationToken">CancellationToken</see>
/// has already been disposed.
/// </exception>
- [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var have to be marked non-inlineable
public Task ContinueWith(Action<Task<TResult>> continuationAction, CancellationToken cancellationToken,
TaskContinuationOptions continuationOptions, TaskScheduler scheduler)
{
- StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
- return ContinueWith(continuationAction, scheduler, cancellationToken, continuationOptions, ref stackMark);
+ return ContinueWith(continuationAction, scheduler, cancellationToken, continuationOptions);
}
// Same as the above overload, only with a stack mark.
internal Task ContinueWith(Action<Task<TResult>> continuationAction, TaskScheduler scheduler, CancellationToken cancellationToken,
- TaskContinuationOptions continuationOptions, ref StackCrawlMark stackMark)
+ TaskContinuationOptions continuationOptions)
{
if (continuationAction == null)
{
@@ -895,8 +822,7 @@ namespace System.Threading.Tasks
Task continuationTask = new ContinuationTaskFromResultTask<TResult>(
this, continuationAction, null,
- creationOptions, internalOptions,
- ref stackMark
+ creationOptions, internalOptions
);
// Register the continuation. If synchronous execution is requested, this may
@@ -926,11 +852,9 @@ namespace System.Threading.Tasks
/// <exception cref="T:System.ArgumentNullException">
/// The <paramref name="continuationAction"/> argument is null.
/// </exception>
- [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var have to be marked non-inlineable
public Task ContinueWith(Action<Task<TResult>, Object> continuationAction, Object state)
{
- StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
- return ContinueWith(continuationAction, state, TaskScheduler.Current, default(CancellationToken), TaskContinuationOptions.None, ref stackMark);
+ return ContinueWith(continuationAction, state, TaskScheduler.Current, default(CancellationToken), TaskContinuationOptions.None);
}
@@ -955,11 +879,9 @@ namespace System.Threading.Tasks
/// <exception cref="T:System.ObjectDisposedException">The provided <see cref="System.Threading.CancellationToken">CancellationToken</see>
/// has already been disposed.
/// </exception>
- [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var have to be marked non-inlineable
public Task ContinueWith(Action<Task<TResult>, Object> continuationAction, Object state,CancellationToken cancellationToken)
{
- StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
- return ContinueWith(continuationAction, state, TaskScheduler.Current, cancellationToken, TaskContinuationOptions.None, ref stackMark);
+ return ContinueWith(continuationAction, state, TaskScheduler.Current, cancellationToken, TaskContinuationOptions.None);
}
@@ -986,11 +908,9 @@ namespace System.Threading.Tasks
/// <exception cref="T:System.ArgumentNullException">
/// The <paramref name="scheduler"/> argument is null.
/// </exception>
- [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var have to be marked non-inlineable
public Task ContinueWith(Action<Task<TResult>, Object> continuationAction, Object state, TaskScheduler scheduler)
{
- StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
- return ContinueWith(continuationAction, state, scheduler, default(CancellationToken), TaskContinuationOptions.None, ref stackMark);
+ return ContinueWith(continuationAction, state, scheduler, default(CancellationToken), TaskContinuationOptions.None);
}
/// <summary>
@@ -1022,11 +942,9 @@ namespace System.Threading.Tasks
/// The <paramref name="continuationOptions"/> argument specifies an invalid value for <see
/// cref="T:System.Threading.Tasks.TaskContinuationOptions">TaskContinuationOptions</see>.
/// </exception>
- [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var have to be marked non-inlineable
public Task ContinueWith(Action<Task<TResult>, Object> continuationAction, Object state,TaskContinuationOptions continuationOptions)
{
- StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
- return ContinueWith(continuationAction, state, TaskScheduler.Current, default(CancellationToken), continuationOptions, ref stackMark);
+ return ContinueWith(continuationAction, state, TaskScheduler.Current, default(CancellationToken), continuationOptions);
}
/// <summary>
@@ -1068,17 +986,15 @@ namespace System.Threading.Tasks
/// <exception cref="T:System.ObjectDisposedException">The provided <see cref="System.Threading.CancellationToken">CancellationToken</see>
/// has already been disposed.
/// </exception>
- [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var have to be marked non-inlineable
public Task ContinueWith(Action<Task<TResult>, Object> continuationAction, Object state, CancellationToken cancellationToken,
TaskContinuationOptions continuationOptions, TaskScheduler scheduler)
{
- StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
- return ContinueWith(continuationAction, state, scheduler, cancellationToken, continuationOptions, ref stackMark);
+ return ContinueWith(continuationAction, state, scheduler, cancellationToken, continuationOptions);
}
// Same as the above overload, only with a stack mark.
internal Task ContinueWith(Action<Task<TResult>, Object> continuationAction, Object state, TaskScheduler scheduler, CancellationToken cancellationToken,
- TaskContinuationOptions continuationOptions, ref StackCrawlMark stackMark)
+ TaskContinuationOptions continuationOptions)
{
if (continuationAction == null)
{
@@ -1099,8 +1015,7 @@ namespace System.Threading.Tasks
Task continuationTask = new ContinuationTaskFromResultTask<TResult>(
this, continuationAction, state,
- creationOptions, internalOptions,
- ref stackMark
+ creationOptions, internalOptions
);
// Register the continuation. If synchronous execution is requested, this may
@@ -1133,11 +1048,9 @@ namespace System.Threading.Tasks
/// <exception cref="T:System.ArgumentNullException">
/// The <paramref name="continuationFunction"/> argument is null.
/// </exception>
- [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var have to be marked non-inlineable
public Task<TNewResult> ContinueWith<TNewResult>(Func<Task<TResult>, TNewResult> continuationFunction)
{
- StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
- return ContinueWith<TNewResult>(continuationFunction, TaskScheduler.Current, default(CancellationToken), TaskContinuationOptions.None, ref stackMark);
+ return ContinueWith<TNewResult>(continuationFunction, TaskScheduler.Current, default(CancellationToken), TaskContinuationOptions.None);
}
@@ -1164,11 +1077,9 @@ namespace System.Threading.Tasks
/// <exception cref="T:System.ObjectDisposedException">The provided <see cref="System.Threading.CancellationToken">CancellationToken</see>
/// has already been disposed.
/// </exception>
- [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var have to be marked non-inlineable
public Task<TNewResult> ContinueWith<TNewResult>(Func<Task<TResult>, TNewResult> continuationFunction, CancellationToken cancellationToken)
{
- StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
- return ContinueWith<TNewResult>(continuationFunction, TaskScheduler.Current, cancellationToken, TaskContinuationOptions.None, ref stackMark);
+ return ContinueWith<TNewResult>(continuationFunction, TaskScheduler.Current, cancellationToken, TaskContinuationOptions.None);
}
/// <summary>
@@ -1196,11 +1107,9 @@ namespace System.Threading.Tasks
/// <exception cref="T:System.ArgumentNullException">
/// The <paramref name="scheduler"/> argument is null.
/// </exception>
- [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var have to be marked non-inlineable
public Task<TNewResult> ContinueWith<TNewResult>(Func<Task<TResult>, TNewResult> continuationFunction, TaskScheduler scheduler)
{
- StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
- return ContinueWith<TNewResult>(continuationFunction, scheduler, default(CancellationToken), TaskContinuationOptions.None, ref stackMark);
+ return ContinueWith<TNewResult>(continuationFunction, scheduler, default(CancellationToken), TaskContinuationOptions.None);
}
/// <summary>
@@ -1240,11 +1149,9 @@ namespace System.Threading.Tasks
/// The <paramref name="continuationOptions"/> argument specifies an invalid value for <see
/// cref="T:System.Threading.Tasks.TaskContinuationOptions">TaskContinuationOptions</see>.
/// </exception>
- [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var have to be marked non-inlineable
public Task<TNewResult> ContinueWith<TNewResult>(Func<Task<TResult>, TNewResult> continuationFunction, TaskContinuationOptions continuationOptions)
{
- StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
- return ContinueWith<TNewResult>(continuationFunction, TaskScheduler.Current, default(CancellationToken), continuationOptions, ref stackMark);
+ return ContinueWith<TNewResult>(continuationFunction, TaskScheduler.Current, default(CancellationToken), continuationOptions);
}
/// <summary>
@@ -1295,17 +1202,15 @@ namespace System.Threading.Tasks
/// <exception cref="T:System.ObjectDisposedException">The provided <see cref="System.Threading.CancellationToken">CancellationToken</see>
/// has already been disposed.
/// </exception>
- [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var have to be marked non-inlineable
public Task<TNewResult> ContinueWith<TNewResult>(Func<Task<TResult>, TNewResult> continuationFunction, CancellationToken cancellationToken,
TaskContinuationOptions continuationOptions, TaskScheduler scheduler)
{
- StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
- return ContinueWith<TNewResult>(continuationFunction, scheduler, cancellationToken, continuationOptions, ref stackMark);
+ return ContinueWith<TNewResult>(continuationFunction, scheduler, cancellationToken, continuationOptions);
}
// Same as the above overload, just with a stack mark.
internal Task<TNewResult> ContinueWith<TNewResult>(Func<Task<TResult>, TNewResult> continuationFunction, TaskScheduler scheduler,
- CancellationToken cancellationToken, TaskContinuationOptions continuationOptions, ref StackCrawlMark stackMark)
+ CancellationToken cancellationToken, TaskContinuationOptions continuationOptions)
{
if (continuationFunction == null)
{
@@ -1326,8 +1231,7 @@ namespace System.Threading.Tasks
Task<TNewResult> continuationFuture = new ContinuationResultTaskFromResultTask<TResult,TNewResult>(
this, continuationFunction, null,
- creationOptions, internalOptions,
- ref stackMark
+ creationOptions, internalOptions
);
// Register the continuation. If synchronous execution is requested, this may
@@ -1360,11 +1264,9 @@ namespace System.Threading.Tasks
/// <exception cref="T:System.ArgumentNullException">
/// The <paramref name="continuationFunction"/> argument is null.
/// </exception>
- [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var have to be marked non-inlineable
public Task<TNewResult> ContinueWith<TNewResult>(Func<Task<TResult>, Object, TNewResult> continuationFunction, Object state)
{
- StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
- return ContinueWith<TNewResult>(continuationFunction, state, TaskScheduler.Current, default(CancellationToken), TaskContinuationOptions.None, ref stackMark);
+ return ContinueWith<TNewResult>(continuationFunction, state, TaskScheduler.Current, default(CancellationToken), TaskContinuationOptions.None);
}
@@ -1392,12 +1294,10 @@ namespace System.Threading.Tasks
/// <exception cref="T:System.ObjectDisposedException">The provided <see cref="System.Threading.CancellationToken">CancellationToken</see>
/// has already been disposed.
/// </exception>
- [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var have to be marked non-inlineable
public Task<TNewResult> ContinueWith<TNewResult>(Func<Task<TResult>, Object, TNewResult> continuationFunction, Object state,
CancellationToken cancellationToken)
{
- StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
- return ContinueWith<TNewResult>(continuationFunction, state, TaskScheduler.Current, cancellationToken, TaskContinuationOptions.None, ref stackMark);
+ return ContinueWith<TNewResult>(continuationFunction, state, TaskScheduler.Current, cancellationToken, TaskContinuationOptions.None);
}
/// <summary>
@@ -1426,12 +1326,10 @@ namespace System.Threading.Tasks
/// <exception cref="T:System.ArgumentNullException">
/// The <paramref name="scheduler"/> argument is null.
/// </exception>
- [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var have to be marked non-inlineable
public Task<TNewResult> ContinueWith<TNewResult>(Func<Task<TResult>, Object, TNewResult> continuationFunction, Object state,
TaskScheduler scheduler)
{
- StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
- return ContinueWith<TNewResult>(continuationFunction, state, scheduler, default(CancellationToken), TaskContinuationOptions.None, ref stackMark);
+ return ContinueWith<TNewResult>(continuationFunction, state, scheduler, default(CancellationToken), TaskContinuationOptions.None);
}
/// <summary>
@@ -1472,12 +1370,10 @@ namespace System.Threading.Tasks
/// The <paramref name="continuationOptions"/> argument specifies an invalid value for <see
/// cref="T:System.Threading.Tasks.TaskContinuationOptions">TaskContinuationOptions</see>.
/// </exception>
- [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var have to be marked non-inlineable
public Task<TNewResult> ContinueWith<TNewResult>(Func<Task<TResult>, Object, TNewResult> continuationFunction, Object state,
TaskContinuationOptions continuationOptions)
{
- StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
- return ContinueWith<TNewResult>(continuationFunction, state, TaskScheduler.Current, default(CancellationToken), continuationOptions, ref stackMark);
+ return ContinueWith<TNewResult>(continuationFunction, state, TaskScheduler.Current, default(CancellationToken), continuationOptions);
}
/// <summary>
@@ -1529,17 +1425,15 @@ namespace System.Threading.Tasks
/// <exception cref="T:System.ObjectDisposedException">The provided <see cref="System.Threading.CancellationToken">CancellationToken</see>
/// has already been disposed.
/// </exception>
- [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var have to be marked non-inlineable
public Task<TNewResult> ContinueWith<TNewResult>(Func<Task<TResult>, Object, TNewResult> continuationFunction, Object state,
CancellationToken cancellationToken, TaskContinuationOptions continuationOptions, TaskScheduler scheduler)
{
- StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
- return ContinueWith<TNewResult>(continuationFunction, state, scheduler, cancellationToken, continuationOptions, ref stackMark);
+ return ContinueWith<TNewResult>(continuationFunction, state, scheduler, cancellationToken, continuationOptions);
}
// Same as the above overload, just with a stack mark.
internal Task<TNewResult> ContinueWith<TNewResult>(Func<Task<TResult>, Object, TNewResult> continuationFunction, Object state,
- TaskScheduler scheduler, CancellationToken cancellationToken, TaskContinuationOptions continuationOptions, ref StackCrawlMark stackMark)
+ TaskScheduler scheduler, CancellationToken cancellationToken, TaskContinuationOptions continuationOptions)
{
if (continuationFunction == null)
{
@@ -1560,8 +1454,7 @@ namespace System.Threading.Tasks
Task<TNewResult> continuationFuture = new ContinuationResultTaskFromResultTask<TResult,TNewResult>(
this, continuationFunction, state,
- creationOptions, internalOptions,
- ref stackMark
+ creationOptions, internalOptions
);
// Register the continuation. If synchronous execution is requested, this may
diff --git a/src/mscorlib/src/System/Threading/Thread.cs b/src/mscorlib/src/System/Threading/Thread.cs
index 8294c20c4d..d28002729a 100644
--- a/src/mscorlib/src/System/Threading/Thread.cs
+++ b/src/mscorlib/src/System/Threading/Thread.cs
@@ -19,8 +19,6 @@ namespace System.Threading {
using System.Runtime;
using System.Runtime.InteropServices;
using System;
- using System.Security.Permissions;
- using System.Security.Principal;
using System.Globalization;
using System.Collections.Generic;
using System.Runtime.Serialization;
@@ -103,11 +101,7 @@ namespace System.Threading {
}
}
- // deliberately not [serializable]
- [ClassInterface(ClassInterfaceType.None)]
- [ComDefaultInterface(typeof(_Thread))]
- [System.Runtime.InteropServices.ComVisible(true)]
- public sealed class Thread : RuntimeThread, _Thread
+ public sealed class Thread : RuntimeThread
{
/*=========================================================================
** Data accessed from managed code that needs to be defined in
@@ -120,10 +114,6 @@ namespace System.Threading {
private String m_Name;
private Delegate m_Delegate; // Delegate
-#if FEATURE_LEAK_CULTURE_INFO
- private CultureInfo m_CurrentCulture;
- private CultureInfo m_CurrentUICulture;
-#endif
private Object m_ThreadStartArg;
/*=========================================================================
@@ -149,47 +139,25 @@ namespace System.Threading {
private bool m_ForbidExecutionContextMutation;
#endif
- /*=========================================================================
- ** This manager is responsible for storing the global data that is
- ** shared amongst all the thread local stores.
- =========================================================================*/
- static private LocalDataStoreMgr s_LocalDataStoreMgr;
-
- /*=========================================================================
- ** Thread-local data store
- =========================================================================*/
- [ThreadStatic]
- static private LocalDataStoreHolder s_LocalDataStore;
-
// Do not move! Order of above fields needs to be preserved for alignment
// with native code
// See code:#threadCultureInfo
-#if !FEATURE_LEAK_CULTURE_INFO
[ThreadStatic]
internal static CultureInfo m_CurrentCulture;
[ThreadStatic]
internal static CultureInfo m_CurrentUICulture;
-#endif
static AsyncLocal<CultureInfo> s_asyncLocalCurrentCulture;
static AsyncLocal<CultureInfo> s_asyncLocalCurrentUICulture;
static void AsyncLocalSetCurrentCulture(AsyncLocalValueChangedArgs<CultureInfo> args)
{
-#if FEATURE_LEAK_CULTURE_INFO
- Thread.CurrentThread.m_CurrentCulture = args.CurrentValue;
-#else
m_CurrentCulture = args.CurrentValue;
-#endif // FEATURE_LEAK_CULTURE_INFO
}
static void AsyncLocalSetCurrentUICulture(AsyncLocalValueChangedArgs<CultureInfo> args)
{
-#if FEATURE_LEAK_CULTURE_INFO
- Thread.CurrentThread.m_CurrentUICulture = args.CurrentValue;
-#else
m_CurrentUICulture = args.CurrentValue;
-#endif // FEATURE_LEAK_CULTURE_INFO
}
// Adding an empty default ctor for annotation purposes
@@ -209,7 +177,7 @@ namespace System.Threading {
SetStartHelper((Delegate)start,0); //0 will setup Thread with default stackSize
}
- public Thread(ThreadStart start, int maxStackSize) {
+ internal Thread(ThreadStart start, int maxStackSize) {
if (start == null) {
throw new ArgumentNullException(nameof(start));
}
@@ -226,7 +194,7 @@ namespace System.Threading {
SetStartHelper((Delegate)start, 0);
}
- public Thread(ParameterizedThreadStart start, int maxStackSize) {
+ internal Thread(ParameterizedThreadStart start, int maxStackSize) {
if (start == null) {
throw new ArgumentNullException(nameof(start));
}
@@ -236,7 +204,6 @@ namespace System.Threading {
SetStartHelper((Delegate)start, maxStackSize);
}
- [ComVisible(false)]
public override int GetHashCode()
{
return m_ManagedThreadId;
@@ -244,7 +211,6 @@ namespace System.Threading {
extern public new int ManagedThreadId
{
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
get;
}
@@ -310,14 +276,11 @@ namespace System.Threading {
// If we reach here with a null delegate, something is broken. But we'll let the StartInternal method take care of
// reporting an error. Just make sure we dont try to dereference a null delegate.
ThreadHelper t = (ThreadHelper)(m_Delegate.Target);
- ExecutionContext ec = ExecutionContext.Capture(
- ref stackMark,
- ExecutionContext.CaptureOptions.IgnoreSyncCtx);
+ ExecutionContext ec = ExecutionContext.Capture();
t.SetExecutionContextHelper(ec);
}
- IPrincipal principal = null;
- StartInternal(principal, ref stackMark);
+ StartInternal(ref stackMark);
}
internal ExecutionContext ExecutionContext
@@ -333,30 +296,7 @@ namespace System.Threading {
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
- private extern void StartInternal(IPrincipal principal, ref StackCrawlMark stackMark);
-#if FEATURE_COMPRESSEDSTACK
- /// <internalonly/>
- [DynamicSecurityMethodAttribute()]
- [Obsolete("Thread.SetCompressedStack is no longer supported. Please use the System.Threading.CompressedStack class")]
- public void SetCompressedStack( CompressedStack stack )
- {
- throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_ThreadAPIsNotSupported"));
- }
-
- [MethodImplAttribute(MethodImplOptions.InternalCall), ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
- internal extern IntPtr SetAppDomainStack( SafeCompressedStackHandle csHandle);
-
- [MethodImplAttribute(MethodImplOptions.InternalCall), ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
- internal extern void RestoreAppDomainStack( IntPtr appDomainStack);
-
-
- /// <internalonly/>
- [Obsolete("Thread.GetCompressedStack is no longer supported. Please use the System.Threading.CompressedStack class")]
- public CompressedStack GetCompressedStack()
- {
- throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_ThreadAPIsNotSupported"));
- }
-#endif // #if FEATURE_COMPRESSEDSTACK
+ private extern void StartInternal(ref StackCrawlMark stackMark);
// Helper method to get a logical thread ID for StringBuilder (for
@@ -366,43 +306,6 @@ namespace System.Threading {
internal extern static IntPtr InternalGetCurrentThread();
/*=========================================================================
- ** Raises a ThreadAbortException in the thread, which usually
- ** results in the thread's death. The ThreadAbortException is a special
- ** exception that is not catchable. The finally clauses of all try
- ** statements will be executed before the thread dies. This includes the
- ** finally that a thread might be executing at the moment the Abort is raised.
- ** The thread is not stopped immediately--you must Join on the
- ** thread to guarantee it has stopped.
- ** It is possible for a thread to do an unbounded amount of computation in
- ** the finally's and thus indefinitely delay the threads death.
- ** If Abort() is called on a thread that has not been started, the thread
- ** will abort when Start() is called.
- ** If Abort is called twice on the same thread, a DuplicateThreadAbort
- ** exception is thrown.
- =========================================================================*/
-#pragma warning disable 618
- [SecurityPermissionAttribute(SecurityAction.Demand, ControlThread = true)]
-#pragma warning restore 618
- public void Abort()
- {
- AbortInternal();
- }
-
- // Internal helper (since we can't place security demands on
- // ecalls/fcalls).
- [MethodImplAttribute(MethodImplOptions.InternalCall)]
- private extern void AbortInternal();
-
- public bool Join(TimeSpan timeout)
- {
- long tm = (long)timeout.TotalMilliseconds;
- if (tm < -1 || tm > (long) Int32.MaxValue)
- throw new ArgumentOutOfRangeException(nameof(timeout), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegOrNegative1"));
-
- return Join((int)tm);
- }
-
- /*=========================================================================
** Suspends the current thread for timeout milliseconds. If timeout == 0,
** forces the thread to give up the remainer of its timeslice. If timeout
** == Timeout.Infinite, no timeout will occur.
@@ -435,10 +338,8 @@ namespace System.Threading {
a explict busy loop because the hardware can be informed that it is busy waiting. */
[MethodImplAttribute(MethodImplOptions.InternalCall)]
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
private static extern void SpinWaitInternal(int iterations);
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
public static new void SpinWait(int iterations)
{
SpinWaitInternal(iterations);
@@ -446,17 +347,14 @@ namespace System.Threading {
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
private static extern bool YieldInternal();
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
- public static new bool Yield()
+ internal static new bool Yield()
{
return YieldInternal();
}
public static new Thread CurrentThread {
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
get {
Contract.Ensures(Contract.Result<Thread>() != null);
return GetCurrentThreadNative();
@@ -467,8 +365,7 @@ namespace System.Threading {
private void SetStartHelper(Delegate start, int maxStackSize)
{
- // We only support default stacks in CoreCLR
- Debug.Assert(maxStackSize == 0);
+ Debug.Assert(maxStackSize >= 0);
ThreadHelper threadStartCallBack = new ThreadHelper(start);
if(start is ThreadStart)
@@ -481,10 +378,6 @@ namespace System.Threading {
}
}
- [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
- [SuppressUnmanagedCodeSecurity]
- private static extern ulong GetProcessDefaultStackSize();
-
/*=========================================================================
** PRIVATE Sets the IThreadable interface for the thread. Assumes that
** start != null.
@@ -495,122 +388,21 @@ namespace System.Threading {
/*=========================================================================
** Clean up the thread when it goes away.
=========================================================================*/
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
~Thread()
{
// Delegate to the unmanaged portion.
InternalFinalize();
}
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private extern void InternalFinalize();
#if FEATURE_COMINTEROP_APARTMENT_SUPPORT
- /*=========================================================================
- ** An unstarted thread can be marked to indicate that it will host a
- ** single-threaded or multi-threaded apartment.
- **
- ** Exceptions: ArgumentException if state is not a valid apartment state
- ** (ApartmentSTA or ApartmentMTA).
- =========================================================================*/
- [Obsolete("The ApartmentState property has been deprecated. Use GetApartmentState, SetApartmentState or TrySetApartmentState instead.", false)]
- public ApartmentState ApartmentState
- {
- get
- {
- return (ApartmentState)GetApartmentStateNative();
- }
-
- set
- {
- SetApartmentStateNative((int)value, true);
- }
- }
-
- public void SetApartmentState(ApartmentState state)
- {
- bool result = SetApartmentStateHelper(state, true);
- if (!result)
- throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_ApartmentStateSwitchFailed"));
- }
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private extern void StartupSetApartmentStateInternal();
#endif // FEATURE_COMINTEROP_APARTMENT_SUPPORT
- /*=========================================================================
- ** Allocates an un-named data slot. The slot is allocated on ALL the
- ** threads.
- =========================================================================*/
- public static LocalDataStoreSlot AllocateDataSlot()
- {
- return LocalDataStoreManager.AllocateDataSlot();
- }
-
- /*=========================================================================
- ** Allocates a named data slot. The slot is allocated on ALL the
- ** threads. Named data slots are "public" and can be manipulated by
- ** anyone.
- =========================================================================*/
- public static LocalDataStoreSlot AllocateNamedDataSlot(String name)
- {
- return LocalDataStoreManager.AllocateNamedDataSlot(name);
- }
-
- /*=========================================================================
- ** Looks up a named data slot. If the name has not been used, a new slot is
- ** allocated. Named data slots are "public" and can be manipulated by
- ** anyone.
- =========================================================================*/
- public static LocalDataStoreSlot GetNamedDataSlot(String name)
- {
- return LocalDataStoreManager.GetNamedDataSlot(name);
- }
-
- /*=========================================================================
- ** Frees a named data slot. The slot is allocated on ALL the
- ** threads. Named data slots are "public" and can be manipulated by
- ** anyone.
- =========================================================================*/
- public static void FreeNamedDataSlot(String name)
- {
- LocalDataStoreManager.FreeNamedDataSlot(name);
- }
-
- /*=========================================================================
- ** Retrieves the value from the specified slot on the current thread, for that thread's current domain.
- =========================================================================*/
- public static Object GetData(LocalDataStoreSlot slot)
- {
- LocalDataStoreHolder dls = s_LocalDataStore;
- if (dls == null)
- {
- // Make sure to validate the slot even if we take the quick path
- LocalDataStoreManager.ValidateSlot(slot);
- return null;
- }
-
- return dls.Store.GetData(slot);
- }
-
- /*=========================================================================
- ** Sets the data in the specified slot on the currently running thread, for that thread's current domain.
- =========================================================================*/
- public static void SetData(LocalDataStoreSlot slot, Object data)
- {
- LocalDataStoreHolder dls = s_LocalDataStore;
-
- // Create new DLS if one hasn't been created for this domain for this thread
- if (dls == null) {
- dls = LocalDataStoreManager.CreateLocalDataStore();
- s_LocalDataStore = dls;
- }
-
- dls.Store.SetData(slot, data);
- }
-
-
// #threadCultureInfo
//
// Background:
@@ -623,10 +415,6 @@ namespace System.Threading {
// - thread instance member cultures (CurrentCulture and CurrentUICulture)
// confined within AppDomains
// - changes to these properties don't affect the underlying native thread
- //
- // Ifdef:
- // FEATURE_LEAK_CULTURE_INFO : CultureInfos can leak across AppDomains, not
- // enabled in Silverlight
//
// Implementation notes:
// In Silverlight, culture members thread static (per Thread, per AppDomain).
@@ -636,10 +424,6 @@ namespace System.Threading {
// now need to special case resource lookup for mscorlib, which transitions to the
// default domain to lookup resources. See Environment.cs for more details.
//
-#if FEATURE_LEAK_CULTURE_INFO
- [MethodImplAttribute(MethodImplOptions.InternalCall)]
- static extern private bool nativeGetSafeCulture(Thread t, int appDomainId, bool isUI, ref CultureInfo safeCulture);
-#endif // FEATURE_LEAK_CULTURE_INFO
// As the culture can be customized object then we cannot hold any
// reference to it before we check if it is safe because the app domain
@@ -680,16 +464,8 @@ namespace System.Threading {
// If you add more pre-conditions to this method, check to see if you also need to
// add them to CultureInfo.DefaultThreadCurrentUICulture.set.
-#if FEATURE_LEAK_CULTURE_INFO
- if (nativeSetThreadUILocale(value.SortName) == false)
- {
- throw new ArgumentException(Environment.GetResourceString("Argument_InvalidResourceCultureName", value.Name));
- }
- value.StartCrossDomainTracking();
-#else
if (m_CurrentUICulture == null && m_CurrentCulture == null)
nativeInitCultureAccessors();
-#endif
if (!AppContextSwitches.NoAsyncCurrentCulture)
{
@@ -708,8 +484,6 @@ namespace System.Threading {
}
}
-#if FEATURE_LEAK_CULTURE_INFO
-#endif
internal CultureInfo GetCurrentUICultureNoAppX() {
Contract.Ensures(Contract.Result<CultureInfo>() != null);
@@ -725,25 +499,11 @@ namespace System.Threading {
return (appDomainDefaultUICulture != null ? appDomainDefaultUICulture : CultureInfo.UserDefaultUICulture);
}
-#if FEATURE_LEAK_CULTURE_INFO
- CultureInfo culture = null;
-
- if (!nativeGetSafeCulture(this, GetDomainID(), true, ref culture) || culture == null) {
- return CultureInfo.UserDefaultUICulture;
- }
-
- return culture;
-#else
return m_CurrentUICulture;
#endif
-#endif
}
// This returns the exposed context for a given context ID.
-#if FEATURE_LEAK_CULTURE_INFO
- [MethodImplAttribute(MethodImplOptions.InternalCall)]
- static extern private bool nativeSetThreadUILocale(String locale);
-#endif
// As the culture can be customized object then we cannot hold any
// reference to it before we check if it is safe because the app domain
@@ -772,8 +532,6 @@ namespace System.Threading {
}
}
-#if FEATURE_LEAK_CULTURE_INFO
-#endif
set {
if (null==value) {
throw new ArgumentNullException(nameof(value));
@@ -783,16 +541,8 @@ namespace System.Threading {
// If you add more pre-conditions to this method, check to see if you also need to
// add them to CultureInfo.DefaultThreadCurrentCulture.set.
-#if FEATURE_LEAK_CULTURE_INFO
- //If we can't set the nativeThreadLocale, we'll just let it stay
- //at whatever value it had before. This allows people who use
- //just managed code not to be limited by the underlying OS.
- CultureInfo.nativeSetThreadLocale(value.SortName);
- value.StartCrossDomainTracking();
-#else
if (m_CurrentCulture == null && m_CurrentUICulture == null)
nativeInitCultureAccessors();
-#endif
if (!AppContextSwitches.NoAsyncCurrentCulture)
{
@@ -810,8 +560,6 @@ namespace System.Threading {
}
}
-#if FEATURE_LEAK_CULTURE_INFO
-#endif
private CultureInfo GetCurrentCultureNoAppX() {
#if FEATURE_COREFX_GLOBALIZATION
@@ -826,25 +574,13 @@ namespace System.Threading {
return (appDomainDefaultCulture != null ? appDomainDefaultCulture : CultureInfo.UserDefaultCulture);
}
-#if FEATURE_LEAK_CULTURE_INFO
- CultureInfo culture = null;
-
- if (!nativeGetSafeCulture(this, GetDomainID(), false, ref culture) || culture == null) {
- return CultureInfo.UserDefaultCulture;
- }
-
- return culture;
-#else
return m_CurrentCulture;
#endif
-#endif
}
-#if !FEATURE_LEAK_CULTURE_INFO
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private static extern void nativeInitCultureAccessors();
-#endif
/*======================================================================
** Returns the current domain in which current thread is running.
@@ -855,7 +591,7 @@ namespace System.Threading {
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern AppDomain GetFastDomainInternal();
- public static AppDomain GetDomain()
+ internal static AppDomain GetDomain()
{
Contract.Ensures(Contract.Result<AppDomain>() != null);
@@ -872,7 +608,7 @@ namespace System.Threading {
/*
* This returns a unique id to identify an appdomain.
*/
- public static int GetDomainID()
+ internal static int GetDomainID()
{
return GetDomain().GetId();
}
@@ -899,267 +635,9 @@ namespace System.Threading {
[SuppressUnmanagedCodeSecurity]
private static extern void InformThreadNameChange(ThreadHandle t, String name, int len);
- internal Object AbortReason {
- get {
- object result = null;
- try
- {
- result = GetAbortReason();
- }
- catch (Exception e)
- {
- throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_ExceptionStateCrossAppDomain"), e);
- }
- return result;
- }
- set { SetAbortReason(value); }
- }
-
- /*=========================================================================
- ** Volatile Read & Write and MemoryBarrier methods.
- ** Provides the ability to read and write values ensuring that the values
- ** are read/written each time they are accessed.
- =========================================================================*/
-
- [MethodImplAttribute(MethodImplOptions.NoInlining)] // disable optimizations
- public static byte VolatileRead(ref byte address)
- {
- byte ret = address;
- MemoryBarrier(); // Call MemoryBarrier to ensure the proper semantic in a portable way.
- return ret;
- }
-
- [MethodImplAttribute(MethodImplOptions.NoInlining)] // disable optimizations
- public static short VolatileRead(ref short address)
- {
- short ret = address;
- MemoryBarrier(); // Call MemoryBarrier to ensure the proper semantic in a portable way.
- return ret;
- }
-
- [MethodImplAttribute(MethodImplOptions.NoInlining)] // disable optimizations
- public static int VolatileRead(ref int address)
- {
- int ret = address;
- MemoryBarrier(); // Call MemoryBarrier to ensure the proper semantic in a portable way.
- return ret;
- }
-
- [MethodImplAttribute(MethodImplOptions.NoInlining)] // disable optimizations
- public static long VolatileRead(ref long address)
- {
- long ret = address;
- MemoryBarrier(); // Call MemoryBarrier to ensure the proper semantic in a portable way.
- return ret;
- }
-
- [CLSCompliant(false)]
- [MethodImplAttribute(MethodImplOptions.NoInlining)] // disable optimizations
- public static sbyte VolatileRead(ref sbyte address)
- {
- sbyte ret = address;
- MemoryBarrier(); // Call MemoryBarrier to ensure the proper semantic in a portable way.
- return ret;
- }
-
- [CLSCompliant(false)]
- [MethodImplAttribute(MethodImplOptions.NoInlining)] // disable optimizations
- public static ushort VolatileRead(ref ushort address)
- {
- ushort ret = address;
- MemoryBarrier(); // Call MemoryBarrier to ensure the proper semantic in a portable way.
- return ret;
- }
-
- [CLSCompliant(false)]
- [MethodImplAttribute(MethodImplOptions.NoInlining)] // disable optimizations
- public static uint VolatileRead(ref uint address)
- {
- uint ret = address;
- MemoryBarrier(); // Call MemoryBarrier to ensure the proper semantic in a portable way.
- return ret;
- }
-
- [MethodImplAttribute(MethodImplOptions.NoInlining)] // disable optimizations
- public static IntPtr VolatileRead(ref IntPtr address)
- {
- IntPtr ret = address;
- MemoryBarrier(); // Call MemoryBarrier to ensure the proper semantic in a portable way.
- return ret;
- }
-
- [CLSCompliant(false)]
- [MethodImplAttribute(MethodImplOptions.NoInlining)] // disable optimizations
- public static UIntPtr VolatileRead(ref UIntPtr address)
- {
- UIntPtr ret = address;
- MemoryBarrier(); // Call MemoryBarrier to ensure the proper semantic in a portable way.
- return ret;
- }
-
- [CLSCompliant(false)]
- [MethodImplAttribute(MethodImplOptions.NoInlining)] // disable optimizations
- public static ulong VolatileRead(ref ulong address)
- {
- ulong ret = address;
- MemoryBarrier(); // Call MemoryBarrier to ensure the proper semantic in a portable way.
- return ret;
- }
-
- [MethodImplAttribute(MethodImplOptions.NoInlining)] // disable optimizations
- public static float VolatileRead(ref float address)
- {
- float ret = address;
- MemoryBarrier(); // Call MemoryBarrier to ensure the proper semantic in a portable way.
- return ret;
- }
-
- [MethodImplAttribute(MethodImplOptions.NoInlining)] // disable optimizations
- public static double VolatileRead(ref double address)
- {
- double ret = address;
- MemoryBarrier(); // Call MemoryBarrier to ensure the proper semantic in a portable way.
- return ret;
- }
-
- [MethodImplAttribute(MethodImplOptions.NoInlining)] // disable optimizations
- public static Object VolatileRead(ref Object address)
- {
- Object ret = address;
- MemoryBarrier(); // Call MemoryBarrier to ensure the proper semantic in a portable way.
- return ret;
- }
-
- [MethodImplAttribute(MethodImplOptions.NoInlining)] // disable optimizations
- public static void VolatileWrite(ref byte address, byte value)
- {
- MemoryBarrier(); // Call MemoryBarrier to ensure the proper semantic in a portable way.
- address = value;
- }
-
- [MethodImplAttribute(MethodImplOptions.NoInlining)] // disable optimizations
- public static void VolatileWrite(ref short address, short value)
- {
- MemoryBarrier(); // Call MemoryBarrier to ensure the proper semantic in a portable way.
- address = value;
- }
-
- [MethodImplAttribute(MethodImplOptions.NoInlining)] // disable optimizations
- public static void VolatileWrite(ref int address, int value)
- {
- MemoryBarrier(); // Call MemoryBarrier to ensure the proper semantic in a portable way.
- address = value;
- }
-
- [MethodImplAttribute(MethodImplOptions.NoInlining)] // disable optimizations
- public static void VolatileWrite(ref long address, long value)
- {
- MemoryBarrier(); // Call MemoryBarrier to ensure the proper semantic in a portable way.
- address = value;
- }
-
- [CLSCompliant(false)]
- [MethodImplAttribute(MethodImplOptions.NoInlining)] // disable optimizations
- public static void VolatileWrite(ref sbyte address, sbyte value)
- {
- MemoryBarrier(); // Call MemoryBarrier to ensure the proper semantic in a portable way.
- address = value;
- }
-
- [CLSCompliant(false)]
- [MethodImplAttribute(MethodImplOptions.NoInlining)] // disable optimizations
- public static void VolatileWrite(ref ushort address, ushort value)
- {
- MemoryBarrier(); // Call MemoryBarrier to ensure the proper semantic in a portable way.
- address = value;
- }
-
- [CLSCompliant(false)]
- [MethodImplAttribute(MethodImplOptions.NoInlining)] // disable optimizations
- public static void VolatileWrite(ref uint address, uint value)
- {
- MemoryBarrier(); // Call MemoryBarrier to ensure the proper semantic in a portable way.
- address = value;
- }
-
- [MethodImplAttribute(MethodImplOptions.NoInlining)] // disable optimizations
- public static void VolatileWrite(ref IntPtr address, IntPtr value)
- {
- MemoryBarrier(); // Call MemoryBarrier to ensure the proper semantic in a portable way.
- address = value;
- }
-
- [CLSCompliant(false)]
- [MethodImplAttribute(MethodImplOptions.NoInlining)] // disable optimizations
- public static void VolatileWrite(ref UIntPtr address, UIntPtr value)
- {
- MemoryBarrier(); // Call MemoryBarrier to ensure the proper semantic in a portable way.
- address = value;
- }
-
- [CLSCompliant(false)]
- [MethodImplAttribute(MethodImplOptions.NoInlining)] // disable optimizations
- public static void VolatileWrite(ref ulong address, ulong value)
- {
- MemoryBarrier(); // Call MemoryBarrier to ensure the proper semantic in a portable way.
- address = value;
- }
-
- [MethodImplAttribute(MethodImplOptions.NoInlining)] // disable optimizations
- public static void VolatileWrite(ref float address, float value)
- {
- MemoryBarrier(); // Call MemoryBarrier to ensure the proper semantic in a portable way.
- address = value;
- }
-
- [MethodImplAttribute(MethodImplOptions.NoInlining)] // disable optimizations
- public static void VolatileWrite(ref double address, double value)
- {
- MemoryBarrier(); // Call MemoryBarrier to ensure the proper semantic in a portable way.
- address = value;
- }
-
- [MethodImplAttribute(MethodImplOptions.NoInlining)] // disable optimizations
- public static void VolatileWrite(ref Object address, Object value)
- {
- MemoryBarrier(); // Call MemoryBarrier to ensure the proper semantic in a portable way.
- address = value;
- }
-
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public static extern void MemoryBarrier();
- private static LocalDataStoreMgr LocalDataStoreManager
- {
- get
- {
- if (s_LocalDataStoreMgr == null)
- {
- Interlocked.CompareExchange(ref s_LocalDataStoreMgr, new LocalDataStoreMgr(), null);
- }
-
- return s_LocalDataStoreMgr;
- }
- }
-
- // 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).
- [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.
- [MethodImplAttribute(MethodImplOptions.InternalCall)]
- internal extern Object GetAbortReason();
-
- // Helper function to clear the AbortReason. Takes care of
- // AppDomain related cleanup if required.
- [MethodImplAttribute(MethodImplOptions.InternalCall)]
- internal extern void ClearAbortReason();
-
-
} // End of class Thread
// declaring a local var of this enum type and passing it by ref into a function that needs to do a
diff --git a/src/mscorlib/src/System/Threading/ThreadAbortException.cs b/src/mscorlib/src/System/Threading/ThreadAbortException.cs
index 09ad4e1bd6..25925048bf 100644
--- a/src/mscorlib/src/System/Threading/ThreadAbortException.cs
+++ b/src/mscorlib/src/System/Threading/ThreadAbortException.cs
@@ -21,7 +21,6 @@ namespace System.Threading
using System.Runtime.Serialization;
using System.Runtime.CompilerServices;
- [System.Runtime.InteropServices.ComVisible(true)]
[Serializable]
public sealed class ThreadAbortException : SystemException
{
@@ -36,10 +35,5 @@ namespace System.Threading
: base(info, context)
{
}
-
- public Object ExceptionState
- {
- get {return Thread.CurrentThread.AbortReason;}
- }
}
}
diff --git a/src/mscorlib/src/System/Threading/ThreadInterruptedException.cs b/src/mscorlib/src/System/Threading/ThreadInterruptedException.cs
index 0056611955..71c09649e2 100644
--- a/src/mscorlib/src/System/Threading/ThreadInterruptedException.cs
+++ b/src/mscorlib/src/System/Threading/ThreadInterruptedException.cs
@@ -17,7 +17,6 @@ namespace System.Threading {
using System;
using System.Runtime.Serialization;
- [System.Runtime.InteropServices.ComVisible(true)]
[Serializable]
public class ThreadInterruptedException : SystemException {
public ThreadInterruptedException()
diff --git a/src/mscorlib/src/System/Threading/ThreadLocal.cs b/src/mscorlib/src/System/Threading/ThreadLocal.cs
index 2b996cb34d..eedf6d0c81 100644
--- a/src/mscorlib/src/System/Threading/ThreadLocal.cs
+++ b/src/mscorlib/src/System/Threading/ThreadLocal.cs
@@ -16,7 +16,6 @@
// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
using System.Collections.Generic;
-using System.Security.Permissions;
using System.Diagnostics;
using System.Diagnostics.Contracts;
diff --git a/src/mscorlib/src/System/Threading/ThreadPool.cs b/src/mscorlib/src/System/Threading/ThreadPool.cs
index 451b15d22f..adf0615819 100644
--- a/src/mscorlib/src/System/Threading/ThreadPool.cs
+++ b/src/mscorlib/src/System/Threading/ThreadPool.cs
@@ -11,36 +11,20 @@
**
=============================================================================*/
-#pragma warning disable 0420
-
-/*
- * Below you'll notice two sets of APIs that are separated by the
- * use of 'Unsafe' in their names. The unsafe versions are called
- * that because they do not propagate the calling stack onto the
- * worker thread. This allows code to lose the calling stack and
- * thereby elevate its security privileges. Note that this operation
- * is much akin to the combined ability to control security policy
- * and control security evidence. With these privileges, a person
- * can gain the right to load assemblies that are fully trusted which
- * then assert full trust and can call any code they want regardless
- * of the previous stack information.
- */
+using System.Collections.Concurrent;
+using System.Collections.Generic;
+using System.Diagnostics;
+using System.Diagnostics.CodeAnalysis;
+using System.Diagnostics.Contracts;
+using System.Diagnostics.Tracing;
+using System.Runtime.CompilerServices;
+using System.Runtime.ConstrainedExecution;
+using System.Runtime.InteropServices;
+using System.Security;
+using Microsoft.Win32;
namespace System.Threading
{
- using System.Security;
- using System.Security.Permissions;
- using System;
- using Microsoft.Win32;
- using System.Runtime.CompilerServices;
- using System.Runtime.ConstrainedExecution;
- using System.Runtime.InteropServices;
- using System.Collections.Generic;
- using System.Diagnostics;
- using System.Diagnostics.Contracts;
- using System.Diagnostics.CodeAnalysis;
- using System.Diagnostics.Tracing;
-
internal static class ThreadPoolGlobals
{
//Per-appDomain quantum (in ms) for which the thread keeps processing
@@ -55,78 +39,76 @@ namespace System.Threading
public static bool enableWorkerTracking;
public static readonly ThreadPoolWorkQueue workQueue = new ThreadPoolWorkQueue();
-
- static ThreadPoolGlobals()
- {
- }
}
internal sealed class ThreadPoolWorkQueue
{
- // Simple sparsely populated array to allow lock-free reading.
- internal class SparseArray<T> where T : class
+ internal static class WorkStealingQueueList
{
- private volatile T[] m_array;
+ private static volatile WorkStealingQueue[] _queues = new WorkStealingQueue[0];
- internal SparseArray(int initialSize)
- {
- m_array = new T[initialSize];
- }
+ public static WorkStealingQueue[] Queues => _queues;
- internal T[] Current
- {
- get { return m_array; }
- }
-
- internal int Add(T e)
+ public static void Add(WorkStealingQueue queue)
{
+ Debug.Assert(queue != null);
while (true)
{
- T[] array = m_array;
- lock (array)
+ WorkStealingQueue[] oldQueues = _queues;
+ Debug.Assert(Array.IndexOf(oldQueues, queue) == -1);
+
+ var newQueues = new WorkStealingQueue[oldQueues.Length + 1];
+ Array.Copy(oldQueues, 0, newQueues, 0, oldQueues.Length);
+ newQueues[newQueues.Length - 1] = queue;
+ if (Interlocked.CompareExchange(ref _queues, newQueues, oldQueues) == oldQueues)
{
- for (int i = 0; i < array.Length; i++)
- {
- if (array[i] == null)
- {
- Volatile.Write(ref array[i], e);
- return i;
- }
- else if (i == array.Length - 1)
- {
- // Must resize. If there was a race condition, we start over again.
- if (array != m_array)
- continue;
-
- T[] newArray = new T[array.Length * 2];
- Array.Copy(array, newArray, i + 1);
- newArray[i + 1] = e;
- m_array = newArray;
- return i + 1;
- }
- }
+ break;
}
}
}
- internal void Remove(T e)
+ public static void Remove(WorkStealingQueue queue)
{
- T[] array = m_array;
- lock (array)
+ Debug.Assert(queue != null);
+ while (true)
{
- for (int i = 0; i < m_array.Length; i++)
+ WorkStealingQueue[] oldQueues = _queues;
+ if (oldQueues.Length == 0)
{
- if (m_array[i] == e)
- {
- Volatile.Write(ref m_array[i], null);
- break;
- }
+ return;
+ }
+
+ int pos = Array.IndexOf(oldQueues, queue);
+ if (pos == -1)
+ {
+ Debug.Fail("Should have found the queue");
+ return;
+ }
+
+ var newQueues = new WorkStealingQueue[oldQueues.Length - 1];
+ if (pos == 0)
+ {
+ Array.Copy(oldQueues, 1, newQueues, 0, newQueues.Length);
+ }
+ else if (pos == oldQueues.Length - 1)
+ {
+ Array.Copy(oldQueues, 0, newQueues, 0, newQueues.Length);
+ }
+ else
+ {
+ Array.Copy(oldQueues, 0, newQueues, 0, pos);
+ Array.Copy(oldQueues, pos + 1, newQueues, pos, newQueues.Length - pos);
+ }
+
+ if (Interlocked.CompareExchange(ref _queues, newQueues, oldQueues) == oldQueues)
+ {
+ break;
}
}
}
}
- internal class WorkStealingQueue
+ internal sealed class WorkStealingQueue
{
private const int INITIAL_SIZE = 32;
internal volatile IThreadPoolWorkItem[] m_array = new IThreadPoolWorkItem[INITIAL_SIZE];
@@ -142,7 +124,7 @@ namespace System.Threading
private volatile int m_headIndex = START_INDEX;
private volatile int m_tailIndex = START_INDEX;
- private SpinLock m_foreignLock = new SpinLock(false);
+ private SpinLock m_foreignLock = new SpinLock(enableThreadOwnerTracking:false);
public void LocalPush(IThreadPoolWorkItem obj)
{
@@ -176,7 +158,7 @@ namespace System.Threading
finally
{
if (lockTaken)
- m_foreignLock.Exit(true);
+ m_foreignLock.Exit(useMemoryBarrier:true);
}
}
@@ -201,7 +183,7 @@ namespace System.Threading
if (count >= m_mask)
{
// We're full; expand the queue by doubling its size.
- IThreadPoolWorkItem[] newArray = new IThreadPoolWorkItem[m_array.Length << 1];
+ var newArray = new IThreadPoolWorkItem[m_array.Length << 1];
for (int i = 0; i < m_array.Length; i++)
newArray[i] = m_array[(i + head) & m_mask];
@@ -218,7 +200,7 @@ namespace System.Threading
finally
{
if (lockTaken)
- m_foreignLock.Exit(false);
+ m_foreignLock.Exit(useMemoryBarrier:false);
}
}
}
@@ -229,13 +211,9 @@ namespace System.Threading
// Fast path: check the tail. If equal, we can skip the lock.
if (m_array[(m_tailIndex - 1) & m_mask] == obj)
{
- IThreadPoolWorkItem unused;
- if (LocalPop(out unused))
- {
- Debug.Assert(unused == obj);
- return true;
- }
- return false;
+ IThreadPoolWorkItem unused = LocalPop();
+ Debug.Assert(unused == null || unused == obj);
+ return unused != null;
}
// Else, do an O(N) search for the work item. The theory of work stealing and our
@@ -276,7 +254,7 @@ namespace System.Threading
finally
{
if (lockTaken)
- m_foreignLock.Exit(false);
+ m_foreignLock.Exit(useMemoryBarrier:false);
}
}
}
@@ -284,19 +262,20 @@ namespace System.Threading
return false;
}
+ public IThreadPoolWorkItem LocalPop() => m_headIndex < m_tailIndex ? LocalPopCore() : null;
+
[SuppressMessage("Microsoft.Concurrency", "CA8001", Justification = "Reviewed for thread safety")]
- public bool LocalPop(out IThreadPoolWorkItem obj)
+ private IThreadPoolWorkItem LocalPopCore()
{
while (true)
{
- // Decrement the tail using a fence to ensure subsequent read doesn't come before.
int tail = m_tailIndex;
if (m_headIndex >= tail)
{
- obj = null;
- return false;
+ return null;
}
+ // Decrement the tail using a fence to ensure subsequent read doesn't come before.
tail -= 1;
Interlocked.Exchange(ref m_tailIndex, tail);
@@ -304,13 +283,13 @@ namespace System.Threading
if (m_headIndex <= tail)
{
int idx = tail & m_mask;
- obj = Volatile.Read(ref m_array[idx]);
+ IThreadPoolWorkItem obj = Volatile.Read(ref m_array[idx]);
// Check for nulls in the array.
if (obj == null) continue;
m_array[idx] = null;
- return true;
+ return obj;
}
else
{
@@ -324,241 +303,93 @@ namespace System.Threading
{
// Element still available. Take it.
int idx = tail & m_mask;
- obj = Volatile.Read(ref m_array[idx]);
+ IThreadPoolWorkItem obj = Volatile.Read(ref m_array[idx]);
// Check for nulls in the array.
if (obj == null) continue;
m_array[idx] = null;
- return true;
+ return obj;
}
else
{
// If we encountered a race condition and element was stolen, restore the tail.
m_tailIndex = tail + 1;
- obj = null;
- return false;
+ return null;
}
}
finally
{
if (lockTaken)
- m_foreignLock.Exit(false);
+ m_foreignLock.Exit(useMemoryBarrier:false);
}
}
}
}
- public bool TrySteal(out IThreadPoolWorkItem obj, ref bool missedSteal)
- {
- return TrySteal(out obj, ref missedSteal, 0); // no blocking by default.
- }
+ public bool CanSteal => m_headIndex < m_tailIndex;
- private bool TrySteal(out IThreadPoolWorkItem obj, ref bool missedSteal, int millisecondsTimeout)
+ public IThreadPoolWorkItem TrySteal(ref bool missedSteal)
{
- obj = null;
-
while (true)
{
- if (m_headIndex >= m_tailIndex)
- return false;
-
- bool taken = false;
- try
+ if (CanSteal)
{
- m_foreignLock.TryEnter(millisecondsTimeout, ref taken);
- if (taken)
+ bool taken = false;
+ try
{
- // Increment head, and ensure read of tail doesn't move before it (fence).
- int head = m_headIndex;
- Interlocked.Exchange(ref m_headIndex, head + 1);
-
- if (head < m_tailIndex)
+ m_foreignLock.TryEnter(ref taken);
+ if (taken)
{
- int idx = head & m_mask;
- obj = Volatile.Read(ref m_array[idx]);
+ // Increment head, and ensure read of tail doesn't move before it (fence).
+ int head = m_headIndex;
+ Interlocked.Exchange(ref m_headIndex, head + 1);
- // Check for nulls in the array.
- if (obj == null) continue;
+ if (head < m_tailIndex)
+ {
+ int idx = head & m_mask;
+ IThreadPoolWorkItem obj = Volatile.Read(ref m_array[idx]);
- m_array[idx] = null;
- return true;
- }
- else
- {
- // Failed, restore head.
- m_headIndex = head;
- obj = null;
- missedSteal = true;
+ // Check for nulls in the array.
+ if (obj == null) continue;
+
+ m_array[idx] = null;
+ return obj;
+ }
+ else
+ {
+ // Failed, restore head.
+ m_headIndex = head;
+ }
}
}
- else
+ finally
{
- missedSteal = true;
+ if (taken)
+ m_foreignLock.Exit(useMemoryBarrier:false);
}
- }
- finally
- {
- if (taken)
- m_foreignLock.Exit(false);
- }
-
- return false;
- }
- }
- }
-
- internal class QueueSegment
- {
- // Holds a segment of the queue. Enqueues/Dequeues start at element 0, and work their way up.
- internal readonly IThreadPoolWorkItem[] nodes;
- private const int QueueSegmentLength = 256;
-
- // Holds the indexes of the lowest and highest valid elements of the nodes array.
- // The low index is in the lower 16 bits, high index is in the upper 16 bits.
- // Use GetIndexes and CompareExchangeIndexes to manipulate this.
- private volatile int indexes;
-
- // The next segment in the queue.
- public volatile QueueSegment Next;
-
-
- const int SixteenBits = 0xffff;
-
- void GetIndexes(out int upper, out int lower)
- {
- int i = indexes;
- upper = (i >> 16) & SixteenBits;
- lower = i & SixteenBits;
-
- 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)
- {
- 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);
- int prevIndexes = Interlocked.CompareExchange(ref indexes, newIndexes, oldIndexes);
- prevUpper = (prevIndexes >> 16) & SixteenBits;
- prevLower = prevIndexes & SixteenBits;
- return prevIndexes == oldIndexes;
- }
-
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
- public QueueSegment()
- {
- Debug.Assert(QueueSegmentLength <= SixteenBits);
- nodes = new IThreadPoolWorkItem[QueueSegmentLength];
- }
-
-
- public bool IsUsedUp()
- {
- int upper, lower;
- GetIndexes(out upper, out lower);
- return (upper == nodes.Length) &&
- (lower == nodes.Length);
- }
-
- public bool TryEnqueue(IThreadPoolWorkItem node)
- {
- //
- // If there's room in this segment, atomically increment the upper count (to reserve
- // space for this node), then store the node.
- // Note that this leaves a window where it will look like there is data in that
- // array slot, but it hasn't been written yet. This is taken care of in TryDequeue
- // 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.
- //
- Debug.Assert(null != node);
-
- int upper, lower;
- GetIndexes(out upper, out lower);
-
- while (true)
- {
- if (upper == nodes.Length)
- return false;
-
- if (CompareExchangeIndexes(ref upper, upper + 1, ref lower, lower))
- {
- Debug.Assert(Volatile.Read(ref nodes[upper]) == null);
- Volatile.Write(ref nodes[upper], node);
- return true;
+ missedSteal = true;
}
- }
- }
-
- [SuppressMessage("Microsoft.Concurrency", "CA8001", Justification = "Reviewed for thread safety")]
- public bool TryDequeue(out IThreadPoolWorkItem node)
- {
- //
- // If there are nodes in this segment, increment the lower count, then take the
- // element we find there.
- //
- int upper, lower;
- GetIndexes(out upper, out lower);
-
- while(true)
- {
- if (lower == upper)
- {
- node = null;
- return false;
- }
-
- if (CompareExchangeIndexes(ref upper, upper, ref lower, lower + 1))
- {
- // It's possible that a concurrent call to Enqueue hasn't yet
- // written the node reference to the array. We need to spin until
- // it shows up.
- SpinWait spinner = new SpinWait();
- while ((node = Volatile.Read(ref nodes[lower])) == null)
- spinner.SpinOnce();
-
- // Null-out the reference so the object can be GC'd earlier.
- nodes[lower] = null;
- return true;
- }
+ return null;
}
}
}
- // The head and tail of the queue. We enqueue to the head, and dequeue from the tail.
- internal volatile QueueSegment queueHead;
- internal volatile QueueSegment queueTail;
internal bool loggingEnabled;
-
- internal static readonly SparseArray<WorkStealingQueue> allThreadQueues = new SparseArray<WorkStealingQueue>(16);
+ internal readonly ConcurrentQueue<IThreadPoolWorkItem> workItems = new ConcurrentQueue<IThreadPoolWorkItem>();
private volatile int numOutstandingThreadRequests = 0;
public ThreadPoolWorkQueue()
{
- queueTail = queueHead = new QueueSegment();
loggingEnabled = FrameworkEventSource.Log.IsEnabled(EventLevel.Verbose, FrameworkEventSource.Keywords.ThreadPool|FrameworkEventSource.Keywords.ThreadTransfer);
}
- public ThreadPoolWorkQueueThreadLocals EnsureCurrentThreadHasQueue()
- {
- if (null == ThreadPoolWorkQueueThreadLocals.threadLocals)
- ThreadPoolWorkQueueThreadLocals.threadLocals = new ThreadPoolWorkQueueThreadLocals(this);
- return ThreadPoolWorkQueueThreadLocals.threadLocals;
- }
+ public ThreadPoolWorkQueueThreadLocals EnsureCurrentThreadHasQueue() =>
+ ThreadPoolWorkQueueThreadLocals.threadLocals ??
+ (ThreadPoolWorkQueueThreadLocals.threadLocals = new ThreadPoolWorkQueueThreadLocals(this));
internal void EnsureThreadRequested()
{
@@ -602,12 +433,12 @@ namespace System.Threading
public void Enqueue(IThreadPoolWorkItem callback, bool forceGlobal)
{
+ if (loggingEnabled)
+ System.Diagnostics.Tracing.FrameworkEventSource.Log.ThreadPoolEnqueueWorkObject(callback);
+
ThreadPoolWorkQueueThreadLocals tl = null;
if (!forceGlobal)
tl = ThreadPoolWorkQueueThreadLocals.threadLocals;
-
- if (loggingEnabled)
- System.Diagnostics.Tracing.FrameworkEventSource.Log.ThreadPoolEnqueueWorkObject(callback);
if (null != tl)
{
@@ -615,18 +446,7 @@ namespace System.Threading
}
else
{
- QueueSegment head = queueHead;
-
- while (!head.TryEnqueue(callback))
- {
- Interlocked.CompareExchange(ref head.Next, new QueueSegment(), null);
-
- while (head.Next != null)
- {
- Interlocked.CompareExchange(ref queueHead, head.Next, head);
- head = queueHead;
- }
- }
+ workItems.Enqueue(callback);
}
EnsureThreadRequested();
@@ -635,67 +455,43 @@ namespace System.Threading
internal bool LocalFindAndPop(IThreadPoolWorkItem callback)
{
ThreadPoolWorkQueueThreadLocals tl = ThreadPoolWorkQueueThreadLocals.threadLocals;
- if (null == tl)
- return false;
-
- return tl.workStealingQueue.LocalFindAndPop(callback);
+ return tl != null && tl.workStealingQueue.LocalFindAndPop(callback);
}
- public void Dequeue(ThreadPoolWorkQueueThreadLocals tl, out IThreadPoolWorkItem callback, out bool missedSteal)
+ public IThreadPoolWorkItem Dequeue(ThreadPoolWorkQueueThreadLocals tl, ref bool missedSteal)
{
- callback = null;
- missedSteal = false;
- WorkStealingQueue wsq = tl.workStealingQueue;
+ WorkStealingQueue localWsq = tl.workStealingQueue;
+ IThreadPoolWorkItem callback;
- if (wsq.LocalPop(out callback))
- Debug.Assert(null != callback);
-
- if (null == callback)
+ if ((callback = localWsq.LocalPop()) == null && // first try the local queue
+ !workItems.TryDequeue(out callback)) // then try the global queue
{
- QueueSegment tail = queueTail;
- while (true)
- {
- if (tail.TryDequeue(out callback))
- {
- Debug.Assert(null != callback);
- break;
- }
-
- if (null == tail.Next || !tail.IsUsedUp())
- {
- break;
- }
- else
- {
- Interlocked.CompareExchange(ref queueTail, tail.Next, tail);
- tail = queueTail;
- }
- }
- }
-
- if (null == callback)
- {
- WorkStealingQueue[] otherQueues = allThreadQueues.Current;
- int c = otherQueues.Length;
+ // finally try to steal from another thread's local queue
+ WorkStealingQueue[] queues = WorkStealingQueueList.Queues;
+ int c = queues.Length;
+ Debug.Assert(c > 0, "There must at least be a queue for this thread.");
int maxIndex = c - 1;
int i = tl.random.Next(c);
while (c > 0)
{
i = (i < maxIndex) ? i + 1 : 0;
- WorkStealingQueue otherQueue = Volatile.Read(ref otherQueues[i]);
- if (otherQueue != null &&
- otherQueue != wsq &&
- otherQueue.TrySteal(out callback, ref missedSteal))
+ WorkStealingQueue otherQueue = queues[i];
+ if (otherQueue != localWsq && otherQueue.CanSteal)
{
- Debug.Assert(null != callback);
- break;
+ callback = otherQueue.TrySteal(ref missedSteal);
+ if (callback != null)
+ {
+ break;
+ }
}
c--;
}
}
+
+ return callback;
}
- static internal bool Dispatch()
+ internal static bool Dispatch()
{
var workQueue = ThreadPoolGlobals.workQueue;
//
@@ -735,85 +531,66 @@ namespace System.Threading
//
while ((Environment.TickCount - quantumStartTime) < ThreadPoolGlobals.TP_QUANTUM)
{
- //
- // Dequeue and EnsureThreadRequested must be protected from ThreadAbortException.
- // These are fast, so this will not delay aborts/AD-unloads for very long.
- //
- try { }
- finally
- {
- bool missedSteal = false;
- workQueue.Dequeue(tl, out workItem, out missedSteal);
-
- if (workItem == null)
- {
- //
- // No work. We're going to return to the VM once we leave this protected region.
- // If we missed a steal, though, there may be more work in the queue.
- // Instead of looping around and trying again, we'll just request another thread. This way
- // we won't starve other AppDomains while we spin trying to get locks, and hopefully the thread
- // that owns the contended work-stealing queue will pick up its own workitems in the meantime,
- // which will be more efficient than this thread doing it anyway.
- //
- needAnotherThread = missedSteal;
- }
- else
- {
- //
- // If we found work, there may be more work. Ask for another thread so that the other work can be processed
- // in parallel. Note that this will only ask for a max of #procs threads, so it's safe to call it for every dequeue.
- //
- workQueue.EnsureThreadRequested();
- }
- }
+ bool missedSteal = false;
+ workItem = workQueue.Dequeue(tl, ref missedSteal);
if (workItem == null)
{
+ //
+ // No work. We're going to return to the VM once we leave this protected region.
+ // If we missed a steal, though, there may be more work in the queue.
+ // Instead of looping around and trying again, we'll just request another thread. This way
+ // we won't starve other AppDomains while we spin trying to get locks, and hopefully the thread
+ // that owns the contended work-stealing queue will pick up its own workitems in the meantime,
+ // which will be more efficient than this thread doing it anyway.
+ //
+ needAnotherThread = missedSteal;
+
// Tell the VM we're returning normally, not because Hill Climbing asked us to return.
return true;
}
- else
- {
- if (workQueue.loggingEnabled)
- System.Diagnostics.Tracing.FrameworkEventSource.Log.ThreadPoolDequeueWorkObject(workItem);
- //
- // Execute the workitem outside of any finally blocks, so that it can be aborted if needed.
- //
- if (ThreadPoolGlobals.enableWorkerTracking)
+ if (workQueue.loggingEnabled)
+ System.Diagnostics.Tracing.FrameworkEventSource.Log.ThreadPoolDequeueWorkObject(workItem);
+
+ //
+ // If we found work, there may be more work. Ask for another thread so that the other work can be processed
+ // in parallel. Note that this will only ask for a max of #procs threads, so it's safe to call it for every dequeue.
+ //
+ workQueue.EnsureThreadRequested();
+
+ //
+ // Execute the workitem outside of any finally blocks, so that it can be aborted if needed.
+ //
+ if (ThreadPoolGlobals.enableWorkerTracking)
+ {
+ bool reportedStatus = false;
+ try
{
- bool reportedStatus = false;
- try
- {
- try { }
- finally
- {
- ThreadPool.ReportThreadStatus(true);
- reportedStatus = true;
- }
- workItem.ExecuteWorkItem();
- workItem = null;
- }
- finally
- {
- if (reportedStatus)
- ThreadPool.ReportThreadStatus(false);
- }
+ ThreadPool.ReportThreadStatus(isWorking: true);
+ reportedStatus = true;
+ workItem.ExecuteWorkItem();
}
- else
+ finally
{
- workItem.ExecuteWorkItem();
- workItem = null;
+ if (reportedStatus)
+ ThreadPool.ReportThreadStatus(isWorking: false);
}
-
- //
- // Notify the VM that we executed this workitem. This is also our opportunity to ask whether Hill Climbing wants
- // us to return the thread to the pool or not.
- //
- if (!ThreadPool.NotifyWorkItemComplete())
- return false;
}
+ else
+ {
+ workItem.ExecuteWorkItem();
+ }
+ workItem = null;
+
+ //
+ // Notify the VM that we executed this workitem. This is also our opportunity to ask whether Hill Climbing wants
+ // us to return the thread to the pool or not.
+ //
+ if (!ThreadPool.NotifyWorkItemComplete())
+ return false;
}
+
// If we get here, it's because our quantum expired. Tell the VM we're returning normally.
return true;
}
@@ -825,8 +602,7 @@ namespace System.Threading
// it was executed or not (in debug builds only). Task uses this to communicate the ThreadAbortException to anyone
// who waits for the task to complete.
//
- if (workItem != null)
- workItem.MarkAborted(tae);
+ workItem?.MarkAborted(tae);
//
// In this case, the VM is going to request another thread on our behalf. No need to do it twice.
@@ -845,11 +621,36 @@ 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.
- Debug.Assert(false);
+ Debug.Fail("Should never reach this point");
return true;
}
}
+ // Simple random number generator. We don't need great randomness, we just need a little and for it to be fast.
+ internal struct FastRandom // xorshift prng
+ {
+ private uint _w, _x, _y, _z;
+
+ public FastRandom(int seed)
+ {
+ _x = (uint)seed;
+ _w = 88675123;
+ _y = 362436069;
+ _z = 521288629;
+ }
+
+ public int Next(int maxValue)
+ {
+ Debug.Assert(maxValue > 0);
+
+ uint t = _x ^ (_x << 11);
+ _x = _y; _y = _z; _z = _w;
+ _w = _w ^ (_w >> 19) ^ (t ^ (t >> 8));
+
+ return (int)(_w % (uint)maxValue);
+ }
+ }
+
// Holds a WorkStealingQueue, and remmoves it from the list when this object is no longer referened.
internal sealed class ThreadPoolWorkQueueThreadLocals
{
@@ -858,13 +659,13 @@ namespace System.Threading
public readonly ThreadPoolWorkQueue workQueue;
public readonly ThreadPoolWorkQueue.WorkStealingQueue workStealingQueue;
- public readonly Random random = new Random(Thread.CurrentThread.ManagedThreadId);
+ public FastRandom random = new FastRandom(Thread.CurrentThread.ManagedThreadId); // mutable struct, do not copy or make readonly
public ThreadPoolWorkQueueThreadLocals(ThreadPoolWorkQueue tpq)
{
workQueue = tpq;
workStealingQueue = new ThreadPoolWorkQueue.WorkStealingQueue();
- ThreadPoolWorkQueue.allThreadQueues.Add(workStealingQueue);
+ ThreadPoolWorkQueue.WorkStealingQueueList.Add(workStealingQueue);
}
private void CleanUp()
@@ -873,28 +674,15 @@ namespace System.Threading
{
if (null != workQueue)
{
- bool done = false;
- while (!done)
+ IThreadPoolWorkItem cb;
+ while ((cb = workStealingQueue.LocalPop()) != null)
{
- // Ensure that we won't be aborted between LocalPop and Enqueue.
- try { }
- finally
- {
- IThreadPoolWorkItem cb = null;
- if (workStealingQueue.LocalPop(out cb))
- {
- Debug.Assert(null != cb);
- workQueue.Enqueue(cb, true);
- }
- else
- {
- done = true;
- }
- }
+ Debug.Assert(null != cb);
+ workQueue.Enqueue(cb, forceGlobal: true);
}
}
- ThreadPoolWorkQueue.allThreadQueues.Remove(workStealingQueue);
+ ThreadPoolWorkQueue.WorkStealingQueueList.Remove(workStealingQueue);
}
}
@@ -912,34 +700,19 @@ namespace System.Threading
internal sealed class RegisteredWaitHandleSafe : CriticalFinalizerObject
{
- private static IntPtr InvalidHandle
- {
- get
- {
- return Win32Native.INVALID_HANDLE_VALUE;
- }
- }
- private IntPtr registeredWaitHandle;
+ private static IntPtr InvalidHandle => Win32Native.INVALID_HANDLE_VALUE;
+ private IntPtr registeredWaitHandle = InvalidHandle;
private WaitHandle m_internalWaitObject;
private bool bReleaseNeeded = false;
private volatile int m_lock = 0;
- internal RegisteredWaitHandleSafe()
- {
- registeredWaitHandle = InvalidHandle;
- }
-
- internal IntPtr GetHandle()
- {
- return registeredWaitHandle;
- }
+ internal IntPtr GetHandle() => registeredWaitHandle;
internal void SetHandle(IntPtr handle)
{
registeredWaitHandle = handle;
}
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
internal void SetWaitObject(WaitHandle waitObject)
{
// needed for DangerousAddRef
@@ -957,7 +730,6 @@ namespace System.Threading
}
}
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
internal bool Unregister(
WaitHandle waitObject // object to be notified when all callbacks to delegates have completed
)
@@ -1009,10 +781,8 @@ namespace System.Threading
return result;
}
- private bool ValidHandle()
- {
- return (registeredWaitHandle != InvalidHandle && registeredWaitHandle != IntPtr.Zero);
- }
+ private bool ValidHandle() =>
+ registeredWaitHandle != InvalidHandle && registeredWaitHandle != IntPtr.Zero;
~RegisteredWaitHandleSafe()
{
@@ -1071,9 +841,8 @@ namespace System.Threading
private static extern bool UnregisterWaitNative(IntPtr handle, SafeHandle waitObject);
}
-[System.Runtime.InteropServices.ComVisible(true)]
public sealed class RegisteredWaitHandle : MarshalByRefObject {
- private RegisteredWaitHandleSafe internalRegisteredWait;
+ private readonly RegisteredWaitHandleSafe internalRegisteredWait;
internal RegisteredWaitHandle()
{
@@ -1090,8 +859,6 @@ namespace System.Threading
internalRegisteredWait.SetWaitObject(waitObject);
}
-
-[System.Runtime.InteropServices.ComVisible(true)]
// This is the only public method on this class
public bool Unregister(
WaitHandle waitObject // object to be notified when all callbacks to delegates have completed
@@ -1101,10 +868,8 @@ namespace System.Threading
}
}
- [System.Runtime.InteropServices.ComVisible(true)]
public delegate void WaitCallback(Object state);
- [System.Runtime.InteropServices.ComVisible(true)]
public delegate void WaitOrTimerCallback(Object state, bool timedOut); // signalled or timed out
//
@@ -1115,10 +880,7 @@ namespace System.Threading
//
internal static class _ThreadPoolWaitCallback
{
- static internal bool PerformWaitCallback()
- {
- return ThreadPoolWorkQueue.Dispatch();
- }
+ internal static bool PerformWaitCallback() => ThreadPoolWorkQueue.Dispatch();
}
//
@@ -1138,11 +900,9 @@ namespace System.Threading
internal sealed class QueueUserWorkItemCallback : IThreadPoolWorkItem
{
- static QueueUserWorkItemCallback() {}
-
private WaitCallback callback;
- private ExecutionContext context;
- private Object state;
+ private readonly ExecutionContext context;
+ private readonly Object state;
#if DEBUG
volatile int executed;
@@ -1173,7 +933,7 @@ namespace System.Threading
void IThreadPoolWorkItem.ExecuteWorkItem()
{
#if DEBUG
- MarkExecuted(false);
+ MarkExecuted(aborted:false);
#endif
// call directly if it is an unsafe call OR EC flow is suppressed
if (context == null)
@@ -1184,7 +944,7 @@ namespace System.Threading
}
else
{
- ExecutionContext.Run(context, ccb, this, true);
+ ExecutionContext.Run(context, ccb, this);
}
}
@@ -1193,16 +953,16 @@ namespace System.Threading
#if DEBUG
// this workitem didn't execute because we got a ThreadAbortException prior to the call to ExecuteWorkItem.
// This counts as being executed for our purposes.
- MarkExecuted(true);
+ MarkExecuted(aborted:true);
#endif
}
- static internal ContextCallback ccb = new ContextCallback(WaitCallback_Context);
+ internal static readonly ContextCallback ccb = new ContextCallback(WaitCallback_Context);
- static private void WaitCallback_Context(Object state)
+ private static void WaitCallback_Context(Object state)
{
QueueUserWorkItemCallback obj = (QueueUserWorkItemCallback)state;
- WaitCallback wc = obj.callback as WaitCallback;
+ WaitCallback wc = obj.callback;
Debug.Assert(null != wc);
wc(obj.state);
}
@@ -1210,10 +970,8 @@ namespace System.Threading
internal sealed class QueueUserWorkItemCallbackDefaultContext : IThreadPoolWorkItem
{
- static QueueUserWorkItemCallbackDefaultContext() { }
-
private WaitCallback callback;
- private Object state;
+ private readonly Object state;
#if DEBUG
private volatile int executed;
@@ -1243,9 +1001,9 @@ namespace System.Threading
void IThreadPoolWorkItem.ExecuteWorkItem()
{
#if DEBUG
- MarkExecuted(false);
+ MarkExecuted(aborted:false);
#endif
- ExecutionContext.Run(ExecutionContext.PreAllocatedDefault, ccb, this, true);
+ ExecutionContext.Run(ExecutionContext.Default, ccb, this);
}
void IThreadPoolWorkItem.MarkAborted(ThreadAbortException tae)
@@ -1253,16 +1011,16 @@ namespace System.Threading
#if DEBUG
// this workitem didn't execute because we got a ThreadAbortException prior to the call to ExecuteWorkItem.
// This counts as being executed for our purposes.
- MarkExecuted(true);
+ MarkExecuted(aborted:true);
#endif
}
- static internal ContextCallback ccb = new ContextCallback(WaitCallback_Context);
+ internal static readonly ContextCallback ccb = new ContextCallback(WaitCallback_Context);
- static private void WaitCallback_Context(Object state)
+ private static void WaitCallback_Context(Object state)
{
QueueUserWorkItemCallbackDefaultContext obj = (QueueUserWorkItemCallbackDefaultContext)state;
- WaitCallback wc = obj.callback as WaitCallback;
+ WaitCallback wc = obj.callback;
Debug.Assert(null != wc);
obj.callback = null;
wc(obj.state);
@@ -1271,46 +1029,38 @@ namespace System.Threading
internal class _ThreadPoolWaitOrTimerCallback
{
- static _ThreadPoolWaitOrTimerCallback() {}
-
WaitOrTimerCallback _waitOrTimerCallback;
ExecutionContext _executionContext;
Object _state;
- static private ContextCallback _ccbt = new ContextCallback(WaitOrTimerCallback_Context_t);
- static private ContextCallback _ccbf = new ContextCallback(WaitOrTimerCallback_Context_f);
+ private static readonly ContextCallback _ccbt = new ContextCallback(WaitOrTimerCallback_Context_t);
+ private static readonly ContextCallback _ccbf = new ContextCallback(WaitOrTimerCallback_Context_f);
- internal _ThreadPoolWaitOrTimerCallback(WaitOrTimerCallback waitOrTimerCallback, Object state, bool compressStack, ref StackCrawlMark stackMark)
+ internal _ThreadPoolWaitOrTimerCallback(WaitOrTimerCallback waitOrTimerCallback, Object state, bool compressStack)
{
_waitOrTimerCallback = waitOrTimerCallback;
_state = state;
- if (compressStack && !ExecutionContext.IsFlowSuppressed())
+ if (compressStack)
{
// capture the exection context
- _executionContext = ExecutionContext.Capture(
- ref stackMark,
- ExecutionContext.CaptureOptions.IgnoreSyncCtx | ExecutionContext.CaptureOptions.OptimizeDefaultCase);
+ _executionContext = ExecutionContext.Capture();
}
}
- static private void WaitOrTimerCallback_Context_t(Object state)
- {
- WaitOrTimerCallback_Context(state, true);
- }
+ private static void WaitOrTimerCallback_Context_t(Object state) =>
+ WaitOrTimerCallback_Context(state, timedOut:true);
- static private void WaitOrTimerCallback_Context_f(Object state)
- {
- WaitOrTimerCallback_Context(state, false);
- }
+ private static void WaitOrTimerCallback_Context_f(Object state) =>
+ WaitOrTimerCallback_Context(state, timedOut:false);
- static private void WaitOrTimerCallback_Context(Object state, bool timedOut)
+ private static void WaitOrTimerCallback_Context(Object state, bool timedOut)
{
_ThreadPoolWaitOrTimerCallback helper = (_ThreadPoolWaitOrTimerCallback)state;
helper._waitOrTimerCallback(helper._state, timedOut);
}
// call back helper
- static internal void PerformWaitOrTimerCallback(Object state, bool timedOut)
+ internal static void PerformWaitOrTimerCallback(Object state, bool timedOut)
{
_ThreadPoolWaitOrTimerCallback helper = (_ThreadPoolWaitOrTimerCallback)state;
Debug.Assert(helper != null, "Null state passed to PerformWaitOrTimerCallback!");
@@ -1322,20 +1072,13 @@ namespace System.Threading
}
else
{
- using (ExecutionContext executionContext = helper._executionContext.CreateCopy())
- {
- if (timedOut)
- ExecutionContext.Run(executionContext, _ccbt, helper, true);
- else
- ExecutionContext.Run(executionContext, _ccbf, helper, true);
- }
+ ExecutionContext.Run(helper._executionContext, timedOut ? _ccbt : _ccbf, helper);
}
}
}
[CLSCompliant(false)]
- [System.Runtime.InteropServices.ComVisible(true)]
unsafe public delegate void IOCompletionCallback(uint errorCode, // Error code
uint numBytes, // No. of bytes transferred
NativeOverlapped* pOVERLAP // ptr to OVERLAP structure
@@ -1343,7 +1086,6 @@ namespace System.Threading
public static class ThreadPool
{
-
public static bool SetMaxThreads(int workerThreads, int completionPortThreads)
{
return SetMaxThreadsNative(workerThreads, completionPortThreads);
@@ -1412,7 +1154,7 @@ namespace System.Threading
if (callBack != null)
{
- _ThreadPoolWaitOrTimerCallback callBackHelper = new _ThreadPoolWaitOrTimerCallback(callBack, state, compressStack, ref stackMark);
+ _ThreadPoolWaitOrTimerCallback callBackHelper = new _ThreadPoolWaitOrTimerCallback(callBack, state, compressStack);
state = (Object)callBackHelper;
// call SetWaitObject before native call so that waitObject won't be closed before threadpoolmgr registration
// this could occur if callback were to fire before SetWaitObject does its addref
@@ -1533,141 +1275,84 @@ namespace System.Threading
StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
return RegisterWaitForSingleObject(waitObject,callBack,state,(UInt32)tm,executeOnlyOnce,ref stackMark,false);
}
-
- [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
- Object state
- )
- {
- StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
- return QueueUserWorkItemHelper(callBack,state,ref stackMark,true);
- }
-
- [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
- )
- {
- StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
- return QueueUserWorkItemHelper(callBack,null,ref stackMark,true);
- }
-
- [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
- Object state
- )
- {
- StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
- return QueueUserWorkItemHelper(callBack,state,ref stackMark,false);
- }
- //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.
- private static bool QueueUserWorkItemHelper(WaitCallback callBack, Object state, ref StackCrawlMark stackMark, bool compressStack )
- {
- bool success = true;
+ public static bool QueueUserWorkItem(WaitCallback callBack) =>
+ QueueUserWorkItem(callBack, null);
- if (callBack != null)
+ public static bool QueueUserWorkItem(WaitCallback callBack, object state)
+ {
+ if (callBack == null)
{
- //The thread pool maintains a per-appdomain managed work queue.
- //New thread pool entries are added in the managed queue.
- //The VM is responsible for the actual growing/shrinking of
- //threads.
+ ThrowHelper.ThrowArgumentNullException(ExceptionArgument.callBack);
+ }
- EnsureVMInitialized();
+ EnsureVMInitialized();
- //
- // If we are able to create the workitem, we need to get it in the queue without being interrupted
- // by a ThreadAbortException.
- //
- try { }
- finally
- {
- ExecutionContext context = compressStack && !ExecutionContext.IsFlowSuppressed() ?
- ExecutionContext.Capture(ref stackMark, ExecutionContext.CaptureOptions.IgnoreSyncCtx | ExecutionContext.CaptureOptions.OptimizeDefaultCase) :
- null;
+ ExecutionContext context = ExecutionContext.Capture();
- IThreadPoolWorkItem tpcallBack = context == ExecutionContext.PreAllocatedDefault ?
- new QueueUserWorkItemCallbackDefaultContext(callBack, state) :
- (IThreadPoolWorkItem)new QueueUserWorkItemCallback(callBack, state, context);
+ IThreadPoolWorkItem tpcallBack = context == ExecutionContext.Default ?
+ new QueueUserWorkItemCallbackDefaultContext(callBack, state) :
+ (IThreadPoolWorkItem)new QueueUserWorkItemCallback(callBack, state, context);
- ThreadPoolGlobals.workQueue.Enqueue(tpcallBack, true);
- success = true;
- }
- }
- else
+ ThreadPoolGlobals.workQueue.Enqueue(tpcallBack, forceGlobal: true);
+
+ return true;
+ }
+
+ public static bool UnsafeQueueUserWorkItem(WaitCallback callBack, Object state)
+ {
+ if (callBack == null)
{
- throw new ArgumentNullException(nameof(WaitCallback));
+ ThrowHelper.ThrowArgumentNullException(ExceptionArgument.callBack);
}
- return success;
+
+ EnsureVMInitialized();
+
+ IThreadPoolWorkItem tpcallBack = new QueueUserWorkItemCallback(callBack, state, null);
+
+ ThreadPoolGlobals.workQueue.Enqueue(tpcallBack, forceGlobal: true);
+
+ return true;
}
internal static void UnsafeQueueCustomWorkItem(IThreadPoolWorkItem workItem, bool forceGlobal)
{
Debug.Assert(null != workItem);
EnsureVMInitialized();
-
- //
- // Enqueue needs to be protected from ThreadAbort
- //
- try { }
- finally
- {
- ThreadPoolGlobals.workQueue.Enqueue(workItem, forceGlobal);
- }
+ ThreadPoolGlobals.workQueue.Enqueue(workItem, forceGlobal);
}
// This method tries to take the target callback out of the current thread's queue.
internal static bool TryPopCustomWorkItem(IThreadPoolWorkItem 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);
+ return
+ ThreadPoolGlobals.vmTpInitialized && // if not initialized, so there's no way this workitem was ever queued.
+ ThreadPoolGlobals.workQueue.LocalFindAndPop(workItem);
}
// Get all workitems. Called by TaskScheduler in its debugger hooks.
internal static IEnumerable<IThreadPoolWorkItem> GetQueuedWorkItems()
{
- return EnumerateQueuedWorkItems(ThreadPoolWorkQueue.allThreadQueues.Current, ThreadPoolGlobals.workQueue.queueTail);
- }
-
- internal static IEnumerable<IThreadPoolWorkItem> EnumerateQueuedWorkItems(ThreadPoolWorkQueue.WorkStealingQueue[] wsQueues, ThreadPoolWorkQueue.QueueSegment globalQueueTail)
- {
- if (wsQueues != null)
+ // Enumerate global queue
+ foreach (IThreadPoolWorkItem workItem in ThreadPoolGlobals.workQueue.workItems)
{
- // First, enumerate all workitems in thread-local queues.
- foreach (ThreadPoolWorkQueue.WorkStealingQueue wsq in wsQueues)
- {
- if (wsq != null && wsq.m_array != null)
- {
- IThreadPoolWorkItem[] items = wsq.m_array;
- for (int i = 0; i < items.Length; i++)
- {
- IThreadPoolWorkItem item = items[i];
- if (item != null)
- yield return item;
- }
- }
- }
+ yield return workItem;
}
- if (globalQueueTail != null)
+ // Enumerate each local queue
+ foreach (ThreadPoolWorkQueue.WorkStealingQueue wsq in ThreadPoolWorkQueue.WorkStealingQueueList.Queues)
{
- // Now the global queue
- for (ThreadPoolWorkQueue.QueueSegment segment = globalQueueTail;
- segment != null;
- segment = segment.Next)
+ if (wsq != null && wsq.m_array != null)
{
- IThreadPoolWorkItem[] items = segment.nodes;
+ IThreadPoolWorkItem[] items = wsq.m_array;
for (int i = 0; i < items.Length; i++)
{
IThreadPoolWorkItem item = items[i];
if (item != null)
+ {
yield return item;
+ }
}
}
}
@@ -1675,13 +1360,20 @@ namespace System.Threading
internal static IEnumerable<IThreadPoolWorkItem> GetLocallyQueuedWorkItems()
{
- return EnumerateQueuedWorkItems(new ThreadPoolWorkQueue.WorkStealingQueue[] { ThreadPoolWorkQueueThreadLocals.threadLocals.workStealingQueue }, null);
+ ThreadPoolWorkQueue.WorkStealingQueue wsq = ThreadPoolWorkQueueThreadLocals.threadLocals.workStealingQueue;
+ if (wsq != null && wsq.m_array != null)
+ {
+ IThreadPoolWorkItem[] items = wsq.m_array;
+ for (int i = 0; i < items.Length; i++)
+ {
+ IThreadPoolWorkItem item = items[i];
+ if (item != null)
+ yield return item;
+ }
+ }
}
- internal static IEnumerable<IThreadPoolWorkItem> GetGloballyQueuedWorkItems()
- {
- return EnumerateQueuedWorkItems(null, ThreadPoolGlobals.workQueue.queueTail);
- }
+ internal static IEnumerable<IThreadPoolWorkItem> GetGloballyQueuedWorkItems() => ThreadPoolGlobals.workQueue.workItems;
private static object[] ToObjectArray(IEnumerable<IThreadPoolWorkItem> workitems)
{
@@ -1705,20 +1397,14 @@ 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.
- internal static object[] GetQueuedWorkItemsForDebugger()
- {
- return ToObjectArray(GetQueuedWorkItems());
- }
+ internal static object[] GetQueuedWorkItemsForDebugger() =>
+ ToObjectArray(GetQueuedWorkItems());
- internal static object[] GetGloballyQueuedWorkItemsForDebugger()
- {
- return ToObjectArray(GetGloballyQueuedWorkItems());
- }
+ internal static object[] GetGloballyQueuedWorkItemsForDebugger() =>
+ ToObjectArray(GetGloballyQueuedWorkItems());
- internal static object[] GetLocallyQueuedWorkItemsForDebugger()
- {
- return ToObjectArray(GetLocallyQueuedWorkItems());
- }
+ internal static object[] GetLocallyQueuedWorkItemsForDebugger() =>
+ ToObjectArray(GetLocallyQueuedWorkItems());
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
@@ -1728,19 +1414,26 @@ namespace System.Threading
unsafe private static extern bool PostQueuedCompletionStatus(NativeOverlapped* overlapped);
[CLSCompliant(false)]
- unsafe public static bool UnsafeQueueNativeOverlapped(NativeOverlapped* overlapped)
- {
- return PostQueuedCompletionStatus(overlapped);
- }
+ unsafe public static bool UnsafeQueueNativeOverlapped(NativeOverlapped* overlapped) =>
+ PostQueuedCompletionStatus(overlapped);
+ // The thread pool maintains a per-appdomain managed work queue.
+ // New thread pool entries are added in the managed queue.
+ // The VM is responsible for the actual growing/shrinking of
+ // threads.
private static void EnsureVMInitialized()
{
if (!ThreadPoolGlobals.vmTpInitialized)
{
- ThreadPool.InitializeVMTp(ref ThreadPoolGlobals.enableWorkerTracking);
- ThreadPoolGlobals.vmTpInitialized = true;
+ EnsureVMInitializedCore(); // separate out to help with inlining
}
}
+
+ private static void EnsureVMInitializedCore()
+ {
+ ThreadPool.InitializeVMTp(ref ThreadPoolGlobals.enableWorkerTracking);
+ ThreadPoolGlobals.vmTpInitialized = true;
+ }
// Native methods:
@@ -1795,9 +1488,7 @@ namespace System.Threading
[Obsolete("ThreadPool.BindHandle(IntPtr) has been deprecated. Please use ThreadPool.BindHandle(SafeHandle) instead.", false)]
- public static bool BindHandle(
- IntPtr osHandle
- )
+ public static bool BindHandle(IntPtr osHandle)
{
return BindIOCompletionCallbackNative(osHandle);
}
@@ -1822,7 +1513,6 @@ namespace System.Threading
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
private static extern bool BindIOCompletionCallbackNative(IntPtr fileHandle);
}
}
diff --git a/src/mscorlib/src/System/Threading/ThreadPriority.cs b/src/mscorlib/src/System/Threading/ThreadPriority.cs
index c56156eb89..6303c2fd94 100644
--- a/src/mscorlib/src/System/Threading/ThreadPriority.cs
+++ b/src/mscorlib/src/System/Threading/ThreadPriority.cs
@@ -16,7 +16,6 @@ namespace System.Threading {
using System.Threading;
[Serializable]
-[System.Runtime.InteropServices.ComVisible(true)]
public enum ThreadPriority
{
/*=========================================================================
diff --git a/src/mscorlib/src/System/Threading/ThreadStart.cs b/src/mscorlib/src/System/Threading/ThreadStart.cs
index b968117195..e4beddcd75 100644
--- a/src/mscorlib/src/System/Threading/ThreadStart.cs
+++ b/src/mscorlib/src/System/Threading/ThreadStart.cs
@@ -14,12 +14,10 @@
=============================================================================*/
namespace System.Threading {
- using System.Security.Permissions;
using System.Threading;
// Define the delegate
// NOTE: If you change the signature here, there is code in COMSynchronization
// that invokes this delegate in native.
-[System.Runtime.InteropServices.ComVisible(true)]
public delegate void ThreadStart();
}
diff --git a/src/mscorlib/src/System/Threading/ThreadState.cs b/src/mscorlib/src/System/Threading/ThreadState.cs
index 007e1bf6e9..2d953f384a 100644
--- a/src/mscorlib/src/System/Threading/ThreadState.cs
+++ b/src/mscorlib/src/System/Threading/ThreadState.cs
@@ -16,7 +16,6 @@ namespace System.Threading {
[Serializable]
[Flags]
-[System.Runtime.InteropServices.ComVisible(true)]
public enum ThreadState
{
/*=========================================================================
diff --git a/src/mscorlib/src/System/Threading/ThreadStateException.cs b/src/mscorlib/src/System/Threading/ThreadStateException.cs
index 535dffcdbf..97c03ce06c 100644
--- a/src/mscorlib/src/System/Threading/ThreadStateException.cs
+++ b/src/mscorlib/src/System/Threading/ThreadStateException.cs
@@ -16,7 +16,6 @@
namespace System.Threading {
using System;
using System.Runtime.Serialization;
- [System.Runtime.InteropServices.ComVisible(true)]
[Serializable]
public class ThreadStateException : SystemException {
public ThreadStateException()
diff --git a/src/mscorlib/src/System/Threading/Timeout.cs b/src/mscorlib/src/System/Threading/Timeout.cs
index 99e24159b2..80bdbccf4e 100644
--- a/src/mscorlib/src/System/Threading/Timeout.cs
+++ b/src/mscorlib/src/System/Threading/Timeout.cs
@@ -8,10 +8,8 @@ namespace System.Threading {
// A constant used by methods that take a timeout (Object.Wait, Thread.Sleep
// etc) to indicate that no timeout should occur.
//
- [System.Runtime.InteropServices.ComVisible(true)]
public static class Timeout
{
- [System.Runtime.InteropServices.ComVisible(false)]
public static readonly TimeSpan InfiniteTimeSpan = new TimeSpan(0, 0, 0, 0, Timeout.Infinite);
public const int Infinite = -1;
diff --git a/src/mscorlib/src/System/Threading/Timer.cs b/src/mscorlib/src/System/Threading/Timer.cs
index 5bfefccad2..93d2922799 100644
--- a/src/mscorlib/src/System/Threading/Timer.cs
+++ b/src/mscorlib/src/System/Threading/Timer.cs
@@ -8,7 +8,6 @@ namespace System.Threading
{
using System;
using System.Security;
- using System.Security.Permissions;
using Microsoft.Win32;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
@@ -21,7 +20,6 @@ namespace System.Threading
- [System.Runtime.InteropServices.ComVisible(true)]
public delegate void TimerCallback(Object state);
//
@@ -109,7 +107,6 @@ namespace System.Threading
{
}
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
protected override bool ReleaseHandle()
{
return DeleteAppDomainTimer(handle);
@@ -206,7 +203,6 @@ namespace System.Threading
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
static extern bool DeleteAppDomainTimer(IntPtr handle);
#endregion
@@ -221,83 +217,6 @@ namespace System.Threading
volatile int m_pauseTicks = 0; // Time when Pause was called
- internal void Pause()
- {
- lock(this)
- {
- // Delete the native timer so that no timers are fired in the Pause zone
- if(m_appDomainTimer != null && !m_appDomainTimer.IsInvalid)
- {
- m_appDomainTimer.Dispose();
- m_appDomainTimer = null;
- m_isAppDomainTimerScheduled = false;
- m_pauseTicks = TickCount;
- }
- }
- }
-
- internal void Resume()
- {
- //
- // Update timers to adjust their due-time to accomodate Pause/Resume
- //
- lock (this)
- {
- // prevent ThreadAbort while updating state
- try { }
- finally
- {
- int pauseTicks = m_pauseTicks;
- m_pauseTicks = 0; // Set this to 0 so that now timers can be scheduled
-
- int resumedTicks = TickCount;
- int pauseDuration = resumedTicks - pauseTicks;
-
- bool haveTimerToSchedule = false;
- uint nextAppDomainTimerDuration = uint.MaxValue;
-
- TimerQueueTimer timer = m_timers;
- while (timer != null)
- {
- Debug.Assert(timer.m_dueTime != Timeout.UnsignedInfinite);
- Debug.Assert(resumedTicks >= timer.m_startTicks);
-
- uint elapsed; // How much of the timer dueTime has already elapsed
-
- // Timers started before the paused event has to be sufficiently delayed to accomodate
- // for the Pause time. However, timers started after the Paused event shouldnt be adjusted.
- // E.g. ones created by the app in its Activated event should fire when it was designated.
- // The Resumed event which is where this routine is executing is after this Activated and hence
- // shouldn't delay this timer
-
- if(timer.m_startTicks <= pauseTicks)
- elapsed = (uint)(pauseTicks - timer.m_startTicks);
- else
- elapsed = (uint)(resumedTicks - timer.m_startTicks);
-
- // Handling the corner cases where a Timer was already due by the time Resume is happening,
- // We shouldn't delay those timers.
- // Example is a timer started in App's Activated event with a very small duration
- timer.m_dueTime = (timer.m_dueTime > elapsed) ? timer.m_dueTime - elapsed : 0;;
- timer.m_startTicks = resumedTicks; // re-baseline
-
- if (timer.m_dueTime < nextAppDomainTimerDuration)
- {
- haveTimerToSchedule = true;
- nextAppDomainTimerDuration = timer.m_dueTime;
- }
-
- timer = timer.m_next;
- }
-
- if (haveTimerToSchedule)
- {
- EnsureAppDomainTimerFiresBy(nextAppDomainTimerDuration);
- }
- }
- }
- }
-
//
// Fire any timers that have expired, and update the native timer to schedule the rest of them.
@@ -512,19 +431,13 @@ namespace System.Threading
volatile WaitHandle m_notifyWhenNoCallbacksRunning;
- internal TimerQueueTimer(TimerCallback timerCallback, object state, uint dueTime, uint period, ref StackCrawlMark stackMark)
+ internal TimerQueueTimer(TimerCallback timerCallback, object state, uint dueTime, uint period)
{
m_timerCallback = timerCallback;
m_state = state;
m_dueTime = Timeout.UnsignedInfinite;
m_period = Timeout.UnsignedInfinite;
-
- if (!ExecutionContext.IsFlowSuppressed())
- {
- m_executionContext = ExecutionContext.Capture(
- ref stackMark,
- ExecutionContext.CaptureOptions.IgnoreSyncCtx | ExecutionContext.CaptureOptions.OptimizeDefaultCase);
- }
+ m_executionContext = ExecutionContext.Capture();
//
// After the following statement, the timer may fire. No more manipulation of timer state outside of
@@ -678,29 +591,15 @@ namespace System.Threading
}
else
{
- using (ExecutionContext executionContext =
- m_executionContext.IsPreAllocatedDefault ? m_executionContext : m_executionContext.CreateCopy())
- {
- ContextCallback callback = s_callCallbackInContext;
- if (callback == null)
- s_callCallbackInContext = callback = new ContextCallback(CallCallbackInContext);
-
- ExecutionContext.Run(
- executionContext,
- callback,
- this, // state
- true); // ignoreSyncCtx
- }
+ ExecutionContext.Run(m_executionContext, s_callCallbackInContext, this);
}
}
- private static ContextCallback s_callCallbackInContext;
-
- private static void CallCallbackInContext(object state)
+ private static readonly ContextCallback s_callCallbackInContext = state =>
{
TimerQueueTimer t = (TimerQueueTimer)state;
t.m_timerCallback(t.m_state);
- }
+ };
}
//
@@ -756,14 +655,12 @@ namespace System.Threading
}
- [System.Runtime.InteropServices.ComVisible(true)]
public sealed class Timer : MarshalByRefObject, IDisposable
{
private const UInt32 MAX_SUPPORTED_TIMEOUT = (uint)0xfffffffe;
private TimerHolder m_timer;
- [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
public Timer(TimerCallback callback,
Object state,
int dueTime,
@@ -774,12 +671,10 @@ namespace System.Threading
if (period < -1 )
throw new ArgumentOutOfRangeException(nameof(period), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegOrNegative1"));
Contract.EndContractBlock();
- StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
- TimerSetup(callback,state,(UInt32)dueTime,(UInt32)period,ref stackMark);
+ TimerSetup(callback,state,(UInt32)dueTime,(UInt32)period);
}
- [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
public Timer(TimerCallback callback,
Object state,
TimeSpan dueTime,
@@ -797,22 +692,18 @@ namespace System.Threading
if (periodTm > MAX_SUPPORTED_TIMEOUT)
throw new ArgumentOutOfRangeException(nameof(periodTm),Environment.GetResourceString("ArgumentOutOfRange_PeriodTooLarge"));
- StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
- TimerSetup(callback,state,(UInt32)dueTm,(UInt32)periodTm,ref stackMark);
+ TimerSetup(callback,state,(UInt32)dueTm,(UInt32)periodTm);
}
[CLSCompliant(false)]
- [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
public Timer(TimerCallback callback,
Object state,
UInt32 dueTime,
UInt32 period)
{
- StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
- TimerSetup(callback,state,dueTime,period,ref stackMark);
+ TimerSetup(callback,state,dueTime,period);
}
- [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
public Timer(TimerCallback callback,
Object state,
long dueTime,
@@ -827,11 +718,9 @@ namespace System.Threading
if (period > MAX_SUPPORTED_TIMEOUT)
throw new ArgumentOutOfRangeException(nameof(period),Environment.GetResourceString("ArgumentOutOfRange_PeriodTooLarge"));
Contract.EndContractBlock();
- StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
- TimerSetup(callback,state,(UInt32) dueTime, (UInt32) period,ref stackMark);
+ TimerSetup(callback,state,(UInt32) dueTime, (UInt32) period);
}
- [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
public Timer(TimerCallback callback)
{
int dueTime = -1; // we want timer to be registered, but not activated. Requires caller to call
@@ -839,31 +728,19 @@ namespace System.Threading
// for a timer to be fired before the returned value is assigned to the variable,
// potentially causing the callback to reference a bogus value (if passing the timer to the callback).
- StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
- TimerSetup(callback, this, (UInt32)dueTime, (UInt32)period, ref stackMark);
+ TimerSetup(callback, this, (UInt32)dueTime, (UInt32)period);
}
private void TimerSetup(TimerCallback callback,
Object state,
UInt32 dueTime,
- UInt32 period,
- ref StackCrawlMark stackMark)
+ UInt32 period)
{
if (callback == null)
throw new ArgumentNullException(nameof(TimerCallback));
Contract.EndContractBlock();
- m_timer = new TimerHolder(new TimerQueueTimer(callback, state, dueTime, period, ref stackMark));
- }
-
- internal static void Pause()
- {
- TimerQueue.Instance.Pause();
- }
-
- internal static void Resume()
- {
- TimerQueue.Instance.Resume();
+ m_timer = new TimerHolder(new TimerQueueTimer(callback, state, dueTime, period));
}
public bool Change(int dueTime, int period)
diff --git a/src/mscorlib/src/System/Threading/Volatile.cs b/src/mscorlib/src/System/Threading/Volatile.cs
index 3894b435fa..c94a69ab7b 100644
--- a/src/mscorlib/src/System/Threading/Volatile.cs
+++ b/src/mscorlib/src/System/Threading/Volatile.cs
@@ -26,7 +26,6 @@ namespace System.Threading
//
public static class Volatile
{
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
[System.Runtime.Versioning.NonVersionable]
public static bool Read(ref bool location)
{
@@ -38,7 +37,6 @@ namespace System.Threading
return value;
}
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
[CLSCompliant(false)]
[System.Runtime.Versioning.NonVersionable]
public static sbyte Read(ref sbyte location)
@@ -51,7 +49,6 @@ namespace System.Threading
return value;
}
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
[System.Runtime.Versioning.NonVersionable]
public static byte Read(ref byte location)
{
@@ -63,7 +60,6 @@ namespace System.Threading
return value;
}
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
[System.Runtime.Versioning.NonVersionable]
public static short Read(ref short location)
{
@@ -75,7 +71,6 @@ namespace System.Threading
return value;
}
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
[CLSCompliant(false)]
[System.Runtime.Versioning.NonVersionable]
public static ushort Read(ref ushort location)
@@ -88,7 +83,6 @@ namespace System.Threading
return value;
}
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
[System.Runtime.Versioning.NonVersionable]
public static int Read(ref int location)
{
@@ -100,7 +94,6 @@ namespace System.Threading
return value;
}
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
[CLSCompliant(false)]
[System.Runtime.Versioning.NonVersionable]
public static uint Read(ref uint location)
@@ -114,7 +107,6 @@ namespace System.Threading
}
#if BIT64
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
[System.Runtime.Versioning.NonVersionable]
public static long Read(ref long location)
{
@@ -126,7 +118,6 @@ namespace System.Threading
return value;
}
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
[CLSCompliant(false)]
[System.Runtime.Versioning.NonVersionable]
public static ulong Read(ref ulong location)
@@ -139,7 +130,6 @@ namespace System.Threading
return value;
}
#else
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
public static long Read(ref long location)
{
//
@@ -151,7 +141,6 @@ namespace System.Threading
return Interlocked.CompareExchange(ref location, 0, 0);
}
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
[CLSCompliant(false)]
public static ulong Read(ref ulong location)
{
@@ -169,7 +158,6 @@ namespace System.Threading
}
#endif
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
[System.Runtime.Versioning.NonVersionable]
public static IntPtr Read(ref IntPtr location)
{
@@ -181,7 +169,6 @@ namespace System.Threading
return value;
}
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
[CLSCompliant(false)]
[System.Runtime.Versioning.NonVersionable]
public static UIntPtr Read(ref UIntPtr location)
@@ -194,7 +181,6 @@ namespace System.Threading
return value;
}
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
[System.Runtime.Versioning.NonVersionable]
public static float Read(ref float location)
{
@@ -206,7 +192,6 @@ namespace System.Threading
return value;
}
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
[System.Runtime.Versioning.NonVersionable]
public static double Read(ref double location)
{
@@ -219,7 +204,6 @@ namespace System.Threading
return Interlocked.CompareExchange(ref location, 0, 0);
}
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
[System.Runtime.Versioning.NonVersionable]
public static T Read<T>(ref T location) where T : class
{
@@ -234,7 +218,6 @@ namespace System.Threading
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
[System.Runtime.Versioning.NonVersionable]
public static void Write(ref bool location, bool value)
{
@@ -245,7 +228,6 @@ namespace System.Threading
location = value;
}
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
[CLSCompliant(false)]
[System.Runtime.Versioning.NonVersionable]
public static void Write(ref sbyte location, sbyte value)
@@ -257,7 +239,6 @@ namespace System.Threading
location = value;
}
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
[System.Runtime.Versioning.NonVersionable]
public static void Write(ref byte location, byte value)
{
@@ -268,7 +249,6 @@ namespace System.Threading
location = value;
}
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
[System.Runtime.Versioning.NonVersionable]
public static void Write(ref short location, short value)
{
@@ -279,7 +259,6 @@ namespace System.Threading
location = value;
}
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
[CLSCompliant(false)]
[System.Runtime.Versioning.NonVersionable]
public static void Write(ref ushort location, ushort value)
@@ -291,7 +270,6 @@ namespace System.Threading
location = value;
}
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
[System.Runtime.Versioning.NonVersionable]
public static void Write(ref int location, int value)
{
@@ -302,7 +280,6 @@ namespace System.Threading
location = value;
}
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
[CLSCompliant(false)]
[System.Runtime.Versioning.NonVersionable]
public static void Write(ref uint location, uint value)
@@ -315,7 +292,6 @@ namespace System.Threading
}
#if BIT64
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
[System.Runtime.Versioning.NonVersionable]
public static void Write(ref long location, long value)
{
@@ -326,7 +302,6 @@ namespace System.Threading
location = value;
}
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
[CLSCompliant(false)]
[System.Runtime.Versioning.NonVersionable]
public static void Write(ref ulong location, ulong value)
@@ -338,7 +313,6 @@ namespace System.Threading
location = value;
}
#else
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
public static void Write(ref long location, long value)
{
//
@@ -350,7 +324,6 @@ namespace System.Threading
Interlocked.Exchange(ref location, value);
}
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
[CLSCompliant(false)]
public static void Write(ref ulong location, ulong value)
{
@@ -374,7 +347,6 @@ namespace System.Threading
}
#endif
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
[System.Runtime.Versioning.NonVersionable]
public static void Write(ref IntPtr location, IntPtr value)
{
@@ -385,7 +357,6 @@ namespace System.Threading
location = value;
}
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
[CLSCompliant(false)]
[System.Runtime.Versioning.NonVersionable]
public static void Write(ref UIntPtr location, UIntPtr value)
@@ -397,7 +368,6 @@ namespace System.Threading
location = value;
}
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
[System.Runtime.Versioning.NonVersionable]
public static void Write(ref float location, float value)
{
@@ -408,7 +378,6 @@ namespace System.Threading
location = value;
}
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
[System.Runtime.Versioning.NonVersionable]
public static void Write(ref double location, double value)
{
@@ -421,7 +390,6 @@ namespace System.Threading
Interlocked.Exchange(ref location, value);
}
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
[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 7638c8b35b..d4dcd710be 100644
--- a/src/mscorlib/src/System/Threading/WaitHandle.cs
+++ b/src/mscorlib/src/System/Threading/WaitHandle.cs
@@ -17,7 +17,6 @@ namespace System.Threading
using System.Threading;
using System.Runtime.Remoting;
using System;
- using System.Security.Permissions;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using Microsoft.Win32.SafeHandles;
@@ -27,7 +26,6 @@ namespace System.Threading
using System.Diagnostics.CodeAnalysis;
using Win32Native = Microsoft.Win32.Win32Native;
- [System.Runtime.InteropServices.ComVisible(true)]
public abstract class WaitHandle : MarshalByRefObject, IDisposable {
public const int WaitTimeout = 0x102;
@@ -102,7 +100,6 @@ namespace System.Threading
public SafeWaitHandle SafeWaitHandle
{
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
get
{
if (safeWaitHandle == null)
@@ -112,7 +109,6 @@ namespace System.Threading
return safeWaitHandle;
}
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
set
{
// Set safeWaitHandle and waitHandle in a CER so we won't take
@@ -245,7 +241,6 @@ namespace System.Threading
========================================================================*/
[MethodImplAttribute(MethodImplOptions.InternalCall)]
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
private static extern int WaitMultiple(WaitHandle[] waitHandles, int millisecondsTimeout, bool exitContext, bool WaitAll);
public static bool WaitAll(WaitHandle[] waitHandles, int millisecondsTimeout, bool exitContext)
@@ -350,7 +345,6 @@ namespace System.Threading
** (if in a synchronized context) is exited before the wait and reacquired
========================================================================*/
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
public static int WaitAny(WaitHandle[] waitHandles, int millisecondsTimeout, bool exitContext)
{
if (waitHandles==null)
@@ -406,7 +400,6 @@ namespace System.Threading
return ret;
}
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
public static int WaitAny(
WaitHandle[] waitHandles,
TimeSpan timeout,
@@ -419,7 +412,6 @@ namespace System.Threading
}
return WaitAny(waitHandles,(int)tm, exitContext);
}
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
public static int WaitAny(WaitHandle[] waitHandles, TimeSpan timeout)
{
return WaitAny(waitHandles, timeout, true);
@@ -429,13 +421,11 @@ namespace System.Threading
/*========================================================================
** Shorthand for WaitAny with timeout = Timeout.Infinite and exitContext = true
========================================================================*/
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
public static int WaitAny(WaitHandle[] waitHandles)
{
return WaitAny(waitHandles, Timeout.Infinite, true);
}
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
public static int WaitAny(WaitHandle[] waitHandles, int millisecondsTimeout)
{
return WaitAny(waitHandles, millisecondsTimeout, true);
@@ -446,10 +436,11 @@ namespace System.Threading
== SignalAndWait
==
==================================================*/
-
+#if !PLATFORM_UNIX
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern int SignalAndWaitOne(SafeWaitHandle waitHandleToSignal,SafeWaitHandle waitHandleToWaitOn, int millisecondsTimeout,
bool hasThreadAffinity, bool exitContext);
+#endif // !PLATFORM_UNIX
public static bool SignalAndWait(
WaitHandle toSignal,
diff --git a/src/mscorlib/src/System/ThrowHelper.cs b/src/mscorlib/src/System/ThrowHelper.cs
index a534dec818..1ed8317633 100644
--- a/src/mscorlib/src/System/ThrowHelper.cs
+++ b/src/mscorlib/src/System/ThrowHelper.cs
@@ -39,12 +39,10 @@ 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();
}
@@ -72,7 +70,6 @@ namespace System {
internal static void ThrowNotSupportedException_CannotCallGetHashCodeOnSpan() {
throw new NotSupportedException(Environment.GetResourceString("NotSupported_CannotCallGetHashCodeOnSpan"));
}
-#endif
internal static void ThrowArgumentOutOfRange_IndexException() {
throw GetArgumentOutOfRangeException(ExceptionArgument.index,
@@ -127,8 +124,12 @@ namespace System {
throw GetArgumentException(resource, argument);
}
+ private static ArgumentNullException GetArgumentNullException(ExceptionArgument argument) {
+ return new ArgumentNullException(GetArgumentName(argument));
+ }
+
internal static void ThrowArgumentNullException(ExceptionArgument argument) {
- throw new ArgumentNullException(GetArgumentName(argument));
+ throw GetArgumentNullException(argument);
}
internal static void ThrowArgumentNullException(ExceptionResource resource) {
@@ -211,11 +212,27 @@ namespace System {
throw GetInvalidOperationException(ExceptionResource.InvalidOperation_EnumOpCantHappen);
}
+ internal static void ThrowArraySegmentCtorValidationFailedExceptions(Array array, int offset, int count) {
+ throw GetArraySegmentCtorValidationFailedException(array, offset, count);
+ }
+
+ private static Exception GetArraySegmentCtorValidationFailedException(Array array, int offset, int count) {
+ if (array == null)
+ return GetArgumentNullException(ExceptionArgument.array);
+ if (offset < 0)
+ return GetArgumentOutOfRangeException(ExceptionArgument.offset, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum);
+ if (count < 0)
+ return GetArgumentOutOfRangeException(ExceptionArgument.count, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum);
+
+ Debug.Assert(array.Length - offset < count);
+ return GetArgumentException(ExceptionResource.Argument_InvalidOffLen);
+ }
+
private static ArgumentException GetArgumentException(ExceptionResource resource) {
return new ArgumentException(GetResourceString(resource));
}
- private static InvalidOperationException GetInvalidOperationException(ExceptionResource resource) {
+ internal static InvalidOperationException GetInvalidOperationException(ExceptionResource resource) {
return new InvalidOperationException(GetResourceString(resource));
}
@@ -227,7 +244,7 @@ namespace System {
return new ArgumentException(Environment.GetResourceString("Arg_WrongType", value, targetType), nameof(value));
}
- private static ArgumentOutOfRangeException GetArgumentOutOfRangeException(ExceptionArgument argument, ExceptionResource resource) {
+ internal static ArgumentOutOfRangeException GetArgumentOutOfRangeException(ExceptionArgument argument, ExceptionResource resource) {
return new ArgumentOutOfRangeException(GetArgumentName(argument), GetResourceString(resource));
}
@@ -363,7 +380,8 @@ namespace System {
updateValueFactory,
concurrencyLevel,
text,
-
+ callBack,
+ type,
}
//
@@ -453,7 +471,6 @@ namespace System {
Task_ContinueWith_NotOnAnything,
Task_ContinueWith_ESandLR,
TaskT_TransitionToFinal_AlreadyCompleted,
- TaskT_ctor_SelfReplicating,
TaskCompletionSourceT_TrySetException_NullException,
TaskCompletionSourceT_TrySetException_NoExceptions,
InvalidOperation_WrongAsyncResultOrEndCalledMultiple,
@@ -468,7 +485,8 @@ namespace System {
ConcurrentDictionary_ArrayNotLargeEnough,
ConcurrentDictionary_ArrayIncorrectType,
ConcurrentCollection_SyncRoot_NotSupported,
-
+ ArgumentOutOfRange_Enum,
+ InvalidOperation_HandleIsNotInitialized,
}
}
diff --git a/src/mscorlib/src/System/TimeSpan.cs b/src/mscorlib/src/System/TimeSpan.cs
index a594da20e7..7b71b48fed 100644
--- a/src/mscorlib/src/System/TimeSpan.cs
+++ b/src/mscorlib/src/System/TimeSpan.cs
@@ -28,7 +28,6 @@ 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)]
[Serializable] public struct TimeSpan : IComparable
, IComparable<TimeSpan>, IEquatable<TimeSpan>, IFormattable
{
diff --git a/src/mscorlib/src/System/TimeZone.cs b/src/mscorlib/src/System/TimeZone.cs
index c0a369fd3c..8ede49293e 100644
--- a/src/mscorlib/src/System/TimeZone.cs
+++ b/src/mscorlib/src/System/TimeZone.cs
@@ -26,7 +26,6 @@ namespace System {
using System.Globalization;
[Serializable]
- [System.Runtime.InteropServices.ComVisible(true)]
[Obsolete("System.TimeZone has been deprecated. Please investigate the use of System.TimeZoneInfo instead.")]
public abstract class TimeZone {
private static volatile TimeZone currentTimeZone = null;
diff --git a/src/mscorlib/src/System/TimeZoneInfo.AdjustmentRule.cs b/src/mscorlib/src/System/TimeZoneInfo.AdjustmentRule.cs
new file mode 100644
index 0000000000..d27d2386e2
--- /dev/null
+++ b/src/mscorlib/src/System/TimeZoneInfo.AdjustmentRule.cs
@@ -0,0 +1,251 @@
+// 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.Serialization;
+
+namespace System
+{
+ public sealed partial class TimeZoneInfo
+ {
+ [Serializable]
+ public sealed class AdjustmentRule : IEquatable<AdjustmentRule>, ISerializable, IDeserializationCallback
+ {
+ private readonly DateTime _dateStart;
+ private readonly DateTime _dateEnd;
+ private readonly TimeSpan _daylightDelta;
+ private readonly TransitionTime _daylightTransitionStart;
+ private readonly TransitionTime _daylightTransitionEnd;
+ private readonly TimeSpan _baseUtcOffsetDelta; // delta from the default Utc offset (utcOffset = defaultUtcOffset + _baseUtcOffsetDelta)
+ private readonly bool _noDaylightTransitions;
+
+ public DateTime DateStart => _dateStart;
+
+ public DateTime DateEnd => _dateEnd;
+
+ public TimeSpan DaylightDelta => _daylightDelta;
+
+ public TransitionTime DaylightTransitionStart => _daylightTransitionStart;
+
+ public TransitionTime DaylightTransitionEnd => _daylightTransitionEnd;
+
+ internal TimeSpan BaseUtcOffsetDelta => _baseUtcOffsetDelta;
+
+ /// <summary>
+ /// Gets a value indicating that this AdjustmentRule fixes the time zone offset
+ /// from DateStart to DateEnd without any daylight transitions in between.
+ /// </summary>
+ internal bool NoDaylightTransitions => _noDaylightTransitions;
+
+ internal bool HasDaylightSaving =>
+ DaylightDelta != TimeSpan.Zero ||
+ (DaylightTransitionStart != default(TransitionTime) && DaylightTransitionStart.TimeOfDay != DateTime.MinValue) ||
+ (DaylightTransitionEnd != default(TransitionTime) && DaylightTransitionEnd.TimeOfDay != DateTime.MinValue.AddMilliseconds(1));
+
+ public bool Equals(AdjustmentRule other) =>
+ other != null &&
+ _dateStart == other._dateStart &&
+ _dateEnd == other._dateEnd &&
+ _daylightDelta == other._daylightDelta &&
+ _baseUtcOffsetDelta == other._baseUtcOffsetDelta &&
+ _daylightTransitionEnd.Equals(other._daylightTransitionEnd) &&
+ _daylightTransitionStart.Equals(other._daylightTransitionStart);
+
+ public override int GetHashCode() => _dateStart.GetHashCode();
+
+ private AdjustmentRule(
+ DateTime dateStart,
+ DateTime dateEnd,
+ TimeSpan daylightDelta,
+ TransitionTime daylightTransitionStart,
+ TransitionTime daylightTransitionEnd,
+ TimeSpan baseUtcOffsetDelta,
+ bool noDaylightTransitions)
+ {
+ ValidateAdjustmentRule(dateStart, dateEnd, daylightDelta,
+ daylightTransitionStart, daylightTransitionEnd, noDaylightTransitions);
+
+ _dateStart = dateStart;
+ _dateEnd = dateEnd;
+ _daylightDelta = daylightDelta;
+ _daylightTransitionStart = daylightTransitionStart;
+ _daylightTransitionEnd = daylightTransitionEnd;
+ _baseUtcOffsetDelta = baseUtcOffsetDelta;
+ _noDaylightTransitions = noDaylightTransitions;
+ }
+
+ public static AdjustmentRule CreateAdjustmentRule(
+ DateTime dateStart,
+ DateTime dateEnd,
+ TimeSpan daylightDelta,
+ TransitionTime daylightTransitionStart,
+ TransitionTime daylightTransitionEnd)
+ {
+ return new AdjustmentRule(
+ dateStart,
+ dateEnd,
+ daylightDelta,
+ daylightTransitionStart,
+ daylightTransitionEnd,
+ baseUtcOffsetDelta: TimeSpan.Zero,
+ noDaylightTransitions: false);
+ }
+
+ internal static AdjustmentRule CreateAdjustmentRule(
+ DateTime dateStart,
+ DateTime dateEnd,
+ TimeSpan daylightDelta,
+ TransitionTime daylightTransitionStart,
+ TransitionTime daylightTransitionEnd,
+ TimeSpan baseUtcOffsetDelta,
+ bool noDaylightTransitions)
+ {
+ return new AdjustmentRule(
+ dateStart,
+ dateEnd,
+ daylightDelta,
+ daylightTransitionStart,
+ daylightTransitionEnd,
+ baseUtcOffsetDelta,
+ noDaylightTransitions);
+ }
+
+ //
+ // When Windows sets the daylight transition start Jan 1st at 12:00 AM, it means the year starts with the daylight saving on.
+ // We have to special case this value and not adjust it when checking if any date is in the daylight saving period.
+ //
+ internal bool IsStartDateMarkerForBeginningOfYear() =>
+ !NoDaylightTransitions &&
+ DaylightTransitionStart.Month == 1 && DaylightTransitionStart.Day == 1 && DaylightTransitionStart.TimeOfDay.Hour == 0 &&
+ DaylightTransitionStart.TimeOfDay.Minute == 0 && DaylightTransitionStart.TimeOfDay.Second == 0 &&
+ _dateStart.Year == _dateEnd.Year;
+
+ //
+ // When Windows sets the daylight transition end Jan 1st at 12:00 AM, it means the year ends with the daylight saving on.
+ // We have to special case this value and not adjust it when checking if any date is in the daylight saving period.
+ //
+ internal bool IsEndDateMarkerForEndOfYear() =>
+ !NoDaylightTransitions &&
+ DaylightTransitionEnd.Month == 1 && DaylightTransitionEnd.Day == 1 && DaylightTransitionEnd.TimeOfDay.Hour == 0 &&
+ DaylightTransitionEnd.TimeOfDay.Minute == 0 && DaylightTransitionEnd.TimeOfDay.Second == 0 &&
+ _dateStart.Year == _dateEnd.Year;
+
+ /// <summary>
+ /// Helper function that performs all of the validation checks for the actory methods and deserialization callback.
+ /// </summary>
+ private static void ValidateAdjustmentRule(
+ DateTime dateStart,
+ DateTime dateEnd,
+ TimeSpan daylightDelta,
+ TransitionTime daylightTransitionStart,
+ TransitionTime daylightTransitionEnd,
+ bool noDaylightTransitions)
+ {
+ if (dateStart.Kind != DateTimeKind.Unspecified && dateStart.Kind != DateTimeKind.Utc)
+ {
+ 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"), nameof(dateEnd));
+ }
+
+ if (daylightTransitionStart.Equals(daylightTransitionEnd) && !noDaylightTransitions)
+ {
+ throw new ArgumentException(Environment.GetResourceString("Argument_TransitionTimesAreIdentical"), nameof(daylightTransitionEnd));
+ }
+
+ if (dateStart > dateEnd)
+ {
+ 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,
+ // which caused their current BaseUtcOffset to be +13. But on the other side of the line it was UTC-11 (+1 for daylight).
+ // 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(nameof(daylightDelta), daylightDelta, Environment.GetResourceString("ArgumentOutOfRange_UtcOffset"));
+ }
+
+ if (daylightDelta.Ticks % TimeSpan.TicksPerMinute != 0)
+ {
+ throw new ArgumentException(Environment.GetResourceString("Argument_TimeSpanHasSeconds"), nameof(daylightDelta));
+ }
+
+ if (dateStart != DateTime.MinValue && dateStart.Kind == DateTimeKind.Unspecified && dateStart.TimeOfDay != TimeSpan.Zero)
+ {
+ throw new ArgumentException(Environment.GetResourceString("Argument_DateTimeHasTimeOfDay"), nameof(dateStart));
+ }
+
+ if (dateEnd != DateTime.MaxValue && dateEnd.Kind == DateTimeKind.Unspecified && dateEnd.TimeOfDay != TimeSpan.Zero)
+ {
+ throw new ArgumentException(Environment.GetResourceString("Argument_DateTimeHasTimeOfDay"), nameof(dateEnd));
+ }
+ Contract.EndContractBlock();
+ }
+
+ void IDeserializationCallback.OnDeserialization(object sender)
+ {
+ // OnDeserialization is called after each instance of this class is deserialized.
+ // This callback method performs AdjustmentRule validation after being deserialized.
+
+ try
+ {
+ ValidateAdjustmentRule(_dateStart, _dateEnd, _daylightDelta,
+ _daylightTransitionStart, _daylightTransitionEnd, _noDaylightTransitions);
+ }
+ catch (ArgumentException e)
+ {
+ throw new SerializationException(Environment.GetResourceString("Serialization_InvalidData"), e);
+ }
+ }
+
+ void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
+ {
+ if (info == null)
+ {
+ throw new ArgumentNullException(nameof(info));
+ }
+ Contract.EndContractBlock();
+
+ info.AddValue("DateStart", _dateStart);
+ info.AddValue("DateEnd", _dateEnd);
+ info.AddValue("DaylightDelta", _daylightDelta);
+ info.AddValue("DaylightTransitionStart", _daylightTransitionStart);
+ info.AddValue("DaylightTransitionEnd", _daylightTransitionEnd);
+ info.AddValue("BaseUtcOffsetDelta", _baseUtcOffsetDelta);
+ info.AddValue("NoDaylightTransitions", _noDaylightTransitions);
+ }
+
+ AdjustmentRule(SerializationInfo info, StreamingContext context)
+ {
+ if (info == null)
+ {
+ throw new ArgumentNullException(nameof(info));
+ }
+
+ _dateStart = (DateTime)info.GetValue("DateStart", typeof(DateTime));
+ _dateEnd = (DateTime)info.GetValue("DateEnd", typeof(DateTime));
+ _daylightDelta = (TimeSpan)info.GetValue("DaylightDelta", typeof(TimeSpan));
+ _daylightTransitionStart = (TransitionTime)info.GetValue("DaylightTransitionStart", typeof(TransitionTime));
+ _daylightTransitionEnd = (TransitionTime)info.GetValue("DaylightTransitionEnd", typeof(TransitionTime));
+
+ object o = info.GetValueNoThrow("BaseUtcOffsetDelta", typeof(TimeSpan));
+ if (o != null)
+ {
+ _baseUtcOffsetDelta = (TimeSpan)o;
+ }
+
+ o = info.GetValueNoThrow("NoDaylightTransitions", typeof(bool));
+ if (o != null)
+ {
+ _noDaylightTransitions = (bool)o;
+ }
+ }
+ }
+ }
+}
diff --git a/src/mscorlib/src/System/TimeZoneInfo.StringSerializer.cs b/src/mscorlib/src/System/TimeZoneInfo.StringSerializer.cs
new file mode 100644
index 0000000000..9c1d5c3502
--- /dev/null
+++ b/src/mscorlib/src/System/TimeZoneInfo.StringSerializer.cs
@@ -0,0 +1,625 @@
+// 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.Globalization;
+using System.Runtime.Serialization;
+using System.Text;
+
+namespace System
+{
+ public sealed partial class TimeZoneInfo
+ {
+ /// <summary>
+ /// Used to serialize and deserialize TimeZoneInfo objects based on the custom string serialization format.
+ /// </summary>
+ private struct StringSerializer
+ {
+ private enum State
+ {
+ Escaped = 0,
+ NotEscaped = 1,
+ StartOfToken = 2,
+ EndOfLine = 3
+ }
+
+ private readonly string _serializedText;
+ private int _currentTokenStartIndex;
+ private State _state;
+
+ // the majority of the strings contained in the OS time zones fit in 64 chars
+ private const int InitialCapacityForString = 64;
+ private const char Esc = '\\';
+ private const char Sep = ';';
+ private const char Lhs = '[';
+ private const char Rhs = ']';
+ private const string DateTimeFormat = "MM:dd:yyyy";
+ private const string TimeOfDayFormat = "HH:mm:ss.FFF";
+
+ /// <summary>
+ /// Creates the custom serialized string representation of a TimeZoneInfo instance.
+ /// </summary>
+ public static string GetSerializedString(TimeZoneInfo zone)
+ {
+ StringBuilder serializedText = StringBuilderCache.Acquire();
+
+ //
+ // <_id>;<_baseUtcOffset>;<_displayName>;<_standardDisplayName>;<_daylightDispayName>
+ //
+ SerializeSubstitute(zone.Id, serializedText);
+ serializedText.Append(Sep);
+ serializedText.Append(zone.BaseUtcOffset.TotalMinutes.ToString(CultureInfo.InvariantCulture));
+ serializedText.Append(Sep);
+ SerializeSubstitute(zone.DisplayName, serializedText);
+ serializedText.Append(Sep);
+ SerializeSubstitute(zone.StandardName, serializedText);
+ serializedText.Append(Sep);
+ SerializeSubstitute(zone.DaylightName, serializedText);
+ serializedText.Append(Sep);
+
+ AdjustmentRule[] rules = zone.GetAdjustmentRules();
+ foreach (AdjustmentRule rule in rules)
+ {
+ serializedText.Append(Lhs);
+ serializedText.Append(rule.DateStart.ToString(DateTimeFormat, DateTimeFormatInfo.InvariantInfo));
+ serializedText.Append(Sep);
+ serializedText.Append(rule.DateEnd.ToString(DateTimeFormat, DateTimeFormatInfo.InvariantInfo));
+ serializedText.Append(Sep);
+ serializedText.Append(rule.DaylightDelta.TotalMinutes.ToString(CultureInfo.InvariantCulture));
+ serializedText.Append(Sep);
+ // serialize the TransitionTime's
+ SerializeTransitionTime(rule.DaylightTransitionStart, serializedText);
+ serializedText.Append(Sep);
+ SerializeTransitionTime(rule.DaylightTransitionEnd, serializedText);
+ serializedText.Append(Sep);
+ if (rule.BaseUtcOffsetDelta != TimeSpan.Zero)
+ {
+ // Serialize it only when BaseUtcOffsetDelta has a value to reduce the impact of adding rule.BaseUtcOffsetDelta
+ serializedText.Append(rule.BaseUtcOffsetDelta.TotalMinutes.ToString(CultureInfo.InvariantCulture));
+ serializedText.Append(Sep);
+ }
+ if (rule.NoDaylightTransitions)
+ {
+ // Serialize it only when NoDaylightTransitions is true to reduce the impact of adding rule.NoDaylightTransitions
+ serializedText.Append('1');
+ serializedText.Append(Sep);
+ }
+ serializedText.Append(Rhs);
+ }
+ serializedText.Append(Sep);
+
+ return StringBuilderCache.GetStringAndRelease(serializedText);
+ }
+
+ /// <summary>
+ /// Instantiates a TimeZoneInfo from a custom serialized string.
+ /// </summary>
+ public static TimeZoneInfo GetDeserializedTimeZoneInfo(string source)
+ {
+ StringSerializer s = new StringSerializer(source);
+
+ string id = s.GetNextStringValue();
+ TimeSpan baseUtcOffset = s.GetNextTimeSpanValue();
+ string displayName = s.GetNextStringValue();
+ string standardName = s.GetNextStringValue();
+ string daylightName = s.GetNextStringValue();
+ AdjustmentRule[] rules = s.GetNextAdjustmentRuleArrayValue();
+
+ try
+ {
+ return new TimeZoneInfo(id, baseUtcOffset, displayName, standardName, daylightName, rules, disableDaylightSavingTime: false);
+ }
+ catch (ArgumentException ex)
+ {
+ throw new SerializationException(Environment.GetResourceString("Serialization_InvalidData"), ex);
+ }
+ catch (InvalidTimeZoneException ex)
+ {
+ throw new SerializationException(Environment.GetResourceString("Serialization_InvalidData"), ex);
+ }
+ }
+
+ private StringSerializer(string str)
+ {
+ _serializedText = str;
+ _currentTokenStartIndex = 0;
+ _state = State.StartOfToken;
+ }
+
+ /// <summary>
+ /// Appends the String to the StringBuilder with all of the reserved chars escaped.
+ ///
+ /// ";" -> "\;"
+ /// "[" -> "\["
+ /// "]" -> "\]"
+ /// "\" -> "\\"
+ /// </summary>
+ private static void SerializeSubstitute(string text, StringBuilder serializedText)
+ {
+ foreach (char c in text)
+ {
+ if (c == Esc || c == Lhs || c == Rhs || c == Sep)
+ {
+ serializedText.Append('\\');
+ }
+ serializedText.Append(c);
+ }
+ }
+
+ /// <summary>
+ /// Helper method to serialize a TimeZoneInfo.TransitionTime object.
+ /// </summary>
+ private static void SerializeTransitionTime(TransitionTime time, StringBuilder serializedText)
+ {
+ serializedText.Append(Lhs);
+ serializedText.Append(time.IsFixedDateRule ? '1' : '0');
+ serializedText.Append(Sep);
+ serializedText.Append(time.TimeOfDay.ToString(TimeOfDayFormat, DateTimeFormatInfo.InvariantInfo));
+ serializedText.Append(Sep);
+ serializedText.Append(time.Month.ToString(CultureInfo.InvariantCulture));
+ serializedText.Append(Sep);
+ if (time.IsFixedDateRule)
+ {
+ serializedText.Append(time.Day.ToString(CultureInfo.InvariantCulture));
+ serializedText.Append(Sep);
+ }
+ else
+ {
+ serializedText.Append(time.Week.ToString(CultureInfo.InvariantCulture));
+ serializedText.Append(Sep);
+ serializedText.Append(((int)time.DayOfWeek).ToString(CultureInfo.InvariantCulture));
+ serializedText.Append(Sep);
+ }
+ serializedText.Append(Rhs);
+ }
+
+ /// <summary>
+ /// Helper function to determine if the passed in string token is allowed to be preceeded by an escape sequence token.
+ /// </summary>
+ private static void VerifyIsEscapableCharacter(char c)
+ {
+ if (c != Esc && c != Sep && c != Lhs && c != Rhs)
+ {
+ throw new SerializationException(Environment.GetResourceString("Serialization_InvalidEscapeSequence", c));
+ }
+ }
+
+ /// <summary>
+ /// Helper function that reads past "v.Next" data fields. Receives a "depth" parameter indicating the
+ /// current relative nested bracket depth that _currentTokenStartIndex is at. The function ends
+ /// successfully when "depth" returns to zero (0).
+ /// </summary>
+ private void SkipVersionNextDataFields(int depth /* starting depth in the nested brackets ('[', ']')*/)
+ {
+ if (_currentTokenStartIndex < 0 || _currentTokenStartIndex >= _serializedText.Length)
+ {
+ throw new SerializationException(Environment.GetResourceString("Serialization_InvalidData"));
+ }
+ State tokenState = State.NotEscaped;
+
+ // walk the serialized text, building up the token as we go...
+ for (int i = _currentTokenStartIndex; i < _serializedText.Length; i++)
+ {
+ if (tokenState == State.Escaped)
+ {
+ VerifyIsEscapableCharacter(_serializedText[i]);
+ tokenState = State.NotEscaped;
+ }
+ else if (tokenState == State.NotEscaped)
+ {
+ switch (_serializedText[i])
+ {
+ case Esc:
+ tokenState = State.Escaped;
+ break;
+
+ case Lhs:
+ depth++;
+ break;
+ case Rhs:
+ depth--;
+ if (depth == 0)
+ {
+ _currentTokenStartIndex = i + 1;
+ if (_currentTokenStartIndex >= _serializedText.Length)
+ {
+ _state = State.EndOfLine;
+ }
+ else
+ {
+ _state = State.StartOfToken;
+ }
+ return;
+ }
+ break;
+
+ case '\0':
+ // invalid character
+ throw new SerializationException(Environment.GetResourceString("Serialization_InvalidData"));
+
+ default:
+ break;
+ }
+ }
+ }
+
+ throw new SerializationException(Environment.GetResourceString("Serialization_InvalidData"));
+ }
+
+ /// <summary>
+ /// Helper function that reads a string token from the serialized text. The function
+ /// updates <see cref="_currentTokenStartIndex"/> to point to the next token on exit.
+ /// Also <see cref="_state"/> is set to either <see cref="State.StartOfToken"/> or
+ /// <see cref="State.EndOfLine"/> on exit.
+ /// </summary>
+ private string GetNextStringValue()
+ {
+ // first verify the internal state of the object
+ if (_state == State.EndOfLine)
+ {
+ throw new SerializationException(Environment.GetResourceString("Serialization_InvalidData"));
+ }
+ if (_currentTokenStartIndex < 0 || _currentTokenStartIndex >= _serializedText.Length)
+ {
+ throw new SerializationException(Environment.GetResourceString("Serialization_InvalidData"));
+ }
+ State tokenState = State.NotEscaped;
+ StringBuilder token = StringBuilderCache.Acquire(InitialCapacityForString);
+
+ // walk the serialized text, building up the token as we go...
+ for (int i = _currentTokenStartIndex; i < _serializedText.Length; i++)
+ {
+ if (tokenState == State.Escaped)
+ {
+ VerifyIsEscapableCharacter(_serializedText[i]);
+ token.Append(_serializedText[i]);
+ tokenState = State.NotEscaped;
+ }
+ else if (tokenState == State.NotEscaped)
+ {
+ switch (_serializedText[i])
+ {
+ case Esc:
+ tokenState = State.Escaped;
+ break;
+
+ case Lhs:
+ // '[' is an unexpected character
+ throw new SerializationException(Environment.GetResourceString("Serialization_InvalidData"));
+
+ case Rhs:
+ // ']' is an unexpected character
+ throw new SerializationException(Environment.GetResourceString("Serialization_InvalidData"));
+
+ case Sep:
+ _currentTokenStartIndex = i + 1;
+ if (_currentTokenStartIndex >= _serializedText.Length)
+ {
+ _state = State.EndOfLine;
+ }
+ else
+ {
+ _state = State.StartOfToken;
+ }
+ return StringBuilderCache.GetStringAndRelease(token);
+
+ case '\0':
+ // invalid character
+ throw new SerializationException(Environment.GetResourceString("Serialization_InvalidData"));
+
+ default:
+ token.Append(_serializedText[i]);
+ break;
+ }
+ }
+ }
+ //
+ // we are at the end of the line
+ //
+ if (tokenState == State.Escaped)
+ {
+ // we are at the end of the serialized text but we are in an escaped state
+ throw new SerializationException(Environment.GetResourceString("Serialization_InvalidEscapeSequence", string.Empty));
+ }
+
+ throw new SerializationException(Environment.GetResourceString("Serialization_InvalidData"));
+ }
+
+ /// <summary>
+ /// Helper function to read a DateTime token.
+ /// </summary>
+ private DateTime GetNextDateTimeValue(string format)
+ {
+ string token = GetNextStringValue();
+ DateTime time;
+ if (!DateTime.TryParseExact(token, format, DateTimeFormatInfo.InvariantInfo, DateTimeStyles.None, out time))
+ {
+ throw new SerializationException(Environment.GetResourceString("Serialization_InvalidData"));
+ }
+ return time;
+ }
+
+ /// <summary>
+ /// Helper function to read a TimeSpan token.
+ /// </summary>
+ private TimeSpan GetNextTimeSpanValue()
+ {
+ int token = GetNextInt32Value();
+ try
+ {
+ return new TimeSpan(hours: 0, minutes: token, seconds: 0);
+ }
+ catch (ArgumentOutOfRangeException e)
+ {
+ throw new SerializationException(Environment.GetResourceString("Serialization_InvalidData"), e);
+ }
+ }
+
+ /// <summary>
+ /// Helper function to read an Int32 token.
+ /// </summary>
+ private int GetNextInt32Value()
+ {
+ string token = GetNextStringValue();
+ int value;
+ if (!int.TryParse(token, NumberStyles.AllowLeadingSign /* "[sign]digits" */, CultureInfo.InvariantCulture, out value))
+ {
+ throw new SerializationException(Environment.GetResourceString("Serialization_InvalidData"));
+ }
+ return value;
+ }
+
+ /// <summary>
+ /// Helper function to read an AdjustmentRule[] token.
+ /// </summary>
+ private AdjustmentRule[] GetNextAdjustmentRuleArrayValue()
+ {
+ List<AdjustmentRule> rules = new List<AdjustmentRule>(1);
+ int count = 0;
+
+ // individual AdjustmentRule array elements do not require semicolons
+ AdjustmentRule rule = GetNextAdjustmentRuleValue();
+ while (rule != null)
+ {
+ rules.Add(rule);
+ count++;
+
+ rule = GetNextAdjustmentRuleValue();
+ }
+
+ // the AdjustmentRule array must end with a separator
+ if (_state == State.EndOfLine)
+ {
+ throw new SerializationException(Environment.GetResourceString("Serialization_InvalidData"));
+ }
+ if (_currentTokenStartIndex < 0 || _currentTokenStartIndex >= _serializedText.Length)
+ {
+ throw new SerializationException(Environment.GetResourceString("Serialization_InvalidData"));
+ }
+
+ return count != 0 ? rules.ToArray() : null;
+ }
+
+ /// <summary>
+ /// Helper function to read an AdjustmentRule token.
+ /// </summary>
+ private AdjustmentRule GetNextAdjustmentRuleValue()
+ {
+ // first verify the internal state of the object
+ if (_state == State.EndOfLine)
+ {
+ return null;
+ }
+
+ if (_currentTokenStartIndex < 0 || _currentTokenStartIndex >= _serializedText.Length)
+ {
+ throw new SerializationException(Environment.GetResourceString("Serialization_InvalidData"));
+ }
+
+ // check to see if the very first token we see is the separator
+ if (_serializedText[_currentTokenStartIndex] == Sep)
+ {
+ return null;
+ }
+
+ // verify the current token is a left-hand-side marker ("[")
+ if (_serializedText[_currentTokenStartIndex] != Lhs)
+ {
+ throw new SerializationException(Environment.GetResourceString("Serialization_InvalidData"));
+ }
+ _currentTokenStartIndex++;
+
+ DateTime dateStart = GetNextDateTimeValue(DateTimeFormat);
+ DateTime dateEnd = GetNextDateTimeValue(DateTimeFormat);
+ TimeSpan daylightDelta = GetNextTimeSpanValue();
+ TransitionTime daylightStart = GetNextTransitionTimeValue();
+ TransitionTime daylightEnd = GetNextTransitionTimeValue();
+ TimeSpan baseUtcOffsetDelta = TimeSpan.Zero;
+ int noDaylightTransitions = 0;
+
+ // verify that the string is now at the right-hand-side marker ("]") ...
+
+ if (_state == State.EndOfLine || _currentTokenStartIndex >= _serializedText.Length)
+ {
+ throw new SerializationException(Environment.GetResourceString("Serialization_InvalidData"));
+ }
+
+ // Check if we have baseUtcOffsetDelta in the serialized string and then deserialize it
+ if ((_serializedText[_currentTokenStartIndex] >= '0' && _serializedText[_currentTokenStartIndex] <= '9') ||
+ _serializedText[_currentTokenStartIndex] == '-' || _serializedText[_currentTokenStartIndex] == '+')
+ {
+ baseUtcOffsetDelta = GetNextTimeSpanValue();
+ }
+
+ // Check if we have NoDaylightTransitions in the serialized string and then deserialize it
+ if ((_serializedText[_currentTokenStartIndex] >= '0' && _serializedText[_currentTokenStartIndex] <= '1'))
+ {
+ noDaylightTransitions = GetNextInt32Value();
+ }
+
+ if (_state == State.EndOfLine || _currentTokenStartIndex >= _serializedText.Length)
+ {
+ throw new SerializationException(Environment.GetResourceString("Serialization_InvalidData"));
+ }
+
+ if (_serializedText[_currentTokenStartIndex] != Rhs)
+ {
+ // skip ahead of any "v.Next" data at the end of the AdjustmentRule
+ //
+ // FUTURE: if the serialization format is extended in the future then this
+ // code section will need to be changed to read the new fields rather
+ // than just skipping the data at the end of the [AdjustmentRule].
+ SkipVersionNextDataFields(1);
+ }
+ else
+ {
+ _currentTokenStartIndex++;
+ }
+
+ // create the AdjustmentRule from the deserialized fields ...
+
+ AdjustmentRule rule;
+ try
+ {
+ rule = AdjustmentRule.CreateAdjustmentRule(dateStart, dateEnd, daylightDelta, daylightStart, daylightEnd, baseUtcOffsetDelta, noDaylightTransitions > 0);
+ }
+ catch (ArgumentException e)
+ {
+ throw new SerializationException(Environment.GetResourceString("Serialization_InvalidData"), e);
+ }
+
+ // finally set the state to either EndOfLine or StartOfToken for the next caller
+ if (_currentTokenStartIndex >= _serializedText.Length)
+ {
+ _state = State.EndOfLine;
+ }
+ else
+ {
+ _state = State.StartOfToken;
+ }
+ return rule;
+ }
+
+ /// <summary>
+ /// Helper function to read a TransitionTime token.
+ /// </summary>
+ private TransitionTime GetNextTransitionTimeValue()
+ {
+ // first verify the internal state of the object
+
+ if (_state == State.EndOfLine ||
+ (_currentTokenStartIndex < _serializedText.Length && _serializedText[_currentTokenStartIndex] == Rhs))
+ {
+ //
+ // we are at the end of the line or we are starting at a "]" character
+ //
+ throw new SerializationException(Environment.GetResourceString("Serialization_InvalidData"));
+ }
+
+ if (_currentTokenStartIndex < 0 || _currentTokenStartIndex >= _serializedText.Length)
+ {
+ throw new SerializationException(Environment.GetResourceString("Serialization_InvalidData"));
+ }
+
+ // verify the current token is a left-hand-side marker ("[")
+
+ if (_serializedText[_currentTokenStartIndex] != Lhs)
+ {
+ throw new SerializationException(Environment.GetResourceString("Serialization_InvalidData"));
+ }
+ _currentTokenStartIndex++;
+
+ int isFixedDate = GetNextInt32Value();
+
+ if (isFixedDate != 0 && isFixedDate != 1)
+ {
+ throw new SerializationException(Environment.GetResourceString("Serialization_InvalidData"));
+ }
+
+ TransitionTime transition;
+
+ DateTime timeOfDay = GetNextDateTimeValue(TimeOfDayFormat);
+ timeOfDay = new DateTime(1, 1, 1, timeOfDay.Hour, timeOfDay.Minute, timeOfDay.Second, timeOfDay.Millisecond);
+
+ int month = GetNextInt32Value();
+
+ if (isFixedDate == 1)
+ {
+ int day = GetNextInt32Value();
+
+ try
+ {
+ transition = TransitionTime.CreateFixedDateRule(timeOfDay, month, day);
+ }
+ catch (ArgumentException e)
+ {
+ throw new SerializationException(Environment.GetResourceString("Serialization_InvalidData"), e);
+ }
+ }
+ else
+ {
+ int week = GetNextInt32Value();
+ int dayOfWeek = GetNextInt32Value();
+
+ try
+ {
+ transition = TransitionTime.CreateFloatingDateRule(timeOfDay, month, week, (DayOfWeek)dayOfWeek);
+ }
+ catch (ArgumentException e)
+ {
+ throw new SerializationException(Environment.GetResourceString("Serialization_InvalidData"), e);
+ }
+ }
+
+ // verify that the string is now at the right-hand-side marker ("]") ...
+
+ if (_state == State.EndOfLine || _currentTokenStartIndex >= _serializedText.Length)
+ {
+ throw new SerializationException(Environment.GetResourceString("Serialization_InvalidData"));
+ }
+
+ if (_serializedText[_currentTokenStartIndex] != Rhs)
+ {
+ // skip ahead of any "v.Next" data at the end of the AdjustmentRule
+ //
+ // FUTURE: if the serialization format is extended in the future then this
+ // code section will need to be changed to read the new fields rather
+ // than just skipping the data at the end of the [TransitionTime].
+ SkipVersionNextDataFields(1);
+ }
+ else
+ {
+ _currentTokenStartIndex++;
+ }
+
+ // check to see if the string is now at the separator (";") ...
+ bool sepFound = false;
+ if (_currentTokenStartIndex < _serializedText.Length &&
+ _serializedText[_currentTokenStartIndex] == Sep)
+ {
+ // handle the case where we ended on a ";"
+ _currentTokenStartIndex++;
+ sepFound = true;
+ }
+
+ if (!sepFound)
+ {
+ // we MUST end on a separator
+ throw new SerializationException(Environment.GetResourceString("Serialization_InvalidData"));
+ }
+
+ // finally set the state to either EndOfLine or StartOfToken for the next caller
+ if (_currentTokenStartIndex >= _serializedText.Length)
+ {
+ _state = State.EndOfLine;
+ }
+ else
+ {
+ _state = State.StartOfToken;
+ }
+ return transition;
+ }
+ }
+ }
+}
diff --git a/src/mscorlib/src/System/TimeZoneInfo.TransitionTime.cs b/src/mscorlib/src/System/TimeZoneInfo.TransitionTime.cs
new file mode 100644
index 0000000000..dedcb880a4
--- /dev/null
+++ b/src/mscorlib/src/System/TimeZoneInfo.TransitionTime.cs
@@ -0,0 +1,159 @@
+// 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.Serialization;
+
+namespace System
+{
+ public sealed partial class TimeZoneInfo
+ {
+ [Serializable]
+ public struct TransitionTime : IEquatable<TransitionTime>, ISerializable, IDeserializationCallback
+ {
+ private readonly DateTime _timeOfDay;
+ private readonly byte _month;
+ private readonly byte _week;
+ private readonly byte _day;
+ private readonly DayOfWeek _dayOfWeek;
+ private readonly bool _isFixedDateRule;
+
+ public DateTime TimeOfDay => _timeOfDay;
+
+ public int Month => _month;
+
+ public int Week => _week;
+
+ public int Day => _day;
+
+ public DayOfWeek DayOfWeek => _dayOfWeek;
+
+ public bool IsFixedDateRule => _isFixedDateRule;
+
+ [Pure]
+ public override bool Equals(object obj) =>
+ obj is TransitionTime && Equals((TransitionTime)obj);
+
+ public static bool operator ==(TransitionTime t1, TransitionTime t2) => t1.Equals(t2);
+
+ public static bool operator !=(TransitionTime t1, TransitionTime t2) => !t1.Equals(t2);
+
+ [Pure]
+ public bool Equals(TransitionTime other) =>
+ _isFixedDateRule == other._isFixedDateRule &&
+ _timeOfDay == other._timeOfDay &&
+ _month == other._month &&
+ (other._isFixedDateRule ?
+ _day == other._day :
+ _week == other._week && _dayOfWeek == other._dayOfWeek);
+
+ public override int GetHashCode() => (int)_month ^ (int)_week << 8;
+
+ private TransitionTime(DateTime timeOfDay, int month, int week, int day, DayOfWeek dayOfWeek, bool isFixedDateRule)
+ {
+ ValidateTransitionTime(timeOfDay, month, week, day, dayOfWeek);
+
+ _timeOfDay = timeOfDay;
+ _month = (byte)month;
+ _week = (byte)week;
+ _day = (byte)day;
+ _dayOfWeek = dayOfWeek;
+ _isFixedDateRule = isFixedDateRule;
+ }
+
+ public static TransitionTime CreateFixedDateRule(DateTime timeOfDay, int month, int day) =>
+ new TransitionTime(timeOfDay, month, 1, day, DayOfWeek.Sunday, isFixedDateRule: true);
+
+ public static TransitionTime CreateFloatingDateRule(DateTime timeOfDay, int month, int week, DayOfWeek dayOfWeek) =>
+ new TransitionTime(timeOfDay, month, week, 1, dayOfWeek, isFixedDateRule: false);
+
+ /// <summary>
+ /// Helper function that validates a TransitionTime instance.
+ /// </summary>
+ private static void ValidateTransitionTime(DateTime timeOfDay, int month, int week, int day, DayOfWeek dayOfWeek)
+ {
+ if (timeOfDay.Kind != DateTimeKind.Unspecified)
+ {
+ throw new ArgumentException(Environment.GetResourceString("Argument_DateTimeKindMustBeUnspecified"), nameof(timeOfDay));
+ }
+
+ // Month range 1-12
+ if (month < 1 || month > 12)
+ {
+ throw new ArgumentOutOfRangeException(nameof(month), Environment.GetResourceString("ArgumentOutOfRange_MonthParam"));
+ }
+
+ // Day range 1-31
+ if (day < 1 || day > 31)
+ {
+ throw new ArgumentOutOfRangeException(nameof(day), Environment.GetResourceString("ArgumentOutOfRange_DayParam"));
+ }
+
+ // Week range 1-5
+ if (week < 1 || week > 5)
+ {
+ throw new ArgumentOutOfRangeException(nameof(week), Environment.GetResourceString("ArgumentOutOfRange_Week"));
+ }
+
+ // DayOfWeek range 0-6
+ if ((int)dayOfWeek < 0 || (int)dayOfWeek > 6)
+ {
+ 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"), nameof(timeOfDay));
+ }
+ }
+
+ void IDeserializationCallback.OnDeserialization(object sender)
+ {
+ // OnDeserialization is called after each instance of this class is deserialized.
+ // This callback method performs TransitionTime validation after being deserialized.
+
+ try
+ {
+ ValidateTransitionTime(_timeOfDay, _month, _week, _day, _dayOfWeek);
+ }
+ catch (ArgumentException e)
+ {
+ throw new SerializationException(Environment.GetResourceString("Serialization_InvalidData"), e);
+ }
+ }
+
+ void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
+ {
+ if (info == null)
+ {
+ throw new ArgumentNullException(nameof(info));
+ }
+ Contract.EndContractBlock();
+
+ info.AddValue("TimeOfDay", _timeOfDay);
+ info.AddValue("Month", _month);
+ info.AddValue("Week", _week);
+ info.AddValue("Day", _day);
+ info.AddValue("DayOfWeek", _dayOfWeek);
+ info.AddValue("IsFixedDateRule", _isFixedDateRule);
+ }
+
+ TransitionTime(SerializationInfo info, StreamingContext context)
+ {
+ if (info == null)
+ {
+ throw new ArgumentNullException(nameof(info));
+ }
+
+ _timeOfDay = (DateTime)info.GetValue("TimeOfDay", typeof(DateTime));
+ _month = (byte)info.GetValue("Month", typeof(byte));
+ _week = (byte)info.GetValue("Week", typeof(byte));
+ _day = (byte)info.GetValue("Day", typeof(byte));
+ _dayOfWeek = (DayOfWeek)info.GetValue("DayOfWeek", typeof(DayOfWeek));
+ _isFixedDateRule = (bool)info.GetValue("IsFixedDateRule", typeof(bool));
+ }
+ }
+ }
+}
diff --git a/src/mscorlib/src/System/TimeZoneInfo.Unix.cs b/src/mscorlib/src/System/TimeZoneInfo.Unix.cs
new file mode 100644
index 0000000000..b94c8b71c1
--- /dev/null
+++ b/src/mscorlib/src/System/TimeZoneInfo.Unix.cs
@@ -0,0 +1,1463 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+// See the LICENSE file in the project root for more information.
+
+using System.Collections.Generic;
+using System.Diagnostics;
+using System.Diagnostics.Contracts;
+using System.Globalization;
+using System.IO;
+using System.Text;
+using System.Threading;
+using System.Security;
+
+namespace System
+{
+ public sealed partial class TimeZoneInfo
+ {
+ private const string DefaultTimeZoneDirectory = "/usr/share/zoneinfo/";
+ private const string ZoneTabFileName = "zone.tab";
+ private const string TimeZoneEnvironmentVariable = "TZ";
+ private const string TimeZoneDirectoryEnvironmentVariable = "TZDIR";
+
+ private TimeZoneInfo(byte[] data, string id, bool dstDisabled)
+ {
+ TZifHead t;
+ DateTime[] dts;
+ byte[] typeOfLocalTime;
+ TZifType[] transitionType;
+ string zoneAbbreviations;
+ bool[] StandardTime;
+ bool[] GmtTime;
+ string futureTransitionsPosixFormat;
+
+ // parse the raw TZif bytes; this method can throw ArgumentException when the data is malformed.
+ TZif_ParseRaw(data, out t, out dts, out typeOfLocalTime, out transitionType, out zoneAbbreviations, out StandardTime, out GmtTime, out futureTransitionsPosixFormat);
+
+ _id = id;
+ _displayName = LocalId;
+ _baseUtcOffset = TimeSpan.Zero;
+
+ // find the best matching baseUtcOffset and display strings based on the current utcNow value.
+ // NOTE: read the display strings from the the tzfile now in case they can't be loaded later
+ // from the globalization data.
+ DateTime utcNow = DateTime.UtcNow;
+ for (int i = 0; i < dts.Length && dts[i] <= utcNow; i++)
+ {
+ int type = typeOfLocalTime[i];
+ if (!transitionType[type].IsDst)
+ {
+ _baseUtcOffset = transitionType[type].UtcOffset;
+ _standardDisplayName = TZif_GetZoneAbbreviation(zoneAbbreviations, transitionType[type].AbbreviationIndex);
+ }
+ else
+ {
+ _daylightDisplayName = TZif_GetZoneAbbreviation(zoneAbbreviations, transitionType[type].AbbreviationIndex);
+ }
+ }
+
+ if (dts.Length == 0)
+ {
+ // time zones like Africa/Bujumbura and Etc/GMT* have no transition times but still contain
+ // TZifType entries that may contain a baseUtcOffset and display strings
+ for (int i = 0; i < transitionType.Length; i++)
+ {
+ if (!transitionType[i].IsDst)
+ {
+ _baseUtcOffset = transitionType[i].UtcOffset;
+ _standardDisplayName = TZif_GetZoneAbbreviation(zoneAbbreviations, transitionType[i].AbbreviationIndex);
+ }
+ else
+ {
+ _daylightDisplayName = TZif_GetZoneAbbreviation(zoneAbbreviations, transitionType[i].AbbreviationIndex);
+ }
+ }
+ }
+ _displayName = _standardDisplayName;
+
+ GetDisplayName(Interop.GlobalizationInterop.TimeZoneDisplayNameType.Generic, ref _displayName);
+ GetDisplayName(Interop.GlobalizationInterop.TimeZoneDisplayNameType.Standard, ref _standardDisplayName);
+ GetDisplayName(Interop.GlobalizationInterop.TimeZoneDisplayNameType.DaylightSavings, ref _daylightDisplayName);
+
+ // TZif supports seconds-level granularity with offsets but TimeZoneInfo only supports minutes since it aligns
+ // with DateTimeOffset, SQL Server, and the W3C XML Specification
+ if (_baseUtcOffset.Ticks % TimeSpan.TicksPerMinute != 0)
+ {
+ _baseUtcOffset = new TimeSpan(_baseUtcOffset.Hours, _baseUtcOffset.Minutes, 0);
+ }
+
+ if (!dstDisabled)
+ {
+ // only create the adjustment rule if DST is enabled
+ TZif_GenerateAdjustmentRules(out _adjustmentRules, _baseUtcOffset, dts, typeOfLocalTime, transitionType, StandardTime, GmtTime, futureTransitionsPosixFormat);
+ }
+
+ ValidateTimeZoneInfo(_id, _baseUtcOffset, _adjustmentRules, out _supportsDaylightSavingTime);
+ }
+
+ private void GetDisplayName(Interop.GlobalizationInterop.TimeZoneDisplayNameType nameType, ref string displayName)
+ {
+ string timeZoneDisplayName;
+ bool result = Interop.CallStringMethod(
+ (locale, id, type, stringBuilder) => Interop.GlobalizationInterop.GetTimeZoneDisplayName(
+ locale,
+ id,
+ type,
+ stringBuilder,
+ stringBuilder.Capacity),
+ CultureInfo.CurrentUICulture.Name,
+ _id,
+ nameType,
+ out timeZoneDisplayName);
+
+ // If there is an unknown error, don't set the displayName field.
+ // It will be set to the abbreviation that was read out of the tzfile.
+ if (result)
+ {
+ displayName = timeZoneDisplayName;
+ }
+ }
+
+ /// <summary>
+ /// Returns a cloned array of AdjustmentRule objects
+ /// </summary>
+ public AdjustmentRule[] GetAdjustmentRules()
+ {
+ if (_adjustmentRules == null)
+ {
+ return Array.Empty<AdjustmentRule>();
+ }
+
+ // 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
+
+ AdjustmentRule[] rules = new AdjustmentRule[_adjustmentRules.Length];
+
+ for (int i = 0; i < _adjustmentRules.Length; i++)
+ {
+ var rule = _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;
+ }
+
+ private static void PopulateAllSystemTimeZones(CachedData cachedData)
+ {
+ Debug.Assert(Monitor.IsEntered(cachedData));
+
+ string timeZoneDirectory = GetTimeZoneDirectory();
+ foreach (string timeZoneId in GetTimeZoneIds(timeZoneDirectory))
+ {
+ TimeZoneInfo value;
+ Exception ex;
+ TryGetTimeZone(timeZoneId, false, out value, out ex, cachedData, alwaysFallbackToLocalMachine: true); // populate the cache
+ }
+ }
+
+ /// <summary>
+ /// Helper function for retrieving the local system time zone.
+ /// May throw COMException, TimeZoneNotFoundException, InvalidTimeZoneException.
+ /// Assumes cachedData lock is taken.
+ /// </summary>
+ /// <returns>A new TimeZoneInfo instance.</returns>
+ private static TimeZoneInfo GetLocalTimeZone(CachedData cachedData)
+ {
+ Debug.Assert(Monitor.IsEntered(cachedData));
+
+ // Without Registry support, create the TimeZoneInfo from a TZ file
+ return GetLocalTimeZoneFromTzFile();
+ }
+
+ private static TimeZoneInfoResult TryGetTimeZoneFromLocalMachine(string id, out TimeZoneInfo value, out Exception e)
+ {
+ value = null;
+ e = null;
+
+ string timeZoneDirectory = GetTimeZoneDirectory();
+ string timeZoneFilePath = Path.Combine(timeZoneDirectory, id);
+ byte[] rawData;
+ try
+ {
+ rawData = File.ReadAllBytes(timeZoneFilePath);
+ }
+ catch (UnauthorizedAccessException ex)
+ {
+ e = ex;
+ return TimeZoneInfoResult.SecurityException;
+ }
+ catch (FileNotFoundException ex)
+ {
+ e = ex;
+ return TimeZoneInfoResult.TimeZoneNotFoundException;
+ }
+ catch (DirectoryNotFoundException ex)
+ {
+ e = ex;
+ return TimeZoneInfoResult.TimeZoneNotFoundException;
+ }
+ catch (IOException ex)
+ {
+ e = new InvalidTimeZoneException(Environment.GetResourceString("InvalidTimeZone_InvalidFileData", id, timeZoneFilePath), ex);
+ return TimeZoneInfoResult.InvalidTimeZoneException;
+ }
+
+ value = GetTimeZoneFromTzData(rawData, id);
+
+ if (value == null)
+ {
+ e = new InvalidTimeZoneException(Environment.GetResourceString("InvalidTimeZone_InvalidFileData", id, timeZoneFilePath));
+ return TimeZoneInfoResult.InvalidTimeZoneException;
+ }
+
+ return TimeZoneInfoResult.Success;
+ }
+
+ /// <summary>
+ /// Returns a collection of TimeZone Id values from the zone.tab file in the timeZoneDirectory.
+ /// </summary>
+ /// <remarks>
+ /// Lines that start with # are comments and are skipped.
+ /// </remarks>
+ private static List<string> GetTimeZoneIds(string timeZoneDirectory)
+ {
+ string[] zoneTabFileLines = null;
+ try
+ {
+ zoneTabFileLines = File.ReadAllLines(Path.Combine(timeZoneDirectory, ZoneTabFileName));
+ }
+ catch (IOException) { }
+ catch (UnauthorizedAccessException) { }
+
+ if (zoneTabFileLines == null)
+ {
+ return new List<string>();
+ }
+
+ List<string> timeZoneIds = new List<string>(zoneTabFileLines.Length);
+
+ foreach (string zoneTabFileLine in zoneTabFileLines)
+ {
+ if (!string.IsNullOrEmpty(zoneTabFileLine) && zoneTabFileLine[0] != '#')
+ {
+ // the format of the line is "country-code \t coordinates \t TimeZone Id \t comments"
+
+ int firstTabIndex = zoneTabFileLine.IndexOf('\t');
+ if (firstTabIndex != -1)
+ {
+ int secondTabIndex = zoneTabFileLine.IndexOf('\t', firstTabIndex + 1);
+ if (secondTabIndex != -1)
+ {
+ string timeZoneId;
+ int startIndex = secondTabIndex + 1;
+ int thirdTabIndex = zoneTabFileLine.IndexOf('\t', startIndex);
+ if (thirdTabIndex != -1)
+ {
+ int length = thirdTabIndex - startIndex;
+ timeZoneId = zoneTabFileLine.Substring(startIndex, length);
+ }
+ else
+ {
+ timeZoneId = zoneTabFileLine.Substring(startIndex);
+ }
+
+ if (!string.IsNullOrEmpty(timeZoneId))
+ {
+ timeZoneIds.Add(timeZoneId);
+ }
+ }
+ }
+ }
+ }
+
+ return timeZoneIds;
+ }
+
+ /// <summary>
+ /// Gets the tzfile raw data for the current 'local' time zone using the following rules.
+ /// 1. Read the TZ environment variable. If it is set, use it.
+ /// 2. Look for the data in /etc/localtime.
+ /// 3. Look for the data in GetTimeZoneDirectory()/localtime.
+ /// 4. Use UTC if all else fails.
+ /// </summary>
+ private static bool TryGetLocalTzFile(out byte[] rawData, out string id)
+ {
+ rawData = null;
+ id = null;
+ string tzVariable = GetTzEnvironmentVariable();
+
+ // If the env var is null, use the localtime file
+ if (tzVariable == null)
+ {
+ return
+ TryLoadTzFile("/etc/localtime", ref rawData, ref id) ||
+ TryLoadTzFile(Path.Combine(GetTimeZoneDirectory(), "localtime"), ref rawData, ref id);
+ }
+
+ // If it's empty, use UTC (TryGetLocalTzFile() should return false).
+ if (tzVariable.Length == 0)
+ {
+ return false;
+ }
+
+ // Otherwise, use the path from the env var. If it's not absolute, make it relative
+ // to the system timezone directory
+ string tzFilePath;
+ if (tzVariable[0] != '/')
+ {
+ id = tzVariable;
+ tzFilePath = Path.Combine(GetTimeZoneDirectory(), tzVariable);
+ }
+ else
+ {
+ tzFilePath = tzVariable;
+ }
+ return TryLoadTzFile(tzFilePath, ref rawData, ref id);
+ }
+
+ private static string GetTzEnvironmentVariable()
+ {
+ string result = Environment.GetEnvironmentVariable(TimeZoneEnvironmentVariable);
+ if (!string.IsNullOrEmpty(result))
+ {
+ if (result[0] == ':')
+ {
+ // strip off the ':' prefix
+ result = result.Substring(1);
+ }
+ }
+
+ return result;
+ }
+
+ private static bool TryLoadTzFile(string tzFilePath, ref byte[] rawData, ref string id)
+ {
+ if (File.Exists(tzFilePath))
+ {
+ try
+ {
+ rawData = File.ReadAllBytes(tzFilePath);
+ if (string.IsNullOrEmpty(id))
+ {
+ id = FindTimeZoneIdUsingReadLink(tzFilePath);
+
+ if (string.IsNullOrEmpty(id))
+ {
+ id = FindTimeZoneId(rawData);
+ }
+ }
+ return true;
+ }
+ catch (IOException) { }
+ catch (SecurityException) { }
+ catch (UnauthorizedAccessException) { }
+ }
+ return false;
+ }
+
+ /// <summary>
+ /// Finds the time zone id by using 'readlink' on the path to see if tzFilePath is
+ /// a symlink to a file.
+ /// </summary>
+ private static string FindTimeZoneIdUsingReadLink(string tzFilePath)
+ {
+ string id = null;
+
+ StringBuilder symlinkPathBuilder = StringBuilderCache.Acquire(Path.MaxPath);
+ bool result = Interop.GlobalizationInterop.ReadLink(tzFilePath, symlinkPathBuilder, (uint)symlinkPathBuilder.Capacity);
+ if (result)
+ {
+ string symlinkPath = StringBuilderCache.GetStringAndRelease(symlinkPathBuilder);
+ // time zone Ids have to point under the time zone directory
+ string timeZoneDirectory = GetTimeZoneDirectory();
+ if (symlinkPath.StartsWith(timeZoneDirectory))
+ {
+ id = symlinkPath.Substring(timeZoneDirectory.Length);
+ }
+ }
+ else
+ {
+ StringBuilderCache.Release(symlinkPathBuilder);
+ }
+
+ return id;
+ }
+
+ /// <summary>
+ /// Find the time zone id by searching all the tzfiles for the one that matches rawData
+ /// and return its file name.
+ /// </summary>
+ private static string FindTimeZoneId(byte[] rawData)
+ {
+ // default to "Local" if we can't find the right tzfile
+ string id = LocalId;
+ string timeZoneDirectory = GetTimeZoneDirectory();
+ string localtimeFilePath = Path.Combine(timeZoneDirectory, "localtime");
+ string posixrulesFilePath = Path.Combine(timeZoneDirectory, "posixrules");
+ byte[] buffer = new byte[rawData.Length];
+
+ try
+ {
+ foreach (string filePath in Directory.EnumerateFiles(timeZoneDirectory, "*", SearchOption.AllDirectories))
+ {
+ // skip the localtime and posixrules file, since they won't give us the correct id
+ if (!string.Equals(filePath, localtimeFilePath, StringComparison.OrdinalIgnoreCase)
+ && !string.Equals(filePath, posixrulesFilePath, StringComparison.OrdinalIgnoreCase))
+ {
+ if (CompareTimeZoneFile(filePath, buffer, rawData))
+ {
+ // if all bytes are the same, this must be the right tz file
+ id = filePath;
+
+ // strip off the root time zone directory
+ if (id.StartsWith(timeZoneDirectory))
+ {
+ id = id.Substring(timeZoneDirectory.Length);
+ }
+ break;
+ }
+ }
+ }
+ }
+ catch (IOException) { }
+ catch (SecurityException) { }
+ catch (UnauthorizedAccessException) { }
+
+ return id;
+ }
+
+ private static bool CompareTimeZoneFile(string filePath, byte[] buffer, byte[] rawData)
+ {
+ try
+ {
+ using (FileStream stream = new FileStream(filePath, FileMode.Open, FileAccess.Read))
+ {
+ if (stream.Length == rawData.Length)
+ {
+ int index = 0;
+ int count = rawData.Length;
+
+ while (count > 0)
+ {
+ int n = stream.Read(buffer, index, count);
+ if (n == 0)
+ __Error.EndOfFile();
+
+ int end = index + n;
+ for (; index < end; index++)
+ {
+ if (buffer[index] != rawData[index])
+ {
+ return false;
+ }
+ }
+
+ count -= n;
+ }
+
+ return true;
+ }
+ }
+ }
+ catch (IOException) { }
+ catch (SecurityException) { }
+ catch (UnauthorizedAccessException) { }
+
+ return false;
+ }
+
+ /// <summary>
+ /// Helper function used by 'GetLocalTimeZone()' - this function wraps the call
+ /// for loading time zone data from computers without Registry support.
+ ///
+ /// The TryGetLocalTzFile() call returns a Byte[] containing the compiled tzfile.
+ /// </summary>
+ private static TimeZoneInfo GetLocalTimeZoneFromTzFile()
+ {
+ byte[] rawData;
+ string id;
+ if (TryGetLocalTzFile(out rawData, out id))
+ {
+ TimeZoneInfo result = GetTimeZoneFromTzData(rawData, id);
+ if (result != null)
+ {
+ return result;
+ }
+ }
+
+ // if we can't find a local time zone, return UTC
+ return Utc;
+ }
+
+ private static TimeZoneInfo GetTimeZoneFromTzData(byte[] rawData, string id)
+ {
+ if (rawData != null)
+ {
+ try
+ {
+ return new TimeZoneInfo(rawData, id, dstDisabled: false); // create a TimeZoneInfo instance from the TZif data w/ DST support
+ }
+ catch (ArgumentException) { }
+ catch (InvalidTimeZoneException) { }
+ try
+ {
+ return new TimeZoneInfo(rawData, id, dstDisabled: true); // create a TimeZoneInfo instance from the TZif data w/o DST support
+ }
+ catch (ArgumentException) { }
+ catch (InvalidTimeZoneException) { }
+ }
+
+ return null;
+ }
+
+ private static string GetTimeZoneDirectory()
+ {
+ string tzDirectory = Environment.GetEnvironmentVariable(TimeZoneDirectoryEnvironmentVariable);
+
+ if (tzDirectory == null)
+ {
+ tzDirectory = DefaultTimeZoneDirectory;
+ }
+ else if (!tzDirectory.EndsWith(Path.DirectorySeparatorChar))
+ {
+ tzDirectory += Path.DirectorySeparatorChar;
+ }
+
+ return tzDirectory;
+ }
+
+ /// <summary>
+ /// Helper function for retrieving a TimeZoneInfo object by <time_zone_name>.
+ /// This function wraps the logic necessary to keep the private
+ /// SystemTimeZones cache in working order
+ ///
+ /// This function will either return a valid TimeZoneInfo instance or
+ /// it will throw 'InvalidTimeZoneException' / 'TimeZoneNotFoundException'.
+ /// </summary>
+ public static TimeZoneInfo FindSystemTimeZoneById(string id)
+ {
+ // Special case for Utc as it will not exist in the dictionary with the rest
+ // of the system time zones. There is no need to do this check for Local.Id
+ // since Local is a real time zone that exists in the dictionary cache
+ if (string.Equals(id, UtcId, StringComparison.OrdinalIgnoreCase))
+ {
+ return Utc;
+ }
+
+ if (id == null)
+ {
+ throw new ArgumentNullException(nameof(id));
+ }
+ else if (id.Length == 0 || id.Contains("\0"))
+ {
+ throw new TimeZoneNotFoundException(Environment.GetResourceString("TimeZoneNotFound_MissingData", id));
+ }
+
+ TimeZoneInfo value;
+ Exception e;
+
+ TimeZoneInfoResult result;
+
+ CachedData cachedData = s_cachedData;
+
+ lock (cachedData)
+ {
+ result = TryGetTimeZone(id, false, out value, out e, cachedData, alwaysFallbackToLocalMachine: true);
+ }
+
+ if (result == TimeZoneInfoResult.Success)
+ {
+ return value;
+ }
+ else if (result == TimeZoneInfoResult.InvalidTimeZoneException)
+ {
+ Debug.Assert(e is InvalidTimeZoneException,
+ "TryGetTimeZone must create an InvalidTimeZoneException when it returns TimeZoneInfoResult.InvalidTimeZoneException");
+ throw e;
+ }
+ else if (result == TimeZoneInfoResult.SecurityException)
+ {
+ throw new SecurityException(Environment.GetResourceString("Security_CannotReadFileData", id), e);
+ }
+ else
+ {
+ throw new TimeZoneNotFoundException(Environment.GetResourceString("TimeZoneNotFound_MissingData", id), e);
+ }
+ }
+
+ // DateTime.Now fast path that avoids allocating an historically accurate TimeZoneInfo.Local and just creates a 1-year (current year) accurate time zone
+ internal static TimeSpan GetDateTimeNowUtcOffsetFromUtc(DateTime time, out bool isAmbiguousLocalDst)
+ {
+ bool isDaylightSavings;
+ // Use the standard code path for Unix since there isn't a faster way of handling current-year-only time zones
+ return GetUtcOffsetFromUtc(time, Local, out isDaylightSavings, out isAmbiguousLocalDst);
+ }
+
+ // TZFILE(5) BSD File Formats Manual TZFILE(5)
+ //
+ // NAME
+ // tzfile -- timezone information
+ //
+ // SYNOPSIS
+ // #include "/usr/src/lib/libc/stdtime/tzfile.h"
+ //
+ // DESCRIPTION
+ // The time zone information files used by tzset(3) begin with the magic
+ // characters ``TZif'' to identify them as time zone information files, fol-
+ // lowed by sixteen bytes reserved for future use, followed by four four-
+ // byte values written in a ``standard'' byte order (the high-order byte of
+ // the value is written first). These values are, in order:
+ //
+ // tzh_ttisgmtcnt The number of UTC/local indicators stored in the file.
+ // tzh_ttisstdcnt The number of standard/wall indicators stored in the
+ // file.
+ // tzh_leapcnt The number of leap seconds for which data is stored in
+ // the file.
+ // tzh_timecnt The number of ``transition times'' for which data is
+ // stored in the file.
+ // tzh_typecnt The number of ``local time types'' for which data is
+ // stored in the file (must not be zero).
+ // tzh_charcnt The number of characters of ``time zone abbreviation
+ // strings'' stored in the file.
+ //
+ // The above header is followed by tzh_timecnt four-byte values of type
+ // long, sorted in ascending order. These values are written in ``stan-
+ // dard'' byte order. Each is used as a transition time (as returned by
+ // time(3)) at which the rules for computing local time change. Next come
+ // tzh_timecnt one-byte values of type unsigned char; each one tells which
+ // of the different types of ``local time'' types described in the file is
+ // associated with the same-indexed transition time. These values serve as
+ // indices into an array of ttinfo structures that appears next in the file;
+ // these structures are defined as follows:
+ //
+ // struct ttinfo {
+ // long tt_gmtoff;
+ // int tt_isdst;
+ // unsigned int tt_abbrind;
+ // };
+ //
+ // Each structure is written as a four-byte value for tt_gmtoff of type
+ // long, in a standard byte order, followed by a one-byte value for tt_isdst
+ // and a one-byte value for tt_abbrind. In each structure, tt_gmtoff gives
+ // the number of seconds to be added to UTC, tt_isdst tells whether tm_isdst
+ // should be set by localtime(3) and tt_abbrind serves as an index into the
+ // array of time zone abbreviation characters that follow the ttinfo struc-
+ // ture(s) in the file.
+ //
+ // Then there are tzh_leapcnt pairs of four-byte values, written in standard
+ // byte order; the first value of each pair gives the time (as returned by
+ // time(3)) at which a leap second occurs; the second gives the total number
+ // of leap seconds to be applied after the given time. The pairs of values
+ // are sorted in ascending order by time.b
+ //
+ // Then there are tzh_ttisstdcnt standard/wall indicators, each stored as a
+ // one-byte value; they tell whether the transition times associated with
+ // local time types were specified as standard time or wall clock time, and
+ // are used when a time zone file is used in handling POSIX-style time zone
+ // environment variables.
+ //
+ // Finally there are tzh_ttisgmtcnt UTC/local indicators, each stored as a
+ // one-byte value; they tell whether the transition times associated with
+ // local time types were specified as UTC or local time, and are used when a
+ // time zone file is used in handling POSIX-style time zone environment
+ // variables.
+ //
+ // localtime uses the first standard-time ttinfo structure in the file (or
+ // simply the first ttinfo structure in the absence of a standard-time
+ // structure) if either tzh_timecnt is zero or the time argument is less
+ // than the first transition time recorded in the file.
+ //
+ // SEE ALSO
+ // ctime(3), time2posix(3), zic(8)
+ //
+ // BSD September 13, 1994 BSD
+ //
+ //
+ //
+ // TIME(3) BSD Library Functions Manual TIME(3)
+ //
+ // NAME
+ // time -- get time of day
+ //
+ // LIBRARY
+ // Standard C Library (libc, -lc)
+ //
+ // SYNOPSIS
+ // #include <time.h>
+ //
+ // time_t
+ // time(time_t *tloc);
+ //
+ // DESCRIPTION
+ // The time() function returns the value of time in seconds since 0 hours, 0
+ // minutes, 0 seconds, January 1, 1970, Coordinated Universal Time, without
+ // including leap seconds. If an error occurs, time() returns the value
+ // (time_t)-1.
+ //
+ // The return value is also stored in *tloc, provided that tloc is non-null.
+ //
+ // ERRORS
+ // The time() function may fail for any of the reasons described in
+ // gettimeofday(2).
+ //
+ // SEE ALSO
+ // gettimeofday(2), ctime(3)
+ //
+ // STANDARDS
+ // The time function conforms to IEEE Std 1003.1-2001 (``POSIX.1'').
+ //
+ // BUGS
+ // Neither ISO/IEC 9899:1999 (``ISO C99'') nor IEEE Std 1003.1-2001
+ // (``POSIX.1'') requires time() to set errno on failure; thus, it is impos-
+ // sible for an application to distinguish the valid time value -1 (repre-
+ // senting the last UTC second of 1969) from the error return value.
+ //
+ // Systems conforming to earlier versions of the C and POSIX standards
+ // (including older versions of FreeBSD) did not set *tloc in the error
+ // case.
+ //
+ // HISTORY
+ // A time() function appeared in Version 6 AT&T UNIX.
+ //
+ // BSD July 18, 2003 BSD
+ //
+ //
+ private static void TZif_GenerateAdjustmentRules(out AdjustmentRule[] rules, TimeSpan baseUtcOffset, DateTime[] dts, byte[] typeOfLocalTime,
+ TZifType[] transitionType, bool[] StandardTime, bool[] GmtTime, string futureTransitionsPosixFormat)
+ {
+ rules = null;
+
+ if (dts.Length > 0)
+ {
+ int index = 0;
+ List<AdjustmentRule> rulesList = new List<AdjustmentRule>();
+
+ while (index <= dts.Length)
+ {
+ TZif_GenerateAdjustmentRule(ref index, baseUtcOffset, rulesList, dts, typeOfLocalTime, transitionType, StandardTime, GmtTime, futureTransitionsPosixFormat);
+ }
+
+ rules = rulesList.ToArray();
+ if (rules != null && rules.Length == 0)
+ {
+ rules = null;
+ }
+ }
+ }
+
+ private static void TZif_GenerateAdjustmentRule(ref int index, TimeSpan timeZoneBaseUtcOffset, List<AdjustmentRule> rulesList, DateTime[] dts,
+ byte[] typeOfLocalTime, TZifType[] transitionTypes, bool[] StandardTime, bool[] GmtTime, string futureTransitionsPosixFormat)
+ {
+ // To generate AdjustmentRules, use the following approach:
+ // The first AdjustmentRule will go from DateTime.MinValue to the first transition time greater than DateTime.MinValue.
+ // Each middle AdjustmentRule wil go from dts[index-1] to dts[index].
+ // The last AdjustmentRule will go from dts[dts.Length-1] to Datetime.MaxValue.
+
+ // 0. Skip any DateTime.MinValue transition times. In newer versions of the tzfile, there
+ // is a "big bang" transition time, which is before the year 0001. Since any times before year 0001
+ // cannot be represented by DateTime, there is no reason to make AdjustmentRules for these unrepresentable time periods.
+ // 1. If there are no DateTime.MinValue times, the first AdjustmentRule goes from DateTime.MinValue
+ // to the first transition and uses the first standard transitionType (or the first transitionType if none of them are standard)
+ // 2. Create an AdjustmentRule for each transition, i.e. from dts[index - 1] to dts[index].
+ // This rule uses the transitionType[index - 1] and the whole AdjustmentRule only describes a single offset - either
+ // all daylight savings, or all stanard time.
+ // 3. After all the transitions are filled out, the last AdjustmentRule is created from either:
+ // a. a POSIX-style timezone description ("futureTransitionsPosixFormat"), if there is one or
+ // b. continue the last transition offset until DateTime.Max
+
+ while (index < dts.Length && dts[index] == DateTime.MinValue)
+ {
+ index++;
+ }
+
+ if (index == 0)
+ {
+ TZifType transitionType = TZif_GetEarlyDateTransitionType(transitionTypes);
+ DateTime endTransitionDate = dts[index];
+
+ TimeSpan transitionOffset = TZif_CalculateTransitionOffsetFromBase(transitionType.UtcOffset, timeZoneBaseUtcOffset);
+ TimeSpan daylightDelta = transitionType.IsDst ? transitionOffset : TimeSpan.Zero;
+ TimeSpan baseUtcDelta = transitionType.IsDst ? TimeSpan.Zero : transitionOffset;
+
+ AdjustmentRule r = AdjustmentRule.CreateAdjustmentRule(
+ DateTime.MinValue,
+ endTransitionDate.AddTicks(-1),
+ daylightDelta,
+ default(TransitionTime),
+ default(TransitionTime),
+ baseUtcDelta,
+ noDaylightTransitions: true);
+ rulesList.Add(r);
+ }
+ else if (index < dts.Length)
+ {
+ DateTime startTransitionDate = dts[index - 1];
+ TZifType startTransitionType = transitionTypes[typeOfLocalTime[index - 1]];
+
+ DateTime endTransitionDate = dts[index];
+
+ TimeSpan transitionOffset = TZif_CalculateTransitionOffsetFromBase(startTransitionType.UtcOffset, timeZoneBaseUtcOffset);
+ TimeSpan daylightDelta = startTransitionType.IsDst ? transitionOffset : TimeSpan.Zero;
+ TimeSpan baseUtcDelta = startTransitionType.IsDst ? TimeSpan.Zero : transitionOffset;
+
+ TransitionTime dstStart;
+ if (startTransitionType.IsDst)
+ {
+ // the TransitionTime fields are not used when AdjustmentRule.NoDaylightTransitions == true.
+ // However, there are some cases in the past where DST = true, and the daylight savings offset
+ // now equals what the current BaseUtcOffset is. In that case, the AdjustmentRule.DaylightOffset
+ // is going to be TimeSpan.Zero. But we still need to return 'true' from AdjustmentRule.HasDaylightSaving.
+ // To ensure we always return true from HasDaylightSaving, make a "special" dstStart that will make the logic
+ // in HasDaylightSaving return true.
+ dstStart = TransitionTime.CreateFixedDateRule(DateTime.MinValue.AddMilliseconds(2), 1, 1);
+ }
+ else
+ {
+ dstStart = default(TransitionTime);
+ }
+
+ AdjustmentRule r = AdjustmentRule.CreateAdjustmentRule(
+ startTransitionDate,
+ endTransitionDate.AddTicks(-1),
+ daylightDelta,
+ dstStart,
+ default(TransitionTime),
+ baseUtcDelta,
+ noDaylightTransitions: true);
+ rulesList.Add(r);
+ }
+ else
+ {
+ // create the AdjustmentRule that will be used for all DateTimes after the last transition
+
+ // NOTE: index == dts.Length
+ DateTime startTransitionDate = dts[index - 1];
+
+ if (!string.IsNullOrEmpty(futureTransitionsPosixFormat))
+ {
+ AdjustmentRule r = TZif_CreateAdjustmentRuleForPosixFormat(futureTransitionsPosixFormat, startTransitionDate, timeZoneBaseUtcOffset);
+ if (r != null)
+ {
+ rulesList.Add(r);
+ }
+ }
+ else
+ {
+ // just use the last transition as the rule which will be used until the end of time
+
+ TZifType transitionType = transitionTypes[typeOfLocalTime[index - 1]];
+ TimeSpan transitionOffset = TZif_CalculateTransitionOffsetFromBase(transitionType.UtcOffset, timeZoneBaseUtcOffset);
+ TimeSpan daylightDelta = transitionType.IsDst ? transitionOffset : TimeSpan.Zero;
+ TimeSpan baseUtcDelta = transitionType.IsDst ? TimeSpan.Zero : transitionOffset;
+
+ AdjustmentRule r = AdjustmentRule.CreateAdjustmentRule(
+ startTransitionDate,
+ DateTime.MaxValue,
+ daylightDelta,
+ default(TransitionTime),
+ default(TransitionTime),
+ baseUtcDelta,
+ noDaylightTransitions: true);
+ rulesList.Add(r);
+ }
+ }
+
+ index++;
+ }
+
+ private static TimeSpan TZif_CalculateTransitionOffsetFromBase(TimeSpan transitionOffset, TimeSpan timeZoneBaseUtcOffset)
+ {
+ TimeSpan result = transitionOffset - timeZoneBaseUtcOffset;
+
+ // TZif supports seconds-level granularity with offsets but TimeZoneInfo only supports minutes since it aligns
+ // with DateTimeOffset, SQL Server, and the W3C XML Specification
+ if (result.Ticks % TimeSpan.TicksPerMinute != 0)
+ {
+ result = new TimeSpan(result.Hours, result.Minutes, 0);
+ }
+
+ return result;
+ }
+
+ /// <summary>
+ /// Gets the first standard-time transition type, or simply the first transition type
+ /// if there are no standard transition types.
+ /// </summary>>
+ /// <remarks>
+ /// from 'man tzfile':
+ /// localtime(3) uses the first standard-time ttinfo structure in the file
+ /// (or simply the first ttinfo structure in the absence of a standard-time
+ /// structure) if either tzh_timecnt is zero or the time argument is less
+ /// than the first transition time recorded in the file.
+ /// </remarks>
+ private static TZifType TZif_GetEarlyDateTransitionType(TZifType[] transitionTypes)
+ {
+ foreach (TZifType transitionType in transitionTypes)
+ {
+ if (!transitionType.IsDst)
+ {
+ return transitionType;
+ }
+ }
+
+ if (transitionTypes.Length > 0)
+ {
+ return transitionTypes[0];
+ }
+
+ throw new InvalidTimeZoneException(Environment.GetResourceString("InvalidTimeZone_NoTTInfoStructures"));
+ }
+
+ /// <summary>
+ /// Creates an AdjustmentRule given the POSIX TZ environment variable string.
+ /// </summary>
+ /// <remarks>
+ /// See http://www.gnu.org/software/libc/manual/html_node/TZ-Variable.html for the format and semantics of this POSX string.
+ /// </remarks>
+ private static AdjustmentRule TZif_CreateAdjustmentRuleForPosixFormat(string posixFormat, DateTime startTransitionDate, TimeSpan timeZoneBaseUtcOffset)
+ {
+ string standardName;
+ string standardOffset;
+ string daylightSavingsName;
+ string daylightSavingsOffset;
+ string start;
+ string startTime;
+ string end;
+ string endTime;
+
+ if (TZif_ParsePosixFormat(posixFormat, out standardName, out standardOffset, out daylightSavingsName,
+ out daylightSavingsOffset, out start, out startTime, out end, out endTime))
+ {
+ // a valid posixFormat has at least standardName and standardOffset
+
+ TimeSpan? parsedBaseOffset = TZif_ParseOffsetString(standardOffset);
+ if (parsedBaseOffset.HasValue)
+ {
+ TimeSpan baseOffset = parsedBaseOffset.Value.Negate(); // offsets are backwards in POSIX notation
+ baseOffset = TZif_CalculateTransitionOffsetFromBase(baseOffset, timeZoneBaseUtcOffset);
+
+ // having a daylightSavingsName means there is a DST rule
+ if (!string.IsNullOrEmpty(daylightSavingsName))
+ {
+ TimeSpan? parsedDaylightSavings = TZif_ParseOffsetString(daylightSavingsOffset);
+ TimeSpan daylightSavingsTimeSpan;
+ if (!parsedDaylightSavings.HasValue)
+ {
+ // default DST to 1 hour if it isn't specified
+ daylightSavingsTimeSpan = new TimeSpan(1, 0, 0);
+ }
+ else
+ {
+ daylightSavingsTimeSpan = parsedDaylightSavings.Value.Negate(); // offsets are backwards in POSIX notation
+ daylightSavingsTimeSpan = TZif_CalculateTransitionOffsetFromBase(daylightSavingsTimeSpan, timeZoneBaseUtcOffset);
+ daylightSavingsTimeSpan = TZif_CalculateTransitionOffsetFromBase(daylightSavingsTimeSpan, baseOffset);
+ }
+
+ TransitionTime dstStart = TZif_CreateTransitionTimeFromPosixRule(start, startTime);
+ TransitionTime dstEnd = TZif_CreateTransitionTimeFromPosixRule(end, endTime);
+
+ return AdjustmentRule.CreateAdjustmentRule(
+ startTransitionDate,
+ DateTime.MaxValue,
+ daylightSavingsTimeSpan,
+ dstStart,
+ dstEnd,
+ baseOffset,
+ noDaylightTransitions: false);
+ }
+ else
+ {
+ // if there is no daylightSavingsName, the whole AdjustmentRule should be with no transitions - just the baseOffset
+ return AdjustmentRule.CreateAdjustmentRule(
+ startTransitionDate,
+ DateTime.MaxValue,
+ TimeSpan.Zero,
+ default(TransitionTime),
+ default(TransitionTime),
+ baseOffset,
+ noDaylightTransitions: true);
+ }
+ }
+ }
+
+ return null;
+ }
+
+ private static TimeSpan? TZif_ParseOffsetString(string offset)
+ {
+ TimeSpan? result = null;
+
+ if (!string.IsNullOrEmpty(offset))
+ {
+ bool negative = offset[0] == '-';
+ if (negative || offset[0] == '+')
+ {
+ offset = offset.Substring(1);
+ }
+
+ // Try parsing just hours first.
+ // Note, TimeSpan.TryParseExact "%h" can't be used here because some time zones using values
+ // like "26" or "144" and TimeSpan parsing would turn that into 26 or 144 *days* instead of hours.
+ int hours;
+ if (int.TryParse(offset, out hours))
+ {
+ result = new TimeSpan(hours, 0, 0);
+ }
+ else
+ {
+ TimeSpan parsedTimeSpan;
+ if (TimeSpan.TryParseExact(offset, "g", CultureInfo.InvariantCulture, out parsedTimeSpan))
+ {
+ result = parsedTimeSpan;
+ }
+ }
+
+ if (result.HasValue && negative)
+ {
+ result = result.Value.Negate();
+ }
+ }
+
+ return result;
+ }
+
+ private static TransitionTime TZif_CreateTransitionTimeFromPosixRule(string date, string time)
+ {
+ if (string.IsNullOrEmpty(date))
+ {
+ return default(TransitionTime);
+ }
+
+ if (date[0] == 'M')
+ {
+ // Mm.w.d
+ // This specifies day d of week w of month m. The day d must be between 0(Sunday) and 6.The week w must be between 1 and 5;
+ // week 1 is the first week in which day d occurs, and week 5 specifies the last d day in the month. The month m should be between 1 and 12.
+
+ int month;
+ int week;
+ DayOfWeek day;
+ if (!TZif_ParseMDateRule(date, out month, out week, out day))
+ {
+ throw new InvalidTimeZoneException(Environment.GetResourceString("InvalidTimeZone_UnparseablePosixMDateString", date));
+ }
+
+ DateTime timeOfDay;
+ TimeSpan? timeOffset = TZif_ParseOffsetString(time);
+ if (timeOffset.HasValue)
+ {
+ // This logic isn't correct and can't be corrected until https://github.com/dotnet/corefx/issues/2618 is fixed.
+ // Some time zones use time values like, "26", "144", or "-2".
+ // This allows the week to sometimes be week 4 and sometimes week 5 in the month.
+ // For now, strip off any 'days' in the offset, and just get the time of day correct
+ timeOffset = new TimeSpan(timeOffset.Value.Hours, timeOffset.Value.Minutes, timeOffset.Value.Seconds);
+ if (timeOffset.Value < TimeSpan.Zero)
+ {
+ timeOfDay = new DateTime(1, 1, 2, 0, 0, 0);
+ }
+ else
+ {
+ timeOfDay = new DateTime(1, 1, 1, 0, 0, 0);
+ }
+
+ timeOfDay += timeOffset.Value;
+ }
+ else
+ {
+ // default to 2AM.
+ timeOfDay = new DateTime(1, 1, 1, 2, 0, 0);
+ }
+
+ return TransitionTime.CreateFloatingDateRule(timeOfDay, month, week, day);
+ }
+ else
+ {
+ // Jn
+ // This specifies the Julian day, with n between 1 and 365.February 29 is never counted, even in leap years.
+
+ // n
+ // This specifies the Julian day, with n between 0 and 365.February 29 is counted in leap years.
+
+ // These two rules cannot be expressed with the current AdjustmentRules
+ // One of them *could* be supported if we relaxed the TransitionTime validation rules, and allowed
+ // "IsFixedDateRule = true, Month = 0, Day = n" to mean the nth day of the year, picking one of the rules above
+
+ throw new InvalidTimeZoneException(Environment.GetResourceString("InvalidTimeZone_JulianDayNotSupported"));
+ }
+ }
+
+ /// <summary>
+ /// Parses a string like Mm.w.d into month, week and DayOfWeek values.
+ /// </summary>
+ /// <returns>
+ /// true if the parsing succeeded; otherwise, false.
+ /// </returns>
+ private static bool TZif_ParseMDateRule(string dateRule, out int month, out int week, out DayOfWeek dayOfWeek)
+ {
+ month = 0;
+ week = 0;
+ dayOfWeek = default(DayOfWeek);
+
+ if (dateRule[0] == 'M')
+ {
+ int firstDotIndex = dateRule.IndexOf('.');
+ if (firstDotIndex > 0)
+ {
+ int secondDotIndex = dateRule.IndexOf('.', firstDotIndex + 1);
+ if (secondDotIndex > 0)
+ {
+ string monthString = dateRule.Substring(1, firstDotIndex - 1);
+ string weekString = dateRule.Substring(firstDotIndex + 1, secondDotIndex - firstDotIndex - 1);
+ string dayString = dateRule.Substring(secondDotIndex + 1);
+
+ if (int.TryParse(monthString, out month))
+ {
+ if (int.TryParse(weekString, out week))
+ {
+ int day;
+ if (int.TryParse(dayString, out day))
+ {
+ dayOfWeek = (DayOfWeek)day;
+ return true;
+ }
+ }
+ }
+ }
+ }
+ }
+
+ return false;
+ }
+
+ private static bool TZif_ParsePosixFormat(
+ string posixFormat,
+ out string standardName,
+ out string standardOffset,
+ out string daylightSavingsName,
+ out string daylightSavingsOffset,
+ out string start,
+ out string startTime,
+ out string end,
+ out string endTime)
+ {
+ standardName = null;
+ standardOffset = null;
+ daylightSavingsName = null;
+ daylightSavingsOffset = null;
+ start = null;
+ startTime = null;
+ end = null;
+ endTime = null;
+
+ int index = 0;
+ standardName = TZif_ParsePosixName(posixFormat, ref index);
+ standardOffset = TZif_ParsePosixOffset(posixFormat, ref index);
+
+ daylightSavingsName = TZif_ParsePosixName(posixFormat, ref index);
+ if (!string.IsNullOrEmpty(daylightSavingsName))
+ {
+ daylightSavingsOffset = TZif_ParsePosixOffset(posixFormat, ref index);
+
+ if (index < posixFormat.Length && posixFormat[index] == ',')
+ {
+ index++;
+ TZif_ParsePosixDateTime(posixFormat, ref index, out start, out startTime);
+
+ if (index < posixFormat.Length && posixFormat[index] == ',')
+ {
+ index++;
+ TZif_ParsePosixDateTime(posixFormat, ref index, out end, out endTime);
+ }
+ }
+ }
+
+ return !string.IsNullOrEmpty(standardName) && !string.IsNullOrEmpty(standardOffset);
+ }
+
+ private static string TZif_ParsePosixName(string posixFormat, ref int index) =>
+ TZif_ParsePosixString(posixFormat, ref index, c => char.IsDigit(c) || c == '+' || c == '-' || c == ',');
+
+ private static string TZif_ParsePosixOffset(string posixFormat, ref int index) =>
+ TZif_ParsePosixString(posixFormat, ref index, c => !char.IsDigit(c) && c != '+' && c != '-' && c != ':');
+
+ private static void TZif_ParsePosixDateTime(string posixFormat, ref int index, out string date, out string time)
+ {
+ time = null;
+
+ date = TZif_ParsePosixDate(posixFormat, ref index);
+ if (index < posixFormat.Length && posixFormat[index] == '/')
+ {
+ index++;
+ time = TZif_ParsePosixTime(posixFormat, ref index);
+ }
+ }
+
+ private static string TZif_ParsePosixDate(string posixFormat, ref int index) =>
+ TZif_ParsePosixString(posixFormat, ref index, c => c == '/' || c == ',');
+
+ private static string TZif_ParsePosixTime(string posixFormat, ref int index) =>
+ TZif_ParsePosixString(posixFormat, ref index, c => c == ',');
+
+ private static string TZif_ParsePosixString(string posixFormat, ref int index, Func<char, bool> breakCondition)
+ {
+ int startIndex = index;
+ for (; index < posixFormat.Length; index++)
+ {
+ char current = posixFormat[index];
+ if (breakCondition(current))
+ {
+ break;
+ }
+ }
+
+ return posixFormat.Substring(startIndex, index - startIndex);
+ }
+
+ // Returns the Substring from zoneAbbreviations starting at index and ending at '\0'
+ // zoneAbbreviations is expected to be in the form: "PST\0PDT\0PWT\0\PPT"
+ private static string TZif_GetZoneAbbreviation(string zoneAbbreviations, int index)
+ {
+ int lastIndex = zoneAbbreviations.IndexOf('\0', index);
+ return lastIndex > 0 ?
+ zoneAbbreviations.Substring(index, lastIndex - index) :
+ zoneAbbreviations.Substring(index);
+ }
+
+ // Converts an array of bytes into an int - always using standard byte order (Big Endian)
+ // per TZif file standard
+ private static unsafe int TZif_ToInt32(byte[] value, int startIndex)
+ {
+ fixed (byte* pbyte = &value[startIndex])
+ {
+ return (*pbyte << 24) | (*(pbyte + 1) << 16) | (*(pbyte + 2) << 8) | (*(pbyte + 3));
+ }
+ }
+
+ // Converts an array of bytes into a long - always using standard byte order (Big Endian)
+ // per TZif file standard
+ private static unsafe long TZif_ToInt64(byte[] value, int startIndex)
+ {
+ fixed (byte* pbyte = &value[startIndex])
+ {
+ int i1 = (*pbyte << 24) | (*(pbyte + 1) << 16) | (*(pbyte + 2) << 8) | (*(pbyte + 3));
+ int i2 = (*(pbyte + 4) << 24) | (*(pbyte + 5) << 16) | (*(pbyte + 6) << 8) | (*(pbyte + 7));
+ return (uint)i2 | ((long)i1 << 32);
+ }
+ }
+
+ private static long TZif_ToUnixTime(byte[] value, int startIndex, TZVersion version) =>
+ version != TZVersion.V1 ?
+ TZif_ToInt64(value, startIndex) :
+ TZif_ToInt32(value, startIndex);
+
+ private static DateTime TZif_UnixTimeToDateTime(long unixTime) =>
+ unixTime < DateTimeOffset.UnixMinSeconds ? DateTime.MinValue :
+ unixTime > DateTimeOffset.UnixMaxSeconds ? DateTime.MaxValue :
+ DateTimeOffset.FromUnixTimeSeconds(unixTime).UtcDateTime;
+
+ private static void TZif_ParseRaw(byte[] data, out TZifHead t, out DateTime[] dts, out byte[] typeOfLocalTime, out TZifType[] transitionType,
+ out string zoneAbbreviations, out bool[] StandardTime, out bool[] GmtTime, out string futureTransitionsPosixFormat)
+ {
+ // initialize the out parameters in case the TZifHead ctor throws
+ dts = null;
+ typeOfLocalTime = null;
+ transitionType = null;
+ zoneAbbreviations = string.Empty;
+ StandardTime = null;
+ GmtTime = null;
+ futureTransitionsPosixFormat = null;
+
+ // read in the 44-byte TZ header containing the count/length fields
+ //
+ int index = 0;
+ t = new TZifHead(data, index);
+ index += TZifHead.Length;
+
+ int timeValuesLength = 4; // the first version uses 4-bytes to specify times
+ if (t.Version != TZVersion.V1)
+ {
+ // move index past the V1 information to read the V2 information
+ index += (int)((timeValuesLength * t.TimeCount) + t.TimeCount + (6 * t.TypeCount) + ((timeValuesLength + 4) * t.LeapCount) + t.IsStdCount + t.IsGmtCount + t.CharCount);
+
+ // read the V2 header
+ t = new TZifHead(data, index);
+ index += TZifHead.Length;
+ timeValuesLength = 8; // the second version uses 8-bytes
+ }
+
+ // initialize the containers for the rest of the TZ data
+ dts = new DateTime[t.TimeCount];
+ typeOfLocalTime = new byte[t.TimeCount];
+ transitionType = new TZifType[t.TypeCount];
+ zoneAbbreviations = string.Empty;
+ StandardTime = new bool[t.TypeCount];
+ GmtTime = new bool[t.TypeCount];
+
+ // read in the UTC transition points and convert them to Windows
+ //
+ for (int i = 0; i < t.TimeCount; i++)
+ {
+ long unixTime = TZif_ToUnixTime(data, index, t.Version);
+ dts[i] = TZif_UnixTimeToDateTime(unixTime);
+ index += timeValuesLength;
+ }
+
+ // read in the Type Indices; there is a 1:1 mapping of UTC transition points to Type Indices
+ // these indices directly map to the array index in the transitionType array below
+ //
+ for (int i = 0; i < t.TimeCount; i++)
+ {
+ typeOfLocalTime[i] = data[index];
+ index += 1;
+ }
+
+ // read in the Type table. Each 6-byte entry represents
+ // {UtcOffset, IsDst, AbbreviationIndex}
+ //
+ // each AbbreviationIndex is a character index into the zoneAbbreviations string below
+ //
+ for (int i = 0; i < t.TypeCount; i++)
+ {
+ transitionType[i] = new TZifType(data, index);
+ index += 6;
+ }
+
+ // read in the Abbreviation ASCII string. This string will be in the form:
+ // "PST\0PDT\0PWT\0\PPT"
+ //
+ Encoding enc = Encoding.UTF8;
+ zoneAbbreviations = enc.GetString(data, index, (int)t.CharCount);
+ index += (int)t.CharCount;
+
+ // skip ahead of the Leap-Seconds Adjustment data. In a future release, consider adding
+ // support for Leap-Seconds
+ //
+ index += (int)(t.LeapCount * (timeValuesLength + 4)); // skip the leap second transition times
+
+ // read in the Standard Time table. There should be a 1:1 mapping between Type-Index and Standard
+ // Time table entries.
+ //
+ // TRUE = transition time is standard time
+ // FALSE = transition time is wall clock time
+ // ABSENT = transition time is wall clock time
+ //
+ for (int i = 0; i < t.IsStdCount && i < t.TypeCount && index < data.Length; i++)
+ {
+ StandardTime[i] = (data[index++] != 0);
+ }
+
+ // read in the GMT Time table. There should be a 1:1 mapping between Type-Index and GMT Time table
+ // entries.
+ //
+ // TRUE = transition time is UTC
+ // FALSE = transition time is local time
+ // ABSENT = transition time is local time
+ //
+ for (int i = 0; i < t.IsGmtCount && i < t.TypeCount && index < data.Length; i++)
+ {
+ GmtTime[i] = (data[index++] != 0);
+ }
+
+ if (t.Version != TZVersion.V1)
+ {
+ // read the POSIX-style format, which should be wrapped in newlines with the last newline at the end of the file
+ if (data[index++] == '\n' && data[data.Length - 1] == '\n')
+ {
+ futureTransitionsPosixFormat = enc.GetString(data, index, data.Length - index - 1);
+ }
+ }
+ }
+
+ private struct TZifType
+ {
+ public const int Length = 6;
+
+ public readonly TimeSpan UtcOffset;
+ public readonly bool IsDst;
+ public readonly byte AbbreviationIndex;
+
+ public TZifType(byte[] data, int index)
+ {
+ if (data == null || data.Length < index + Length)
+ {
+ throw new ArgumentException(Environment.GetResourceString("Argument_TimeZoneInfoInvalidTZif"), nameof(data));
+ }
+ Contract.EndContractBlock();
+ UtcOffset = new TimeSpan(0, 0, TZif_ToInt32(data, index + 00));
+ IsDst = (data[index + 4] != 0);
+ AbbreviationIndex = data[index + 5];
+ }
+ }
+
+ private struct TZifHead
+ {
+ public const int Length = 44;
+
+ public readonly uint Magic; // TZ_MAGIC "TZif"
+ public readonly TZVersion Version; // 1 byte for a \0 or 2 or 3
+ // public byte[15] Reserved; // reserved for future use
+ public readonly uint IsGmtCount; // number of transition time flags
+ public readonly uint IsStdCount; // number of transition time flags
+ public readonly uint LeapCount; // number of leap seconds
+ public readonly uint TimeCount; // number of transition times
+ public readonly uint TypeCount; // number of local time types
+ public readonly uint CharCount; // number of abbreviated characters
+
+ public TZifHead(byte[] data, int index)
+ {
+ if (data == null || data.Length < Length)
+ {
+ throw new ArgumentException("bad data", nameof(data));
+ }
+ Contract.EndContractBlock();
+
+ Magic = (uint)TZif_ToInt32(data, index + 00);
+
+ if (Magic != 0x545A6966)
+ {
+ // 0x545A6966 = {0x54, 0x5A, 0x69, 0x66} = "TZif"
+ throw new ArgumentException(Environment.GetResourceString("Argument_TimeZoneInfoBadTZif"), nameof(data));
+ }
+
+ byte version = data[index + 04];
+ Version =
+ version == '2' ? TZVersion.V2 :
+ version == '3' ? TZVersion.V3 :
+ TZVersion.V1; // default/fallback to V1 to guard against future, unsupported version numbers
+
+ // skip the 15 byte reserved field
+
+ // don't use the BitConverter class which parses data
+ // based on the Endianess of the machine architecture.
+ // this data is expected to always be in "standard byte order",
+ // regardless of the machine it is being processed on.
+
+ IsGmtCount = (uint)TZif_ToInt32(data, index + 20);
+ IsStdCount = (uint)TZif_ToInt32(data, index + 24);
+ LeapCount = (uint)TZif_ToInt32(data, index + 28);
+ TimeCount = (uint)TZif_ToInt32(data, index + 32);
+ TypeCount = (uint)TZif_ToInt32(data, index + 36);
+ CharCount = (uint)TZif_ToInt32(data, index + 40);
+ }
+ }
+
+ private enum TZVersion : byte
+ {
+ V1 = 0,
+ V2,
+ V3,
+ // when adding more versions, ensure all the logic using TZVersion is still correct
+ }
+ }
+}
diff --git a/src/mscorlib/src/System/TimeZoneInfo.Win32.cs b/src/mscorlib/src/System/TimeZoneInfo.Win32.cs
new file mode 100644
index 0000000000..79ee535505
--- /dev/null
+++ b/src/mscorlib/src/System/TimeZoneInfo.Win32.cs
@@ -0,0 +1,1023 @@
+// 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.Globalization;
+using System.IO;
+using System.Security;
+using System.Text;
+using System.Threading;
+using Microsoft.Win32;
+
+namespace System
+{
+ public sealed partial class TimeZoneInfo
+ {
+ // registry constants for the 'Time Zones' hive
+ //
+ private const string TimeZonesRegistryHive = @"SOFTWARE\Microsoft\Windows NT\CurrentVersion\Time Zones";
+ private const string DisplayValue = "Display";
+ private const string DaylightValue = "Dlt";
+ private const string StandardValue = "Std";
+ private const string MuiDisplayValue = "MUI_Display";
+ private const string MuiDaylightValue = "MUI_Dlt";
+ private const string MuiStandardValue = "MUI_Std";
+ private const string TimeZoneInfoValue = "TZI";
+ private const string FirstEntryValue = "FirstEntry";
+ private const string LastEntryValue = "LastEntry";
+
+ private const int MaxKeyLength = 255;
+ private const int RegByteLength = 44;
+
+#pragma warning disable 0420
+ private sealed partial class CachedData
+ {
+ private static TimeZoneInfo GetCurrentOneYearLocal()
+ {
+ // load the data from the OS
+ Win32Native.TimeZoneInformation timeZoneInformation;
+ long result = UnsafeNativeMethods.GetTimeZoneInformation(out timeZoneInformation);
+ return result == Win32Native.TIME_ZONE_ID_INVALID ?
+ CreateCustomTimeZone(LocalId, TimeSpan.Zero, LocalId, LocalId) :
+ GetLocalTimeZoneFromWin32Data(timeZoneInformation, dstDisabled: false);
+ }
+
+ private volatile OffsetAndRule _oneYearLocalFromUtc;
+
+ public OffsetAndRule GetOneYearLocalFromUtc(int year)
+ {
+ OffsetAndRule oneYearLocFromUtc = _oneYearLocalFromUtc;
+ if (oneYearLocFromUtc == null || oneYearLocFromUtc.Year != year)
+ {
+ TimeZoneInfo currentYear = GetCurrentOneYearLocal();
+ AdjustmentRule rule = currentYear._adjustmentRules == null ? null : currentYear._adjustmentRules[0];
+ oneYearLocFromUtc = new OffsetAndRule(year, currentYear.BaseUtcOffset, rule);
+ _oneYearLocalFromUtc = oneYearLocFromUtc;
+ }
+ return oneYearLocFromUtc;
+ }
+ }
+#pragma warning restore 0420
+
+ private sealed class OffsetAndRule
+ {
+ public readonly int Year;
+ public readonly TimeSpan Offset;
+ public readonly AdjustmentRule Rule;
+
+ public OffsetAndRule(int year, TimeSpan offset, AdjustmentRule rule)
+ {
+ Year = year;
+ Offset = offset;
+ Rule = rule;
+ }
+ }
+
+ /// <summary>
+ /// Returns a cloned array of AdjustmentRule objects
+ /// </summary>
+ public AdjustmentRule[] GetAdjustmentRules()
+ {
+ if (_adjustmentRules == null)
+ {
+ return Array.Empty<AdjustmentRule>();
+ }
+
+ return (AdjustmentRule[])_adjustmentRules.Clone();
+ }
+
+ private static void PopulateAllSystemTimeZones(CachedData cachedData)
+ {
+ Debug.Assert(Monitor.IsEntered(cachedData));
+
+ using (RegistryKey reg = Registry.LocalMachine.OpenSubKey(TimeZonesRegistryHive, writable: 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
+ }
+ }
+ }
+ }
+
+ private TimeZoneInfo(Win32Native.TimeZoneInformation zone, bool dstDisabled)
+ {
+ if (string.IsNullOrEmpty(zone.StandardName))
+ {
+ _id = LocalId; // the ID must contain at least 1 character - initialize _id to "Local"
+ }
+ else
+ {
+ _id = zone.StandardName;
+ }
+ _baseUtcOffset = new TimeSpan(0, -(zone.Bias), 0);
+
+ if (!dstDisabled)
+ {
+ // only create the adjustment rule if DST is enabled
+ Win32Native.RegistryTimeZoneInformation regZone = new Win32Native.RegistryTimeZoneInformation(zone);
+ AdjustmentRule rule = CreateAdjustmentRuleFromTimeZoneInformation(regZone, DateTime.MinValue.Date, DateTime.MaxValue.Date, zone.Bias);
+ if (rule != null)
+ {
+ _adjustmentRules = new AdjustmentRule[1];
+ _adjustmentRules[0] = rule;
+ }
+ }
+
+ ValidateTimeZoneInfo(_id, _baseUtcOffset, _adjustmentRules, out _supportsDaylightSavingTime);
+ _displayName = zone.StandardName;
+ _standardDisplayName = zone.StandardName;
+ _daylightDisplayName = zone.DaylightName;
+ }
+
+ /// <summary>
+ /// Helper function to check if the current TimeZoneInformation struct does not support DST.
+ /// This check returns true when the DaylightDate == StandardDate.
+ /// This check is only meant to be used for "Local".
+ /// </summary>
+ private static bool CheckDaylightSavingTimeNotSupported(Win32Native.TimeZoneInformation timeZone) =>
+ timeZone.DaylightDate.Year == timeZone.StandardDate.Year &&
+ timeZone.DaylightDate.Month == timeZone.StandardDate.Month &&
+ timeZone.DaylightDate.DayOfWeek == timeZone.StandardDate.DayOfWeek &&
+ timeZone.DaylightDate.Day == timeZone.StandardDate.Day &&
+ timeZone.DaylightDate.Hour == timeZone.StandardDate.Hour &&
+ timeZone.DaylightDate.Minute == timeZone.StandardDate.Minute &&
+ timeZone.DaylightDate.Second == timeZone.StandardDate.Second &&
+ timeZone.DaylightDate.Milliseconds == timeZone.StandardDate.Milliseconds;
+
+ /// <summary>
+ /// Converts a Win32Native.RegistryTimeZoneInformation (REG_TZI_FORMAT struct) to an AdjustmentRule.
+ /// </summary>
+ private static AdjustmentRule CreateAdjustmentRuleFromTimeZoneInformation(Win32Native.RegistryTimeZoneInformation timeZoneInformation, DateTime startDate, DateTime endDate, int defaultBaseUtcOffset)
+ {
+ bool supportsDst = timeZoneInformation.StandardDate.Month != 0;
+
+ if (!supportsDst)
+ {
+ if (timeZoneInformation.Bias == defaultBaseUtcOffset)
+ {
+ // this rule will not contain any information to be used to adjust dates. just ignore it
+ return null;
+ }
+
+ return AdjustmentRule.CreateAdjustmentRule(
+ startDate,
+ endDate,
+ TimeSpan.Zero, // no daylight saving transition
+ TransitionTime.CreateFixedDateRule(DateTime.MinValue, 1, 1),
+ TransitionTime.CreateFixedDateRule(DateTime.MinValue.AddMilliseconds(1), 1, 1),
+ new TimeSpan(0, defaultBaseUtcOffset - timeZoneInformation.Bias, 0), // Bias delta is all what we need from this rule
+ noDaylightTransitions: false);
+ }
+
+ //
+ // Create an AdjustmentRule with TransitionTime objects
+ //
+ TransitionTime daylightTransitionStart;
+ if (!TransitionTimeFromTimeZoneInformation(timeZoneInformation, out daylightTransitionStart, readStartDate: true))
+ {
+ return null;
+ }
+
+ TransitionTime daylightTransitionEnd;
+ if (!TransitionTimeFromTimeZoneInformation(timeZoneInformation, out daylightTransitionEnd, readStartDate: false))
+ {
+ return null;
+ }
+
+ if (daylightTransitionStart.Equals(daylightTransitionEnd))
+ {
+ // this happens when the time zone does support DST but the OS has DST disabled
+ return null;
+ }
+
+ return AdjustmentRule.CreateAdjustmentRule(
+ startDate,
+ endDate,
+ new TimeSpan(0, -timeZoneInformation.DaylightBias, 0),
+ daylightTransitionStart,
+ daylightTransitionEnd,
+ new TimeSpan(0, defaultBaseUtcOffset - timeZoneInformation.Bias, 0),
+ noDaylightTransitions: false);
+ }
+
+ /// <summary>
+ /// Helper function that searches the registry for a time zone entry
+ /// that matches the TimeZoneInformation struct.
+ /// </summary>
+ private static string FindIdFromTimeZoneInformation(Win32Native.TimeZoneInformation timeZone, out bool dstDisabled)
+ {
+ dstDisabled = false;
+
+ using (RegistryKey key = Registry.LocalMachine.OpenSubKey(TimeZonesRegistryHive, writable: false))
+ {
+ if (key == null)
+ {
+ return null;
+ }
+
+ foreach (string keyName in key.GetSubKeyNames())
+ {
+ if (TryCompareTimeZoneInformationToRegistry(timeZone, keyName, out dstDisabled))
+ {
+ return keyName;
+ }
+ }
+ }
+
+ return null;
+ }
+
+ /// <summary>
+ /// Helper function for retrieving the local system time zone.
+ /// May throw COMException, TimeZoneNotFoundException, InvalidTimeZoneException.
+ /// Assumes cachedData lock is taken.
+ /// </summary>
+ /// <returns>A new TimeZoneInfo instance.</returns>
+ private static TimeZoneInfo GetLocalTimeZone(CachedData cachedData)
+ {
+ Debug.Assert(Monitor.IsEntered(cachedData));
+
+ string id = null;
+
+ //
+ // Try using the "kernel32!GetDynamicTimeZoneInformation" API to get the "id"
+ //
+ var dynamicTimeZoneInformation = new Win32Native.DynamicTimeZoneInformation();
+
+ // call kernel32!GetDynamicTimeZoneInformation...
+ long result = UnsafeNativeMethods.GetDynamicTimeZoneInformation(out dynamicTimeZoneInformation);
+ if (result == Win32Native.TIME_ZONE_ID_INVALID)
+ {
+ // return a dummy entry
+ return CreateCustomTimeZone(LocalId, TimeSpan.Zero, LocalId, LocalId);
+ }
+
+ var timeZoneInformation = new Win32Native.TimeZoneInformation(dynamicTimeZoneInformation);
+
+ bool dstDisabled = dynamicTimeZoneInformation.DynamicDaylightTimeDisabled;
+
+ // check to see if we can use the key name returned from the API call
+ if (!string.IsNullOrEmpty(dynamicTimeZoneInformation.TimeZoneKeyName))
+ {
+ TimeZoneInfo zone;
+ Exception ex;
+
+ if (TryGetTimeZone(dynamicTimeZoneInformation.TimeZoneKeyName, dstDisabled, out zone, out ex, cachedData) == TimeZoneInfoResult.Success)
+ {
+ // successfully loaded the time zone from the registry
+ return zone;
+ }
+ }
+
+ // the key name was not returned or it pointed to a bogus entry - search for the entry ourselves
+ id = FindIdFromTimeZoneInformation(timeZoneInformation, out dstDisabled);
+
+ if (id != null)
+ {
+ TimeZoneInfo zone;
+ Exception ex;
+ if (TryGetTimeZone(id, dstDisabled, out zone, out ex, cachedData) == TimeZoneInfoResult.Success)
+ {
+ // successfully loaded the time zone from the registry
+ return zone;
+ }
+ }
+
+ // We could not find the data in the registry. Fall back to using
+ // the data from the Win32 API
+ return GetLocalTimeZoneFromWin32Data(timeZoneInformation, dstDisabled);
+ }
+
+ /// <summary>
+ /// Helper function used by 'GetLocalTimeZone()' - this function wraps a bunch of
+ /// try/catch logic for handling the TimeZoneInfo private constructor that takes
+ /// a Win32Native.TimeZoneInformation structure.
+ /// </summary>
+ private static TimeZoneInfo GetLocalTimeZoneFromWin32Data(Win32Native.TimeZoneInformation timeZoneInformation, bool dstDisabled)
+ {
+ // first try to create the TimeZoneInfo with the original 'dstDisabled' flag
+ try
+ {
+ return new TimeZoneInfo(timeZoneInformation, dstDisabled);
+ }
+ catch (ArgumentException) { }
+ catch (InvalidTimeZoneException) { }
+
+ // if 'dstDisabled' was false then try passing in 'true' as a last ditch effort
+ if (!dstDisabled)
+ {
+ try
+ {
+ return new TimeZoneInfo(timeZoneInformation, dstDisabled: true);
+ }
+ catch (ArgumentException) { }
+ catch (InvalidTimeZoneException) { }
+ }
+
+ // the data returned from Windows is completely bogus; return a dummy entry
+ return CreateCustomTimeZone(LocalId, TimeSpan.Zero, LocalId, LocalId);
+ }
+
+ /// <summary>
+ /// Helper function for retrieving a TimeZoneInfo object by <time_zone_name>.
+ /// This function wraps the logic necessary to keep the private
+ /// SystemTimeZones cache in working order
+ ///
+ /// This function will either return a valid TimeZoneInfo instance or
+ /// it will throw 'InvalidTimeZoneException' / 'TimeZoneNotFoundException'.
+ /// </summary>
+ public static TimeZoneInfo FindSystemTimeZoneById(string id)
+ {
+ // Special case for Utc as it will not exist in the dictionary with the rest
+ // of the system time zones. There is no need to do this check for Local.Id
+ // since Local is a real time zone that exists in the dictionary cache
+ if (string.Equals(id, UtcId, StringComparison.OrdinalIgnoreCase))
+ {
+ return Utc;
+ }
+
+ if (id == null)
+ {
+ throw new ArgumentNullException(nameof(id));
+ }
+ else if (id.Length == 0 || id.Length > MaxKeyLength || id.Contains("\0"))
+ {
+ throw new TimeZoneNotFoundException(Environment.GetResourceString("TimeZoneNotFound_MissingData", id));
+ }
+
+ TimeZoneInfo value;
+ Exception e;
+
+ TimeZoneInfoResult result;
+
+ CachedData cachedData = s_cachedData;
+
+ lock (cachedData)
+ {
+ result = TryGetTimeZone(id, false, out value, out e, cachedData);
+ }
+
+ if (result == TimeZoneInfoResult.Success)
+ {
+ return value;
+ }
+ else if (result == TimeZoneInfoResult.InvalidTimeZoneException)
+ {
+ throw new InvalidTimeZoneException(Environment.GetResourceString("InvalidTimeZone_InvalidRegistryData", id), e);
+ }
+ else if (result == TimeZoneInfoResult.SecurityException)
+ {
+ throw new SecurityException(Environment.GetResourceString("Security_CannotReadRegistryData", id), e);
+ }
+ else
+ {
+ throw new TimeZoneNotFoundException(Environment.GetResourceString("TimeZoneNotFound_MissingData", id), e);
+ }
+ }
+
+ // DateTime.Now fast path that avoids allocating an historically accurate TimeZoneInfo.Local and just creates a 1-year (current year) accurate time zone
+ internal static TimeSpan GetDateTimeNowUtcOffsetFromUtc(DateTime time, out bool isAmbiguousLocalDst)
+ {
+ bool isDaylightSavings = false;
+ isAmbiguousLocalDst = false;
+ TimeSpan baseOffset;
+ int timeYear = time.Year;
+
+ OffsetAndRule match = s_cachedData.GetOneYearLocalFromUtc(timeYear);
+ baseOffset = match.Offset;
+
+ if (match.Rule != null)
+ {
+ baseOffset = baseOffset + match.Rule.BaseUtcOffsetDelta;
+ if (match.Rule.HasDaylightSaving)
+ {
+ isDaylightSavings = GetIsDaylightSavingsFromUtc(time, timeYear, match.Offset, match.Rule, out isAmbiguousLocalDst, Local);
+ baseOffset += (isDaylightSavings ? match.Rule.DaylightDelta : TimeSpan.Zero /* FUTURE: rule.StandardDelta */);
+ }
+ }
+ return baseOffset;
+ }
+
+ /// <summary>
+ /// Converts a Win32Native.RegistryTimeZoneInformation (REG_TZI_FORMAT struct) to a TransitionTime
+ /// - When the argument 'readStart' is true the corresponding daylightTransitionTimeStart field is read
+ /// - When the argument 'readStart' is false the corresponding dayightTransitionTimeEnd field is read
+ /// </summary>
+ private static bool TransitionTimeFromTimeZoneInformation(Win32Native.RegistryTimeZoneInformation timeZoneInformation, out TransitionTime transitionTime, bool readStartDate)
+ {
+ //
+ // SYSTEMTIME -
+ //
+ // If the time zone does not support daylight saving time or if the caller needs
+ // to disable daylight saving time, the wMonth member in the SYSTEMTIME structure
+ // must be zero. If this date is specified, the DaylightDate value in the
+ // TIME_ZONE_INFORMATION structure must also be specified. Otherwise, the system
+ // assumes the time zone data is invalid and no changes will be applied.
+ //
+ bool supportsDst = (timeZoneInformation.StandardDate.Month != 0);
+
+ if (!supportsDst)
+ {
+ transitionTime = default(TransitionTime);
+ return false;
+ }
+
+ //
+ // SYSTEMTIME -
+ //
+ // * FixedDateRule -
+ // If the Year member is not zero, the transition date is absolute; it will only occur one time
+ //
+ // * FloatingDateRule -
+ // To select the correct day in the month, set the Year member to zero, the Hour and Minute
+ // members to the transition time, the DayOfWeek member to the appropriate weekday, and the
+ // Day member to indicate the occurence of the day of the week within the month (first through fifth).
+ //
+ // Using this notation, specify the 2:00a.m. on the first Sunday in April as follows:
+ // Hour = 2,
+ // Month = 4,
+ // DayOfWeek = 0,
+ // Day = 1.
+ //
+ // Specify 2:00a.m. on the last Thursday in October as follows:
+ // Hour = 2,
+ // Month = 10,
+ // DayOfWeek = 4,
+ // Day = 5.
+ //
+ if (readStartDate)
+ {
+ //
+ // read the "daylightTransitionStart"
+ //
+ if (timeZoneInformation.DaylightDate.Year == 0)
+ {
+ transitionTime = TransitionTime.CreateFloatingDateRule(
+ new DateTime(1, /* year */
+ 1, /* month */
+ 1, /* day */
+ timeZoneInformation.DaylightDate.Hour,
+ timeZoneInformation.DaylightDate.Minute,
+ timeZoneInformation.DaylightDate.Second,
+ timeZoneInformation.DaylightDate.Milliseconds),
+ timeZoneInformation.DaylightDate.Month,
+ timeZoneInformation.DaylightDate.Day, /* Week 1-5 */
+ (DayOfWeek)timeZoneInformation.DaylightDate.DayOfWeek);
+ }
+ else
+ {
+ transitionTime = TransitionTime.CreateFixedDateRule(
+ new DateTime(1, /* year */
+ 1, /* month */
+ 1, /* day */
+ timeZoneInformation.DaylightDate.Hour,
+ timeZoneInformation.DaylightDate.Minute,
+ timeZoneInformation.DaylightDate.Second,
+ timeZoneInformation.DaylightDate.Milliseconds),
+ timeZoneInformation.DaylightDate.Month,
+ timeZoneInformation.DaylightDate.Day);
+ }
+ }
+ else
+ {
+ //
+ // read the "daylightTransitionEnd"
+ //
+ if (timeZoneInformation.StandardDate.Year == 0)
+ {
+ transitionTime = TransitionTime.CreateFloatingDateRule(
+ new DateTime(1, /* year */
+ 1, /* month */
+ 1, /* day */
+ timeZoneInformation.StandardDate.Hour,
+ timeZoneInformation.StandardDate.Minute,
+ timeZoneInformation.StandardDate.Second,
+ timeZoneInformation.StandardDate.Milliseconds),
+ timeZoneInformation.StandardDate.Month,
+ timeZoneInformation.StandardDate.Day, /* Week 1-5 */
+ (DayOfWeek)timeZoneInformation.StandardDate.DayOfWeek);
+ }
+ else
+ {
+ transitionTime = TransitionTime.CreateFixedDateRule(
+ new DateTime(1, /* year */
+ 1, /* month */
+ 1, /* day */
+ timeZoneInformation.StandardDate.Hour,
+ timeZoneInformation.StandardDate.Minute,
+ timeZoneInformation.StandardDate.Second,
+ timeZoneInformation.StandardDate.Milliseconds),
+ timeZoneInformation.StandardDate.Month,
+ timeZoneInformation.StandardDate.Day);
+ }
+ }
+
+ return true;
+ }
+
+ /// <summary>
+ /// Helper function that takes:
+ /// 1. A string representing a <time_zone_name> registry key name.
+ /// 2. A RegistryTimeZoneInformation struct containing the default rule.
+ /// 3. An AdjustmentRule[] out-parameter.
+ /// </summary>
+ private static bool TryCreateAdjustmentRules(string id, Win32Native.RegistryTimeZoneInformation defaultTimeZoneInformation, out AdjustmentRule[] rules, out Exception e, int defaultBaseUtcOffset)
+ {
+ e = null;
+
+ try
+ {
+ // Optional, Dynamic Time Zone Registry Data
+ // -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
+ //
+ // HKLM
+ // Software
+ // Microsoft
+ // Windows NT
+ // CurrentVersion
+ // Time Zones
+ // <time_zone_name>
+ // Dynamic DST
+ // * "FirstEntry" REG_DWORD "1980"
+ // First year in the table. If the current year is less than this value,
+ // this entry will be used for DST boundaries
+ // * "LastEntry" REG_DWORD "2038"
+ // Last year in the table. If the current year is greater than this value,
+ // this entry will be used for DST boundaries"
+ // * "<year1>" REG_BINARY REG_TZI_FORMAT
+ // See Win32Native.RegistryTimeZoneInformation
+ // * "<year2>" REG_BINARY REG_TZI_FORMAT
+ // See Win32Native.RegistryTimeZoneInformation
+ // * "<year3>" REG_BINARY REG_TZI_FORMAT
+ // See Win32Native.RegistryTimeZoneInformation
+ //
+ using (RegistryKey dynamicKey = Registry.LocalMachine.OpenSubKey(TimeZonesRegistryHive + "\\" + id + "\\Dynamic DST", writable: false))
+ {
+ if (dynamicKey == null)
+ {
+ AdjustmentRule rule = CreateAdjustmentRuleFromTimeZoneInformation(
+ defaultTimeZoneInformation, DateTime.MinValue.Date, DateTime.MaxValue.Date, defaultBaseUtcOffset);
+ rules = rule == null ? null : new[] { rule };
+ return true;
+ }
+
+ //
+ // loop over all of the "<time_zone_name>\Dynamic DST" hive entries
+ //
+ // read FirstEntry {MinValue - (year1, 12, 31)}
+ // read MiddleEntry {(yearN, 1, 1) - (yearN, 12, 31)}
+ // read LastEntry {(yearN, 1, 1) - MaxValue }
+
+ // read the FirstEntry and LastEntry key values (ex: "1980", "2038")
+ int first = (int)dynamicKey.GetValue(FirstEntryValue, -1, RegistryValueOptions.None);
+ int last = (int)dynamicKey.GetValue(LastEntryValue, -1, RegistryValueOptions.None);
+
+ if (first == -1 || last == -1 || first > last)
+ {
+ rules = null;
+ return false;
+ }
+
+ // 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 != RegByteLength)
+ {
+ rules = null;
+ return false;
+ }
+ dtzi = new Win32Native.RegistryTimeZoneInformation(regValue);
+
+ if (first == last)
+ {
+ // there is just 1 dynamic rule for this time zone.
+ AdjustmentRule rule = CreateAdjustmentRuleFromTimeZoneInformation(dtzi, DateTime.MinValue.Date, DateTime.MaxValue.Date, defaultBaseUtcOffset);
+ rules = rule == null ? null : new[] { rule };
+ return true;
+ }
+
+ List<AdjustmentRule> rulesList = new List<AdjustmentRule>(1);
+
+ // 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)
+ {
+ rulesList.Add(firstRule);
+ }
+
+ // read the middle year entries
+ for (int i = first + 1; i < last; i++)
+ {
+ regValue = dynamicKey.GetValue(i.ToString(CultureInfo.InvariantCulture), null, RegistryValueOptions.None) as byte[];
+ if (regValue == null || regValue.Length != RegByteLength)
+ {
+ rules = null;
+ return false;
+ }
+ dtzi = new Win32Native.RegistryTimeZoneInformation(regValue);
+ AdjustmentRule middleRule = CreateAdjustmentRuleFromTimeZoneInformation(
+ dtzi,
+ new DateTime(i, 1, 1), // January 01, <Year>
+ new DateTime(i, 12, 31), // December 31, <Year>
+ defaultBaseUtcOffset);
+
+ 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 != RegByteLength)
+ {
+ rules = null;
+ return false;
+ }
+ AdjustmentRule lastRule = CreateAdjustmentRuleFromTimeZoneInformation(
+ dtzi,
+ new DateTime(last, 1, 1), // January 01, <LastYear>
+ DateTime.MaxValue.Date, // MaxValue
+ defaultBaseUtcOffset);
+
+ if (lastRule != null)
+ {
+ rulesList.Add(lastRule);
+ }
+
+ // convert the ArrayList to an AdjustmentRule array
+ rules = rulesList.ToArray();
+ if (rules != null && rules.Length == 0)
+ {
+ rules = null;
+ }
+ } // end of: using (RegistryKey dynamicKey...
+ }
+ catch (InvalidCastException ex)
+ {
+ // one of the RegistryKey.GetValue calls could not be cast to an expected value type
+ rules = null;
+ e = ex;
+ return false;
+ }
+ catch (ArgumentOutOfRangeException ex)
+ {
+ rules = null;
+ e = ex;
+ return false;
+ }
+ catch (ArgumentException ex)
+ {
+ rules = null;
+ e = ex;
+ return false;
+ }
+ return true;
+ }
+
+ /// <summary>
+ /// Helper function that compares the StandardBias and StandardDate portion a
+ /// TimeZoneInformation struct to a time zone registry entry.
+ /// </summary>
+ private static bool TryCompareStandardDate(Win32Native.TimeZoneInformation timeZone, Win32Native.RegistryTimeZoneInformation registryTimeZoneInfo) =>
+ timeZone.Bias == registryTimeZoneInfo.Bias &&
+ timeZone.StandardBias == registryTimeZoneInfo.StandardBias &&
+ timeZone.StandardDate.Year == registryTimeZoneInfo.StandardDate.Year &&
+ timeZone.StandardDate.Month == registryTimeZoneInfo.StandardDate.Month &&
+ timeZone.StandardDate.DayOfWeek == registryTimeZoneInfo.StandardDate.DayOfWeek &&
+ timeZone.StandardDate.Day == registryTimeZoneInfo.StandardDate.Day &&
+ timeZone.StandardDate.Hour == registryTimeZoneInfo.StandardDate.Hour &&
+ timeZone.StandardDate.Minute == registryTimeZoneInfo.StandardDate.Minute &&
+ timeZone.StandardDate.Second == registryTimeZoneInfo.StandardDate.Second &&
+ timeZone.StandardDate.Milliseconds == registryTimeZoneInfo.StandardDate.Milliseconds;
+
+ /// <summary>
+ /// Helper function that compares a TimeZoneInformation struct to a time zone registry entry.
+ /// </summary>
+ private static bool TryCompareTimeZoneInformationToRegistry(Win32Native.TimeZoneInformation timeZone, string id, out bool dstDisabled)
+ {
+ dstDisabled = false;
+
+ using (RegistryKey key = Registry.LocalMachine.OpenSubKey(TimeZonesRegistryHive + "\\" + id, writable: false))
+ {
+ if (key == null)
+ {
+ return false;
+ }
+
+ Win32Native.RegistryTimeZoneInformation registryTimeZoneInfo;
+ byte[] regValue = key.GetValue(TimeZoneInfoValue, null, RegistryValueOptions.None) as byte[];
+ if (regValue == null || regValue.Length != RegByteLength) return false;
+ registryTimeZoneInfo = new Win32Native.RegistryTimeZoneInformation(regValue);
+
+ //
+ // first compare the bias and standard date information between the data from the Win32 API
+ // and the data from the registry...
+ //
+ bool result = TryCompareStandardDate(timeZone, registryTimeZoneInfo);
+
+ if (!result)
+ {
+ return false;
+ }
+
+ result = dstDisabled || CheckDaylightSavingTimeNotSupported(timeZone) ||
+ //
+ // 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.DaylightDate.Milliseconds == registryTimeZoneInfo.DaylightDate.Milliseconds);
+
+ // Finally compare the "StandardName" string value...
+ //
+ // 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)
+ {
+ string registryStandardName = key.GetValue(StandardValue, string.Empty, RegistryValueOptions.None) as string;
+ result = string.Equals(registryStandardName, timeZone.StandardName, StringComparison.Ordinal);
+ }
+ return result;
+ }
+ }
+
+ /// <summary>
+ /// Helper function for retrieving a localized string resource via MUI.
+ /// The function expects a string in the form: "@resource.dll, -123"
+ ///
+ /// "resource.dll" is a language-neutral portable executable (LNPE) file in
+ /// the %windir%\system32 directory. The OS is queried to find the best-fit
+ /// localized resource file for this LNPE (ex: %windir%\system32\en-us\resource.dll.mui).
+ /// If a localized resource file exists, we LoadString resource ID "123" and
+ /// return it to our caller.
+ /// </summary>
+ private static string TryGetLocalizedNameByMuiNativeResource(string resource)
+ {
+ if (string.IsNullOrEmpty(resource))
+ {
+ return string.Empty;
+ }
+
+ // parse "@tzres.dll, -100"
+ //
+ // filePath = "C:\Windows\System32\tzres.dll"
+ // resourceId = -100
+ //
+ string[] resources = resource.Split(',');
+ if (resources.Length != 2)
+ {
+ return string.Empty;
+ }
+
+ string filePath;
+ int resourceId;
+
+ // get the path to Windows\System32
+ string system32 = Environment.SystemDirectory;
+
+ // trim the string "@tzres.dll" => "tzres.dll"
+ string tzresDll = resources[0].TrimStart('@');
+
+ try
+ {
+ filePath = Path.Combine(system32, tzresDll);
+ }
+ catch (ArgumentException)
+ {
+ // there were probably illegal characters in the path
+ return string.Empty;
+ }
+
+ if (!int.TryParse(resources[1], NumberStyles.Integer, CultureInfo.InvariantCulture, out resourceId))
+ {
+ return string.Empty;
+ }
+ resourceId = -resourceId;
+
+ try
+ {
+ StringBuilder fileMuiPath = StringBuilderCache.Acquire(Path.MaxPath);
+ fileMuiPath.Length = Path.MaxPath;
+ int fileMuiPathLength = Path.MaxPath;
+ int languageLength = 0;
+ long enumerator = 0;
+
+ bool succeeded = UnsafeNativeMethods.GetFileMUIPath(
+ Win32Native.MUI_PREFERRED_UI_LANGUAGES,
+ filePath, null /* language */, ref languageLength,
+ fileMuiPath, ref fileMuiPathLength, ref enumerator);
+ if (!succeeded)
+ {
+ StringBuilderCache.Release(fileMuiPath);
+ return string.Empty;
+ }
+ return TryGetLocalizedNameByNativeResource(StringBuilderCache.GetStringAndRelease(fileMuiPath), resourceId);
+ }
+ catch (EntryPointNotFoundException)
+ {
+ return string.Empty;
+ }
+ }
+
+ /// <summary>
+ /// Helper function for retrieving a localized string resource via a native resource DLL.
+ /// The function expects a string in the form: "C:\Windows\System32\en-us\resource.dll"
+ ///
+ /// "resource.dll" is a language-specific resource DLL.
+ /// If the localized resource DLL exists, LoadString(resource) is returned.
+ /// </summary>
+ private static string TryGetLocalizedNameByNativeResource(string filePath, int resource)
+ {
+ using (SafeLibraryHandle handle =
+ UnsafeNativeMethods.LoadLibraryEx(filePath, IntPtr.Zero, Win32Native.LOAD_LIBRARY_AS_DATAFILE))
+ {
+ if (!handle.IsInvalid)
+ {
+ StringBuilder localizedResource = StringBuilderCache.Acquire(Win32Native.LOAD_STRING_MAX_LENGTH);
+ localizedResource.Length = Win32Native.LOAD_STRING_MAX_LENGTH;
+
+ int result = UnsafeNativeMethods.LoadString(handle, resource,
+ localizedResource, localizedResource.Length);
+
+ if (result != 0)
+ {
+ return StringBuilderCache.GetStringAndRelease(localizedResource);
+ }
+ }
+ }
+ return string.Empty;
+ }
+
+ /// <summary>
+ /// Helper function for retrieving the DisplayName, StandardName, and DaylightName from the registry
+ ///
+ /// The function first checks the MUI_ key-values, and if they exist, it loads the strings from the MUI
+ /// resource dll(s). When the keys do not exist, the function falls back to reading from the standard
+ /// key-values
+ /// </summary>
+ private static bool TryGetLocalizedNamesByRegistryKey(RegistryKey key, out string displayName, out string standardName, out string daylightName)
+ {
+ displayName = string.Empty;
+ standardName = string.Empty;
+ daylightName = string.Empty;
+
+ // read the MUI_ registry keys
+ string displayNameMuiResource = key.GetValue(MuiDisplayValue, string.Empty, RegistryValueOptions.None) as string;
+ string standardNameMuiResource = key.GetValue(MuiStandardValue, string.Empty, RegistryValueOptions.None) as string;
+ string daylightNameMuiResource = key.GetValue(MuiDaylightValue, string.Empty, RegistryValueOptions.None) as string;
+
+ // try to load the strings from the native resource DLL(s)
+ if (!string.IsNullOrEmpty(displayNameMuiResource))
+ {
+ displayName = TryGetLocalizedNameByMuiNativeResource(displayNameMuiResource);
+ }
+
+ if (!string.IsNullOrEmpty(standardNameMuiResource))
+ {
+ standardName = TryGetLocalizedNameByMuiNativeResource(standardNameMuiResource);
+ }
+
+ if (!string.IsNullOrEmpty(daylightNameMuiResource))
+ {
+ daylightName = TryGetLocalizedNameByMuiNativeResource(daylightNameMuiResource);
+ }
+
+ // fallback to using the standard registry keys
+ if (string.IsNullOrEmpty(displayName))
+ {
+ displayName = key.GetValue(DisplayValue, string.Empty, RegistryValueOptions.None) as string;
+ }
+ if (string.IsNullOrEmpty(standardName))
+ {
+ standardName = key.GetValue(StandardValue, string.Empty, RegistryValueOptions.None) as string;
+ }
+ if (string.IsNullOrEmpty(daylightName))
+ {
+ daylightName = key.GetValue(DaylightValue, string.Empty, RegistryValueOptions.None) as string;
+ }
+
+ return true;
+ }
+
+ /// <summary>
+ /// Helper function that takes a string representing a <time_zone_name> registry key name
+ /// and returns a TimeZoneInfo instance.
+ /// </summary>
+ private static TimeZoneInfoResult TryGetTimeZoneFromLocalMachine(string id, out TimeZoneInfo value, out Exception e)
+ {
+ e = null;
+
+ // Standard Time Zone Registry Data
+ // -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+ // HKLM
+ // Software
+ // Microsoft
+ // Windows NT
+ // CurrentVersion
+ // Time Zones
+ // <time_zone_name>
+ // * STD, REG_SZ "Standard Time Name"
+ // (For OS installed zones, this will always be English)
+ // * MUI_STD, REG_SZ "@tzres.dll,-1234"
+ // Indirect string to localized resource for Standard Time,
+ // add "%windir%\system32\" after "@"
+ // * DLT, REG_SZ "Daylight Time Name"
+ // (For OS installed zones, this will always be English)
+ // * MUI_DLT, REG_SZ "@tzres.dll,-1234"
+ // Indirect string to localized resource for Daylight Time,
+ // add "%windir%\system32\" after "@"
+ // * Display, REG_SZ "Display Name like (GMT-8:00) Pacific Time..."
+ // * MUI_Display, REG_SZ "@tzres.dll,-1234"
+ // Indirect string to localized resource for the Display,
+ // add "%windir%\system32\" after "@"
+ // * TZI, REG_BINARY REG_TZI_FORMAT
+ // See Win32Native.RegistryTimeZoneInformation
+ //
+ using (RegistryKey key = Registry.LocalMachine.OpenSubKey(TimeZonesRegistryHive + "\\" + id, writable: false))
+ {
+ if (key == null)
+ {
+ value = null;
+ return TimeZoneInfoResult.TimeZoneNotFoundException;
+ }
+
+ Win32Native.RegistryTimeZoneInformation defaultTimeZoneInformation;
+ byte[] regValue = key.GetValue(TimeZoneInfoValue, null, RegistryValueOptions.None) as byte[];
+ if (regValue == null || regValue.Length != RegByteLength)
+ {
+ // the registry value could not be cast to a byte array
+ value = null;
+ return TimeZoneInfoResult.InvalidTimeZoneException;
+ }
+ defaultTimeZoneInformation = new Win32Native.RegistryTimeZoneInformation(regValue);
+
+ AdjustmentRule[] adjustmentRules;
+ if (!TryCreateAdjustmentRules(id, defaultTimeZoneInformation, out adjustmentRules, out e, defaultTimeZoneInformation.Bias))
+ {
+ value = null;
+ return TimeZoneInfoResult.InvalidTimeZoneException;
+ }
+
+ string displayName;
+ string standardName;
+ string daylightName;
+
+ if (!TryGetLocalizedNamesByRegistryKey(key, out displayName, out standardName, out daylightName))
+ {
+ value = null;
+ return TimeZoneInfoResult.InvalidTimeZoneException;
+ }
+
+ try
+ {
+ value = new TimeZoneInfo(
+ id,
+ new TimeSpan(0, -(defaultTimeZoneInformation.Bias), 0),
+ displayName,
+ standardName,
+ daylightName,
+ adjustmentRules,
+ disableDaylightSavingTime: false);
+
+ return TimeZoneInfoResult.Success;
+ }
+ catch (ArgumentException ex)
+ {
+ // TimeZoneInfo constructor can throw ArgumentException and InvalidTimeZoneException
+ value = null;
+ e = ex;
+ return TimeZoneInfoResult.InvalidTimeZoneException;
+ }
+ catch (InvalidTimeZoneException ex)
+ {
+ // TimeZoneInfo constructor can throw ArgumentException and InvalidTimeZoneException
+ value = null;
+ e = ex;
+ return TimeZoneInfoResult.InvalidTimeZoneException;
+ }
+
+ }
+ }
+ }
+}
diff --git a/src/mscorlib/src/System/TimeZoneInfo.cs b/src/mscorlib/src/System/TimeZoneInfo.cs
index 72fc28fc3e..fc5625be2e 100644
--- a/src/mscorlib/src/System/TimeZoneInfo.cs
+++ b/src/mscorlib/src/System/TimeZoneInfo.cs
@@ -2,38 +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.
-/*============================================================
-**
-**
-**
-** Purpose:
-** This class is used to represent a Dynamic TimeZone. It
-** has methods for converting a DateTime between TimeZones,
-** and for reading TimeZone data from the Windows Registry
-**
-**
-============================================================*/
-
-namespace System {
- using Microsoft.Win32;
- using Microsoft.Win32.SafeHandles;
- using System;
- using System.Collections;
- using System.Collections.Generic;
- using System.Collections.ObjectModel;
- using System.Diagnostics;
- using System.Diagnostics.Contracts;
- using System.Globalization;
- using System.IO;
- using System.Runtime.CompilerServices;
- using System.Runtime.InteropServices;
- using System.Runtime.Serialization;
- using System.Runtime.Versioning;
- using System.Security;
- using System.Security.Permissions;
- using System.Text;
- using System.Threading;
-
+using System.Collections.Generic;
+using System.Collections.ObjectModel;
+using System.Diagnostics.Contracts;
+using System.Globalization;
+using System.Runtime.Serialization;
+using System.Threading;
+
+namespace System
+{
//
// DateTime uses TimeZoneInfo under the hood for IsDaylightSavingTime, IsAmbiguousTime, and GetUtcOffset.
// These TimeZoneInfo APIs can throw ArgumentException when an Invalid-Time is passed in. To avoid this
@@ -44,137 +21,101 @@ namespace System {
// demand for this alternate behavior.
//
[Flags]
- internal enum TimeZoneInfoOptions {
- None = 1,
- NoThrowOnInvalidTime = 2
+ internal enum TimeZoneInfoOptions
+ {
+ None = 1,
+ NoThrowOnInvalidTime = 2
};
[Serializable]
- [System.Security.Permissions.HostProtection(MayLeakOnAbort = true)]
- sealed public class TimeZoneInfo : IEquatable<TimeZoneInfo>, ISerializable, IDeserializationCallback
+ public sealed partial class TimeZoneInfo : IEquatable<TimeZoneInfo>, ISerializable, IDeserializationCallback
{
- // ---- SECTION: members supporting exposed properties -------------*
- 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 {
- Success = 0,
+ private enum TimeZoneInfoResult
+ {
+ Success = 0,
TimeZoneNotFoundException = 1,
- InvalidTimeZoneException = 2,
- SecurityException = 3
+ InvalidTimeZoneException = 2,
+ SecurityException = 3
};
-
-#if FEATURE_WIN32_REGISTRY
- // registry constants for the 'Time Zones' hive
- //
- private const string c_timeZonesRegistryHive = @"SOFTWARE\Microsoft\Windows NT\CurrentVersion\Time Zones";
- private const string c_timeZonesRegistryHivePermissionList = @"HKEY_LOCAL_MACHINE\" + c_timeZonesRegistryHive;
- private const string c_displayValue = "Display";
- private const string c_daylightValue = "Dlt";
- private const string c_standardValue = "Std";
- private const string c_muiDisplayValue = "MUI_Display";
- private const string c_muiDaylightValue = "MUI_Dlt";
- private const string c_muiStandardValue = "MUI_Std";
- private const string c_timeZoneInfoValue = "TZI";
- private const string c_firstEntryValue = "FirstEntry";
- private const string c_lastEntryValue = "LastEntry";
-
-#endif // FEATURE_WIN32_REGISTRY
-
-#if PLATFORM_UNIX
- private const string c_defaultTimeZoneDirectory = "/usr/share/zoneinfo/";
- private const string c_zoneTabFileName = "zone.tab";
- private const string c_timeZoneEnvironmentVariable = "TZ";
- private const string c_timeZoneDirectoryEnvironmentVariable = "TZDIR";
-#endif // PLATFORM_UNIX
+ private readonly string _id;
+ private readonly string _displayName;
+ private readonly string _standardDisplayName;
+ private readonly string _daylightDisplayName;
+ private readonly TimeSpan _baseUtcOffset;
+ private readonly bool _supportsDaylightSavingTime;
+ private readonly AdjustmentRule[] _adjustmentRules;
// constants for TimeZoneInfo.Local and TimeZoneInfo.Utc
- private const string c_utcId = "UTC";
- private const string c_localId = "Local";
-
- private const int c_maxKeyLength = 255;
+ private const string UtcId = "UTC";
+ private const string LocalId = "Local";
- private const int c_regByteLength = 44;
+ private static readonly TimeZoneInfo s_utcTimeZone = CreateCustomTimeZone(UtcId, TimeSpan.Zero, UtcId, UtcId);
- // Number of 100ns ticks per time unit
- private const long c_ticksPerMillisecond = 10000;
- private const long c_ticksPerSecond = c_ticksPerMillisecond * 1000;
- private const long c_ticksPerMinute = c_ticksPerSecond * 60;
- private const long c_ticksPerHour = c_ticksPerMinute * 60;
- 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);
+ private static CachedData s_cachedData = new CachedData();
//
// All cached data are encapsulated in a helper class to allow consistent view even when the data are refreshed using ClearCachedData()
//
- // For example, TimeZoneInfo.Local can be cleared by another thread calling TimeZoneInfo.ClearCachedData. Without the consistent snapshot,
+ // For example, TimeZoneInfo.Local can be cleared by another thread calling TimeZoneInfo.ClearCachedData. Without the consistent snapshot,
// there is a chance that the internal ConvertTime calls will throw since 'source' won't be reference equal to the new TimeZoneInfo.Local.
//
#pragma warning disable 0420
- class CachedData
+ private sealed partial class CachedData
{
- private volatile TimeZoneInfo m_localTimeZone;
+ private volatile TimeZoneInfo _localTimeZone;
private TimeZoneInfo CreateLocal()
{
lock (this)
{
- TimeZoneInfo timeZone = m_localTimeZone;
- if (timeZone == null) {
- timeZone = TimeZoneInfo.GetLocalTimeZone(this);
+ TimeZoneInfo timeZone = _localTimeZone;
+ if (timeZone == null)
+ {
+ timeZone = GetLocalTimeZone(this);
// this step is to break the reference equality
// between TimeZoneInfo.Local and a second time zone
// such as "Pacific Standard Time"
timeZone = new TimeZoneInfo(
- timeZone.m_id,
- timeZone.m_baseUtcOffset,
- timeZone.m_displayName,
- timeZone.m_standardDisplayName,
- timeZone.m_daylightDisplayName,
- timeZone.m_adjustmentRules,
- false);
-
- m_localTimeZone = timeZone;
+ timeZone._id,
+ timeZone._baseUtcOffset,
+ timeZone._displayName,
+ timeZone._standardDisplayName,
+ timeZone._daylightDisplayName,
+ timeZone._adjustmentRules,
+ disableDaylightSavingTime: false);
+
+ _localTimeZone = timeZone;
}
return timeZone;
}
}
- public TimeZoneInfo Local {
- get {
- TimeZoneInfo timeZone = m_localTimeZone;
- if (timeZone == null) {
+ public TimeZoneInfo Local
+ {
+ get
+ {
+ TimeZoneInfo timeZone = _localTimeZone;
+ if (timeZone == null)
+ {
timeZone = CreateLocal();
}
return timeZone;
}
}
- //
- // GetCorrespondingKind-
- //
- // Helper function that returns the corresponding DateTimeKind for this TimeZoneInfo
- //
- public DateTimeKind GetCorrespondingKind(TimeZoneInfo timeZone) {
- DateTimeKind kind;
-
- //
- // we check reference equality to see if 'this' is the same as
- // TimeZoneInfo.Local or TimeZoneInfo.Utc. This check is needed to
+ /// <summary>
+ /// Helper function that returns the corresponding DateTimeKind for this TimeZoneInfo.
+ /// </summary>
+ public DateTimeKind GetCorrespondingKind(TimeZoneInfo timeZone)
+ {
+ // We check reference equality to see if 'this' is the same as
+ // TimeZoneInfo.Local or TimeZoneInfo.Utc. This check is needed to
// support setting the DateTime Kind property to 'Local' or
- // 'Utc' on the ConverTime(...) return value.
+ // 'Utc' on the ConverTime(...) return value.
//
- // Using reference equality instead of value equality was a
+ // Using reference equality instead of value equality was a
// performance based design compromise. The reference equality
// has much greater performance, but it reduces the number of
// returned DateTime's that can be properly set as 'Local' or 'Utc'.
@@ -187,244 +128,133 @@ 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)s_utcTimeZone) {
- kind = DateTimeKind.Utc;
- }
- else if ((object)timeZone == (object)m_localTimeZone) {
- kind = DateTimeKind.Local;
- }
- else {
- kind = DateTimeKind.Unspecified;
- }
-
- return kind;
- }
-
- public Dictionary<string, TimeZoneInfo> m_systemTimeZones;
- public ReadOnlyCollection<TimeZoneInfo> m_readOnlySystemTimeZones;
- public bool m_allSystemTimeZonesRead;
-
-#if FEATURE_WIN32_REGISTRY
- private static TimeZoneInfo GetCurrentOneYearLocal() {
- // load the data from the OS
- TimeZoneInfo match;
-
- Win32Native.TimeZoneInformation timeZoneInformation = new Win32Native.TimeZoneInformation();
- long result = UnsafeNativeMethods.GetTimeZoneInformation(out timeZoneInformation);
- if (result == Win32Native.TIME_ZONE_ID_INVALID)
- match = CreateCustomTimeZone(c_localId, TimeSpan.Zero, c_localId, c_localId);
- else
- match = GetLocalTimeZoneFromWin32Data(timeZoneInformation, false);
- return match;
- }
-
- private volatile OffsetAndRule m_oneYearLocalFromUtc;
-
- public OffsetAndRule GetOneYearLocalFromUtc(int year) {
- OffsetAndRule oneYearLocFromUtc = m_oneYearLocalFromUtc;
- if (oneYearLocFromUtc == null || oneYearLocFromUtc.year != year) {
- TimeZoneInfo currentYear = GetCurrentOneYearLocal();
- AdjustmentRule rule = currentYear.m_adjustmentRules == null ? null : currentYear.m_adjustmentRules[0];
- oneYearLocFromUtc = new OffsetAndRule(year, currentYear.BaseUtcOffset, rule);
- m_oneYearLocalFromUtc = oneYearLocFromUtc;
- }
- return oneYearLocFromUtc;
+ return
+ ReferenceEquals(timeZone, s_utcTimeZone) ? DateTimeKind.Utc :
+ ReferenceEquals(timeZone, _localTimeZone) ? DateTimeKind.Local :
+ DateTimeKind.Unspecified;
}
-#endif // FEATURE_WIN32_REGISTRY
+ public Dictionary<string, TimeZoneInfo> _systemTimeZones;
+ public ReadOnlyCollection<TimeZoneInfo> _readOnlySystemTimeZones;
+ public bool _allSystemTimeZonesRead;
};
#pragma warning restore 0420
- static CachedData s_cachedData = new CachedData();
-
- private class OffsetAndRule {
- public int year;
- public TimeSpan offset;
- public AdjustmentRule rule;
- public OffsetAndRule(int year, TimeSpan offset, AdjustmentRule rule) {
- this.year = year;
- this.offset = offset;
- this.rule = rule;
- }
- }
-
// used by GetUtcOffsetFromUtc (DateTime.Now, DateTime.ToLocalTime) for max/min whole-day range checks
- private static DateTime s_maxDateOnly = new DateTime(9999, 12, 31);
- private static DateTime s_minDateOnly = new DateTime(1, 1, 2);
-
- // ---- SECTION: public properties --------------*
-
- public String Id {
- get {
- return m_id;
- }
- }
-
- public String DisplayName {
- get {
- return (m_displayName == null ? String.Empty : m_displayName);
- }
- }
+ private static readonly DateTime s_maxDateOnly = new DateTime(9999, 12, 31);
+ private static readonly DateTime s_minDateOnly = new DateTime(1, 1, 2);
- public String StandardName {
- get {
- return (m_standardDisplayName == null ? String.Empty : m_standardDisplayName);
- }
- }
+ public string Id => _id;
- public String DaylightName {
- get {
- return (m_daylightDisplayName == null? String.Empty : m_daylightDisplayName);
- }
- }
-
- public TimeSpan BaseUtcOffset {
- get {
- return m_baseUtcOffset;
- }
- }
+ public string DisplayName => _displayName ?? string.Empty;
- public Boolean SupportsDaylightSavingTime {
- get {
- return m_supportsDaylightSavingTime;
- }
- }
+ public string StandardName => _standardDisplayName ?? string.Empty;
-#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
+ public string DaylightName => _daylightDisplayName ?? string.Empty;
- private AdjustmentRule[] GetFilledRules()
- {
- Debug.Assert(m_adjustmentRules != null, "m_adjustmentRules expected to be not null");
- AdjustmentRule[] rules = new AdjustmentRule[m_adjustmentRules.Length];
+ public TimeSpan BaseUtcOffset => _baseUtcOffset;
- 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);
- }
+ public bool SupportsDaylightSavingTime => _supportsDaylightSavingTime;
- return rules;
- }
-#endif // PLATFORM_UNIX
-
- // ---- SECTION: public methods --------------*
- //
- // GetAdjustmentRules -
- //
- // returns a cloned array of AdjustmentRule objects
- //
- public AdjustmentRule [] GetAdjustmentRules()
+ /// <summary>
+ /// Returns an array of TimeSpan objects representing all of
+ /// possible UTC offset values for this ambiguous time.
+ /// </summary>
+ public TimeSpan[] GetAmbiguousTimeOffsets(DateTimeOffset dateTimeOffset)
{
- if (m_adjustmentRules == null)
- {
- return Array.Empty<AdjustmentRule>();
- }
- else
+ if (!SupportsDaylightSavingTime)
{
-#if PLATFORM_UNIX
- return GetFilledRules();
-#else
- return (AdjustmentRule[]) m_adjustmentRules.Clone();
-#endif // PLATFORM_UNIX
- }
- }
-
- //
- // GetAmbiguousTimeOffsets -
- //
- // returns an array of TimeSpan objects representing all of
- // possible UTC offset values for this ambiguous time
- //
- public TimeSpan[] GetAmbiguousTimeOffsets(DateTimeOffset dateTimeOffset) {
- if (!SupportsDaylightSavingTime) {
throw new ArgumentException(Environment.GetResourceString("Argument_DateTimeOffsetIsNotAmbiguous"), nameof(dateTimeOffset));
}
Contract.EndContractBlock();
- DateTime adjustedTime = (TimeZoneInfo.ConvertTime(dateTimeOffset, this)).DateTime;
+ DateTime adjustedTime = ConvertTime(dateTimeOffset, this).DateTime;
- Boolean isAmbiguous = false;
+ bool isAmbiguous = false;
AdjustmentRule rule = GetAdjustmentRuleForAmbiguousOffsets(adjustedTime);
- if (rule != null && rule.HasDaylightSaving) {
+ if (rule != null && rule.HasDaylightSaving)
+ {
DaylightTimeStruct daylightTime = GetDaylightTime(adjustedTime.Year, rule);
isAmbiguous = GetIsAmbiguousTime(adjustedTime, rule, daylightTime);
}
- if (!isAmbiguous) {
+ if (!isAmbiguous)
+ {
throw new ArgumentException(Environment.GetResourceString("Argument_DateTimeOffsetIsNotAmbiguous"), nameof(dateTimeOffset));
}
// the passed in dateTime is ambiguous in this TimeZoneInfo instance
TimeSpan[] timeSpans = new TimeSpan[2];
- TimeSpan actualUtcOffset = m_baseUtcOffset + rule.BaseUtcOffsetDelta;
+ TimeSpan actualUtcOffset = _baseUtcOffset + rule.BaseUtcOffsetDelta;
// the TimeSpan array must be sorted from least to greatest
- if (rule.DaylightDelta > TimeSpan.Zero) {
+ if (rule.DaylightDelta > TimeSpan.Zero)
+ {
timeSpans[0] = actualUtcOffset; // FUTURE: + rule.StandardDelta;
timeSpans[1] = actualUtcOffset + rule.DaylightDelta;
- }
- else {
+ }
+ else
+ {
timeSpans[0] = actualUtcOffset + rule.DaylightDelta;
timeSpans[1] = actualUtcOffset; // FUTURE: + rule.StandardDelta;
}
return timeSpans;
}
-
- public TimeSpan[] GetAmbiguousTimeOffsets(DateTime dateTime) {
- if (!SupportsDaylightSavingTime) {
+ /// <summary>
+ /// Returns an array of TimeSpan objects representing all of
+ /// possible UTC offset values for this ambiguous time.
+ /// </summary>
+ public TimeSpan[] GetAmbiguousTimeOffsets(DateTime dateTime)
+ {
+ if (!SupportsDaylightSavingTime)
+ {
throw new ArgumentException(Environment.GetResourceString("Argument_DateTimeIsNotAmbiguous"), nameof(dateTime));
}
Contract.EndContractBlock();
DateTime adjustedTime;
- if (dateTime.Kind == DateTimeKind.Local) {
+ if (dateTime.Kind == DateTimeKind.Local)
+ {
CachedData cachedData = s_cachedData;
- adjustedTime = TimeZoneInfo.ConvertTime(dateTime, cachedData.Local, this, TimeZoneInfoOptions.None, cachedData);
+ adjustedTime = ConvertTime(dateTime, cachedData.Local, this, TimeZoneInfoOptions.None, cachedData);
}
- else if (dateTime.Kind == DateTimeKind.Utc) {
+ else if (dateTime.Kind == DateTimeKind.Utc)
+ {
CachedData cachedData = s_cachedData;
- adjustedTime = TimeZoneInfo.ConvertTime(dateTime, s_utcTimeZone, this, TimeZoneInfoOptions.None, cachedData);
+ adjustedTime = ConvertTime(dateTime, s_utcTimeZone, this, TimeZoneInfoOptions.None, cachedData);
}
- else {
+ else
+ {
adjustedTime = dateTime;
}
- Boolean isAmbiguous = false;
+ bool isAmbiguous = false;
AdjustmentRule rule = GetAdjustmentRuleForAmbiguousOffsets(adjustedTime);
- if (rule != null && rule.HasDaylightSaving) {
+ if (rule != null && rule.HasDaylightSaving)
+ {
DaylightTimeStruct daylightTime = GetDaylightTime(adjustedTime.Year, rule);
isAmbiguous = GetIsAmbiguousTime(adjustedTime, rule, daylightTime);
}
- if (!isAmbiguous) {
+ if (!isAmbiguous)
+ {
throw new ArgumentException(Environment.GetResourceString("Argument_DateTimeIsNotAmbiguous"), nameof(dateTime));
}
// the passed in dateTime is ambiguous in this TimeZoneInfo instance
TimeSpan[] timeSpans = new TimeSpan[2];
- TimeSpan actualUtcOffset = m_baseUtcOffset + rule.BaseUtcOffsetDelta;
-
+ TimeSpan actualUtcOffset = _baseUtcOffset + rule.BaseUtcOffsetDelta;
+
// the TimeSpan array must be sorted from least to greatest
- if (rule.DaylightDelta > TimeSpan.Zero) {
+ if (rule.DaylightDelta > TimeSpan.Zero)
+ {
timeSpans[0] = actualUtcOffset; // FUTURE: + rule.StandardDelta;
timeSpans[1] = actualUtcOffset + rule.DaylightDelta;
- }
- else {
+ }
+ else
+ {
timeSpans[0] = actualUtcOffset + rule.DaylightDelta;
timeSpans[1] = actualUtcOffset; // FUTURE: + rule.StandardDelta;
}
@@ -448,55 +278,58 @@ namespace System {
/// <summary>
/// Gets the AdjustmentRule that is immediately preceeding the specified rule.
- /// If the specified rule is the first AdjustmentRule, or it isn't in m_adjustmentRules,
+ /// If the specified rule is the first AdjustmentRule, or it isn't in _adjustmentRules,
/// then the specified rule is returned.
/// </summary>
private AdjustmentRule GetPreviousAdjustmentRule(AdjustmentRule rule)
{
AdjustmentRule result = rule;
- for (int i = 1; i < m_adjustmentRules.Length; i++)
+ for (int i = 1; i < _adjustmentRules.Length; i++)
{
- if (rule.Equals(m_adjustmentRules[i]))
+ if (rule.Equals(_adjustmentRules[i]))
{
- result = m_adjustmentRules[i - 1];
+ result = _adjustmentRules[i - 1];
break;
}
}
return result;
}
- //
- // GetUtcOffset -
- //
- // returns the Universal Coordinated Time (UTC) Offset
- // for the current TimeZoneInfo instance.
- //
- public TimeSpan GetUtcOffset(DateTimeOffset dateTimeOffset) {
- return GetUtcOffsetFromUtc(dateTimeOffset.UtcDateTime, this);
- }
-
+ /// <summary>
+ /// Returns the Universal Coordinated Time (UTC) Offset for the current TimeZoneInfo instance.
+ /// </summary>
+ public TimeSpan GetUtcOffset(DateTimeOffset dateTimeOffset) =>
+ GetUtcOffsetFromUtc(dateTimeOffset.UtcDateTime, this);
- public TimeSpan GetUtcOffset(DateTime dateTime) {
- return GetUtcOffset(dateTime, TimeZoneInfoOptions.NoThrowOnInvalidTime, s_cachedData);
- }
+ /// <summary>
+ /// Returns the Universal Coordinated Time (UTC) Offset for the current TimeZoneInfo instance.
+ /// </summary>
+ public TimeSpan GetUtcOffset(DateTime dateTime) =>
+ GetUtcOffset(dateTime, TimeZoneInfoOptions.NoThrowOnInvalidTime, s_cachedData);
// Shortcut for TimeZoneInfo.Local.GetUtcOffset
- internal static TimeSpan GetLocalUtcOffset(DateTime dateTime, TimeZoneInfoOptions flags) {
+ internal static TimeSpan GetLocalUtcOffset(DateTime dateTime, TimeZoneInfoOptions flags)
+ {
CachedData cachedData = s_cachedData;
return cachedData.Local.GetUtcOffset(dateTime, flags, cachedData);
}
- internal TimeSpan GetUtcOffset(DateTime dateTime, TimeZoneInfoOptions flags) {
- return GetUtcOffset(dateTime, flags, s_cachedData);
- }
+ /// <summary>
+ /// Returns the Universal Coordinated Time (UTC) Offset for the current TimeZoneInfo instance.
+ /// </summary>
+ internal TimeSpan GetUtcOffset(DateTime dateTime, TimeZoneInfoOptions flags) =>
+ GetUtcOffset(dateTime, flags, s_cachedData);
- private TimeSpan GetUtcOffset(DateTime dateTime, TimeZoneInfoOptions flags, CachedData cachedData) {
- if (dateTime.Kind == DateTimeKind.Local) {
- if (cachedData.GetCorrespondingKind(this) != DateTimeKind.Local) {
+ private TimeSpan GetUtcOffset(DateTime dateTime, TimeZoneInfoOptions flags, CachedData cachedData)
+ {
+ if (dateTime.Kind == DateTimeKind.Local)
+ {
+ if (cachedData.GetCorrespondingKind(this) != DateTimeKind.Local)
+ {
//
// normal case of converting from Local to Utc and then getting the offset from the UTC DateTime
//
- DateTime adjustedTime = TimeZoneInfo.ConvertTime(dateTime, cachedData.Local, s_utcTimeZone, flags);
+ DateTime adjustedTime = ConvertTime(dateTime, cachedData.Local, s_utcTimeZone, flags);
return GetUtcOffsetFromUtc(adjustedTime, this);
}
@@ -507,7 +340,7 @@ namespace System {
// Consider the invalid PST time "2007-03-11T02:00:00.0000000-08:00"
//
// By directly calling GetUtcOffset instead of converting to UTC and then calling GetUtcOffsetFromUtc
- // the correct invalid offset of "-08:00" is returned. In the normal case of converting to UTC as an
+ // the correct invalid offset of "-08:00" is returned. In the normal case of converting to UTC as an
// interim-step, the invalid time is adjusted into a *valid* UTC time which causes a change in output:
//
// 1) invalid PST time "2007-03-11T02:00:00.0000000-08:00"
@@ -515,11 +348,14 @@ namespace System {
// 3) offset returned "2007-03-11T03:00:00.0000000-07:00"
//
}
- else if (dateTime.Kind == DateTimeKind.Utc) {
- if (cachedData.GetCorrespondingKind(this) == DateTimeKind.Utc) {
- return m_baseUtcOffset;
+ else if (dateTime.Kind == DateTimeKind.Utc)
+ {
+ if (cachedData.GetCorrespondingKind(this) == DateTimeKind.Utc)
+ {
+ return _baseUtcOffset;
}
- else {
+ else
+ {
//
// passing in a UTC dateTime to a non-UTC TimeZoneInfo instance is a
// special Loss-Less case.
@@ -531,90 +367,93 @@ namespace System {
return GetUtcOffset(dateTime, this, flags);
}
- //
- // IsAmbiguousTime -
- //
- // returns true if the time is during the ambiguous time period
- // for the current TimeZoneInfo instance.
- //
- public Boolean IsAmbiguousTime(DateTimeOffset dateTimeOffset) {
- if (!m_supportsDaylightSavingTime) {
+ /// <summary>
+ /// Returns true if the time is during the ambiguous time period
+ /// for the current TimeZoneInfo instance.
+ /// </summary>
+ public bool IsAmbiguousTime(DateTimeOffset dateTimeOffset)
+ {
+ if (!_supportsDaylightSavingTime)
+ {
return false;
}
- DateTimeOffset adjustedTime = TimeZoneInfo.ConvertTime(dateTimeOffset, this);
+ DateTimeOffset adjustedTime = ConvertTime(dateTimeOffset, this);
return IsAmbiguousTime(adjustedTime.DateTime);
}
+ /// <summary>
+ /// Returns true if the time is during the ambiguous time period
+ /// for the current TimeZoneInfo instance.
+ /// </summary>
+ public bool IsAmbiguousTime(DateTime dateTime) =>
+ IsAmbiguousTime(dateTime, TimeZoneInfoOptions.NoThrowOnInvalidTime);
- public Boolean IsAmbiguousTime(DateTime dateTime) {
- return IsAmbiguousTime(dateTime, TimeZoneInfoOptions.NoThrowOnInvalidTime);
- }
-
- internal Boolean IsAmbiguousTime(DateTime dateTime, TimeZoneInfoOptions flags) {
- if (!m_supportsDaylightSavingTime) {
+ /// <summary>
+ /// Returns true if the time is during the ambiguous time period
+ /// for the current TimeZoneInfo instance.
+ /// </summary>
+ internal bool IsAmbiguousTime(DateTime dateTime, TimeZoneInfoOptions flags)
+ {
+ if (!_supportsDaylightSavingTime)
+ {
return false;
}
- DateTime adjustedTime;
- if (dateTime.Kind == DateTimeKind.Local) {
- CachedData cachedData = s_cachedData;
- adjustedTime = TimeZoneInfo.ConvertTime(dateTime, cachedData.Local, this, flags, cachedData);
- }
- else if (dateTime.Kind == DateTimeKind.Utc) {
- CachedData cachedData = s_cachedData;
- adjustedTime = TimeZoneInfo.ConvertTime(dateTime, s_utcTimeZone, this, flags, cachedData);
- }
- else {
- adjustedTime = dateTime;
- }
+ CachedData cachedData = s_cachedData;
+ DateTime adjustedTime =
+ dateTime.Kind == DateTimeKind.Local ? ConvertTime(dateTime, cachedData.Local, this, flags, cachedData) :
+ dateTime.Kind == DateTimeKind.Utc ? ConvertTime(dateTime, s_utcTimeZone, this, flags, cachedData) :
+ dateTime;
AdjustmentRule rule = GetAdjustmentRuleForTime(adjustedTime);
- if (rule != null && rule.HasDaylightSaving) {
+ if (rule != null && rule.HasDaylightSaving)
+ {
DaylightTimeStruct daylightTime = GetDaylightTime(adjustedTime.Year, rule);
return GetIsAmbiguousTime(adjustedTime, rule, daylightTime);
}
return false;
}
-
-
- //
- // IsDaylightSavingTime -
- //
- // Returns true if the time is during Daylight Saving time
- // for the current TimeZoneInfo instance.
- //
- public Boolean IsDaylightSavingTime(DateTimeOffset dateTimeOffset) {
- Boolean isDaylightSavingTime;
+ /// <summary>
+ /// Returns true if the time is during Daylight Saving time for the current TimeZoneInfo instance.
+ /// </summary>
+ public bool IsDaylightSavingTime(DateTimeOffset dateTimeOffset)
+ {
+ bool isDaylightSavingTime;
GetUtcOffsetFromUtc(dateTimeOffset.UtcDateTime, this, out isDaylightSavingTime);
return isDaylightSavingTime;
}
+ /// <summary>
+ /// Returns true if the time is during Daylight Saving time for the current TimeZoneInfo instance.
+ /// </summary>
+ public bool IsDaylightSavingTime(DateTime dateTime) =>
+ IsDaylightSavingTime(dateTime, TimeZoneInfoOptions.NoThrowOnInvalidTime, s_cachedData);
- public Boolean IsDaylightSavingTime(DateTime dateTime) {
- return IsDaylightSavingTime(dateTime, TimeZoneInfoOptions.NoThrowOnInvalidTime, s_cachedData);
- }
-
- internal Boolean IsDaylightSavingTime(DateTime dateTime, TimeZoneInfoOptions flags) {
- return IsDaylightSavingTime(dateTime, flags, s_cachedData);
- }
+ /// <summary>
+ /// Returns true if the time is during Daylight Saving time for the current TimeZoneInfo instance.
+ /// </summary>
+ internal bool IsDaylightSavingTime(DateTime dateTime, TimeZoneInfoOptions flags) =>
+ IsDaylightSavingTime(dateTime, flags, s_cachedData);
- private Boolean IsDaylightSavingTime(DateTime dateTime, TimeZoneInfoOptions flags, CachedData cachedData) {
+ private bool IsDaylightSavingTime(DateTime dateTime, TimeZoneInfoOptions flags, CachedData cachedData)
+ {
//
// dateTime.Kind is UTC, then time will be converted from UTC
// into current instance's timezone
- // dateTime.Kind is Local, then time will be converted from Local
+ // dateTime.Kind is Local, then time will be converted from Local
// into current instance's timezone
// dateTime.Kind is UnSpecified, then time is already in
// current instance's timezone
//
// Our DateTime handles ambiguous times, (one is in the daylight and
- // one is in standard.) If a new DateTime is constructed during ambiguous
+ // one is in standard.) If a new DateTime is constructed during ambiguous
// time, it is defaulted to "Standard" (i.e. this will return false).
// For Invalid times, we will return false
- if (!m_supportsDaylightSavingTime || m_adjustmentRules == null) {
+ if (!_supportsDaylightSavingTime || _adjustmentRules == null)
+ {
return false;
}
@@ -622,25 +461,30 @@ namespace System {
//
// handle any Local/Utc special cases...
//
- if (dateTime.Kind == DateTimeKind.Local) {
- adjustedTime = TimeZoneInfo.ConvertTime(dateTime, cachedData.Local, this, flags, cachedData);
- }
- else if (dateTime.Kind == DateTimeKind.Utc) {
- if (cachedData.GetCorrespondingKind(this) == DateTimeKind.Utc) {
+ if (dateTime.Kind == DateTimeKind.Local)
+ {
+ adjustedTime = ConvertTime(dateTime, cachedData.Local, this, flags, cachedData);
+ }
+ else if (dateTime.Kind == DateTimeKind.Utc)
+ {
+ if (cachedData.GetCorrespondingKind(this) == DateTimeKind.Utc)
+ {
// simple always false case: TimeZoneInfo.Utc.IsDaylightSavingTime(dateTime, flags);
return false;
}
- else {
+ else
+ {
//
// passing in a UTC dateTime to a non-UTC TimeZoneInfo instance is a
// special Loss-Less case.
//
- Boolean isDaylightSavings;
+ bool isDaylightSavings;
GetUtcOffsetFromUtc(dateTime, this, out isDaylightSavings);
return isDaylightSavings;
}
}
- else {
+ else
+ {
adjustedTime = dateTime;
}
@@ -648,35 +492,38 @@ namespace System {
// handle the normal cases...
//
AdjustmentRule rule = GetAdjustmentRuleForTime(adjustedTime);
- if (rule != null && rule.HasDaylightSaving) {
+ if (rule != null && rule.HasDaylightSaving)
+ {
DaylightTimeStruct daylightTime = GetDaylightTime(adjustedTime.Year, rule);
return GetIsDaylightSavings(adjustedTime, rule, daylightTime, flags);
}
- else {
+ else
+ {
return false;
}
}
+ /// <summary>
+ /// Returns true when dateTime falls into a "hole in time".
+ /// </summary>
+ public bool IsInvalidTime(DateTime dateTime)
+ {
+ bool isInvalid = false;
- //
- // IsInvalidTime -
- //
- // returns true when dateTime falls into a "hole in time".
- //
- public Boolean IsInvalidTime(DateTime dateTime) {
- Boolean isInvalid = false;
-
- if ( (dateTime.Kind == DateTimeKind.Unspecified)
- || (dateTime.Kind == DateTimeKind.Local && s_cachedData.GetCorrespondingKind(this) == DateTimeKind.Local) ) {
+ if ((dateTime.Kind == DateTimeKind.Unspecified) ||
+ (dateTime.Kind == DateTimeKind.Local && s_cachedData.GetCorrespondingKind(this) == DateTimeKind.Local))
+ {
// only check Unspecified and (Local when this TimeZoneInfo instance is Local)
AdjustmentRule rule = GetAdjustmentRuleForTime(dateTime);
- if (rule != null && rule.HasDaylightSaving) {
+ if (rule != null && rule.HasDaylightSaving)
+ {
DaylightTimeStruct daylightTime = GetDaylightTime(dateTime.Year, rule);
isInvalid = GetIsInvalidTime(dateTime, rule, daylightTime);
}
- else {
+ else
+ {
isInvalid = false;
}
}
@@ -684,35 +531,33 @@ namespace System {
return isInvalid;
}
-
- //
- // ClearCachedData -
- //
- // Clears data from static members
- //
- static public void ClearCachedData() {
+ /// <summary>
+ /// Clears data from static members.
+ /// </summary>
+ public static void ClearCachedData()
+ {
// Clear a fresh instance of cached data
s_cachedData = new CachedData();
}
- //
- // ConvertTimeBySystemTimeZoneId -
- //
- // Converts the value of a DateTime object from sourceTimeZone to destinationTimeZone
- //
- static public DateTimeOffset ConvertTimeBySystemTimeZoneId(DateTimeOffset dateTimeOffset, String destinationTimeZoneId)
- {
- return ConvertTime(dateTimeOffset, FindSystemTimeZoneById(destinationTimeZoneId));
- }
+ /// <summary>
+ /// Converts the value of a DateTime object from sourceTimeZone to destinationTimeZone.
+ /// </summary>
+ public static DateTimeOffset ConvertTimeBySystemTimeZoneId(DateTimeOffset dateTimeOffset, string destinationTimeZoneId) =>
+ ConvertTime(dateTimeOffset, FindSystemTimeZoneById(destinationTimeZoneId));
- static public DateTime ConvertTimeBySystemTimeZoneId(DateTime dateTime, String destinationTimeZoneId)
- {
- return ConvertTime(dateTime, FindSystemTimeZoneById(destinationTimeZoneId));
- }
+ /// <summary>
+ /// Converts the value of a DateTime object from sourceTimeZone to destinationTimeZone.
+ /// </summary>
+ public static DateTime ConvertTimeBySystemTimeZoneId(DateTime dateTime, string destinationTimeZoneId) =>
+ ConvertTime(dateTime, FindSystemTimeZoneById(destinationTimeZoneId));
- static public DateTime ConvertTimeBySystemTimeZoneId(DateTime dateTime, String sourceTimeZoneId, String destinationTimeZoneId)
+ /// <summary>
+ /// Converts the value of a DateTime object from sourceTimeZone to destinationTimeZone.
+ /// </summary>
+ public static DateTime ConvertTimeBySystemTimeZoneId(DateTime dateTime, string sourceTimeZoneId, string destinationTimeZoneId)
{
- if (dateTime.Kind == DateTimeKind.Local && String.Compare(sourceTimeZoneId, TimeZoneInfo.Local.Id, StringComparison.OrdinalIgnoreCase) == 0)
+ if (dateTime.Kind == DateTimeKind.Local && string.Equals(sourceTimeZoneId, Local.Id, StringComparison.OrdinalIgnoreCase))
{
// 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.
@@ -721,16 +566,10 @@ 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.Equals(sourceTimeZoneId, Utc.Id, StringComparison.OrdinalIgnoreCase))
{
- // 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, s_utcTimeZone, FindSystemTimeZoneById(destinationTimeZoneId), TimeZoneInfoOptions.None, cachedData);
+ return ConvertTime(dateTime, s_utcTimeZone, FindSystemTimeZoneById(destinationTimeZoneId), TimeZoneInfoOptions.None, s_cachedData);
}
else
{
@@ -738,77 +577,80 @@ namespace System {
}
}
- //
- // ConvertTime -
- //
- // Converts the value of the dateTime object from sourceTimeZone to destinationTimeZone
- //
-
- static public DateTimeOffset ConvertTime(DateTimeOffset dateTimeOffset, TimeZoneInfo destinationTimeZone) {
- if (destinationTimeZone == null) {
+ /// <summary>
+ /// Converts the value of the dateTime object from sourceTimeZone to destinationTimeZone
+ /// </summary>
+ public static DateTimeOffset ConvertTime(DateTimeOffset dateTimeOffset, TimeZoneInfo destinationTimeZone)
+ {
+ if (destinationTimeZone == null)
+ {
throw new ArgumentNullException(nameof(destinationTimeZone));
}
-
Contract.EndContractBlock();
+
// calculate the destination time zone offset
DateTime utcDateTime = dateTimeOffset.UtcDateTime;
TimeSpan destinationOffset = GetUtcOffsetFromUtc(utcDateTime, destinationTimeZone);
// check for overflow
- Int64 ticks = utcDateTime.Ticks + destinationOffset.Ticks;
+ long ticks = utcDateTime.Ticks + destinationOffset.Ticks;
- if (ticks > DateTimeOffset.MaxValue.Ticks) {
- return DateTimeOffset.MaxValue;
- }
- else if (ticks < DateTimeOffset.MinValue.Ticks) {
- return DateTimeOffset.MinValue;
- }
- else {
- return new DateTimeOffset(ticks, destinationOffset);
- }
+ return
+ ticks > DateTimeOffset.MaxValue.Ticks ? DateTimeOffset.MaxValue :
+ ticks < DateTimeOffset.MinValue.Ticks ? DateTimeOffset.MinValue :
+ new DateTimeOffset(ticks, destinationOffset);
}
- static public DateTime ConvertTime(DateTime dateTime, TimeZoneInfo destinationTimeZone) {
- if (destinationTimeZone == null) {
+ /// <summary>
+ /// Converts the value of the dateTime object from sourceTimeZone to destinationTimeZone
+ /// </summary>
+ public static DateTime ConvertTime(DateTime dateTime, TimeZoneInfo destinationTimeZone)
+ {
+ if (destinationTimeZone == null)
+ {
throw new ArgumentNullException(nameof(destinationTimeZone));
}
Contract.EndContractBlock();
// Special case to give a way clearing the cache without exposing ClearCachedData()
- if (dateTime.Ticks == 0) {
+ if (dateTime.Ticks == 0)
+ {
ClearCachedData();
}
CachedData cachedData = s_cachedData;
- if (dateTime.Kind == DateTimeKind.Utc) {
- return ConvertTime(dateTime, s_utcTimeZone, destinationTimeZone, TimeZoneInfoOptions.None, cachedData);
- }
- else {
- return ConvertTime(dateTime, cachedData.Local, destinationTimeZone, TimeZoneInfoOptions.None, cachedData);
- }
- }
-
- static public DateTime ConvertTime(DateTime dateTime, TimeZoneInfo sourceTimeZone, TimeZoneInfo destinationTimeZone) {
- return ConvertTime(dateTime, sourceTimeZone, destinationTimeZone, TimeZoneInfoOptions.None, s_cachedData);
+ TimeZoneInfo sourceTimeZone = dateTime.Kind == DateTimeKind.Utc ? s_utcTimeZone : cachedData.Local;
+ return ConvertTime(dateTime, sourceTimeZone, destinationTimeZone, TimeZoneInfoOptions.None, cachedData);
}
+ /// <summary>
+ /// Converts the value of the dateTime object from sourceTimeZone to destinationTimeZone
+ /// </summary>
+ public static DateTime ConvertTime(DateTime dateTime, TimeZoneInfo sourceTimeZone, TimeZoneInfo destinationTimeZone) =>
+ ConvertTime(dateTime, sourceTimeZone, destinationTimeZone, TimeZoneInfoOptions.None, s_cachedData);
- static internal DateTime ConvertTime(DateTime dateTime, TimeZoneInfo sourceTimeZone, TimeZoneInfo destinationTimeZone, TimeZoneInfoOptions flags) {
- return ConvertTime(dateTime, sourceTimeZone, destinationTimeZone, flags, s_cachedData);
- }
+ /// <summary>
+ /// Converts the value of the dateTime object from sourceTimeZone to destinationTimeZone
+ /// </summary>
+ internal static DateTime ConvertTime(DateTime dateTime, TimeZoneInfo sourceTimeZone, TimeZoneInfo destinationTimeZone, TimeZoneInfoOptions flags) =>
+ ConvertTime(dateTime, sourceTimeZone, destinationTimeZone, flags, s_cachedData);
- static private DateTime ConvertTime(DateTime dateTime, TimeZoneInfo sourceTimeZone, TimeZoneInfo destinationTimeZone, TimeZoneInfoOptions flags, CachedData cachedData) {
- if (sourceTimeZone == null) {
+ private static DateTime ConvertTime(DateTime dateTime, TimeZoneInfo sourceTimeZone, TimeZoneInfo destinationTimeZone, TimeZoneInfoOptions flags, CachedData cachedData)
+ {
+ if (sourceTimeZone == null)
+ {
throw new ArgumentNullException(nameof(sourceTimeZone));
}
- if (destinationTimeZone == null) {
+ if (destinationTimeZone == null)
+ {
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"), nameof(sourceTimeZone));
+ if (((flags & TimeZoneInfoOptions.NoThrowOnInvalidTime) == 0) && (dateTime.Kind != DateTimeKind.Unspecified) && (dateTime.Kind != sourceKind))
+ {
+ throw new ArgumentException(Environment.GetResourceString("Argument_ConvertMismatch"), nameof(sourceTimeZone));
}
//
@@ -822,15 +664,18 @@ namespace System {
AdjustmentRule sourceRule = sourceTimeZone.GetAdjustmentRuleForTime(dateTime);
TimeSpan sourceOffset = sourceTimeZone.BaseUtcOffset;
- if (sourceRule != null) {
+ if (sourceRule != null)
+ {
sourceOffset = sourceOffset + sourceRule.BaseUtcOffsetDelta;
- if (sourceRule.HasDaylightSaving) {
- Boolean sourceIsDaylightSavings = false;
+ if (sourceRule.HasDaylightSaving)
+ {
+ bool sourceIsDaylightSavings = false;
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)) {
+ // period that supports DST
+ if (((flags & TimeZoneInfoOptions.NoThrowOnInvalidTime) == 0) && GetIsInvalidTime(dateTime, sourceRule, sourceDaylightTime))
+ {
throw new ArgumentException(Environment.GetResourceString("Argument_DateTimeIsInvalid"), nameof(dateTime));
}
sourceIsDaylightSavings = GetIsDaylightSavings(dateTime, sourceRule, sourceDaylightTime, flags);
@@ -843,91 +688,86 @@ namespace System {
DateTimeKind targetKind = cachedData.GetCorrespondingKind(destinationTimeZone);
// handle the special case of Loss-less Local->Local and UTC->UTC)
- if (dateTime.Kind != DateTimeKind.Unspecified && sourceKind != DateTimeKind.Unspecified
- && sourceKind == targetKind) {
+ if (dateTime.Kind != DateTimeKind.Unspecified && sourceKind != DateTimeKind.Unspecified && sourceKind == targetKind)
+ {
return dateTime;
}
- Int64 utcTicks = dateTime.Ticks - sourceOffset.Ticks;
+ long utcTicks = dateTime.Ticks - sourceOffset.Ticks;
// handle the normal case by converting from 'source' to UTC and then to 'target'
- Boolean isAmbiguousLocalDst = false;
+ bool isAmbiguousLocalDst;
DateTime targetConverted = ConvertUtcToTimeZone(utcTicks, destinationTimeZone, out isAmbiguousLocalDst);
-
- if (targetKind == DateTimeKind.Local) {
- // Because the ticks conversion between UTC and local is lossy, we need to capture whether the
+
+ if (targetKind == DateTimeKind.Local)
+ {
+ // Because the ticks conversion between UTC and local is lossy, we need to capture whether the
// time is in a repeated hour so that it can be passed to the DateTime constructor.
- return new DateTime(targetConverted.Ticks, DateTimeKind.Local, isAmbiguousLocalDst);
+ return new DateTime(targetConverted.Ticks, DateTimeKind.Local, isAmbiguousLocalDst);
}
- else {
+ else
+ {
return new DateTime(targetConverted.Ticks, targetKind);
}
}
+ /// <summary>
+ /// Converts the value of a DateTime object from Coordinated Universal Time (UTC) to the destinationTimeZone.
+ /// </summary>
+ public static DateTime ConvertTimeFromUtc(DateTime dateTime, TimeZoneInfo destinationTimeZone) =>
+ ConvertTime(dateTime, s_utcTimeZone, destinationTimeZone, TimeZoneInfoOptions.None, s_cachedData);
-
- //
- // ConvertTimeFromUtc -
- //
- // Converts the value of a DateTime object from Coordinated Universal Time (UTC) to
- // the destinationTimeZone.
- //
- static public DateTime ConvertTimeFromUtc(DateTime dateTime, TimeZoneInfo destinationTimeZone) {
- CachedData cachedData = s_cachedData;
- return ConvertTime(dateTime, s_utcTimeZone, destinationTimeZone, TimeZoneInfoOptions.None, cachedData);
- }
-
-
- //
- // ConvertTimeToUtc -
- //
- // Converts the value of a DateTime object to Coordinated Universal Time (UTC).
- //
- static public DateTime ConvertTimeToUtc(DateTime dateTime) {
- if (dateTime.Kind == DateTimeKind.Utc) {
+ /// <summary>
+ /// Converts the value of a DateTime object to Coordinated Universal Time (UTC).
+ /// </summary>
+ public static DateTime ConvertTimeToUtc(DateTime dateTime)
+ {
+ if (dateTime.Kind == DateTimeKind.Utc)
+ {
return dateTime;
}
CachedData cachedData = s_cachedData;
return ConvertTime(dateTime, cachedData.Local, s_utcTimeZone, TimeZoneInfoOptions.None, cachedData);
}
-
- static internal DateTime ConvertTimeToUtc(DateTime dateTime, TimeZoneInfoOptions flags) {
- if (dateTime.Kind == DateTimeKind.Utc) {
+ /// <summary>
+ /// Converts the value of a DateTime object to Coordinated Universal Time (UTC).
+ /// </summary>
+ internal static DateTime ConvertTimeToUtc(DateTime dateTime, TimeZoneInfoOptions flags)
+ {
+ if (dateTime.Kind == DateTimeKind.Utc)
+ {
return dateTime;
}
CachedData cachedData = s_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, s_utcTimeZone, TimeZoneInfoOptions.None, cachedData);
- }
-
+ /// <summary>
+ /// Converts the value of a DateTime object to Coordinated Universal Time (UTC).
+ /// </summary>
+ public static DateTime ConvertTimeToUtc(DateTime dateTime, TimeZoneInfo sourceTimeZone) =>
+ ConvertTime(dateTime, sourceTimeZone, s_utcTimeZone, TimeZoneInfoOptions.None, s_cachedData);
- //
- // IEquatable.Equals -
- //
- // returns value equality. Equals does not compare any localizable
- // String objects (DisplayName, StandardName, DaylightName).
- //
- public bool Equals(TimeZoneInfo other) {
- return (other != null && String.Compare(this.m_id, other.m_id, StringComparison.OrdinalIgnoreCase) == 0 && HasSameRules(other));
- }
+ /// <summary>
+ /// Returns value equality. Equals does not compare any localizable
+ /// String objects (DisplayName, StandardName, DaylightName).
+ /// </summary>
+ public bool Equals(TimeZoneInfo other) =>
+ other != null &&
+ string.Equals(_id, other._id, StringComparison.OrdinalIgnoreCase) &&
+ HasSameRules(other);
- public override bool Equals(object obj) {
- return Equals(obj as TimeZoneInfo);
- }
+ public override bool Equals(object obj) => Equals(obj as TimeZoneInfo);
- //
- // FromSerializedString -
- //
- static public TimeZoneInfo FromSerializedString(string source) {
- if (source == null) {
+ public static TimeZoneInfo FromSerializedString(string source)
+ {
+ if (source == null)
+ {
throw new ArgumentNullException(nameof(source));
}
- if (source.Length == 0) {
+ if (source.Length == 0)
+ {
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidSerializedString", source), nameof(source));
}
Contract.EndContractBlock();
@@ -935,42 +775,33 @@ namespace System {
return StringSerializer.GetDeserializedTimeZoneInfo(source);
}
+ public override int GetHashCode() => StringComparer.OrdinalIgnoreCase.GetHashCode(_id);
- //
- // GetHashCode -
- //
- public override int GetHashCode() {
- return StringComparer.OrdinalIgnoreCase.GetHashCode(m_id);
- }
-
- //
- // GetSystemTimeZones -
- //
- // returns a ReadOnlyCollection<TimeZoneInfo> containing all valid TimeZone's
- // from the local machine. The entries in the collection are sorted by
- // 'DisplayName'.
- //
- // This method does *not* throw TimeZoneNotFoundException or
- // InvalidTimeZoneException.
- //
- // <SecurityKernel Critical="True" Ring="0">
- // <Asserts Name="Imperative: System.Security.PermissionSet" />
- // </SecurityKernel>
- static public ReadOnlyCollection<TimeZoneInfo> GetSystemTimeZones() {
-
+ /// <summary>
+ /// Returns a ReadOnlyCollection<TimeZoneInfo> containing all valid TimeZone's
+ /// from the local machine. The entries in the collection are sorted by
+ /// <see cref="DisplayName"/>.
+ /// This method does *not* throw TimeZoneNotFoundException or InvalidTimeZoneException.
+ /// </summary>
+ public static ReadOnlyCollection<TimeZoneInfo> GetSystemTimeZones()
+ {
CachedData cachedData = s_cachedData;
- lock (cachedData) {
- if (cachedData.m_readOnlySystemTimeZones == null) {
+ lock (cachedData)
+ {
+ if (cachedData._readOnlySystemTimeZones == null)
+ {
PopulateAllSystemTimeZones(cachedData);
- cachedData.m_allSystemTimeZonesRead = true;
+ cachedData._allSystemTimeZonesRead = true;
List<TimeZoneInfo> list;
- if (cachedData.m_systemTimeZones != null) {
+ if (cachedData._systemTimeZones != null)
+ {
// return a collection of the cached system time zones
- list = new List<TimeZoneInfo>(cachedData.m_systemTimeZones.Values);
+ list = new List<TimeZoneInfo>(cachedData._systemTimeZones.Values);
}
- else {
+ else
+ {
// return an empty collection
list = new List<TimeZoneInfo>();
}
@@ -983,111 +814,79 @@ namespace System {
return comparison == 0 ? string.CompareOrdinal(x.DisplayName, y.DisplayName) : comparison;
});
- cachedData.m_readOnlySystemTimeZones = new ReadOnlyCollection<TimeZoneInfo>(list);
- }
+ cachedData._readOnlySystemTimeZones = new ReadOnlyCollection<TimeZoneInfo>(list);
+ }
}
- return cachedData.m_readOnlySystemTimeZones;
+ return cachedData._readOnlySystemTimeZones;
}
- private static void PopulateAllSystemTimeZones(CachedData cachedData)
+ /// <summary>
+ /// Value equality on the "adjustmentRules" array
+ /// </summary>
+ public bool HasSameRules(TimeZoneInfo other)
{
-#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, 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
- }
- }
- }
-#elif PLATFORM_UNIX // FEATURE_WIN32_REGISTRY
- string timeZoneDirectory = GetTimeZoneDirectory();
- foreach (string timeZoneId in GetTimeZoneIds(timeZoneDirectory))
+ if (other == null)
{
- TimeZoneInfo value;
- Exception ex;
- TryGetTimeZone(timeZoneId, false, out value, out ex, cachedData); // populate the cache
- }
-#endif // FEATURE_WIN32_REGISTRY
- }
-
- //
- // HasSameRules -
- //
- // Value equality on the "adjustmentRules" array
- //
- public Boolean HasSameRules(TimeZoneInfo other) {
- if (other == null) {
throw new ArgumentNullException(nameof(other));
}
-
- // check the utcOffset and supportsDaylightSavingTime members
Contract.EndContractBlock();
- if (this.m_baseUtcOffset != other.m_baseUtcOffset
- || this.m_supportsDaylightSavingTime != other.m_supportsDaylightSavingTime) {
+ // check the utcOffset and supportsDaylightSavingTime members
+ if (_baseUtcOffset != other._baseUtcOffset ||
+ _supportsDaylightSavingTime != other._supportsDaylightSavingTime)
+ {
return false;
}
bool sameRules;
- AdjustmentRule[] currentRules = this.m_adjustmentRules;
- AdjustmentRule[] otherRules = other.m_adjustmentRules;
+ AdjustmentRule[] currentRules = _adjustmentRules;
+ AdjustmentRule[] otherRules = other._adjustmentRules;
- sameRules = (currentRules == null && otherRules == null)
- ||(currentRules != null && otherRules != null);
+ sameRules =
+ (currentRules == null && otherRules == null) ||
+ (currentRules != null && otherRules != null);
- if (!sameRules) {
+ if (!sameRules)
+ {
// AdjustmentRule array mismatch
return false;
}
- if (currentRules != null) {
- if (currentRules.Length != otherRules.Length) {
+ if (currentRules != null)
+ {
+ if (currentRules.Length != otherRules.Length)
+ {
// AdjustmentRule array length mismatch
return false;
}
- for(int i = 0; i < currentRules.Length; i++) {
- if (!(currentRules[i]).Equals(otherRules[i])) {
+ for (int i = 0; i < currentRules.Length; i++)
+ {
+ if (!(currentRules[i]).Equals(otherRules[i]))
+ {
// AdjustmentRule value-equality mismatch
return false;
}
}
}
- return sameRules;
- }
-
- //
- // Local -
- //
- // returns a TimeZoneInfo instance that represents the local time on the machine.
- // Accessing this property may throw InvalidTimeZoneException or COMException
- // if the machine is in an unstable or corrupt state.
- //
- static public TimeZoneInfo Local {
- get {
- Contract.Ensures(Contract.Result<TimeZoneInfo>() != null);
- return s_cachedData.Local;
- }
+ return sameRules;
}
+ /// <summary>
+ /// Returns a TimeZoneInfo instance that represents the local time on the machine.
+ /// Accessing this property may throw InvalidTimeZoneException or COMException
+ /// if the machine is in an unstable or corrupt state.
+ /// </summary>
+ public static TimeZoneInfo Local => s_cachedData.Local;
//
// ToSerializedString -
//
// "TimeZoneInfo" := TimeZoneInfo Data;[AdjustmentRule Data 1];...;[AdjustmentRule Data N]
//
- // "TimeZoneInfo Data" := <m_id>;<m_baseUtcOffset>;<m_displayName>;
- // <m_standardDisplayName>;<m_daylightDispayName>;
+ // "TimeZoneInfo Data" := <_id>;<_baseUtcOffset>;<_displayName>;
+ // <_standardDisplayName>;<_daylightDispayName>;
//
// "AdjustmentRule Data" := <DateStart>;<DateEnd>;<DaylightDelta>;
// [TransitionTime Data DST Start]
@@ -1095,322 +894,166 @@ namespace System {
//
// "TransitionTime Data" += <DaylightStartTimeOfDat>;<Month>;<Week>;<DayOfWeek>;<Day>
//
- public String ToSerializedString() {
- return StringSerializer.GetSerializedString(this);
- }
-
-
- //
- // ToString -
- //
- // returns the DisplayName:
- // "(GMT-08:00) Pacific Time (US & Canada); Tijuana"
- //
- public override string ToString() {
- return this.DisplayName;
- }
-
-
- //
- // Utc -
- //
- // returns a TimeZoneInfo instance that represents Universal Coordinated Time (UTC)
- //
- static public TimeZoneInfo Utc {
- get {
- Contract.Ensures(Contract.Result<TimeZoneInfo>() != null);
- return s_utcTimeZone;
- }
- }
-
-
- // -------- SECTION: constructors -----------------*
- //
- // TimeZoneInfo -
- //
- // private ctor
- //
-#if FEATURE_WIN32_REGISTRY
- private TimeZoneInfo(Win32Native.TimeZoneInformation zone, Boolean dstDisabled) {
-
- if (String.IsNullOrEmpty(zone.StandardName)) {
- m_id = c_localId; // the ID must contain at least 1 character - initialize m_id to "Local"
- }
- else {
- m_id = zone.StandardName;
- }
- m_baseUtcOffset = new TimeSpan(0, -(zone.Bias), 0);
-
- if (!dstDisabled) {
- // only create the adjustment rule if DST is enabled
- Win32Native.RegistryTimeZoneInformation regZone = new Win32Native.RegistryTimeZoneInformation(zone);
- AdjustmentRule rule = CreateAdjustmentRuleFromTimeZoneInformation(regZone, DateTime.MinValue.Date, DateTime.MaxValue.Date, zone.Bias);
- if (rule != null) {
- m_adjustmentRules = new AdjustmentRule[1];
- m_adjustmentRules[0] = rule;
- }
- }
-
- ValidateTimeZoneInfo(m_id, m_baseUtcOffset, m_adjustmentRules, out m_supportsDaylightSavingTime);
- m_displayName = zone.StandardName;
- m_standardDisplayName = zone.StandardName;
- m_daylightDisplayName = zone.DaylightName;
- }
-#endif // FEATURE_WIN32_REGISTRY
-
-#if PLATFORM_UNIX
- private TimeZoneInfo(byte[] data, string id, Boolean dstDisabled)
- {
- TZifHead t;
- DateTime[] dts;
- Byte[] typeOfLocalTime;
- TZifType[] transitionType;
- String zoneAbbreviations;
- Boolean[] StandardTime;
- Boolean[] GmtTime;
- string futureTransitionsPosixFormat;
-
- // parse the raw TZif bytes; this method can throw ArgumentException when the data is malformed.
- TZif_ParseRaw(data, out t, out dts, out typeOfLocalTime, out transitionType, out zoneAbbreviations, out StandardTime, out GmtTime, out futureTransitionsPosixFormat);
-
- m_id = id;
- m_displayName = c_localId;
- m_baseUtcOffset = TimeSpan.Zero;
-
- // find the best matching baseUtcOffset and display strings based on the current utcNow value.
- // NOTE: read the display strings from the the tzfile now in case they can't be loaded later
- // from the globalization data.
- DateTime utcNow = DateTime.UtcNow;
- for (int i = 0; i < dts.Length && dts[i] <= utcNow; i++) {
- int type = typeOfLocalTime[i];
- if (!transitionType[type].IsDst) {
- m_baseUtcOffset = transitionType[type].UtcOffset;
- m_standardDisplayName = TZif_GetZoneAbbreviation(zoneAbbreviations, transitionType[type].AbbreviationIndex);
- }
- else {
- m_daylightDisplayName = TZif_GetZoneAbbreviation(zoneAbbreviations, transitionType[type].AbbreviationIndex);
- }
- }
-
- if (dts.Length == 0) {
- // time zones like Africa/Bujumbura and Etc/GMT* have no transition times but still contain
- // TZifType entries that may contain a baseUtcOffset and display strings
- for (int i = 0; i < transitionType.Length; i++) {
- if (!transitionType[i].IsDst) {
- m_baseUtcOffset = transitionType[i].UtcOffset;
- m_standardDisplayName = TZif_GetZoneAbbreviation(zoneAbbreviations, transitionType[i].AbbreviationIndex);
- }
- else {
- m_daylightDisplayName = TZif_GetZoneAbbreviation(zoneAbbreviations, transitionType[i].AbbreviationIndex);
- }
- }
- }
- m_displayName = m_standardDisplayName;
-
- GetDisplayName(Interop.GlobalizationInterop.TimeZoneDisplayNameType.Generic, ref m_displayName);
- GetDisplayName(Interop.GlobalizationInterop.TimeZoneDisplayNameType.Standard, ref m_standardDisplayName);
- GetDisplayName(Interop.GlobalizationInterop.TimeZoneDisplayNameType.DaylightSavings, ref m_daylightDisplayName);
-
- // TZif supports seconds-level granularity with offsets but TimeZoneInfo only supports minutes since it aligns
- // with DateTimeOffset, SQL Server, and the W3C XML Specification
- if (m_baseUtcOffset.Ticks % TimeSpan.TicksPerMinute != 0) {
- m_baseUtcOffset = new TimeSpan(m_baseUtcOffset.Hours, m_baseUtcOffset.Minutes, 0);
- }
-
- if (!dstDisabled) {
- // only create the adjustment rule if DST is enabled
- TZif_GenerateAdjustmentRules(out m_adjustmentRules, m_baseUtcOffset, dts, typeOfLocalTime, transitionType, StandardTime, GmtTime, futureTransitionsPosixFormat);
- }
+ public string ToSerializedString() => StringSerializer.GetSerializedString(this);
- ValidateTimeZoneInfo(m_id, m_baseUtcOffset, m_adjustmentRules, out m_supportsDaylightSavingTime);
- }
-
- private void GetDisplayName(Interop.GlobalizationInterop.TimeZoneDisplayNameType nameType, ref string displayName)
- {
- string timeZoneDisplayName;
- bool result = Interop.CallStringMethod(
- (locale, id, type, stringBuilder) => Interop.GlobalizationInterop.GetTimeZoneDisplayName(
- locale,
- id,
- type,
- stringBuilder,
- stringBuilder.Capacity),
- CultureInfo.CurrentUICulture.Name,
- m_id,
- nameType,
- out timeZoneDisplayName);
-
- // If there is an unknown error, don't set the displayName field.
- // It will be set to the abbreviation that was read out of the tzfile.
- if (result)
- {
- displayName = timeZoneDisplayName;
- }
- }
+ /// <summary>
+ /// Returns the <see cref="DisplayName"/>: "(GMT-08:00) Pacific Time (US &amp; Canada); Tijuana"
+ /// </summary>
+ public override string ToString() => DisplayName;
-#endif // PLATFORM_UNIX
+ /// <summary>
+ /// Returns a TimeZoneInfo instance that represents Universal Coordinated Time (UTC)
+ /// </summary>
+ public static TimeZoneInfo Utc => s_utcTimeZone;
private TimeZoneInfo(
- String id,
+ string id,
TimeSpan baseUtcOffset,
- String displayName,
- String standardDisplayName,
- String daylightDisplayName,
- AdjustmentRule [] adjustmentRules,
- Boolean disableDaylightSavingTime) {
+ string displayName,
+ string standardDisplayName,
+ string daylightDisplayName,
+ AdjustmentRule[] adjustmentRules,
+ bool disableDaylightSavingTime)
+ {
- Boolean adjustmentRulesSupportDst;
+ bool adjustmentRulesSupportDst;
ValidateTimeZoneInfo(id, baseUtcOffset, adjustmentRules, out adjustmentRulesSupportDst);
- m_id = id;
- m_baseUtcOffset = baseUtcOffset;
- m_displayName = displayName;
- m_standardDisplayName = standardDisplayName;
- m_daylightDisplayName = (disableDaylightSavingTime ? null : daylightDisplayName);
- m_supportsDaylightSavingTime = adjustmentRulesSupportDst && !disableDaylightSavingTime;
- m_adjustmentRules = adjustmentRules;
+ _id = id;
+ _baseUtcOffset = baseUtcOffset;
+ _displayName = displayName;
+ _standardDisplayName = standardDisplayName;
+ _daylightDisplayName = disableDaylightSavingTime ? null : daylightDisplayName;
+ _supportsDaylightSavingTime = adjustmentRulesSupportDst && !disableDaylightSavingTime;
+ _adjustmentRules = adjustmentRules;
}
- // -------- SECTION: factory methods -----------------*
-
- //
- // CreateCustomTimeZone -
- //
- // returns a simple TimeZoneInfo instance that does
- // not support Daylight Saving Time
- //
- static public TimeZoneInfo CreateCustomTimeZone(
- String id,
- TimeSpan baseUtcOffset,
- String displayName,
- String standardDisplayName) {
-
+ /// <summary>
+ /// Returns a simple TimeZoneInfo instance that does not support Daylight Saving Time.
+ /// </summary>
+ public static TimeZoneInfo CreateCustomTimeZone(
+ string id,
+ TimeSpan baseUtcOffset,
+ string displayName,
+ string standardDisplayName)
+ {
return new TimeZoneInfo(
- id,
- baseUtcOffset,
- displayName,
- standardDisplayName,
- standardDisplayName,
- null,
- false);
+ id,
+ baseUtcOffset,
+ displayName,
+ standardDisplayName,
+ standardDisplayName,
+ adjustmentRules: null,
+ disableDaylightSavingTime: false);
}
- //
- // CreateCustomTimeZone -
- //
- // returns a TimeZoneInfo instance that may
- // support Daylight Saving Time
- //
- static public TimeZoneInfo CreateCustomTimeZone(
- String id,
- TimeSpan baseUtcOffset,
- String displayName,
- String standardDisplayName,
- String daylightDisplayName,
- AdjustmentRule [] adjustmentRules) {
-
+ /// <summary>
+ /// Returns a TimeZoneInfo instance that may support Daylight Saving Time.
+ /// </summary>
+ public static TimeZoneInfo CreateCustomTimeZone(
+ string id,
+ TimeSpan baseUtcOffset,
+ string displayName,
+ string standardDisplayName,
+ string daylightDisplayName,
+ AdjustmentRule[] adjustmentRules)
+ {
return CreateCustomTimeZone(
- id,
- baseUtcOffset,
- displayName,
- standardDisplayName,
- daylightDisplayName,
- adjustmentRules,
- false);
+ id,
+ baseUtcOffset,
+ displayName,
+ standardDisplayName,
+ daylightDisplayName,
+ adjustmentRules,
+ disableDaylightSavingTime: false);
}
-
- //
- // CreateCustomTimeZone -
- //
- // returns a TimeZoneInfo instance that may
- // support Daylight Saving Time
- //
- // This class factory method is identical to the
- // TimeZoneInfo private constructor
- //
- static public TimeZoneInfo CreateCustomTimeZone(
- String id,
- TimeSpan baseUtcOffset,
- String displayName,
- String standardDisplayName,
- String daylightDisplayName,
- AdjustmentRule [] adjustmentRules,
- Boolean disableDaylightSavingTime) {
-
- if (!disableDaylightSavingTime && adjustmentRules?.Length > 0) {
+ /// <summary>
+ /// Returns a TimeZoneInfo instance that may support Daylight Saving Time.
+ /// </summary>
+ public static TimeZoneInfo CreateCustomTimeZone(
+ string id,
+ TimeSpan baseUtcOffset,
+ string displayName,
+ string standardDisplayName,
+ string daylightDisplayName,
+ AdjustmentRule[] adjustmentRules,
+ bool disableDaylightSavingTime)
+ {
+ if (!disableDaylightSavingTime && adjustmentRules?.Length > 0)
+ {
adjustmentRules = (AdjustmentRule[])adjustmentRules.Clone();
}
return new TimeZoneInfo(
- id,
- baseUtcOffset,
- displayName,
- standardDisplayName,
- daylightDisplayName,
- adjustmentRules,
- disableDaylightSavingTime);
+ id,
+ baseUtcOffset,
+ displayName,
+ standardDisplayName,
+ daylightDisplayName,
+ adjustmentRules,
+ disableDaylightSavingTime);
}
+ void IDeserializationCallback.OnDeserialization(object sender)
+ {
+ try
+ {
+ bool adjustmentRulesSupportDst;
+ ValidateTimeZoneInfo(_id, _baseUtcOffset, _adjustmentRules, out adjustmentRulesSupportDst);
-
- // ----- SECTION: private serialization instance methods ----------------*
-
- void IDeserializationCallback.OnDeserialization(Object sender) {
- try {
- Boolean adjustmentRulesSupportDst;
- ValidateTimeZoneInfo(m_id, m_baseUtcOffset, m_adjustmentRules, out adjustmentRulesSupportDst);
-
- if (adjustmentRulesSupportDst != m_supportsDaylightSavingTime) {
+ if (adjustmentRulesSupportDst != _supportsDaylightSavingTime)
+ {
throw new SerializationException(Environment.GetResourceString("Serialization_CorruptField", "SupportsDaylightSavingTime"));
}
}
- catch (ArgumentException e) {
+ catch (ArgumentException e)
+ {
throw new SerializationException(Environment.GetResourceString("Serialization_InvalidData"), e);
}
- catch (InvalidTimeZoneException e) {
+ catch (InvalidTimeZoneException e)
+ {
throw new SerializationException(Environment.GetResourceString("Serialization_InvalidData"), e);
}
}
-
- void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context) {
- if (info == null) {
+ void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
+ {
+ if (info == null)
+ {
throw new ArgumentNullException(nameof(info));
}
Contract.EndContractBlock();
- info.AddValue("Id", m_id);
- info.AddValue("DisplayName", m_displayName);
- info.AddValue("StandardName", m_standardDisplayName);
- info.AddValue("DaylightName", m_daylightDisplayName);
- info.AddValue("BaseUtcOffset", m_baseUtcOffset);
- info.AddValue("AdjustmentRules", m_adjustmentRules);
- info.AddValue("SupportsDaylightSavingTime", m_supportsDaylightSavingTime);
+ info.AddValue("Id", _id);
+ info.AddValue("DisplayName", _displayName);
+ info.AddValue("StandardName", _standardDisplayName);
+ info.AddValue("DaylightName", _daylightDisplayName);
+ info.AddValue("BaseUtcOffset", _baseUtcOffset);
+ info.AddValue("AdjustmentRules", _adjustmentRules);
+ info.AddValue("SupportsDaylightSavingTime", _supportsDaylightSavingTime);
}
-
- TimeZoneInfo(SerializationInfo info, StreamingContext context) {
- if (info == null) {
+ TimeZoneInfo(SerializationInfo info, StreamingContext context)
+ {
+ if (info == null)
+ {
throw new ArgumentNullException(nameof(info));
}
- m_id = (String)info.GetValue("Id", typeof(String));
- m_displayName = (String)info.GetValue("DisplayName", typeof(String));
- m_standardDisplayName = (String)info.GetValue("StandardName", typeof(String));
- m_daylightDisplayName = (String)info.GetValue("DaylightName", typeof(String));
- m_baseUtcOffset = (TimeSpan)info.GetValue("BaseUtcOffset", typeof(TimeSpan));
- m_adjustmentRules = (AdjustmentRule[])info.GetValue("AdjustmentRules", typeof(AdjustmentRule[]));
- m_supportsDaylightSavingTime = (Boolean)info.GetValue("SupportsDaylightSavingTime", typeof(Boolean));
+ _id = (string)info.GetValue("Id", typeof(string));
+ _displayName = (string)info.GetValue("DisplayName", typeof(string));
+ _standardDisplayName = (string)info.GetValue("StandardName", typeof(string));
+ _daylightDisplayName = (string)info.GetValue("DaylightName", typeof(string));
+ _baseUtcOffset = (TimeSpan)info.GetValue("BaseUtcOffset", typeof(TimeSpan));
+ _adjustmentRules = (AdjustmentRule[])info.GetValue("AdjustmentRules", typeof(AdjustmentRule[]));
+ _supportsDaylightSavingTime = (bool)info.GetValue("SupportsDaylightSavingTime", typeof(bool));
}
-
-
- // ----- SECTION: internal instance utility methods ----------------*
-
-
- private AdjustmentRule GetAdjustmentRuleForTime(DateTime dateTime, bool dateTimeisUtc = false) {
- if (m_adjustmentRules == null || m_adjustmentRules.Length == 0) {
+ private AdjustmentRule GetAdjustmentRuleForTime(DateTime dateTime, bool dateTimeisUtc = false)
+ {
+ if (_adjustmentRules == null || _adjustmentRules.Length == 0)
+ {
return null;
}
@@ -1418,20 +1061,16 @@ namespace System {
// This is because the AdjustmentRule DateStart & DateEnd are stored as
// Date-only values {4/2/2006 - 10/28/2006} but actually represent the
// time span {4/2/2006@00:00:00.00000 - 10/28/2006@23:59:59.99999}
- DateTime date;
- if (dateTimeisUtc)
- {
- date = (dateTime + BaseUtcOffset).Date;
- }
- else
- {
- date = dateTime.Date;
- }
+ DateTime date = dateTimeisUtc ?
+ (dateTime + BaseUtcOffset).Date :
+ dateTime.Date;
- for (int i = 0; i < m_adjustmentRules.Length; i++) {
- AdjustmentRule rule = m_adjustmentRules[i];
- AdjustmentRule previousRule = i > 0 ? m_adjustmentRules[i - 1] : rule;
- if (IsAdjustmentRuleValid(rule, previousRule, dateTime, date, dateTimeisUtc)) {
+ for (int i = 0; i < _adjustmentRules.Length; i++)
+ {
+ AdjustmentRule rule = _adjustmentRules[i];
+ AdjustmentRule previousRule = i > 0 ? _adjustmentRules[i - 1] : rule;
+ if (IsAdjustmentRuleValid(rule, previousRule, dateTime, date, dateTimeisUtc))
+ {
return rule;
}
}
@@ -1448,18 +1087,11 @@ namespace System {
bool isAfterStart;
if (rule.DateStart.Kind == DateTimeKind.Utc)
{
- DateTime dateTimeToCompare;
- if (dateTimeisUtc)
- {
- dateTimeToCompare = dateTime;
- }
- else
- {
- dateTimeToCompare = ConvertToUtc(dateTime,
- // use the previous rule to compute the dateTimeToCompare, since the time daylight savings "switches"
- // is based on the previous rule's offset
- previousRule.DaylightDelta, previousRule.BaseUtcOffsetDelta);
- }
+ DateTime dateTimeToCompare = dateTimeisUtc ?
+ dateTime :
+ // use the previous rule to compute the dateTimeToCompare, since the time daylight savings "switches"
+ // is based on the previous rule's offset
+ ConvertToUtc(dateTime, previousRule.DaylightDelta, previousRule.BaseUtcOffsetDelta);
isAfterStart = dateTimeToCompare >= rule.DateStart;
}
@@ -1477,15 +1109,9 @@ namespace System {
bool isBeforeEnd;
if (rule.DateEnd.Kind == DateTimeKind.Utc)
{
- DateTime dateTimeToCompare;
- if (dateTimeisUtc)
- {
- dateTimeToCompare = dateTime;
- }
- else
- {
- dateTimeToCompare = ConvertToUtc(dateTime, rule.DaylightDelta, rule.BaseUtcOffsetDelta);
- }
+ DateTime dateTimeToCompare = dateTimeisUtc ?
+ dateTime :
+ ConvertToUtc(dateTime, rule.DaylightDelta, rule.BaseUtcOffsetDelta);
isBeforeEnd = dateTimeToCompare <= rule.DateEnd;
}
@@ -1501,18 +1127,14 @@ namespace System {
/// <summary>
/// Converts the dateTime to UTC using the specified deltas.
/// </summary>
- private DateTime ConvertToUtc(DateTime dateTime, TimeSpan daylightDelta, TimeSpan baseUtcOffsetDelta)
- {
- return ConvertToFromUtc(dateTime, daylightDelta, baseUtcOffsetDelta, convertToUtc: true);
- }
+ private DateTime ConvertToUtc(DateTime dateTime, TimeSpan daylightDelta, TimeSpan baseUtcOffsetDelta) =>
+ ConvertToFromUtc(dateTime, daylightDelta, baseUtcOffsetDelta, convertToUtc: true);
/// <summary>
/// Converts the dateTime from UTC using the specified deltas.
/// </summary>
- private DateTime ConvertFromUtc(DateTime dateTime, TimeSpan daylightDelta, TimeSpan baseUtcOffsetDelta)
- {
- return ConvertToFromUtc(dateTime, daylightDelta, baseUtcOffsetDelta, convertToUtc: false);
- }
+ private DateTime ConvertFromUtc(DateTime dateTime, TimeSpan daylightDelta, TimeSpan baseUtcOffsetDelta) =>
+ ConvertToFromUtc(dateTime, daylightDelta, baseUtcOffsetDelta, convertToUtc: false);
/// <summary>
/// Converts the dateTime to or from UTC using the specified deltas.
@@ -1527,184 +1149,40 @@ namespace System {
long ticks = dateTime.Ticks + offset.Ticks;
- DateTime result;
- if (ticks > DateTime.MaxValue.Ticks)
- {
- result = DateTime.MaxValue;
- }
- else if (ticks < DateTime.MinValue.Ticks)
- {
- result = DateTime.MinValue;
- }
- else
- {
- result = new DateTime(ticks);
- }
-
- return result;
- }
-
- // ----- SECTION: internal static utility methods ----------------*
-
- //
- // CheckDaylightSavingTimeNotSupported -
- //
- // Helper function to check if the current TimeZoneInformation struct does not support DST. This
- // check returns true when the DaylightDate == StandardDate
- //
- // This check is only meant to be used for "Local".
- //
- static private Boolean CheckDaylightSavingTimeNotSupported(Win32Native.TimeZoneInformation timeZone) {
- return ( timeZone.DaylightDate.Year == timeZone.StandardDate.Year
- && timeZone.DaylightDate.Month == timeZone.StandardDate.Month
- && timeZone.DaylightDate.DayOfWeek == timeZone.StandardDate.DayOfWeek
- && timeZone.DaylightDate.Day == timeZone.StandardDate.Day
- && timeZone.DaylightDate.Hour == timeZone.StandardDate.Hour
- && timeZone.DaylightDate.Minute == timeZone.StandardDate.Minute
- && timeZone.DaylightDate.Second == timeZone.StandardDate.Second
- && timeZone.DaylightDate.Milliseconds == timeZone.StandardDate.Milliseconds);
+ return
+ ticks > DateTime.MaxValue.Ticks ? DateTime.MaxValue :
+ ticks < DateTime.MinValue.Ticks ? DateTime.MinValue :
+ new DateTime(ticks);
}
-
- //
- // ConvertUtcToTimeZone -
- //
- // Helper function that converts a dateTime from UTC into the destinationTimeZone
- //
- // * returns DateTime.MaxValue when the converted value is too large
- // * returns DateTime.MinValue when the converted value is too small
- //
- static private DateTime ConvertUtcToTimeZone(Int64 ticks, TimeZoneInfo destinationTimeZone, out Boolean isAmbiguousLocalDst) {
- DateTime utcConverted;
- DateTime localConverted;
-
- // utcConverted is used to calculate the UTC offset in the destinationTimeZone
- if (ticks > DateTime.MaxValue.Ticks) {
- utcConverted = DateTime.MaxValue;
- }
- else if (ticks < DateTime.MinValue.Ticks) {
- utcConverted = DateTime.MinValue;
- }
- else {
- utcConverted = new DateTime(ticks);
- }
+ /// <summary>
+ /// Helper function that converts a dateTime from UTC into the destinationTimeZone
+ /// - Returns DateTime.MaxValue when the converted value is too large.
+ /// - Returns DateTime.MinValue when the converted value is too small.
+ /// </summary>
+ private static DateTime ConvertUtcToTimeZone(long ticks, TimeZoneInfo destinationTimeZone, out bool isAmbiguousLocalDst)
+ {
+ // used to calculate the UTC offset in the destinationTimeZone
+ DateTime utcConverted =
+ ticks > DateTime.MaxValue.Ticks ? DateTime.MaxValue :
+ ticks < DateTime.MinValue.Ticks ? DateTime.MinValue :
+ new DateTime(ticks);
// verify the time is between MinValue and MaxValue in the new time zone
TimeSpan offset = GetUtcOffsetFromUtc(utcConverted, destinationTimeZone, out isAmbiguousLocalDst);
ticks += offset.Ticks;
- if (ticks > DateTime.MaxValue.Ticks) {
- localConverted = DateTime.MaxValue;
- }
- else if (ticks < DateTime.MinValue.Ticks) {
- localConverted = DateTime.MinValue;
- }
- else {
- localConverted = new DateTime(ticks);
- }
- return localConverted;
+ return
+ ticks > DateTime.MaxValue.Ticks ? DateTime.MaxValue :
+ ticks < DateTime.MinValue.Ticks ? DateTime.MinValue :
+ new DateTime(ticks);
}
-#if FEATURE_WIN32_REGISTRY
- //
- // CreateAdjustmentRuleFromTimeZoneInformation-
- //
- // Converts a Win32Native.RegistryTimeZoneInformation (REG_TZI_FORMAT struct) to an AdjustmentRule
- //
- static private AdjustmentRule CreateAdjustmentRuleFromTimeZoneInformation(Win32Native.RegistryTimeZoneInformation timeZoneInformation, DateTime startDate, DateTime endDate, int defaultBaseUtcOffset) {
- AdjustmentRule rule;
- bool supportsDst = (timeZoneInformation.StandardDate.Month != 0);
-
- if (!supportsDst) {
- if (timeZoneInformation.Bias == defaultBaseUtcOffset)
- {
- // this rule will not contain any information to be used to adjust dates. just ignore it
- return null;
- }
-
- return rule = AdjustmentRule.CreateAdjustmentRule(
- startDate,
- endDate,
- TimeSpan.Zero, // no daylight saving transition
- TransitionTime.CreateFixedDateRule(DateTime.MinValue, 1, 1),
- TransitionTime.CreateFixedDateRule(DateTime.MinValue.AddMilliseconds(1), 1, 1),
- new TimeSpan(0, defaultBaseUtcOffset - timeZoneInformation.Bias, 0), // Bias delta is all what we need from this rule
- noDaylightTransitions: false);
- }
-
- //
- // Create an AdjustmentRule with TransitionTime objects
- //
- TransitionTime daylightTransitionStart;
- if (!TransitionTimeFromTimeZoneInformation(timeZoneInformation, out daylightTransitionStart, true /* start date */)) {
- return null;
- }
-
- TransitionTime daylightTransitionEnd;
- if (!TransitionTimeFromTimeZoneInformation(timeZoneInformation, out daylightTransitionEnd, false /* end date */)) {
- return null;
- }
-
- if (daylightTransitionStart.Equals(daylightTransitionEnd)) {
- // this happens when the time zone does support DST but the OS has DST disabled
- return null;
- }
-
- rule = AdjustmentRule.CreateAdjustmentRule(
- startDate,
- endDate,
- new TimeSpan(0, -timeZoneInformation.DaylightBias, 0),
- (TransitionTime)daylightTransitionStart,
- (TransitionTime)daylightTransitionEnd,
- new TimeSpan(0, defaultBaseUtcOffset - timeZoneInformation.Bias, 0),
- noDaylightTransitions: false);
-
- return rule;
- }
-
- //
- // FindIdFromTimeZoneInformation -
- //
- // Helper function that searches the registry for a time zone entry
- // that matches the TimeZoneInformation struct
- //
- static private String FindIdFromTimeZoneInformation(Win32Native.TimeZoneInformation timeZone, out Boolean dstDisabled) {
- dstDisabled = false;
-
- try {
- PermissionSet permSet = new PermissionSet(PermissionState.None);
- permSet.AddPermission(new RegistryPermission(RegistryPermissionAccess.Read, c_timeZonesRegistryHivePermissionList));
- permSet.Assert();
-
- 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))
- {
- return keyName;
- }
- }
- }
- }
- finally {
- PermissionSet.RevertAssert();
- }
- return null;
- }
-#endif // FEATURE_WIN32_REGISTRY
-
-
- //
- // GetDaylightTime -
- //
- // Helper function that returns a DaylightTime from a year and AdjustmentRule
- //
- private DaylightTimeStruct GetDaylightTime(Int32 year, AdjustmentRule rule) {
+ /// <summary>
+ /// Helper function that returns a DaylightTime from a year and AdjustmentRule.
+ /// </summary>
+ private DaylightTimeStruct GetDaylightTime(int year, AdjustmentRule rule)
+ {
TimeSpan delta = rule.DaylightDelta;
DateTime startTime;
DateTime endTime;
@@ -1728,28 +1206,35 @@ namespace System {
return new DaylightTimeStruct(startTime, endTime, delta);
}
- //
- // GetIsDaylightSavings -
- //
- // 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, DaylightTimeStruct daylightTime, TimeZoneInfoOptions flags) {
- if (rule == null) {
+ /// <summary>
+ /// 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.
+ /// </summary>
+ private static bool GetIsDaylightSavings(DateTime time, AdjustmentRule rule, DaylightTimeStruct daylightTime, TimeZoneInfoOptions flags)
+ {
+ if (rule == null)
+ {
return false;
}
DateTime startTime;
DateTime endTime;
-
- if (time.Kind == DateTimeKind.Local) {
- // startTime and endTime represent the period from either the start of DST to the end and ***includes*** the
- // potentially overlapped times
- startTime = rule.IsStartDateMarkerForBeginningOfYear() ? new DateTime(daylightTime.Start.Year, 1, 1, 0, 0, 0) : daylightTime.Start + daylightTime.Delta;
- endTime = rule.IsEndDateMarkerForEndOfYear() ? new DateTime(daylightTime.End.Year + 1, 1, 1, 0, 0, 0).AddTicks(-1) : daylightTime.End;
+
+ if (time.Kind == DateTimeKind.Local)
+ {
+ // startTime and endTime represent the period from either the start of
+ // DST to the end and ***includes*** the potentially overlapped times
+ startTime = rule.IsStartDateMarkerForBeginningOfYear() ?
+ new DateTime(daylightTime.Start.Year, 1, 1, 0, 0, 0) :
+ daylightTime.Start + daylightTime.Delta;
+
+ endTime = rule.IsEndDateMarkerForEndOfYear() ?
+ new DateTime(daylightTime.End.Year + 1, 1, 1, 0, 0, 0).AddTicks(-1) :
+ daylightTime.End;
}
- else {
- // startTime and endTime represent the period from either the start of DST to the end and
+ else
+ {
+ // startTime and endTime represent the period from either the start of DST to the end and
// ***does not include*** the potentially overlapped times
//
// -=-=-=-=-=- Pacific Standard Time -=-=-=-=-=-=-
@@ -1766,20 +1251,28 @@ namespace System {
// | <ambiguous time> | | <invalid time> |
// [======== DST ========>)
//
- Boolean invalidAtStart = rule.DaylightDelta > TimeSpan.Zero;
- startTime = rule.IsStartDateMarkerForBeginningOfYear() ? new DateTime(daylightTime.Start.Year, 1, 1, 0, 0, 0) : daylightTime.Start + (invalidAtStart ? rule.DaylightDelta : TimeSpan.Zero); /* FUTURE: - rule.StandardDelta; */
- endTime = rule.IsEndDateMarkerForEndOfYear() ? new DateTime(daylightTime.End.Year + 1, 1, 1, 0, 0, 0).AddTicks(-1) : daylightTime.End + (invalidAtStart ? -rule.DaylightDelta : TimeSpan.Zero);
+ bool invalidAtStart = rule.DaylightDelta > TimeSpan.Zero;
+
+ startTime = rule.IsStartDateMarkerForBeginningOfYear() ?
+ new DateTime(daylightTime.Start.Year, 1, 1, 0, 0, 0) :
+ daylightTime.Start + (invalidAtStart ? rule.DaylightDelta : TimeSpan.Zero); /* FUTURE: - rule.StandardDelta; */
+
+ endTime = rule.IsEndDateMarkerForEndOfYear() ?
+ new DateTime(daylightTime.End.Year + 1, 1, 1, 0, 0, 0).AddTicks(-1) :
+ daylightTime.End + (invalidAtStart ? -rule.DaylightDelta : TimeSpan.Zero);
}
- Boolean isDst = CheckIsDst(startTime, time, endTime, false, rule);
+ bool isDst = CheckIsDst(startTime, time, endTime, false, rule);
// If this date was previously converted from a UTC date and we were able to detect that the local
- // DateTime would be ambiguous, this data is stored in the DateTime to resolve this ambiguity.
- if (isDst && time.Kind == DateTimeKind.Local) {
- // For normal time zones, the ambiguous hour is the last hour of daylight saving when you wind the
+ // DateTime would be ambiguous, this data is stored in the DateTime to resolve this ambiguity.
+ if (isDst && time.Kind == DateTimeKind.Local)
+ {
+ // For normal time zones, the ambiguous hour is the last hour of daylight saving when you wind the
// clock back. It is theoretically possible to have a positive delta, (which would really be daylight
// reduction time), where you would have to wind the clock back in the begnning.
- if (GetIsAmbiguousTime(time, rule, daylightTime)) {
+ if (GetIsAmbiguousTime(time, rule, daylightTime))
+ {
isDst = time.IsAmbiguousDaylightSavingTime();
}
}
@@ -1810,110 +1303,132 @@ namespace System {
private TimeSpan GetDaylightSavingsEndOffsetFromUtc(TimeSpan baseUtcOffset, AdjustmentRule rule)
{
// NOTE: even NoDaylightTransitions rules use this logic since DST ends w.r.t. the current rule
-
return baseUtcOffset + rule.BaseUtcOffsetDelta + rule.DaylightDelta; /* FUTURE: + rule.StandardDelta; */
}
- //
- // GetIsDaylightSavingsFromUtc -
- //
- // Helper function that checks if a given dateTime is in Daylight Saving Time (DST)
- // This function assumes the dateTime is in UTC and AdjustmentRule is in a different time zone
- //
- static private Boolean GetIsDaylightSavingsFromUtc(DateTime time, Int32 Year, TimeSpan utc, AdjustmentRule rule, out Boolean isAmbiguousLocalDst, TimeZoneInfo zone) {
+ /// <summary>
+ /// Helper function that checks if a given dateTime is in Daylight Saving Time (DST).
+ /// This function assumes the dateTime is in UTC and AdjustmentRule is in a different time zone.
+ /// </summary>
+ private static bool GetIsDaylightSavingsFromUtc(DateTime time, int year, TimeSpan utc, AdjustmentRule rule, out bool isAmbiguousLocalDst, TimeZoneInfo zone)
+ {
isAmbiguousLocalDst = false;
- if (rule == null) {
+ if (rule == null)
+ {
return false;
}
-
// Get the daylight changes for the year of the specified time.
- DaylightTimeStruct 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.
+ // 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
// the unusual case of a negative daylight savings delta.
- // We need to handle the case if the current rule has daylight saving end by the end of year. If so, we need to check if next year starts with daylight saving on
+ // We need to handle the case if the current rule has daylight saving end by the end of year. If so, we need to check if next year starts with daylight saving on
// and get the actual daylight saving end time. Here is example for such case:
- // Converting the UTC datetime "12/31/2011 8:00:00 PM" to "(UTC+03:00) Moscow, St. Petersburg, Volgograd (RTZ 2)" zone.
- // In 2011 the daylight saving will go through the end of the year. If we use the end of 2011 as the daylight saving end,
- // that will fail the conversion because the UTC time +4 hours (3 hours for the zone UTC offset and 1 hour for daylight saving) will move us to the next year "1/1/2012 12:00 AM",
+ // Converting the UTC datetime "12/31/2011 8:00:00 PM" to "(UTC+03:00) Moscow, St. Petersburg, Volgograd (RTZ 2)" zone.
+ // In 2011 the daylight saving will go through the end of the year. If we use the end of 2011 as the daylight saving end,
+ // that will fail the conversion because the UTC time +4 hours (3 hours for the zone UTC offset and 1 hour for daylight saving) will move us to the next year "1/1/2012 12:00 AM",
// checking against the end of 2011 will tell we are not in daylight saving which is wrong and the conversion will be off by one hour.
// Note we handle the similar case when rule year start with daylight saving and previous year end with daylight saving.
bool ignoreYearAdjustment = false;
TimeSpan dstStartOffset = zone.GetDaylightSavingsStartOffsetFromUtc(utc, rule);
DateTime startTime;
- if (rule.IsStartDateMarkerForBeginningOfYear() && daylightTime.Start.Year > DateTime.MinValue.Year) {
+ 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()) {
+ if (previousYearRule != null && previousYearRule.IsEndDateMarkerForEndOfYear())
+ {
DaylightTimeStruct previousDaylightTime = zone.GetDaylightTime(daylightTime.Start.Year - 1, previousYearRule);
startTime = previousDaylightTime.Start - utc - previousYearRule.BaseUtcOffsetDelta;
ignoreYearAdjustment = true;
- } else {
+ }
+ else
+ {
startTime = new DateTime(daylightTime.Start.Year, 1, 1, 0, 0, 0) - dstStartOffset;
}
- } else {
+ }
+ else
+ {
startTime = daylightTime.Start - dstStartOffset;
}
TimeSpan dstEndOffset = zone.GetDaylightSavingsEndOffsetFromUtc(utc, rule);
DateTime endTime;
- if (rule.IsEndDateMarkerForEndOfYear() && daylightTime.End.Year < DateTime.MaxValue.Year) {
+ if (rule.IsEndDateMarkerForEndOfYear() && daylightTime.End.Year < DateTime.MaxValue.Year)
+ {
AdjustmentRule nextYearRule = zone.GetAdjustmentRuleForTime(new DateTime(daylightTime.End.Year + 1, 1, 1));
- if (nextYearRule != null && nextYearRule.IsStartDateMarkerForBeginningOfYear()) {
- if (nextYearRule.IsEndDateMarkerForEndOfYear()) {// next year end with daylight saving on too
+ if (nextYearRule != null && nextYearRule.IsStartDateMarkerForBeginningOfYear())
+ {
+ 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 {
+ }
+ else
+ {
DaylightTimeStruct nextdaylightTime = zone.GetDaylightTime(daylightTime.End.Year + 1, nextYearRule);
endTime = nextdaylightTime.End - utc - nextYearRule.BaseUtcOffsetDelta - nextYearRule.DaylightDelta;
}
ignoreYearAdjustment = true;
- } else {
+ }
+ else
+ {
endTime = new DateTime(daylightTime.End.Year + 1, 1, 1, 0, 0, 0).AddTicks(-1) - dstEndOffset;
}
- } else {
+ }
+ else
+ {
endTime = daylightTime.End - dstEndOffset;
}
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 = CheckIsDst(startTime, time, endTime, ignoreYearAdjustment, rule);
+ bool isDst = CheckIsDst(startTime, time, endTime, ignoreYearAdjustment, rule);
// 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 (isDst) {
+ if (isDst)
+ {
isAmbiguousLocalDst = (time >= ambiguousStart && time < ambiguousEnd);
- if (!isAmbiguousLocalDst && ambiguousStart.Year != ambiguousEnd.Year) {
+ if (!isAmbiguousLocalDst && ambiguousStart.Year != ambiguousEnd.Year)
+ {
// there exists an extreme corner case where the start or end period is on a year boundary and
// because of this the comparison above might have been performed for a year-early or a year-later
// than it should have been.
DateTime ambiguousStartModified;
DateTime ambiguousEndModified;
- try {
+ try
+ {
ambiguousStartModified = ambiguousStart.AddYears(1);
- ambiguousEndModified = ambiguousEnd.AddYears(1);
- isAmbiguousLocalDst = (time >= ambiguousStart && time < ambiguousEnd);
+ ambiguousEndModified = ambiguousEnd.AddYears(1);
+ isAmbiguousLocalDst = (time >= ambiguousStart && time < ambiguousEnd);
}
- catch (ArgumentOutOfRangeException) {}
+ catch (ArgumentOutOfRangeException) { }
- if (!isAmbiguousLocalDst) {
- try {
+ if (!isAmbiguousLocalDst)
+ {
+ try
+ {
ambiguousStartModified = ambiguousStart.AddYears(-1);
- ambiguousEndModified = ambiguousEnd.AddYears(-1);
+ ambiguousEndModified = ambiguousEnd.AddYears(-1);
isAmbiguousLocalDst = (time >= ambiguousStart && time < ambiguousEnd);
}
- catch (ArgumentOutOfRangeException) {}
+ catch (ArgumentOutOfRangeException) { }
}
}
@@ -1922,59 +1437,62 @@ namespace System {
return isDst;
}
-
- static private Boolean CheckIsDst(DateTime startTime, DateTime time, DateTime endTime, bool ignoreYearAdjustment, AdjustmentRule rule) {
- Boolean isDst;
-
+ private static bool CheckIsDst(DateTime startTime, DateTime time, DateTime endTime, bool ignoreYearAdjustment, AdjustmentRule rule)
+ {
// NoDaylightTransitions AdjustmentRules should never get their year adjusted since they adjust the offset for the
// entire time period - which may be for multiple years
- if (!ignoreYearAdjustment && !rule.NoDaylightTransitions) {
+ if (!ignoreYearAdjustment && !rule.NoDaylightTransitions)
+ {
int startTimeYear = startTime.Year;
int endTimeYear = endTime.Year;
- if (startTimeYear != endTimeYear) {
+ if (startTimeYear != endTimeYear)
+ {
endTime = endTime.AddYears(startTimeYear - endTimeYear);
}
int timeYear = time.Year;
- if (startTimeYear != timeYear) {
+ if (startTimeYear != timeYear)
+ {
time = time.AddYears(startTimeYear - timeYear);
}
}
- 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);
+ return (time < endTime || time >= startTime);
}
- else if (rule.NoDaylightTransitions) {
+ else if (rule.NoDaylightTransitions)
+ {
// In NoDaylightTransitions AdjustmentRules, the startTime is always before the endTime,
// and both the start and end times are inclusive
- isDst = (time >= startTime && time <= endTime);
+ return time >= startTime && time <= endTime;
}
- else {
+ else
+ {
// In northern hemisphere, the daylight saving time starts in the middle of the year.
- isDst = (time >= startTime && time < endTime);
+ return time >= startTime && time < endTime;
}
- return isDst;
}
-
- //
- // GetIsAmbiguousTime(DateTime dateTime, AdjustmentRule rule, DaylightTime daylightTime) -
- //
- // returns true when the dateTime falls into an ambiguous time range.
- // For example, in Pacific Standard Time on Sunday, October 29, 2006 time jumps from
- // 2AM to 1AM. This means the timeline on Sunday proceeds as follows:
- // 12AM ... [1AM ... 1:59:59AM -> 1AM ... 1:59:59AM] 2AM ... 3AM ...
- //
- // 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, DaylightTimeStruct daylightTime) {
- Boolean isAmbiguous = false;
- if (rule == null || rule.DaylightDelta == TimeSpan.Zero) {
+ /// <summary>
+ /// Returns true when the dateTime falls into an ambiguous time range.
+ ///
+ /// For example, in Pacific Standard Time on Sunday, October 29, 2006 time jumps from
+ /// 2AM to 1AM. This means the timeline on Sunday proceeds as follows:
+ /// 12AM ... [1AM ... 1:59:59AM -> 1AM ... 1:59:59AM] 2AM ... 3AM ...
+ ///
+ /// 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.
+ /// </summary>
+ private static bool GetIsAmbiguousTime(DateTime time, AdjustmentRule rule, DaylightTimeStruct daylightTime)
+ {
+ bool isAmbiguous = false;
+ if (rule == null || rule.DaylightDelta == TimeSpan.Zero)
+ {
return isAmbiguous;
}
@@ -1982,15 +1500,19 @@ namespace System {
DateTime endAmbiguousTime;
// if at DST start we transition forward in time then there is an ambiguous time range at the DST end
- if (rule.DaylightDelta > TimeSpan.Zero) {
- if (rule.IsEndDateMarkerForEndOfYear()) { // year end with daylight on so there is no ambiguous time
+ if (rule.DaylightDelta > TimeSpan.Zero)
+ {
+ if (rule.IsEndDateMarkerForEndOfYear())
+ { // year end with daylight on so there is no ambiguous time
return false;
}
startAmbiguousTime = daylightTime.End;
endAmbiguousTime = daylightTime.End - rule.DaylightDelta; /* FUTURE: + rule.StandardDelta; */
}
- else {
- if (rule.IsStartDateMarkerForBeginningOfYear()) { // year start with daylight on so there is no ambiguous time
+ else
+ {
+ if (rule.IsStartDateMarkerForBeginningOfYear())
+ { // year start with daylight on so there is no ambiguous time
return false;
}
startAmbiguousTime = daylightTime.Start;
@@ -1999,46 +1521,48 @@ namespace System {
isAmbiguous = (time >= endAmbiguousTime && time < startAmbiguousTime);
- if (!isAmbiguous && startAmbiguousTime.Year != endAmbiguousTime.Year) {
+ if (!isAmbiguous && startAmbiguousTime.Year != endAmbiguousTime.Year)
+ {
// there exists an extreme corner case where the start or end period is on a year boundary and
// because of this the comparison above might have been performed for a year-early or a year-later
// than it should have been.
DateTime startModifiedAmbiguousTime;
DateTime endModifiedAmbiguousTime;
- try {
+ try
+ {
startModifiedAmbiguousTime = startAmbiguousTime.AddYears(1);
- endModifiedAmbiguousTime = endAmbiguousTime.AddYears(1);
+ endModifiedAmbiguousTime = endAmbiguousTime.AddYears(1);
isAmbiguous = (time >= endModifiedAmbiguousTime && time < startModifiedAmbiguousTime);
}
- catch (ArgumentOutOfRangeException) {}
+ catch (ArgumentOutOfRangeException) { }
- if (!isAmbiguous) {
- try {
+ if (!isAmbiguous)
+ {
+ try
+ {
startModifiedAmbiguousTime = startAmbiguousTime.AddYears(-1);
- endModifiedAmbiguousTime = endAmbiguousTime.AddYears(-1);
+ endModifiedAmbiguousTime = endAmbiguousTime.AddYears(-1);
isAmbiguous = (time >= endModifiedAmbiguousTime && time < startModifiedAmbiguousTime);
}
- catch (ArgumentOutOfRangeException) {}
+ catch (ArgumentOutOfRangeException) { }
}
}
return isAmbiguous;
}
-
-
- //
- // GetIsInvalidTime -
- //
- // Helper function that checks if a given DateTime is in an invalid time ("time hole")
- // A "time hole" occurs at a DST transition point when time jumps forward;
- // For example, in Pacific Standard Time on Sunday, April 2, 2006 time jumps from
- // 1:59:59.9999999 to 3AM. The time range 2AM to 2:59:59.9999999AM is the "time hole".
- // 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, DaylightTimeStruct daylightTime) {
- Boolean isInvalid = false;
- if (rule == null || rule.DaylightDelta == TimeSpan.Zero) {
+ /// <summary>
+ /// Helper function that checks if a given DateTime is in an invalid time ("time hole")
+ /// A "time hole" occurs at a DST transition point when time jumps forward;
+ /// For example, in Pacific Standard Time on Sunday, April 2, 2006 time jumps from
+ /// 1:59:59.9999999 to 3AM. The time range 2AM to 2:59:59.9999999AM is the "time hole".
+ /// A "time hole" is not limited to only occurring at the start of DST, and may occur at
+ /// the end of DST as well.
+ /// </summary>
+ private static bool GetIsInvalidTime(DateTime time, AdjustmentRule rule, DaylightTimeStruct daylightTime)
+ {
+ bool isInvalid = false;
+ if (rule == null || rule.DaylightDelta == TimeSpan.Zero)
+ {
return isInvalid;
}
@@ -2046,7 +1570,8 @@ namespace System {
DateTime endInvalidTime;
// if at DST start we transition forward in time then there is an ambiguous time range at the DST end
- if (rule.DaylightDelta < TimeSpan.Zero) {
+ if (rule.DaylightDelta < TimeSpan.Zero)
+ {
// if the year ends with daylight saving on then there cannot be any time-hole's in that year.
if (rule.IsEndDateMarkerForEndOfYear())
return false;
@@ -2054,7 +1579,8 @@ namespace System {
startInvalidTime = daylightTime.End;
endInvalidTime = daylightTime.End - rule.DaylightDelta; /* FUTURE: + rule.StandardDelta; */
}
- else {
+ else
+ {
// if the year starts with daylight saving on then there cannot be any time-hole's in that year.
if (rule.IsStartDateMarkerForBeginningOfYear())
return false;
@@ -2065,646 +1591,105 @@ namespace System {
isInvalid = (time >= startInvalidTime && time < endInvalidTime);
- if (!isInvalid && startInvalidTime.Year != endInvalidTime.Year) {
+ if (!isInvalid && startInvalidTime.Year != endInvalidTime.Year)
+ {
// there exists an extreme corner case where the start or end period is on a year boundary and
// because of this the comparison above might have been performed for a year-early or a year-later
// than it should have been.
DateTime startModifiedInvalidTime;
DateTime endModifiedInvalidTime;
- try {
+ try
+ {
startModifiedInvalidTime = startInvalidTime.AddYears(1);
- endModifiedInvalidTime = endInvalidTime.AddYears(1);
+ endModifiedInvalidTime = endInvalidTime.AddYears(1);
isInvalid = (time >= startModifiedInvalidTime && time < endModifiedInvalidTime);
}
- catch (ArgumentOutOfRangeException) {}
+ catch (ArgumentOutOfRangeException) { }
- if (!isInvalid) {
- try {
+ if (!isInvalid)
+ {
+ try
+ {
startModifiedInvalidTime = startInvalidTime.AddYears(-1);
- endModifiedInvalidTime = endInvalidTime.AddYears(-1);
+ endModifiedInvalidTime = endInvalidTime.AddYears(-1);
isInvalid = (time >= startModifiedInvalidTime && time < endModifiedInvalidTime);
}
- catch (ArgumentOutOfRangeException) {}
+ catch (ArgumentOutOfRangeException) { }
}
}
return isInvalid;
}
-
-
- //
- // GetLocalTimeZone -
- //
- // Helper function for retrieving the local system time zone.
- //
- // returns a new TimeZoneInfo instance
- //
- // may throw COMException, TimeZoneNotFoundException, InvalidTimeZoneException
- //
- // assumes cachedData lock is taken
- //
-
- static private TimeZoneInfo GetLocalTimeZone(CachedData cachedData) {
-
-
-#if FEATURE_WIN32_REGISTRY
- String id = null;
-
- //
- // Try using the "kernel32!GetDynamicTimeZoneInformation" API to get the "id"
- //
- Win32Native.DynamicTimeZoneInformation dynamicTimeZoneInformation =
- new Win32Native.DynamicTimeZoneInformation();
-
- // call kernel32!GetDynamicTimeZoneInformation...
- long result = UnsafeNativeMethods.GetDynamicTimeZoneInformation(out dynamicTimeZoneInformation);
- if (result == Win32Native.TIME_ZONE_ID_INVALID) {
- // return a dummy entry
- return CreateCustomTimeZone(c_localId, TimeSpan.Zero, c_localId, c_localId);
- }
-
- Win32Native.TimeZoneInformation timeZoneInformation =
- new Win32Native.TimeZoneInformation(dynamicTimeZoneInformation);
-
- Boolean dstDisabled = dynamicTimeZoneInformation.DynamicDaylightTimeDisabled;
-
- // check to see if we can use the key name returned from the API call
- if (!String.IsNullOrEmpty(dynamicTimeZoneInformation.TimeZoneKeyName)) {
- TimeZoneInfo zone;
- Exception ex;
-
- if (TryGetTimeZone(dynamicTimeZoneInformation.TimeZoneKeyName, dstDisabled, out zone, out ex, cachedData) == TimeZoneInfoResult.Success) {
- // successfully loaded the time zone from the registry
- return zone;
- }
- }
-
- // the key name was not returned or it pointed to a bogus entry - search for the entry ourselves
- id = FindIdFromTimeZoneInformation(timeZoneInformation, out dstDisabled);
-
- if (id != null) {
- TimeZoneInfo zone;
- Exception ex;
- if (TryGetTimeZone(id, dstDisabled, out zone, out ex, cachedData) == TimeZoneInfoResult.Success) {
- // successfully loaded the time zone from the registry
- return zone;
- }
- }
-
- // We could not find the data in the registry. Fall back to using
- // the data from the Win32 API
- return GetLocalTimeZoneFromWin32Data(timeZoneInformation, dstDisabled);
-
-#elif PLATFORM_UNIX // FEATURE_WIN32_REGISTRY
- // Without Registry support, create the TimeZoneInfo from a TZ file
- return GetLocalTimeZoneFromTzFile();
-#endif // FEATURE_WIN32_REGISTRY
- }
-
-
-#if PLATFORM_UNIX
- private static TimeZoneInfoResult TryGetTimeZoneByFile(string id, out TimeZoneInfo value, out Exception e)
- {
- value = null;
- e = null;
-
- string timeZoneDirectory = GetTimeZoneDirectory();
- string timeZoneFilePath = Path.Combine(timeZoneDirectory, id);
- byte[] rawData;
- try
- {
- rawData = File.ReadAllBytes(timeZoneFilePath);
- }
- catch (UnauthorizedAccessException ex)
- {
- e = ex;
- return TimeZoneInfoResult.SecurityException;
- }
- catch (FileNotFoundException ex)
- {
- e = ex;
- return TimeZoneInfoResult.TimeZoneNotFoundException;
- }
- catch (DirectoryNotFoundException ex)
- {
- e = ex;
- return TimeZoneInfoResult.TimeZoneNotFoundException;
- }
- catch (IOException ex)
- {
- e = new InvalidTimeZoneException(Environment.GetResourceString("InvalidTimeZone_InvalidFileData", id, timeZoneFilePath), ex);
- return TimeZoneInfoResult.InvalidTimeZoneException;
- }
-
- value = GetTimeZoneFromTzData(rawData, id);
-
- if (value == null)
- {
- e = new InvalidTimeZoneException(Environment.GetResourceString("InvalidTimeZone_InvalidFileData", id, timeZoneFilePath));
- return TimeZoneInfoResult.InvalidTimeZoneException;
- }
-
- return TimeZoneInfoResult.Success;
- }
-
/// <summary>
- /// Returns a collection of TimeZone Id values from the zone.tab file in the timeZoneDirectory.
+ /// Helper function that calculates the UTC offset for a dateTime in a timeZone.
+ /// This function assumes that the dateTime is already converted into the timeZone.
/// </summary>
- /// <remarks>
- /// Lines that start with # are comments and are skipped.
- /// </remarks>
- private static IEnumerable<string> GetTimeZoneIds(string timeZoneDirectory)
+ private static TimeSpan GetUtcOffset(DateTime time, TimeZoneInfo zone, TimeZoneInfoOptions flags)
{
- string[] zoneTabFileLines = null;
- try
- {
- zoneTabFileLines = File.ReadAllLines(Path.Combine(timeZoneDirectory, c_zoneTabFileName));
- }
- catch (IOException) { }
- catch (UnauthorizedAccessException) { }
+ TimeSpan baseOffset = zone.BaseUtcOffset;
+ AdjustmentRule rule = zone.GetAdjustmentRuleForTime(time);
- List<string> timeZoneIds = new List<string>();
- if (zoneTabFileLines != null)
+ if (rule != null)
{
- foreach (string zoneTabFileLine in zoneTabFileLines)
+ baseOffset = baseOffset + rule.BaseUtcOffsetDelta;
+ if (rule.HasDaylightSaving)
{
- if (!string.IsNullOrEmpty(zoneTabFileLine) && !zoneTabFileLine.StartsWith("#"))
- {
- // the format of the line is "country-code \t coordinates \t TimeZone Id \t comments"
-
- int firstTabIndex = zoneTabFileLine.IndexOf('\t');
- if (firstTabIndex != -1)
- {
- int secondTabIndex = zoneTabFileLine.IndexOf('\t', firstTabIndex + 1);
- if (secondTabIndex != -1)
- {
- string timeZoneId;
- int startIndex = secondTabIndex + 1;
- int thirdTabIndex = zoneTabFileLine.IndexOf('\t', startIndex);
- if (thirdTabIndex != -1)
- {
- int length = thirdTabIndex - startIndex;
- timeZoneId = zoneTabFileLine.Substring(startIndex, length);
- }
- else
- {
- timeZoneId = zoneTabFileLine.Substring(startIndex);
- }
-
- if (!string.IsNullOrEmpty(timeZoneId))
- {
- timeZoneIds.Add(timeZoneId);
- }
- }
- }
- }
+ DaylightTimeStruct daylightTime = zone.GetDaylightTime(time.Year, rule);
+ bool isDaylightSavings = GetIsDaylightSavings(time, rule, daylightTime, flags);
+ baseOffset += (isDaylightSavings ? rule.DaylightDelta : TimeSpan.Zero /* FUTURE: rule.StandardDelta */);
}
}
- return timeZoneIds;
+ return baseOffset;
}
/// <summary>
- /// Gets the tzfile raw data for the current 'local' time zone using the following rules.
- /// 1. Read the TZ environment variable. If it is set, use it.
- /// 2. Look for the data in /etc/localtime.
- /// 3. Look for the data in GetTimeZoneDirectory()/localtime.
- /// 4. Use UTC if all else fails.
+ /// Helper function that calculates the UTC offset for a UTC-dateTime in a timeZone.
+ /// This function assumes that the dateTime is represented in UTC and has *not* already been converted into the timeZone.
/// </summary>
- private static bool TryGetLocalTzFile(out byte[] rawData, out string id)
+ private static TimeSpan GetUtcOffsetFromUtc(DateTime time, TimeZoneInfo zone)
{
- rawData = null;
- id = null;
- string tzVariable = GetTzEnvironmentVariable();
-
- // If the env var is null, use the localtime file
- if (tzVariable == null)
- {
- return
- TryLoadTzFile("/etc/localtime", ref rawData, ref id) ||
- TryLoadTzFile(Path.Combine(GetTimeZoneDirectory(), "localtime"), ref rawData, ref id);
- }
-
- // If it's empty, use UTC (TryGetLocalTzFile() should return false).
- if (tzVariable.Length == 0)
- {
- return false;
- }
-
- // Otherwise, use the path from the env var. If it's not absolute, make it relative
- // to the system timezone directory
- string tzFilePath;
- if (tzVariable[0] != '/')
- {
- id = tzVariable;
- tzFilePath = Path.Combine(GetTimeZoneDirectory(), tzVariable);
- }
- else
- {
- tzFilePath = tzVariable;
- }
- return TryLoadTzFile(tzFilePath, ref rawData, ref id);
- }
-
- private static string GetTzEnvironmentVariable()
- {
- string result = Environment.GetEnvironmentVariable(c_timeZoneEnvironmentVariable);
- if (!string.IsNullOrEmpty(result))
- {
- if (result[0] == ':')
- {
- // strip off the ':' prefix
- result = result.Substring(1);
- }
- }
-
- return result;
- }
-
- private static bool TryLoadTzFile(string tzFilePath, ref byte[] rawData, ref string id)
- {
- if (File.Exists(tzFilePath))
- {
- try
- {
- rawData = File.ReadAllBytes(tzFilePath);
- if (string.IsNullOrEmpty(id))
- {
- id = FindTimeZoneIdUsingReadLink(tzFilePath);
-
- if (string.IsNullOrEmpty(id))
- {
- id = FindTimeZoneId(rawData);
- }
- }
- return true;
- }
- catch (IOException) { }
- catch (SecurityException) { }
- catch (UnauthorizedAccessException) { }
- }
- return false;
+ bool isDaylightSavings;
+ return GetUtcOffsetFromUtc(time, zone, out isDaylightSavings);
}
/// <summary>
- /// Finds the time zone id by using 'readlink' on the path to see if tzFilePath is
- /// a symlink to a file
+ /// Helper function that calculates the UTC offset for a UTC-dateTime in a timeZone.
+ /// This function assumes that the dateTime is represented in UTC and has *not* already been converted into the timeZone.
/// </summary>
- private static string FindTimeZoneIdUsingReadLink(string tzFilePath)
+ private static TimeSpan GetUtcOffsetFromUtc(DateTime time, TimeZoneInfo zone, out bool isDaylightSavings)
{
- string id = null;
-
- StringBuilder symlinkPathBuilder = StringBuilderCache.Acquire(Path.MaxPath);
- bool result = Interop.GlobalizationInterop.ReadLink(tzFilePath, symlinkPathBuilder, (uint)symlinkPathBuilder.Capacity);
- if (result)
- {
- string symlinkPath = StringBuilderCache.GetStringAndRelease(symlinkPathBuilder);
- // time zone Ids have to point under the time zone directory
- string timeZoneDirectory = GetTimeZoneDirectory();
- if (symlinkPath.StartsWith(timeZoneDirectory))
- {
- id = symlinkPath.Substring(timeZoneDirectory.Length);
- }
- }
- else
- {
- StringBuilderCache.Release(symlinkPathBuilder);
- }
-
- return id;
+ bool isAmbiguousLocalDst;
+ return GetUtcOffsetFromUtc(time, zone, out isDaylightSavings, out isAmbiguousLocalDst);
}
/// <summary>
- /// Find the time zone id by searching all the tzfiles for the one that matches rawData
- /// and return its file name.
+ /// Helper function that calculates the UTC offset for a UTC-dateTime in a timeZone.
+ /// This function assumes that the dateTime is represented in UTC and has *not* already been converted into the timeZone.
/// </summary>
- private static string FindTimeZoneId(byte[] rawData)
- {
- // default to "Local" if we can't find the right tzfile
- string id = c_localId;
- string timeZoneDirectory = GetTimeZoneDirectory();
- string localtimeFilePath = Path.Combine(timeZoneDirectory, "localtime");
- string posixrulesFilePath = Path.Combine(timeZoneDirectory, "posixrules");
- byte[] buffer = new byte[rawData.Length];
-
- try
- {
- foreach (string filePath in Directory.EnumerateFiles(timeZoneDirectory, "*", SearchOption.AllDirectories))
- {
- // skip the localtime and posixrules file, since they won't give us the correct id
- if (!string.Equals(filePath, localtimeFilePath, StringComparison.OrdinalIgnoreCase)
- && !string.Equals(filePath, posixrulesFilePath, StringComparison.OrdinalIgnoreCase))
- {
- if (CompareTimeZoneFile(filePath, buffer, rawData))
- {
- // if all bytes are the same, this must be the right tz file
- id = filePath;
-
- // strip off the root time zone directory
- if (id.StartsWith(timeZoneDirectory))
- {
- id = id.Substring(timeZoneDirectory.Length);
- }
- break;
- }
- }
- }
- }
- catch (IOException) { }
- catch (SecurityException) { }
- catch (UnauthorizedAccessException) { }
-
- return id;
- }
-
- private static bool CompareTimeZoneFile(string filePath, byte[] buffer, byte[] rawData)
- {
- try
- {
- using (FileStream stream = new FileStream(filePath, FileMode.Open, FileAccess.Read))
- {
- if (stream.Length == rawData.Length)
- {
- int index = 0;
- int count = rawData.Length;
-
- while (count > 0)
- {
- int n = stream.Read(buffer, index, count);
- if (n == 0)
- __Error.EndOfFile();
-
- int end = index + n;
- for (; index < end; index++)
- {
- if (buffer[index] != rawData[index])
- {
- return false;
- }
- }
-
- count -= n;
- }
-
- return true;
- }
- }
- }
- catch (IOException) { }
- catch (SecurityException) { }
- catch (UnauthorizedAccessException) { }
-
- return false;
- }
-
- //
- // GetLocalTimeZoneFromTzFile -
- //
- // Helper function used by 'GetLocalTimeZone()' - this function wraps the call
- // for loading time zone data from computers without Registry support.
- //
- // The TryGetLocalTzFile() call returns a Byte[] containing the compiled tzfile.
- //
- static private TimeZoneInfo GetLocalTimeZoneFromTzFile()
- {
- byte[] rawData;
- string id;
- if (TryGetLocalTzFile(out rawData, out id))
- {
- TimeZoneInfo result = GetTimeZoneFromTzData(rawData, id);
- if (result != null)
- {
- return result;
- }
- }
-
- // if we can't find a local time zone, return UTC
- return Utc;
- }
-
- private static TimeZoneInfo GetTimeZoneFromTzData(byte[] rawData, string id)
+ internal static TimeSpan GetUtcOffsetFromUtc(DateTime time, TimeZoneInfo zone, out bool isDaylightSavings, out bool isAmbiguousLocalDst)
{
- if (rawData != null)
- {
- try
- {
- return new TimeZoneInfo(rawData, id, false); // create a TimeZoneInfo instance from the TZif data w/ DST support
- }
- catch (ArgumentException) { }
- catch (InvalidTimeZoneException) { }
- try
- {
- return new TimeZoneInfo(rawData, id, true); // create a TimeZoneInfo instance from the TZif data w/o DST support
- }
- catch (ArgumentException) { }
- catch (InvalidTimeZoneException) { }
- }
-
- return null;
- }
-
- private static string GetTimeZoneDirectory()
- {
- string tzDirectory = Environment.GetEnvironmentVariable(c_timeZoneDirectoryEnvironmentVariable);
-
- if (tzDirectory == null)
- {
- tzDirectory = c_defaultTimeZoneDirectory;
- }
- else if (!tzDirectory.EndsWith(Path.DirectorySeparatorChar))
- {
- tzDirectory += Path.DirectorySeparatorChar;
- }
-
- return tzDirectory;
- }
-#elif FEATURE_WIN32_REGISTRY // PLATFORM_UNIX
-
- //
- // GetLocalTimeZoneFromWin32Data -
- //
- // Helper function used by 'GetLocalTimeZone()' - this function wraps a bunch of
- // try/catch logic for handling the TimeZoneInfo private constructor that takes
- // a Win32Native.TimeZoneInformation structure.
- //
- static private TimeZoneInfo GetLocalTimeZoneFromWin32Data(Win32Native.TimeZoneInformation timeZoneInformation, Boolean dstDisabled) {
- // first try to create the TimeZoneInfo with the original 'dstDisabled' flag
- try {
- return new TimeZoneInfo(timeZoneInformation, dstDisabled);
- }
- catch (ArgumentException) {}
- catch (InvalidTimeZoneException) {}
-
- // if 'dstDisabled' was false then try passing in 'true' as a last ditch effort
- if (!dstDisabled) {
- try {
- return new TimeZoneInfo(timeZoneInformation, true);
- }
- catch (ArgumentException) {}
- catch (InvalidTimeZoneException) {}
- }
-
- // the data returned from Windows is completely bogus; return a dummy entry
- return CreateCustomTimeZone(c_localId, TimeSpan.Zero, c_localId, c_localId);
- }
-#endif // PLATFORM_UNIX
-
- //
- // FindSystemTimeZoneById -
- //
- // Helper function for retrieving a TimeZoneInfo object by <time_zone_name>.
- // This function wraps the logic necessary to keep the private
- // SystemTimeZones cache in working order
- //
- // This function will either return a valid TimeZoneInfo instance or
- // it will throw 'InvalidTimeZoneException' / 'TimeZoneNotFoundException'.
- //
- static public TimeZoneInfo FindSystemTimeZoneById(string id) {
-
- // Special case for Utc as it will not exist in the dictionary with the rest
- // of the system time zones. There is no need to do this check for Local.Id
- // since Local is a real time zone that exists in the dictionary cache
- if (String.Compare(id, c_utcId, StringComparison.OrdinalIgnoreCase) == 0) {
- return TimeZoneInfo.Utc;
- }
-
- if (id == null) {
- throw new ArgumentNullException(nameof(id));
- }
- else if (!IsValidSystemTimeZoneId(id)) {
- throw new TimeZoneNotFoundException(Environment.GetResourceString("TimeZoneNotFound_MissingData", id));
- }
-
- TimeZoneInfo value;
- Exception e;
-
- TimeZoneInfoResult result;
-
- CachedData cachedData = s_cachedData;
-
- lock (cachedData) {
- result = TryGetTimeZone(id, false, out value, out e, cachedData);
- }
-
- if (result == TimeZoneInfoResult.Success) {
- return value;
- }
- else if (result == TimeZoneInfoResult.InvalidTimeZoneException) {
-#if FEATURE_WIN32_REGISTRY
- throw new InvalidTimeZoneException(Environment.GetResourceString("InvalidTimeZone_InvalidRegistryData", id), e);
-#elif PLATFORM_UNIX
- Debug.Assert(e is InvalidTimeZoneException,
- "TryGetTimeZone must create an InvalidTimeZoneException when it returns TimeZoneInfoResult.InvalidTimeZoneException");
- throw e;
-#endif
- }
- else if (result == TimeZoneInfoResult.SecurityException) {
-#if FEATURE_WIN32_REGISTRY
- throw new SecurityException(Environment.GetResourceString("Security_CannotReadRegistryData", id), e);
-#elif PLATFORM_UNIX
- throw new SecurityException(Environment.GetResourceString("Security_CannotReadFileData", id), e);
-#endif
- }
- else {
- throw new TimeZoneNotFoundException(Environment.GetResourceString("TimeZoneNotFound_MissingData", id), e);
- }
- }
-
- private static bool IsValidSystemTimeZoneId(string id)
- {
- bool isValid = id.Length != 0 && !id.Contains("\0");
-
-#if FEATURE_WIN32_REGISTRY
- isValid &= id.Length <= c_maxKeyLength;
-#endif // FEATURE_WIN32_REGISTRY
-
- return isValid;
- }
-
- //
- // GetUtcOffset -
- //
- // Helper function that calculates the UTC offset for a dateTime in a timeZone.
- // This function assumes that the dateTime is already converted into the timeZone.
- //
- static private TimeSpan GetUtcOffset(DateTime time, TimeZoneInfo zone, TimeZoneInfoOptions flags) {
- TimeSpan baseOffset = zone.BaseUtcOffset;
- AdjustmentRule rule = zone.GetAdjustmentRuleForTime(time);
-
- if (rule != null) {
- baseOffset = baseOffset + rule.BaseUtcOffsetDelta;
- if (rule.HasDaylightSaving) {
- DaylightTimeStruct daylightTime = zone.GetDaylightTime(time.Year, rule);
- Boolean isDaylightSavings = GetIsDaylightSavings(time, rule, daylightTime, flags);
- baseOffset += (isDaylightSavings ? rule.DaylightDelta : TimeSpan.Zero /* FUTURE: rule.StandardDelta */);
- }
- }
-
- return baseOffset;
- }
-
-
- //
- // GetUtcOffsetFromUtc -
- //
- // Helper function that calculates the UTC offset for a UTC-dateTime in a timeZone.
- // This function assumes that the dateTime is represented in UTC and has *not*
- // already been converted into the timeZone.
- //
- static private TimeSpan GetUtcOffsetFromUtc(DateTime time, TimeZoneInfo zone) {
- Boolean isDaylightSavings;
- return GetUtcOffsetFromUtc(time, zone, out isDaylightSavings);
- }
-
- static private TimeSpan GetUtcOffsetFromUtc(DateTime time, TimeZoneInfo zone, out Boolean isDaylightSavings) {
- Boolean isAmbiguousLocalDst;
- return GetUtcOffsetFromUtc(time, zone, out isDaylightSavings, out isAmbiguousLocalDst);
- }
-
- // DateTime.Now fast path that avoids allocating an historically accurate TimeZoneInfo.Local and just creates a 1-year (current year) accurate time zone
- static internal TimeSpan GetDateTimeNowUtcOffsetFromUtc(DateTime time, out Boolean isAmbiguousLocalDst) {
- Boolean isDaylightSavings = false;
-#if FEATURE_WIN32_REGISTRY
- isAmbiguousLocalDst = false;
- TimeSpan baseOffset;
- int timeYear = time.Year;
-
- OffsetAndRule match = s_cachedData.GetOneYearLocalFromUtc(timeYear);
- baseOffset = match.offset;
-
- if (match.rule != null) {
- baseOffset = baseOffset + match.rule.BaseUtcOffsetDelta;
- if (match.rule.HasDaylightSaving) {
- isDaylightSavings = GetIsDaylightSavingsFromUtc(time, timeYear, match.offset, match.rule, out isAmbiguousLocalDst, TimeZoneInfo.Local);
- baseOffset += (isDaylightSavings ? match.rule.DaylightDelta : TimeSpan.Zero /* FUTURE: rule.StandardDelta */);
- }
- }
- return baseOffset;
-#elif PLATFORM_UNIX
- // Use the standard code path for the Macintosh since there isn't a faster way of handling current-year-only time zones
- return GetUtcOffsetFromUtc(time, TimeZoneInfo.Local, out isDaylightSavings, out isAmbiguousLocalDst);
-#endif // FEATURE_WIN32_REGISTRY
- }
-
- static internal TimeSpan GetUtcOffsetFromUtc(DateTime time, TimeZoneInfo zone, out Boolean isDaylightSavings, out Boolean isAmbiguousLocalDst) {
isDaylightSavings = false;
isAmbiguousLocalDst = false;
TimeSpan baseOffset = zone.BaseUtcOffset;
- Int32 year;
+ int year;
AdjustmentRule rule;
- if (time > s_maxDateOnly) {
+ if (time > s_maxDateOnly)
+ {
rule = zone.GetAdjustmentRuleForTime(DateTime.MaxValue);
year = 9999;
}
- else if (time < s_minDateOnly) {
+ else if (time < s_minDateOnly)
+ {
rule = zone.GetAdjustmentRuleForTime(DateTime.MinValue);
year = 1;
}
- else {
+ else
+ {
rule = zone.GetAdjustmentRuleForTime(time, dateTimeisUtc: true);
- // As we get the associated rule using the adjusted targetTime, we should use the adjusted year (targetTime.Year) too as after adding the baseOffset,
+ // 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
// "W. Australia Standard Time" used with date 2005-12-31T23:59:00.0000000Z
@@ -2712,10 +1697,12 @@ namespace System {
year = targetTime.Year;
}
- if (rule != null) {
+ if (rule != null)
+ {
baseOffset = baseOffset + rule.BaseUtcOffsetDelta;
- if (rule.HasDaylightSaving) {
- isDaylightSavings = GetIsDaylightSavingsFromUtc(time, year, zone.m_baseUtcOffset, rule, out isAmbiguousLocalDst, zone);
+ if (rule.HasDaylightSaving)
+ {
+ isDaylightSavings = GetIsDaylightSavingsFromUtc(time, year, zone._baseUtcOffset, rule, out isAmbiguousLocalDst, zone);
baseOffset += (isDaylightSavings ? rule.DaylightDelta : TimeSpan.Zero /* FUTURE: rule.StandardDelta */);
}
}
@@ -2723,140 +1710,28 @@ namespace System {
return baseOffset;
}
-#if FEATURE_WIN32_REGISTRY
- //
- // TransitionTimeFromTimeZoneInformation -
- //
- // Converts a Win32Native.RegistryTimeZoneInformation (REG_TZI_FORMAT struct) to a TransitionTime
- //
- // * when the argument 'readStart' is true the corresponding daylightTransitionTimeStart field is read
- // * when the argument 'readStart' is false the corresponding dayightTransitionTimeEnd field is read
- //
- static private bool TransitionTimeFromTimeZoneInformation(Win32Native.RegistryTimeZoneInformation timeZoneInformation, out TransitionTime transitionTime, bool readStartDate) {
- //
- // SYSTEMTIME -
- //
- // If the time zone does not support daylight saving time or if the caller needs
- // to disable daylight saving time, the wMonth member in the SYSTEMTIME structure
- // must be zero. If this date is specified, the DaylightDate value in the
- // TIME_ZONE_INFORMATION structure must also be specified. Otherwise, the system
- // assumes the time zone data is invalid and no changes will be applied.
- //
- bool supportsDst = (timeZoneInformation.StandardDate.Month != 0);
-
- if (!supportsDst) {
- transitionTime = default(TransitionTime);
- return false;
- }
-
- //
- // SYSTEMTIME -
- //
- // * FixedDateRule -
- // If the Year member is not zero, the transition date is absolute; it will only occur one time
- //
- // * FloatingDateRule -
- // To select the correct day in the month, set the Year member to zero, the Hour and Minute
- // members to the transition time, the DayOfWeek member to the appropriate weekday, and the
- // Day member to indicate the occurence of the day of the week within the month (first through fifth).
- //
- // Using this notation, specify the 2:00a.m. on the first Sunday in April as follows:
- // Hour = 2,
- // Month = 4,
- // DayOfWeek = 0,
- // Day = 1.
- //
- // Specify 2:00a.m. on the last Thursday in October as follows:
- // Hour = 2,
- // Month = 10,
- // DayOfWeek = 4,
- // Day = 5.
- //
- if (readStartDate) {
- //
- // read the "daylightTransitionStart"
- //
- if (timeZoneInformation.DaylightDate.Year == 0) {
- transitionTime = TransitionTime.CreateFloatingDateRule(
- new DateTime(1, /* year */
- 1, /* month */
- 1, /* day */
- timeZoneInformation.DaylightDate.Hour,
- timeZoneInformation.DaylightDate.Minute,
- timeZoneInformation.DaylightDate.Second,
- timeZoneInformation.DaylightDate.Milliseconds),
- timeZoneInformation.DaylightDate.Month,
- timeZoneInformation.DaylightDate.Day, /* Week 1-5 */
- (DayOfWeek) timeZoneInformation.DaylightDate.DayOfWeek);
- }
- else {
- transitionTime = TransitionTime.CreateFixedDateRule(
- new DateTime(1, /* year */
- 1, /* month */
- 1, /* day */
- timeZoneInformation.DaylightDate.Hour,
- timeZoneInformation.DaylightDate.Minute,
- timeZoneInformation.DaylightDate.Second,
- timeZoneInformation.DaylightDate.Milliseconds),
- timeZoneInformation.DaylightDate.Month,
- timeZoneInformation.DaylightDate.Day);
- }
- }
- else {
- //
- // read the "daylightTransitionEnd"
- //
- if (timeZoneInformation.StandardDate.Year == 0) {
- transitionTime = TransitionTime.CreateFloatingDateRule(
- new DateTime(1, /* year */
- 1, /* month */
- 1, /* day */
- timeZoneInformation.StandardDate.Hour,
- timeZoneInformation.StandardDate.Minute,
- timeZoneInformation.StandardDate.Second,
- timeZoneInformation.StandardDate.Milliseconds),
- timeZoneInformation.StandardDate.Month,
- timeZoneInformation.StandardDate.Day, /* Week 1-5 */
- (DayOfWeek) timeZoneInformation.StandardDate.DayOfWeek);
- }
- else {
- transitionTime = TransitionTime.CreateFixedDateRule(
- new DateTime(1, /* year */
- 1, /* month */
- 1, /* day */
- timeZoneInformation.StandardDate.Hour,
- timeZoneInformation.StandardDate.Minute,
- timeZoneInformation.StandardDate.Second,
- timeZoneInformation.StandardDate.Milliseconds),
- timeZoneInformation.StandardDate.Month,
- timeZoneInformation.StandardDate.Day);
- }
- }
-
- return true;
- }
-#endif // FEATURE_WIN32_REGISTRY
-
- //
- // TransitionTimeToDateTime -
- //
- // Helper function that converts a year and TransitionTime into a DateTime
- //
- internal static DateTime TransitionTimeToDateTime(Int32 year, TransitionTime transitionTime) {
+ /// <summary>
+ /// Helper function that converts a year and TransitionTime into a DateTime.
+ /// </summary>
+ internal static DateTime TransitionTimeToDateTime(int year, TransitionTime transitionTime)
+ {
DateTime value;
DateTime timeOfDay = transitionTime.TimeOfDay;
- if (transitionTime.IsFixedDateRule) {
+ if (transitionTime.IsFixedDateRule)
+ {
// create a DateTime from the passed in year and the properties on the transitionTime
// if the day is out of range for the month then use the last day of the month
- Int32 day = DateTime.DaysInMonth(year, transitionTime.Month);
+ int day = DateTime.DaysInMonth(year, transitionTime.Month);
- value = new DateTime(year, transitionTime.Month, (day < transitionTime.Day) ? day : transitionTime.Day,
+ value = new DateTime(year, transitionTime.Month, (day < transitionTime.Day) ? day : transitionTime.Day,
timeOfDay.Hour, timeOfDay.Minute, timeOfDay.Second, timeOfDay.Millisecond);
}
- else {
- if (transitionTime.Week <= 4) {
+ else
+ {
+ if (transitionTime.Week <= 4)
+ {
//
// Get the (transitionTime.Week)th Sunday.
//
@@ -2865,31 +1740,36 @@ namespace System {
int dayOfWeek = (int)value.DayOfWeek;
int delta = (int)transitionTime.DayOfWeek - dayOfWeek;
- if (delta < 0) {
+ if (delta < 0)
+ {
delta += 7;
}
delta += 7 * (transitionTime.Week - 1);
- if (delta > 0) {
+ if (delta > 0)
+ {
value = value.AddDays(delta);
}
}
- else {
+ else
+ {
//
// If TransitionWeek is greater than 4, we will get the last week.
//
- Int32 daysInMonth = DateTime.DaysInMonth(year, transitionTime.Month);
+ int daysInMonth = DateTime.DaysInMonth(year, transitionTime.Month);
value = new DateTime(year, transitionTime.Month, daysInMonth,
timeOfDay.Hour, timeOfDay.Minute, timeOfDay.Second, timeOfDay.Millisecond);
// This is the day of week for the last day of the month.
int dayOfWeek = (int)value.DayOfWeek;
int delta = dayOfWeek - (int)transitionTime.DayOfWeek;
- if (delta < 0) {
+ if (delta < 0)
+ {
delta += 7;
}
- if (delta > 0) {
+ if (delta > 0)
+ {
value = value.AddDays(-delta);
}
}
@@ -2897,598 +1777,56 @@ namespace System {
return value;
}
-#if FEATURE_WIN32_REGISTRY
- //
- // TryCreateAdjustmentRules -
- //
- // Helper function that takes
- // 1. a string representing a <time_zone_name> registry key name
- // 2. a RegistryTimeZoneInformation struct containing the default rule
- // 3. an AdjustmentRule[] out-parameter
- //
- // returns
- // TimeZoneInfoResult.InvalidTimeZoneException,
- // TimeZoneInfoResult.TimeZoneNotFoundException,
- // TimeZoneInfoResult.Success
- //
- // Optional, Dynamic Time Zone Registry Data
- // -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
- //
- // HKLM
- // Software
- // Microsoft
- // Windows NT
- // CurrentVersion
- // Time Zones
- // <time_zone_name>
- // Dynamic DST
- // * "FirstEntry" REG_DWORD "1980"
- // First year in the table. If the current year is less than this value,
- // this entry will be used for DST boundaries
- // * "LastEntry" REG_DWORD "2038"
- // Last year in the table. If the current year is greater than this value,
- // this entry will be used for DST boundaries"
- // * "<year1>" REG_BINARY REG_TZI_FORMAT
- // See Win32Native.RegistryTimeZoneInformation
- // * "<year2>" REG_BINARY REG_TZI_FORMAT
- // See Win32Native.RegistryTimeZoneInformation
- // * "<year3>" REG_BINARY REG_TZI_FORMAT
- // See Win32Native.RegistryTimeZoneInformation
- //
- // This method expects that its caller has already Asserted RegistryPermission.Read
- //
- 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(
- c_timeZonesRegistryHive + "\\" + id + "\\Dynamic DST",
- false)) {
- if (dynamicKey == null) {
- AdjustmentRule rule = CreateAdjustmentRuleFromTimeZoneInformation(
- defaultTimeZoneInformation, DateTime.MinValue.Date, DateTime.MaxValue.Date, defaultBaseUtcOffset);
-
- if (rule == null)
- {
- rules = null;
- }
- else
- {
- rules = new AdjustmentRule[1];
- rules[0] = rule;
- }
-
- return true;
- }
-
- //
- // loop over all of the "<time_zone_name>\Dynamic DST" hive entries
- //
- // read FirstEntry {MinValue - (year1, 12, 31)}
- // read MiddleEntry {(yearN, 1, 1) - (yearN, 12, 31)}
- // read LastEntry {(yearN, 1, 1) - MaxValue }
-
- // read the FirstEntry and LastEntry key values (ex: "1980", "2038")
- 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)
- {
- rules = null;
- return false;
- }
-
- // 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)
- {
- rules = null;
- return false;
- }
- dtzi = new Win32Native.RegistryTimeZoneInformation(regValue);
-
- if (first == last)
- {
- // there is just 1 dynamic rule for this time zone.
- AdjustmentRule rule = CreateAdjustmentRuleFromTimeZoneInformation(dtzi, DateTime.MinValue.Date, DateTime.MaxValue.Date, defaultBaseUtcOffset);
-
- if (rule == null)
- {
- rules = null;
- }
- else
- {
- rules = new AdjustmentRule[1];
- rules[0] = rule;
- }
-
- return true;
- }
-
- List<AdjustmentRule> rulesList = new List<AdjustmentRule>(1);
-
- // 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)
- {
- rulesList.Add(firstRule);
- }
-
- // read the middle year entries
- 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)
- {
- rules = null;
- return false;
- }
- dtzi = new Win32Native.RegistryTimeZoneInformation(regValue);
- AdjustmentRule middleRule = CreateAdjustmentRuleFromTimeZoneInformation(
- dtzi,
- new DateTime(i, 1, 1), // January 01, <Year>
- new DateTime(i, 12, 31), // December 31, <Year>
- defaultBaseUtcOffset);
- 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)
- {
- rules = null;
- return false;
- }
- AdjustmentRule lastRule = CreateAdjustmentRuleFromTimeZoneInformation(
- dtzi,
- new DateTime(last, 1, 1), // January 01, <LastYear>
- DateTime.MaxValue.Date, // MaxValue
- defaultBaseUtcOffset);
- if (lastRule != null)
- {
- rulesList.Add(lastRule);
- }
-
- // convert the ArrayList to an AdjustmentRule array
- rules = rulesList.ToArray();
- if (rules != null && rules.Length == 0)
- {
- rules = null;
- }
- } // end of: using (RegistryKey dynamicKey...
- }
- catch (InvalidCastException ex) {
- // one of the RegistryKey.GetValue calls could not be cast to an expected value type
- rules = null;
- e = ex;
- return false;
- }
- catch (ArgumentOutOfRangeException ex) {
- rules = null;
- e = ex;
- return false;
- }
- catch (ArgumentException ex) {
- rules = null;
- e = ex;
- return false;
- }
- return true;
- }
-
- //
- // TryCompareStandardDate -
- //
- // Helper function that compares the StandardBias and StandardDate portion a
- // TimeZoneInformation struct to a time zone registry entry
- //
- static private Boolean TryCompareStandardDate(Win32Native.TimeZoneInformation timeZone, Win32Native.RegistryTimeZoneInformation registryTimeZoneInfo) {
- return timeZone.Bias == registryTimeZoneInfo.Bias
- && timeZone.StandardBias == registryTimeZoneInfo.StandardBias
- && timeZone.StandardDate.Year == registryTimeZoneInfo.StandardDate.Year
- && timeZone.StandardDate.Month == registryTimeZoneInfo.StandardDate.Month
- && timeZone.StandardDate.DayOfWeek == registryTimeZoneInfo.StandardDate.DayOfWeek
- && timeZone.StandardDate.Day == registryTimeZoneInfo.StandardDate.Day
- && timeZone.StandardDate.Hour == registryTimeZoneInfo.StandardDate.Hour
- && timeZone.StandardDate.Minute == registryTimeZoneInfo.StandardDate.Minute
- && timeZone.StandardDate.Second == registryTimeZoneInfo.StandardDate.Second
- && timeZone.StandardDate.Milliseconds == registryTimeZoneInfo.StandardDate.Milliseconds;
- }
-
- //
- // TryCompareTimeZoneInformationToRegistry -
- //
- // Helper function that compares a TimeZoneInformation struct to a time zone registry entry
- //
- static private Boolean TryCompareTimeZoneInformationToRegistry(Win32Native.TimeZoneInformation timeZone, string id, out Boolean dstDisabled)
+ /// <summary>
+ /// Helper function for retrieving a TimeZoneInfo object by <time_zone_name>.
+ ///
+ /// This function may return null.
+ ///
+ /// assumes cachedData lock is taken
+ /// </summary>
+ private static TimeZoneInfoResult TryGetTimeZone(string id, bool dstDisabled, out TimeZoneInfo value, out Exception e, CachedData cachedData, bool alwaysFallbackToLocalMachine = false)
{
- dstDisabled = false;
- try {
- PermissionSet permSet = new PermissionSet(PermissionState.None);
- permSet.AddPermission(new RegistryPermission(RegistryPermissionAccess.Read, c_timeZonesRegistryHivePermissionList));
- permSet.Assert();
-
- using (RegistryKey key = Registry.LocalMachine.OpenSubKey(
- c_timeZonesRegistryHive + "\\" + id,
- false))
- {
-
- if (key == null) {
- return false;
- }
-
- Win32Native.RegistryTimeZoneInformation registryTimeZoneInfo;
- Byte[] regValue = (Byte[])key.GetValue(c_timeZoneInfoValue, null, RegistryValueOptions.None) as Byte[];
- if (regValue == null || regValue.Length != c_regByteLength) return false;
- registryTimeZoneInfo = new Win32Native.RegistryTimeZoneInformation(regValue);
-
- //
- // first compare the bias and standard date information between the data from the Win32 API
- // and the data from the registry...
- //
- Boolean result = TryCompareStandardDate(timeZone, registryTimeZoneInfo);
-
- if (!result)
- {
- return false;
- }
-
- result = dstDisabled || CheckDaylightSavingTimeNotSupported(timeZone)
- //
- // 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.DaylightDate.Milliseconds == registryTimeZoneInfo.DaylightDate.Milliseconds);
-
- // Finally compare the "StandardName" string value...
- //
- // 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)
- {
- String registryStandardName = key.GetValue(c_standardValue, String.Empty, RegistryValueOptions.None) as String;
- result = String.Compare(registryStandardName, timeZone.StandardName, StringComparison.Ordinal) == 0;
- }
- return result;
- }
- }
- finally {
- PermissionSet.RevertAssert();
- }
- }
-
- //
- // TryGetLocalizedNameByMuiNativeResource -
- //
- // Helper function for retrieving a localized string resource via MUI.
- // The function expects a string in the form: "@resource.dll, -123"
- //
- // "resource.dll" is a language-neutral portable executable (LNPE) file in
- // the %windir%\system32 directory. The OS is queried to find the best-fit
- // localized resource file for this LNPE (ex: %windir%\system32\en-us\resource.dll.mui).
- // If a localized resource file exists, we LoadString resource ID "123" and
- // return it to our caller.
- //
- // <SecurityKernel Critical="True" Ring="0">
- // <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>
- static private string TryGetLocalizedNameByMuiNativeResource(string resource) {
- if (String.IsNullOrEmpty(resource)) {
- return String.Empty;
- }
-
- // parse "@tzres.dll, -100"
- //
- // filePath = "C:\Windows\System32\tzres.dll"
- // resourceId = -100
- //
- string[] resources = resource.Split(new char[] {','}, StringSplitOptions.None);
- if (resources.Length != 2) {
- return String.Empty;
- }
-
- string filePath;
- int resourceId;
-
- // get the path to Windows\System32
- string system32 = Environment.UnsafeGetFolderPath(Environment.SpecialFolder.System);
-
- // trim the string "@tzres.dll" => "tzres.dll"
- string tzresDll = resources[0].TrimStart(new char[] {'@'});
-
- try {
- filePath = Path.Combine(system32, tzresDll);
- }
- catch (ArgumentException) {
- // there were probably illegal characters in the path
- return String.Empty;
- }
-
- if (!Int32.TryParse(resources[1], NumberStyles.Integer, CultureInfo.InvariantCulture, out resourceId)) {
- return String.Empty;
- }
- resourceId = -resourceId;
-
-
- try {
- StringBuilder fileMuiPath = StringBuilderCache.Acquire(Path.MaxPath);
- fileMuiPath.Length = Path.MaxPath;
- int fileMuiPathLength = Path.MaxPath;
- int languageLength = 0;
- Int64 enumerator = 0;
-
- Boolean succeeded = UnsafeNativeMethods.GetFileMUIPath(
- Win32Native.MUI_PREFERRED_UI_LANGUAGES,
- filePath, null /* language */, ref languageLength,
- fileMuiPath, ref fileMuiPathLength, ref enumerator);
- if (!succeeded) {
- StringBuilderCache.Release(fileMuiPath);
- return String.Empty;
- }
- return TryGetLocalizedNameByNativeResource(StringBuilderCache.GetStringAndRelease(fileMuiPath), resourceId);
- }
- catch (EntryPointNotFoundException) {
- return String.Empty;
- }
- }
-
- //
- // TryGetLocalizedNameByNativeResource -
- //
- // Helper function for retrieving a localized string resource via a native resource DLL.
- // The function expects a string in the form: "C:\Windows\System32\en-us\resource.dll"
- //
- // "resource.dll" is a language-specific resource DLL.
- // If the localized resource DLL exists, LoadString(resource) is returned.
- //
- static private string TryGetLocalizedNameByNativeResource(string filePath, int resource) {
- using (SafeLibraryHandle handle =
- UnsafeNativeMethods.LoadLibraryEx(filePath, IntPtr.Zero, Win32Native.LOAD_LIBRARY_AS_DATAFILE)) {
-
- if (!handle.IsInvalid) {
- StringBuilder localizedResource = StringBuilderCache.Acquire(Win32Native.LOAD_STRING_MAX_LENGTH);
- localizedResource.Length = Win32Native.LOAD_STRING_MAX_LENGTH;
-
- int result = UnsafeNativeMethods.LoadString(handle, resource,
- localizedResource, localizedResource.Length);
-
- if (result != 0) {
- return StringBuilderCache.GetStringAndRelease(localizedResource);
- }
- }
- }
- return String.Empty;
- }
-
- //
- // TryGetLocalizedNamesByRegistryKey -
- //
- // Helper function for retrieving the DisplayName, StandardName, and DaylightName from the registry
- //
- // The function first checks the MUI_ key-values, and if they exist, it loads the strings from the MUI
- // resource dll(s). When the keys do not exist, the function falls back to reading from the standard
- // key-values
- //
- // This method expects that its caller has already Asserted RegistryPermission.Read
- //
- static private Boolean TryGetLocalizedNamesByRegistryKey(RegistryKey key, out String displayName, out String standardName, out String daylightName) {
- displayName = String.Empty;
- standardName = String.Empty;
- daylightName = String.Empty;
-
- // read the MUI_ registry keys
- String displayNameMuiResource = key.GetValue(c_muiDisplayValue, String.Empty, RegistryValueOptions.None) as String;
- String standardNameMuiResource = key.GetValue(c_muiStandardValue, String.Empty, RegistryValueOptions.None) as String;
- String daylightNameMuiResource = key.GetValue(c_muiDaylightValue, String.Empty, RegistryValueOptions.None) as String;
-
- // try to load the strings from the native resource DLL(s)
- if (!String.IsNullOrEmpty(displayNameMuiResource)) {
- displayName = TryGetLocalizedNameByMuiNativeResource(displayNameMuiResource);
- }
-
- if (!String.IsNullOrEmpty(standardNameMuiResource)) {
- standardName = TryGetLocalizedNameByMuiNativeResource(standardNameMuiResource);
- }
-
- if (!String.IsNullOrEmpty(daylightNameMuiResource)) {
- daylightName = TryGetLocalizedNameByMuiNativeResource(daylightNameMuiResource);
- }
-
- // fallback to using the standard registry keys
- if (String.IsNullOrEmpty(displayName)) {
- displayName = key.GetValue(c_displayValue, String.Empty, RegistryValueOptions.None) as String;
- }
- if (String.IsNullOrEmpty(standardName)) {
- standardName = key.GetValue(c_standardValue, String.Empty, RegistryValueOptions.None) as String;
- }
- if (String.IsNullOrEmpty(daylightName)) {
- daylightName = key.GetValue(c_daylightValue, String.Empty, RegistryValueOptions.None) as String;
- }
-
- return true;
- }
-
- //
- // TryGetTimeZoneByRegistryKey -
- //
- // Helper function that takes a string representing a <time_zone_name> registry key name
- // and returns a TimeZoneInfo instance.
- //
- // returns
- // TimeZoneInfoResult.InvalidTimeZoneException,
- // TimeZoneInfoResult.TimeZoneNotFoundException,
- // TimeZoneInfoResult.SecurityException,
- // TimeZoneInfoResult.Success
- //
- //
- // Standard Time Zone Registry Data
- // -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
- // HKLM
- // Software
- // Microsoft
- // Windows NT
- // CurrentVersion
- // Time Zones
- // <time_zone_name>
- // * STD, REG_SZ "Standard Time Name"
- // (For OS installed zones, this will always be English)
- // * MUI_STD, REG_SZ "@tzres.dll,-1234"
- // Indirect string to localized resource for Standard Time,
- // add "%windir%\system32\" after "@"
- // * DLT, REG_SZ "Daylight Time Name"
- // (For OS installed zones, this will always be English)
- // * MUI_DLT, REG_SZ "@tzres.dll,-1234"
- // Indirect string to localized resource for Daylight Time,
- // add "%windir%\system32\" after "@"
- // * Display, REG_SZ "Display Name like (GMT-8:00) Pacific Time..."
- // * MUI_Display, REG_SZ "@tzres.dll,-1234"
- // Indirect string to localized resource for the Display,
- // add "%windir%\system32\" after "@"
- // * TZI, REG_BINARY REG_TZI_FORMAT
- // See Win32Native.RegistryTimeZoneInformation
- //
- static private TimeZoneInfoResult TryGetTimeZoneByRegistryKey(string id, out TimeZoneInfo value, out Exception e) {
- e = null;
-
- try {
- PermissionSet permSet = new PermissionSet(PermissionState.None);
- permSet.AddPermission(new RegistryPermission(RegistryPermissionAccess.Read, c_timeZonesRegistryHivePermissionList));
- permSet.Assert();
-
- using (RegistryKey key = Registry.LocalMachine.OpenSubKey(
- c_timeZonesRegistryHive + "\\" + id,
- false)) {
-
- if (key == null) {
- value = null;
- return TimeZoneInfoResult.TimeZoneNotFoundException;
- }
-
- Win32Native.RegistryTimeZoneInformation defaultTimeZoneInformation;
- Byte[] regValue = key.GetValue(c_timeZoneInfoValue, null, RegistryValueOptions.None) as Byte[];
- if (regValue == null || regValue.Length != c_regByteLength) {
- // the registry value could not be cast to a byte array
- value = null;
- return TimeZoneInfoResult.InvalidTimeZoneException;
- }
- defaultTimeZoneInformation = new Win32Native.RegistryTimeZoneInformation(regValue);
+ Debug.Assert(Monitor.IsEntered(cachedData));
- AdjustmentRule[] adjustmentRules;
- if (!TryCreateAdjustmentRules(id, defaultTimeZoneInformation, out adjustmentRules, out e, defaultTimeZoneInformation.Bias)) {
- value = null;
- return TimeZoneInfoResult.InvalidTimeZoneException;
- }
-
- string displayName;
- string standardName;
- string daylightName;
-
- if (!TryGetLocalizedNamesByRegistryKey(key, out displayName, out standardName, out daylightName)) {
- value = null;
- return TimeZoneInfoResult.InvalidTimeZoneException;
- }
-
- try {
- value = new TimeZoneInfo(
- id,
- new TimeSpan(0, -(defaultTimeZoneInformation.Bias), 0),
- displayName,
- standardName,
- daylightName,
- adjustmentRules,
- false);
-
- return TimeZoneInfoResult.Success;
- }
- catch (ArgumentException ex) {
- // TimeZoneInfo constructor can throw ArgumentException and InvalidTimeZoneException
- value = null;
- e = ex;
- return TimeZoneInfoResult.InvalidTimeZoneException;
- }
- catch (InvalidTimeZoneException ex) {
- // TimeZoneInfo constructor can throw ArgumentException and InvalidTimeZoneException
- value = null;
- e = ex;
- return TimeZoneInfoResult.InvalidTimeZoneException;
- }
-
- }
- }
- finally {
- PermissionSet.RevertAssert();
- }
- }
-#endif // FEATURE_WIN32_REGISTRY
-
-
- //
- // TryGetTimeZone -
- //
- // Helper function for retrieving a TimeZoneInfo object by <time_zone_name>.
- //
- // This function may return null.
- //
- // assumes cachedData lock is taken
- //
- static private TimeZoneInfoResult TryGetTimeZone(string id, Boolean dstDisabled, out TimeZoneInfo value, out Exception e, CachedData cachedData) {
TimeZoneInfoResult result = TimeZoneInfoResult.Success;
e = null;
TimeZoneInfo match = null;
// check the cache
- if (cachedData.m_systemTimeZones != null) {
- if (cachedData.m_systemTimeZones.TryGetValue(id, out match)) {
- if (dstDisabled && match.m_supportsDaylightSavingTime) {
+ if (cachedData._systemTimeZones != null)
+ {
+ if (cachedData._systemTimeZones.TryGetValue(id, out match))
+ {
+ if (dstDisabled && match._supportsDaylightSavingTime)
+ {
// we found a cache hit but we want a time zone without DST and this one has DST data
- value = CreateCustomTimeZone(match.m_id, match.m_baseUtcOffset, match.m_displayName, match.m_standardDisplayName);
+ value = CreateCustomTimeZone(match._id, match._baseUtcOffset, match._displayName, match._standardDisplayName);
}
- else {
- value = new TimeZoneInfo(match.m_id, match.m_baseUtcOffset, match.m_displayName, match.m_standardDisplayName,
- match.m_daylightDisplayName, match.m_adjustmentRules, false);
+ else
+ {
+ value = new TimeZoneInfo(match._id, match._baseUtcOffset, match._displayName, match._standardDisplayName,
+ match._daylightDisplayName, match._adjustmentRules, disableDaylightSavingTime: false);
}
return result;
}
}
- // fall back to reading from the local machine
- // when the cache is not fully populated
- if (!cachedData.m_allSystemTimeZonesRead) {
- result = TryGetTimeZoneFromLocalMachine(id, dstDisabled, out value, out e, cachedData);
- }
-#if PLATFORM_UNIX
+ // Fall back to reading from the local machine when the cache is not fully populated.
// On UNIX, there may be some tzfiles that aren't in the zones.tab file, and thus aren't returned from GetSystemTimeZones().
// If a caller asks for one of these zones before calling GetSystemTimeZones(), the time zone is returned successfully. But if
// GetSystemTimeZones() is called first, FindSystemTimeZoneById will throw TimeZoneNotFoundException, which is inconsistent.
- // To fix this, even if m_allSystemTimeZonesRead is true, try reading the tzfile from disk, but don't add the time zone to the
- // list returned from GetSystemTimeZones(). These time zones will only be available if asked for directly.
- else {
+ // To fix this, when 'alwaysFallbackToLocalMachine' is true, even if _allSystemTimeZonesRead is true, try reading the tzfile
+ // from disk, but don't add the time zone to the list returned from GetSystemTimeZones(). These time zones will only be
+ // available if asked for directly.
+ if (!cachedData._allSystemTimeZonesRead || alwaysFallbackToLocalMachine)
+ {
result = TryGetTimeZoneFromLocalMachine(id, dstDisabled, out value, out e, cachedData);
}
-#else
- else {
+ else
+ {
result = TimeZoneInfoResult.TimeZoneNotFoundException;
value = null;
}
-#endif // PLATFORM_UNIX
return result;
}
@@ -3498,28 +1836,24 @@ namespace System {
TimeZoneInfoResult result;
TimeZoneInfo match;
-#if FEATURE_WIN32_REGISTRY
- result = TryGetTimeZoneByRegistryKey(id, out match, out e);
-#elif PLATFORM_UNIX
- result = TryGetTimeZoneByFile(id, out match, out e);
-#endif // FEATURE_WIN32_REGISTRY
+ result = TryGetTimeZoneFromLocalMachine(id, out match, out e);
if (result == TimeZoneInfoResult.Success)
{
- if (cachedData.m_systemTimeZones == null)
- cachedData.m_systemTimeZones = new Dictionary<string, TimeZoneInfo>();
+ if (cachedData._systemTimeZones == null)
+ cachedData._systemTimeZones = new Dictionary<string, TimeZoneInfo>();
- cachedData.m_systemTimeZones.Add(id, match);
+ cachedData._systemTimeZones.Add(id, match);
- if (dstDisabled && match.m_supportsDaylightSavingTime)
+ if (dstDisabled && match._supportsDaylightSavingTime)
{
// we found a cache hit but we want a time zone without DST and this one has DST data
- value = CreateCustomTimeZone(match.m_id, match.m_baseUtcOffset, match.m_displayName, match.m_standardDisplayName);
+ value = CreateCustomTimeZone(match._id, match._baseUtcOffset, match._displayName, match._standardDisplayName);
}
else
{
- value = new TimeZoneInfo(match.m_id, match.m_baseUtcOffset, match.m_displayName, match.m_standardDisplayName,
- match.m_daylightDisplayName, match.m_adjustmentRules, false);
+ value = new TimeZoneInfo(match._id, match._baseUtcOffset, match._displayName, match._standardDisplayName,
+ match._daylightDisplayName, match._adjustmentRules, disableDaylightSavingTime: false);
}
}
else
@@ -3530,843 +1864,37 @@ namespace System {
return result;
}
-#if PLATFORM_UNIX
- // TZFILE(5) BSD File Formats Manual TZFILE(5)
- //
- // NAME
- // tzfile -- timezone information
- //
- // SYNOPSIS
- // #include "/usr/src/lib/libc/stdtime/tzfile.h"
- //
- // DESCRIPTION
- // The time zone information files used by tzset(3) begin with the magic
- // characters ``TZif'' to identify them as time zone information files, fol-
- // lowed by sixteen bytes reserved for future use, followed by four four-
- // byte values written in a ``standard'' byte order (the high-order byte of
- // the value is written first). These values are, in order:
- //
- // tzh_ttisgmtcnt The number of UTC/local indicators stored in the file.
- // tzh_ttisstdcnt The number of standard/wall indicators stored in the
- // file.
- // tzh_leapcnt The number of leap seconds for which data is stored in
- // the file.
- // tzh_timecnt The number of ``transition times'' for which data is
- // stored in the file.
- // tzh_typecnt The number of ``local time types'' for which data is
- // stored in the file (must not be zero).
- // tzh_charcnt The number of characters of ``time zone abbreviation
- // strings'' stored in the file.
- //
- // The above header is followed by tzh_timecnt four-byte values of type
- // long, sorted in ascending order. These values are written in ``stan-
- // dard'' byte order. Each is used as a transition time (as returned by
- // time(3)) at which the rules for computing local time change. Next come
- // tzh_timecnt one-byte values of type unsigned char; each one tells which
- // of the different types of ``local time'' types described in the file is
- // associated with the same-indexed transition time. These values serve as
- // indices into an array of ttinfo structures that appears next in the file;
- // these structures are defined as follows:
- //
- // struct ttinfo {
- // long tt_gmtoff;
- // int tt_isdst;
- // unsigned int tt_abbrind;
- // };
- //
- // Each structure is written as a four-byte value for tt_gmtoff of type
- // long, in a standard byte order, followed by a one-byte value for tt_isdst
- // and a one-byte value for tt_abbrind. In each structure, tt_gmtoff gives
- // the number of seconds to be added to UTC, tt_isdst tells whether tm_isdst
- // should be set by localtime(3) and tt_abbrind serves as an index into the
- // array of time zone abbreviation characters that follow the ttinfo struc-
- // ture(s) in the file.
- //
- // Then there are tzh_leapcnt pairs of four-byte values, written in standard
- // byte order; the first value of each pair gives the time (as returned by
- // time(3)) at which a leap second occurs; the second gives the total number
- // of leap seconds to be applied after the given time. The pairs of values
- // are sorted in ascending order by time.b
- //
- // Then there are tzh_ttisstdcnt standard/wall indicators, each stored as a
- // one-byte value; they tell whether the transition times associated with
- // local time types were specified as standard time or wall clock time, and
- // are used when a time zone file is used in handling POSIX-style time zone
- // environment variables.
- //
- // Finally there are tzh_ttisgmtcnt UTC/local indicators, each stored as a
- // one-byte value; they tell whether the transition times associated with
- // local time types were specified as UTC or local time, and are used when a
- // time zone file is used in handling POSIX-style time zone environment
- // variables.
- //
- // localtime uses the first standard-time ttinfo structure in the file (or
- // simply the first ttinfo structure in the absence of a standard-time
- // structure) if either tzh_timecnt is zero or the time argument is less
- // than the first transition time recorded in the file.
- //
- // SEE ALSO
- // ctime(3), time2posix(3), zic(8)
- //
- // BSD September 13, 1994 BSD
- //
- //
- //
- // TIME(3) BSD Library Functions Manual TIME(3)
- //
- // NAME
- // time -- get time of day
- //
- // LIBRARY
- // Standard C Library (libc, -lc)
- //
- // SYNOPSIS
- // #include <time.h>
- //
- // time_t
- // time(time_t *tloc);
- //
- // DESCRIPTION
- // The time() function returns the value of time in seconds since 0 hours, 0
- // minutes, 0 seconds, January 1, 1970, Coordinated Universal Time, without
- // including leap seconds. If an error occurs, time() returns the value
- // (time_t)-1.
- //
- // The return value is also stored in *tloc, provided that tloc is non-null.
- //
- // ERRORS
- // The time() function may fail for any of the reasons described in
- // gettimeofday(2).
- //
- // SEE ALSO
- // gettimeofday(2), ctime(3)
- //
- // STANDARDS
- // The time function conforms to IEEE Std 1003.1-2001 (``POSIX.1'').
- //
- // BUGS
- // Neither ISO/IEC 9899:1999 (``ISO C99'') nor IEEE Std 1003.1-2001
- // (``POSIX.1'') requires time() to set errno on failure; thus, it is impos-
- // sible for an application to distinguish the valid time value -1 (repre-
- // senting the last UTC second of 1969) from the error return value.
- //
- // Systems conforming to earlier versions of the C and POSIX standards
- // (including older versions of FreeBSD) did not set *tloc in the error
- // case.
- //
- // HISTORY
- // A time() function appeared in Version 6 AT&T UNIX.
- //
- // BSD July 18, 2003 BSD
- //
- //
- static private void TZif_GenerateAdjustmentRules(out AdjustmentRule[] rules, TimeSpan baseUtcOffset, DateTime[] dts, Byte[] typeOfLocalTime,
- TZifType[] transitionType, Boolean[] StandardTime, Boolean[] GmtTime, string futureTransitionsPosixFormat)
- {
- rules = null;
-
- if (dts.Length > 0)
- {
- int index = 0;
- List<AdjustmentRule> rulesList = new List<AdjustmentRule>();
-
- while (index <= dts.Length)
- {
- TZif_GenerateAdjustmentRule(ref index, baseUtcOffset, rulesList, dts, typeOfLocalTime, transitionType, StandardTime, GmtTime, futureTransitionsPosixFormat);
- }
-
- rules = rulesList.ToArray();
- if (rules != null && rules.Length == 0)
- {
- rules = null;
- }
- }
- }
-
- static private void TZif_GenerateAdjustmentRule(ref int index, TimeSpan timeZoneBaseUtcOffset, List<AdjustmentRule> rulesList, DateTime[] dts,
- Byte[] typeOfLocalTime, TZifType[] transitionTypes, Boolean[] StandardTime, Boolean[] GmtTime, string futureTransitionsPosixFormat)
- {
- // To generate AdjustmentRules, use the following approach:
- // The first AdjustmentRule will go from DateTime.MinValue to the first transition time greater than DateTime.MinValue.
- // Each middle AdjustmentRule wil go from dts[index-1] to dts[index].
- // The last AdjustmentRule will go from dts[dts.Length-1] to Datetime.MaxValue.
-
- // 0. Skip any DateTime.MinValue transition times. In newer versions of the tzfile, there
- // is a "big bang" transition time, which is before the year 0001. Since any times before year 0001
- // cannot be represented by DateTime, there is no reason to make AdjustmentRules for these unrepresentable time periods.
- // 1. If there are no DateTime.MinValue times, the first AdjustmentRule goes from DateTime.MinValue
- // to the first transition and uses the first standard transitionType (or the first transitionType if none of them are standard)
- // 2. Create an AdjustmentRule for each transition, i.e. from dts[index - 1] to dts[index].
- // This rule uses the transitionType[index - 1] and the whole AdjustmentRule only describes a single offset - either
- // all daylight savings, or all stanard time.
- // 3. After all the transitions are filled out, the last AdjustmentRule is created from either:
- // a. a POSIX-style timezone description ("futureTransitionsPosixFormat"), if there is one or
- // b. continue the last transition offset until DateTime.Max
-
- while (index < dts.Length && dts[index] == DateTime.MinValue)
- {
- index++;
- }
-
- if (index == 0)
- {
- TZifType transitionType = TZif_GetEarlyDateTransitionType(transitionTypes);
- DateTime endTransitionDate = dts[index];
-
- TimeSpan transitionOffset = TZif_CalculateTransitionOffsetFromBase(transitionType.UtcOffset, timeZoneBaseUtcOffset);
- TimeSpan daylightDelta = transitionType.IsDst ? transitionOffset : TimeSpan.Zero;
- TimeSpan baseUtcDelta = transitionType.IsDst ? TimeSpan.Zero : transitionOffset;
-
- AdjustmentRule r = AdjustmentRule.CreateAdjustmentRule(
- DateTime.MinValue,
- endTransitionDate.AddTicks(-1),
- daylightDelta,
- default(TransitionTime),
- default(TransitionTime),
- baseUtcDelta,
- noDaylightTransitions: true);
- rulesList.Add(r);
- }
- else if (index < dts.Length)
- {
- DateTime startTransitionDate = dts[index - 1];
- TZifType startTransitionType = transitionTypes[typeOfLocalTime[index - 1]];
-
- DateTime endTransitionDate = dts[index];
-
- TimeSpan transitionOffset = TZif_CalculateTransitionOffsetFromBase(startTransitionType.UtcOffset, timeZoneBaseUtcOffset);
- TimeSpan daylightDelta = startTransitionType.IsDst ? transitionOffset : TimeSpan.Zero;
- TimeSpan baseUtcDelta = startTransitionType.IsDst ? TimeSpan.Zero : transitionOffset;
-
- TransitionTime dstStart;
- if (startTransitionType.IsDst)
- {
- // the TransitionTime fields are not used when AdjustmentRule.NoDaylightTransitions == true.
- // However, there are some cases in the past where DST = true, and the daylight savings offset
- // now equals what the current BaseUtcOffset is. In that case, the AdjustmentRule.DaylightOffset
- // is going to be TimeSpan.Zero. But we still need to return 'true' from AdjustmentRule.HasDaylightSaving.
- // To ensure we always return true from HasDaylightSaving, make a "special" dstStart that will make the logic
- // in HasDaylightSaving return true.
- dstStart = TransitionTime.CreateFixedDateRule(DateTime.MinValue.AddMilliseconds(2), 1, 1);
- }
- else
- {
- dstStart = default(TransitionTime);
- }
-
- AdjustmentRule r = AdjustmentRule.CreateAdjustmentRule(
- startTransitionDate,
- endTransitionDate.AddTicks(-1),
- daylightDelta,
- dstStart,
- default(TransitionTime),
- baseUtcDelta,
- noDaylightTransitions: true);
- rulesList.Add(r);
- }
- else
- {
- // create the AdjustmentRule that will be used for all DateTimes after the last transition
-
- // NOTE: index == dts.Length
- DateTime startTransitionDate = dts[index - 1];
-
- if (!string.IsNullOrEmpty(futureTransitionsPosixFormat))
- {
- AdjustmentRule r = TZif_CreateAdjustmentRuleForPosixFormat(futureTransitionsPosixFormat, startTransitionDate, timeZoneBaseUtcOffset);
- if (r != null)
- {
- rulesList.Add(r);
- }
- }
- else
- {
- // just use the last transition as the rule which will be used until the end of time
-
- TZifType transitionType = transitionTypes[typeOfLocalTime[index - 1]];
- TimeSpan transitionOffset = TZif_CalculateTransitionOffsetFromBase(transitionType.UtcOffset, timeZoneBaseUtcOffset);
- TimeSpan daylightDelta = transitionType.IsDst ? transitionOffset : TimeSpan.Zero;
- TimeSpan baseUtcDelta = transitionType.IsDst ? TimeSpan.Zero : transitionOffset;
-
- AdjustmentRule r = AdjustmentRule.CreateAdjustmentRule(
- startTransitionDate,
- DateTime.MaxValue,
- daylightDelta,
- default(TransitionTime),
- default(TransitionTime),
- baseUtcDelta,
- noDaylightTransitions: true);
- rulesList.Add(r);
- }
- }
-
- index++;
- }
-
- private static TimeSpan TZif_CalculateTransitionOffsetFromBase(TimeSpan transitionOffset, TimeSpan timeZoneBaseUtcOffset)
- {
- TimeSpan result = transitionOffset - timeZoneBaseUtcOffset;
-
- // TZif supports seconds-level granularity with offsets but TimeZoneInfo only supports minutes since it aligns
- // with DateTimeOffset, SQL Server, and the W3C XML Specification
- if (result.Ticks % TimeSpan.TicksPerMinute != 0)
- {
- result = new TimeSpan(result.Hours, result.Minutes, 0);
- }
-
- return result;
- }
-
/// <summary>
- /// Gets the first standard-time transition type, or simply the first transition type
- /// if there are no standard transition types.
- /// </summary>>
- /// <remarks>
- /// from 'man tzfile':
- /// localtime(3) uses the first standard-time ttinfo structure in the file
- /// (or simply the first ttinfo structure in the absence of a standard-time
- /// structure) if either tzh_timecnt is zero or the time argument is less
- /// than the first transition time recorded in the file.
- /// </remarks>
- private static TZifType TZif_GetEarlyDateTransitionType(TZifType[] transitionTypes)
- {
- for (int i = 0; i < transitionTypes.Length; i++)
- {
- TZifType transitionType = transitionTypes[i];
- if (!transitionType.IsDst)
- {
- return transitionType;
- }
- }
-
- if (transitionTypes.Length > 0)
- {
- return transitionTypes[0];
- }
-
- throw new InvalidTimeZoneException(Environment.GetResourceString("InvalidTimeZone_NoTTInfoStructures"));
- }
-
- /// <summary>
- /// Creates an AdjustmentRule given the POSIX TZ environment variable string.
+ /// Helper function that validates the TimeSpan is within +/- 14.0 hours
/// </summary>
- /// <remarks>
- /// See http://www.gnu.org/software/libc/manual/html_node/TZ-Variable.html for the format and semantics of this POSX string.
- /// </remarks>
- private static AdjustmentRule TZif_CreateAdjustmentRuleForPosixFormat(string posixFormat, DateTime startTransitionDate, TimeSpan timeZoneBaseUtcOffset)
- {
- string standardName;
- string standardOffset;
- string daylightSavingsName;
- string daylightSavingsOffset;
- string start;
- string startTime;
- string end;
- string endTime;
-
- if (TZif_ParsePosixFormat(posixFormat, out standardName, out standardOffset, out daylightSavingsName,
- out daylightSavingsOffset, out start, out startTime, out end, out endTime))
- {
- // a valid posixFormat has at least standardName and standardOffset
-
- TimeSpan? parsedBaseOffset = TZif_ParseOffsetString(standardOffset);
- if (parsedBaseOffset.HasValue)
- {
- TimeSpan baseOffset = parsedBaseOffset.Value.Negate(); // offsets are backwards in POSIX notation
- baseOffset = TZif_CalculateTransitionOffsetFromBase(baseOffset, timeZoneBaseUtcOffset);
-
- // having a daylightSavingsName means there is a DST rule
- if (!string.IsNullOrEmpty(daylightSavingsName))
- {
- TimeSpan? parsedDaylightSavings = TZif_ParseOffsetString(daylightSavingsOffset);
- TimeSpan daylightSavingsTimeSpan;
- if (!parsedDaylightSavings.HasValue)
- {
- // default DST to 1 hour if it isn't specified
- daylightSavingsTimeSpan = new TimeSpan(1, 0, 0);
- }
- else
- {
- daylightSavingsTimeSpan = parsedDaylightSavings.Value.Negate(); // offsets are backwards in POSIX notation
- daylightSavingsTimeSpan = TZif_CalculateTransitionOffsetFromBase(daylightSavingsTimeSpan, timeZoneBaseUtcOffset);
- daylightSavingsTimeSpan = TZif_CalculateTransitionOffsetFromBase(daylightSavingsTimeSpan, baseOffset);
- }
-
- TransitionTime dstStart = TZif_CreateTransitionTimeFromPosixRule(start, startTime);
- TransitionTime dstEnd = TZif_CreateTransitionTimeFromPosixRule(end, endTime);
-
- return AdjustmentRule.CreateAdjustmentRule(
- startTransitionDate,
- DateTime.MaxValue,
- daylightSavingsTimeSpan,
- dstStart,
- dstEnd,
- baseOffset,
- noDaylightTransitions: false);
- }
- else
- {
- // if there is no daylightSavingsName, the whole AdjustmentRule should be with no transitions - just the baseOffset
- return AdjustmentRule.CreateAdjustmentRule(
- startTransitionDate,
- DateTime.MaxValue,
- TimeSpan.Zero,
- default(TransitionTime),
- default(TransitionTime),
- baseOffset,
- noDaylightTransitions: true);
- }
- }
- }
-
- return null;
- }
-
- private static TimeSpan? TZif_ParseOffsetString(string offset)
- {
- TimeSpan? result = null;
-
- if (!string.IsNullOrEmpty(offset))
- {
- bool negative = offset[0] == '-';
- if (negative || offset[0] == '+')
- {
- offset = offset.Substring(1);
- }
-
- // Try parsing just hours first.
- // Note, TimeSpan.TryParseExact "%h" can't be used here because some time zones using values
- // like "26" or "144" and TimeSpan parsing would turn that into 26 or 144 *days* instead of hours.
- int hours;
- if (int.TryParse(offset, out hours))
- {
- result = new TimeSpan(hours, 0, 0);
- }
- else
- {
- TimeSpan parsedTimeSpan;
- if (TimeSpan.TryParseExact(offset, "g", CultureInfo.InvariantCulture, out parsedTimeSpan))
- {
- result = parsedTimeSpan;
- }
- }
-
- if (result.HasValue && negative)
- {
- result = result.Value.Negate();
- }
- }
-
- return result;
- }
-
- private static TransitionTime TZif_CreateTransitionTimeFromPosixRule(string date, string time)
- {
- if (string.IsNullOrEmpty(date))
- {
- return default(TransitionTime);
- }
-
- if (date[0] == 'M')
- {
- // Mm.w.d
- // This specifies day d of week w of month m. The day d must be between 0(Sunday) and 6.The week w must be between 1 and 5;
- // week 1 is the first week in which day d occurs, and week 5 specifies the last d day in the month. The month m should be between 1 and 12.
-
- int month;
- int week;
- DayOfWeek day;
- if (!TZif_ParseMDateRule(date, out month, out week, out day))
- {
- throw new InvalidTimeZoneException(Environment.GetResourceString("InvalidTimeZone_UnparseablePosixMDateString", date));
- }
-
- DateTime timeOfDay;
- TimeSpan? timeOffset = TZif_ParseOffsetString(time);
- if (timeOffset.HasValue)
- {
- // This logic isn't correct and can't be corrected until https://github.com/dotnet/corefx/issues/2618 is fixed.
- // Some time zones use time values like, "26", "144", or "-2".
- // This allows the week to sometimes be week 4 and sometimes week 5 in the month.
- // For now, strip off any 'days' in the offset, and just get the time of day correct
- timeOffset = new TimeSpan(timeOffset.Value.Hours, timeOffset.Value.Minutes, timeOffset.Value.Seconds);
- if (timeOffset.Value < TimeSpan.Zero)
- {
- timeOfDay = new DateTime(1, 1, 2, 0, 0, 0);
- }
- else
- {
- timeOfDay = new DateTime(1, 1, 1, 0, 0, 0);
- }
-
- timeOfDay += timeOffset.Value;
- }
- else
- {
- // default to 2AM.
- timeOfDay = new DateTime(1, 1, 1, 2, 0, 0);
- }
-
- return TransitionTime.CreateFloatingDateRule(timeOfDay, month, week, day);
- }
- else
- {
- // Jn
- // This specifies the Julian day, with n between 1 and 365.February 29 is never counted, even in leap years.
-
- // n
- // This specifies the Julian day, with n between 0 and 365.February 29 is counted in leap years.
-
- // These two rules cannot be expressed with the current AdjustmentRules
- // One of them *could* be supported if we relaxed the TransitionTime validation rules, and allowed
- // "IsFixedDateRule = true, Month = 0, Day = n" to mean the nth day of the year, picking one of the rules above
-
- throw new InvalidTimeZoneException(Environment.GetResourceString("InvalidTimeZone_JulianDayNotSupported"));
- }
- }
+ [Pure]
+ internal static bool UtcOffsetOutOfRange(TimeSpan offset) =>
+ offset.TotalHours < -14.0 || offset.TotalHours > 14.0;
/// <summary>
- /// Parses a string like Mm.w.d into month, week and DayOfWeek values.
+ /// Helper function that performs all of the validation checks for the
+ /// factory methods and deserialization callback.
/// </summary>
- /// <returns>
- /// true if the parsing succeeded; otherwise, false.
- /// </returns>
- private static bool TZif_ParseMDateRule(string dateRule, out int month, out int week, out DayOfWeek dayOfWeek)
+ private static void ValidateTimeZoneInfo(string id, TimeSpan baseUtcOffset, AdjustmentRule[] adjustmentRules, out bool adjustmentRulesSupportDst)
{
- month = 0;
- week = 0;
- dayOfWeek = default(DayOfWeek);
-
- if (dateRule[0] == 'M')
+ if (id == null)
{
- int firstDotIndex = dateRule.IndexOf('.');
- if (firstDotIndex > 0)
- {
- int secondDotIndex = dateRule.IndexOf('.', firstDotIndex + 1);
- if (secondDotIndex > 0)
- {
- string monthString = dateRule.Substring(1, firstDotIndex - 1);
- string weekString = dateRule.Substring(firstDotIndex + 1, secondDotIndex - firstDotIndex - 1);
- string dayString = dateRule.Substring(secondDotIndex + 1);
-
- if (int.TryParse(monthString, out month))
- {
- if (int.TryParse(weekString, out week))
- {
- int day;
- if (int.TryParse(dayString, out day))
- {
- dayOfWeek = (DayOfWeek)day;
- return true;
- }
- }
- }
- }
- }
- }
-
- return false;
- }
-
- private static bool TZif_ParsePosixFormat(
- string posixFormat,
- out string standardName,
- out string standardOffset,
- out string daylightSavingsName,
- out string daylightSavingsOffset,
- out string start,
- out string startTime,
- out string end,
- out string endTime)
- {
- standardName = null;
- standardOffset = null;
- daylightSavingsName = null;
- daylightSavingsOffset = null;
- start = null;
- startTime = null;
- end = null;
- endTime = null;
-
- int index = 0;
- standardName = TZif_ParsePosixName(posixFormat, ref index);
- standardOffset = TZif_ParsePosixOffset(posixFormat, ref index);
-
- daylightSavingsName = TZif_ParsePosixName(posixFormat, ref index);
- if (!string.IsNullOrEmpty(daylightSavingsName))
- {
- daylightSavingsOffset = TZif_ParsePosixOffset(posixFormat, ref index);
-
- if (index < posixFormat.Length && posixFormat[index] == ',')
- {
- index++;
- TZif_ParsePosixDateTime(posixFormat, ref index, out start, out startTime);
-
- if (index < posixFormat.Length && posixFormat[index] == ',')
- {
- index++;
- TZif_ParsePosixDateTime(posixFormat, ref index, out end, out endTime);
- }
- }
- }
-
- return !string.IsNullOrEmpty(standardName) && !string.IsNullOrEmpty(standardOffset);
- }
-
- private static string TZif_ParsePosixName(string posixFormat, ref int index)
- {
- return TZif_ParsePosixString(posixFormat, ref index, c => char.IsDigit(c) || c == '+' || c == '-' || c == ',');
- }
-
- private static string TZif_ParsePosixOffset(string posixFormat, ref int index)
- {
- return TZif_ParsePosixString(posixFormat, ref index, c => !char.IsDigit(c) && c != '+' && c != '-' && c != ':');
- }
-
- private static void TZif_ParsePosixDateTime(string posixFormat, ref int index, out string date, out string time)
- {
- time = null;
-
- date = TZif_ParsePosixDate(posixFormat, ref index);
- if (index < posixFormat.Length && posixFormat[index] == '/')
- {
- index++;
- time = TZif_ParsePosixTime(posixFormat, ref index);
- }
- }
-
- private static string TZif_ParsePosixDate(string posixFormat, ref int index)
- {
- return TZif_ParsePosixString(posixFormat, ref index, c => c == '/' || c == ',');
- }
-
- private static string TZif_ParsePosixTime(string posixFormat, ref int index)
- {
- return TZif_ParsePosixString(posixFormat, ref index, c => c == ',');
- }
-
- private static string TZif_ParsePosixString(string posixFormat, ref int index, Func<char, bool> breakCondition)
- {
- int startIndex = index;
- for (; index < posixFormat.Length; index++)
- {
- char current = posixFormat[index];
- if (breakCondition(current))
- {
- break;
- }
- }
-
- return posixFormat.Substring(startIndex, index - startIndex);
- }
-
- // Returns the Substring from zoneAbbreviations starting at index and ending at '\0'
- // zoneAbbreviations is expected to be in the form: "PST\0PDT\0PWT\0\PPT"
- static private String TZif_GetZoneAbbreviation(String zoneAbbreviations, int index) {
- int lastIndex = zoneAbbreviations.IndexOf('\0', index);
- if (lastIndex > 0) {
- return zoneAbbreviations.Substring(index, lastIndex - index);
- }
- else {
- return zoneAbbreviations.Substring(index);
- }
- }
-
- // Converts an array of bytes into an int - always using standard byte order (Big Endian)
- // per TZif file standard
- 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));
- }
- }
-
- // Converts an array of bytes into a long - always using standard byte order (Big Endian)
- // per TZif file standard
- static private unsafe long TZif_ToInt64(byte[] value, int startIndex)
- {
- fixed (byte* pbyte = &value[startIndex])
- {
- int i1 = (*pbyte << 24) | (*(pbyte + 1) << 16) | (*(pbyte + 2) << 8) | (*(pbyte + 3));
- int i2 = (*(pbyte + 4) << 24) | (*(pbyte + 5) << 16) | (*(pbyte + 6) << 8) | (*(pbyte + 7));
- return (uint)i2 | ((long)i1 << 32);
- }
- }
-
- static private long TZif_ToUnixTime(byte[] value, int startIndex, TZVersion version)
- {
- if (version != TZVersion.V1)
- {
- return TZif_ToInt64(value, startIndex);
- }
- else
- {
- return TZif_ToInt32(value, startIndex);
- }
- }
-
- private static DateTime TZif_UnixTimeToDateTime(long unixTime)
- {
- if (unixTime < DateTimeOffset.UnixMinSeconds)
- {
- return DateTime.MinValue;
- }
-
- if (unixTime > DateTimeOffset.UnixMaxSeconds)
- {
- return DateTime.MaxValue;
- }
-
- return DateTimeOffset.FromUnixTimeSeconds(unixTime).UtcDateTime;
- }
-
- static private void TZif_ParseRaw(Byte[] data, out TZifHead t, out DateTime[] dts, out Byte[] typeOfLocalTime, out TZifType[] transitionType,
- out String zoneAbbreviations, out Boolean[] StandardTime, out Boolean[] GmtTime, out string futureTransitionsPosixFormat)
- {
- // initialize the out parameters in case the TZifHead ctor throws
- dts = null;
- typeOfLocalTime = null;
- transitionType = null;
- zoneAbbreviations = String.Empty;
- StandardTime = null;
- GmtTime = null;
- futureTransitionsPosixFormat = null;
-
- // read in the 44-byte TZ header containing the count/length fields
- //
- int index = 0;
- t = new TZifHead(data, index);
- index += TZifHead.Length;
-
- int timeValuesLength = 4; // the first version uses 4-bytes to specify times
- if (t.Version != TZVersion.V1)
- {
- // move index past the V1 information to read the V2 information
- index += (int)((timeValuesLength * t.TimeCount) + t.TimeCount + (6 * t.TypeCount) + ((timeValuesLength + 4) * t.LeapCount) + t.IsStdCount + t.IsGmtCount + t.CharCount);
-
- // read the V2 header
- t = new TZifHead(data, index);
- index += TZifHead.Length;
- timeValuesLength = 8; // the second version uses 8-bytes
- }
-
- // initialize the containers for the rest of the TZ data
- dts = new DateTime[t.TimeCount];
- typeOfLocalTime = new Byte[t.TimeCount];
- transitionType = new TZifType[t.TypeCount];
- zoneAbbreviations = String.Empty;
- StandardTime = new Boolean[t.TypeCount];
- GmtTime = new Boolean[t.TypeCount];
-
- // read in the UTC transition points and convert them to Windows
- //
- for (int i = 0; i < t.TimeCount; i++) {
- long unixTime = TZif_ToUnixTime(data, index, t.Version);
- dts[i] = TZif_UnixTimeToDateTime(unixTime);
- index += timeValuesLength;
- }
-
- // read in the Type Indices; there is a 1:1 mapping of UTC transition points to Type Indices
- // these indices directly map to the array index in the transitionType array below
- //
- for (int i = 0; i < t.TimeCount; i++) {
- typeOfLocalTime[i] = data[index];
- index += 1;
- }
-
- // read in the Type table. Each 6-byte entry represents
- // {UtcOffset, IsDst, AbbreviationIndex}
- //
- // each AbbreviationIndex is a character index into the zoneAbbreviations string below
- //
- for (int i = 0; i < t.TypeCount; i++) {
- transitionType[i] = new TZifType(data, index);
- index += 6;
- }
-
- // read in the Abbreviation ASCII string. This string will be in the form:
- // "PST\0PDT\0PWT\0\PPT"
- //
- System.Text.Encoding enc = new System.Text.UTF8Encoding();
- zoneAbbreviations = enc.GetString(data, index, (int)t.CharCount);
- index += (int)t.CharCount;
-
- // skip ahead of the Leap-Seconds Adjustment data. In a future release, consider adding
- // support for Leap-Seconds
- //
- index += (int)(t.LeapCount * (timeValuesLength + 4)); // skip the leap second transition times
-
- // read in the Standard Time table. There should be a 1:1 mapping between Type-Index and Standard
- // Time table entries.
- //
- // TRUE = transition time is standard time
- // FALSE = transition time is wall clock time
- // ABSENT = transition time is wall clock time
- //
- for (int i = 0; i < t.IsStdCount && i < t.TypeCount && index < data.Length; i++) {
- StandardTime[i] = (data[index++] != 0);
- }
-
- // read in the GMT Time table. There should be a 1:1 mapping between Type-Index and GMT Time table
- // entries.
- //
- // TRUE = transition time is UTC
- // FALSE = transition time is local time
- // ABSENT = transition time is local time
- //
- for (int i = 0; i < t.IsGmtCount && i < t.TypeCount && index < data.Length; i++) {
- GmtTime[i] = (data[index++] != 0);
- }
-
- if (t.Version != TZVersion.V1)
- {
- // read the POSIX-style format, which should be wrapped in newlines with the last newline at the end of the file
- if (data[index++] == '\n' && data[data.Length - 1] == '\n')
- {
- futureTransitionsPosixFormat = enc.GetString(data, index, data.Length - index - 1);
- }
- }
- }
-#endif // PLATFORM_UNIX
-
- //
- // UtcOffsetOutOfRange -
- //
- // Helper function that validates the TimeSpan is within +/- 14.0 hours
- //
- [Pure]
- static internal Boolean UtcOffsetOutOfRange(TimeSpan offset) {
- return (offset.TotalHours < -14.0 || offset.TotalHours > 14.0);
- }
-
-
- //
- // ValidateTimeZoneInfo -
- //
- // Helper function that performs all of the validation checks for the
- // factory methods and deserialization callback
- //
- // returns a Boolean indicating whether the AdjustmentRule[] supports DST
- //
- static private void ValidateTimeZoneInfo(
- String id,
- TimeSpan baseUtcOffset,
- AdjustmentRule [] adjustmentRules,
- out Boolean adjustmentRulesSupportDst) {
-
- if (id == null) {
throw new ArgumentNullException(nameof(id));
}
- if (id.Length == 0) {
+ if (id.Length == 0)
+ {
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidId", id), nameof(id));
}
- if (UtcOffsetOutOfRange(baseUtcOffset)) {
+ if (UtcOffsetOutOfRange(baseUtcOffset))
+ {
throw new ArgumentOutOfRangeException(nameof(baseUtcOffset), Environment.GetResourceString("ArgumentOutOfRange_UtcOffset"));
}
- if (baseUtcOffset.Ticks % TimeSpan.TicksPerMinute != 0) {
+ if (baseUtcOffset.Ticks % TimeSpan.TicksPerMinute != 0)
+ {
throw new ArgumentException(Environment.GetResourceString("Argument_TimeSpanHasSeconds"), nameof(baseUtcOffset));
}
Contract.EndContractBlock();
@@ -4379,15 +1907,18 @@ namespace System {
// are sorted in chronological order
//
- if (adjustmentRules != null && adjustmentRules.Length != 0) {
+ if (adjustmentRules != null && adjustmentRules.Length != 0)
+ {
adjustmentRulesSupportDst = true;
AdjustmentRule prev = null;
AdjustmentRule current = null;
- for (int i = 0; i < adjustmentRules.Length; i++) {
+ for (int i = 0; i < adjustmentRules.Length; i++)
+ {
prev = current;
current = adjustmentRules[i];
- if (current == null) {
+ if (current == null)
+ {
throw new InvalidTimeZoneException(Environment.GetResourceString("Argument_AdjustmentRulesNoNulls"));
}
@@ -4395,1308 +1926,18 @@ namespace System {
// adjustmentRulesSupportDst = adjustmentRulesSupportDst || current.SupportsDaylightSavingTime;
// FUTURE: test baseUtcOffset + current.StandardDelta
- if (UtcOffsetOutOfRange(baseUtcOffset + current.DaylightDelta)) {
+ if (UtcOffsetOutOfRange(baseUtcOffset + current.DaylightDelta))
+ {
throw new InvalidTimeZoneException(Environment.GetResourceString("ArgumentOutOfRange_UtcOffsetAndDaylightDelta"));
}
- if (prev != null && current.DateStart <= prev.DateEnd) {
+ if (prev != null && current.DateStart <= prev.DateEnd)
+ {
// verify the rules are in chronological order and the DateStart/DateEnd do not overlap
throw new InvalidTimeZoneException(Environment.GetResourceString("Argument_AdjustmentRulesOutOfOrder"));
}
}
}
}
-
-/*============================================================
-**
-** Class: TimeZoneInfo.AdjustmentRule
-**
-**
-** Purpose:
-** This class is used to represent a Dynamic TimeZone. It
-** has methods for converting a DateTime to UTC from local time
-** and to local time from UTC and methods for getting the
-** standard name and daylight name of the time zone.
-**
-**
-============================================================*/
- [Serializable]
- [System.Security.Permissions.HostProtection(MayLeakOnAbort = true)]
- sealed public class AdjustmentRule : IEquatable<AdjustmentRule>, ISerializable, IDeserializationCallback
- {
-
- // ---- SECTION: members supporting exposed properties -------------*
- 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 {
- get {
- return this.m_dateStart;
- }
- }
-
- public DateTime DateEnd {
- get {
- return this.m_dateEnd;
- }
- }
-
- public TimeSpan DaylightDelta {
- get {
- return this.m_daylightDelta;
- }
- }
-
-
- public TransitionTime DaylightTransitionStart {
- get {
- return this.m_daylightTransitionStart;
- }
- }
-
-
- public TransitionTime DaylightTransitionEnd {
- get {
- return this.m_daylightTransitionEnd;
- }
- }
-
- internal TimeSpan BaseUtcOffsetDelta {
- get {
- return this.m_baseUtcOffsetDelta;
- }
- }
-
- /// <summary>
- /// Gets a value indicating that this AdjustmentRule fixes the time zone offset
- /// from DateStart to DateEnd without any daylight transitions in between.
- /// </summary>
- internal bool NoDaylightTransitions {
- get {
- return this.m_noDaylightTransitions;
- }
- }
-
- internal bool HasDaylightSaving {
- get {
- return this.DaylightDelta != TimeSpan.Zero
- ||
- (this.DaylightTransitionStart != default(TransitionTime)
- && this.DaylightTransitionStart.TimeOfDay != DateTime.MinValue)
- ||
- (this.DaylightTransitionEnd != default(TransitionTime)
- && this.DaylightTransitionEnd.TimeOfDay != DateTime.MinValue.AddMilliseconds(1));
- }
- }
-
- // ---- SECTION: public methods --------------*
-
- // IEquatable<AdjustmentRule>
- public bool Equals(AdjustmentRule other) {
- 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);
- }
-
-
- public override int GetHashCode() {
- return m_dateStart.GetHashCode();
- }
-
-
-
- // -------- SECTION: constructors -----------------*
-
- private AdjustmentRule(
- DateTime dateStart,
- DateTime dateEnd,
- TimeSpan daylightDelta,
- TransitionTime daylightTransitionStart,
- TransitionTime daylightTransitionEnd,
- TimeSpan baseUtcOffsetDelta,
- bool noDaylightTransitions)
- {
- ValidateAdjustmentRule(dateStart, dateEnd, daylightDelta,
- daylightTransitionStart, daylightTransitionEnd, noDaylightTransitions);
-
- m_dateStart = dateStart;
- m_dateEnd = dateEnd;
- m_daylightDelta = daylightDelta;
- m_daylightTransitionStart = daylightTransitionStart;
- m_daylightTransitionEnd = daylightTransitionEnd;
- m_baseUtcOffsetDelta = baseUtcOffsetDelta;
- m_noDaylightTransitions = noDaylightTransitions;
- }
-
-
- // -------- SECTION: factory methods -----------------*
-
- static public AdjustmentRule CreateAdjustmentRule(
- DateTime dateStart,
- DateTime dateEnd,
- TimeSpan daylightDelta,
- TransitionTime daylightTransitionStart,
- TransitionTime daylightTransitionEnd)
- {
- return new AdjustmentRule(
- dateStart,
- dateEnd,
- daylightDelta,
- daylightTransitionStart,
- daylightTransitionEnd,
- baseUtcOffsetDelta: TimeSpan.Zero,
- noDaylightTransitions: false);
- }
-
- static internal AdjustmentRule CreateAdjustmentRule(
- DateTime dateStart,
- DateTime dateEnd,
- TimeSpan daylightDelta,
- TransitionTime daylightTransitionStart,
- TransitionTime daylightTransitionEnd,
- TimeSpan baseUtcOffsetDelta,
- bool noDaylightTransitions)
- {
- return new AdjustmentRule(
- dateStart,
- dateEnd,
- daylightDelta,
- daylightTransitionStart,
- daylightTransitionEnd,
- baseUtcOffsetDelta,
- noDaylightTransitions);
- }
-
- // ----- SECTION: internal utility methods ----------------*
-
- //
- // When Windows sets the daylight transition start Jan 1st at 12:00 AM, it means the year starts with the daylight saving on.
- // We have to special case this value and not adjust it when checking if any date is in the daylight saving period.
- //
- internal bool IsStartDateMarkerForBeginningOfYear() {
- return !NoDaylightTransitions &&
- DaylightTransitionStart.Month == 1 && DaylightTransitionStart.Day == 1 && DaylightTransitionStart.TimeOfDay.Hour == 0 &&
- DaylightTransitionStart.TimeOfDay.Minute == 0 && DaylightTransitionStart.TimeOfDay.Second == 0 &&
- m_dateStart.Year == m_dateEnd.Year;
- }
-
- //
- // When Windows sets the daylight transition end Jan 1st at 12:00 AM, it means the year ends with the daylight saving on.
- // We have to special case this value and not adjust it when checking if any date is in the daylight saving period.
- //
- internal bool IsEndDateMarkerForEndOfYear() {
- return !NoDaylightTransitions &&
- DaylightTransitionEnd.Month == 1 && DaylightTransitionEnd.Day == 1 && DaylightTransitionEnd.TimeOfDay.Hour == 0 &&
- DaylightTransitionEnd.TimeOfDay.Minute == 0 && DaylightTransitionEnd.TimeOfDay.Second == 0 &&
- m_dateStart.Year == m_dateEnd.Year;
- }
-
- //
- // ValidateAdjustmentRule -
- //
- // Helper function that performs all of the validation checks for the
- // factory methods and deserialization callback
- //
- static private void ValidateAdjustmentRule(
- DateTime dateStart,
- DateTime dateEnd,
- TimeSpan daylightDelta,
- TransitionTime daylightTransitionStart,
- TransitionTime daylightTransitionEnd,
- bool noDaylightTransitions) {
-
-
- if (dateStart.Kind != DateTimeKind.Unspecified && dateStart.Kind != DateTimeKind.Utc) {
- 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"), nameof(dateEnd));
- }
-
- if (daylightTransitionStart.Equals(daylightTransitionEnd) && !noDaylightTransitions) {
- throw new ArgumentException(Environment.GetResourceString("Argument_TransitionTimesAreIdentical"),
- nameof(daylightTransitionEnd));
- }
-
-
- if (dateStart > dateEnd) {
- 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,
- // which caused their current BaseUtcOffset to be +13. But on the other side of the line it was UTC-11 (+1 for daylight).
- // 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(nameof(daylightDelta), daylightDelta,
- Environment.GetResourceString("ArgumentOutOfRange_UtcOffset"));
- }
-
- if (daylightDelta.Ticks % TimeSpan.TicksPerMinute != 0) {
- throw new ArgumentException(Environment.GetResourceString("Argument_TimeSpanHasSeconds"),
- nameof(daylightDelta));
- }
-
- if (dateStart != DateTime.MinValue && dateStart.Kind == DateTimeKind.Unspecified && dateStart.TimeOfDay != TimeSpan.Zero) {
- throw new ArgumentException(Environment.GetResourceString("Argument_DateTimeHasTimeOfDay"),
- nameof(dateStart));
- }
-
- if (dateEnd != DateTime.MaxValue && dateEnd.Kind == DateTimeKind.Unspecified && dateEnd.TimeOfDay != TimeSpan.Zero) {
- throw new ArgumentException(Environment.GetResourceString("Argument_DateTimeHasTimeOfDay"),
- nameof(dateEnd));
- }
- Contract.EndContractBlock();
- }
-
-
-
- // ----- SECTION: private serialization instance methods ----------------*
-
- void IDeserializationCallback.OnDeserialization(Object sender) {
- // OnDeserialization is called after each instance of this class is deserialized.
- // This callback method performs AdjustmentRule validation after being deserialized.
-
- try {
- ValidateAdjustmentRule(m_dateStart, m_dateEnd, m_daylightDelta,
- m_daylightTransitionStart, m_daylightTransitionEnd, m_noDaylightTransitions);
- }
- catch (ArgumentException e) {
- throw new SerializationException(Environment.GetResourceString("Serialization_InvalidData"), e);
- }
- }
-
- void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context) {
- if (info == null) {
- throw new ArgumentNullException(nameof(info));
- }
- Contract.EndContractBlock();
-
- info.AddValue("DateStart", m_dateStart);
- info.AddValue("DateEnd", m_dateEnd);
- info.AddValue("DaylightDelta", m_daylightDelta);
- info.AddValue("DaylightTransitionStart", m_daylightTransitionStart);
- info.AddValue("DaylightTransitionEnd", m_daylightTransitionEnd);
- info.AddValue("BaseUtcOffsetDelta", m_baseUtcOffsetDelta);
- info.AddValue("NoDaylightTransitions", m_noDaylightTransitions);
- }
-
- AdjustmentRule(SerializationInfo info, StreamingContext context) {
- if (info == null) {
- throw new ArgumentNullException(nameof(info));
- }
-
- m_dateStart = (DateTime)info.GetValue("DateStart", typeof(DateTime));
- m_dateEnd = (DateTime)info.GetValue("DateEnd", typeof(DateTime));
- m_daylightDelta = (TimeSpan)info.GetValue("DaylightDelta", typeof(TimeSpan));
- m_daylightTransitionStart = (TransitionTime)info.GetValue("DaylightTransitionStart", typeof(TransitionTime));
- m_daylightTransitionEnd = (TransitionTime)info.GetValue("DaylightTransitionEnd", typeof(TransitionTime));
-
- object o = info.GetValueNoThrow("BaseUtcOffsetDelta", typeof(TimeSpan));
- if (o != null) {
- m_baseUtcOffsetDelta = (TimeSpan) o;
- }
-
- o = info.GetValueNoThrow("NoDaylightTransitions", typeof(bool));
- if (o != null) {
- m_noDaylightTransitions = (bool)o;
- }
- }
- }
-
-
-/*============================================================
-**
-** Class: TimeZoneInfo.TransitionTime
-**
-**
-** Purpose:
-** This class is used to represent a Dynamic TimeZone. It
-** has methods for converting a DateTime to UTC from local time
-** and to local time from UTC and methods for getting the
-** standard name and daylight name of the time zone.
-**
-**
-============================================================*/
- [Serializable]
- [System.Security.Permissions.HostProtection(MayLeakOnAbort = true)]
- public struct TransitionTime : IEquatable<TransitionTime>, ISerializable, IDeserializationCallback
- {
- // ---- SECTION: members supporting exposed properties -------------*
- 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 --------------*
- public DateTime TimeOfDay {
- get {
- return m_timeOfDay;
- }
- }
-
- public Int32 Month {
- get {
- return (int)m_month;
- }
- }
-
-
- public Int32 Week {
- get {
- return (int)m_week;
- }
- }
-
- public Int32 Day {
- get {
- return (int)m_day;
- }
- }
-
- public DayOfWeek DayOfWeek {
- get {
- return m_dayOfWeek;
- }
- }
-
- public Boolean IsFixedDateRule {
- get {
- return m_isFixedDateRule;
- }
- }
-
- // ---- SECTION: public methods --------------*
- [Pure]
- public override bool Equals(Object obj) {
- if (obj is TransitionTime) {
- return Equals((TransitionTime)obj);
- }
- return false;
- }
-
- public static bool operator ==(TransitionTime t1, TransitionTime t2) {
- return t1.Equals(t2);
- }
-
- public static bool operator !=(TransitionTime t1, TransitionTime t2) {
- return (!t1.Equals(t2));
- }
-
- [Pure]
- public bool Equals(TransitionTime other) {
-
- bool equal = (this.m_isFixedDateRule == other.m_isFixedDateRule
- && this.m_timeOfDay == other.m_timeOfDay
- && this.m_month == other.m_month);
-
- if (equal) {
- if (other.m_isFixedDateRule) {
- equal = (this.m_day == other.m_day);
- }
- else {
- equal = (this.m_week == other.m_week
- && this.m_dayOfWeek == other.m_dayOfWeek);
- }
- }
- return equal;
- }
-
-
- public override int GetHashCode() {
- return ((int)m_month ^ (int)m_week << 8);
- }
-
-
- // -------- SECTION: constructors -----------------*
-
- 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 -----------------*
-
-
- static public TransitionTime CreateFixedDateRule(
- DateTime timeOfDay,
- Int32 month,
- Int32 day) {
-
- return new TransitionTime(timeOfDay, month, 1, day, DayOfWeek.Sunday, isFixedDateRule: true);
- }
-
-
- static public TransitionTime CreateFloatingDateRule(
- DateTime timeOfDay,
- Int32 month,
- Int32 week,
- DayOfWeek dayOfWeek) {
-
- return new TransitionTime(timeOfDay, month, week, 1, dayOfWeek, isFixedDateRule: false);
- }
-
-
- // ----- SECTION: internal utility methods ----------------*
-
- //
- // ValidateTransitionTime -
- //
- // Helper function that validates a TransitionTime instance
- //
- static private void ValidateTransitionTime(
- DateTime timeOfDay,
- Int32 month,
- Int32 week,
- Int32 day,
- DayOfWeek dayOfWeek) {
-
- if (timeOfDay.Kind != DateTimeKind.Unspecified) {
- throw new ArgumentException(Environment.GetResourceString("Argument_DateTimeKindMustBeUnspecified"), nameof(timeOfDay));
- }
-
- // Month range 1-12
- if (month < 1 || month > 12) {
- throw new ArgumentOutOfRangeException(nameof(month), Environment.GetResourceString("ArgumentOutOfRange_MonthParam"));
- }
-
- // Day range 1-31
- if (day < 1 || day > 31) {
- throw new ArgumentOutOfRangeException(nameof(day), Environment.GetResourceString("ArgumentOutOfRange_DayParam"));
- }
-
- // Week range 1-5
- if (week < 1 || week > 5) {
- throw new ArgumentOutOfRangeException(nameof(week), Environment.GetResourceString("ArgumentOutOfRange_Week"));
- }
-
- // DayOfWeek range 0-6
- if ((int)dayOfWeek < 0 || (int)dayOfWeek > 6) {
- 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"), nameof(timeOfDay));
- }
- }
-
- void IDeserializationCallback.OnDeserialization(Object sender) {
- // OnDeserialization is called after each instance of this class is deserialized.
- // This callback method performs TransitionTime validation after being deserialized.
-
- try {
- ValidateTransitionTime(m_timeOfDay, (Int32)m_month, (Int32)m_week, (Int32)m_day, m_dayOfWeek);
- }
- catch (ArgumentException e) {
- throw new SerializationException(Environment.GetResourceString("Serialization_InvalidData"), e);
- }
- }
-
-
- void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context) {
- if (info == null) {
- throw new ArgumentNullException(nameof(info));
- }
- Contract.EndContractBlock();
-
- info.AddValue("TimeOfDay", m_timeOfDay);
- info.AddValue("Month", m_month);
- info.AddValue("Week", m_week);
- info.AddValue("Day", m_day);
- info.AddValue("DayOfWeek", m_dayOfWeek);
- info.AddValue("IsFixedDateRule", m_isFixedDateRule);
- }
-
- TransitionTime(SerializationInfo info, StreamingContext context) {
- if (info == null) {
- throw new ArgumentNullException(nameof(info));
- }
-
- m_timeOfDay = (DateTime)info.GetValue("TimeOfDay", typeof(DateTime));
- m_month = (byte)info.GetValue("Month", typeof(byte));
- m_week = (byte)info.GetValue("Week", typeof(byte));
- m_day = (byte)info.GetValue("Day", typeof(byte));
- m_dayOfWeek = (DayOfWeek)info.GetValue("DayOfWeek", typeof(DayOfWeek));
- m_isFixedDateRule = (Boolean)info.GetValue("IsFixedDateRule", typeof(Boolean));
- }
- }
-
-
-/*============================================================
-**
-** Class: TimeZoneInfo.StringSerializer
-**
-**
-** Purpose:
-** This class is used to serialize and deserialize TimeZoneInfo
-** objects based on the custom string serialization format
-**
-**
-============================================================*/
- sealed private class StringSerializer {
-
- // ---- SECTION: private members -------------*
- private enum State {
- Escaped = 0,
- NotEscaped = 1,
- StartOfToken = 2,
- EndOfLine = 3
- }
-
- private String m_serializedText;
- private int m_currentTokenStartIndex;
- private State m_state;
-
- // the majority of the strings contained in the OS time zones fit in 64 chars
- private const int initialCapacityForString = 64;
- private const char esc = '\\';
- private const char sep = ';';
- private const char lhs = '[';
- private const char rhs = ']';
- private const string escString = "\\";
- private const string sepString = ";";
- private const string lhsString = "[";
- private const string rhsString = "]";
- private const string escapedEsc = "\\\\";
- private const string escapedSep = "\\;";
- private const string escapedLhs = "\\[";
- private const string escapedRhs = "\\]";
- private const string dateTimeFormat = "MM:dd:yyyy";
- private const string timeOfDayFormat = "HH:mm:ss.FFF";
-
-
- // ---- SECTION: public static methods --------------*
-
- //
- // GetSerializedString -
- //
- // static method that creates the custom serialized string
- // representation of a TimeZoneInfo instance
- //
- static public String GetSerializedString(TimeZoneInfo zone) {
- StringBuilder serializedText = StringBuilderCache.Acquire();
-
- //
- // <m_id>;<m_baseUtcOffset>;<m_displayName>;<m_standardDisplayName>;<m_daylightDispayName>
- //
- serializedText.Append(SerializeSubstitute(zone.Id));
- serializedText.Append(sep);
- serializedText.Append(SerializeSubstitute(
- zone.BaseUtcOffset.TotalMinutes.ToString(CultureInfo.InvariantCulture)));
- serializedText.Append(sep);
- serializedText.Append(SerializeSubstitute(zone.DisplayName));
- serializedText.Append(sep);
- serializedText.Append(SerializeSubstitute(zone.StandardName));
- serializedText.Append(sep);
- serializedText.Append(SerializeSubstitute(zone.DaylightName));
- serializedText.Append(sep);
-
- AdjustmentRule[] rules = zone.GetAdjustmentRules();
-
- if (rules != null && rules.Length > 0) {
- for (int i = 0; i < rules.Length; i++) {
- AdjustmentRule rule = rules[i];
-
- serializedText.Append(lhs);
- serializedText.Append(SerializeSubstitute(rule.DateStart.ToString(
- dateTimeFormat, DateTimeFormatInfo.InvariantInfo)));
- serializedText.Append(sep);
- serializedText.Append(SerializeSubstitute(rule.DateEnd.ToString(
- dateTimeFormat, DateTimeFormatInfo.InvariantInfo)));
- serializedText.Append(sep);
- serializedText.Append(SerializeSubstitute(rule.DaylightDelta.TotalMinutes.ToString(CultureInfo.InvariantCulture)));
- serializedText.Append(sep);
- // serialize the TransitionTime's
- SerializeTransitionTime(rule.DaylightTransitionStart, serializedText);
- serializedText.Append(sep);
- SerializeTransitionTime(rule.DaylightTransitionEnd, serializedText);
- serializedText.Append(sep);
- if (rule.BaseUtcOffsetDelta != TimeSpan.Zero) { // Serialize it only when BaseUtcOffsetDelta has a value to reduce the impact of adding rule.BaseUtcOffsetDelta
- serializedText.Append(SerializeSubstitute(rule.BaseUtcOffsetDelta.TotalMinutes.ToString(CultureInfo.InvariantCulture)));
- serializedText.Append(sep);
- }
- if (rule.NoDaylightTransitions) { // Serialize it only when NoDaylightTransitions is true to reduce the impact of adding rule.NoDaylightTransitions
- serializedText.Append(SerializeSubstitute("1"));
- serializedText.Append(sep);
- }
- serializedText.Append(rhs);
- }
- }
- serializedText.Append(sep);
- return StringBuilderCache.GetStringAndRelease(serializedText);
- }
-
-
- //
- // GetDeserializedTimeZoneInfo -
- //
- // static method that instantiates a TimeZoneInfo from a custom serialized
- // string
- //
- static public TimeZoneInfo GetDeserializedTimeZoneInfo(String source) {
- StringSerializer s = new StringSerializer(source);
-
- String id = s.GetNextStringValue(false);
- TimeSpan baseUtcOffset = s.GetNextTimeSpanValue(false);
- String displayName = s.GetNextStringValue(false);
- String standardName = s.GetNextStringValue(false);
- String daylightName = s.GetNextStringValue(false);
- AdjustmentRule[] rules = s.GetNextAdjustmentRuleArrayValue(false);
-
- try {
- return new TimeZoneInfo(id, baseUtcOffset, displayName, standardName, daylightName, rules, disableDaylightSavingTime: false);
- }
- catch (ArgumentException ex) {
- throw new SerializationException(Environment.GetResourceString("Serialization_InvalidData"), ex);
- }
- catch (InvalidTimeZoneException ex) {
- throw new SerializationException(Environment.GetResourceString("Serialization_InvalidData"), ex);
- }
- }
-
- // ---- SECTION: public instance methods --------------*
-
-
- // -------- SECTION: constructors -----------------*
-
- //
- // StringSerializer -
- //
- // private constructor - used by GetDeserializedTimeZoneInfo()
- //
- private StringSerializer(String str) {
- m_serializedText = str;
- m_state = State.StartOfToken;
- }
-
-
-
- // ----- SECTION: internal static utility methods ----------------*
-
- //
- // SerializeSubstitute -
- //
- // returns a new string with all of the reserved sub-strings escaped
- //
- // ";" -> "\;"
- // "[" -> "\["
- // "]" -> "\]"
- // "\" -> "\\"
- //
- static private String SerializeSubstitute(String text) {
- text = text.Replace(escString, escapedEsc);
- text = text.Replace(lhsString, escapedLhs);
- text = text.Replace(rhsString, escapedRhs);
- return text.Replace(sepString, escapedSep);
- }
-
-
- //
- // SerializeTransitionTime -
- //
- // Helper method to serialize a TimeZoneInfo.TransitionTime object
- //
- static private void SerializeTransitionTime(TransitionTime time, StringBuilder serializedText) {
- serializedText.Append(lhs);
- Int32 fixedDate = (time.IsFixedDateRule ? 1 : 0);
- serializedText.Append(fixedDate.ToString(CultureInfo.InvariantCulture));
- serializedText.Append(sep);
-
- if (time.IsFixedDateRule) {
- serializedText.Append(SerializeSubstitute(time.TimeOfDay.ToString(timeOfDayFormat, DateTimeFormatInfo.InvariantInfo)));
- serializedText.Append(sep);
- serializedText.Append(SerializeSubstitute(time.Month.ToString(CultureInfo.InvariantCulture)));
- serializedText.Append(sep);
- serializedText.Append(SerializeSubstitute(time.Day.ToString(CultureInfo.InvariantCulture)));
- serializedText.Append(sep);
- }
- else {
- serializedText.Append(SerializeSubstitute(time.TimeOfDay.ToString(timeOfDayFormat, DateTimeFormatInfo.InvariantInfo)));
- serializedText.Append(sep);
- serializedText.Append(SerializeSubstitute(time.Month.ToString(CultureInfo.InvariantCulture)));
- serializedText.Append(sep);
- serializedText.Append(SerializeSubstitute(time.Week.ToString(CultureInfo.InvariantCulture)));
- serializedText.Append(sep);
- serializedText.Append(SerializeSubstitute(((int)time.DayOfWeek).ToString(CultureInfo.InvariantCulture)));
- serializedText.Append(sep);
- }
- serializedText.Append(rhs);
- }
-
- //
- // VerifyIsEscapableCharacter -
- //
- // Helper function to determine if the passed in string token is allowed to be preceeded by an escape sequence token
- //
- static private void VerifyIsEscapableCharacter(char c) {
- if (c != esc && c != sep && c != lhs && c != rhs) {
- throw new SerializationException(Environment.GetResourceString("Serialization_InvalidEscapeSequence", c));
- }
- }
-
- // ----- SECTION: internal instance utility methods ----------------*
-
- //
- // SkipVersionNextDataFields -
- //
- // Helper function that reads past "v.Next" data fields. Receives a "depth" parameter indicating the
- // current relative nested bracket depth that m_currentTokenStartIndex is at. The function ends
- // successfully when "depth" returns to zero (0).
- //
- //
- private void SkipVersionNextDataFields(Int32 depth /* starting depth in the nested brackets ('[', ']')*/) {
- if (m_currentTokenStartIndex < 0 || m_currentTokenStartIndex >= m_serializedText.Length) {
- throw new SerializationException(Environment.GetResourceString("Serialization_InvalidData"));
- }
- State tokenState = State.NotEscaped;
-
- // walk the serialized text, building up the token as we go...
- for (int i = m_currentTokenStartIndex; i < m_serializedText.Length; i++) {
- if (tokenState == State.Escaped) {
- VerifyIsEscapableCharacter(m_serializedText[i]);
- tokenState = State.NotEscaped;
- }
- else if (tokenState == State.NotEscaped) {
- switch (m_serializedText[i]) {
- case esc:
- tokenState = State.Escaped;
- break;
-
- case lhs:
- depth++;
- break;
- case rhs:
- depth--;
- if (depth == 0) {
- m_currentTokenStartIndex = i + 1;
- if (m_currentTokenStartIndex >= m_serializedText.Length) {
- m_state = State.EndOfLine;
- }
- else {
- m_state = State.StartOfToken;
- }
- return;
- }
- break;
-
- case '\0':
- // invalid character
- throw new SerializationException(Environment.GetResourceString("Serialization_InvalidData"));
-
- default:
- break;
- }
- }
- }
-
- throw new SerializationException(Environment.GetResourceString("Serialization_InvalidData"));
- }
-
-
- //
- // GetNextStringValue -
- //
- // Helper function that reads a string token from the serialized text. The function
- // updates the m_currentTokenStartIndex to point to the next token on exit. Also m_state
- // is set to either State.StartOfToken or State.EndOfLine on exit.
- //
- // The function takes a parameter "canEndWithoutSeparator".
- //
- // * When set to 'false' the function requires the string token end with a ";".
- // * When set to 'true' the function requires that the string token end with either
- // ";", State.EndOfLine, or "]". In the case that "]" is the terminal case the
- // m_currentTokenStartIndex is left pointing at index "]" to allow the caller to update
- // its depth logic.
- //
- private String GetNextStringValue(Boolean canEndWithoutSeparator) {
-
- // first verify the internal state of the object
- if (m_state == State.EndOfLine) {
- if (canEndWithoutSeparator) {
- return null;
- }
- else {
- throw new SerializationException(Environment.GetResourceString("Serialization_InvalidData"));
- }
- }
- if (m_currentTokenStartIndex < 0 || m_currentTokenStartIndex >= m_serializedText.Length) {
- throw new SerializationException(Environment.GetResourceString("Serialization_InvalidData"));
- }
- State tokenState = State.NotEscaped;
- StringBuilder token = StringBuilderCache.Acquire(initialCapacityForString);
-
- // walk the serialized text, building up the token as we go...
- for (int i = m_currentTokenStartIndex; i < m_serializedText.Length; i++) {
- if (tokenState == State.Escaped) {
- VerifyIsEscapableCharacter(m_serializedText[i]);
- token.Append(m_serializedText[i]);
- tokenState = State.NotEscaped;
- }
- else if (tokenState == State.NotEscaped) {
- switch (m_serializedText[i]) {
- case esc:
- tokenState = State.Escaped;
- break;
-
- case lhs:
- // '[' is an unexpected character
- throw new SerializationException(Environment.GetResourceString("Serialization_InvalidData"));
-
- case rhs:
- if (canEndWithoutSeparator) {
- // if ';' is not a required terminal then treat ']' as a terminal
- // leave m_currentTokenStartIndex pointing to ']' so our callers can handle
- // this special case
- m_currentTokenStartIndex = i;
- m_state = State.StartOfToken;
- return token.ToString();
- }
- else {
- // ']' is an unexpected character
- throw new SerializationException(Environment.GetResourceString("Serialization_InvalidData"));
- }
-
- case sep:
- m_currentTokenStartIndex = i + 1;
- if (m_currentTokenStartIndex >= m_serializedText.Length) {
- m_state = State.EndOfLine;
- }
- else {
- m_state = State.StartOfToken;
- }
- return StringBuilderCache.GetStringAndRelease(token);
-
- case '\0':
- // invalid character
- throw new SerializationException(Environment.GetResourceString("Serialization_InvalidData"));
-
- default:
- token.Append(m_serializedText[i]);
- break;
- }
- }
- }
- //
- // we are at the end of the line
- //
- if (tokenState == State.Escaped) {
- // we are at the end of the serialized text but we are in an escaped state
- throw new SerializationException(Environment.GetResourceString("Serialization_InvalidEscapeSequence", String.Empty));
- }
-
- if (!canEndWithoutSeparator) {
- throw new SerializationException(Environment.GetResourceString("Serialization_InvalidData"));
- }
- m_currentTokenStartIndex = m_serializedText.Length;
- m_state = State.EndOfLine;
- return StringBuilderCache.GetStringAndRelease(token);
- }
-
- //
- // GetNextDateTimeValue -
- //
- // Helper function to read a DateTime token. Takes a boolean "canEndWithoutSeparator"
- // and a "format" string.
- //
- private DateTime GetNextDateTimeValue(Boolean canEndWithoutSeparator, string format) {
- String token = GetNextStringValue(canEndWithoutSeparator);
- DateTime time;
- if (!DateTime.TryParseExact(token, format, DateTimeFormatInfo.InvariantInfo, DateTimeStyles.None, out time)) {
- throw new SerializationException(Environment.GetResourceString("Serialization_InvalidData"));
- }
- return time;
- }
-
- //
- // GetNextTimeSpanValue -
- //
- // Helper function to read a DateTime token. Takes a boolean "canEndWithoutSeparator".
- //
- private TimeSpan GetNextTimeSpanValue(Boolean canEndWithoutSeparator) {
- Int32 token = GetNextInt32Value(canEndWithoutSeparator);
-
- try {
- return new TimeSpan(0 /* hours */, token /* minutes */, 0 /* seconds */);
- }
- catch (ArgumentOutOfRangeException e) {
- throw new SerializationException(Environment.GetResourceString("Serialization_InvalidData"), e);
- }
- }
-
-
- //
- // GetNextInt32Value -
- //
- // Helper function to read an Int32 token. Takes a boolean "canEndWithoutSeparator".
- //
- private Int32 GetNextInt32Value(Boolean canEndWithoutSeparator) {
- String token = GetNextStringValue(canEndWithoutSeparator);
- Int32 value;
- if (!Int32.TryParse(token, NumberStyles.AllowLeadingSign /* "[sign]digits" */, CultureInfo.InvariantCulture, out value)) {
- throw new SerializationException(Environment.GetResourceString("Serialization_InvalidData"));
- }
- return value;
- }
-
-
- //
- // GetNextAdjustmentRuleArrayValue -
- //
- // Helper function to read an AdjustmentRule[] token. Takes a boolean "canEndWithoutSeparator".
- //
- private AdjustmentRule[] GetNextAdjustmentRuleArrayValue(Boolean canEndWithoutSeparator) {
- List<AdjustmentRule> rules = new List<AdjustmentRule>(1);
- int count = 0;
-
- // individual AdjustmentRule array elements do not require semicolons
- AdjustmentRule rule = GetNextAdjustmentRuleValue(true);
- while (rule != null) {
- rules.Add(rule);
- count++;
-
- rule = GetNextAdjustmentRuleValue(true);
- }
-
- if (!canEndWithoutSeparator) {
- // the AdjustmentRule array must end with a separator
- if (m_state == State.EndOfLine) {
- throw new SerializationException(Environment.GetResourceString("Serialization_InvalidData"));
- }
- if (m_currentTokenStartIndex < 0 || m_currentTokenStartIndex >= m_serializedText.Length) {
- throw new SerializationException(Environment.GetResourceString("Serialization_InvalidData"));
- }
- }
-
- return (count != 0 ? rules.ToArray() : null);
- }
-
- //
- // GetNextAdjustmentRuleValue -
- //
- // Helper function to read an AdjustmentRule token. Takes a boolean "canEndWithoutSeparator".
- //
- private AdjustmentRule GetNextAdjustmentRuleValue(Boolean canEndWithoutSeparator) {
- // first verify the internal state of the object
- if (m_state == State.EndOfLine) {
- if (canEndWithoutSeparator) {
- return null;
- }
- else {
- throw new SerializationException(Environment.GetResourceString("Serialization_InvalidData"));
- }
- }
-
- if (m_currentTokenStartIndex < 0 || m_currentTokenStartIndex >= m_serializedText.Length) {
- throw new SerializationException(Environment.GetResourceString("Serialization_InvalidData"));
- }
-
- // check to see if the very first token we see is the separator
- if (m_serializedText[m_currentTokenStartIndex] == sep) {
- return null;
- }
-
- // verify the current token is a left-hand-side marker ("[")
- if (m_serializedText[m_currentTokenStartIndex] != lhs) {
- throw new SerializationException(Environment.GetResourceString("Serialization_InvalidData"));
- }
- m_currentTokenStartIndex++;
-
- DateTime dateStart = GetNextDateTimeValue(false, dateTimeFormat);
- DateTime dateEnd = GetNextDateTimeValue(false, dateTimeFormat);
- TimeSpan daylightDelta = GetNextTimeSpanValue(false);
- TransitionTime daylightStart = GetNextTransitionTimeValue(false);
- TransitionTime daylightEnd = GetNextTransitionTimeValue(false);
- TimeSpan baseUtcOffsetDelta = TimeSpan.Zero;
- Int32 noDaylightTransitions = 0;
-
- // verify that the string is now at the right-hand-side marker ("]") ...
-
- if (m_state == State.EndOfLine || m_currentTokenStartIndex >= m_serializedText.Length) {
- throw new SerializationException(Environment.GetResourceString("Serialization_InvalidData"));
- }
-
- // Check if we have baseUtcOffsetDelta in the serialized string and then deserialize it
- if ((m_serializedText[m_currentTokenStartIndex] >= '0' && m_serializedText[m_currentTokenStartIndex] <= '9') ||
- m_serializedText[m_currentTokenStartIndex] == '-' || m_serializedText[m_currentTokenStartIndex] == '+') {
- baseUtcOffsetDelta = GetNextTimeSpanValue(false);
- }
-
- // Check if we have NoDaylightTransitions in the serialized string and then deserialize it
- if ((m_serializedText[m_currentTokenStartIndex] >= '0' && m_serializedText[m_currentTokenStartIndex] <= '1')) {
- noDaylightTransitions = GetNextInt32Value(false);
- }
-
- if (m_state == State.EndOfLine || m_currentTokenStartIndex >= m_serializedText.Length) {
- throw new SerializationException(Environment.GetResourceString("Serialization_InvalidData"));
- }
-
- if (m_serializedText[m_currentTokenStartIndex] != rhs) {
- // skip ahead of any "v.Next" data at the end of the AdjustmentRule
- //
- // FUTURE: if the serialization format is extended in the future then this
- // code section will need to be changed to read the new fields rather
- // than just skipping the data at the end of the [AdjustmentRule].
- SkipVersionNextDataFields(1);
- }
- else {
- m_currentTokenStartIndex++;
- }
-
- // create the AdjustmentRule from the deserialized fields ...
-
- AdjustmentRule rule;
- try {
- rule = AdjustmentRule.CreateAdjustmentRule(dateStart, dateEnd, daylightDelta, daylightStart, daylightEnd, baseUtcOffsetDelta, noDaylightTransitions > 0);
- }
- catch (ArgumentException e) {
- throw new SerializationException(Environment.GetResourceString("Serialization_InvalidData"), e);
- }
-
- // finally set the state to either EndOfLine or StartOfToken for the next caller
- if (m_currentTokenStartIndex >= m_serializedText.Length) {
- m_state = State.EndOfLine;
- }
- else {
- m_state = State.StartOfToken;
- }
- return rule;
- }
-
-
- //
- // GetNextTransitionTimeValue -
- //
- // Helper function to read a TransitionTime token. Takes a boolean "canEndWithoutSeparator".
- //
- private TransitionTime GetNextTransitionTimeValue(Boolean canEndWithoutSeparator) {
-
- // first verify the internal state of the object
-
- if (m_state == State.EndOfLine
- || (m_currentTokenStartIndex < m_serializedText.Length
- && m_serializedText[m_currentTokenStartIndex] == rhs)) {
- //
- // we are at the end of the line or we are starting at a "]" character
- //
- throw new SerializationException(Environment.GetResourceString("Serialization_InvalidData"));
- }
-
- if (m_currentTokenStartIndex < 0 || m_currentTokenStartIndex >= m_serializedText.Length) {
- throw new SerializationException(Environment.GetResourceString("Serialization_InvalidData"));
- }
-
- // verify the current token is a left-hand-side marker ("[")
-
- if (m_serializedText[m_currentTokenStartIndex] != lhs) {
- throw new SerializationException(Environment.GetResourceString("Serialization_InvalidData"));
- }
- m_currentTokenStartIndex++;
-
- Int32 isFixedDate = GetNextInt32Value(false);
-
- if (isFixedDate != 0 && isFixedDate != 1) {
- throw new SerializationException(Environment.GetResourceString("Serialization_InvalidData"));
- }
-
- TransitionTime transition;
-
- DateTime timeOfDay = GetNextDateTimeValue(false, timeOfDayFormat);
- timeOfDay = new DateTime(1, 1, 1, timeOfDay.Hour,timeOfDay.Minute,timeOfDay.Second, timeOfDay.Millisecond);
-
- Int32 month = GetNextInt32Value(false);
-
- if (isFixedDate == 1) {
- Int32 day = GetNextInt32Value(false);
-
- try {
- transition = TransitionTime.CreateFixedDateRule(timeOfDay, month, day);
- }
- catch (ArgumentException e) {
- throw new SerializationException(Environment.GetResourceString("Serialization_InvalidData"), e);
- }
- }
- else {
- Int32 week = GetNextInt32Value(false);
- Int32 dayOfWeek = GetNextInt32Value(false);
-
- try {
- transition = TransitionTime.CreateFloatingDateRule(timeOfDay, month, week, (DayOfWeek)dayOfWeek);
- }
- catch (ArgumentException e) {
- throw new SerializationException(Environment.GetResourceString("Serialization_InvalidData"), e);
- }
-
- }
-
- // verify that the string is now at the right-hand-side marker ("]") ...
-
- if (m_state == State.EndOfLine || m_currentTokenStartIndex >= m_serializedText.Length) {
- throw new SerializationException(Environment.GetResourceString("Serialization_InvalidData"));
- }
-
- if (m_serializedText[m_currentTokenStartIndex] != rhs) {
- // skip ahead of any "v.Next" data at the end of the AdjustmentRule
- //
- // FUTURE: if the serialization format is extended in the future then this
- // code section will need to be changed to read the new fields rather
- // than just skipping the data at the end of the [TransitionTime].
- SkipVersionNextDataFields(1);
- }
- else {
- m_currentTokenStartIndex++;
- }
-
- // check to see if the string is now at the separator (";") ...
- Boolean sepFound = false;
- if (m_currentTokenStartIndex < m_serializedText.Length
- && m_serializedText[m_currentTokenStartIndex] == sep) {
- // handle the case where we ended on a ";"
- m_currentTokenStartIndex++;
- sepFound = true;
- }
-
- if (!sepFound && !canEndWithoutSeparator) {
- // we MUST end on a separator
- throw new SerializationException(Environment.GetResourceString("Serialization_InvalidData"));
- }
-
-
- // finally set the state to either EndOfLine or StartOfToken for the next caller
- if (m_currentTokenStartIndex >= m_serializedText.Length) {
- m_state = State.EndOfLine;
- }
- else {
- m_state = State.StartOfToken;
- }
- return transition;
- }
- }
-
-#if PLATFORM_UNIX
- private struct TZifType
- {
- private const int c_len = 6;
- public static int Length
- {
- get
- {
- return c_len;
- }
- }
-
- public TimeSpan UtcOffset;
- public Boolean IsDst;
- public Byte AbbreviationIndex;
-
- public TZifType(Byte[] data, Int32 index)
- {
- if (data == null || data.Length < index + c_len)
- {
- throw new ArgumentException(Environment.GetResourceString("Argument_TimeZoneInfoInvalidTZif"), nameof(data));
- }
- Contract.EndContractBlock();
- UtcOffset = new TimeSpan(0, 0, TZif_ToInt32(data, index + 00));
- IsDst = (data[index + 4] != 0);
- AbbreviationIndex = data[index + 5];
- }
- }
-
- private struct TZifHead
- {
- private const int c_len = 44;
- public static int Length
- {
- get
- {
- return c_len;
- }
- }
-
- public TZifHead(Byte[] data, Int32 index)
- {
- if (data == null || data.Length < c_len)
- {
- throw new ArgumentException("bad data", nameof(data));
- }
- Contract.EndContractBlock();
-
- Magic = (uint)TZif_ToInt32(data, index + 00);
-
- if (Magic != 0x545A6966)
- {
- // 0x545A6966 = {0x54, 0x5A, 0x69, 0x66} = "TZif"
- throw new ArgumentException(Environment.GetResourceString("Argument_TimeZoneInfoBadTZif"), nameof(data));
- }
-
- byte version = data[index + 04];
- Version = version == '2' ? TZVersion.V2 :
- version == '3' ? TZVersion.V3 :
- TZVersion.V1; // default/fallback to V1 to guard against future, unsupported version numbers
-
- // skip the 15 byte reserved field
-
- // don't use the BitConverter class which parses data
- // based on the Endianess of the machine architecture.
- // this data is expected to always be in "standard byte order",
- // regardless of the machine it is being processed on.
-
- IsGmtCount = (uint)TZif_ToInt32(data, index + 20);
- IsStdCount = (uint)TZif_ToInt32(data, index + 24);
- LeapCount = (uint)TZif_ToInt32(data, index + 28);
- TimeCount = (uint)TZif_ToInt32(data, index + 32);
- TypeCount = (uint)TZif_ToInt32(data, index + 36);
- CharCount = (uint)TZif_ToInt32(data, index + 40);
- }
-
- public UInt32 Magic; // TZ_MAGIC "TZif"
- public TZVersion Version; // 1 byte for a \0 or 2 or 3
- // public Byte[15] Reserved; // reserved for future use
- public UInt32 IsGmtCount; // number of transition time flags
- public UInt32 IsStdCount; // number of transition time flags
- public UInt32 LeapCount; // number of leap seconds
- public UInt32 TimeCount; // number of transition times
- public UInt32 TypeCount; // number of local time types
- public UInt32 CharCount; // number of abbreviated characters
- }
-
- private enum TZVersion : byte
- {
- V1 = 0,
- V2,
- V3,
- // when adding more versions, ensure all the logic using TZVersion is still correct
- }
-#endif // PLATFORM_UNIX
-
- } // TimezoneInfo
-} // namespace System
+ }
+}
diff --git a/src/mscorlib/src/System/TimeZoneNotFoundException.cs b/src/mscorlib/src/System/TimeZoneNotFoundException.cs
index cabcc150f6..ee21c2524f 100644
--- a/src/mscorlib/src/System/TimeZoneNotFoundException.cs
+++ b/src/mscorlib/src/System/TimeZoneNotFoundException.cs
@@ -2,22 +2,27 @@
// 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;
- [Serializable]
- [System.Security.Permissions.HostProtection(MayLeakOnAbort = true)]
- public class TimeZoneNotFoundException : Exception {
- public TimeZoneNotFoundException(String message)
- : base(message) { }
+namespace System
+{
+ [Serializable]
+ public class TimeZoneNotFoundException : Exception
+ {
+ public TimeZoneNotFoundException()
+ {
+ }
- public TimeZoneNotFoundException(String message, Exception innerException)
- : base(message, innerException) { }
+ public TimeZoneNotFoundException(String message)
+ : base(message)
+ {
+ }
- protected TimeZoneNotFoundException(SerializationInfo info, StreamingContext context)
- : base(info, context) { }
+ public TimeZoneNotFoundException(String message, Exception innerException)
+ : base(message, innerException)
+ {
+ }
- public TimeZoneNotFoundException() { }
- }
+ protected TimeZoneNotFoundException(SerializationInfo info, StreamingContext context) : base(info, context) { }
+ }
}
diff --git a/src/mscorlib/src/System/TimeoutException.cs b/src/mscorlib/src/System/TimeoutException.cs
index 0b45f62fbd..32775a1c56 100644
--- a/src/mscorlib/src/System/TimeoutException.cs
+++ b/src/mscorlib/src/System/TimeoutException.cs
@@ -11,35 +11,31 @@
**
=============================================================================*/
-namespace System
-{
- using System.Runtime.Serialization;
+using System.Runtime.Serialization;
+namespace System
+{
[Serializable]
- [System.Runtime.InteropServices.ComVisible(true)]
- public class TimeoutException : SystemException {
-
- public TimeoutException()
- : base(Environment.GetResourceString("Arg_TimeoutException")) {
- SetErrorCode(__HResults.COR_E_TIMEOUT);
+ public class TimeoutException : SystemException
+ {
+ public TimeoutException()
+ : base(SR.Arg_TimeoutException)
+ {
+ HResult = __HResults.COR_E_TIMEOUT;
}
-
- public TimeoutException(String message)
- : base(message) {
- SetErrorCode(__HResults.COR_E_TIMEOUT);
+
+ public TimeoutException(String message)
+ : base(message)
+ {
+ HResult = __HResults.COR_E_TIMEOUT;
}
-
+
public TimeoutException(String message, Exception innerException)
- : base(message, innerException) {
- SetErrorCode(__HResults.COR_E_TIMEOUT);
- }
-
- //
- //This constructor is required for serialization.
- //
- protected TimeoutException(SerializationInfo info, StreamingContext context)
- : base(info, context) {
+ : base(message, innerException)
+ {
+ HResult = __HResults.COR_E_TIMEOUT;
}
+
+ protected TimeoutException(SerializationInfo info, StreamingContext context) : base(info, context) { }
}
}
-
diff --git a/src/mscorlib/src/System/Tuple.cs b/src/mscorlib/src/System/Tuple.cs
index 037b2ceee8..bb0dbcad6f 100644
--- a/src/mscorlib/src/System/Tuple.cs
+++ b/src/mscorlib/src/System/Tuple.cs
@@ -7,161 +7,206 @@ using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.Contracts;
+using System.Runtime.CompilerServices;
//
// Note: F# compiler depends on the exact tuple hashing algorithm. Do not ever change it.
//
-namespace System {
+namespace System
+{
/// <summary>
/// Helper so we can call some tuple methods recursively without knowing the underlying types.
/// </summary>
- internal interface ITuple {
+ internal interface ITupleInternal : ITuple
+ {
string ToString(StringBuilder sb);
int GetHashCode(IEqualityComparer comparer);
- int Size { get; }
-
}
- public static class Tuple {
- public static Tuple<T1> Create<T1>(T1 item1) {
+ public static class Tuple
+ {
+ public static Tuple<T1> Create<T1>(T1 item1)
+ {
return new Tuple<T1>(item1);
}
- public static Tuple<T1, T2> Create<T1, T2>(T1 item1, T2 item2) {
+ public static Tuple<T1, T2> Create<T1, T2>(T1 item1, T2 item2)
+ {
return new Tuple<T1, T2>(item1, item2);
}
- public static Tuple<T1, T2, T3> Create<T1, T2, T3>(T1 item1, T2 item2, T3 item3) {
+ public static Tuple<T1, T2, T3> Create<T1, T2, T3>(T1 item1, T2 item2, T3 item3)
+ {
return new Tuple<T1, T2, T3>(item1, item2, item3);
}
- public static Tuple<T1, T2, T3, T4> Create<T1, T2, T3, T4>(T1 item1, T2 item2, T3 item3, T4 item4) {
+ public static Tuple<T1, T2, T3, T4> Create<T1, T2, T3, T4>(T1 item1, T2 item2, T3 item3, T4 item4)
+ {
return new Tuple<T1, T2, T3, T4>(item1, item2, item3, item4);
}
- public static Tuple<T1, T2, T3, T4, T5> Create<T1, T2, T3, T4, T5>(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5) {
+ public static Tuple<T1, T2, T3, T4, T5> Create<T1, T2, T3, T4, T5>(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5)
+ {
return new Tuple<T1, T2, T3, T4, T5>(item1, item2, item3, item4, item5);
}
- public static Tuple<T1, T2, T3, T4, T5, T6> Create<T1, T2, T3, T4, T5, T6>(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5, T6 item6) {
+ public static Tuple<T1, T2, T3, T4, T5, T6> Create<T1, T2, T3, T4, T5, T6>(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5, T6 item6)
+ {
return new Tuple<T1, T2, T3, T4, T5, T6>(item1, item2, item3, item4, item5, item6);
}
- public static Tuple<T1, T2, T3, T4, T5, T6, T7> Create<T1, T2, T3, T4, T5, T6, T7>(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5, T6 item6, T7 item7) {
+ public static Tuple<T1, T2, T3, T4, T5, T6, T7> Create<T1, T2, T3, T4, T5, T6, T7>(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5, T6 item6, T7 item7)
+ {
return new Tuple<T1, T2, T3, T4, T5, T6, T7>(item1, item2, item3, item4, item5, item6, item7);
}
- public static Tuple<T1, T2, T3, T4, T5, T6, T7, Tuple<T8>> Create<T1, T2, T3, T4, T5, T6, T7, T8>(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5, T6 item6, T7 item7, T8 item8) {
+ public static Tuple<T1, T2, T3, T4, T5, T6, T7, Tuple<T8>> Create<T1, T2, T3, T4, T5, T6, T7, T8>(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5, T6 item6, T7 item7, T8 item8)
+ {
return new Tuple<T1, T2, T3, T4, T5, T6, T7, Tuple<T8>>(item1, item2, item3, item4, item5, item6, item7, new Tuple<T8>(item8));
}
// From System.Web.Util.HashCodeCombiner
- internal static int CombineHashCodes(int h1, int h2) {
+ internal static int CombineHashCodes(int h1, int h2)
+ {
return (((h1 << 5) + h1) ^ h2);
}
- internal static int CombineHashCodes(int h1, int h2, int h3) {
+ internal static int CombineHashCodes(int h1, int h2, int h3)
+ {
return CombineHashCodes(CombineHashCodes(h1, h2), h3);
}
- internal static int CombineHashCodes(int h1, int h2, int h3, int h4) {
+ internal static int CombineHashCodes(int h1, int h2, int h3, int h4)
+ {
return CombineHashCodes(CombineHashCodes(h1, h2), CombineHashCodes(h3, h4));
}
- internal static int CombineHashCodes(int h1, int h2, int h3, int h4, int h5) {
+ internal static int CombineHashCodes(int h1, int h2, int h3, int h4, int h5)
+ {
return CombineHashCodes(CombineHashCodes(h1, h2, h3, h4), h5);
}
- internal static int CombineHashCodes(int h1, int h2, int h3, int h4, int h5, int h6) {
+ internal static int CombineHashCodes(int h1, int h2, int h3, int h4, int h5, int h6)
+ {
return CombineHashCodes(CombineHashCodes(h1, h2, h3, h4), CombineHashCodes(h5, h6));
}
- internal static int CombineHashCodes(int h1, int h2, int h3, int h4, int h5, int h6, int h7) {
+ internal static int CombineHashCodes(int h1, int h2, int h3, int h4, int h5, int h6, int h7)
+ {
return CombineHashCodes(CombineHashCodes(h1, h2, h3, h4), CombineHashCodes(h5, h6, h7));
}
- internal static int CombineHashCodes(int h1, int h2, int h3, int h4, int h5, int h6, int h7, int h8) {
+ internal static int CombineHashCodes(int h1, int h2, int h3, int h4, int h5, int h6, int h7, int h8)
+ {
return CombineHashCodes(CombineHashCodes(h1, h2, h3, h4), CombineHashCodes(h5, h6, h7, h8));
}
}
[Serializable]
- public class Tuple<T1> : IStructuralEquatable, IStructuralComparable, IComparable, ITuple {
+ public class Tuple<T1> : IStructuralEquatable, IStructuralComparable, IComparable, ITupleInternal, ITuple
+ {
private readonly T1 m_Item1;
public T1 Item1 { get { return m_Item1; } }
- public Tuple(T1 item1) {
+ public Tuple(T1 item1)
+ {
m_Item1 = item1;
}
- public override Boolean Equals(Object obj) {
- return ((IStructuralEquatable) this).Equals(obj, EqualityComparer<Object>.Default);
+ public override Boolean Equals(Object obj)
+ {
+ return ((IStructuralEquatable)this).Equals(obj, EqualityComparer<Object>.Default);
}
- Boolean IStructuralEquatable.Equals(Object other, IEqualityComparer comparer) {
+ Boolean IStructuralEquatable.Equals(Object other, IEqualityComparer comparer)
+ {
if (other == null) return false;
Tuple<T1> objTuple = other as Tuple<T1>;
- if (objTuple == null) {
+ if (objTuple == null)
+ {
return false;
}
return comparer.Equals(m_Item1, objTuple.m_Item1);
}
- Int32 IComparable.CompareTo(Object obj) {
- return ((IStructuralComparable) this).CompareTo(obj, Comparer<Object>.Default);
+ Int32 IComparable.CompareTo(Object obj)
+ {
+ return ((IStructuralComparable)this).CompareTo(obj, Comparer<Object>.Default);
}
- Int32 IStructuralComparable.CompareTo(Object other, IComparer comparer) {
+ Int32 IStructuralComparable.CompareTo(Object other, IComparer comparer)
+ {
if (other == null) return 1;
Tuple<T1> objTuple = other as Tuple<T1>;
- if (objTuple == null) {
- throw new ArgumentException(Environment.GetResourceString("ArgumentException_TupleIncorrectType", this.GetType().ToString()), nameof(other));
+ if (objTuple == null)
+ {
+ throw new ArgumentException(Environment.GetResourceString("ArgumentException_TupleIncorrectType", this.GetType().ToString()), "other");
}
return comparer.Compare(m_Item1, objTuple.m_Item1);
}
- public override int GetHashCode() {
- return ((IStructuralEquatable) this).GetHashCode(EqualityComparer<Object>.Default);
+ public override int GetHashCode()
+ {
+ return ((IStructuralEquatable)this).GetHashCode(EqualityComparer<Object>.Default);
}
- Int32 IStructuralEquatable.GetHashCode(IEqualityComparer comparer) {
+ Int32 IStructuralEquatable.GetHashCode(IEqualityComparer comparer)
+ {
return comparer.GetHashCode(m_Item1);
}
- Int32 ITuple.GetHashCode(IEqualityComparer comparer) {
- return ((IStructuralEquatable) this).GetHashCode(comparer);
+ Int32 ITupleInternal.GetHashCode(IEqualityComparer comparer)
+ {
+ return ((IStructuralEquatable)this).GetHashCode(comparer);
}
- public override string ToString() {
+ public override string ToString()
+ {
StringBuilder sb = new StringBuilder();
sb.Append("(");
- return ((ITuple)this).ToString(sb);
+ return ((ITupleInternal)this).ToString(sb);
}
- string ITuple.ToString(StringBuilder sb) {
+ string ITupleInternal.ToString(StringBuilder sb)
+ {
sb.Append(m_Item1);
sb.Append(")");
return sb.ToString();
}
- int ITuple.Size {
- get {
- return 1;
+ /// <summary>
+ /// The number of positions in this data structure.
+ /// </summary>
+ int ITuple.Length => 1;
+
+ /// <summary>
+ /// Get the element at position <param name="index"/>.
+ /// </summary>
+ object ITuple.this[int index]
+ {
+ get
+ {
+ if (index != 0)
+ {
+ throw new IndexOutOfRangeException();
+ }
+ return Item1;
}
}
}
[Serializable]
- public class Tuple<T1, T2> : IStructuralEquatable, IStructuralComparable, IComparable, ITuple {
+ public class Tuple<T1, T2> : IStructuralEquatable, IStructuralComparable, IComparable, ITupleInternal, ITuple
+ {
private readonly T1 m_Item1;
private readonly T2 m_Item2;
@@ -169,38 +214,45 @@ namespace System {
public T1 Item1 { get { return m_Item1; } }
public T2 Item2 { get { return m_Item2; } }
- public Tuple(T1 item1, T2 item2) {
+ public Tuple(T1 item1, T2 item2)
+ {
m_Item1 = item1;
m_Item2 = item2;
}
- public override Boolean Equals(Object obj) {
- return ((IStructuralEquatable) this).Equals(obj, EqualityComparer<Object>.Default);;
+ public override Boolean Equals(Object obj)
+ {
+ return ((IStructuralEquatable)this).Equals(obj, EqualityComparer<Object>.Default); ;
}
- Boolean IStructuralEquatable.Equals(Object other, IEqualityComparer comparer) {
+ Boolean IStructuralEquatable.Equals(Object other, IEqualityComparer comparer)
+ {
if (other == null) return false;
Tuple<T1, T2> objTuple = other as Tuple<T1, T2>;
- if (objTuple == null) {
+ if (objTuple == null)
+ {
return false;
}
return comparer.Equals(m_Item1, objTuple.m_Item1) && comparer.Equals(m_Item2, objTuple.m_Item2);
}
- Int32 IComparable.CompareTo(Object obj) {
- return ((IStructuralComparable) this).CompareTo(obj, Comparer<Object>.Default);
+ Int32 IComparable.CompareTo(Object obj)
+ {
+ return ((IStructuralComparable)this).CompareTo(obj, Comparer<Object>.Default);
}
- Int32 IStructuralComparable.CompareTo(Object other, IComparer comparer) {
+ Int32 IStructuralComparable.CompareTo(Object other, IComparer comparer)
+ {
if (other == null) return 1;
Tuple<T1, T2> objTuple = other as Tuple<T1, T2>;
- if (objTuple == null) {
- throw new ArgumentException(Environment.GetResourceString("ArgumentException_TupleIncorrectType", this.GetType().ToString()), nameof(other));
+ if (objTuple == null)
+ {
+ throw new ArgumentException(Environment.GetResourceString("ArgumentException_TupleIncorrectType", this.GetType().ToString()), "other");
}
int c = 0;
@@ -212,24 +264,29 @@ namespace System {
return comparer.Compare(m_Item2, objTuple.m_Item2);
}
- public override int GetHashCode() {
- return ((IStructuralEquatable) this).GetHashCode(EqualityComparer<Object>.Default);
+ public override int GetHashCode()
+ {
+ return ((IStructuralEquatable)this).GetHashCode(EqualityComparer<Object>.Default);
}
- Int32 IStructuralEquatable.GetHashCode(IEqualityComparer comparer) {
+ Int32 IStructuralEquatable.GetHashCode(IEqualityComparer comparer)
+ {
return Tuple.CombineHashCodes(comparer.GetHashCode(m_Item1), comparer.GetHashCode(m_Item2));
}
- Int32 ITuple.GetHashCode(IEqualityComparer comparer) {
- return ((IStructuralEquatable) this).GetHashCode(comparer);
+ Int32 ITupleInternal.GetHashCode(IEqualityComparer comparer)
+ {
+ return ((IStructuralEquatable)this).GetHashCode(comparer);
}
- public override string ToString() {
+ public override string ToString()
+ {
StringBuilder sb = new StringBuilder();
sb.Append("(");
- return ((ITuple)this).ToString(sb);
+ return ((ITupleInternal)this).ToString(sb);
}
- string ITuple.ToString(StringBuilder sb) {
+ string ITupleInternal.ToString(StringBuilder sb)
+ {
sb.Append(m_Item1);
sb.Append(", ");
sb.Append(m_Item2);
@@ -237,15 +294,34 @@ namespace System {
return sb.ToString();
}
- int ITuple.Size {
- get {
- return 2;
+ /// <summary>
+ /// The number of positions in this data structure.
+ /// </summary>
+ int ITuple.Length => 2;
+
+ /// <summary>
+ /// Get the element at position <param name="index"/>.
+ /// </summary>
+ object ITuple.this[int index]
+ {
+ get
+ {
+ switch (index)
+ {
+ case 0:
+ return Item1;
+ case 1:
+ return Item2;
+ default:
+ throw new IndexOutOfRangeException();
+ }
}
}
}
[Serializable]
- public class Tuple<T1, T2, T3> : IStructuralEquatable, IStructuralComparable, IComparable, ITuple {
+ public class Tuple<T1, T2, T3> : IStructuralEquatable, IStructuralComparable, IComparable, ITupleInternal, ITuple
+ {
private readonly T1 m_Item1;
private readonly T2 m_Item2;
@@ -255,39 +331,46 @@ namespace System {
public T2 Item2 { get { return m_Item2; } }
public T3 Item3 { get { return m_Item3; } }
- public Tuple(T1 item1, T2 item2, T3 item3) {
+ public Tuple(T1 item1, T2 item2, T3 item3)
+ {
m_Item1 = item1;
m_Item2 = item2;
m_Item3 = item3;
}
- public override Boolean Equals(Object obj) {
- return ((IStructuralEquatable) this).Equals(obj, EqualityComparer<Object>.Default);;
+ public override Boolean Equals(Object obj)
+ {
+ return ((IStructuralEquatable)this).Equals(obj, EqualityComparer<Object>.Default); ;
}
- Boolean IStructuralEquatable.Equals(Object other, IEqualityComparer comparer) {
+ Boolean IStructuralEquatable.Equals(Object other, IEqualityComparer comparer)
+ {
if (other == null) return false;
Tuple<T1, T2, T3> objTuple = other as Tuple<T1, T2, T3>;
- if (objTuple == null) {
+ if (objTuple == null)
+ {
return false;
}
return comparer.Equals(m_Item1, objTuple.m_Item1) && comparer.Equals(m_Item2, objTuple.m_Item2) && comparer.Equals(m_Item3, objTuple.m_Item3);
}
- Int32 IComparable.CompareTo(Object obj) {
- return ((IStructuralComparable) this).CompareTo(obj, Comparer<Object>.Default);
+ Int32 IComparable.CompareTo(Object obj)
+ {
+ return ((IStructuralComparable)this).CompareTo(obj, Comparer<Object>.Default);
}
- Int32 IStructuralComparable.CompareTo(Object other, IComparer comparer) {
+ Int32 IStructuralComparable.CompareTo(Object other, IComparer comparer)
+ {
if (other == null) return 1;
Tuple<T1, T2, T3> objTuple = other as Tuple<T1, T2, T3>;
- if (objTuple == null) {
- throw new ArgumentException(Environment.GetResourceString("ArgumentException_TupleIncorrectType", this.GetType().ToString()), nameof(other));
+ if (objTuple == null)
+ {
+ throw new ArgumentException(Environment.GetResourceString("ArgumentException_TupleIncorrectType", this.GetType().ToString()), "other");
}
int c = 0;
@@ -303,24 +386,29 @@ namespace System {
return comparer.Compare(m_Item3, objTuple.m_Item3);
}
- public override int GetHashCode() {
- return ((IStructuralEquatable) this).GetHashCode(EqualityComparer<Object>.Default);
+ public override int GetHashCode()
+ {
+ return ((IStructuralEquatable)this).GetHashCode(EqualityComparer<Object>.Default);
}
- Int32 IStructuralEquatable.GetHashCode(IEqualityComparer comparer) {
+ Int32 IStructuralEquatable.GetHashCode(IEqualityComparer comparer)
+ {
return Tuple.CombineHashCodes(comparer.GetHashCode(m_Item1), comparer.GetHashCode(m_Item2), comparer.GetHashCode(m_Item3));
}
- Int32 ITuple.GetHashCode(IEqualityComparer comparer) {
- return ((IStructuralEquatable) this).GetHashCode(comparer);
+ Int32 ITupleInternal.GetHashCode(IEqualityComparer comparer)
+ {
+ return ((IStructuralEquatable)this).GetHashCode(comparer);
}
- public override string ToString() {
+ public override string ToString()
+ {
StringBuilder sb = new StringBuilder();
sb.Append("(");
- return ((ITuple)this).ToString(sb);
+ return ((ITupleInternal)this).ToString(sb);
}
- string ITuple.ToString(StringBuilder sb) {
+ string ITupleInternal.ToString(StringBuilder sb)
+ {
sb.Append(m_Item1);
sb.Append(", ");
sb.Append(m_Item2);
@@ -330,15 +418,36 @@ namespace System {
return sb.ToString();
}
- int ITuple.Size {
- get {
- return 3;
+ /// <summary>
+ /// The number of positions in this data structure.
+ /// </summary>
+ int ITuple.Length => 3;
+
+ /// <summary>
+ /// Get the element at position <param name="index"/>.
+ /// </summary>
+ object ITuple.this[int index]
+ {
+ get
+ {
+ switch (index)
+ {
+ case 0:
+ return Item1;
+ case 1:
+ return Item2;
+ case 2:
+ return Item3;
+ default:
+ throw new IndexOutOfRangeException();
+ }
}
}
}
[Serializable]
- public class Tuple<T1, T2, T3, T4> : IStructuralEquatable, IStructuralComparable, IComparable, ITuple {
+ public class Tuple<T1, T2, T3, T4> : IStructuralEquatable, IStructuralComparable, IComparable, ITupleInternal, ITuple
+ {
private readonly T1 m_Item1;
private readonly T2 m_Item2;
@@ -350,40 +459,47 @@ namespace System {
public T3 Item3 { get { return m_Item3; } }
public T4 Item4 { get { return m_Item4; } }
- public Tuple(T1 item1, T2 item2, T3 item3, T4 item4) {
+ public Tuple(T1 item1, T2 item2, T3 item3, T4 item4)
+ {
m_Item1 = item1;
m_Item2 = item2;
m_Item3 = item3;
m_Item4 = item4;
}
- public override Boolean Equals(Object obj) {
- return ((IStructuralEquatable) this).Equals(obj, EqualityComparer<Object>.Default);;
+ public override Boolean Equals(Object obj)
+ {
+ return ((IStructuralEquatable)this).Equals(obj, EqualityComparer<Object>.Default); ;
}
- Boolean IStructuralEquatable.Equals(Object other, IEqualityComparer comparer) {
+ Boolean IStructuralEquatable.Equals(Object other, IEqualityComparer comparer)
+ {
if (other == null) return false;
Tuple<T1, T2, T3, T4> objTuple = other as Tuple<T1, T2, T3, T4>;
- if (objTuple == null) {
+ if (objTuple == null)
+ {
return false;
}
return comparer.Equals(m_Item1, objTuple.m_Item1) && comparer.Equals(m_Item2, objTuple.m_Item2) && comparer.Equals(m_Item3, objTuple.m_Item3) && comparer.Equals(m_Item4, objTuple.m_Item4);
}
- Int32 IComparable.CompareTo(Object obj) {
- return ((IStructuralComparable) this).CompareTo(obj, Comparer<Object>.Default);
+ Int32 IComparable.CompareTo(Object obj)
+ {
+ return ((IStructuralComparable)this).CompareTo(obj, Comparer<Object>.Default);
}
- Int32 IStructuralComparable.CompareTo(Object other, IComparer comparer) {
+ Int32 IStructuralComparable.CompareTo(Object other, IComparer comparer)
+ {
if (other == null) return 1;
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()), nameof(other));
+ if (objTuple == null)
+ {
+ throw new ArgumentException(Environment.GetResourceString("ArgumentException_TupleIncorrectType", this.GetType().ToString()), "other");
}
int c = 0;
@@ -403,24 +519,29 @@ namespace System {
return comparer.Compare(m_Item4, objTuple.m_Item4);
}
- public override int GetHashCode() {
- return ((IStructuralEquatable) this).GetHashCode(EqualityComparer<Object>.Default);
+ public override int GetHashCode()
+ {
+ return ((IStructuralEquatable)this).GetHashCode(EqualityComparer<Object>.Default);
}
- Int32 IStructuralEquatable.GetHashCode(IEqualityComparer comparer) {
+ Int32 IStructuralEquatable.GetHashCode(IEqualityComparer comparer)
+ {
return Tuple.CombineHashCodes(comparer.GetHashCode(m_Item1), comparer.GetHashCode(m_Item2), comparer.GetHashCode(m_Item3), comparer.GetHashCode(m_Item4));
}
- Int32 ITuple.GetHashCode(IEqualityComparer comparer) {
- return ((IStructuralEquatable) this).GetHashCode(comparer);
+ Int32 ITupleInternal.GetHashCode(IEqualityComparer comparer)
+ {
+ return ((IStructuralEquatable)this).GetHashCode(comparer);
}
- public override string ToString() {
+ public override string ToString()
+ {
StringBuilder sb = new StringBuilder();
sb.Append("(");
- return ((ITuple)this).ToString(sb);
+ return ((ITupleInternal)this).ToString(sb);
}
- string ITuple.ToString(StringBuilder sb) {
+ string ITupleInternal.ToString(StringBuilder sb)
+ {
sb.Append(m_Item1);
sb.Append(", ");
sb.Append(m_Item2);
@@ -432,15 +553,38 @@ namespace System {
return sb.ToString();
}
- int ITuple.Size {
- get {
- return 4;
+ /// <summary>
+ /// The number of positions in this data structure.
+ /// </summary>
+ int ITuple.Length => 4;
+
+ /// <summary>
+ /// Get the element at position <param name="index"/>.
+ /// </summary>
+ object ITuple.this[int index]
+ {
+ get
+ {
+ switch (index)
+ {
+ case 0:
+ return Item1;
+ case 1:
+ return Item2;
+ case 2:
+ return Item3;
+ case 3:
+ return Item4;
+ default:
+ throw new IndexOutOfRangeException();
+ }
}
}
}
[Serializable]
- public class Tuple<T1, T2, T3, T4, T5> : IStructuralEquatable, IStructuralComparable, IComparable, ITuple {
+ public class Tuple<T1, T2, T3, T4, T5> : IStructuralEquatable, IStructuralComparable, IComparable, ITupleInternal, ITuple
+ {
private readonly T1 m_Item1;
private readonly T2 m_Item2;
@@ -454,7 +598,8 @@ namespace System {
public T4 Item4 { get { return m_Item4; } }
public T5 Item5 { get { return m_Item5; } }
- public Tuple(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5) {
+ public Tuple(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5)
+ {
m_Item1 = item1;
m_Item2 = item2;
m_Item3 = item3;
@@ -462,33 +607,39 @@ namespace System {
m_Item5 = item5;
}
- public override Boolean Equals(Object obj) {
- return ((IStructuralEquatable) this).Equals(obj, EqualityComparer<Object>.Default);;
+ public override Boolean Equals(Object obj)
+ {
+ return ((IStructuralEquatable)this).Equals(obj, EqualityComparer<Object>.Default); ;
}
- Boolean IStructuralEquatable.Equals(Object other, IEqualityComparer comparer) {
+ Boolean IStructuralEquatable.Equals(Object other, IEqualityComparer comparer)
+ {
if (other == null) return false;
Tuple<T1, T2, T3, T4, T5> objTuple = other as Tuple<T1, T2, T3, T4, T5>;
- if (objTuple == null) {
+ if (objTuple == null)
+ {
return false;
}
return comparer.Equals(m_Item1, objTuple.m_Item1) && comparer.Equals(m_Item2, objTuple.m_Item2) && comparer.Equals(m_Item3, objTuple.m_Item3) && comparer.Equals(m_Item4, objTuple.m_Item4) && comparer.Equals(m_Item5, objTuple.m_Item5);
}
- Int32 IComparable.CompareTo(Object obj) {
- return ((IStructuralComparable) this).CompareTo(obj, Comparer<Object>.Default);
+ Int32 IComparable.CompareTo(Object obj)
+ {
+ return ((IStructuralComparable)this).CompareTo(obj, Comparer<Object>.Default);
}
- Int32 IStructuralComparable.CompareTo(Object other, IComparer comparer) {
+ Int32 IStructuralComparable.CompareTo(Object other, IComparer comparer)
+ {
if (other == null) return 1;
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()), nameof(other));
+ if (objTuple == null)
+ {
+ throw new ArgumentException(Environment.GetResourceString("ArgumentException_TupleIncorrectType", this.GetType().ToString()), "other");
}
int c = 0;
@@ -512,24 +663,29 @@ namespace System {
return comparer.Compare(m_Item5, objTuple.m_Item5);
}
- public override int GetHashCode() {
- return ((IStructuralEquatable) this).GetHashCode(EqualityComparer<Object>.Default);
+ public override int GetHashCode()
+ {
+ return ((IStructuralEquatable)this).GetHashCode(EqualityComparer<Object>.Default);
}
- Int32 IStructuralEquatable.GetHashCode(IEqualityComparer comparer) {
+ Int32 IStructuralEquatable.GetHashCode(IEqualityComparer comparer)
+ {
return Tuple.CombineHashCodes(comparer.GetHashCode(m_Item1), comparer.GetHashCode(m_Item2), comparer.GetHashCode(m_Item3), comparer.GetHashCode(m_Item4), comparer.GetHashCode(m_Item5));
}
- Int32 ITuple.GetHashCode(IEqualityComparer comparer) {
- return ((IStructuralEquatable) this).GetHashCode(comparer);
+ Int32 ITupleInternal.GetHashCode(IEqualityComparer comparer)
+ {
+ return ((IStructuralEquatable)this).GetHashCode(comparer);
}
- public override string ToString() {
+ public override string ToString()
+ {
StringBuilder sb = new StringBuilder();
sb.Append("(");
- return ((ITuple)this).ToString(sb);
+ return ((ITupleInternal)this).ToString(sb);
}
- string ITuple.ToString(StringBuilder sb) {
+ string ITupleInternal.ToString(StringBuilder sb)
+ {
sb.Append(m_Item1);
sb.Append(", ");
sb.Append(m_Item2);
@@ -543,15 +699,40 @@ namespace System {
return sb.ToString();
}
- int ITuple.Size {
- get {
- return 5;
+ /// <summary>
+ /// The number of positions in this data structure.
+ /// </summary>
+ int ITuple.Length => 5;
+
+ /// <summary>
+ /// Get the element at position <param name="index"/>.
+ /// </summary>
+ object ITuple.this[int index]
+ {
+ get
+ {
+ switch (index)
+ {
+ case 0:
+ return Item1;
+ case 1:
+ return Item2;
+ case 2:
+ return Item3;
+ case 3:
+ return Item4;
+ case 4:
+ return Item5;
+ default:
+ throw new IndexOutOfRangeException();
+ }
}
}
}
[Serializable]
- public class Tuple<T1, T2, T3, T4, T5, T6> : IStructuralEquatable, IStructuralComparable, IComparable, ITuple {
+ public class Tuple<T1, T2, T3, T4, T5, T6> : IStructuralEquatable, IStructuralComparable, IComparable, ITupleInternal, ITuple
+ {
private readonly T1 m_Item1;
private readonly T2 m_Item2;
@@ -567,7 +748,8 @@ namespace System {
public T5 Item5 { get { return m_Item5; } }
public T6 Item6 { get { return m_Item6; } }
- public Tuple(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5, T6 item6) {
+ public Tuple(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5, T6 item6)
+ {
m_Item1 = item1;
m_Item2 = item2;
m_Item3 = item3;
@@ -576,33 +758,39 @@ namespace System {
m_Item6 = item6;
}
- public override Boolean Equals(Object obj) {
- return ((IStructuralEquatable) this).Equals(obj, EqualityComparer<Object>.Default);;
+ public override Boolean Equals(Object obj)
+ {
+ return ((IStructuralEquatable)this).Equals(obj, EqualityComparer<Object>.Default); ;
}
- Boolean IStructuralEquatable.Equals(Object other, IEqualityComparer comparer) {
+ Boolean IStructuralEquatable.Equals(Object other, IEqualityComparer comparer)
+ {
if (other == null) return false;
Tuple<T1, T2, T3, T4, T5, T6> objTuple = other as Tuple<T1, T2, T3, T4, T5, T6>;
- if (objTuple == null) {
+ if (objTuple == null)
+ {
return false;
}
return comparer.Equals(m_Item1, objTuple.m_Item1) && comparer.Equals(m_Item2, objTuple.m_Item2) && comparer.Equals(m_Item3, objTuple.m_Item3) && comparer.Equals(m_Item4, objTuple.m_Item4) && comparer.Equals(m_Item5, objTuple.m_Item5) && comparer.Equals(m_Item6, objTuple.m_Item6);
}
- Int32 IComparable.CompareTo(Object obj) {
- return ((IStructuralComparable) this).CompareTo(obj, Comparer<Object>.Default);
+ Int32 IComparable.CompareTo(Object obj)
+ {
+ return ((IStructuralComparable)this).CompareTo(obj, Comparer<Object>.Default);
}
- Int32 IStructuralComparable.CompareTo(Object other, IComparer comparer) {
+ Int32 IStructuralComparable.CompareTo(Object other, IComparer comparer)
+ {
if (other == null) return 1;
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()), nameof(other));
+ if (objTuple == null)
+ {
+ throw new ArgumentException(Environment.GetResourceString("ArgumentException_TupleIncorrectType", this.GetType().ToString()), "other");
}
int c = 0;
@@ -630,24 +818,29 @@ namespace System {
return comparer.Compare(m_Item6, objTuple.m_Item6);
}
- public override int GetHashCode() {
- return ((IStructuralEquatable) this).GetHashCode(EqualityComparer<Object>.Default);
+ public override int GetHashCode()
+ {
+ return ((IStructuralEquatable)this).GetHashCode(EqualityComparer<Object>.Default);
}
- Int32 IStructuralEquatable.GetHashCode(IEqualityComparer comparer) {
+ Int32 IStructuralEquatable.GetHashCode(IEqualityComparer comparer)
+ {
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));
}
- Int32 ITuple.GetHashCode(IEqualityComparer comparer) {
- return ((IStructuralEquatable) this).GetHashCode(comparer);
+ Int32 ITupleInternal.GetHashCode(IEqualityComparer comparer)
+ {
+ return ((IStructuralEquatable)this).GetHashCode(comparer);
}
- public override string ToString() {
+ public override string ToString()
+ {
StringBuilder sb = new StringBuilder();
sb.Append("(");
- return ((ITuple)this).ToString(sb);
+ return ((ITupleInternal)this).ToString(sb);
}
- string ITuple.ToString(StringBuilder sb) {
+ string ITupleInternal.ToString(StringBuilder sb)
+ {
sb.Append(m_Item1);
sb.Append(", ");
sb.Append(m_Item2);
@@ -663,15 +856,42 @@ namespace System {
return sb.ToString();
}
- int ITuple.Size {
- get {
- return 6;
+ /// <summary>
+ /// The number of positions in this data structure.
+ /// </summary>
+ int ITuple.Length => 6;
+
+ /// <summary>
+ /// Get the element at position <param name="index"/>.
+ /// </summary>
+ object ITuple.this[int index]
+ {
+ get
+ {
+ switch (index)
+ {
+ case 0:
+ return Item1;
+ case 1:
+ return Item2;
+ case 2:
+ return Item3;
+ case 3:
+ return Item4;
+ case 4:
+ return Item5;
+ case 5:
+ return Item6;
+ default:
+ throw new IndexOutOfRangeException();
+ }
}
}
}
[Serializable]
- public class Tuple<T1, T2, T3, T4, T5, T6, T7> : IStructuralEquatable, IStructuralComparable, IComparable, ITuple {
+ public class Tuple<T1, T2, T3, T4, T5, T6, T7> : IStructuralEquatable, IStructuralComparable, IComparable, ITupleInternal, ITuple
+ {
private readonly T1 m_Item1;
private readonly T2 m_Item2;
@@ -689,7 +909,8 @@ namespace System {
public T6 Item6 { get { return m_Item6; } }
public T7 Item7 { get { return m_Item7; } }
- public Tuple(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5, T6 item6, T7 item7) {
+ public Tuple(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5, T6 item6, T7 item7)
+ {
m_Item1 = item1;
m_Item2 = item2;
m_Item3 = item3;
@@ -699,33 +920,39 @@ namespace System {
m_Item7 = item7;
}
- public override Boolean Equals(Object obj) {
- return ((IStructuralEquatable) this).Equals(obj, EqualityComparer<Object>.Default);;
+ public override Boolean Equals(Object obj)
+ {
+ return ((IStructuralEquatable)this).Equals(obj, EqualityComparer<Object>.Default); ;
}
- Boolean IStructuralEquatable.Equals(Object other, IEqualityComparer comparer) {
+ Boolean IStructuralEquatable.Equals(Object other, IEqualityComparer comparer)
+ {
if (other == null) return false;
Tuple<T1, T2, T3, T4, T5, T6, T7> objTuple = other as Tuple<T1, T2, T3, T4, T5, T6, T7>;
- if (objTuple == null) {
+ if (objTuple == null)
+ {
return false;
}
return comparer.Equals(m_Item1, objTuple.m_Item1) && comparer.Equals(m_Item2, objTuple.m_Item2) && comparer.Equals(m_Item3, objTuple.m_Item3) && comparer.Equals(m_Item4, objTuple.m_Item4) && comparer.Equals(m_Item5, objTuple.m_Item5) && comparer.Equals(m_Item6, objTuple.m_Item6) && comparer.Equals(m_Item7, objTuple.m_Item7);
}
- Int32 IComparable.CompareTo(Object obj) {
- return ((IStructuralComparable) this).CompareTo(obj, Comparer<Object>.Default);
+ Int32 IComparable.CompareTo(Object obj)
+ {
+ return ((IStructuralComparable)this).CompareTo(obj, Comparer<Object>.Default);
}
- Int32 IStructuralComparable.CompareTo(Object other, IComparer comparer) {
+ Int32 IStructuralComparable.CompareTo(Object other, IComparer comparer)
+ {
if (other == null) return 1;
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()), nameof(other));
+ if (objTuple == null)
+ {
+ throw new ArgumentException(Environment.GetResourceString("ArgumentException_TupleIncorrectType", this.GetType().ToString()), "other");
}
int c = 0;
@@ -757,24 +984,29 @@ namespace System {
return comparer.Compare(m_Item7, objTuple.m_Item7);
}
- public override int GetHashCode() {
- return ((IStructuralEquatable) this).GetHashCode(EqualityComparer<Object>.Default);
+ public override int GetHashCode()
+ {
+ return ((IStructuralEquatable)this).GetHashCode(EqualityComparer<Object>.Default);
}
- Int32 IStructuralEquatable.GetHashCode(IEqualityComparer comparer) {
+ Int32 IStructuralEquatable.GetHashCode(IEqualityComparer comparer)
+ {
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));
}
- Int32 ITuple.GetHashCode(IEqualityComparer comparer) {
- return ((IStructuralEquatable) this).GetHashCode(comparer);
+ Int32 ITupleInternal.GetHashCode(IEqualityComparer comparer)
+ {
+ return ((IStructuralEquatable)this).GetHashCode(comparer);
}
- public override string ToString() {
+ public override string ToString()
+ {
StringBuilder sb = new StringBuilder();
sb.Append("(");
- return ((ITuple)this).ToString(sb);
+ return ((ITupleInternal)this).ToString(sb);
}
- string ITuple.ToString(StringBuilder sb) {
+ string ITupleInternal.ToString(StringBuilder sb)
+ {
sb.Append(m_Item1);
sb.Append(", ");
sb.Append(m_Item2);
@@ -792,15 +1024,44 @@ namespace System {
return sb.ToString();
}
- int ITuple.Size {
- get {
- return 7;
+ /// <summary>
+ /// The number of positions in this data structure.
+ /// </summary>
+ int ITuple.Length => 7;
+
+ /// <summary>
+ /// Get the element at position <param name="index"/>.
+ /// </summary>
+ object ITuple.this[int index]
+ {
+ get
+ {
+ switch (index)
+ {
+ case 0:
+ return Item1;
+ case 1:
+ return Item2;
+ case 2:
+ return Item3;
+ case 3:
+ return Item4;
+ case 4:
+ return Item5;
+ case 5:
+ return Item6;
+ case 6:
+ return Item7;
+ default:
+ throw new IndexOutOfRangeException();
+ }
}
}
}
[Serializable]
- public class Tuple<T1, T2, T3, T4, T5, T6, T7, TRest> : IStructuralEquatable, IStructuralComparable, IComparable, ITuple {
+ public class Tuple<T1, T2, T3, T4, T5, T6, T7, TRest> : IStructuralEquatable, IStructuralComparable, IComparable, ITupleInternal, ITuple
+ {
private readonly T1 m_Item1;
private readonly T2 m_Item2;
@@ -820,8 +1081,10 @@ namespace System {
public T7 Item7 { get { return m_Item7; } }
public TRest Rest { get { return m_Rest; } }
- public Tuple(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5, T6 item6, T7 item7, TRest rest) {
- if (!(rest is ITuple)) {
+ public Tuple(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5, T6 item6, T7 item7, TRest rest)
+ {
+ if (!(rest is ITupleInternal))
+ {
throw new ArgumentException(Environment.GetResourceString("ArgumentException_TupleLastArgumentNotATuple"));
}
@@ -835,33 +1098,39 @@ namespace System {
m_Rest = rest;
}
- public override Boolean Equals(Object obj) {
- return ((IStructuralEquatable) this).Equals(obj, EqualityComparer<Object>.Default);;
+ public override Boolean Equals(Object obj)
+ {
+ return ((IStructuralEquatable)this).Equals(obj, EqualityComparer<Object>.Default); ;
}
- Boolean IStructuralEquatable.Equals(Object other, IEqualityComparer comparer) {
+ Boolean IStructuralEquatable.Equals(Object other, IEqualityComparer comparer)
+ {
if (other == null) return false;
Tuple<T1, T2, T3, T4, T5, T6, T7, TRest> objTuple = other as Tuple<T1, T2, T3, T4, T5, T6, T7, TRest>;
- if (objTuple == null) {
+ if (objTuple == null)
+ {
return false;
}
return comparer.Equals(m_Item1, objTuple.m_Item1) && comparer.Equals(m_Item2, objTuple.m_Item2) && comparer.Equals(m_Item3, objTuple.m_Item3) && comparer.Equals(m_Item4, objTuple.m_Item4) && comparer.Equals(m_Item5, objTuple.m_Item5) && comparer.Equals(m_Item6, objTuple.m_Item6) && comparer.Equals(m_Item7, objTuple.m_Item7) && comparer.Equals(m_Rest, objTuple.m_Rest);
}
- Int32 IComparable.CompareTo(Object obj) {
- return ((IStructuralComparable) this).CompareTo(obj, Comparer<Object>.Default);
+ Int32 IComparable.CompareTo(Object obj)
+ {
+ return ((IStructuralComparable)this).CompareTo(obj, Comparer<Object>.Default);
}
- Int32 IStructuralComparable.CompareTo(Object other, IComparer comparer) {
+ Int32 IStructuralComparable.CompareTo(Object other, IComparer comparer)
+ {
if (other == null) return 1;
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()), nameof(other));
+ if (objTuple == null)
+ {
+ throw new ArgumentException(Environment.GetResourceString("ArgumentException_TupleIncorrectType", this.GetType().ToString()), "other");
}
int c = 0;
@@ -897,47 +1166,53 @@ namespace System {
return comparer.Compare(m_Rest, objTuple.m_Rest);
}
- public override int GetHashCode() {
- return ((IStructuralEquatable) this).GetHashCode(EqualityComparer<Object>.Default);
+ public override int GetHashCode()
+ {
+ return ((IStructuralEquatable)this).GetHashCode(EqualityComparer<Object>.Default);
}
- Int32 IStructuralEquatable.GetHashCode(IEqualityComparer comparer) {
+ Int32 IStructuralEquatable.GetHashCode(IEqualityComparer comparer)
+ {
// We want to have a limited hash in this case. We'll use the last 8 elements of the tuple
- ITuple t = (ITuple) m_Rest;
- if(t.Size >= 8) { return t.GetHashCode(comparer); }
-
+ ITupleInternal t = (ITupleInternal)m_Rest;
+ if (t.Length >= 8) { return t.GetHashCode(comparer); }
+
// In this case, the rest memeber has less than 8 elements so we need to combine some our elements with the elements in rest
- int k = 8 - t.Size;
- switch(k) {
+ int k = 8 - t.Length;
+ switch (k)
+ {
case 1:
- return Tuple.CombineHashCodes(comparer.GetHashCode(m_Item7), t.GetHashCode(comparer));
+ return Tuple.CombineHashCodes(comparer.GetHashCode(m_Item7), t.GetHashCode(comparer));
case 2:
- return Tuple.CombineHashCodes(comparer.GetHashCode(m_Item6), comparer.GetHashCode(m_Item7), t.GetHashCode(comparer));
+ return Tuple.CombineHashCodes(comparer.GetHashCode(m_Item6), comparer.GetHashCode(m_Item7), t.GetHashCode(comparer));
case 3:
- return Tuple.CombineHashCodes(comparer.GetHashCode(m_Item5), comparer.GetHashCode(m_Item6), comparer.GetHashCode(m_Item7), t.GetHashCode(comparer));
+ return Tuple.CombineHashCodes(comparer.GetHashCode(m_Item5), comparer.GetHashCode(m_Item6), comparer.GetHashCode(m_Item7), t.GetHashCode(comparer));
case 4:
- return Tuple.CombineHashCodes(comparer.GetHashCode(m_Item4), comparer.GetHashCode(m_Item5), comparer.GetHashCode(m_Item6), comparer.GetHashCode(m_Item7), t.GetHashCode(comparer));
+ return Tuple.CombineHashCodes(comparer.GetHashCode(m_Item4), comparer.GetHashCode(m_Item5), comparer.GetHashCode(m_Item6), comparer.GetHashCode(m_Item7), t.GetHashCode(comparer));
case 5:
- return Tuple.CombineHashCodes(comparer.GetHashCode(m_Item3), comparer.GetHashCode(m_Item4), comparer.GetHashCode(m_Item5), comparer.GetHashCode(m_Item6), comparer.GetHashCode(m_Item7), t.GetHashCode(comparer));
+ return Tuple.CombineHashCodes(comparer.GetHashCode(m_Item3), comparer.GetHashCode(m_Item4), comparer.GetHashCode(m_Item5), comparer.GetHashCode(m_Item6), comparer.GetHashCode(m_Item7), t.GetHashCode(comparer));
case 6:
- return Tuple.CombineHashCodes(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));
+ return Tuple.CombineHashCodes(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));
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));
+ 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));
}
Debug.Assert(false, "Missed all cases for computing Tuple hash code");
return -1;
}
- Int32 ITuple.GetHashCode(IEqualityComparer comparer) {
- return ((IStructuralEquatable) this).GetHashCode(comparer);
+ Int32 ITupleInternal.GetHashCode(IEqualityComparer comparer)
+ {
+ return ((IStructuralEquatable)this).GetHashCode(comparer);
}
- public override string ToString() {
+ public override string ToString()
+ {
StringBuilder sb = new StringBuilder();
sb.Append("(");
- return ((ITuple)this).ToString(sb);
+ return ((ITupleInternal)this).ToString(sb);
}
- string ITuple.ToString(StringBuilder sb) {
+ string ITupleInternal.ToString(StringBuilder sb)
+ {
sb.Append(m_Item1);
sb.Append(", ");
sb.Append(m_Item2);
@@ -952,12 +1227,46 @@ namespace System {
sb.Append(", ");
sb.Append(m_Item7);
sb.Append(", ");
- return ((ITuple)m_Rest).ToString(sb);
+ return ((ITupleInternal)m_Rest).ToString(sb);
+ }
+
+ /// <summary>
+ /// The number of positions in this data structure.
+ /// </summary>
+ int ITuple.Length
+ {
+ get
+ {
+ return 7 + ((ITupleInternal)Rest).Length;
+ }
}
- int ITuple.Size {
- get {
- return 7 + ((ITuple)m_Rest).Size;
+ /// <summary>
+ /// Get the element at position <param name="index"/>.
+ /// </summary>
+ object ITuple.this[int index]
+ {
+ get
+ {
+ switch (index)
+ {
+ case 0:
+ return Item1;
+ case 1:
+ return Item2;
+ case 2:
+ return Item3;
+ case 3:
+ return Item4;
+ case 4:
+ return Item5;
+ case 5:
+ return Item6;
+ case 6:
+ return Item7;
+ }
+
+ return ((ITupleInternal)Rest)[index - 7];
}
}
}
diff --git a/src/mscorlib/src/System/TupleExtensions.cs b/src/mscorlib/src/System/TupleExtensions.cs
new file mode 100644
index 0000000000..b63cb41213
--- /dev/null
+++ b/src/mscorlib/src/System/TupleExtensions.cs
@@ -0,0 +1,930 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+// See the LICENSE file in the project root for more information.
+
+using System.ComponentModel;
+using System.Runtime.CompilerServices;
+
+namespace System
+{
+ /// <summary>
+ /// Provides extension methods for <see cref="Tuple"/> instances to interop with C# tuples features (deconstruction syntax, converting from and to <see cref="ValueTuple"/>).
+ /// </summary>
+ public static class TupleExtensions
+ {
+ #region Deconstruct
+ /// <summary>
+ /// Deconstruct a properly nested <see cref="Tuple"/> with 1 elements.
+ /// </summary>
+ [EditorBrowsable(EditorBrowsableState.Never)]
+ public static void Deconstruct<T1>(
+ this Tuple<T1> value,
+ out T1 item1)
+ {
+ item1 = value.Item1;
+ }
+
+ /// <summary>
+ /// Deconstruct a properly nested <see cref="Tuple"/> with 2 elements.
+ /// </summary>
+ [EditorBrowsable(EditorBrowsableState.Never)]
+ public static void Deconstruct<T1, T2>(
+ this Tuple<T1, T2> value,
+ out T1 item1, out T2 item2)
+ {
+ item1 = value.Item1;
+ item2 = value.Item2;
+ }
+
+ /// <summary>
+ /// Deconstruct a properly nested <see cref="Tuple"/> with 3 elements.
+ /// </summary>
+ [EditorBrowsable(EditorBrowsableState.Never)]
+ public static void Deconstruct<T1, T2, T3>(
+ this Tuple<T1, T2, T3> value,
+ out T1 item1, out T2 item2, out T3 item3)
+ {
+ item1 = value.Item1;
+ item2 = value.Item2;
+ item3 = value.Item3;
+ }
+
+ /// <summary>
+ /// Deconstruct a properly nested <see cref="Tuple"/> with 4 elements.
+ /// </summary>
+ [EditorBrowsable(EditorBrowsableState.Never)]
+ public static void Deconstruct<T1, T2, T3, T4>(
+ this Tuple<T1, T2, T3, T4> value,
+ out T1 item1, out T2 item2, out T3 item3, out T4 item4)
+ {
+ item1 = value.Item1;
+ item2 = value.Item2;
+ item3 = value.Item3;
+ item4 = value.Item4;
+ }
+
+ /// <summary>
+ /// Deconstruct a properly nested <see cref="Tuple"/> with 5 elements.
+ /// </summary>
+ [EditorBrowsable(EditorBrowsableState.Never)]
+ public static void Deconstruct<T1, T2, T3, T4, T5>(
+ this Tuple<T1, T2, T3, T4, T5> value,
+ out T1 item1, out T2 item2, out T3 item3, out T4 item4, out T5 item5)
+ {
+ item1 = value.Item1;
+ item2 = value.Item2;
+ item3 = value.Item3;
+ item4 = value.Item4;
+ item5 = value.Item5;
+ }
+
+ /// <summary>
+ /// Deconstruct a properly nested <see cref="Tuple"/> with 6 elements.
+ /// </summary>
+ [EditorBrowsable(EditorBrowsableState.Never)]
+ public static void Deconstruct<T1, T2, T3, T4, T5, T6>(
+ this Tuple<T1, T2, T3, T4, T5, T6> value,
+ out T1 item1, out T2 item2, out T3 item3, out T4 item4, out T5 item5, out T6 item6)
+ {
+ item1 = value.Item1;
+ item2 = value.Item2;
+ item3 = value.Item3;
+ item4 = value.Item4;
+ item5 = value.Item5;
+ item6 = value.Item6;
+ }
+
+ /// <summary>
+ /// Deconstruct a properly nested <see cref="Tuple"/> with 7 elements.
+ /// </summary>
+ [EditorBrowsable(EditorBrowsableState.Never)]
+ public static void Deconstruct<T1, T2, T3, T4, T5, T6, T7>(
+ this Tuple<T1, T2, T3, T4, T5, T6, T7> value,
+ out T1 item1, out T2 item2, out T3 item3, out T4 item4, out T5 item5, out T6 item6, out T7 item7)
+ {
+ item1 = value.Item1;
+ item2 = value.Item2;
+ item3 = value.Item3;
+ item4 = value.Item4;
+ item5 = value.Item5;
+ item6 = value.Item6;
+ item7 = value.Item7;
+ }
+
+ /// <summary>
+ /// Deconstruct a properly nested <see cref="Tuple"/> with 8 elements.
+ /// </summary>
+ [EditorBrowsable(EditorBrowsableState.Never)]
+ public static void Deconstruct<T1, T2, T3, T4, T5, T6, T7, T8>(
+ this Tuple<T1, T2, T3, T4, T5, T6, T7, Tuple<T8>> value,
+ out T1 item1, out T2 item2, out T3 item3, out T4 item4, out T5 item5, out T6 item6, out T7 item7, out T8 item8)
+ {
+ item1 = value.Item1;
+ item2 = value.Item2;
+ item3 = value.Item3;
+ item4 = value.Item4;
+ item5 = value.Item5;
+ item6 = value.Item6;
+ item7 = value.Item7;
+ item8 = value.Rest.Item1;
+ }
+
+ /// <summary>
+ /// Deconstruct a properly nested <see cref="Tuple"/> with 9 elements.
+ /// </summary>
+ [EditorBrowsable(EditorBrowsableState.Never)]
+ public static void Deconstruct<T1, T2, T3, T4, T5, T6, T7, T8, T9>(
+ this Tuple<T1, T2, T3, T4, T5, T6, T7, Tuple<T8, T9>> value,
+ out T1 item1, out T2 item2, out T3 item3, out T4 item4, out T5 item5, out T6 item6, out T7 item7, out T8 item8, out T9 item9)
+ {
+ item1 = value.Item1;
+ item2 = value.Item2;
+ item3 = value.Item3;
+ item4 = value.Item4;
+ item5 = value.Item5;
+ item6 = value.Item6;
+ item7 = value.Item7;
+ item8 = value.Rest.Item1;
+ item9 = value.Rest.Item2;
+ }
+
+ /// <summary>
+ /// Deconstruct a properly nested <see cref="Tuple"/> with 10 elements.
+ /// </summary>
+ [EditorBrowsable(EditorBrowsableState.Never)]
+ public static void Deconstruct<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10>(
+ this Tuple<T1, T2, T3, T4, T5, T6, T7, Tuple<T8, T9, T10>> value,
+ out T1 item1, out T2 item2, out T3 item3, out T4 item4, out T5 item5, out T6 item6, out T7 item7, out T8 item8, out T9 item9, out T10 item10)
+ {
+ item1 = value.Item1;
+ item2 = value.Item2;
+ item3 = value.Item3;
+ item4 = value.Item4;
+ item5 = value.Item5;
+ item6 = value.Item6;
+ item7 = value.Item7;
+ item8 = value.Rest.Item1;
+ item9 = value.Rest.Item2;
+ item10 = value.Rest.Item3;
+ }
+
+ /// <summary>
+ /// Deconstruct a properly nested <see cref="Tuple"/> with 11 elements.
+ /// </summary>
+ [EditorBrowsable(EditorBrowsableState.Never)]
+ public static void Deconstruct<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11>(
+ this Tuple<T1, T2, T3, T4, T5, T6, T7, Tuple<T8, T9, T10, T11>> value,
+ out T1 item1, out T2 item2, out T3 item3, out T4 item4, out T5 item5, out T6 item6, out T7 item7, out T8 item8, out T9 item9, out T10 item10, out T11 item11)
+ {
+ item1 = value.Item1;
+ item2 = value.Item2;
+ item3 = value.Item3;
+ item4 = value.Item4;
+ item5 = value.Item5;
+ item6 = value.Item6;
+ item7 = value.Item7;
+ item8 = value.Rest.Item1;
+ item9 = value.Rest.Item2;
+ item10 = value.Rest.Item3;
+ item11 = value.Rest.Item4;
+ }
+
+ /// <summary>
+ /// Deconstruct a properly nested <see cref="Tuple"/> with 12 elements.
+ /// </summary>
+ [EditorBrowsable(EditorBrowsableState.Never)]
+ public static void Deconstruct<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12>(
+ this Tuple<T1, T2, T3, T4, T5, T6, T7, Tuple<T8, T9, T10, T11, T12>> value,
+ out T1 item1, out T2 item2, out T3 item3, out T4 item4, out T5 item5, out T6 item6, out T7 item7, out T8 item8, out T9 item9, out T10 item10, out T11 item11, out T12 item12)
+ {
+ item1 = value.Item1;
+ item2 = value.Item2;
+ item3 = value.Item3;
+ item4 = value.Item4;
+ item5 = value.Item5;
+ item6 = value.Item6;
+ item7 = value.Item7;
+ item8 = value.Rest.Item1;
+ item9 = value.Rest.Item2;
+ item10 = value.Rest.Item3;
+ item11 = value.Rest.Item4;
+ item12 = value.Rest.Item5;
+ }
+
+ /// <summary>
+ /// Deconstruct a properly nested <see cref="Tuple"/> with 13 elements.
+ /// </summary>
+ [EditorBrowsable(EditorBrowsableState.Never)]
+ public static void Deconstruct<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13>(
+ this Tuple<T1, T2, T3, T4, T5, T6, T7, Tuple<T8, T9, T10, T11, T12, T13>> value,
+ out T1 item1, out T2 item2, out T3 item3, out T4 item4, out T5 item5, out T6 item6, out T7 item7, out T8 item8, out T9 item9, out T10 item10, out T11 item11, out T12 item12, out T13 item13)
+ {
+ item1 = value.Item1;
+ item2 = value.Item2;
+ item3 = value.Item3;
+ item4 = value.Item4;
+ item5 = value.Item5;
+ item6 = value.Item6;
+ item7 = value.Item7;
+ item8 = value.Rest.Item1;
+ item9 = value.Rest.Item2;
+ item10 = value.Rest.Item3;
+ item11 = value.Rest.Item4;
+ item12 = value.Rest.Item5;
+ item13 = value.Rest.Item6;
+ }
+
+ /// <summary>
+ /// Deconstruct a properly nested <see cref="Tuple"/> with 14 elements.
+ /// </summary>
+ [EditorBrowsable(EditorBrowsableState.Never)]
+ public static void Deconstruct<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14>(
+ this Tuple<T1, T2, T3, T4, T5, T6, T7, Tuple<T8, T9, T10, T11, T12, T13, T14>> value,
+ out T1 item1, out T2 item2, out T3 item3, out T4 item4, out T5 item5, out T6 item6, out T7 item7, out T8 item8, out T9 item9, out T10 item10, out T11 item11, out T12 item12, out T13 item13, out T14 item14)
+ {
+ item1 = value.Item1;
+ item2 = value.Item2;
+ item3 = value.Item3;
+ item4 = value.Item4;
+ item5 = value.Item5;
+ item6 = value.Item6;
+ item7 = value.Item7;
+ item8 = value.Rest.Item1;
+ item9 = value.Rest.Item2;
+ item10 = value.Rest.Item3;
+ item11 = value.Rest.Item4;
+ item12 = value.Rest.Item5;
+ item13 = value.Rest.Item6;
+ item14 = value.Rest.Item7;
+ }
+
+ /// <summary>
+ /// Deconstruct a properly nested <see cref="Tuple"/> with 15 elements.
+ /// </summary>
+ [EditorBrowsable(EditorBrowsableState.Never)]
+ public static void Deconstruct<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15>(
+ this Tuple<T1, T2, T3, T4, T5, T6, T7, Tuple<T8, T9, T10, T11, T12, T13, T14, Tuple<T15>>> value,
+ out T1 item1, out T2 item2, out T3 item3, out T4 item4, out T5 item5, out T6 item6, out T7 item7, out T8 item8, out T9 item9, out T10 item10, out T11 item11, out T12 item12, out T13 item13, out T14 item14, out T15 item15)
+ {
+ item1 = value.Item1;
+ item2 = value.Item2;
+ item3 = value.Item3;
+ item4 = value.Item4;
+ item5 = value.Item5;
+ item6 = value.Item6;
+ item7 = value.Item7;
+ item8 = value.Rest.Item1;
+ item9 = value.Rest.Item2;
+ item10 = value.Rest.Item3;
+ item11 = value.Rest.Item4;
+ item12 = value.Rest.Item5;
+ item13 = value.Rest.Item6;
+ item14 = value.Rest.Item7;
+ item15 = value.Rest.Rest.Item1;
+ }
+
+ /// <summary>
+ /// Deconstruct a properly nested <see cref="Tuple"/> with 16 elements.
+ /// </summary>
+ [EditorBrowsable(EditorBrowsableState.Never)]
+ public static void Deconstruct<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16>(
+ this Tuple<T1, T2, T3, T4, T5, T6, T7, Tuple<T8, T9, T10, T11, T12, T13, T14, Tuple<T15, T16>>> value,
+ out T1 item1, out T2 item2, out T3 item3, out T4 item4, out T5 item5, out T6 item6, out T7 item7, out T8 item8, out T9 item9, out T10 item10, out T11 item11, out T12 item12, out T13 item13, out T14 item14, out T15 item15, out T16 item16)
+ {
+ item1 = value.Item1;
+ item2 = value.Item2;
+ item3 = value.Item3;
+ item4 = value.Item4;
+ item5 = value.Item5;
+ item6 = value.Item6;
+ item7 = value.Item7;
+ item8 = value.Rest.Item1;
+ item9 = value.Rest.Item2;
+ item10 = value.Rest.Item3;
+ item11 = value.Rest.Item4;
+ item12 = value.Rest.Item5;
+ item13 = value.Rest.Item6;
+ item14 = value.Rest.Item7;
+ item15 = value.Rest.Rest.Item1;
+ item16 = value.Rest.Rest.Item2;
+ }
+
+ /// <summary>
+ /// Deconstruct a properly nested <see cref="Tuple"/> with 17 elements.
+ /// </summary>
+ [EditorBrowsable(EditorBrowsableState.Never)]
+ public static void Deconstruct<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17>(
+ this Tuple<T1, T2, T3, T4, T5, T6, T7, Tuple<T8, T9, T10, T11, T12, T13, T14, Tuple<T15, T16, T17>>> value,
+ out T1 item1, out T2 item2, out T3 item3, out T4 item4, out T5 item5, out T6 item6, out T7 item7, out T8 item8, out T9 item9, out T10 item10, out T11 item11, out T12 item12, out T13 item13, out T14 item14, out T15 item15, out T16 item16, out T17 item17)
+ {
+ item1 = value.Item1;
+ item2 = value.Item2;
+ item3 = value.Item3;
+ item4 = value.Item4;
+ item5 = value.Item5;
+ item6 = value.Item6;
+ item7 = value.Item7;
+ item8 = value.Rest.Item1;
+ item9 = value.Rest.Item2;
+ item10 = value.Rest.Item3;
+ item11 = value.Rest.Item4;
+ item12 = value.Rest.Item5;
+ item13 = value.Rest.Item6;
+ item14 = value.Rest.Item7;
+ item15 = value.Rest.Rest.Item1;
+ item16 = value.Rest.Rest.Item2;
+ item17 = value.Rest.Rest.Item3;
+ }
+
+ /// <summary>
+ /// Deconstruct a properly nested <see cref="Tuple"/> with 18 elements.
+ /// </summary>
+ [EditorBrowsable(EditorBrowsableState.Never)]
+ public static void Deconstruct<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18>(
+ this Tuple<T1, T2, T3, T4, T5, T6, T7, Tuple<T8, T9, T10, T11, T12, T13, T14, Tuple<T15, T16, T17, T18>>> value,
+ out T1 item1, out T2 item2, out T3 item3, out T4 item4, out T5 item5, out T6 item6, out T7 item7, out T8 item8, out T9 item9, out T10 item10, out T11 item11, out T12 item12, out T13 item13, out T14 item14, out T15 item15, out T16 item16, out T17 item17, out T18 item18)
+ {
+ item1 = value.Item1;
+ item2 = value.Item2;
+ item3 = value.Item3;
+ item4 = value.Item4;
+ item5 = value.Item5;
+ item6 = value.Item6;
+ item7 = value.Item7;
+ item8 = value.Rest.Item1;
+ item9 = value.Rest.Item2;
+ item10 = value.Rest.Item3;
+ item11 = value.Rest.Item4;
+ item12 = value.Rest.Item5;
+ item13 = value.Rest.Item6;
+ item14 = value.Rest.Item7;
+ item15 = value.Rest.Rest.Item1;
+ item16 = value.Rest.Rest.Item2;
+ item17 = value.Rest.Rest.Item3;
+ item18 = value.Rest.Rest.Item4;
+ }
+
+ /// <summary>
+ /// Deconstruct a properly nested <see cref="Tuple"/> with 19 elements.
+ /// </summary>
+ [EditorBrowsable(EditorBrowsableState.Never)]
+ public static void Deconstruct<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19>(
+ this Tuple<T1, T2, T3, T4, T5, T6, T7, Tuple<T8, T9, T10, T11, T12, T13, T14, Tuple<T15, T16, T17, T18, T19>>> value,
+ out T1 item1, out T2 item2, out T3 item3, out T4 item4, out T5 item5, out T6 item6, out T7 item7, out T8 item8, out T9 item9, out T10 item10, out T11 item11, out T12 item12, out T13 item13, out T14 item14, out T15 item15, out T16 item16, out T17 item17, out T18 item18, out T19 item19)
+ {
+ item1 = value.Item1;
+ item2 = value.Item2;
+ item3 = value.Item3;
+ item4 = value.Item4;
+ item5 = value.Item5;
+ item6 = value.Item6;
+ item7 = value.Item7;
+ item8 = value.Rest.Item1;
+ item9 = value.Rest.Item2;
+ item10 = value.Rest.Item3;
+ item11 = value.Rest.Item4;
+ item12 = value.Rest.Item5;
+ item13 = value.Rest.Item6;
+ item14 = value.Rest.Item7;
+ item15 = value.Rest.Rest.Item1;
+ item16 = value.Rest.Rest.Item2;
+ item17 = value.Rest.Rest.Item3;
+ item18 = value.Rest.Rest.Item4;
+ item19 = value.Rest.Rest.Item5;
+ }
+
+ /// <summary>
+ /// Deconstruct a properly nested <see cref="Tuple"/> with 20 elements.
+ /// </summary>
+ [EditorBrowsable(EditorBrowsableState.Never)]
+ public static void Deconstruct<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20>(
+ this Tuple<T1, T2, T3, T4, T5, T6, T7, Tuple<T8, T9, T10, T11, T12, T13, T14, Tuple<T15, T16, T17, T18, T19, T20>>> value,
+ out T1 item1, out T2 item2, out T3 item3, out T4 item4, out T5 item5, out T6 item6, out T7 item7, out T8 item8, out T9 item9, out T10 item10, out T11 item11, out T12 item12, out T13 item13, out T14 item14, out T15 item15, out T16 item16, out T17 item17, out T18 item18, out T19 item19, out T20 item20)
+ {
+ item1 = value.Item1;
+ item2 = value.Item2;
+ item3 = value.Item3;
+ item4 = value.Item4;
+ item5 = value.Item5;
+ item6 = value.Item6;
+ item7 = value.Item7;
+ item8 = value.Rest.Item1;
+ item9 = value.Rest.Item2;
+ item10 = value.Rest.Item3;
+ item11 = value.Rest.Item4;
+ item12 = value.Rest.Item5;
+ item13 = value.Rest.Item6;
+ item14 = value.Rest.Item7;
+ item15 = value.Rest.Rest.Item1;
+ item16 = value.Rest.Rest.Item2;
+ item17 = value.Rest.Rest.Item3;
+ item18 = value.Rest.Rest.Item4;
+ item19 = value.Rest.Rest.Item5;
+ item20 = value.Rest.Rest.Item6;
+ }
+
+ /// <summary>
+ /// Deconstruct a properly nested <see cref="Tuple"/> with 21 elements.
+ /// </summary>
+ [EditorBrowsable(EditorBrowsableState.Never)]
+ public static void Deconstruct<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21>(
+ this Tuple<T1, T2, T3, T4, T5, T6, T7, Tuple<T8, T9, T10, T11, T12, T13, T14, Tuple<T15, T16, T17, T18, T19, T20, T21>>> value,
+ out T1 item1, out T2 item2, out T3 item3, out T4 item4, out T5 item5, out T6 item6, out T7 item7, out T8 item8, out T9 item9, out T10 item10, out T11 item11, out T12 item12, out T13 item13, out T14 item14, out T15 item15, out T16 item16, out T17 item17, out T18 item18, out T19 item19, out T20 item20, out T21 item21)
+ {
+ item1 = value.Item1;
+ item2 = value.Item2;
+ item3 = value.Item3;
+ item4 = value.Item4;
+ item5 = value.Item5;
+ item6 = value.Item6;
+ item7 = value.Item7;
+ item8 = value.Rest.Item1;
+ item9 = value.Rest.Item2;
+ item10 = value.Rest.Item3;
+ item11 = value.Rest.Item4;
+ item12 = value.Rest.Item5;
+ item13 = value.Rest.Item6;
+ item14 = value.Rest.Item7;
+ item15 = value.Rest.Rest.Item1;
+ item16 = value.Rest.Rest.Item2;
+ item17 = value.Rest.Rest.Item3;
+ item18 = value.Rest.Rest.Item4;
+ item19 = value.Rest.Rest.Item5;
+ item20 = value.Rest.Rest.Item6;
+ item21 = value.Rest.Rest.Item7;
+ }
+ #endregion
+
+ #region ToValueTuple
+ /// <summary>
+ /// Make a properly nested <see cref="ValueTuple"/> from a properly nested <see cref="Tuple"/> with 1 element.
+ /// </summary>
+ public static ValueTuple<T1>
+ ToValueTuple<T1>(
+ this Tuple<T1> value)
+ {
+ return ValueTuple.Create(value.Item1);
+ }
+
+ /// <summary>
+ /// Make a properly nested <see cref="ValueTuple"/> from a properly nested <see cref="Tuple"/> with 2 elements.
+ /// </summary>
+ public static ValueTuple<T1, T2>
+ ToValueTuple<T1, T2>(
+ this Tuple<T1, T2> value)
+ {
+ return ValueTuple.Create(value.Item1, value.Item2);
+ }
+
+ /// <summary>
+ /// Make a properly nested <see cref="ValueTuple"/> from a properly nested <see cref="Tuple"/> with 3 elements.
+ /// </summary>
+ public static ValueTuple<T1, T2, T3>
+ ToValueTuple<T1, T2, T3>(
+ this Tuple<T1, T2, T3> value)
+ {
+ return ValueTuple.Create(value.Item1, value.Item2, value.Item3);
+ }
+
+ /// <summary>
+ /// Make a properly nested <see cref="ValueTuple"/> from a properly nested <see cref="Tuple"/> with 4 elements.
+ /// </summary>
+ public static ValueTuple<T1, T2, T3, T4>
+ ToValueTuple<T1, T2, T3, T4>(
+ this Tuple<T1, T2, T3, T4> value)
+ {
+ return ValueTuple.Create(value.Item1, value.Item2, value.Item3, value.Item4);
+ }
+
+ /// <summary>
+ /// Make a properly nested <see cref="ValueTuple"/> from a properly nested <see cref="Tuple"/> with 5 elements.
+ /// </summary>
+ public static ValueTuple<T1, T2, T3, T4, T5>
+ ToValueTuple<T1, T2, T3, T4, T5>(
+ this Tuple<T1, T2, T3, T4, T5> value)
+ {
+ return ValueTuple.Create(value.Item1, value.Item2, value.Item3, value.Item4, value.Item5);
+ }
+
+ /// <summary>
+ /// Make a properly nested <see cref="ValueTuple"/> from a properly nested <see cref="Tuple"/> with 6 elements.
+ /// </summary>
+ public static ValueTuple<T1, T2, T3, T4, T5, T6>
+ ToValueTuple<T1, T2, T3, T4, T5, T6>(
+ this Tuple<T1, T2, T3, T4, T5, T6> value)
+ {
+ return ValueTuple.Create(value.Item1, value.Item2, value.Item3, value.Item4, value.Item5, value.Item6);
+ }
+
+ /// <summary>
+ /// Make a properly nested <see cref="ValueTuple"/> from a properly nested <see cref="Tuple"/> with 7 elements.
+ /// </summary>
+ public static ValueTuple<T1, T2, T3, T4, T5, T6, T7>
+ ToValueTuple<T1, T2, T3, T4, T5, T6, T7>(
+ this Tuple<T1, T2, T3, T4, T5, T6, T7> value)
+ {
+ return ValueTuple.Create(value.Item1, value.Item2, value.Item3, value.Item4, value.Item5, value.Item6, value.Item7);
+ }
+
+ /// <summary>
+ /// Make a properly nested <see cref="ValueTuple"/> from a properly nested <see cref="Tuple"/> with 8 elements.
+ /// </summary>
+ public static ValueTuple<T1, T2, T3, T4, T5, T6, T7, ValueTuple<T8>>
+ ToValueTuple<T1, T2, T3, T4, T5, T6, T7, T8>(
+ this Tuple<T1, T2, T3, T4, T5, T6, T7, Tuple<T8>> value)
+ {
+ return CreateLong(value.Item1, value.Item2, value.Item3, value.Item4, value.Item5, value.Item6, value.Item7,
+ ValueTuple.Create(value.Rest.Item1));
+ }
+
+ /// <summary>
+ /// Make a properly nested <see cref="ValueTuple"/> from a properly nested <see cref="Tuple"/> with 9 elements.
+ /// </summary>
+ public static ValueTuple<T1, T2, T3, T4, T5, T6, T7, ValueTuple<T8, T9>>
+ ToValueTuple<T1, T2, T3, T4, T5, T6, T7, T8, T9>(
+ this Tuple<T1, T2, T3, T4, T5, T6, T7, Tuple<T8, T9>> value)
+ {
+ return CreateLong(value.Item1, value.Item2, value.Item3, value.Item4, value.Item5, value.Item6, value.Item7,
+ ValueTuple.Create(value.Rest.Item1, value.Rest.Item2));
+ }
+
+ /// <summary>
+ /// Make a properly nested <see cref="ValueTuple"/> from a properly nested <see cref="Tuple"/> with 10 elements.
+ /// </summary>
+ public static ValueTuple<T1, T2, T3, T4, T5, T6, T7, ValueTuple<T8, T9, T10>>
+ ToValueTuple<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10>(
+ this Tuple<T1, T2, T3, T4, T5, T6, T7, Tuple<T8, T9, T10>> value)
+ {
+ return CreateLong(value.Item1, value.Item2, value.Item3, value.Item4, value.Item5, value.Item6, value.Item7,
+ ValueTuple.Create(value.Rest.Item1, value.Rest.Item2, value.Rest.Item3));
+ }
+
+ /// <summary>
+ /// Make a properly nested <see cref="ValueTuple"/> from a properly nested <see cref="Tuple"/> with 11 elements.
+ /// </summary>
+ public static ValueTuple<T1, T2, T3, T4, T5, T6, T7, ValueTuple<T8, T9, T10, T11>>
+ ToValueTuple<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11>(
+ this Tuple<T1, T2, T3, T4, T5, T6, T7, Tuple<T8, T9, T10, T11>> value)
+ {
+ return CreateLong(value.Item1, value.Item2, value.Item3, value.Item4, value.Item5, value.Item6, value.Item7,
+ ValueTuple.Create(value.Rest.Item1, value.Rest.Item2, value.Rest.Item3, value.Rest.Item4));
+ }
+
+ /// <summary>
+ /// Make a properly nested <see cref="ValueTuple"/> from a properly nested <see cref="Tuple"/> with 12 elements.
+ /// </summary>
+ public static ValueTuple<T1, T2, T3, T4, T5, T6, T7, ValueTuple<T8, T9, T10, T11, T12>>
+ ToValueTuple<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12>(
+ this Tuple<T1, T2, T3, T4, T5, T6, T7, Tuple<T8, T9, T10, T11, T12>> value)
+ {
+ return CreateLong(value.Item1, value.Item2, value.Item3, value.Item4, value.Item5, value.Item6, value.Item7,
+ ValueTuple.Create(value.Rest.Item1, value.Rest.Item2, value.Rest.Item3, value.Rest.Item4, value.Rest.Item5));
+ }
+
+ /// <summary>
+ /// Make a properly nested <see cref="ValueTuple"/> from a properly nested <see cref="Tuple"/> with 13 elements.
+ /// </summary>
+ public static ValueTuple<T1, T2, T3, T4, T5, T6, T7, ValueTuple<T8, T9, T10, T11, T12, T13>>
+ ToValueTuple<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13>(
+ this Tuple<T1, T2, T3, T4, T5, T6, T7, Tuple<T8, T9, T10, T11, T12, T13>> value)
+ {
+ return CreateLong(value.Item1, value.Item2, value.Item3, value.Item4, value.Item5, value.Item6, value.Item7,
+ ValueTuple.Create(value.Rest.Item1, value.Rest.Item2, value.Rest.Item3, value.Rest.Item4, value.Rest.Item5, value.Rest.Item6));
+ }
+
+ /// <summary>
+ /// Make a properly nested <see cref="ValueTuple"/> from a properly nested <see cref="Tuple"/> with 14 elements.
+ /// </summary>
+ public static ValueTuple<T1, T2, T3, T4, T5, T6, T7, ValueTuple<T8, T9, T10, T11, T12, T13, T14>>
+ ToValueTuple<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14>(
+ this Tuple<T1, T2, T3, T4, T5, T6, T7, Tuple<T8, T9, T10, T11, T12, T13, T14>> value)
+ {
+ return CreateLong(value.Item1, value.Item2, value.Item3, value.Item4, value.Item5, value.Item6, value.Item7,
+ ValueTuple.Create(value.Rest.Item1, value.Rest.Item2, value.Rest.Item3, value.Rest.Item4, value.Rest.Item5, value.Rest.Item6, value.Rest.Item7));
+ }
+
+ /// <summary>
+ /// Make a properly nested <see cref="ValueTuple"/> from a properly nested <see cref="Tuple"/> with 15 elements.
+ /// </summary>
+ public static ValueTuple<T1, T2, T3, T4, T5, T6, T7, ValueTuple<T8, T9, T10, T11, T12, T13, T14, ValueTuple<T15>>>
+ ToValueTuple<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15>(
+ this Tuple<T1, T2, T3, T4, T5, T6, T7, Tuple<T8, T9, T10, T11, T12, T13, T14, Tuple<T15>>> value)
+ {
+ return CreateLong(value.Item1, value.Item2, value.Item3, value.Item4, value.Item5, value.Item6, value.Item7,
+ CreateLong(value.Rest.Item1, value.Rest.Item2, value.Rest.Item3, value.Rest.Item4, value.Rest.Item5, value.Rest.Item6, value.Rest.Item7,
+ ValueTuple.Create(value.Rest.Rest.Item1)));
+ }
+
+ /// <summary>
+ /// Make a properly nested <see cref="ValueTuple"/> from a properly nested <see cref="Tuple"/> with 16 elements.
+ /// </summary>
+ public static ValueTuple<T1, T2, T3, T4, T5, T6, T7, ValueTuple<T8, T9, T10, T11, T12, T13, T14, ValueTuple<T15, T16>>>
+ ToValueTuple<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16>(
+ this Tuple<T1, T2, T3, T4, T5, T6, T7, Tuple<T8, T9, T10, T11, T12, T13, T14, Tuple<T15, T16>>> value)
+ {
+ return CreateLong(value.Item1, value.Item2, value.Item3, value.Item4, value.Item5, value.Item6, value.Item7,
+ CreateLong(value.Rest.Item1, value.Rest.Item2, value.Rest.Item3, value.Rest.Item4, value.Rest.Item5, value.Rest.Item6, value.Rest.Item7,
+ ValueTuple.Create(value.Rest.Rest.Item1, value.Rest.Rest.Item2)));
+ }
+
+ /// <summary>
+ /// Make a properly nested <see cref="ValueTuple"/> from a properly nested <see cref="Tuple"/> with 17 elements.
+ /// </summary>
+ public static ValueTuple<T1, T2, T3, T4, T5, T6, T7, ValueTuple<T8, T9, T10, T11, T12, T13, T14, ValueTuple<T15, T16, T17>>>
+ ToValueTuple<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17>(
+ this Tuple<T1, T2, T3, T4, T5, T6, T7, Tuple<T8, T9, T10, T11, T12, T13, T14, Tuple<T15, T16, T17>>> value)
+ {
+ return CreateLong(value.Item1, value.Item2, value.Item3, value.Item4, value.Item5, value.Item6, value.Item7,
+ CreateLong(value.Rest.Item1, value.Rest.Item2, value.Rest.Item3, value.Rest.Item4, value.Rest.Item5, value.Rest.Item6, value.Rest.Item7,
+ ValueTuple.Create(value.Rest.Rest.Item1, value.Rest.Rest.Item2, value.Rest.Rest.Item3)));
+ }
+
+ /// <summary>
+ /// Make a properly nested <see cref="ValueTuple"/> from a properly nested <see cref="Tuple"/> with 18 elements.
+ /// </summary>
+ public static ValueTuple<T1, T2, T3, T4, T5, T6, T7, ValueTuple<T8, T9, T10, T11, T12, T13, T14, ValueTuple<T15, T16, T17, T18>>>
+ ToValueTuple<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18>(
+ this Tuple<T1, T2, T3, T4, T5, T6, T7, Tuple<T8, T9, T10, T11, T12, T13, T14, Tuple<T15, T16, T17, T18>>> value)
+ {
+ return CreateLong(value.Item1, value.Item2, value.Item3, value.Item4, value.Item5, value.Item6, value.Item7,
+ CreateLong(value.Rest.Item1, value.Rest.Item2, value.Rest.Item3, value.Rest.Item4, value.Rest.Item5, value.Rest.Item6, value.Rest.Item7,
+ ValueTuple.Create(value.Rest.Rest.Item1, value.Rest.Rest.Item2, value.Rest.Rest.Item3, value.Rest.Rest.Item4)));
+ }
+
+ /// <summary>
+ /// Make a properly nested <see cref="ValueTuple"/> from a properly nested <see cref="Tuple"/> with 19 elements.
+ /// </summary>
+ public static ValueTuple<T1, T2, T3, T4, T5, T6, T7, ValueTuple<T8, T9, T10, T11, T12, T13, T14, ValueTuple<T15, T16, T17, T18, T19>>>
+ ToValueTuple<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19>(
+ this Tuple<T1, T2, T3, T4, T5, T6, T7, Tuple<T8, T9, T10, T11, T12, T13, T14, Tuple<T15, T16, T17, T18, T19>>> value)
+ {
+ return CreateLong(value.Item1, value.Item2, value.Item3, value.Item4, value.Item5, value.Item6, value.Item7,
+ CreateLong(value.Rest.Item1, value.Rest.Item2, value.Rest.Item3, value.Rest.Item4, value.Rest.Item5, value.Rest.Item6, value.Rest.Item7,
+ ValueTuple.Create(value.Rest.Rest.Item1, value.Rest.Rest.Item2, value.Rest.Rest.Item3, value.Rest.Rest.Item4, value.Rest.Rest.Item5)));
+ }
+
+ /// <summary>
+ /// Make a properly nested <see cref="ValueTuple"/> from a properly nested <see cref="Tuple"/> with 20 elements.
+ /// </summary>
+ public static ValueTuple<T1, T2, T3, T4, T5, T6, T7, ValueTuple<T8, T9, T10, T11, T12, T13, T14, ValueTuple<T15, T16, T17, T18, T19, T20>>>
+ ToValueTuple<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20>(
+ this Tuple<T1, T2, T3, T4, T5, T6, T7, Tuple<T8, T9, T10, T11, T12, T13, T14, Tuple<T15, T16, T17, T18, T19, T20>>> value)
+ {
+ return CreateLong(value.Item1, value.Item2, value.Item3, value.Item4, value.Item5, value.Item6, value.Item7,
+ CreateLong(value.Rest.Item1, value.Rest.Item2, value.Rest.Item3, value.Rest.Item4, value.Rest.Item5, value.Rest.Item6, value.Rest.Item7,
+ ValueTuple.Create(value.Rest.Rest.Item1, value.Rest.Rest.Item2, value.Rest.Rest.Item3, value.Rest.Rest.Item4, value.Rest.Rest.Item5, value.Rest.Rest.Item6)));
+ }
+
+ /// <summary>
+ /// Make a properly nested <see cref="ValueTuple"/> from a properly nested <see cref="Tuple"/> with 21 elements.
+ /// </summary>
+ public static ValueTuple<T1, T2, T3, T4, T5, T6, T7, ValueTuple<T8, T9, T10, T11, T12, T13, T14, ValueTuple<T15, T16, T17, T18, T19, T20, T21>>>
+ ToValueTuple<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21>(
+ this Tuple<T1, T2, T3, T4, T5, T6, T7, Tuple<T8, T9, T10, T11, T12, T13, T14, Tuple<T15, T16, T17, T18, T19, T20, T21>>> value)
+ {
+ return CreateLong(value.Item1, value.Item2, value.Item3, value.Item4, value.Item5, value.Item6, value.Item7,
+ CreateLong(value.Rest.Item1, value.Rest.Item2, value.Rest.Item3, value.Rest.Item4, value.Rest.Item5, value.Rest.Item6, value.Rest.Item7,
+ ValueTuple.Create(value.Rest.Rest.Item1, value.Rest.Rest.Item2, value.Rest.Rest.Item3, value.Rest.Rest.Item4, value.Rest.Rest.Item5, value.Rest.Rest.Item6, value.Rest.Rest.Item7)));
+ }
+ #endregion
+
+ #region ToTuple
+ /// <summary>
+ /// Make a properly nested <see cref="Tuple"/> from a properly nested <see cref="ValueTuple"/> with 1 element.
+ /// </summary>
+ public static Tuple<T1>
+ ToTuple<T1>(
+ this ValueTuple<T1> value)
+ {
+ return Tuple.Create(value.Item1);
+ }
+
+ /// <summary>
+ /// Make a properly nested <see cref="Tuple"/> from a properly nested <see cref="ValueTuple"/> with 2 elements.
+ /// </summary>
+ public static Tuple<T1, T2>
+ ToTuple<T1, T2>(
+ this ValueTuple<T1, T2> value)
+ {
+ return Tuple.Create(value.Item1, value.Item2);
+ }
+
+ /// <summary>
+ /// Make a properly nested <see cref="Tuple"/> from a properly nested <see cref="ValueTuple"/> with 3 elements.
+ /// </summary>
+ public static Tuple<T1, T2, T3>
+ ToTuple<T1, T2, T3>(
+ this ValueTuple<T1, T2, T3> value)
+ {
+ return Tuple.Create(value.Item1, value.Item2, value.Item3);
+ }
+
+ /// <summary>
+ /// Make a properly nested <see cref="Tuple"/> from a properly nested <see cref="ValueTuple"/> with 4 elements.
+ /// </summary>
+ public static Tuple<T1, T2, T3, T4>
+ ToTuple<T1, T2, T3, T4>(
+ this ValueTuple<T1, T2, T3, T4> value)
+ {
+ return Tuple.Create(value.Item1, value.Item2, value.Item3, value.Item4);
+ }
+
+ /// <summary>
+ /// Make a properly nested <see cref="Tuple"/> from a properly nested <see cref="ValueTuple"/> with 5 elements.
+ /// </summary>
+ public static Tuple<T1, T2, T3, T4, T5>
+ ToTuple<T1, T2, T3, T4, T5>(
+ this ValueTuple<T1, T2, T3, T4, T5> value)
+ {
+ return Tuple.Create(value.Item1, value.Item2, value.Item3, value.Item4, value.Item5);
+ }
+
+ /// <summary>
+ /// Make a properly nested <see cref="Tuple"/> from a properly nested <see cref="ValueTuple"/> with 6 elements.
+ /// </summary>
+ public static Tuple<T1, T2, T3, T4, T5, T6>
+ ToTuple<T1, T2, T3, T4, T5, T6>(
+ this ValueTuple<T1, T2, T3, T4, T5, T6> value)
+ {
+ return Tuple.Create(value.Item1, value.Item2, value.Item3, value.Item4, value.Item5, value.Item6);
+ }
+
+ /// <summary>
+ /// Make a properly nested <see cref="Tuple"/> from a properly nested <see cref="ValueTuple"/> with 7 elements.
+ /// </summary>
+ public static Tuple<T1, T2, T3, T4, T5, T6, T7>
+ ToTuple<T1, T2, T3, T4, T5, T6, T7>(
+ this ValueTuple<T1, T2, T3, T4, T5, T6, T7> value)
+ {
+ return Tuple.Create(value.Item1, value.Item2, value.Item3, value.Item4, value.Item5, value.Item6, value.Item7);
+ }
+
+ /// <summary>
+ /// Make a properly nested <see cref="Tuple"/> from a properly nested <see cref="ValueTuple"/> with 8 elements.
+ /// </summary>
+ public static Tuple<T1, T2, T3, T4, T5, T6, T7, Tuple<T8>>
+ ToTuple<T1, T2, T3, T4, T5, T6, T7, T8>(
+ this ValueTuple<T1, T2, T3, T4, T5, T6, T7, ValueTuple<T8>> value)
+ {
+ return CreateLongRef(value.Item1, value.Item2, value.Item3, value.Item4, value.Item5, value.Item6, value.Item7,
+ Tuple.Create(value.Rest.Item1));
+ }
+
+ /// <summary>
+ /// Make a properly nested <see cref="Tuple"/> from a properly nested <see cref="ValueTuple"/> with 9 elements.
+ /// </summary>
+ public static Tuple<T1, T2, T3, T4, T5, T6, T7, Tuple<T8, T9>>
+ ToTuple<T1, T2, T3, T4, T5, T6, T7, T8, T9>(
+ this ValueTuple<T1, T2, T3, T4, T5, T6, T7, ValueTuple<T8, T9>> value)
+ {
+ return CreateLongRef(value.Item1, value.Item2, value.Item3, value.Item4, value.Item5, value.Item6, value.Item7,
+ Tuple.Create(value.Rest.Item1, value.Rest.Item2));
+ }
+
+ /// <summary>
+ /// Make a properly nested <see cref="Tuple"/> from a properly nested <see cref="ValueTuple"/> with 10 elements.
+ /// </summary>
+ public static Tuple<T1, T2, T3, T4, T5, T6, T7, Tuple<T8, T9, T10>>
+ ToTuple<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10>(
+ this ValueTuple<T1, T2, T3, T4, T5, T6, T7, ValueTuple<T8, T9, T10>> value)
+ {
+ return CreateLongRef(value.Item1, value.Item2, value.Item3, value.Item4, value.Item5, value.Item6, value.Item7,
+ Tuple.Create(value.Rest.Item1, value.Rest.Item2, value.Rest.Item3));
+ }
+
+ /// <summary>
+ /// Make a properly nested <see cref="Tuple"/> from a properly nested <see cref="ValueTuple"/> with 11 elements.
+ /// </summary>
+ public static Tuple<T1, T2, T3, T4, T5, T6, T7, Tuple<T8, T9, T10, T11>>
+ ToTuple<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11>(
+ this ValueTuple<T1, T2, T3, T4, T5, T6, T7, ValueTuple<T8, T9, T10, T11>> value)
+ {
+ return CreateLongRef(value.Item1, value.Item2, value.Item3, value.Item4, value.Item5, value.Item6, value.Item7,
+ Tuple.Create(value.Rest.Item1, value.Rest.Item2, value.Rest.Item3, value.Rest.Item4));
+ }
+
+ /// <summary>
+ /// Make a properly nested <see cref="Tuple"/> from a properly nested <see cref="ValueTuple"/> with 12 elements.
+ /// </summary>
+ public static Tuple<T1, T2, T3, T4, T5, T6, T7, Tuple<T8, T9, T10, T11, T12>>
+ ToTuple<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12>(
+ this ValueTuple<T1, T2, T3, T4, T5, T6, T7, ValueTuple<T8, T9, T10, T11, T12>> value)
+ {
+ return CreateLongRef(value.Item1, value.Item2, value.Item3, value.Item4, value.Item5, value.Item6, value.Item7,
+ Tuple.Create(value.Rest.Item1, value.Rest.Item2, value.Rest.Item3, value.Rest.Item4, value.Rest.Item5));
+ }
+
+ /// <summary>
+ /// Make a properly nested <see cref="Tuple"/> from a properly nested <see cref="ValueTuple"/> with 13 elements.
+ /// </summary>
+ public static Tuple<T1, T2, T3, T4, T5, T6, T7, Tuple<T8, T9, T10, T11, T12, T13>>
+ ToTuple<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13>(
+ this ValueTuple<T1, T2, T3, T4, T5, T6, T7, ValueTuple<T8, T9, T10, T11, T12, T13>> value)
+ {
+ return CreateLongRef(value.Item1, value.Item2, value.Item3, value.Item4, value.Item5, value.Item6, value.Item7,
+ Tuple.Create(value.Rest.Item1, value.Rest.Item2, value.Rest.Item3, value.Rest.Item4, value.Rest.Item5, value.Rest.Item6));
+ }
+
+ /// <summary>
+ /// Make a properly nested <see cref="Tuple"/> from a properly nested <see cref="ValueTuple"/> with 14 elements.
+ /// </summary>
+ public static Tuple<T1, T2, T3, T4, T5, T6, T7, Tuple<T8, T9, T10, T11, T12, T13, T14>>
+ ToTuple<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14>(
+ this ValueTuple<T1, T2, T3, T4, T5, T6, T7, ValueTuple<T8, T9, T10, T11, T12, T13, T14>> value)
+ {
+ return CreateLongRef(value.Item1, value.Item2, value.Item3, value.Item4, value.Item5, value.Item6, value.Item7,
+ Tuple.Create(value.Rest.Item1, value.Rest.Item2, value.Rest.Item3, value.Rest.Item4, value.Rest.Item5, value.Rest.Item6, value.Rest.Item7));
+ }
+
+ /// <summary>
+ /// Make a properly nested <see cref="Tuple"/> from a properly nested <see cref="ValueTuple"/> with 15 elements.
+ /// </summary>
+ public static Tuple<T1, T2, T3, T4, T5, T6, T7, Tuple<T8, T9, T10, T11, T12, T13, T14, Tuple<T15>>>
+ ToTuple<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15>(
+ this ValueTuple<T1, T2, T3, T4, T5, T6, T7, ValueTuple<T8, T9, T10, T11, T12, T13, T14, ValueTuple<T15>>> value)
+ {
+ return CreateLongRef(value.Item1, value.Item2, value.Item3, value.Item4, value.Item5, value.Item6, value.Item7,
+ CreateLongRef(value.Rest.Item1, value.Rest.Item2, value.Rest.Item3, value.Rest.Item4, value.Rest.Item5, value.Rest.Item6, value.Rest.Item7,
+ Tuple.Create(value.Rest.Rest.Item1)));
+ }
+
+ /// <summary>
+ /// Make a properly nested <see cref="Tuple"/> from a properly nested <see cref="ValueTuple"/> with 16 elements.
+ /// </summary>
+ public static Tuple<T1, T2, T3, T4, T5, T6, T7, Tuple<T8, T9, T10, T11, T12, T13, T14, Tuple<T15, T16>>>
+ ToTuple<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16>(
+ this ValueTuple<T1, T2, T3, T4, T5, T6, T7, ValueTuple<T8, T9, T10, T11, T12, T13, T14, ValueTuple<T15, T16>>> value)
+ {
+ return CreateLongRef(value.Item1, value.Item2, value.Item3, value.Item4, value.Item5, value.Item6, value.Item7,
+ CreateLongRef(value.Rest.Item1, value.Rest.Item2, value.Rest.Item3, value.Rest.Item4, value.Rest.Item5, value.Rest.Item6, value.Rest.Item7,
+ Tuple.Create(value.Rest.Rest.Item1, value.Rest.Rest.Item2)));
+ }
+
+ /// <summary>
+ /// Make a properly nested <see cref="Tuple"/> from a properly nested <see cref="ValueTuple"/> with 17 elements.
+ /// </summary>
+ public static Tuple<T1, T2, T3, T4, T5, T6, T7, Tuple<T8, T9, T10, T11, T12, T13, T14, Tuple<T15, T16, T17>>>
+ ToTuple<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17>(
+ this ValueTuple<T1, T2, T3, T4, T5, T6, T7, ValueTuple<T8, T9, T10, T11, T12, T13, T14, ValueTuple<T15, T16, T17>>> value)
+ {
+ return CreateLongRef(value.Item1, value.Item2, value.Item3, value.Item4, value.Item5, value.Item6, value.Item7,
+ CreateLongRef(value.Rest.Item1, value.Rest.Item2, value.Rest.Item3, value.Rest.Item4, value.Rest.Item5, value.Rest.Item6, value.Rest.Item7,
+ Tuple.Create(value.Rest.Rest.Item1, value.Rest.Rest.Item2, value.Rest.Rest.Item3)));
+ }
+
+ /// <summary>
+ /// Make a properly nested <see cref="Tuple"/> from a properly nested <see cref="ValueTuple"/> with 18 elements.
+ /// </summary>
+ public static Tuple<T1, T2, T3, T4, T5, T6, T7, Tuple<T8, T9, T10, T11, T12, T13, T14, Tuple<T15, T16, T17, T18>>>
+ ToTuple<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18>(
+ this ValueTuple<T1, T2, T3, T4, T5, T6, T7, ValueTuple<T8, T9, T10, T11, T12, T13, T14, ValueTuple<T15, T16, T17, T18>>> value)
+ {
+ return CreateLongRef(value.Item1, value.Item2, value.Item3, value.Item4, value.Item5, value.Item6, value.Item7,
+ CreateLongRef(value.Rest.Item1, value.Rest.Item2, value.Rest.Item3, value.Rest.Item4, value.Rest.Item5, value.Rest.Item6, value.Rest.Item7,
+ Tuple.Create(value.Rest.Rest.Item1, value.Rest.Rest.Item2, value.Rest.Rest.Item3, value.Rest.Rest.Item4)));
+ }
+
+ /// <summary>
+ /// Make a properly nested <see cref="Tuple"/> from a properly nested <see cref="ValueTuple"/> with 19 elements.
+ /// </summary>
+ public static Tuple<T1, T2, T3, T4, T5, T6, T7, Tuple<T8, T9, T10, T11, T12, T13, T14, Tuple<T15, T16, T17, T18, T19>>>
+ ToTuple<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19>(
+ this ValueTuple<T1, T2, T3, T4, T5, T6, T7, ValueTuple<T8, T9, T10, T11, T12, T13, T14, ValueTuple<T15, T16, T17, T18, T19>>> value)
+ {
+ return CreateLongRef(value.Item1, value.Item2, value.Item3, value.Item4, value.Item5, value.Item6, value.Item7,
+ CreateLongRef(value.Rest.Item1, value.Rest.Item2, value.Rest.Item3, value.Rest.Item4, value.Rest.Item5, value.Rest.Item6, value.Rest.Item7,
+ Tuple.Create(value.Rest.Rest.Item1, value.Rest.Rest.Item2, value.Rest.Rest.Item3, value.Rest.Rest.Item4, value.Rest.Rest.Item5)));
+ }
+
+ /// <summary>
+ /// Make a properly nested <see cref="Tuple"/> from a properly nested <see cref="ValueTuple"/> with 20 elements.
+ /// </summary>
+ public static Tuple<T1, T2, T3, T4, T5, T6, T7, Tuple<T8, T9, T10, T11, T12, T13, T14, Tuple<T15, T16, T17, T18, T19, T20>>>
+ ToTuple<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20>(
+ this ValueTuple<T1, T2, T3, T4, T5, T6, T7, ValueTuple<T8, T9, T10, T11, T12, T13, T14, ValueTuple<T15, T16, T17, T18, T19, T20>>> value)
+ {
+ return CreateLongRef(value.Item1, value.Item2, value.Item3, value.Item4, value.Item5, value.Item6, value.Item7,
+ CreateLongRef(value.Rest.Item1, value.Rest.Item2, value.Rest.Item3, value.Rest.Item4, value.Rest.Item5, value.Rest.Item6, value.Rest.Item7,
+ Tuple.Create(value.Rest.Rest.Item1, value.Rest.Rest.Item2, value.Rest.Rest.Item3, value.Rest.Rest.Item4, value.Rest.Rest.Item5, value.Rest.Rest.Item6)));
+ }
+
+ /// <summary>
+ /// Make a properly nested <see cref="Tuple"/> from a properly nested <see cref="ValueTuple"/> with 21 elements.
+ /// </summary>
+ public static Tuple<T1, T2, T3, T4, T5, T6, T7, Tuple<T8, T9, T10, T11, T12, T13, T14, Tuple<T15, T16, T17, T18, T19, T20, T21>>>
+ ToTuple<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21>(
+ this ValueTuple<T1, T2, T3, T4, T5, T6, T7, ValueTuple<T8, T9, T10, T11, T12, T13, T14, ValueTuple<T15, T16, T17, T18, T19, T20, T21>>> value)
+ {
+ return CreateLongRef(value.Item1, value.Item2, value.Item3, value.Item4, value.Item5, value.Item6, value.Item7,
+ CreateLongRef(value.Rest.Item1, value.Rest.Item2, value.Rest.Item3, value.Rest.Item4, value.Rest.Item5, value.Rest.Item6, value.Rest.Item7,
+ Tuple.Create(value.Rest.Rest.Item1, value.Rest.Rest.Item2, value.Rest.Rest.Item3, value.Rest.Rest.Item4, value.Rest.Rest.Item5, value.Rest.Rest.Item6, value.Rest.Rest.Item7)));
+ }
+ #endregion
+
+ private static ValueTuple<T1, T2, T3, T4, T5, T6, T7, TRest> CreateLong<T1, T2, T3, T4, T5, T6, T7, TRest>(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5, T6 item6, T7 item7, TRest rest) where TRest : struct, ITuple =>
+ new ValueTuple<T1, T2, T3, T4, T5, T6, T7, TRest>(item1, item2, item3, item4, item5, item6, item7, rest);
+
+ private static Tuple<T1, T2, T3, T4, T5, T6, T7, TRest> CreateLongRef<T1, T2, T3, T4, T5, T6, T7, TRest>(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5, T6 item6, T7 item7, TRest rest) where TRest : ITuple =>
+ new Tuple<T1, T2, T3, T4, T5, T6, T7, TRest>(item1, item2, item3, item4, item5, item6, item7, rest);
+ }
+} \ No newline at end of file
diff --git a/src/mscorlib/src/System/Type.cs b/src/mscorlib/src/System/Type.cs
index 2d30c4c7f2..3647451445 100644
--- a/src/mscorlib/src/System/Type.cs
+++ b/src/mscorlib/src/System/Type.cs
@@ -19,7 +19,6 @@ namespace System
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
using System.Security;
- using System.Security.Permissions;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.Versioning;
@@ -29,10 +28,7 @@ namespace System
using DebuggerStepThroughAttribute = System.Diagnostics.DebuggerStepThroughAttribute;
[Serializable]
- [ClassInterface(ClassInterfaceType.None)]
- [ComDefaultInterface(typeof(_Type))]
- [System.Runtime.InteropServices.ComVisible(true)]
- public abstract class Type : MemberInfo, _Type, IReflect
+ public abstract class Type : MemberInfo, IReflect
{
//
// System.Type is appdomain agile type. Appdomain agile types cannot have precise static constructors. Make
@@ -135,8 +131,11 @@ namespace System
[MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
public static Type ReflectionOnlyGetType(String typeName, bool throwIfNotFound, bool ignoreCase)
{
- StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
- return RuntimeType.GetType(typeName, throwIfNotFound, ignoreCase, true /*reflectionOnly*/, ref stackMark);
+ if (typeName == null)
+ throw new ArgumentNullException(nameof(typeName));
+ if (typeName.Length == 0 && throwIfNotFound)
+ throw new TypeLoadException(Environment.GetResourceString("Arg_TypeLoadNullStr"));
+ throw new NotSupportedException(Environment.GetResourceString("NotSupported_ReflectionOnlyGetType"));
}
public virtual Type MakePointerType() { throw new NotSupportedException(); }
@@ -297,7 +296,6 @@ namespace System
// Module Property associated with a class.
- // _Type.Module
public new abstract Module Module { get; }
// Assembly Property associated with a class.
@@ -376,7 +374,6 @@ namespace System
// This method will search for the specified constructor. For constructors,
// unlike everything else, the default is to not look for static methods. The
// reason is that we don't typically expose the class initializer.
- [System.Runtime.InteropServices.ComVisible(true)]
public ConstructorInfo GetConstructor(BindingFlags bindingAttr,
Binder binder,
CallingConventions callConvention,
@@ -393,7 +390,6 @@ namespace System
return GetConstructorImpl(bindingAttr, binder, callConvention, types, modifiers);
}
- [System.Runtime.InteropServices.ComVisible(true)]
public ConstructorInfo GetConstructor(BindingFlags bindingAttr, Binder binder, Type[] types, ParameterModifier[] modifiers)
{
if (types == null)
@@ -405,7 +401,6 @@ namespace System
return GetConstructorImpl(bindingAttr, binder, CallingConventions.Any, types, modifiers);
}
- [System.Runtime.InteropServices.ComVisible(true)]
public ConstructorInfo GetConstructor(Type[] types)
{
// The arguments are checked in the called version of GetConstructor.
@@ -422,15 +417,12 @@ namespace System
// This routine will return an array of all constructors supported by the class.
// Unlike everything else, the default is to not look for static methods. The
// reason is that we don't typically expose the class initializer.
- [System.Runtime.InteropServices.ComVisible(true)]
public ConstructorInfo[] GetConstructors() {
return GetConstructors(BindingFlags.Public | BindingFlags.Instance);
}
- [System.Runtime.InteropServices.ComVisible(true)]
abstract public ConstructorInfo[] GetConstructors(BindingFlags bindingAttr);
- [System.Runtime.InteropServices.ComVisible(true)]
public ConstructorInfo TypeInitializer {
get {
return GetConstructorImpl(BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic,
@@ -676,16 +668,6 @@ namespace System
return GetPropertyImpl(name,Type.DefaultLookup,null,returnType,null,null);
}
- internal PropertyInfo GetProperty(String name, BindingFlags bindingAttr, Type returnType)
- {
- if (name == null)
- throw new ArgumentNullException(nameof(name));
- if (returnType == null)
- throw new ArgumentNullException(nameof(returnType));
- Contract.EndContractBlock();
- return GetPropertyImpl(name, bindingAttr, null, returnType, null, null);
- }
-
public PropertyInfo GetProperty(String name)
{
if (name == null)
@@ -1229,11 +1211,6 @@ namespace System
[Pure]
get {return IsMarshalByRefImpl();}
}
-
- internal bool HasProxyAttribute {
- [Pure]
- get {return HasProxyAttributeImpl();}
- }
// Protected routine to determine if this class represents a value class
// The default implementation of IsValueTypeImpl never returns true for non-runtime types.
@@ -1297,12 +1274,6 @@ namespace System
return false;
}
- internal virtual bool HasProxyAttributeImpl()
- {
- // We will override this in RuntimeType
- return false;
- }
-
[Pure]
abstract public Type GetElementType();
@@ -1599,7 +1570,6 @@ namespace System
// else returns false. If this class and c are the same class false is
// returned.
//
- [System.Runtime.InteropServices.ComVisible(true)]
[Pure]
public virtual bool IsSubclassOf(Type c)
{
@@ -1746,7 +1716,6 @@ namespace System
return Equals(o as Type);
}
- // _Type.Equals(Type)
[Pure]
public virtual bool Equals(Type o)
{
@@ -1777,14 +1746,12 @@ namespace System
// This method will return an interface mapping for the interface
// requested. It will throw an argument exception if the Type doesn't
// implemenet the interface.
- [System.Runtime.InteropServices.ComVisible(true)]
public virtual InterfaceMapping GetInterfaceMap(Type interfaceType)
{
throw new NotSupportedException(Environment.GetResourceString("NotSupported_SubclassOverride"));
}
// this method is required so Object.GetType is not made virtual by the compiler
- // _Type.GetType()
public new Type GetType()
{
return base.GetType();
diff --git a/src/mscorlib/src/System/TypeAccessException.cs b/src/mscorlib/src/System/TypeAccessException.cs
index 5ddc9a7538..32afbdfeb8 100644
--- a/src/mscorlib/src/System/TypeAccessException.cs
+++ b/src/mscorlib/src/System/TypeAccessException.cs
@@ -2,9 +2,7 @@
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
-
using System.Runtime.Serialization;
-using System.Security;
namespace System
{
@@ -14,27 +12,23 @@ namespace System
public class TypeAccessException : TypeLoadException
{
public TypeAccessException()
- : base(Environment.GetResourceString("Arg_TypeAccessException"))
+ : base(SR.Arg_TypeAccessException)
{
- SetErrorCode(__HResults.COR_E_TYPEACCESS);
+ HResult = __HResults.COR_E_TYPEACCESS;
}
- public TypeAccessException(string message)
+ public TypeAccessException(string message)
: base(message)
{
- SetErrorCode(__HResults.COR_E_TYPEACCESS);
+ HResult = __HResults.COR_E_TYPEACCESS;
}
-
- public TypeAccessException(string message, Exception inner)
+
+ public TypeAccessException(string message, Exception inner)
: base(message, inner)
{
- SetErrorCode(__HResults.COR_E_TYPEACCESS);
+ HResult = __HResults.COR_E_TYPEACCESS;
}
-
- protected TypeAccessException(SerializationInfo info, StreamingContext context)
- : base(info, context)
- {
- SetErrorCode(__HResults.COR_E_TYPEACCESS);
- }
+
+ protected TypeAccessException(SerializationInfo info, StreamingContext context) : base(info, context) { }
}
}
diff --git a/src/mscorlib/src/System/TypeCode.cs b/src/mscorlib/src/System/TypeCode.cs
index bf71c2fd5b..293eb1f1aa 100644
--- a/src/mscorlib/src/System/TypeCode.cs
+++ b/src/mscorlib/src/System/TypeCode.cs
@@ -20,10 +20,12 @@
// These types of values are instead represented as classes. When the type code
// of an object is TypeCode.Object, a further instance-of check can be used to
// determine if the object is one of these values.
-namespace System {
+
+namespace System
+{
[Serializable]
- [System.Runtime.InteropServices.ComVisible(true)]
- public enum TypeCode {
+ public enum TypeCode
+ {
Empty = 0, // Null reference
Object = 1, // Instance that isn't a value
DBNull = 2, // Database null value
@@ -44,5 +46,3 @@ namespace System {
String = 18, // Unicode character string
}
}
-
-
diff --git a/src/mscorlib/src/System/TypeInitializationException.cs b/src/mscorlib/src/System/TypeInitializationException.cs
index bcc1c3e968..9191028346 100644
--- a/src/mscorlib/src/System/TypeInitializationException.cs
+++ b/src/mscorlib/src/System/TypeInitializationException.cs
@@ -13,53 +13,67 @@
**
**
=============================================================================*/
-using System;
-using System.Runtime.Serialization;
+
using System.Globalization;
-using System.Security.Permissions;
+using System.Runtime.Serialization;
-namespace System {
+namespace System
+{
[Serializable]
- [System.Runtime.InteropServices.ComVisible(true)]
- public sealed class TypeInitializationException : SystemException {
+ public sealed class TypeInitializationException : SystemException
+ {
private String _typeName;
// This exception is not creatable without specifying the
// inner exception.
private TypeInitializationException()
- : base(Environment.GetResourceString("TypeInitialization_Default")) {
- SetErrorCode(__HResults.COR_E_TYPEINITIALIZATION);
+ : base(SR.TypeInitialization_Default)
+ {
+ HResult = __HResults.COR_E_TYPEINITIALIZATION;
+ }
+
+
+ public TypeInitializationException(String fullTypeName, Exception innerException)
+ : this(fullTypeName, SR.Format(SR.TypeInitialization_Type, fullTypeName), innerException)
+ {
}
// This is called from within the runtime. I believe this is necessary
// for Interop only, though it's not particularly useful.
- private TypeInitializationException(String message) : base(message) {
- SetErrorCode(__HResults.COR_E_TYPEINITIALIZATION);
+ internal TypeInitializationException(String message) : base(message)
+ {
+ HResult = __HResults.COR_E_TYPEINITIALIZATION;
}
-
- public TypeInitializationException(String fullTypeName, Exception innerException) : base(Environment.GetResourceString("TypeInitialization_Type", fullTypeName), innerException) {
+
+ internal TypeInitializationException(String fullTypeName, String message, Exception innerException)
+ : base(message, innerException)
+ {
_typeName = fullTypeName;
- SetErrorCode(__HResults.COR_E_TYPEINITIALIZATION);
+ HResult = __HResults.COR_E_TYPEINITIALIZATION;
}
- internal TypeInitializationException(SerializationInfo info, StreamingContext context) : base(info, context) {
+ internal TypeInitializationException(SerializationInfo info, StreamingContext context)
+ : base(info, context)
+ {
_typeName = info.GetString("TypeName");
}
+ public override void GetObjectData(SerializationInfo info, StreamingContext context)
+ {
+ base.GetObjectData(info, context);
+ info.AddValue("TypeName", TypeName, typeof(String));
+ }
+
public String TypeName
{
- get {
- if (_typeName == null) {
+ get
+ {
+ if (_typeName == null)
+ {
return String.Empty;
}
return _typeName;
}
}
-
- 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 d73a97f9c5..7bc3a1bcce 100644
--- a/src/mscorlib/src/System/TypeLoadException.cs
+++ b/src/mscorlib/src/System/TypeLoadException.cs
@@ -20,11 +20,9 @@ namespace System {
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security;
- using System.Security.Permissions;
using System.Diagnostics.Contracts;
[Serializable]
- [System.Runtime.InteropServices.ComVisible(true)]
public class TypeLoadException : SystemException, ISerializable {
public TypeLoadException()
diff --git a/src/mscorlib/src/System/TypeUnloadedException.cs b/src/mscorlib/src/System/TypeUnloadedException.cs
index 511314d329..f05d673a74 100644
--- a/src/mscorlib/src/System/TypeUnloadedException.cs
+++ b/src/mscorlib/src/System/TypeUnloadedException.cs
@@ -15,7 +15,6 @@ namespace System {
using System.Runtime.Serialization;
- [System.Runtime.InteropServices.ComVisible(true)]
[Serializable]
public class TypeUnloadedException : SystemException {
public TypeUnloadedException()
diff --git a/src/mscorlib/src/System/TypedReference.cs b/src/mscorlib/src/System/TypedReference.cs
index b65652e590..5e8f3c4c04 100644
--- a/src/mscorlib/src/System/TypedReference.cs
+++ b/src/mscorlib/src/System/TypedReference.cs
@@ -11,12 +11,10 @@ namespace System {
using System.Runtime.CompilerServices;
using CultureInfo = System.Globalization.CultureInfo;
using FieldInfo = System.Reflection.FieldInfo;
- using System.Security.Permissions;
using System.Runtime.Versioning;
using System.Diagnostics.Contracts;
[CLSCompliant(false)]
- [System.Runtime.InteropServices.ComVisible(true)]
[System.Runtime.Versioning.NonVersionable] // This only applies to field layout
public struct TypedReference
{
diff --git a/src/mscorlib/src/System/UInt16.cs b/src/mscorlib/src/System/UInt16.cs
index 399ef02d7d..5cd1a65b70 100644
--- a/src/mscorlib/src/System/UInt16.cs
+++ b/src/mscorlib/src/System/UInt16.cs
@@ -19,7 +19,6 @@ namespace System {
// Wrapper for unsigned 16 bit integers.
[Serializable]
[CLSCompliant(false), System.Runtime.InteropServices.StructLayout(LayoutKind.Sequential)]
-[System.Runtime.InteropServices.ComVisible(true)]
public struct UInt16 : IComparable, IFormattable, IConvertible
, IComparable<UInt16>, IEquatable<UInt16>
{
diff --git a/src/mscorlib/src/System/UInt32.cs b/src/mscorlib/src/System/UInt32.cs
index f3d60092f7..fc3f10f96f 100644
--- a/src/mscorlib/src/System/UInt32.cs
+++ b/src/mscorlib/src/System/UInt32.cs
@@ -21,7 +21,6 @@ namespace System {
// * Wrapper for unsigned 32 bit integers.
[Serializable]
[CLSCompliant(false), System.Runtime.InteropServices.StructLayout(LayoutKind.Sequential)]
- [System.Runtime.InteropServices.ComVisible(true)]
public struct UInt32 : IComparable, IFormattable, IConvertible
, IComparable<UInt32>, IEquatable<UInt32>
{
diff --git a/src/mscorlib/src/System/UInt64.cs b/src/mscorlib/src/System/UInt64.cs
index b55cd7ce6a..3b64f056e9 100644
--- a/src/mscorlib/src/System/UInt64.cs
+++ b/src/mscorlib/src/System/UInt64.cs
@@ -19,7 +19,6 @@ namespace System {
// Wrapper for unsigned 64 bit integers.
[Serializable]
[CLSCompliant(false), System.Runtime.InteropServices.StructLayout(LayoutKind.Sequential)]
-[System.Runtime.InteropServices.ComVisible(true)]
public struct UInt64 : IComparable, IFormattable, IConvertible
, IComparable<UInt64>, IEquatable<UInt64>
{
diff --git a/src/mscorlib/src/System/UIntPtr.cs b/src/mscorlib/src/System/UIntPtr.cs
index eab424fc69..d0f988dbb8 100644
--- a/src/mscorlib/src/System/UIntPtr.cs
+++ b/src/mscorlib/src/System/UIntPtr.cs
@@ -21,7 +21,6 @@ namespace System {
[Serializable]
[CLSCompliant(false)]
- [System.Runtime.InteropServices.ComVisible(true)]
public struct UIntPtr : IEquatable<UIntPtr>, ISerializable
{
unsafe private void* m_value;
diff --git a/src/mscorlib/src/System/UnauthorizedAccessException.cs b/src/mscorlib/src/System/UnauthorizedAccessException.cs
index 07e95d547c..997358826f 100644
--- a/src/mscorlib/src/System/UnauthorizedAccessException.cs
+++ b/src/mscorlib/src/System/UnauthorizedAccessException.cs
@@ -13,31 +13,33 @@
**
===========================================================*/
-using System;
using System.Runtime.Serialization;
-namespace System {
+namespace System
+{
// The UnauthorizedAccessException is thrown when access errors
// occur from IO or other OS methods.
[Serializable]
- [System.Runtime.InteropServices.ComVisible(true)]
- public class UnauthorizedAccessException : SystemException {
- public UnauthorizedAccessException()
- : base(Environment.GetResourceString("Arg_UnauthorizedAccessException")) {
- SetErrorCode(__HResults.COR_E_UNAUTHORIZEDACCESS);
+ public class UnauthorizedAccessException : SystemException
+ {
+ public UnauthorizedAccessException()
+ : base(SR.Arg_UnauthorizedAccessException)
+ {
+ HResult = __HResults.COR_E_UNAUTHORIZEDACCESS;
}
-
- public UnauthorizedAccessException(String message)
- : base(message) {
- SetErrorCode(__HResults.COR_E_UNAUTHORIZEDACCESS);
- }
-
- public UnauthorizedAccessException(String message, Exception inner)
- : base(message, inner) {
- SetErrorCode(__HResults.COR_E_UNAUTHORIZEDACCESS);
+
+ public UnauthorizedAccessException(String message)
+ : base(message)
+ {
+ HResult = __HResults.COR_E_UNAUTHORIZEDACCESS;
}
- protected UnauthorizedAccessException(SerializationInfo info, StreamingContext context) : base(info, context) {
+ public UnauthorizedAccessException(String message, Exception inner)
+ : base(message, inner)
+ {
+ HResult = __HResults.COR_E_UNAUTHORIZEDACCESS;
}
+
+ protected UnauthorizedAccessException(SerializationInfo info, StreamingContext context) : base(info, context) { }
}
}
diff --git a/src/mscorlib/src/System/UnhandledExceptionEventArgs.cs b/src/mscorlib/src/System/UnhandledExceptionEventArgs.cs
index e155ffc68e..d33830181c 100644
--- a/src/mscorlib/src/System/UnhandledExceptionEventArgs.cs
+++ b/src/mscorlib/src/System/UnhandledExceptionEventArgs.cs
@@ -2,28 +2,28 @@
// 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;
- using System.Runtime.ConstrainedExecution;
-
+namespace System
+{
[Serializable]
-[System.Runtime.InteropServices.ComVisible(true)]
- public class UnhandledExceptionEventArgs : EventArgs {
- private Object _Exception;
- private bool _IsTerminating;
+ public class UnhandledExceptionEventArgs : EventArgs
+ {
+ private Object _exception;
+ private bool _isTerminating;
- public UnhandledExceptionEventArgs(Object exception, bool isTerminating) {
- _Exception = exception;
- _IsTerminating = isTerminating;
+ public UnhandledExceptionEventArgs(Object exception, bool isTerminating)
+ {
+ _exception = exception;
+ _isTerminating = isTerminating;
}
- public Object ExceptionObject {
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
- get { return _Exception; }
+
+ public Object ExceptionObject
+ {
+ get { return _exception; }
}
- public bool IsTerminating {
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
- get { return _IsTerminating; }
+
+ public bool IsTerminating
+ {
+ get { return _isTerminating; }
}
}
}
diff --git a/src/mscorlib/src/System/UnhandledExceptionEventHandler.cs b/src/mscorlib/src/System/UnhandledExceptionEventHandler.cs
index 8c2798230c..b99414c189 100644
--- a/src/mscorlib/src/System/UnhandledExceptionEventHandler.cs
+++ b/src/mscorlib/src/System/UnhandledExceptionEventHandler.cs
@@ -2,10 +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 {
-
- using System;
+namespace System
+{
[Serializable]
- [System.Runtime.InteropServices.ComVisible(true)]
public delegate void UnhandledExceptionEventHandler(Object sender, UnhandledExceptionEventArgs e);
}
diff --git a/src/mscorlib/src/System/ValueTuple.cs b/src/mscorlib/src/System/ValueTuple.cs
new file mode 100644
index 0000000000..0f0863a2ed
--- /dev/null
+++ b/src/mscorlib/src/System/ValueTuple.cs
@@ -0,0 +1,2324 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+// See the LICENSE file in the project root for more information.
+
+using System.Collections;
+using System.Collections.Generic;
+using System.Diagnostics.Contracts;
+using System.Runtime.InteropServices;
+using System.Runtime.CompilerServices;
+using HashHelpers = System.Numerics.Hashing.HashHelpers;
+
+namespace System
+{
+ /// <summary>
+ /// Helper so we can call some tuple methods recursively without knowing the underlying types.
+ /// </summary>
+ internal interface IValueTupleInternal : ITuple
+ {
+ int GetHashCode(IEqualityComparer comparer);
+ string ToStringEnd();
+ }
+
+ /// <summary>
+ /// The ValueTuple types (from arity 0 to 8) comprise the runtime implementation that underlies tuples in C# and struct tuples in F#.
+ /// Aside from created via language syntax, they are most easily created via the ValueTuple.Create factory methods.
+ /// The System.ValueTuple types differ from the System.Tuple types in that:
+ /// - they are structs rather than classes,
+ /// - they are mutable rather than readonly, and
+ /// - their members (such as Item1, Item2, etc) are fields rather than properties.
+ /// </summary>
+ [Serializable]
+ public struct ValueTuple
+ : IEquatable<ValueTuple>, IStructuralEquatable, IStructuralComparable, IComparable, IComparable<ValueTuple>, IValueTupleInternal, ITuple
+ {
+ /// <summary>
+ /// Returns a value that indicates whether the current <see cref="ValueTuple"/> instance is equal to a specified object.
+ /// </summary>
+ /// <param name="obj">The object to compare with this instance.</param>
+ /// <returns><see langword="true"/> if <paramref name="obj"/> is a <see cref="ValueTuple"/>.</returns>
+ public override bool Equals(object obj)
+ {
+ return obj is ValueTuple;
+ }
+
+ /// <summary>Returns a value indicating whether this instance is equal to a specified value.</summary>
+ /// <param name="other">An instance to compare to this instance.</param>
+ /// <returns>true if <paramref name="other"/> has the same value as this instance; otherwise, false.</returns>
+ public bool Equals(ValueTuple other)
+ {
+ return true;
+ }
+
+ bool IStructuralEquatable.Equals(object other, IEqualityComparer comparer)
+ {
+ return other is ValueTuple;
+ }
+
+ int IComparable.CompareTo(object other)
+ {
+ if (other == null) return 1;
+
+ if (!(other is ValueTuple))
+ {
+ throw new ArgumentException(SR.Format(SR.ArgumentException_ValueTupleIncorrectType, this.GetType().ToString()), nameof(other));
+ }
+
+ return 0;
+ }
+
+ /// <summary>Compares this instance to a specified instance and returns an indication of their relative values.</summary>
+ /// <param name="other">An instance to compare.</param>
+ /// <returns>
+ /// A signed number indicating the relative values of this instance and <paramref name="other"/>.
+ /// Returns less than zero if this instance is less than <paramref name="other"/>, zero if this
+ /// instance is equal to <paramref name="other"/>, and greater than zero if this instance is greater
+ /// than <paramref name="other"/>.
+ /// </returns>
+ public int CompareTo(ValueTuple other)
+ {
+ return 0;
+ }
+
+ int IStructuralComparable.CompareTo(object other, IComparer comparer)
+ {
+ if (other == null) return 1;
+
+ if (!(other is ValueTuple))
+ {
+ throw new ArgumentException(SR.Format(SR.ArgumentException_ValueTupleIncorrectType, this.GetType().ToString()), nameof(other));
+ }
+
+ return 0;
+ }
+
+ /// <summary>Returns the hash code for this instance.</summary>
+ /// <returns>A 32-bit signed integer hash code.</returns>
+ public override int GetHashCode()
+ {
+ return 0;
+ }
+
+ int IStructuralEquatable.GetHashCode(IEqualityComparer comparer)
+ {
+ return 0;
+ }
+
+ int IValueTupleInternal.GetHashCode(IEqualityComparer comparer)
+ {
+ return 0;
+ }
+
+ /// <summary>
+ /// Returns a string that represents the value of this <see cref="ValueTuple"/> instance.
+ /// </summary>
+ /// <returns>The string representation of this <see cref="ValueTuple"/> instance.</returns>
+ /// <remarks>
+ /// The string returned by this method takes the form <c>()</c>.
+ /// </remarks>
+ public override string ToString()
+ {
+ return "()";
+ }
+
+ string IValueTupleInternal.ToStringEnd()
+ {
+ return ")";
+ }
+
+ /// <summary>
+ /// The number of positions in this data structure.
+ /// </summary>
+ int ITuple.Length => 0;
+
+ /// <summary>
+ /// Get the element at position <param name="index"/>.
+ /// </summary>
+ object ITuple.this[int index]
+ {
+ get
+ {
+ throw new IndexOutOfRangeException();
+ }
+ }
+
+ /// <summary>Creates a new struct 0-tuple.</summary>
+ /// <returns>A 0-tuple.</returns>
+ public static ValueTuple Create() =>
+ new ValueTuple();
+
+ /// <summary>Creates a new struct 1-tuple, or singleton.</summary>
+ /// <typeparam name="T1">The type of the first component of the tuple.</typeparam>
+ /// <param name="item1">The value of the first component of the tuple.</param>
+ /// <returns>A 1-tuple (singleton) whose value is (item1).</returns>
+ public static ValueTuple<T1> Create<T1>(T1 item1) =>
+ new ValueTuple<T1>(item1);
+
+ /// <summary>Creates a new struct 2-tuple, or pair.</summary>
+ /// <typeparam name="T1">The type of the first component of the tuple.</typeparam>
+ /// <typeparam name="T2">The type of the second component of the tuple.</typeparam>
+ /// <param name="item1">The value of the first component of the tuple.</param>
+ /// <param name="item2">The value of the second component of the tuple.</param>
+ /// <returns>A 2-tuple (pair) whose value is (item1, item2).</returns>
+ public static ValueTuple<T1, T2> Create<T1, T2>(T1 item1, T2 item2) =>
+ new ValueTuple<T1, T2>(item1, item2);
+
+ /// <summary>Creates a new struct 3-tuple, or triple.</summary>
+ /// <typeparam name="T1">The type of the first component of the tuple.</typeparam>
+ /// <typeparam name="T2">The type of the second component of the tuple.</typeparam>
+ /// <typeparam name="T3">The type of the third component of the tuple.</typeparam>
+ /// <param name="item1">The value of the first component of the tuple.</param>
+ /// <param name="item2">The value of the second component of the tuple.</param>
+ /// <param name="item3">The value of the third component of the tuple.</param>
+ /// <returns>A 3-tuple (triple) whose value is (item1, item2, item3).</returns>
+ public static ValueTuple<T1, T2, T3> Create<T1, T2, T3>(T1 item1, T2 item2, T3 item3) =>
+ new ValueTuple<T1, T2, T3>(item1, item2, item3);
+
+ /// <summary>Creates a new struct 4-tuple, or quadruple.</summary>
+ /// <typeparam name="T1">The type of the first component of the tuple.</typeparam>
+ /// <typeparam name="T2">The type of the second component of the tuple.</typeparam>
+ /// <typeparam name="T3">The type of the third component of the tuple.</typeparam>
+ /// <typeparam name="T4">The type of the fourth component of the tuple.</typeparam>
+ /// <param name="item1">The value of the first component of the tuple.</param>
+ /// <param name="item2">The value of the second component of the tuple.</param>
+ /// <param name="item3">The value of the third component of the tuple.</param>
+ /// <param name="item4">The value of the fourth component of the tuple.</param>
+ /// <returns>A 4-tuple (quadruple) whose value is (item1, item2, item3, item4).</returns>
+ public static ValueTuple<T1, T2, T3, T4> Create<T1, T2, T3, T4>(T1 item1, T2 item2, T3 item3, T4 item4) =>
+ new ValueTuple<T1, T2, T3, T4>(item1, item2, item3, item4);
+
+ /// <summary>Creates a new struct 5-tuple, or quintuple.</summary>
+ /// <typeparam name="T1">The type of the first component of the tuple.</typeparam>
+ /// <typeparam name="T2">The type of the second component of the tuple.</typeparam>
+ /// <typeparam name="T3">The type of the third component of the tuple.</typeparam>
+ /// <typeparam name="T4">The type of the fourth component of the tuple.</typeparam>
+ /// <typeparam name="T5">The type of the fifth component of the tuple.</typeparam>
+ /// <param name="item1">The value of the first component of the tuple.</param>
+ /// <param name="item2">The value of the second component of the tuple.</param>
+ /// <param name="item3">The value of the third component of the tuple.</param>
+ /// <param name="item4">The value of the fourth component of the tuple.</param>
+ /// <param name="item5">The value of the fifth component of the tuple.</param>
+ /// <returns>A 5-tuple (quintuple) whose value is (item1, item2, item3, item4, item5).</returns>
+ public static ValueTuple<T1, T2, T3, T4, T5> Create<T1, T2, T3, T4, T5>(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5) =>
+ new ValueTuple<T1, T2, T3, T4, T5>(item1, item2, item3, item4, item5);
+
+ /// <summary>Creates a new struct 6-tuple, or sextuple.</summary>
+ /// <typeparam name="T1">The type of the first component of the tuple.</typeparam>
+ /// <typeparam name="T2">The type of the second component of the tuple.</typeparam>
+ /// <typeparam name="T3">The type of the third component of the tuple.</typeparam>
+ /// <typeparam name="T4">The type of the fourth component of the tuple.</typeparam>
+ /// <typeparam name="T5">The type of the fifth component of the tuple.</typeparam>
+ /// <typeparam name="T6">The type of the sixth component of the tuple.</typeparam>
+ /// <param name="item1">The value of the first component of the tuple.</param>
+ /// <param name="item2">The value of the second component of the tuple.</param>
+ /// <param name="item3">The value of the third component of the tuple.</param>
+ /// <param name="item4">The value of the fourth component of the tuple.</param>
+ /// <param name="item5">The value of the fifth component of the tuple.</param>
+ /// <param name="item6">The value of the sixth component of the tuple.</param>
+ /// <returns>A 6-tuple (sextuple) whose value is (item1, item2, item3, item4, item5, item6).</returns>
+ public static ValueTuple<T1, T2, T3, T4, T5, T6> Create<T1, T2, T3, T4, T5, T6>(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5, T6 item6) =>
+ new ValueTuple<T1, T2, T3, T4, T5, T6>(item1, item2, item3, item4, item5, item6);
+
+ /// <summary>Creates a new struct 7-tuple, or septuple.</summary>
+ /// <typeparam name="T1">The type of the first component of the tuple.</typeparam>
+ /// <typeparam name="T2">The type of the second component of the tuple.</typeparam>
+ /// <typeparam name="T3">The type of the third component of the tuple.</typeparam>
+ /// <typeparam name="T4">The type of the fourth component of the tuple.</typeparam>
+ /// <typeparam name="T5">The type of the fifth component of the tuple.</typeparam>
+ /// <typeparam name="T6">The type of the sixth component of the tuple.</typeparam>
+ /// <typeparam name="T7">The type of the seventh component of the tuple.</typeparam>
+ /// <param name="item1">The value of the first component of the tuple.</param>
+ /// <param name="item2">The value of the second component of the tuple.</param>
+ /// <param name="item3">The value of the third component of the tuple.</param>
+ /// <param name="item4">The value of the fourth component of the tuple.</param>
+ /// <param name="item5">The value of the fifth component of the tuple.</param>
+ /// <param name="item6">The value of the sixth component of the tuple.</param>
+ /// <param name="item7">The value of the seventh component of the tuple.</param>
+ /// <returns>A 7-tuple (septuple) whose value is (item1, item2, item3, item4, item5, item6, item7).</returns>
+ public static ValueTuple<T1, T2, T3, T4, T5, T6, T7> Create<T1, T2, T3, T4, T5, T6, T7>(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5, T6 item6, T7 item7) =>
+ new ValueTuple<T1, T2, T3, T4, T5, T6, T7>(item1, item2, item3, item4, item5, item6, item7);
+
+ /// <summary>Creates a new struct 8-tuple, or octuple.</summary>
+ /// <typeparam name="T1">The type of the first component of the tuple.</typeparam>
+ /// <typeparam name="T2">The type of the second component of the tuple.</typeparam>
+ /// <typeparam name="T3">The type of the third component of the tuple.</typeparam>
+ /// <typeparam name="T4">The type of the fourth component of the tuple.</typeparam>
+ /// <typeparam name="T5">The type of the fifth component of the tuple.</typeparam>
+ /// <typeparam name="T6">The type of the sixth component of the tuple.</typeparam>
+ /// <typeparam name="T7">The type of the seventh component of the tuple.</typeparam>
+ /// <typeparam name="T8">The type of the eighth component of the tuple.</typeparam>
+ /// <param name="item1">The value of the first component of the tuple.</param>
+ /// <param name="item2">The value of the second component of the tuple.</param>
+ /// <param name="item3">The value of the third component of the tuple.</param>
+ /// <param name="item4">The value of the fourth component of the tuple.</param>
+ /// <param name="item5">The value of the fifth component of the tuple.</param>
+ /// <param name="item6">The value of the sixth component of the tuple.</param>
+ /// <param name="item7">The value of the seventh component of the tuple.</param>
+ /// <param name="item8">The value of the eighth component of the tuple.</param>
+ /// <returns>An 8-tuple (octuple) whose value is (item1, item2, item3, item4, item5, item6, item7, item8).</returns>
+ public static ValueTuple<T1, T2, T3, T4, T5, T6, T7, ValueTuple<T8>> Create<T1, T2, T3, T4, T5, T6, T7, T8>(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5, T6 item6, T7 item7, T8 item8) =>
+ new ValueTuple<T1, T2, T3, T4, T5, T6, T7, ValueTuple<T8>>(item1, item2, item3, item4, item5, item6, item7, ValueTuple.Create(item8));
+
+ internal static int CombineHashCodes(int h1, int h2)
+ {
+ return HashHelpers.Combine(HashHelpers.Combine(HashHelpers.RandomSeed, h1), h2);
+ }
+
+ internal static int CombineHashCodes(int h1, int h2, int h3)
+ {
+ return HashHelpers.Combine(CombineHashCodes(h1, h2), h3);
+ }
+
+ internal static int CombineHashCodes(int h1, int h2, int h3, int h4)
+ {
+ return HashHelpers.Combine(CombineHashCodes(h1, h2, h3), h4);
+ }
+
+ internal static int CombineHashCodes(int h1, int h2, int h3, int h4, int h5)
+ {
+ return HashHelpers.Combine(CombineHashCodes(h1, h2, h3, h4), h5);
+ }
+
+ internal static int CombineHashCodes(int h1, int h2, int h3, int h4, int h5, int h6)
+ {
+ return HashHelpers.Combine(CombineHashCodes(h1, h2, h3, h4, h5), h6);
+ }
+
+ internal static int CombineHashCodes(int h1, int h2, int h3, int h4, int h5, int h6, int h7)
+ {
+ return HashHelpers.Combine(CombineHashCodes(h1, h2, h3, h4, h5, h6), h7);
+ }
+
+ internal static int CombineHashCodes(int h1, int h2, int h3, int h4, int h5, int h6, int h7, int h8)
+ {
+ return HashHelpers.Combine(CombineHashCodes(h1, h2, h3, h4, h5, h6, h7), h8);
+ }
+ }
+
+ /// <summary>Represents a 1-tuple, or singleton, as a value type.</summary>
+ /// <typeparam name="T1">The type of the tuple's only component.</typeparam>
+ [Serializable]
+ public struct ValueTuple<T1>
+ : IEquatable<ValueTuple<T1>>, IStructuralEquatable, IStructuralComparable, IComparable, IComparable<ValueTuple<T1>>, IValueTupleInternal, ITuple
+ {
+ /// <summary>
+ /// The current <see cref="ValueTuple{T1}"/> instance's first component.
+ /// </summary>
+ public T1 Item1;
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="ValueTuple{T1}"/> value type.
+ /// </summary>
+ /// <param name="item1">The value of the tuple's first component.</param>
+ public ValueTuple(T1 item1)
+ {
+ Item1 = item1;
+ }
+
+ /// <summary>
+ /// Returns a value that indicates whether the current <see cref="ValueTuple{T1}"/> instance is equal to a specified object.
+ /// </summary>
+ /// <param name="obj">The object to compare with this instance.</param>
+ /// <returns><see langword="true"/> if the current instance is equal to the specified object; otherwise, <see langword="false"/>.</returns>
+ /// <remarks>
+ /// The <paramref name="obj"/> parameter is considered to be equal to the current instance under the following conditions:
+ /// <list type="bullet">
+ /// <item><description>It is a <see cref="ValueTuple{T1}"/> value type.</description></item>
+ /// <item><description>Its components are of the same types as those of the current instance.</description></item>
+ /// <item><description>Its components are equal to those of the current instance. Equality is determined by the default object equality comparer for each component.</description></item>
+ /// </list>
+ /// </remarks>
+ public override bool Equals(object obj)
+ {
+ return obj is ValueTuple<T1> && Equals((ValueTuple<T1>)obj);
+ }
+
+ /// <summary>
+ /// Returns a value that indicates whether the current <see cref="ValueTuple{T1}"/>
+ /// instance is equal to a specified <see cref="ValueTuple{T1}"/>.
+ /// </summary>
+ /// <param name="other">The tuple to compare with this instance.</param>
+ /// <returns><see langword="true"/> if the current instance is equal to the specified tuple; otherwise, <see langword="false"/>.</returns>
+ /// <remarks>
+ /// The <paramref name="other"/> parameter is considered to be equal to the current instance if each of its field
+ /// is equal to that of the current instance, using the default comparer for that field's type.
+ /// </remarks>
+ public bool Equals(ValueTuple<T1> other)
+ {
+ return EqualityComparer<T1>.Default.Equals(Item1, other.Item1);
+ }
+
+ bool IStructuralEquatable.Equals(object other, IEqualityComparer comparer)
+ {
+ if (other == null || !(other is ValueTuple<T1>)) return false;
+
+ var objTuple = (ValueTuple<T1>)other;
+
+ return comparer.Equals(Item1, objTuple.Item1);
+ }
+
+ int IComparable.CompareTo(object other)
+ {
+ if (other == null) return 1;
+
+ if (!(other is ValueTuple<T1>))
+ {
+ throw new ArgumentException(SR.Format(SR.ArgumentException_ValueTupleIncorrectType, this.GetType().ToString()), nameof(other));
+ }
+
+ var objTuple = (ValueTuple<T1>)other;
+
+ return Comparer<T1>.Default.Compare(Item1, objTuple.Item1);
+ }
+
+ /// <summary>Compares this instance to a specified instance and returns an indication of their relative values.</summary>
+ /// <param name="other">An instance to compare.</param>
+ /// <returns>
+ /// A signed number indicating the relative values of this instance and <paramref name="other"/>.
+ /// Returns less than zero if this instance is less than <paramref name="other"/>, zero if this
+ /// instance is equal to <paramref name="other"/>, and greater than zero if this instance is greater
+ /// than <paramref name="other"/>.
+ /// </returns>
+ public int CompareTo(ValueTuple<T1> other)
+ {
+ return Comparer<T1>.Default.Compare(Item1, other.Item1);
+ }
+
+ int IStructuralComparable.CompareTo(object other, IComparer comparer)
+ {
+ if (other == null) return 1;
+
+ if (!(other is ValueTuple<T1>))
+ {
+ throw new ArgumentException(SR.Format(SR.ArgumentException_ValueTupleIncorrectType, this.GetType().ToString()), nameof(other));
+ }
+
+ var objTuple = (ValueTuple<T1>)other;
+
+ return comparer.Compare(Item1, objTuple.Item1);
+ }
+
+ /// <summary>
+ /// Returns the hash code for the current <see cref="ValueTuple{T1}"/> instance.
+ /// </summary>
+ /// <returns>A 32-bit signed integer hash code.</returns>
+ public override int GetHashCode()
+ {
+ return Item1?.GetHashCode() ?? 0;
+ }
+
+ int IStructuralEquatable.GetHashCode(IEqualityComparer comparer)
+ {
+ return comparer.GetHashCode(Item1);
+ }
+
+ int IValueTupleInternal.GetHashCode(IEqualityComparer comparer)
+ {
+ return comparer.GetHashCode(Item1);
+ }
+
+ /// <summary>
+ /// Returns a string that represents the value of this <see cref="ValueTuple{T1}"/> instance.
+ /// </summary>
+ /// <returns>The string representation of this <see cref="ValueTuple{T1}"/> instance.</returns>
+ /// <remarks>
+ /// The string returned by this method takes the form <c>(Item1)</c>,
+ /// where <c>Item1</c> represents the value of <see cref="Item1"/>. If the field is <see langword="null"/>,
+ /// it is represented as <see cref="string.Empty"/>.
+ /// </remarks>
+ public override string ToString()
+ {
+ return "(" + Item1?.ToString() + ")";
+ }
+
+ string IValueTupleInternal.ToStringEnd()
+ {
+ return Item1?.ToString() + ")";
+ }
+
+ /// <summary>
+ /// The number of positions in this data structure.
+ /// </summary>
+ int ITuple.Length => 1;
+
+ /// <summary>
+ /// Get the element at position <param name="index"/>.
+ /// </summary>
+ object ITuple.this[int index]
+ {
+ get
+ {
+ if (index != 0)
+ {
+ throw new IndexOutOfRangeException();
+ }
+ return Item1;
+ }
+ }
+ }
+
+ /// <summary>
+ /// Represents a 2-tuple, or pair, as a value type.
+ /// </summary>
+ /// <typeparam name="T1">The type of the tuple's first component.</typeparam>
+ /// <typeparam name="T2">The type of the tuple's second component.</typeparam>
+ [Serializable]
+ [StructLayout(LayoutKind.Auto)]
+ public struct ValueTuple<T1, T2>
+ : IEquatable<ValueTuple<T1, T2>>, IStructuralEquatable, IStructuralComparable, IComparable, IComparable<ValueTuple<T1, T2>>, IValueTupleInternal, ITuple
+ {
+ /// <summary>
+ /// The current <see cref="ValueTuple{T1, T2}"/> instance's first component.
+ /// </summary>
+ public T1 Item1;
+
+ /// <summary>
+ /// The current <see cref="ValueTuple{T1, T2}"/> instance's first component.
+ /// </summary>
+ public T2 Item2;
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="ValueTuple{T1, T2}"/> value type.
+ /// </summary>
+ /// <param name="item1">The value of the tuple's first component.</param>
+ /// <param name="item2">The value of the tuple's second component.</param>
+ public ValueTuple(T1 item1, T2 item2)
+ {
+ Item1 = item1;
+ Item2 = item2;
+ }
+
+ /// <summary>
+ /// Returns a value that indicates whether the current <see cref="ValueTuple{T1, T2}"/> instance is equal to a specified object.
+ /// </summary>
+ /// <param name="obj">The object to compare with this instance.</param>
+ /// <returns><see langword="true"/> if the current instance is equal to the specified object; otherwise, <see langword="false"/>.</returns>
+ ///
+ /// <remarks>
+ /// The <paramref name="obj"/> parameter is considered to be equal to the current instance under the following conditions:
+ /// <list type="bullet">
+ /// <item><description>It is a <see cref="ValueTuple{T1, T2}"/> value type.</description></item>
+ /// <item><description>Its components are of the same types as those of the current instance.</description></item>
+ /// <item><description>Its components are equal to those of the current instance. Equality is determined by the default object equality comparer for each component.</description></item>
+ /// </list>
+ /// </remarks>
+ public override bool Equals(object obj)
+ {
+ return obj is ValueTuple<T1, T2> && Equals((ValueTuple<T1, T2>)obj);
+ }
+
+ /// <summary>
+ /// Returns a value that indicates whether the current <see cref="ValueTuple{T1, T2}"/> instance is equal to a specified <see cref="ValueTuple{T1, T2}"/>.
+ /// </summary>
+ /// <param name="other">The tuple to compare with this instance.</param>
+ /// <returns><see langword="true"/> if the current instance is equal to the specified tuple; otherwise, <see langword="false"/>.</returns>
+ /// <remarks>
+ /// The <paramref name="other"/> parameter is considered to be equal to the current instance if each of its fields
+ /// are equal to that of the current instance, using the default comparer for that field's type.
+ /// </remarks>
+ public bool Equals(ValueTuple<T1, T2> other)
+ {
+ return EqualityComparer<T1>.Default.Equals(Item1, other.Item1)
+ && EqualityComparer<T2>.Default.Equals(Item2, other.Item2);
+ }
+
+ /// <summary>
+ /// Returns a value that indicates whether the current <see cref="ValueTuple{T1, T2}"/> instance is equal to a specified object based on a specified comparison method.
+ /// </summary>
+ /// <param name="other">The object to compare with this instance.</param>
+ /// <param name="comparer">An object that defines the method to use to evaluate whether the two objects are equal.</param>
+ /// <returns><see langword="true"/> if the current instance is equal to the specified object; otherwise, <see langword="false"/>.</returns>
+ ///
+ /// <remarks>
+ /// This member is an explicit interface member implementation. It can be used only when the
+ /// <see cref="ValueTuple{T1, T2}"/> instance is cast to an <see cref="IStructuralEquatable"/> interface.
+ ///
+ /// The <see cref="IEqualityComparer.Equals"/> implementation is called only if <c>other</c> is not <see langword="null"/>,
+ /// and if it can be successfully cast (in C#) or converted (in Visual Basic) to a <see cref="ValueTuple{T1, T2}"/>
+ /// whose components are of the same types as those of the current instance. The IStructuralEquatable.Equals(Object, IEqualityComparer) method
+ /// first passes the <see cref="Item1"/> values of the <see cref="ValueTuple{T1, T2}"/> objects to be compared to the
+ /// <see cref="IEqualityComparer.Equals"/> implementation. If this method call returns <see langword="true"/>, the method is
+ /// called again and passed the <see cref="Item2"/> values of the two <see cref="ValueTuple{T1, T2}"/> instances.
+ /// </remarks>
+ bool IStructuralEquatable.Equals(object other, IEqualityComparer comparer)
+ {
+ if (other == null || !(other is ValueTuple<T1, T2>)) return false;
+
+ var objTuple = (ValueTuple<T1, T2>)other;
+
+ return comparer.Equals(Item1, objTuple.Item1)
+ && comparer.Equals(Item2, objTuple.Item2);
+ }
+
+ int IComparable.CompareTo(object other)
+ {
+ if (other == null) return 1;
+
+ if (!(other is ValueTuple<T1, T2>))
+ {
+ throw new ArgumentException(SR.Format(SR.ArgumentException_ValueTupleIncorrectType, this.GetType().ToString()), nameof(other));
+ }
+
+ return CompareTo((ValueTuple<T1, T2>)other);
+ }
+
+ /// <summary>Compares this instance to a specified instance and returns an indication of their relative values.</summary>
+ /// <param name="other">An instance to compare.</param>
+ /// <returns>
+ /// A signed number indicating the relative values of this instance and <paramref name="other"/>.
+ /// Returns less than zero if this instance is less than <paramref name="other"/>, zero if this
+ /// instance is equal to <paramref name="other"/>, and greater than zero if this instance is greater
+ /// than <paramref name="other"/>.
+ /// </returns>
+ public int CompareTo(ValueTuple<T1, T2> other)
+ {
+ int c = Comparer<T1>.Default.Compare(Item1, other.Item1);
+ if (c != 0) return c;
+
+ return Comparer<T2>.Default.Compare(Item2, other.Item2);
+ }
+
+ int IStructuralComparable.CompareTo(object other, IComparer comparer)
+ {
+ if (other == null) return 1;
+
+ if (!(other is ValueTuple<T1, T2>))
+ {
+ throw new ArgumentException(SR.Format(SR.ArgumentException_ValueTupleIncorrectType, this.GetType().ToString()), nameof(other));
+ }
+
+ var objTuple = (ValueTuple<T1, T2>)other;
+
+ int c = comparer.Compare(Item1, objTuple.Item1);
+ if (c != 0) return c;
+
+ return comparer.Compare(Item2, objTuple.Item2);
+ }
+
+ /// <summary>
+ /// Returns the hash code for the current <see cref="ValueTuple{T1, T2}"/> instance.
+ /// </summary>
+ /// <returns>A 32-bit signed integer hash code.</returns>
+ public override int GetHashCode()
+ {
+ return ValueTuple.CombineHashCodes(Item1?.GetHashCode() ?? 0,
+ Item2?.GetHashCode() ?? 0);
+ }
+
+ int IStructuralEquatable.GetHashCode(IEqualityComparer comparer)
+ {
+ return GetHashCodeCore(comparer);
+ }
+
+ private int GetHashCodeCore(IEqualityComparer comparer)
+ {
+ return ValueTuple.CombineHashCodes(comparer.GetHashCode(Item1),
+ comparer.GetHashCode(Item2));
+ }
+
+ int IValueTupleInternal.GetHashCode(IEqualityComparer comparer)
+ {
+ return GetHashCodeCore(comparer);
+ }
+
+ /// <summary>
+ /// Returns a string that represents the value of this <see cref="ValueTuple{T1, T2}"/> instance.
+ /// </summary>
+ /// <returns>The string representation of this <see cref="ValueTuple{T1, T2}"/> instance.</returns>
+ /// <remarks>
+ /// The string returned by this method takes the form <c>(Item1, Item2)</c>,
+ /// where <c>Item1</c> and <c>Item2</c> represent the values of the <see cref="Item1"/>
+ /// and <see cref="Item2"/> fields. If either field value is <see langword="null"/>,
+ /// it is represented as <see cref="String.Empty"/>.
+ /// </remarks>
+ public override string ToString()
+ {
+ return "(" + Item1?.ToString() + ", " + Item2?.ToString() + ")";
+ }
+
+ string IValueTupleInternal.ToStringEnd()
+ {
+ return Item1?.ToString() + ", " + Item2?.ToString() + ")";
+ }
+
+ /// <summary>
+ /// The number of positions in this data structure.
+ /// </summary>
+ int ITuple.Length => 2;
+
+ /// <summary>
+ /// Get the element at position <param name="index"/>.
+ /// </summary>
+ object ITuple.this[int index]
+ {
+ get
+ {
+ switch (index)
+ {
+ case 0:
+ return Item1;
+ case 1:
+ return Item2;
+ default:
+ throw new IndexOutOfRangeException();
+ }
+ }
+ }
+ }
+
+ /// <summary>
+ /// Represents a 3-tuple, or triple, as a value type.
+ /// </summary>
+ /// <typeparam name="T1">The type of the tuple's first component.</typeparam>
+ /// <typeparam name="T2">The type of the tuple's second component.</typeparam>
+ /// <typeparam name="T3">The type of the tuple's third component.</typeparam>
+ [Serializable]
+ [StructLayout(LayoutKind.Auto)]
+ public struct ValueTuple<T1, T2, T3>
+ : IEquatable<ValueTuple<T1, T2, T3>>, IStructuralEquatable, IStructuralComparable, IComparable, IComparable<ValueTuple<T1, T2, T3>>, IValueTupleInternal, ITuple
+ {
+ /// <summary>
+ /// The current <see cref="ValueTuple{T1, T2, T3}"/> instance's first component.
+ /// </summary>
+ public T1 Item1;
+ /// <summary>
+ /// The current <see cref="ValueTuple{T1, T2, T3}"/> instance's second component.
+ /// </summary>
+ public T2 Item2;
+ /// <summary>
+ /// The current <see cref="ValueTuple{T1, T2, T3}"/> instance's third component.
+ /// </summary>
+ public T3 Item3;
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="ValueTuple{T1, T2, T3}"/> value type.
+ /// </summary>
+ /// <param name="item1">The value of the tuple's first component.</param>
+ /// <param name="item2">The value of the tuple's second component.</param>
+ /// <param name="item3">The value of the tuple's third component.</param>
+ public ValueTuple(T1 item1, T2 item2, T3 item3)
+ {
+ Item1 = item1;
+ Item2 = item2;
+ Item3 = item3;
+ }
+
+ /// <summary>
+ /// Returns a value that indicates whether the current <see cref="ValueTuple{T1, T2, T3}"/> instance is equal to a specified object.
+ /// </summary>
+ /// <param name="obj">The object to compare with this instance.</param>
+ /// <returns><see langword="true"/> if the current instance is equal to the specified object; otherwise, <see langword="false"/>.</returns>
+ /// <remarks>
+ /// The <paramref name="obj"/> parameter is considered to be equal to the current instance under the following conditions:
+ /// <list type="bullet">
+ /// <item><description>It is a <see cref="ValueTuple{T1, T2, T3}"/> value type.</description></item>
+ /// <item><description>Its components are of the same types as those of the current instance.</description></item>
+ /// <item><description>Its components are equal to those of the current instance. Equality is determined by the default object equality comparer for each component.</description></item>
+ /// </list>
+ /// </remarks>
+ public override bool Equals(object obj)
+ {
+ return obj is ValueTuple<T1, T2, T3> && Equals((ValueTuple<T1, T2, T3>)obj);
+ }
+
+ /// <summary>
+ /// Returns a value that indicates whether the current <see cref="ValueTuple{T1, T2, T3}"/>
+ /// instance is equal to a specified <see cref="ValueTuple{T1, T2, T3}"/>.
+ /// </summary>
+ /// <param name="other">The tuple to compare with this instance.</param>
+ /// <returns><see langword="true"/> if the current instance is equal to the specified tuple; otherwise, <see langword="false"/>.</returns>
+ /// <remarks>
+ /// The <paramref name="other"/> parameter is considered to be equal to the current instance if each of its fields
+ /// are equal to that of the current instance, using the default comparer for that field's type.
+ /// </remarks>
+ public bool Equals(ValueTuple<T1, T2, T3> other)
+ {
+ return EqualityComparer<T1>.Default.Equals(Item1, other.Item1)
+ && EqualityComparer<T2>.Default.Equals(Item2, other.Item2)
+ && EqualityComparer<T3>.Default.Equals(Item3, other.Item3);
+ }
+
+ bool IStructuralEquatable.Equals(object other, IEqualityComparer comparer)
+ {
+ if (other == null || !(other is ValueTuple<T1, T2, T3>)) return false;
+
+ var objTuple = (ValueTuple<T1, T2, T3>)other;
+
+ return comparer.Equals(Item1, objTuple.Item1)
+ && comparer.Equals(Item2, objTuple.Item2)
+ && comparer.Equals(Item3, objTuple.Item3);
+ }
+
+ int IComparable.CompareTo(object other)
+ {
+ if (other == null) return 1;
+
+ if (!(other is ValueTuple<T1, T2, T3>))
+ {
+ throw new ArgumentException(SR.Format(SR.ArgumentException_ValueTupleIncorrectType, this.GetType().ToString()), nameof(other));
+ }
+
+ return CompareTo((ValueTuple<T1, T2, T3>)other);
+ }
+
+ /// <summary>Compares this instance to a specified instance and returns an indication of their relative values.</summary>
+ /// <param name="other">An instance to compare.</param>
+ /// <returns>
+ /// A signed number indicating the relative values of this instance and <paramref name="other"/>.
+ /// Returns less than zero if this instance is less than <paramref name="other"/>, zero if this
+ /// instance is equal to <paramref name="other"/>, and greater than zero if this instance is greater
+ /// than <paramref name="other"/>.
+ /// </returns>
+ public int CompareTo(ValueTuple<T1, T2, T3> other)
+ {
+ int c = Comparer<T1>.Default.Compare(Item1, other.Item1);
+ if (c != 0) return c;
+
+ c = Comparer<T2>.Default.Compare(Item2, other.Item2);
+ if (c != 0) return c;
+
+ return Comparer<T3>.Default.Compare(Item3, other.Item3);
+ }
+
+ int IStructuralComparable.CompareTo(object other, IComparer comparer)
+ {
+ if (other == null) return 1;
+
+ if (!(other is ValueTuple<T1, T2, T3>))
+ {
+ throw new ArgumentException(SR.Format(SR.ArgumentException_ValueTupleIncorrectType, this.GetType().ToString()), nameof(other));
+ }
+
+ var objTuple = (ValueTuple<T1, T2, T3>)other;
+
+ int c = comparer.Compare(Item1, objTuple.Item1);
+ if (c != 0) return c;
+
+ c = comparer.Compare(Item2, objTuple.Item2);
+ if (c != 0) return c;
+
+ return comparer.Compare(Item3, objTuple.Item3);
+ }
+
+ /// <summary>
+ /// Returns the hash code for the current <see cref="ValueTuple{T1, T2, T3}"/> instance.
+ /// </summary>
+ /// <returns>A 32-bit signed integer hash code.</returns>
+ public override int GetHashCode()
+ {
+ return ValueTuple.CombineHashCodes(Item1?.GetHashCode() ?? 0,
+ Item2?.GetHashCode() ?? 0,
+ Item3?.GetHashCode() ?? 0);
+ }
+
+ int IStructuralEquatable.GetHashCode(IEqualityComparer comparer)
+ {
+ return GetHashCodeCore(comparer);
+ }
+
+ private int GetHashCodeCore(IEqualityComparer comparer)
+ {
+ return ValueTuple.CombineHashCodes(comparer.GetHashCode(Item1),
+ comparer.GetHashCode(Item2),
+ comparer.GetHashCode(Item3));
+ }
+
+ int IValueTupleInternal.GetHashCode(IEqualityComparer comparer)
+ {
+ return GetHashCodeCore(comparer);
+ }
+
+ /// <summary>
+ /// Returns a string that represents the value of this <see cref="ValueTuple{T1, T2, T3}"/> instance.
+ /// </summary>
+ /// <returns>The string representation of this <see cref="ValueTuple{T1, T2, T3}"/> instance.</returns>
+ /// <remarks>
+ /// The string returned by this method takes the form <c>(Item1, Item2, Item3)</c>.
+ /// If any field value is <see langword="null"/>, it is represented as <see cref="String.Empty"/>.
+ /// </remarks>
+ public override string ToString()
+ {
+ return "(" + Item1?.ToString() + ", " + Item2?.ToString() + ", " + Item3?.ToString() + ")";
+ }
+
+ string IValueTupleInternal.ToStringEnd()
+ {
+ return Item1?.ToString() + ", " + Item2?.ToString() + ", " + Item3?.ToString() + ")";
+ }
+
+ /// <summary>
+ /// The number of positions in this data structure.
+ /// </summary>
+ int ITuple.Length => 3;
+
+ /// <summary>
+ /// Get the element at position <param name="index"/>.
+ /// </summary>
+ object ITuple.this[int index]
+ {
+ get
+ {
+ switch (index)
+ {
+ case 0:
+ return Item1;
+ case 1:
+ return Item2;
+ case 2:
+ return Item3;
+ default:
+ throw new IndexOutOfRangeException();
+ }
+ }
+ }
+ }
+
+ /// <summary>
+ /// Represents a 4-tuple, or quadruple, as a value type.
+ /// </summary>
+ /// <typeparam name="T1">The type of the tuple's first component.</typeparam>
+ /// <typeparam name="T2">The type of the tuple's second component.</typeparam>
+ /// <typeparam name="T3">The type of the tuple's third component.</typeparam>
+ /// <typeparam name="T4">The type of the tuple's fourth component.</typeparam>
+ [Serializable]
+ [StructLayout(LayoutKind.Auto)]
+ public struct ValueTuple<T1, T2, T3, T4>
+ : IEquatable<ValueTuple<T1, T2, T3, T4>>, IStructuralEquatable, IStructuralComparable, IComparable, IComparable<ValueTuple<T1, T2, T3, T4>>, IValueTupleInternal, ITuple
+ {
+ /// <summary>
+ /// The current <see cref="ValueTuple{T1, T2, T3, T4}"/> instance's first component.
+ /// </summary>
+ public T1 Item1;
+ /// <summary>
+ /// The current <see cref="ValueTuple{T1, T2, T3, T4}"/> instance's second component.
+ /// </summary>
+ public T2 Item2;
+ /// <summary>
+ /// The current <see cref="ValueTuple{T1, T2, T3, T4}"/> instance's third component.
+ /// </summary>
+ public T3 Item3;
+ /// <summary>
+ /// The current <see cref="ValueTuple{T1, T2, T3, T4}"/> instance's fourth component.
+ /// </summary>
+ public T4 Item4;
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="ValueTuple{T1, T2, T3, T4}"/> value type.
+ /// </summary>
+ /// <param name="item1">The value of the tuple's first component.</param>
+ /// <param name="item2">The value of the tuple's second component.</param>
+ /// <param name="item3">The value of the tuple's third component.</param>
+ /// <param name="item4">The value of the tuple's fourth component.</param>
+ public ValueTuple(T1 item1, T2 item2, T3 item3, T4 item4)
+ {
+ Item1 = item1;
+ Item2 = item2;
+ Item3 = item3;
+ Item4 = item4;
+ }
+
+ /// <summary>
+ /// Returns a value that indicates whether the current <see cref="ValueTuple{T1, T2, T3, T4}"/> instance is equal to a specified object.
+ /// </summary>
+ /// <param name="obj">The object to compare with this instance.</param>
+ /// <returns><see langword="true"/> if the current instance is equal to the specified object; otherwise, <see langword="false"/>.</returns>
+ /// <remarks>
+ /// The <paramref name="obj"/> parameter is considered to be equal to the current instance under the following conditions:
+ /// <list type="bullet">
+ /// <item><description>It is a <see cref="ValueTuple{T1, T2, T3, T4}"/> value type.</description></item>
+ /// <item><description>Its components are of the same types as those of the current instance.</description></item>
+ /// <item><description>Its components are equal to those of the current instance. Equality is determined by the default object equality comparer for each component.</description></item>
+ /// </list>
+ /// </remarks>
+ public override bool Equals(object obj)
+ {
+ return obj is ValueTuple<T1, T2, T3, T4> && Equals((ValueTuple<T1, T2, T3, T4>)obj);
+ }
+
+ /// <summary>
+ /// Returns a value that indicates whether the current <see cref="ValueTuple{T1, T2, T3, T4}"/>
+ /// instance is equal to a specified <see cref="ValueTuple{T1, T2, T3, T4}"/>.
+ /// </summary>
+ /// <param name="other">The tuple to compare with this instance.</param>
+ /// <returns><see langword="true"/> if the current instance is equal to the specified tuple; otherwise, <see langword="false"/>.</returns>
+ /// <remarks>
+ /// The <paramref name="other"/> parameter is considered to be equal to the current instance if each of its fields
+ /// are equal to that of the current instance, using the default comparer for that field's type.
+ /// </remarks>
+ public bool Equals(ValueTuple<T1, T2, T3, T4> other)
+ {
+ return EqualityComparer<T1>.Default.Equals(Item1, other.Item1)
+ && EqualityComparer<T2>.Default.Equals(Item2, other.Item2)
+ && EqualityComparer<T3>.Default.Equals(Item3, other.Item3)
+ && EqualityComparer<T4>.Default.Equals(Item4, other.Item4);
+ }
+
+ bool IStructuralEquatable.Equals(object other, IEqualityComparer comparer)
+ {
+ if (other == null || !(other is ValueTuple<T1, T2, T3, T4>)) return false;
+
+ var objTuple = (ValueTuple<T1, T2, T3, T4>)other;
+
+ return comparer.Equals(Item1, objTuple.Item1)
+ && comparer.Equals(Item2, objTuple.Item2)
+ && comparer.Equals(Item3, objTuple.Item3)
+ && comparer.Equals(Item4, objTuple.Item4);
+ }
+
+ int IComparable.CompareTo(object other)
+ {
+ if (other == null) return 1;
+
+ if (!(other is ValueTuple<T1, T2, T3, T4>))
+ {
+ throw new ArgumentException(SR.Format(SR.ArgumentException_ValueTupleIncorrectType, this.GetType().ToString()), nameof(other));
+ }
+
+ return CompareTo((ValueTuple<T1, T2, T3, T4>)other);
+ }
+
+ /// <summary>Compares this instance to a specified instance and returns an indication of their relative values.</summary>
+ /// <param name="other">An instance to compare.</param>
+ /// <returns>
+ /// A signed number indicating the relative values of this instance and <paramref name="other"/>.
+ /// Returns less than zero if this instance is less than <paramref name="other"/>, zero if this
+ /// instance is equal to <paramref name="other"/>, and greater than zero if this instance is greater
+ /// than <paramref name="other"/>.
+ /// </returns>
+ public int CompareTo(ValueTuple<T1, T2, T3, T4> other)
+ {
+ int c = Comparer<T1>.Default.Compare(Item1, other.Item1);
+ if (c != 0) return c;
+
+ c = Comparer<T2>.Default.Compare(Item2, other.Item2);
+ if (c != 0) return c;
+
+ c = Comparer<T3>.Default.Compare(Item3, other.Item3);
+ if (c != 0) return c;
+
+ return Comparer<T4>.Default.Compare(Item4, other.Item4);
+ }
+
+ int IStructuralComparable.CompareTo(object other, IComparer comparer)
+ {
+ if (other == null) return 1;
+
+ if (!(other is ValueTuple<T1, T2, T3, T4>))
+ {
+ throw new ArgumentException(SR.Format(SR.ArgumentException_ValueTupleIncorrectType, this.GetType().ToString()), nameof(other));
+ }
+
+ var objTuple = (ValueTuple<T1, T2, T3, T4>)other;
+
+ int c = comparer.Compare(Item1, objTuple.Item1);
+ if (c != 0) return c;
+
+ c = comparer.Compare(Item2, objTuple.Item2);
+ if (c != 0) return c;
+
+ c = comparer.Compare(Item3, objTuple.Item3);
+ if (c != 0) return c;
+
+ return comparer.Compare(Item4, objTuple.Item4);
+ }
+
+ /// <summary>
+ /// Returns the hash code for the current <see cref="ValueTuple{T1, T2, T3, T4}"/> instance.
+ /// </summary>
+ /// <returns>A 32-bit signed integer hash code.</returns>
+ public override int GetHashCode()
+ {
+ return ValueTuple.CombineHashCodes(Item1?.GetHashCode() ?? 0,
+ Item2?.GetHashCode() ?? 0,
+ Item3?.GetHashCode() ?? 0,
+ Item4?.GetHashCode() ?? 0);
+ }
+
+ int IStructuralEquatable.GetHashCode(IEqualityComparer comparer)
+ {
+ return GetHashCodeCore(comparer);
+ }
+
+ private int GetHashCodeCore(IEqualityComparer comparer)
+ {
+ return ValueTuple.CombineHashCodes(comparer.GetHashCode(Item1),
+ comparer.GetHashCode(Item2),
+ comparer.GetHashCode(Item3),
+ comparer.GetHashCode(Item4));
+ }
+
+ int IValueTupleInternal.GetHashCode(IEqualityComparer comparer)
+ {
+ return GetHashCodeCore(comparer);
+ }
+
+ /// <summary>
+ /// Returns a string that represents the value of this <see cref="ValueTuple{T1, T2, T3, T4}"/> instance.
+ /// </summary>
+ /// <returns>The string representation of this <see cref="ValueTuple{T1, T2, T3, T4}"/> instance.</returns>
+ /// <remarks>
+ /// The string returned by this method takes the form <c>(Item1, Item2, Item3, Item4)</c>.
+ /// If any field value is <see langword="null"/>, it is represented as <see cref="String.Empty"/>.
+ /// </remarks>
+ public override string ToString()
+ {
+ return "(" + Item1?.ToString() + ", " + Item2?.ToString() + ", " + Item3?.ToString() + ", " + Item4?.ToString() + ")";
+ }
+
+ string IValueTupleInternal.ToStringEnd()
+ {
+ return Item1?.ToString() + ", " + Item2?.ToString() + ", " + Item3?.ToString() + ", " + Item4?.ToString() + ")";
+ }
+
+ /// <summary>
+ /// The number of positions in this data structure.
+ /// </summary>
+ int ITuple.Length => 4;
+
+ /// <summary>
+ /// Get the element at position <param name="index"/>.
+ /// </summary>
+ object ITuple.this[int index]
+ {
+ get
+ {
+ switch (index)
+ {
+ case 0:
+ return Item1;
+ case 1:
+ return Item2;
+ case 2:
+ return Item3;
+ case 3:
+ return Item4;
+ default:
+ throw new IndexOutOfRangeException();
+ }
+ }
+ }
+ }
+
+ /// <summary>
+ /// Represents a 5-tuple, or quintuple, as a value type.
+ /// </summary>
+ /// <typeparam name="T1">The type of the tuple's first component.</typeparam>
+ /// <typeparam name="T2">The type of the tuple's second component.</typeparam>
+ /// <typeparam name="T3">The type of the tuple's third component.</typeparam>
+ /// <typeparam name="T4">The type of the tuple's fourth component.</typeparam>
+ /// <typeparam name="T5">The type of the tuple's fifth component.</typeparam>
+ [Serializable]
+ [StructLayout(LayoutKind.Auto)]
+ public struct ValueTuple<T1, T2, T3, T4, T5>
+ : IEquatable<ValueTuple<T1, T2, T3, T4, T5>>, IStructuralEquatable, IStructuralComparable, IComparable, IComparable<ValueTuple<T1, T2, T3, T4, T5>>, IValueTupleInternal, ITuple
+ {
+ /// <summary>
+ /// The current <see cref="ValueTuple{T1, T2, T3, T4, T5}"/> instance's first component.
+ /// </summary>
+ public T1 Item1;
+ /// <summary>
+ /// The current <see cref="ValueTuple{T1, T2, T3, T4, T5}"/> instance's second component.
+ /// </summary>
+ public T2 Item2;
+ /// <summary>
+ /// The current <see cref="ValueTuple{T1, T2, T3, T4, T5}"/> instance's third component.
+ /// </summary>
+ public T3 Item3;
+ /// <summary>
+ /// The current <see cref="ValueTuple{T1, T2, T3, T4, T5}"/> instance's fourth component.
+ /// </summary>
+ public T4 Item4;
+ /// <summary>
+ /// The current <see cref="ValueTuple{T1, T2, T3, T4, T5}"/> instance's fifth component.
+ /// </summary>
+ public T5 Item5;
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="ValueTuple{T1, T2, T3, T4, T5}"/> value type.
+ /// </summary>
+ /// <param name="item1">The value of the tuple's first component.</param>
+ /// <param name="item2">The value of the tuple's second component.</param>
+ /// <param name="item3">The value of the tuple's third component.</param>
+ /// <param name="item4">The value of the tuple's fourth component.</param>
+ /// <param name="item5">The value of the tuple's fifth component.</param>
+ public ValueTuple(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5)
+ {
+ Item1 = item1;
+ Item2 = item2;
+ Item3 = item3;
+ Item4 = item4;
+ Item5 = item5;
+ }
+
+ /// <summary>
+ /// Returns a value that indicates whether the current <see cref="ValueTuple{T1, T2, T3, T4, T5}"/> instance is equal to a specified object.
+ /// </summary>
+ /// <param name="obj">The object to compare with this instance.</param>
+ /// <returns><see langword="true"/> if the current instance is equal to the specified object; otherwise, <see langword="false"/>.</returns>
+ /// <remarks>
+ /// The <paramref name="obj"/> parameter is considered to be equal to the current instance under the following conditions:
+ /// <list type="bullet">
+ /// <item><description>It is a <see cref="ValueTuple{T1, T2, T3, T4, T5}"/> value type.</description></item>
+ /// <item><description>Its components are of the same types as those of the current instance.</description></item>
+ /// <item><description>Its components are equal to those of the current instance. Equality is determined by the default object equality comparer for each component.</description></item>
+ /// </list>
+ /// </remarks>
+ public override bool Equals(object obj)
+ {
+ return obj is ValueTuple<T1, T2, T3, T4, T5> && Equals((ValueTuple<T1, T2, T3, T4, T5>)obj);
+ }
+
+ /// <summary>
+ /// Returns a value that indicates whether the current <see cref="ValueTuple{T1, T2, T3, T4, T5}"/>
+ /// instance is equal to a specified <see cref="ValueTuple{T1, T2, T3, T4, T5}"/>.
+ /// </summary>
+ /// <param name="other">The tuple to compare with this instance.</param>
+ /// <returns><see langword="true"/> if the current instance is equal to the specified tuple; otherwise, <see langword="false"/>.</returns>
+ /// <remarks>
+ /// The <paramref name="other"/> parameter is considered to be equal to the current instance if each of its fields
+ /// are equal to that of the current instance, using the default comparer for that field's type.
+ /// </remarks>
+ public bool Equals(ValueTuple<T1, T2, T3, T4, T5> other)
+ {
+ return EqualityComparer<T1>.Default.Equals(Item1, other.Item1)
+ && EqualityComparer<T2>.Default.Equals(Item2, other.Item2)
+ && EqualityComparer<T3>.Default.Equals(Item3, other.Item3)
+ && EqualityComparer<T4>.Default.Equals(Item4, other.Item4)
+ && EqualityComparer<T5>.Default.Equals(Item5, other.Item5);
+ }
+
+ bool IStructuralEquatable.Equals(object other, IEqualityComparer comparer)
+ {
+ if (other == null || !(other is ValueTuple<T1, T2, T3, T4, T5>)) return false;
+
+ var objTuple = (ValueTuple<T1, T2, T3, T4, T5>)other;
+
+ return comparer.Equals(Item1, objTuple.Item1)
+ && comparer.Equals(Item2, objTuple.Item2)
+ && comparer.Equals(Item3, objTuple.Item3)
+ && comparer.Equals(Item4, objTuple.Item4)
+ && comparer.Equals(Item5, objTuple.Item5);
+ }
+
+ int IComparable.CompareTo(object other)
+ {
+ if (other == null) return 1;
+
+ if (!(other is ValueTuple<T1, T2, T3, T4, T5>))
+ {
+ throw new ArgumentException(SR.Format(SR.ArgumentException_ValueTupleIncorrectType, this.GetType().ToString()), nameof(other));
+ }
+
+ return CompareTo((ValueTuple<T1, T2, T3, T4, T5>)other);
+ }
+
+ /// <summary>Compares this instance to a specified instance and returns an indication of their relative values.</summary>
+ /// <param name="other">An instance to compare.</param>
+ /// <returns>
+ /// A signed number indicating the relative values of this instance and <paramref name="other"/>.
+ /// Returns less than zero if this instance is less than <paramref name="other"/>, zero if this
+ /// instance is equal to <paramref name="other"/>, and greater than zero if this instance is greater
+ /// than <paramref name="other"/>.
+ /// </returns>
+ public int CompareTo(ValueTuple<T1, T2, T3, T4, T5> other)
+ {
+ int c = Comparer<T1>.Default.Compare(Item1, other.Item1);
+ if (c != 0) return c;
+
+ c = Comparer<T2>.Default.Compare(Item2, other.Item2);
+ if (c != 0) return c;
+
+ c = Comparer<T3>.Default.Compare(Item3, other.Item3);
+ if (c != 0) return c;
+
+ c = Comparer<T4>.Default.Compare(Item4, other.Item4);
+ if (c != 0) return c;
+
+ return Comparer<T5>.Default.Compare(Item5, other.Item5);
+ }
+
+ int IStructuralComparable.CompareTo(object other, IComparer comparer)
+ {
+ if (other == null) return 1;
+
+ if (!(other is ValueTuple<T1, T2, T3, T4, T5>))
+ {
+ throw new ArgumentException(SR.Format(SR.ArgumentException_ValueTupleIncorrectType, this.GetType().ToString()), nameof(other));
+ }
+
+ var objTuple = (ValueTuple<T1, T2, T3, T4, T5>)other;
+
+ int c = comparer.Compare(Item1, objTuple.Item1);
+ if (c != 0) return c;
+
+ c = comparer.Compare(Item2, objTuple.Item2);
+ if (c != 0) return c;
+
+ c = comparer.Compare(Item3, objTuple.Item3);
+ if (c != 0) return c;
+
+ c = comparer.Compare(Item4, objTuple.Item4);
+ if (c != 0) return c;
+
+ return comparer.Compare(Item5, objTuple.Item5);
+ }
+
+ /// <summary>
+ /// Returns the hash code for the current <see cref="ValueTuple{T1, T2, T3, T4, T5}"/> instance.
+ /// </summary>
+ /// <returns>A 32-bit signed integer hash code.</returns>
+ public override int GetHashCode()
+ {
+ return ValueTuple.CombineHashCodes(Item1?.GetHashCode() ?? 0,
+ Item2?.GetHashCode() ?? 0,
+ Item3?.GetHashCode() ?? 0,
+ Item4?.GetHashCode() ?? 0,
+ Item5?.GetHashCode() ?? 0);
+ }
+
+ int IStructuralEquatable.GetHashCode(IEqualityComparer comparer)
+ {
+ return GetHashCodeCore(comparer);
+ }
+
+ private int GetHashCodeCore(IEqualityComparer comparer)
+ {
+ return ValueTuple.CombineHashCodes(comparer.GetHashCode(Item1),
+ comparer.GetHashCode(Item2),
+ comparer.GetHashCode(Item3),
+ comparer.GetHashCode(Item4),
+ comparer.GetHashCode(Item5));
+ }
+
+ int IValueTupleInternal.GetHashCode(IEqualityComparer comparer)
+ {
+ return GetHashCodeCore(comparer);
+ }
+
+ /// <summary>
+ /// Returns a string that represents the value of this <see cref="ValueTuple{T1, T2, T3, T4, T5}"/> instance.
+ /// </summary>
+ /// <returns>The string representation of this <see cref="ValueTuple{T1, T2, T3, T4, T5}"/> instance.</returns>
+ /// <remarks>
+ /// The string returned by this method takes the form <c>(Item1, Item2, Item3, Item4, Item5)</c>.
+ /// If any field value is <see langword="null"/>, it is represented as <see cref="String.Empty"/>.
+ /// </remarks>
+ public override string ToString()
+ {
+ return "(" + Item1?.ToString() + ", " + Item2?.ToString() + ", " + Item3?.ToString() + ", " + Item4?.ToString() + ", " + Item5?.ToString() + ")";
+ }
+
+ string IValueTupleInternal.ToStringEnd()
+ {
+ return Item1?.ToString() + ", " + Item2?.ToString() + ", " + Item3?.ToString() + ", " + Item4?.ToString() + ", " + Item5?.ToString() + ")";
+ }
+
+ /// <summary>
+ /// The number of positions in this data structure.
+ /// </summary>
+ int ITuple.Length => 5;
+
+ /// <summary>
+ /// Get the element at position <param name="index"/>.
+ /// </summary>
+ object ITuple.this[int index]
+ {
+ get
+ {
+ switch (index)
+ {
+ case 0:
+ return Item1;
+ case 1:
+ return Item2;
+ case 2:
+ return Item3;
+ case 3:
+ return Item4;
+ case 4:
+ return Item5;
+ default:
+ throw new IndexOutOfRangeException();
+ }
+ }
+ }
+ }
+
+ /// <summary>
+ /// Represents a 6-tuple, or sixtuple, as a value type.
+ /// </summary>
+ /// <typeparam name="T1">The type of the tuple's first component.</typeparam>
+ /// <typeparam name="T2">The type of the tuple's second component.</typeparam>
+ /// <typeparam name="T3">The type of the tuple's third component.</typeparam>
+ /// <typeparam name="T4">The type of the tuple's fourth component.</typeparam>
+ /// <typeparam name="T5">The type of the tuple's fifth component.</typeparam>
+ /// <typeparam name="T6">The type of the tuple's sixth component.</typeparam>
+ [Serializable]
+ [StructLayout(LayoutKind.Auto)]
+ public struct ValueTuple<T1, T2, T3, T4, T5, T6>
+ : IEquatable<ValueTuple<T1, T2, T3, T4, T5, T6>>, IStructuralEquatable, IStructuralComparable, IComparable, IComparable<ValueTuple<T1, T2, T3, T4, T5, T6>>, IValueTupleInternal, ITuple
+ {
+ /// <summary>
+ /// The current <see cref="ValueTuple{T1, T2, T3, T4, T5, T6}"/> instance's first component.
+ /// </summary>
+ public T1 Item1;
+ /// <summary>
+ /// The current <see cref="ValueTuple{T1, T2, T3, T4, T5, T6}"/> instance's second component.
+ /// </summary>
+ public T2 Item2;
+ /// <summary>
+ /// The current <see cref="ValueTuple{T1, T2, T3, T4, T5, T6}"/> instance's third component.
+ /// </summary>
+ public T3 Item3;
+ /// <summary>
+ /// The current <see cref="ValueTuple{T1, T2, T3, T4, T5, T6}"/> instance's fourth component.
+ /// </summary>
+ public T4 Item4;
+ /// <summary>
+ /// The current <see cref="ValueTuple{T1, T2, T3, T4, T5, T6}"/> instance's fifth component.
+ /// </summary>
+ public T5 Item5;
+ /// <summary>
+ /// The current <see cref="ValueTuple{T1, T2, T3, T4, T5, T6}"/> instance's sixth component.
+ /// </summary>
+ public T6 Item6;
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="ValueTuple{T1, T2, T3, T4, T5, T6}"/> value type.
+ /// </summary>
+ /// <param name="item1">The value of the tuple's first component.</param>
+ /// <param name="item2">The value of the tuple's second component.</param>
+ /// <param name="item3">The value of the tuple's third component.</param>
+ /// <param name="item4">The value of the tuple's fourth component.</param>
+ /// <param name="item5">The value of the tuple's fifth component.</param>
+ /// <param name="item6">The value of the tuple's sixth component.</param>
+ public ValueTuple(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5, T6 item6)
+ {
+ Item1 = item1;
+ Item2 = item2;
+ Item3 = item3;
+ Item4 = item4;
+ Item5 = item5;
+ Item6 = item6;
+ }
+
+ /// <summary>
+ /// Returns a value that indicates whether the current <see cref="ValueTuple{T1, T2, T3, T4, T5, T6}"/> instance is equal to a specified object.
+ /// </summary>
+ /// <param name="obj">The object to compare with this instance.</param>
+ /// <returns><see langword="true"/> if the current instance is equal to the specified object; otherwise, <see langword="false"/>.</returns>
+ /// <remarks>
+ /// The <paramref name="obj"/> parameter is considered to be equal to the current instance under the following conditions:
+ /// <list type="bullet">
+ /// <item><description>It is a <see cref="ValueTuple{T1, T2, T3, T4, T5, T6}"/> value type.</description></item>
+ /// <item><description>Its components are of the same types as those of the current instance.</description></item>
+ /// <item><description>Its components are equal to those of the current instance. Equality is determined by the default object equality comparer for each component.</description></item>
+ /// </list>
+ /// </remarks>
+ public override bool Equals(object obj)
+ {
+ return obj is ValueTuple<T1, T2, T3, T4, T5, T6> && Equals((ValueTuple<T1, T2, T3, T4, T5, T6>)obj);
+ }
+
+ /// <summary>
+ /// Returns a value that indicates whether the current <see cref="ValueTuple{T1, T2, T3, T4, T5, T6}"/>
+ /// instance is equal to a specified <see cref="ValueTuple{T1, T2, T3, T4, T5, T6}"/>.
+ /// </summary>
+ /// <param name="other">The tuple to compare with this instance.</param>
+ /// <returns><see langword="true"/> if the current instance is equal to the specified tuple; otherwise, <see langword="false"/>.</returns>
+ /// <remarks>
+ /// The <paramref name="other"/> parameter is considered to be equal to the current instance if each of its fields
+ /// are equal to that of the current instance, using the default comparer for that field's type.
+ /// </remarks>
+ public bool Equals(ValueTuple<T1, T2, T3, T4, T5, T6> other)
+ {
+ return EqualityComparer<T1>.Default.Equals(Item1, other.Item1)
+ && EqualityComparer<T2>.Default.Equals(Item2, other.Item2)
+ && EqualityComparer<T3>.Default.Equals(Item3, other.Item3)
+ && EqualityComparer<T4>.Default.Equals(Item4, other.Item4)
+ && EqualityComparer<T5>.Default.Equals(Item5, other.Item5)
+ && EqualityComparer<T6>.Default.Equals(Item6, other.Item6);
+ }
+
+ bool IStructuralEquatable.Equals(object other, IEqualityComparer comparer)
+ {
+ if (other == null || !(other is ValueTuple<T1, T2, T3, T4, T5, T6>)) return false;
+
+ var objTuple = (ValueTuple<T1, T2, T3, T4, T5, T6>)other;
+
+ return comparer.Equals(Item1, objTuple.Item1)
+ && comparer.Equals(Item2, objTuple.Item2)
+ && comparer.Equals(Item3, objTuple.Item3)
+ && comparer.Equals(Item4, objTuple.Item4)
+ && comparer.Equals(Item5, objTuple.Item5)
+ && comparer.Equals(Item6, objTuple.Item6);
+ }
+
+ int IComparable.CompareTo(object other)
+ {
+ if (other == null) return 1;
+
+ if (!(other is ValueTuple<T1, T2, T3, T4, T5, T6>))
+ {
+ throw new ArgumentException(SR.Format(SR.ArgumentException_ValueTupleIncorrectType, this.GetType().ToString()), nameof(other));
+ }
+
+ return CompareTo((ValueTuple<T1, T2, T3, T4, T5, T6>)other);
+ }
+
+ /// <summary>Compares this instance to a specified instance and returns an indication of their relative values.</summary>
+ /// <param name="other">An instance to compare.</param>
+ /// <returns>
+ /// A signed number indicating the relative values of this instance and <paramref name="other"/>.
+ /// Returns less than zero if this instance is less than <paramref name="other"/>, zero if this
+ /// instance is equal to <paramref name="other"/>, and greater than zero if this instance is greater
+ /// than <paramref name="other"/>.
+ /// </returns>
+ public int CompareTo(ValueTuple<T1, T2, T3, T4, T5, T6> other)
+ {
+ int c = Comparer<T1>.Default.Compare(Item1, other.Item1);
+ if (c != 0) return c;
+
+ c = Comparer<T2>.Default.Compare(Item2, other.Item2);
+ if (c != 0) return c;
+
+ c = Comparer<T3>.Default.Compare(Item3, other.Item3);
+ if (c != 0) return c;
+
+ c = Comparer<T4>.Default.Compare(Item4, other.Item4);
+ if (c != 0) return c;
+
+ c = Comparer<T5>.Default.Compare(Item5, other.Item5);
+ if (c != 0) return c;
+
+ return Comparer<T6>.Default.Compare(Item6, other.Item6);
+ }
+
+ int IStructuralComparable.CompareTo(object other, IComparer comparer)
+ {
+ if (other == null) return 1;
+
+ if (!(other is ValueTuple<T1, T2, T3, T4, T5, T6>))
+ {
+ throw new ArgumentException(SR.Format(SR.ArgumentException_ValueTupleIncorrectType, this.GetType().ToString()), nameof(other));
+ }
+
+ var objTuple = (ValueTuple<T1, T2, T3, T4, T5, T6>)other;
+
+ int c = comparer.Compare(Item1, objTuple.Item1);
+ if (c != 0) return c;
+
+ c = comparer.Compare(Item2, objTuple.Item2);
+ if (c != 0) return c;
+
+ c = comparer.Compare(Item3, objTuple.Item3);
+ if (c != 0) return c;
+
+ c = comparer.Compare(Item4, objTuple.Item4);
+ if (c != 0) return c;
+
+ c = comparer.Compare(Item5, objTuple.Item5);
+ if (c != 0) return c;
+
+ return comparer.Compare(Item6, objTuple.Item6);
+ }
+
+ /// <summary>
+ /// Returns the hash code for the current <see cref="ValueTuple{T1, T2, T3, T4, T5, T6}"/> instance.
+ /// </summary>
+ /// <returns>A 32-bit signed integer hash code.</returns>
+ public override int GetHashCode()
+ {
+ return ValueTuple.CombineHashCodes(Item1?.GetHashCode() ?? 0,
+ Item2?.GetHashCode() ?? 0,
+ Item3?.GetHashCode() ?? 0,
+ Item4?.GetHashCode() ?? 0,
+ Item5?.GetHashCode() ?? 0,
+ Item6?.GetHashCode() ?? 0);
+ }
+
+ int IStructuralEquatable.GetHashCode(IEqualityComparer comparer)
+ {
+ return GetHashCodeCore(comparer);
+ }
+
+ private int GetHashCodeCore(IEqualityComparer comparer)
+ {
+ return ValueTuple.CombineHashCodes(comparer.GetHashCode(Item1),
+ comparer.GetHashCode(Item2),
+ comparer.GetHashCode(Item3),
+ comparer.GetHashCode(Item4),
+ comparer.GetHashCode(Item5),
+ comparer.GetHashCode(Item6));
+ }
+
+ int IValueTupleInternal.GetHashCode(IEqualityComparer comparer)
+ {
+ return GetHashCodeCore(comparer);
+ }
+
+ /// <summary>
+ /// Returns a string that represents the value of this <see cref="ValueTuple{T1, T2, T3, T4, T5, T6}"/> instance.
+ /// </summary>
+ /// <returns>The string representation of this <see cref="ValueTuple{T1, T2, T3, T4, T5, T6}"/> instance.</returns>
+ /// <remarks>
+ /// The string returned by this method takes the form <c>(Item1, Item2, Item3, Item4, Item5, Item6)</c>.
+ /// If any field value is <see langword="null"/>, it is represented as <see cref="String.Empty"/>.
+ /// </remarks>
+ public override string ToString()
+ {
+ return "(" + Item1?.ToString() + ", " + Item2?.ToString() + ", " + Item3?.ToString() + ", " + Item4?.ToString() + ", " + Item5?.ToString() + ", " + Item6?.ToString() + ")";
+ }
+
+ string IValueTupleInternal.ToStringEnd()
+ {
+ return Item1?.ToString() + ", " + Item2?.ToString() + ", " + Item3?.ToString() + ", " + Item4?.ToString() + ", " + Item5?.ToString() + ", " + Item6?.ToString() + ")";
+ }
+
+ /// <summary>
+ /// The number of positions in this data structure.
+ /// </summary>
+ int ITuple.Length => 6;
+
+ /// <summary>
+ /// Get the element at position <param name="index"/>.
+ /// </summary>
+ object ITuple.this[int index]
+ {
+ get
+ {
+ switch (index)
+ {
+ case 0:
+ return Item1;
+ case 1:
+ return Item2;
+ case 2:
+ return Item3;
+ case 3:
+ return Item4;
+ case 4:
+ return Item5;
+ case 5:
+ return Item6;
+ default:
+ throw new IndexOutOfRangeException();
+ }
+ }
+ }
+ }
+
+ /// <summary>
+ /// Represents a 7-tuple, or sentuple, as a value type.
+ /// </summary>
+ /// <typeparam name="T1">The type of the tuple's first component.</typeparam>
+ /// <typeparam name="T2">The type of the tuple's second component.</typeparam>
+ /// <typeparam name="T3">The type of the tuple's third component.</typeparam>
+ /// <typeparam name="T4">The type of the tuple's fourth component.</typeparam>
+ /// <typeparam name="T5">The type of the tuple's fifth component.</typeparam>
+ /// <typeparam name="T6">The type of the tuple's sixth component.</typeparam>
+ /// <typeparam name="T7">The type of the tuple's seventh component.</typeparam>
+ [Serializable]
+ [StructLayout(LayoutKind.Auto)]
+ public struct ValueTuple<T1, T2, T3, T4, T5, T6, T7>
+ : IEquatable<ValueTuple<T1, T2, T3, T4, T5, T6, T7>>, IStructuralEquatable, IStructuralComparable, IComparable, IComparable<ValueTuple<T1, T2, T3, T4, T5, T6, T7>>, IValueTupleInternal, ITuple
+ {
+ /// <summary>
+ /// The current <see cref="ValueTuple{T1, T2, T3, T4, T5, T6, T7}"/> instance's first component.
+ /// </summary>
+ public T1 Item1;
+ /// <summary>
+ /// The current <see cref="ValueTuple{T1, T2, T3, T4, T5, T6, T7}"/> instance's second component.
+ /// </summary>
+ public T2 Item2;
+ /// <summary>
+ /// The current <see cref="ValueTuple{T1, T2, T3, T4, T5, T6, T7}"/> instance's third component.
+ /// </summary>
+ public T3 Item3;
+ /// <summary>
+ /// The current <see cref="ValueTuple{T1, T2, T3, T4, T5, T6, T7}"/> instance's fourth component.
+ /// </summary>
+ public T4 Item4;
+ /// <summary>
+ /// The current <see cref="ValueTuple{T1, T2, T3, T4, T5, T6, T7}"/> instance's fifth component.
+ /// </summary>
+ public T5 Item5;
+ /// <summary>
+ /// The current <see cref="ValueTuple{T1, T2, T3, T4, T5, T6, T7}"/> instance's sixth component.
+ /// </summary>
+ public T6 Item6;
+ /// <summary>
+ /// The current <see cref="ValueTuple{T1, T2, T3, T4, T5, T6, T7}"/> instance's seventh component.
+ /// </summary>
+ public T7 Item7;
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="ValueTuple{T1, T2, T3, T4, T5, T6, T7}"/> value type.
+ /// </summary>
+ /// <param name="item1">The value of the tuple's first component.</param>
+ /// <param name="item2">The value of the tuple's second component.</param>
+ /// <param name="item3">The value of the tuple's third component.</param>
+ /// <param name="item4">The value of the tuple's fourth component.</param>
+ /// <param name="item5">The value of the tuple's fifth component.</param>
+ /// <param name="item6">The value of the tuple's sixth component.</param>
+ /// <param name="item7">The value of the tuple's seventh component.</param>
+ public ValueTuple(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5, T6 item6, T7 item7)
+ {
+ Item1 = item1;
+ Item2 = item2;
+ Item3 = item3;
+ Item4 = item4;
+ Item5 = item5;
+ Item6 = item6;
+ Item7 = item7;
+ }
+
+ /// <summary>
+ /// Returns a value that indicates whether the current <see cref="ValueTuple{T1, T2, T3, T4, T5, T6, T7}"/> instance is equal to a specified object.
+ /// </summary>
+ /// <param name="obj">The object to compare with this instance.</param>
+ /// <returns><see langword="true"/> if the current instance is equal to the specified object; otherwise, <see langword="false"/>.</returns>
+ /// <remarks>
+ /// The <paramref name="obj"/> parameter is considered to be equal to the current instance under the following conditions:
+ /// <list type="bullet">
+ /// <item><description>It is a <see cref="ValueTuple{T1, T2, T3, T4, T5, T6, T7}"/> value type.</description></item>
+ /// <item><description>Its components are of the same types as those of the current instance.</description></item>
+ /// <item><description>Its components are equal to those of the current instance. Equality is determined by the default object equality comparer for each component.</description></item>
+ /// </list>
+ /// </remarks>
+ public override bool Equals(object obj)
+ {
+ return obj is ValueTuple<T1, T2, T3, T4, T5, T6, T7> && Equals((ValueTuple<T1, T2, T3, T4, T5, T6, T7>)obj);
+ }
+
+ /// <summary>
+ /// Returns a value that indicates whether the current <see cref="ValueTuple{T1, T2, T3, T4, T5, T6, T7}"/>
+ /// instance is equal to a specified <see cref="ValueTuple{T1, T2, T3, T4, T5, T6, T7}"/>.
+ /// </summary>
+ /// <param name="other">The tuple to compare with this instance.</param>
+ /// <returns><see langword="true"/> if the current instance is equal to the specified tuple; otherwise, <see langword="false"/>.</returns>
+ /// <remarks>
+ /// The <paramref name="other"/> parameter is considered to be equal to the current instance if each of its fields
+ /// are equal to that of the current instance, using the default comparer for that field's type.
+ /// </remarks>
+ public bool Equals(ValueTuple<T1, T2, T3, T4, T5, T6, T7> other)
+ {
+ return EqualityComparer<T1>.Default.Equals(Item1, other.Item1)
+ && EqualityComparer<T2>.Default.Equals(Item2, other.Item2)
+ && EqualityComparer<T3>.Default.Equals(Item3, other.Item3)
+ && EqualityComparer<T4>.Default.Equals(Item4, other.Item4)
+ && EqualityComparer<T5>.Default.Equals(Item5, other.Item5)
+ && EqualityComparer<T6>.Default.Equals(Item6, other.Item6)
+ && EqualityComparer<T7>.Default.Equals(Item7, other.Item7);
+ }
+
+ bool IStructuralEquatable.Equals(object other, IEqualityComparer comparer)
+ {
+ if (other == null || !(other is ValueTuple<T1, T2, T3, T4, T5, T6, T7>)) return false;
+
+ var objTuple = (ValueTuple<T1, T2, T3, T4, T5, T6, T7>)other;
+
+ return comparer.Equals(Item1, objTuple.Item1)
+ && comparer.Equals(Item2, objTuple.Item2)
+ && comparer.Equals(Item3, objTuple.Item3)
+ && comparer.Equals(Item4, objTuple.Item4)
+ && comparer.Equals(Item5, objTuple.Item5)
+ && comparer.Equals(Item6, objTuple.Item6)
+ && comparer.Equals(Item7, objTuple.Item7);
+ }
+
+ int IComparable.CompareTo(object other)
+ {
+ if (other == null) return 1;
+
+ if (!(other is ValueTuple<T1, T2, T3, T4, T5, T6, T7>))
+ {
+ throw new ArgumentException(SR.Format(SR.ArgumentException_ValueTupleIncorrectType, this.GetType().ToString()), nameof(other));
+ }
+
+ return CompareTo((ValueTuple<T1, T2, T3, T4, T5, T6, T7>)other);
+ }
+
+ /// <summary>Compares this instance to a specified instance and returns an indication of their relative values.</summary>
+ /// <param name="other">An instance to compare.</param>
+ /// <returns>
+ /// A signed number indicating the relative values of this instance and <paramref name="other"/>.
+ /// Returns less than zero if this instance is less than <paramref name="other"/>, zero if this
+ /// instance is equal to <paramref name="other"/>, and greater than zero if this instance is greater
+ /// than <paramref name="other"/>.
+ /// </returns>
+ public int CompareTo(ValueTuple<T1, T2, T3, T4, T5, T6, T7> other)
+ {
+ int c = Comparer<T1>.Default.Compare(Item1, other.Item1);
+ if (c != 0) return c;
+
+ c = Comparer<T2>.Default.Compare(Item2, other.Item2);
+ if (c != 0) return c;
+
+ c = Comparer<T3>.Default.Compare(Item3, other.Item3);
+ if (c != 0) return c;
+
+ c = Comparer<T4>.Default.Compare(Item4, other.Item4);
+ if (c != 0) return c;
+
+ c = Comparer<T5>.Default.Compare(Item5, other.Item5);
+ if (c != 0) return c;
+
+ c = Comparer<T6>.Default.Compare(Item6, other.Item6);
+ if (c != 0) return c;
+
+ return Comparer<T7>.Default.Compare(Item7, other.Item7);
+ }
+
+ int IStructuralComparable.CompareTo(object other, IComparer comparer)
+ {
+ if (other == null) return 1;
+
+ if (!(other is ValueTuple<T1, T2, T3, T4, T5, T6, T7>))
+ {
+ throw new ArgumentException(SR.Format(SR.ArgumentException_ValueTupleIncorrectType, this.GetType().ToString()), nameof(other));
+ }
+
+ var objTuple = (ValueTuple<T1, T2, T3, T4, T5, T6, T7>)other;
+
+ int c = comparer.Compare(Item1, objTuple.Item1);
+ if (c != 0) return c;
+
+ c = comparer.Compare(Item2, objTuple.Item2);
+ if (c != 0) return c;
+
+ c = comparer.Compare(Item3, objTuple.Item3);
+ if (c != 0) return c;
+
+ c = comparer.Compare(Item4, objTuple.Item4);
+ if (c != 0) return c;
+
+ c = comparer.Compare(Item5, objTuple.Item5);
+ if (c != 0) return c;
+
+ c = comparer.Compare(Item6, objTuple.Item6);
+ if (c != 0) return c;
+
+ return comparer.Compare(Item7, objTuple.Item7);
+ }
+
+ /// <summary>
+ /// Returns the hash code for the current <see cref="ValueTuple{T1, T2, T3, T4, T5, T6, T7}"/> instance.
+ /// </summary>
+ /// <returns>A 32-bit signed integer hash code.</returns>
+ public override int GetHashCode()
+ {
+ return ValueTuple.CombineHashCodes(Item1?.GetHashCode() ?? 0,
+ Item2?.GetHashCode() ?? 0,
+ Item3?.GetHashCode() ?? 0,
+ Item4?.GetHashCode() ?? 0,
+ Item5?.GetHashCode() ?? 0,
+ Item6?.GetHashCode() ?? 0,
+ Item7?.GetHashCode() ?? 0);
+ }
+
+ int IStructuralEquatable.GetHashCode(IEqualityComparer comparer)
+ {
+ return GetHashCodeCore(comparer);
+ }
+
+ private int GetHashCodeCore(IEqualityComparer comparer)
+ {
+ return ValueTuple.CombineHashCodes(comparer.GetHashCode(Item1),
+ comparer.GetHashCode(Item2),
+ comparer.GetHashCode(Item3),
+ comparer.GetHashCode(Item4),
+ comparer.GetHashCode(Item5),
+ comparer.GetHashCode(Item6),
+ comparer.GetHashCode(Item7));
+ }
+
+ int IValueTupleInternal.GetHashCode(IEqualityComparer comparer)
+ {
+ return GetHashCodeCore(comparer);
+ }
+
+ /// <summary>
+ /// Returns a string that represents the value of this <see cref="ValueTuple{T1, T2, T3, T4, T5, T6, T7}"/> instance.
+ /// </summary>
+ /// <returns>The string representation of this <see cref="ValueTuple{T1, T2, T3, T4, T5, T6, T7}"/> instance.</returns>
+ /// <remarks>
+ /// The string returned by this method takes the form <c>(Item1, Item2, Item3, Item4, Item5, Item6, Item7)</c>.
+ /// If any field value is <see langword="null"/>, it is represented as <see cref="String.Empty"/>.
+ /// </remarks>
+ public override string ToString()
+ {
+ return "(" + Item1?.ToString() + ", " + Item2?.ToString() + ", " + Item3?.ToString() + ", " + Item4?.ToString() + ", " + Item5?.ToString() + ", " + Item6?.ToString() + ", " + Item7?.ToString() + ")";
+ }
+
+ string IValueTupleInternal.ToStringEnd()
+ {
+ return Item1?.ToString() + ", " + Item2?.ToString() + ", " + Item3?.ToString() + ", " + Item4?.ToString() + ", " + Item5?.ToString() + ", " + Item6?.ToString() + ", " + Item7?.ToString() + ")";
+ }
+
+ /// <summary>
+ /// The number of positions in this data structure.
+ /// </summary>
+ int ITuple.Length => 7;
+
+ /// <summary>
+ /// Get the element at position <param name="index"/>.
+ /// </summary>
+ object ITuple.this[int index]
+ {
+ get
+ {
+ switch (index)
+ {
+ case 0:
+ return Item1;
+ case 1:
+ return Item2;
+ case 2:
+ return Item3;
+ case 3:
+ return Item4;
+ case 4:
+ return Item5;
+ case 5:
+ return Item6;
+ case 6:
+ return Item7;
+ default:
+ throw new IndexOutOfRangeException();
+ }
+ }
+ }
+ }
+
+ /// <summary>
+ /// Represents an 8-tuple, or octuple, as a value type.
+ /// </summary>
+ /// <typeparam name="T1">The type of the tuple's first component.</typeparam>
+ /// <typeparam name="T2">The type of the tuple's second component.</typeparam>
+ /// <typeparam name="T3">The type of the tuple's third component.</typeparam>
+ /// <typeparam name="T4">The type of the tuple's fourth component.</typeparam>
+ /// <typeparam name="T5">The type of the tuple's fifth component.</typeparam>
+ /// <typeparam name="T6">The type of the tuple's sixth component.</typeparam>
+ /// <typeparam name="T7">The type of the tuple's seventh component.</typeparam>
+ /// <typeparam name="TRest">The type of the tuple's eighth component.</typeparam>
+ [Serializable]
+ [StructLayout(LayoutKind.Auto)]
+ public struct ValueTuple<T1, T2, T3, T4, T5, T6, T7, TRest>
+ : IEquatable<ValueTuple<T1, T2, T3, T4, T5, T6, T7, TRest>>, IStructuralEquatable, IStructuralComparable, IComparable, IComparable<ValueTuple<T1, T2, T3, T4, T5, T6, T7, TRest>>, IValueTupleInternal, ITuple
+ where TRest : struct
+ {
+ /// <summary>
+ /// The current <see cref="ValueTuple{T1, T2, T3, T4, T5, T6, T7, TRest}"/> instance's first component.
+ /// </summary>
+ public T1 Item1;
+ /// <summary>
+ /// The current <see cref="ValueTuple{T1, T2, T3, T4, T5, T6, T7, TRest}"/> instance's second component.
+ /// </summary>
+ public T2 Item2;
+ /// <summary>
+ /// The current <see cref="ValueTuple{T1, T2, T3, T4, T5, T6, T7, TRest}"/> instance's third component.
+ /// </summary>
+ public T3 Item3;
+ /// <summary>
+ /// The current <see cref="ValueTuple{T1, T2, T3, T4, T5, T6, T7, TRest}"/> instance's fourth component.
+ /// </summary>
+ public T4 Item4;
+ /// <summary>
+ /// The current <see cref="ValueTuple{T1, T2, T3, T4, T5, T6, T7, TRest}"/> instance's fifth component.
+ /// </summary>
+ public T5 Item5;
+ /// <summary>
+ /// The current <see cref="ValueTuple{T1, T2, T3, T4, T5, T6, T7, TRest}"/> instance's sixth component.
+ /// </summary>
+ public T6 Item6;
+ /// <summary>
+ /// The current <see cref="ValueTuple{T1, T2, T3, T4, T5, T6, T7, TRest}"/> instance's seventh component.
+ /// </summary>
+ public T7 Item7;
+ /// <summary>
+ /// The current <see cref="ValueTuple{T1, T2, T3, T4, T5, T6, T7, TRest}"/> instance's eighth component.
+ /// </summary>
+ public TRest Rest;
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="ValueTuple{T1, T2, T3, T4, T5, T6, T7, TRest}"/> value type.
+ /// </summary>
+ /// <param name="item1">The value of the tuple's first component.</param>
+ /// <param name="item2">The value of the tuple's second component.</param>
+ /// <param name="item3">The value of the tuple's third component.</param>
+ /// <param name="item4">The value of the tuple's fourth component.</param>
+ /// <param name="item5">The value of the tuple's fifth component.</param>
+ /// <param name="item6">The value of the tuple's sixth component.</param>
+ /// <param name="item7">The value of the tuple's seventh component.</param>
+ /// <param name="rest">The value of the tuple's eight component.</param>
+ public ValueTuple(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5, T6 item6, T7 item7, TRest rest)
+ {
+ if (!(rest is IValueTupleInternal))
+ {
+ throw new ArgumentException(SR.ArgumentException_ValueTupleLastArgumentNotATuple);
+ }
+
+ Item1 = item1;
+ Item2 = item2;
+ Item3 = item3;
+ Item4 = item4;
+ Item5 = item5;
+ Item6 = item6;
+ Item7 = item7;
+ Rest = rest;
+ }
+
+ /// <summary>
+ /// Returns a value that indicates whether the current <see cref="ValueTuple{T1, T2, T3, T4, T5, T6, T7, TRest}"/> instance is equal to a specified object.
+ /// </summary>
+ /// <param name="obj">The object to compare with this instance.</param>
+ /// <returns><see langword="true"/> if the current instance is equal to the specified object; otherwise, <see langword="false"/>.</returns>
+ /// <remarks>
+ /// The <paramref name="obj"/> parameter is considered to be equal to the current instance under the following conditions:
+ /// <list type="bullet">
+ /// <item><description>It is a <see cref="ValueTuple{T1, T2, T3, T4, T5, T6, T7, TRest}"/> value type.</description></item>
+ /// <item><description>Its components are of the same types as those of the current instance.</description></item>
+ /// <item><description>Its components are equal to those of the current instance. Equality is determined by the default object equality comparer for each component.</description></item>
+ /// </list>
+ /// </remarks>
+ public override bool Equals(object obj)
+ {
+ return obj is ValueTuple<T1, T2, T3, T4, T5, T6, T7, TRest> && Equals((ValueTuple<T1, T2, T3, T4, T5, T6, T7, TRest>)obj);
+ }
+
+ /// <summary>
+ /// Returns a value that indicates whether the current <see cref="ValueTuple{T1, T2, T3, T4, T5, T6, T7, TRest}"/>
+ /// instance is equal to a specified <see cref="ValueTuple{T1, T2, T3, T4, T5, T6, T7, TRest}"/>.
+ /// </summary>
+ /// <param name="other">The tuple to compare with this instance.</param>
+ /// <returns><see langword="true"/> if the current instance is equal to the specified tuple; otherwise, <see langword="false"/>.</returns>
+ /// <remarks>
+ /// The <paramref name="other"/> parameter is considered to be equal to the current instance if each of its fields
+ /// are equal to that of the current instance, using the default comparer for that field's type.
+ /// </remarks>
+ public bool Equals(ValueTuple<T1, T2, T3, T4, T5, T6, T7, TRest> other)
+ {
+ return EqualityComparer<T1>.Default.Equals(Item1, other.Item1)
+ && EqualityComparer<T2>.Default.Equals(Item2, other.Item2)
+ && EqualityComparer<T3>.Default.Equals(Item3, other.Item3)
+ && EqualityComparer<T4>.Default.Equals(Item4, other.Item4)
+ && EqualityComparer<T5>.Default.Equals(Item5, other.Item5)
+ && EqualityComparer<T6>.Default.Equals(Item6, other.Item6)
+ && EqualityComparer<T7>.Default.Equals(Item7, other.Item7)
+ && EqualityComparer<TRest>.Default.Equals(Rest, other.Rest);
+ }
+
+ bool IStructuralEquatable.Equals(object other, IEqualityComparer comparer)
+ {
+ if (other == null || !(other is ValueTuple<T1, T2, T3, T4, T5, T6, T7, TRest>)) return false;
+
+ var objTuple = (ValueTuple<T1, T2, T3, T4, T5, T6, T7, TRest>)other;
+
+ return comparer.Equals(Item1, objTuple.Item1)
+ && comparer.Equals(Item2, objTuple.Item2)
+ && comparer.Equals(Item3, objTuple.Item3)
+ && comparer.Equals(Item4, objTuple.Item4)
+ && comparer.Equals(Item5, objTuple.Item5)
+ && comparer.Equals(Item6, objTuple.Item6)
+ && comparer.Equals(Item7, objTuple.Item7)
+ && comparer.Equals(Rest, objTuple.Rest);
+ }
+
+ int IComparable.CompareTo(object other)
+ {
+ if (other == null) return 1;
+
+ if (!(other is ValueTuple<T1, T2, T3, T4, T5, T6, T7, TRest>))
+ {
+ throw new ArgumentException(SR.Format(SR.ArgumentException_ValueTupleIncorrectType, this.GetType().ToString()), nameof(other));
+ }
+
+ return CompareTo((ValueTuple<T1, T2, T3, T4, T5, T6, T7, TRest>)other);
+ }
+
+ /// <summary>Compares this instance to a specified instance and returns an indication of their relative values.</summary>
+ /// <param name="other">An instance to compare.</param>
+ /// <returns>
+ /// A signed number indicating the relative values of this instance and <paramref name="other"/>.
+ /// Returns less than zero if this instance is less than <paramref name="other"/>, zero if this
+ /// instance is equal to <paramref name="other"/>, and greater than zero if this instance is greater
+ /// than <paramref name="other"/>.
+ /// </returns>
+ public int CompareTo(ValueTuple<T1, T2, T3, T4, T5, T6, T7, TRest> other)
+ {
+ int c = Comparer<T1>.Default.Compare(Item1, other.Item1);
+ if (c != 0) return c;
+
+ c = Comparer<T2>.Default.Compare(Item2, other.Item2);
+ if (c != 0) return c;
+
+ c = Comparer<T3>.Default.Compare(Item3, other.Item3);
+ if (c != 0) return c;
+
+ c = Comparer<T4>.Default.Compare(Item4, other.Item4);
+ if (c != 0) return c;
+
+ c = Comparer<T5>.Default.Compare(Item5, other.Item5);
+ if (c != 0) return c;
+
+ c = Comparer<T6>.Default.Compare(Item6, other.Item6);
+ if (c != 0) return c;
+
+ c = Comparer<T7>.Default.Compare(Item7, other.Item7);
+ if (c != 0) return c;
+
+ return Comparer<TRest>.Default.Compare(Rest, other.Rest);
+ }
+
+ int IStructuralComparable.CompareTo(object other, IComparer comparer)
+ {
+ if (other == null) return 1;
+
+ if (!(other is ValueTuple<T1, T2, T3, T4, T5, T6, T7, TRest>))
+ {
+ throw new ArgumentException(SR.Format(SR.ArgumentException_ValueTupleIncorrectType, this.GetType().ToString()), nameof(other));
+ }
+
+ var objTuple = (ValueTuple<T1, T2, T3, T4, T5, T6, T7, TRest>)other;
+
+ int c = comparer.Compare(Item1, objTuple.Item1);
+ if (c != 0) return c;
+
+ c = comparer.Compare(Item2, objTuple.Item2);
+ if (c != 0) return c;
+
+ c = comparer.Compare(Item3, objTuple.Item3);
+ if (c != 0) return c;
+
+ c = comparer.Compare(Item4, objTuple.Item4);
+ if (c != 0) return c;
+
+ c = comparer.Compare(Item5, objTuple.Item5);
+ if (c != 0) return c;
+
+ c = comparer.Compare(Item6, objTuple.Item6);
+ if (c != 0) return c;
+
+ c = comparer.Compare(Item7, objTuple.Item7);
+ if (c != 0) return c;
+
+ return comparer.Compare(Rest, objTuple.Rest);
+ }
+
+ /// <summary>
+ /// Returns the hash code for the current <see cref="ValueTuple{T1, T2, T3, T4, T5, T6, T7, TRest}"/> instance.
+ /// </summary>
+ /// <returns>A 32-bit signed integer hash code.</returns>
+ public override int GetHashCode()
+ {
+ // We want to have a limited hash in this case. We'll use the last 8 elements of the tuple
+ IValueTupleInternal rest = Rest as IValueTupleInternal;
+ if (rest == null)
+ {
+ return ValueTuple.CombineHashCodes(Item1?.GetHashCode() ?? 0,
+ Item2?.GetHashCode() ?? 0,
+ Item3?.GetHashCode() ?? 0,
+ Item4?.GetHashCode() ?? 0,
+ Item5?.GetHashCode() ?? 0,
+ Item6?.GetHashCode() ?? 0,
+ Item7?.GetHashCode() ?? 0);
+ }
+
+ int size = rest.Length;
+ if (size >= 8) { return rest.GetHashCode(); }
+
+ // In this case, the rest member has less than 8 elements so we need to combine some our elements with the elements in rest
+ int k = 8 - size;
+ switch (k)
+ {
+ case 1:
+ return ValueTuple.CombineHashCodes(Item7?.GetHashCode() ?? 0,
+ rest.GetHashCode());
+ case 2:
+ return ValueTuple.CombineHashCodes(Item6?.GetHashCode() ?? 0,
+ Item7?.GetHashCode() ?? 0,
+ rest.GetHashCode());
+ case 3:
+ return ValueTuple.CombineHashCodes(Item5?.GetHashCode() ?? 0,
+ Item6?.GetHashCode() ?? 0,
+ Item7?.GetHashCode() ?? 0,
+ rest.GetHashCode());
+ case 4:
+ return ValueTuple.CombineHashCodes(Item4?.GetHashCode() ?? 0,
+ Item5?.GetHashCode() ?? 0,
+ Item6?.GetHashCode() ?? 0,
+ Item7?.GetHashCode() ?? 0,
+ rest.GetHashCode());
+ case 5:
+ return ValueTuple.CombineHashCodes(Item3?.GetHashCode() ?? 0,
+ Item4?.GetHashCode() ?? 0,
+ Item5?.GetHashCode() ?? 0,
+ Item6?.GetHashCode() ?? 0,
+ Item7?.GetHashCode() ?? 0,
+ rest.GetHashCode());
+ case 6:
+ return ValueTuple.CombineHashCodes(Item2?.GetHashCode() ?? 0,
+ Item3?.GetHashCode() ?? 0,
+ Item4?.GetHashCode() ?? 0,
+ Item5?.GetHashCode() ?? 0,
+ Item6?.GetHashCode() ?? 0,
+ Item7?.GetHashCode() ?? 0,
+ rest.GetHashCode());
+ case 7:
+ case 8:
+ return ValueTuple.CombineHashCodes(Item1?.GetHashCode() ?? 0,
+ Item2?.GetHashCode() ?? 0,
+ Item3?.GetHashCode() ?? 0,
+ Item4?.GetHashCode() ?? 0,
+ Item5?.GetHashCode() ?? 0,
+ Item6?.GetHashCode() ?? 0,
+ Item7?.GetHashCode() ?? 0,
+ rest.GetHashCode());
+ }
+
+ Contract.Assert(false, "Missed all cases for computing ValueTuple hash code");
+ return -1;
+ }
+
+ int IStructuralEquatable.GetHashCode(IEqualityComparer comparer)
+ {
+ return GetHashCodeCore(comparer);
+ }
+
+ private int GetHashCodeCore(IEqualityComparer comparer)
+ {
+ // We want to have a limited hash in this case. We'll use the last 8 elements of the tuple
+ IValueTupleInternal rest = Rest as IValueTupleInternal;
+ if (rest == null)
+ {
+ return ValueTuple.CombineHashCodes(comparer.GetHashCode(Item1), comparer.GetHashCode(Item2), comparer.GetHashCode(Item3),
+ comparer.GetHashCode(Item4), comparer.GetHashCode(Item5), comparer.GetHashCode(Item6),
+ comparer.GetHashCode(Item7));
+ }
+
+ int size = rest.Length;
+ if (size >= 8) { return rest.GetHashCode(comparer); }
+
+ // In this case, the rest member has less than 8 elements so we need to combine some our elements with the elements in rest
+ int k = 8 - size;
+ switch (k)
+ {
+ case 1:
+ return ValueTuple.CombineHashCodes(comparer.GetHashCode(Item7), rest.GetHashCode(comparer));
+ case 2:
+ return ValueTuple.CombineHashCodes(comparer.GetHashCode(Item6), comparer.GetHashCode(Item7), rest.GetHashCode(comparer));
+ case 3:
+ return ValueTuple.CombineHashCodes(comparer.GetHashCode(Item5), comparer.GetHashCode(Item6), comparer.GetHashCode(Item7),
+ rest.GetHashCode(comparer));
+ case 4:
+ return ValueTuple.CombineHashCodes(comparer.GetHashCode(Item4), comparer.GetHashCode(Item5), comparer.GetHashCode(Item6),
+ comparer.GetHashCode(Item7), rest.GetHashCode(comparer));
+ case 5:
+ return ValueTuple.CombineHashCodes(comparer.GetHashCode(Item3), comparer.GetHashCode(Item4), comparer.GetHashCode(Item5),
+ comparer.GetHashCode(Item6), comparer.GetHashCode(Item7), rest.GetHashCode(comparer));
+ case 6:
+ return ValueTuple.CombineHashCodes(comparer.GetHashCode(Item2), comparer.GetHashCode(Item3), comparer.GetHashCode(Item4),
+ comparer.GetHashCode(Item5), comparer.GetHashCode(Item6), comparer.GetHashCode(Item7),
+ rest.GetHashCode(comparer));
+ case 7:
+ case 8:
+ return ValueTuple.CombineHashCodes(comparer.GetHashCode(Item1), comparer.GetHashCode(Item2), comparer.GetHashCode(Item3),
+ comparer.GetHashCode(Item4), comparer.GetHashCode(Item5), comparer.GetHashCode(Item6),
+ comparer.GetHashCode(Item7), rest.GetHashCode(comparer));
+ }
+
+ Contract.Assert(false, "Missed all cases for computing ValueTuple hash code");
+ return -1;
+ }
+
+ int IValueTupleInternal.GetHashCode(IEqualityComparer comparer)
+ {
+ return GetHashCodeCore(comparer);
+ }
+
+ /// <summary>
+ /// Returns a string that represents the value of this <see cref="ValueTuple{T1, T2, T3, T4, T5, T6, T7, TRest}"/> instance.
+ /// </summary>
+ /// <returns>The string representation of this <see cref="ValueTuple{T1, T2, T3, T4, T5, T6, T7, TRest}"/> instance.</returns>
+ /// <remarks>
+ /// The string returned by this method takes the form <c>(Item1, Item2, Item3, Item4, Item5, Item6, Item7, Rest)</c>.
+ /// If any field value is <see langword="null"/>, it is represented as <see cref="String.Empty"/>.
+ /// </remarks>
+ public override string ToString()
+ {
+ IValueTupleInternal rest = Rest as IValueTupleInternal;
+ if (rest == null)
+ {
+ return "(" + Item1?.ToString() + ", " + Item2?.ToString() + ", " + Item3?.ToString() + ", " + Item4?.ToString() + ", " + Item5?.ToString() + ", " + Item6?.ToString() + ", " + Item7?.ToString() + ", " + Rest.ToString() + ")";
+ }
+ else
+ {
+ return "(" + Item1?.ToString() + ", " + Item2?.ToString() + ", " + Item3?.ToString() + ", " + Item4?.ToString() + ", " + Item5?.ToString() + ", " + Item6?.ToString() + ", " + Item7?.ToString() + ", " + rest.ToStringEnd();
+ }
+ }
+
+ string IValueTupleInternal.ToStringEnd()
+ {
+ IValueTupleInternal rest = Rest as IValueTupleInternal;
+ if (rest == null)
+ {
+ return Item1?.ToString() + ", " + Item2?.ToString() + ", " + Item3?.ToString() + ", " + Item4?.ToString() + ", " + Item5?.ToString() + ", " + Item6?.ToString() + ", " + Item7?.ToString() + ", " + Rest.ToString() + ")";
+ }
+ else
+ {
+ return Item1?.ToString() + ", " + Item2?.ToString() + ", " + Item3?.ToString() + ", " + Item4?.ToString() + ", " + Item5?.ToString() + ", " + Item6?.ToString() + ", " + Item7?.ToString() + ", " + rest.ToStringEnd();
+ }
+ }
+
+ /// <summary>
+ /// The number of positions in this data structure.
+ /// </summary>
+ int ITuple.Length
+ {
+ get
+ {
+ IValueTupleInternal rest = Rest as IValueTupleInternal;
+ return rest == null ? 8 : 7 + rest.Length;
+ }
+ }
+
+ /// <summary>
+ /// Get the element at position <param name="index"/>.
+ /// </summary>
+ object ITuple.this[int index]
+ {
+ get
+ {
+ switch (index)
+ {
+ case 0:
+ return Item1;
+ case 1:
+ return Item2;
+ case 2:
+ return Item3;
+ case 3:
+ return Item4;
+ case 4:
+ return Item5;
+ case 5:
+ return Item6;
+ case 6:
+ return Item7;
+ }
+
+ IValueTupleInternal rest = Rest as IValueTupleInternal;
+ if (rest == null)
+ {
+ if (index == 7)
+ {
+ return Rest;
+ }
+ throw new IndexOutOfRangeException();
+ }
+ return rest[index - 7];
+ }
+ }
+ }
+}
diff --git a/src/mscorlib/src/System/ValueType.cs b/src/mscorlib/src/System/ValueType.cs
index 102a0d2b92..06a64e397c 100644
--- a/src/mscorlib/src/System/ValueType.cs
+++ b/src/mscorlib/src/System/ValueType.cs
@@ -17,7 +17,6 @@ namespace System {
using System.Runtime.Versioning;
[Serializable]
-[System.Runtime.InteropServices.ComVisible(true)]
public abstract class ValueType {
public override bool Equals (Object obj) {
diff --git a/src/mscorlib/src/System/Variant.cs b/src/mscorlib/src/System/Variant.cs
index 2a9593cf42..509650b8fc 100644
--- a/src/mscorlib/src/System/Variant.cs
+++ b/src/mscorlib/src/System/Variant.cs
@@ -334,21 +334,6 @@ namespace System {
m_flags |= ((int)vt << VTBitShift);
}
-
- unsafe public Variant(void* voidPointer,Type pointerType) {
- if (pointerType == null)
- throw new ArgumentNullException(nameof(pointerType));
- if (!pointerType.IsPointer)
- throw new ArgumentException(Environment.GetResourceString("Arg_MustBePointer"),nameof(pointerType));
- Contract.EndContractBlock();
-
- m_objref = pointerType;
- m_flags=CV_PTR;
- m_data1=(int)voidPointer;
- m_data2=0;
-
- }
-
//This is a family-only accessor for the CVType.
//This is never to be exposed externally.
internal int CVType {
diff --git a/src/mscorlib/src/System/Version.cs b/src/mscorlib/src/System/Version.cs
index f2ef5d4486..7c58d3c0c4 100644
--- a/src/mscorlib/src/System/Version.cs
+++ b/src/mscorlib/src/System/Version.cs
@@ -25,7 +25,6 @@ namespace System {
// specified component.
[Serializable]
-[System.Runtime.InteropServices.ComVisible(true)]
public sealed class Version : ICloneable, IComparable
, IComparable<Version>, IEquatable<Version>
{
@@ -34,7 +33,6 @@ namespace System {
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)
@@ -301,7 +299,7 @@ namespace System {
return false;
}
- String[] parsedComponents = version.Split(SeparatorsArray);
+ String[] parsedComponents = version.Split('.');
int parsedComponentsLength = parsedComponents.Length;
if ((parsedComponentsLength < 2) || (parsedComponentsLength > 4)) {
result.SetFailure(ParseFailureKind.ArgumentException);
diff --git a/src/mscorlib/src/System/Void.cs b/src/mscorlib/src/System/Void.cs
index 51df8781aa..5c20f634fc 100644
--- a/src/mscorlib/src/System/Void.cs
+++ b/src/mscorlib/src/System/Void.cs
@@ -7,12 +7,11 @@
// This class represents the void return type
////////////////////////////////////////////////////////////////////////////////
-namespace System {
-
- using System;
+namespace System
+{
+ // This class represents the void return type
[Serializable]
- [System.Runtime.InteropServices.ComVisible(true)]
- public struct Void
+ public struct Void
{
}
}
diff --git a/src/mscorlib/src/System/WeakReference.cs b/src/mscorlib/src/System/WeakReference.cs
index d5648527f0..6600d15855 100644
--- a/src/mscorlib/src/System/WeakReference.cs
+++ b/src/mscorlib/src/System/WeakReference.cs
@@ -13,13 +13,11 @@ namespace System {
using System;
using System.Runtime.Serialization;
using System.Security;
- using System.Security.Permissions;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Diagnostics;
using System.Diagnostics.Contracts;
- [System.Runtime.InteropServices.ComVisible(true)]
[Serializable]
public class WeakReference : ISerializable
{
diff --git a/src/mscorlib/src/System/_LocalDataStore.cs b/src/mscorlib/src/System/_LocalDataStore.cs
deleted file mode 100644
index a1fa488076..0000000000
--- a/src/mscorlib/src/System/_LocalDataStore.cs
+++ /dev/null
@@ -1,244 +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: Class that stores local data. This class is used in cooperation
-** with the _LocalDataStoreMgr class.
-**
-**
-=============================================================================*/
-
-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
- // LocalDataStoreMgr does not holds references to LocalDataStoreHolder. It holds
- // references to LocalDataStore only. LocalDataStoreHolder finalizer will run once
- // the only outstanding reference to the store is in LocalDataStoreMgr.
- sealed internal class LocalDataStoreHolder
- {
- private LocalDataStore m_Store;
-
- public LocalDataStoreHolder(LocalDataStore store)
- {
- m_Store = store;
- }
-
- ~LocalDataStoreHolder()
- {
- LocalDataStore store = m_Store;
- if (store == null)
- return;
-
- store.Dispose();
- }
-
- public LocalDataStore Store
- {
- get
- {
- return m_Store;
- }
- }
- }
-
- sealed internal class LocalDataStoreElement
- {
- private Object m_value;
- private long m_cookie; // This is immutable cookie of the slot used to verify that
- // the value is indeed indeed owned by the slot. Necessary
- // to avoid resurection holes.
-
- public LocalDataStoreElement(long cookie)
- {
- m_cookie = cookie;
- }
-
- public Object Value
- {
- get
- {
- return m_value;
- }
- set
- {
- m_value = value;
- }
- }
-
- public long Cookie
- {
- get
- {
- return m_cookie;
- }
- }
- }
-
- // This class will not be marked serializable
- sealed internal class LocalDataStore
- {
- private LocalDataStoreElement[] m_DataTable;
- private LocalDataStoreMgr m_Manager;
-
- /*=========================================================================
- ** Initialize the data store.
- =========================================================================*/
- public LocalDataStore(LocalDataStoreMgr mgr, int InitialCapacity)
- {
- // Store the manager of the local data store.
- m_Manager = mgr;
-
- // Allocate the array that will contain the data.
- m_DataTable = new LocalDataStoreElement[InitialCapacity];
- }
-
- /*=========================================================================
- ** Delete this store from its manager
- =========================================================================*/
- internal void Dispose()
- {
- m_Manager.DeleteLocalDataStore(this);
- }
-
- /*=========================================================================
- ** Retrieves the value from the specified slot.
- =========================================================================*/
- public Object GetData(LocalDataStoreSlot slot)
- {
- // Validate the slot.
- m_Manager.ValidateSlot(slot);
-
- // Cache the slot index to avoid synchronization issues.
- int slotIdx = slot.Slot;
-
- if (slotIdx >= 0)
- {
- // Delay expansion of m_DataTable if we can
- if (slotIdx >= m_DataTable.Length)
- return null;
-
- // Retrieve the data from the given slot.
- LocalDataStoreElement element = m_DataTable[slotIdx];
-
- //Initially we prepopulate the elements to be null.
- if (element == null)
- return null;
-
- // Check that the element is owned by this slot by comparing cookies.
- // This is necesary to avoid resurection race conditions.
- if (element.Cookie == slot.Cookie)
- return element.Value;
-
- // Fall thru and throw exception
- }
-
- throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_SlotHasBeenFreed"));
- }
-
- /*=========================================================================
- ** Sets the data in the specified slot.
- =========================================================================*/
- public void SetData(LocalDataStoreSlot slot, Object data)
- {
- // Validate the slot.
- m_Manager.ValidateSlot(slot);
-
- // Cache the slot index to avoid synchronization issues.
- int slotIdx = slot.Slot;
-
- if (slotIdx >= 0)
- {
- LocalDataStoreElement element = (slotIdx < m_DataTable.Length) ? m_DataTable[slotIdx] : null;
- if (element == null)
- {
- element = PopulateElement(slot);
- }
-
- // Check that the element is owned by this slot by comparing cookies.
- // This is necesary to avoid resurection race conditions.
- if (element.Cookie == slot.Cookie)
- {
- // Set the data on the given slot.
- element.Value = data;
- return;
- }
-
- // Fall thru and throw exception
- }
-
- throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_SlotHasBeenFreed"));
- }
-
- /*=========================================================================
- ** This method does clears the unused slot.
- * Assumes lock on m_Manager is taken
- =========================================================================*/
- internal void FreeData(int slot, long cookie)
- {
- // We try to delay allocate the dataTable (in cases like the manager clearing a
- // just-freed slot in all stores
- if (slot >= m_DataTable.Length)
- return;
-
- LocalDataStoreElement element = m_DataTable[slot];
- if (element != null && element.Cookie == cookie)
- m_DataTable[slot] = null;
- }
-
- /*=========================================================================
- ** Method used to expand the capacity of the local data store.
- =========================================================================*/
- private LocalDataStoreElement PopulateElement(LocalDataStoreSlot slot)
- {
- bool tookLock = false;
- RuntimeHelpers.PrepareConstrainedRegions();
- try {
- Monitor.Enter(m_Manager, ref tookLock);
-
- // Make sure that the slot was not freed in the meantime
- int slotIdx = slot.Slot;
- if (slotIdx < 0)
- throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_SlotHasBeenFreed"));
-
- if (slotIdx >= m_DataTable.Length)
- {
- int capacity = m_Manager.GetSlotTableLength();
-
- // Validate that the specified capacity is larger than the current one.
- Debug.Assert(capacity >= m_DataTable.Length, "LocalDataStore corrupted: capacity >= m_DataTable.Length");
-
- // Allocate the new data table.
- LocalDataStoreElement[] NewDataTable = new LocalDataStoreElement[capacity];
-
- // Copy all the objects into the new table.
- Array.Copy(m_DataTable, NewDataTable, m_DataTable.Length);
-
- // Save the new table.
- m_DataTable = NewDataTable;
- }
-
- // Validate that there is enough space in the local data store now
- Debug.Assert(slotIdx < m_DataTable.Length, "LocalDataStore corrupted: slotIdx < m_DataTable.Length");
-
- if (m_DataTable[slotIdx] == null)
- m_DataTable[slotIdx] = new LocalDataStoreElement(slot.Cookie);
-
- return m_DataTable[slotIdx];
- }
- finally {
- if (tookLock)
- Monitor.Exit(m_Manager);
- }
- }
- }
-}
diff --git a/src/mscorlib/src/System/_LocalDataStoreMgr.cs b/src/mscorlib/src/System/_LocalDataStoreMgr.cs
deleted file mode 100644
index 8f60d6f754..0000000000
--- a/src/mscorlib/src/System/_LocalDataStoreMgr.cs
+++ /dev/null
@@ -1,332 +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: Class that manages stores of local data. This class is used in
-** cooperation with the LocalDataStore class.
-**
-**
-=============================================================================*/
-namespace System {
-
- using System;
- using System.Collections.Generic;
- using System.Threading;
- using System.Runtime.CompilerServices;
- using System.Diagnostics.Contracts;
-
- // This class is an encapsulation of a slot so that it is managed in a secure fashion.
- // It is constructed by the LocalDataStoreManager, holds the slot and the manager
- // and cleans up when it is finalized.
- // This class will not be marked serializable
-[System.Runtime.InteropServices.ComVisible(true)]
- public sealed class LocalDataStoreSlot
- {
- private LocalDataStoreMgr m_mgr;
- private int m_slot;
- private long m_cookie;
-
- // Construct the object to encapsulate the slot.
- internal LocalDataStoreSlot(LocalDataStoreMgr mgr, int slot, long cookie)
- {
- m_mgr = mgr;
- m_slot = slot;
- m_cookie = cookie;
- }
-
- // Accessors for the two fields of this class.
- internal LocalDataStoreMgr Manager
- {
- get
- {
- return m_mgr;
- }
- }
- internal int Slot
- {
- get
- {
- return m_slot;
- }
- }
- internal long Cookie
- {
- get
- {
- return m_cookie;
- }
- }
-
- // Release the slot reserved by this object when this object goes away.
- ~LocalDataStoreSlot()
- {
- LocalDataStoreMgr mgr = m_mgr;
- if (mgr == null)
- return;
-
- int slot = m_slot;
-
- // Mark the slot as free.
- m_slot = -1;
-
- mgr.FreeDataSlot(slot, m_cookie);
- }
- }
-
- // This class will not be marked serializable
- sealed internal class LocalDataStoreMgr
- {
- private const int InitialSlotTableSize = 64;
- private const int SlotTableDoubleThreshold = 512;
- private const int LargeSlotTableSizeIncrease = 128;
-
- /*=========================================================================
- ** Create a data store to be managed by this manager and add it to the
- ** list. The initial size of the new store matches the number of slots
- ** allocated in this manager.
- =========================================================================*/
- public LocalDataStoreHolder CreateLocalDataStore()
- {
- // Create a new local data store.
- LocalDataStore store = new LocalDataStore(this, m_SlotInfoTable.Length);
- LocalDataStoreHolder holder = new LocalDataStoreHolder(store);
-
- bool tookLock = false;
- RuntimeHelpers.PrepareConstrainedRegions();
- try
- {
- Monitor.Enter(this, ref tookLock);
- // Add the store to the array list and return it.
- m_ManagedLocalDataStores.Add(store);
- }
- finally
- {
- if (tookLock)
- Monitor.Exit(this);
- }
- return holder;
- }
-
- /*=========================================================================
- * Remove the specified store from the list of managed stores..
- =========================================================================*/
- public void DeleteLocalDataStore(LocalDataStore store)
- {
- bool tookLock = false;
- RuntimeHelpers.PrepareConstrainedRegions();
- try
- {
- Monitor.Enter(this, ref tookLock);
- // Remove the store to the array list and return it.
- m_ManagedLocalDataStores.Remove(store);
- }
- finally
- {
- if (tookLock)
- Monitor.Exit(this);
- }
- }
-
- /*=========================================================================
- ** Allocates a data slot by finding an available index and wrapping it
- ** an object to prevent clients from manipulating it directly, allowing us
- ** to make assumptions its integrity.
- =========================================================================*/
- public LocalDataStoreSlot AllocateDataSlot()
- {
- bool tookLock = false;
- RuntimeHelpers.PrepareConstrainedRegions();
- try
- {
- Monitor.Enter(this, ref tookLock);
- LocalDataStoreSlot slot;
-
- int slotTableSize = m_SlotInfoTable.Length;
-
- // In case FreeDataSlot has moved the pointer back, the next slot may not be available.
- // Find the first actually available slot.
- int availableSlot = m_FirstAvailableSlot;
- while (availableSlot < slotTableSize)
- {
- if (!m_SlotInfoTable[availableSlot])
- break;
- availableSlot++;
- }
-
- // Check if there are any slots left.
- if (availableSlot >= slotTableSize)
- {
- // The table is full so we need to increase its size.
- int newSlotTableSize;
- if (slotTableSize < SlotTableDoubleThreshold)
- {
- // The table is still relatively small so double it.
- newSlotTableSize = slotTableSize * 2;
- }
- else
- {
- // The table is relatively large so simply increase its size by a given amount.
- newSlotTableSize = slotTableSize + LargeSlotTableSizeIncrease;
- }
-
- // Allocate the new slot info table.
- bool[] newSlotInfoTable = new bool[newSlotTableSize];
-
- // Copy the old array into the new one.
- Array.Copy(m_SlotInfoTable, newSlotInfoTable, slotTableSize);
- m_SlotInfoTable = newSlotInfoTable;
- }
-
- // availableSlot is the index of the empty slot.
- m_SlotInfoTable[availableSlot] = true;
-
- // We do not need to worry about overflowing m_CookieGenerator. It would take centuries
- // of intensive slot allocations on current machines to get the 2^64 counter to overflow.
- // We will perform the increment with overflow check just to play it on the safe side.
- slot = new LocalDataStoreSlot(this, availableSlot, checked(m_CookieGenerator++));
-
- // Save the new "first available slot".hint
- m_FirstAvailableSlot = availableSlot + 1;
-
- // Return the selected slot
- return slot;
- }
- finally
- {
- if (tookLock)
- Monitor.Exit(this);
- }
- }
-
- /*=========================================================================
- ** Allocate a slot and associate a name with it.
- =========================================================================*/
- public LocalDataStoreSlot AllocateNamedDataSlot(String name)
- {
- bool tookLock = false;
- RuntimeHelpers.PrepareConstrainedRegions();
- try
- {
- Monitor.Enter(this, ref tookLock);
- // Allocate a normal data slot.
- LocalDataStoreSlot slot = AllocateDataSlot();
-
- // Insert the association between the name and the data slot number
- // in the hash table.
- m_KeyToSlotMap.Add(name, slot);
- return slot;
- }
- finally
- {
- if (tookLock)
- Monitor.Exit(this);
- }
- }
-
- /*=========================================================================
- ** Retrieve the slot associated with a name, allocating it if no such
- ** association has been defined.
- =========================================================================*/
- public LocalDataStoreSlot GetNamedDataSlot(String name)
- {
- bool tookLock = false;
- RuntimeHelpers.PrepareConstrainedRegions();
- try
- {
- Monitor.Enter(this, ref tookLock);
- // Lookup in the hashtable to try find a slot for the name.
- LocalDataStoreSlot slot = m_KeyToSlotMap.GetValueOrDefault(name);
-
- // If the name is not yet in the hashtable then add it.
- if (null == slot)
- return AllocateNamedDataSlot(name);
-
- // The name was in the hashtable so return the associated slot.
- return slot;
- }
- finally
- {
- if (tookLock)
- Monitor.Exit(this);
- }
- }
-
- /*=========================================================================
- ** Eliminate the association of a name with a slot. The actual slot will
- ** be reclaimed when the finalizer for the slot object runs.
- =========================================================================*/
- public void FreeNamedDataSlot(String name)
- {
- bool tookLock = false;
- RuntimeHelpers.PrepareConstrainedRegions();
- try
- {
- Monitor.Enter(this, ref tookLock);
- // Remove the name slot association from the hashtable.
- m_KeyToSlotMap.Remove(name);
- }
- finally
- {
- if (tookLock)
- Monitor.Exit(this);
- }
- }
-
- /*=========================================================================
- ** Free's a previously allocated data slot on ALL the managed data stores.
- =========================================================================*/
- internal void FreeDataSlot(int slot, long cookie)
- {
- bool tookLock = false;
- RuntimeHelpers.PrepareConstrainedRegions();
- try
- {
- Monitor.Enter(this, ref tookLock);
- // Go thru all the managed stores and set the data on the specified slot to 0.
- for (int i = 0; i < m_ManagedLocalDataStores.Count; i++)
- {
- ((LocalDataStore)m_ManagedLocalDataStores[i]).FreeData(slot, cookie);
- }
-
- // Mark the slot as being no longer occupied.
- m_SlotInfoTable[slot] = false;
- if (slot < m_FirstAvailableSlot)
- m_FirstAvailableSlot = slot;
- }
- finally
- {
- if (tookLock)
- Monitor.Exit(this);
- }
- }
-
- /*=========================================================================
- ** Check that this is a valid slot for this store
- =========================================================================*/
- public void ValidateSlot(LocalDataStoreSlot slot)
- {
- // Make sure the slot was allocated for this store.
- if (slot == null || slot.Manager != this)
- throw new ArgumentException(Environment.GetResourceString("Argument_ALSInvalidSlot"));
- Contract.EndContractBlock();
- }
-
- /*=========================================================================
- ** Return the number of allocated slots in this manager.
- =========================================================================*/
- internal int GetSlotTableLength()
- {
- return m_SlotInfoTable.Length;
- }
-
- private bool[] m_SlotInfoTable = new bool[InitialSlotTableSize];
- private int m_FirstAvailableSlot;
- private List<LocalDataStore> m_ManagedLocalDataStores = new List<LocalDataStore>();
- private Dictionary<String, LocalDataStoreSlot> m_KeyToSlotMap = new Dictionary<String, LocalDataStoreSlot>();
- private long m_CookieGenerator;
- }
-}
diff --git a/src/mscorlib/src/System/__ComObject.cs b/src/mscorlib/src/System/__ComObject.cs
index 9f9bac6084..86800a51f8 100644
--- a/src/mscorlib/src/System/__ComObject.cs
+++ b/src/mscorlib/src/System/__ComObject.cs
@@ -21,7 +21,6 @@ namespace System
using System.Runtime.InteropServices.WindowsRuntime;
using System.Runtime.CompilerServices;
using System.Reflection;
- using System.Security.Permissions;
internal class __ComObject : MarshalByRefObject
{
@@ -58,12 +57,6 @@ namespace System
return base.ToString();
}
-
- internal IntPtr GetIUnknown(out bool fIsURTAggregated)
- {
- fIsURTAggregated = !GetType().IsDefined(typeof(ComImportAttribute), false);
- return System.Runtime.InteropServices.Marshal.GetIUnknownForObject(this);
- }
//====================================================================
// This method retrieves the data associated with the specified
diff --git a/src/mscorlib/src/System/cominterfaces.cs b/src/mscorlib/src/System/cominterfaces.cs
deleted file mode 100644
index a83943d586..0000000000
--- a/src/mscorlib/src/System/cominterfaces.cs
+++ /dev/null
@@ -1,40 +0,0 @@
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-// See the LICENSE file in the project root for more information.
-
-namespace System.Runtime.InteropServices
-{
- [GuidAttribute("03973551-57A1-3900-A2B5-9083E3FF2943")]
- [InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)]
- [CLSCompliant(false)]
- [TypeLibImportClassAttribute(typeof(System.Activator))]
- [System.Runtime.InteropServices.ComVisible(true)]
- public interface _Activator
- {
- 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);
- }
-
- [GuidAttribute("917B14D0-2D9E-38B8-92A9-381ACF52F7C0")]
- [InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)]
- [CLSCompliant(false)]
- [TypeLibImportClassAttribute(typeof(System.Attribute))]
- [System.Runtime.InteropServices.ComVisible(true)]
- public interface _Attribute
- {
- }
-
- [GuidAttribute("C281C7F1-4AA9-3517-961A-463CFED57E75")]
- [InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)]
- [CLSCompliant(false)]
- [TypeLibImportClassAttribute(typeof(System.Threading.Thread))]
- [System.Runtime.InteropServices.ComVisible(true)]
- public interface _Thread
- {
- }
-}
diff --git a/src/mscorlib/src/mscorlib.Friends.cs b/src/mscorlib/src/mscorlib.Friends.cs
index 0e55301656..0e57812638 100644
--- a/src/mscorlib/src/mscorlib.Friends.cs
+++ b/src/mscorlib/src/mscorlib.Friends.cs
@@ -8,18 +8,10 @@ using System.Runtime.CompilerServices;
// 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.
-#if FEATURE_CORESYSTEM
// Depends on things like SuppressUnmanagedCodeAttribute and WindowsRuntimeImportAttribute
-[assembly: InternalsVisibleTo("System.Runtime.WindowsRuntime, PublicKey=" + _InternalsVisibleToKeys.EcmaPublicKeyFull, AllInternalsVisible=false)]
+[assembly: InternalsVisibleTo("System.Runtime.WindowsRuntime, PublicKey=00000000000000000400000000000000", AllInternalsVisible=false)]
// Depends on WindowsRuntimeImportAttribute
-[assembly: InternalsVisibleTo("System.Runtime.WindowsRuntime.UI.Xaml, PublicKey=" + _InternalsVisibleToKeys.EcmaPublicKeyFull, AllInternalsVisible=false)]
+[assembly: InternalsVisibleTo("System.Runtime.WindowsRuntime.UI.Xaml, PublicKey=00000000000000000400000000000000", AllInternalsVisible=false)]
-internal class _InternalsVisibleToKeys
-{
- // Token = b77a5c561934e089
- internal const string EcmaPublicKeyFull = "00000000000000000400000000000000";
-}
-
-#endif // FEATURE_CORESYS