From: Jeremy Kuhne Date: Fri, 9 Dec 2016 05:39:00 +0000 (-0800) Subject: Strip more defines from CoreLib (dotnet/coreclr#8545) X-Git-Tag: submit/tizen/20210909.063632~11030^2~8661 X-Git-Url: http://review.tizen.org/git/?a=commitdiff_plain;h=df2159aed842bd06ee306221b76a763dc13c47fb;p=platform%2Fupstream%2Fdotnet%2Fruntime.git Strip more defines from CoreLib (dotnet/coreclr#8545) * Strip more defines from CoreLib Removes the rest of FEATURE_CAS_POLICY FEATURE_REMOTING FEATURE_MACL And another significant chunk of !FEATURE_CORECLR * Address feedback Commit migrated from https://github.com/dotnet/coreclr/commit/76c62b72ef2642c3ad91209acf02db6c8b42aff7 --- diff --git a/src/coreclr/src/mscorlib/Common/PinnableBufferCache.cs b/src/coreclr/src/mscorlib/Common/PinnableBufferCache.cs index fee3e46..880bcc7 100644 --- a/src/coreclr/src/mscorlib/Common/PinnableBufferCache.cs +++ b/src/coreclr/src/mscorlib/Common/PinnableBufferCache.cs @@ -4,9 +4,6 @@ #define ENABLE #define MINBUFFERS using System; -#if !FEATURE_CORECLR -using System.Diagnostics.Tracing; -#endif using System.Runtime.InteropServices; using System.Runtime.ConstrainedExecution; using System.Collections.Generic; diff --git a/src/coreclr/src/mscorlib/src/Microsoft/Win32/Registry.cs b/src/coreclr/src/mscorlib/src/Microsoft/Win32/Registry.cs index a8ec83f..5743a5a 100644 --- a/src/coreclr/src/mscorlib/src/Microsoft/Win32/Registry.cs +++ b/src/coreclr/src/mscorlib/src/Microsoft/Win32/Registry.cs @@ -63,17 +63,6 @@ namespace Microsoft.Win32 { * This is where current configuration information is stored. */ public static readonly RegistryKey CurrentConfig = RegistryKey.GetBaseKey(RegistryKey.HKEY_CURRENT_CONFIG); - -#if !FEATURE_CORECLR - /** - * Dynamic Data Root Key. - * - * LEGACY: This is where dynamic performance data is stored on Win9X. - * This does not exist on NT. - */ - [Obsolete("The DynData registry key only works on Win9x, which is no longer supported by the CLR. On NT-based operating systems, use the PerformanceData registry key instead.")] - public static readonly RegistryKey DynData = RegistryKey.GetBaseKey(RegistryKey.HKEY_DYN_DATA); -#endif // // Following function will parse a keyName and returns the basekey for it. @@ -116,11 +105,6 @@ namespace Microsoft.Win32 { case "HKEY_CURRENT_CONFIG": basekey = Registry.CurrentConfig; break; -#if !FEATURE_CORECLR - case "HKEY_DYN_DATA": - basekey = RegistryKey.GetBaseKey(RegistryKey.HKEY_DYN_DATA); - break; -#endif default: throw new ArgumentException(Environment.GetResourceString("Arg_RegInvalidKeyName", nameof(keyName))); } diff --git a/src/coreclr/src/mscorlib/src/Microsoft/Win32/RegistryKey.cs b/src/coreclr/src/mscorlib/src/Microsoft/Win32/RegistryKey.cs index dd75310..53d93ef 100644 --- a/src/coreclr/src/mscorlib/src/Microsoft/Win32/RegistryKey.cs +++ b/src/coreclr/src/mscorlib/src/Microsoft/Win32/RegistryKey.cs @@ -49,15 +49,12 @@ */ -namespace Microsoft.Win32 { - +namespace Microsoft.Win32 +{ using System; using System.Collections; using System.Collections.Generic; using System.Security; -#if FEATURE_MACL - using System.Security.AccessControl; -#endif using System.Security.Permissions; using System.Text; using System.Threading; @@ -74,7 +71,7 @@ namespace Microsoft.Win32 { * Registry hive values. Useful only for GetRemoteBaseKey */ [Serializable] -[System.Runtime.InteropServices.ComVisible(true)] + [System.Runtime.InteropServices.ComVisible(true)] public enum RegistryHive { ClassesRoot = unchecked((int)0x80000000), @@ -83,9 +80,6 @@ namespace Microsoft.Win32 { Users = unchecked((int)0x80000003), PerformanceData = unchecked((int)0x80000004), CurrentConfig = unchecked((int)0x80000005), -#if !FEATURE_CORECLR - DynData = unchecked((int)0x80000006), -#endif } /** @@ -107,9 +101,6 @@ namespace Microsoft.Win32 { internal static readonly IntPtr HKEY_USERS = new IntPtr(unchecked((int)0x80000003)); internal static readonly IntPtr HKEY_PERFORMANCE_DATA = new IntPtr(unchecked((int)0x80000004)); internal static readonly IntPtr HKEY_CURRENT_CONFIG = new IntPtr(unchecked((int)0x80000005)); -#if !FEATURE_CORECLR - internal static readonly IntPtr HKEY_DYN_DATA = new IntPtr(unchecked((int)0x80000006)); -#endif // Dirty indicates that we have munged data that should be potentially // written to disk. @@ -137,9 +128,6 @@ namespace Microsoft.Win32 { "HKEY_USERS", "HKEY_PERFORMANCE_DATA", "HKEY_CURRENT_CONFIG", -#if !FEATURE_CORECLR - "HKEY_DYN_DATA" -#endif }; // MSDN defines the following limits for registry key names & values: @@ -264,11 +252,7 @@ namespace Microsoft.Win32 { } } -#if FEATURE_CORECLR void IDisposable.Dispose() -#else - public void Dispose() -#endif { Dispose(true); } @@ -309,21 +293,6 @@ namespace Microsoft.Win32 { return CreateSubKeyInternal(subkey, writable ? RegistryKeyPermissionCheck.ReadWriteSubTree : RegistryKeyPermissionCheck.ReadSubTree, null, options); } - -#if FEATURE_MACL - [ComVisible(false)] - public unsafe RegistryKey CreateSubKey(String subkey, RegistryKeyPermissionCheck permissionCheck, RegistrySecurity registrySecurity) - { - return CreateSubKeyInternal(subkey, permissionCheck, registrySecurity, RegistryOptions.None); - } - - [ComVisible(false)] - public unsafe RegistryKey CreateSubKey(String subkey, RegistryKeyPermissionCheck permissionCheck, RegistryOptions registryOptions, RegistrySecurity registrySecurity) - { - return CreateSubKeyInternal(subkey, permissionCheck, registrySecurity, registryOptions); - } -#endif - [System.Security.SecuritySafeCritical] // auto-generated [ComVisible(false)] private unsafe RegistryKey CreateSubKeyInternal(String subkey, RegistryKeyPermissionCheck permissionCheck, object registrySecurityObj, RegistryOptions registryOptions) @@ -346,23 +315,9 @@ namespace Microsoft.Win32 { } CheckPermission(RegistryInternalCheck.CheckSubKeyCreatePermission, subkey, false, RegistryKeyPermissionCheck.Default); - + Win32Native.SECURITY_ATTRIBUTES secAttrs = null; -#if FEATURE_MACL - RegistrySecurity registrySecurity = (RegistrySecurity)registrySecurityObj; - // For ACL's, get the security descriptor from the RegistrySecurity. - if (registrySecurity != null) { - secAttrs = new Win32Native.SECURITY_ATTRIBUTES(); - secAttrs.nLength = (int)Marshal.SizeOf(secAttrs); - - byte[] sd = registrySecurity.GetSecurityDescriptorBinaryForm(); - // We allocate memory on the stack to improve the speed. - // So this part of code can't be refactored into a method. - byte* pSecDescriptor = stackalloc byte[sd.Length]; - Buffer.Memcpy(pSecDescriptor, 0, sd, 0, sd.Length); - secAttrs.pSecurityDescriptor = pSecDescriptor; - } -#endif + int disposition = 0; // By default, the new key will be writable. @@ -536,7 +491,7 @@ namespace Microsoft.Win32 { if (ret!=0) Win32Error(ret, null); } else { - ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_RegSubKeyAbsent); + ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_RegSubKeyAbsent); } } @@ -717,60 +672,6 @@ namespace Microsoft.Win32 { return null; } -#if FEATURE_MACL - - [System.Security.SecuritySafeCritical] // auto-generated - [ComVisible(false)] - public RegistryKey OpenSubKey(String name, RegistryKeyPermissionCheck permissionCheck) { - ValidateKeyMode(permissionCheck); - return InternalOpenSubKey(name, permissionCheck, GetRegistryKeyAccess(permissionCheck)); - } - - [System.Security.SecuritySafeCritical] - [ComVisible(false)] - public RegistryKey OpenSubKey(String name, RegistryRights rights) - { - return InternalOpenSubKey(name, this.checkMode, (int)rights); - } - - [System.Security.SecuritySafeCritical] // auto-generated - [ComVisible(false)] - public RegistryKey OpenSubKey(String name, RegistryKeyPermissionCheck permissionCheck, RegistryRights rights) { - return InternalOpenSubKey(name, permissionCheck, (int)rights); - } - - [System.Security.SecurityCritical] // auto-generated - private RegistryKey InternalOpenSubKey(String name, RegistryKeyPermissionCheck permissionCheck, int rights) { - ValidateKeyName(name); - ValidateKeyMode(permissionCheck); - - ValidateKeyRights(rights); - - EnsureNotDisposed(); - name = FixupName(name); // Fixup multiple slashes to a single slash - - CheckPermission(RegistryInternalCheck.CheckOpenSubKeyPermission, name, false, permissionCheck); - CheckPermission(RegistryInternalCheck.CheckSubTreePermission, name, false, permissionCheck); - SafeRegistryHandle result = null; - int ret = Win32Native.RegOpenKeyEx(hkey, name, 0, (rights | (int)regView), out result); - if (ret == 0 && !result.IsInvalid) { - RegistryKey key = new RegistryKey(result, (permissionCheck == RegistryKeyPermissionCheck.ReadWriteSubTree), false, remoteKey, false, regView); - key.keyName = keyName + "\\" + name; - key.checkMode = permissionCheck; - return key; - } - - // Return null if we didn't find the key. - if (ret == Win32Native.ERROR_ACCESS_DENIED || ret == Win32Native.ERROR_BAD_IMPERSONATION_LEVEL) { - // We need to throw SecurityException here for compatiblity reason, - // although UnauthorizedAccessException will make more sense. - ThrowHelper.ThrowSecurityException(ExceptionResource.Security_RegistryPermission); - } - - return null; - } -#endif - // This required no security checks. This is to get around the Deleting SubKeys which only require // write permission. They call OpenSubKey which required read. Now instead call this function w/o security checks [System.Security.SecurityCritical] // auto-generated @@ -829,82 +730,6 @@ namespace Microsoft.Win32 { } } -#if !FEATURE_CORECLR - [ComVisible(false)] - public SafeRegistryHandle Handle { - [System.Security.SecurityCritical] - [SecurityPermissionAttribute(SecurityAction.Demand, Flags = SecurityPermissionFlag.UnmanagedCode)] - get { - EnsureNotDisposed(); - int ret = Win32Native.ERROR_INVALID_HANDLE; - if (IsSystemKey()) { - IntPtr baseKey = (IntPtr)0; - switch (keyName) { - case "HKEY_CLASSES_ROOT": - baseKey = HKEY_CLASSES_ROOT; - break; - case "HKEY_CURRENT_USER": - baseKey = HKEY_CURRENT_USER; - break; - case "HKEY_LOCAL_MACHINE": - baseKey = HKEY_LOCAL_MACHINE; - break; - case "HKEY_USERS": - baseKey = HKEY_USERS; - break; - case "HKEY_PERFORMANCE_DATA": - baseKey = HKEY_PERFORMANCE_DATA; - break; - case "HKEY_CURRENT_CONFIG": - baseKey = HKEY_CURRENT_CONFIG; - break; - case "HKEY_DYN_DATA": - baseKey = HKEY_DYN_DATA; - break; - default: - Win32Error(ret, null); - break; - } - // open the base key so that RegistryKey.Handle will return a valid handle - SafeRegistryHandle result; - ret = Win32Native.RegOpenKeyEx(baseKey, - null, - 0, - GetRegistryKeyAccess(IsWritable()) | (int)regView, - out result); - - if (ret == 0 && !result.IsInvalid) { - return result; - } - else { - Win32Error(ret, null); - } - } - else { - return hkey; - } - throw new IOException(Win32Native.GetMessage(ret), ret); - } - } - - [System.Security.SecurityCritical] - [ComVisible(false)] - [SecurityPermissionAttribute(SecurityAction.Demand, Flags = SecurityPermissionFlag.UnmanagedCode)] - public static RegistryKey FromHandle(SafeRegistryHandle handle) { - return FromHandle(handle, RegistryView.Default); - } - - [System.Security.SecurityCritical] - [ComVisible(false)] - [SecurityPermissionAttribute(SecurityAction.Demand, Flags = SecurityPermissionFlag.UnmanagedCode)] - public static RegistryKey FromHandle(SafeRegistryHandle handle, RegistryView view) { - if (handle == null) throw new ArgumentNullException(nameof(handle)); - ValidateKeyView(view); - - return new RegistryKey(handle, true /* isWritable */, view); - } -#endif - [System.Security.SecurityCritical] // auto-generated internal int InternalSubKeyCount() { EnsureNotDisposed(); @@ -1576,27 +1401,6 @@ namespace Microsoft.Win32 { return keyName; } -#if FEATURE_MACL - public RegistrySecurity GetAccessControl() { - return GetAccessControl(AccessControlSections.Access | AccessControlSections.Owner | AccessControlSections.Group); - } - - [System.Security.SecuritySafeCritical] // auto-generated - public RegistrySecurity GetAccessControl(AccessControlSections includeSections) { - EnsureNotDisposed(); - return new RegistrySecurity(hkey, keyName, includeSections); - } - - [System.Security.SecuritySafeCritical] // auto-generated - public void SetAccessControl(RegistrySecurity registrySecurity) { - EnsureWriteable(); - if (registrySecurity == null) - throw new ArgumentNullException(nameof(registrySecurity)); - - registrySecurity.Persist(hkey, keyName); - } -#endif - /** * After calling GetLastWin32Error(), it clears the last error field, * so you must save the HResult and pass it to this method. This method @@ -1774,17 +1578,12 @@ namespace Microsoft.Win32 { } [System.Security.SecurityCritical] // auto-generated - private void CheckPermission(RegistryInternalCheck check, string item, bool subKeyWritable, RegistryKeyPermissionCheck subKeyCheck) { + private void CheckPermission(RegistryInternalCheck check, string item, bool subKeyWritable, RegistryKeyPermissionCheck subKeyCheck) + { bool demand = false; RegistryPermissionAccess access = RegistryPermissionAccess.NoAccess; string path = null; -#if !FEATURE_CORECLR - if (CodeAccessSecurityEngine.QuickCheckForAllDemands()) { - return; // full trust fast path - } -#endif // !FEATURE_CORECLR - switch (check) { // // Read/Write/Create SubKey Permission @@ -2129,16 +1928,6 @@ namespace Microsoft.Win32 { } } - -#if FEATURE_MACL - static private void ValidateKeyRights(int rights) { - if(0 != (rights & ~((int)RegistryRights.FullControl))) { - // We need to throw SecurityException here for compatiblity reason, - // although UnauthorizedAccessException will make more sense. - ThrowHelper.ThrowSecurityException(ExceptionResource.Security_RegistryPermission); - } - } -#endif // Win32 constants for error handling private const int FORMAT_MESSAGE_IGNORE_INSERTS = 0x00000200; private const int FORMAT_MESSAGE_FROM_SYSTEM = 0x00001000; diff --git a/src/coreclr/src/mscorlib/src/Microsoft/Win32/SafeHandles/Win32SafeHandles.cs b/src/coreclr/src/mscorlib/src/Microsoft/Win32/SafeHandles/Win32SafeHandles.cs index 6f7dddf..538bb31 100644 --- a/src/coreclr/src/mscorlib/src/Microsoft/Win32/SafeHandles/Win32SafeHandles.cs +++ b/src/coreclr/src/mscorlib/src/Microsoft/Win32/SafeHandles/Win32SafeHandles.cs @@ -23,9 +23,6 @@ namespace Microsoft.Win32.SafeHandles // Class of safe handle which uses 0 or -1 as an invalid handle. [System.Security.SecurityCritical] // auto-generated_required -#if !FEATURE_CORECLR - [SecurityPermission(SecurityAction.InheritanceDemand, UnmanagedCode=true)] -#endif public abstract class SafeHandleZeroOrMinusOneIsInvalid : SafeHandle { [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)] @@ -33,13 +30,11 @@ namespace Microsoft.Win32.SafeHandles { } -#if FEATURE_CORECLR // A default constructor is needed to satisfy CoreCLR inheritence rules. It should not be called at runtime protected SafeHandleZeroOrMinusOneIsInvalid() { throw new NotImplementedException(); } -#endif // FEATURE_CORECLR public override bool IsInvalid { [System.Security.SecurityCritical] @@ -49,9 +44,6 @@ namespace Microsoft.Win32.SafeHandles // Class of safe handle which uses only -1 as an invalid handle. [System.Security.SecurityCritical] // auto-generated_required -#if !FEATURE_CORECLR - [SecurityPermission(SecurityAction.InheritanceDemand, UnmanagedCode=true)] -#endif public abstract class SafeHandleMinusOneIsInvalid : SafeHandle { [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)] @@ -59,13 +51,11 @@ namespace Microsoft.Win32.SafeHandles { } -#if FEATURE_CORECLR // A default constructor is needed to satisfy CoreCLR inheritence rules. It should not be called at runtime protected SafeHandleMinusOneIsInvalid() { throw new NotImplementedException(); } -#endif // FEATURE_CORECLR public override bool IsInvalid { [System.Security.SecurityCritical] @@ -75,9 +65,6 @@ namespace Microsoft.Win32.SafeHandles // Class of critical handle which uses 0 or -1 as an invalid handle. [System.Security.SecurityCritical] // auto-generated_required -#if !FEATURE_CORECLR - [SecurityPermission(SecurityAction.InheritanceDemand, UnmanagedCode=true)] -#endif public abstract class CriticalHandleZeroOrMinusOneIsInvalid : CriticalHandle { [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)] @@ -93,9 +80,6 @@ namespace Microsoft.Win32.SafeHandles // Class of critical handle which uses only -1 as an invalid handle. [System.Security.SecurityCritical] // auto-generated_required -#if !FEATURE_CORECLR - [SecurityPermission(SecurityAction.InheritanceDemand, UnmanagedCode=true)] -#endif public abstract class CriticalHandleMinusOneIsInvalid : CriticalHandle { [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)] diff --git a/src/coreclr/src/mscorlib/src/Microsoft/Win32/Win32Native.cs b/src/coreclr/src/mscorlib/src/Microsoft/Win32/Win32Native.cs index 98ee8ff..9704f17 100644 --- a/src/coreclr/src/mscorlib/src/Microsoft/Win32/Win32Native.cs +++ b/src/coreclr/src/mscorlib/src/Microsoft/Win32/Win32Native.cs @@ -907,58 +907,6 @@ namespace Microsoft.Win32 { [DllImport(KERNEL32, SetLastError = true, CharSet = CharSet.Unicode, ExactSpelling = true)] internal static extern uint GetLongPathNameW(string lpszShortPath, SafeHandle lpszLongPath, uint cchBuffer); -#if !FEATURE_CORECLR - // Disallow access to all non-file devices from methods that take - // a String. This disallows DOS devices like "con:", "com1:", - // "lpt1:", etc. Use this to avoid security problems, like allowing - // a web client asking a server for "http://server/com1.aspx" and - // then causing a worker process to hang. - [System.Security.SecurityCritical] // auto-generated - internal static SafeFileHandle SafeCreateFile(String lpFileName, - int dwDesiredAccess, System.IO.FileShare dwShareMode, - SECURITY_ATTRIBUTES securityAttrs, System.IO.FileMode dwCreationDisposition, - int dwFlagsAndAttributes, IntPtr hTemplateFile) - { - SafeFileHandle handle = CreateFile( lpFileName, dwDesiredAccess, dwShareMode, - securityAttrs, dwCreationDisposition, - dwFlagsAndAttributes, hTemplateFile ); - - if (!handle.IsInvalid) - { - int fileType = Win32Native.GetFileType(handle); - if (fileType != Win32Native.FILE_TYPE_DISK) { - handle.Dispose(); - throw new NotSupportedException(Environment.GetResourceString("NotSupported_FileStreamOnNonFiles")); - } - } - - return handle; - } - - [System.Security.SecurityCritical] // auto-generated - internal static SafeFileHandle UnsafeCreateFile(String lpFileName, - int dwDesiredAccess, System.IO.FileShare dwShareMode, - SECURITY_ATTRIBUTES securityAttrs, System.IO.FileMode dwCreationDisposition, - int dwFlagsAndAttributes, IntPtr hTemplateFile) - { - SafeFileHandle handle = CreateFile( lpFileName, dwDesiredAccess, dwShareMode, - securityAttrs, dwCreationDisposition, - dwFlagsAndAttributes, hTemplateFile ); - - return handle; - } - - // Do not use these directly, use the safe or unsafe versions above. - // The safe version does not support devices (aka if will only open - // files on disk), while the unsafe version give you the full semantic - // of the native version. - [DllImport(KERNEL32, SetLastError=true, CharSet=CharSet.Auto, BestFitMapping=false)] - private static extern SafeFileHandle CreateFile(String lpFileName, - int dwDesiredAccess, System.IO.FileShare dwShareMode, - SECURITY_ATTRIBUTES securityAttrs, System.IO.FileMode dwCreationDisposition, - int dwFlagsAndAttributes, IntPtr hTemplateFile); -#endif - [DllImport(KERNEL32, SetLastError=true, CharSet=CharSet.Auto, BestFitMapping=false)] internal static extern SafeFileMappingHandle CreateFileMapping(SafeFileHandle hFile, IntPtr lpAttributes, uint fProtect, uint dwMaximumSizeHigh, uint dwMaximumSizeLow, String lpName); diff --git a/src/coreclr/src/mscorlib/src/System.Private.CoreLib.txt b/src/coreclr/src/mscorlib/src/System.Private.CoreLib.txt index bad4a0d..c379612 100644 --- a/src/coreclr/src/mscorlib/src/System.Private.CoreLib.txt +++ b/src/coreclr/src/mscorlib/src/System.Private.CoreLib.txt @@ -70,25 +70,6 @@ InvariantFailed = Invariant failed. InvariantFailed_Cnd = Invariant failed: {0} MustUseCCRewrite = An assembly (probably "{1}") must be rewritten using the code contracts binary rewriter (CCRewrite) because it is calling Contract.{0} and the CONTRACTS_FULL symbol is defined. Remove any explicit definitions of the CONTRACTS_FULL symbol from your project and rebuild. CCRewrite can be downloaded from http://go.microsoft.com/fwlink/?LinkID=169180. \r\nAfter the rewriter is installed, it can be enabled in Visual Studio from the project's Properties page on the Code Contracts pane. Ensure that "Perform Runtime Contract Checking" is enabled, which will define CONTRACTS_FULL. -; Access Control -#if FEATURE_MACL -AccessControl_MustSpecifyContainerAcl = The named parameter must be a container ACL. -AccessControl_MustSpecifyLeafObjectAcl = The named parameter must be a non-container ACL. -AccessControl_AclTooLong = Length of the access control list exceed the allowed maximum. -AccessControl_MustSpecifyDirectoryObjectAcl = The named parameter must be a directory-object ACL. -AccessControl_MustSpecifyNonDirectoryObjectAcl = The named parameter must be a non-directory-object ACL. -AccessControl_InvalidSecurityDescriptorRevision = Security descriptor with revision other than '1' are not legal. -AccessControl_InvalidSecurityDescriptorSelfRelativeForm = Security descriptor must be in the self-relative form. -AccessControl_NoAssociatedSecurity = Unable to perform a security operation on an object that has no associated security. This can happen when trying to get an ACL of an anonymous kernel object. -AccessControl_InvalidHandle = The supplied handle is invalid. This can happen when trying to set an ACL on an anonymous kernel object. -AccessControl_UnexpectedError = Method failed with unexpected error code {0}. -AccessControl_InvalidSidInSDDLString = The SDDL string contains an invalid sid or a sid that cannot be translated. -AccessControl_InvalidOwner = The security identifier is not allowed to be the owner of this object. -AccessControl_InvalidGroup = The security identifier is not allowed to be the primary group of this object. -AccessControl_InvalidAccessRuleType = The access rule is not the correct type. -AccessControl_InvalidAuditRuleType = The audit rule is not the correct type. -#endif // FEATURE_MACL - ; Identity Reference Library #if FEATURE_IDENTITY_REFERENCE IdentityReference_IdentityNotMapped = Some or all identity references could not be translated. @@ -1128,9 +1109,6 @@ InvalidOperation_EnumFailedVersion = Collection was modified; enumeration operat InvalidOperation_EnumNotStarted = Enumeration has not started. Call MoveNext. InvalidOperation_EnumOpCantHappen = Enumeration has either not started or has already finished. InvalidOperation_ModifyRONumFmtInfo = Unable to modify a read-only NumberFormatInfo object. -#if FEATURE_CAS_POLICY -InvalidOperation_ModifyROPermSet = ReadOnlyPermissionSet objects may not be modified. -#endif // FEATURE_CAS_POLICY InvalidOperation_MustBeSameThread = This operation must take place on the same thread on which the object was created. InvalidOperation_MustRevertPrivilege = Must revert the privilege prior to attempting this operation. InvalidOperation_ReadOnly = Instance is read-only. @@ -1441,12 +1419,6 @@ NotSupported_NonBlittableTypes = Non-blittable parameter types are not supported NotSupported_UserDllImport = DllImport cannot be used on user-defined methods. NotSupported_UserCOM = COM Interop is not supported for user-defined types. #endif //FEATURE_WINDOWSPHONE -#if FEATURE_CAS_POLICY -NotSupported_RequiresCasPolicyExplicit = This method explicitly uses CAS policy, which has been obsoleted by the .NET Framework. In order to enable CAS policy for compatibility reasons, please use the NetFx40_LegacySecurityPolicy configuration switch. Please see http://go.microsoft.com/fwlink/?LinkID=155570 for more information. -NotSupported_RequiresCasPolicyImplicit = This method implicitly uses CAS policy, which has been obsoleted by the .NET Framework. In order to enable CAS policy for compatibility reasons, please use the NetFx40_LegacySecurityPolicy configuration switch. Please see http://go.microsoft.com/fwlink/?LinkID=155570 for more information. -NotSupported_CasDeny = The Deny stack modifier has been obsoleted by the .NET Framework. Please see http://go.microsoft.com/fwlink/?LinkId=155571 for more information. -NotSupported_SecurityContextSourceAppDomainInHeterogenous = SecurityContextSource.CurrentAppDomain is not supported in heterogenous AppDomains. -#endif // FEATURE_CAS_POLICY #if FEATURE_APPX NotSupported_AppX = {0} is not supported in AppX. LoadOfFxAssemblyNotSupported_AppX = {0} of .NET Framework assemblies is not supported in AppX. @@ -1456,9 +1428,6 @@ NotSupported_WinRT_PartialTrust = Windows Runtime is not supported in partial tr #endif // FEATURE_COMINTEROP ; ReflectionTypeLoadException ReflectionTypeLoad_LoadFailed = Unable to load one or more of the requested types. Retrieve the LoaderExceptions property for more information. -#if !FEATURE_CORECLR -NotSupported_NoTypeInfo = Cannot resolve {0} to a TypeInfo object. -#endif #if FEATURE_COMINTEROP NotSupported_PIAInAppxProcess = A Primary Interop Assembly is not supported in AppX. #endif @@ -1580,125 +1549,6 @@ Remoting_Message_BadRetValOrOutArg = Bad return value or out-argument inside the Remoting_NonPublicOrStaticCantBeCalledRemotely = Permission denied: cannot call non-public or static methods remotely. Remoting_Proxy_ProxyTypeIsNotMBR = classToProxy argument must derive from MarshalByRef type. Remoting_TP_NonNull = The transparent proxy field of a real proxy must be null. -#if FEATURE_REMOTING -Remoting_Activation_BadAttribute = Activation attribute does not implement the IContextAttribute interface. -Remoting_Activation_BadObject = Proxy Attribute returned an incompatible object when constructing an instance of type {0}. -Remoting_Activation_MBR_ProxyAttribute = Proxy Attributes are supported on ContextBound types only. -Remoting_Activation_ConnectFailed = An attempt to connect to the remote activator failed with exception '{0}'. -Remoting_Activation_Failed = Activation failed due to an unknown reason. -Remoting_Activation_InconsistentState = Inconsistent state during activation; there may be two proxies for the same object. -Remoting_Activation_MissingRemoteAppEntry = Cannot find an entry for remote application '{0}'. -Remoting_Activation_NullReturnValue = Return value of construction call was null. -Remoting_Activation_NullFromInternalUnmarshal = InternalUnmarshal of returned ObjRef from activation call returned null. -Remoting_Activation_WellKnownCTOR = Cannot run a non-default constructor when connecting to well-known objects. -Remoting_Activation_PermissionDenied = Type '{0}' is not registered for activation. -Remoting_Activation_PropertyUnhappy = A context property did not approve the candidate context for activating the object. -Remoting_Activation_AsyncUnsupported = Async Activation not supported. -Remoting_AmbiguousCTOR = Cannot resolve the invocation to the correct constructor. -Remoting_AmbiguousMethod = Cannot resolve the invocation to the correct method. -Remoting_AppDomains_NYI = This feature is not yet supported for cross-application domain. -Remoting_AppDomainsCantBeCalledRemotely = Permission denied: cannot call methods on the AppDomain class remotely. -Remoting_AssemblyLoadFailed = Cannot load assembly '{0}'. -Remoting_Attribute_UseAttributeNotsettable = UseAttribute not allowed in SoapTypeAttribute. -Remoting_BadType = Cannot load type '{0}'. -Remoting_BadField = Remoting cannot find field '{0}' on type '{1}'. -Remoting_BadInternalState_ActivationFailure = Invalid internal state: Activation service failed to initialize. -Remoting_BadInternalState_ProxySameAppDomain = Invalid internal state: A marshal by ref object should not have a proxy in its own AppDomain. -Remoting_BadInternalState_FailEnvoySink = Invalid internal state: Failed to create an envoy sink for the object. -Remoting_CantDisconnectClientProxy = Cannot call disconnect on a proxy. -Remoting_CantInvokeIRemoteDispatch = Cannot invoke methods on IRemoteDispatch. -Remoting_ChannelNameAlreadyRegistered = The channel '{0}' is already registered. -Remoting_ChannelNotRegistered = The channel '{0}' is not registered with remoting services. -Remoting_Channel_PopOnEmptySinkStack = Tried to pop data from an empty channel sink stack. -Remoting_Channel_PopFromSinkStackWithoutPush = A channel sink tried to pop data from the stack without first pushing data onto the stack. -Remoting_Channel_StoreOnEmptySinkStack = A channel sink called the Store method when the sink stack was empty. -Remoting_Channel_StoreOnSinkStackWithoutPush = A channel sink called the Store method on the sink stack without first pushing data onto the stack. -Remoting_Channel_CantCallAPRWhenStackEmpty = Cannot call the AsyncProcessResponse method on the previous channel sink because the stack is empty. -Remoting_Channel_CantCallFRSWhenStackEmtpy = Called FlipRememberedStack() when stack was not null. -Remoting_Channel_CantCallGetResponseStreamWhenStackEmpty = Cannot call the GetResponseStream method on the previous channel sink because the stack is empty. -Remoting_Channel_DispatchSinkMessageMissing = No message was deserialized prior to calling the DispatchChannelSink. -Remoting_Channel_DispatchSinkWantsNullRequestStream = The request stream should be null when the DispatchChannelSink is called. -Remoting_Channel_CannotBeSecured = Channel {0} cannot be secured. Please consider using a channel that implements ISecurableChannel -Remoting_Config_ChannelMissingCtor = To be used from a .config file, the channel type '{0}' must have a constructor of the form '{1}' -Remoting_Config_SinkProviderMissingCtor = To be used from a .config file, the sink provider type '{0}' must have a constructor of the form '{1}' -Remoting_Config_SinkProviderNotFormatter = A sink provider of type '{0}' is incorrectly labeled as a 'formatter'. -Remoting_Config_ConfigurationFailure = Remoting configuration failed with the exception '{0}'. -Remoting_Config_InvalidTimeFormat = Invalid time format '{0}'. Examples of valid time formats include 7D, 10H, 5M, 30S, or 20MS. -Remoting_Config_AppNameSet = The remoting application name, '{0}', had already been set. -Remoting_Config_ErrorsModeSet = The remoting custom errors mode had already been set. -Remoting_Config_CantRedirectActivationOfWellKnownService = Attempt to redirect activation for type '{0}, {1}'. This is not allowed since either a well-known service type has already been registered with that type or that type has been registered has a activated service type. -Remoting_Config_CantUseRedirectedTypeForWellKnownService = Attempt to register a well-known or activated service type of type '{0}, {1}'. This is not allowed since the type has already been redirected to activate elsewhere. -Remoting_Config_InvalidChannelType = '{0}' does not implement IChannelReceiver or IChannelSender. All channels must implement one of these interfaces. -Remoting_Config_InvalidSinkProviderType = Unable to use '{0}' as a channel sink provider. It does not implement '{1}'. -Remoting_Config_MissingWellKnownModeAttribute = Well-known service entries must contain a 'mode' attribute with a value of 'Singleton' or 'SingleCall'. -Remoting_Config_MissingTypeAttribute = '{0}' entries must contain a '{1}' attribute of the form 'typeName, assemblyName'. -Remoting_Config_MissingXmlTypeAttribute = '{0}' entries must contain a '{1}' attribute of the form 'xmlTypeName, xmlTypeNamespace'. -Remoting_Config_NoAppName = Improper remoting configuration: missing ApplicationName property. -Remoting_Config_NonTemplateIdAttribute = Only '{0}' templates can have an 'id' attribute. -Remoting_Config_PreloadRequiresTypeOrAssembly = Preload entries require a type or assembly attribute. -Remoting_Config_ProviderNeedsElementName = Sink providers must have an element name of 'formatter' or 'provider'. -Remoting_Config_RequiredXmlAttribute = '{0}' entries require a '{1}' attribute. -Remoting_Config_ReadFailure = .Config file '{0}' cannot be read successfully due to exception '{1}'. -Remoting_Config_NodeMustBeUnique = There can be only one '{0}' node in the '{1}' section of a config file. -Remoting_Config_TemplateCannotReferenceTemplate = A '{0}' template cannot reference another '{0}' template. -Remoting_Config_TypeAlreadyRedirected = Attempt to redirect activation of type '{0}, {1}' which is already redirected. -Remoting_Config_UnknownValue = Unknown value {1} was found on the {0} node. -Remoting_Config_UnableToResolveTemplate = Cannot resolve '{0}' template reference: '{1}'. -Remoting_Config_VersionPresent = Version information is present in the assembly name '{0}' which is not allowed for '{1}' entries. -Remoting_Contexts_BadProperty = A property that contributed a bad sink to the chain was found. -Remoting_Contexts_NoProperty = A property with the name '{0}' was not found. -Remoting_Contexts_ContextNotFrozenForCallBack = Context should be frozen before calling the DoCallBack method. -Remoting_Default = Unknown remoting error. -Remoting_HandlerNotRegistered = The tracking handler of type '{0}' is not registered with Remoting Services. -Remoting_InvalidMsg = Invalid Message Object. -Remoting_InvalidCallingType = Attempted to call a method declared on type '{0}' on an object which exposes '{1}'. -Remoting_InvalidRequestedType = The server object type cannot be cast to the requested type '{0}'. -Remoting_InternalError = Server encountered an internal error. For more information, turn off customErrors in the server's .config file. -Remoting_Lifetime_ILeaseReturn = Expected a return object of type ILease, but received '{0}'. -Remoting_Lifetime_InitialStateInitialLeaseTime = InitialLeaseTime property can only be set when the lease is in initial state. The state is '{0}'. -Remoting_Lifetime_InitialStateRenewOnCall = RenewOnCallTime property can only be set when the lease is in initial state. The state is '{0}'. -Remoting_Lifetime_InitialStateSponsorshipTimeout = SponsorshipTimeout property can only be set when the lease is in initial state. State is '{0}'. -Remoting_Lifetime_SetOnce = '{0}' can only be set once within an AppDomain. -Remoting_Message_ArgMismatch = {2} arguments were passed to '{0}::{1}'. {3} arguments were expected by this method. -Remoting_Message_BadAsyncResult = The async result object is null or of an unexpected type. -Remoting_Message_BadType = The method was called with a Message of an unexpected type. -Remoting_Message_CoercionFailed = The argument type '{0}' cannot be converted into parameter type '{1}'. -Remoting_Message_MissingArgValue = Expecting an instance of type '{0}' at pos {1} in the args array. -Remoting_Message_BadSerialization = Invalid or malformed serialization information for the message object. -Remoting_NoIdentityEntry = No remoting information was found for this object. -Remoting_NotRemotableByReference = Trying to create a proxy to an unbound type. -Remoting_NullMessage = The method was called with a null message. -Remoting_Proxy_BadType = The proxy is of an unsupported type. -Remoting_ResetURI = Attempt to reset the URI for an object from '{0}' to '{1}'. -Remoting_ServerObjectNotFound = The server object for URI '{0}' is not registered with the remoting infrastructure (it may have been disconnected). -Remoting_SetObjectUriForMarshal__ObjectNeedsToBeLocal = SetObjectUriForMarshal method should only be called for MarshalByRefObjects that exist in the current AppDomain. -Remoting_SetObjectUriForMarshal__UriExists = SetObjectUriForMarshal method has already been called on this object or the object has already been marshaled. -Remoting_Proxy_BadReturnType = Return argument has an invalid type. -Remoting_Proxy_ReturnValueTypeCannotBeNull = ByRef value type parameter cannot be null. -Remoting_Proxy_BadReturnTypeForActivation = Bad return type for activation call via Invoke: must be of type IConstructionReturnMessage. -Remoting_Proxy_BadTypeForActivation = Type mismatch between proxy type '{0}' and activation type '{1}'. -Remoting_Proxy_ExpectedOriginalMessage = The message passed to Invoke should be passed to PropagateOutParameters. -Remoting_Proxy_InvalidCall = Trying to call proxy while constructor call is in progress. -Remoting_Proxy_InvalidState = Channel sink does not exist. Failed to dispatch async call. -Remoting_Proxy_NoChannelSink = This remoting proxy has no channel sink which means either the server has no registered server channels that are listening, or this application has no suitable client channel to talk to the server. -Remoting_Proxy_InvalidCallType = Only the synchronous call type is supported for messages that are not of type Message. -Remoting_Proxy_WrongContext = ExecuteMessage can be called only from the native context of the object. -Remoting_SOAPInteropxsdInvalid = Soap Parse error, xsd:type '{0}' invalid {1} -Remoting_SOAPQNameNamespace = SoapQName missing a Namespace value '{0}'. -Remoting_ThreadAffinity_InvalidFlag = The specified flag '{0}' does not have one of the valid values. -Remoting_TrackingHandlerAlreadyRegistered = The handler has already been registered with TrackingServices. -Remoting_URIClash = Found two different objects associated with the same URI, '{0}'. -Remoting_URIExists = The remoted object already has an associated URI. -Remoting_URIToProxy = Trying to associate the URI with a proxy. -Remoting_WellKnown_MustBeMBR = Attempted to create well-known object of type '{0}'. Well-known objects must derive from the MarshalByRefObject class. -Remoting_WellKnown_CtorCantMarshal = '{0}': A well-known object cannot marshal itself in its constructor, or perform any action that would cause it to be marshaled (such as passing the 'this' pointer as a parameter to a remote method). -Remoting_WellKnown_CantDirectlyConnect = Attempt to connect to a server using its object URI: '{0}'. A valid, complete URL must be used. -Remoting_Connect_CantCreateChannelSink = Cannot create channel sink to connect to URL '{0}'. An appropriate channel has probably not been registered. -Remoting_UnexpectedNullTP = Failed to create a transparent proxy. If a custom RealProxy is being used ensure it sets the proxy type. -; The following remoting exception messages appear in native resources too (mscorrc.rc) -Remoting_Disconnected = Object '{0}' has been disconnected or does not exist at the server. -Remoting_Message_MethodMissing = The method '{0}' was not found on the interface/type '{1}'. -#endif // FEATURE_REMOTING ; Resources exceptions ; @@ -1727,24 +1577,6 @@ Security_GenericNoType = Request failed. Security_NoAPTCA = That assembly does not allow partially trusted callers. Security_RegistryPermission = Requested registry access is not allowed. Security_MustRevertOverride = Stack walk modifier must be reverted before another modification of the same type can be performed. -#if FEATURE_CAS_POLICY -Security_CannotGenerateHash = Hash for the assembly cannot be generated. -Security_CannotGetRawData = Assembly bytes could not be retrieved. -Security_PrincipalPermission = Request for principal permission failed. -Security_Action = The action that failed was: -Security_TypeFirstPermThatFailed = The type of the first permission that failed was: -Security_FirstPermThatFailed = The first permission that failed was: -Security_Demanded = The demand was for: -Security_GrantedSet = The granted set of the failing assembly was: -Security_RefusedSet = The refused set of the failing assembly was: -Security_Denied = The denied permissions were: -Security_PermitOnly = The only permitted permissions were: -Security_Assembly = The assembly or AppDomain that failed was: -Security_Method = The method that caused the failure was: -Security_Zone = The Zone of the assembly that failed was: -Security_Url = The Url of the assembly that failed was: -Security_AnonymouslyHostedDynamicMethodCheckFailed = The demand failed due to the code access security information captured during the creation of an anonymously hosted dynamic method. In order for this operation to succeed, ensure that the demand would have succeeded at the time the method was created. See http://go.microsoft.com/fwlink/?LinkId=288746 for more information. -#endif // FEATURE_CAS_POLICY ; ; HostProtection exceptions @@ -2197,14 +2029,6 @@ XMLSyntax_InvalidSyntaxSatAssemTag = Invalid XML in file "{0}" near element "{1} XMLSyntax_InvalidSyntaxSatAssemTagBadAttr = Invalid XML in file "{0}" near "{1}" and "{2}". In the section, the tag must have exactly 1 attribute called 'name', whose value is a fully-qualified assembly name. XMLSyntax_InvalidSyntaxSatAssemTagNoAttr = Invalid XML in file "{0}". In the section, the tag must have exactly 1 attribute called 'name', whose value is a fully-qualified assembly name. -; CodeGroup -#if FEATURE_CAS_POLICY -NetCodeGroup_PermissionSet = Same site Web -MergeLogic_Union = Union -MergeLogic_FirstMatch = First Match -FileCodeGroup_PermissionSet = Same directory FileIO - '{0}' -#endif // FEATURE_CAS_POLICY - ; MembershipConditions StrongName_ToString = StrongName - {0}{1}{2} StrongName_Name = name = {0} @@ -2217,12 +2041,6 @@ Zone_ToString = Zone - {0} All_ToString = All code Url_ToString = Url GAC_ToString = GAC -#if FEATURE_CAS_POLICY -Site_ToStringArg = Site - {0} -Publisher_ToStringArg = Publisher - {0} -Url_ToStringArg = Url - {0} -#endif // FEATURE_CAS_POLICY - ; Interop non exception strings. TypeLibConverter_ImportedTypeLibProductName = Assembly imported from type library '{0}'. diff --git a/src/coreclr/src/mscorlib/src/System/Action.cs b/src/coreclr/src/mscorlib/src/System/Action.cs index d6653c7..27f7faf 100644 --- a/src/coreclr/src/mscorlib/src/System/Action.cs +++ b/src/coreclr/src/mscorlib/src/System/Action.cs @@ -2,62 +2,23 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -// - -namespace System { - using System.Runtime.CompilerServices; - +namespace System +{ public delegate void Action(T obj); // Action/Func delegates first shipped with .NET Framework 3.5 in System.Core.dll as part of LINQ // These were type forwarded to mscorlib.dll in .NET Framework 4.0 and in Silverlight 5.0 - -#if !FEATURE_CORECLR - [TypeForwardedFrom("System.Core, Version=3.5.0.0, Culture=Neutral, PublicKeyToken=b77a5c561934e089")] -#endif public delegate void Action(); - -#if !FEATURE_CORECLR - [TypeForwardedFrom("System.Core, Version=3.5.0.0, Culture=Neutral, PublicKeyToken=b77a5c561934e089")] -#endif public delegate void Action(T1 arg1, T2 arg2); - -#if !FEATURE_CORECLR - [TypeForwardedFrom("System.Core, Version=3.5.0.0, Culture=Neutral, PublicKeyToken=b77a5c561934e089")] -#endif public delegate void Action(T1 arg1, T2 arg2, T3 arg3); - -#if !FEATURE_CORECLR - [TypeForwardedFrom("System.Core, Version=3.5.0.0, Culture=Neutral, PublicKeyToken=b77a5c561934e089")] -#endif public delegate void Action(T1 arg1, T2 arg2, T3 arg3, T4 arg4); -#if !FEATURE_CORECLR - [TypeForwardedFrom("System.Core, Version=3.5.0.0, Culture=Neutral, PublicKeyToken=b77a5c561934e089")] -#endif public delegate TResult Func(); - -#if !FEATURE_CORECLR - [TypeForwardedFrom("System.Core, Version=3.5.0.0, Culture=Neutral, PublicKeyToken=b77a5c561934e089")] -#endif public delegate TResult Func(T arg); - -#if !FEATURE_CORECLR - [TypeForwardedFrom("System.Core, Version=3.5.0.0, Culture=Neutral, PublicKeyToken=b77a5c561934e089")] -#endif public delegate TResult Func(T1 arg1, T2 arg2); - -#if !FEATURE_CORECLR - [TypeForwardedFrom("System.Core, Version=3.5.0.0, Culture=Neutral, PublicKeyToken=b77a5c561934e089")] -#endif public delegate TResult Func(T1 arg1, T2 arg2, T3 arg3); - -#if !FEATURE_CORECLR - [TypeForwardedFrom("System.Core, Version=3.5.0.0, Culture=Neutral, PublicKeyToken=b77a5c561934e089")] -#endif public delegate TResult Func(T1 arg1, T2 arg2, T3 arg3, T4 arg4); - public delegate void Action(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5); public delegate void Action(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6); public delegate void Action(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7); diff --git a/src/coreclr/src/mscorlib/src/System/Activator.cs b/src/coreclr/src/mscorlib/src/System/Activator.cs index afd46e7..1675066 100644 --- a/src/coreclr/src/mscorlib/src/System/Activator.cs +++ b/src/coreclr/src/mscorlib/src/System/Activator.cs @@ -16,10 +16,6 @@ namespace System { using System; using System.Reflection; using System.Runtime.Remoting; -#if FEATURE_REMOTING - using System.Runtime.Remoting.Activation; - using Message = System.Runtime.Remoting.Messaging.Message; -#endif using System.Security; using CultureInfo = System.Globalization.CultureInfo; using Evidence = System.Security.Policy.Evidence; @@ -34,7 +30,7 @@ namespace System { // Only statics, does not need to be marked with the serializable attribute [ClassInterface(ClassInterfaceType.None)] [ComDefaultInterface(typeof(_Activator))] -[System.Runtime.InteropServices.ComVisible(true)] + [System.Runtime.InteropServices.ComVisible(true)] public sealed class Activator : _Activator { internal const int LookupMask = 0x000000FF; @@ -81,22 +77,7 @@ namespace System { bindingAttr |= Activator.ConstructorDefault; if (activationAttributes != null && activationAttributes.Length > 0){ - // If type does not derive from MBR - // throw notsupportedexception -#if FEATURE_REMOTING - if(type.IsMarshalByRef){ - // The fix below is preventative. - // - if(!(type.IsContextful)){ - if(activationAttributes.Length > 1 || !(activationAttributes[0] is UrlAttribute)) - throw new NotSupportedException(Environment.GetResourceString("NotSupported_NonUrlAttrOnMBR")); - } - } - else - throw new NotSupportedException(Environment.GetResourceString("NotSupported_ActivAttrOnNonMBR" )); -#else - throw new PlatformNotSupportedException(Environment.GetResourceString("NotSupported_ActivAttr" )); -#endif + throw new PlatformNotSupportedException(Environment.GetResourceString("NotSupported_ActivAttr" )); } RuntimeType rt = type.UnderlyingSystemType as RuntimeType; @@ -294,13 +275,6 @@ namespace System { Evidence securityInfo, ref StackCrawlMark stackMark) { -#if FEATURE_CAS_POLICY - if (securityInfo != null && !AppDomain.CurrentDomain.IsLegacyCasPolicyEnabled) - { - throw new NotSupportedException(Environment.GetResourceString("NotSupported_RequiresCasPolicyImplicit")); - } -#endif // FEATURE_CAS_POLICY - Type type = null; Assembly assembly = null; if (assemblyString == null) { @@ -358,13 +332,6 @@ namespace System { Evidence securityInfo) { -#if FEATURE_CAS_POLICY - if (securityInfo != null && !AppDomain.CurrentDomain.IsLegacyCasPolicyEnabled) - { - throw new NotSupportedException(Environment.GetResourceString("NotSupported_RequiresCasPolicyImplicit")); - } -#endif // FEATURE_CAS_POLICY - return CreateInstanceFromInternal(assemblyFile, typeName, ignoreCase, @@ -406,10 +373,6 @@ namespace System { Object[] activationAttributes, Evidence securityInfo) { -#if FEATURE_CAS_POLICY - Contract.Assert(AppDomain.CurrentDomain.IsLegacyCasPolicyEnabled || securityInfo == null); -#endif // FEATURE_CAS_POLICY - #pragma warning disable 618 Assembly assembly = Assembly.LoadFrom(assemblyFile, securityInfo); #pragma warning restore 618 @@ -462,13 +425,6 @@ namespace System { throw new ArgumentNullException(nameof(domain)); Contract.EndContractBlock(); -#if FEATURE_CAS_POLICY - if (securityAttributes != null && !AppDomain.CurrentDomain.IsLegacyCasPolicyEnabled) - { - throw new NotSupportedException(Environment.GetResourceString("NotSupported_RequiresCasPolicyImplicit")); - } -#endif // FEATURE_CAS_POLICY - return domain.InternalCreateInstanceWithNoSecurity(assemblyName, typeName, ignoreCase, bindingAttr, binder, args, culture, activationAttributes, securityAttributes); } @@ -529,13 +485,6 @@ namespace System { throw new ArgumentNullException(nameof(domain)); Contract.EndContractBlock(); -#if FEATURE_CAS_POLICY - if (securityAttributes != null && !AppDomain.CurrentDomain.IsLegacyCasPolicyEnabled) - { - throw new NotSupportedException(Environment.GetResourceString("NotSupported_RequiresCasPolicyImplicit")); - } -#endif // FEATURE_CAS_POLICY - return domain.InternalCreateInstanceFromWithNoSecurity(assemblyFile, typeName, ignoreCase, bindingAttr, binder, args, culture, activationAttributes, securityAttributes); } @@ -612,38 +561,11 @@ namespace System { } } -#if FEATURE_REMOTING - // This method is a helper method and delegates to the remoting - // services to do the actual work. - [System.Security.SecurityCritical] // auto-generated_required - static public Object GetObject(Type type, String url) - { - return GetObject(type, url, null); - } - - // This method is a helper method and delegates to the remoting - // services to do the actual work. - [System.Security.SecurityCritical] // auto-generated_required - static public Object GetObject(Type type, String url, Object state) - { - if (type == null) - throw new ArgumentNullException(nameof(type)); - Contract.EndContractBlock(); - return RemotingServices.Connect(type, url, state); - } -#endif - [System.Diagnostics.Conditional("_DEBUG")] private static void Log(bool test, string title, string success, string failure) { -#if FEATURE_REMOTING - if(test) - BCLDebug.Trace("REMOTE", "{0}{1}", title, success); - else - BCLDebug.Trace("REMOTE", "{0}{1}", title, failure); -#endif } - + void _Activator.GetTypeInfoCount(out uint pcTInfo) { throw new NotImplementedException(); diff --git a/src/coreclr/src/mscorlib/src/System/Array.cs b/src/coreclr/src/mscorlib/src/System/Array.cs index 1e899762..106cea9 100644 --- a/src/coreclr/src/mscorlib/src/System/Array.cs +++ b/src/coreclr/src/mscorlib/src/System/Array.cs @@ -219,41 +219,30 @@ namespace System { fixed(int* pLowerBounds = lowerBounds) return InternalCreate((void*)t.TypeHandle.Value,lengths.Length,pLengths,pLowerBounds); } + [System.Security.SecurityCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.InternalCall)] private unsafe static extern Array InternalCreate(void* elementType,int rank,int *pLengths,int *pLowerBounds); [SecurityCritical] -#if !FEATURE_CORECLR - [PermissionSet(SecurityAction.Assert, Unrestricted = true)] -#endif internal static Array UnsafeCreateInstance(Type elementType, int length) { return CreateInstance(elementType, length); } [SecurityCritical] -#if !FEATURE_CORECLR - [PermissionSet(SecurityAction.Assert, Unrestricted = true)] -#endif internal static Array UnsafeCreateInstance(Type elementType, int length1, int length2) { return CreateInstance(elementType, length1, length2); } [SecurityCritical] -#if !FEATURE_CORECLR - [PermissionSet(SecurityAction.Assert, Unrestricted = true)] -#endif internal static Array UnsafeCreateInstance(Type elementType, params int[] lengths) { return CreateInstance(elementType, lengths); } [SecurityCritical] -#if !FEATURE_CORECLR - [PermissionSet(SecurityAction.Assert, Unrestricted = true)] -#endif internal static Array UnsafeCreateInstance(Type elementType, int[] lengths, int[] lowerBounds) { return CreateInstance(elementType, lengths, lowerBounds); diff --git a/src/coreclr/src/mscorlib/src/System/Attribute.cs b/src/coreclr/src/mscorlib/src/System/Attribute.cs index 66aa48c..b932280 100644 --- a/src/coreclr/src/mscorlib/src/System/Attribute.cs +++ b/src/coreclr/src/mscorlib/src/System/Attribute.cs @@ -958,27 +958,5 @@ namespace System { #region Public Members public virtual bool IsDefaultAttribute() { return false; } #endregion - -#if !FEATURE_CORECLR - void _Attribute.GetTypeInfoCount(out uint pcTInfo) - { - throw new NotImplementedException(); - } - - void _Attribute.GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo) - { - throw new NotImplementedException(); - } - - void _Attribute.GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId) - { - throw new NotImplementedException(); - } - - void _Attribute.Invoke(uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr) - { - throw new NotImplementedException(); - } -#endif } } diff --git a/src/coreclr/src/mscorlib/src/System/BCLDebug.cs b/src/coreclr/src/mscorlib/src/System/BCLDebug.cs index f5ad6aa..91f845f 100644 --- a/src/coreclr/src/mscorlib/src/System/BCLDebug.cs +++ b/src/coreclr/src/mscorlib/src/System/BCLDebug.cs @@ -338,31 +338,6 @@ namespace System { System.Diagnostics.Log.LogMessage(LoggingLevels.TraceLevel0, logSwitch, trace.ToString()); } -#if !FEATURE_CORECLR - // For logging errors related to the console - we often can't expect to - // write to stdout if it doesn't exist. - [SecuritySafeCritical] - [Conditional("_DEBUG")] - internal static void ConsoleError(String msg) - { - if (AppDomain.CurrentDomain.IsUnloadingForcedFinalize()) - return; - - if (m_MakeConsoleErrorLoggingWork == null) { - PermissionSet perms = new PermissionSet(); - perms.AddPermission(new EnvironmentPermission(PermissionState.Unrestricted)); - perms.AddPermission(new FileIOPermission(FileIOPermissionAccess.AllAccess, Path.GetFullPath("."))); - m_MakeConsoleErrorLoggingWork = perms; - } - m_MakeConsoleErrorLoggingWork.Assert(); - - using (TextWriter err = File.AppendText("ConsoleErrors.log")) - { - err.WriteLine(msg); - } - } -#endif // !FEATURE_CORECLR - // For perf-related asserts. On a debug build, set the registry key // BCLPerfWarnings to non-zero. [Conditional("_DEBUG")] diff --git a/src/coreclr/src/mscorlib/src/System/Collections/Concurrent/ConcurrentDictionary.cs b/src/coreclr/src/mscorlib/src/System/Collections/Concurrent/ConcurrentDictionary.cs index c704ea3..0eb2546 100644 --- a/src/coreclr/src/mscorlib/src/System/Collections/Concurrent/ConcurrentDictionary.cs +++ b/src/coreclr/src/mscorlib/src/System/Collections/Concurrent/ConcurrentDictionary.cs @@ -28,7 +28,6 @@ using System.Security.Permissions; namespace System.Collections.Concurrent { - /// /// Represents a thread-safe collection of keys and values. /// @@ -38,9 +37,6 @@ namespace System.Collections.Concurrent /// All public and protected members of are thread-safe and may be used /// concurrently from multiple threads. /// -#if !FEATURE_CORECLR - [Serializable] -#endif [ComVisible(false)] [DebuggerTypeProxy(typeof(Mscorlib_DictionaryDebugView<,>))] [DebuggerDisplay("Count = {Count}")] @@ -68,41 +64,20 @@ namespace System.Collections.Concurrent m_comparer = comparer; } } -#if !FEATURE_CORECLR - [NonSerialized] -#endif + private volatile Tables m_tables; // Internal tables of the dictionary // NOTE: this is only used for compat reasons to serialize the comparer. // This should not be accessed from anywhere else outside of the serialization methods. internal IEqualityComparer m_comparer; -#if !FEATURE_CORECLR - [NonSerialized] -#endif private readonly bool m_growLockArray; // Whether to dynamically increase the size of the striped lock // How many times we resized becaused of collisions. // This is used to make sure we don't resize the dictionary because of multi-threaded Add() calls // that generate collisions. Whenever a GrowTable() should be the only place that changes this -#if !FEATURE_CORECLR - // The field should be have been marked as NonSerialized but because we shipped it without that attribute in 4.5.1. - // we can't add it back without breaking compat. To maximize compat we are going to keep the OptionalField attribute - // This will prevent cases where the field was not serialized. - [OptionalField] -#endif private int m_keyRehashCount; -#if !FEATURE_CORECLR - [NonSerialized] -#endif private int m_budget; // The maximum number of elements per lock before a resize operation is triggered -#if !FEATURE_CORECLR // These fields are not used in CoreCLR - private KeyValuePair[] m_serializationArray; // Used for custom serialization - - private int m_serializationConcurrencyLevel; // used to save the concurrency level in serialization - - private int m_serializationCapacity; // used to save the capacity in serialization -#endif // The default concurrency level is DEFAULT_CONCURRENCY_MULTIPLIER * #CPUs. The higher the // DEFAULT_CONCURRENCY_MULTIPLIER, the more concurrent writes can take place without interference // and blocking, but also the more expensive operations that require all locks become (e.g. table @@ -803,11 +778,6 @@ namespace System.Collections.Concurrent bool resizeDesired = false; bool lockTaken = false; -#if FEATURE_RANDOMIZED_STRING_HASHING -#if !FEATURE_CORECLR - bool resizeDueToCollisions = false; -#endif // !FEATURE_CORECLR -#endif try { @@ -821,12 +791,6 @@ namespace System.Collections.Concurrent continue; } -#if FEATURE_RANDOMIZED_STRING_HASHING -#if !FEATURE_CORECLR - int collisionCount = 0; -#endif // !FEATURE_CORECLR -#endif - // Try to find this key in the bucket Node prev = null; for (Node node = tables.m_buckets[bucketNo]; node != null; node = node.m_next) @@ -864,24 +828,8 @@ namespace System.Collections.Concurrent return false; } prev = node; - -#if FEATURE_RANDOMIZED_STRING_HASHING -#if !FEATURE_CORECLR - collisionCount++; -#endif // !FEATURE_CORECLR -#endif } -#if FEATURE_RANDOMIZED_STRING_HASHING -#if !FEATURE_CORECLR - if(collisionCount > HashHelpers.HashCollisionThreshold && HashHelpers.IsWellKnownEqualityComparer(comparer)) - { - resizeDesired = true; - resizeDueToCollisions = true; - } -#endif // !FEATURE_CORECLR -#endif - // The key was not found in the bucket. Insert the key-value pair. Volatile.Write(ref tables.m_buckets[bucketNo], new Node(key, value, hashcode, tables.m_buckets[bucketNo])); checked @@ -916,16 +864,7 @@ namespace System.Collections.Concurrent if (resizeDesired) { #if FEATURE_RANDOMIZED_STRING_HASHING -#if !FEATURE_CORECLR - if (resizeDueToCollisions) - { - GrowTable(tables, (IEqualityComparer)HashHelpers.GetRandomizedEqualityComparer(comparer), true, m_keyRehashCount); - } - else -#endif // !FEATURE_CORECLR - { - GrowTable(tables, tables.m_comparer, false, m_keyRehashCount); - } + GrowTable(tables, tables.m_comparer, false, m_keyRehashCount); #else GrowTable(tables, tables.m_comparer, false, m_keyRehashCount); #endif @@ -1850,13 +1789,6 @@ namespace System.Collections.Concurrent /// private void AcquireAllLocks(ref int locksAcquired) { -#if !FEATURE_CORECLR - if (CDSCollectionETWBCLProvider.Log.IsEnabled()) - { - CDSCollectionETWBCLProvider.Log.ConcurrentDictionary_AcquiringAllLocks(m_tables.m_buckets.Length); - } -#endif //!FEATURE_CORECLR - // First, acquire lock 0 AcquireLocks(0, 1, ref locksAcquired); @@ -2038,46 +1970,5 @@ namespace System.Collections.Concurrent m_enumerator.Reset(); } } - -#if !FEATURE_CORECLR - /// - /// Get the data array to be serialized - /// - [OnSerializing] - private void OnSerializing(StreamingContext context) - { - Tables tables = m_tables; - - // save the data into the serialization array to be saved - m_serializationArray = ToArray(); - m_serializationConcurrencyLevel = tables.m_locks.Length; - m_serializationCapacity = tables.m_buckets.Length; - m_comparer = (IEqualityComparer)HashHelpers.GetEqualityComparerForSerialization(tables.m_comparer); - } - - /// - /// Construct the dictionary from a previously serialized one - /// - [OnDeserialized] - private void OnDeserialized(StreamingContext context) - { - KeyValuePair[] array = m_serializationArray; - - var buckets = new Node[m_serializationCapacity]; - var countPerLock = new int[m_serializationConcurrencyLevel]; - - var locks = new object[m_serializationConcurrencyLevel]; - for (int i = 0; i < locks.Length; i++) - { - locks[i] = new object(); - } - - m_tables = new Tables(buckets, locks, countPerLock, m_comparer); - - InitializeFromCollection(array); - m_serializationArray = null; - - } -#endif } } diff --git a/src/coreclr/src/mscorlib/src/System/Collections/Concurrent/ConcurrentStack.cs b/src/coreclr/src/mscorlib/src/System/Collections/Concurrent/ConcurrentStack.cs index c418aa0..c97e0f6 100644 --- a/src/coreclr/src/mscorlib/src/System/Collections/Concurrent/ConcurrentStack.cs +++ b/src/coreclr/src/mscorlib/src/System/Collections/Concurrent/ConcurrentStack.cs @@ -46,9 +46,6 @@ namespace System.Collections.Concurrent [DebuggerDisplay("Count = {Count}")] [DebuggerTypeProxy(typeof(SystemCollectionsConcurrent_ProducerConsumerCollectionDebugView<>))] [HostProtection(Synchronization = true, ExternalThreading = true)] -#if !FEATURE_CORECLR - [Serializable] -#endif //!FEATURE_CORECLR public class ConcurrentStack : IProducerConsumerCollection, IReadOnlyCollection { /// @@ -70,15 +67,8 @@ namespace System.Collections.Concurrent } } -#if !FEATURE_CORECLR - [NonSerialized] -#endif //!FEATURE_CORECLR private volatile Node m_head; // The stack is a singly linked list, and only remembers the head. -#if !FEATURE_CORECLR - private T[] m_serializationArray; // Used for custom serialization. -#endif //!FEATURE_CORECLR - private const int BACKOFF_MAX_YIELDS = 8; // Arbitrary number to cap backoff. /// @@ -124,50 +114,6 @@ namespace System.Collections.Concurrent m_head = lastNode; } -#if !FEATURE_CORECLR - /// - /// Get the data array to be serialized - /// - [OnSerializing] - private void OnSerializing(StreamingContext context) - { - // save the data into the serialization array to be saved - m_serializationArray = ToArray(); - } - - /// - /// Construct the stack from a previously seiralized one - /// - [OnDeserialized] - private void OnDeserialized(StreamingContext context) - { - Contract.Assert(m_serializationArray != null); - // Add the elements to our stack. We need to add them from head-to-tail, to - // preserve the original ordering of the stack before serialization. - Node prevNode = null; - Node head = null; - for (int i = 0; i < m_serializationArray.Length; i++) - { - Node currNode = new Node(m_serializationArray[i]); - - if (prevNode == null) - { - head = currNode; - } - else - { - prevNode.m_next = currNode; - } - - prevNode = currNode; - } - - m_head = head; - m_serializationArray = null; - } -#endif //!FEATURE_CORECLR - - /// /// Gets a value that indicates whether the is empty. /// @@ -221,7 +167,6 @@ namespace System.Collections.Concurrent } } - /// /// Gets a value indicating whether access to the is /// synchronized with the SyncRoot. @@ -455,13 +400,6 @@ namespace System.Collections.Concurrent } while (Interlocked.CompareExchange( ref m_head, head, tail.m_next) != tail.m_next); - -#if !FEATURE_CORECLR - if (CDSCollectionETWBCLProvider.Log.IsEnabled()) - { - CDSCollectionETWBCLProvider.Log.ConcurrentStack_FastPushFailed(spin.Count); - } -#endif // !FEATURE_CORECLR } /// @@ -683,12 +621,6 @@ namespace System.Collections.Concurrent // Is the stack empty? if (head == null) { -#if !FEATURE_CORECLR - if (count == 1 && CDSCollectionETWBCLProvider.Log.IsEnabled()) - { - CDSCollectionETWBCLProvider.Log.ConcurrentStack_FastPopFailed(spin.Count); - } -#endif //!FEATURE_CORECLR poppedHead = null; return 0; } @@ -702,12 +634,6 @@ namespace System.Collections.Concurrent // Try to swap the new head. If we succeed, break out of the loop. if (Interlocked.CompareExchange(ref m_head, next.m_next, head) == head) { -#if !FEATURE_CORECLR - if (count == 1 && CDSCollectionETWBCLProvider.Log.IsEnabled()) - { - CDSCollectionETWBCLProvider.Log.ConcurrentStack_FastPopFailed(spin.Count); - } -#endif //!FEATURE_CORECLR // Return the popped Node. poppedHead = head; return nodesCount; diff --git a/src/coreclr/src/mscorlib/src/System/Collections/Concurrent/PartitionerStatic.cs b/src/coreclr/src/mscorlib/src/System/Collections/Concurrent/PartitionerStatic.cs index 5568f9b..5a7f8f4 100644 --- a/src/coreclr/src/mscorlib/src/System/Collections/Concurrent/PartitionerStatic.cs +++ b/src/coreclr/src/mscorlib/src/System/Collections/Concurrent/PartitionerStatic.cs @@ -26,9 +26,6 @@ namespace System.Collections.Concurrent /// non-blocking. These behaviors can be overridden via this enumeration. /// [Flags] -#if !FEATURE_CORECLR - [Serializable] -#endif public enum EnumerablePartitionerOptions { /// @@ -1704,21 +1701,7 @@ namespace System.Collections.Concurrent if (typeof(TSource).IsValueType) { -#if !FEATURE_CORECLR // Marshal.SizeOf is not supported in CoreCLR - - if (typeof(TSource).StructLayoutAttribute.Value == LayoutKind.Explicit) - { - chunkSize = Math.Max(1, DEFAULT_BYTES_PER_CHUNK / Marshal.SizeOf(typeof(TSource))); - } - else - { - // We choose '128' because this ensures, no matter the actual size of the value type, - // the total bytes used will be a multiple of 128. This ensures it's cache aligned. - chunkSize = 128; - } -#else chunkSize = 128; -#endif } else { @@ -1728,6 +1711,5 @@ namespace System.Collections.Concurrent return chunkSize; } #endregion - } } diff --git a/src/coreclr/src/mscorlib/src/System/Collections/Hashtable.cs b/src/coreclr/src/mscorlib/src/System/Collections/Hashtable.cs index 8d74c8f..930e1be 100644 --- a/src/coreclr/src/mscorlib/src/System/Collections/Hashtable.cs +++ b/src/coreclr/src/mscorlib/src/System/Collections/Hashtable.cs @@ -23,10 +23,7 @@ namespace System.Collections { using System.Runtime.CompilerServices; using System.Runtime.ConstrainedExecution; using System.Diagnostics.Contracts; -#if !FEATURE_CORECLR - using System.Security.Cryptography; -#endif - + // The Hashtable class represents a dictionary of associated keys and values // with constant lookup time. // @@ -449,9 +446,6 @@ namespace System.Collections { if (count == 0 && occupancy == 0) return; -#if !FEATURE_CORECLR - Thread.BeginCriticalRegion(); -#endif isWriterInProgress = true; for (int i = 0; i < buckets.Length; i++){ buckets[i].hash_coll = 0; @@ -463,9 +457,6 @@ namespace System.Collections { occupancy = 0; UpdateVersion(); isWriterInProgress = false; -#if !FEATURE_CORECLR - Thread.EndCriticalRegion(); -#endif } // Clone returns a virtually identical copy of this hash table. This does @@ -526,9 +517,7 @@ namespace System.Collections { } while (b.hash_coll < 0 && ++ntry < lbuckets.Length); return false; } - - - + // Checks if this hashtable contains an entry with the given value. The // values of the entries of the hashtable are compared to the given value // using the Object.Equals method. This method performs a linear @@ -750,28 +739,23 @@ namespace System.Collections { for (nb = 0; nb < buckets.Length; nb++){ bucket oldb = buckets[nb]; if ((oldb.key != null) && (oldb.key != buckets)) { - int hashcode = ((forceNewHashCode ? GetHash(oldb.key) : oldb.hash_coll) & 0x7FFFFFFF); + int hashcode = ((forceNewHashCode ? GetHash(oldb.key) : oldb.hash_coll) & 0x7FFFFFFF); putEntry(newBuckets, oldb.key, oldb.val, hashcode); } } - + // New bucket[] is good to go - replace buckets and other internal state. -#if !FEATURE_CORECLR - Thread.BeginCriticalRegion(); -#endif isWriterInProgress = true; buckets = newBuckets; loadsize = (int)(loadFactor * newsize); UpdateVersion(); isWriterInProgress = false; -#if !FEATURE_CORECLR - Thread.EndCriticalRegion(); -#endif + // minimun size of hashtable is 3 now and maximum loadFactor is 0.72 now. Contract.Assert(loadsize < newsize, "Our current implementaion means this is not possible."); return; } - + // Returns an enumerator for this hashtable. // If modifications made to the hashtable while an enumeration is // in progress, the MoveNext and Current methods of the @@ -913,36 +897,14 @@ namespace System.Collections { // We pretty much have to insert in this order. Don't set hash // code until the value & key are set appropriately. -#if !FEATURE_CORECLR - Thread.BeginCriticalRegion(); -#endif - isWriterInProgress = true; + isWriterInProgress = true; buckets[bucketNumber].val = nvalue; buckets[bucketNumber].key = key; buckets[bucketNumber].hash_coll |= (int) hashcode; count++; UpdateVersion(); isWriterInProgress = false; -#if !FEATURE_CORECLR - Thread.EndCriticalRegion(); -#endif -#if FEATURE_RANDOMIZED_STRING_HASHING -#if !FEATURE_CORECLR - // coreclr has the randomized string hashing on by default so we don't need to resize at this point - - if(ntry > HashHelpers.HashCollisionThreshold && HashHelpers.IsWellKnownEqualityComparer(_keycomparer)) - { - // PERF: We don't want to rehash if _keycomparer is already a RandomizedObjectEqualityComparer since in some - // cases there may not be any strings in the hashtable and we wouldn't get any mixing. - if(_keycomparer == null || !(_keycomparer is System.Collections.Generic.RandomizedObjectEqualityComparer)) - { - _keycomparer = HashHelpers.GetRandomizedEqualityComparer(_keycomparer); - rehash(buckets.Length, true); - } - } -#endif // !FEATURE_CORECLR -#endif // FEATURE_RANDOMIZED_STRING_HASHING return; } @@ -954,31 +916,10 @@ namespace System.Collections { if (add) { throw new ArgumentException(Environment.GetResourceString("Argument_AddingDuplicate__", buckets[bucketNumber].key, key)); } -#if !FEATURE_CORECLR - Thread.BeginCriticalRegion(); -#endif - isWriterInProgress = true; + isWriterInProgress = true; buckets[bucketNumber].val = nvalue; - UpdateVersion(); + UpdateVersion(); isWriterInProgress = false; -#if !FEATURE_CORECLR - Thread.EndCriticalRegion(); -#endif - -#if FEATURE_RANDOMIZED_STRING_HASHING -#if !FEATURE_CORECLR - if(ntry > HashHelpers.HashCollisionThreshold && HashHelpers.IsWellKnownEqualityComparer(_keycomparer)) - { - // PERF: We don't want to rehash if _keycomparer is already a RandomizedObjectEqualityComparer since in some - // cases there may not be any strings in the hashtable and we wouldn't get any mixing. - if(_keycomparer == null || !(_keycomparer is System.Collections.Generic.RandomizedObjectEqualityComparer)) - { - _keycomparer = HashHelpers.GetRandomizedEqualityComparer(_keycomparer); - rehash(buckets.Length, true); - } - } -#endif // !FEATURE_CORECLR -#endif return; } @@ -992,7 +933,7 @@ namespace System.Collections { } } - bucketNumber = (int) (((long)bucketNumber + incr)% (uint)buckets.Length); + bucketNumber = (int) (((long)bucketNumber + incr)% (uint)buckets.Length); } while (++ntry < buckets.Length); // This code is here if and only if there were no buckets without a collision bit set in the entire table @@ -1000,37 +941,17 @@ namespace System.Collections { { // We pretty much have to insert in this order. Don't set hash // code until the value & key are set appropriately. -#if !FEATURE_CORECLR - Thread.BeginCriticalRegion(); -#endif - isWriterInProgress = true; + isWriterInProgress = true; buckets[emptySlotNumber].val = nvalue; buckets[emptySlotNumber].key = key; buckets[emptySlotNumber].hash_coll |= (int) hashcode; count++; UpdateVersion(); isWriterInProgress = false; -#if !FEATURE_CORECLR - Thread.EndCriticalRegion(); -#endif -#if FEATURE_RANDOMIZED_STRING_HASHING -#if !FEATURE_CORECLR - if(buckets.Length > HashHelpers.HashCollisionThreshold && HashHelpers.IsWellKnownEqualityComparer(_keycomparer)) - { - // PERF: We don't want to rehash if _keycomparer is already a RandomizedObjectEqualityComparer since in some - // cases there may not be any strings in the hashtable and we wouldn't get any mixing. - if(_keycomparer == null || !(_keycomparer is System.Collections.Generic.RandomizedObjectEqualityComparer)) - { - _keycomparer = HashHelpers.GetRandomizedEqualityComparer(_keycomparer); - rehash(buckets.Length, true); - } - } -#endif // !FEATURE_CORECLR -#endif return; } - + // If you see this assert, make sure load factor & count are reasonable. // Then verify that our double hash function (h2, described at top of file) // meets the requirements described above. You should never see this assert. @@ -1058,7 +979,7 @@ namespace System.Collections { newBuckets[bucketNumber].hash_coll |= unchecked((int)0x80000000); occupancy++; } - bucketNumber = (int) (((long)bucketNumber + incr)% (uint)newBuckets.Length); + bucketNumber = (int) (((long)bucketNumber + incr)% (uint)newBuckets.Length); } while (true); } @@ -1086,9 +1007,6 @@ namespace System.Collections { b = buckets[bn]; if (((b.hash_coll & 0x7FFFFFFF) == hashcode) && KeyEquals (b.key, key)) { -#if !FEATURE_CORECLR - Thread.BeginCriticalRegion(); -#endif isWriterInProgress = true; // Clear hash_coll field, then key, then value buckets[bn].hash_coll &= unchecked((int)0x80000000); @@ -1102,12 +1020,9 @@ namespace System.Collections { count--; UpdateVersion(); isWriterInProgress = false; -#if !FEATURE_CORECLR - Thread.EndCriticalRegion(); -#endif return; } - bn = (int) (((long)bn + incr)% (uint)buckets.Length); + bn = (int) (((long)bn + incr)% (uint)buckets.Length); } while (b.hash_coll < 0 && ++ntry < buckets.Length); //throw new ArgumentException(Environment.GetResourceString("Arg_RemoveArgNotFound")); @@ -1804,9 +1719,6 @@ namespace System.Collections { } private const int bufferSize = 1024; -#if !FEATURE_CORECLR - private static RandomNumberGenerator rng; -#endif private static byte[] data; private static int currentIndex = bufferSize; private static readonly object lockObj = new Object(); @@ -1822,17 +1734,9 @@ namespace System.Collections { { data = new byte[bufferSize]; Contract.Assert(bufferSize % 8 == 0, "We increment our current index by 8, so our buffer size must be a multiple of 8"); -#if !FEATURE_CORECLR - rng = RandomNumberGenerator.Create(); -#endif - } -#if FEATURE_CORECLR Microsoft.Win32.Win32Native.Random(true, data, data.Length); -#else - rng.GetBytes(data); -#endif currentIndex = 0; } diff --git a/src/coreclr/src/mscorlib/src/System/CompatibilitySwitches.cs b/src/coreclr/src/mscorlib/src/System/CompatibilitySwitches.cs index 893a47e..bb2f02a 100644 --- a/src/coreclr/src/mscorlib/src/System/CompatibilitySwitches.cs +++ b/src/coreclr/src/mscorlib/src/System/CompatibilitySwitches.cs @@ -2,8 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. - -using System.Runtime; using System.Runtime.CompilerServices; namespace System @@ -12,16 +10,7 @@ namespace System internal static class CompatibilitySwitches { private static bool s_AreSwitchesSet; - -#if FEATURE_CORECLR private static bool s_useLatestBehaviorWhenTFMNotSpecified; // Which behavior to use when the TFM is not specified. -#endif //FEATURE_CORECLR - -#if !FEATURE_CORECLR - private static bool s_isNetFx40TimeSpanLegacyFormatMode; - private static bool s_isNetFx40LegacySecurityPolicy; - private static bool s_isNetFx45LegacyManagedDeflateStream; -#endif //!FEATURE_CORECLR public static bool IsCompatibilityBehaviorDefined { @@ -39,51 +28,14 @@ namespace System internal static void InitializeSwitches() { -#if !FEATURE_CORECLR - s_isNetFx40TimeSpanLegacyFormatMode = IsCompatibilitySwitchSet("NetFx40_TimeSpanLegacyFormatMode"); - s_isNetFx40LegacySecurityPolicy = IsCompatibilitySwitchSet("NetFx40_LegacySecurityPolicy"); - s_isNetFx45LegacyManagedDeflateStream = IsCompatibilitySwitchSet("NetFx45_LegacyManagedDeflateStream"); -#endif //FEATURE_CORECLR - s_AreSwitchesSet = true; } -#if !FEATURE_CORECLR - public static bool IsAppEarlierThanSilverlight4 - { - get - { - return false; - } - } - - public static bool IsAppEarlierThanWindowsPhone8 - { - get - { - return false; - } - } - - public static bool IsAppEarlierThanWindowsPhoneMango - { - get - { - return false; - } - } - -#endif //!FEATURE_CORECLR - public static bool IsNetFx40TimeSpanLegacyFormatMode { get { -#if !FEATURE_CORECLR - return s_isNetFx40TimeSpanLegacyFormatMode; -#else return false; -#endif //!FEATURE_CORECLR } } @@ -91,11 +43,7 @@ namespace System { get { -#if !FEATURE_CORECLR - return s_isNetFx40LegacySecurityPolicy; -#else return false; -#endif //!FEATURE_CORECLR } } @@ -103,11 +51,7 @@ namespace System { get { -#if !FEATURE_CORECLR - return s_isNetFx45LegacyManagedDeflateStream; -#else return false; -#endif //!FEATURE_CORECLR } } } diff --git a/src/coreclr/src/mscorlib/src/System/DelegateSerializationHolder.cs b/src/coreclr/src/mscorlib/src/System/DelegateSerializationHolder.cs index 9313dfd..39a95e9 100644 --- a/src/coreclr/src/mscorlib/src/System/DelegateSerializationHolder.cs +++ b/src/coreclr/src/mscorlib/src/System/DelegateSerializationHolder.cs @@ -218,27 +218,19 @@ namespace System // If we received the new style delegate encoding we already have the target MethodInfo in hand. if (m_methods != null) { -#if FEATURE_REMOTING - Object target = de.target != null ? RemotingServices.CheckCast(de.target, targetType) : null; -#else if(de.target != null && !targetType.IsInstanceOfType(de.target)) throw new InvalidCastException(); Object target=de.target; -#endif d = Delegate.CreateDelegateNoSecurityCheck(type, target, m_methods[index]); } else { if (de.target != null) -#if FEATURE_REMOTING - d = Delegate.CreateDelegate(type, RemotingServices.CheckCast(de.target, targetType), de.methodName); -#else - { - if(!targetType.IsInstanceOfType(de.target)) - throw new InvalidCastException(); - d = Delegate.CreateDelegate(type, de.target, de.methodName); - } -#endif + { + if(!targetType.IsInstanceOfType(de.target)) + throw new InvalidCastException(); + d = Delegate.CreateDelegate(type, de.target, de.methodName); + } else d = Delegate.CreateDelegate(type, targetType, de.methodName); } diff --git a/src/coreclr/src/mscorlib/src/System/Diagnostics/Contracts/ContractsBCL.cs b/src/coreclr/src/mscorlib/src/System/Diagnostics/Contracts/ContractsBCL.cs index 8434447..75a85fe 100644 --- a/src/coreclr/src/mscorlib/src/System/Diagnostics/Contracts/ContractsBCL.cs +++ b/src/coreclr/src/mscorlib/src/System/Diagnostics/Contracts/ContractsBCL.cs @@ -361,10 +361,6 @@ namespace System.Runtime.CompilerServices } if (eventArgs.Unwind) { -#if !FEATURE_CORECLR - if (Environment.IsCLRHosted) - TriggerCodeContractEscalationPolicy(failureKind, displayMessage, conditionText, innerException); -#endif // unwind if (innerException == null) { innerException = eventArgs.thrownDuringHandler; } throw new ContractException(failureKind, displayMessage, userMessage, conditionText, innerException); @@ -393,9 +389,6 @@ namespace System.Runtime.CompilerServices [SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "kind")] [SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "innerException")] [System.Diagnostics.DebuggerNonUserCode] -#if FEATURE_UNTRUSTED_CALLERS && !FEATURE_CORECLR - [SecuritySafeCritical] -#endif static partial void TriggerFailureImplementation(ContractFailureKind kind, String displayMessage, String userMessage, String conditionText, Exception innerException) { // If we're here, our intent is to pop up a dialog box (if we can). For developers @@ -403,21 +396,12 @@ namespace System.Runtime.CompilerServices // hosted in Internet Explorer, the assert window is great. If we cannot // pop up a dialog box, throw an exception (consider a library compiled with // "Assert On Failure" but used in a process that can't pop up asserts, like an - // NT Service). For the CLR hosted by server apps like SQL or Exchange, we should - // trigger escalation policy. -#if !FEATURE_CORECLR - if (Environment.IsCLRHosted) - { - TriggerCodeContractEscalationPolicy(kind, displayMessage, conditionText, innerException); - // Hosts like SQL may choose to abort the thread, so we will not get here in all cases. - // But if the host's chosen action was to throw an exception, we should throw an exception - // here (which is easier to do in managed code with the right parameters). - throw new ContractException(kind, displayMessage, userMessage, conditionText, innerException); - } -#endif // !FEATURE_CORECLR + // NT Service). + if (!Environment.UserInteractive) { throw new ContractException(kind, displayMessage, userMessage, conditionText, innerException); } + // May need to rethink Assert.Fail w/ TaskDialogIndirect as a model. Window title. Main instruction. Content. Expanded info. // Optional info like string for collapsed text vs. expanded text. String windowTitle = Environment.GetResourceString(GetResourceNameForFailure(kind)); @@ -494,28 +478,6 @@ namespace System.Runtime.CompilerServices return failureMessage; } } - -#if !FEATURE_CORECLR - // Will trigger escalation policy, if hosted and the host requested us to do something (such as - // abort the thread or exit the process). Starting in Dev11, for hosted apps the default behavior - // is to throw an exception. - // Implementation notes: - // We implement our default behavior of throwing an exception by simply returning from our native - // method inside the runtime and falling through to throw an exception. - // We must call through this method before calling the method on the Environment class - // because our security team does not yet support SecuritySafeCritical on P/Invoke methods. - // Note this can be called in the context of throwing another exception (EnsuresOnThrow). - [SecuritySafeCritical] - [DebuggerNonUserCode] - [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] - private static void TriggerCodeContractEscalationPolicy(ContractFailureKind failureKind, String message, String conditionText, Exception innerException) - { - String exceptionAsString = null; - if (innerException != null) - exceptionAsString = innerException.ToString(); - Environment.TriggerCodeContractFailure(failureKind, message, conditionText, exceptionAsString); - } -#endif // !FEATURE_CORECLR } } // namespace System.Runtime.CompilerServices diff --git a/src/coreclr/src/mscorlib/src/System/Diagnostics/Eventing/EventSource.cs b/src/coreclr/src/mscorlib/src/System/Diagnostics/Eventing/EventSource.cs index b089381..3bfcf52 100644 --- a/src/coreclr/src/mscorlib/src/System/Diagnostics/Eventing/EventSource.cs +++ b/src/coreclr/src/mscorlib/src/System/Diagnostics/Eventing/EventSource.cs @@ -6645,13 +6645,7 @@ namespace System.Diagnostics.Tracing private static List GetSupportedCultures(ResourceManager resources) { var cultures = new List(); -#if !ES_BUILD_PCL && !FEATURE_CORECLR && !PROJECTN - foreach (CultureInfo ci in CultureInfo.GetCultures(CultureTypes.SpecificCultures /*| CultureTypes.NeutralCultures*/)) - { - if (resources.GetResourceSet(ci, true, false) != null) - cultures.Add(ci); - } -#endif // !ES_BUILD_PCL && !FEATURE_CORECLR + if (!cultures.Contains(CultureInfo.CurrentUICulture)) cultures.Insert(0, CultureInfo.CurrentUICulture); return cultures; diff --git a/src/coreclr/src/mscorlib/src/System/Diagnostics/Stackframe.cs b/src/coreclr/src/mscorlib/src/System/Diagnostics/Stackframe.cs index 397c3e1..3992a82 100644 --- a/src/coreclr/src/mscorlib/src/System/Diagnostics/Stackframe.cs +++ b/src/coreclr/src/mscorlib/src/System/Diagnostics/Stackframe.cs @@ -11,13 +11,7 @@ namespace System.Diagnostics { using System.Security.Permissions; using System.Diagnostics.Contracts; - // There is no good reason for the methods of this class to be virtual. - // In order to ensure trusted code can trust the data it gets from a - // StackTrace, we use an InheritanceDemand to prevent partially-trusted - // subclasses. -#if !FEATURE_CORECLR - [SecurityPermission(SecurityAction.InheritanceDemand, UnmanagedCode=true)] -#endif + // There is no good reason for the methods of this class to be virtual. [Serializable] [System.Runtime.InteropServices.ComVisible(true)] public class StackFrame diff --git a/src/coreclr/src/mscorlib/src/System/Diagnostics/Stacktrace.cs b/src/coreclr/src/mscorlib/src/System/Diagnostics/Stacktrace.cs index 06f38c4..6c2140f 100644 --- a/src/coreclr/src/mscorlib/src/System/Diagnostics/Stacktrace.cs +++ b/src/coreclr/src/mscorlib/src/System/Diagnostics/Stacktrace.cs @@ -712,15 +712,6 @@ namespace System.Diagnostics { { fileName = sf.GetFileName(); } -#if FEATURE_CAS_POLICY - catch (NotSupportedException) - { - // Having a deprecated stack modifier on the callstack (such as Deny) will cause - // a NotSupportedException to be thrown. Since we don't know if the app can - // access the file names, we'll conservatively hide them. - displayFilenames = false; - } -#endif // FEATURE_CAS_POLICY catch (SecurityException) { // If the demand for displaying filenames fails, then it won't diff --git a/src/coreclr/src/mscorlib/src/System/Environment.cs b/src/coreclr/src/mscorlib/src/System/Environment.cs index 6799078..50be7d4 100644 --- a/src/coreclr/src/mscorlib/src/System/Environment.cs +++ b/src/coreclr/src/mscorlib/src/System/Environment.cs @@ -305,40 +305,6 @@ namespace System { [MethodImplAttribute(MethodImplOptions.InternalCall)] public static extern void FailFast(String message, Exception exception); -#if !FEATURE_CORECLR - [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] - [SecurityCritical] // Our security team doesn't yet allow safe-critical P/Invoke methods. - [SuppressUnmanagedCodeSecurity] - [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)] - internal static extern void TriggerCodeContractFailure(ContractFailureKind failureKind, String message, String condition, String exceptionAsString); - - [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] - [SecurityCritical] // Our security team doesn't yet allow safe-critical P/Invoke methods. - [SuppressUnmanagedCodeSecurity] - [return: MarshalAs(UnmanagedType.Bool)] - private static extern bool GetIsCLRHosted(); - - internal static bool IsCLRHosted { - [SecuritySafeCritical] - get { return GetIsCLRHosted(); } - } - - public static String CommandLine { - [System.Security.SecuritySafeCritical] // auto-generated - get { - new EnvironmentPermission(EnvironmentPermissionAccess.Read, "Path").Demand(); - - String commandLine = null; - GetCommandLine(JitHelpers.GetStringHandleOnStack(ref commandLine)); - return commandLine; - } - } - - [System.Security.SecurityCritical] // auto-generated - [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode), SuppressUnmanagedCodeSecurity] - private static extern void GetCommandLine(StringHandleOnStack retString); -#endif // !FEATURE_CORECLR - /*===============================CurrentDirectory=============================== **Action: Provides a getter and setter for the current directory. The original ** current directory is the one from which the process was started. @@ -373,11 +339,6 @@ namespace System { Contract.Assert(r < Path.MaxPath, "r < Path.MaxPath"); if (r==0) __Error.WinIOError(); String path = sb.ToString(); - -#if !FEATURE_CORECLR - // Do security check - new FileIOPermission(FileIOPermissionAccess.PathDiscovery, path).Demand(); -#endif return path; } @@ -441,63 +402,6 @@ namespace System { int size; -#if !FEATURE_CORECLR - bool isFullTrust = CodeAccessSecurityEngine.QuickCheckForAllDemands(); - - // Do a security check to guarantee we can read each of the - // individual environment variables requested here. - String[] varArray = name.Split(new char[] {'%'}); - StringBuilder vars = isFullTrust ? null : new StringBuilder(); - - bool fJustExpanded = false; // to accommodate expansion alg. - - for(int i=1; i currentSize) { - currentSize = size; - blob.Capacity = currentSize; - blob.Length = 0; - size = Win32Native.ExpandEnvironmentStrings(envVar, blob, currentSize); - if (size == 0) - Marshal.ThrowExceptionForHR(Marshal.GetHRForLastWin32Error()); - } - - if (!isFullTrust) { - String temp = blob.ToString(); - fJustExpanded = (temp != envVar); - if (fJustExpanded) { // We expanded successfully, we need to do String comparison here - // since %FOO% can become %FOOD - vars.Append(varArray[i]); - vars.Append(';'); - } - } - } - - if (!isFullTrust) - new EnvironmentPermission(EnvironmentPermissionAccess.Read, vars.ToString()).Demand(); -#endif // !FEATURE_CORECLR - blob.Length = 0; size = Win32Native.ExpandEnvironmentStrings(name, blob, currentSize); if (size == 0) @@ -530,9 +434,6 @@ namespace System { // In future release of operating systems, you might be able to rename a machine without // rebooting. Therefore, don't cache this machine name. -#if !FEATURE_CORECLR - new EnvironmentPermission(EnvironmentPermissionAccess.Read, "COMPUTERNAME").Demand(); -#endif StringBuilder buf = new StringBuilder(MaxMachineNameLength); int len = MaxMachineNameLength; if (Win32Native.GetComputerName(buf, ref len) == 0) @@ -574,7 +475,6 @@ namespace System { public static String[] GetCommandLineArgs() { new EnvironmentPermission(EnvironmentPermissionAccess.Read, "Path").Demand(); -#if FEATURE_CORECLR /* * There are multiple entry points to a hosted app. * The host could use ::ExecuteAssembly() or ::CreateDelegate option @@ -590,7 +490,7 @@ namespace System { */ if(s_CommandLineArgs != null) return (string[])s_CommandLineArgs.Clone(); -#endif + return GetCommandLineArgsNative(); } @@ -598,23 +498,11 @@ namespace System { [MethodImplAttribute(MethodImplOptions.InternalCall)] private static extern String[] GetCommandLineArgsNative(); -#if !FEATURE_CORECLR - // We need to keep this Fcall since it is used in AppDomain.cs. - // If we call GetEnvironmentVariable from AppDomain.cs, we will use StringBuilder class. - // That has side effect to change the ApartmentState of the calling Thread to MTA. - // So runtime can't change the ApartmentState of calling thread any more. - [System.Security.SecurityCritical] // auto-generated - [MethodImplAttribute(MethodImplOptions.InternalCall)] - internal static extern String nativeGetEnvironmentVariable(String variable); -#endif //!FEATURE_CORECLR - -#if FEATURE_CORECLR private static string[] s_CommandLineArgs = null; private static void SetCommandLineArgs(string[] cmdLineArgs) { s_CommandLineArgs = cmdLineArgs; } -#endif private unsafe static char[] GetEnvironmentCharArray() { @@ -873,9 +761,7 @@ namespace System { } } -#if FEATURE_CORECLR [System.Security.SecurityCritical] // auto-generated -#endif internal static String GetStackTrace(Exception e, bool needFileInfo) { // Note: Setting needFileInfo to true will start up COM and set our @@ -917,20 +803,12 @@ namespace System { } } -#if !FEATURE_CORECLR - [System.Security.SecurityCritical] // auto-generated - [MethodImplAttribute(MethodImplOptions.InternalCall)] - internal extern static String GetResourceFromDefault(String key); -#endif - // Looks up the resource string value for key. // // if you change this method's signature then you must change the code that calls it // in excep.cpp and probably you will have to visit mscorlib.h to add the new signature // as well as metasig.h to create the new signature type -#if FEATURE_CORECLR [System.Security.SecurityCritical] // auto-generated -#endif // NoInlining causes the caller and callee to not be inlined in mscorlib as it is an assumption of StackCrawlMark use [MethodImpl(MethodImplOptions.NoInlining)] internal static String GetResourceStringLocal(String key) { @@ -942,11 +820,7 @@ namespace System { [System.Security.SecuritySafeCritical] // auto-generated internal static String GetResourceString(String key) { -#if FEATURE_CORECLR return GetResourceStringLocal(key); -#else - return GetResourceFromDefault(key); -#endif //FEATURE_CORECLR } // The reason the following overloads exist are to reduce code bloat. @@ -1046,13 +920,6 @@ namespace System { get; } -#if !FEATURE_CORECLR - // This is the temporary Whidbey stub for compatibility flags - [MethodImplAttribute(MethodImplOptions.InternalCall)] - [System.Security.SecurityCritical] - internal static extern bool GetCompatibilityFlag(CompatibilityFlag flag); -#endif //!FEATURE_CORECLR - public static string UserName { [System.Security.SecuritySafeCritical] // auto-generated get { @@ -1068,36 +935,11 @@ namespace System { } } - // Note that this is a handle to a process window station, but it does - // not need to be closed. CloseWindowStation would ignore this handle. - // We also do handle equality checking as well. This isn't a great fit - // for SafeHandle. We don't gain anything by using SafeHandle here. -#if !FEATURE_CORECLR - private static volatile IntPtr processWinStation; // Doesn't need to be initialized as they're zero-init. - private static volatile bool isUserNonInteractive; -#endif - - public static bool UserInteractive { + public static bool UserInteractive + { [System.Security.SecuritySafeCritical] // auto-generated get { -#if !FEATURE_CORECLR - IntPtr hwinsta = Win32Native.GetProcessWindowStation(); - if (hwinsta != IntPtr.Zero && processWinStation != hwinsta) { - int lengthNeeded = 0; - Win32Native.USEROBJECTFLAGS flags = new Win32Native.USEROBJECTFLAGS(); - if (Win32Native.GetUserObjectInformation(hwinsta, Win32Native.UOI_FLAGS, flags, Marshal.SizeOf(flags),ref lengthNeeded)) { - if ((flags.dwFlags & Win32Native.WSF_VISIBLE) == 0) { - isUserNonInteractive = true; - } - } - processWinStation = hwinsta; - } - - // The logic is reversed to avoid static initialization to true - return !isUserNonInteractive; -#else return true; -#endif } } @@ -1148,13 +990,6 @@ namespace System { throw new PlatformNotSupportedException(); } #else // FEATURE_CORESYSTEM -#if !FEATURE_CORECLR - if (option == SpecialFolderOption.Create && !suppressSecurityChecks) { - FileIOPermission createPermission = new FileIOPermission(PermissionState.None); - createPermission.AllFiles = FileIOPermissionAccess.Write; - createPermission.Demand(); - } -#endif StringBuilder sb = new StringBuilder(Path.MaxPath); int hresult = Win32Native.SHGetFolderPath(IntPtr.Zero, /* hwndOwner: [in] Reserved */ @@ -1192,14 +1027,12 @@ namespace System { // On CoreCLR we can check with the host if we're not trying to use any special options. // Otherwise, we need to do a full demand since hosts aren't expecting to handle requests to // create special folders. -#if FEATURE_CORECLR if (option == SpecialFolderOption.None) { FileSecurityState state = new FileSecurityState(FileSecurityStateAccess.PathDiscovery, String.Empty, s); state.EnsureState(); } else -#endif // FEATURE_CORECLR { new FileIOPermission(FileIOPermissionAccess.PathDiscovery, s).Demand(); } @@ -1343,7 +1176,7 @@ namespace System { // // "MyDocuments" is a better name than "Personal" // - MyDocuments = Win32Native.CSIDL_PERSONAL, + MyDocuments = Win32Native.CSIDL_PERSONAL, // // Represents the program files folder. // @@ -1351,101 +1184,7 @@ namespace System { // // Represents the folder for components that are shared across applications. // - CommonProgramFiles = Win32Native.CSIDL_PROGRAM_FILES_COMMON, -#if !FEATURE_CORECLR - // - // \Start Menu\Programs\Administrative Tools - // - AdminTools = Win32Native.CSIDL_ADMINTOOLS, - // - // USERPROFILE\Local Settings\Application Data\Microsoft\CD Burning - // - CDBurning = Win32Native.CSIDL_CDBURN_AREA, - // - // All Users\Start Menu\Programs\Administrative Tools - // - CommonAdminTools = Win32Native.CSIDL_COMMON_ADMINTOOLS, - // - // All Users\Documents - // - CommonDocuments = Win32Native.CSIDL_COMMON_DOCUMENTS, - // - // All Users\My Music - // - CommonMusic = Win32Native.CSIDL_COMMON_MUSIC, - // - // Links to All Users OEM specific apps - // - CommonOemLinks = Win32Native.CSIDL_COMMON_OEM_LINKS, - // - // All Users\My Pictures - // - CommonPictures = Win32Native.CSIDL_COMMON_PICTURES, - // - // All Users\Start Menu - // - CommonStartMenu = Win32Native.CSIDL_COMMON_STARTMENU, - // - // All Users\Start Menu\Programs - // - CommonPrograms = Win32Native.CSIDL_COMMON_PROGRAMS, - // - // All Users\Startup - // - CommonStartup = Win32Native.CSIDL_COMMON_STARTUP, - // - // All Users\Desktop - // - CommonDesktopDirectory = Win32Native.CSIDL_COMMON_DESKTOPDIRECTORY, - // - // All Users\Templates - // - CommonTemplates = Win32Native.CSIDL_COMMON_TEMPLATES, - // - // All Users\My Video - // - CommonVideos = Win32Native.CSIDL_COMMON_VIDEO, - // - // windows\fonts - // - Fonts = Win32Native.CSIDL_FONTS, - // - // %APPDATA%\Microsoft\Windows\Network Shortcuts - // - NetworkShortcuts = Win32Native.CSIDL_NETHOOD, - // - // %APPDATA%\Microsoft\Windows\Printer Shortcuts - // - PrinterShortcuts = Win32Native.CSIDL_PRINTHOOD, - // - // USERPROFILE - // - UserProfile = Win32Native.CSIDL_PROFILE, - // - // x86 Program Files\Common on RISC - // - CommonProgramFilesX86 = Win32Native.CSIDL_PROGRAM_FILES_COMMONX86, - // - // x86 C:\Program Files on RISC - // - ProgramFilesX86 = Win32Native.CSIDL_PROGRAM_FILESX86, - // - // Resource Directory - // - Resources = Win32Native.CSIDL_RESOURCES, - // - // Localized Resource Directory - // - LocalizedResources = Win32Native.CSIDL_RESOURCES_LOCALIZED, - // - // %windir%\System32 or %windir%\syswow64 - // - SystemX86 = Win32Native.CSIDL_SYSTEMX86, - // - // GetWindowsDirectory() - // - Windows = Win32Native.CSIDL_WINDOWS, -#endif // !FEATURE_CORECLR + CommonProgramFiles = Win32Native.CSIDL_PROGRAM_FILES_COMMON, } public static int CurrentManagedThreadId diff --git a/src/coreclr/src/mscorlib/src/System/Exception.cs b/src/coreclr/src/mscorlib/src/System/Exception.cs index 07e34c2..c610daa 100644 --- a/src/coreclr/src/mscorlib/src/System/Exception.cs +++ b/src/coreclr/src/mscorlib/src/System/Exception.cs @@ -321,24 +321,12 @@ namespace System { // is true. Note that this requires FileIOPermission(PathDiscovery), and so // will usually fail in CoreCLR. To avoid the demand and resulting // SecurityException we can explicitly not even try to get fileinfo. -#if FEATURE_CORECLR [System.Security.SecurityCritical] // auto-generated -#endif private string GetStackTrace(bool needFileInfo) { string stackTraceString = _stackTraceString; string remoteStackTraceString = _remoteStackTraceString; -#if !FEATURE_CORECLR - if (!needFileInfo) - { - // Filter out file names/paths and line numbers from _stackTraceString and _remoteStackTraceString. - // This is used only when generating stack trace for Watson where the strings must be PII-free. - stackTraceString = StripFileInfo(stackTraceString, false); - remoteStackTraceString = StripFileInfo(remoteStackTraceString, true); - } -#endif // !FEATURE_CORECLR - // if no stack trace, try to get one if (stackTraceString != null) { @@ -380,9 +368,7 @@ namespace System { } public virtual String Source { -#if FEATURE_CORECLR [System.Security.SecurityCritical] // auto-generated -#endif get { if (_source == null) { @@ -411,9 +397,7 @@ namespace System { return _source; } -#if FEATURE_CORECLR [System.Security.SecurityCritical] // auto-generated -#endif set { _source = value; } } @@ -757,12 +741,6 @@ namespace System { [MethodImplAttribute(MethodImplOptions.InternalCall)] private static extern object CopyDynamicMethods(object currentDynamicMethods); -#if !FEATURE_CORECLR - [System.Security.SecuritySafeCritical] - [MethodImplAttribute(MethodImplOptions.InternalCall)] - private extern string StripFileInfo(string stackTrace, bool isRemoteStackTrace); -#endif // !FEATURE_CORECLR - [SecuritySafeCritical] internal object DeepCopyStackTrace(object currentStackTrace) { diff --git a/src/coreclr/src/mscorlib/src/System/GC.cs b/src/coreclr/src/mscorlib/src/System/GC.cs index 93c3bbd..3ee6114 100644 --- a/src/coreclr/src/mscorlib/src/System/GC.cs +++ b/src/coreclr/src/mscorlib/src/System/GC.cs @@ -542,100 +542,4 @@ namespace System { EndNoGCRegionWorker(); } } - -#if !FEATURE_CORECLR - internal class SizedReference : IDisposable - { - [System.Security.SecurityCritical] - [MethodImplAttribute(MethodImplOptions.InternalCall)] - private static extern IntPtr CreateSizedRef(Object o); - - [System.Security.SecurityCritical] - [MethodImplAttribute(MethodImplOptions.InternalCall)] - private static extern void FreeSizedRef(IntPtr h); - - [System.Security.SecurityCritical] - [MethodImplAttribute(MethodImplOptions.InternalCall)] - private static extern Object GetTargetOfSizedRef(IntPtr h); - - [System.Security.SecurityCritical] - [MethodImplAttribute(MethodImplOptions.InternalCall)] - private static extern Int64 GetApproximateSizeOfSizedRef(IntPtr h); - - #pragma warning disable 420 - [System.Security.SecuritySafeCritical] - private void Free() - { - IntPtr temp = _handle; - if (temp != IntPtr.Zero && - (Interlocked.CompareExchange(ref _handle, IntPtr.Zero, temp) == temp)) - { - FreeSizedRef(temp); - } - } - - internal volatile IntPtr _handle; - - [System.Security.SecuritySafeCritical] - public SizedReference(Object target) - { - IntPtr temp = IntPtr.Zero; - temp = CreateSizedRef(target); - _handle = temp; - } - - ~SizedReference() - { - Free(); - } - - public Object Target - { - [System.Security.SecuritySafeCritical] - get - { - IntPtr temp = _handle; - if (temp == IntPtr.Zero) - { - return null; - } - - Object o = GetTargetOfSizedRef(temp); - - return (_handle == IntPtr.Zero) ? null : o; - } - } - - public Int64 ApproximateSize - { - [System.Security.SecuritySafeCritical] - get - { - IntPtr temp = _handle; - - if (temp == IntPtr.Zero) - { - throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_HandleIsNotInitialized")); - } - - Int64 size = GetApproximateSizeOfSizedRef(temp); - - if (_handle == IntPtr.Zero) - { - throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_HandleIsNotInitialized")); - } - else - { - return size; - } - } - } - - public void Dispose() - { - Free(); - GC.SuppressFinalize(this); - } - } -#endif } diff --git a/src/coreclr/src/mscorlib/src/System/Globalization/CompareInfo.cs b/src/coreclr/src/mscorlib/src/System/Globalization/CompareInfo.cs index 9da4a6b..b6b1a53 100644 --- a/src/coreclr/src/mscorlib/src/System/Globalization/CompareInfo.cs +++ b/src/coreclr/src/mscorlib/src/System/Globalization/CompareInfo.cs @@ -322,13 +322,6 @@ namespace System.Globalization { get { Contract.Assert(m_name != null, "CompareInfo.Name Expected m_name to be set"); -#if !FEATURE_CORECLR - if (m_name == "zh-CHT" || m_name == "zh-CHS") - { - return m_name; - } -#endif // FEATURE_CORECLR - return (m_sortName); } } @@ -1267,28 +1260,6 @@ namespace System.Globalization { return NativeInternalInitSortHandle(localeName, out handleOrigin); } -#if !FEATURE_CORECLR - private const int SORT_VERSION_WHIDBEY = 0x00001000; - private const int SORT_VERSION_V4 = 0x00060101; - - internal static bool IsLegacy20SortingBehaviorRequested - { - get - { - return InternalSortVersion == SORT_VERSION_WHIDBEY; - } - } - - private static uint InternalSortVersion - { - [System.Security.SecuritySafeCritical] - get - { - return InternalGetSortVersion(); - } - } -#endif - [OptionalField(VersionAdded = 3)] private SortVersion m_SortVersion; @@ -1315,13 +1286,6 @@ namespace System.Globalization { [return: MarshalAs(UnmanagedType.Bool)] private static extern bool InternalGetNlsVersionEx(IntPtr handle, IntPtr handleOrigin, String localeName, ref Win32Native.NlsVersionInfoEx lpNlsVersionInformation); -#if !FEATURE_CORECLR - [System.Security.SecurityCritical] - [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] - [SuppressUnmanagedCodeSecurity] - private static extern uint InternalGetSortVersion(); - -#endif [System.Security.SecurityCritical] [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [SuppressUnmanagedCodeSecurity] diff --git a/src/coreclr/src/mscorlib/src/System/Globalization/CultureData.cs b/src/coreclr/src/mscorlib/src/System/Globalization/CultureData.cs index 7b56ba4..d6c66a7 100644 --- a/src/coreclr/src/mscorlib/src/System/Globalization/CultureData.cs +++ b/src/coreclr/src/mscorlib/src/System/Globalization/CultureData.cs @@ -10,10 +10,6 @@ namespace System.Globalization using System.Collections.Generic; using System.Text; using System.Threading; -#if !FEATURE_CORECLR - using System.Reflection; - using System.Resources; -#endif using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Versioning; @@ -466,23 +462,6 @@ namespace System.Globalization } private volatile static CultureData s_Invariant; - -#if !FEATURE_CORECLR - internal static volatile ResourceSet MscorlibResourceSet; -#endif - -#if !FEATURE_CORECLR - [System.Security.SecurityCritical] // auto-generated - private static bool IsResourcePresent(String resourceKey) - { - if (MscorlibResourceSet == null) - { - MscorlibResourceSet = new ResourceSet(typeof(Environment).Assembly.GetManifestResourceStream("mscorlib.resources")); - } - return MscorlibResourceSet.GetString(resourceKey) != null; - } -#endif - /////////////// // Constructors // /////////////// @@ -549,13 +528,7 @@ namespace System.Globalization // Ask native code if that one's real if (culture.InitCultureData() == false) { -#if !FEATURE_CORECLR - if (culture.InitCompatibilityCultureData() == false - && culture.InitLegacyAlternateSortData() == false) -#endif - { - return null; - } + return null; } return culture; @@ -567,138 +540,9 @@ namespace System.Globalization { return false; } - -#if !FEATURE_CORECLR - if (CultureInfo.IsTaiwanSku) - { - TreatTaiwanParentChainAsHavingTaiwanAsSpecific(); - } -#endif - return true; - } - -#if !FEATURE_CORECLR - [System.Security.SecuritySafeCritical] - private void TreatTaiwanParentChainAsHavingTaiwanAsSpecific() - { - if (IsNeutralInParentChainOfTaiwan() && IsOsPriorToWin7() && !IsReplacementCulture) - { - // force population of fields that should have information that is - // different than zh-TW: - string s = SNATIVELANGUAGE; - s = SENGLISHLANGUAGE; - s = SLOCALIZEDLANGUAGE; - s = STEXTINFO; - s = SCOMPAREINFO; - s = FONTSIGNATURE; - int i = IDEFAULTANSICODEPAGE; - i = IDEFAULTOEMCODEPAGE; - i = IDEFAULTMACCODEPAGE; - - this.sSpecificCulture = "zh-TW"; - this.sWindowsName = "zh-TW"; - } - } - - private bool IsNeutralInParentChainOfTaiwan() - { - return this.sRealName == "zh" || this.sRealName == "zh-Hant"; - } - - static readonly Version s_win7Version = new Version(6, 1); - static private bool IsOsPriorToWin7() - { - return Environment.OSVersion.Platform == PlatformID.Win32NT && - Environment.OSVersion.Version < s_win7Version; - } - static private bool IsOsWin7OrPrior() - { - return Environment.OSVersion.Platform == PlatformID.Win32NT && - Environment.OSVersion.Version < new Version(6, 2); // Win7 is 6.1.Build.Revision so we have to check for anything less than 6.2 - } - - private bool InitCompatibilityCultureData() - { - // for compatibility handle the deprecated ids: zh-chs, zh-cht - string cultureName = this.sRealName; - - string fallbackCultureName; - string realCultureName; - switch (AnsiToLower(cultureName)) - { - case "zh-chs": - fallbackCultureName = "zh-Hans"; - realCultureName = "zh-CHS"; - break; - case "zh-cht": - fallbackCultureName = "zh-Hant"; - realCultureName = "zh-CHT"; - break; - default: - return false; - } - - this.sRealName = fallbackCultureName; - if (InitCultureData() == false) - { - return false; - } - // fixup our data - this.sName = realCultureName; // the name that goes back to the user - this.sParent = fallbackCultureName; - this.bFramework = true; - - return true; - } - - private bool InitLegacyAlternateSortData() - { - if (!CompareInfo.IsLegacy20SortingBehaviorRequested) - { - return false; - } - - // For V2 compatibility, handle deprecated alternate sorts - string cultureName = this.sRealName; - - switch (AnsiToLower(cultureName)) - { - case "ko-kr_unicod": - cultureName = "ko-KR_unicod"; - this.sRealName = "ko-KR"; - this.iLanguage = 0x00010412; - break; - case "ja-jp_unicod": - cultureName = "ja-JP_unicod"; - this.sRealName = "ja-JP"; - this.iLanguage = 0x00010411; - break; - case "zh-hk_stroke": - cultureName = "zh-HK_stroke"; - this.sRealName = "zh-HK"; - this.iLanguage = 0x00020c04; - break; - default: - return false; - } - - if (nativeInitCultureData(this) == false) - { - return false; - } - - this.sRealName = cultureName; - this.sCompareInfo = cultureName; - this.bFramework = true; - return true; } -#if FEATURE_WIN32_REGISTRY - private static String s_RegionKey = @"System\CurrentControlSet\Control\Nls\RegionMapping"; -#endif // FEATURE_WIN32_REGISTRY - -#endif // !FEATURE_CORECLR // Cache of regions we've already looked up private static volatile Dictionary s_cachedRegions; @@ -749,41 +593,6 @@ namespace System.Globalization // // Not found in the hash table, look it up the hard way // -#if !FEATURE_CORECLR -#if FEATURE_WIN32_REGISTRY - // First try the registry in case there are overrides of our table - try - { - // Open in read-only mode. - // Use InternalOpenSubKey so that we avoid the security check. - Microsoft.Win32.RegistryKey key = Microsoft.Win32.Registry.LocalMachine.InternalOpenSubKey(s_RegionKey, false); - - if (key != null) - { - try - { - Object value = key.InternalGetValue(cultureName, null, false, false); - - if (value != null) - { - // Get the name of the locale to try. - String specificForRegion = value.ToString(); - - // See if it's real - retVal = GetCultureData(specificForRegion, useUserOverride); - } - } - finally - { - key.Close(); - } - } - } - // If this fails for any reason, we'll just ignore it, likely it just isn't there. - catch (ObjectDisposedException) { } - catch (ArgumentException) { } -#endif // FEATURE_WIN32_REGISTRY -#endif // !FEATURE_CORECLR // If not a valid mapping from the registry we'll have to try the hard coded table if (retVal == null || (retVal.IsNeutralCulture == true)) @@ -851,25 +660,6 @@ namespace System.Globalization String localeName = null; CultureData retVal = null; -#if !FEATURE_CORECLR - // If V2 legacy sort is requested, then provide deprecated alternate sorts - if (CompareInfo.IsLegacy20SortingBehaviorRequested) - { - switch (culture) - { - case 0x00010412: - localeName = "ko-KR_unicod"; - break; - case 0x00010411: - localeName = "ja-JP_unicod"; - break; - case 0x00020c04: - localeName = "zh-HK_stroke"; - break; - } - } -#endif - if (localeName == null) { // Convert the lcid to a name, then use that @@ -886,19 +676,6 @@ namespace System.Globalization } else { -#if !FEATURE_CORECLR - switch (localeName) - { - // for compatibility with Whidbey, when requesting - // a locale from LCID, return the old localeName - case "zh-Hans": - localeName = "zh-CHS"; - break; - case "zh-Hant": - localeName = "zh-CHT"; - break; - } -#endif // Valid name, use it retVal = GetCultureData(localeName, bUseUserOverride); } @@ -972,29 +749,12 @@ namespace System.Globalization int arrayLength = cultureNames.Length; -#if !FEATURE_CORECLR - if ((types & (CultureTypes.NeutralCultures | CultureTypes.FrameworkCultures)) != 0) // add zh-CHT and zh-CHS - { - arrayLength += 2; - } -#endif // FEATURE_CORECLR - CultureInfo[] cultures = new CultureInfo[arrayLength]; for (int i = 0; i < cultureNames.Length; i++) { cultures[i] = new CultureInfo(cultureNames[i]); } - -#if !FEATURE_CORECLR - if ((types & (CultureTypes.NeutralCultures | CultureTypes.FrameworkCultures)) != 0) // add zh-CHT and zh-CHS - { - Contract.Assert(arrayLength == cultureNames.Length + 2, "CultureData.nativeEnumCultureNames() Incorrect array size"); - cultures[cultureNames.Length] = new CultureInfo("zh-CHS"); - cultures[cultureNames.Length + 1] = new CultureInfo("zh-CHT"); - } -#endif // FEATURE_CORECLR - #pragma warning restore 618 return cultures; @@ -1117,24 +877,6 @@ namespace System.Globalization { // Ask using the real name, so that we get parents of neutrals this.sParent = DoGetLocaleInfo(this.sRealName, LOCALE_SPARENT); - -#if !FEATURE_CORECLR - // for compatibility, the chain should be: - // zh-CN -> zh-CHS -> zh-Hans -> zh - // zh-TW -> zh-CHT -> zh-Hant -> zh - Contract.Assert(this.sName != "zh-CHS" && this.sName != "zh-CHT", - "sParent should have been initialized for zh-CHS and zh-CHT when they were constructed, otherwise we get recursion"); - switch (this.sParent) - { - case "zh-Hans": - this.sParent = "zh-CHS"; - break; - case "zh-Hant": - this.sParent = "zh-CHT"; - break; - } -#endif - } return this.sParent; } @@ -1148,13 +890,6 @@ namespace System.Globalization { if (this.sLocalizedDisplayName == null) { -#if !FEATURE_CORECLR - String resourceKey = "Globalization.ci_" + this.sName; - if (IsResourcePresent(resourceKey)) - { - this.sLocalizedDisplayName = Environment.GetResourceString(resourceKey); - } -#endif // If it hasn't been found (Windows 8 and up), fallback to the system if (String.IsNullOrEmpty(this.sLocalizedDisplayName)) { @@ -1193,17 +928,6 @@ namespace System.Globalization if (this.IsNeutralCulture) { this.sEnglishDisplayName = this.SENGLISHLANGUAGE; -#if !FEATURE_CORECLR - // differentiate the legacy display names - switch (this.sName) - { - case "zh-CHS": - case "zh-CHT": - this.sEnglishDisplayName += " Legacy"; - break; - } -#endif - } else { @@ -1246,32 +970,10 @@ namespace System.Globalization if (this.IsNeutralCulture) { this.sNativeDisplayName = this.SNATIVELANGUAGE; -#if !FEATURE_CORECLR - // differentiate the legacy display names - switch (this.sName) - { - case "zh-CHS": - this.sNativeDisplayName += " \u65E7\u7248"; - break; - case "zh-CHT": - this.sNativeDisplayName += " \u820A\u7248"; - break; - } -#endif } else { -#if !FEATURE_CORECLR - if (IsIncorrectNativeLanguageForSinhala()) - { - // work around bug in Windows 7 for native name of Sinhala - this.sNativeDisplayName ="\x0dc3\x0dd2\x0d82\x0dc4\x0dbd (\x0DC1\x0DCA\x200D\x0DBB\x0DD3\x0020\x0DBD\x0D82\x0D9A\x0DCF)"; - } - else -#endif - { - this.sNativeDisplayName = DoGetLocaleInfo(LOCALE_SNATIVEDISPLAYNAME); - } + this.sNativeDisplayName = DoGetLocaleInfo(LOCALE_SNATIVEDISPLAYNAME); // if it isn't found build one: if (String.IsNullOrEmpty(this.sNativeDisplayName)) @@ -1388,13 +1090,6 @@ namespace System.Globalization { if (this.sNativeLanguage == null) { -#if !FEATURE_CORECLR - if (IsIncorrectNativeLanguageForSinhala()) - { - this.sNativeLanguage = "\x0dc3\x0dd2\x0d82\x0dc4\x0dbd"; - } - else -#endif { this.sNativeLanguage = DoGetLocaleInfo(LOCALE_SNATIVELANGUAGENAME); } @@ -1403,15 +1098,6 @@ namespace System.Globalization } } -#if !FEATURE_CORECLR - private bool IsIncorrectNativeLanguageForSinhala() - { - return IsOsWin7OrPrior() - && (sName == "si-LK" || sName == "si") - && !IsReplacementCulture; - } -#endif - /////////// // Region // /////////// @@ -1460,13 +1146,6 @@ namespace System.Globalization { if (this.sLocalizedCountry == null) { -#if !FEATURE_CORECLR - String resourceKey = "Globalization.ri_" + this.SREGIONNAME; - if (IsResourcePresent(resourceKey)) - { - this.sLocalizedCountry = Environment.GetResourceString(resourceKey); - } -#endif // If it hasn't been found (Windows 8 and up), fallback to the system if (String.IsNullOrEmpty(this.sLocalizedCountry)) { @@ -2297,14 +1976,6 @@ namespace System.Globalization { Contract.Assert(this.sWindowsName != null, "[CultureData.GetCalendar] Expected this.sWindowsName to be populated by COMNlsInfo::nativeInitCultureData already"); calendarData = new CalendarData(this.sWindowsName, calendarId, this.UseUserOverride); -#if !FEATURE_CORECLR - //Work around issue where Win7 data for MonthDay contains invalid two sets of data separated by semicolon - //even though MonthDay is not enumerated - if (IsOsWin7OrPrior() && !IsSupplementalCustomCulture && !IsReplacementCulture) - { - calendarData.FixupWin7MonthDaySemicolonBug(); - } -#endif calendars[calendarIndex] = calendarData; } @@ -3060,17 +2731,6 @@ namespace System.Globalization { nfi.currencyDecimalSeparator = nfi.numberDecimalSeparator; } - -#if !FEATURE_CORECLR - if ((932 == this.IDEFAULTANSICODEPAGE) || - (949 == this.IDEFAULTANSICODEPAGE)) - { - // Legacy behavior for cultures that use Japanese/Korean default ANSI code pages - // Note that this is a code point, not a character. On Japanese/Korean machines this - // will be rendered as their currency symbol, not rendered as a "\" - nfi.ansiCurrencySymbol = "\x5c"; - } -#endif // !FEATURE_CORECLR } static private int ConvertFirstDayOfWeekMonToSun(int iTemp) diff --git a/src/coreclr/src/mscorlib/src/System/Globalization/CultureInfo.cs b/src/coreclr/src/mscorlib/src/System/Globalization/CultureInfo.cs index 1ef3809..54ea32b 100644 --- a/src/coreclr/src/mscorlib/src/System/Globalization/CultureInfo.cs +++ b/src/coreclr/src/mscorlib/src/System/Globalization/CultureInfo.cs @@ -66,10 +66,6 @@ namespace System.Globalization { internal bool m_isReadOnly; internal CompareInfo compareInfo; internal TextInfo textInfo; - // Not serialized for now since we only build it privately for use in the CARIB (so rebuilding is OK) -#if !FEATURE_CORECLR - [NonSerialized]internal RegionInfo regionInfo; -#endif internal NumberFormatInfo numInfo; internal DateTimeFormatInfo dateTimeInfo; internal Calendar calendar; @@ -670,9 +666,6 @@ namespace System.Globalization { get { Contract.Ensures(Contract.Result() != null); -#if !FEATURE_CORECLR - return Thread.CurrentThread.CurrentCulture; -#else // In the case of CoreCLR, Thread.m_CurrentCulture and // Thread.m_CurrentUICulture are thread static so as not to let // CultureInfo objects leak across AppDomain boundaries. The @@ -693,7 +686,6 @@ namespace System.Globalization { s_DefaultThreadCurrentCulture ?? s_userDefaultCulture ?? UserDefaultCulture; -#endif } set { @@ -768,9 +760,6 @@ namespace System.Globalization { get { Contract.Ensures(Contract.Result() != null); -#if !FEATURE_CORECLR - return Thread.CurrentThread.CurrentUICulture; -#else // In the case of CoreCLR, Thread.m_CurrentCulture and // Thread.m_CurrentUICulture are thread static so as not to let // CultureInfo objects leak across AppDomain boundaries. The @@ -791,7 +780,6 @@ namespace System.Globalization { s_DefaultThreadCurrentUICulture ?? s_userDefaultUICulture ?? UserDefaultUICulture; -#endif } set { @@ -1174,31 +1162,6 @@ namespace System.Globalization { } } -#if !FEATURE_CORECLR - //////////////////////////////////////////////////////////////////////// - // - // RegionInfo - // - // Gets the RegionInfo for this culture. - // - //////////////////////////////////////////////////////////////////////// - private RegionInfo Region - { - get - { - if (regionInfo==null) - { - // Make a new regionInfo - RegionInfo tempRegionInfo = new RegionInfo(this.m_cultureData); - regionInfo = tempRegionInfo; - } - return (regionInfo); - } - } -#endif // FEATURE_CORECLR - - - //////////////////////////////////////////////////////////////////////// // // TextInfo @@ -1395,17 +1358,16 @@ namespace System.Globalization { } } - - public void ClearCachedData() { s_userDefaultUICulture = null; s_userDefaultCulture = null; RegionInfo.s_currentRegionInfo = null; -#if !FEATURE_CORECLR // System.TimeZone does not exist in CoreCLR +#pragma warning disable CS0618 TimeZone.ResetTimeZone(); -#endif // FEATURE_CORECLR +#pragma warning restore CS0618 TimeZoneInfo.ClearCachedData(); + // Delete the cached cultures. s_LcidCachedCultures = null; s_NameCachedCultures = null; diff --git a/src/coreclr/src/mscorlib/src/System/Globalization/DateTimeFormatInfo.cs b/src/coreclr/src/mscorlib/src/System/Globalization/DateTimeFormatInfo.cs index 767757a..dd878a4 100644 --- a/src/coreclr/src/mscorlib/src/System/Globalization/DateTimeFormatInfo.cs +++ b/src/coreclr/src/mscorlib/src/System/Globalization/DateTimeFormatInfo.cs @@ -335,10 +335,6 @@ namespace System.Globalization { // m_isDefaultCalendar is set in the setter of Calendar below. this.Calendar = cal; } - -#if !FEATURE_CORECLR - [System.Security.SecuritySafeCritical] -#endif private void InitializeOverridableProperties(CultureData cultureData, int calendarID) { // Silverlight 2.0 never took a snapshot of the user's overridable properties @@ -446,11 +442,6 @@ namespace System.Globalization { // make sure the m_name is initialized. m_name = this.CultureName; -#if !FEATURE_CORECLR - if (s_calendarNativeNames == null) - s_calendarNativeNames = new Hashtable(); -#endif // FEATURE_CORECLR - // Important to initialize these fields otherwise we may run into exception when deserializing on Whidbey // because Whidbey try to initialize some of these fields using calendar data which could be null values // and then we get exceptions. So we call the accessors to force the caches to get loaded. diff --git a/src/coreclr/src/mscorlib/src/System/Globalization/DateTimeParse.cs b/src/coreclr/src/mscorlib/src/System/Globalization/DateTimeParse.cs index e2b0c95..b48067b 100644 --- a/src/coreclr/src/mscorlib/src/System/Globalization/DateTimeParse.cs +++ b/src/coreclr/src/mscorlib/src/System/Globalization/DateTimeParse.cs @@ -35,16 +35,6 @@ namespace System { internal static MatchNumberDelegate m_hebrewNumberParser = new MatchNumberDelegate(DateTimeParse.MatchHebrewDigits); -#if !FEATURE_CORECLR - [SecuritySafeCritical] - internal static bool GetAmPmParseFlag() - { - return DateTime.EnableAmPmParseAdjustment(); - } - - internal static bool enableAmPmParseAdjustment = GetAmPmParseFlag(); -#endif - internal static DateTime ParseExact(String s, String format, DateTimeFormatInfo dtfi, DateTimeStyles style) { DateTimeResult result = new DateTimeResult(); // The buffer to store the parsing result. result.Init(); @@ -761,11 +751,7 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR, raw.timeMark = (sep == TokenType.SEP_Am ? TM.AM : TM.PM); dtok.dtt = DTT.NumAmpm; // Fix AM/PM parsing case, e.g. "1/10 5 AM" - if (dps == DS.D_NN -#if !FEATURE_CORECLR - && enableAmPmParseAdjustment -#endif - ) + if (dps == DS.D_NN) { if (!ProcessTerminaltState(DS.DX_NN, ref result, ref styles, ref raw, dtfi)) { @@ -1076,16 +1062,6 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR, return (false); } -#if !FEATURE_CORECLR - // If DateTimeParseIgnorePunctuation is defined, we want to have the V1.1 behavior of just - // ignoring any unrecognized punctuation and moving on to the next character - if (Environment.GetCompatibilityFlag(CompatibilityFlag.DateTimeParseIgnorePunctuation) && ((result.flags & ParseFlags.CaptureOffset) == 0)) { - str.GetNext(); - LexTraceExit("0210 (success)", dps); - return true; - } -#endif // FEATURE_CORECLR - if ((str.m_current == '-' || str.m_current == '+') && ((result.flags & ParseFlags.TimeZoneUsed) == 0)) { Int32 originalIndex = str.Index; if (ParseTimeZone(ref str, ref result.timeZoneOffset)) { @@ -1096,7 +1072,7 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR, else { // Time zone parse attempt failed. Fall through to punctuation handling. str.Index = originalIndex; - } + } } // Visual Basic implements string to date conversions on top of DateTime.Parse: @@ -1104,7 +1080,7 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR, // if (VerifyValidPunctuation(ref str)) { LexTraceExit("0230 (success)", dps); - return true; + return true; } result.SetFailure(ParseFailureKind.Format, "Format_BadDateTime", null); diff --git a/src/coreclr/src/mscorlib/src/System/Globalization/NumberFormatInfo.cs b/src/coreclr/src/mscorlib/src/System/Globalization/NumberFormatInfo.cs index bdd4dfc..886fd88 100644 --- a/src/coreclr/src/mscorlib/src/System/Globalization/NumberFormatInfo.cs +++ b/src/coreclr/src/mscorlib/src/System/Globalization/NumberFormatInfo.cs @@ -120,28 +120,8 @@ namespace System.Globalization { [OnSerializing] private void OnSerializing(StreamingContext ctx) { -#if !FEATURE_CORECLR - // Update these legacy flags, so that 1.1/2.0 versions of the framework - // can still throw while parsing; even when using a de-serialized - // NumberFormatInfo from a 4.0+ version of the framework - if (numberDecimalSeparator != numberGroupSeparator) { - validForParseAsNumber = true; - } else { - validForParseAsNumber = false; - } - - if ((numberDecimalSeparator != numberGroupSeparator) && - (numberDecimalSeparator != currencyGroupSeparator) && - (currencyDecimalSeparator != numberGroupSeparator) && - (currencyDecimalSeparator != currencyGroupSeparator)) { - validForParseAsCurrency = true; - } else { - validForParseAsCurrency = false; - } -#endif // !FEATURE_CORECLR } - [OnDeserializing] private void OnDeserializing(StreamingContext ctx) { @@ -153,7 +133,6 @@ namespace System.Globalization { } #endregion Serialization - static private void VerifyDecimalSeparator(String decSep, String propertyName) { if (decSep==null) { throw new ArgumentNullException(propertyName, diff --git a/src/coreclr/src/mscorlib/src/System/Globalization/RegionInfo.cs b/src/coreclr/src/mscorlib/src/System/Globalization/RegionInfo.cs index d635458..1159d01 100644 --- a/src/coreclr/src/mscorlib/src/System/Globalization/RegionInfo.cs +++ b/src/coreclr/src/mscorlib/src/System/Globalization/RegionInfo.cs @@ -163,169 +163,13 @@ namespace System.Globalization { [OptionalField(VersionAdded = 2)] internal int m_dataItem = 0; -#if !FEATURE_CORECLR - static private readonly int[] IdFromEverettRegionInfoDataItem = - { - 0x3801, /* 0 */ // AE ar-AE Arabic (U.A.E.) - 0x041C, /* 1 */ // AL sq-AL Albanian (Albania) - 0x042B, /* 2 */ // AM hy-AM Armenian (Armenia) - 0x2C0A, /* 3 */ // AR es-AR Spanish (Argentina) - 0x0C07, /* 4 */ // AT de-AT German (Austria) - 0x0C09, /* 5 */ // AU en-AU English (Australia) - 0x042C, /* 6 */ // AZ az-AZ-Latn Azeri (Latin) (Azerbaijan) - // 0x082C, 6, // AZ az-AZ-Cyrl Azeri (Cyrillic) (Azerbaijan) - 0x080C, /* 7 */ // BE fr-BE French (Belgium) - // 0x0813, 7, // BE nl-BE Dutch (Belgium) - 0x0402, /* 8 */ // BG bg-BG Bulgarian (Bulgaria) - 0x3C01, /* 9 */ // BH ar-BH Arabic (Bahrain) - 0x083E, /* 10 */ // BN ms-BN Malay (Brunei Darussalam) - 0x400A, /* 11 */ // BO es-BO Spanish (Bolivia) - 0x0416, /* 12 */ // BR pt-BR Portuguese (Brazil) - 0x0423, /* 13 */ // BY be-BY Belarusian (Belarus) - 0x2809, /* 14 */ // BZ en-BZ English (Belize) - 0x0C0C, /* 15 */ // CA fr-CA French (Canada) - // 0x1009, 15, // CA en-CA English (Canada) - 0x2409, /* 16 */ // CB en-CB English (Caribbean) - 0x0807, /* 17 */ // CH de-CH German (Switzerland) - // 0x0810, 17, // CH it-CH Italian (Switzerland) - // 0x100C, 17, // CH fr-CH French (Switzerland) - 0x340A, /* 18 */ // CL es-CL Spanish (Chile) - 0x0804, /* 19 */ // CN zh-CN Chinese (People's Republic of China) - 0x240A, /* 20 */ // CO es-CO Spanish (Colombia) - 0x140A, /* 21 */ // CR es-CR Spanish (Costa Rica) - 0x0405, /* 22 */ // CZ cs-CZ Czech (Czech Republic) - 0x0407, /* 23 */ // DE de-DE German (Germany) - 0x0406, /* 24 */ // DK da-DK Danish (Denmark) - 0x1C0A, /* 25 */ // DO es-DO Spanish (Dominican Republic) - 0x1401, /* 26 */ // DZ ar-DZ Arabic (Algeria) - 0x300A, /* 27 */ // EC es-EC Spanish (Ecuador) - 0x0425, /* 28 */ // EE et-EE Estonian (Estonia) - 0x0C01, /* 29 */ // EG ar-EG Arabic (Egypt) - 0x0403, /* 30 */ // ES ca-ES Catalan (Catalan) - // 0x042D, 30, // ES eu-ES Basque (Basque) - // 0x0456, 30, // ES gl-ES Galician (Galician) - // 0x0C0A, 30, // ES es-ES Spanish (Spain) - 0x040B, /* 31 */ // FI fi-FI Finnish (Finland) - // 0x081D, 31, // FI sv-FI Swedish (Finland) - 0x0438, /* 32 */ // FO fo-FO Faroese (Faroe Islands) - 0x040C, /* 33 */ // FR fr-FR French (France) - 0x0809, /* 34 */ // GB en-GB English (United Kingdom) - 0x0437, /* 35 */ // GE ka-GE Georgian (Georgia) - 0x0408, /* 36 */ // GR el-GR Greek (Greece) - 0x100A, /* 37 */ // GT es-GT Spanish (Guatemala) - 0x0C04, /* 38 */ // HK zh-HK Chinese (Hong Kong S.A.R.) - 0x480A, /* 39 */ // HN es-HN Spanish (Honduras) - 0x041A, /* 40 */ // HR hr-HR Croatian (Croatia) - 0x040E, /* 41 */ // HU hu-HU Hungarian (Hungary) - 0x0421, /* 42 */ // ID id-ID Indonesian (Indonesia) - 0x1809, /* 43 */ // IE en-IE English (Ireland) - 0x040D, /* 44 */ // IL he-IL Hebrew (Israel) - 0x0439, /* 45 */ // IN hi-IN Hindi (India) - // 0x0446, 45, // IN pa-IN Punjabi (India) - // 0x0447, 45, // IN gu-IN Gujarati (India) - // 0x0449, 45, // IN ta-IN Tamil (India) - // 0x044A, 45, // IN te-IN Telugu (India) - // 0x044B, 45, // IN kn-IN Kannada (India) - // 0x044E, 45, // IN mr-IN Marathi (India) - // 0x044F, 45, // IN sa-IN Sanskrit (India) - // 0x0457, 45, // IN kok-IN Konkani (India) - 0x0801, /* 46 */ // IQ ar-IQ Arabic (Iraq) - 0x0429, /* 47 */ // IR fa-IR (Iran) - 0x040F, /* 48 */ // IS is-IS Icelandic (Iceland) - 0x0410, /* 49 */ // IT it-IT Italian (Italy) - 0x2009, /* 50 */ // JM en-JM English (Jamaica) - 0x2C01, /* 51 */ // JO ar-JO Arabic (Jordan) - 0x0411, /* 52 */ // JP ja-JP Japanese (Japan) - 0x0441, /* 53 */ // KE sw-KE Swahili (Kenya) - 0x0440, /* 54 */ // KG ky-KG Kyrgyz (Kyrgyzstan) - 0x0412, /* 55 */ // KR ko-KR Korean (Korea) - 0x3401, /* 56 */ // KW ar-KW Arabic (Kuwait) - 0x043F, /* 57 */ // KZ kk-KZ Kazakh (Kazakhstan) - 0x3001, /* 58 */ // LB ar-LB Arabic (Lebanon) - 0x1407, /* 59 */ // LI de-LI German (Liechtenstein) - 0x0427, /* 60 */ // LT lt-LT Lithuanian (Lithuania) - 0x1007, /* 61 */ // LU de-LU German (Luxembourg) - // 0x140C, 61, // LU fr-LU French (Luxembourg) - 0x0426, /* 62 */ // LV lv-LV Latvian (Latvia) - 0x1001, /* 63 */ // LY ar-LY Arabic (Libya) - 0x1801, /* 64 */ // MA ar-MA Arabic (Morocco) - 0x180C, /* 65 */ // MC fr-MC French (Principality of Monaco) - 0x042F, /* 66 */ // MK mk-MK Macedonian (Macedonia, FYRO) - 0x0450, /* 67 */ // MN mn-MN Mongolian (Mongolia) - 0x1404, /* 68 */ // MO zh-MO Chinese (Macau S.A.R.) - 0x0465, /* 69 */ // MV div-MV Divehi (Maldives) - 0x080A, /* 70 */ // MX es-MX Spanish (Mexico) - 0x043E, /* 71 */ // MY ms-MY Malay (Malaysia) - 0x4C0A, /* 72 */ // NI es-NI Spanish (Nicaragua) - 0x0413, /* 73 */ // NL nl-NL Dutch (Netherlands) - 0x0414, /* 74 */ // NO nb-NO Norwegian (Bokm?) (Norway) - // 0x0814, 74, // NO nn-NO Norwegian (Nynorsk) (Norway) - 0x1409, /* 75 */ // NZ en-NZ English (New Zealand) - 0x2001, /* 76 */ // OM ar-OM Arabic (Oman) - 0x180A, /* 77 */ // PA es-PA Spanish (Panama) - 0x280A, /* 78 */ // PE es-PE Spanish (Peru) - 0x3409, /* 79 */ // PH en-PH English (Republic of the Philippines) - 0x0420, /* 80 */ // PK ur-PK Urdu (Islamic Republic of Pakistan) - 0x0415, /* 81 */ // PL pl-PL Polish (Poland) - 0x500A, /* 82 */ // PR es-PR Spanish (Puerto Rico) - 0x0816, /* 83 */ // PT pt-PT Portuguese (Portugal) - 0x3C0A, /* 84 */ // PY es-PY Spanish (Paraguay) - 0x4001, /* 85 */ // QA ar-QA Arabic (Qatar) - 0x0418, /* 86 */ // RO ro-RO Romanian (Romania) - 0x0419, /* 87 */ // RU ru-RU Russian (Russia) - // 0x0444, 87, // RU tt-RU Tatar (Russia) - 0x0401, /* 88 */ // SA ar-SA Arabic (Saudi Arabia) - 0x041D, /* 89 */ // SE sv-SE Swedish (Sweden) - 0x1004, /* 90 */ // SG zh-SG Chinese (Singapore) - 0x0424, /* 91 */ // SI sl-SI Slovenian (Slovenia) - 0x041B, /* 92 */ // SK sk-SK Slovak (Slovakia) - 0x081A, /* 93 */ // SP sr-SP-Latn Serbian (Latin) (Serbia) - // 0x0C1A, 93, // SP sr-SP-Cyrl Serbian (Cyrillic) (Serbia) - 0x440A, /* 94 */ // SV es-SV Spanish (El Salvador) - 0x045A, /* 95 */ // SY syr-SY Syriac (Syria) - // 0x2801, 95, // SY ar-SY Arabic (Syria) - 0x041E, /* 96 */ // TH th-TH Thai (Thailand) - 0x1C01, /* 97 */ // TN ar-TN Arabic (Tunisia) - 0x041F, /* 98 */ // TR tr-TR Turkish (Turkey) - 0x2C09, /* 99 */ // TT en-TT English (Trinidad and Tobago) - 0x0404, /*100 */ // TW zh-TW Chinese (Taiwan) - 0x0422, /*101 */ // UA uk-UA Ukrainian (Ukraine) - 0x0409, /*102 */ // US en-US English (United States) - 0x380A, /*103 */ // UY es-UY Spanish (Uruguay) - 0x0443, /*104 */ // UZ uz-UZ-Latn Uzbek (Latin) (Uzbekistan) - // 0x0843, 104 // UZ uz-UZ-Cyrl Uzbek (Cyrillic) (Uzbekistan) - 0x200A, /*105*/ // VE es-VE Spanish (Venezuela) - 0x042A, /*106*/ // VN vi-VN Vietnamese (Viet Nam) - 0x2401, /*107*/ // YE ar-YE Arabic (Yemen) - 0x0436, /*108*/ // ZA af-ZA Afrikaans (South Africa) - // 0x1C09, 108, // ZA en-ZA English (South Africa) - 0x3009, /*109*/ // ZW en-ZW English (Zimbabwe) - }; -#endif [System.Security.SecurityCritical] // auto-generated [OnDeserialized] private void OnDeserialized(StreamingContext ctx) { -#if FEATURE_CORECLR // This won't happen anyway since CoreCLR doesn't support serialization this.m_cultureData = CultureData.GetCultureData(m_name, true); -#else - if (m_name == null) - { - Contract.Assert(m_dataItem >= 0, "[RegionInfo.OnDeserialized] null name and invalid dataItem"); - m_cultureId = IdFromEverettRegionInfoDataItem[m_dataItem]; - } - if (m_cultureId == 0) - { - this.m_cultureData = CultureData.GetCultureDataForRegion(this.m_name, true); - } - else - { - this.m_cultureData = CultureData.GetCultureData(m_cultureId, true); - } - -#endif if (this.m_cultureData == null) throw new ArgumentException( String.Format( diff --git a/src/coreclr/src/mscorlib/src/System/Globalization/TextInfo.cs b/src/coreclr/src/mscorlib/src/System/Globalization/TextInfo.cs index 4fa9f66..7eff22a 100644 --- a/src/coreclr/src/mscorlib/src/System/Globalization/TextInfo.cs +++ b/src/coreclr/src/mscorlib/src/System/Globalization/TextInfo.cs @@ -106,11 +106,6 @@ namespace System.Globalization { this.m_cultureData = cultureData; this.m_cultureName = this.m_cultureData.CultureName; this.m_textInfoName = this.m_cultureData.STEXTINFO; -#if !FEATURE_CORECLR - IntPtr handleOrigin; - this.m_dataHandle = CompareInfo.InternalInitSortHandle(m_textInfoName, out handleOrigin); - this.m_handleOrigin = handleOrigin; -#endif } //////////////////////////////////////////////////////////////////////// @@ -179,30 +174,18 @@ namespace System.Globalization { // Get the text info name belonging to that culture this.m_cultureData = CultureInfo.GetCultureInfo(m_cultureName).m_cultureData; this.m_textInfoName = this.m_cultureData.STEXTINFO; -#if !FEATURE_CORECLR - IntPtr handleOrigin; - this.m_dataHandle = CompareInfo.InternalInitSortHandle(m_textInfoName, out handleOrigin); - this.m_handleOrigin = handleOrigin; -#endif - } + } } - [OnDeserialized] private void OnDeserialized(StreamingContext ctx) { OnDeserialized(); - } - + } + [OnSerializing] private void OnSerializing(StreamingContext ctx) - { -#if !FEATURE_CORECLR - // Initialize the fields Whidbey expects: - // Whidbey expected this, so set it, but the value doesn't matter much - this.m_useUserOverride = false; -#endif // FEATURE_CORECLR - + { // Relabel our name since Whidbey expects it to be called customCultureName this.customCultureName = this.m_cultureName; diff --git a/src/coreclr/src/mscorlib/src/System/IO/BinaryWriter.cs b/src/coreclr/src/mscorlib/src/System/IO/BinaryWriter.cs index ed3ae5b..ca11868c 100644 --- a/src/coreclr/src/mscorlib/src/System/IO/BinaryWriter.cs +++ b/src/coreclr/src/mscorlib/src/System/IO/BinaryWriter.cs @@ -25,7 +25,7 @@ namespace System.IO { // give unique encodings. // [Serializable] -[System.Runtime.InteropServices.ComVisible(true)] + [System.Runtime.InteropServices.ComVisible(true)] public class BinaryWriter : IDisposable { public static readonly BinaryWriter Null = new BinaryWriter(); @@ -38,16 +38,6 @@ namespace System.IO { [OptionalField] // New in .NET FX 4.5. False is the right default value. private bool _leaveOpen; -#if !FEATURE_CORECLR - // This field should never have been serialized and has not been used since before v2.0. - // However, this type is serializable, and we need to keep the field name around when deserializing. - // Also, we'll make .NET FX 4.5 not break if it's missing. -#pragma warning disable 169 - [OptionalField] - private char[] _tmpOneCharBuffer; -#pragma warning restore 169 -#endif - // Perf optimization stuff private byte[] _largeByteBuffer; // temp space for writing chars. private int _maxChars; // max # of chars we can put in _largeByteBuffer diff --git a/src/coreclr/src/mscorlib/src/System/IO/Directory.cs b/src/coreclr/src/mscorlib/src/System/IO/Directory.cs index e4b41eb..2d24d67 100644 --- a/src/coreclr/src/mscorlib/src/System/IO/Directory.cs +++ b/src/coreclr/src/mscorlib/src/System/IO/Directory.cs @@ -15,25 +15,16 @@ ** ===========================================================*/ -using System; -using System.Collections; using System.Collections.Generic; using System.Security; using System.Security.Permissions; using Microsoft.Win32; using Microsoft.Win32.SafeHandles; -using System.Text; using System.Runtime.InteropServices; -using System.Globalization; -using System.Runtime.Versioning; using System.Diagnostics.Contracts; -using System.Threading; -#if FEATURE_MACL -using System.Security.AccessControl; -#endif - -namespace System.IO { +namespace System.IO +{ [ComVisible(true)] public static class Directory { public static DirectoryInfo GetParent(String path) @@ -90,45 +81,17 @@ namespace System.IO { // a demand at every level. String demandDir = GetDemandDir(fullPath, true); -#if FEATURE_CORECLR if (checkHost) { FileSecurityState state = new FileSecurityState(FileSecurityStateAccess.Read, path, demandDir); state.EnsureState(); // do the check on the AppDomainManager to make sure this is allowed } -#else - FileIOPermission.QuickDemand(FileIOPermissionAccess.Read, demandDir, false, false); -#endif InternalCreateDirectory(fullPath, path, null, checkHost); return new DirectoryInfo(fullPath, false); } -#if FEATURE_MACL - [System.Security.SecuritySafeCritical] // auto-generated - public static DirectoryInfo CreateDirectory(String path, DirectorySecurity directorySecurity) { - if (path==null) - throw new ArgumentNullException(nameof(path)); - if (path.Length == 0) - throw new ArgumentException(Environment.GetResourceString("Argument_PathEmpty")); - Contract.EndContractBlock(); - - String fullPath = Path.GetFullPathInternal(path); - - // You need read access to the directory to be returned back and write access to all the directories - // that you need to create. If we fail any security checks we will not create any directories at all. - // We attempt to create directories only after all the security checks have passed. This is avoid doing - // a demand at every level. - String demandDir = GetDemandDir(fullPath, true); - FileIOPermission.QuickDemand(FileIOPermissionAccess.Read, demandDir, false, false ); - - InternalCreateDirectory(fullPath, path, directorySecurity); - - return new DirectoryInfo(fullPath, false); - } -#endif // FEATURE_MACL - // Input to this method should already be fullpath. This method will ensure that we append // the trailing slash only when appropriate and when thisDirOnly is specified append a "." // at the end of the path to indicate that the demand is only for the fullpath and not @@ -163,10 +126,6 @@ namespace System.IO { [System.Security.SecuritySafeCritical] internal unsafe static void InternalCreateDirectory(String fullPath, String path, Object dirSecurityObj, bool checkHost) { -#if FEATURE_MACL - DirectorySecurity dirSecurity = (DirectorySecurity)dirSecurityObj; -#endif // FEATURE_MACL - int length = fullPath.Length; // We need to trim the trailing slash or the code will try to create 2 directories of the same name. @@ -215,15 +174,7 @@ namespace System.IO { int count = stackDir.Count; - if (stackDir.Count != 0 -#if FEATURE_CAS_POLICY - // All demands in full trust domains are no-ops, so skip - // - // The full path went through validity checks by being passed through FileIOPermissions already. - // As a sub string of the full path can't fail the checks if the full path passes. - && !CodeAccessSecurityEngine.QuickCheckForAllDemands() -#endif - ) + if (stackDir.Count != 0) { String[] securityList = new String[stackDir.Count]; stackDir.CopyTo(securityList, 0); @@ -231,11 +182,6 @@ namespace System.IO { securityList[j] += "\\."; // leaf will never have a slash at the end // Security check for all directories not present only. -#if FEATURE_MACL - AccessControlActions control = (dirSecurity == null) ? AccessControlActions.None : AccessControlActions.Change; - FileIOPermission.QuickDemand(FileIOPermissionAccess.Write, control, securityList, false, false); -#else -#if FEATURE_CORECLR if (checkHost) { foreach (String demandPath in securityList) @@ -244,27 +190,11 @@ namespace System.IO { state.EnsureState(); } } -#else - FileIOPermission.QuickDemand(FileIOPermissionAccess.Write, securityList, false, false); -#endif -#endif //FEATURE_MACL } // If we were passed a DirectorySecurity, convert it to a security // descriptor and set it in he call to CreateDirectory. Win32Native.SECURITY_ATTRIBUTES secAttrs = null; -#if FEATURE_MACL - if (dirSecurity != null) { - secAttrs = new Win32Native.SECURITY_ATTRIBUTES(); - secAttrs.nLength = (int)Marshal.SizeOf(secAttrs); - - // For ACL's, get the security descriptor from the FileSecurity. - byte[] sd = dirSecurity.GetSecurityDescriptorBinaryForm(); - byte * bytesOnStack = stackalloc byte[sd.Length]; - Buffer.Memcpy(bytesOnStack, 0, sd, 0, sd.Length); - secAttrs.pSecurityDescriptor = bytesOnStack; - } -#endif bool r = true; int firstError = 0; @@ -294,15 +224,11 @@ namespace System.IO { firstError = currentError; // Give the user a nice error message, but don't leak path information. try { -#if FEATURE_CORECLR if (checkHost) { FileSecurityState state = new FileSecurityState(FileSecurityStateAccess.PathDiscovery, String.Empty, GetDemandDir(name, true)); state.EnsureState(); } -#else - FileIOPermission.QuickDemand(FileIOPermissionAccess.PathDiscovery, GetDemandDir(name, true)); -#endif // FEATURE_CORECLR errorString = name; } catch(SecurityException) {} @@ -361,16 +287,11 @@ namespace System.IO { String fullPath = Path.GetFullPath(path); String demandPath = GetDemandDir(fullPath, true); -#if FEATURE_CORECLR if (checkHost) { FileSecurityState state = new FileSecurityState(FileSecurityStateAccess.Read, path, demandPath); state.EnsureState(); } -#else - FileIOPermission.QuickDemand(FileIOPermissionAccess.Read, demandPath, false, false); -#endif - return InternalExists(fullPath); } @@ -404,27 +325,6 @@ namespace System.IO { && ((data.fileAttributes & Win32Native.FILE_ATTRIBUTE_DIRECTORY) != 0); } -#if !FEATURE_CORECLR - public static void SetCreationTime(String path,DateTime creationTime) - { - SetCreationTimeUtc(path, creationTime.ToUniversalTime()); - } - - [System.Security.SecuritySafeCritical] // auto-generated - public unsafe static void SetCreationTimeUtc(String path,DateTime creationTimeUtc) - { - using (SafeFileHandle handle = Directory.OpenHandle(path)) { - Win32Native.FILE_TIME fileTime = new Win32Native.FILE_TIME(creationTimeUtc.ToFileTimeUtc()); - bool r = Win32Native.SetFileTime(handle, &fileTime, null, null); - if (!r) - { - int errorCode = Marshal.GetLastWin32Error(); - __Error.WinIOError(errorCode, path); - } - } - } -#endif // !FEATURE_CORECLR - public static DateTime GetCreationTime(String path) { return File.GetCreationTime(path); @@ -435,27 +335,6 @@ namespace System.IO { return File.GetCreationTimeUtc(path); } -#if !FEATURE_CORECLR - public static void SetLastWriteTime(String path,DateTime lastWriteTime) - { - SetLastWriteTimeUtc(path, lastWriteTime.ToUniversalTime()); - } - - [System.Security.SecuritySafeCritical] // auto-generated - public unsafe static void SetLastWriteTimeUtc(String path,DateTime lastWriteTimeUtc) - { - using (SafeFileHandle handle = Directory.OpenHandle(path)) { - Win32Native.FILE_TIME fileTime = new Win32Native.FILE_TIME(lastWriteTimeUtc.ToFileTimeUtc()); - bool r = Win32Native.SetFileTime(handle, null, null, &fileTime); - if (!r) - { - int errorCode = Marshal.GetLastWin32Error(); - __Error.WinIOError(errorCode, path); - } - } - } -#endif // !FEATURE_CORECLR - public static DateTime GetLastWriteTime(String path) { return File.GetLastWriteTime(path); @@ -466,27 +345,6 @@ namespace System.IO { return File.GetLastWriteTimeUtc(path); } -#if !FEATURE_CORECLR - public static void SetLastAccessTime(String path,DateTime lastAccessTime) - { - SetLastAccessTimeUtc(path, lastAccessTime.ToUniversalTime()); - } - - [System.Security.SecuritySafeCritical] // auto-generated - public unsafe static void SetLastAccessTimeUtc(String path,DateTime lastAccessTimeUtc) - { - using (SafeFileHandle handle = Directory.OpenHandle(path)) { - Win32Native.FILE_TIME fileTime = new Win32Native.FILE_TIME(lastAccessTimeUtc.ToFileTimeUtc()); - bool r = Win32Native.SetFileTime(handle, null, &fileTime, null); - if (!r) - { - int errorCode = Marshal.GetLastWin32Error(); - __Error.WinIOError(errorCode, path); - } - } - } -#endif // !FEATURE_CORECLR - public static DateTime GetLastAccessTime(String path) { return File.GetLastAccessTime(path); @@ -495,31 +353,8 @@ namespace System.IO { public static DateTime GetLastAccessTimeUtc(String path) { return File.GetLastAccessTimeUtc(path); - } - -#if FEATURE_MACL - public static DirectorySecurity GetAccessControl(String path) - { - return new DirectorySecurity(path, AccessControlSections.Access | AccessControlSections.Owner | AccessControlSections.Group); } - public static DirectorySecurity GetAccessControl(String path, AccessControlSections includeSections) - { - return new DirectorySecurity(path, includeSections); - } - - [System.Security.SecuritySafeCritical] // auto-generated - public static void SetAccessControl(String path, DirectorySecurity directorySecurity) - { - if (directorySecurity == null) - throw new ArgumentNullException(nameof(directorySecurity)); - Contract.EndContractBlock(); - - String fullPath = Path.GetFullPathInternal(path); - directorySecurity.Persist(fullPath); - } -#endif - // Returns an array of filenames in the DirectoryInfo specified by path public static String[] GetFiles(String path) { @@ -930,13 +765,9 @@ namespace System.IO { string root = fullPath.Substring(0, PathInternal.GetRootLength(fullPath)); string demandPath = GetDemandDir(root, true); -#if FEATURE_CORECLR FileSecurityState state = new FileSecurityState(FileSecurityStateAccess.PathDiscovery, path, demandPath); state.EnsureState(); -#else - FileIOPermission.QuickDemand(FileIOPermissionAccess.PathDiscovery, demandPath, false, false); -#endif - + return root; } @@ -1309,39 +1140,7 @@ namespace System.IO { } } -#if !FEATURE_CORECLR - // WinNT only. Win9x this code will not work. - [System.Security.SecurityCritical] // auto-generated - private static SafeFileHandle OpenHandle(String path) - { - String fullPath = Path.GetFullPathInternal(path); - String root = Path.GetPathRoot(fullPath); - if (root == fullPath && root[1] == Path.VolumeSeparatorChar) - throw new ArgumentException(Environment.GetResourceString("Arg_PathIsVolume")); - -#if !FEATURE_CORECLR - FileIOPermission.QuickDemand(FileIOPermissionAccess.Write, GetDemandDir(fullPath, true), false, false); -#endif - - SafeFileHandle handle = Win32Native.SafeCreateFile ( - fullPath, - GENERIC_WRITE, - (FileShare) (FILE_SHARE_WRITE|FILE_SHARE_DELETE), - null, - FileMode.Open, - FILE_FLAG_BACKUP_SEMANTICS, - IntPtr.Zero - ); - - if (handle.IsInvalid) { - int hr = Marshal.GetLastWin32Error(); - __Error.WinIOError(hr, fullPath); - } - return handle; - } -#endif // !FEATURE_CORECLR - - private const int FILE_ATTRIBUTE_DIRECTORY = 0x00000010; + private const int FILE_ATTRIBUTE_DIRECTORY = 0x00000010; private const int GENERIC_WRITE = unchecked((int)0x40000000); private const int FILE_SHARE_WRITE = 0x00000002; private const int FILE_SHARE_DELETE = 0x00000004; diff --git a/src/coreclr/src/mscorlib/src/System/IO/DirectoryInfo.cs b/src/coreclr/src/mscorlib/src/System/IO/DirectoryInfo.cs index d29ab57..9597382 100644 --- a/src/coreclr/src/mscorlib/src/System/IO/DirectoryInfo.cs +++ b/src/coreclr/src/mscorlib/src/System/IO/DirectoryInfo.cs @@ -19,9 +19,6 @@ using System; using System.Collections; using System.Collections.Generic; using System.Security; -#if FEATURE_MACL -using System.Security.AccessControl; -#endif using System.Security.Permissions; using Microsoft.Win32; using System.Text; @@ -31,14 +28,15 @@ using System.Runtime.Serialization; using System.Runtime.Versioning; using System.Diagnostics.Contracts; -namespace System.IO { +namespace System.IO +{ [Serializable] [ComVisible(true)] - public sealed class DirectoryInfo : FileSystemInfo { + public sealed class DirectoryInfo : FileSystemInfo + { private String[] demandDir; -#if FEATURE_CORECLR - // Migrating InheritanceDemands requires this default ctor, so we can annotate it. + // Migrating InheritanceDemands requires this default ctor, so we can annotate it. #if FEATURE_CORESYSTEM [System.Security.SecurityCritical] #else @@ -58,7 +56,6 @@ namespace System.IO { di.Init(path, false); return di; } -#endif [System.Security.SecuritySafeCritical] public DirectoryInfo(String path) @@ -87,15 +84,12 @@ namespace System.IO { String fullPath = Path.GetFullPath(path); demandDir = new String[] {Directory.GetDemandDir(fullPath, true)}; -#if FEATURE_CORECLR + if (checkHost) { FileSecurityState state = new FileSecurityState(FileSecurityStateAccess.Read, OriginalPath, fullPath); state.EnsureState(); } -#else - new FileIOPermission(FileIOPermissionAccess.Read, demandDir, false, false ).Demand(); -#endif FullPath = fullPath; DisplayPath = GetDisplayName(OriginalPath, FullPath); @@ -118,23 +112,15 @@ namespace System.IO { [System.Security.SecurityCritical] // auto-generated private DirectoryInfo(SerializationInfo info, StreamingContext context) : base(info, context) { -#if !FEATURE_CORECLR - demandDir = new String[] {Directory.GetDemandDir(FullPath, true)}; - new FileIOPermission(FileIOPermissionAccess.Read, demandDir, false, false ).Demand(); -#endif DisplayPath = GetDisplayName(OriginalPath, FullPath); } - public override String Name { + public override String Name + { get { -#if FEATURE_CORECLR // DisplayPath is dir name for coreclr return DisplayPath; -#else - // Return just dir name - return GetDirName(FullPath); -#endif } } @@ -161,10 +147,7 @@ namespace System.IO { } } - -#if FEATURE_CORECLR [System.Security.SecuritySafeCritical] -#endif public DirectoryInfo CreateSubdirectory(String path) { if (path == null) throw new ArgumentNullException(nameof(path)); @@ -173,16 +156,7 @@ namespace System.IO { return CreateSubdirectory(path, null); } -#if FEATURE_MACL - [System.Security.SecuritySafeCritical] // auto-generated - public DirectoryInfo CreateSubdirectory(String path, DirectorySecurity directorySecurity) - { - return CreateSubdirectoryHelper(path, directorySecurity); - } -#else // FEATURE_MACL - #if FEATURE_CORECLR [System.Security.SecurityCritical] // auto-generated - #endif public DirectoryInfo CreateSubdirectory(String path, Object directorySecurity) { if (path == null) @@ -191,7 +165,6 @@ namespace System.IO { return CreateSubdirectoryHelper(path, directorySecurity); } -#endif // FEATURE_MACL [System.Security.SecurityCritical] // auto-generated private DirectoryInfo CreateSubdirectoryHelper(String path, Object directorySecurity) @@ -208,12 +181,8 @@ namespace System.IO { // Ensure we have permission to create this subdirectory. String demandDirForCreation = Directory.GetDemandDir(fullPath, true); -#if FEATURE_CORECLR FileSecurityState state = new FileSecurityState(FileSecurityStateAccess.Write, OriginalPath, demandDirForCreation); state.EnsureState(); -#else - new FileIOPermission(FileIOPermissionAccess.Write, new String[] { demandDirForCreation }, false, false).Demand(); -#endif Directory.InternalCreateDirectory(fullPath, path, directorySecurity); @@ -226,13 +195,6 @@ namespace System.IO { Directory.InternalCreateDirectory(FullPath, OriginalPath, null, true); } -#if FEATURE_MACL - public void Create(DirectorySecurity directorySecurity) - { - Directory.InternalCreateDirectory(FullPath, OriginalPath, directorySecurity, true); - } -#endif - // Tests if the given path refers to an existing DirectoryInfo on disk. // // Your application must have Read permission to the directory's @@ -257,23 +219,6 @@ namespace System.IO { } } } - -#if FEATURE_MACL - public DirectorySecurity GetAccessControl() - { - return Directory.GetAccessControl(FullPath, AccessControlSections.Access | AccessControlSections.Owner | AccessControlSections.Group); - } - - public DirectorySecurity GetAccessControl(AccessControlSections includeSections) - { - return Directory.GetAccessControl(FullPath, includeSections); - } - - public void SetAccessControl(DirectorySecurity directorySecurity) - { - Directory.SetAccessControl(FullPath, directorySecurity); - } -#endif // Returns an array of Files in the current DirectoryInfo matching the // given search criteria (ie, "*.txt"). diff --git a/src/coreclr/src/mscorlib/src/System/IO/File.cs b/src/coreclr/src/mscorlib/src/System/IO/File.cs index ce70220..c4b7c68 100644 --- a/src/coreclr/src/mscorlib/src/System/IO/File.cs +++ b/src/coreclr/src/mscorlib/src/System/IO/File.cs @@ -14,23 +14,17 @@ ** ===========================================================*/ -using System; using System.Security.Permissions; -using PermissionSet = System.Security.PermissionSet; using Win32Native = Microsoft.Win32.Win32Native; using System.Runtime.InteropServices; using System.Security; -#if FEATURE_MACL -using System.Security.AccessControl; -#endif using System.Text; using Microsoft.Win32.SafeHandles; using System.Collections.Generic; -using System.Globalization; -using System.Runtime.Versioning; using System.Diagnostics.Contracts; - -namespace System.IO { + +namespace System.IO +{ // Class for creating FileStream objects, and some basic file management // routines such as Delete, etc. [ComVisible(true)] @@ -133,7 +127,8 @@ namespace System.IO { /// Note: This returns the fully qualified name of the destination file. /// [System.Security.SecuritySafeCritical] - internal static String InternalCopy(String sourceFileName, String destFileName, bool overwrite, bool checkHost) { + internal static String InternalCopy(String sourceFileName, String destFileName, bool overwrite, bool checkHost) + { Contract.Requires(sourceFileName != null); Contract.Requires(destFileName != null); Contract.Requires(sourceFileName.Length > 0); @@ -141,19 +136,14 @@ namespace System.IO { String fullSourceFileName = Path.GetFullPath(sourceFileName); String fullDestFileName = Path.GetFullPath(destFileName); - -#if FEATURE_CORECLR + if (checkHost) { FileSecurityState sourceState = new FileSecurityState(FileSecurityStateAccess.Read, sourceFileName, fullSourceFileName); FileSecurityState destState = new FileSecurityState(FileSecurityStateAccess.Write, destFileName, fullDestFileName); sourceState.EnsureState(); destState.EnsureState(); } -#else - FileIOPermission.QuickDemand(FileIOPermissionAccess.Read, fullSourceFileName, false, false); - FileIOPermission.QuickDemand(FileIOPermissionAccess.Write, fullDestFileName, false, false); -#endif - + bool r = Win32Native.CopyFile(fullSourceFileName, fullDestFileName, !overwrite); if (!r) { // Save Win32 error because subsequent checks will overwrite this HRESULT. @@ -161,16 +151,6 @@ namespace System.IO { String fileName = destFileName; if (errorCode != Win32Native.ERROR_FILE_EXISTS) { -#if !FEATURE_CORECLR - // For a number of error codes (sharing violation, path - // not found, etc) we don't know if the problem was with - // the source or dest file. Try reading the source file. - using(SafeFileHandle handle = Win32Native.UnsafeCreateFile(fullSourceFileName, GENERIC_READ, FileShare.Read, null, FileMode.Open, 0, IntPtr.Zero)) { - if (handle.IsInvalid) - fileName = sourceFileName; - } -#endif // !FEATURE_CORECLR - if (errorCode == Win32Native.ERROR_ACCESS_DENIED) { if (Directory.InternalExists(fullDestFileName)) throw new IOException(Environment.GetResourceString("Arg_FileIsDirectory_Name", destFileName), Win32Native.ERROR_ACCESS_DENIED, fullDestFileName); @@ -213,13 +193,6 @@ namespace System.IO { FileShare.None, bufferSize, options); } -#if FEATURE_MACL - public static FileStream Create(String path, int bufferSize, FileOptions options, FileSecurity fileSecurity) { - return new FileStream(path, FileMode.Create, FileSystemRights.Read | FileSystemRights.Write, - FileShare.None, bufferSize, options, fileSecurity); - } -#endif - // Deletes a file. The file specified by the designated path is deleted. // If the file does not exist, Delete succeeds without throwing // an exception. @@ -253,17 +226,12 @@ namespace System.IO { { String fullPath = Path.GetFullPath(path); -#if FEATURE_CORECLR if (checkHost) { FileSecurityState state = new FileSecurityState(FileSecurityStateAccess.Write, path, fullPath); state.EnsureState(); } -#else - // For security check, path should be resolved to an absolute path. - FileIOPermission.QuickDemand(FileIOPermissionAccess.Write, fullPath, false, false); -#endif bool r = Win32Native.DeleteFile(fullPath); if (!r) { int hr = Marshal.GetLastWin32Error(); @@ -404,28 +372,6 @@ namespace System.IO { return new FileStream(path, mode, access, share); } -#if !FEATURE_CORECLR - public static void SetCreationTime(String path, DateTime creationTime) - { - SetCreationTimeUtc(path, creationTime.ToUniversalTime()); - } - - [System.Security.SecuritySafeCritical] // auto-generated - public unsafe static void SetCreationTimeUtc(String path, DateTime creationTimeUtc) - { - SafeFileHandle handle; - using(OpenFile(path, FileAccess.Write, out handle)) { - Win32Native.FILE_TIME fileTime = new Win32Native.FILE_TIME(creationTimeUtc.ToFileTimeUtc()); - bool r = Win32Native.SetFileTime(handle, &fileTime, null, null); - if (!r) - { - int errorCode = Marshal.GetLastWin32Error(); - __Error.WinIOError(errorCode, path); - } - } - } -#endif // !FEATURE_CORECLR - [System.Security.SecuritySafeCritical] public static DateTime GetCreationTime(String path) { @@ -442,15 +388,12 @@ namespace System.IO { private static DateTime InternalGetCreationTimeUtc(String path, bool checkHost) { String fullPath = Path.GetFullPath(path); -#if FEATURE_CORECLR + if (checkHost) { FileSecurityState state = new FileSecurityState(FileSecurityStateAccess.Read, path, fullPath); state.EnsureState(); } -#else - FileIOPermission.QuickDemand(FileIOPermissionAccess.Read, fullPath, false, false); -#endif Win32Native.WIN32_FILE_ATTRIBUTE_DATA data = new Win32Native.WIN32_FILE_ATTRIBUTE_DATA(); int dataInitialised = FillAttributeInfo(fullPath, ref data, false, false); @@ -461,28 +404,6 @@ namespace System.IO { return DateTime.FromFileTimeUtc(dt); } -#if !FEATURE_CORECLR - public static void SetLastAccessTime(String path, DateTime lastAccessTime) - { - SetLastAccessTimeUtc(path, lastAccessTime.ToUniversalTime()); - } - - [System.Security.SecuritySafeCritical] // auto-generated - public unsafe static void SetLastAccessTimeUtc(String path, DateTime lastAccessTimeUtc) - { - SafeFileHandle handle; - using(OpenFile(path, FileAccess.Write, out handle)) { - Win32Native.FILE_TIME fileTime = new Win32Native.FILE_TIME(lastAccessTimeUtc.ToFileTimeUtc()); - bool r = Win32Native.SetFileTime(handle, null, &fileTime, null); - if (!r) - { - int errorCode = Marshal.GetLastWin32Error(); - __Error.WinIOError(errorCode, path); - } - } - } -#endif // FEATURE_CORECLR - [System.Security.SecuritySafeCritical] public static DateTime GetLastAccessTime(String path) { @@ -497,17 +418,14 @@ namespace System.IO { [System.Security.SecurityCritical] private static DateTime InternalGetLastAccessTimeUtc(String path, bool checkHost) - { + { String fullPath = Path.GetFullPath(path); -#if FEATURE_CORECLR + if (checkHost) { FileSecurityState state = new FileSecurityState(FileSecurityStateAccess.Read, path, fullPath); state.EnsureState(); } -#else - FileIOPermission.QuickDemand(FileIOPermissionAccess.Read, fullPath, false, false); -#endif Win32Native.WIN32_FILE_ATTRIBUTE_DATA data = new Win32Native.WIN32_FILE_ATTRIBUTE_DATA(); int dataInitialised = FillAttributeInfo(fullPath, ref data, false, false); @@ -518,28 +436,6 @@ namespace System.IO { return DateTime.FromFileTimeUtc(dt); } -#if !FEATURE_CORECLR - public static void SetLastWriteTime(String path, DateTime lastWriteTime) - { - SetLastWriteTimeUtc(path, lastWriteTime.ToUniversalTime()); - } - - [System.Security.SecuritySafeCritical] // auto-generated - public unsafe static void SetLastWriteTimeUtc(String path, DateTime lastWriteTimeUtc) - { - SafeFileHandle handle; - using(OpenFile(path, FileAccess.Write, out handle)) { - Win32Native.FILE_TIME fileTime = new Win32Native.FILE_TIME(lastWriteTimeUtc.ToFileTimeUtc()); - bool r = Win32Native.SetFileTime(handle, null, null, &fileTime); - if (!r) - { - int errorCode = Marshal.GetLastWin32Error(); - __Error.WinIOError(errorCode, path); - } - } - } -#endif // !FEATURE_CORECLR - [System.Security.SecuritySafeCritical] public static DateTime GetLastWriteTime(String path) { @@ -556,15 +452,12 @@ namespace System.IO { private static DateTime InternalGetLastWriteTimeUtc(String path, bool checkHost) { String fullPath = Path.GetFullPath(path); -#if FEATURE_CORECLR + if (checkHost) { FileSecurityState state = new FileSecurityState(FileSecurityStateAccess.Read, path, fullPath); state.EnsureState(); } -#else - FileIOPermission.QuickDemand(FileIOPermissionAccess.Read, fullPath, false, false); -#endif Win32Native.WIN32_FILE_ATTRIBUTE_DATA data = new Win32Native.WIN32_FILE_ATTRIBUTE_DATA(); int dataInitialised = FillAttributeInfo(fullPath, ref data, false, false); @@ -579,12 +472,9 @@ namespace System.IO { public static FileAttributes GetAttributes(String path) { String fullPath = Path.GetFullPath(path); -#if FEATURE_CORECLR + FileSecurityState state = new FileSecurityState(FileSecurityStateAccess.Read, path, fullPath); state.EnsureState(); -#else - FileIOPermission.QuickDemand(FileIOPermissionAccess.Read, fullPath, false, false); -#endif Win32Native.WIN32_FILE_ATTRIBUTE_DATA data = new Win32Native.WIN32_FILE_ATTRIBUTE_DATA(); int dataInitialised = FillAttributeInfo(fullPath, ref data, false, true); @@ -594,17 +484,10 @@ namespace System.IO { return (FileAttributes) data.fileAttributes; } -#if FEATURE_CORECLR [System.Security.SecurityCritical] -#else - [System.Security.SecuritySafeCritical] -#endif public static void SetAttributes(String path, FileAttributes fileAttributes) { String fullPath = Path.GetFullPath(path); -#if !FEATURE_CORECLR - FileIOPermission.QuickDemand(FileIOPermissionAccess.Write, fullPath, false, false); -#endif bool r = Win32Native.SetFileAttributes(fullPath, (int) fileAttributes); if (!r) { int hr = Marshal.GetLastWin32Error(); @@ -614,31 +497,6 @@ namespace System.IO { } } -#if FEATURE_MACL - public static FileSecurity GetAccessControl(String path) - { - return GetAccessControl(path, AccessControlSections.Access | AccessControlSections.Owner | AccessControlSections.Group); - } - - public static FileSecurity GetAccessControl(String path, AccessControlSections includeSections) - { - // Appropriate security check should be done for us by FileSecurity. - return new FileSecurity(path, includeSections); - } - - [System.Security.SecuritySafeCritical] // auto-generated - public static void SetAccessControl(String path, FileSecurity fileSecurity) - { - if (fileSecurity == null) - throw new ArgumentNullException(nameof(fileSecurity)); - Contract.EndContractBlock(); - - String fullPath = Path.GetFullPath(path); - // Appropriate security check should be done for us by FileSecurity. - fileSecurity.Persist(fullPath); - } -#endif - public static FileStream OpenRead(String path) { return new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read); } @@ -1055,17 +913,12 @@ namespace System.IO { String fullSourceFileName = Path.GetFullPath(sourceFileName); String fullDestFileName = Path.GetFullPath(destFileName); -#if FEATURE_CORECLR if (checkHost) { FileSecurityState sourceState = new FileSecurityState(FileSecurityStateAccess.Write | FileSecurityStateAccess.Read, sourceFileName, fullSourceFileName); FileSecurityState destState = new FileSecurityState(FileSecurityStateAccess.Write, destFileName, fullDestFileName); sourceState.EnsureState(); destState.EnsureState(); } -#else - FileIOPermission.QuickDemand(FileIOPermissionAccess.Write | FileIOPermissionAccess.Read, fullSourceFileName, false, false); - FileIOPermission.QuickDemand(FileIOPermissionAccess.Write, fullDestFileName, false, false); -#endif if (!InternalExists(fullSourceFileName)) __Error.WinIOError(Win32Native.ERROR_FILE_NOT_FOUND, fullSourceFileName); @@ -1113,19 +966,12 @@ namespace System.IO { if (destinationBackupFileName != null) fullBackupPath = Path.GetFullPath(destinationBackupFileName); -#if FEATURE_CORECLR FileSecurityState sourceState = new FileSecurityState(FileSecurityStateAccess.Read | FileSecurityStateAccess.Write, sourceFileName, fullSrcPath); FileSecurityState destState = new FileSecurityState(FileSecurityStateAccess.Read | FileSecurityStateAccess.Write, destinationFileName, fullDestPath); FileSecurityState backupState = new FileSecurityState(FileSecurityStateAccess.Read | FileSecurityStateAccess.Write, destinationBackupFileName, fullBackupPath); sourceState.EnsureState(); destState.EnsureState(); backupState.EnsureState(); -#else - FileIOPermission perm = new FileIOPermission(FileIOPermissionAccess.Read | FileIOPermissionAccess.Write, new String[] { fullSrcPath, fullDestPath}); - if (destinationBackupFileName != null) - perm.AddPathList(FileIOPermissionAccess.Write, fullBackupPath); - perm.Demand(); -#endif int flags = Win32Native.REPLACEFILE_WRITE_THROUGH; if (ignoreMetadataErrors) @@ -1236,35 +1082,8 @@ namespace System.IO { return dataInitialised; } -#if !FEATURE_CORECLR - [System.Security.SecurityCritical] // auto-generated - private static FileStream OpenFile(String path, FileAccess access, out SafeFileHandle handle) - { - FileStream fs = new FileStream(path, FileMode.Open, access, FileShare.ReadWrite, 1); - handle = fs.SafeFileHandle; - - if (handle.IsInvalid) { - // Return a meaningful error, using the RELATIVE path to - // the file to avoid returning extra information to the caller. - - // NT5 oddity - when trying to open "C:\" as a FileStream, - // we usually get ERROR_PATH_NOT_FOUND from the OS. We should - // probably be consistent w/ every other directory. - int hr = Marshal.GetLastWin32Error(); - String FullPath = Path.GetFullPath(path); - if (hr==__Error.ERROR_PATH_NOT_FOUND && FullPath.Equals(Directory.GetDirectoryRoot(FullPath))) - hr = __Error.ERROR_ACCESS_DENIED; - - - __Error.WinIOError(hr, path); - } - return fs; - } -#endif // !FEATURE_CORECLR - - - // Defined in WinError.h + // Defined in WinError.h private const int ERROR_INVALID_PARAMETER = 87; - private const int ERROR_ACCESS_DENIED = 0x5; + private const int ERROR_ACCESS_DENIED = 0x5; } } diff --git a/src/coreclr/src/mscorlib/src/System/IO/FileAttributes.cs b/src/coreclr/src/mscorlib/src/System/IO/FileAttributes.cs index 19d5f22..51ef597 100644 --- a/src/coreclr/src/mscorlib/src/System/IO/FileAttributes.cs +++ b/src/coreclr/src/mscorlib/src/System/IO/FileAttributes.cs @@ -11,13 +11,13 @@ ===========================================================*/ using System; -namespace System.IO { +namespace System.IO +{ // File attributes for use with the FileEnumerator class. // These constants correspond to the constants in WinNT.h. - // -[Serializable] + [Serializable] [Flags] -[System.Runtime.InteropServices.ComVisible(true)] + [System.Runtime.InteropServices.ComVisible(true)] public enum FileAttributes { // From WinNT.h (FILE_ATTRIBUTE_XXX) @@ -35,17 +35,5 @@ namespace System.IO { Offline = 0x1000, NotContentIndexed = 0x2000, Encrypted = 0x4000, - -#if !FEATURE_CORECLR -#if FEATURE_COMINTEROP - [System.Runtime.InteropServices.ComVisible(false)] -#endif // FEATURE_COMINTEROP - IntegrityStream = 0x8000, - -#if FEATURE_COMINTEROP - [System.Runtime.InteropServices.ComVisible(false)] -#endif // FEATURE_COMINTEROP - NoScrubData = 0x20000, -#endif } } diff --git a/src/coreclr/src/mscorlib/src/System/IO/FileInfo.cs b/src/coreclr/src/mscorlib/src/System/IO/FileInfo.cs index 60a7b35..5641951 100644 --- a/src/coreclr/src/mscorlib/src/System/IO/FileInfo.cs +++ b/src/coreclr/src/mscorlib/src/System/IO/FileInfo.cs @@ -15,9 +15,6 @@ ===========================================================*/ using System; -#if FEATURE_MACL -using System.Security.AccessControl; -#endif using System.Security.Permissions; using PermissionSet = System.Security.PermissionSet; using Win32Native = Microsoft.Win32.Win32Native; @@ -28,7 +25,8 @@ using System.Globalization; using System.Runtime.Versioning; using System.Diagnostics.Contracts; -namespace System.IO { +namespace System.IO +{ // Class for creating FileStream objects, and some basic file management // routines such as Delete, etc. [Serializable] @@ -37,7 +35,6 @@ namespace System.IO { { private String _name; -#if FEATURE_CORECLR // Migrating InheritanceDemands requires this default ctor, so we can annotate it. #if FEATURE_CORESYSTEM [System.Security.SecurityCritical] @@ -57,7 +54,6 @@ namespace System.IO { fi.Init(fileName, false); return fi; } -#endif [System.Security.SecuritySafeCritical] public FileInfo(String fileName) @@ -75,15 +71,12 @@ namespace System.IO { OriginalPath = fileName; // Must fully qualify the path for the security check String fullPath = Path.GetFullPath(fileName); -#if FEATURE_CORECLR + if (checkHost) { FileSecurityState state = new FileSecurityState(FileSecurityStateAccess.Read, fileName, fullPath); state.EnsureState(); } -#else - FileIOPermission.QuickDemand(FileIOPermissionAccess.Read, fullPath, false, false); -#endif _name = Path.GetFileName(fileName); FullPath = fullPath; @@ -92,20 +85,12 @@ namespace System.IO { private String GetDisplayPath(String originalPath) { -#if FEATURE_CORECLR return Path.GetFileName(originalPath); -#else - return originalPath; -#endif - } [System.Security.SecurityCritical] // auto-generated private FileInfo(SerializationInfo info, StreamingContext context) : base(info, context) { -#if !FEATURE_CORECLR - new FileIOPermission(FileIOPermissionAccess.Read, new String[] { FullPath }, false, false).Demand(); -#endif _name = Path.GetFileName(OriginalPath); DisplayPath = GetDisplayPath(OriginalPath); } @@ -125,8 +110,7 @@ namespace System.IO { public override String Name { get { return _name; } } - - + public long Length { [System.Security.SecuritySafeCritical] // auto-generated get { @@ -152,12 +136,8 @@ namespace System.IO { String directoryName = Path.GetDirectoryName(FullPath); if (directoryName != null) { -#if FEATURE_CORECLR FileSecurityState state = new FileSecurityState(FileSecurityStateAccess.Read, DisplayPath, FullPath); state.EnsureState(); -#else - new FileIOPermission(FileIOPermissionAccess.PathDiscovery, new String[] { directoryName }, false, false).Demand(); -#endif } return directoryName; } @@ -171,7 +151,7 @@ namespace System.IO { String dirName = DirectoryName; if (dirName == null) return null; - return new DirectoryInfo(dirName); + return new DirectoryInfo(dirName); } } @@ -187,23 +167,6 @@ namespace System.IO { } } -#if FEATURE_MACL - public FileSecurity GetAccessControl() - { - return File.GetAccessControl(FullPath, AccessControlSections.Access | AccessControlSections.Owner | AccessControlSections.Group); - } - - public FileSecurity GetAccessControl(AccessControlSections includeSections) - { - return File.GetAccessControl(FullPath, includeSections); - } - - public void SetAccessControl(FileSecurity fileSecurity) - { - File.SetAccessControl(FullPath, fileSecurity); - } -#endif - [System.Security.SecuritySafeCritical] // auto-generated public StreamReader OpenText() { @@ -279,13 +242,8 @@ namespace System.IO { [System.Security.SecuritySafeCritical] public override void Delete() { -#if FEATURE_CORECLR FileSecurityState state = new FileSecurityState(FileSecurityStateAccess.Write, DisplayPath, FullPath); state.EnsureState(); -#else - // For security check, path should be resolved to an absolute path. - new FileIOPermission(FileIOPermissionAccess.Write, new String[] { FullPath }, false, false).Demand(); -#endif bool r = Win32Native.DeleteFile(FullPath); if (!r) { @@ -335,9 +293,6 @@ namespace System.IO { } } - - - // User must explicitly specify opening a new file or appending to one. public FileStream Open(FileMode mode) { return Open(mode, FileAccess.ReadWrite, FileShare.None); @@ -351,27 +306,18 @@ namespace System.IO { return new FileStream(FullPath, mode, access, share); } - -#if FEATURE_CORECLR [System.Security.SecuritySafeCritical] // auto-generated -#endif public FileStream OpenRead() { return new FileStream(FullPath, FileMode.Open, FileAccess.Read, FileShare.Read, 4096, false); } - public FileStream OpenWrite() { return new FileStream(FullPath, FileMode.OpenOrCreate, FileAccess.Write, FileShare.None); } - - - - - // Moves a given file to a new location and potentially a new file name. // This method does work across volumes. // @@ -389,16 +335,12 @@ namespace System.IO { Contract.EndContractBlock(); string fullDestFileName = Path.GetFullPath(destFileName); -#if FEATURE_CORECLR + FileSecurityState sourceState = new FileSecurityState(FileSecurityStateAccess.Write | FileSecurityStateAccess.Read, DisplayPath, FullPath); FileSecurityState destState = new FileSecurityState(FileSecurityStateAccess.Write, destFileName, fullDestFileName); sourceState.EnsureState(); destState.EnsureState(); -#else - new FileIOPermission(FileIOPermissionAccess.Write | FileIOPermissionAccess.Read, new String[] { FullPath }, false, false).Demand(); - FileIOPermission.QuickDemand(FileIOPermissionAccess.Write, fullDestFileName, false, false); -#endif - + if (!Win32Native.MoveFile(FullPath, fullDestFileName)) __Error.WinIOError(); FullPath = fullDestFileName; diff --git a/src/coreclr/src/mscorlib/src/System/IO/FileSystemInfo.cs b/src/coreclr/src/mscorlib/src/System/IO/FileSystemInfo.cs index fe39b2d..f088235 100644 --- a/src/coreclr/src/mscorlib/src/System/IO/FileSystemInfo.cs +++ b/src/coreclr/src/mscorlib/src/System/IO/FileSystemInfo.cs @@ -2,17 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -/*============================================================ -** -** -** -** -** -** Purpose: -** -** -===========================================================*/ - using System; using System.Collections; using System.Security; @@ -24,13 +13,11 @@ using System.Runtime.Serialization; using System.Runtime.Versioning; using System.Diagnostics.Contracts; -namespace System.IO { +namespace System.IO +{ #if FEATURE_SERIALIZATION [Serializable] #endif -#if !FEATURE_CORECLR - [FileIOPermissionAttribute(SecurityAction.InheritanceDemand,Unrestricted=true)] -#endif [ComVisible(true)] public abstract class FileSystemInfo : MarshalByRefObject, ISerializable { @@ -47,13 +34,11 @@ namespace System.IO { protected String OriginalPath; // path passed in by the user private String _displayPath = ""; // path that can be displayed to the user -#if FEATURE_CORECLR #if FEATURE_CORESYSTEM [System.Security.SecurityCritical] #else [System.Security.SecuritySafeCritical] #endif //FEATURE_CORESYSTEM -#endif protected FileSystemInfo() { } @@ -91,12 +76,9 @@ namespace System.IO { demandDir = Directory.GetDemandDir(FullPath, true); else demandDir = FullPath; -#if FEATURE_CORECLR + FileSecurityState sourceState = new FileSecurityState(FileSecurityStateAccess.PathDiscovery, String.Empty, demandDir); sourceState.EnsureState(); -#else - new FileIOPermission(FileIOPermissionAccess.PathDiscovery, demandDir).Demand(); -#endif return FullPath; } } @@ -111,9 +93,6 @@ namespace System.IO { demandDir = Directory.GetDemandDir(FullPath, true); else demandDir = FullPath; -#if !FEATURE_CORECLR - new FileIOPermission(FileIOPermissionAccess.PathDiscovery, demandDir).Demand(); -#endif return FullPath; } } @@ -156,23 +135,16 @@ namespace System.IO { // depends on the security check in get_CreationTimeUtc return CreationTimeUtc.ToLocalTime(); } -#if !FEATURE_CORECLR - set - { - CreationTimeUtc = value.ToUniversalTime(); - } -#endif // !FEATURE_CORECLR } [ComVisible(false)] public DateTime CreationTimeUtc { [System.Security.SecuritySafeCritical] get { -#if FEATURE_CORECLR // get_CreationTime also depends on this security check FileSecurityState sourceState = new FileSecurityState(FileSecurityStateAccess.Read, String.Empty, FullPath); sourceState.EnsureState(); -#endif + if (_dataInitialised == -1) { _data = new Win32Native.WIN32_FILE_ATTRIBUTE_DATA(); Refresh(); @@ -185,18 +157,8 @@ namespace System.IO { return DateTime.FromFileTimeUtc(fileTime); } -#if !FEATURE_CORECLR - set { - if (this is DirectoryInfo) - Directory.SetCreationTimeUtc(FullPath,value); - else - File.SetCreationTimeUtc(FullPath,value); - _dataInitialised = -1; - } -#endif // !FEATURE_CORECLR } - public DateTime LastAccessTime { get { @@ -212,11 +174,10 @@ namespace System.IO { public DateTime LastAccessTimeUtc { [System.Security.SecuritySafeCritical] get { -#if FEATURE_CORECLR // get_LastAccessTime also depends on this security check FileSecurityState sourceState = new FileSecurityState(FileSecurityStateAccess.Read, String.Empty, FullPath); sourceState.EnsureState(); -#endif + if (_dataInitialised == -1) { _data = new Win32Native.WIN32_FILE_ATTRIBUTE_DATA(); Refresh(); @@ -231,13 +192,6 @@ namespace System.IO { } set { -#if !FEATURE_CORECLR - if (this is DirectoryInfo) - Directory.SetLastAccessTimeUtc(FullPath,value); - else - File.SetLastAccessTimeUtc(FullPath,value); - _dataInitialised = -1; -#endif // !FEATURE_CORECLR } } @@ -257,11 +211,9 @@ namespace System.IO { public DateTime LastWriteTimeUtc { [System.Security.SecuritySafeCritical] get { -#if FEATURE_CORECLR // get_LastWriteTime also depends on this security check FileSecurityState sourceState = new FileSecurityState(FileSecurityStateAccess.Read, String.Empty, FullPath); sourceState.EnsureState(); -#endif if (_dataInitialised == -1) { _data = new Win32Native.WIN32_FILE_ATTRIBUTE_DATA(); Refresh(); @@ -276,13 +228,6 @@ namespace System.IO { } set { -#if !FEATURE_CORECLR - if (this is DirectoryInfo) - Directory.SetLastWriteTimeUtc(FullPath,value); - else - File.SetLastWriteTimeUtc(FullPath,value); - _dataInitialised = -1; -#endif // !FEATURE_CORECLR } } @@ -296,10 +241,9 @@ namespace System.IO { [System.Security.SecuritySafeCritical] get { -#if FEATURE_CORECLR FileSecurityState sourceState = new FileSecurityState(FileSecurityStateAccess.Read, String.Empty, FullPath); sourceState.EnsureState(); -#endif + if (_dataInitialised == -1) { _data = new Win32Native.WIN32_FILE_ATTRIBUTE_DATA(); Refresh(); // Call refresh to intialise the data @@ -310,15 +254,9 @@ namespace System.IO { return (FileAttributes) _data.fileAttributes; } -#if FEATURE_CORECLR + [System.Security.SecurityCritical] // auto-generated -#else - [System.Security.SecuritySafeCritical] -#endif set { -#if !FEATURE_CORECLR - new FileIOPermission(FileIOPermissionAccess.Write, FullPath).Demand(); -#endif bool r = Win32Native.SetFileAttributes(FullPath, (int) value); if (!r) { int hr = Marshal.GetLastWin32Error(); @@ -341,10 +279,6 @@ namespace System.IO { [ComVisible(false)] public virtual void GetObjectData(SerializationInfo info, StreamingContext context) { -#if !FEATURE_CORECLR - new FileIOPermission(FileIOPermissionAccess.PathDiscovery, FullPath).Demand(); -#endif - info.AddValue("OriginalPath", OriginalPath, typeof(String)); info.AddValue("FullPath", FullPath, typeof(String)); } diff --git a/src/coreclr/src/mscorlib/src/System/IO/__Error.cs b/src/coreclr/src/mscorlib/src/System/IO/__Error.cs index c67bc96..af9c502 100644 --- a/src/coreclr/src/mscorlib/src/System/IO/__Error.cs +++ b/src/coreclr/src/mscorlib/src/System/IO/__Error.cs @@ -97,9 +97,6 @@ namespace System.IO { bool safeToReturn = false; try { if (!isInvalidPath) { -#if !FEATURE_CORECLR - new FileIOPermission(FileIOPermissionAccess.PathDiscovery, new String[] { path }, false, false).Demand(); -#endif safeToReturn = true; } } diff --git a/src/coreclr/src/mscorlib/src/System/InvalidTimeZoneException.cs b/src/coreclr/src/mscorlib/src/System/InvalidTimeZoneException.cs index 2c57bc8..f334754 100644 --- a/src/coreclr/src/mscorlib/src/System/InvalidTimeZoneException.cs +++ b/src/coreclr/src/mscorlib/src/System/InvalidTimeZoneException.cs @@ -2,16 +2,14 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -namespace System { - using System.Runtime.Serialization; - using System.Runtime.CompilerServices; +using System.Runtime.Serialization; +namespace System +{ [Serializable] [System.Security.Permissions.HostProtection(MayLeakOnAbort = true)] -#if !FEATURE_CORECLR - [TypeForwardedFrom("System.Core, Version=3.5.0.0, Culture=Neutral, PublicKeyToken=b77a5c561934e089")] -#endif - public class InvalidTimeZoneException : Exception { + public class InvalidTimeZoneException : Exception + { public InvalidTimeZoneException(String message) : base(message) { } diff --git a/src/coreclr/src/mscorlib/src/System/MarshalByRefObject.cs b/src/coreclr/src/mscorlib/src/System/MarshalByRefObject.cs index 8b6a843..53ebda7 100644 --- a/src/coreclr/src/mscorlib/src/System/MarshalByRefObject.cs +++ b/src/coreclr/src/mscorlib/src/System/MarshalByRefObject.cs @@ -13,249 +13,12 @@ ** ** ===========================================================*/ -namespace System { - - using System; - using System.Security; - using System.Security.Permissions; - using System.Threading; - using System.Runtime.Remoting; -#if FEATURE_REMOTING - using System.Runtime.Remoting.Lifetime; - using System.Runtime.Remoting.Services; -#endif - using System.Runtime.InteropServices; - using System.Reflection; - using System.Runtime.CompilerServices; - using System.Runtime.Versioning; - using System.Diagnostics.Contracts; - using CultureInfo = System.Globalization.CultureInfo; - +namespace System +{ [Serializable] -[System.Runtime.InteropServices.ComVisible(true)] + [System.Runtime.InteropServices.ComVisible(true)] public abstract class MarshalByRefObject { -#if FEATURE_REMOTING - private Object __identity; - - private Object Identity { get { return __identity; } set { __identity = value; } } -#if FEATURE_COMINTEROP - [System.Security.SecuritySafeCritical] // auto-generated - internal IntPtr GetComIUnknown(bool fIsBeingMarshalled) - { - IntPtr pUnk; - if(RemotingServices.IsTransparentProxy(this)) - { - pUnk = RemotingServices.GetRealProxy(this).GetCOMIUnknown(fIsBeingMarshalled); - } - else - { - pUnk = Marshal.GetIUnknownForObject(this); - } - return pUnk; - } - - [System.Security.SecurityCritical] // auto-generated - [MethodImplAttribute(MethodImplOptions.InternalCall)] - internal static extern IntPtr GetComIUnknown(MarshalByRefObject o); -#endif // FEATURE_COMINTEROP - - // (1) for remote COM objects IsInstance of can't be executed on - // the proxies, so we need this method to be executed on the - // actual object. - // (2) for remote objects that do not have the complete type information - // we intercept calls to check the type and execute it on the actual - // object - internal bool IsInstanceOfType(Type T) - { - return T.IsInstanceOfType(this); - } - - // for remote COM Objects the late binding methods can't be - // executed on proxies, so we need this method to execute on - // the real object - internal Object InvokeMember(String name,BindingFlags invokeAttr,Binder binder, - Object[] args,ParameterModifier[] modifiers,CultureInfo culture,String[] namedParameters) - { - Type t = GetType(); - - // Sanity check - if(!t.IsCOMObject) - throw new InvalidOperationException(Environment.GetResourceString("Arg_InvokeMember")); - - // Call into the runtime to invoke on the COM object. - return t.InvokeMember(name, invokeAttr, binder, this, args, modifiers, culture, namedParameters); - } - - - // Returns a new cloned MBR instance that is a memberwise copy of this - // with the identity nulled out, so there are no identity conflicts - // when the cloned object is marshalled - protected MarshalByRefObject MemberwiseClone(bool cloneIdentity) - { - MarshalByRefObject mbr = (MarshalByRefObject)base.MemberwiseClone(); - // set the identity on the cloned object to null - if (!cloneIdentity) - mbr.Identity = null; - return mbr; - } - - // A helper routine to extract the identity either from the marshalbyrefobject base - // class if it is not a proxy, otherwise from the real proxy. - // A flag is set to indicate whether the object passed in is a server or a proxy - [System.Security.SecuritySafeCritical] // auto-generated - internal static Identity GetIdentity(MarshalByRefObject obj, out bool fServer) - { - fServer = true; - Identity id = null; - - if(null != obj) - { - if(!RemotingServices.IsTransparentProxy(obj)) - { - id = (Identity)obj.Identity; - } - else - { - // Toggle flag to indicate that we have a proxy - fServer = false; - id = RemotingServices.GetRealProxy(obj).IdentityObject; - } - } - - return id; - } - - // Another helper that delegates to the helper above - internal static Identity GetIdentity(MarshalByRefObject obj) - { - Contract.Assert(!RemotingServices.IsTransparentProxy(obj), "Use this method for server objects only"); - - bool fServer; - return GetIdentity(obj, out fServer); - } - - - internal ServerIdentity __RaceSetServerIdentity(ServerIdentity id) - { - if (__identity == null) - { - // For strictly MBR types, the TP field in the identity - // holds the real server - if (!id.IsContextBound) - { - id.RaceSetTransparentProxy(this); - } - Interlocked.CompareExchange(ref __identity, id, null); - } - return (ServerIdentity)__identity; - } - - - internal void __ResetServerIdentity() - { - __identity = null; - } - - // This method is used return a lifetime service object which - // is used to control the lifetime policy to the object. - // For the default Lifetime service this will be an object of typoe ILease. - // - [System.Security.SecurityCritical] // auto-generated_required - public Object GetLifetimeService() - { - return LifetimeServices.GetLease(this); - } - - // This method is used return lifetime service object. This method - // can be overridden to return a LifetimeService object with properties unique to - // this object. - // For the default Lifetime service this will be an object of type ILease. - // - [System.Security.SecurityCritical] // auto-generated_required - public virtual Object InitializeLifetimeService() - { - return LifetimeServices.GetLeaseInitial(this); - } - - [System.Security.SecurityCritical] // auto-generated_required - public virtual ObjRef CreateObjRef(Type requestedType) - { - if(__identity == null) - { - throw new RemotingException(Environment.GetResourceString( - "Remoting_NoIdentityEntry")); - } - return new ObjRef(this, requestedType); - } - - // This is for casting interop ObjRefLite's. - // ObjRefLite's have been deprecated. These methods are not exposed - // through any user APIs and would be removed in the future - [System.Security.SecuritySafeCritical] // auto-generated - internal bool CanCastToXmlType(String xmlTypeName, String xmlTypeNamespace) - { - Type castType = SoapServices.GetInteropTypeFromXmlType(xmlTypeName, xmlTypeNamespace); - if (castType == null) - { - String typeNamespace; - String assemblyName; - if (!SoapServices.DecodeXmlNamespaceForClrTypeNamespace(xmlTypeNamespace, - out typeNamespace, out assemblyName)) - return false; - - String typeName; - if ((typeNamespace != null) && (typeNamespace.Length > 0)) - typeName = typeNamespace + "." + xmlTypeName; - else - typeName = xmlTypeName; - - try - { - Assembly asm = Assembly.Load(assemblyName); - castType = asm.GetType(typeName, false, false); - } - catch - { - return false; - } - } - - if (castType != null) - return castType.IsAssignableFrom(this.GetType()); - - return false; - } // CanCastToXmlType - - // helper method for calling CanCastToXmlType - // ObjRefLite's have been deprecated. These methods are not exposed - // through any user APIs and would be removed in the future - [System.Security.SecuritySafeCritical] // auto-generated - internal static bool CanCastToXmlTypeHelper(RuntimeType castType, MarshalByRefObject o) - { - if (castType == null) - throw new ArgumentNullException(nameof(castType)); - - Contract.EndContractBlock(); - // MarshalByRefObject's can only be casted to MarshalByRefObject's or interfaces. - if (!castType.IsInterface && !castType.IsMarshalByRef) - return false; - - // figure out xml type name - String xmlTypeName = null; - String xmlTypeNamespace = null; - if (!SoapServices.GetXmlTypeForInteropType(castType, out xmlTypeName, out xmlTypeNamespace)) - { - // There's no registered interop type name, so just use the default. - xmlTypeName = castType.Name; - xmlTypeNamespace = - SoapServices.CodeXmlNamespaceForClrTypeNamespace( - castType.Namespace, castType.GetRuntimeAssembly().GetSimpleName()); - } - - return o.CanCastToXmlType(xmlTypeName, xmlTypeNamespace); - } // CanCastToXmlType -#else protected MarshalByRefObject() { } public object GetLifetimeService() { @@ -270,7 +33,5 @@ namespace System { MarshalByRefObject mbr = (MarshalByRefObject)base.MemberwiseClone(); return mbr; } -#endif // FEATURE_REMOTING - - } -} // namespace + } +} diff --git a/src/coreclr/src/mscorlib/src/System/Object.cs b/src/coreclr/src/mscorlib/src/System/Object.cs index 769c5a6..4fca978 100644 --- a/src/coreclr/src/mscorlib/src/System/Object.cs +++ b/src/coreclr/src/mscorlib/src/System/Object.cs @@ -12,7 +12,8 @@ ** ===========================================================*/ -namespace System { +namespace System +{ using System; using System.Runtime; using System.Runtime.InteropServices; @@ -23,9 +24,7 @@ namespace System { using CultureInfo = System.Globalization.CultureInfo; using FieldInfo = System.Reflection.FieldInfo; using BindingFlags = System.Reflection.BindingFlags; -#if FEATURE_REMOTING - using RemotingException = System.Runtime.Remoting.RemotingException; -#endif + // The Object is the root class for all object in the CLR System. Object // is the super class for all other CLR objects and provide a set of methods and low level // services to subclasses. These services include object synchronization and support for clone @@ -135,26 +134,21 @@ public class Object // Make sure that the value is compatible with the type // of field -#if FEATURE_REMOTING - System.Runtime.Remoting.Messaging.Message.CoerceArg(val, fldInfo.FieldType); -#else Type pt=fldInfo.FieldType; if (pt.IsByRef) { pt = pt.GetElementType(); } - + if (!pt.IsInstanceOfType(val)) { val = Convert.ChangeType(val, pt, CultureInfo.InvariantCulture); } -#endif - - // Set the value + // Set the value fldInfo.SetValue(this, val); } - + // Gets the value specified in the variant on the field // private void FieldGetter(String typeName, String fieldName, ref Object val) @@ -166,7 +160,7 @@ public class Object FieldInfo fldInfo = GetFieldInfo(typeName, fieldName); // Get the value - val = fldInfo.GetValue(this); + val = fldInfo.GetValue(this); } // Gets the field info object given the type name and field name. @@ -190,13 +184,7 @@ public class Object if (null == t) { -#if FEATURE_REMOTING - throw new RemotingException(String.Format( - CultureInfo.CurrentCulture, Environment.GetResourceString("Remoting_BadType"), - typeName)); -#else throw new ArgumentException(); -#endif } FieldInfo fldInfo = t.GetField(fieldName, BindingFlags.Public | @@ -204,16 +192,9 @@ public class Object BindingFlags.IgnoreCase); if(null == fldInfo) { -#if FEATURE_REMOTING - throw new RemotingException(String.Format( - CultureInfo.CurrentCulture, Environment.GetResourceString("Remoting_BadField"), - fieldName, typeName)); -#else throw new ArgumentException(); -#endif - } - + return fldInfo; } } diff --git a/src/coreclr/src/mscorlib/src/System/Reflection/ConstructorInfo.cs b/src/coreclr/src/mscorlib/src/System/Reflection/ConstructorInfo.cs index 07b29d7..db294cb 100644 --- a/src/coreclr/src/mscorlib/src/System/Reflection/ConstructorInfo.cs +++ b/src/coreclr/src/mscorlib/src/System/Reflection/ConstructorInfo.cs @@ -14,9 +14,6 @@ namespace System.Reflection using System.Runtime; using System.Runtime.ConstrainedExecution; using System.Runtime.InteropServices; -#if FEATURE_REMOTING - using System.Runtime.Remoting.Metadata; -#endif //FEATURE_REMOTING using System.Runtime.Serialization; using System.Security; using System.Security.Permissions; @@ -276,36 +273,6 @@ namespace System.Reflection } #endregion -#if FEATURE_REMOTING - #region Legacy Remoting Cache - // The size of CachedData is accounted for by BaseObjectWithCachedData in object.h. - // This member is currently being used by Remoting for caching remoting data. If you - // need to cache data here, talk to the Remoting team to work out a mechanism, so that - // both caching systems can happily work together. - private RemotingMethodCachedData m_cachedData; - - internal RemotingMethodCachedData RemotingCache - { - get - { - // This grabs an internal copy of m_cachedData and uses - // that instead of looking at m_cachedData directly because - // the cache may get cleared asynchronously. This prevents - // us from having to take a lock. - RemotingMethodCachedData cache = m_cachedData; - if (cache == null) - { - cache = new RemotingMethodCachedData(this); - RemotingMethodCachedData ret = Interlocked.CompareExchange(ref m_cachedData, cache, null); - if (ret != null) - cache = ret; - } - return cache; - } - } - #endregion -#endif //FEATURE_REMOTING - #region NonPublic Methods RuntimeMethodHandleInternal IRuntimeMethodInfo.Value { diff --git a/src/coreclr/src/mscorlib/src/System/Reflection/CustomAttribute.cs b/src/coreclr/src/mscorlib/src/System/Reflection/CustomAttribute.cs index 92d230c..ba943d1 100644 --- a/src/coreclr/src/mscorlib/src/System/Reflection/CustomAttribute.cs +++ b/src/coreclr/src/mscorlib/src/System/Reflection/CustomAttribute.cs @@ -2076,21 +2076,10 @@ namespace System.Reflection #endregion #region FCalls -#if FEATURE_CAS_POLICY - [System.Security.SecurityCritical] // auto-generated - [MethodImplAttribute(MethodImplOptions.InternalCall)] - unsafe private static extern void _GetSecurityAttributes(RuntimeModule module, int token, bool assembly, out object[] securityAttributes); - [System.Security.SecurityCritical] // auto-generated - unsafe internal static void GetSecurityAttributes(RuntimeModule module, int token, bool assembly, out object[] securityAttributes) - { - _GetSecurityAttributes(module.GetNativeHandle(), token, assembly, out securityAttributes); - } -#else internal static void GetSecurityAttributes(RuntimeModule module, int token, bool assembly, out object[] securityAttributes) { securityAttributes = null; } -#endif #endregion #region Static Constructor diff --git a/src/coreclr/src/mscorlib/src/System/Reflection/Emit/AssemblyBuilder.cs b/src/coreclr/src/mscorlib/src/System/Reflection/Emit/AssemblyBuilder.cs index 3e13c01..3d6d21a 100644 --- a/src/coreclr/src/mscorlib/src/System/Reflection/Emit/AssemblyBuilder.cs +++ b/src/coreclr/src/mscorlib/src/System/Reflection/Emit/AssemblyBuilder.cs @@ -517,13 +517,6 @@ namespace System.Reflection.Emit IEnumerable unsafeAssemblyAttributes, SecurityContextSource securityContextSource) { -#if FEATURE_CAS_POLICY - if (evidence != null && !AppDomain.CurrentDomain.IsLegacyCasPolicyEnabled) - { - throw new NotSupportedException(Environment.GetResourceString("NotSupported_RequiresCasPolicyExplicit")); - } -#endif // FEATURE_CAS_POLICY - lock (typeof(AssemblyBuilderLock)) { // we can only create dynamic assemblies in the current domain @@ -987,33 +980,6 @@ namespace System.Reflection.Emit return InternalAssembly.GetType(name, throwOnError, ignoreCase); } -#if FEATURE_CAS_POLICY - public override Evidence Evidence - { - get - { - return InternalAssembly.Evidence; - } - } - - public override PermissionSet PermissionSet - { - [SecurityCritical] - get - { - return InternalAssembly.PermissionSet; - } - } - - public override SecurityRuleSet SecurityRuleSet - { - get - { - return InternalAssembly.SecurityRuleSet; - } - } -#endif // FEATURE_CAS_POLICY - public override Module ManifestModule { get @@ -1421,358 +1387,15 @@ namespace System.Reflection.Emit } } -#if FEATURE_CORECLR private void SaveNoLock(String assemblyFileName, PortableExecutableKinds portableExecutableKind, ImageFileMachine imageFileMachine) { // AssemblyBuilderAccess.Save can never be set with FEATURE_CORECLR throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_CantSaveTransientAssembly")); } -#else // FEATURE_CORECLR - [System.Security.SecurityCritical] // auto-generated - private void SaveNoLock(String assemblyFileName, - PortableExecutableKinds portableExecutableKind, ImageFileMachine imageFileMachine) - { - if (assemblyFileName == null) - throw new ArgumentNullException(nameof(assemblyFileName)); - if (assemblyFileName.Length == 0) - throw new ArgumentException(Environment.GetResourceString("Argument_EmptyFileName"), nameof(assemblyFileName)); - if (!String.Equals(assemblyFileName, Path.GetFileName(assemblyFileName))) - throw new ArgumentException(Environment.GetResourceString("Argument_NotSimpleFileName"), nameof(assemblyFileName)); - Contract.EndContractBlock(); - - int i; - int size; - Type type; - TypeBuilder typeBuilder; - ModuleBuilder modBuilder; - String strModFileName; - ModuleBuilder assemblyModule; - ResWriterData tempRes; - int[] tkAttrs = null; - int[] tkAttrs2 = null; - ModuleBuilder onDiskAssemblyModule; - - BCLDebug.Log("DYNIL","## DYNIL LOGGING: AssemblyBuilder.Save( " + assemblyFileName + " )"); - - String tmpVersionFile = null; - try - { - if (m_assemblyData.m_iCABuilder != 0) - tkAttrs = new int[m_assemblyData.m_iCABuilder]; - if ( m_assemblyData.m_iCAs != 0) - tkAttrs2 = new int[m_assemblyData.m_iCAs]; - - if (m_assemblyData.m_isSaved == true) - { - // assembly has been saved before! - throw new InvalidOperationException(Environment.GetResourceString(ResId.InvalidOperation_AssemblyHasBeenSaved, - InternalAssembly.GetSimpleName())); - } - - if ((m_assemblyData.m_access & AssemblyBuilderAccess.Save) != AssemblyBuilderAccess.Save) - { - throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_CantSaveTransientAssembly")); - } - - // Check if assembly info is supposed to be stored with one of the module files. - assemblyModule = m_assemblyData.FindModuleWithFileName(assemblyFileName); - - if (assemblyModule != null) - { - m_onDiskAssemblyModuleBuilder = assemblyModule; - - // In memory this module is not the manifest module and has a valid file token - // On disk it will be the manifest module so lets clean the file token - // We should not retrieve FileToken after the assembly has been saved - // If that is absolutely necessary, we need two separate fields on ModuleBuilderData: - // the in memory file token and the on disk file token. - assemblyModule.m_moduleData.FileToken = 0; - } - else - { // If assembly is to be stored alone, then no file name should conflict with it. - // This check will ensure resource file names are different assembly file name. - m_assemblyData.CheckFileNameConflict(assemblyFileName); - } - - if (m_assemblyData.m_strDir == null) - { - // set it to current directory - m_assemblyData.m_strDir = Directory.GetCurrentDirectory(); - } - else if (Directory.Exists(m_assemblyData.m_strDir) == false) - { - throw new ArgumentException(Environment.GetResourceString("Argument_InvalidDirectory", - m_assemblyData.m_strDir)); - } - - // after this point, assemblyFileName is the full path name. - assemblyFileName = Path.Combine(m_assemblyData.m_strDir, assemblyFileName); - assemblyFileName = Path.GetFullPath(assemblyFileName); - - // Check caller has the right to create the assembly file itself. - new FileIOPermission(FileIOPermissionAccess.Write | FileIOPermissionAccess.Append, assemblyFileName).Demand(); - - // 1. setup/create the IMetaDataAssemblyEmit for the on disk version - if (assemblyModule != null) - { - // prepare saving CAs on assembly def. We need to introduce the MemberRef for - // the CA's type first of all. This is for the case the we have embedded manifest. - // We need to introduce these MRs before we call PreSave where we will snap - // into a ondisk metadata. If we do it after this, the ondisk metadata will - // not contain the proper MRs. - // - for (i=0; i < m_assemblyData.m_iCABuilder; i++) - { - tkAttrs[i] = m_assemblyData.m_CABuilders[i].PrepareCreateCustomAttributeToDisk( - assemblyModule); - } - for (i=0; i < m_assemblyData.m_iCAs; i++) - { - tkAttrs2[i] = assemblyModule.InternalGetConstructorToken(m_assemblyData.m_CACons[i], true).Token; - } - assemblyModule.PreSave(assemblyFileName, portableExecutableKind, imageFileMachine); - } - - RuntimeModule runtimeAssemblyModule = (assemblyModule != null) ? assemblyModule.ModuleHandle.GetRuntimeModule() : null; - PrepareForSavingManifestToDisk(GetNativeHandle(), runtimeAssemblyModule); - - // This function will return the embedded manifest module, an already exposed ModuleBuilder - // created by user, or make the stand alone manifest module exposed through managed code. - // - onDiskAssemblyModule = GetOnDiskAssemblyModuleBuilder(); - - // Set any native resources on the OnDiskAssemblyModule. - if (m_assemblyData.m_strResourceFileName != null) - onDiskAssemblyModule.DefineUnmanagedResourceFileInternalNoLock(m_assemblyData.m_strResourceFileName); - else if (m_assemblyData.m_resourceBytes != null) - onDiskAssemblyModule.DefineUnmanagedResourceInternalNoLock(m_assemblyData.m_resourceBytes); - else if (m_assemblyData.m_hasUnmanagedVersionInfo == true) - { - // calculate unmanaged version info from assembly's custom attributes - m_assemblyData.FillUnmanagedVersionInfo(); - - String strFileVersion = m_assemblyData.m_nativeVersion.m_strFileVersion; - if (strFileVersion == null) - strFileVersion = GetVersion().ToString(); - - // Create the file. - CreateVersionInfoResource( - assemblyFileName, - m_assemblyData.m_nativeVersion.m_strTitle, // title - null, // Icon filename - m_assemblyData.m_nativeVersion.m_strDescription, // description - m_assemblyData.m_nativeVersion.m_strCopyright, - m_assemblyData.m_nativeVersion.m_strTrademark, - m_assemblyData.m_nativeVersion.m_strCompany, - m_assemblyData.m_nativeVersion.m_strProduct, - m_assemblyData.m_nativeVersion.m_strProductVersion, - strFileVersion, - m_assemblyData.m_nativeVersion.m_lcid, - m_assemblyData.m_peFileKind == PEFileKinds.Dll, - JitHelpers.GetStringHandleOnStack(ref tmpVersionFile)); - - onDiskAssemblyModule.DefineUnmanagedResourceFileInternalNoLock(tmpVersionFile); - } - - if (assemblyModule == null) - { - - // This is for introducing the MRs for CA's type. This case is for stand alone - // manifest. We need to wait till PrepareForSavingManifestToDisk is called. - // That will trigger the creation of the on-disk stand alone manifest module. - // - for (i=0; i < m_assemblyData.m_iCABuilder; i++) - { - tkAttrs[i] = m_assemblyData.m_CABuilders[i].PrepareCreateCustomAttributeToDisk( - onDiskAssemblyModule); - } - for (i=0; i < m_assemblyData.m_iCAs; i++) - { - tkAttrs2[i] = onDiskAssemblyModule.InternalGetConstructorToken(m_assemblyData.m_CACons[i], true).Token; - } - } - - // 2. save all of the persistable modules contained by this AssemblyBuilder except the module that is going to contain - // Assembly information - // - // 3. create the file list in the manifest and track the file token. If it is embedded assembly, - // the assembly file should not be on the file list. - // - size = m_assemblyData.m_moduleBuilderList.Count; - for (i = 0; i < size; i++) - { - ModuleBuilder mBuilder = (ModuleBuilder) m_assemblyData.m_moduleBuilderList[i]; - if (mBuilder.IsTransient() == false && mBuilder != assemblyModule) - { - strModFileName = mBuilder.m_moduleData.m_strFileName; - if (m_assemblyData.m_strDir != null) - { - strModFileName = Path.Combine(m_assemblyData.m_strDir, strModFileName); - strModFileName = Path.GetFullPath(strModFileName); - } - - // Check caller has the right to create the Module file itself. - new FileIOPermission(FileIOPermissionAccess.Write | FileIOPermissionAccess.Append, strModFileName).Demand(); - - mBuilder.m_moduleData.FileToken = AddFile(GetNativeHandle(), mBuilder.m_moduleData.m_strFileName); - mBuilder.PreSave(strModFileName, portableExecutableKind, imageFileMachine); - mBuilder.Save(strModFileName, false, portableExecutableKind, imageFileMachine); - - // Cannot set the hash value when creating the file since the file token - // is needed to created the entries for the embedded resources in the - // module and the resources need to be there before you figure the hash. - SetFileHashValue(GetNativeHandle(), mBuilder.m_moduleData.FileToken, strModFileName); - } - } - - // 4. Add the public ComType - for (i=0; i < m_assemblyData.m_iPublicComTypeCount; i++) - { - type = m_assemblyData.m_publicComTypeList[i]; - // If the type that was added as a Public Com Type was obtained via Reflection, - // it will be a System.RuntimeType, even if it was really, at the same time, - // a TypeBuilder. Unfortunately, you can't get back to the TypeBuilder, so - // this code has to deal with either-or. - if (type is RuntimeType) - { - // If type is a runtime type, it must be a baked TypeBuilder, - // ttype.Module should be an InternalModuleBuilder - - InternalModuleBuilder internalMB = (InternalModuleBuilder)type.Module; - modBuilder = this.GetModuleBuilder(internalMB); - if (modBuilder != assemblyModule) - DefineNestedComType(type, modBuilder.m_moduleData.FileToken, type.MetadataToken); - } - else - { - // Could assert that "type" is a TypeBuilder, but next statement throws if it isn't. - typeBuilder = (TypeBuilder) type; - // If type is a TypeBuilder, type.Module must be a ModuleBuilder. - modBuilder = typeBuilder.GetModuleBuilder(); - if (modBuilder != assemblyModule) - DefineNestedComType(type, modBuilder.m_moduleData.FileToken, typeBuilder.MetadataTokenInternal); - } - } - - // 5. write AssemblyDef's CAs (only if we are not saving directly the manifest module itself) - if (onDiskAssemblyModule != m_manifestModuleBuilder) - { - for (i = 0; i < m_assemblyData.m_iCABuilder; i++) - { - m_assemblyData.m_CABuilders[i].CreateCustomAttribute( - onDiskAssemblyModule, - AssemblyBuilderData.m_tkAssembly, // This is the AssemblyDef token - tkAttrs[i], true); - } - - for (i = 0; i < m_assemblyData.m_iCAs; i++) - { - TypeBuilder.DefineCustomAttribute( - onDiskAssemblyModule, // pass in the in-memory assembly module - AssemblyBuilderData.m_tkAssembly, // This is the AssemblyDef token - tkAttrs2[i], - m_assemblyData.m_CABytes[i], - true, false); - } - } - - // 6. write security permission requests to the manifest. -#pragma warning disable 618 - if (m_assemblyData.m_RequiredPset != null) - AddDeclarativeSecurity(m_assemblyData.m_RequiredPset, SecurityAction.RequestMinimum); - - if (m_assemblyData.m_RefusedPset != null) - AddDeclarativeSecurity(m_assemblyData.m_RefusedPset, SecurityAction.RequestRefuse); - - if (m_assemblyData.m_OptionalPset != null) - AddDeclarativeSecurity(m_assemblyData.m_OptionalPset, SecurityAction.RequestOptional); -#pragma warning restore 618 - - // 7. Save the stand alone managed resources - size = m_assemblyData.m_resWriterList.Count; - for (i = 0; i < size; i++) - { - tempRes = null; - - try - { - tempRes = (ResWriterData)m_assemblyData.m_resWriterList[i]; - - // If the user added an existing resource to the manifest, the - // corresponding ResourceWriter will be null. - if (tempRes.m_resWriter != null) - // Check caller has the right to create the Resource file itself. - new FileIOPermission(FileIOPermissionAccess.Write | FileIOPermissionAccess.Append, tempRes.m_strFullFileName).Demand(); - } - finally - { - if (tempRes != null && tempRes.m_resWriter != null) - tempRes.m_resWriter.Close(); - } - - // Add entry to manifest for this stand alone resource - AddStandAloneResource(GetNativeHandle(), tempRes.m_strName, tempRes.m_strFileName, tempRes.m_strFullFileName, (int)tempRes.m_attribute); - } - - // Save now!! - if (assemblyModule == null) - { - onDiskAssemblyModule.DefineNativeResource(portableExecutableKind, imageFileMachine); - - // Stand alone manifest - int entryPoint = (m_assemblyData.m_entryPointModule != null) ? m_assemblyData.m_entryPointModule.m_moduleData.FileToken : 0; - - SaveManifestToDisk(GetNativeHandle(), assemblyFileName, entryPoint, (int)m_assemblyData.m_peFileKind, - (int)portableExecutableKind, (int)imageFileMachine); - } - else - { - // embedded manifest - - // If the module containing the entry point is not the manifest file, we need to - // let the manifest file point to the module which contains the entry point. - // - // - // - // - if (m_assemblyData.m_entryPointModule != null && m_assemblyData.m_entryPointModule != assemblyModule) - assemblyModule.SetEntryPoint(new MethodToken(m_assemblyData.m_entryPointModule.m_moduleData.FileToken)); - assemblyModule.Save(assemblyFileName, true, portableExecutableKind, imageFileMachine); - } - m_assemblyData.m_isSaved = true; - } - finally - { - if (tmpVersionFile != null) - { - // Delete file. - System.IO.File.Delete(tmpVersionFile); - } - } - } -#endif // FEATURE_CORECLR - -#if FEATURE_CAS_POLICY - [System.Security.SecurityCritical] // auto-generated - private void AddDeclarativeSecurity(PermissionSet pset, SecurityAction action) - { - // Translate sets into internal encoding (uses standard binary serialization). - byte[] blob = pset.EncodeXml(); - AddDeclarativeSecurity(GetNativeHandle(), action, blob, blob.Length); - } -#endif // FEATURE_CAS_POLICY - internal bool IsPersistable() { -#if !FEATURE_CORECLR // AssemblyBuilderAccess.Save is never set in CoreCLR - if ((m_assemblyData.m_access & AssemblyBuilderAccess.Save) == AssemblyBuilderAccess.Save) - { - return true; - } - else -#endif // FEATURE_CORECLR { return false; } diff --git a/src/coreclr/src/mscorlib/src/System/Reflection/Emit/ConstructorBuilder.cs b/src/coreclr/src/mscorlib/src/System/Reflection/Emit/ConstructorBuilder.cs index 7bf3a67..acdfc44 100644 --- a/src/coreclr/src/mscorlib/src/System/Reflection/Emit/ConstructorBuilder.cs +++ b/src/coreclr/src/mscorlib/src/System/Reflection/Emit/ConstructorBuilder.cs @@ -218,36 +218,6 @@ namespace System.Reflection.Emit m_methodBuilder.SetMethodBody(il, maxStack, localSignature, exceptionHandlers, tokenFixups); } -#if FEATURE_CAS_POLICY - [System.Security.SecuritySafeCritical] // auto-generated - public void AddDeclarativeSecurity(SecurityAction action, PermissionSet pset) - { - if (pset == null) - throw new ArgumentNullException(nameof(pset)); - -#pragma warning disable 618 - if (!Enum.IsDefined(typeof(SecurityAction), action) || - action == SecurityAction.RequestMinimum || - action == SecurityAction.RequestOptional || - action == SecurityAction.RequestRefuse) - { - throw new ArgumentOutOfRangeException(nameof(action)); - } -#pragma warning restore 618 - Contract.EndContractBlock(); - - // Cannot add declarative security after type is created. - if (m_methodBuilder.IsTypeCreated()) - throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_TypeHasBeenCreated")); - - // Translate permission set into serialized format (use standard binary serialization). - byte[] blob = pset.EncodeXml(); - - // Write the blob into the metadata. - TypeBuilder.AddDeclarativeSecurity(GetModuleBuilder().GetNativeHandle(), GetToken().Token, action, blob, blob.Length); - } -#endif // FEATURE_CAS_POLICY - public override CallingConventions CallingConvention { get diff --git a/src/coreclr/src/mscorlib/src/System/Reflection/Emit/MethodBuilder.cs b/src/coreclr/src/mscorlib/src/System/Reflection/Emit/MethodBuilder.cs index a060098..3c45e50 100644 --- a/src/coreclr/src/mscorlib/src/System/Reflection/Emit/MethodBuilder.cs +++ b/src/coreclr/src/mscorlib/src/System/Reflection/Emit/MethodBuilder.cs @@ -927,43 +927,6 @@ namespace System.Reflection.Emit m_symCustomAttrs.Add(new SymCustomAttr(name, data)); } -#if FEATURE_CAS_POLICY - [System.Security.SecuritySafeCritical] // auto-generated - public void AddDeclarativeSecurity(SecurityAction action, PermissionSet pset) - { - if (pset == null) - throw new ArgumentNullException(nameof(pset)); - Contract.EndContractBlock(); - - ThrowIfGeneric (); - -#pragma warning disable 618 - if (!Enum.IsDefined(typeof(SecurityAction), action) || - action == SecurityAction.RequestMinimum || - action == SecurityAction.RequestOptional || - action == SecurityAction.RequestRefuse) - { - throw new ArgumentOutOfRangeException(nameof(action)); - } -#pragma warning restore 618 - - // cannot declarative security after type is created - m_containingType.ThrowIfCreated(); - - // Translate permission set into serialized format (uses standard binary serialization format). - byte[] blob = null; - int length = 0; - if (!pset.IsEmpty()) - { - blob = pset.EncodeXml(); - length = blob.Length; - } - - // Write the blob into the metadata. - TypeBuilder.AddDeclarativeSecurity(m_module.GetNativeHandle(), MetadataTokenInternal, action, blob, length); - } -#endif // FEATURE_CAS_POLICY - #if FEATURE_CORECLR [System.Security.SecurityCritical] // auto-generated #endif diff --git a/src/coreclr/src/mscorlib/src/System/Reflection/Emit/ModuleBuilder.cs b/src/coreclr/src/mscorlib/src/System/Reflection/Emit/ModuleBuilder.cs index c474b70..11d2668 100644 --- a/src/coreclr/src/mscorlib/src/System/Reflection/Emit/ModuleBuilder.cs +++ b/src/coreclr/src/mscorlib/src/System/Reflection/Emit/ModuleBuilder.cs @@ -1085,12 +1085,6 @@ namespace System.Reflection.Emit } } -#if FEATURE_X509 && FEATURE_CAS_POLICY - public override System.Security.Cryptography.X509Certificates.X509Certificate GetSignerCertificate() - { - return InternalModule.GetSignerCertificate(); - } -#endif // FEATURE_X509 && FEATURE_CAS_POLICY #endregion #region Public Members @@ -2384,27 +2378,5 @@ namespace System.Reflection.Emit #endregion #endregion - -#if !FEATURE_CORECLR - void _ModuleBuilder.GetTypeInfoCount(out uint pcTInfo) - { - throw new NotImplementedException(); - } - - void _ModuleBuilder.GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo) - { - throw new NotImplementedException(); - } - - void _ModuleBuilder.GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId) - { - throw new NotImplementedException(); - } - - void _ModuleBuilder.Invoke(uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr) - { - throw new NotImplementedException(); - } -#endif } } diff --git a/src/coreclr/src/mscorlib/src/System/Reflection/Emit/TypeBuilder.cs b/src/coreclr/src/mscorlib/src/System/Reflection/Emit/TypeBuilder.cs index dd34891..cee2db4 100644 --- a/src/coreclr/src/mscorlib/src/System/Reflection/Emit/TypeBuilder.cs +++ b/src/coreclr/src/mscorlib/src/System/Reflection/Emit/TypeBuilder.cs @@ -297,13 +297,6 @@ namespace System.Reflection.Emit { [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [SuppressUnmanagedCodeSecurity] private static extern unsafe void SetConstantValue(RuntimeModule module, int tk, int corType, void* pValue); - -#if FEATURE_CAS_POLICY - [System.Security.SecurityCritical] // auto-generated - [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] - [SuppressUnmanagedCodeSecurity] - internal static extern void AddDeclarativeSecurity(RuntimeModule module, int parent, SecurityAction action, byte[] blob, int cb); -#endif #endregion #region Internal\Private Static Members @@ -2518,50 +2511,6 @@ namespace System.Reflection.Emit { m_typeInterfaces.Add(interfaceType); } -#if FEATURE_CAS_POLICY - [System.Security.SecuritySafeCritical] // auto-generated - public void AddDeclarativeSecurity(SecurityAction action, PermissionSet pset) - { - lock(SyncRoot) - { - AddDeclarativeSecurityNoLock(action, pset); - } - } - - [System.Security.SecurityCritical] // auto-generated - private void AddDeclarativeSecurityNoLock(SecurityAction action, PermissionSet pset) - { - if (pset == null) - throw new ArgumentNullException(nameof(pset)); - -#pragma warning disable 618 - if (!Enum.IsDefined(typeof(SecurityAction), action) || - action == SecurityAction.RequestMinimum || - action == SecurityAction.RequestOptional || - action == SecurityAction.RequestRefuse) - { - throw new ArgumentOutOfRangeException(nameof(action)); - } -#pragma warning restore 618 - - Contract.EndContractBlock(); - - ThrowIfCreated(); - - // Translate permission set into serialized format(uses standard binary serialization format). - byte[] blob = null; - int length = 0; - if (!pset.IsEmpty()) - { - blob = pset.EncodeXml(); - length = blob.Length; - } - - // Write the blob into the metadata. - AddDeclarativeSecurity(m_module.GetNativeHandle(), m_tdType.Token, action, blob, length); - } -#endif // FEATURE_CAS_POLICY - public TypeToken TypeToken { get diff --git a/src/coreclr/src/mscorlib/src/System/Reflection/FieldInfo.cs b/src/coreclr/src/mscorlib/src/System/Reflection/FieldInfo.cs index 5852de7..ed4d296 100644 --- a/src/coreclr/src/mscorlib/src/System/Reflection/FieldInfo.cs +++ b/src/coreclr/src/mscorlib/src/System/Reflection/FieldInfo.cs @@ -15,9 +15,6 @@ namespace System.Reflection using System.Runtime.CompilerServices; using System.Runtime.ConstrainedExecution; using System.Runtime.InteropServices; -#if FEATURE_REMOTING - using System.Runtime.Remoting.Metadata; -#endif //FEATURE_REMOTING using System.Runtime.Serialization; using System.Security.Permissions; using System.Threading; @@ -239,36 +236,6 @@ namespace System.Reflection } #endregion -#if FEATURE_REMOTING - #region Legacy Remoting Cache - // The size of CachedData is accounted for by BaseObjectWithCachedData in object.h. - // This member is currently being used by Remoting for caching remoting data. If you - // need to cache data here, talk to the Remoting team to work out a mechanism, so that - // both caching systems can happily work together. - private RemotingFieldCachedData m_cachedData; - - internal RemotingFieldCachedData RemotingCache - { - get - { - // This grabs an internal copy of m_cachedData and uses - // that instead of looking at m_cachedData directly because - // the cache may get cleared asynchronously. This prevents - // us from having to take a lock. - RemotingFieldCachedData cache = m_cachedData; - if (cache == null) - { - cache = new RemotingFieldCachedData(this); - RemotingFieldCachedData ret = Interlocked.CompareExchange(ref m_cachedData, cache, null); - if (ret != null) - cache = ret; - } - return cache; - } - } - #endregion -#endif //FEATURE_REMOTING - #region NonPublic Members internal BindingFlags BindingFlags { get { return m_bindingFlags; } } private RuntimeType ReflectedTypeInternal diff --git a/src/coreclr/src/mscorlib/src/System/Reflection/MethodInfo.cs b/src/coreclr/src/mscorlib/src/System/Reflection/MethodInfo.cs index 8a67d42..2e59b3d 100644 --- a/src/coreclr/src/mscorlib/src/System/Reflection/MethodInfo.cs +++ b/src/coreclr/src/mscorlib/src/System/Reflection/MethodInfo.cs @@ -14,9 +14,6 @@ namespace System.Reflection using System.Runtime; using System.Runtime.InteropServices; using System.Runtime.ConstrainedExecution; -#if FEATURE_REMOTING - using System.Runtime.Remoting.Metadata; -#endif //FEATURE_REMOTING using System.Runtime.Serialization; using System.Security; using System.Security.Permissions; @@ -262,36 +259,6 @@ namespace System.Reflection } #endregion -#if FEATURE_REMOTING - #region Legacy Remoting Cache - // The size of CachedData is accounted for by BaseObjectWithCachedData in object.h. - // This member is currently being used by Remoting for caching remoting data. If you - // need to cache data here, talk to the Remoting team to work out a mechanism, so that - // both caching systems can happily work together. - private RemotingMethodCachedData m_cachedData; - - internal RemotingMethodCachedData RemotingCache - { - get - { - // This grabs an internal copy of m_cachedData and uses - // that instead of looking at m_cachedData directly because - // the cache may get cleared asynchronously. This prevents - // us from having to take a lock. - RemotingMethodCachedData cache = m_cachedData; - if (cache == null) - { - cache = new RemotingMethodCachedData(this); - RemotingMethodCachedData ret = Interlocked.CompareExchange(ref m_cachedData, cache, null); - if (ret != null) - cache = ret; - } - return cache; - } - } - #endregion -#endif //FEATURE_REMOTING - #region Private Methods RuntimeMethodHandleInternal IRuntimeMethodInfo.Value { diff --git a/src/coreclr/src/mscorlib/src/System/Reflection/Module.cs b/src/coreclr/src/mscorlib/src/System/Reflection/Module.cs index e19a569..2ccaa00 100644 --- a/src/coreclr/src/mscorlib/src/System/Reflection/Module.cs +++ b/src/coreclr/src/mscorlib/src/System/Reflection/Module.cs @@ -543,36 +543,7 @@ namespace System.Reflection { return ModuleHandle.EmptyHandle; } - -#if FEATURE_X509 && FEATURE_CAS_POLICY - public virtual System.Security.Cryptography.X509Certificates.X509Certificate GetSignerCertificate() - { - throw new NotImplementedException(); - } -#endif // FEATURE_X509 && FEATURE_CAS_POLICY #endregion - -#if !FEATURE_CORECLR - void _Module.GetTypeInfoCount(out uint pcTInfo) - { - throw new NotImplementedException(); - } - - void _Module.GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo) - { - throw new NotImplementedException(); - } - - void _Module.GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId) - { - throw new NotImplementedException(); - } - - void _Module.Invoke(uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr) - { - throw new NotImplementedException(); - } -#endif } [Serializable] @@ -614,13 +585,6 @@ namespace System.Reflection [System.Security.SecuritySafeCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.InternalCall)] private extern static bool IsResource(RuntimeModule module); - -#if FEATURE_X509 && FEATURE_CAS_POLICY - [System.Security.SecurityCritical] // auto-generated - [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] - [SuppressUnmanagedCodeSecurity] - static private extern void GetSignerCertificate(RuntimeModule module, ObjectHandleOnStack retData); -#endif // FEATURE_X509 && FEATURE_CAS_POLICY #endregion #region Module overrides @@ -1215,16 +1179,6 @@ namespace System.Reflection { return this; } - -#if FEATURE_X509 && FEATURE_CAS_POLICY - [System.Security.SecuritySafeCritical] // auto-generated - public override System.Security.Cryptography.X509Certificates.X509Certificate GetSignerCertificate() - { - byte[] data = null; - GetSignerCertificate(GetNativeHandle(), JitHelpers.GetObjectHandleOnStack(ref data)); - return (data != null) ? new System.Security.Cryptography.X509Certificates.X509Certificate(data) : null; - } -#endif // FEATURE_X509 && FEATURE_CAS_POLICY #endregion } } diff --git a/src/coreclr/src/mscorlib/src/System/Reflection/ParameterInfo.cs b/src/coreclr/src/mscorlib/src/System/Reflection/ParameterInfo.cs index 5186e69..682db15 100644 --- a/src/coreclr/src/mscorlib/src/System/Reflection/ParameterInfo.cs +++ b/src/coreclr/src/mscorlib/src/System/Reflection/ParameterInfo.cs @@ -12,9 +12,6 @@ namespace System.Reflection using System.Runtime.InteropServices; using System.Runtime.Serialization; using System.Runtime.CompilerServices; -#if FEATURE_REMOTING - using System.Runtime.Remoting.Metadata; -#endif //FEATURE_REMOTING using System.Security.Permissions; using System.Threading; using MdToken = System.Reflection.MetadataToken; @@ -765,31 +762,5 @@ namespace System.Reflection return CustomAttributeData.GetCustomAttributesInternal(this); } #endregion - -#if FEATURE_REMOTING - #region Remoting Cache - private RemotingParameterCachedData m_cachedData; - - internal RemotingParameterCachedData RemotingCache - { - get - { - // This grabs an internal copy of m_cachedData and uses - // that instead of looking at m_cachedData directly because - // the cache may get cleared asynchronously. This prevents - // us from having to take a lock. - RemotingParameterCachedData cache = m_cachedData; - if (cache == null) - { - cache = new RemotingParameterCachedData(this); - RemotingParameterCachedData ret = Interlocked.CompareExchange(ref m_cachedData, cache, null); - if (ret != null) - cache = ret; - } - return cache; - } - } - #endregion -#endif //FEATURE_REMOTING } } diff --git a/src/coreclr/src/mscorlib/src/System/RtType.cs b/src/coreclr/src/mscorlib/src/System/RtType.cs index 6558338..711945d 100644 --- a/src/coreclr/src/mscorlib/src/System/RtType.cs +++ b/src/coreclr/src/mscorlib/src/System/RtType.cs @@ -25,12 +25,6 @@ using System.Runtime.CompilerServices; using System.Security; using System.Text; using System.Runtime.Remoting; -#if FEATURE_REMOTING -using System.Runtime.Remoting.Proxies; -using System.Runtime.Remoting.Messaging; -using System.Runtime.Remoting.Activation; -using System.Runtime.Remoting.Metadata; -#endif using MdSigCallingConvention = System.Signature.MdSigCallingConvention; using RuntimeTypeCache = System.RuntimeType.RuntimeTypeCache; using System.Runtime.InteropServices; @@ -1832,36 +1826,6 @@ namespace System } #endregion -#if FEATURE_REMOTING - #region Legacy Remoting Cache - // The size of CachedData is accounted for by BaseObjectWithCachedData in object.h. - // This member is currently being used by Remoting for caching remoting data. If you - // need to cache data here, talk to the Remoting team to work out a mechanism, so that - // both caching systems can happily work together. - private RemotingTypeCachedData m_cachedData; - - internal RemotingTypeCachedData RemotingCache - { - get - { - // This grabs an internal copy of m_cachedData and uses - // that instead of looking at m_cachedData directly because - // the cache may get cleared asynchronously. This prevents - // us from having to take a lock. - RemotingTypeCachedData cache = m_cachedData; - if (cache == null) - { - cache = new RemotingTypeCachedData(this); - RemotingTypeCachedData ret = Interlocked.CompareExchange(ref m_cachedData, cache, null); - if (ret != null) - cache = ret; - } - return cache; - } - } - #endregion -#endif //FEATURE_REMOTING - #region Static Members #region Internal @@ -3660,20 +3624,9 @@ namespace System [System.Security.SecuritySafeCritical] // auto-generated protected override bool IsContextfulImpl() { -#if FEATURE_REMOTING - return RuntimeTypeHandle.IsContextful(this); -#else return false; -#endif } - /* - protected override bool IsMarshalByRefImpl() - { - return GetTypeHandleInternal().IsMarshalByRef(); - } - */ - protected override bool IsByRefImpl() { return RuntimeTypeHandle.IsByRef(this); @@ -4113,24 +4066,7 @@ namespace System // because it is faster than RuntimeType.IsValueType Contract.Assert(!IsGenericParameter); - Type type = null; - -#if FEATURE_REMOTING - // For the remoting objects Object.GetType goes through proxy. Avoid the proxy call and just get - // the type directly. It is necessary to support proxies that do not handle GetType. - RealProxy realProxy = System.Runtime.Remoting.RemotingServices.GetRealProxy(value); - - if (realProxy != null) - { - type = realProxy.GetProxiedType(); - } - else - { - type = value.GetType(); - } -#else - type = value.GetType(); -#endif + Type type = value.GetType(); if (!Object.ReferenceEquals(type, this) && RuntimeTypeHandle.IsValueType(this)) { @@ -4317,9 +4253,6 @@ namespace System throw new ArgumentException(Environment.GetResourceString("Arg_COMPropSetPut"), nameof(bindingFlags)); #endregion -#if FEATURE_REMOTING - if(!RemotingServices.IsTransparentProxy(target)) -#endif { #region Non-TransparentProxy case if (name == null) @@ -4333,14 +4266,6 @@ namespace System return InvokeDispMethod(name, bindingFlags, target, providedArgs, isByRef, lcid, namedParams); #endregion } -#if FEATURE_REMOTING - else - { - #region TransparentProxy case - return ((MarshalByRefObject)target).InvokeMember(name, bindingFlags, binder, providedArgs, modifiers, culture, namedParams); - #endregion - } -#endif // FEATURE_REMOTING } #endif // FEATURE_COMINTEROP && FEATURE_USE_LCID #endregion @@ -4927,170 +4852,117 @@ namespace System Object server = null; - try - { - try - { - // Store the activation attributes in thread local storage. - // These attributes are later picked up by specialized - // activation services like remote activation services to - // influence the activation. -#if FEATURE_REMOTING - if(null != activationAttributes) - { - ActivationServices.PushActivationAttributes(this, activationAttributes); - } -#endif - - if (args == null) - args = EmptyArray.Value; + if (args == null) + args = EmptyArray.Value; + + int argCnt = args.Length; - int argCnt = args.Length; + // Without a binder we need to do use the default binder... + if (binder == null) + binder = DefaultBinder; - // Without a binder we need to do use the default binder... - if (binder == null) - binder = DefaultBinder; + // deal with the __COMObject case first. It is very special because from a reflection point of view it has no ctors + // so a call to GetMemberCons would fail + if (argCnt == 0 && (bindingAttr & BindingFlags.Public) != 0 && (bindingAttr & BindingFlags.Instance) != 0 + && (IsGenericCOMObjectImpl() || IsValueType)) + { + server = CreateInstanceDefaultCtor((bindingAttr & BindingFlags.NonPublic) == 0 , false, true, ref stackMark); + } + else + { + ConstructorInfo[] candidates = GetConstructors(bindingAttr); + List matches = new List(candidates.Length); - // deal with the __COMObject case first. It is very special because from a reflection point of view it has no ctors - // so a call to GetMemberCons would fail - if (argCnt == 0 && (bindingAttr & BindingFlags.Public) != 0 && (bindingAttr & BindingFlags.Instance) != 0 - && (IsGenericCOMObjectImpl() || IsValueType)) + // We cannot use Type.GetTypeArray here because some of the args might be null + Type[] argsType = new Type[argCnt]; + for (int i = 0; i < argCnt; i++) + { + if (args[i] != null) { - server = CreateInstanceDefaultCtor((bindingAttr & BindingFlags.NonPublic) == 0 , false, true, ref stackMark); + argsType[i] = args[i].GetType(); } - else - { - ConstructorInfo[] candidates = GetConstructors(bindingAttr); - List matches = new List(candidates.Length); - - // We cannot use Type.GetTypeArray here because some of the args might be null - Type[] argsType = new Type[argCnt]; - for (int i = 0; i < argCnt; i++) - { - if (args[i] != null) - { - argsType[i] = args[i].GetType(); - } - } + } - for(int i = 0; i < candidates.Length; i ++) - { - if (FilterApplyConstructorInfo((RuntimeConstructorInfo)candidates[i], bindingAttr, CallingConventions.Any, argsType)) - matches.Add(candidates[i]); - } + for(int i = 0; i < candidates.Length; i ++) + { + if (FilterApplyConstructorInfo((RuntimeConstructorInfo)candidates[i], bindingAttr, CallingConventions.Any, argsType)) + matches.Add(candidates[i]); + } - MethodBase[] cons = new MethodBase[matches.Count]; - matches.CopyTo(cons); - if (cons != null && cons.Length == 0) - cons = null; + MethodBase[] cons = new MethodBase[matches.Count]; + matches.CopyTo(cons); + if (cons != null && cons.Length == 0) + cons = null; - if (cons == null) - { - // Null out activation attributes before throwing exception -#if FEATURE_REMOTING - if(null != activationAttributes) - { - ActivationServices.PopActivationAttributes(this); - activationAttributes = null; - } -#endif - throw new MissingMethodException(Environment.GetResourceString("MissingConstructor_Name", FullName)); - } - - MethodBase invokeMethod; - Object state = null; + if (cons == null) + { + throw new MissingMethodException(Environment.GetResourceString("MissingConstructor_Name", FullName)); + } - try - { - invokeMethod = binder.BindToMethod(bindingAttr, cons, ref args, null, culture, null, out state); - } - catch (MissingMethodException) { invokeMethod = null; } + MethodBase invokeMethod; + Object state = null; - if (invokeMethod == null) - { -#if FEATURE_REMOTING - // Null out activation attributes before throwing exception - if(null != activationAttributes) - { - ActivationServices.PopActivationAttributes(this); - activationAttributes = null; - } -#endif - throw new MissingMethodException(Environment.GetResourceString("MissingConstructor_Name", FullName)); - } + try + { + invokeMethod = binder.BindToMethod(bindingAttr, cons, ref args, null, culture, null, out state); + } + catch (MissingMethodException) { invokeMethod = null; } - // If we're creating a delegate, we're about to call a - // constructor taking an integer to represent a target - // method. Since this is very difficult (and expensive) - // to verify, we're just going to demand UnmanagedCode - // permission before allowing this. Partially trusted - // clients can instead use Delegate.CreateDelegate, - // which allows specification of the target method via - // name or MethodInfo. - //if (isDelegate) - if (RuntimeType.DelegateType.IsAssignableFrom(invokeMethod.DeclaringType)) - { -#if FEATURE_CORECLR - // In CoreCLR, CAS is not exposed externally. So what we really are looking - // for is to see if the external caller of this API is transparent or not. - // We get that information from the fact that a Demand will succeed only if - // the external caller is not transparent. - try - { + if (invokeMethod == null) + { + throw new MissingMethodException(Environment.GetResourceString("MissingConstructor_Name", FullName)); + } + + // If we're creating a delegate, we're about to call a + // constructor taking an integer to represent a target + // method. Since this is very difficult (and expensive) + // to verify, we're just going to demand UnmanagedCode + // permission before allowing this. Partially trusted + // clients can instead use Delegate.CreateDelegate, + // which allows specification of the target method via + // name or MethodInfo. + //if (isDelegate) + if (RuntimeType.DelegateType.IsAssignableFrom(invokeMethod.DeclaringType)) + { + // In CoreCLR, CAS is not exposed externally. So what we really are looking + // for is to see if the external caller of this API is transparent or not. + // We get that information from the fact that a Demand will succeed only if + // the external caller is not transparent. + try + { #pragma warning disable 618 - new SecurityPermission(SecurityPermissionFlag.UnmanagedCode).Demand(); + new SecurityPermission(SecurityPermissionFlag.UnmanagedCode).Demand(); #pragma warning restore 618 - } - catch - { - throw new NotSupportedException(String.Format(CultureInfo.CurrentCulture, Environment.GetResourceString("NotSupported_DelegateCreationFromPT"))); - } -#else // FEATURE_CORECLR - new SecurityPermission(SecurityPermissionFlag.UnmanagedCode).Demand(); -#endif // FEATURE_CORECLR - } - - if (invokeMethod.GetParametersNoCopy().Length == 0) - { - if (args.Length != 0) - { - - Contract.Assert((invokeMethod.CallingConvention & CallingConventions.VarArgs) == - CallingConventions.VarArgs); - throw new NotSupportedException(String.Format(CultureInfo.CurrentCulture, - Environment.GetResourceString("NotSupported_CallToVarArg"))); - } - - // fast path?? - server = Activator.CreateInstance(this, true); - } - else - { - server = ((ConstructorInfo)invokeMethod).Invoke(bindingAttr, binder, args, culture); - if (state != null) - binder.ReorderArgumentArray(ref args, state); - } } - } - finally + catch + { + throw new NotSupportedException(String.Format(CultureInfo.CurrentCulture, Environment.GetResourceString("NotSupported_DelegateCreationFromPT"))); + } + } + + if (invokeMethod.GetParametersNoCopy().Length == 0) { -#if FEATURE_REMOTING - // Reset the TLS to null - if(null != activationAttributes) + if (args.Length != 0) { - ActivationServices.PopActivationAttributes(this); - activationAttributes = null; + + Contract.Assert((invokeMethod.CallingConvention & CallingConventions.VarArgs) == + CallingConventions.VarArgs); + throw new NotSupportedException(String.Format(CultureInfo.CurrentCulture, + Environment.GetResourceString("NotSupported_CallToVarArg"))); } -#endif + + // fast path?? + server = Activator.CreateInstance(this, true); + } + else + { + server = ((ConstructorInfo)invokeMethod).Invoke(bindingAttr, binder, args, culture); + if (state != null) + binder.ReorderArgumentArray(ref args, state); } } - catch (Exception) - { - throw; - } - - //Console.WriteLine(server); - return server; + + return server; } // the cache entry @@ -5346,213 +5218,6 @@ namespace System #endregion #region COM -#if FEATURE_COMINTEROP && FEATURE_REMOTING - [System.Security.SecuritySafeCritical] // auto-generated - private Object ForwardCallToInvokeMember(String memberName, BindingFlags flags, Object target, int[] aWrapperTypes, ref MessageData msgData) - { - ParameterModifier[] aParamMod = null; - Object ret = null; - - // Allocate a new message - Message reqMsg = new Message(); - reqMsg.InitFields(msgData); - - // Retrieve the required information from the message object. - MethodInfo meth = (MethodInfo)reqMsg.GetMethodBase(); - Object[] aArgs = reqMsg.Args; - int cArgs = aArgs.Length; - - // Retrieve information from the method we are invoking on. - ParameterInfo[] aParams = meth.GetParametersNoCopy(); - - // If we have arguments, then set the byref flags to true for byref arguments. - // We also wrap the arguments that require wrapping. - if (cArgs > 0) - { - ParameterModifier paramMod = new ParameterModifier(cArgs); - for (int i = 0; i < cArgs; i++) - { - if (aParams[i].ParameterType.IsByRef) - paramMod[i] = true; - } - - aParamMod = new ParameterModifier[1]; - aParamMod[0] = paramMod; - - if (aWrapperTypes != null) - WrapArgsForInvokeCall(aArgs, aWrapperTypes); - } - - // If the method has a void return type, then set the IgnoreReturn binding flag. - if (Object.ReferenceEquals(meth.ReturnType, typeof(void))) - flags |= BindingFlags.IgnoreReturn; - - try - { - // Invoke the method using InvokeMember(). - ret = InvokeMember(memberName, flags, null, target, aArgs, aParamMod, null, null); - } - catch (TargetInvocationException e) - { - // For target invocation exceptions, we need to unwrap the inner exception and - // re-throw it. - throw e.InnerException; - } - - // Convert each byref argument that is not of the proper type to - // the parameter type using the OleAutBinder. - for (int i = 0; i < cArgs; i++) - { - if (aParamMod[0][i] && aArgs[i] != null) - { - // The parameter is byref. - Type paramType = aParams[i].ParameterType.GetElementType(); - if (!Object.ReferenceEquals(paramType, aArgs[i].GetType())) - aArgs[i] = ForwardCallBinder.ChangeType(aArgs[i], paramType, null); - } - } - - // If the return type is not of the proper type, then convert it - // to the proper type using the OleAutBinder. - if (ret != null) - { - Type retType = meth.ReturnType; - if (!Object.ReferenceEquals(retType, ret.GetType())) - ret = ForwardCallBinder.ChangeType(ret, retType, null); - } - - // Propagate the out parameters - RealProxy.PropagateOutParameters(reqMsg, aArgs, ret); - - // Return the value returned by the InvokeMember call. - return ret; - } - - [SecuritySafeCritical] - private void WrapArgsForInvokeCall(Object[] aArgs, int[] aWrapperTypes) - { - int cArgs = aArgs.Length; - for (int i = 0; i < cArgs; i++) - { - if (aWrapperTypes[i] == 0) - continue; - - if (((DispatchWrapperType)aWrapperTypes[i] & DispatchWrapperType.SafeArray) != 0) - { - Type wrapperType = null; - bool isString = false; - - // Determine the type of wrapper to use. - switch ((DispatchWrapperType)aWrapperTypes[i] & ~DispatchWrapperType.SafeArray) - { - case DispatchWrapperType.Unknown: - wrapperType = typeof(UnknownWrapper); - break; - case DispatchWrapperType.Dispatch: - wrapperType = typeof(DispatchWrapper); - break; - case DispatchWrapperType.Error: - wrapperType = typeof(ErrorWrapper); - break; - case DispatchWrapperType.Currency: - wrapperType = typeof(CurrencyWrapper); - break; - case DispatchWrapperType.BStr: - wrapperType = typeof(BStrWrapper); - isString = true; - break; - default: - Contract.Assert(false, "[RuntimeType.WrapArgsForInvokeCall]Invalid safe array wrapper type specified."); - break; - } - - // Allocate the new array of wrappers. - Array oldArray = (Array)aArgs[i]; - int numElems = oldArray.Length; - Object[] newArray = (Object[])Array.UnsafeCreateInstance(wrapperType, numElems); - - // Retrieve the ConstructorInfo for the wrapper type. - ConstructorInfo wrapperCons; - if(isString) - { - wrapperCons = wrapperType.GetConstructor(new Type[] {typeof(String)}); - } - else - { - wrapperCons = wrapperType.GetConstructor(new Type[] {typeof(Object)}); - } - - // Wrap each of the elements of the array. - for (int currElem = 0; currElem < numElems; currElem++) - { - if(isString) - { - newArray[currElem] = wrapperCons.Invoke(new Object[] {(String)oldArray.GetValue(currElem)}); - } - else - { - newArray[currElem] = wrapperCons.Invoke(new Object[] {oldArray.GetValue(currElem)}); - } - } - - // Update the argument. - aArgs[i] = newArray; - } - else - { - // Determine the wrapper to use and then wrap the argument. - switch ((DispatchWrapperType)aWrapperTypes[i]) - { - case DispatchWrapperType.Unknown: - aArgs[i] = new UnknownWrapper(aArgs[i]); - break; - case DispatchWrapperType.Dispatch: - aArgs[i] = new DispatchWrapper(aArgs[i]); - break; - case DispatchWrapperType.Error: - aArgs[i] = new ErrorWrapper(aArgs[i]); - break; - case DispatchWrapperType.Currency: - aArgs[i] = new CurrencyWrapper(aArgs[i]); - break; - case DispatchWrapperType.BStr: - aArgs[i] = new BStrWrapper((String)aArgs[i]); - break; - default: - Contract.Assert(false, "[RuntimeType.WrapArgsForInvokeCall]Invalid wrapper type specified."); - break; - } - } - } - } - - private OleAutBinder ForwardCallBinder - { - get - { - // Synchronization is not required. - if (s_ForwardCallBinder == null) - s_ForwardCallBinder = new OleAutBinder(); - - return s_ForwardCallBinder; - } - } - - [Flags] - private enum DispatchWrapperType : int - { - // This enum must stay in sync with the DispatchWrapperType enum defined in MLInfo.h - Unknown = 0x00000001, - Dispatch = 0x00000002, - Record = 0x00000004, - Error = 0x00000008, - Currency = 0x00000010, - BStr = 0x00000020, - SafeArray = 0x00010000 - } - - private static volatile OleAutBinder s_ForwardCallBinder; -#endif // FEATURE_COMINTEROP && FEATURE_REMOTING #endregion } diff --git a/src/coreclr/src/mscorlib/src/System/Runtime/InteropServices/ComEventsHelper.cs b/src/coreclr/src/mscorlib/src/System/Runtime/InteropServices/ComEventsHelper.cs index 0bf616d..4230428 100644 --- a/src/coreclr/src/mscorlib/src/System/Runtime/InteropServices/ComEventsHelper.cs +++ b/src/coreclr/src/mscorlib/src/System/Runtime/InteropServices/ComEventsHelper.cs @@ -184,17 +184,8 @@ namespace System.Runtime.InteropServices { } [System.Security.SecurityCritical] - internal static object UnwrapIfTransparentProxy(object rcw) { -#if FEATURE_REMOTING - if (RemotingServices.IsTransparentProxy(rcw)) { - IntPtr punk = Marshal.GetIUnknownForObject(rcw); - try { - rcw = Marshal.GetObjectForIUnknown(punk); - } finally { - Marshal.Release(punk); - } - } -#endif + internal static object UnwrapIfTransparentProxy(object rcw) + { return rcw; } } diff --git a/src/coreclr/src/mscorlib/src/System/Runtime/InteropServices/RegistrationServices.cs b/src/coreclr/src/mscorlib/src/System/Runtime/InteropServices/RegistrationServices.cs index 9fd818d..5fa059d 100644 --- a/src/coreclr/src/mscorlib/src/System/Runtime/InteropServices/RegistrationServices.cs +++ b/src/coreclr/src/mscorlib/src/System/Runtime/InteropServices/RegistrationServices.cs @@ -937,20 +937,12 @@ namespace System.Runtime.InteropServices { private static bool ManagedCategoryExists() { using (RegistryKey componentCategoryKey = Registry.ClassesRoot.OpenSubKey(strComponentCategorySubKey, -#if FEATURE_MACL - RegistryKeyPermissionCheck.ReadSubTree)) -#else false)) -#endif { if (componentCategoryKey == null) return false; using (RegistryKey managedCategoryKey = componentCategoryKey.OpenSubKey(strManagedCategoryGuid, -#if FEATURE_MACL - RegistryKeyPermissionCheck.ReadSubTree)) -#else false)) -#endif { if (managedCategoryKey == null) return false; diff --git a/src/coreclr/src/mscorlib/src/System/Runtime/Remoting/ObjectHandle.cs b/src/coreclr/src/mscorlib/src/System/Runtime/Remoting/ObjectHandle.cs index d10df9d..5555670 100644 --- a/src/coreclr/src/mscorlib/src/System/Runtime/Remoting/ObjectHandle.cs +++ b/src/coreclr/src/mscorlib/src/System/Runtime/Remoting/ObjectHandle.cs @@ -14,23 +14,14 @@ ** ===========================================================*/ -namespace System.Runtime.Remoting{ - +namespace System.Runtime.Remoting +{ using System; - using System.Security.Permissions; using System.Runtime.InteropServices; - using System.Runtime.Remoting; -#if FEATURE_REMOTING - using System.Runtime.Remoting.Activation; - using System.Runtime.Remoting.Lifetime; -#endif [ClassInterface(ClassInterfaceType.AutoDual)] [System.Runtime.InteropServices.ComVisible(true)] public class ObjectHandle: -#if FEATURE_REMOTING - MarshalByRefObject, -#endif IObjectHandle { private Object WrappedObject; @@ -48,34 +39,5 @@ namespace System.Runtime.Remoting{ { return WrappedObject; } - - // ObjectHandle has a finite lifetime. For now the default - // lifetime is being used, this can be changed in this method to - // specify a custom lifetime. -#if FEATURE_REMOTING - [System.Security.SecurityCritical] // auto-generated_required - public override Object InitializeLifetimeService() - { - BCLDebug.Trace("REMOTE", "ObjectHandle.InitializeLifetimeService"); - - // - // If the wrapped object has implemented InitializeLifetimeService to return null, - // we don't want to go to the base class (which will result in a lease being - // requested from the MarshalByRefObject, which starts up the LeaseManager, - // which starts up the ThreadPool, adding three threads to the process. - // We check if the wrapped object is a MarshalByRef object, and call InitializeLifetimeServices on it - // and if it returns null, we return null. Otherwise we fall back to the old behavior. - // - - MarshalByRefObject mbr = WrappedObject as MarshalByRefObject; - if (mbr != null) { - Object o = mbr.InitializeLifetimeService(); - if (o == null) - return null; - } - ILease lease = (ILease)base.InitializeLifetimeService(); - return lease; - } -#endif // FEATURE_REMOTING } } diff --git a/src/coreclr/src/mscorlib/src/System/Runtime/Serialization/FormatterServices.cs b/src/coreclr/src/mscorlib/src/System/Runtime/Serialization/FormatterServices.cs index 82fb362..c2911d9 100644 --- a/src/coreclr/src/mscorlib/src/System/Runtime/Serialization/FormatterServices.cs +++ b/src/coreclr/src/mscorlib/src/System/Runtime/Serialization/FormatterServices.cs @@ -230,14 +230,9 @@ namespace System.Runtime.Serialization { static readonly Type[] advancedTypes = new Type[]{ typeof(System.DelegateSerializationHolder), -#if FEATURE_REMOTING - typeof(System.Runtime.Remoting.ObjRef), - typeof(System.Runtime.Remoting.IEnvoyInfo), - typeof(System.Runtime.Remoting.Lifetime.ISponsor), -#endif }; - - public static void CheckTypeSecurity(Type t, TypeFilterLevel securityLevel) { + + public static void CheckTypeSecurity(Type t, TypeFilterLevel securityLevel) { if (securityLevel == TypeFilterLevel.Low){ for(int i=0;i "; -#if FEATURE_CAS_POLICY - private const string s_wpfExtensionXml = - @" - - - "; - - private const string s_wpfExtensionUnrestrictedXml = - @" - - - "; -#endif //FEATURE_CAS_POLICY - // // Built in permission set objects // @@ -222,11 +198,7 @@ namespace System.Security internal static NamedPermissionSet Everything { - get { return GetOrDeserializeExtendablePermissionSet(ref s_everything, s_everythingXml -#if FEATURE_CAS_POLICY - , s_wpfExtensionUnrestrictedXml -#endif // FEATURE_CAS_POLICY - ); } + get { return GetOrDeserializeExtendablePermissionSet(ref s_everything, s_everythingXml); } } internal static NamedPermissionSet Execution @@ -241,20 +213,12 @@ namespace System.Security internal static NamedPermissionSet Internet { - get { return GetOrDeserializeExtendablePermissionSet(ref s_internet, s_internetXml -#if FEATURE_CAS_POLICY - , s_wpfExtensionXml -#endif // FEATURE_CAS_POLICY - ); } + get { return GetOrDeserializeExtendablePermissionSet(ref s_internet, s_internetXml); } } internal static NamedPermissionSet LocalIntranet { - get { return GetOrDeserializeExtendablePermissionSet(ref s_localIntranet, s_localIntranetXml -#if FEATURE_CAS_POLICY - , s_wpfExtensionXml -#endif // FEATURE_CAS_POLICY - ); } + get { return GetOrDeserializeExtendablePermissionSet(ref s_localIntranet, s_localIntranetXml); } } internal static NamedPermissionSet Nothing @@ -272,31 +236,11 @@ namespace System.Security // set extensions if necessary // - private static NamedPermissionSet GetOrDeserializeExtendablePermissionSet(ref NamedPermissionSet permissionSet, - string permissionSetXml -#if FEATURE_CAS_POLICY - ,string extensionXml -#endif // FEATURE_CAS_POLICY - ) + private static NamedPermissionSet GetOrDeserializeExtendablePermissionSet( + ref NamedPermissionSet permissionSet, + string permissionSetXml) { Contract.Requires(!String.IsNullOrEmpty(permissionSetXml)); -#if FEATURE_CAS_POLICY - Contract.Requires(!String.IsNullOrEmpty(extensionXml)); -#endif // FEATURE_CAS_POLICY - - if (permissionSet == null) - { -#if FEATURE_CAS_POLICY - SecurityElement securityElement = SecurityElement.FromString(permissionSetXml); - NamedPermissionSet deserializedPermissionSet = new NamedPermissionSet(securityElement); - - PermissionSet extensions = GetPermissionSetExtensions(extensionXml); - deserializedPermissionSet.InplaceUnion(extensions); - - permissionSet = deserializedPermissionSet; -#endif // FEATURE_CAS_POLICY - } - return permissionSet.Copy() as NamedPermissionSet; } @@ -304,39 +248,7 @@ namespace System.Security string permissionSetXml) { Contract.Assert(!String.IsNullOrEmpty(permissionSetXml)); - -#if FEATURE_CAS_POLICY - if (permissionSet == null) - { - SecurityElement securityElement = SecurityElement.FromString(permissionSetXml); - NamedPermissionSet deserializedPermissionSet = new NamedPermissionSet(securityElement); - - permissionSet = deserializedPermissionSet; - } -#endif // FEATURE_CAS_POLICY - return permissionSet.Copy() as NamedPermissionSet; } - -#if FEATURE_CAS_POLICY - private static PermissionSet GetPermissionSetExtensions(string extensionXml) - { - Contract.Requires(!String.IsNullOrEmpty(extensionXml)); - - SecurityElement se = SecurityElement.FromString(extensionXml); - - // Return the permission set extension only if WPF is in the present framework profile. - // XMLUtil.GetClassFromElement() helps do the quickest check, with no exception thrown and - // minimal parsing. - SecurityElement firstPermission = (SecurityElement)se.Children[0]; - if (System.Security.Util.XMLUtil.GetClassFromElement(firstPermission, /*ignoreTypeLoadFailures*/true) != null) - { - PermissionSet extensions = new NamedPermissionSet(se); - return extensions; - } - - return null; - } -#endif // FEATURE_CAS_POLICY } } diff --git a/src/coreclr/src/mscorlib/src/System/Security/CodeAccessPermission.cs b/src/coreclr/src/mscorlib/src/System/Security/CodeAccessPermission.cs index 46a1286..16f3a5b 100644 --- a/src/coreclr/src/mscorlib/src/System/Security/CodeAccessPermission.cs +++ b/src/coreclr/src/mscorlib/src/System/Security/CodeAccessPermission.cs @@ -160,48 +160,6 @@ namespace System.Security // otherwise we don't support it. throw new NotSupportedException(Environment.GetResourceString( "NotSupported_SecurityPermissionUnion" )); } - -#if FEATURE_CAS_POLICY - static internal SecurityElement CreatePermissionElement( IPermission perm, String permname ) - { - SecurityElement root = new SecurityElement( "IPermission" ); - XMLUtil.AddClassAttribute( root, perm.GetType(), permname ); - // If you hit this assert then most likely you are trying to change the name of this class. - // This is ok as long as you change the hard coded string above and change the assert below. - Contract.Assert( perm.GetType().FullName.Equals( permname ), "Incorrect class name passed in! Was: " + permname + " Should be " + perm.GetType().FullName); - - root.AddAttribute( "version", "1" ); - return root; - } - - static internal void ValidateElement( SecurityElement elem, IPermission perm ) - { - if (elem == null) - throw new ArgumentNullException( nameof(elem) ); - Contract.EndContractBlock(); - - if (!XMLUtil.IsPermissionElement( perm, elem )) - throw new ArgumentException( Environment.GetResourceString( "Argument_NotAPermissionElement")); - - String version = elem.Attribute( "version" ); - - if (version != null && !version.Equals( "1" )) - throw new ArgumentException( Environment.GetResourceString( "Argument_InvalidXMLBadVersion") ); - } - - abstract public SecurityElement ToXml(); - abstract public void FromXml( SecurityElement elem ); - - // - // Unimplemented interface methods - // (as a reminder only) - // - - public override String ToString() - { - return ToXml().ToString(); - } -#endif // FEATURE_CAS_POLICY // // HELPERS FOR IMPLEMENTING ABSTRACT METHODS diff --git a/src/coreclr/src/mscorlib/src/System/Security/CodeAccessSecurityEngine.cs b/src/coreclr/src/mscorlib/src/System/Security/CodeAccessSecurityEngine.cs index 2a1cf9a..ca65cc1 100644 --- a/src/coreclr/src/mscorlib/src/System/Security/CodeAccessSecurityEngine.cs +++ b/src/coreclr/src/mscorlib/src/System/Security/CodeAccessSecurityEngine.cs @@ -109,10 +109,6 @@ namespace System.Security { // there will be an infinite recursion that overflows the stack. PermissionSet.s_fullTrust.Assert(); asmName = asm.GetName(); -#if FEATURE_CAS_POLICY - if(asm != Assembly.GetExecutingAssembly()) // this condition is to avoid having to marshal mscorlib's evidence (which is always in teh default domain) to the current domain - asmEvidence = asm.Evidence; -#endif // FEATURE_CAS_POLICY } throw SecurityException.MakeSecurityException(asmName, asmEvidence, granted, refused, rmh, action, demand, permThatFailed); } @@ -183,19 +179,7 @@ namespace System.Security { bool throwException) #pragma warning restore 618 { - Contract.Assert(demands != null, "Should not reach here with a null demand set"); -#if _DEBUG && FEATURE_CAS_POLICY - if (debug) - { - DEBUG_OUT("Granted: "); - DEBUG_OUT(grants.ToXml().ToString()); - DEBUG_OUT("Refused: "); - DEBUG_OUT(refused != null ? refused.ToXml().ToString() : ""); - DEBUG_OUT("Demanded: "); - DEBUG_OUT(demands!=null ? demands.ToXml().ToString() : ""); - } -#endif // _DEBUG && FEATURE_CAS_POLICY IPermission permThatFailed = null; if (grants != null) @@ -299,18 +283,6 @@ namespace System.Security { { // We should never get here with a null demand Contract.Assert(demand != null, "Should not reach here with a null demand"); - -#if _DEBUG && FEATURE_CAS_POLICY - if (debug) - { - DEBUG_OUT("Granted: "); - DEBUG_OUT(grantedSet.ToXml().ToString()); - DEBUG_OUT("Refused: "); - DEBUG_OUT(refusedSet != null ? refusedSet.ToXml().ToString() : ""); - DEBUG_OUT("Demanded: "); - DEBUG_OUT(demand.ToString()); - } -#endif // _DEBUG && FEATURE_CAS_POLICY if (permToken == null) permToken = PermissionToken.GetToken(demand); @@ -411,187 +383,15 @@ namespace System.Security { return true; } -#if FEATURE_CAS_POLICY - /// - /// Demand for the grant set of an assembly - /// - /// - /// Managed half of SecurityStackWalk::DemandGrantSet. - /// - [System.Security.SecurityCritical] // auto-generated - private static void CheckGrantSetHelper(PermissionSet grantSet) - { - Contract.Assert(grantSet != null, "Missing grant set"); - grantSet.CopyWithNoIdentityPermissions().Demand(); - } - - /// - /// Perform a security demand which succeeds if either a compatibilty permission is granted to the - /// call stack, or restricted member access and the grant set of the target of the reflection - /// operation is granted. - /// - /// compatibility permission to check - /// grant set of the reflection target - [System.Security.SecurityCritical] // auto-generated - internal static void ReflectionTargetDemandHelper(PermissionType permission, PermissionSet targetGrant) - { - ReflectionTargetDemandHelper((int)permission, targetGrant); - } - - /// - /// Perform a security demand which succeeds if either a compatibilty permission is granted to the - /// call stack, or restricted member access and the grant set of the target of the reflection - /// operation is granted. - /// - /// - /// Managed half of SecurityStackWalk::ReflectionTargetDemand. - /// - /// compatibility permission to check (See PermissionType) - /// grant set of the reflection target - [System.Security.SecurityCritical] // auto-generated - [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable - private static void ReflectionTargetDemandHelper(int permission, PermissionSet targetGrant) - { - // Capture a compressed stack so that we can make both permission checks without walking the stack - // multiple times. - StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; - CompressedStack cs = CompressedStack.GetCompressedStack(ref stackMark); - - ReflectionTargetDemandHelper(permission, targetGrant, cs); - } - - /// - /// Perform a reflection target demand against a given access context - /// - /// - /// Managed half of SecurityStackWalk::ReflectionTargetDemand - /// - /// compatibility permission to check (See PermissionType) - /// grant set of the reflection target - /// access context to do the demand against - [System.Security.SecurityCritical] // auto-generated - private static void ReflectionTargetDemandHelper(int permission, - PermissionSet targetGrant, - Resolver accessContext) - { - ReflectionTargetDemandHelper(permission, targetGrant, accessContext.GetSecurityContext()); - } - - /// - /// Perform a reflection target demand against a given compressed stack - /// - /// - /// Managed half of SecurityStackWalk::ReflectionTargetDemand - /// - /// compatibility permission to check (See PermissionType) - /// grant set of the reflection target - /// compressed stack to do the demand against - [System.Security.SecurityCritical] // auto-generated - private static void ReflectionTargetDemandHelper(int permission, - PermissionSet targetGrant, - CompressedStack securityContext) - { - Contract.Assert(securityContext != null, "securityContext != null"); - - // We need to remove all identity permissions from the grant set of the target, otherwise the - // disjunctive demand will fail unless we're reflecting on the same assembly. - PermissionSet demandSet = null; - if (targetGrant == null) - { - demandSet = new PermissionSet(PermissionState.Unrestricted); - } - else - { - demandSet = targetGrant.CopyWithNoIdentityPermissions(); - demandSet.AddPermission(new ReflectionPermission(ReflectionPermissionFlag.RestrictedMemberAccess)); - } - - securityContext.DemandFlagsOrGrantSet((1 << (int)permission), demandSet); - } - - [System.Security.SecurityCritical] // auto-generated - internal static void GetZoneAndOriginHelper( CompressedStack cs, PermissionSet grantSet, PermissionSet refusedSet, ArrayList zoneList, ArrayList originList ) - { - if (cs != null) - cs.GetZoneAndOrigin(zoneList, originList, PermissionToken.GetToken(typeof(ZoneIdentityPermission)), PermissionToken.GetToken(typeof(UrlIdentityPermission))); - else - { - ZoneIdentityPermission zone = (ZoneIdentityPermission)grantSet.GetPermission( typeof( ZoneIdentityPermission ) ); - UrlIdentityPermission url = (UrlIdentityPermission)grantSet.GetPermission( typeof( UrlIdentityPermission ) ); - - if (zone != null) - zoneList.Add( zone.SecurityZone ); - - if (url != null) - originList.Add( url.Url ); - } - } - - [System.Security.SecurityCritical] // auto-generated - internal static void GetZoneAndOrigin( ref StackCrawlMark mark, out ArrayList zone, out ArrayList origin ) - { - zone = new ArrayList(); - origin = new ArrayList(); - - GetZoneAndOriginInternal( zone, origin, ref mark); - } - - [System.Security.SecurityCritical] // auto-generated - [MethodImplAttribute(MethodImplOptions.InternalCall)] - private static extern void GetZoneAndOriginInternal(ArrayList zoneList, - ArrayList originList, - ref StackCrawlMark stackMark); - - [System.Security.SecurityCritical] // auto-generated - internal static void CheckAssembly(RuntimeAssembly asm, CodeAccessPermission demand ) - { - Contract.Assert( asm != null, "Must pass in a good assembly" ); - Contract.Assert( demand != null, "Must pass in a good demand" ); - - PermissionSet granted, refused; - asm.GetGrantSet( out granted, out refused ); -#pragma warning disable 618 - CheckHelper( granted, refused, demand, PermissionToken.GetToken(demand), RuntimeMethodHandleInternal.EmptyHandle, asm, SecurityAction.Demand, true ); -#pragma warning restore 618 - } - - // Check - Used to initiate a code-access security check. - // This method invokes a stack walk after skipping to the frame - // referenced by stackMark. - [System.Security.SecurityCritical] // auto-generated - [MethodImplAttribute(MethodImplOptions.InternalCall)] - private static extern void Check (Object demand, - ref StackCrawlMark stackMark, - bool isPermSet); - - - [System.Security.SecurityCritical] // auto-generated - [MethodImplAttribute(MethodImplOptions.InternalCall)] - internal static extern bool QuickCheckForAllDemands(); - [System.Security.SecurityCritical] // auto-generated - [MethodImplAttribute(MethodImplOptions.InternalCall)] - internal static extern bool AllDomainsHomogeneousWithNoStackModifiers(); -#endif // FEATURE_CAS_POLICY - [System.Security.SecurityCritical] // auto-generated internal static void Check(CodeAccessPermission cap, ref StackCrawlMark stackMark) { -#if FEATURE_CAS_POLICY - Check(cap, - ref stackMark, - false); -#endif // FEATURE_CAS_POLICY } [System.Security.SecurityCritical] // auto-generated internal static void Check(PermissionSet permSet, ref StackCrawlMark stackMark) { -#if FEATURE_CAS_POLICY - Check(permSet, - ref stackMark, - true); -#endif // FEATURE_CAS_POLICY } [System.Security.SecurityCritical] // auto-generated @@ -604,223 +404,17 @@ namespace System.Security { [System.Security.SecurityCritical] // auto-generated internal static void Assert(CodeAccessPermission cap, ref StackCrawlMark stackMark) { -#if FEATURE_CAS_POLICY - // Make sure the caller of assert has the permission to assert - //WARNING: The placement of the call here is just right to check - // the appropriate frame. - - // Note: if the "AssertPermission" is not a permission that implements IUnrestrictedPermission - // you need to change the last parameter to a zero. - Contract.Assert(AssertPermissionToken != null && AssertPermission != null, "Assert Permission not setup correctly"); - FrameSecurityDescriptor secObj = CheckNReturnSO(AssertPermissionToken, - AssertPermission, - ref stackMark, - 1 ); - if (secObj == null) - { - // Security: REQ_SQ flag is missing. Bad compiler ? - // This can happen when you create delegates over functions that need the REQ_SQ - System.Environment.FailFast(Environment.GetResourceString("ExecutionEngine_MissingSecurityDescriptor")); - } - else - { - if (secObj.HasImperativeAsserts()) - throw new SecurityException( Environment.GetResourceString( "Security_MustRevertOverride" ) ); - - secObj.SetAssert(cap); - } -#endif // FEATURE_CAS_POLICY } [System.Security.SecurityCritical] // auto-generated internal static void Deny(CodeAccessPermission cap, ref StackCrawlMark stackMark) { -#if FEATURE_CAS_POLICY - // Deny is only valid in legacy mode - if (!AppDomain.CurrentDomain.IsLegacyCasPolicyEnabled) - { - throw new NotSupportedException(Environment.GetResourceString("NotSupported_CasDeny")); - } - - FrameSecurityDescriptor secObj = - SecurityRuntime.GetSecurityObjectForFrame(ref stackMark, true); - if (secObj == null) - { - // Security: REQ_SQ flag is missing. Bad compiler ? - // This can happen when you create delegates over functions that need the REQ_SQ - System.Environment.FailFast(Environment.GetResourceString("ExecutionEngine_MissingSecurityDescriptor")); - } - else - { - if (secObj.HasImperativeDenials()) - throw new SecurityException( Environment.GetResourceString( "Security_MustRevertOverride" ) ); - - secObj.SetDeny(cap); - } -#endif // FEATURE_CAS_POLICY } [System.Security.SecurityCritical] // auto-generated internal static void PermitOnly(CodeAccessPermission cap, ref StackCrawlMark stackMark) { -#if FEATURE_CAS_POLICY - FrameSecurityDescriptor secObj = - SecurityRuntime.GetSecurityObjectForFrame(ref stackMark, true); - if (secObj == null) - { - // Security: REQ_SQ flag is missing. Bad compiler ? - // This can happen when you create delegates over functions that need the REQ_SQ - System.Environment.FailFast(Environment.GetResourceString("ExecutionEngine_MissingSecurityDescriptor")); - } - else - { - if (secObj.HasImperativeRestrictions()) - throw new SecurityException( Environment.GetResourceString( "Security_MustRevertOverride" ) ); - - secObj.SetPermitOnly(cap); - } -#endif // FEATURE_CAS_POLICY - } - -#if FEATURE_CAS_POLICY - // Called from the VM to do a pre-domain initialization check of the security state of the - // AppDomain. This method looks at the state of the security of an AppDomain before it is - // completely initialized - so the output of this method does not always match what will be true - // when the domain is completely initialized. Instead, it is used to read what the input parameters - // to the domain setup say about the domain. - private static void PreResolve(out bool isFullyTrusted, out bool isHomogeneous) - { - // - // There are three main cases: - // 1. The AppDomain has an explict ApplicationTrust - we can use this to read the input state - // of the AppDomain. - // 2. The AppDomain is using legacy CAS policy - this means we can't tell much about the - // domain itself without a full policy resolution. - // 3. The domain is a standard v4+ AppDomain - these are always full trust and homogenous by - // default. - // - - // If the AppDomain is setup with an ApplicationTrust then it is always homogenous and we can - // tell its grant set right from the ApplicaitonTrust - ApplicationTrust domainTrust = AppDomain.CurrentDomain.SetupInformation.ApplicationTrust; - if (domainTrust != null) - { - isFullyTrusted = domainTrust.DefaultGrantSet.PermissionSet.IsUnrestricted(); - isHomogeneous = true; - return; - } - - // Otherwise, see if the domain is being configured on input to use legacy CAS policy - if (CompatibilitySwitches.IsNetFx40LegacySecurityPolicy || AppDomain.CurrentDomain.IsLegacyCasPolicyEnabled) - { - isFullyTrusted = false; - isHomogeneous = false; - return; - } - - // If none of the above is true, then we must be a standard AppDomain - isFullyTrusted = true; - isHomogeneous = true; - } - - // Called from the VM when either a HostSecurityManager or simple sandbox domain can determine the - // grant set of an assembly - private static PermissionSet ResolveGrantSet(Evidence evidence, out int specialFlags, bool checkExecutionPermission) - { - Contract.Assert(evidence != null); - Contract.Assert(!AppDomain.CurrentDomain.IsLegacyCasPolicyEnabled); // This API does not do CAS policy resolution - - PermissionSet grantSet = null; - if (!TryResolveGrantSet(evidence, out grantSet)) - { - // If we couldn't figure out a grant set from the domain or the host, then we treat the - // assembly as fully trusted. - grantSet = new PermissionSet(PermissionState.Unrestricted); - } - - // Make sure the grant set includes the ability to execute code if that has been requested. - if (checkExecutionPermission) - { - SecurityPermission executionPermission = new SecurityPermission(SecurityPermissionFlag.Execution); - if (!grantSet.Contains(executionPermission)) - { - throw new PolicyException(Environment.GetResourceString("Policy_NoExecutionPermission"), - System.__HResults.CORSEC_E_NO_EXEC_PERM); - } - } - - specialFlags = SecurityManager.GetSpecialFlags(grantSet, null); - return grantSet; - } - - // Consult the host and the current AppDomain if it is homogenous to determine what the grant set - // of an assembly is. This API returns true if it was able to determine a grant set for the evidence, - // false if it cannot and other policy needs to be applied. - [SecuritySafeCritical] - internal static bool TryResolveGrantSet(Evidence evidence, out PermissionSet grantSet) - { - Contract.Assert(evidence != null); - - HostSecurityManager securityManager = AppDomain.CurrentDomain.HostSecurityManager; - - // GAC assemblies always are fully trusted - if (evidence.GetHostEvidence() != null) - { - grantSet = new PermissionSet(PermissionState.Unrestricted); - return true; - } - // If the host wants to participate in policy resolution, then our next option is to ask it for - // a grant set - else if ((securityManager.Flags & HostSecurityManagerOptions.HostResolvePolicy) == HostSecurityManagerOptions.HostResolvePolicy) - { - PermissionSet hostGrantSet = securityManager.ResolvePolicy(evidence); - - if (hostGrantSet == null) - { - throw new PolicyException(Environment.GetResourceString("Policy_NullHostGrantSet", securityManager.GetType().FullName)); - } - - // If we're in a homogenous domain, we don't want to allow the host to create multiple - // levels of permissions within the domain. So, if we see the host return something other - // than full trust or the homogenous grant set, we reject the grant set. - if (AppDomain.CurrentDomain.IsHomogenous) - { - // Some hosts, such as ASP.NET, return Nothing as a way of saying that the assembly should - // not be allowed to run in the AppDomain. Reject that with a specific - // no-execution-allowed-here exception message, rather than the return value validation - // exception message we'd hit below. - if (hostGrantSet.IsEmpty()) - { - throw new PolicyException(Environment.GetResourceString("Policy_NoExecutionPermission")); - } - - PermissionSet homogenousGrantSet = AppDomain.CurrentDomain.ApplicationTrust.DefaultGrantSet.PermissionSet; - bool isValidGrantSet = hostGrantSet.IsUnrestricted() || - (hostGrantSet.IsSubsetOf(homogenousGrantSet) && homogenousGrantSet.IsSubsetOf(hostGrantSet)); - - if (!isValidGrantSet) - { - throw new PolicyException(Environment.GetResourceString("Policy_GrantSetDoesNotMatchDomain", securityManager.GetType().FullName)); - } - } - - grantSet = hostGrantSet; - return true; - } - // If we're in a homogenous domain, we can get the grant set directly from the application trust - else if (AppDomain.CurrentDomain.IsHomogenous) - { - grantSet = AppDomain.CurrentDomain.GetHomogenousGrantSet(evidence); - return true; - } - // Otherwise we have no way to figure out what the grant set is - else - { - grantSet = null; - return false; - } } -#endif // FEATURE_CAS_POLICY #if FEATURE_PLS // Update the PLS used for optimization in the AppDomain: called from the VM diff --git a/src/coreclr/src/mscorlib/src/System/Security/FrameSecurityDescriptor.cs b/src/coreclr/src/mscorlib/src/System/Security/FrameSecurityDescriptor.cs index 8f25bda..f49a377 100644 --- a/src/coreclr/src/mscorlib/src/System/Security/FrameSecurityDescriptor.cs +++ b/src/coreclr/src/mscorlib/src/System/Security/FrameSecurityDescriptor.cs @@ -144,13 +144,8 @@ namespace System.Security { [System.Security.SecurityCritical] // auto-generated internal void SetDeny(IPermission perm) { -#if FEATURE_CAS_POLICY - BCLDebug.Assert(AppDomain.CurrentDomain.IsLegacyCasPolicyEnabled, "Deny is only valid in legacy CAS mode"); -#endif // FEATURE_CAS_POLICY - m_denials = CreateSingletonSet(perm); IncrementOverridesCount(); - } [System.Security.SecurityCritical] // auto-generated diff --git a/src/coreclr/src/mscorlib/src/System/Security/HostSecurityManager.cs b/src/coreclr/src/mscorlib/src/System/Security/HostSecurityManager.cs index 15d98c0..2da75ce 100644 --- a/src/coreclr/src/mscorlib/src/System/Security/HostSecurityManager.cs +++ b/src/coreclr/src/mscorlib/src/System/Security/HostSecurityManager.cs @@ -52,20 +52,6 @@ namespace System.Security } } -#if FEATURE_CAS_POLICY - // provide policy for the AppDomain. - [Obsolete("AppDomain policy levels are obsolete and will be removed in a future release of the .NET Framework. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.")] - public virtual PolicyLevel DomainPolicy { - get { - if (!AppDomain.CurrentDomain.IsLegacyCasPolicyEnabled) - { - throw new NotSupportedException(Environment.GetResourceString("NotSupported_RequiresCasPolicyExplicit")); - } - - return null; - } - } -#endif public virtual Evidence ProvideAppDomainEvidence (Evidence inputEvidence) { // The default implementation does not modify the input evidence. return inputEvidence; diff --git a/src/coreclr/src/mscorlib/src/System/Security/IEvidenceFactory.cs b/src/coreclr/src/mscorlib/src/System/Security/IEvidenceFactory.cs index 93f82a6..592ab53 100644 --- a/src/coreclr/src/mscorlib/src/System/Security/IEvidenceFactory.cs +++ b/src/coreclr/src/mscorlib/src/System/Security/IEvidenceFactory.cs @@ -2,19 +2,10 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -namespace System.Security { - using System.Runtime.Remoting; - using System; - using System.Security.Policy; -[System.Runtime.InteropServices.ComVisible(true)] +namespace System.Security +{ + [System.Runtime.InteropServices.ComVisible(true)] public interface IEvidenceFactory { -#if FEATURE_CAS_POLICY - Evidence Evidence - { - get; - } -#endif // FEATURE_CAS_POLICY } - } diff --git a/src/coreclr/src/mscorlib/src/System/Security/ISecurityEncodable.cs b/src/coreclr/src/mscorlib/src/System/Security/ISecurityEncodable.cs index 9915da3..689b3e4 100644 --- a/src/coreclr/src/mscorlib/src/System/Security/ISecurityEncodable.cs +++ b/src/coreclr/src/mscorlib/src/System/Security/ISecurityEncodable.cs @@ -8,22 +8,10 @@ // implement this interface // -namespace System.Security { - - using System; - using System.Security.Util; - - -[System.Runtime.InteropServices.ComVisible(true)] +namespace System.Security +{ + [System.Runtime.InteropServices.ComVisible(true)] public interface ISecurityEncodable { -#if FEATURE_CAS_POLICY - SecurityElement ToXml(); - - void FromXml( SecurityElement e ); -#endif // FEATURE_CAS_POLICY } - } - - diff --git a/src/coreclr/src/mscorlib/src/System/Security/ISecurityPolicyEncodable.cs b/src/coreclr/src/mscorlib/src/System/Security/ISecurityPolicyEncodable.cs index b1c8d16..567e41e 100644 --- a/src/coreclr/src/mscorlib/src/System/Security/ISecurityPolicyEncodable.cs +++ b/src/coreclr/src/mscorlib/src/System/Security/ISecurityPolicyEncodable.cs @@ -8,21 +8,10 @@ // implement this interface // -namespace System.Security { - - using System; - using System.Security.Util; - using System.Security.Policy; - - -[System.Runtime.InteropServices.ComVisible(true)] +namespace System.Security +{ + [System.Runtime.InteropServices.ComVisible(true)] public interface ISecurityPolicyEncodable { -#if FEATURE_CAS_POLICY - SecurityElement ToXml( PolicyLevel level ); - - void FromXml( SecurityElement e, PolicyLevel level ); -#endif // FEATURE_CAS_POLICY } - } diff --git a/src/coreclr/src/mscorlib/src/System/Security/NamedPermissionSet.cs b/src/coreclr/src/mscorlib/src/System/Security/NamedPermissionSet.cs index a8779ad..1bc166f 100644 --- a/src/coreclr/src/mscorlib/src/System/Security/NamedPermissionSet.cs +++ b/src/coreclr/src/mscorlib/src/System/Security/NamedPermissionSet.cs @@ -7,212 +7,19 @@ // Extends PermissionSet to allow an associated name and description // -namespace System.Security { - +namespace System.Security +{ using System; - using System.Security.Util; using System.Security.Permissions; - using System.Runtime.Serialization; - using System.Diagnostics.Contracts; -#if !FEATURE_CAS_POLICY - using Microsoft.Win32; - using System.Collections; - using System.Globalization; - using System.IO; - using System.Reflection; - using System.Runtime.InteropServices; - using System.Runtime.Remoting; - using System.Runtime.Versioning; - using System.Text; - -#else // FEATURE_CAS_POLICY - - using System.Threading; - -#endif // FEATURE_CAS_POLICY - [Serializable] -[System.Runtime.InteropServices.ComVisible(true)] + [System.Runtime.InteropServices.ComVisible(true)] public sealed class NamedPermissionSet : PermissionSet { -#if FEATURE_CAS_POLICY - // The name of this PermissionSet - private String m_name; - - // The description of this PermissionSet - private String m_description; - [OptionalField(VersionAdded = 2)] - internal String m_descrResource; - - internal NamedPermissionSet() - : base() - { - } - - public NamedPermissionSet( String name ) - : base() - { - CheckName( name ); - m_name = name; - } - - public NamedPermissionSet( String name, PermissionState state) - : base( state ) - { - CheckName( name ); - m_name = name; - } - - - public NamedPermissionSet( String name, PermissionSet permSet ) - : base( permSet ) - { - CheckName( name ); - m_name = name; - } - - public NamedPermissionSet( NamedPermissionSet permSet ) - : base( permSet ) - { - m_name = permSet.m_name; - m_description = permSet.Description; - } - - internal NamedPermissionSet(SecurityElement permissionSetXml) - : base(PermissionState.None) - { - Contract.Assert(permissionSetXml != null); - FromXml(permissionSetXml); - } - - public String Name { - get { return m_name; } - set { CheckName( value ); m_name = value; } - } - - private static void CheckName( String name ) - { - if (name == null || name.Equals( "" )) - throw new ArgumentException( Environment.GetResourceString( "Argument_NPMSInvalidName" )); - Contract.EndContractBlock(); - } - - public String Description { - get - { - if(m_descrResource != null) - { - m_description = Environment.GetResourceString(m_descrResource); - m_descrResource = null; - } - return m_description; - } - - set - { - m_description = value; - m_descrResource = null; - } - } - - public override PermissionSet Copy() - { - return new NamedPermissionSet( this ); - } - - public NamedPermissionSet Copy( String name ) - { - NamedPermissionSet set = new NamedPermissionSet( this ); - set.Name = name; - return set; - } - - public override SecurityElement ToXml() - { - SecurityElement elem = base.ToXml("System.Security.NamedPermissionSet"); - // If you hit this assert then most likely you are trying to change the name of this class. - // This is ok as long as you change the hard coded string above and change the assert below. - Contract.Assert( this.GetType().FullName.Equals( "System.Security.NamedPermissionSet" ), "Class name changed!" ); - - if (m_name != null && !m_name.Equals( "" )) - { - elem.AddAttribute( "Name", SecurityElement.Escape( m_name ) ); - } - - if (Description != null && !Description.Equals( "" )) - { - elem.AddAttribute( "Description", SecurityElement.Escape( Description ) ); - } - - return elem; - } - - public override void FromXml( SecurityElement et ) - { - FromXml( et, false, false ); - } - - internal override void FromXml( SecurityElement et, bool allowInternalOnly, bool ignoreTypeLoadFailures ) - { - if (et == null) - throw new ArgumentNullException( nameof(et) ); - Contract.EndContractBlock(); - - String elem; - - elem = et.Attribute( "Name" ); - m_name = elem == null ? null : elem; - - elem = et.Attribute( "Description" ); - m_description = (elem == null ? "" : elem); - m_descrResource = null; - - base.FromXml( et, allowInternalOnly, ignoreTypeLoadFailures ); - } - - internal void FromXmlNameOnly( SecurityElement et ) + internal static PermissionSet GetBuiltInSet(string name) { - // This function gets only the name for the permission set, ignoring all other info. - - String elem; - - elem = et.Attribute( "Name" ); - m_name = (elem == null ? null : elem); - } - - // NamedPermissionSet Equals should have the exact semantic as PermissionSet. - // We explicitly override them here to make sure that no one accidently - // changes this. - - [System.Runtime.InteropServices.ComVisible(false)] - public override bool Equals( Object obj ) - { - return base.Equals( obj ); - } - - [System.Runtime.InteropServices.ComVisible(false)] - public override int GetHashCode() - { - return base.GetHashCode(); - } - - private static Object s_InternalSyncObject; - private static Object InternalSyncObject { - get { - if (s_InternalSyncObject == null) { - Object o = new Object(); - Interlocked.CompareExchange(ref s_InternalSyncObject, o, null); - } - return s_InternalSyncObject; - } - } -#else // FEATURE_CAS_POLICY - - internal static PermissionSet GetBuiltInSet(string name) { // Used by PermissionSetAttribute to create one of the built-in, // immutable permission sets. - if (name == null) return null; else if (name.Equals("FullTrust")) @@ -264,6 +71,5 @@ namespace System.Security { } -#endif // !FEATURE_CAS_POLICY } } diff --git a/src/coreclr/src/mscorlib/src/System/Security/PermissionSet.cs b/src/coreclr/src/mscorlib/src/System/Security/PermissionSet.cs index 195323b..a587ae1 100644 --- a/src/coreclr/src/mscorlib/src/System/Security/PermissionSet.cs +++ b/src/coreclr/src/mscorlib/src/System/Security/PermissionSet.cs @@ -36,9 +36,6 @@ namespace System.Security { #if FEATURE_SERIALIZATION [Serializable] #endif -#if !FEATURE_CORECLR - [StrongNameIdentityPermissionAttribute(SecurityAction.InheritanceDemand, Name = "mscorlib", PublicKey = "0x" + AssemblyRef.EcmaPublicKeyFull)] -#endif [System.Runtime.InteropServices.ComVisible(true)] public class PermissionSet : ISecurityEncodable, ICollection, IStackWalk #if FEATURE_SERIALIZATION @@ -114,71 +111,13 @@ namespace System.Security { internal static readonly PermissionSet s_fullTrust = new PermissionSet( true ); -#if FEATURE_REMOTING - [OnDeserializing] - private void OnDeserializing(StreamingContext ctx) - { - Reset(); - } - - [OnDeserialized] - private void OnDeserialized(StreamingContext ctx) - { - if (m_serializedPermissionSet != null) - { - // Whidbey non X-AD case - FromXml(SecurityElement.FromString(m_serializedPermissionSet)); - } - else if (m_normalPermSet != null) - { - // Everett non X-AD case - m_permSet = m_normalPermSet.SpecialUnion(m_unrestrictedPermSet); - } - else if (m_unrestrictedPermSet != null) - { - // Everett non X-AD case - m_permSet = m_unrestrictedPermSet.SpecialUnion(m_normalPermSet); - } - - m_serializedPermissionSet = null; - m_normalPermSet = null; - m_unrestrictedPermSet = null; - - } - - [OnSerializing] - private void OnSerializing(StreamingContext ctx) - { - - if ((ctx.State & ~(StreamingContextStates.Clone|StreamingContextStates.CrossAppDomain)) != 0) - { - m_serializedPermissionSet = ToString(); // For v2.x and beyond - if (m_permSet != null) - m_permSet.SpecialSplit(ref m_unrestrictedPermSet, ref m_normalPermSet, m_ignoreTypeLoadFailures); - m_permSetSaved = m_permSet; - m_permSet = null; - } - } -#endif // !FEATURE_REMOTING - -#if FEATURE_REMOTING || _DEBUG +#if _DEBUG [OnSerialized] private void OnSerialized(StreamingContext context) { -#if FEATURE_REMOTING - if ((context.State & ~(StreamingContextStates.Clone|StreamingContextStates.CrossAppDomain)) != 0) - { - m_serializedPermissionSet = null; - m_permSet = m_permSetSaved; - m_permSetSaved = null; - m_unrestrictedPermSet = null; - m_normalPermSet = null; - } -#else // !FEATURE_REMOTING Contract.Assert(false, "PermissionSet does not support serialization on CoreCLR"); -#endif // !FEATURE_REMOTING } -#endif // FEATURE_REMOTING || _DEBUG +#endif // _DEBUG internal PermissionSet() { @@ -233,19 +172,11 @@ namespace System.Security { { Object obj = m_permSet.GetItem(i); IPermission perm = obj as IPermission; -#if FEATURE_CAS_POLICY - ISecurityElementFactory elem = obj as ISecurityElementFactory; -#endif // FEATURE_CAS_POLICY + if (perm != null) { m_permSet.SetItem(i, perm.Copy()); } -#if FEATURE_CAS_POLICY - else if (elem != null) - { - m_permSet.SetItem(i, elem.Copy()); - } -#endif // FEATURE_CAS_POLICY } } } @@ -365,19 +296,7 @@ namespace System.Security { Object obj = m_permSet.GetItem( index ); if (obj == null) return null; - IPermission perm = obj as IPermission; - if (perm != null) - return perm; -#if FEATURE_CAS_POLICY - perm = CreatePermission(obj, index); -#endif // FEATURE_CAS_POLICY - if (perm == null) - return null; - Contract.Assert( PermissionToken.IsTokenProperlyAssigned( perm, PermissionToken.GetToken( perm ) ), - "PermissionToken was improperly assigned" ); - Contract.Assert( PermissionToken.GetToken( perm ).m_index == index, - "Assigning permission to incorrect index in tokenbasedset" ); - return perm; + return obj as IPermission; } internal IPermission GetPermission(PermissionToken permToken) @@ -396,21 +315,6 @@ namespace System.Security { return GetPermission(PermissionToken.GetToken( perm )); } -#if FEATURE_CAS_POLICY - public IPermission GetPermission(Type permClass) - { - return GetPermissionImpl(permClass); - } - - protected virtual IPermission GetPermissionImpl(Type permClass) - { - if (permClass == null) - return null; - - return GetPermission(PermissionToken.FindToken(permClass)); - } -#endif // FEATURE_CAS_POLICY - public IPermission SetPermission(IPermission perm) { return SetPermissionImpl(perm); @@ -494,29 +398,6 @@ namespace System.Security { return (IPermission)m_permSet.RemoveItem( index ); // this cast is safe because the call to GetPermission will guarantee it is an IPermission } -#if FEATURE_CAS_POLICY - public IPermission RemovePermission(Type permClass) - { - return RemovePermissionImpl(permClass); - } - - protected virtual IPermission RemovePermissionImpl(Type permClass) - { - if (permClass == null) - { - return null; - } - - PermissionToken permToken = PermissionToken.FindToken(permClass); - if (permToken == null) - { - return null; - } - - return RemovePermission(permToken.m_index); - } -#endif // FEATURE_CAS_POLICY - // Make this internal soon. internal void SetUnrestricted(bool unrestricted) { @@ -527,12 +408,12 @@ namespace System.Security { m_permSet = null; } } - + public bool IsUnrestricted() { return m_Unrestricted; } - + internal enum IsSubsetOfType { Normal, @@ -728,37 +609,6 @@ namespace System.Security { } } -#if FEATURE_CAS_POLICY - static internal void SafeChildAdd( SecurityElement parent, ISecurityElementFactory child, bool copy ) - { - if (child == parent) - return; - if (child.GetTag().Equals( "IPermission" ) || child.GetTag().Equals( "Permission" )) - { - parent.AddChild( child ); - } - else if (parent.Tag.Equals( child.GetTag() )) - { - Contract.Assert( child is SecurityElement, "SecurityElement expected" ); - SecurityElement elChild = (SecurityElement)child; - Contract.Assert( elChild.InternalChildren != null, - "Non-permission elements should have children" ); - - for (int i = 0; i < elChild.InternalChildren.Count; ++i) - { - ISecurityElementFactory current = (ISecurityElementFactory)elChild.InternalChildren[i]; - Contract.Assert( !current.GetTag().Equals( parent.Tag ), - "Illegal to insert a like-typed element" ); - parent.AddChildNoDuplicates( current ); - } - } - else - { - parent.AddChild( (ISecurityElementFactory)(copy ? child.Copy() : child) ); - } - } -#endif // FEATURE_CAS_POLICY - internal void InplaceIntersect( PermissionSet other ) { Exception savedException = null; @@ -796,75 +646,18 @@ namespace System.Security { { Object thisObj = this.m_permSet.GetItem( i ); IPermission thisPerm = thisObj as IPermission; -#if FEATURE_CAS_POLICY - ISecurityElementFactory thisElem = thisObj as ISecurityElementFactory; -#endif // FEATURE_CAS_POLICY Object otherObj = other.m_permSet.GetItem( i ); IPermission otherPerm = otherObj as IPermission; -#if FEATURE_CAS_POLICY - ISecurityElementFactory otherElem = otherObj as ISecurityElementFactory; -#endif // FEATURE_CAS_POLICY if (thisObj == null && otherObj == null) continue; -#if FEATURE_CAS_POLICY - if (thisElem != null && otherElem != null) - { - // If we already have an intersection node, just add another child - if (thisElem.GetTag().Equals( s_str_PermissionIntersection ) || - thisElem.GetTag().Equals( s_str_PermissionUnrestrictedIntersection )) - { - Contract.Assert( thisElem is SecurityElement, "SecurityElement expected" ); - SafeChildAdd( (SecurityElement)thisElem, otherElem, true ); - } - // If either set is unrestricted, intersect the nodes unrestricted - else - { - bool copyOther = true; - if (this.IsUnrestricted()) - { - SecurityElement newElemUU = new SecurityElement( s_str_PermissionUnrestrictedUnion ); - newElemUU.AddAttribute( "class", thisElem.Attribute( "class" ) ); - SafeChildAdd( newElemUU, thisElem, false ); - thisElem = newElemUU; - } - if (other.IsUnrestricted()) - { - SecurityElement newElemUU = new SecurityElement( s_str_PermissionUnrestrictedUnion ); - newElemUU.AddAttribute( "class", otherElem.Attribute( "class" ) ); - SafeChildAdd( newElemUU, otherElem, true ); - otherElem = newElemUU; - copyOther = false; - } - - SecurityElement newElem = new SecurityElement( s_str_PermissionIntersection ); - newElem.AddAttribute( "class", thisElem.Attribute( "class" ) ); - - SafeChildAdd( newElem, thisElem, false ); - SafeChildAdd( newElem, otherElem, copyOther ); - this.m_permSet.SetItem( i, newElem ); - } - } - else -#endif // FEATURE_CAS_POLICY if (thisObj == null) { // There is no object in , so intersection is empty except for IUnrestrictedPermissions if (this.IsUnrestricted()) { -#if FEATURE_CAS_POLICY - if (otherElem != null) - { - SecurityElement newElem = new SecurityElement( s_str_PermissionUnrestrictedIntersection ); - newElem.AddAttribute( "class", otherElem.Attribute( "class" ) ); - SafeChildAdd( newElem, otherElem, true ); - this.m_permSet.SetItem( i, newElem ); - Contract.Assert( PermissionToken.s_tokenSet.GetItem( i ) != null, "PermissionToken should already be assigned" ); - } - else -#endif // FEATURE_CAS_POLICY { PermissionToken token = (PermissionToken)PermissionToken.s_tokenSet.GetItem( i ); if ((token.m_type & PermissionTokenType.IUnrestricted) != 0) @@ -879,16 +672,6 @@ namespace System.Security { { if (other.IsUnrestricted()) { -#if FEATURE_CAS_POLICY - if (thisElem != null) - { - SecurityElement newElem = new SecurityElement( s_str_PermissionUnrestrictedIntersection ); - newElem.AddAttribute( "class", thisElem.Attribute( "class" ) ); - SafeChildAdd( newElem, thisElem, false ); - this.m_permSet.SetItem( i, newElem ); - } - else -#endif // FEATURE_CAS_POLICY { PermissionToken token = (PermissionToken)PermissionToken.s_tokenSet.GetItem( i ); if ((token.m_type & PermissionTokenType.IUnrestricted) == 0) @@ -902,13 +685,6 @@ namespace System.Security { } else { -#if FEATURE_CAS_POLICY - if (thisElem != null) - thisPerm = this.CreatePermission(thisElem, i); - if (otherElem != null) - otherPerm = other.CreatePermission(otherElem, i); -#endif // FEATURE_CAS_POLICY - try { IPermission intersectPerm; @@ -968,64 +744,16 @@ namespace System.Security { { Object thisObj = this.m_permSet.GetItem( i ); IPermission thisPerm = thisObj as IPermission; -#if FEATURE_CAS_POLICY - ISecurityElementFactory thisElem = thisObj as ISecurityElementFactory; -#endif // FEATURE_CAS_POLICY - Object otherObj = other.m_permSet.GetItem( i ); IPermission otherPerm = otherObj as IPermission; -#if FEATURE_CAS_POLICY - ISecurityElementFactory otherElem = otherObj as ISecurityElementFactory; -#endif // FEATURE_CAS_POLICY if (thisObj == null && otherObj == null) continue; -#if FEATURE_CAS_POLICY - if (thisElem != null && otherElem != null) - { - bool copyOther = true; - bool copyThis = true; - SecurityElement newElem = new SecurityElement( s_str_PermissionIntersection ); - newElem.AddAttribute( "class", otherElem.Attribute( "class" ) ); - if (this.IsUnrestricted()) - { - SecurityElement newElemUU = new SecurityElement( s_str_PermissionUnrestrictedUnion ); - newElemUU.AddAttribute( "class", thisElem.Attribute( "class" ) ); - SafeChildAdd( newElemUU, thisElem, true ); - copyThis = false; - thisElem = newElemUU; - } - if (other.IsUnrestricted()) - { - SecurityElement newElemUU = new SecurityElement( s_str_PermissionUnrestrictedUnion ); - newElemUU.AddAttribute( "class", otherElem.Attribute( "class" ) ); - SafeChildAdd( newElemUU, otherElem, true ); - copyOther = false; - otherElem = newElemUU; - } - - SafeChildAdd( newElem, otherElem, copyOther ); - SafeChildAdd( newElem, thisElem, copyThis ); - pset.m_permSet.SetItem( i, newElem ); - } - else -#endif // FEATURE_CAS_POLICY if (thisObj == null) { if (this.m_Unrestricted) { -#if FEATURE_CAS_POLICY - if (otherElem != null) - { - SecurityElement newElem = new SecurityElement( s_str_PermissionUnrestrictedIntersection ); - newElem.AddAttribute( "class", otherElem.Attribute( "class" ) ); - SafeChildAdd( newElem, otherElem, true ); - pset.m_permSet.SetItem( i, newElem ); - Contract.Assert( PermissionToken.s_tokenSet.GetItem( i ) != null, "PermissionToken should already be assigned" ); - } - else -#endif // FEATURE_CAS_POLICY if (otherPerm != null) { PermissionToken token = (PermissionToken)PermissionToken.s_tokenSet.GetItem( i ); @@ -1041,17 +769,6 @@ namespace System.Security { { if (other.m_Unrestricted) { -#if FEATURE_CAS_POLICY - if (thisElem != null) - { - SecurityElement newElem = new SecurityElement( s_str_PermissionUnrestrictedIntersection ); - newElem.AddAttribute( "class", thisElem.Attribute( "class" ) ); - SafeChildAdd( newElem, thisElem, true ); - pset.m_permSet.SetItem( i, newElem ); - Contract.Assert( PermissionToken.s_tokenSet.GetItem( i ) != null, "PermissionToken should already be assigned" ); - } - else -#endif // FEATURE_CAS_POLICY if (thisPerm != null) { PermissionToken token = (PermissionToken)PermissionToken.s_tokenSet.GetItem( i ); @@ -1065,13 +782,6 @@ namespace System.Security { } else { -#if FEATURE_CAS_POLICY - if (thisElem != null) - thisPerm = this.CreatePermission(thisElem, i); - if (otherElem != null) - otherPerm = other.CreatePermission(otherElem, i); -#endif // FEATURE_CAS_POLICY - IPermission intersectPerm; if (thisPerm == null) intersectPerm = otherPerm; @@ -1102,13 +812,9 @@ namespace System.Security { // Quick out conditions, union doesn't change this PermissionSet if (other == null || other.FastIsEmpty()) return; - - - m_CheckedForNonCas = false; - + m_CheckedForNonCas = false; - this.m_Unrestricted = this.m_Unrestricted || other.m_Unrestricted; if (this.m_Unrestricted) @@ -1124,7 +830,7 @@ namespace System.Security { int maxMax = -1; if (other.m_permSet != null) { - maxMax = other.m_permSet.GetMaxUsedIndex(); + maxMax = other.m_permSet.GetMaxUsedIndex(); this.CheckSet(); } // Save exceptions until the end @@ -1134,52 +840,15 @@ namespace System.Security { { Object thisObj = this.m_permSet.GetItem( i ); IPermission thisPerm = thisObj as IPermission; -#if FEATURE_CAS_POLICY - ISecurityElementFactory thisElem = thisObj as ISecurityElementFactory; -#endif // FEATURE_CAS_POLICY Object otherObj = other.m_permSet.GetItem( i ); IPermission otherPerm = otherObj as IPermission; -#if FEATURE_CAS_POLICY - ISecurityElementFactory otherElem = otherObj as ISecurityElementFactory; -#endif // FEATURE_CAS_POLICY if (thisObj == null && otherObj == null) continue; -#if FEATURE_CAS_POLICY - if (thisElem != null && otherElem != null) - { - if (thisElem.GetTag().Equals( s_str_PermissionUnion ) || - thisElem.GetTag().Equals( s_str_PermissionUnrestrictedUnion )) - { - Contract.Assert( thisElem is SecurityElement, "SecurityElement expected" ); - SafeChildAdd( (SecurityElement)thisElem, otherElem, true ); - } - else - { - SecurityElement newElem; - if (this.IsUnrestricted() || other.IsUnrestricted()) - newElem = new SecurityElement( s_str_PermissionUnrestrictedUnion ); - else - newElem = new SecurityElement( s_str_PermissionUnion ); - newElem.AddAttribute( "class", thisElem.Attribute( "class" ) ); - SafeChildAdd( newElem, thisElem, false ); - SafeChildAdd( newElem, otherElem, true ); - this.m_permSet.SetItem( i, newElem ); - } - } - else -#endif // FEATURE_CAS_POLICY if (thisObj == null) { -#if FEATURE_CAS_POLICY - if (otherElem != null) - { - this.m_permSet.SetItem( i, otherElem.Copy() ); - } - else -#endif // FEATURE_CAS_POLICY if (otherPerm != null) { PermissionToken token = (PermissionToken)PermissionToken.s_tokenSet.GetItem( i ); @@ -1195,13 +864,6 @@ namespace System.Security { } else { -#if FEATURE_CAS_POLICY - if (thisElem != null) - thisPerm = this.CreatePermission(thisElem, i); - if (otherElem != null) - otherPerm = other.CreatePermission(otherElem, i); -#endif // FEATURE_CAS_POLICY - try { IPermission unionPerm; @@ -1260,44 +922,15 @@ namespace System.Security { { Object thisObj = this.m_permSet.GetItem( i ); IPermission thisPerm = thisObj as IPermission; -#if FEATURE_CAS_POLICY - ISecurityElementFactory thisElem = thisObj as ISecurityElementFactory; -#endif // FEATURE_CAS_POLICY Object otherObj = other.m_permSet.GetItem( i ); IPermission otherPerm = otherObj as IPermission; -#if FEATURE_CAS_POLICY - ISecurityElementFactory otherElem = otherObj as ISecurityElementFactory; -#endif // FEATURE_CAS_POLICY if (thisObj == null && otherObj == null) continue; -#if FEATURE_CAS_POLICY - if (thisElem != null && otherElem != null) - { - SecurityElement newElem; - if (this.IsUnrestricted() || other.IsUnrestricted()) - newElem = new SecurityElement( s_str_PermissionUnrestrictedUnion ); - else - newElem = new SecurityElement( s_str_PermissionUnion ); - newElem.AddAttribute( "class", thisElem.Attribute( "class" ) ); - SafeChildAdd( newElem, thisElem, true ); - SafeChildAdd( newElem, otherElem, true ); - pset.m_permSet.SetItem( i, newElem ); - } - else -#endif // FEATURE_CAS_POLICY if (thisObj == null) { -#if FEATURE_CAS_POLICY - if (otherElem != null) - { - pset.m_permSet.SetItem( i, otherElem.Copy() ); - Contract.Assert( PermissionToken.s_tokenSet.GetItem( i ) != null, "PermissionToken should already be assigned" ); - } - else -#endif // FEATURE_CAS_POLICY if (otherPerm != null) { PermissionToken token = (PermissionToken)PermissionToken.s_tokenSet.GetItem( i ); @@ -1310,13 +943,6 @@ namespace System.Security { } else if (otherObj == null) { -#if FEATURE_CAS_POLICY - if (thisElem != null) - { - pset.m_permSet.SetItem( i, thisElem.Copy() ); - } - else -#endif // FEATURE_CAS_POLICY if (thisPerm != null) { PermissionToken token = (PermissionToken)PermissionToken.s_tokenSet.GetItem( i ); @@ -1329,13 +955,6 @@ namespace System.Security { } else { -#if FEATURE_CAS_POLICY - if (thisElem != null) - thisPerm = this.CreatePermission(thisElem, i); - if (otherElem != null) - otherPerm = other.CreatePermission(otherElem, i); -#endif // FEATURE_CAS_POLICY - IPermission unionPerm; if(thisPerm == null) unionPerm = otherPerm; @@ -1347,7 +966,7 @@ namespace System.Security { Contract.Assert( unionPerm == null || PermissionToken.s_tokenSet.GetItem( i ) != null, "PermissionToken should already be assigned" ); } } - + return pset; } @@ -1588,21 +1207,7 @@ namespace System.Security { { // Explicitly make a new PermissionSet, rather than copying, since we may have a // ReadOnlyPermissionSet which cannot have identity permissions removed from it in a true copy. - PermissionSet copy = new PermissionSet(this); - - // There's no easy way to distinguish an identity permission from any other CodeAccessPermission, - // so remove them directly. -#if FEATURE_CAS_POLICY - copy.RemovePermission(typeof(GacIdentityPermission)); -#if FEATURE_X509 - copy.RemovePermission(typeof(PublisherIdentityPermission)); -#endif - copy.RemovePermission(typeof(StrongNameIdentityPermission)); - copy.RemovePermission(typeof(UrlIdentityPermission)); - copy.RemovePermission(typeof(ZoneIdentityPermission)); -#endif // FEATURE_CAS_POLICY - - return copy; + return new PermissionSet(this); } public IEnumerator GetEnumerator() @@ -1620,13 +1225,6 @@ namespace System.Security { return new PermissionSetEnumeratorInternal(this); } -#if FEATURE_CAS_POLICY - public override String ToString() - { - return ToXml().ToString(); - } -#endif // FEATURE_CAS_POLICY - private void NormalizePermissionSet() { // This function guarantees that all the permissions are placed at @@ -1645,12 +1243,6 @@ namespace System.Security { { Object obj = this.m_permSet.GetItem(i); IPermission perm = obj as IPermission; -#if FEATURE_CAS_POLICY - ISecurityElementFactory elem = obj as ISecurityElementFactory; - - if (elem != null) - perm = CreatePerm( elem ); -#endif // FEATURE_CAS_POLICY if (perm != null) permSetTemp.SetPermission( perm ); } @@ -1659,29 +1251,6 @@ namespace System.Security { this.m_permSet = permSetTemp.m_permSet; } -#if FEATURE_CAS_POLICY - private bool DecodeXml(byte[] data, HostProtectionResource fullTrustOnlyResources, HostProtectionResource inaccessibleResources ) - { - if (data != null && data.Length > 0) - { - FromXml( new Parser( data, Tokenizer.ByteTokenEncoding.UnicodeTokens ).GetTopElement() ); - } - - FilterHostProtectionPermissions(fullTrustOnlyResources, inaccessibleResources); - - // We call this method from unmanaged to code a set we are going to use declaratively. In - // this case, all the lazy evaluation for partial policy resolution is wasted since we'll - // need to decode all of these shortly to make the demand for whatever. Therefore, we - // pay that price now so that we can calculate whether all the permissions in the set - // implement the IUnrestrictedPermission interface (the common case) for use in some - // unmanaged optimizations. - - DecodeAllPermissions(); - - return true; - } -#endif // FEATURE_CAS_POLICY - private void DecodeAllPermissions() { if (m_permSet == null) @@ -1710,11 +1279,7 @@ namespace System.Security { HostProtectionPermission newHpp = (HostProtectionPermission)hpp.Intersect(new HostProtectionPermission(fullTrustOnly)); if (newHpp == null) { -#if FEATURE_CAS_POLICY - RemovePermission(typeof(HostProtectionPermission)); -#else // !FEATURE_CAS_POLICY RemovePermission(HostProtectionPermission.GetTokenIndex()); -#endif // FEATURE_CAS_POLICY } else if (newHpp.Resources != hpp.Resources) { @@ -1722,539 +1287,9 @@ namespace System.Security { } } -#if FEATURE_CAS_POLICY - public virtual void FromXml( SecurityElement et ) - { - FromXml( et, false, false ); - } - - internal static bool IsPermissionTag( String tag, bool allowInternalOnly ) - { - if (tag.Equals( s_str_Permission ) || - tag.Equals( s_str_IPermission )) - { - return true; - } - - if (allowInternalOnly && - (tag.Equals( s_str_PermissionUnion ) || - tag.Equals( s_str_PermissionIntersection ) || - tag.Equals( s_str_PermissionUnrestrictedIntersection ) || - tag.Equals( s_str_PermissionUnrestrictedUnion))) - { - return true; - } - - return false; - } - - internal virtual void FromXml( SecurityElement et, bool allowInternalOnly, bool ignoreTypeLoadFailures ) - { - if (et == null) - throw new ArgumentNullException(nameof(et)); - - if (!et.Tag.Equals(s_str_PermissionSet)) - throw new ArgumentException(String.Format( null, Environment.GetResourceString( "Argument_InvalidXMLElement" ), nameof(PermissionSet), this.GetType().FullName) ); - Contract.EndContractBlock(); - - Reset(); - m_ignoreTypeLoadFailures = ignoreTypeLoadFailures; - m_allPermissionsDecoded = false; - m_Unrestricted = XMLUtil.IsUnrestricted( et ); - - if (et.InternalChildren != null) - { - int childCount = et.InternalChildren.Count; - for (int i = 0; i < childCount; ++i) - { - SecurityElement elem = (SecurityElement)et.Children[i]; - - if (IsPermissionTag( elem.Tag, allowInternalOnly )) - { - String className = elem.Attribute( "class" ); - - PermissionToken token; - Object objectToInsert; - - if (className != null) - { - token = PermissionToken.GetToken( className ); - if (token == null) - { - objectToInsert = CreatePerm( elem ); -#if _DEBUG - PermissionToken tokenDebug = PermissionToken.GetToken( (IPermission)objectToInsert ); - Contract.Assert( tokenDebug != null && (tokenDebug.m_type & PermissionTokenType.BuiltIn) != 0, "This should only be called for built-ins" ); -#endif - if (objectToInsert != null) - { - Contract.Assert( objectToInsert.GetType().Module.Assembly == System.Reflection.Assembly.GetExecutingAssembly(), - "PermissionToken.GetToken returned null for non-mscorlib permission" ); - token = PermissionToken.GetToken( (IPermission)objectToInsert ); - Contract.Assert( (token.m_type & PermissionTokenType.DontKnow) == 0, "We should always know the permission type when getting a token from an instance" ); - } - } - else - { - objectToInsert = elem; - } - } - else - { - IPermission ip = CreatePerm( elem ); - if (ip == null) - { - token = null; - objectToInsert = null; - } - else - { - token = PermissionToken.GetToken( ip ); - Contract.Assert( PermissionToken.IsTokenProperlyAssigned( ip, token ), - "PermissionToken was improperly assigned" ); - objectToInsert = ip; - } - } - - if (token != null && objectToInsert != null) - { - if (m_permSet == null) - m_permSet = new TokenBasedSet(); - - if (this.m_permSet.GetItem( token.m_index ) != null) - { - // If there is already something in that slot, let's union them - // together. - - IPermission permInSlot; - - if (this.m_permSet.GetItem( token.m_index ) is IPermission) - permInSlot = (IPermission)this.m_permSet.GetItem( token.m_index ); - else - permInSlot = CreatePerm( (SecurityElement)this.m_permSet.GetItem( token.m_index ) ); - - if (objectToInsert is IPermission) - objectToInsert = ((IPermission)objectToInsert).Union( permInSlot ); - else - objectToInsert = CreatePerm( (SecurityElement)objectToInsert ).Union( permInSlot ); - } - - if(m_Unrestricted && objectToInsert is IPermission) - objectToInsert = null; - - this.m_permSet.SetItem( token.m_index, objectToInsert ); - } - } - } - } - } - - internal virtual void FromXml( SecurityDocument doc, int position, bool allowInternalOnly ) - { - if (doc == null) - throw new ArgumentNullException(nameof(doc)); - Contract.EndContractBlock(); - - if (!doc.GetTagForElement( position ).Equals(s_str_PermissionSet)) - throw new ArgumentException(String.Format( null, Environment.GetResourceString( "Argument_InvalidXMLElement" ), nameof(PermissionSet), this.GetType().FullName) ); - - Reset(); - m_allPermissionsDecoded = false; - Exception savedException = null; - String strUnrestricted = doc.GetAttributeForElement( position, "Unrestricted" ); - if (strUnrestricted != null) - m_Unrestricted = strUnrestricted.Equals( "True" ) || strUnrestricted.Equals( "true" ) || strUnrestricted.Equals( "TRUE" ); - else - m_Unrestricted = false; - - ArrayList childrenIndices = doc.GetChildrenPositionForElement( position ); - int childCount = childrenIndices.Count; - for (int i = 0; i < childCount; ++i) - { - int childIndex = (int)childrenIndices[i]; - if (IsPermissionTag( doc.GetTagForElement( childIndex ), allowInternalOnly )) - { - try - { - String className = doc.GetAttributeForElement( childIndex, "class" ); - - PermissionToken token; - Object objectToInsert; - - if (className != null) - { - token = PermissionToken.GetToken( className ); - if (token == null) - { - objectToInsert = CreatePerm( doc.GetElement( childIndex, true ) ); - - if (objectToInsert != null) - { -#if _DEBUG - PermissionToken tokenDebug = PermissionToken.GetToken( (IPermission)objectToInsert ); - Contract.Assert((tokenDebug != null), "PermissionToken.GetToken returned null "); - Contract.Assert( (tokenDebug.m_type & PermissionTokenType.BuiltIn) != 0, "This should only be called for built-ins" ); -#endif - Contract.Assert( objectToInsert.GetType().Module.Assembly == System.Reflection.Assembly.GetExecutingAssembly(), - "PermissionToken.GetToken returned null for non-mscorlib permission" ); - token = PermissionToken.GetToken( (IPermission)objectToInsert ); - Contract.Assert((token != null), "PermissionToken.GetToken returned null "); - Contract.Assert( (token.m_type & PermissionTokenType.DontKnow) == 0, "We should always know the permission type when getting a token from an instance" ); - } - } - else - { - objectToInsert = ((ISecurityElementFactory)new SecurityDocumentElement(doc, childIndex)).CreateSecurityElement(); - } - } - else - { - IPermission ip = CreatePerm( doc.GetElement( childIndex, true ) ); - if (ip == null) - { - token = null; - objectToInsert = null; - } - else - { - token = PermissionToken.GetToken( ip ); - Contract.Assert( PermissionToken.IsTokenProperlyAssigned( ip, token ), - "PermissionToken was improperly assigned" ); - objectToInsert = ip; - } - } - - if (token != null && objectToInsert != null) - { - if (m_permSet == null) - m_permSet = new TokenBasedSet(); - - IPermission permInSlot = null; - if (this.m_permSet.GetItem( token.m_index ) != null) - { - // If there is already something in that slot, let's union them - // together. - - if (this.m_permSet.GetItem( token.m_index ) is IPermission) - permInSlot = (IPermission)this.m_permSet.GetItem( token.m_index ); - else - permInSlot = CreatePerm( this.m_permSet.GetItem( token.m_index ) ); - } - - if (permInSlot != null) - { - if (objectToInsert is IPermission) - objectToInsert = permInSlot.Union((IPermission)objectToInsert); - else - objectToInsert = permInSlot.Union(CreatePerm( objectToInsert )); - } - - if(m_Unrestricted && objectToInsert is IPermission) - objectToInsert = null; - - this.m_permSet.SetItem( token.m_index, objectToInsert ); - } - } - catch (Exception e) - { -#if _DEBUG - if (debug) - DEBUG_WRITE( "error while decoding permission set =\n" + e.ToString() ); -#endif - if (savedException == null) - savedException = e; - - } - } - } - - if (savedException != null) - throw savedException; - - } - - private IPermission CreatePerm(Object obj) - { - return CreatePerm(obj, m_ignoreTypeLoadFailures); - } - - internal static IPermission CreatePerm(Object obj, bool ignoreTypeLoadFailures) - { - SecurityElement el = obj as SecurityElement; - ISecurityElementFactory isf = obj as ISecurityElementFactory; - if (el == null && isf != null) - { - el = isf.CreateSecurityElement(); - } - - IEnumerator enumerator; - IPermission finalPerm = null; - - switch (el.Tag) - { - case s_str_PermissionUnion: - enumerator = el.Children.GetEnumerator(); - while (enumerator.MoveNext()) - { - IPermission tempPerm = CreatePerm( (SecurityElement)enumerator.Current, ignoreTypeLoadFailures); - - if (finalPerm != null) - finalPerm = finalPerm.Union( tempPerm ); - else - finalPerm = tempPerm; - } - break; - - case s_str_PermissionIntersection: - enumerator = el.Children.GetEnumerator(); - while (enumerator.MoveNext()) - { - IPermission tempPerm = CreatePerm( (SecurityElement)enumerator.Current, ignoreTypeLoadFailures); - - if (finalPerm != null) - finalPerm = finalPerm.Intersect( tempPerm ); - else - finalPerm = tempPerm; - - if (finalPerm == null) - return null; - } - break; - - case s_str_PermissionUnrestrictedUnion: - enumerator = el.Children.GetEnumerator(); - bool first = true; - while (enumerator.MoveNext()) - { - IPermission tempPerm = CreatePerm( (SecurityElement)enumerator.Current, ignoreTypeLoadFailures ); - - if (tempPerm == null) - continue; - - PermissionToken token = PermissionToken.GetToken( tempPerm ); - - Contract.Assert( (token.m_type & PermissionTokenType.DontKnow) == 0, "We should know the permission type already" ); - - if ((token.m_type & PermissionTokenType.IUnrestricted) != 0) - { - finalPerm = XMLUtil.CreatePermission( GetPermissionElement((SecurityElement)enumerator.Current), PermissionState.Unrestricted, ignoreTypeLoadFailures ); - first = false; - break; - } - else - { - Contract.Assert( tempPerm != null, "We should only come here if we have a real permission" ); - if (first) - finalPerm = tempPerm; - else - finalPerm = tempPerm.Union( finalPerm ); - first = false; - } - } - break; - - case s_str_PermissionUnrestrictedIntersection: - enumerator = el.Children.GetEnumerator(); - while (enumerator.MoveNext()) - { - IPermission tempPerm = CreatePerm( (SecurityElement)enumerator.Current, ignoreTypeLoadFailures ); - - if (tempPerm == null) - return null; - - PermissionToken token = PermissionToken.GetToken( tempPerm ); - - Contract.Assert( (token.m_type & PermissionTokenType.DontKnow) == 0, "We should know the permission type already" ); - - if ((token.m_type & PermissionTokenType.IUnrestricted) != 0) - { - if (finalPerm != null) - finalPerm = tempPerm.Intersect( finalPerm ); - else - finalPerm = tempPerm; - } - else - { - finalPerm = null; - } - - if (finalPerm == null) - return null; - } - break; - - case "IPermission": - case "Permission": - finalPerm = el.ToPermission(ignoreTypeLoadFailures); - break; - - default: - Contract.Assert( false, "Unrecognized case found during permission creation" ); - break; - } - - return finalPerm; - } - - internal IPermission CreatePermission(Object obj, int index) - { - IPermission perm = CreatePerm(obj); - if(perm == null) - return null; - - // See if the PermissionSet.m_Unrestricted flag covers this permission - if(m_Unrestricted) - perm = null; - - // Store the decoded result - CheckSet(); - m_permSet.SetItem(index, perm); - - // Do some consistency checks - Contract.Assert(perm == null || PermissionToken.IsTokenProperlyAssigned( perm, PermissionToken.GetToken( perm ) ), "PermissionToken was improperly assigned"); - if (perm != null) - { - PermissionToken permToken = PermissionToken.GetToken(perm); - if (permToken != null && permToken.m_index != index) - throw new ArgumentException( Environment.GetResourceString( "Argument_UnableToGeneratePermissionSet")); - } - - - return perm; - } - - private static SecurityElement GetPermissionElement( SecurityElement el ) - { - switch (el.Tag) - { - case "IPermission": - case "Permission": - return el; - } - IEnumerator enumerator = el.Children.GetEnumerator(); - if (enumerator.MoveNext()) - return GetPermissionElement((SecurityElement)enumerator.Current); - Contract.Assert( false, "No Permission or IPermission tag found" ); - return null; - } - - internal static SecurityElement CreateEmptyPermissionSetXml() - { - - SecurityElement elTrunk = new SecurityElement("PermissionSet"); - elTrunk.AddAttribute( "class", "System.Security.PermissionSet" ); - - elTrunk.AddAttribute( "version", "1" ); - return elTrunk; - - } - // internal helper which takes in the hardcoded permission name to avoid lookup at runtime - // can be called from classes that derive from PermissionSet - internal SecurityElement ToXml(String permName) - { - SecurityElement elTrunk = new SecurityElement("PermissionSet"); - elTrunk.AddAttribute( "class", permName ); - - elTrunk.AddAttribute( "version", "1" ); - - PermissionSetEnumeratorInternal enumerator = new PermissionSetEnumeratorInternal(this); - - if (m_Unrestricted) - { - elTrunk.AddAttribute(s_str_Unrestricted, "true" ); - } - - while (enumerator.MoveNext()) - { - IPermission perm = (IPermission)enumerator.Current; - - if (!m_Unrestricted) - elTrunk.AddChild( perm.ToXml() ); - } - return elTrunk; - } - - internal SecurityElement InternalToXml() - { - SecurityElement elTrunk = new SecurityElement("PermissionSet"); - elTrunk.AddAttribute( "class", this.GetType().FullName); - elTrunk.AddAttribute( "version", "1" ); - - if (m_Unrestricted) - { - elTrunk.AddAttribute(s_str_Unrestricted, "true" ); - } - - if (this.m_permSet != null) - { - int maxIndex = this.m_permSet.GetMaxUsedIndex(); - - for (int i = m_permSet.GetStartingIndex(); i <= maxIndex; ++i) - { - Object obj = this.m_permSet.GetItem( i ); - if (obj != null) - { - if (obj is IPermission) - { - if (!m_Unrestricted) - elTrunk.AddChild( ((IPermission)obj).ToXml() ); - } - else - { - elTrunk.AddChild( (SecurityElement)obj ); - } - } - - } - } - return elTrunk ; - } - - public virtual SecurityElement ToXml() - { - // If you hit this assert then most likely you are trying to change the name of this class. - // This is ok as long as you change the hard coded string above and change the assert below. - Contract.Assert( this.GetType().FullName.Equals( "System.Security.PermissionSet" ), "Class name changed! Was: System.Security.PermissionSet Should be:" + this.GetType().FullName); - - return ToXml("System.Security.PermissionSet"); - } -#endif // FEATURE_CAS_POLICY - -#if FEATURE_CAS_POLICY && FEATURE_SERIALIZATION - internal - byte[] EncodeXml() - { - MemoryStream ms = new MemoryStream(); - BinaryWriter writer = new BinaryWriter( ms, Encoding.Unicode ); - writer.Write( this.ToXml().ToString() ); - writer.Flush(); - - // The BinaryWriter is going to place - // two bytes indicating a Unicode stream. - // We want to chop those off before returning - // the bytes out. - - ms.Position = 2; - int countBytes = (int)ms.Length - 2; - byte[] retval = new byte[countBytes]; - ms.Read( retval, 0, retval.Length ); - return retval; - } - - /// - [Obsolete("This method is obsolete and shoud no longer be used.")] - public static byte[] ConvertPermissionSet(String inFormat, byte[] inData, String outFormat) - { - // Since this method has shipped and is public, we cannot remove it without being a breaking change - throw new NotImplementedException(); - } -#endif - // Determines whether the permission set contains any non-code access // security permissions. - #if FEATURE_CORECLR [System.Security.SecurityCritical] // auto-generated - #endif public bool ContainsNonCodeAccessPermissions() { if (m_CheckedForNonCas) @@ -2324,54 +1359,6 @@ namespace System.Security { return pset; } -#if FEATURE_CAS_POLICY - private const String s_str_PermissionSet = "PermissionSet"; - private const String s_str_Permission = "Permission"; - private const String s_str_IPermission = "IPermission"; - private const String s_str_Unrestricted = "Unrestricted"; - private const String s_str_PermissionUnion = "PermissionUnion"; - private const String s_str_PermissionIntersection = "PermissionIntersection"; - private const String s_str_PermissionUnrestrictedUnion = "PermissionUnrestrictedUnion"; - private const String s_str_PermissionUnrestrictedIntersection = "PermissionUnrestrictedIntersection"; - - // This method supports v1.x security attrbutes only - we'll require legacy CAS policy mode - // to be enabled for that to work. -#pragma warning disable 618 - // Internal routine used to setup a special security context - // for creating and manipulated security custom attributes - // that we use when the Runtime is hosted. - [System.Security.SecurityCritical] // auto-generated - private static void SetupSecurity() - { - PolicyLevel level = PolicyLevel.CreateAppDomainLevel(); - - CodeGroup rootGroup = new UnionCodeGroup( new AllMembershipCondition(), level.GetNamedPermissionSet( "Execution" ) ); - - StrongNamePublicKeyBlob microsoftBlob = new StrongNamePublicKeyBlob( AssemblyRef.MicrosoftPublicKeyFull ); - CodeGroup microsoftGroup = new UnionCodeGroup( new StrongNameMembershipCondition( microsoftBlob, null, null ), level.GetNamedPermissionSet( "FullTrust" ) ); - - StrongNamePublicKeyBlob ecmaBlob = new StrongNamePublicKeyBlob( AssemblyRef.EcmaPublicKeyFull ); - CodeGroup ecmaGroup = new UnionCodeGroup( new StrongNameMembershipCondition( ecmaBlob, null, null ), level.GetNamedPermissionSet( "FullTrust" ) ); - - CodeGroup gacGroup = new UnionCodeGroup( new GacMembershipCondition(), level.GetNamedPermissionSet( "FullTrust" ) ); - - rootGroup.AddChild( microsoftGroup ); - rootGroup.AddChild( ecmaGroup ); - rootGroup.AddChild( gacGroup ); - - level.RootCodeGroup = rootGroup; - - try - { - AppDomain.CurrentDomain.SetAppDomainPolicy( level ); - } - catch (PolicyException) - { - } - } -#endif -#pragma warning restore 618 - // Internal routine used by CreateSerialized to add a permission to the set private static void MergePermission(IPermission perm, bool separateCasFromNonCas, ref PermissionSet casPset, ref PermissionSet nonCasPset) { @@ -2475,22 +1462,8 @@ namespace System.Security { nonCasPset = null; } - // Serialize the set(s). - byte[] casBlob = null; - nonCasBlob = null; -#if FEATURE_CAS_POLICY - if(serialize) - { - if(casPset != null) - casBlob = casPset.EncodeXml(); - if(nonCasPset != null) - nonCasBlob = nonCasPset.EncodeXml(); - } -#else // FEATURE_CAS_POLICY Contract.Assert(!serialize, "Cannot serialize permission sets on CoreCLR"); -#endif // FEATURE_CAS_POLICY - - return casBlob; + return null; } #if FEATURE_SERIALIZATION diff --git a/src/coreclr/src/mscorlib/src/System/Security/PermissionSetEnumerator.cs b/src/coreclr/src/mscorlib/src/System/Security/PermissionSetEnumerator.cs index 55b56cb..7b234e9 100644 --- a/src/coreclr/src/mscorlib/src/System/Security/PermissionSetEnumerator.cs +++ b/src/coreclr/src/mscorlib/src/System/Security/PermissionSetEnumerator.cs @@ -81,20 +81,6 @@ namespace System.Security enm.Current = perm; return true; } - -#if FEATURE_CAS_POLICY - SecurityElement elem = obj as SecurityElement; - - if (elem != null) - { - perm = m_permSet.CreatePermission(elem, enm.Index); - if (perm != null) - { - enm.Current = perm; - return true; - } - } -#endif // FEATURE_CAS_POLICY } return false; } diff --git a/src/coreclr/src/mscorlib/src/System/Security/PermissionToken.cs b/src/coreclr/src/mscorlib/src/System/Security/PermissionToken.cs index 1896dd9..f6df2c5 100644 --- a/src/coreclr/src/mscorlib/src/System/Security/PermissionToken.cs +++ b/src/coreclr/src/mscorlib/src/System/Security/PermissionToken.cs @@ -2,7 +2,8 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -namespace System.Security { +namespace System.Security +{ using System; using System.Security.Util; using System.Security.Permissions; @@ -90,16 +91,9 @@ namespace System.Security { internal sealed class PermissionToken : ISecurityEncodable { private static readonly PermissionTokenFactory s_theTokenFactory; -#if FEATURE_CAS_POLICY - private static volatile ReflectionPermission s_reflectPerm = null; -#endif // FEATURE_CAS_POLICY - private const string c_mscorlibName = System.CoreLib.Name; internal int m_index; internal volatile PermissionTokenType m_type; -#if FEATURE_CAS_POLICY - internal String m_strTypeName; -#endif // FEATURE_CAS_POLICY static internal TokenBasedSet s_tokenSet = new TokenBasedSet(); internal static bool IsMscorlibClassName (string className) { @@ -119,11 +113,7 @@ namespace System.Security { // Search for the string 'mscorlib' in the classname. If we find it, we will conservatively assume it's an mscorlib.dll type and load it. for (int i = index; i < className.Length; i++) { -#if FEATURE_CORECLR - if (className[i] == 's' || className[i] == 'S') -#else - if (className[i] == 'm' || className[i] == 'M') -#endif + if (className[i] == 's' || className[i] == 'S') { if (String.Compare(className, i, c_mscorlibName, 0, c_mscorlibName.Length, StringComparison.OrdinalIgnoreCase) == 0) return true; @@ -145,9 +135,6 @@ namespace System.Security { { m_index = index; m_type = type; -#if FEATURE_CAS_POLICY - m_strTypeName = strTypeName; -#endif // FEATURE_CAS_POLICY } [System.Security.SecurityCritical] // auto-generated @@ -155,29 +142,8 @@ namespace System.Security { { if (cls == null) return null; - -#if FEATURE_CAS_POLICY - if (cls.GetInterface( "System.Security.Permissions.IBuiltInPermission" ) != null) - { - if (s_reflectPerm == null) - s_reflectPerm = new ReflectionPermission(PermissionState.Unrestricted); - s_reflectPerm.Assert(); - MethodInfo method = cls.GetMethod( "GetTokenIndex", BindingFlags.Static | BindingFlags.NonPublic ); - Contract.Assert( method != null, "IBuiltInPermission types should have a static method called 'GetTokenIndex'" ); - - // GetTokenIndex needs to be invoked without any security checks, since doing a security check - // will involve a ReflectionTargetDemand which creates a CompressedStack and attempts to get the - // token. - RuntimeMethodInfo getTokenIndex = method as RuntimeMethodInfo; - Contract.Assert(getTokenIndex != null, "method is not a RuntimeMethodInfo"); - int token = (int)getTokenIndex.UnsafeInvoke(null, BindingFlags.Default, null, null, null); - return s_theTokenFactory.BuiltInGetToken(token, null, cls); - } - else -#endif // FEATURE_CAS_POLICY - { - return s_theTokenFactory.GetToken(cls, null); - } + + return s_theTokenFactory.GetToken(cls, null); } public static PermissionToken GetToken(IPermission perm) @@ -193,82 +159,6 @@ namespace System.Security { return s_theTokenFactory.GetToken(perm.GetType(), perm); } -#if FEATURE_CAS_POLICY - public static PermissionToken GetToken(String typeStr) - { - return GetToken( typeStr, false ); - } - -#if _DEBUG - [System.Security.SecuritySafeCritical] // auto-generated - [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable - private static void GetTokenHelper(String typeStr) - { - new PermissionSet(PermissionState.Unrestricted).Assert(); - StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; - Type type = RuntimeTypeHandle.GetTypeByName( typeStr.Trim().Replace( '\'', '\"' ), ref stackMark); - Contract.Assert( (type == null) || (type.Module.Assembly != System.Reflection.Assembly.GetExecutingAssembly()) || (typeStr.IndexOf("mscorlib", StringComparison.Ordinal) < 0), - "We should not go through this path for mscorlib based permissions" ); - } -#endif - - public static PermissionToken GetToken(String typeStr, bool bCreateMscorlib) - { - if (typeStr == null) - return null; - - if (IsMscorlibClassName( typeStr )) - { - if (!bCreateMscorlib) - { - return null; - } - else - { - return FindToken( Type.GetType( typeStr ) ); - } - } - else - { - PermissionToken token = s_theTokenFactory.GetToken(typeStr); -#if _DEBUG - GetTokenHelper(typeStr); -#endif - return token; - } - } - - [SecuritySafeCritical] - public static PermissionToken FindToken( Type cls ) - { - if (cls == null) - return null; - -#if FEATURE_CAS_POLICY - if (cls.GetInterface( "System.Security.Permissions.IBuiltInPermission" ) != null) - { - if (s_reflectPerm == null) - s_reflectPerm = new ReflectionPermission(PermissionState.Unrestricted); - s_reflectPerm.Assert(); - MethodInfo method = cls.GetMethod( "GetTokenIndex", BindingFlags.Static | BindingFlags.NonPublic ); - Contract.Assert( method != null, "IBuiltInPermission types should have a static method called 'GetTokenIndex'" ); - - // GetTokenIndex needs to be invoked without any security checks, since doing a security check - // will involve a ReflectionTargetDemand which creates a CompressedStack and attempts to get the - // token. - RuntimeMethodInfo getTokenIndex = method as RuntimeMethodInfo; - Contract.Assert(getTokenIndex != null, "method is not a RuntimeMethodInfo"); - int token = (int)getTokenIndex.UnsafeInvoke(null, BindingFlags.Default, null, null, null); - return s_theTokenFactory.BuiltInGetToken(token, null, cls); - } - else -#endif // FEATURE_CAS_POLICY - { - return s_theTokenFactory.FindToken( cls ); - } - } -#endif // FEATURE_CAS_POLICY - public static PermissionToken FindTokenByIndex( int i ) { return s_theTokenFactory.FindTokenByIndex( i ); @@ -289,41 +179,6 @@ namespace System.Security { return true; } - -#if FEATURE_CAS_POLICY - public SecurityElement ToXml() - { - Contract.Assert( (m_type & PermissionTokenType.DontKnow) == 0, "Should have valid token type when ToXml is called" ); - SecurityElement elRoot = new SecurityElement( "PermissionToken" ); - if ((m_type & PermissionTokenType.BuiltIn) != 0) - elRoot.AddAttribute( "Index", "" + this.m_index ); - else - elRoot.AddAttribute( "Name", SecurityElement.Escape( m_strTypeName ) ); - elRoot.AddAttribute("Type", m_type.ToString("F")); - return elRoot; - } - - public void FromXml(SecurityElement elRoot) - { - // For the most part there is no parameter checking here since this is an - // internal class and the serialization/deserialization path is controlled. - - if (!elRoot.Tag.Equals( "PermissionToken" )) - Contract.Assert( false, "Tried to deserialize non-PermissionToken element here" ); - - String strName = elRoot.Attribute( "Name" ); - PermissionToken realToken; - if (strName != null) - realToken = GetToken( strName, true ); - else - realToken = FindTokenByIndex( Int32.Parse( elRoot.Attribute( "Index" ), CultureInfo.InvariantCulture ) ); - - this.m_index = realToken.m_index; - this.m_type = (PermissionTokenType) Enum.Parse(typeof(PermissionTokenType), elRoot.Attribute("Type")); - Contract.Assert((this.m_type & PermissionTokenType.DontKnow) == 0, "Should have valid token type when FromXml is called."); - this.m_strTypeName = realToken.m_strTypeName; - } -#endif // FEATURE_CAS_POLICY } // Package access only @@ -357,33 +212,6 @@ namespace System.Security { m_indexTable = new Hashtable(size); } -#if FEATURE_CAS_POLICY - [SecuritySafeCritical] - internal PermissionToken FindToken( Type cls ) - { - IntPtr typePtr = cls.TypeHandle.Value; - PermissionToken tok = (PermissionToken)m_handleTable[typePtr]; - - if (tok != null) - return tok; - - if (m_tokenTable == null) - return null; - - tok = (PermissionToken)m_tokenTable[cls.AssemblyQualifiedName]; - - if (tok != null) - { - lock (this) - { - m_handleTable.Add(typePtr, tok); - } - } - - return tok; - } -#endif // FEATURE_CAS_POLICY - internal PermissionToken FindTokenByIndex( int i ) { PermissionToken token; @@ -461,9 +289,6 @@ namespace System.Security { { Contract.Assert( !(perm is IBuiltInPermission), "This should not be called for built-ins" ); ((PermissionToken)tok).m_type = PermissionTokenType.IUnrestricted; -#if FEATURE_CAS_POLICY - ((PermissionToken)tok).m_strTypeName = perm.GetType().AssemblyQualifiedName; -#endif // FEATURE_CAS_POLICY } else { @@ -472,9 +297,6 @@ namespace System.Security { ((PermissionToken)tok).m_type = PermissionTokenType.IUnrestricted; else ((PermissionToken)tok).m_type = PermissionTokenType.Normal; -#if FEATURE_CAS_POLICY - ((PermissionToken)tok).m_strTypeName = cls.AssemblyQualifiedName; -#endif // FEATURE_CAS_POLICY } } diff --git a/src/coreclr/src/mscorlib/src/System/Security/Permissions/EnvironmentPermission.cs b/src/coreclr/src/mscorlib/src/System/Security/Permissions/EnvironmentPermission.cs index 8208ed3..23b4517 100644 --- a/src/coreclr/src/mscorlib/src/System/Security/Permissions/EnvironmentPermission.cs +++ b/src/coreclr/src/mscorlib/src/System/Security/Permissions/EnvironmentPermission.cs @@ -334,61 +334,8 @@ namespace System.Security.Permissions { } } - return copy; + return copy; } - -#if FEATURE_CAS_POLICY - public override SecurityElement ToXml() - { - SecurityElement esd = CodeAccessPermission.CreatePermissionElement( this, "System.Security.Permissions.EnvironmentPermission" ); - if (!IsUnrestricted()) - { - if (this.m_read != null && !this.m_read.IsEmpty()) - { - esd.AddAttribute( "Read", SecurityElement.Escape( m_read.ToString() ) ); - } - if (this.m_write != null && !this.m_write.IsEmpty()) - { - esd.AddAttribute( "Write", SecurityElement.Escape( m_write.ToString() ) ); - } - } - else - { - esd.AddAttribute( "Unrestricted", "true" ); - } - return esd; - } - - public override void FromXml(SecurityElement esd) - { - CodeAccessPermission.ValidateElement( esd, this ); - - String et; - - if (XMLUtil.IsUnrestricted(esd)) - { - m_unrestricted = true; - return; - } - - m_unrestricted = false; - m_read = null; - m_write = null; - - et = esd.Attribute( "Read" ); - if (et != null) - { - m_read = new EnvironmentStringExpressionSet( et ); - } - - et = esd.Attribute( "Write" ); - if (et != null) - { - m_write = new EnvironmentStringExpressionSet( et ); - } - - } -#endif // FEATURE_CAS_POLICY /// int IBuiltInPermission.GetTokenIndex() diff --git a/src/coreclr/src/mscorlib/src/System/Security/Permissions/FileDialogPermission.cs b/src/coreclr/src/mscorlib/src/System/Security/Permissions/FileDialogPermission.cs index 6d6c221..98a7d54 100644 --- a/src/coreclr/src/mscorlib/src/System/Security/Permissions/FileDialogPermission.cs +++ b/src/coreclr/src/mscorlib/src/System/Security/Permissions/FileDialogPermission.cs @@ -66,22 +66,6 @@ namespace System.Security.Permissions { return new FileDialogPermission(this.access); } -#if FEATURE_CAS_POLICY - public override void FromXml(SecurityElement esd) { - CodeAccessPermission.ValidateElement(esd, this); - if (XMLUtil.IsUnrestricted(esd)) { - SetUnrestricted(true); - return; - } - - access = FileDialogPermissionAccess.None; - - string accessXml = esd.Attribute("Access"); - if (accessXml != null) - access = (FileDialogPermissionAccess)Enum.Parse(typeof(FileDialogPermissionAccess), accessXml); - } -#endif // FEATURE_CAS_POLICY - /// int IBuiltInPermission.GetTokenIndex() { return FileDialogPermission.GetTokenIndex(); @@ -152,21 +136,6 @@ namespace System.Security.Permissions { } } -#if FEATURE_CAS_POLICY - public override SecurityElement ToXml() { - SecurityElement esd = CodeAccessPermission.CreatePermissionElement( this, "System.Security.Permissions.FileDialogPermission" ); - if (!IsUnrestricted()) { - if (access != FileDialogPermissionAccess.None) { - esd.AddAttribute("Access", Enum.GetName(typeof(FileDialogPermissionAccess), access)); - } - } - else { - esd.AddAttribute("Unrestricted", "true"); - } - return esd; - } -#endif // FEATURE_CAS_POLICY - public override IPermission Union(IPermission target) { if (target == null) { return this.Copy(); @@ -177,7 +146,7 @@ namespace System.Security.Permissions { FileDialogPermission operand = (FileDialogPermission)target; return new FileDialogPermission(access | operand.Access); - } + } static void VerifyAccess(FileDialogPermissionAccess access) { if ((access & ~FileDialogPermissionAccess.OpenSave) != 0 ) { diff --git a/src/coreclr/src/mscorlib/src/System/Security/Permissions/FileIOPermission.cs b/src/coreclr/src/mscorlib/src/System/Security/Permissions/FileIOPermission.cs index b524318..0797485 100644 --- a/src/coreclr/src/mscorlib/src/System/Security/Permissions/FileIOPermission.cs +++ b/src/coreclr/src/mscorlib/src/System/Security/Permissions/FileIOPermission.cs @@ -2,13 +2,11 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -namespace System.Security.Permissions { +namespace System.Security.Permissions +{ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; -#if FEATURE_CAS_POLICY - using SecurityElement = System.Security.SecurityElement; -#endif // FEATURE_CAS_POLICY using System.Security.AccessControl; using System.Security.Util; using System.IO; @@ -18,9 +16,9 @@ namespace System.Security.Permissions { using System.Runtime.Versioning; using System.Diagnostics.Contracts; -[Serializable] + [Serializable] [Flags] -[System.Runtime.InteropServices.ComVisible(true)] + [System.Runtime.InteropServices.ComVisible(true)] public enum FileIOPermissionAccess { NoAccess = 0x00, @@ -30,9 +28,8 @@ namespace System.Security.Permissions { PathDiscovery = 0x08, AllAccess = 0x0F, } - - -[System.Runtime.InteropServices.ComVisible(true)] + + [System.Runtime.InteropServices.ComVisible(true)] [Serializable] sealed public class FileIOPermission : CodeAccessPermission, IUnrestrictedPermission, IBuiltInPermission { @@ -79,23 +76,6 @@ namespace System.Security.Permissions { AddPathList( access, pathList, false, true, false ); } -#if FEATURE_MACL - [System.Security.SecuritySafeCritical] // auto-generated - public FileIOPermission( FileIOPermissionAccess access, AccessControlActions control, String path ) - { - VerifyAccess( access ); - - String[] pathList = new String[] { path }; - AddPathList( access, control, pathList, false, true, false ); - } - - [System.Security.SecuritySafeCritical] // auto-generated - public FileIOPermission( FileIOPermissionAccess access, AccessControlActions control, String[] pathList ) - : this( access, control, pathList, true, true ) - { - } -#endif - [System.Security.SecurityCritical] // auto-generated internal FileIOPermission( FileIOPermissionAccess access, String[] pathList, bool checkForDuplicates, bool needFullPath ) { @@ -104,16 +84,6 @@ namespace System.Security.Permissions { AddPathList( access, pathList, checkForDuplicates, needFullPath, true ); } -#if FEATURE_MACL - [System.Security.SecurityCritical] // auto-generated - internal FileIOPermission( FileIOPermissionAccess access, AccessControlActions control, String[] pathList, bool checkForDuplicates, bool needFullPath ) - { - VerifyAccess( access ); - - AddPathList( access, control, pathList, checkForDuplicates, needFullPath, true ); - } -#endif - public void SetPathList( FileIOPermissionAccess access, String path ) { String[] pathList; @@ -152,23 +122,11 @@ namespace System.Security.Permissions { if ((access & FileIOPermissionAccess.PathDiscovery) != 0) m_pathDiscovery = null; -#if FEATURE_MACL - if ((control & AccessControlActions.View) != 0) - m_viewAcl = null; - - if ((control & AccessControlActions.Change) != 0) - m_changeAcl = null; -#else m_viewAcl = null; m_changeAcl = null; -#endif - m_unrestricted = false; -#if FEATURE_MACL - AddPathList( access, control, pathList, checkForDuplicates, true, true ); -#else + AddPathList( access, pathList, checkForDuplicates, true, true ); -#endif } [System.Security.SecuritySafeCritical] // auto-generated @@ -267,28 +225,8 @@ namespace System.Security.Permissions { } m_pathDiscovery.AddExpressions( pathArrayList, checkForDuplicates); } - -#if FEATURE_MACL - if ((control & AccessControlActions.View) != 0) - { - if (m_viewAcl == null) - { - m_viewAcl = new FileIOAccess(); - } - m_viewAcl.AddExpressions( pathArrayList, checkForDuplicates); - } - - if ((control & AccessControlActions.Change) != 0) - { - if (m_changeAcl == null) - { - m_changeAcl = new FileIOAccess(); - } - m_changeAcl.AddExpressions( pathArrayList, checkForDuplicates); - } -#endif } - + [SecuritySafeCritical] public String[] GetPathList( FileIOPermissionAccess access ) { @@ -335,7 +273,6 @@ namespace System.Security.Permissions { return null; } - public FileIOPermissionAccess AllLocalFiles { @@ -785,123 +722,6 @@ namespace System.Security.Permissions { } return copy; } - -#if FEATURE_CAS_POLICY - public override SecurityElement ToXml() - { - SecurityElement esd = CodeAccessPermission.CreatePermissionElement( this, "System.Security.Permissions.FileIOPermission" ); - if (!IsUnrestricted()) - { - if (this.m_read != null && !this.m_read.IsEmpty()) - { - esd.AddAttribute( "Read", SecurityElement.Escape( m_read.ToString() ) ); - } - if (this.m_write != null && !this.m_write.IsEmpty()) - { - esd.AddAttribute( "Write", SecurityElement.Escape( m_write.ToString() ) ); - } - if (this.m_append != null && !this.m_append.IsEmpty()) - { - esd.AddAttribute( "Append", SecurityElement.Escape( m_append.ToString() ) ); - } - if (this.m_pathDiscovery != null && !this.m_pathDiscovery.IsEmpty()) - { - esd.AddAttribute( "PathDiscovery", SecurityElement.Escape( m_pathDiscovery.ToString() ) ); - } - if (this.m_viewAcl != null && !this.m_viewAcl.IsEmpty()) - { - esd.AddAttribute( "ViewAcl", SecurityElement.Escape( m_viewAcl.ToString() ) ); - } - if (this.m_changeAcl != null && !this.m_changeAcl.IsEmpty()) - { - esd.AddAttribute( "ChangeAcl", SecurityElement.Escape( m_changeAcl.ToString() ) ); - } - - } - else - { - esd.AddAttribute( "Unrestricted", "true" ); - } - return esd; - } - - [System.Security.SecuritySafeCritical] // auto-generated - public override void FromXml(SecurityElement esd) - { - CodeAccessPermission.ValidateElement( esd, this ); - String et; - - if (XMLUtil.IsUnrestricted(esd)) - { - m_unrestricted = true; - return; - } - - - m_unrestricted = false; - - et = esd.Attribute( "Read" ); - if (et != null) - { - m_read = new FileIOAccess( et ); - } - else - { - m_read = null; - } - - et = esd.Attribute( "Write" ); - if (et != null) - { - m_write = new FileIOAccess( et ); - } - else - { - m_write = null; - } - - et = esd.Attribute( "Append" ); - if (et != null) - { - m_append = new FileIOAccess( et ); - } - else - { - m_append = null; - } - - et = esd.Attribute( "PathDiscovery" ); - if (et != null) - { - m_pathDiscovery = new FileIOAccess( et ); - m_pathDiscovery.PathDiscovery = true; - } - else - { - m_pathDiscovery = null; - } - - et = esd.Attribute( "ViewAcl" ); - if (et != null) - { - m_viewAcl = new FileIOAccess( et ); - } - else - { - m_viewAcl = null; - } - - et = esd.Attribute( "ChangeAcl" ); - if (et != null) - { - m_changeAcl = new FileIOAccess( et ); - } - else - { - m_changeAcl = null; - } - } -#endif // FEATURE_CAS_POLICY /// int IBuiltInPermission.GetTokenIndex() @@ -996,16 +816,7 @@ namespace System.Security.Permissions { [System.Security.SecuritySafeCritical] internal static void QuickDemand(FileIOPermissionAccess access, string fullPath, bool checkForDuplicates = false, bool needFullPath = false) { -#if FEATURE_CAS_POLICY - if (!CodeAccessSecurityEngine.QuickCheckForAllDemands()) - { - new FileIOPermission(access, new string[] { fullPath }, checkForDuplicates, needFullPath).Demand(); - } - else -#endif - { - EmulateFileIOPermissionChecks(fullPath); - } + EmulateFileIOPermissionChecks(fullPath); } /// @@ -1021,18 +832,9 @@ namespace System.Security.Permissions { [System.Security.SecuritySafeCritical] internal static void QuickDemand(FileIOPermissionAccess access, string[] fullPathList, bool checkForDuplicates = false, bool needFullPath = true) { -#if FEATURE_CAS_POLICY - if (!CodeAccessSecurityEngine.QuickCheckForAllDemands()) - { - new FileIOPermission(access, fullPathList, checkForDuplicates, needFullPath).Demand(); - } - else -#endif + foreach (string fullPath in fullPathList) { - foreach (string fullPath in fullPathList) - { - EmulateFileIOPermissionChecks(fullPath); - } + EmulateFileIOPermissionChecks(fullPath); } } @@ -1040,45 +842,8 @@ namespace System.Security.Permissions { internal static void QuickDemand(PermissionState state) { // Should be a no-op without CAS -#if FEATURE_CAS_POLICY - if (!CodeAccessSecurityEngine.QuickCheckForAllDemands()) - { - new FileIOPermission(state).Demand(); - } -#endif - } - -#if FEATURE_MACL - [System.Security.SecuritySafeCritical] - internal static void QuickDemand(FileIOPermissionAccess access, AccessControlActions control, string fullPath, bool checkForDuplicates = false, bool needFullPath = true) - { - if (!CodeAccessSecurityEngine.QuickCheckForAllDemands()) - { - new FileIOPermission(access, control, new string[] { fullPath }, checkForDuplicates, needFullPath).Demand(); - } - else - { - EmulateFileIOPermissionChecks(fullPath); - } } - [System.Security.SecuritySafeCritical] - internal static void QuickDemand(FileIOPermissionAccess access, AccessControlActions control, string[] fullPathList, bool checkForDuplicates = true, bool needFullPath = true) - { - if (!CodeAccessSecurityEngine.QuickCheckForAllDemands()) - { - new FileIOPermission(access, control, fullPathList, checkForDuplicates, needFullPath).Demand(); - } - else - { - foreach (string fullPath in fullPathList) - { - EmulateFileIOPermissionChecks(fullPath); - } - } - } -#endif - /// /// Perform the additional path checks that would normally happen when creating a FileIOPermission object. /// diff --git a/src/coreclr/src/mscorlib/src/System/Security/Permissions/GACIdentityPermission.cs b/src/coreclr/src/mscorlib/src/System/Security/Permissions/GACIdentityPermission.cs index 5c209af..f93f26d 100644 --- a/src/coreclr/src/mscorlib/src/System/Security/Permissions/GACIdentityPermission.cs +++ b/src/coreclr/src/mscorlib/src/System/Security/Permissions/GACIdentityPermission.cs @@ -5,9 +5,6 @@ namespace System.Security.Permissions { using System; -#if FEATURE_CAS_POLICY - using SecurityElement = System.Security.SecurityElement; -#endif // FEATURE_CAS_POLICY using System.Globalization; [AttributeUsage(AttributeTargets.Method | AttributeTargets.Constructor | AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Assembly, AllowMultiple = true, Inherited = false )] @@ -92,19 +89,6 @@ namespace System.Security.Permissions return this.Copy(); } -#if FEATURE_CAS_POLICY - public override SecurityElement ToXml() - { - SecurityElement securityElement = CodeAccessPermission.CreatePermissionElement( this, "System.Security.Permissions.GacIdentityPermission" ); - return securityElement; - } - - public override void FromXml(SecurityElement securityElement) - { - CodeAccessPermission.ValidateElement(securityElement, this); - } -#endif // FEATURE_CAS_POLICY - /// int IBuiltInPermission.GetTokenIndex() { diff --git a/src/coreclr/src/mscorlib/src/System/Security/Permissions/HostProtectionPermission.cs b/src/coreclr/src/mscorlib/src/System/Security/Permissions/HostProtectionPermission.cs index 85be61a..d346a11 100644 --- a/src/coreclr/src/mscorlib/src/System/Security/Permissions/HostProtectionPermission.cs +++ b/src/coreclr/src/mscorlib/src/System/Security/Permissions/HostProtectionPermission.cs @@ -247,38 +247,6 @@ namespace System.Security.Permissions return new HostProtectionPermission(m_resources); } -#if FEATURE_CAS_POLICY - //------------------------------------------------------ - // - // XML - // - //------------------------------------------------------ - public override SecurityElement ToXml() - { - SecurityElement esd = CodeAccessPermission.CreatePermissionElement( this, this.GetType().FullName ); - if(IsUnrestricted()) - esd.AddAttribute( "Unrestricted", "true" ); - else - esd.AddAttribute( "Resources", XMLUtil.BitFieldEnumToString( typeof( HostProtectionResource ), Resources ) ); - return esd; - } - - public override void FromXml(SecurityElement esd) - { - CodeAccessPermission.ValidateElement( esd, this ); - if (XMLUtil.IsUnrestricted( esd )) - Resources = HostProtectionResource.All; - else - { - String resources = esd.Attribute( "Resources" ); - if (resources == null) - Resources = HostProtectionResource.None; - else - Resources = (HostProtectionResource)Enum.Parse( typeof( HostProtectionResource ), resources ); - } - } -#endif // FEATURE_CAS_POLICY - //------------------------------------------------------ // // OBJECT OVERRIDES diff --git a/src/coreclr/src/mscorlib/src/System/Security/Permissions/IsolatedStorageFilePermission.cs b/src/coreclr/src/mscorlib/src/System/Security/Permissions/IsolatedStorageFilePermission.cs index 1e11b4a..42bc648 100644 --- a/src/coreclr/src/mscorlib/src/System/Security/Permissions/IsolatedStorageFilePermission.cs +++ b/src/coreclr/src/mscorlib/src/System/Security/Permissions/IsolatedStorageFilePermission.cs @@ -158,19 +158,6 @@ namespace System.Security.Permissions { { return BuiltInPermissionIndex.IsolatedStorageFilePermissionIndex; } - - //------------------------------------------------------ - // - // IsolatedStoragePermission OVERRIDES - // - //------------------------------------------------------ -#if FEATURE_CAS_POLICY - [System.Runtime.InteropServices.ComVisible(false)] - public override SecurityElement ToXml() - { - return base.ToXml( "System.Security.Permissions.IsolatedStorageFilePermission" ); - } -#endif // FEATURE_CAS_POLICY } } diff --git a/src/coreclr/src/mscorlib/src/System/Security/Permissions/IsolatedStoragePermission.cs b/src/coreclr/src/mscorlib/src/System/Security/Permissions/IsolatedStoragePermission.cs index 308adbd..9f09a37 100644 --- a/src/coreclr/src/mscorlib/src/System/Security/Permissions/IsolatedStoragePermission.cs +++ b/src/coreclr/src/mscorlib/src/System/Security/Permissions/IsolatedStoragePermission.cs @@ -32,9 +32,6 @@ namespace System.Security.Permissions { [Serializable] -#if !FEATURE_CORECLR - [SecurityPermissionAttribute( SecurityAction.InheritanceDemand, ControlEvidence = true, ControlPolicy = true )] -#endif [System.Runtime.InteropServices.ComVisible(true)] abstract public class IsolatedStoragePermission : CodeAccessPermission, IUnrestrictedPermission @@ -182,93 +179,5 @@ namespace System.Security.Permissions { //------------------------------------------------------ internal static long min(long x,long y) {return x>y?y:x;} internal static long max(long x,long y) {return x0) - { - esd.AddAttribute(_strUserQuota, (m_userQuota).ToString(CultureInfo.InvariantCulture)) ; - } - if (m_machineQuota>0) - { - esd.AddAttribute(_strMachineQuota, (m_machineQuota).ToString(CultureInfo.InvariantCulture)) ; - } - if (m_expirationDays>0) - { - esd.AddAttribute( _strExpiry, (m_expirationDays).ToString(CultureInfo.InvariantCulture)) ; - } - if (m_permanentData) - { - esd.AddAttribute(_strPermDat, (m_permanentData).ToString()) ; - } - } - else - { - esd.AddAttribute( "Unrestricted", "true" ); - } - return esd; - } - - - public override void FromXml(SecurityElement esd) - { - CodeAccessPermission.ValidateElement( esd, this ); - - m_allowed = IsolatedStorageContainment.None; // default if no match - - if (XMLUtil.IsUnrestricted(esd)) - { - m_allowed = IsolatedStorageContainment.UnrestrictedIsolatedStorage; - } - else - { - String allowed = esd.Attribute( "Allowed" ); - - if (allowed != null) - m_allowed = (IsolatedStorageContainment)Enum.Parse( typeof( IsolatedStorageContainment ), allowed ); - } - - if (m_allowed == IsolatedStorageContainment.UnrestrictedIsolatedStorage) - { - m_userQuota = Int64.MaxValue; - m_machineQuota = Int64.MaxValue; - m_expirationDays = Int64.MaxValue ; - m_permanentData = true; - } - else - { - String param; - param = esd.Attribute (_strUserQuota) ; - m_userQuota = param != null ? Int64.Parse(param, CultureInfo.InvariantCulture) : 0 ; - param = esd.Attribute (_strMachineQuota) ; - m_machineQuota = param != null ? Int64.Parse(param, CultureInfo.InvariantCulture) : 0 ; - param = esd.Attribute (_strExpiry) ; - m_expirationDays = param != null ? Int64.Parse(param, CultureInfo.InvariantCulture) : 0 ; - param = esd.Attribute (_strPermDat) ; - m_permanentData = param != null ? (Boolean.Parse(param)) : false ; - } - } -#endif // FEATURE_CAS_POLICY } } diff --git a/src/coreclr/src/mscorlib/src/System/Security/Permissions/PermissionAttributes.cs b/src/coreclr/src/mscorlib/src/System/Security/Permissions/PermissionAttributes.cs index f14fb0d..3e41c72 100644 --- a/src/coreclr/src/mscorlib/src/System/Security/Permissions/PermissionAttributes.cs +++ b/src/coreclr/src/mscorlib/src/System/Security/Permissions/PermissionAttributes.cs @@ -8,9 +8,6 @@ namespace System.Security.Permissions using System.Security.Util; using System.IO; using System.Security.Policy; -#if FEATURE_MACL - using System.Security.AccessControl; -#endif using System.Text; using System.Threading; using System.Runtime.InteropServices; @@ -23,11 +20,9 @@ namespace System.Security.Permissions using System.Diagnostics.Contracts; [Serializable] -[System.Runtime.InteropServices.ComVisible(true)] -#if !FEATURE_CAS_POLICY + [System.Runtime.InteropServices.ComVisible(true)] // The csharp compiler requires these types to be public, but they are not used elsewhere. [Obsolete("SecurityAction is no longer accessible to application code.")] -#endif public enum SecurityAction { // Demand permission of all caller @@ -62,14 +57,11 @@ namespace System.Security.Permissions RequestRefuse = 10, } - -[Serializable] -[AttributeUsage(AttributeTargets.Method | AttributeTargets.Constructor | AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Assembly, AllowMultiple = true, Inherited = false )] -[System.Runtime.InteropServices.ComVisible(true)] -#if !FEATURE_CAS_POLICY + [Serializable] + [AttributeUsage(AttributeTargets.Method | AttributeTargets.Constructor | AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Assembly, AllowMultiple = true, Inherited = false )] + [System.Runtime.InteropServices.ComVisible(true)] // The csharp compiler requires these types to be public, but they are not used elsewhere. [Obsolete("SecurityAttribute is no longer accessible to application code.")] -#endif public abstract class SecurityAttribute : System.Attribute { /// @@ -108,13 +100,11 @@ namespace System.Security.Permissions } } -[Serializable] -[AttributeUsage(AttributeTargets.Method | AttributeTargets.Constructor | AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Assembly, AllowMultiple = true, Inherited = false )] -[System.Runtime.InteropServices.ComVisible(true)] -#if !FEATURE_CAS_POLICY + [Serializable] + [AttributeUsage(AttributeTargets.Method | AttributeTargets.Constructor | AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Assembly, AllowMultiple = true, Inherited = false )] + [System.Runtime.InteropServices.ComVisible(true)] // The csharp compiler requires these types to be public, but they are not used elsewhere. [Obsolete("CodeAccessSecurityAttribute is no longer accessible to application code.")] -#endif public abstract class CodeAccessSecurityAttribute : SecurityAttribute { protected CodeAccessSecurityAttribute( SecurityAction action ) @@ -307,12 +297,6 @@ namespace System.Security.Permissions perm.SetPathList( FileIOPermissionAccess.Append, m_append ); if (m_pathDiscovery != null) perm.SetPathList( FileIOPermissionAccess.PathDiscovery, m_pathDiscovery ); -#if FEATURE_MACL - if (m_viewAccess != null) - perm.SetPathList( FileIOPermissionAccess.NoAccess, AccessControlActions.View, new String[] { m_viewAccess }, false ); - if (m_changeAccess != null) - perm.SetPathList( FileIOPermissionAccess.NoAccess, AccessControlActions.Change, new String[] { m_changeAccess }, false ); -#endif perm.AllFiles = m_allFiles; perm.AllLocalFiles = m_allLocalFiles; @@ -384,59 +368,6 @@ namespace System.Security.Permissions } } -#if !FEATURE_CORECLR - // PrincipalPermissionAttribute currently derives from - // CodeAccessSecurityAttribute, even though it's not related to code access - // security. This is because compilers are currently looking for - // CodeAccessSecurityAttribute as a direct parent class rather than - // SecurityAttribute as the root class. - [AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, AllowMultiple = true, Inherited = false )] -[System.Runtime.InteropServices.ComVisible(true)] - [Serializable] - sealed public class PrincipalPermissionAttribute : CodeAccessSecurityAttribute - { - private String m_name = null; - private String m_role = null; - private bool m_authenticated = true; - - public PrincipalPermissionAttribute( SecurityAction action ) - : base( action ) - { - } - - public String Name - { - get { return m_name; } - set { m_name = value; } - } - - public String Role - { - get { return m_role; } - set { m_role = value; } - } - - public bool Authenticated - { - get { return m_authenticated; } - set { m_authenticated = value; } - } - - - public override IPermission CreatePermission() - { - if (m_unrestricted) - { - return new PrincipalPermission( PermissionState.Unrestricted ); - } - else - { - return new PrincipalPermission( m_name, m_role, m_authenticated ); - } - } - } -#endif // !FEATURE_CORECLR - [AttributeUsage(AttributeTargets.Method | AttributeTargets.Constructor | AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Assembly, AllowMultiple = true, Inherited = false )] [System.Runtime.InteropServices.ComVisible(true)] [Serializable] @@ -570,24 +501,16 @@ namespace System.Security.Permissions perm.SetPathList( RegistryPermissionAccess.Write, m_write ); if (m_create != null) perm.SetPathList( RegistryPermissionAccess.Create, m_create ); -#if FEATURE_MACL - if (m_viewAcl != null) - perm.SetPathList( AccessControlActions.View, m_viewAcl ); - if (m_changeAcl != null) - perm.SetPathList( AccessControlActions.Change, m_changeAcl ); -#endif return perm; } } } [AttributeUsage(AttributeTargets.Method | AttributeTargets.Constructor | AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Assembly, AllowMultiple = true, Inherited = false )] -[System.Runtime.InteropServices.ComVisible(true)] + [System.Runtime.InteropServices.ComVisible(true)] [Serializable] -#if !FEATURE_CAS_POLICY // The csharp compiler requires these types to be public, but they are not used elsewhere. [Obsolete("SecurityPermissionAttribute is no longer accessible to application code.")] -#endif sealed public class SecurityPermissionAttribute : CodeAccessSecurityAttribute { private SecurityPermissionFlag m_flag = SecurityPermissionFlag.NoFlags; @@ -662,7 +585,7 @@ namespace System.Security.Permissions set { m_flag = value ? m_flag | SecurityPermissionFlag.RemotingConfiguration : m_flag & ~SecurityPermissionFlag.RemotingConfiguration; } } -[System.Runtime.InteropServices.ComVisible(true)] + [System.Runtime.InteropServices.ComVisible(true)] public bool Infrastructure { get { return (m_flag & SecurityPermissionFlag.Infrastructure) != 0; } set { m_flag = value ? m_flag | SecurityPermissionFlag.Infrastructure : m_flag & ~SecurityPermissionFlag.Infrastructure; } @@ -893,170 +816,6 @@ namespace System.Security.Permissions } } } - -#if FEATURE_X509 && FEATURE_CAS_POLICY - [AttributeUsage(AttributeTargets.Method | AttributeTargets.Constructor | AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Assembly, AllowMultiple = true, Inherited = false )] -[System.Runtime.InteropServices.ComVisible(true)] - [Serializable] - sealed public class PublisherIdentityPermissionAttribute : CodeAccessSecurityAttribute - { - private String m_x509cert = null; - private String m_certFile = null; - private String m_signedFile = null; - - public PublisherIdentityPermissionAttribute( SecurityAction action ) - : base( action ) - { - m_x509cert = null; - m_certFile = null; - m_signedFile = null; - } - - public String X509Certificate { - get { return m_x509cert; } - set { m_x509cert = value; } - } - - public String CertFile { - get { return m_certFile; } - set { m_certFile = value; } - } - - public String SignedFile { - get { return m_signedFile; } - set { m_signedFile = value; } - } - - public override IPermission CreatePermission() - { - if (m_unrestricted) - { - return new PublisherIdentityPermission( PermissionState.Unrestricted ); - } - else - { - if (m_x509cert != null) - { - return new PublisherIdentityPermission( new X509Certificate( System.Security.Util.Hex.DecodeHexString( m_x509cert ) ) ); - } - else if (m_certFile != null) - { - return new PublisherIdentityPermission( System.Security.Cryptography.X509Certificates.X509Certificate.CreateFromCertFile( m_certFile ) ); - } - else if (m_signedFile != null) - { - return new PublisherIdentityPermission( System.Security.Cryptography.X509Certificates.X509Certificate.CreateFromSignedFile( m_signedFile ) ); - } - else - { - return new PublisherIdentityPermission( PermissionState.None ); - } - } - } - } -#endif // #if FEATURE_X509 && FEATURE_CAS_POLICY - -#if !FEATURE_CORECLR -[Serializable] -[AttributeUsage(AttributeTargets.Method | AttributeTargets.Constructor - | AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Assembly, - AllowMultiple=true, Inherited=false)] -[System.Runtime.InteropServices.ComVisible(true)] - public abstract class IsolatedStoragePermissionAttribute : CodeAccessSecurityAttribute - { - /// - internal long m_userQuota; -#if false - /// - internal long m_machineQuota; - /// - internal long m_expirationDays; - /// - internal bool m_permanentData; -#endif - /// - internal IsolatedStorageContainment m_allowed; - protected IsolatedStoragePermissionAttribute(SecurityAction action) : base(action) - { - } - - // properties - public long UserQuota { - set{ - m_userQuota = value; - } - get{ - return m_userQuota; - } - } -#if false - internal long MachineQuota { - set{ - m_machineQuota = value; - } - get{ - return m_machineQuota; - } - } - internal long ExpirationDays { - set{ - m_expirationDays = value; - } - get{ - return m_expirationDays; - } - } - internal bool PermanentData { - set{ - m_permanentData = value; - } - get{ - return m_permanentData; - } - } -#endif - public IsolatedStorageContainment UsageAllowed { - set{ - m_allowed = value; - } - get{ - return m_allowed; - } - } - - } - - [AttributeUsage(AttributeTargets.Method | AttributeTargets.Constructor - | AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Assembly, - AllowMultiple=true, Inherited=false)] -[System.Runtime.InteropServices.ComVisible(true)] - [Serializable] - sealed public class IsolatedStorageFilePermissionAttribute : IsolatedStoragePermissionAttribute - { - public IsolatedStorageFilePermissionAttribute(SecurityAction action) : base(action) - { - - } - public override IPermission CreatePermission() - { - IsolatedStorageFilePermission p; - if (m_unrestricted) { - p = new IsolatedStorageFilePermission - (PermissionState.Unrestricted); - } else { - p = new IsolatedStorageFilePermission(PermissionState.None); - p.UserQuota = m_userQuota; - p.UsageAllowed = m_allowed; -#if false - p.PermanentData = m_permanentData; - p.MachineQuota = m_machineQuota; - p.ExpirationDays = m_expirationDays; -#endif - } - return p; - } - } -#endif // FEATURE_CORECLR [AttributeUsage(AttributeTargets.Method | AttributeTargets.Constructor | AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Assembly, AllowMultiple = true, Inherited = false )] [System.Runtime.InteropServices.ComVisible(true)] @@ -1109,66 +868,12 @@ namespace System.Security.Permissions return null; } -#if FEATURE_CAS_POLICY - private PermissionSet BruteForceParseStream(Stream stream) - { - Encoding[] encodings = new Encoding[] { Encoding.UTF8, - Encoding.ASCII, - Encoding.Unicode }; - - StreamReader reader = null; - Exception exception = null; - - for (int i = 0; reader == null && i < encodings.Length; ++i) - { - try - { - stream.Position = 0; - reader = new StreamReader( stream, encodings[i] ); - - return ParsePermissionSet( new Parser(reader) ); - } - catch (Exception e1) - { - if (exception == null) - exception = e1; - } - } - - throw exception; - } - - private PermissionSet ParsePermissionSet(Parser parser) - { - SecurityElement e = parser.GetTopElement(); - PermissionSet permSet = new PermissionSet( PermissionState.None ); - permSet.FromXml( e ); - - return permSet; - } -#endif // FEATURE_CAS_POLICY - -#if FEATURE_CAS_POLICY - [System.Security.SecuritySafeCritical] // auto-generated -#endif public PermissionSet CreatePermissionSet() { if (m_unrestricted) return new PermissionSet( PermissionState.Unrestricted ); else if (m_name != null) -#if FEATURE_CAS_POLICY - return PolicyLevel.GetBuiltInSet( m_name ); -#else return NamedPermissionSet.GetBuiltInSet( m_name ); -#endif // FEATURE_CAS_POLICY -#if FEATURE_CAS_POLICY - else if (m_xml != null) - return ParsePermissionSet( new Parser(m_xml.ToCharArray()) ); - else if (m_hex != null) - return BruteForceParseStream( new MemoryStream(Util.Hex.DecodeHexString(m_hex)) ); - else if (m_file != null) - return BruteForceParseStream( new FileStream( m_file, FileMode.Open, FileAccess.Read) ); -#endif // FEATURE_CAS_POLICY else return new PermissionSet( PermissionState.None ); } diff --git a/src/coreclr/src/mscorlib/src/System/Security/Permissions/ReflectionPermission.cs b/src/coreclr/src/mscorlib/src/System/Security/Permissions/ReflectionPermission.cs index 2bc3c08..1c9dd76 100644 --- a/src/coreclr/src/mscorlib/src/System/Security/Permissions/ReflectionPermission.cs +++ b/src/coreclr/src/mscorlib/src/System/Security/Permissions/ReflectionPermission.cs @@ -259,45 +259,6 @@ namespace System.Security.Permissions throw new ArgumentException(Environment.GetResourceString("Arg_EnumIllegalVal", (int)type)); Contract.EndContractBlock(); } - -#if FEATURE_CAS_POLICY - //------------------------------------------------------ - // - // PUBLIC ENCODING METHODS - // - //------------------------------------------------------ - - public override SecurityElement ToXml() - { - SecurityElement esd = CodeAccessPermission.CreatePermissionElement( this, "System.Security.Permissions.ReflectionPermission" ); - if (!IsUnrestricted()) - { - esd.AddAttribute( "Flags", XMLUtil.BitFieldEnumToString( typeof( ReflectionPermissionFlag ), m_flags ) ); - } - else - { - esd.AddAttribute( "Unrestricted", "true" ); - } - return esd; - } - - public override void FromXml(SecurityElement esd) - { - CodeAccessPermission.ValidateElement( esd, this ); - if (XMLUtil.IsUnrestricted( esd )) - { - m_flags = ReflectionPermission.AllFlagsAndMore; - return; - } - - Reset () ; - SetUnrestricted (false) ; - - String flags = esd.Attribute( "Flags" ); - if (flags != null) - m_flags = (ReflectionPermissionFlag)Enum.Parse( typeof( ReflectionPermissionFlag ), flags ); - } -#endif // FEATURE_CAS_POLICY /// int IBuiltInPermission.GetTokenIndex() diff --git a/src/coreclr/src/mscorlib/src/System/Security/Permissions/RegistryPermission.cs b/src/coreclr/src/mscorlib/src/System/Security/Permissions/RegistryPermission.cs index bf801d6..af6c5d4 100644 --- a/src/coreclr/src/mscorlib/src/System/Security/Permissions/RegistryPermission.cs +++ b/src/coreclr/src/mscorlib/src/System/Security/Permissions/RegistryPermission.cs @@ -59,14 +59,6 @@ namespace System.Security.Permissions SetPathList( access, pathList ); } -#if FEATURE_MACL - public RegistryPermission( RegistryPermissionAccess access, AccessControlActions control, String pathList ) - { - m_unrestricted = false; - AddPathList( access, control, pathList ); - } -#endif - public void SetPathList( RegistryPermissionAccess access, String pathList ) { VerifyAccess( access ); @@ -85,21 +77,6 @@ namespace System.Security.Permissions AddPathList( access, pathList ); } -#if FEATURE_MACL - internal void SetPathList( AccessControlActions control, String pathList ) - { - m_unrestricted = false; - - if ((control & AccessControlActions.View) != 0) - m_viewAcl = null; - - if ((control & AccessControlActions.Change) != 0) - m_changeAcl = null; - - AddPathList( RegistryPermissionAccess.NoAccess, control, pathList ); - } -#endif - public void AddPathList( RegistryPermissionAccess access, String pathList ) { AddPathList( access, AccessControlActions.None, pathList ); @@ -130,22 +107,6 @@ namespace System.Security.Permissions m_create = new StringExpressionSet(); m_create.AddExpressions( pathList ); } - -#if FEATURE_MACL - if ((control & AccessControlActions.View) != 0) - { - if (m_viewAcl == null) - m_viewAcl = new StringExpressionSet(); - m_viewAcl.AddExpressions( pathList ); - } - - if ((control & AccessControlActions.Change) != 0) - { - if (m_changeAcl == null) - m_changeAcl = new StringExpressionSet(); - m_changeAcl.AddExpressions( pathList ); - } -#endif } [SecuritySafeCritical] @@ -391,93 +352,6 @@ namespace System.Security.Permissions } return copy; } - -#if FEATURE_CAS_POLICY - [SecuritySafeCritical] - public override SecurityElement ToXml() - { - // SafeCritical: our string expression sets don't contain paths, so there's no information that - // needs to be guarded in them. - SecurityElement esd = CodeAccessPermission.CreatePermissionElement( this, "System.Security.Permissions.RegistryPermission" ); - if (!IsUnrestricted()) - { - if (this.m_read != null && !this.m_read.IsEmpty()) - { - esd.AddAttribute( "Read", SecurityElement.Escape( m_read.UnsafeToString() ) ); - } - if (this.m_write != null && !this.m_write.IsEmpty()) - { - esd.AddAttribute( "Write", SecurityElement.Escape( m_write.UnsafeToString() ) ); - } - if (this.m_create != null && !this.m_create.IsEmpty()) - { - esd.AddAttribute( "Create", SecurityElement.Escape( m_create.UnsafeToString() ) ); - } - if (this.m_viewAcl != null && !this.m_viewAcl.IsEmpty()) - { - esd.AddAttribute( "ViewAccessControl", SecurityElement.Escape( m_viewAcl.UnsafeToString() ) ); - } - if (this.m_changeAcl != null && !this.m_changeAcl.IsEmpty()) - { - esd.AddAttribute( "ChangeAccessControl", SecurityElement.Escape( m_changeAcl.UnsafeToString() ) ); - } - } - else - { - esd.AddAttribute( "Unrestricted", "true" ); - } - return esd; - } - - public override void FromXml(SecurityElement esd) - { - CodeAccessPermission.ValidateElement( esd, this ); - String et; - - if (XMLUtil.IsUnrestricted( esd )) - { - m_unrestricted = true; - return; - } - - m_unrestricted = false; - m_read = null; - m_write = null; - m_create = null; - m_viewAcl = null; - m_changeAcl = null; - - et = esd.Attribute( "Read" ); - if (et != null) - { - m_read = new StringExpressionSet( et ); - } - - et = esd.Attribute( "Write" ); - if (et != null) - { - m_write = new StringExpressionSet( et ); - } - - et = esd.Attribute( "Create" ); - if (et != null) - { - m_create = new StringExpressionSet( et ); - } - - et = esd.Attribute( "ViewAccessControl" ); - if (et != null) - { - m_viewAcl = new StringExpressionSet( et ); - } - - et = esd.Attribute( "ChangeAccessControl" ); - if (et != null) - { - m_changeAcl = new StringExpressionSet( et ); - } - } -#endif // FEATURE_CAS_POLICY /// int IBuiltInPermission.GetTokenIndex() diff --git a/src/coreclr/src/mscorlib/src/System/Security/Permissions/SecurityPermission.cs b/src/coreclr/src/mscorlib/src/System/Security/Permissions/SecurityPermission.cs index b359cc5..cf30029 100644 --- a/src/coreclr/src/mscorlib/src/System/Security/Permissions/SecurityPermission.cs +++ b/src/coreclr/src/mscorlib/src/System/Security/Permissions/SecurityPermission.cs @@ -16,13 +16,11 @@ namespace System.Security.Permissions using System.Globalization; using System.Diagnostics.Contracts; -[Serializable] + [Serializable] [Flags] -[System.Runtime.InteropServices.ComVisible(true)] -#if !FEATURE_CAS_POLICY + [System.Runtime.InteropServices.ComVisible(true)] // The csharp compiler requires these types to be public, but they are not used elsewhere. [Obsolete("SecurityPermissionFlag is no longer accessible to application code.")] -#endif public enum SecurityPermissionFlag { NoFlags = 0x00, @@ -254,99 +252,9 @@ namespace System.Security.Permissions Contract.EndContractBlock(); } -#if FEATURE_CAS_POLICY - //------------------------------------------------------ - // - // PUBLIC ENCODING METHODS - // - //------------------------------------------------------ - - private const String _strHeaderAssertion = "Assertion"; - private const String _strHeaderUnmanagedCode = "UnmanagedCode"; - private const String _strHeaderExecution = "Execution"; - private const String _strHeaderSkipVerification = "SkipVerification"; - private const String _strHeaderControlThread = "ControlThread"; - private const String _strHeaderControlEvidence = "ControlEvidence"; - private const String _strHeaderControlPolicy = "ControlPolicy"; - private const String _strHeaderSerializationFormatter = "SerializationFormatter"; - private const String _strHeaderControlDomainPolicy = "ControlDomainPolicy"; - private const String _strHeaderControlPrincipal = "ControlPrincipal"; - private const String _strHeaderControlAppDomain = "ControlAppDomain"; - - public override SecurityElement ToXml() - { - SecurityElement esd = CodeAccessPermission.CreatePermissionElement( this, "System.Security.Permissions.SecurityPermission" ); - if (!IsUnrestricted()) - { - esd.AddAttribute( "Flags", XMLUtil.BitFieldEnumToString( typeof( SecurityPermissionFlag ), m_flags ) ); - } - else - { - esd.AddAttribute( "Unrestricted", "true" ); - } - return esd; - } - - public override void FromXml(SecurityElement esd) - { - CodeAccessPermission.ValidateElement( esd, this ); - if (XMLUtil.IsUnrestricted( esd )) - { - m_flags = SecurityPermissionFlag.AllFlags; - return; - } - - Reset () ; - SetUnrestricted (false) ; - - String flags = esd.Attribute( "Flags" ); - - if (flags != null) - m_flags = (SecurityPermissionFlag)Enum.Parse( typeof( SecurityPermissionFlag ), flags ); - } -#endif // FEATURE_CAS_POLICY - // // Object Overrides // - - #if ZERO // Do not remove this code, usefull for debugging - public override String ToString() - { - StringBuilder sb = new StringBuilder(); - sb.Append("SecurityPermission("); - if (IsUnrestricted()) - { - sb.Append("Unrestricted"); - } - else - { - if (GetFlag(SecurityPermissionFlag.Assertion)) - sb.Append("Assertion; "); - if (GetFlag(SecurityPermissionFlag.UnmanagedCode)) - sb.Append("UnmangedCode; "); - if (GetFlag(SecurityPermissionFlag.SkipVerification)) - sb.Append("SkipVerification; "); - if (GetFlag(SecurityPermissionFlag.Execution)) - sb.Append("Execution; "); - if (GetFlag(SecurityPermissionFlag.ControlThread)) - sb.Append("ControlThread; "); - if (GetFlag(SecurityPermissionFlag.ControlEvidence)) - sb.Append("ControlEvidence; "); - if (GetFlag(SecurityPermissionFlag.ControlPolicy)) - sb.Append("ControlPolicy; "); - if (GetFlag(SecurityPermissionFlag.SerializationFormatter)) - sb.Append("SerializationFormatter; "); - if (GetFlag(SecurityPermissionFlag.ControlDomainPolicy)) - sb.Append("ControlDomainPolicy; "); - if (GetFlag(SecurityPermissionFlag.ControlPrincipal)) - sb.Append("ControlPrincipal; "); - } - - sb.Append(")"); - return sb.ToString(); - } - #endif /// int IBuiltInPermission.GetTokenIndex() diff --git a/src/coreclr/src/mscorlib/src/System/Security/Permissions/SiteIdentityPermission.cs b/src/coreclr/src/mscorlib/src/System/Security/Permissions/SiteIdentityPermission.cs index 6050b58..ff38d51 100644 --- a/src/coreclr/src/mscorlib/src/System/Security/Permissions/SiteIdentityPermission.cs +++ b/src/coreclr/src/mscorlib/src/System/Security/Permissions/SiteIdentityPermission.cs @@ -5,9 +5,6 @@ namespace System.Security.Permissions { using System; -#if FEATURE_CAS_POLICY - using SecurityElement = System.Security.SecurityElement; -#endif // FEATURE_CAS_POLICY using SiteString = System.Security.Util.SiteString; using System.Text; using System.Collections; @@ -31,55 +28,6 @@ namespace System.Security.Permissions [OptionalField(VersionAdded = 2)] private SiteString[] m_sites; -#if FEATURE_REMOTING - // This field will be populated only for non X-AD scenarios where we create a XML-ised string of the Permission - [OptionalField(VersionAdded = 2)] - private String m_serializedPermission; - - // This field is legacy info from v1.x and is never used in v2.0 and beyond: purely for serialization purposes - private SiteString m_site; - - [OnDeserialized] - private void OnDeserialized(StreamingContext ctx) - { - // v2.0 and beyond XML case - if (m_serializedPermission != null) - { - FromXml(SecurityElement.FromString(m_serializedPermission)); - m_serializedPermission = null; - } - else if (m_site != null) //v1.x case where we read the m_site value - { - m_unrestricted = false; - m_sites = new SiteString[1]; - m_sites[0] = m_site; - m_site = null; - } - } - - [OnSerializing] - private void OnSerializing(StreamingContext ctx) - { - - if ((ctx.State & ~(StreamingContextStates.Clone|StreamingContextStates.CrossAppDomain)) != 0) - { - m_serializedPermission = ToXml().ToString(); //for the v2 and beyond case - if (m_sites != null && m_sites.Length == 1) // for the v1.x case - m_site = m_sites[0]; - - } - } - [OnSerialized] - private void OnSerialized(StreamingContext ctx) - { - if ((ctx.State & ~(StreamingContextStates.Clone|StreamingContextStates.CrossAppDomain)) != 0) - { - m_serializedPermission = null; - m_site = null; - } - } -#endif // FEATURE_REMOTING - //------------------------------------------------------ // // PUBLIC CONSTRUCTORS @@ -150,8 +98,6 @@ namespace System.Security.Permissions // IPERMISSION IMPLEMENTATION // //------------------------------------------------------ - - public override IPermission Copy() { SiteIdentityPermission perm = new SiteIdentityPermission( PermissionState.None ); @@ -291,60 +237,6 @@ namespace System.Security.Permissions return result; } -#if FEATURE_CAS_POLICY - public override void FromXml(SecurityElement esd) - { - m_unrestricted = false; - m_sites = null; - CodeAccessPermission.ValidateElement( esd, this ); - String unr = esd.Attribute( "Unrestricted" ); - if(unr != null && String.Compare(unr, "true", StringComparison.OrdinalIgnoreCase) == 0) - { - m_unrestricted = true; - return; - } - String elem = esd.Attribute( "Site" ); - List al = new List(); - if(elem != null) - al.Add(new SiteString( elem )); - ArrayList alChildren = esd.Children; - if(alChildren != null) - { - foreach(SecurityElement child in alChildren) - { - elem = child.Attribute( "Site" ); - if(elem != null) - al.Add(new SiteString( elem )); - } - } - if(al.Count != 0) - m_sites = al.ToArray(); - } - - public override SecurityElement ToXml() - { - SecurityElement esd = CodeAccessPermission.CreatePermissionElement( this, "System.Security.Permissions.SiteIdentityPermission" ); - if (m_unrestricted) - esd.AddAttribute( "Unrestricted", "true" ); - else if (m_sites != null) - { - if (m_sites.Length == 1) - esd.AddAttribute( "Site", m_sites[0].ToString() ); - else - { - int n; - for(n = 0; n < m_sites.Length; n++) - { - SecurityElement child = new SecurityElement("Site"); - child.AddAttribute( "Site", m_sites[n].ToString() ); - esd.AddChild(child); - } - } - } - return esd; - } -#endif // FEATURE_CAS_POLICY - /// int IBuiltInPermission.GetTokenIndex() { diff --git a/src/coreclr/src/mscorlib/src/System/Security/Permissions/StrongNameIdentityPermission.cs b/src/coreclr/src/mscorlib/src/System/Security/Permissions/StrongNameIdentityPermission.cs index 0bc689b..f09d84d 100644 --- a/src/coreclr/src/mscorlib/src/System/Security/Permissions/StrongNameIdentityPermission.cs +++ b/src/coreclr/src/mscorlib/src/System/Security/Permissions/StrongNameIdentityPermission.cs @@ -5,9 +5,6 @@ namespace System.Security.Permissions { using System; -#if FEATURE_CAS_POLICY - using SecurityElement = System.Security.SecurityElement; -#endif // FEATURE_CAS_POLICY using System.Security.Util; using System.IO; using String = System.String; @@ -389,89 +386,6 @@ namespace System.Security.Permissions return result; } -#if FEATURE_CAS_POLICY - public override void FromXml(SecurityElement e) - { - m_unrestricted = false; - m_strongNames = null; - CodeAccessPermission.ValidateElement( e, this ); - String unr = e.Attribute( "Unrestricted" ); - if(unr != null && String.Compare(unr, "true", StringComparison.OrdinalIgnoreCase) == 0) - { - m_unrestricted = true; - return; - } - String elBlob = e.Attribute("PublicKeyBlob"); - String elName = e.Attribute("Name"); - String elVersion = e.Attribute("AssemblyVersion"); - StrongName2 sn; - List al = new List(); - if(elBlob != null || elName != null || elVersion != null) - { - sn = new StrongName2( - (elBlob == null ? null : new StrongNamePublicKeyBlob(elBlob)), - elName, - (elVersion == null ? null : new Version(elVersion))); - al.Add(sn); - } - ArrayList alChildren = e.Children; - if(alChildren != null) - { - foreach(SecurityElement child in alChildren) - { - elBlob = child.Attribute("PublicKeyBlob"); - elName = child.Attribute("Name"); - elVersion = child.Attribute("AssemblyVersion"); - if(elBlob != null || elName != null || elVersion != null) - { - sn = new StrongName2( - (elBlob == null ? null : new StrongNamePublicKeyBlob(elBlob)), - elName, - (elVersion == null ? null : new Version(elVersion))); - al.Add(sn); - } - } - } - if(al.Count != 0) - m_strongNames = al.ToArray(); - } - - public override SecurityElement ToXml() - { - SecurityElement esd = CodeAccessPermission.CreatePermissionElement( this, "System.Security.Permissions.StrongNameIdentityPermission" ); - if (m_unrestricted) - esd.AddAttribute( "Unrestricted", "true" ); - else if (m_strongNames != null) - { - if (m_strongNames.Length == 1) - { - if (m_strongNames[0].m_publicKeyBlob != null) - esd.AddAttribute("PublicKeyBlob", Hex.EncodeHexString(m_strongNames[0].m_publicKeyBlob.PublicKey)); - if (m_strongNames[0].m_name != null) - esd.AddAttribute("Name", m_strongNames[0].m_name); - if ((Object)m_strongNames[0].m_version != null) - esd.AddAttribute("AssemblyVersion", m_strongNames[0].m_version.ToString()); - } - else - { - int n; - for(n = 0; n < m_strongNames.Length; n++) - { - SecurityElement child = new SecurityElement("StrongName"); - if (m_strongNames[n].m_publicKeyBlob != null) - child.AddAttribute("PublicKeyBlob", Hex.EncodeHexString(m_strongNames[n].m_publicKeyBlob.PublicKey)); - if (m_strongNames[n].m_name != null) - child.AddAttribute("Name", m_strongNames[n].m_name); - if ((Object)m_strongNames[n].m_version != null) - child.AddAttribute("AssemblyVersion", m_strongNames[n].m_version.ToString()); - esd.AddChild(child); - } - } - } - return esd; - } -#endif // FEATURE_CAS_POLICY - /// int IBuiltInPermission.GetTokenIndex() { diff --git a/src/coreclr/src/mscorlib/src/System/Security/Permissions/UIPermission.cs b/src/coreclr/src/mscorlib/src/System/Security/Permissions/UIPermission.cs index bb122b7..4abe801 100644 --- a/src/coreclr/src/mscorlib/src/System/Security/Permissions/UIPermission.cs +++ b/src/coreclr/src/mscorlib/src/System/Security/Permissions/UIPermission.cs @@ -309,50 +309,6 @@ namespace System.Security.Permissions { return new UIPermission(this.m_windowFlag, this.m_clipboardFlag); } - -#if FEATURE_CAS_POLICY - public override SecurityElement ToXml() - { - SecurityElement esd = CodeAccessPermission.CreatePermissionElement( this, "System.Security.Permissions.UIPermission" ); - if (!IsUnrestricted()) - { - if (m_windowFlag != UIPermissionWindow.NoWindows) - { - esd.AddAttribute( "Window", Enum.GetName( typeof( UIPermissionWindow ), m_windowFlag ) ); - } - if (m_clipboardFlag != UIPermissionClipboard.NoClipboard) - { - esd.AddAttribute( "Clipboard", Enum.GetName( typeof( UIPermissionClipboard ), m_clipboardFlag ) ); - } - } - else - { - esd.AddAttribute( "Unrestricted", "true" ); - } - return esd; - } - - public override void FromXml(SecurityElement esd) - { - CodeAccessPermission.ValidateElement( esd, this ); - if (XMLUtil.IsUnrestricted( esd )) - { - SetUnrestricted( true ); - return; - } - - m_windowFlag = UIPermissionWindow.NoWindows; - m_clipboardFlag = UIPermissionClipboard.NoClipboard; - - String window = esd.Attribute( "Window" ); - if (window != null) - m_windowFlag = (UIPermissionWindow)Enum.Parse( typeof( UIPermissionWindow ), window ); - - String clipboard = esd.Attribute( "Clipboard" ); - if (clipboard != null) - m_clipboardFlag = (UIPermissionClipboard)Enum.Parse( typeof( UIPermissionClipboard ), clipboard ); - } -#endif // FEATURE_CAS_POLICY /// int IBuiltInPermission.GetTokenIndex() diff --git a/src/coreclr/src/mscorlib/src/System/Security/Permissions/URLIdentityPermission.cs b/src/coreclr/src/mscorlib/src/System/Security/Permissions/URLIdentityPermission.cs index 99f86ed..0883bf8 100644 --- a/src/coreclr/src/mscorlib/src/System/Security/Permissions/URLIdentityPermission.cs +++ b/src/coreclr/src/mscorlib/src/System/Security/Permissions/URLIdentityPermission.cs @@ -5,9 +5,6 @@ namespace System.Security.Permissions { using System; -#if FEATURE_CAS_POLICY - using SecurityElement = System.Security.SecurityElement; -#endif // FEATURE_CAS_POLICY using System.Security.Util; using System.IO; using System.Text; @@ -31,58 +28,8 @@ namespace System.Security.Permissions [OptionalField(VersionAdded = 2)] private bool m_unrestricted; - [OptionalField(VersionAdded = 2)] - private URLString[] m_urls; - -#if FEATURE_REMOTING - // This field will be populated only for non X-AD scenarios where we create a XML-ised string of the Permission [OptionalField(VersionAdded = 2)] - private String m_serializedPermission; - - // This field is legacy info from v1.x and is never used in v2.0 and beyond: purely for serialization purposes - private URLString m_url; - - [OnDeserialized] - private void OnDeserialized(StreamingContext ctx) - { - // v2.0 and beyond XML case - if (m_serializedPermission != null) - { - FromXml(SecurityElement.FromString(m_serializedPermission)); - m_serializedPermission = null; - } - else if (m_url != null) //v1.x case where we read the m_site value - { - m_unrestricted = false; - m_urls = new URLString[1]; - m_urls[0] = m_url; - m_url = null; - } - - } - - [OnSerializing] - private void OnSerializing(StreamingContext ctx) - { - - if ((ctx.State & ~(StreamingContextStates.Clone|StreamingContextStates.CrossAppDomain)) != 0) - { - m_serializedPermission = ToXml().ToString(); //for the v2 and beyond case - if (m_urls != null && m_urls.Length == 1) // for the v1.x case - m_url = m_urls[0]; - - } - } - [OnSerialized] - private void OnSerialized(StreamingContext ctx) - { - if ((ctx.State & ~(StreamingContextStates.Clone|StreamingContextStates.CrossAppDomain)) != 0) - { - m_serializedPermission = null; - m_url = null; - } - } -#endif // FEATURE_REMOTING + private URLString[] m_urls; //------------------------------------------------------ // @@ -323,60 +270,6 @@ namespace System.Security.Permissions return result; } -#if FEATURE_CAS_POLICY - public override void FromXml(SecurityElement esd) - { - m_unrestricted = false; - m_urls = null; - CodeAccessPermission.ValidateElement( esd, this ); - String unr = esd.Attribute( "Unrestricted" ); - if(unr != null && String.Compare(unr, "true", StringComparison.OrdinalIgnoreCase) == 0) - { - m_unrestricted = true; - return; - } - String elem = esd.Attribute( "Url" ); - List al = new List(); - if(elem != null) - al.Add(new URLString( elem, true )); - ArrayList alChildren = esd.Children; - if(alChildren != null) - { - foreach(SecurityElement child in alChildren) - { - elem = child.Attribute( "Url" ); - if(elem != null) - al.Add(new URLString( elem, true )); - } - } - if(al.Count != 0) - m_urls = al.ToArray(); - } - - public override SecurityElement ToXml() - { - SecurityElement esd = CodeAccessPermission.CreatePermissionElement( this, "System.Security.Permissions.UrlIdentityPermission" ); - if (m_unrestricted) - esd.AddAttribute( "Unrestricted", "true" ); - else if (m_urls != null) - { - if (m_urls.Length == 1) - esd.AddAttribute( "Url", m_urls[0].ToString() ); - else - { - int n; - for(n = 0; n < m_urls.Length; n++) - { - SecurityElement child = new SecurityElement("Url"); - child.AddAttribute( "Url", m_urls[n].ToString() ); - esd.AddChild(child); - } - } - } - return esd; - } -#endif // FEATURE_CAS_POLICY - /// int IBuiltInPermission.GetTokenIndex() { diff --git a/src/coreclr/src/mscorlib/src/System/Security/Permissions/ZoneIdentityPermission.cs b/src/coreclr/src/mscorlib/src/System/Security/Permissions/ZoneIdentityPermission.cs index 803bd34..9023c7e 100644 --- a/src/coreclr/src/mscorlib/src/System/Security/Permissions/ZoneIdentityPermission.cs +++ b/src/coreclr/src/mscorlib/src/System/Security/Permissions/ZoneIdentityPermission.cs @@ -8,9 +8,6 @@ namespace System.Security.Permissions { using System; -#if FEATURE_CAS_POLICY - using SecurityElement = System.Security.SecurityElement; -#endif // FEATURE_CAS_POLICY using System.Globalization; using System.Runtime.Serialization; using System.Collections; @@ -42,57 +39,6 @@ namespace System.Security.Permissions [OptionalField(VersionAdded = 2)] private uint m_zones; -#if FEATURE_REMOTING - // This field will be populated only for non X-AD scenarios where we create a XML-ised string of the Permission - [OptionalField(VersionAdded = 2)] - private String m_serializedPermission; - - // This field is legacy info from v1.x and is never used in v2.0 and beyond: purely for serialization purposes - private SecurityZone m_zone = SecurityZone.NoZone; - - [OnDeserialized] - private void OnDeserialized(StreamingContext ctx) - { - if ((ctx.State & ~(StreamingContextStates.Clone|StreamingContextStates.CrossAppDomain)) != 0) - { - // v2.0 and beyond XML case - if (m_serializedPermission != null) - { - FromXml(SecurityElement.FromString(m_serializedPermission)); - m_serializedPermission = null; - } - else //v1.x case where we read the m_zone value - { - SecurityZone = m_zone; - m_zone = SecurityZone.NoZone; - } - } - - - } - - [OnSerializing] - private void OnSerializing(StreamingContext ctx) - { - - if ((ctx.State & ~(StreamingContextStates.Clone|StreamingContextStates.CrossAppDomain)) != 0) - { - m_serializedPermission = ToXml().ToString(); //for the v2 and beyond case - m_zone = SecurityZone; - - } - } - [OnSerialized] - private void OnSerialized(StreamingContext ctx) - { - if ((ctx.State & ~(StreamingContextStates.Clone|StreamingContextStates.CrossAppDomain)) != 0) - { - m_serializedPermission = null; - m_zone = SecurityZone.NoZone; - } - } -#endif // FEATURE_REMOTING - //------------------------------------------------------ // // PUBLIC CONSTRUCTORS @@ -247,53 +193,6 @@ namespace System.Security.Permissions return new ZoneIdentityPermission(this.m_zones | that.m_zones); } -#if FEATURE_CAS_POLICY - public override SecurityElement ToXml() - { - SecurityElement esd = CodeAccessPermission.CreatePermissionElement( this, "System.Security.Permissions.ZoneIdentityPermission" ); - if (SecurityZone != SecurityZone.NoZone) - { - esd.AddAttribute( "Zone", Enum.GetName( typeof( SecurityZone ), this.SecurityZone ) ); - } - else - { - int nEnum = 0; - uint nFlag; - for(nFlag = 1; nFlag < AllZones; nFlag <<= 1) - { - if((m_zones & nFlag) != 0) - { - SecurityElement child = new SecurityElement("Zone"); - child.AddAttribute( "Zone", Enum.GetName( typeof( SecurityZone ), (SecurityZone)nEnum ) ); - esd.AddChild(child); - } - nEnum++; - } - } - return esd; - } - - public override void FromXml(SecurityElement esd) - { - m_zones = 0; - CodeAccessPermission.ValidateElement( esd, this ); - String eZone = esd.Attribute( "Zone" ); - if (eZone != null) - SecurityZone = (SecurityZone)Enum.Parse( typeof( SecurityZone ), eZone ); - if(esd.Children != null) - { - foreach(SecurityElement child in esd.Children) - { - eZone = child.Attribute( "Zone" ); - int enm = (int)Enum.Parse( typeof( SecurityZone ), eZone ); - if(enm == (int)SecurityZone.NoZone) - continue; - m_zones |= ((uint)1 << enm); - } - } - } -#endif // FEATURE_CAS_POLICY - /// int IBuiltInPermission.GetTokenIndex() { diff --git a/src/coreclr/src/mscorlib/src/System/Security/Permissions/keycontainerpermission.cs b/src/coreclr/src/mscorlib/src/System/Security/Permissions/keycontainerpermission.cs index feb5911..927097c 100644 --- a/src/coreclr/src/mscorlib/src/System/Security/Permissions/keycontainerpermission.cs +++ b/src/coreclr/src/mscorlib/src/System/Security/Permissions/keycontainerpermission.cs @@ -525,61 +525,6 @@ namespace System.Security.Permissions { return cp; } -#if FEATURE_CAS_POLICY - public override SecurityElement ToXml () { - SecurityElement securityElement = CodeAccessPermission.CreatePermissionElement(this, "System.Security.Permissions.KeyContainerPermission"); - if (!IsUnrestricted()) { - securityElement.AddAttribute("Flags", m_flags.ToString()); - if (AccessEntries.Count > 0) { - SecurityElement al = new SecurityElement("AccessList"); - foreach (KeyContainerPermissionAccessEntry accessEntry in AccessEntries) { - SecurityElement entryElem = new SecurityElement("AccessEntry"); - entryElem.AddAttribute("KeyStore", accessEntry.KeyStore); - entryElem.AddAttribute("ProviderName", accessEntry.ProviderName); - entryElem.AddAttribute("ProviderType", accessEntry.ProviderType.ToString(null, null)); - entryElem.AddAttribute("KeyContainerName", accessEntry.KeyContainerName); - entryElem.AddAttribute("KeySpec", accessEntry.KeySpec.ToString(null, null)); - entryElem.AddAttribute("Flags", accessEntry.Flags.ToString()); - al.AddChild(entryElem); - } - securityElement.AddChild(al); - } - } else - securityElement.AddAttribute("Unrestricted", "true"); - - return securityElement; - } - - public override void FromXml (SecurityElement securityElement) { - CodeAccessPermission.ValidateElement(securityElement, this); - if (XMLUtil.IsUnrestricted(securityElement)) { - m_flags = KeyContainerPermissionFlags.AllFlags; - m_accessEntries = new KeyContainerPermissionAccessEntryCollection(m_flags); - return; - } - - m_flags = KeyContainerPermissionFlags.NoFlags; - string strFlags = securityElement.Attribute("Flags"); - if (strFlags != null) { - KeyContainerPermissionFlags flags = (KeyContainerPermissionFlags) Enum.Parse(typeof(KeyContainerPermissionFlags), strFlags); - VerifyFlags(flags); - m_flags = flags; - } - m_accessEntries = new KeyContainerPermissionAccessEntryCollection(m_flags); - - if (securityElement.InternalChildren != null && securityElement.InternalChildren.Count != 0) { - IEnumerator enumerator = securityElement.Children.GetEnumerator(); - while (enumerator.MoveNext()) { - SecurityElement current = (SecurityElement) enumerator.Current; - if (current != null) { - if (String.Equals(current.Tag, "AccessList")) - AddAccessEntries(current); - } - } - } - } -#endif // FEATURE_CAS_POLICY - /// int IBuiltInPermission.GetTokenIndex () { return KeyContainerPermission.GetTokenIndex(); diff --git a/src/coreclr/src/mscorlib/src/System/Security/Policy/PolicyStatement.cs b/src/coreclr/src/mscorlib/src/System/Security/Policy/PolicyStatement.cs index 5fb61d1..9b58ece 100644 --- a/src/coreclr/src/mscorlib/src/System/Security/Policy/PolicyStatement.cs +++ b/src/coreclr/src/mscorlib/src/System/Security/Policy/PolicyStatement.cs @@ -35,14 +35,6 @@ namespace System.Security.Policy { // The PermissionSet associated with this policy internal PermissionSet m_permSet; -#if FEATURE_CAS_POLICY - // Evidence which was not verified but which was required to generate this policy statement. - // This is not serialized, since once we serialize we lose the ability to verify the evidence, - // meaning that restoring this state is meaningless. - [NonSerialized] - private List m_dependentEvidence; -#endif - // The bitfield of inheritance properties associated with this policy internal PolicyStatementAttribute m_attributes; @@ -144,20 +136,13 @@ namespace System.Security.Policy { } } } - + public PolicyStatement Copy() { - PolicyStatement copy = new PolicyStatement(m_permSet, Attributes, true); // The PolicyStatement .ctor will copy the permission set -#if FEATURE_CAS_POLICY - if (HasDependentEvidence) - { - copy.m_dependentEvidence = new List(m_dependentEvidence); - } -#endif - - return copy; + // The PolicyStatement .ctor will copy the permission set + return new PolicyStatement(m_permSet, Attributes, true); } - + public String AttributeString { get @@ -199,44 +184,6 @@ namespace System.Security.Policy { return (flag & (int)m_attributes) != 0; } -#if FEATURE_CAS_POLICY - /// - /// Gets all of the delay evaluated evidence which needs to be verified before this policy can - /// be used. - /// - internal IEnumerable DependentEvidence - { - get - { - BCLDebug.Assert(HasDependentEvidence, "HasDependentEvidence"); - return m_dependentEvidence.AsReadOnly(); - } - } - - /// - /// Determine if this policy dependent upon the evaluation of any delay evaluated evidence - /// - internal bool HasDependentEvidence - { - get { return m_dependentEvidence != null && m_dependentEvidence.Count > 0; } - } - - /// - /// Add evidence which this policy statement is depending upon being verified to be valid. - /// - internal void AddDependentEvidence(IDelayEvaluatedEvidence dependentEvidence) - { - BCLDebug.Assert(dependentEvidence != null, "dependentEvidence != null"); - - if (m_dependentEvidence == null) - { - m_dependentEvidence = new List(); - } - - m_dependentEvidence.Add(dependentEvidence); - } -#endif - /// /// Union a child policy statement into this policy statement /// @@ -249,27 +196,6 @@ namespace System.Security.Policy { throw new PolicyException(Environment.GetResourceString( "Policy_MultipleExclusive" )); } -#if FEATURE_CAS_POLICY - // If our code group generated a grant set based upon unverified evidence, or it generated a grant - // set strictly less than that of a child group based upon unverified evidence, we need to keep - // track of any unverified evidence our child group has. - if (childPolicy.HasDependentEvidence) - { - bool childEvidenceNeedsVerification = m_permSet.IsSubsetOf(childPolicy.GetPermissionSetNoCopy()) && - !childPolicy.GetPermissionSetNoCopy().IsSubsetOf(m_permSet); - - if (HasDependentEvidence || childEvidenceNeedsVerification) - { - if (m_dependentEvidence == null) - { - m_dependentEvidence = new List(); - } - - m_dependentEvidence.AddRange(childPolicy.DependentEvidence); - } - } -#endif - // We need to merge together our grant set and attributes. The result of this merge is // dependent upon if we're merging a child marked exclusive or not. If the child is not // exclusive, we need to union in its grant set and or in its attributes. However, if the child @@ -287,226 +213,6 @@ namespace System.Security.Policy { } } -#if FEATURE_CAS_POLICY - - public SecurityElement ToXml() - { - return ToXml( null ); - } - - public void FromXml( SecurityElement et ) - { - FromXml( et, null ); - } - - public SecurityElement ToXml( PolicyLevel level ) - { - return ToXml( level, false ); - } - - internal SecurityElement ToXml( PolicyLevel level, bool useInternal ) - { - SecurityElement e = new SecurityElement( "PolicyStatement" ); - e.AddAttribute( "version", "1" ); - if (m_attributes != PolicyStatementAttribute.Nothing) - e.AddAttribute( "Attributes", XMLUtil.BitFieldEnumToString( typeof( PolicyStatementAttribute ), m_attributes ) ); - - lock (this) - { - if (m_permSet != null) - { - if (m_permSet is NamedPermissionSet) - { - // If the named permission set exists in the parent level of this - // policy struct, then just save the name of the permission set. - // Otherwise, serialize it like normal. - - NamedPermissionSet namedPermSet = (NamedPermissionSet)m_permSet; - if (level != null && level.GetNamedPermissionSet( namedPermSet.Name ) != null) - { - e.AddAttribute( "PermissionSetName", namedPermSet.Name ); - } - else - { - if (useInternal) - e.AddChild( namedPermSet.InternalToXml() ); - else - e.AddChild( namedPermSet.ToXml() ); - } - } - else - { - if (useInternal) - e.AddChild( m_permSet.InternalToXml() ); - else - e.AddChild( m_permSet.ToXml() ); - } - } - } - - return e; - } - - [System.Security.SecuritySafeCritical] // auto-generated - public void FromXml( SecurityElement et, PolicyLevel level ) - { - FromXml( et, level, false ); - } - - [System.Security.SecurityCritical] // auto-generated - internal void FromXml( SecurityElement et, PolicyLevel level, bool allowInternalOnly ) - { - if (et == null) - throw new ArgumentNullException( nameof(et) ); - - if (!et.Tag.Equals( "PolicyStatement" )) - throw new ArgumentException( String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "Argument_InvalidXMLElement" ), nameof(PolicyStatement), this.GetType().FullName ) ); - Contract.EndContractBlock(); - - m_attributes = (PolicyStatementAttribute) 0; - - String strAttributes = et.Attribute( "Attributes" ); - - if (strAttributes != null) - m_attributes = (PolicyStatementAttribute)Enum.Parse( typeof( PolicyStatementAttribute ), strAttributes ); - - lock (this) - { - m_permSet = null; - - if (level != null) - { - String permSetName = et.Attribute( "PermissionSetName" ); - - if (permSetName != null) - { - m_permSet = level.GetNamedPermissionSetInternal( permSetName ); - - if (m_permSet == null) - m_permSet = new PermissionSet( PermissionState.None ); - } - } - - - if (m_permSet == null) - { - // There is no provided level, it is not a named permission set, or - // the named permission set doesn't exist in the provided level, - // so just create the class through reflection and decode normally. - - SecurityElement e = et.SearchForChildByTag( "PermissionSet" ); - - if (e != null) - { - String className = e.Attribute( "class" ); - - if (className != null && (className.Equals( "NamedPermissionSet" ) || - className.Equals( "System.Security.NamedPermissionSet" ))) - m_permSet = new NamedPermissionSet( "DefaultName", PermissionState.None ); - else - m_permSet = new PermissionSet( PermissionState.None ); - - try - { - m_permSet.FromXml( e, allowInternalOnly, true ); - } - catch - { - // ignore any exceptions from the decode process. - // Note: we go ahead and use the permission set anyway. This should be safe since - // the decode process should never give permission beyond what a proper decode would have - // given. - } - } - else - { - throw new ArgumentException( Environment.GetResourceString( "Argument_InvalidXML" ) ); - } - } - - if (m_permSet == null) - m_permSet = new PermissionSet( PermissionState.None ); - } - } - - - [System.Security.SecurityCritical] // auto-generated - internal void FromXml( SecurityDocument doc, int position, PolicyLevel level, bool allowInternalOnly ) - { - if (doc == null) - throw new ArgumentNullException( nameof(doc) ); - Contract.EndContractBlock(); - - if (!doc.GetTagForElement( position ).Equals( "PolicyStatement" )) - throw new ArgumentException( String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "Argument_InvalidXMLElement" ), nameof(PolicyStatement), this.GetType().FullName ) ); - - m_attributes = (PolicyStatementAttribute) 0; - - String strAttributes = doc.GetAttributeForElement( position, "Attributes" ); - - if (strAttributes != null) - m_attributes = (PolicyStatementAttribute)Enum.Parse( typeof( PolicyStatementAttribute ), strAttributes ); - - lock (this) - { - m_permSet = null; - - if (level != null) - { - String permSetName = doc.GetAttributeForElement( position, "PermissionSetName" ); - - if (permSetName != null) - { - m_permSet = level.GetNamedPermissionSetInternal( permSetName ); - - if (m_permSet == null) - m_permSet = new PermissionSet( PermissionState.None ); - } - } - - - if (m_permSet == null) - { - // There is no provided level, it is not a named permission set, or - // the named permission set doesn't exist in the provided level, - // so just create the class through reflection and decode normally. - - ArrayList childPositions = doc.GetChildrenPositionForElement( position ); - int positionPermissionSet = -1; - - for (int i = 0; i < childPositions.Count; ++i) - { - if (doc.GetTagForElement( (int)childPositions[i] ).Equals( "PermissionSet" )) - { - positionPermissionSet = (int)childPositions[i]; - } - } - - if (positionPermissionSet != -1) - { - String className = doc.GetAttributeForElement( positionPermissionSet, "class" ); - - if (className != null && (className.Equals( "NamedPermissionSet" ) || - className.Equals( "System.Security.NamedPermissionSet" ))) - m_permSet = new NamedPermissionSet( "DefaultName", PermissionState.None ); - else - m_permSet = new PermissionSet( PermissionState.None ); - - m_permSet.FromXml( doc, positionPermissionSet, allowInternalOnly ); - } - else - { - throw new ArgumentException( Environment.GetResourceString( "Argument_InvalidXML" ) ); - } - } - - if (m_permSet == null) - m_permSet = new PermissionSet( PermissionState.None ); - } - } -#endif // FEATURE_CAS_POLICY - - [System.Runtime.InteropServices.ComVisible(false)] public override bool Equals( Object obj ) { diff --git a/src/coreclr/src/mscorlib/src/System/Security/Policy/Site.cs b/src/coreclr/src/mscorlib/src/System/Security/Policy/Site.cs index 9c954d2..937bb27 100644 --- a/src/coreclr/src/mscorlib/src/System/Security/Policy/Site.cs +++ b/src/coreclr/src/mscorlib/src/System/Security/Policy/Site.cs @@ -94,30 +94,6 @@ namespace System.Security.Policy return Clone(); } -#if FEATURE_CAS_POLICY - internal SecurityElement ToXml() - { - SecurityElement elem = new SecurityElement( "System.Security.Policy.Site" ); - // If you hit this assert then most likely you are trying to change the name of this class. - // This is ok as long as you change the hard coded string above and change the assert below. - Contract.Assert( this.GetType().FullName.Equals( "System.Security.Policy.Site" ), "Class name changed!" ); - - elem.AddAttribute( "version", "1" ); - - if(m_name != null) - elem.AddChild( new SecurityElement( "Name", m_name.ToString() ) ); - - return elem; - } -#endif // FEATURE_CAS_POLICY - -#if FEATURE_CAS_POLICY - public override String ToString() - { - return ToXml().ToString(); - } -#endif // FEATURE_CAS_POLICY - // INormalizeForIsolatedStorage is not implemented for startup perf // equivalent to INormalizeForIsolatedStorage.Normalize() internal Object Normalize() diff --git a/src/coreclr/src/mscorlib/src/System/Security/Policy/StrongName.cs b/src/coreclr/src/mscorlib/src/System/Security/Policy/StrongName.cs index 0cdf85f..613e297 100644 --- a/src/coreclr/src/mscorlib/src/System/Security/Policy/StrongName.cs +++ b/src/coreclr/src/mscorlib/src/System/Security/Policy/StrongName.cs @@ -92,11 +92,7 @@ namespace System.Security.Policy { [System.Security.SecurityCritical] // auto-generated get { -#if FEATURE_CAS_POLICY - return m_assembly != null ? m_assembly.IsStrongNameVerified : true; -#else // !FEATURE_CAS_POLICY return true; -#endif // FEATURE_CAS_POLICY } } @@ -133,52 +129,6 @@ namespace System.Security.Policy { return Clone(); } -#if FEATURE_CAS_POLICY - internal SecurityElement ToXml() - { - SecurityElement root = new SecurityElement( "StrongName" ); - root.AddAttribute( "version", "1" ); - - if (m_publicKeyBlob != null) - root.AddAttribute( "Key", System.Security.Util.Hex.EncodeHexString( m_publicKeyBlob.PublicKey ) ); - - if (m_name != null) - root.AddAttribute( "Name", m_name ); - - if (m_version != null) - root.AddAttribute( "Version", m_version.ToString() ); - - return root; - } - - internal void FromXml (SecurityElement element) - { - if (element == null) - throw new ArgumentNullException(nameof(element)); - if (String.Compare(element.Tag, "StrongName", StringComparison.Ordinal) != 0) - throw new ArgumentException(Environment.GetResourceString("Argument_InvalidXML")); - Contract.EndContractBlock(); - - m_publicKeyBlob = null; - m_version = null; - - string key = element.Attribute("Key"); - if (key != null) - m_publicKeyBlob = new StrongNamePublicKeyBlob(System.Security.Util.Hex.DecodeHexString(key)); - - m_name = element.Attribute("Name"); - - string version = element.Attribute("Version"); - if (version != null) - m_version = new Version(version); - } - - public override String ToString() - { - return ToXml().ToString(); - } -#endif // FEATURE_CAS_POLICY - public override bool Equals( Object o ) { StrongName that = (o as StrongName); diff --git a/src/coreclr/src/mscorlib/src/System/Security/Policy/URL.cs b/src/coreclr/src/mscorlib/src/System/Security/Policy/URL.cs index dba8ca8..baa5b1c 100644 --- a/src/coreclr/src/mscorlib/src/System/Security/Policy/URL.cs +++ b/src/coreclr/src/mscorlib/src/System/Security/Policy/URL.cs @@ -87,28 +87,6 @@ namespace System.Security.Policy { return Clone(); } -#if FEATURE_CAS_POLICY - internal SecurityElement ToXml() - { - SecurityElement root = new SecurityElement( "System.Security.Policy.Url" ); - // If you hit this assert then most likely you are trying to change the name of this class. - // This is ok as long as you change the hard coded string above and change the assert below. - Contract.Assert( this.GetType().FullName.Equals( "System.Security.Policy.Url" ), "Class name changed!" ); - - root.AddAttribute( "version", "1" ); - - if (m_url != null) - root.AddChild( new SecurityElement( "Url", m_url.ToString() ) ); - - return root; - } - - public override String ToString() - { - return ToXml().ToString(); - } -#endif // FEATURE_CAS_POLICY - // INormalizeForIsolatedStorage is not implemented for startup perf // equivalent to INormalizeForIsolatedStorage.Normalize() internal Object Normalize() diff --git a/src/coreclr/src/mscorlib/src/System/Security/Policy/Zone.cs b/src/coreclr/src/mscorlib/src/System/Security/Policy/Zone.cs index 267c059..c7c5346 100644 --- a/src/coreclr/src/mscorlib/src/System/Security/Policy/Zone.cs +++ b/src/coreclr/src/mscorlib/src/System/Security/Policy/Zone.cs @@ -9,7 +9,8 @@ // Zone is an IIdentity representing Internet/Intranet/MyComputer etc. // -namespace System.Security.Policy { +namespace System.Security.Policy +{ using System.Security.Util; using ZoneIdentityPermission = System.Security.Permissions.ZoneIdentityPermission; using System.Runtime.CompilerServices; @@ -22,10 +23,6 @@ namespace System.Security.Policy { [System.Runtime.InteropServices.ComVisible(true)] public sealed class Zone : EvidenceBase, IIdentityPermissionFactory { -#if FEATURE_CAS_POLICY - [OptionalField(VersionAdded = 2)] - private String m_url; -#endif // FEATURE_CAS_POLICY private SecurityZone m_zone; private static readonly String[] s_names = @@ -43,35 +40,9 @@ namespace System.Security.Policy { private Zone(Zone zone) { Contract.Assert(zone != null); - -#if FEATURE_CAS_POLICY - m_url = zone.m_url; -#endif // FEATURE_CAS_POLICY m_zone = zone.m_zone; } -#if FEATURE_CAS_POLICY - private Zone(String url) - { - m_url = url; - m_zone = SecurityZone.NoZone; - } - - public static Zone CreateFromUrl( String url ) - { - if (url == null) - throw new ArgumentNullException( nameof(url) ); - Contract.EndContractBlock(); - - return new Zone( url ); - } - - [System.Security.SecurityCritical] // auto-generated - [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] - [SuppressUnmanagedCodeSecurity] - private extern static SecurityZone _CreateFromUrl( String url ); -#endif // FEATURE_CAS_POLICY - public IPermission CreateIdentityPermission( Evidence evidence ) { return new ZoneIdentityPermission( SecurityZone ); @@ -82,11 +53,6 @@ namespace System.Security.Policy { [System.Security.SecuritySafeCritical] // auto-generated get { -#if FEATURE_CAS_POLICY - if (m_url != null) - m_zone = _CreateFromUrl( m_url ); -#endif // FEATURE_CAS_POLICY - return m_zone; } } @@ -117,30 +83,6 @@ namespace System.Security.Policy { return Clone(); } -#if FEATURE_CAS_POLICY - internal SecurityElement ToXml() - { - SecurityElement elem = new SecurityElement( "System.Security.Policy.Zone" ); - // If you hit this assert then most likely you are trying to change the name of this class. - // This is ok as long as you change the hard coded string above and change the assert below. - Contract.Assert( this.GetType().FullName.Equals( "System.Security.Policy.Zone" ), "Class name changed!" ); - - elem.AddAttribute( "version", "1" ); - if (SecurityZone != SecurityZone.NoZone) - elem.AddChild( new SecurityElement( "Zone", s_names[(int)SecurityZone] ) ); - else - elem.AddChild( new SecurityElement( "Zone", s_names[s_names.Length-1] ) ); - return elem; - } -#endif // FEATURE_CAS_POLICY - -#if FEATURE_CAS_POLICY - public override String ToString() - { - return ToXml().ToString(); - } -#endif // FEATURE_CAS_POLICY - // INormalizeForIsolatedStorage is not implemented for startup perf // equivalent to INormalizeForIsolatedStorage.Normalize() internal Object Normalize() diff --git a/src/coreclr/src/mscorlib/src/System/Security/SecurityElement.cs b/src/coreclr/src/mscorlib/src/System/Security/SecurityElement.cs index 667bf7f..5fe7b65 100644 --- a/src/coreclr/src/mscorlib/src/System/Security/SecurityElement.cs +++ b/src/coreclr/src/mscorlib/src/System/Security/SecurityElement.cs @@ -93,19 +93,6 @@ namespace System.Security return ((SecurityElement)this).Attribute( attributeName ); } -////////////// - -#if FEATURE_CAS_POLICY - public static SecurityElement FromString( String xml ) - { - if (xml == null) - throw new ArgumentNullException( nameof(xml) ); - Contract.EndContractBlock(); - - return new Parser( xml ).GetTopElement(); - } -#endif // FEATURE_CAS_POLICY - public SecurityElement( String tag ) { if (tag == null) @@ -831,38 +818,6 @@ namespace System.Security return null; } -#if FEATURE_CAS_POLICY - internal IPermission ToPermission(bool ignoreTypeLoadFailures) - { - IPermission ip = XMLUtil.CreatePermission( this, PermissionState.None, ignoreTypeLoadFailures ); - if (ip == null) - return null; - ip.FromXml(this); - - // Get the permission token here to ensure that the token - // type is updated appropriately now that we've loaded the type. - PermissionToken token = PermissionToken.GetToken( ip ); - Contract.Assert((token.m_type & PermissionTokenType.DontKnow) == 0, "Token type not properly assigned"); - - return ip; - } - - [System.Security.SecurityCritical] // auto-generated - internal Object ToSecurityObject() - { - switch (m_strTag) - { - case "PermissionSet": - PermissionSet pset = new PermissionSet(PermissionState.None); - pset.FromXml(this); - return pset; - - default: - return ToPermission(false); - } - } -#endif // FEATURE_CAS_POLICY - internal String SearchForTextOfLocalName(String strLocalName) { // Search on each child in order and each diff --git a/src/coreclr/src/mscorlib/src/System/Security/SecurityException.cs b/src/coreclr/src/mscorlib/src/System/Security/SecurityException.cs index 4de9d65..d071201 100644 --- a/src/coreclr/src/mscorlib/src/System/Security/SecurityException.cs +++ b/src/coreclr/src/mscorlib/src/System/Security/SecurityException.cs @@ -34,36 +34,6 @@ namespace System.Security [Serializable] public class SecurityException : SystemException { -#if FEATURE_CAS_POLICY - private String m_debugString; // NOTE: If you change the name of this field, you'll have to update SOS as well! - private SecurityAction m_action; - [NonSerialized] private Type m_typeOfPermissionThatFailed; - private String m_permissionThatFailed; - private String m_demanded; - private String m_granted; - private String m_refused; - private String m_denied; - private String m_permitOnly; - private AssemblyName m_assemblyName; - private byte[] m_serializedMethodInfo; - private String m_strMethodInfo; - private SecurityZone m_zone; - private String m_url; - - private const String ActionName = "Action"; - private const String FirstPermissionThatFailedName = "FirstPermissionThatFailed"; - private const String DemandedName = "Demanded"; - private const String GrantedSetName = "GrantedSet"; - private const String RefusedSetName = "RefusedSet"; - private const String DeniedName = "Denied"; - private const String PermitOnlyName = "PermitOnly"; - private const String Assembly_Name = "Assembly"; - private const String MethodName_Serialized = "Method"; - private const String MethodName_String = "Method_String"; - private const String ZoneName = "Zone"; - private const String UrlName = "Url"; -#endif // #if FEATURE_CAS_POLICY - [System.Security.SecuritySafeCritical] // auto-generated internal static string GetResString(string sResourceName) { @@ -76,87 +46,9 @@ namespace System.Security internal static Exception MakeSecurityException(AssemblyName asmName, Evidence asmEvidence, PermissionSet granted, PermissionSet refused, RuntimeMethodHandleInternal rmh, SecurityAction action, Object demand, IPermission permThatFailed) #pragma warning restore 618 { -#if FEATURE_CAS_POLICY - // See if we need to throw a HostProtectionException instead - HostProtectionPermission hostProtectionPerm = permThatFailed as HostProtectionPermission; - if(hostProtectionPerm != null) - return new HostProtectionException(GetResString("HostProtection_HostProtection"), HostProtectionPermission.protectedResources, hostProtectionPerm.Resources); - - // Produce relevant strings - String message = ""; - MethodInfo method = null; - try - { - if(granted == null && refused == null && demand == null) - { - message = GetResString("Security_NoAPTCA"); - } - else - { - if(demand != null && demand is IPermission) - message = String.Format(CultureInfo.InvariantCulture, GetResString("Security_Generic"), demand.GetType().AssemblyQualifiedName ); - else if (permThatFailed != null) - message = String.Format(CultureInfo.InvariantCulture, GetResString("Security_Generic"), permThatFailed.GetType().AssemblyQualifiedName); - else - message = GetResString("Security_GenericNoType"); - } - - method = SecurityRuntime.GetMethodInfo(rmh); - } - catch(Exception e) - { - // Environment.GetResourceString will throw if we are ReadyForAbort (thread abort). (We shouldn't do a Contract.Assert in this case or it will lock up the thread.) - if(e is System.Threading.ThreadAbortException) - throw; - } - -/* catch(System.Threading.ThreadAbortException) - { - // Environment.GetResourceString will throw if we are ReadyForAbort (thread abort). (We shouldn't do a BCLDebug.Assert in this case or it will lock up the thread.) - throw; - } - catch - { - } -*/ - // make the exception object - return new SecurityException(message, asmName, granted, refused, method, action, demand, permThatFailed, asmEvidence); -#else return new SecurityException(GetResString("Arg_SecurityException")); -#endif - } -#if FEATURE_CAS_POLICY - private static byte[] ObjectToByteArray(Object obj) - { - if(obj == null) - return null; - MemoryStream stream = new MemoryStream(); - BinaryFormatter formatter = new BinaryFormatter(); - try { - formatter.Serialize(stream, obj); - byte[] array = stream.ToArray(); - return array; - } catch (NotSupportedException) { - // Serialization of certain methods is not supported (namely - // global methods, since they have no representation outside of - // a module scope). - return null; - } - } - - private static Object ByteArrayToObject(byte[] array) - { - if(array == null || array.Length == 0) - return null; - MemoryStream stream = new MemoryStream(array); - BinaryFormatter formatter = new BinaryFormatter(); - Object obj = formatter.Deserialize(stream); - return obj; - } -#endif // FEATURE_CAS_POLICY - public SecurityException() : base(GetResString("Arg_SecurityException")) { @@ -170,427 +62,12 @@ namespace System.Security SetErrorCode(System.__HResults.COR_E_SECURITY); } -#if FEATURE_CAS_POLICY - [System.Security.SecuritySafeCritical] // auto-generated - public SecurityException(String message, Type type ) - : base(message) - { - PermissionSet.s_fullTrust.Assert(); - SetErrorCode(System.__HResults.COR_E_SECURITY); - m_typeOfPermissionThatFailed = type; - } - - // *** Don't use this constructor internally *** - [System.Security.SecuritySafeCritical] // auto-generated - public SecurityException(String message, Type type, String state ) - : base(message) - { - PermissionSet.s_fullTrust.Assert(); - SetErrorCode(System.__HResults.COR_E_SECURITY); - m_typeOfPermissionThatFailed = type; - m_demanded = state; - } -#endif //FEATURE_CAS_POLICY - public SecurityException(String message, Exception inner) : base(message, inner) { SetErrorCode(System.__HResults.COR_E_SECURITY); } -#if FEATURE_CAS_POLICY - // *** Don't use this constructor internally *** - [System.Security.SecurityCritical] // auto-generated - internal SecurityException( PermissionSet grantedSetObj, PermissionSet refusedSetObj ) - : base(GetResString("Arg_SecurityException")) - { - PermissionSet.s_fullTrust.Assert(); - SetErrorCode(System.__HResults.COR_E_SECURITY); - if (grantedSetObj != null) - m_granted = grantedSetObj.ToXml().ToString(); - if (refusedSetObj != null) - m_refused = refusedSetObj.ToXml().ToString(); - } - - // *** Don't use this constructor internally *** - [System.Security.SecurityCritical] // auto-generated - internal SecurityException( String message, PermissionSet grantedSetObj, PermissionSet refusedSetObj ) - : base(message) - { - PermissionSet.s_fullTrust.Assert(); - SetErrorCode(System.__HResults.COR_E_SECURITY); - if (grantedSetObj != null) - m_granted = grantedSetObj.ToXml().ToString(); - if (refusedSetObj != null) - m_refused = refusedSetObj.ToXml().ToString(); - } - - [System.Security.SecuritySafeCritical] // auto-generated - protected SecurityException(SerializationInfo info, StreamingContext context) : base (info, context) - { - if (info==null) - throw new ArgumentNullException(nameof(info)); - Contract.EndContractBlock(); - - try - { - m_action = (SecurityAction)info.GetValue(ActionName, typeof(SecurityAction)); - m_permissionThatFailed = (String)info.GetValueNoThrow(FirstPermissionThatFailedName, typeof(String)); - m_demanded = (String)info.GetValueNoThrow(DemandedName, typeof(String)); - m_granted = (String)info.GetValueNoThrow(GrantedSetName, typeof(String)); - m_refused = (String)info.GetValueNoThrow(RefusedSetName, typeof(String)); - m_denied = (String)info.GetValueNoThrow(DeniedName, typeof(String)); - m_permitOnly = (String)info.GetValueNoThrow(PermitOnlyName, typeof(String)); - m_assemblyName = (AssemblyName)info.GetValueNoThrow(Assembly_Name, typeof(AssemblyName)); - m_serializedMethodInfo = (byte[])info.GetValueNoThrow(MethodName_Serialized, typeof(byte[])); - m_strMethodInfo = (String)info.GetValueNoThrow(MethodName_String, typeof(String)); - m_zone = (SecurityZone)info.GetValue(ZoneName, typeof(SecurityZone)); - m_url = (String)info.GetValueNoThrow(UrlName, typeof(String)); - } - catch - { - m_action = 0; - m_permissionThatFailed = ""; - m_demanded = ""; - m_granted = ""; - m_refused = ""; - m_denied = ""; - m_permitOnly = ""; - m_assemblyName = null; - m_serializedMethodInfo = null; - m_strMethodInfo = null; - m_zone = SecurityZone.NoZone; - m_url = ""; - } - } - - // ------------------------------------------ - // | For failures due to insufficient grant | - // ------------------------------------------ - [System.Security.SecuritySafeCritical] // auto-generated - public SecurityException(string message, AssemblyName assemblyName, PermissionSet grant, PermissionSet refused, MethodInfo method, SecurityAction action, Object demanded, IPermission permThatFailed, Evidence evidence) - : base(message) - { - PermissionSet.s_fullTrust.Assert(); - SetErrorCode(System.__HResults.COR_E_SECURITY); - Action = action; - if(permThatFailed != null) - m_typeOfPermissionThatFailed = permThatFailed.GetType(); - FirstPermissionThatFailed = permThatFailed; - Demanded = demanded; - m_granted = (grant == null ? "" : grant.ToXml().ToString()); - m_refused = (refused == null ? "" : refused.ToXml().ToString()); - m_denied = ""; - m_permitOnly = ""; - m_assemblyName = assemblyName; - Method = method; - m_url = ""; - m_zone = SecurityZone.NoZone; - if(evidence != null) - { - Url url = evidence.GetHostEvidence(); - if(url != null) - m_url = url.GetURLString().ToString(); - Zone zone = evidence.GetHostEvidence(); - if(zone != null) - m_zone = zone.SecurityZone; - } - m_debugString = this.ToString(true, false); - } - - // ------------------------------------------ - // | For failures due to deny or PermitOnly | - // ------------------------------------------ - [System.Security.SecuritySafeCritical] // auto-generated - public SecurityException(string message, Object deny, Object permitOnly, MethodInfo method, Object demanded, IPermission permThatFailed) - : base(message) - { - PermissionSet.s_fullTrust.Assert(); - SetErrorCode(System.__HResults.COR_E_SECURITY); - Action = SecurityAction.Demand; - if(permThatFailed != null) - m_typeOfPermissionThatFailed = permThatFailed.GetType(); - FirstPermissionThatFailed = permThatFailed; - Demanded = demanded; - m_granted = ""; - m_refused = ""; - DenySetInstance = deny; - PermitOnlySetInstance = permitOnly; - m_assemblyName = null; - Method = method; - m_zone = SecurityZone.NoZone; - m_url = ""; - m_debugString = this.ToString(true, false); - } - - - - - - - - - - - - [System.Runtime.InteropServices.ComVisible(false)] - public SecurityAction Action - { - get - { - return m_action; - } - - set - { - m_action = value; - } - } - - public Type PermissionType - { - [System.Security.SecuritySafeCritical] // auto-generated - get - { - if(m_typeOfPermissionThatFailed == null) - { - Object ob = XMLUtil.XmlStringToSecurityObject(m_permissionThatFailed); - if(ob == null) - ob = XMLUtil.XmlStringToSecurityObject(m_demanded); - if(ob != null) - m_typeOfPermissionThatFailed = ob.GetType(); - } - return m_typeOfPermissionThatFailed; - } - - set - { - m_typeOfPermissionThatFailed = value; - } - } - - public IPermission FirstPermissionThatFailed - { - [System.Security.SecuritySafeCritical] // auto-generated - [SecurityPermissionAttribute( SecurityAction.Demand, Flags = SecurityPermissionFlag.ControlEvidence | SecurityPermissionFlag.ControlPolicy)] - get - { - return (IPermission)XMLUtil.XmlStringToSecurityObject(m_permissionThatFailed); - } - - set - { - m_permissionThatFailed = XMLUtil.SecurityObjectToXmlString(value); - } - } - - public String PermissionState - { - [System.Security.SecuritySafeCritical] // auto-generated - [SecurityPermissionAttribute( SecurityAction.Demand, Flags = SecurityPermissionFlag.ControlEvidence | SecurityPermissionFlag.ControlPolicy)] - get - { - return m_demanded; - } - - set - { - m_demanded = value; - } - } - - [System.Runtime.InteropServices.ComVisible(false)] - public Object Demanded - { - [System.Security.SecuritySafeCritical] // auto-generated - [SecurityPermissionAttribute( SecurityAction.Demand, Flags = SecurityPermissionFlag.ControlEvidence | SecurityPermissionFlag.ControlPolicy)] - get - { - return XMLUtil.XmlStringToSecurityObject(m_demanded); - } - - set - { - m_demanded = XMLUtil.SecurityObjectToXmlString(value); - } - } - - public String GrantedSet - { - [System.Security.SecuritySafeCritical] // auto-generated - [SecurityPermissionAttribute( SecurityAction.Demand, Flags = SecurityPermissionFlag.ControlEvidence | SecurityPermissionFlag.ControlPolicy)] - get - { - return m_granted; - } - - set - { - m_granted = value; - } - } - - public String RefusedSet - { - [System.Security.SecuritySafeCritical] // auto-generated - [SecurityPermissionAttribute( SecurityAction.Demand, Flags = SecurityPermissionFlag.ControlEvidence | SecurityPermissionFlag.ControlPolicy)] - get - { - return m_refused; - } - - set - { - m_refused = value; - } - } - - [System.Runtime.InteropServices.ComVisible(false)] - public Object DenySetInstance - { - [System.Security.SecuritySafeCritical] // auto-generated - [SecurityPermissionAttribute( SecurityAction.Demand, Flags = SecurityPermissionFlag.ControlEvidence | SecurityPermissionFlag.ControlPolicy)] - get - { - return XMLUtil.XmlStringToSecurityObject(m_denied); - } - - set - { - m_denied = XMLUtil.SecurityObjectToXmlString(value); - } - } - - [System.Runtime.InteropServices.ComVisible(false)] - public Object PermitOnlySetInstance - { - [System.Security.SecuritySafeCritical] // auto-generated - [SecurityPermissionAttribute( SecurityAction.Demand, Flags = SecurityPermissionFlag.ControlEvidence | SecurityPermissionFlag.ControlPolicy)] - get - { - return XMLUtil.XmlStringToSecurityObject(m_permitOnly); - } - - set - { - m_permitOnly = XMLUtil.SecurityObjectToXmlString(value); - } - } - - [System.Runtime.InteropServices.ComVisible(false)] - public AssemblyName FailedAssemblyInfo - { - [System.Security.SecuritySafeCritical] // auto-generated - [SecurityPermissionAttribute( SecurityAction.Demand, Flags = SecurityPermissionFlag.ControlEvidence | SecurityPermissionFlag.ControlPolicy)] - get - { - return m_assemblyName; - } - - set - { - m_assemblyName = value; - } - } - - private MethodInfo getMethod() - { - return (MethodInfo)ByteArrayToObject(m_serializedMethodInfo); - } - - [System.Runtime.InteropServices.ComVisible(false)] - public MethodInfo Method - { - [System.Security.SecuritySafeCritical] // auto-generated - [SecurityPermissionAttribute( SecurityAction.Demand, Flags = SecurityPermissionFlag.ControlEvidence | SecurityPermissionFlag.ControlPolicy)] - get - { - return getMethod(); - } - - set - { - RuntimeMethodInfo m = value as RuntimeMethodInfo; - m_serializedMethodInfo = ObjectToByteArray(m); - if (m != null) - { - m_strMethodInfo = m.ToString(); - } - } - } - - public SecurityZone Zone - { - get - { - return m_zone; - } - - set - { - m_zone = value; - } - } - - public String Url - { - [System.Security.SecuritySafeCritical] // auto-generated - [SecurityPermissionAttribute( SecurityAction.Demand, Flags = SecurityPermissionFlag.ControlEvidence | SecurityPermissionFlag.ControlPolicy)] - get - { - return m_url; - } - - set - { - m_url = value; - } - } - - private void ToStringHelper(StringBuilder sb, String resourceString, Object attr) - { - if (attr == null) - return; - String attrString = attr as String; - if (attrString == null) - attrString = attr.ToString(); - if (attrString.Length == 0) - return; - sb.Append(Environment.NewLine); - sb.Append(GetResString(resourceString)); - sb.Append(Environment.NewLine); - sb.Append(attrString); - } - - [System.Security.SecurityCritical] // auto-generated - private String ToString(bool includeSensitiveInfo, bool includeBaseInfo) - { - PermissionSet.s_fullTrust.Assert(); - StringBuilder sb = new StringBuilder(); - - if(includeBaseInfo) - sb.Append(base.ToString()); - if(Action > 0) - ToStringHelper(sb, "Security_Action", Action); - ToStringHelper(sb, "Security_TypeFirstPermThatFailed", PermissionType); - if(includeSensitiveInfo) - { - ToStringHelper(sb, "Security_FirstPermThatFailed", m_permissionThatFailed); - ToStringHelper(sb, "Security_Demanded", m_demanded); - ToStringHelper(sb, "Security_GrantedSet", m_granted); - ToStringHelper(sb, "Security_RefusedSet", m_refused); - ToStringHelper(sb, "Security_Denied", m_denied); - ToStringHelper(sb, "Security_PermitOnly", m_permitOnly); - ToStringHelper(sb, "Security_Assembly", m_assemblyName); - ToStringHelper(sb, "Security_Method", m_strMethodInfo); - } - if(m_zone != SecurityZone.NoZone) - ToStringHelper(sb, "Security_Zone", m_zone); - if(includeSensitiveInfo) - ToStringHelper(sb, "Security_Url", m_url); - return sb.ToString(); - } -#else // FEATURE_CAS_POLICY internal SecurityException(PermissionSet grantedSetObj, PermissionSet refusedSetObj) : this(){} #pragma warning disable 618 @@ -614,8 +91,6 @@ namespace System.Security return base.ToString(); } -#endif // FEATURE_CAS_POLICY - [System.Security.SecurityCritical] // auto-generated private bool CanAccessSensitiveInfo() { @@ -632,13 +107,7 @@ namespace System.Security } return retVal; } -#if FEATURE_CAS_POLICY - [System.Security.SecuritySafeCritical] // auto-generated - public override String ToString() - { - return ToString(CanAccessSensitiveInfo(), true); - } -#endif //FEATURE_CAS_POLICY + [System.Security.SecurityCritical] // auto-generated_required public override void GetObjectData(SerializationInfo info, StreamingContext context) { @@ -647,24 +116,8 @@ namespace System.Security Contract.EndContractBlock(); base.GetObjectData(info, context); -#if FEATURE_CAS_POLICY - - info.AddValue(ActionName, m_action, typeof(SecurityAction)); - info.AddValue(FirstPermissionThatFailedName, m_permissionThatFailed, typeof(String)); - info.AddValue(DemandedName, m_demanded, typeof(String)); - info.AddValue(GrantedSetName, m_granted, typeof(String)); - info.AddValue(RefusedSetName, m_refused, typeof(String)); - info.AddValue(DeniedName, m_denied, typeof(String)); - info.AddValue(PermitOnlyName, m_permitOnly, typeof(String)); - info.AddValue(Assembly_Name, m_assemblyName, typeof(AssemblyName)); - info.AddValue(MethodName_Serialized, m_serializedMethodInfo, typeof(byte[])); - info.AddValue(MethodName_String, m_strMethodInfo, typeof(String)); - info.AddValue(ZoneName, m_zone, typeof(SecurityZone)); - info.AddValue(UrlName, m_url, typeof(String)); -#endif // FEATURE_CAS_POLICY } -#if !FEATURE_CAS_POLICY // Stubs for surface area compatibility only public SecurityException(String message, Type type) : base(message) @@ -691,6 +144,5 @@ namespace System.Security public object PermitOnlySetInstance { get; set; } public string RefusedSet { get; set; } public string Url { get; set; } -#endif // !FEATURE_CAS_POLICY } } diff --git a/src/coreclr/src/mscorlib/src/System/Security/SecurityRuntime.cs b/src/coreclr/src/mscorlib/src/System/Security/SecurityRuntime.cs index 9d776af..7b62549 100644 --- a/src/coreclr/src/mscorlib/src/System/Security/SecurityRuntime.cs +++ b/src/coreclr/src/mscorlib/src/System/Security/SecurityRuntime.cs @@ -4,7 +4,8 @@ // -namespace System.Security { +namespace System.Security +{ using System; using System.Globalization; using System.Threading; @@ -122,176 +123,49 @@ namespace System.Security { // // API for PermissionSets // - + [System.Security.SecurityCritical] // auto-generated internal static void Assert(PermissionSet permSet, ref StackCrawlMark stackMark) { -#if FEATURE_CAS_POLICY - // Note: if the "AssertPermission" is not a permission that implements IUnrestrictedPermission - // you need to change the fourth parameter to a zero. - FrameSecurityDescriptor secObj = CodeAccessSecurityEngine.CheckNReturnSO( - CodeAccessSecurityEngine.AssertPermissionToken, - CodeAccessSecurityEngine.AssertPermission, - ref stackMark, - 1 ); - - Contract.Assert(secObj != null,"Failure in SecurityRuntime.Assert() - secObj != null"); - if (secObj == null) - { - // Security: REQ_SQ flag is missing. Bad compiler ? - System.Environment.FailFast(Environment.GetResourceString("ExecutionEngine_MissingSecurityDescriptor")); - } - else - { - if (secObj.HasImperativeAsserts()) - throw new SecurityException( Environment.GetResourceString( "Security_MustRevertOverride" ) ); - - secObj.SetAssert(permSet); - } -#endif // FEATURE_CAS_POLICY } - + [System.Security.SecurityCritical] // auto-generated internal static void AssertAllPossible(ref StackCrawlMark stackMark) { -#if FEATURE_CAS_POLICY - FrameSecurityDescriptor secObj = - SecurityRuntime.GetSecurityObjectForFrame(ref stackMark, true); - - Contract.Assert(secObj != null, "Failure in SecurityRuntime.AssertAllPossible() - secObj != null"); - if (secObj == null) - { - // Security: REQ_SQ flag is missing. Bad compiler ? - System.Environment.FailFast(Environment.GetResourceString("ExecutionEngine_MissingSecurityDescriptor")); - } - else - { - if (secObj.GetAssertAllPossible()) - throw new SecurityException( Environment.GetResourceString( "Security_MustRevertOverride" ) ); - - secObj.SetAssertAllPossible(); - } -#endif // FEATURE_CAS_POLICY } - + [System.Security.SecurityCritical] // auto-generated internal static void Deny(PermissionSet permSet, ref StackCrawlMark stackMark) { -#if FEATURE_CAS_POLICY - // Deny is only valid in legacy mode - if (!AppDomain.CurrentDomain.IsLegacyCasPolicyEnabled) - { - throw new NotSupportedException(Environment.GetResourceString("NotSupported_CasDeny")); - } - - FrameSecurityDescriptor secObj = - SecurityRuntime.GetSecurityObjectForFrame(ref stackMark, true); - - Contract.Assert(secObj != null, "Failure in SecurityRuntime.Deny() - secObj != null"); - if (secObj == null) - { - // Security: REQ_SQ flag is missing. Bad compiler ? - System.Environment.FailFast(Environment.GetResourceString("ExecutionEngine_MissingSecurityDescriptor")); - } - else - { - if (secObj.HasImperativeDenials()) - throw new SecurityException( Environment.GetResourceString( "Security_MustRevertOverride" ) ); - - secObj.SetDeny(permSet); - } -#endif // FEATURE_CAS_POLICY } - + [System.Security.SecurityCritical] // auto-generated internal static void PermitOnly(PermissionSet permSet, ref StackCrawlMark stackMark) { -#if FEATURE_CAS_POLICY - FrameSecurityDescriptor secObj = - SecurityRuntime.GetSecurityObjectForFrame(ref stackMark, true); - - Contract.Assert(secObj != null, "Failure in SecurityRuntime.PermitOnly() - secObj != null"); - if (secObj == null) - { - // Security: REQ_SQ flag is missing. Bad compiler ? - System.Environment.FailFast(Environment.GetResourceString("ExecutionEngine_MissingSecurityDescriptor")); - } - else - { - if (secObj.HasImperativeRestrictions()) - throw new SecurityException( Environment.GetResourceString( "Security_MustRevertOverride" ) ); - - secObj.SetPermitOnly(permSet); - } -#endif // FEATURE_CAS_POLICY } - + // // Revert API // - + [System.Security.SecurityCritical] // auto-generated internal static void RevertAssert(ref StackCrawlMark stackMark) { -#if FEATURE_CAS_POLICY - FrameSecurityDescriptor secObj = GetSecurityObjectForFrame(ref stackMark, false); - if (secObj != null) - { - secObj.RevertAssert(); - } - else - { - throw new InvalidOperationException(Environment.GetResourceString("ExecutionEngine_MissingSecurityDescriptor")); - } -#endif // FEATURE_CAS_POLICY } [System.Security.SecurityCritical] // auto-generated internal static void RevertDeny(ref StackCrawlMark stackMark) { -#if FEATURE_CAS_POLICY - FrameSecurityDescriptor secObj = GetSecurityObjectForFrame(ref stackMark, false); - if (secObj != null) - { - secObj.RevertDeny(); - } - else - { - throw new InvalidOperationException(Environment.GetResourceString("ExecutionEngine_MissingSecurityDescriptor")); - } -#endif // FEATURE_CAS_POLICY } [System.Security.SecurityCritical] // auto-generated internal static void RevertPermitOnly(ref StackCrawlMark stackMark) { -#if FEATURE_CAS_POLICY - FrameSecurityDescriptor secObj = GetSecurityObjectForFrame(ref stackMark, false); - if (secObj != null) - { - secObj.RevertPermitOnly(); - } - else - { - throw new InvalidOperationException(Environment.GetResourceString("ExecutionEngine_MissingSecurityDescriptor")); - } -#endif // FEATURE_CAS_POLICY } [System.Security.SecurityCritical] // auto-generated internal static void RevertAll(ref StackCrawlMark stackMark) { -#if FEATURE_CAS_POLICY - FrameSecurityDescriptor secObj = GetSecurityObjectForFrame(ref stackMark, false); - if (secObj != null) - { - secObj.RevertAll(); - } - else - { - throw new InvalidOperationException(Environment.GetResourceString("ExecutionEngine_MissingSecurityDescriptor")); - } -#endif // FEATURE_CAS_POLICY } } } diff --git a/src/coreclr/src/mscorlib/src/System/Security/Util/Config.cs b/src/coreclr/src/mscorlib/src/System/Security/Util/Config.cs index 988a39a..7f96602 100644 --- a/src/coreclr/src/mscorlib/src/System/Security/Util/Config.cs +++ b/src/coreclr/src/mscorlib/src/System/Security/Util/Config.cs @@ -74,48 +74,6 @@ namespace System.Security.Util { } } -#if FEATURE_CAS_POLICY - [System.Security.SecurityCritical] // auto-generated - [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode), SuppressUnmanagedCodeSecurity] - internal static extern int SaveDataByte(string path, [In] byte[] data, int length); - - [System.Security.SecurityCritical] // auto-generated - [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode), SuppressUnmanagedCodeSecurity] - internal static extern bool RecoverData(ConfigId id); - - [System.Security.SecurityCritical] // auto-generated - [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode), SuppressUnmanagedCodeSecurity] - internal static extern void SetQuickCache(ConfigId id, QuickCacheEntryType quickCacheFlags); - - [System.Security.SecurityCritical] // auto-generated - [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode), SuppressUnmanagedCodeSecurity] - private static extern bool GetCacheEntry(ConfigId id, int numKey, [In] byte[] key, int keyLength, ObjectHandleOnStack retData); - - [System.Security.SecurityCritical] // auto-generated - internal static bool GetCacheEntry(ConfigId id, int numKey, byte[] key, out byte[] data) - { - byte[] retData = null; - bool ret = GetCacheEntry(id, numKey, key, key.Length, JitHelpers.GetObjectHandleOnStack(ref retData)); - - data = retData; - return ret; - } - - [System.Security.SecurityCritical] // auto-generated - [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode), SuppressUnmanagedCodeSecurity] - private static extern void AddCacheEntry(ConfigId id, int numKey, [In] byte[] key, int keyLength, byte[] data, int dataLength); - - [System.Security.SecurityCritical] // auto-generated - internal static void AddCacheEntry(ConfigId id, int numKey, byte[] key, byte[] data) - { - AddCacheEntry(id, numKey, key, key.Length, data, data.Length); - } - - [System.Security.SecurityCritical] // auto-generated - [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode), SuppressUnmanagedCodeSecurity] - internal static extern void ResetCacheData(ConfigId id); -#endif - [System.Security.SecurityCritical] // auto-generated [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode), SuppressUnmanagedCodeSecurity] private static extern void GetMachineDirectory(StringHandleOnStack retDirectory); diff --git a/src/coreclr/src/mscorlib/src/System/Security/Util/TokenBasedSet.cs b/src/coreclr/src/mscorlib/src/System/Security/Util/TokenBasedSet.cs index 590a909..45f9176 100644 --- a/src/coreclr/src/mscorlib/src/System/Security/Util/TokenBasedSet.cs +++ b/src/coreclr/src/mscorlib/src/System/Security/Util/TokenBasedSet.cs @@ -368,31 +368,17 @@ namespace System.Security.Util { Object thisObj = this.GetItem( i ); IPermission thisPerm = thisObj as IPermission; -#if FEATURE_CAS_POLICY - ISecurityElementFactory thisElem = thisObj as ISecurityElementFactory; -#endif // FEATURE_CAS_POLICY Object otherObj = (other != null)?other.GetItem( i ):null; IPermission otherPerm = otherObj as IPermission; -#if FEATURE_CAS_POLICY - ISecurityElementFactory otherElem = otherObj as ISecurityElementFactory; -#endif // FEATURE_CAS_POLICY if (thisObj == null && otherObj == null) continue; - - + if (thisObj == null) { -#if FEATURE_CAS_POLICY - if (otherElem != null) - { - otherPerm = PermissionSet.CreatePerm(otherElem, false); - } -#endif // FEATURE_CAS_POLICY - PermissionToken token = PermissionToken.GetToken(otherPerm); - + if (token == null) { throw new SerializationException(Environment.GetResourceString("Serialization_InsufficientState")); @@ -402,13 +388,6 @@ namespace System.Security.Util } else if (otherObj == null) { -#if FEATURE_CAS_POLICY - if (thisElem != null) - { - thisPerm = PermissionSet.CreatePerm(thisElem, false); - } -#endif // FEATURE_CAS_POLICY - PermissionToken token = PermissionToken.GetToken(thisPerm); if (token == null) { @@ -434,10 +413,6 @@ namespace System.Security.Util if (obj != null) { IPermission perm = obj as IPermission; -#if FEATURE_CAS_POLICY - if (perm == null) - perm = PermissionSet.CreatePerm(obj, ignoreTypeLoadFailures); -#endif // FEATURE_CAS_POLICY PermissionToken token = PermissionToken.GetToken(perm); if (perm == null || token == null) diff --git a/src/coreclr/src/mscorlib/src/System/Security/Util/XMLUtil.cs b/src/coreclr/src/mscorlib/src/System/Security/Util/XMLUtil.cs index df8f0c4..a9a8a65 100644 --- a/src/coreclr/src/mscorlib/src/System/Security/Util/XMLUtil.cs +++ b/src/coreclr/src/mscorlib/src/System/Security/Util/XMLUtil.cs @@ -35,12 +35,7 @@ namespace System.Security.Util { // private const String BuiltInPermission = "System.Security.Permissions."; -#if FEATURE_CAS_POLICY - private const String BuiltInMembershipCondition = "System.Security.Policy."; - private const String BuiltInCodeGroup = "System.Security.Policy."; - private const String BuiltInApplicationSecurityManager = "System.Security.Policy."; - private static readonly char[] sepChar = {',', ' '}; -#endif + public static SecurityElement NewPermissionElement (IPermission ip) { @@ -175,28 +170,6 @@ namespace System.Security.Util { return false; } -#if FEATURE_CAS_POLICY - public static String SecurityObjectToXmlString(Object ob) - { - if(ob == null) - return ""; - PermissionSet pset = ob as PermissionSet; - if(pset != null) - return pset.ToXml().ToString(); - return ((IPermission)ob).ToXml().ToString(); - } - - [System.Security.SecurityCritical] // auto-generated - public static Object XmlStringToSecurityObject(String s) - { - if(s == null) - return null; - if(s.Length < 1) - return null; - return SecurityElement.FromString(s).ToSecurityObject(); - } -#endif // FEATURE_CAS_POLICY - [SecuritySafeCritical] public static IPermission CreatePermission (SecurityElement el, PermissionState permState, bool ignoreTypeLoadFailures) @@ -235,9 +208,6 @@ namespace System.Security.Util { // UnsafeForHostPermission // HostProtectionPermission // StrongNameIdentityPermission -#if !FEATURE_CORECLR - // IsolatedStorageFilePermission -#endif // RegistryPermission // PublisherIdentityPermission @@ -274,15 +244,6 @@ namespace System.Security.Util { else goto USEREFLECTION; } - -#if !FEATURE_CORECLR - case 19: - // PrincipalPermission - if (String.Compare(className, classNameStart, "PrincipalPermission", 0, classNameLength, StringComparison.Ordinal) == 0) - return new PrincipalPermission( permState ); - else - goto USEREFLECTION; -#endif // !FEATURE_CORECLR case 20: // ReflectionPermission // FileDialogPermission @@ -326,8 +287,6 @@ namespace System.Security.Util { else goto USEREFLECTION; } - - case 22: // SiteIdentityPermission // ZoneIdentityPermission @@ -353,42 +312,22 @@ namespace System.Security.Util { else goto USEREFLECTION; } - - case 24: // HostProtectionPermission if (String.Compare(className, classNameStart, "HostProtectionPermission", 0, classNameLength, StringComparison.Ordinal) == 0) return new HostProtectionPermission( permState ); else goto USEREFLECTION; - -#if FEATURE_X509 && FEATURE_CAS_POLICY - case 27: - // PublisherIdentityPermission - if (String.Compare(className, classNameStart, "PublisherIdentityPermission", 0, classNameLength, StringComparison.Ordinal) == 0) - return new PublisherIdentityPermission( permState ); - else - goto USEREFLECTION; -#endif // FEATURE_X509 && FEATURE_CAS_POLICY - case 28: // StrongNameIdentityPermission if (String.Compare(className, classNameStart, "StrongNameIdentityPermission", 0, classNameLength, StringComparison.Ordinal) == 0) return new StrongNameIdentityPermission( permState ); else goto USEREFLECTION; -#if !FEATURE_CORECLR - case 29: - // IsolatedStorageFilePermission - if (String.Compare(className, classNameStart, "IsolatedStorageFilePermission", 0, classNameLength, StringComparison.Ordinal) == 0) - return new IsolatedStorageFilePermission( permState ); - else - goto USEREFLECTION; -#endif default: goto USEREFLECTION; } - + USEREFLECTION: Object[] objs = new Object[1]; @@ -409,204 +348,6 @@ USEREFLECTION: return perm; } -#if FEATURE_CAS_POLICY -#pragma warning disable 618 // CodeGroups are obsolete - [System.Security.SecuritySafeCritical] // auto-generated - public static CodeGroup - CreateCodeGroup (SecurityElement el) - { - if (el == null || !el.Tag.Equals("CodeGroup")) - throw new ArgumentException( String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "Argument_WrongElementType" ), "" ) ) ; - Contract.EndContractBlock(); - - String className; - int classNameLength; - int classNameStart; - - if (!ParseElementForObjectCreation( el, - BuiltInCodeGroup, - out className, - out classNameStart, - out classNameLength )) - { - goto USEREFLECTION; - } - - switch (classNameLength) - { - case 12: - // NetCodeGroup - if (String.Compare(className, classNameStart, "NetCodeGroup", 0, classNameLength, StringComparison.Ordinal) == 0) - return new NetCodeGroup(); - else - goto USEREFLECTION; - - case 13: - // FileCodeGroup - if (String.Compare(className, classNameStart, "FileCodeGroup", 0, classNameLength, StringComparison.Ordinal) == 0) - return new FileCodeGroup(); - else - goto USEREFLECTION; - case 14: - // UnionCodeGroup - if (String.Compare(className, classNameStart, "UnionCodeGroup", 0, classNameLength, StringComparison.Ordinal) == 0) - return new UnionCodeGroup(); - else - goto USEREFLECTION; - - case 19: - // FirstMatchCodeGroup - if (String.Compare(className, classNameStart, "FirstMatchCodeGroup", 0, classNameLength, StringComparison.Ordinal) == 0) - return new FirstMatchCodeGroup(); - else - goto USEREFLECTION; - - default: - goto USEREFLECTION; - } - -USEREFLECTION: - Type groupClass = null; - CodeGroup group = null; - - new ReflectionPermission(ReflectionPermissionFlag.MemberAccess).Assert(); - groupClass = GetClassFromElement(el, true); - if (groupClass == null) - return null; - if (!(typeof(CodeGroup).IsAssignableFrom(groupClass))) - throw new ArgumentException( Environment.GetResourceString("Argument_NotACodeGroupType") ); - - group = (CodeGroup) Activator.CreateInstance(groupClass, true); - - Contract.Assert( groupClass.Module.Assembly != Assembly.GetExecutingAssembly(), - "This path should not get called for mscorlib based classes" ); - - return group; - } -#pragma warning restore 618 - - [System.Security.SecurityCritical] // auto-generated - internal static IMembershipCondition - CreateMembershipCondition( SecurityElement el ) - { - if (el == null || !el.Tag.Equals("IMembershipCondition")) - throw new ArgumentException( String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "Argument_WrongElementType" ), "" ) ) ; - Contract.EndContractBlock(); - - String className; - int classNameStart; - int classNameLength; - - if (!ParseElementForObjectCreation( el, - BuiltInMembershipCondition, - out className, - out classNameStart, - out classNameLength )) - { - goto USEREFLECTION; - } - - // We have a built in membership condition, figure out which it is. - - // Here's the list of built in membership conditions as of 9/17/2002 - // System.Security.Policy.AllMembershipCondition - // System.Security.Policy.URLMembershipCondition - // System.Security.Policy.SHA1MembershipCondition - // System.Security.Policy.SiteMembershipCondition - // System.Security.Policy.ZoneMembershipCondition - // System.Security.Policy.PublisherMembershipCondition - // System.Security.Policy.StrongNameMembershipCondition - // System.Security.Policy.ApplicationMembershipCondition - // System.Security.Policy.DomainApplicationMembershipCondition - // System.Security.Policy.ApplicationDirectoryMembershipCondition - - switch (classNameLength) - { - case 22: - // AllMembershipCondition - // URLMembershipCondition - if (className[classNameStart] == 'A') - { - if (String.Compare(className, classNameStart, "AllMembershipCondition", 0, classNameLength, StringComparison.Ordinal) == 0) - return new AllMembershipCondition(); - else - goto USEREFLECTION; - } - else - { - if (String.Compare(className, classNameStart, "UrlMembershipCondition", 0, classNameLength, StringComparison.Ordinal) == 0) - return new UrlMembershipCondition(); - else - goto USEREFLECTION; - } - - case 23: - // HashMembershipCondition - // SiteMembershipCondition - // ZoneMembershipCondition - if (className[classNameStart] == 'H') - { - if (String.Compare(className, classNameStart, "HashMembershipCondition", 0, classNameLength, StringComparison.Ordinal) == 0) - return new HashMembershipCondition(); - else - goto USEREFLECTION; - } - else if (className[classNameStart] == 'S') - { - if (String.Compare(className, classNameStart, "SiteMembershipCondition", 0, classNameLength, StringComparison.Ordinal) == 0) - return new SiteMembershipCondition(); - else - goto USEREFLECTION; - } - else - { - if (String.Compare(className, classNameStart, "ZoneMembershipCondition", 0, classNameLength, StringComparison.Ordinal) == 0) - return new ZoneMembershipCondition(); - else - goto USEREFLECTION; - } - - case 28: - // PublisherMembershipCondition - if (String.Compare(className, classNameStart, "PublisherMembershipCondition", 0, classNameLength, StringComparison.Ordinal) == 0) - return new PublisherMembershipCondition(); - else - goto USEREFLECTION; - - case 29: - // StrongNameMembershipCondition - if (String.Compare(className, classNameStart, "StrongNameMembershipCondition", 0, classNameLength, StringComparison.Ordinal) == 0) - return new StrongNameMembershipCondition(); - else - goto USEREFLECTION; - - case 39: - // ApplicationDirectoryMembershipCondition - if (String.Compare(className, classNameStart, "ApplicationDirectoryMembershipCondition", 0, classNameLength, StringComparison.Ordinal) == 0) - return new ApplicationDirectoryMembershipCondition(); - else - goto USEREFLECTION; - - default: - goto USEREFLECTION; - } - -USEREFLECTION: - Type condClass = null; - IMembershipCondition cond = null; - - new ReflectionPermission(ReflectionPermissionFlag.MemberAccess).Assert(); - condClass = GetClassFromElement(el, true); - if (condClass == null) - return null; - if (!(typeof(IMembershipCondition).IsAssignableFrom(condClass))) - throw new ArgumentException( Environment.GetResourceString("Argument_NotAMembershipCondition") ); - - cond = (IMembershipCondition) Activator.CreateInstance(condClass, true); - - return cond; - } -#endif //#if FEATURE_CAS_POLICY internal static Type GetClassFromElement (SecurityElement el, bool ignoreTypeLoadFailures) { @@ -624,7 +365,7 @@ USEREFLECTION: { try { - return Type.GetType(className, false, false); + return Type.GetType(className, false, false); } catch (SecurityException) { @@ -632,7 +373,7 @@ USEREFLECTION: } } else - return Type.GetType(className, true, false); + return Type.GetType(className, true, false); } public static bool diff --git a/src/coreclr/src/mscorlib/src/System/SharedStatics.cs b/src/coreclr/src/mscorlib/src/System/SharedStatics.cs index ec63a0e..bc34280 100644 --- a/src/coreclr/src/mscorlib/src/System/SharedStatics.cs +++ b/src/coreclr/src/mscorlib/src/System/SharedStatics.cs @@ -11,8 +11,8 @@ ** =============================================================================*/ -namespace System { - +namespace System +{ using System.Threading; using System.Runtime.Remoting; using System.Security; @@ -20,9 +20,6 @@ namespace System { using System.Runtime.CompilerServices; using System.Runtime.ConstrainedExecution; using System.Diagnostics.Contracts; -#if FEATURE_CAS_POLICY - using StringMaker = System.Security.Util.Tokenizer.StringMaker; -#endif // FEATURE_CAS_POLICY internal sealed class SharedStatics { @@ -67,57 +64,6 @@ namespace System { } } -#if FEATURE_CAS_POLICY - private StringMaker _maker; - [System.Security.SecuritySafeCritical] // auto-generated - static public StringMaker GetSharedStringMaker() - { - StringMaker maker = null; - - bool tookLock = false; - RuntimeHelpers.PrepareConstrainedRegions(); - try { - Monitor.Enter(_sharedStatics, ref tookLock); - - if (_sharedStatics._maker != null) - { - maker = _sharedStatics._maker; - _sharedStatics._maker = null; - } - } - finally { - if (tookLock) - Monitor.Exit(_sharedStatics); - } - - if (maker == null) - { - maker = new StringMaker(); - } - - return maker; - } - - [System.Security.SecuritySafeCritical] // auto-generated - static public void ReleaseSharedStringMaker(ref StringMaker maker) - { - // save this stringmaker so someone else can use it - bool tookLock = false; - RuntimeHelpers.PrepareConstrainedRegions(); - try - { - Monitor.Enter(_sharedStatics, ref tookLock); - - _sharedStatics._maker = maker; - maker = null; - } - finally { - if (tookLock) - Monitor.Exit(_sharedStatics); - } - } -#endif // FEATURE_CAS_POLICY - // Note this may not need to be process-wide. private int _Remoting_Identity_IDSeqNum; internal static int Remoting_Identity_GetNextSeqNum() diff --git a/src/coreclr/src/mscorlib/src/System/Text/Encoding.cs b/src/coreclr/src/mscorlib/src/System/Text/Encoding.cs index 160370b..93ea30b 100644 --- a/src/coreclr/src/mscorlib/src/System/Text/Encoding.cs +++ b/src/coreclr/src/mscorlib/src/System/Text/Encoding.cs @@ -389,9 +389,6 @@ namespace System.Text private static volatile Hashtable encodings; #endif -#if !FEATURE_CORECLR - [System.Security.SecurityCritical] -#endif public static void RegisterProvider(EncodingProvider provider) { // Parameters validated inside EncodingProvider @@ -399,9 +396,6 @@ namespace System.Text } [Pure] -#if !FEATURE_CORECLR - [System.Security.SecuritySafeCritical] // auto-generated -#endif public static Encoding GetEncoding(int codepage) { Encoding result = EncodingProvider.GetEncodingFromProvider(codepage); diff --git a/src/coreclr/src/mscorlib/src/System/Threading/EventWaitHandle.cs b/src/coreclr/src/mscorlib/src/System/Threading/EventWaitHandle.cs index 6c14489..9937bd9 100644 --- a/src/coreclr/src/mscorlib/src/System/Threading/EventWaitHandle.cs +++ b/src/coreclr/src/mscorlib/src/System/Threading/EventWaitHandle.cs @@ -13,7 +13,6 @@ =============================================================================*/ -#if !FEATURE_MACL namespace System.Security.AccessControl { public class EventWaitHandleSecurity @@ -23,7 +22,6 @@ namespace System.Security.AccessControl { } } -#endif namespace System.Threading { @@ -111,18 +109,6 @@ namespace System.Threading } Contract.EndContractBlock(); Win32Native.SECURITY_ATTRIBUTES secAttrs = null; -#if FEATURE_MACL - // For ACL's, get the security descriptor from the EventWaitHandleSecurity. - if (eventSecurity != null) { - secAttrs = new Win32Native.SECURITY_ATTRIBUTES(); - secAttrs.nLength = (int)Marshal.SizeOf(secAttrs); - - byte[] sd = eventSecurity.GetSecurityDescriptorBinaryForm(); - byte* pSecDescriptor = stackalloc byte[sd.Length]; - Buffer.Memcpy(pSecDescriptor, 0, sd, 0, sd.Length); - secAttrs.pSecurityDescriptor = pSecDescriptor; - } -#endif SafeWaitHandle _handle = null; Boolean isManualReset; @@ -164,11 +150,7 @@ namespace System.Threading [System.Security.SecurityCritical] // auto-generated_required public static EventWaitHandle OpenExisting(string name) { -#if !FEATURE_MACL return OpenExisting(name, (EventWaitHandleRights)0); -#else - return OpenExisting(name, EventWaitHandleRights.Modify | EventWaitHandleRights.Synchronize); -#endif } [System.Security.SecurityCritical] // auto-generated_required @@ -195,11 +177,7 @@ namespace System.Threading [System.Security.SecurityCritical] // auto-generated_required public static bool TryOpenExisting(string name, out EventWaitHandle result) { -#if !FEATURE_MACL return OpenExistingWorker(name, (EventWaitHandleRights)0, out result) == OpenExistingResult.Success; -#else - return OpenExistingWorker(name, EventWaitHandleRights.Modify | EventWaitHandleRights.Synchronize, out result) == OpenExistingResult.Success; -#endif } [System.Security.SecurityCritical] // auto-generated_required @@ -233,12 +211,8 @@ namespace System.Threading result = null; -#if FEATURE_MACL - SafeWaitHandle myHandle = Win32Native.OpenEvent((int) rights, false, name); -#else SafeWaitHandle myHandle = Win32Native.OpenEvent(Win32Native.EVENT_MODIFY_STATE | Win32Native.SYNCHRONIZE, false, name); -#endif - + if (myHandle.IsInvalid) { int errorCode = Marshal.GetLastWin32Error(); @@ -274,24 +248,6 @@ namespace System.Threading return res; } - -#if FEATURE_MACL - [System.Security.SecuritySafeCritical] // auto-generated - public EventWaitHandleSecurity GetAccessControl() - { - return new EventWaitHandleSecurity(safeWaitHandle, AccessControlSections.Access | AccessControlSections.Owner | AccessControlSections.Group); - } - - [System.Security.SecuritySafeCritical] // auto-generated - public void SetAccessControl(EventWaitHandleSecurity eventSecurity) - { - if (eventSecurity == null) - throw new ArgumentNullException(nameof(eventSecurity)); - Contract.EndContractBlock(); - - eventSecurity.Persist(safeWaitHandle); - } -#endif } } diff --git a/src/coreclr/src/mscorlib/src/System/Threading/Mutex.cs b/src/coreclr/src/mscorlib/src/System/Threading/Mutex.cs index 98789d9..7ea08e4 100644 --- a/src/coreclr/src/mscorlib/src/System/Threading/Mutex.cs +++ b/src/coreclr/src/mscorlib/src/System/Threading/Mutex.cs @@ -25,10 +25,6 @@ namespace System.Threading using System.Runtime.Versioning; using System.Security; using System.Diagnostics.Contracts; - -#if FEATURE_MACL - using System.Security.AccessControl; -#endif [HostProtection(Synchronization=true, ExternalThreading=true)] [ComVisible(true)] @@ -36,10 +32,9 @@ namespace System.Threading { static bool dummyBool; -#if !FEATURE_MACL - public class MutexSecurity { + public class MutexSecurity + { } -#endif [System.Security.SecurityCritical] // auto-generated_required [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)] @@ -65,19 +60,6 @@ namespace System.Threading #endif Contract.EndContractBlock(); Win32Native.SECURITY_ATTRIBUTES secAttrs = null; -#if FEATURE_MACL - // For ACL's, get the security descriptor from the MutexSecurity. - if (mutexSecurity != null) { - - secAttrs = new Win32Native.SECURITY_ATTRIBUTES(); - secAttrs.nLength = (int)Marshal.SizeOf(secAttrs); - - byte[] sd = mutexSecurity.GetSecurityDescriptorBinaryForm(); - byte* pSecDescriptor = stackalloc byte[sd.Length]; - Buffer.Memcpy(pSecDescriptor, 0, sd, 0, sd.Length); - secAttrs.pSecurityDescriptor = pSecDescriptor; - } -#endif CreateMutexWithGuaranteedCleanup(initiallyOwned, name, out createdNew, secAttrs); } @@ -155,14 +137,10 @@ namespace System.Threading if (m_initiallyOwned) { m_cleanupInfo.inCriticalRegion = true; -#if !FEATURE_CORECLR - Thread.BeginThreadAffinity(); - Thread.BeginCriticalRegion(); -#endif //!FEATURE_CORECLR } } - int errorCode = 0; + int errorCode = 0; RuntimeHelpers.PrepareConstrainedRegions(); try { @@ -266,18 +244,12 @@ namespace System.Threading [System.Security.SecurityCritical] // auto-generated_required public static Mutex OpenExisting(string name) { -#if !FEATURE_MACL return OpenExisting(name, (MutexRights) 0); -#else // FEATURE_MACL - return OpenExisting(name, MutexRights.Modify | MutexRights.Synchronize); -#endif // FEATURE_MACL } -#if !FEATURE_MACL public enum MutexRights { } -#endif [System.Security.SecurityCritical] // auto-generated_required public static Mutex OpenExisting(string name, MutexRights rights) @@ -303,11 +275,7 @@ namespace System.Threading [System.Security.SecurityCritical] // auto-generated_required public static bool TryOpenExisting(string name, out Mutex result) { -#if !FEATURE_MACL return OpenExistingWorker(name, (MutexRights)0, out result) == OpenExistingResult.Success; -#else // FEATURE_MACL - return OpenExistingWorker(name, MutexRights.Modify | MutexRights.Synchronize, out result) == OpenExistingResult.Success; -#endif // FEATURE_MACL } [System.Security.SecurityCritical] // auto-generated_required @@ -342,11 +310,7 @@ namespace System.Threading // with parameters to allow us to view & edit the ACL. This will // fail if we don't have permission to view or edit the ACL's. // If that happens, ask for less permissions. -#if FEATURE_MACL - SafeWaitHandle myHandle = Win32Native.OpenMutex((int) rights, false, name); -#else SafeWaitHandle myHandle = Win32Native.OpenMutex(Win32Native.MUTEX_MODIFY_STATE | Win32Native.SYNCHRONIZE, false, name); -#endif int errorCode = 0; if (myHandle.IsInvalid) @@ -380,109 +344,52 @@ namespace System.Threading // MUTEX_MODIFY_STATE rights (0x0001). The other interesting value // in a Mutex's ACL is MUTEX_ALL_ACCESS (0x1F0001). [System.Security.SecuritySafeCritical] // auto-generated - [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)] + [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)] public void ReleaseMutex() { if (Win32Native.ReleaseMutex(safeWaitHandle)) { -#if !FEATURE_CORECLR - Thread.EndCriticalRegion(); - Thread.EndThreadAffinity(); -#endif } else { -#if FEATURE_CORECLR throw new Exception(Environment.GetResourceString("Arg_SynchronizationLockException")); -#else - throw new ApplicationException(Environment.GetResourceString("Arg_SynchronizationLockException")); -#endif // FEATURE_CORECLR - } + } } [System.Security.SecurityCritical] // auto-generated [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)] - static int CreateMutexHandle(bool initiallyOwned, String name, Win32Native.SECURITY_ATTRIBUTES securityAttribute, out SafeWaitHandle mutexHandle) { - int errorCode; - bool fAffinity = false; - - while(true) { + static int CreateMutexHandle(bool initiallyOwned, String name, Win32Native.SECURITY_ATTRIBUTES securityAttribute, out SafeWaitHandle mutexHandle) + { + int errorCode; + + while (true) + { mutexHandle = Win32Native.CreateMutex(securityAttribute, initiallyOwned, name); - errorCode = Marshal.GetLastWin32Error(); - if( !mutexHandle.IsInvalid) { - break; - } + errorCode = Marshal.GetLastWin32Error(); + if (!mutexHandle.IsInvalid) break; - if( errorCode == Win32Native.ERROR_ACCESS_DENIED) { - // If a mutex with the name already exists, OS will try to open it with FullAccess. - // It might fail if we don't have enough access. In that case, we try to open the mutex will modify and synchronize access. - // - - RuntimeHelpers.PrepareConstrainedRegions(); - try - { - try - { - } - finally - { -#if !FEATURE_CORECLR - Thread.BeginThreadAffinity(); -#endif - fAffinity = true; - } - mutexHandle = Win32Native.OpenMutex(Win32Native.MUTEX_MODIFY_STATE | Win32Native.SYNCHRONIZE, false, name); - if(!mutexHandle.IsInvalid) - { - errorCode = Win32Native.ERROR_ALREADY_EXISTS; - } - else - { - errorCode = Marshal.GetLastWin32Error(); - } - } - finally - { - if (fAffinity) { -#if !FEATURE_CORECLR - Thread.EndThreadAffinity(); -#endif - } - } + if (errorCode != Win32Native.ERROR_ACCESS_DENIED) break; - // There could be a race condition here, the other owner of the mutex can free the mutex, - // We need to retry creation in that case. - if( errorCode != Win32Native.ERROR_FILE_NOT_FOUND) { - if( errorCode == Win32Native.ERROR_SUCCESS) { - errorCode = Win32Native.ERROR_ALREADY_EXISTS; - } - break; - } - } - else { + // If a mutex with the name already exists, OS will try to open it with FullAccess. + // It might fail if we don't have enough access. In that case, we try to open the mutex will modify and synchronize access. + RuntimeHelpers.PrepareConstrainedRegions(); + + mutexHandle = Win32Native.OpenMutex( + Win32Native.MUTEX_MODIFY_STATE | Win32Native.SYNCHRONIZE, + false, + name); + + errorCode = !mutexHandle.IsInvalid ? Win32Native.ERROR_ALREADY_EXISTS : Marshal.GetLastWin32Error(); + + // There could be a race condition here, the other owner of the mutex can free the mutex, + // We need to retry creation in that case. + if (errorCode != Win32Native.ERROR_FILE_NOT_FOUND) + { + if (errorCode == Win32Native.ERROR_SUCCESS) errorCode = Win32Native.ERROR_ALREADY_EXISTS; break; } - } + } return errorCode; } - -#if FEATURE_MACL - [System.Security.SecuritySafeCritical] // auto-generated - public MutexSecurity GetAccessControl() - { - return new MutexSecurity(safeWaitHandle, AccessControlSections.Access | AccessControlSections.Owner | AccessControlSections.Group); - } - - [System.Security.SecuritySafeCritical] // auto-generated - public void SetAccessControl(MutexSecurity mutexSecurity) - { - if (mutexSecurity == null) - throw new ArgumentNullException(nameof(mutexSecurity)); - Contract.EndContractBlock(); - - mutexSecurity.Persist(safeWaitHandle); - } -#endif - } } diff --git a/src/coreclr/src/mscorlib/src/System/Threading/Thread.cs b/src/coreclr/src/mscorlib/src/System/Threading/Thread.cs index 1a3bbf8..5b476cc 100644 --- a/src/coreclr/src/mscorlib/src/System/Threading/Thread.cs +++ b/src/coreclr/src/mscorlib/src/System/Threading/Thread.cs @@ -18,10 +18,6 @@ namespace System.Threading { using System.Threading; using System.Runtime; using System.Runtime.InteropServices; -#if FEATURE_REMOTING - using System.Runtime.Remoting.Contexts; - using System.Runtime.Remoting.Messaging; -#endif using System; using System.Diagnostics; using System.Security.Permissions; @@ -131,17 +127,12 @@ namespace System.Threading { ** ThreadBaseObject to maintain alignment between the two classes. ** DON'T CHANGE THESE UNLESS YOU MODIFY ThreadBaseObject in vm\object.h =========================================================================*/ -#if FEATURE_REMOTING - private Context m_Context; -#endif private ExecutionContext m_ExecutionContext; // this call context follows the logical thread -#if FEATURE_CORECLR private SynchronizationContext m_SynchronizationContext; // On CoreCLR, this is maintained separately from ExecutionContext -#endif private String m_Name; private Delegate m_Delegate; // Delegate - + #if FEATURE_LEAK_CULTURE_INFO private CultureInfo m_CurrentCulture; private CultureInfo m_CurrentUICulture; diff --git a/src/coreclr/src/mscorlib/src/System/Threading/ThreadPool.cs b/src/coreclr/src/mscorlib/src/System/Threading/ThreadPool.cs index c11e149..ba8c61a 100644 --- a/src/coreclr/src/mscorlib/src/System/Threading/ThreadPool.cs +++ b/src/coreclr/src/mscorlib/src/System/Threading/ThreadPool.cs @@ -29,9 +29,6 @@ namespace System.Threading { using System.Security; -#if FEATURE_REMOTING - using System.Runtime.Remoting; -#endif using System.Security.Permissions; using System; using Microsoft.Win32; @@ -1479,12 +1476,6 @@ namespace System.Threading bool compressStack ) { -#if FEATURE_REMOTING - if (RemotingServices.IsTransparentProxy(waitObject)) - throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_WaitOnTransparentProxy")); - Contract.EndContractBlock(); -#endif - RegisteredWaitHandle registeredWaitHandle = new RegisteredWaitHandle(); if (callBack != null) diff --git a/src/coreclr/src/mscorlib/src/System/Threading/WaitHandle.cs b/src/coreclr/src/mscorlib/src/System/Threading/WaitHandle.cs index 15d39a0..1dd29e7 100644 --- a/src/coreclr/src/mscorlib/src/System/Threading/WaitHandle.cs +++ b/src/coreclr/src/mscorlib/src/System/Threading/WaitHandle.cs @@ -313,11 +313,6 @@ namespace System.Threading if (waitHandle == null) throw new ArgumentNullException("waitHandles[" + i + "]", Environment.GetResourceString("ArgumentNull_ArrayElement")); -#if FEATURE_REMOTING - if (RemotingServices.IsTransparentProxy(waitHandle)) - throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_WaitOnTransparentProxy")); -#endif - internalWaitHandles[i] = waitHandle; } #if _DEBUG @@ -413,11 +408,6 @@ namespace System.Threading if (waitHandle == null) throw new ArgumentNullException("waitHandles[" + i + "]", Environment.GetResourceString("ArgumentNull_ArrayElement")); -#if FEATURE_REMOTING - if (RemotingServices.IsTransparentProxy(waitHandle)) - throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_WaitOnTransparentProxy")); -#endif - internalWaitHandles[i] = waitHandle; } #if _DEBUG diff --git a/src/coreclr/src/mscorlib/src/System/TimeZoneInfo.cs b/src/coreclr/src/mscorlib/src/System/TimeZoneInfo.cs index 3902450..5e817f2 100644 --- a/src/coreclr/src/mscorlib/src/System/TimeZoneInfo.cs +++ b/src/coreclr/src/mscorlib/src/System/TimeZoneInfo.cs @@ -1002,19 +1002,13 @@ namespace System { PermissionSet permSet = new PermissionSet(PermissionState.None); permSet.AddPermission(new RegistryPermission(RegistryPermissionAccess.Read, c_timeZonesRegistryHivePermissionList)); permSet.Assert(); - - using (RegistryKey reg = Registry.LocalMachine.OpenSubKey( - c_timeZonesRegistryHive, -#if FEATURE_MACL - RegistryKeyPermissionCheck.Default, - System.Security.AccessControl.RegistryRights.ReadKey -#else - false -#endif - )) { - if (reg != null) { - foreach (string keyName in reg.GetSubKeyNames()) { + using (RegistryKey reg = Registry.LocalMachine.OpenSubKey(c_timeZonesRegistryHive, false)) + { + if (reg != null) + { + foreach (string keyName in reg.GetSubKeyNames()) + { TimeZoneInfo value; Exception ex; TryGetTimeZone(keyName, false, out value, out ex, cachedData); // populate the cache @@ -1693,21 +1687,16 @@ namespace System { permSet.AddPermission(new RegistryPermission(RegistryPermissionAccess.Read, c_timeZonesRegistryHivePermissionList)); permSet.Assert(); - using (RegistryKey key = Registry.LocalMachine.OpenSubKey( - c_timeZonesRegistryHive, -#if FEATURE_MACL - RegistryKeyPermissionCheck.Default, - System.Security.AccessControl.RegistryRights.ReadKey -#else - false -#endif - )) { - - if (key == null) { + using (RegistryKey key = Registry.LocalMachine.OpenSubKey(c_timeZonesRegistryHive, false)) + { + if (key == null) + { return null; } - foreach (string keyName in key.GetSubKeyNames()) { - if (TryCompareTimeZoneInformationToRegistry(timeZone, keyName, out dstDisabled)) { + foreach (string keyName in key.GetSubKeyNames()) + { + if (TryCompareTimeZoneInformationToRegistry(timeZone, keyName, out dstDisabled)) + { return keyName; } } @@ -2971,26 +2960,22 @@ namespace System { try { using (RegistryKey dynamicKey = Registry.LocalMachine.OpenSubKey( - c_timeZonesRegistryHive + "\\" + id + "\\Dynamic DST", -#if FEATURE_MACL - RegistryKeyPermissionCheck.Default, - System.Security.AccessControl.RegistryRights.ReadKey -#else - false -#endif - )) { + c_timeZonesRegistryHive + "\\" + id + "\\Dynamic DST", + false)) { if (dynamicKey == null) { AdjustmentRule rule = CreateAdjustmentRuleFromTimeZoneInformation( defaultTimeZoneInformation, DateTime.MinValue.Date, DateTime.MaxValue.Date, defaultBaseUtcOffset); - if (rule == null) { + if (rule == null) + { rules = null; } - else { + else + { rules = new AdjustmentRule[1]; rules[0] = rule; } - + return true; } @@ -3005,7 +2990,8 @@ namespace System { Int32 first = (Int32)dynamicKey.GetValue(c_firstEntryValue, -1, RegistryValueOptions.None); Int32 last = (Int32)dynamicKey.GetValue(c_lastEntryValue, -1, RegistryValueOptions.None); - if (first == -1 || last == -1 || first > last) { + if (first == -1 || last == -1 || first > last) + { rules = null; return false; } @@ -3013,20 +2999,24 @@ namespace System { // read the first year entry Win32Native.RegistryTimeZoneInformation dtzi; Byte[] regValue = dynamicKey.GetValue(first.ToString(CultureInfo.InvariantCulture), null, RegistryValueOptions.None) as Byte[]; - if (regValue == null || regValue.Length != c_regByteLength) { + if (regValue == null || regValue.Length != c_regByteLength) + { rules = null; return false; } dtzi = new Win32Native.RegistryTimeZoneInformation(regValue); - if (first == last) { + if (first == last) + { // there is just 1 dynamic rule for this time zone. - AdjustmentRule rule = CreateAdjustmentRuleFromTimeZoneInformation(dtzi, DateTime.MinValue.Date, DateTime.MaxValue.Date, defaultBaseUtcOffset); + AdjustmentRule rule = CreateAdjustmentRuleFromTimeZoneInformation(dtzi, DateTime.MinValue.Date, DateTime.MaxValue.Date, defaultBaseUtcOffset); - if (rule == null) { + if (rule == null) + { rules = null; } - else { + else + { rules = new AdjustmentRule[1]; rules[0] = rule; } @@ -3036,20 +3026,23 @@ namespace System { List rulesList = new List(1); - // there are more than 1 dynamic rules for this time zone. + // there are more than 1 dynamic rules for this time zone. AdjustmentRule firstRule = CreateAdjustmentRuleFromTimeZoneInformation( dtzi, DateTime.MinValue.Date, // MinValue new DateTime(first, 12, 31), // December 31, - defaultBaseUtcOffset); - if (firstRule != null) { + defaultBaseUtcOffset); + if (firstRule != null) + { rulesList.Add(firstRule); } // read the middle year entries - for (Int32 i = first + 1; i < last; i++) { + for (Int32 i = first + 1; i < last; i++) + { regValue = dynamicKey.GetValue(i.ToString(CultureInfo.InvariantCulture), null, RegistryValueOptions.None) as Byte[]; - if (regValue == null || regValue.Length != c_regByteLength) { + if (regValue == null || regValue.Length != c_regByteLength) + { rules = null; return false; } @@ -3059,14 +3052,16 @@ namespace System { new DateTime(i, 1, 1), // January 01, new DateTime(i, 12, 31), // December 31, defaultBaseUtcOffset); - if (middleRule != null) { + if (middleRule != null) + { rulesList.Add(middleRule); } } // read the last year entry regValue = dynamicKey.GetValue(last.ToString(CultureInfo.InvariantCulture), null, RegistryValueOptions.None) as Byte[]; dtzi = new Win32Native.RegistryTimeZoneInformation(regValue); - if (regValue == null || regValue.Length != c_regByteLength) { + if (regValue == null || regValue.Length != c_regByteLength) + { rules = null; return false; } @@ -3075,13 +3070,15 @@ namespace System { new DateTime(last, 1, 1), // January 01, DateTime.MaxValue.Date, // MaxValue defaultBaseUtcOffset); - if (lastRule != null) { + if (lastRule != null) + { rulesList.Add(lastRule); } // convert the ArrayList to an AdjustmentRule array rules = rulesList.ToArray(); - if (rules != null && rules.Length == 0) { + if (rules != null && rules.Length == 0) + { rules = null; } } // end of: using (RegistryKey dynamicKey... @@ -3131,8 +3128,8 @@ namespace System { // Helper function that compares a TimeZoneInformation struct to a time zone registry entry // [System.Security.SecuritySafeCritical] // auto-generated - static private Boolean TryCompareTimeZoneInformationToRegistry(Win32Native.TimeZoneInformation timeZone, string id, out Boolean dstDisabled) { - + static private Boolean TryCompareTimeZoneInformationToRegistry(Win32Native.TimeZoneInformation timeZone, string id, out Boolean dstDisabled) + { dstDisabled = false; try { PermissionSet permSet = new PermissionSet(PermissionState.None); @@ -3140,14 +3137,9 @@ namespace System { permSet.Assert(); using (RegistryKey key = Registry.LocalMachine.OpenSubKey( - c_timeZonesRegistryHive + "\\" + id, -#if FEATURE_MACL - RegistryKeyPermissionCheck.Default, - System.Security.AccessControl.RegistryRights.ReadKey -#else - false -#endif - )) { + c_timeZonesRegistryHive + "\\" + id, + false)) + { if (key == null) { return false; @@ -3164,7 +3156,8 @@ namespace System { // Boolean result = TryCompareStandardDate(timeZone, registryTimeZoneInfo); - if (!result) { + if (!result) + { return false; } @@ -3173,14 +3166,14 @@ namespace System { // since Daylight Saving Time is not "disabled", do a straight comparision between // the Win32 API data and the registry data ... // - ||( timeZone.DaylightBias == registryTimeZoneInfo.DaylightBias - && timeZone.DaylightDate.Year == registryTimeZoneInfo.DaylightDate.Year - && timeZone.DaylightDate.Month == registryTimeZoneInfo.DaylightDate.Month - && timeZone.DaylightDate.DayOfWeek == registryTimeZoneInfo.DaylightDate.DayOfWeek - && timeZone.DaylightDate.Day == registryTimeZoneInfo.DaylightDate.Day - && timeZone.DaylightDate.Hour == registryTimeZoneInfo.DaylightDate.Hour - && timeZone.DaylightDate.Minute == registryTimeZoneInfo.DaylightDate.Minute - && timeZone.DaylightDate.Second == registryTimeZoneInfo.DaylightDate.Second + || (timeZone.DaylightBias == registryTimeZoneInfo.DaylightBias + && timeZone.DaylightDate.Year == registryTimeZoneInfo.DaylightDate.Year + && timeZone.DaylightDate.Month == registryTimeZoneInfo.DaylightDate.Month + && timeZone.DaylightDate.DayOfWeek == registryTimeZoneInfo.DaylightDate.DayOfWeek + && timeZone.DaylightDate.Day == registryTimeZoneInfo.DaylightDate.Day + && timeZone.DaylightDate.Hour == registryTimeZoneInfo.DaylightDate.Hour + && timeZone.DaylightDate.Minute == registryTimeZoneInfo.DaylightDate.Minute + && timeZone.DaylightDate.Second == registryTimeZoneInfo.DaylightDate.Second && timeZone.DaylightDate.Milliseconds == registryTimeZoneInfo.DaylightDate.Milliseconds); // Finally compare the "StandardName" string value... @@ -3188,11 +3181,12 @@ namespace System { // we do not compare "DaylightName" as this TimeZoneInformation field may contain // either "StandardName" or "DaylightName" depending on the time of year and current machine settings // - if (result) { + if (result) + { String registryStandardName = key.GetValue(c_standardValue, String.Empty, RegistryValueOptions.None) as String; result = String.Compare(registryStandardName, timeZone.StandardName, StringComparison.Ordinal) == 0; } - return result; + return result; } } finally { @@ -3409,14 +3403,8 @@ namespace System { permSet.Assert(); using (RegistryKey key = Registry.LocalMachine.OpenSubKey( - c_timeZonesRegistryHive + "\\" + id, -#if FEATURE_MACL - RegistryKeyPermissionCheck.Default, - System.Security.AccessControl.RegistryRights.ReadKey -#else - false -#endif - )) { + c_timeZonesRegistryHive + "\\" + id, + false)) { if (key == null) { value = null; diff --git a/src/coreclr/src/mscorlib/src/System/Type.cs b/src/coreclr/src/mscorlib/src/System/Type.cs index 6583631..01d3d93 100644 --- a/src/coreclr/src/mscorlib/src/System/Type.cs +++ b/src/coreclr/src/mscorlib/src/System/Type.cs @@ -9,8 +9,8 @@ // // ====================================================================================== -namespace System { - +namespace System +{ using System; using System.Reflection; using System.Threading; @@ -1301,21 +1301,15 @@ namespace System { // Protected routine to determine if this class is contextful - protected virtual bool IsContextfulImpl(){ -#if FEATURE_REMOTING - return typeof(ContextBoundObject).IsAssignableFrom(this); -#else + protected virtual bool IsContextfulImpl() + { return false; -#endif } // Protected routine to determine if this class is marshaled by ref - protected virtual bool IsMarshalByRefImpl(){ -#if FEATURE_REMOTING - return typeof(MarshalByRefObject).IsAssignableFrom(this); -#else + protected virtual bool IsMarshalByRefImpl() + { return false; -#endif } internal virtual bool HasProxyAttributeImpl() diff --git a/src/coreclr/src/mscorlib/src/System/Variant.cs b/src/coreclr/src/mscorlib/src/System/Variant.cs index c75f82f..951c46d 100644 --- a/src/coreclr/src/mscorlib/src/System/Variant.cs +++ b/src/coreclr/src/mscorlib/src/System/Variant.cs @@ -423,11 +423,8 @@ namespace System { [System.Security.SecuritySafeCritical] // auto-generated internal static void MarshalHelperConvertObjectToVariant(Object o, ref Variant v) { -#if FEATURE_REMOTING - IConvertible ic = System.Runtime.Remoting.RemotingServices.IsTransparentProxy(o) ? null : o as IConvertible; -#else IConvertible ic = o as IConvertible; -#endif + if (o == null) { v = Empty; diff --git a/src/coreclr/src/mscorlib/src/System/__ComObject.cs b/src/coreclr/src/mscorlib/src/System/__ComObject.cs index a592370..fc82c28 100644 --- a/src/coreclr/src/mscorlib/src/System/__ComObject.cs +++ b/src/coreclr/src/mscorlib/src/System/__ComObject.cs @@ -12,8 +12,8 @@ ** ** ===========================================================*/ -namespace System { - +namespace System +{ using System; using System.Collections; using System.Threading; @@ -180,9 +180,6 @@ namespace System { } [System.Security.SecurityCritical] // auto-generated -#if !FEATURE_CORECLR - [ReflectionPermissionAttribute(SecurityAction.Assert, MemberAccess=true)] -#endif private Object CreateEventProvider(RuntimeType t) { // Create the event provider for the specified type. diff --git a/src/coreclr/src/mscorlib/src/System/cominterfaces.cs b/src/coreclr/src/mscorlib/src/System/cominterfaces.cs index 7d3620a..a83943d 100644 --- a/src/coreclr/src/mscorlib/src/System/cominterfaces.cs +++ b/src/coreclr/src/mscorlib/src/System/cominterfaces.cs @@ -2,23 +2,13 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. - -using System; -using System.Globalization; -using System.IO; -using System.Reflection; -using System.Runtime.InteropServices; -using System.Runtime.Serialization; -using System.Security.Permissions; -using System.Security.Policy; - namespace System.Runtime.InteropServices { [GuidAttribute("03973551-57A1-3900-A2B5-9083E3FF2943")] [InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)] [CLSCompliant(false)] [TypeLibImportClassAttribute(typeof(System.Activator))] -[System.Runtime.InteropServices.ComVisible(true)] + [System.Runtime.InteropServices.ComVisible(true)] public interface _Activator { void GetTypeInfoCount(out uint pcTInfo); @@ -34,35 +24,17 @@ namespace System.Runtime.InteropServices [InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)] [CLSCompliant(false)] [TypeLibImportClassAttribute(typeof(System.Attribute))] -[System.Runtime.InteropServices.ComVisible(true)] + [System.Runtime.InteropServices.ComVisible(true)] public interface _Attribute { -#if !FEATURE_CORECLR - void GetTypeInfoCount(out uint pcTInfo); - - void GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo); - - void GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId); - - void Invoke(uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr); -#endif } [GuidAttribute("C281C7F1-4AA9-3517-961A-463CFED57E75")] [InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)] [CLSCompliant(false)] [TypeLibImportClassAttribute(typeof(System.Threading.Thread))] -[System.Runtime.InteropServices.ComVisible(true)] + [System.Runtime.InteropServices.ComVisible(true)] public interface _Thread { -#if !FEATURE_CORECLR - void GetTypeInfoCount(out uint pcTInfo); - - void GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo); - - void GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId); - - void Invoke(uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr); -#endif } }