diff options
author | Jiyoung Yun <jy910.yun@samsung.com> | 2017-02-10 20:35:12 +0900 |
---|---|---|
committer | Jiyoung Yun <jy910.yun@samsung.com> | 2017-02-10 20:35:12 +0900 |
commit | 4b11dc566a5bbfa1378d6266525c281b028abcc8 (patch) | |
tree | b48831a898906734f8884d08b6e18f1144ee2b82 /src/mscorlib/src | |
parent | db20f3f1bb8595633a7e16c8900fd401a453a6b5 (diff) | |
download | coreclr-4b11dc566a5bbfa1378d6266525c281b028abcc8.tar.gz coreclr-4b11dc566a5bbfa1378d6266525c281b028abcc8.tar.bz2 coreclr-4b11dc566a5bbfa1378d6266525c281b028abcc8.zip |
Imported Upstream version 1.0.0.9910upstream/1.0.0.9910
Diffstat (limited to 'src/mscorlib/src')
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; - } |