diff options
Diffstat (limited to 'src/mscorlib/src/System/Runtime')
119 files changed, 1650 insertions, 4312 deletions
diff --git a/src/mscorlib/src/System/Runtime/CompilerServices/AsyncMethodBuilder.cs b/src/mscorlib/src/System/Runtime/CompilerServices/AsyncMethodBuilder.cs index 05850605b8..6a16462383 100644 --- a/src/mscorlib/src/System/Runtime/CompilerServices/AsyncMethodBuilder.cs +++ b/src/mscorlib/src/System/Runtime/CompilerServices/AsyncMethodBuilder.cs @@ -32,7 +32,6 @@ namespace System.Runtime.CompilerServices /// Provides a builder for asynchronous methods that return void. /// This type is intended for compiler use only. /// </summary> - [HostProtection(Synchronization = true, ExternalThreading = true)] public struct AsyncVoidMethodBuilder { /// <summary>The synchronization context associated with this operation.</summary> @@ -59,14 +58,13 @@ namespace System.Runtime.CompilerServices /// <typeparam name="TStateMachine">Specifies the type of the state machine.</typeparam> /// <param name="stateMachine">The state machine instance, passed by reference.</param> /// <exception cref="System.ArgumentNullException">The <paramref name="stateMachine"/> argument was null (Nothing in Visual Basic).</exception> - [SecuritySafeCritical] [DebuggerStepThrough] public void Start<TStateMachine>(ref TStateMachine stateMachine) where TStateMachine : IAsyncStateMachine { // See comment on AsyncMethodBuilderCore.Start // AsyncMethodBuilderCore.Start(ref stateMachine); - if (stateMachine == null) throw new ArgumentNullException("stateMachine"); + if (stateMachine == null) throw new ArgumentNullException(nameof(stateMachine)); Contract.EndContractBlock(); // Run the MoveNext method within a copy-on-write ExecutionContext scope. @@ -112,7 +110,7 @@ namespace System.Runtime.CompilerServices { AsyncMethodBuilderCore.MoveNextRunner runnerToInitialize = null; var continuation = m_coreState.GetCompletionAction(AsyncCausalityTracer.LoggingOn ? this.Task : null, ref runnerToInitialize); - Contract.Assert(continuation != null, "GetCompletionAction should always return a valid action."); + Debug.Assert(continuation != null, "GetCompletionAction should always return a valid action."); // If this is our first await, such that we've not yet boxed the state machine, do so now. if (m_coreState.m_stateMachine == null) @@ -149,7 +147,6 @@ namespace System.Runtime.CompilerServices /// <typeparam name="TStateMachine">Specifies the type of the state machine.</typeparam> /// <param name="awaiter">The awaiter.</param> /// <param name="stateMachine">The state machine.</param> - [SecuritySafeCritical] public void AwaitUnsafeOnCompleted<TAwaiter, TStateMachine>( ref TAwaiter awaiter, ref TStateMachine stateMachine) where TAwaiter : ICriticalNotifyCompletion @@ -159,7 +156,7 @@ namespace System.Runtime.CompilerServices { AsyncMethodBuilderCore.MoveNextRunner runnerToInitialize = null; var continuation = m_coreState.GetCompletionAction(AsyncCausalityTracer.LoggingOn ? this.Task : null, ref runnerToInitialize); - Contract.Assert(continuation != null, "GetCompletionAction should always return a valid action."); + Debug.Assert(continuation != null, "GetCompletionAction should always return a valid action."); // If this is our first await, such that we've not yet boxed the state machine, do so now. if (m_coreState.m_stateMachine == null) @@ -200,7 +197,7 @@ namespace System.Runtime.CompilerServices /// <exception cref="System.InvalidOperationException">The builder is not initialized.</exception> public void SetException(Exception exception) { - if (exception == null) throw new ArgumentNullException("exception"); + if (exception == null) throw new ArgumentNullException(nameof(exception)); Contract.EndContractBlock(); if (AsyncCausalityTracer.LoggingOn) @@ -231,7 +228,7 @@ namespace System.Runtime.CompilerServices /// <summary>Notifies the current synchronization context that the operation completed.</summary> private void NotifySynchronizationContextOfCompletion() { - Contract.Assert(m_synchronizationContext != null, "Must only be used with a non-null context."); + Debug.Assert(m_synchronizationContext != null, "Must only be used with a non-null context."); try { m_synchronizationContext.OperationCompleted(); @@ -273,7 +270,6 @@ namespace System.Runtime.CompilerServices /// Prior to being copied, one of its Task, SetResult, or SetException members must be accessed, /// or else the copies may end up building distinct Task instances. /// </remarks> - [HostProtection(Synchronization = true, ExternalThreading = true)] public struct AsyncTaskMethodBuilder { /// <summary>A cached VoidTaskResult task used for builders that complete synchronously.</summary> @@ -294,14 +290,13 @@ namespace System.Runtime.CompilerServices /// <summary>Initiates the builder's execution with the associated state machine.</summary> /// <typeparam name="TStateMachine">Specifies the type of the state machine.</typeparam> /// <param name="stateMachine">The state machine instance, passed by reference.</param> - [SecuritySafeCritical] [DebuggerStepThrough] public void Start<TStateMachine>(ref TStateMachine stateMachine) where TStateMachine : IAsyncStateMachine { // See comment on AsyncMethodBuilderCore.Start // AsyncMethodBuilderCore.Start(ref stateMachine); - if (stateMachine == null) throw new ArgumentNullException("stateMachine"); + if (stateMachine == null) throw new ArgumentNullException(nameof(stateMachine)); Contract.EndContractBlock(); // Run the MoveNext method within a copy-on-write ExecutionContext scope. @@ -421,7 +416,6 @@ namespace System.Runtime.CompilerServices /// Prior to being copied, one of its Task, SetResult, or SetException members must be accessed, /// or else the copies may end up building distinct Task instances. /// </remarks> - [HostProtection(Synchronization = true, ExternalThreading = true)] public struct AsyncTaskMethodBuilder<TResult> { /// <summary>A cached task for default(TResult).</summary> @@ -450,14 +444,13 @@ namespace System.Runtime.CompilerServices /// <summary>Initiates the builder's execution with the associated state machine.</summary> /// <typeparam name="TStateMachine">Specifies the type of the state machine.</typeparam> /// <param name="stateMachine">The state machine instance, passed by reference.</param> - [SecuritySafeCritical] [DebuggerStepThrough] public void Start<TStateMachine>(ref TStateMachine stateMachine) where TStateMachine : IAsyncStateMachine { // See comment on AsyncMethodBuilderCore.Start // AsyncMethodBuilderCore.Start(ref stateMachine); - if (stateMachine == null) throw new ArgumentNullException("stateMachine"); + if (stateMachine == null) throw new ArgumentNullException(nameof(stateMachine)); Contract.EndContractBlock(); // Run the MoveNext method within a copy-on-write ExecutionContext scope. @@ -503,7 +496,7 @@ namespace System.Runtime.CompilerServices { AsyncMethodBuilderCore.MoveNextRunner runnerToInitialize = null; var continuation = m_coreState.GetCompletionAction(AsyncCausalityTracer.LoggingOn ? this.Task : null, ref runnerToInitialize); - Contract.Assert(continuation != null, "GetCompletionAction should always return a valid action."); + Debug.Assert(continuation != null, "GetCompletionAction should always return a valid action."); // If this is our first await, such that we've not yet boxed the state machine, do so now. if (m_coreState.m_stateMachine == null) @@ -534,7 +527,6 @@ namespace System.Runtime.CompilerServices /// <typeparam name="TStateMachine">Specifies the type of the state machine.</typeparam> /// <param name="awaiter">The awaiter.</param> /// <param name="stateMachine">The state machine.</param> - [SecuritySafeCritical] public void AwaitUnsafeOnCompleted<TAwaiter, TStateMachine>( ref TAwaiter awaiter, ref TStateMachine stateMachine) where TAwaiter : ICriticalNotifyCompletion @@ -544,7 +536,7 @@ namespace System.Runtime.CompilerServices { AsyncMethodBuilderCore.MoveNextRunner runnerToInitialize = null; var continuation = m_coreState.GetCompletionAction(AsyncCausalityTracer.LoggingOn ? this.Task : null, ref runnerToInitialize); - Contract.Assert(continuation != null, "GetCompletionAction should always return a valid action."); + Debug.Assert(continuation != null, "GetCompletionAction should always return a valid action."); // If this is our first await, such that we've not yet boxed the state machine, do so now. if (m_coreState.m_stateMachine == null) @@ -595,7 +587,7 @@ namespace System.Runtime.CompilerServices if (task == null) { m_task = GetTaskForResult(result); - Contract.Assert(m_task != null, "GetTaskForResult should never return null"); + Debug.Assert(m_task != null, "GetTaskForResult should never return null"); } // Slow path: complete the existing task. else @@ -650,7 +642,7 @@ namespace System.Runtime.CompilerServices /// <exception cref="System.InvalidOperationException">The task has already completed.</exception> public void SetException(Exception exception) { - if (exception == null) throw new ArgumentNullException("exception"); + if (exception == null) throw new ArgumentNullException(nameof(exception)); Contract.EndContractBlock(); @@ -713,7 +705,6 @@ namespace System.Runtime.CompilerServices /// </summary> /// <param name="result">The result for which we need a task.</param> /// <returns>The completed task containing the result.</returns> - [SecuritySafeCritical] // for JitHelpers.UnsafeCast private Task<TResult> GetTaskForResult(TResult result) { Contract.Ensures( @@ -819,7 +810,7 @@ namespace System.Runtime.CompilerServices /// <summary>Creates an array of cached tasks for the values in the range [INCLUSIVE_MIN,EXCLUSIVE_MAX).</summary> private static Task<Int32>[] CreateInt32Tasks() { - Contract.Assert(EXCLUSIVE_INT32_MAX >= INCLUSIVE_INT32_MIN, "Expected max to be at least min"); + Debug.Assert(EXCLUSIVE_INT32_MAX >= INCLUSIVE_INT32_MIN, "Expected max to be at least min"); var tasks = new Task<Int32>[EXCLUSIVE_INT32_MAX - INCLUSIVE_INT32_MIN]; for (int i = 0; i < tasks.Length; i++) { @@ -854,12 +845,11 @@ namespace System.Runtime.CompilerServices /// <typeparam name="TStateMachine">Specifies the type of the state machine.</typeparam> /// <param name="stateMachine">The state machine instance, passed by reference.</param> /// <exception cref="System.ArgumentNullException">The <paramref name="stateMachine"/> argument is null (Nothing in Visual Basic).</exception> - [SecuritySafeCritical] [DebuggerStepThrough] internal static void Start<TStateMachine>(ref TStateMachine stateMachine) where TStateMachine : IAsyncStateMachine { - if (stateMachine == null) throw new ArgumentNullException("stateMachine"); + if (stateMachine == null) throw new ArgumentNullException(nameof(stateMachine)); Contract.EndContractBlock(); // Run the MoveNext method within a copy-on-write ExecutionContext scope. @@ -887,7 +877,7 @@ namespace System.Runtime.CompilerServices /// <exception cref="System.InvalidOperationException">The builder is incorrectly initialized.</exception> public void SetStateMachine(IAsyncStateMachine stateMachine) { - if (stateMachine == null) throw new ArgumentNullException("stateMachine"); + if (stateMachine == null) throw new ArgumentNullException(nameof(stateMachine)); Contract.EndContractBlock(); if (m_stateMachine != null) throw new InvalidOperationException(Environment.GetResourceString("AsyncMethodBuilder_InstanceNotInitialized")); m_stateMachine = stateMachine; @@ -902,10 +892,9 @@ namespace System.Runtime.CompilerServices /// <param name="builder">The builder.</param> /// <param name="stateMachine">The state machine.</param> /// <returns>An Action to provide to the awaiter.</returns> - [SecuritySafeCritical] internal Action GetCompletionAction(Task taskForTracing, ref MoveNextRunner runnerToInitialize) { - Contract.Assert(m_defaultContextAction == null || m_stateMachine != null, + Debug.Assert(m_defaultContextAction == null || m_stateMachine != null, "Expected non-null m_stateMachine on non-null m_defaultContextAction"); // Alert a listening debugger that we can't make forward progress unless it slips threads. @@ -928,7 +917,7 @@ namespace System.Runtime.CompilerServices action = m_defaultContextAction; if (action != null) { - Contract.Assert(m_stateMachine != null, "If the delegate was set, the state machine should have been as well."); + Debug.Assert(m_stateMachine != null, "If the delegate was set, the state machine should have been as well."); return action; } @@ -994,8 +983,8 @@ namespace System.Runtime.CompilerServices m_stateMachine = stateMachine; m_stateMachine.SetStateMachine(m_stateMachine); - Contract.Assert(runner.m_stateMachine == null, "The runner's state machine should not yet have been populated."); - Contract.Assert(m_stateMachine != null, "The builder's state machine field should have been initialized."); + Debug.Assert(runner.m_stateMachine == null, "The runner's state machine should not yet have been populated."); + Debug.Assert(m_stateMachine != null, "The builder's state machine field should have been initialized."); // Now that we have the state machine, store it into the runner that the action delegate points to. // And return the action. @@ -1045,17 +1034,15 @@ namespace System.Runtime.CompilerServices /// <summary>Initializes the runner.</summary> /// <param name="context">The context with which to run MoveNext.</param> - [SecurityCritical] // Run needs to be SSC to map to Action delegate, so to prevent misuse, we only allow construction through SC internal MoveNextRunnerWithContext(ExecutionContext context, IAsyncStateMachine stateMachine) : base(stateMachine) { m_context = context; } /// <summary>Invokes MoveNext under the provided context.</summary> - [SecuritySafeCritical] internal void RunWithCapturedContext() { - Contract.Assert(m_stateMachine != null, "The state machine must have been set before calling Run."); + Debug.Assert(m_stateMachine != null, "The state machine must have been set before calling Run."); if (m_context != null) { @@ -1080,34 +1067,29 @@ namespace System.Runtime.CompilerServices internal IAsyncStateMachine m_stateMachine; /// <summary>Initializes the runner.</summary> - [SecurityCritical] // Run needs to be SSC to map to Action delegate, so to prevent misuse, we only allow construction through SC internal MoveNextRunner(IAsyncStateMachine stateMachine) { m_stateMachine = stateMachine; } /// <summary>Invokes MoveNext under the default context.</summary> - [SecuritySafeCritical] internal void RunWithDefaultContext() { - Contract.Assert(m_stateMachine != null, "The state machine must have been set before calling Run."); + Debug.Assert(m_stateMachine != null, "The state machine must have been set before calling Run."); ExecutionContext.Run(ExecutionContext.PreAllocatedDefault, InvokeMoveNextCallback, m_stateMachine, preserveSyncCtx: true); } /// <summary>Gets a delegate to the InvokeMoveNext method.</summary> protected static ContextCallback InvokeMoveNextCallback { - [SecuritySafeCritical] get { return s_invokeMoveNext ?? (s_invokeMoveNext = InvokeMoveNext); } } /// <summary>Cached delegate used with ExecutionContext.Run.</summary> - [SecurityCritical] private static ContextCallback s_invokeMoveNext; // lazily-initialized due to SecurityCritical attribution /// <summary>Invokes the MoveNext method on the supplied IAsyncStateMachine.</summary> /// <param name="stateMachine">The IAsyncStateMachine machine instance.</param> - [SecurityCritical] // necessary for ContextCallback in CoreCLR private static void InvokeMoveNext(object stateMachine) { ((IAsyncStateMachine)stateMachine).MoveNext(); diff --git a/src/mscorlib/src/System/Runtime/CompilerServices/CallingConvention.cs b/src/mscorlib/src/System/Runtime/CompilerServices/CallingConvention.cs deleted file mode 100644 index f44251d480..0000000000 --- a/src/mscorlib/src/System/Runtime/CompilerServices/CallingConvention.cs +++ /dev/null @@ -1,30 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -//////////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////////// -namespace System.Runtime.CompilerServices -{ - // Types used in Custom Modifier to specify calling conventions. - [System.Runtime.InteropServices.ComVisible(true)] - public class CallConvCdecl - { - } - - [System.Runtime.InteropServices.ComVisible(true)] - public class CallConvStdcall - { - } - - [System.Runtime.InteropServices.ComVisible(true)] - public class CallConvThiscall - { - } - - [System.Runtime.InteropServices.ComVisible(true)] - public class CallConvFastcall - { - } - -} diff --git a/src/mscorlib/src/System/Runtime/CompilerServices/ConditionalWeakTable.cs b/src/mscorlib/src/System/Runtime/CompilerServices/ConditionalWeakTable.cs index 21d677241d..74559673bb 100644 --- a/src/mscorlib/src/System/Runtime/CompilerServices/ConditionalWeakTable.cs +++ b/src/mscorlib/src/System/Runtime/CompilerServices/ConditionalWeakTable.cs @@ -60,31 +60,29 @@ ** may be delayed until appdomain shutdown. ===========================================================*/ +using System.Collections.Generic; +using System.Runtime.InteropServices; +using System.Threading; + namespace System.Runtime.CompilerServices { - using System; - using System.Collections.Generic; - using System.Runtime.Versioning; - using System.Runtime.InteropServices; - - #region ConditionalWeakTable - [System.Runtime.InteropServices.ComVisible(false)] + [ComVisible(false)] public sealed class ConditionalWeakTable<TKey, TValue> where TKey : class where TValue : class { + #region Fields + private const int InitialCapacity = 8; // Initial length of the table. Must be a power of two. + private readonly object _lock; // This lock protects all mutation of data in the table. Readers do not take this lock. + private volatile Container _container; // The actual storage for the table; swapped out as the table grows. + #endregion #region Constructors - [System.Security.SecuritySafeCritical] public ConditionalWeakTable() { - _buckets = Array.Empty<int>(); - _entries = Array.Empty<Entry>(); - _freeList = -1; - _lock = new Object(); - - Resize(); // Resize at once (so won't need "if initialized" checks all over) + _lock = new object(); + _container = new Container(this); } #endregion @@ -99,18 +97,14 @@ namespace System.Runtime.CompilerServices // Note: The key may get garbaged collected during the TryGetValue operation. If so, TryGetValue // may at its discretion, return "false" and set "value" to the default (as if the key was not present.) //-------------------------------------------------------------------------------------------- - [System.Security.SecuritySafeCritical] public bool TryGetValue(TKey key, out TValue value) { if (key == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key); } - lock(_lock) - { - VerifyIntegrity(); - return TryGetValueWorker(key, out value); - } + + return _container.TryGetValueWorker(key, out value); } //-------------------------------------------------------------------------------------------- @@ -123,7 +117,6 @@ namespace System.Runtime.CompilerServices // has the right to consider any prior entries successfully removed and add a new entry without // throwing an exception. //-------------------------------------------------------------------------------------------- - [System.Security.SecuritySafeCritical] public void Add(TKey key, TValue value) { if (key == null) @@ -131,22 +124,48 @@ namespace System.Runtime.CompilerServices ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key); } - lock(_lock) + lock (_lock) { - VerifyIntegrity(); - _invalid = true; - - int entryIndex = FindEntry(key); + object otherValue; + int entryIndex = _container.FindEntry(key, out otherValue); if (entryIndex != -1) { - _invalid = false; ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_AddingDuplicate); } CreateEntry(key, value); - _invalid = false; } + } + + //-------------------------------------------------------------------------------------------- + // key: key to add or update. May not be null. + // value: value to associate with key. + // + // If the key is already entered into the dictionary, this method will update the value associated with key. + //-------------------------------------------------------------------------------------------- + public void AddOrUpdate(TKey key, TValue value) + { + if (key == null) + { + ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key); + } + + lock (_lock) + { + object otherValue; + int entryIndex = _container.FindEntry(key, out otherValue); + + // if we found a key we should just update, if no we should create a new entry. + if (entryIndex != -1) + { + _container.UpdateValue(entryIndex, value); + } + else + { + CreateEntry(key, value); + } + } } //-------------------------------------------------------------------------------------------- @@ -156,9 +175,8 @@ namespace System.Runtime.CompilerServices // // Note: The key may get garbage collected during the Remove() operation. If so, // Remove() will not fail or throw, however, the return value can be either true or false - // depending on the race condition. + // depending on who wins the race. //-------------------------------------------------------------------------------------------- - [System.Security.SecuritySafeCritical] public bool Remove(TKey key) { if (key == null) @@ -166,40 +184,9 @@ namespace System.Runtime.CompilerServices ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key); } - lock(_lock) + lock (_lock) { - VerifyIntegrity(); - _invalid = true; - - int hashCode = RuntimeHelpers.GetHashCode(key) & Int32.MaxValue; - int bucket = hashCode % _buckets.Length; - int last = -1; - for (int entriesIndex = _buckets[bucket]; entriesIndex != -1; entriesIndex = _entries[entriesIndex].next) - { - if (_entries[entriesIndex].hashCode == hashCode && _entries[entriesIndex].depHnd.GetPrimary() == key) - { - if (last == -1) - { - _buckets[bucket] = _entries[entriesIndex].next; - } - else - { - _entries[last].next = _entries[entriesIndex].next; - } - - _entries[entriesIndex].depHnd.Free(); - _entries[entriesIndex].next = _freeList; - - _freeList = entriesIndex; - - _invalid = false; - return true; - - } - last = entriesIndex; - } - _invalid = false; - return false; + return _container.Remove(key); } } @@ -219,46 +206,39 @@ namespace System.Runtime.CompilerServices // This rule permits the table to invoke createValueCallback outside the internal table lock // to prevent deadlocks. //-------------------------------------------------------------------------------------------- - [System.Security.SecuritySafeCritical] public TValue GetValue(TKey key, CreateValueCallback createValueCallback) { - // Our call to TryGetValue() validates key so no need for us to. - // - // if (key == null) - // { - // ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key); - // } + // key is validated by TryGetValue if (createValueCallback == null) { - throw new ArgumentNullException("createValueCallback"); + throw new ArgumentNullException(nameof(createValueCallback)); } TValue existingValue; - if (TryGetValue(key, out existingValue)) - { - return existingValue; - } + return TryGetValue(key, out existingValue) ? + existingValue : + GetValueLocked(key, createValueCallback); + } - // If we got here, the key is not currently in table. Invoke the callback (outside the lock) + private TValue GetValueLocked(TKey key, CreateValueCallback createValueCallback) + { + // If we got here, the key was not in the table. Invoke the callback (outside the lock) // to generate the new value for the key. TValue newValue = createValueCallback(key); - lock(_lock) + lock (_lock) { - VerifyIntegrity(); - _invalid = true; - - // Now that we've retaken the lock, must recheck in case there was a race condition to add the key. - if (TryGetValueWorker(key, out existingValue)) + // Now that we've taken the lock, must recheck in case we lost a race to add the key. + TValue existingValue; + if (_container.TryGetValueWorker(key, out existingValue)) { - _invalid = false; return existingValue; } else { + // Verified in-lock that we won the race to add the key. Add it now. CreateEntry(key, newValue); - _invalid = false; return newValue; } } @@ -271,17 +251,15 @@ namespace System.Runtime.CompilerServices // to create new instances as needed. If TValue does not have a default constructor, this will // throw. //-------------------------------------------------------------------------------------------- - public TValue GetOrCreateValue(TKey key) - { - return GetValue(key, k => Activator.CreateInstance<TValue>()); - } + + public TValue GetOrCreateValue(TKey key) => GetValue(key, _ => Activator.CreateInstance<TValue>()); public delegate TValue CreateValueCallback(TKey key); - + #endregion - #region internal members - + #region Internal members + //-------------------------------------------------------------------------------------------- // Find a key that equals (value equality) with the given key - don't use in perf critical path // Note that it calls out to Object.Equals which may calls the override version of Equals @@ -290,56 +268,26 @@ namespace System.Runtime.CompilerServices // if you know for sure that either you won't run into dead locks or you need to live with the // possiblity //-------------------------------------------------------------------------------------------- - [System.Security.SecuritySafeCritical] [FriendAccessAllowed] internal TKey FindEquivalentKeyUnsafe(TKey key, out TValue value) { lock (_lock) { - for (int bucket = 0; bucket < _buckets.Length; ++bucket) - { - for (int entriesIndex = _buckets[bucket]; entriesIndex != -1; entriesIndex = _entries[entriesIndex].next) - { - object thisKey, thisValue; - _entries[entriesIndex].depHnd.GetPrimaryAndSecondary(out thisKey, out thisValue); - if (Object.Equals(thisKey, key)) - { - value = (TValue) thisValue; - return (TKey) thisKey; - } - } - } + return _container.FindEquivalentKeyUnsafe(key, out value); } - - value = default(TValue); - return null; } - + //-------------------------------------------------------------------------------------------- // Returns a collection of keys - don't use in perf critical path //-------------------------------------------------------------------------------------------- internal ICollection<TKey> Keys { - [System.Security.SecuritySafeCritical] get { - List<TKey> list = new List<TKey>(); lock (_lock) { - for (int bucket = 0; bucket < _buckets.Length; ++bucket) - { - for (int entriesIndex = _buckets[bucket]; entriesIndex != -1; entriesIndex = _entries[entriesIndex].next) - { - TKey thisKey = (TKey) _entries[entriesIndex].depHnd.GetPrimary(); - if (thisKey != null) - { - list.Add(thisKey); - } - } - } + return _container.Keys; } - - return list; } } @@ -348,332 +296,500 @@ namespace System.Runtime.CompilerServices //-------------------------------------------------------------------------------------------- internal ICollection<TValue> Values { - [System.Security.SecuritySafeCritical] get { - List<TValue> list = new List<TValue>(); lock (_lock) { - for (int bucket = 0; bucket < _buckets.Length; ++bucket) - { - for (int entriesIndex = _buckets[bucket]; entriesIndex != -1; entriesIndex = _entries[entriesIndex].next) - { - Object primary = null; - Object secondary = null; - - _entries[entriesIndex].depHnd.GetPrimaryAndSecondary(out primary, out secondary); - - // Now that we've secured a strong reference to the secondary, must check the primary again - // to ensure it didn't expire (otherwise, we open a race condition where TryGetValue misreports an - // expired key as a live key with a null value.) - if (primary != null) - { - list.Add((TValue)secondary); - } - } - } + return _container.Values; } - - return list; } } - + //-------------------------------------------------------------------------------------------- // Clear all the key/value pairs //-------------------------------------------------------------------------------------------- - [System.Security.SecuritySafeCritical] internal void Clear() { lock (_lock) { - // Clear the buckets - for (int bucketIndex = 0; bucketIndex < _buckets.Length; bucketIndex++) - { - _buckets[bucketIndex] = -1; - } - - // Clear the entries and link them backwards together as part of free list - int entriesIndex; - for (entriesIndex = 0; entriesIndex < _entries.Length; entriesIndex++) - { - if (_entries[entriesIndex].depHnd.IsAllocated) - { - _entries[entriesIndex].depHnd.Free(); - } - - // Link back wards as free list - _entries[entriesIndex].next = entriesIndex - 1; - } - - _freeList = entriesIndex - 1; - } + _container = new Container(this); + } } #endregion - + #region Private Members - [System.Security.SecurityCritical] + //---------------------------------------------------------------------------------------- - // Worker for finding a key/value pair + // Worker for adding a new key/value pair. + // Will resize the container if it is full // // Preconditions: // Must hold _lock. - // Key already validated as non-null + // Key already validated as non-null and not already in table. //---------------------------------------------------------------------------------------- - private bool TryGetValueWorker(TKey key, out TValue value) + private void CreateEntry(TKey key, TValue value) { - int entryIndex = FindEntry(key); - if (entryIndex != -1) + Debug.Assert(Monitor.IsEntered(_lock)); + + Container c = _container; + if (!c.HasCapacity) { - Object primary = null; - Object secondary = null; - _entries[entryIndex].depHnd.GetPrimaryAndSecondary(out primary, out secondary); - // Now that we've secured a strong reference to the secondary, must check the primary again - // to ensure it didn't expire (otherwise, we open a race condition where TryGetValue misreports an - // expired key as a live key with a null value.) - if (primary != null) - { - value = (TValue)secondary; - return true; - } + _container = c = c.Resize(); } + c.CreateEntryNoResize(key, value); + } + + private static bool IsPowerOfTwo(int value) => (value > 0) && ((value & (value - 1)) == 0); - value = default(TValue); - return false; + #endregion + + #region Private Data Members + //-------------------------------------------------------------------------------------------- + // Entry can be in one of four states: + // + // - Unused (stored with an index _firstFreeEntry and above) + // depHnd.IsAllocated == false + // hashCode == <dontcare> + // next == <dontcare>) + // + // - Used with live key (linked into a bucket list where _buckets[hashCode & (_buckets.Length - 1)] points to first entry) + // depHnd.IsAllocated == true, depHnd.GetPrimary() != null + // hashCode == RuntimeHelpers.GetHashCode(depHnd.GetPrimary()) & Int32.MaxValue + // next links to next Entry in bucket. + // + // - Used with dead key (linked into a bucket list where _buckets[hashCode & (_buckets.Length - 1)] points to first entry) + // depHnd.IsAllocated == true, depHnd.GetPrimary() == null + // hashCode == <notcare> + // next links to next Entry in bucket. + // + // - Has been removed from the table (by a call to Remove) + // depHnd.IsAllocated == true, depHnd.GetPrimary() == <notcare> + // hashCode == -1 + // next links to next Entry in bucket. + // + // The only difference between "used with live key" and "used with dead key" is that + // depHnd.GetPrimary() returns null. The transition from "used with live key" to "used with dead key" + // happens asynchronously as a result of normal garbage collection. The dictionary itself + // receives no notification when this happens. + // + // When the dictionary grows the _entries table, it scours it for expired keys and does not + // add those to the new container. + //-------------------------------------------------------------------------------------------- + private struct Entry + { + public DependentHandle depHnd; // Holds key and value using a weak reference for the key and a strong reference + // for the value that is traversed only if the key is reachable without going through the value. + public int HashCode; // Cached copy of key's hashcode + public int Next; // Index of next entry, -1 if last } - //---------------------------------------------------------------------------------------- - // Worker for adding a new key/value pair. // - // Preconditions: - // Must hold _lock. - // Key already validated as non-null and not already in table. - //---------------------------------------------------------------------------------------- - [System.Security.SecurityCritical] - private void CreateEntry(TKey key, TValue value) + // Container holds the actual data for the table. A given instance of Container always has the same capacity. When we need + // more capacity, we create a new Container, copy the old one into the new one, and discard the old one. This helps enable lock-free + // reads from the table, as readers never need to deal with motion of entries due to rehashing. + // + private sealed class Container { - if (_freeList == -1) + private readonly ConditionalWeakTable<TKey, TValue> _parent; // the ConditionalWeakTable with which this container is associated + private int[] _buckets; // _buckets[hashcode & (_buckets.Length - 1)] contains index of the first entry in bucket (-1 if empty) + private Entry[] _entries; // the table entries containing the stored dependency handles + private int _firstFreeEntry; // _firstFreeEntry < _entries.Length => table has capacity, entries grow from the bottom of the table. + private bool _invalid; // flag detects if OOM or other background exception threw us out of the lock. + private bool _finalized; // set to true when initially finalized + private volatile object _oldKeepAlive; // used to ensure the next allocated container isn't finalized until this one is GC'd + + internal Container(ConditionalWeakTable<TKey, TValue> parent) { - Resize(); + Debug.Assert(parent != null); + Debug.Assert(IsPowerOfTwo(InitialCapacity)); + + int size = InitialCapacity; + _buckets = new int[size]; + for (int i = 0; i < _buckets.Length; i++) + { + _buckets[i] = -1; + } + _entries = new Entry[size]; + + // Only store the parent after all of the allocations have happened successfully. + // Otherwise, as part of growing or clearing the container, we could end up allocating + // a new Container that fails (OOMs) part way through construction but that gets finalized + // and ends up clearing out some other container present in the associated CWT. + _parent = parent; } - int hashCode = RuntimeHelpers.GetHashCode(key) & Int32.MaxValue; - int bucket = hashCode % _buckets.Length; + private Container(ConditionalWeakTable<TKey, TValue> parent, int[] buckets, Entry[] entries, int firstFreeEntry) + { + Debug.Assert(parent != null); + Debug.Assert(buckets != null); + Debug.Assert(entries != null); + Debug.Assert(buckets.Length == entries.Length); + Debug.Assert(IsPowerOfTwo(buckets.Length)); + + _parent = parent; + _buckets = buckets; + _entries = entries; + _firstFreeEntry = firstFreeEntry; + } - int newEntry = _freeList; - _freeList = _entries[newEntry].next; + internal bool HasCapacity => _firstFreeEntry < _entries.Length; - _entries[newEntry].hashCode = hashCode; - _entries[newEntry].depHnd = new DependentHandle(key, value); - _entries[newEntry].next = _buckets[bucket]; + //---------------------------------------------------------------------------------------- + // Worker for adding a new key/value pair. + // Preconditions: + // Container must NOT be full + //---------------------------------------------------------------------------------------- + internal void CreateEntryNoResize(TKey key, TValue value) + { + Debug.Assert(HasCapacity); - _buckets[bucket] = newEntry; + VerifyIntegrity(); + _invalid = true; - } + int hashCode = RuntimeHelpers.GetHashCode(key) & int.MaxValue; + int newEntry = _firstFreeEntry++; - //---------------------------------------------------------------------------------------- - // This does two things: resize and scrub expired keys off bucket lists. - // - // Precondition: - // Must hold _lock. - // - // Postcondition: - // _freeList is non-empty on exit. - //---------------------------------------------------------------------------------------- - [System.Security.SecurityCritical] - private void Resize() - { - // Start by assuming we won't resize. - int newSize = _buckets.Length; + _entries[newEntry].HashCode = hashCode; + _entries[newEntry].depHnd = new DependentHandle(key, value); + int bucket = hashCode & (_buckets.Length - 1); + _entries[newEntry].Next = _buckets[bucket]; + + // This write must be volatile, as we may be racing with concurrent readers. If they see + // the new entry, they must also see all of the writes earlier in this method. + Volatile.Write(ref _buckets[bucket], newEntry); + + _invalid = false; + } - // If any expired keys exist, we won't resize. - bool hasExpiredEntries = false; - int entriesIndex; - for (entriesIndex = 0; entriesIndex < _entries.Length; entriesIndex++) + //---------------------------------------------------------------------------------------- + // Worker for finding a key/value pair + // + // Preconditions: + // Must hold _lock. + // Key already validated as non-null + //---------------------------------------------------------------------------------------- + internal bool TryGetValueWorker(TKey key, out TValue value) { - if ( _entries[entriesIndex].depHnd.IsAllocated && _entries[entriesIndex].depHnd.GetPrimary() == null) + object secondary; + int entryIndex = FindEntry(key, out secondary); + value = JitHelpers.UnsafeCast<TValue>(secondary); + return entryIndex != -1; + } + + //---------------------------------------------------------------------------------------- + // Returns -1 if not found (if key expires during FindEntry, this can be treated as "not found.") + // + // Preconditions: + // Must hold _lock, or be prepared to retry the search while holding _lock. + // Key already validated as non-null. + //---------------------------------------------------------------------------------------- + internal int FindEntry(TKey key, out object value) + { + int hashCode = RuntimeHelpers.GetHashCode(key) & int.MaxValue; + int bucket = hashCode & (_buckets.Length - 1); + for (int entriesIndex = Volatile.Read(ref _buckets[bucket]); entriesIndex != -1; entriesIndex = _entries[entriesIndex].Next) { - hasExpiredEntries = true; - break; + if (_entries[entriesIndex].HashCode == hashCode) + { + object primary, secondary; + _entries[entriesIndex].depHnd.GetPrimaryAndSecondary(out primary, out secondary); + if (primary == key) + { + GC.KeepAlive(this); // ensure we don't get finalized while accessing DependentHandles. + value = secondary; + return entriesIndex; + } + } } + + GC.KeepAlive(this); // ensure we don't get finalized while accessing DependentHandles. + value = null; + return -1; } - if (!hasExpiredEntries) + internal bool Remove(TKey key) { - newSize = System.Collections.HashHelpers.GetPrime(_buckets.Length == 0 ? _initialCapacity + 1 : _buckets.Length * 2); + VerifyIntegrity(); + + object value; + int entryIndex = FindEntry(key, out value); + if (entryIndex != -1) + { + ref Entry entry = ref _entries[entryIndex]; + + // We do not free the handle here, as we may be racing with readers who already saw the hash code. + // Instead, we simply overwrite the entry's hash code, so subsequent reads will ignore it. + // The handle will be free'd in Container's finalizer, after the table is resized or discarded. + Volatile.Write(ref entry.HashCode, -1); + + // Also, clear the key to allow GC to collect objects pointed to by the entry + entry.depHnd.SetPrimary(null); + + return true; + } + + return false; } - // Reallocate both buckets and entries and rebuild the bucket and freelists from scratch. - // This serves both to scrub entries with expired keys and to put the new entries in the proper bucket. - int newFreeList = -1; - int[] newBuckets = new int[newSize]; - for (int bucketIndex = 0; bucketIndex < newSize; bucketIndex++) + internal void UpdateValue(int entryIndex, TValue newValue) { - newBuckets[bucketIndex] = -1; + Debug.Assert(entryIndex != -1); + + VerifyIntegrity(); + _invalid = true; + + _entries[entryIndex].depHnd.SetSecondary(newValue); + + _invalid = false; } - Entry[] newEntries = new Entry[newSize]; - // Migrate existing entries to the new table. - for (entriesIndex = 0; entriesIndex < _entries.Length; entriesIndex++) + //---------------------------------------------------------------------------------------- + // This does two things: resize and scrub expired keys off bucket lists. + // + // Precondition: + // Must hold _lock. + // + // Postcondition: + // _firstEntry is less than _entries.Length on exit, that is, the table has at least one free entry. + //---------------------------------------------------------------------------------------- + internal Container Resize() { - DependentHandle depHnd = _entries[entriesIndex].depHnd; - if (depHnd.IsAllocated && depHnd.GetPrimary() != null) + // Start by assuming we won't resize. + int newSize = _buckets.Length; + + // If any expired or removed keys exist, we won't resize. + bool hasExpiredEntries = false; + for (int entriesIndex = 0; entriesIndex < _entries.Length; entriesIndex++) { - // Entry is used and has not expired. Link it into the appropriate bucket list. - int bucket = _entries[entriesIndex].hashCode % newSize; - newEntries[entriesIndex].depHnd = depHnd; - newEntries[entriesIndex].hashCode = _entries[entriesIndex].hashCode; - newEntries[entriesIndex].next = newBuckets[bucket]; - newBuckets[bucket] = entriesIndex; + if (_entries[entriesIndex].HashCode == -1) + { + // the entry was removed + hasExpiredEntries = true; + break; + } + + if (_entries[entriesIndex].depHnd.IsAllocated && _entries[entriesIndex].depHnd.GetPrimary() == null) + { + // the entry has expired + hasExpiredEntries = true; + break; + } } - else + + if (!hasExpiredEntries) { - // Entry has either expired or was on the freelist to begin with. Either way - // insert it on the new freelist. - _entries[entriesIndex].depHnd.Free(); - newEntries[entriesIndex].depHnd = new DependentHandle(); - newEntries[entriesIndex].next = newFreeList; - newFreeList = entriesIndex; + // Not necessary to check for overflow here, the attempt to allocate new arrays will throw + newSize = _buckets.Length * 2; } + + return Resize(newSize); } - // Add remaining entries to freelist. - while (entriesIndex != newEntries.Length) + internal Container Resize(int newSize) { - newEntries[entriesIndex].depHnd = new DependentHandle(); - newEntries[entriesIndex].next = newFreeList; - newFreeList = entriesIndex; - entriesIndex++; - } + Debug.Assert(IsPowerOfTwo(newSize)); - _buckets = newBuckets; - _entries = newEntries; - _freeList = newFreeList; - } + // Reallocate both buckets and entries and rebuild the bucket and entries from scratch. + // This serves both to scrub entries with expired keys and to put the new entries in the proper bucket. + int[] newBuckets = new int[newSize]; + for (int bucketIndex = 0; bucketIndex < newSize; bucketIndex++) + { + newBuckets[bucketIndex] = -1; + } + Entry[] newEntries = new Entry[newSize]; + int newEntriesIndex = 0; - //---------------------------------------------------------------------------------------- - // Returns -1 if not found (if key expires during FindEntry, this can be treated as "not found.") - // - // Preconditions: - // Must hold _lock. - // Key already validated as non-null. - //---------------------------------------------------------------------------------------- - [System.Security.SecurityCritical] - private int FindEntry(TKey key) - { - int hashCode = RuntimeHelpers.GetHashCode(key) & Int32.MaxValue; - for (int entriesIndex = _buckets[hashCode % _buckets.Length]; entriesIndex != -1; entriesIndex = _entries[entriesIndex].next) + // Migrate existing entries to the new table. + for (int entriesIndex = 0; entriesIndex < _entries.Length; entriesIndex++) + { + int hashCode = _entries[entriesIndex].HashCode; + DependentHandle depHnd = _entries[entriesIndex].depHnd; + if (hashCode != -1 && depHnd.IsAllocated) + { + if (depHnd.GetPrimary() != null) + { + // Entry is used and has not expired. Link it into the appropriate bucket list. + newEntries[newEntriesIndex].HashCode = hashCode; + newEntries[newEntriesIndex].depHnd = depHnd; + int bucket = hashCode & (newBuckets.Length - 1); + newEntries[newEntriesIndex].Next = newBuckets[bucket]; + newBuckets[bucket] = newEntriesIndex; + newEntriesIndex++; + } + else + { + // Pretend the item was removed, so that this container's finalizer + // will clean up this dependent handle. + Volatile.Write(ref _entries[entriesIndex].HashCode, -1); + } + } + } + + // Create the new container. We want to transfer the responsibility of freeing the handles from + // the old container to the new container, and also ensure that the new container isn't finalized + // while the old container may still be in use. As such, we store a reference from the old container + // to the new one, which will keep the new container alive as long as the old one is. + var newContainer = new Container(_parent, newBuckets, newEntries, newEntriesIndex); + _oldKeepAlive = newContainer; // once this is set, the old container's finalizer will not free transferred dependent handles + + GC.KeepAlive(this); // ensure we don't get finalized while accessing DependentHandles. + + return newContainer; + } + + internal ICollection<TKey> Keys { - if (_entries[entriesIndex].hashCode == hashCode && _entries[entriesIndex].depHnd.GetPrimary() == key) + get { - return entriesIndex; + var list = new List<TKey>(); + + for (int bucket = 0; bucket < _buckets.Length; ++bucket) + { + for (int entriesIndex = _buckets[bucket]; entriesIndex != -1; entriesIndex = _entries[entriesIndex].Next) + { + TKey thisKey = JitHelpers.UnsafeCast<TKey>(_entries[entriesIndex].depHnd.GetPrimary()); + if (thisKey != null) + { + list.Add(thisKey); + } + } + } + + GC.KeepAlive(this); // ensure we don't get finalized while accessing DependentHandles. + return list; } } - return -1; - } - //---------------------------------------------------------------------------------------- - // Precondition: - // Must hold _lock. - //---------------------------------------------------------------------------------------- - private void VerifyIntegrity() - { - if (_invalid) + internal ICollection<TValue> Values { - throw new InvalidOperationException(Environment.GetResourceString("CollectionCorrupted")); + get + { + var list = new List<TValue>(); + + for (int bucket = 0; bucket < _buckets.Length; ++bucket) + { + for (int entriesIndex = _buckets[bucket]; entriesIndex != -1; entriesIndex = _entries[entriesIndex].Next) + { + object primary = null, secondary = null; + _entries[entriesIndex].depHnd.GetPrimaryAndSecondary(out primary, out secondary); + + // Now that we've secured a strong reference to the secondary, must check the primary again + // to ensure it didn't expire (otherwise, we open a race where TryGetValue misreports an + // expired key as a live key with a null value.) + if (primary != null) + { + list.Add(JitHelpers.UnsafeCast<TValue>(secondary)); + } + } + } + + GC.KeepAlive(this); // ensure we don't get finalized while accessing DependentHandles. + return list; + } } - } - //---------------------------------------------------------------------------------------- - // Finalizer. - //---------------------------------------------------------------------------------------- - [System.Security.SecuritySafeCritical] - ~ConditionalWeakTable() - { + internal TKey FindEquivalentKeyUnsafe(TKey key, out TValue value) + { + for (int bucket = 0; bucket < _buckets.Length; ++bucket) + { + for (int entriesIndex = _buckets[bucket]; entriesIndex != -1; entriesIndex = _entries[entriesIndex].Next) + { + if (_entries[entriesIndex].HashCode == -1) + { + continue; // removed entry whose handle is awaiting condemnation by the finalizer. + } - // We're just freeing per-appdomain unmanaged handles here. If we're already shutting down the AD, - // don't bother. - // - // (Despite its name, Environment.HasShutdownStart also returns true if the current AD is finalizing.) - if (Environment.HasShutdownStarted) + object thisKey, thisValue; + _entries[entriesIndex].depHnd.GetPrimaryAndSecondary(out thisKey, out thisValue); + if (Equals(thisKey, key)) + { + GC.KeepAlive(this); // ensure we don't get finalized while accessing DependentHandles. + value = JitHelpers.UnsafeCast<TValue>(thisValue); + return JitHelpers.UnsafeCast<TKey>(thisKey); + } + } + } + + GC.KeepAlive(this); // ensure we don't get finalized while accessing DependentHandles. + value = default(TValue); + return null; + } + + //---------------------------------------------------------------------------------------- + // Precondition: + // Must hold _lock. + //---------------------------------------------------------------------------------------- + private void VerifyIntegrity() { - return; + if (_invalid) + { + throw new InvalidOperationException(Environment.GetResourceString("CollectionCorrupted")); + } } - if (_lock != null) + //---------------------------------------------------------------------------------------- + // Finalizer. + //---------------------------------------------------------------------------------------- + ~Container() { - lock(_lock) + // We're just freeing per-appdomain unmanaged handles here. If we're already shutting down the AD, + // don't bother. (Despite its name, Environment.HasShutdownStart also returns true if the current + // AD is finalizing.) We also skip doing anything if the container is invalid, including if someone + // the container object was allocated but its associated table never set. + if (Environment.HasShutdownStarted || _invalid || _parent == null) { - if (_invalid) + return; + } + + // It's possible that the ConditionalWeakTable could have been resurrected, in which case code could + // be accessing this Container as it's being finalized. We don't support usage after finalization, + // but we also don't want to potentially corrupt state by allowing dependency handles to be used as + // or after they've been freed. To avoid that, if it's at all possible that another thread has a + // reference to this container via the CWT, we remove such a reference and then re-register for + // finalization: the next time around, we can be sure that no references remain to this and we can + // clean up the dependency handles without fear of corruption. + if (!_finalized) + { + _finalized = true; + lock (_parent._lock) { - return; + if (_parent._container == this) + { + _parent._container = null; + } } - Entry[] entries = _entries; + GC.ReRegisterForFinalize(this); // next time it's finalized, we'll be sure there are no remaining refs + return; + } - // Make sure anyone sneaking into the table post-resurrection - // gets booted before they can damage the native handle table. - _invalid = true; - _entries = null; - _buckets = null; + Entry[] entries = _entries; + _invalid = true; + _entries = null; + _buckets = null; + if (entries != null) + { for (int entriesIndex = 0; entriesIndex < entries.Length; entriesIndex++) { - entries[entriesIndex].depHnd.Free(); + // We need to free handles in two cases: + // - If this container still owns the dependency handle (meaning ownership hasn't been transferred + // to another container that replaced this one), then it should be freed. + // - If this container had the entry removed, then even if in general ownership was transferred to + // another container, removed entries are not, therefore this container must free them. + if (_oldKeepAlive == null || entries[entriesIndex].HashCode == -1) + { + entries[entriesIndex].depHnd.Free(); + } } } } } #endregion - - #region Private Data Members - //-------------------------------------------------------------------------------------------- - // Entry can be in one of three states: - // - // - Linked into the freeList (_freeList points to first entry) - // depHnd.IsAllocated == false - // hashCode == <dontcare> - // next links to next Entry on freelist) - // - // - Used with live key (linked into a bucket list where _buckets[hashCode % _buckets.Length] points to first entry) - // depHnd.IsAllocated == true, depHnd.GetPrimary() != null - // hashCode == RuntimeHelpers.GetHashCode(depHnd.GetPrimary()) & Int32.MaxValue - // next links to next Entry in bucket. - // - // - Used with dead key (linked into a bucket list where _buckets[hashCode % _buckets.Length] points to first entry) - // depHnd.IsAllocated == true, depHnd.GetPrimary() == null - // hashCode == <notcare> - // next links to next Entry in bucket. - // - // The only difference between "used with live key" and "used with dead key" is that - // depHnd.GetPrimary() returns null. The transition from "used with live key" to "used with dead key" - // happens asynchronously as a result of normal garbage collection. The dictionary itself - // receives no notification when this happens. - // - // When the dictionary grows the _entries table, it scours it for expired keys and puts those - // entries back on the freelist. - //-------------------------------------------------------------------------------------------- - private struct Entry - { - public DependentHandle depHnd; // Holds key and value using a weak reference for the key and a strong reference - // for the value that is traversed only if the key is reachable without going through the value. - public int hashCode; // Cached copy of key's hashcode - public int next; // Index of next entry, -1 if last - } - - private int[] _buckets; // _buckets[hashcode & _buckets.Length] contains index of first entry in bucket (-1 if empty) - private Entry[] _entries; - private int _freeList; // -1 = empty, else index of first unused Entry - private const int _initialCapacity = 5; - private readonly Object _lock; // this could be a ReaderWriterLock but CoreCLR does not support RWLocks. - private bool _invalid; // flag detects if OOM or other background exception threw us out of the lock. - #endregion } #endregion - - - #region DependentHandle //========================================================================================= // This struct collects all operations on native DependentHandles. The DependentHandle @@ -700,15 +816,10 @@ namespace System.Runtime.CompilerServices // to use DependentHandles in a thread-safe way. //========================================================================================= [ComVisible(false)] - struct DependentHandle + internal struct DependentHandle { #region Constructors - #if FEATURE_CORECLR - [System.Security.SecuritySafeCritical] // auto-generated - #else - [System.Security.SecurityCritical] - #endif - public DependentHandle(Object primary, Object secondary) + public DependentHandle(object primary, object secondary) { IntPtr handle = (IntPtr)0; nInitialize(primary, secondary, out handle); @@ -718,44 +829,37 @@ namespace System.Runtime.CompilerServices #endregion #region Public Members - public bool IsAllocated - { - get - { - return _handle != (IntPtr)0; - } - } + public bool IsAllocated => _handle != IntPtr.Zero; // Getting the secondary object is more expensive than getting the first so // we provide a separate primary-only accessor for those times we only want the // primary. - #if FEATURE_CORECLR - [System.Security.SecuritySafeCritical] // auto-generated - #else - [System.Security.SecurityCritical] - #endif - public Object GetPrimary() + public object GetPrimary() { - Object primary; + object primary; nGetPrimary(_handle, out primary); return primary; } - #if FEATURE_CORECLR - [System.Security.SecuritySafeCritical] // auto-generated - #else - [System.Security.SecurityCritical] - #endif - public void GetPrimaryAndSecondary(out Object primary, out Object secondary) + public void GetPrimaryAndSecondary(out object primary, out object secondary) { nGetPrimaryAndSecondary(_handle, out primary, out secondary); } + public void SetPrimary(object primary) + { + nSetPrimary(_handle, primary); + } + + public void SetSecondary(object secondary) + { + nSetSecondary(_handle, secondary); + } + //---------------------------------------------------------------------- // Forces dependentHandle back to non-allocated state (if not already there) // and frees the handle if needed. //---------------------------------------------------------------------- - [System.Security.SecurityCritical] public void Free() { if (_handle != (IntPtr)0) @@ -768,20 +872,22 @@ namespace System.Runtime.CompilerServices #endregion #region Private Members - [System.Security.SecurityCritical] - [MethodImplAttribute(MethodImplOptions.InternalCall)] - private static extern void nInitialize(Object primary, Object secondary, out IntPtr dependentHandle); + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void nInitialize(object primary, object secondary, out IntPtr dependentHandle); + + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void nGetPrimary(IntPtr dependentHandle, out object primary); - [System.Security.SecurityCritical] - [MethodImplAttribute(MethodImplOptions.InternalCall)] - private static extern void nGetPrimary(IntPtr dependentHandle, out Object primary); + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void nGetPrimaryAndSecondary(IntPtr dependentHandle, out object primary, out object secondary); - [System.Security.SecurityCritical] - [MethodImplAttribute(MethodImplOptions.InternalCall)] - private static extern void nGetPrimaryAndSecondary(IntPtr dependentHandle, out Object primary, out Object secondary); + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void nSetPrimary(IntPtr dependentHandle, object primary); - [System.Security.SecurityCritical] - [MethodImplAttribute(MethodImplOptions.InternalCall)] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void nSetSecondary(IntPtr dependentHandle, object secondary); + + [MethodImpl(MethodImplOptions.InternalCall)] private static extern void nFree(IntPtr dependentHandle); #endregion @@ -792,4 +898,3 @@ namespace System.Runtime.CompilerServices } // struct DependentHandle #endregion } - diff --git a/src/mscorlib/src/System/Runtime/CompilerServices/DecimalConstantAttribute.cs b/src/mscorlib/src/System/Runtime/CompilerServices/DecimalConstantAttribute.cs index 39a4c86b72..7bfaa7aafd 100644 --- a/src/mscorlib/src/System/Runtime/CompilerServices/DecimalConstantAttribute.cs +++ b/src/mscorlib/src/System/Runtime/CompilerServices/DecimalConstantAttribute.cs @@ -6,6 +6,7 @@ // Note: If you add a new ctor overloads you need to update ParameterInfo.RawDefaultValue using System.Reflection; +using System.Diagnostics; using System.Diagnostics.Contracts; using System.Collections.Generic; @@ -57,16 +58,16 @@ namespace System.Runtime.CompilerServices if (namedArgument.MemberInfo.Name.Equals("Value")) { // This is not possible because Decimal cannot be represented directly in the metadata. - Contract.Assert(false, "Decimal cannot be represented directly in the metadata."); + Debug.Assert(false, "Decimal cannot be represented directly in the metadata."); return (Decimal)namedArgument.TypedValue.Value; } } ParameterInfo[] parameters = attr.Constructor.GetParameters(); - Contract.Assert(parameters.Length == 5); + Debug.Assert(parameters.Length == 5); System.Collections.Generic.IList<CustomAttributeTypedArgument> args = attr.ConstructorArguments; - Contract.Assert(args.Count == 5); + Debug.Assert(args.Count == 5); if (parameters[2].ParameterType == typeof(uint)) { diff --git a/src/mscorlib/src/System/Runtime/CompilerServices/FormattableStringFactory.cs b/src/mscorlib/src/System/Runtime/CompilerServices/FormattableStringFactory.cs index aee3bc2230..4b99a8a5d9 100644 --- a/src/mscorlib/src/System/Runtime/CompilerServices/FormattableStringFactory.cs +++ b/src/mscorlib/src/System/Runtime/CompilerServices/FormattableStringFactory.cs @@ -26,12 +26,12 @@ namespace System.Runtime.CompilerServices { if (format == null) { - throw new ArgumentNullException("format"); + throw new ArgumentNullException(nameof(format)); } if (arguments == null) { - throw new ArgumentNullException("arguments"); + throw new ArgumentNullException(nameof(arguments)); } return new ConcreteFormattableString(format, arguments); diff --git a/src/mscorlib/src/System/Runtime/CompilerServices/HasCopySemanticsAttribute.cs b/src/mscorlib/src/System/Runtime/CompilerServices/HasCopySemanticsAttribute.cs deleted file mode 100644 index 944a2868f2..0000000000 --- a/src/mscorlib/src/System/Runtime/CompilerServices/HasCopySemanticsAttribute.cs +++ /dev/null @@ -1,14 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -namespace System.Runtime.CompilerServices -{ -[Serializable] -[AttributeUsage(AttributeTargets.Struct)] - public sealed class HasCopySemanticsAttribute : Attribute - { - public HasCopySemanticsAttribute() - {} - } -} diff --git a/src/mscorlib/src/System/Runtime/CompilerServices/IDispatchConstantAttribute.cs b/src/mscorlib/src/System/Runtime/CompilerServices/IDispatchConstantAttribute.cs deleted file mode 100644 index d6dfcbbbb9..0000000000 --- a/src/mscorlib/src/System/Runtime/CompilerServices/IDispatchConstantAttribute.cs +++ /dev/null @@ -1,26 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System.Runtime.InteropServices; - -namespace System.Runtime.CompilerServices -{ -[Serializable] -[AttributeUsage(AttributeTargets.Field | AttributeTargets.Parameter, Inherited=false)] -[System.Runtime.InteropServices.ComVisible(true)] - public sealed class IDispatchConstantAttribute : CustomConstantAttribute - { - public IDispatchConstantAttribute() - { - } - - public override Object Value - { - get - { - return new DispatchWrapper(null); - } - } - } -} diff --git a/src/mscorlib/src/System/Runtime/CompilerServices/INotifyCompletion.cs b/src/mscorlib/src/System/Runtime/CompilerServices/INotifyCompletion.cs index 872a79b72b..aba0a0691f 100644 --- a/src/mscorlib/src/System/Runtime/CompilerServices/INotifyCompletion.cs +++ b/src/mscorlib/src/System/Runtime/CompilerServices/INotifyCompletion.cs @@ -34,7 +34,6 @@ namespace System.Runtime.CompilerServices /// <param name="continuation">The action to invoke when the operation completes.</param> /// <exception cref="System.ArgumentNullException">The <paramref name="continuation"/> argument is null (Nothing in Visual Basic).</exception> /// <remarks>Unlike OnCompleted, UnsafeOnCompleted need not propagate ExecutionContext information.</remarks> - [SecurityCritical] void UnsafeOnCompleted(Action continuation); } } diff --git a/src/mscorlib/src/System/Runtime/CompilerServices/IUnknownConstantAttribute.cs b/src/mscorlib/src/System/Runtime/CompilerServices/IUnknownConstantAttribute.cs deleted file mode 100644 index f8717cff52..0000000000 --- a/src/mscorlib/src/System/Runtime/CompilerServices/IUnknownConstantAttribute.cs +++ /dev/null @@ -1,27 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System.Runtime.InteropServices; - -namespace System.Runtime.CompilerServices -{ -[Serializable] -[AttributeUsage(AttributeTargets.Field | AttributeTargets.Parameter, Inherited=false)] -[System.Runtime.InteropServices.ComVisible(true)] - public sealed class IUnknownConstantAttribute : CustomConstantAttribute - { - public IUnknownConstantAttribute() - { - } - - public override Object Value - { - get - { - return new UnknownWrapper(null); - } - } - - } -} diff --git a/src/mscorlib/src/System/Runtime/CompilerServices/IsBoxed.cs b/src/mscorlib/src/System/Runtime/CompilerServices/IsBoxed.cs deleted file mode 100644 index 8b6691c09d..0000000000 --- a/src/mscorlib/src/System/Runtime/CompilerServices/IsBoxed.cs +++ /dev/null @@ -1,11 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -namespace System.Runtime.CompilerServices -{ - // Indicates that the modified reference type is a boxed valuetype - public static class IsBoxed - { - } -} diff --git a/src/mscorlib/src/System/Runtime/CompilerServices/IsByValue.cs b/src/mscorlib/src/System/Runtime/CompilerServices/IsByValue.cs deleted file mode 100644 index d16a853597..0000000000 --- a/src/mscorlib/src/System/Runtime/CompilerServices/IsByValue.cs +++ /dev/null @@ -1,11 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -namespace System.Runtime.CompilerServices -{ - // Indicates that the modified method argument is passed by value - public static class IsByValue - { - } -} diff --git a/src/mscorlib/src/System/Runtime/CompilerServices/IsConst.cs b/src/mscorlib/src/System/Runtime/CompilerServices/IsConst.cs deleted file mode 100644 index 210e5997a7..0000000000 --- a/src/mscorlib/src/System/Runtime/CompilerServices/IsConst.cs +++ /dev/null @@ -1,11 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -namespace System.Runtime.CompilerServices -{ - // Indicates that the modified type is const (i.e. has a const modifier) - public static class IsConst - { - } -} diff --git a/src/mscorlib/src/System/Runtime/CompilerServices/IsCopyConstructed.cs b/src/mscorlib/src/System/Runtime/CompilerServices/IsCopyConstructed.cs deleted file mode 100644 index ee40ee7b02..0000000000 --- a/src/mscorlib/src/System/Runtime/CompilerServices/IsCopyConstructed.cs +++ /dev/null @@ -1,11 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -namespace System.Runtime.CompilerServices -{ - [System.Runtime.InteropServices.ComVisible(true)] - public static class IsCopyConstructed - {} -} - diff --git a/src/mscorlib/src/System/Runtime/CompilerServices/IsExplicitlyDereferenced.cs b/src/mscorlib/src/System/Runtime/CompilerServices/IsExplicitlyDereferenced.cs deleted file mode 100644 index 480a62175d..0000000000 --- a/src/mscorlib/src/System/Runtime/CompilerServices/IsExplicitlyDereferenced.cs +++ /dev/null @@ -1,22 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -namespace System.Runtime.CompilerServices -{ - // Consider the following C++ method prototypes: - // 1) int foo(int ^arg); - // 2) int foo(int &arg); - // - // Both of these methods will have a .NET type signature that looks the - // same, but when importing a method from a metadata scope, the compiler - // needs to know what the calling syntax should be. This modopt and its - // partner "IsImplicitlyDereferenced" disambiguate reference versus - // pointer arguments. - // - // Indicates that the modified GC reference represents a pointer in a - // method signature. - public static class IsExplicitlyDereferenced - { - } -} diff --git a/src/mscorlib/src/System/Runtime/CompilerServices/IsImplicitlyDereferenced.cs b/src/mscorlib/src/System/Runtime/CompilerServices/IsImplicitlyDereferenced.cs deleted file mode 100644 index ea81cb8ec5..0000000000 --- a/src/mscorlib/src/System/Runtime/CompilerServices/IsImplicitlyDereferenced.cs +++ /dev/null @@ -1,22 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -namespace System.Runtime.CompilerServices -{ - // Consider the following C++ method prototypes: - // 1) int foo(int ^arg); - // 2) int foo(int &arg); - // - // Both of these methods will have a .NET type signature that looks the - // same, but when importing a method from a metadata scope, the compiler - // needs to know what the calling syntax should be. This modopt and its - // partner "IsExplicitlyDereferenced" disambiguate reference versus - // pointer arguments. - // - // Indicates that the modified GC reference represents a reference in a - // method signature. - public static class IsImplicitlyDereferenced - { - } -} diff --git a/src/mscorlib/src/System/Runtime/CompilerServices/IsJitIntrinsic.cs b/src/mscorlib/src/System/Runtime/CompilerServices/IsJitIntrinsic.cs deleted file mode 100644 index 013e50f3ea..0000000000 --- a/src/mscorlib/src/System/Runtime/CompilerServices/IsJitIntrinsic.cs +++ /dev/null @@ -1,12 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -namespace System.Runtime.CompilerServices -{ - // Indicates that the modified method is an intrinsic for which the JIT - // can perform special code generation. - public static class IsJitIntrinsic - { - } -} diff --git a/src/mscorlib/src/System/Runtime/CompilerServices/IsLong.cs b/src/mscorlib/src/System/Runtime/CompilerServices/IsLong.cs deleted file mode 100644 index e8bebfb2d3..0000000000 --- a/src/mscorlib/src/System/Runtime/CompilerServices/IsLong.cs +++ /dev/null @@ -1,18 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -namespace System.Runtime.CompilerServices -{ - // The C++ standard indicates that a long is always 4-bytes, whereas the - // size of an integer is system dependent (not exceedign sizeof(long)). - // The CLR does not offer a mechanism for encoding this distinction, - // but it is critically important for maintaining language level type - // safety. - // - // Indicates that the modified integer is a standard C++ long. - // Could also be called IsAlternateIntegerType or something else. - public static class IsLong - { - } -} diff --git a/src/mscorlib/src/System/Runtime/CompilerServices/IsPinned.cs b/src/mscorlib/src/System/Runtime/CompilerServices/IsPinned.cs deleted file mode 100644 index e796d1a1e7..0000000000 --- a/src/mscorlib/src/System/Runtime/CompilerServices/IsPinned.cs +++ /dev/null @@ -1,11 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -namespace System.Runtime.CompilerServices -{ - // Indicates that the modified instance is pinned in memory. - public static class IsPinned - { - } -} diff --git a/src/mscorlib/src/System/Runtime/CompilerServices/IsSignUnspecifiedByte.cs b/src/mscorlib/src/System/Runtime/CompilerServices/IsSignUnspecifiedByte.cs deleted file mode 100644 index e68f4d7751..0000000000 --- a/src/mscorlib/src/System/Runtime/CompilerServices/IsSignUnspecifiedByte.cs +++ /dev/null @@ -1,16 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -namespace System.Runtime.CompilerServices -{ - // C++ recognizes three char types: signed char, unsigned char, and char. - // When a char is neither signed nor unsigned, it is a char. - // This modopt indicates that the modified instance is a char. - // - // Any compiler could use this to indicate that the user has not specified - // Sign behavior for the given byte. - public static class IsSignUnspecifiedByte - { - } -} diff --git a/src/mscorlib/src/System/Runtime/CompilerServices/IsUdtReturn.cs b/src/mscorlib/src/System/Runtime/CompilerServices/IsUdtReturn.cs deleted file mode 100644 index dd85914b53..0000000000 --- a/src/mscorlib/src/System/Runtime/CompilerServices/IsUdtReturn.cs +++ /dev/null @@ -1,11 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -namespace System.Runtime.CompilerServices -{ - // Indicates that the return type is a user defined type - public static class IsUdtReturn - { - } -} diff --git a/src/mscorlib/src/System/Runtime/CompilerServices/NativeCppClassAttribute.cs b/src/mscorlib/src/System/Runtime/CompilerServices/NativeCppClassAttribute.cs deleted file mode 100644 index 0d6c759d76..0000000000 --- a/src/mscorlib/src/System/Runtime/CompilerServices/NativeCppClassAttribute.cs +++ /dev/null @@ -1,16 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System; -using System.Runtime.InteropServices; - -namespace System.Runtime.CompilerServices { -[Serializable] -[AttributeUsage(AttributeTargets.Struct, Inherited = true), - System.Runtime.InteropServices.ComVisible(true)] - public sealed class NativeCppClassAttribute : Attribute - { - public NativeCppClassAttribute () {} - } -} diff --git a/src/mscorlib/src/System/Runtime/CompilerServices/RequiredAttributeAttribute.cs b/src/mscorlib/src/System/Runtime/CompilerServices/RequiredAttributeAttribute.cs deleted file mode 100644 index f363696ebd..0000000000 --- a/src/mscorlib/src/System/Runtime/CompilerServices/RequiredAttributeAttribute.cs +++ /dev/null @@ -1,26 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System; - -namespace System.Runtime.CompilerServices -{ -[Serializable] -[AttributeUsage (AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Enum | AttributeTargets.Interface, - AllowMultiple=true, Inherited=false)] -[System.Runtime.InteropServices.ComVisible(true)] - public sealed class RequiredAttributeAttribute : Attribute - { - private Type requiredContract; - - public RequiredAttributeAttribute (Type requiredContract) - { - this.requiredContract= requiredContract; - } - public Type RequiredContract - { - get { return this.requiredContract; } - } - } -} diff --git a/src/mscorlib/src/System/Runtime/CompilerServices/RuntimeHelpers.cs b/src/mscorlib/src/System/Runtime/CompilerServices/RuntimeHelpers.cs index d20fe0bffd..926eb6c3cb 100644 --- a/src/mscorlib/src/System/Runtime/CompilerServices/RuntimeHelpers.cs +++ b/src/mscorlib/src/System/Runtime/CompilerServices/RuntimeHelpers.cs @@ -25,16 +25,13 @@ namespace System.Runtime.CompilerServices { public static class RuntimeHelpers { -#if FEATURE_CORECLR // Exposed here as a more appropriate place than on FormatterServices itself, // which is a high level reflection heavy type. public static Object GetUninitializedObject(Type type) { return FormatterServices.GetUninitializedObject(type); } -#endif // FEATURE_CORECLR - [System.Security.SecuritySafeCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.InternalCall)] public static extern void InitializeArray(Array array,RuntimeFieldHandle fldHandle); @@ -51,7 +48,6 @@ namespace System.Runtime.CompilerServices { // cloned when you pass them around, and are always passed by value. // Of course, reference types are not cloned. // - [System.Security.SecuritySafeCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.InternalCall)] public static extern Object GetObjectValue(Object obj); @@ -63,7 +59,6 @@ namespace System.Runtime.CompilerServices { // This call will generate an exception if the specified class constructor threw an // exception when it ran. - [System.Security.SecuritySafeCritical] [MethodImplAttribute(MethodImplOptions.InternalCall)] private static extern void _RunClassConstructor(RuntimeType type); @@ -80,7 +75,6 @@ namespace System.Runtime.CompilerServices { // This call will generate an exception if the specified module constructor threw an // exception when it ran. - [System.Security.SecuritySafeCritical] [MethodImplAttribute(MethodImplOptions.InternalCall)] private static extern void _RunModuleConstructor(System.Reflection.RuntimeModule module); @@ -89,72 +83,25 @@ namespace System.Runtime.CompilerServices { _RunModuleConstructor(module.GetRuntimeModule()); } - [System.Security.SecurityCritical] // auto-generated - [MethodImplAttribute(MethodImplOptions.InternalCall)] - private static unsafe extern void _PrepareMethod(IRuntimeMethodInfo method, IntPtr* pInstantiation, int cInstantiation); - [System.Security.SecurityCritical] // auto-generated [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode), SuppressUnmanagedCodeSecurity] internal static extern void _CompileMethod(IRuntimeMethodInfo method); - // Simple (instantiation not required) method. - [System.Security.SecurityCritical] // auto-generated_required - public static void PrepareMethod(RuntimeMethodHandle method) + public static void PrepareMethod(RuntimeMethodHandle method){} + public static void PrepareMethod(RuntimeMethodHandle method, RuntimeTypeHandle[] instantiation){} + public static void PrepareContractedDelegate(Delegate d){} + + public static void PrepareDelegate(Delegate d) { - unsafe + if (d == null) { - _PrepareMethod(method.GetMethodInfo(), null, 0); + throw new ArgumentNullException ("d"); } } - // Generic method or method with generic class with specific instantiation. - [System.Security.SecurityCritical] // auto-generated_required - public static void PrepareMethod(RuntimeMethodHandle method, RuntimeTypeHandle[] instantiation) - { - unsafe - { - int length; - IntPtr[] instantiationHandles = RuntimeTypeHandle.CopyRuntimeTypeHandles(instantiation, out length); - fixed (IntPtr* pInstantiation = instantiationHandles) - { - _PrepareMethod(method.GetMethodInfo(), pInstantiation, length); - GC.KeepAlive(instantiation); - } - } - } - - // This method triggers a given delegate to be prepared. This involves preparing the - // delegate's Invoke method and preparing the target of that Invoke. In the case of - // a multi-cast delegate, we rely on the fact that each individual component was prepared - // prior to the Combine. In other words, this service does not navigate through the - // entire multicasting list. - // If our own reliable event sinks perform the Combine (for example AppDomain.DomainUnload), - // then the result is fully prepared. But if a client calls Combine himself and then - // then adds that combination to e.g. AppDomain.DomainUnload, then the client is responsible - // for his own preparation. - [System.Security.SecurityCritical] // auto-generated_required - [MethodImplAttribute(MethodImplOptions.InternalCall)] - public static extern void PrepareDelegate(Delegate d); - - // See comment above for PrepareDelegate - // - // PrepareContractedDelegate weakens this a bit by only assuring that we prepare - // delegates which also have a ReliabilityContract. This is useful for services that - // want to provide opt-in reliability, generally some random event sink providing - // always reliable semantics to random event handlers that are likely to have not - // been written with relability in mind is a lost cause anyway. - // - // NOTE: that for the NGen case you can sidestep the required ReliabilityContract - // by using the [PrePrepareMethod] attribute. - [System.Security.SecurityCritical] // auto-generated_required - [MethodImplAttribute(MethodImplOptions.InternalCall)] - public static extern void PrepareContractedDelegate(Delegate d); - - [System.Security.SecuritySafeCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.InternalCall)] public static extern int GetHashCode(Object o); - [System.Security.SecuritySafeCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.InternalCall)] public new static extern bool Equals(Object o1, Object o2); @@ -183,30 +130,24 @@ namespace System.Runtime.CompilerServices { // If there is not enough stack, then it throws System.InsufficientExecutionStackException. // Note: this method is not part of the CER support, and is not to be confused with ProbeForSufficientStack // below. - [System.Security.SecuritySafeCritical] [MethodImplAttribute(MethodImplOptions.InternalCall)] [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] public static extern void EnsureSufficientExecutionStack(); -#if FEATURE_CORECLR // This method ensures that there is sufficient stack to execute the average Framework function. // If there is not enough stack, then it return false. // Note: this method is not part of the CER support, and is not to be confused with ProbeForSufficientStack // below. - [System.Security.SecuritySafeCritical] [MethodImplAttribute(MethodImplOptions.InternalCall)] [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] - internal static extern bool TryEnsureSufficientExecutionStack(); -#endif + public static extern bool TryEnsureSufficientExecutionStack(); - [System.Security.SecurityCritical] // auto-generated_required - [MethodImplAttribute(MethodImplOptions.InternalCall)] - [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)] - public static extern void ProbeForSufficientStack(); + public static void ProbeForSufficientStack() + { + } // This method is a marker placed immediately before a try clause to mark the corresponding catch and finally blocks as // constrained. There's no code here other than the probe because most of the work is done at JIT time when we spot a call to this routine. - [System.Security.SecurityCritical] // auto-generated_required [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)] public static void PrepareConstrainedRegions() { @@ -215,29 +156,18 @@ namespace System.Runtime.CompilerServices { // When we detect a CER with no calls, we can point the JIT to this non-probing version instead // as we don't need to probe. - [System.Security.SecurityCritical] // auto-generated_required [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)] public static void PrepareConstrainedRegionsNoOP() { } - #if FEATURE_CORECLR - [System.Security.SecurityCritical] // auto-generated - #endif public delegate void TryCode(Object userData); - #if FEATURE_CORECLR - [System.Security.SecurityCritical] // auto-generated - #endif public delegate void CleanupCode(Object userData, bool exceptionThrown); - [System.Security.SecurityCritical] // auto-generated_required [MethodImplAttribute(MethodImplOptions.InternalCall)] public static extern void ExecuteCodeWithGuaranteedCleanup(TryCode code, CleanupCode backoutCode, Object userData); -#if FEATURE_CORECLR - [System.Security.SecurityCritical] // auto-generated -#endif [PrePrepareMethod] internal static void ExecuteBackoutCodeHelper(Object backoutCode, Object userData, bool exceptionThrown) { diff --git a/src/mscorlib/src/System/Runtime/CompilerServices/RuntimeWrappedException.cs b/src/mscorlib/src/System/Runtime/CompilerServices/RuntimeWrappedException.cs index 2751d61db7..d2691df6b9 100644 --- a/src/mscorlib/src/System/Runtime/CompilerServices/RuntimeWrappedException.cs +++ b/src/mscorlib/src/System/Runtime/CompilerServices/RuntimeWrappedException.cs @@ -33,10 +33,9 @@ namespace System.Runtime.CompilerServices { private Object m_wrappedException; - [System.Security.SecurityCritical] // auto-generated_required public override void GetObjectData(SerializationInfo info, StreamingContext context) { if (info==null) { - throw new ArgumentNullException("info"); + throw new ArgumentNullException(nameof(info)); } Contract.EndContractBlock(); base.GetObjectData(info, context); diff --git a/src/mscorlib/src/System/Runtime/CompilerServices/ScopelessEnumAttribute.cs b/src/mscorlib/src/System/Runtime/CompilerServices/ScopelessEnumAttribute.cs deleted file mode 100644 index 91769187cc..0000000000 --- a/src/mscorlib/src/System/Runtime/CompilerServices/ScopelessEnumAttribute.cs +++ /dev/null @@ -1,14 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -namespace System.Runtime.CompilerServices -{ -[Serializable] -[AttributeUsage(AttributeTargets.Enum)] - public sealed class ScopelessEnumAttribute : Attribute - { - public ScopelessEnumAttribute() - {} - } -} diff --git a/src/mscorlib/src/System/Runtime/CompilerServices/TaskAwaiter.cs b/src/mscorlib/src/System/Runtime/CompilerServices/TaskAwaiter.cs index ea6bb96e16..98a81ea470 100644 --- a/src/mscorlib/src/System/Runtime/CompilerServices/TaskAwaiter.cs +++ b/src/mscorlib/src/System/Runtime/CompilerServices/TaskAwaiter.cs @@ -57,7 +57,6 @@ namespace System.Runtime.CompilerServices { /// <summary>Provides an awaiter for awaiting a <see cref="System.Threading.Tasks.Task"/>.</summary> /// <remarks>This type is intended for compiler use only.</remarks> - [HostProtection(Synchronization = true, ExternalThreading = true)] public struct TaskAwaiter : ICriticalNotifyCompletion { /// <summary>The task being awaited.</summary> @@ -84,7 +83,6 @@ namespace System.Runtime.CompilerServices /// <exception cref="System.ArgumentNullException">The <paramref name="continuation"/> argument is null (Nothing in Visual Basic).</exception> /// <exception cref="System.InvalidOperationException">The awaiter was not properly initialized.</exception> /// <remarks>This method is intended for compiler user rather than use directly in code.</remarks> - [SecuritySafeCritical] public void OnCompleted(Action continuation) { OnCompletedInternal(m_task, continuation, continueOnCapturedContext:true, flowExecutionContext:true); @@ -95,7 +93,6 @@ namespace System.Runtime.CompilerServices /// <exception cref="System.ArgumentNullException">The <paramref name="continuation"/> argument is null (Nothing in Visual Basic).</exception> /// <exception cref="System.InvalidOperationException">The awaiter was not properly initialized.</exception> /// <remarks>This method is intended for compiler user rather than use directly in code.</remarks> - [SecurityCritical] public void UnsafeOnCompleted(Action continuation) { OnCompletedInternal(m_task, continuation, continueOnCapturedContext:true, flowExecutionContext:false); @@ -143,7 +140,7 @@ namespace System.Runtime.CompilerServices if (!task.IsCompleted) { bool taskCompleted = task.InternalWait(Timeout.Infinite, default(CancellationToken)); - Contract.Assert(taskCompleted, "With an infinite timeout, the task should have always completed."); + Debug.Assert(taskCompleted, "With an infinite timeout, the task should have always completed."); } // Now that we're done, alert the debugger if so requested @@ -171,7 +168,7 @@ namespace System.Runtime.CompilerServices if (oceEdi != null) { oceEdi.Throw(); - Contract.Assert(false, "Throw() should have thrown"); + Debug.Assert(false, "Throw() should have thrown"); } throw new TaskCanceledException(task); @@ -182,12 +179,12 @@ namespace System.Runtime.CompilerServices if (edis.Count > 0) { edis[0].Throw(); - Contract.Assert(false, "Throw() should have thrown"); + Debug.Assert(false, "Throw() should have thrown"); break; // Necessary to compile: non-reachable, but compiler can't determine that } else { - Contract.Assert(false, "There should be exceptions if we're Faulted."); + Debug.Assert(false, "There should be exceptions if we're Faulted."); throw task.Exception; } } @@ -202,10 +199,9 @@ namespace System.Runtime.CompilerServices /// <exception cref="System.NullReferenceException">The awaiter was not properly initialized.</exception> /// <remarks>This method is intended for compiler user rather than use directly in code.</remarks> [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var have to be marked non-inlineable - [SecurityCritical] internal static void OnCompletedInternal(Task task, Action continuation, bool continueOnCapturedContext, bool flowExecutionContext) { - if (continuation == null) throw new ArgumentNullException("continuation"); + if (continuation == null) throw new ArgumentNullException(nameof(continuation)); StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; // If TaskWait* ETW events are enabled, trace a beginning event for this await @@ -294,7 +290,6 @@ namespace System.Runtime.CompilerServices /// <summary>Provides an awaiter for awaiting a <see cref="System.Threading.Tasks.Task{TResult}"/>.</summary> /// <remarks>This type is intended for compiler use only.</remarks> - [HostProtection(Synchronization = true, ExternalThreading = true)] public struct TaskAwaiter<TResult> : ICriticalNotifyCompletion { /// <summary>The task being awaited.</summary> @@ -321,7 +316,6 @@ namespace System.Runtime.CompilerServices /// <exception cref="System.ArgumentNullException">The <paramref name="continuation"/> argument is null (Nothing in Visual Basic).</exception> /// <exception cref="System.NullReferenceException">The awaiter was not properly initialized.</exception> /// <remarks>This method is intended for compiler user rather than use directly in code.</remarks> - [SecuritySafeCritical] public void OnCompleted(Action continuation) { TaskAwaiter.OnCompletedInternal(m_task, continuation, continueOnCapturedContext:true, flowExecutionContext:true); @@ -332,7 +326,6 @@ namespace System.Runtime.CompilerServices /// <exception cref="System.ArgumentNullException">The <paramref name="continuation"/> argument is null (Nothing in Visual Basic).</exception> /// <exception cref="System.NullReferenceException">The awaiter was not properly initialized.</exception> /// <remarks>This method is intended for compiler user rather than use directly in code.</remarks> - [SecurityCritical] public void UnsafeOnCompleted(Action continuation) { TaskAwaiter.OnCompletedInternal(m_task, continuation, continueOnCapturedContext:true, flowExecutionContext:false); @@ -377,7 +370,6 @@ namespace System.Runtime.CompilerServices /// <summary>Provides an awaiter for a <see cref="ConfiguredTaskAwaitable"/>.</summary> /// <remarks>This type is intended for compiler use only.</remarks> - [HostProtection(Synchronization = true, ExternalThreading = true)] public struct ConfiguredTaskAwaiter : ICriticalNotifyCompletion { /// <summary>The task being awaited.</summary> @@ -411,7 +403,6 @@ namespace System.Runtime.CompilerServices /// <exception cref="System.ArgumentNullException">The <paramref name="continuation"/> argument is null (Nothing in Visual Basic).</exception> /// <exception cref="System.NullReferenceException">The awaiter was not properly initialized.</exception> /// <remarks>This method is intended for compiler user rather than use directly in code.</remarks> - [SecuritySafeCritical] public void OnCompleted(Action continuation) { TaskAwaiter.OnCompletedInternal(m_task, continuation, m_continueOnCapturedContext, flowExecutionContext:true); @@ -422,7 +413,6 @@ namespace System.Runtime.CompilerServices /// <exception cref="System.ArgumentNullException">The <paramref name="continuation"/> argument is null (Nothing in Visual Basic).</exception> /// <exception cref="System.NullReferenceException">The awaiter was not properly initialized.</exception> /// <remarks>This method is intended for compiler user rather than use directly in code.</remarks> - [SecurityCritical] public void UnsafeOnCompleted(Action continuation) { TaskAwaiter.OnCompletedInternal(m_task, continuation, m_continueOnCapturedContext, flowExecutionContext:false); @@ -466,7 +456,6 @@ namespace System.Runtime.CompilerServices /// <summary>Provides an awaiter for a <see cref="ConfiguredTaskAwaitable{TResult}"/>.</summary> /// <remarks>This type is intended for compiler use only.</remarks> - [HostProtection(Synchronization = true, ExternalThreading = true)] public struct ConfiguredTaskAwaiter : ICriticalNotifyCompletion { /// <summary>The task being awaited.</summary> @@ -499,7 +488,6 @@ namespace System.Runtime.CompilerServices /// <exception cref="System.ArgumentNullException">The <paramref name="continuation"/> argument is null (Nothing in Visual Basic).</exception> /// <exception cref="System.NullReferenceException">The awaiter was not properly initialized.</exception> /// <remarks>This method is intended for compiler user rather than use directly in code.</remarks> - [SecuritySafeCritical] public void OnCompleted(Action continuation) { TaskAwaiter.OnCompletedInternal(m_task, continuation, m_continueOnCapturedContext, flowExecutionContext:true); @@ -510,7 +498,6 @@ namespace System.Runtime.CompilerServices /// <exception cref="System.ArgumentNullException">The <paramref name="continuation"/> argument is null (Nothing in Visual Basic).</exception> /// <exception cref="System.NullReferenceException">The awaiter was not properly initialized.</exception> /// <remarks>This method is intended for compiler user rather than use directly in code.</remarks> - [SecurityCritical] public void UnsafeOnCompleted(Action continuation) { TaskAwaiter.OnCompletedInternal(m_task, continuation, m_continueOnCapturedContext, flowExecutionContext:false); diff --git a/src/mscorlib/src/System/Runtime/CompilerServices/TypeDependencyAttribute.cs b/src/mscorlib/src/System/Runtime/CompilerServices/TypeDependencyAttribute.cs index db04eb9348..2de9c1f785 100644 --- a/src/mscorlib/src/System/Runtime/CompilerServices/TypeDependencyAttribute.cs +++ b/src/mscorlib/src/System/Runtime/CompilerServices/TypeDependencyAttribute.cs @@ -17,7 +17,7 @@ namespace System.Runtime.CompilerServices public TypeDependencyAttribute (string typeName) { - if(typeName == null) throw new ArgumentNullException("typeName"); + if(typeName == null) throw new ArgumentNullException(nameof(typeName)); Contract.EndContractBlock(); this.typeName = typeName; } diff --git a/src/mscorlib/src/System/Runtime/CompilerServices/TypeForwardedFromAttribute.cs b/src/mscorlib/src/System/Runtime/CompilerServices/TypeForwardedFromAttribute.cs index c1656dcf99..671d1f0071 100644 --- a/src/mscorlib/src/System/Runtime/CompilerServices/TypeForwardedFromAttribute.cs +++ b/src/mscorlib/src/System/Runtime/CompilerServices/TypeForwardedFromAttribute.cs @@ -20,7 +20,7 @@ namespace System.Runtime.CompilerServices { if (String.IsNullOrEmpty(assemblyFullName)) { - throw new ArgumentNullException("assemblyFullName"); + throw new ArgumentNullException(nameof(assemblyFullName)); } this.assemblyFullName = assemblyFullName; } diff --git a/src/mscorlib/src/System/Runtime/CompilerServices/TypeForwardedToAttribute.cs b/src/mscorlib/src/System/Runtime/CompilerServices/TypeForwardedToAttribute.cs index 034dad1afe..d9e067bd4c 100644 --- a/src/mscorlib/src/System/Runtime/CompilerServices/TypeForwardedToAttribute.cs +++ b/src/mscorlib/src/System/Runtime/CompilerServices/TypeForwardedToAttribute.cs @@ -26,7 +26,6 @@ namespace System.Runtime.CompilerServices } } - [System.Security.SecurityCritical] internal static TypeForwardedToAttribute[] GetCustomAttribute(RuntimeAssembly assembly) { Type[] types = null; diff --git a/src/mscorlib/src/System/Runtime/CompilerServices/Unsafe.cs b/src/mscorlib/src/System/Runtime/CompilerServices/Unsafe.cs new file mode 100644 index 0000000000..b212f4555b --- /dev/null +++ b/src/mscorlib/src/System/Runtime/CompilerServices/Unsafe.cs @@ -0,0 +1,80 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +using System.Runtime.Versioning; + +namespace System.Runtime.CompilerServices +{ + // + // Subsetted clone of System.Runtime.CompilerServices.Unsafe for internal runtime use. + // Keep in sync with https://github.com/dotnet/corefx/tree/master/src/System.Runtime.CompilerServices.Unsafe. + // + + /// <summary> + /// Contains generic, low-level functionality for manipulating pointers. + /// </summary> + internal static unsafe class Unsafe + { + /// <summary> + /// Returns a pointer to the given by-ref parameter. + /// </summary> + [NonVersionable] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void* AsPointer<T>(ref T value) + { + // The body of this function will be replaced by the EE with unsafe code!!! + // See getILIntrinsicImplementationForUnsafe for how this happens. + throw new InvalidOperationException(); + } + + /// <summary> + /// Returns the size of an object of the given type parameter. + /// </summary> + [NonVersionable] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static int SizeOf<T>() + { + // The body of this function will be replaced by the EE with unsafe code that just returns sizeof !!T + // See getILIntrinsicImplementationForUnsafe for how this happens. + throw new InvalidOperationException(); + } + + /// <summary> + /// Reinterprets the given reference as a reference to a value of type <typeparamref name="TTo"/>. + /// </summary> + [NonVersionable] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static ref TTo As<TFrom, TTo>(ref TFrom source) + { + // The body of this function will be replaced by the EE with unsafe code!!! + // See getILIntrinsicImplementationForUnsafe for how this happens. + throw new InvalidOperationException(); + } + + /// <summary> + /// Adds an element offset to the given reference. + /// </summary> + [NonVersionable] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static ref T Add<T>(ref T source, int elementOffset) + { + // The body of this function will be replaced by the EE with unsafe code!!! + // See getILIntrinsicImplementationForUnsafe for how this happens. + typeof(T).ToString(); // Type used by the actual method body + throw new InvalidOperationException(); + } + + /// <summary> + /// Determines whether the specified references point to the same location. + /// </summary> + [NonVersionable] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static bool AreSame<T>(ref T left, ref T right) + { + // The body of this function will be replaced by the EE with unsafe code!!! + // See getILIntrinsicImplementationForUnsafe for how this happens. + throw new InvalidOperationException(); + } + } +} diff --git a/src/mscorlib/src/System/Runtime/CompilerServices/YieldAwaitable.cs b/src/mscorlib/src/System/Runtime/CompilerServices/YieldAwaitable.cs index b29b39c5bf..86789bf12d 100644 --- a/src/mscorlib/src/System/Runtime/CompilerServices/YieldAwaitable.cs +++ b/src/mscorlib/src/System/Runtime/CompilerServices/YieldAwaitable.cs @@ -48,7 +48,6 @@ namespace System.Runtime.CompilerServices /// <summary>Provides an awaiter that switches into a target environment.</summary> /// <remarks>This type is intended for compiler use only.</remarks> - [HostProtection(Synchronization = true, ExternalThreading = true)] public struct YieldAwaiter : ICriticalNotifyCompletion { /// <summary>Gets whether a yield is not required.</summary> @@ -58,7 +57,6 @@ namespace System.Runtime.CompilerServices /// <summary>Posts the <paramref name="continuation"/> back to the current context.</summary> /// <param name="continuation">The action to invoke asynchronously.</param> /// <exception cref="System.ArgumentNullException">The <paramref name="continuation"/> argument is null (Nothing in Visual Basic).</exception> - [SecuritySafeCritical] public void OnCompleted(Action continuation) { QueueContinuation(continuation, flowContext: true); @@ -67,7 +65,6 @@ namespace System.Runtime.CompilerServices /// <summary>Posts the <paramref name="continuation"/> back to the current context.</summary> /// <param name="continuation">The action to invoke asynchronously.</param> /// <exception cref="System.ArgumentNullException">The <paramref name="continuation"/> argument is null (Nothing in Visual Basic).</exception> - [SecurityCritical] public void UnsafeOnCompleted(Action continuation) { QueueContinuation(continuation, flowContext: false); @@ -77,11 +74,10 @@ namespace System.Runtime.CompilerServices /// <param name="continuation">The action to invoke asynchronously.</param> /// <param name="flowContext">true to flow ExecutionContext; false if flowing is not required.</param> /// <exception cref="System.ArgumentNullException">The <paramref name="continuation"/> argument is null (Nothing in Visual Basic).</exception> - [SecurityCritical] private static void QueueContinuation(Action continuation, bool flowContext) { // Validate arguments - if (continuation == null) throw new ArgumentNullException("continuation"); + if (continuation == null) throw new ArgumentNullException(nameof(continuation)); Contract.EndContractBlock(); if (TplEtwProvider.Log.IsEnabled()) diff --git a/src/mscorlib/src/System/Runtime/CompilerServices/jithelpers.cs b/src/mscorlib/src/System/Runtime/CompilerServices/jithelpers.cs index 8ee50da290..c1346f7527 100644 --- a/src/mscorlib/src/System/Runtime/CompilerServices/jithelpers.cs +++ b/src/mscorlib/src/System/Runtime/CompilerServices/jithelpers.cs @@ -11,6 +11,7 @@ using System; using System.Threading; using System.Runtime; using System.Runtime.Versioning; +using System.Diagnostics; using System.Diagnostics.Contracts; using System.Runtime.InteropServices; using System.Security; @@ -60,6 +61,12 @@ namespace System.Runtime.CompilerServices { public byte m_data; } + internal class ArrayPinningHelper + { + public IntPtr m_lengthAndPadding; + public byte m_arrayData; + } + [FriendAccessAllowed] internal static class JitHelpers { @@ -68,7 +75,6 @@ namespace System.Runtime.CompilerServices { // Wraps object variable into a handle. Used to return managed strings from QCalls. // s has to be a local variable on the stack. - [SecurityCritical] static internal StringHandleOnStack GetStringHandleOnStack(ref string s) { return new StringHandleOnStack(UnsafeCastToStackPointer(ref s)); @@ -76,7 +82,6 @@ namespace System.Runtime.CompilerServices { // Wraps object variable into a handle. Used to pass managed object references in and out of QCalls. // o has to be a local variable on the stack. - [SecurityCritical] static internal ObjectHandleOnStack GetObjectHandleOnStack<T>(ref T o) where T : class { return new ObjectHandleOnStack(UnsafeCastToStackPointer(ref o)); @@ -84,25 +89,22 @@ namespace System.Runtime.CompilerServices { // Wraps StackCrawlMark into a handle. Used to pass StackCrawlMark to QCalls. // stackMark has to be a local variable on the stack. - [SecurityCritical] static internal StackCrawlMarkHandle GetStackCrawlMarkHandle(ref StackCrawlMark stackMark) { return new StackCrawlMarkHandle(UnsafeCastToStackPointer(ref stackMark)); } #if _DEBUG - [SecurityCritical] [FriendAccessAllowed] static internal T UnsafeCast<T>(Object o) where T : class { T ret = UnsafeCastInternal<T>(o); - Contract.Assert(ret == (o as T), "Invalid use of JitHelpers.UnsafeCast!"); + Debug.Assert(ret == (o as T), "Invalid use of JitHelpers.UnsafeCast!"); return ret; } // The IL body of this method is not critical, but its body will be replaced with unsafe code, so // this method is effectively critical - [SecurityCritical] static private T UnsafeCastInternal<T>(Object o) where T : class { // The body of this function will be replaced by the EE with unsafe code that just returns o!!! @@ -112,7 +114,7 @@ namespace System.Runtime.CompilerServices { static internal int UnsafeEnumCast<T>(T val) where T : struct // Actually T must be 4 byte (or less) enum { - Contract.Assert(typeof(T).IsEnum + Debug.Assert(typeof(T).IsEnum && (Enum.GetUnderlyingType(typeof(T)) == typeof(int) || Enum.GetUnderlyingType(typeof(T)) == typeof(uint) || Enum.GetUnderlyingType(typeof(T)) == typeof(short) @@ -132,7 +134,7 @@ namespace System.Runtime.CompilerServices { static internal long UnsafeEnumCastLong<T>(T val) where T : struct // Actually T must be 8 byte enum { - Contract.Assert(typeof(T).IsEnum + Debug.Assert(typeof(T).IsEnum && (Enum.GetUnderlyingType(typeof(T)) == typeof(long) || Enum.GetUnderlyingType(typeof(T)) == typeof(ulong)), "Error, T must be an 8 byte enum JitHelpers.UnsafeEnumCastLong!"); @@ -148,15 +150,13 @@ namespace System.Runtime.CompilerServices { // Internal method for getting a raw pointer for handles in JitHelpers. // The reference has to point into a local stack variable in order so it can not be moved by the GC. - [SecurityCritical] static internal IntPtr UnsafeCastToStackPointer<T>(ref T val) { IntPtr p = UnsafeCastToStackPointerInternal<T>(ref val); - Contract.Assert(IsAddressInStack(p), "Pointer not in the stack!"); + Debug.Assert(IsAddressInStack(p), "Pointer not in the stack!"); return p; } - [SecurityCritical] static private IntPtr UnsafeCastToStackPointerInternal<T>(ref T val) { // The body of this function will be replaced by the EE with unsafe code that just returns val!!! @@ -166,7 +166,6 @@ namespace System.Runtime.CompilerServices { #else // _DEBUG // The IL body of this method is not critical, but its body will be replaced with unsafe code, so // this method is effectively critical - [SecurityCritical] [FriendAccessAllowed] static internal T UnsafeCast<T>(Object o) where T : class { @@ -189,7 +188,6 @@ namespace System.Runtime.CompilerServices { throw new InvalidOperationException(); } - [SecurityCritical] static internal IntPtr UnsafeCastToStackPointer<T>(ref T val) { // The body of this function will be replaced by the EE with unsafe code that just returns o!!! @@ -199,12 +197,10 @@ namespace System.Runtime.CompilerServices { #endif // _DEBUG // Set the given element in the array without any type or range checks - [SecurityCritical] [MethodImplAttribute(MethodImplOptions.InternalCall)] extern static internal void UnsafeSetArrayElement(Object[] target, int index, Object element); // Used for unsafe pinning of arbitrary objects. - [System.Security.SecurityCritical] // auto-generated static internal PinningHelper GetPinningHelper(Object o) { // This cast is really unsafe - call the private version that does not assert in debug @@ -216,9 +212,33 @@ namespace System.Runtime.CompilerServices { } #if _DEBUG - [SecurityCritical] [MethodImplAttribute(MethodImplOptions.InternalCall)] extern static bool IsAddressInStack(IntPtr ptr); #endif + +#if FEATURE_SPAN_OF_T + static internal bool ByRefLessThan<T>(ref T refA, ref T refB) + { + // The body of this function will be replaced by the EE with unsafe code!!! + // See getILIntrinsicImplementation for how this happens. + throw new InvalidOperationException(); + } + + /// <returns>true if given type is reference type or value type that contains references</returns> + static internal bool ContainsReferences<T>() + { + // The body of this function will be replaced by the EE with unsafe code!!! + // See getILIntrinsicImplementation for how this happens. + throw new InvalidOperationException(); + } + + static internal ref T GetArrayData<T>(T[] array) + { + // The body of this function will be replaced by the EE with unsafe code!!! + // See getILIntrinsicImplementation for how this happens. + typeof(ArrayPinningHelper).ToString(); // Type used by the actual method body + throw new InvalidOperationException(); + } +#endif // FEATURE_SPAN_OF_T } } diff --git a/src/mscorlib/src/System/Runtime/ExceptionServices/ExceptionNotification.cs b/src/mscorlib/src/System/Runtime/ExceptionServices/ExceptionNotification.cs new file mode 100644 index 0000000000..b084891768 --- /dev/null +++ b/src/mscorlib/src/System/Runtime/ExceptionServices/ExceptionNotification.cs @@ -0,0 +1,41 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. +/*============================================================================= +** +** File: ExceptionNotification.cs +** +** +** Purpose: Contains definitions for supporting Exception Notifications. +** +** Created: 10/07/2008 +** +** <owner>gkhanna</owner> +** +=============================================================================*/ +#if FEATURE_EXCEPTION_NOTIFICATIONS +namespace System.Runtime.ExceptionServices { + using System; + using System.Runtime.ConstrainedExecution; + + // Definition of the argument-type passed to the FirstChanceException event handler + public class FirstChanceExceptionEventArgs : EventArgs + { + // Constructor + public FirstChanceExceptionEventArgs(Exception exception) + { + m_Exception = exception; + } + + // Returns the exception object pertaining to the first chance exception + public Exception Exception + { + [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] + get { return m_Exception; } + } + + // Represents the FirstChance exception instance + private Exception m_Exception; + } +} +#endif // FEATURE_EXCEPTION_NOTIFICATIONS
\ No newline at end of file diff --git a/src/mscorlib/src/System/Runtime/ExceptionServices/ExceptionServicesCommon.cs b/src/mscorlib/src/System/Runtime/ExceptionServices/ExceptionServicesCommon.cs index 7251d901cd..905f12dfb5 100644 --- a/src/mscorlib/src/System/Runtime/ExceptionServices/ExceptionServicesCommon.cs +++ b/src/mscorlib/src/System/Runtime/ExceptionServices/ExceptionServicesCommon.cs @@ -101,7 +101,7 @@ namespace System.Runtime.ExceptionServices { { if (source == null) { - throw new ArgumentNullException("source", Environment.GetResourceString("ArgumentNull_Obj")); + throw new ArgumentNullException(nameof(source), Environment.GetResourceString("ArgumentNull_Obj")); } return new ExceptionDispatchInfo(source); diff --git a/src/mscorlib/src/System/Runtime/GcSettings.cs b/src/mscorlib/src/System/Runtime/GcSettings.cs index 5b4be27757..91997f5297 100644 --- a/src/mscorlib/src/System/Runtime/GcSettings.cs +++ b/src/mscorlib/src/System/Runtime/GcSettings.cs @@ -40,7 +40,6 @@ namespace System.Runtime { public static GCLatencyMode LatencyMode { - [System.Security.SecuritySafeCritical] // auto-generated [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] get { @@ -48,8 +47,6 @@ namespace System.Runtime { } // We don't want to allow this API when hosted. - [System.Security.SecurityCritical] // auto-generated_required - [HostProtection(MayLeakOnAbort = true)] [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] set { @@ -66,7 +63,6 @@ namespace System.Runtime { public static GCLargeObjectHeapCompactionMode LargeObjectHeapCompactionMode { - [System.Security.SecuritySafeCritical] // auto-generated [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] get { @@ -74,8 +70,6 @@ namespace System.Runtime { } // We don't want to allow this API when hosted. - [System.Security.SecurityCritical] // auto-generated_required - [HostProtection(MayLeakOnAbort = true)] [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] set { @@ -92,7 +86,6 @@ namespace System.Runtime { public static bool IsServerGC { - [System.Security.SecuritySafeCritical] // auto-generated get { return GC.IsServerGC(); } diff --git a/src/mscorlib/src/System/Runtime/InteropServices/ArrayWithOffset.cs b/src/mscorlib/src/System/Runtime/InteropServices/ArrayWithOffset.cs index 83eae1c59c..77db3a7f2c 100644 --- a/src/mscorlib/src/System/Runtime/InteropServices/ArrayWithOffset.cs +++ b/src/mscorlib/src/System/Runtime/InteropServices/ArrayWithOffset.cs @@ -17,7 +17,6 @@ namespace System.Runtime.InteropServices { // throw new Exception(); //} - [System.Security.SecuritySafeCritical] // auto-generated public ArrayWithOffset(Object array, int offset) { m_array = array; @@ -64,7 +63,6 @@ namespace System.Runtime.InteropServices { return !(a == b); } - [System.Security.SecurityCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.InternalCall)] private extern int CalculateCount(); diff --git a/src/mscorlib/src/System/Runtime/InteropServices/Attributes.cs b/src/mscorlib/src/System/Runtime/InteropServices/Attributes.cs index 06c963a555..2de7304a0b 100644 --- a/src/mscorlib/src/System/Runtime/InteropServices/Attributes.cs +++ b/src/mscorlib/src/System/Runtime/InteropServices/Attributes.cs @@ -8,6 +8,7 @@ namespace System.Runtime.InteropServices{ using System; using System.Reflection; + using System.Diagnostics; using System.Diagnostics.Contracts; [AttributeUsage(AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)] @@ -525,31 +526,26 @@ namespace System.Runtime.InteropServices{ [System.Runtime.InteropServices.ComVisible(true)] public unsafe sealed class MarshalAsAttribute : Attribute { - [System.Security.SecurityCritical] // auto-generated internal static Attribute GetCustomAttribute(RuntimeParameterInfo parameter) { return GetCustomAttribute(parameter.MetadataToken, parameter.GetRuntimeModule()); } - [System.Security.SecurityCritical] // auto-generated internal static bool IsDefined(RuntimeParameterInfo parameter) { return GetCustomAttribute(parameter) != null; } - [System.Security.SecurityCritical] // auto-generated internal static Attribute GetCustomAttribute(RuntimeFieldInfo field) { return GetCustomAttribute(field.MetadataToken, field.GetRuntimeModule()); ; } - [System.Security.SecurityCritical] // auto-generated internal static bool IsDefined(RuntimeFieldInfo field) { return GetCustomAttribute(field) != null; } - [System.Security.SecurityCritical] // auto-generated internal static Attribute GetCustomAttribute(int token, RuntimeModule scope) { UnmanagedType unmanagedType, arraySubType; @@ -578,7 +574,7 @@ namespace System.Runtime.InteropServices{ { // The user may have supplied a bad type name string causing this TypeLoadException // Regardless, we return the bad type name - Contract.Assert(marshalTypeName != null); + Debug.Assert(marshalTypeName != null); } return new MarshalAsAttribute( @@ -772,7 +768,6 @@ namespace System.Runtime.InteropServices{ [System.Runtime.InteropServices.ComVisible(true)] public unsafe sealed class DllImportAttribute : Attribute { - [System.Security.SecurityCritical] // auto-generated internal static Attribute GetCustomAttribute(RuntimeMethodInfo method) { if ((method.Attributes & MethodAttributes.PinvokeImpl) == 0) @@ -869,7 +864,6 @@ namespace System.Runtime.InteropServices{ { private const int DEFAULT_PACKING_SIZE = 8; - [System.Security.SecurityCritical] // auto-generated internal static Attribute GetCustomAttribute(RuntimeType type) { if (!IsDefined(type)) @@ -940,7 +934,6 @@ namespace System.Runtime.InteropServices{ [System.Runtime.InteropServices.ComVisible(true)] public unsafe sealed class FieldOffsetAttribute : Attribute { - [System.Security.SecurityCritical] // auto-generated internal static Attribute GetCustomAttribute(RuntimeFieldInfo field) { int fieldOffset; @@ -952,7 +945,6 @@ namespace System.Runtime.InteropServices{ return null; } - [System.Security.SecurityCritical] // auto-generated internal static bool IsDefined(RuntimeFieldInfo field) { return GetCustomAttribute(field) != null; diff --git a/src/mscorlib/src/System/Runtime/InteropServices/BStrWrapper.cs b/src/mscorlib/src/System/Runtime/InteropServices/BStrWrapper.cs index 58e93a87ea..1673c913a6 100644 --- a/src/mscorlib/src/System/Runtime/InteropServices/BStrWrapper.cs +++ b/src/mscorlib/src/System/Runtime/InteropServices/BStrWrapper.cs @@ -21,19 +21,11 @@ namespace System.Runtime.InteropServices { [System.Runtime.InteropServices.ComVisible(true)] public sealed class BStrWrapper { - [System.Security.SecuritySafeCritical] // auto-generated -#pragma warning disable 618 - [SecurityPermissionAttribute(SecurityAction.Demand,Flags=SecurityPermissionFlag.UnmanagedCode)] -#pragma warning restore 618 public BStrWrapper(String value) { m_WrappedObject = value; } - [System.Security.SecuritySafeCritical] // auto-generated -#pragma warning disable 618 - [SecurityPermissionAttribute(SecurityAction.Demand, Flags = SecurityPermissionFlag.UnmanagedCode)] -#pragma warning restore 618 public BStrWrapper(Object value) { m_WrappedObject = (String)value; diff --git a/src/mscorlib/src/System/Runtime/InteropServices/COMException.cs b/src/mscorlib/src/System/Runtime/InteropServices/COMException.cs index 95b925c3f4..fd500fdbce 100644 --- a/src/mscorlib/src/System/Runtime/InteropServices/COMException.cs +++ b/src/mscorlib/src/System/Runtime/InteropServices/COMException.cs @@ -46,7 +46,6 @@ namespace System.Runtime.InteropServices { SetErrorCode(errorCode); } - [SecuritySafeCritical] internal COMException(int hresult) : base(Win32Native.GetMessage(hresult)) { diff --git a/src/mscorlib/src/System/Runtime/InteropServices/ComEventsHelper.cs b/src/mscorlib/src/System/Runtime/InteropServices/ComEventsHelper.cs index 0bf616d94c..82692c1c54 100644 --- a/src/mscorlib/src/System/Runtime/InteropServices/ComEventsHelper.cs +++ b/src/mscorlib/src/System/Runtime/InteropServices/ComEventsHelper.cs @@ -115,7 +115,6 @@ namespace System.Runtime.InteropServices { /// <param name="iid">identifier of the source interface used by COM object to fire events</param> /// <param name="dispid">dispatch identifier of the method on the source interface</param> /// <param name="d">delegate to invoke when specifed COM event is fired</param> - [System.Security.SecurityCritical] public static void Combine(object rcw, Guid iid, int dispid, System.Delegate d) { rcw = UnwrapIfTransparentProxy(rcw); @@ -146,7 +145,6 @@ namespace System.Runtime.InteropServices { /// <param name="dispid">dispatch identifier of the method on the source interface</param> /// <param name="d">delegate to remove from the invocation list</param> /// <returns></returns> - [System.Security.SecurityCritical] public static Delegate Remove(object rcw, Guid iid, int dispid, System.Delegate d) { rcw = UnwrapIfTransparentProxy(rcw); @@ -183,18 +181,8 @@ namespace System.Runtime.InteropServices { } } - [System.Security.SecurityCritical] - internal static object UnwrapIfTransparentProxy(object rcw) { -#if FEATURE_REMOTING - if (RemotingServices.IsTransparentProxy(rcw)) { - IntPtr punk = Marshal.GetIUnknownForObject(rcw); - try { - rcw = Marshal.GetObjectForIUnknown(punk); - } finally { - Marshal.Release(punk); - } - } -#endif + internal static object UnwrapIfTransparentProxy(object rcw) + { return rcw; } } diff --git a/src/mscorlib/src/System/Runtime/InteropServices/ComEventsInfo.cs b/src/mscorlib/src/System/Runtime/InteropServices/ComEventsInfo.cs index 6feb52445d..2456ba35bf 100644 --- a/src/mscorlib/src/System/Runtime/InteropServices/ComEventsInfo.cs +++ b/src/mscorlib/src/System/Runtime/InteropServices/ComEventsInfo.cs @@ -17,7 +17,6 @@ namespace System.Runtime.InteropServices { using ComTypes = System.Runtime.InteropServices.ComTypes; // see code:ComEventsHelper#ComEventsArchitecture - [System.Security.SecurityCritical] internal class ComEventsInfo { @@ -35,7 +34,6 @@ namespace System.Runtime.InteropServices { _rcw = rcw; } - [System.Security.SecuritySafeCritical] ~ComEventsInfo() { // see code:ComEventsHelper#ComEventsFinalization _sinks = ComEventsSink.RemoveAll(_sinks); @@ -46,13 +44,11 @@ namespace System.Runtime.InteropServices { #region static methods - [System.Security.SecurityCritical] internal static ComEventsInfo Find(object rcw) { return (ComEventsInfo)Marshal.GetComObjectData(rcw, typeof(ComEventsInfo)); } // it is caller's responsibility to call this method under lock(rcw) - [System.Security.SecurityCritical] internal static ComEventsInfo FromObject(object rcw) { ComEventsInfo eventsInfo = Find(rcw); if (eventsInfo == null) { @@ -80,7 +76,6 @@ namespace System.Runtime.InteropServices { } // it is caller's responsibility to call this method under lock(rcw) - [System.Security.SecurityCritical] internal ComEventsSink RemoveSink(ComEventsSink sink) { _sinks = ComEventsSink.Remove(_sinks, sink); return _sinks; diff --git a/src/mscorlib/src/System/Runtime/InteropServices/ComEventsSink.cs b/src/mscorlib/src/System/Runtime/InteropServices/ComEventsSink.cs index a414eff3a1..05978a607f 100644 --- a/src/mscorlib/src/System/Runtime/InteropServices/ComEventsSink.cs +++ b/src/mscorlib/src/System/Runtime/InteropServices/ComEventsSink.cs @@ -16,7 +16,6 @@ namespace System.Runtime.InteropServices { using System.Diagnostics; // see code:ComEventsHelper#ComEventsArchitecture - [System.Security.SecurityCritical] internal class ComEventsSink : NativeMethods.IDispatch, ICustomQueryInterface { #region private fields @@ -57,7 +56,6 @@ namespace System.Runtime.InteropServices { return sink; } - [System.Security.SecurityCritical] internal static ComEventsSink RemoveAll(ComEventsSink sinks) { while (sinks != null) { sinks.Unadvise(); @@ -67,7 +65,6 @@ namespace System.Runtime.InteropServices { return null; } - [System.Security.SecurityCritical] internal static ComEventsSink Remove(ComEventsSink sinks, ComEventsSink sink) { BCLDebug.Assert(sinks != null, "removing event sink from empty sinks collection"); BCLDebug.Assert(sink != null, "specify event sink is null"); @@ -114,17 +111,14 @@ namespace System.Runtime.InteropServices { #region IDispatch Members - [System.Security.SecurityCritical] void NativeMethods.IDispatch.GetTypeInfoCount(out uint pctinfo) { pctinfo = 0; } - [System.Security.SecurityCritical] void NativeMethods.IDispatch.GetTypeInfo(uint iTInfo, int lcid, out IntPtr info) { throw new NotImplementedException(); } - [System.Security.SecurityCritical] void NativeMethods.IDispatch.GetIDsOfNames(ref Guid iid, string[] names, uint cNames, int lcid, int[] rgDispId) { throw new NotImplementedException(); } @@ -149,7 +143,6 @@ namespace System.Runtime.InteropServices { return pSrc; } - [System.Security.SecurityCritical] unsafe void NativeMethods.IDispatch.Invoke( int dispid, ref Guid riid, @@ -233,7 +226,6 @@ namespace System.Runtime.InteropServices { static Guid IID_IManagedObject = new Guid("{C3FCC19E-A970-11D2-8B5A-00A0C9B7C9C4}"); - [System.Security.SecurityCritical] CustomQueryInterfaceResult ICustomQueryInterface.GetInterface(ref Guid iid, out IntPtr ppv) { ppv = IntPtr.Zero; if (iid == this._iidSourceItf || iid == typeof(NativeMethods.IDispatch).GUID) { @@ -265,7 +257,6 @@ namespace System.Runtime.InteropServices { _connectionPoint = cp; } - [System.Security.SecurityCritical] private void Unadvise() { BCLDebug.Assert(_connectionPoint != null, "can not unadvise from empty connection point"); diff --git a/src/mscorlib/src/System/Runtime/InteropServices/CriticalHandle.cs b/src/mscorlib/src/System/Runtime/InteropServices/CriticalHandle.cs index 54fd6b0cdd..700e059293 100644 --- a/src/mscorlib/src/System/Runtime/InteropServices/CriticalHandle.cs +++ b/src/mscorlib/src/System/Runtime/InteropServices/CriticalHandle.cs @@ -139,10 +139,6 @@ namespace System.Runtime.InteropServices // we'll do this to ensure we've cut off all attack vectors. Similarly, all // methods have a link demand to ensure untrusted code cannot directly edit // or alter a handle. -[System.Security.SecurityCritical] // auto-generated_required -#if !FEATURE_CORECLR -[SecurityPermission(SecurityAction.InheritanceDemand, UnmanagedCode=true)] -#endif public abstract class CriticalHandle : CriticalFinalizerObject, IDisposable { // ! Do not add or rearrange fields as the EE depends on this layout. @@ -168,19 +164,15 @@ public abstract class CriticalHandle : CriticalFinalizerObject, IDisposable #endif } -#if FEATURE_CORECLR // Adding an empty default constructor for annotation purposes private CriticalHandle(){} -#endif - [System.Security.SecuritySafeCritical] // auto-generated [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] ~CriticalHandle() { Dispose(false); } - [System.Security.SecurityCritical] // auto-generated [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] private void Cleanup() { @@ -229,20 +221,17 @@ public abstract class CriticalHandle : CriticalFinalizerObject, IDisposable get; } - [System.Security.SecurityCritical] // auto-generated [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] public void Close() { Dispose(true); } - [System.Security.SecuritySafeCritical] // auto-generated [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] public void Dispose() { Dispose(true); } - [System.Security.SecurityCritical] // auto-generated [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] protected virtual void Dispose(bool disposing) { diff --git a/src/mscorlib/src/System/Runtime/InteropServices/CurrencyWrapper.cs b/src/mscorlib/src/System/Runtime/InteropServices/CurrencyWrapper.cs index 1f7a9f18bf..470e7b20dd 100644 --- a/src/mscorlib/src/System/Runtime/InteropServices/CurrencyWrapper.cs +++ b/src/mscorlib/src/System/Runtime/InteropServices/CurrencyWrapper.cs @@ -27,7 +27,7 @@ namespace System.Runtime.InteropServices { public CurrencyWrapper(Object obj) { if (!(obj is Decimal)) - throw new ArgumentException(Environment.GetResourceString("Arg_MustBeDecimal"), "obj"); + throw new ArgumentException(Environment.GetResourceString("Arg_MustBeDecimal"), nameof(obj)); m_WrappedObject = (Decimal)obj; } diff --git a/src/mscorlib/src/System/Runtime/InteropServices/DispatchWrapper.cs b/src/mscorlib/src/System/Runtime/InteropServices/DispatchWrapper.cs index 1fc72f74c8..47b7542caf 100644 --- a/src/mscorlib/src/System/Runtime/InteropServices/DispatchWrapper.cs +++ b/src/mscorlib/src/System/Runtime/InteropServices/DispatchWrapper.cs @@ -21,10 +21,6 @@ namespace System.Runtime.InteropServices { [System.Runtime.InteropServices.ComVisible(true)] public sealed class DispatchWrapper { - [System.Security.SecuritySafeCritical] // auto-generated -#pragma warning disable 618 - [SecurityPermissionAttribute(SecurityAction.Demand,Flags=SecurityPermissionFlag.UnmanagedCode)] -#pragma warning restore 618 public DispatchWrapper(Object obj) { if (obj != null) diff --git a/src/mscorlib/src/System/Runtime/InteropServices/ErrorWrapper.cs b/src/mscorlib/src/System/Runtime/InteropServices/ErrorWrapper.cs index d63d69cabd..a9fa58f65f 100644 --- a/src/mscorlib/src/System/Runtime/InteropServices/ErrorWrapper.cs +++ b/src/mscorlib/src/System/Runtime/InteropServices/ErrorWrapper.cs @@ -28,14 +28,10 @@ namespace System.Runtime.InteropServices { public ErrorWrapper(Object errorCode) { if (!(errorCode is int)) - throw new ArgumentException(Environment.GetResourceString("Arg_MustBeInt32"), "errorCode"); + throw new ArgumentException(Environment.GetResourceString("Arg_MustBeInt32"), nameof(errorCode)); m_ErrorCode = (int)errorCode; } - [System.Security.SecuritySafeCritical] // auto-generated -#pragma warning disable 618 - [SecurityPermissionAttribute(SecurityAction.Demand, Flags=SecurityPermissionFlag.UnmanagedCode)] -#pragma warning restore 618 public ErrorWrapper(Exception e) { m_ErrorCode = Marshal.GetHRForException(e); diff --git a/src/mscorlib/src/System/Runtime/InteropServices/ExtensibleClassFactory.cs b/src/mscorlib/src/System/Runtime/InteropServices/ExtensibleClassFactory.cs index 62718de757..a12a38ec6d 100644 --- a/src/mscorlib/src/System/Runtime/InteropServices/ExtensibleClassFactory.cs +++ b/src/mscorlib/src/System/Runtime/InteropServices/ExtensibleClassFactory.cs @@ -34,7 +34,6 @@ namespace System.Runtime.InteropServices { // class for which the callbacks will be made. // It is not legal to register this callback from a class that has any // parents that have already registered a callback. - [System.Security.SecuritySafeCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.InternalCall)] public static extern void RegisterObjectCreationCallback(ObjectCreationDelegate callback); } diff --git a/src/mscorlib/src/System/Runtime/InteropServices/ExternalException.cs b/src/mscorlib/src/System/Runtime/InteropServices/ExternalException.cs index 417cf94bd4..70a6dfe366 100644 --- a/src/mscorlib/src/System/Runtime/InteropServices/ExternalException.cs +++ b/src/mscorlib/src/System/Runtime/InteropServices/ExternalException.cs @@ -52,7 +52,6 @@ namespace System.Runtime.InteropServices { } } -#if !FEATURE_CORECLR // Breaks the subset-of-Orcas property public override String ToString() { String message = Message; String s; @@ -75,6 +74,5 @@ namespace System.Runtime.InteropServices { return s; } -#endif // !FEATURE_CORECLR } } diff --git a/src/mscorlib/src/System/Runtime/InteropServices/GcHandle.cs b/src/mscorlib/src/System/Runtime/InteropServices/GcHandle.cs index 58fea97cb8..5530819c5f 100644 --- a/src/mscorlib/src/System/Runtime/InteropServices/GcHandle.cs +++ b/src/mscorlib/src/System/Runtime/InteropServices/GcHandle.cs @@ -47,7 +47,6 @@ namespace System.Runtime.InteropServices private const GCHandleType MaxHandleType = GCHandleType.Pinned; #if MDA_SUPPORTED - [System.Security.SecuritySafeCritical] // auto-generated static GCHandle() { s_probeIsActive = Mda.IsInvalidGCHandleCookieProbeEnabled(); @@ -57,12 +56,11 @@ namespace System.Runtime.InteropServices #endif // Allocate a handle storing the object and the type. - [System.Security.SecurityCritical] // auto-generated internal GCHandle(Object value, GCHandleType type) { // Make sure the type parameter is within the valid range for the enum. if ((uint)type > (uint)MaxHandleType) - throw new ArgumentOutOfRangeException("type", Environment.GetResourceString("ArgumentOutOfRange_Enum")); + throw new ArgumentOutOfRangeException(nameof(type), Environment.GetResourceString("ArgumentOutOfRange_Enum")); Contract.EndContractBlock(); m_handle = InternalAlloc(value, type); @@ -73,7 +71,6 @@ namespace System.Runtime.InteropServices } // Used in the conversion functions below. - [System.Security.SecurityCritical] // auto-generated internal GCHandle(IntPtr handle) { InternalCheckDomain(handle); @@ -86,13 +83,11 @@ namespace System.Runtime.InteropServices // type - The type of GC handle to create. // // returns a new GC handle that protects the object. - [System.Security.SecurityCritical] // auto-generated_required public static GCHandle Alloc(Object value) { return new GCHandle(value, GCHandleType.Normal); } - [System.Security.SecurityCritical] // auto-generated_required public static GCHandle Alloc(Object value, GCHandleType type) { return new GCHandle(value, type); @@ -100,7 +95,6 @@ namespace System.Runtime.InteropServices // Frees a GC handle. - [System.Security.SecurityCritical] // auto-generated_required public void Free() { // Copy the handle instance member to a local variable. This is required to prevent @@ -134,7 +128,6 @@ namespace System.Runtime.InteropServices // Target property - allows getting / updating of the handle's referent. public Object Target { - [System.Security.SecurityCritical] // auto-generated_required get { // Check if the handle was never initialized or was freed. @@ -144,7 +137,6 @@ namespace System.Runtime.InteropServices return InternalGet(GetHandleValue()); } - [System.Security.SecurityCritical] // auto-generated_required set { // Check if the handle was never initialized or was freed. @@ -157,7 +149,6 @@ namespace System.Runtime.InteropServices // Retrieve the address of an object in a Pinned handle. This throws // an exception if the handle is any type other than Pinned. - [System.Security.SecurityCritical] // auto-generated_required public IntPtr AddrOfPinnedObject() { // Check if the handle was not a pinned handle. @@ -186,13 +177,11 @@ namespace System.Runtime.InteropServices // Used to create a GCHandle from an int. This is intended to // be used with the reverse conversion. - [System.Security.SecurityCritical] // auto-generated_required public static explicit operator GCHandle(IntPtr value) { return FromIntPtr(value); } - [System.Security.SecurityCritical] // auto-generated_required public static GCHandle FromIntPtr(IntPtr value) { if (value == IntPtr.Zero) @@ -293,28 +282,20 @@ namespace System.Runtime.InteropServices } // Internal native calls that this implementation uses. - [System.Security.SecurityCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.InternalCall)] internal static extern IntPtr InternalAlloc(Object value, GCHandleType type); - [System.Security.SecurityCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.InternalCall)] internal static extern void InternalFree(IntPtr handle); - [System.Security.SecurityCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.InternalCall)] internal static extern Object InternalGet(IntPtr handle); - [System.Security.SecurityCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.InternalCall)] internal static extern void InternalSet(IntPtr handle, Object value, bool isPinned); - [System.Security.SecurityCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.InternalCall)] internal static extern Object InternalCompareExchange(IntPtr handle, Object value, Object oldValue, bool isPinned); - [System.Security.SecurityCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.InternalCall)] internal static extern IntPtr InternalAddrOfPinnedObject(IntPtr handle); - [System.Security.SecurityCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.InternalCall)] internal static extern void InternalCheckDomain(IntPtr handle); - [System.Security.SecurityCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.InternalCall)] internal static extern GCHandleType InternalGetHandleType(IntPtr handle); diff --git a/src/mscorlib/src/System/Runtime/InteropServices/ICustomQueryInterface.cs b/src/mscorlib/src/System/Runtime/InteropServices/ICustomQueryInterface.cs index 61688b90b4..c7d7937895 100644 --- a/src/mscorlib/src/System/Runtime/InteropServices/ICustomQueryInterface.cs +++ b/src/mscorlib/src/System/Runtime/InteropServices/ICustomQueryInterface.cs @@ -33,7 +33,6 @@ namespace System.Runtime.InteropServices { [System.Runtime.InteropServices.ComVisible(false)] public interface ICustomQueryInterface { - [System.Security.SecurityCritical] CustomQueryInterfaceResult GetInterface([In]ref Guid iid, out IntPtr ppv); } } diff --git a/src/mscorlib/src/System/Runtime/InteropServices/IException.cs b/src/mscorlib/src/System/Runtime/InteropServices/IException.cs index 2da0a564a2..2330365834 100644 --- a/src/mscorlib/src/System/Runtime/InteropServices/IException.cs +++ b/src/mscorlib/src/System/Runtime/InteropServices/IException.cs @@ -22,48 +22,9 @@ namespace System.Runtime.InteropServices { [GuidAttribute("b36b5c63-42ef-38bc-a07e-0b34c98f164a")] [InterfaceTypeAttribute(ComInterfaceType.InterfaceIsDual)] [CLSCompliant(false)] -[System.Runtime.InteropServices.ComVisible(true)] + [System.Runtime.InteropServices.ComVisible(true)] public interface _Exception { -#if !FEATURE_CORECLR - // This contains all of our V1 Exception class's members. - - // From Object - String ToString(); - bool Equals (Object obj); - int GetHashCode (); - Type GetType (); - - // From V1's Exception class - String Message { - get; - } - - Exception GetBaseException(); - - String StackTrace { - get; - } - - String HelpLink { - get; - set; - } - - String Source { - #if FEATURE_CORECLR - [System.Security.SecurityCritical] // auto-generated - #endif - get; - #if FEATURE_CORECLR - [System.Security.SecurityCritical] // auto-generated - #endif - set; - } - [System.Security.SecurityCritical] // auto-generated_required - void GetObjectData(SerializationInfo info, StreamingContext context); -#endif - // // This method is intentionally included in CoreCLR to make Exception.get_InnerException "newslot virtual final". // Some phone apps include MEF from desktop Silverlight. MEF's ComposablePartException depends on implicit interface @@ -73,12 +34,5 @@ namespace System.Runtime.InteropServices { Exception InnerException { get; } - -#if !FEATURE_CORECLR - MethodBase TargetSite { - get; - } -#endif } - } diff --git a/src/mscorlib/src/System/Runtime/InteropServices/IRegistrationServices.cs b/src/mscorlib/src/System/Runtime/InteropServices/IRegistrationServices.cs index ae330e8652..f2f7c61843 100644 --- a/src/mscorlib/src/System/Runtime/InteropServices/IRegistrationServices.cs +++ b/src/mscorlib/src/System/Runtime/InteropServices/IRegistrationServices.cs @@ -31,24 +31,18 @@ namespace System.Runtime.InteropServices { [System.Runtime.InteropServices.ComVisible(true)] public interface IRegistrationServices { - [System.Security.SecurityCritical] // auto-generated_required bool RegisterAssembly(Assembly assembly, AssemblyRegistrationFlags flags); - [System.Security.SecurityCritical] // auto-generated_required bool UnregisterAssembly(Assembly assembly); - [System.Security.SecurityCritical] // auto-generated_required Type[] GetRegistrableTypesInAssembly(Assembly assembly); - [System.Security.SecurityCritical] // auto-generated_required String GetProgIdForType(Type type); - [System.Security.SecurityCritical] // auto-generated_required void RegisterTypeForComClients(Type type, ref Guid g); Guid GetManagedCategoryGuid(); - [System.Security.SecurityCritical] // auto-generated_required bool TypeRequiresRegistration(Type type); bool TypeRepresentsComType(Type type); diff --git a/src/mscorlib/src/System/Runtime/InteropServices/Marshal.cs b/src/mscorlib/src/System/Runtime/InteropServices/Marshal.cs index 86e88306f0..3a79650bd9 100644 --- a/src/mscorlib/src/System/Runtime/InteropServices/Marshal.cs +++ b/src/mscorlib/src/System/Runtime/InteropServices/Marshal.cs @@ -29,6 +29,7 @@ namespace System.Runtime.InteropServices using System.Runtime.Versioning; using Win32Native = Microsoft.Win32.Win32Native; using Microsoft.Win32.SafeHandles; + using System.Diagnostics; using System.Diagnostics.Contracts; using System.Runtime.InteropServices.ComTypes; @@ -45,9 +46,6 @@ namespace System.Runtime.InteropServices // declaration on the class. //======================================================================== - #if FEATURE_CORECLR - [System.Security.SecurityCritical] // auto-generated - #endif public static partial class Marshal { //==================================================================== @@ -117,7 +115,6 @@ namespace System.Runtime.InteropServices [MethodImplAttribute(MethodImplOptions.InternalCall)] private static extern int GetSystemMaxDBCSCharSize(); - [System.Security.SecurityCritical] // auto-generated_required unsafe public static String PtrToStringAnsi(IntPtr ptr) { if (IntPtr.Zero == ptr) { @@ -137,36 +134,32 @@ namespace System.Runtime.InteropServices } } - [System.Security.SecurityCritical] // auto-generated_required unsafe public static String PtrToStringAnsi(IntPtr ptr, int len) { if (ptr == IntPtr.Zero) - throw new ArgumentNullException("ptr"); + throw new ArgumentNullException(nameof(ptr)); if (len < 0) - throw new ArgumentException("len"); + throw new ArgumentException(null, nameof(len)); return new String((sbyte *)ptr, 0, len); } - [System.Security.SecurityCritical] // auto-generated_required unsafe public static String PtrToStringUni(IntPtr ptr, int len) { if (ptr == IntPtr.Zero) - throw new ArgumentNullException("ptr"); + throw new ArgumentNullException(nameof(ptr)); if (len < 0) - throw new ArgumentException("len"); + throw new ArgumentException(null, nameof(len)); return new String((char *)ptr, 0, len); } - [System.Security.SecurityCritical] // auto-generated_required public static String PtrToStringAuto(IntPtr ptr, int len) { // Ansi platforms are no longer supported return PtrToStringUni(ptr, len); } - [System.Security.SecurityCritical] // auto-generated_required unsafe public static String PtrToStringUni(IntPtr ptr) { if (IntPtr.Zero == ptr) { @@ -180,26 +173,23 @@ namespace System.Runtime.InteropServices } } - [System.Security.SecurityCritical] // auto-generated_required public static String PtrToStringAuto(IntPtr ptr) { // Ansi platforms are no longer supported return PtrToStringUni(ptr); } - [System.Security.SecurityCritical] // auto-generated_required unsafe public static String PtrToStringUTF8(IntPtr ptr) { int nbBytes = System.StubHelpers.StubHelpers.strlen((sbyte*)ptr.ToPointer()); return PtrToStringUTF8(ptr, nbBytes); } - [System.Security.SecurityCritical] // auto-generated_required unsafe public static String PtrToStringUTF8(IntPtr ptr,int byteLen) { if (byteLen < 0) { - throw new ArgumentException("byteLen"); + throw new ArgumentException(null, nameof(byteLen)); } else if (IntPtr.Zero == ptr) { @@ -227,7 +217,7 @@ namespace System.Runtime.InteropServices public static int SizeOf(Object structure) { if (structure == null) - throw new ArgumentNullException("structure"); + throw new ArgumentNullException(nameof(structure)); // we never had a check for generics here Contract.EndContractBlock(); @@ -243,11 +233,11 @@ namespace System.Runtime.InteropServices public static int SizeOf(Type t) { if (t == null) - throw new ArgumentNullException("t"); + throw new ArgumentNullException(nameof(t)); if (!(t is RuntimeType)) - throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeType"), "t"); + throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeType"), nameof(t)); if (t.IsGenericType) - throw new ArgumentException(Environment.GetResourceString("Argument_NeedNonGenericType"), "t"); + throw new ArgumentException(Environment.GetResourceString("Argument_NeedNonGenericType"), nameof(t)); Contract.EndContractBlock(); return SizeOfHelper(t, true); @@ -290,9 +280,6 @@ namespace System.Runtime.InteropServices [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] private static extern uint AlignedSizeOfType(Type type); -#if !FEATURE_CORECLR // Marshal is critical in CoreCLR, so SafeCritical members trigger Annotator violations - [System.Security.SecuritySafeCritical] -#endif // !FEATURE_CORECLR [MethodImplAttribute(MethodImplOptions.InternalCall)] internal static extern int SizeOfHelper(Type t, bool throwIfNotMarshalable); @@ -302,15 +289,15 @@ namespace System.Runtime.InteropServices public static IntPtr OffsetOf(Type t, String fieldName) { if (t == null) - throw new ArgumentNullException("t"); + throw new ArgumentNullException(nameof(t)); Contract.EndContractBlock(); FieldInfo f = t.GetField(fieldName, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); if (f == null) - throw new ArgumentException(Environment.GetResourceString("Argument_OffsetOfFieldNotFound", t.FullName), "fieldName"); + throw new ArgumentException(Environment.GetResourceString("Argument_OffsetOfFieldNotFound", t.FullName), nameof(fieldName)); RtFieldInfo rtField = f as RtFieldInfo; if (rtField == null) - throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeFieldInfo"), "fieldName"); + throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeFieldInfo"), nameof(fieldName)); return OffsetOfHelper(rtField); } @@ -330,11 +317,9 @@ namespace System.Runtime.InteropServices // an array that is not pinned or in the fixed heap can cause // unexpected results ! //==================================================================== - [System.Security.SecurityCritical] // auto-generated_required [MethodImplAttribute(MethodImplOptions.InternalCall)] public static extern IntPtr UnsafeAddrOfPinnedArrayElement(Array arr, int index); - [System.Security.SecurityCritical] public static IntPtr UnsafeAddrOfPinnedArrayElement<T>(T[] arr, int index) { return UnsafeAddrOfPinnedArrayElement((Array)arr, index); @@ -343,42 +328,34 @@ namespace System.Runtime.InteropServices //==================================================================== // Copy blocks from CLR arrays to native memory. //==================================================================== - [System.Security.SecurityCritical] // auto-generated_required public static void Copy(int[] source, int startIndex, IntPtr destination, int length) { CopyToNative(source, startIndex, destination, length); } - [System.Security.SecurityCritical] // auto-generated_required public static void Copy(char[] source, int startIndex, IntPtr destination, int length) { CopyToNative(source, startIndex, destination, length); } - [System.Security.SecurityCritical] // auto-generated_required public static void Copy(short[] source, int startIndex, IntPtr destination, int length) { CopyToNative(source, startIndex, destination, length); } - [System.Security.SecurityCritical] // auto-generated_required public static void Copy(long[] source, int startIndex, IntPtr destination, int length) { CopyToNative(source, startIndex, destination, length); } - [System.Security.SecurityCritical] // auto-generated_required public static void Copy(float[] source, int startIndex, IntPtr destination, int length) { CopyToNative(source, startIndex, destination, length); } - [System.Security.SecurityCritical] // auto-generated_required public static void Copy(double[] source, int startIndex, IntPtr destination, int length) { CopyToNative(source, startIndex, destination, length); } - [System.Security.SecurityCritical] // auto-generated_required public static void Copy(byte[] source, int startIndex, IntPtr destination, int length) { CopyToNative(source, startIndex, destination, length); } - [System.Security.SecurityCritical] // auto-generated_required public static void Copy(IntPtr[] source, int startIndex, IntPtr destination, int length) { CopyToNative(source, startIndex, destination, length); @@ -389,42 +366,34 @@ namespace System.Runtime.InteropServices //==================================================================== // Copy blocks from native memory to CLR arrays //==================================================================== - [System.Security.SecurityCritical] // auto-generated_required public static void Copy(IntPtr source, int[] destination, int startIndex, int length) { CopyToManaged(source, destination, startIndex, length); } - [System.Security.SecurityCritical] // auto-generated_required public static void Copy(IntPtr source, char[] destination, int startIndex, int length) { CopyToManaged(source, destination, startIndex, length); } - [System.Security.SecurityCritical] // auto-generated_required public static void Copy(IntPtr source, short[] destination, int startIndex, int length) { CopyToManaged(source, destination, startIndex, length); } - [System.Security.SecurityCritical] // auto-generated_required public static void Copy(IntPtr source, long[] destination, int startIndex, int length) { CopyToManaged(source, destination, startIndex, length); } - [System.Security.SecurityCritical] // auto-generated_required public static void Copy(IntPtr source, float[] destination, int startIndex, int length) { CopyToManaged(source, destination, startIndex, length); } - [System.Security.SecurityCritical] // auto-generated_required public static void Copy(IntPtr source, double[] destination, int startIndex, int length) { CopyToManaged(source, destination, startIndex, length); } - [System.Security.SecurityCritical] // auto-generated_required public static void Copy(IntPtr source, byte[] destination, int startIndex, int length) { CopyToManaged(source, destination, startIndex, length); } - [System.Security.SecurityCritical] // auto-generated_required public static void Copy(IntPtr source, IntPtr[] destination, int startIndex, int length) { CopyToManaged(source, destination, startIndex, length); @@ -435,19 +404,11 @@ namespace System.Runtime.InteropServices //==================================================================== // Read from memory //==================================================================== - [System.Security.SecurityCritical] // auto-generated -#if !FEATURE_CORECLR - [DllImport(Win32Native.SHIM, EntryPoint="ND_RU1")] - [SuppressUnmanagedCodeSecurity] - public static extern byte ReadByte([MarshalAs(UnmanagedType.AsAny), In] Object ptr, int ofs); -#else public static byte ReadByte([MarshalAs(UnmanagedType.AsAny), In] Object ptr, int ofs) { throw new PlatformNotSupportedException(); - } -#endif // !FEATURE_CORECLR + } - [System.Security.SecurityCritical] // auto-generated_required public static unsafe byte ReadByte(IntPtr ptr, int ofs) { try @@ -462,25 +423,16 @@ namespace System.Runtime.InteropServices } } - [System.Security.SecurityCritical] // auto-generated_required public static byte ReadByte(IntPtr ptr) { return ReadByte(ptr,0); } - - [System.Security.SecurityCritical] // auto-generated -#if !FEATURE_CORECLR - [DllImport(Win32Native.SHIM, EntryPoint="ND_RI2")] - [SuppressUnmanagedCodeSecurity] - public static extern short ReadInt16([MarshalAs(UnmanagedType.AsAny),In] Object ptr, int ofs); -#else + public static short ReadInt16([MarshalAs(UnmanagedType.AsAny),In] Object ptr, int ofs) { throw new PlatformNotSupportedException(); - } -#endif // !FEATURE_CORECLR + } - [System.Security.SecurityCritical] // auto-generated_required public static unsafe short ReadInt16(IntPtr ptr, int ofs) { try @@ -508,25 +460,16 @@ namespace System.Runtime.InteropServices } } - [System.Security.SecurityCritical] // auto-generated_required public static short ReadInt16(IntPtr ptr) { return ReadInt16(ptr, 0); } - - [System.Security.SecurityCritical] // auto-generated -#if !FEATURE_CORECLR - [DllImport(Win32Native.SHIM, EntryPoint="ND_RI4"), ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] - [SuppressUnmanagedCodeSecurity] - public static extern int ReadInt32([MarshalAs(UnmanagedType.AsAny),In] Object ptr, int ofs); -#else + public static int ReadInt32([MarshalAs(UnmanagedType.AsAny),In] Object ptr, int ofs) { throw new PlatformNotSupportedException(); } -#endif // !FEATURE_CORECLR - [System.Security.SecurityCritical] // auto-generated_required [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] public static unsafe int ReadInt32(IntPtr ptr, int ofs) { @@ -557,14 +500,12 @@ namespace System.Runtime.InteropServices } } - [System.Security.SecurityCritical] // auto-generated_required [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] public static int ReadInt32(IntPtr ptr) { return ReadInt32(ptr,0); } - [System.Security.SecurityCritical] // auto-generated_required [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] public static IntPtr ReadIntPtr([MarshalAs(UnmanagedType.AsAny),In] Object ptr, int ofs) { @@ -575,7 +516,6 @@ namespace System.Runtime.InteropServices #endif } - [System.Security.SecurityCritical] // auto-generated_required [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] public static IntPtr ReadIntPtr(IntPtr ptr, int ofs) { @@ -586,7 +526,6 @@ namespace System.Runtime.InteropServices #endif } - [System.Security.SecurityCritical] // auto-generated_required [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] public static IntPtr ReadIntPtr(IntPtr ptr) { @@ -597,19 +536,11 @@ namespace System.Runtime.InteropServices #endif } - [System.Security.SecurityCritical] // auto-generated -#if !FEATURE_CORECLR - [DllImport(Win32Native.SHIM, EntryPoint="ND_RI8"), ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] - [SuppressUnmanagedCodeSecurity] - public static extern long ReadInt64([MarshalAs(UnmanagedType.AsAny),In] Object ptr, int ofs); -#else public static long ReadInt64([MarshalAs(UnmanagedType.AsAny),In] Object ptr, int ofs) { throw new PlatformNotSupportedException(); } -#endif // !FEATURE_CORECLR - [System.Security.SecurityCritical] // auto-generated_required public static unsafe long ReadInt64(IntPtr ptr, int ofs) { try @@ -643,7 +574,6 @@ namespace System.Runtime.InteropServices } } - [System.Security.SecurityCritical] // auto-generated_required [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] public static long ReadInt64(IntPtr ptr) { @@ -654,7 +584,6 @@ namespace System.Runtime.InteropServices //==================================================================== // Write to memory //==================================================================== - [System.Security.SecurityCritical] // auto-generated_required public static unsafe void WriteByte(IntPtr ptr, int ofs, byte val) { try @@ -669,25 +598,16 @@ namespace System.Runtime.InteropServices } } - [System.Security.SecurityCritical] // auto-generated -#if !FEATURE_CORECLR - [DllImport(Win32Native.SHIM, EntryPoint="ND_WU1")] - [SuppressUnmanagedCodeSecurity] - public static extern void WriteByte([MarshalAs(UnmanagedType.AsAny),In,Out] Object ptr, int ofs, byte val); -#else public static void WriteByte([MarshalAs(UnmanagedType.AsAny),In,Out] Object ptr, int ofs, byte val) { throw new PlatformNotSupportedException(); } -#endif // !FEATURE_CORECLR - [System.Security.SecurityCritical] // auto-generated_required public static void WriteByte(IntPtr ptr, byte val) { WriteByte(ptr, 0, val); } - [System.Security.SecurityCritical] // auto-generated_required public static unsafe void WriteInt16(IntPtr ptr, int ofs, short val) { try @@ -712,44 +632,32 @@ namespace System.Runtime.InteropServices throw new AccessViolationException(); } } - - [System.Security.SecurityCritical] // auto-generated -#if !FEATURE_CORECLR - [DllImport(Win32Native.SHIM, EntryPoint="ND_WI2")] - [SuppressUnmanagedCodeSecurity] - public static extern void WriteInt16([MarshalAs(UnmanagedType.AsAny),In,Out] Object ptr, int ofs, short val); -#else + public static void WriteInt16([MarshalAs(UnmanagedType.AsAny),In,Out] Object ptr, int ofs, short val) { throw new PlatformNotSupportedException(); } -#endif // !FEATURE_CORECLR - - [System.Security.SecurityCritical] // auto-generated_required + public static void WriteInt16(IntPtr ptr, short val) { WriteInt16(ptr, 0, val); } - [System.Security.SecurityCritical] // auto-generated_required public static void WriteInt16(IntPtr ptr, int ofs, char val) { WriteInt16(ptr, ofs, (short)val); } - [System.Security.SecurityCritical] // auto-generated_required public static void WriteInt16([In,Out]Object ptr, int ofs, char val) { WriteInt16(ptr, ofs, (short)val); } - [System.Security.SecurityCritical] // auto-generated_required public static void WriteInt16(IntPtr ptr, char val) { WriteInt16(ptr, 0, (short)val); } - [System.Security.SecurityCritical] // auto-generated_required public static unsafe void WriteInt32(IntPtr ptr, int ofs, int val) { try @@ -776,26 +684,17 @@ namespace System.Runtime.InteropServices throw new AccessViolationException(); } } - - [System.Security.SecurityCritical] // auto-generated -#if !FEATURE_CORECLR - [DllImport(Win32Native.SHIM, EntryPoint="ND_WI4")] - [SuppressUnmanagedCodeSecurity] - public static extern void WriteInt32([MarshalAs(UnmanagedType.AsAny),In,Out] Object ptr, int ofs, int val); -#else + public static void WriteInt32([MarshalAs(UnmanagedType.AsAny),In,Out] Object ptr, int ofs, int val) { throw new PlatformNotSupportedException(); } -#endif // !FEATURE_CORECLR - [System.Security.SecurityCritical] // auto-generated_required public static void WriteInt32(IntPtr ptr, int val) { WriteInt32(ptr,0,val); } - [System.Security.SecurityCritical] // auto-generated_required public static void WriteIntPtr(IntPtr ptr, int ofs, IntPtr val) { #if BIT64 @@ -805,7 +704,6 @@ namespace System.Runtime.InteropServices #endif } - [System.Security.SecurityCritical] // auto-generated_required public static void WriteIntPtr([MarshalAs(UnmanagedType.AsAny),In,Out] Object ptr, int ofs, IntPtr val) { #if BIT64 @@ -815,7 +713,6 @@ namespace System.Runtime.InteropServices #endif } - [System.Security.SecurityCritical] // auto-generated_required public static void WriteIntPtr(IntPtr ptr, IntPtr val) { #if BIT64 @@ -825,7 +722,6 @@ namespace System.Runtime.InteropServices #endif } - [System.Security.SecurityCritical] // auto-generated_required public static unsafe void WriteInt64(IntPtr ptr, int ofs, long val) { try @@ -856,20 +752,12 @@ namespace System.Runtime.InteropServices throw new AccessViolationException(); } } - - [System.Security.SecurityCritical] // auto-generated -#if !FEATURE_CORECLR - [DllImport(Win32Native.SHIM, EntryPoint="ND_WI8")] - [SuppressUnmanagedCodeSecurity] - public static extern void WriteInt64([MarshalAs(UnmanagedType.AsAny),In,Out] Object ptr, int ofs, long val); -#else + public static void WriteInt64([MarshalAs(UnmanagedType.AsAny),In,Out] Object ptr, int ofs, long val) { throw new PlatformNotSupportedException(); } -#endif // !FEATURE_CORECLR - [System.Security.SecurityCritical] // auto-generated_required public static void WriteInt64(IntPtr ptr, long val) { WriteInt64(ptr, 0, val); @@ -879,7 +767,6 @@ namespace System.Runtime.InteropServices //==================================================================== // GetLastWin32Error //==================================================================== - [System.Security.SecurityCritical] // auto-generated_required [MethodImplAttribute(MethodImplOptions.InternalCall)] [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] public static extern int GetLastWin32Error(); @@ -896,7 +783,6 @@ namespace System.Runtime.InteropServices //==================================================================== // GetHRForLastWin32Error //==================================================================== - [System.Security.SecurityCritical] // auto-generated_required [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] public static int GetHRForLastWin32Error() { @@ -911,11 +797,10 @@ namespace System.Runtime.InteropServices //==================================================================== // Prelink //==================================================================== - [System.Security.SecurityCritical] // auto-generated_required public static void Prelink(MethodInfo m) { if (m == null) - throw new ArgumentNullException("m"); + throw new ArgumentNullException(nameof(m)); Contract.EndContractBlock(); RuntimeMethodInfo rmi = m as RuntimeMethodInfo; @@ -927,14 +812,12 @@ namespace System.Runtime.InteropServices } [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode), SuppressUnmanagedCodeSecurity] - [SecurityCritical] private static extern void InternalPrelink(IRuntimeMethodInfo m); - [System.Security.SecurityCritical] // auto-generated_required public static void PrelinkAll(Type c) { if (c == null) - throw new ArgumentNullException("c"); + throw new ArgumentNullException(nameof(c)); Contract.EndContractBlock(); MethodInfo[] mi = c.GetMethods(); @@ -950,11 +833,10 @@ namespace System.Runtime.InteropServices //==================================================================== // NumParamBytes //==================================================================== - [System.Security.SecurityCritical] // auto-generated_required public static int NumParamBytes(MethodInfo m) { if (m == null) - throw new ArgumentNullException("m"); + throw new ArgumentNullException(nameof(m)); Contract.EndContractBlock(); RuntimeMethodInfo rmi = m as RuntimeMethodInfo; @@ -965,7 +847,6 @@ namespace System.Runtime.InteropServices } [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode), SuppressUnmanagedCodeSecurity] - [SecurityCritical] private static extern int InternalNumParamBytes(IRuntimeMethodInfo m); //==================================================================== @@ -973,12 +854,10 @@ namespace System.Runtime.InteropServices // These are mostly interesting for Structured exception handling, // but need to be exposed for all exceptions (not just SEHException). //==================================================================== - [System.Security.SecurityCritical] // auto-generated_required [MethodImplAttribute(MethodImplOptions.InternalCall)] [System.Runtime.InteropServices.ComVisible(true)] public static extern /* struct _EXCEPTION_POINTERS* */ IntPtr GetExceptionPointers(); - [System.Security.SecurityCritical] // auto-generated_required [MethodImplAttribute(MethodImplOptions.InternalCall)] public static extern int GetExceptionCode(); @@ -988,12 +867,10 @@ namespace System.Runtime.InteropServices // If the structure contains pointers to allocated blocks and // "fDeleteOld" is true, this routine will call DestroyStructure() first. //==================================================================== - [System.Security.SecurityCritical] // auto-generated_required [MethodImplAttribute(MethodImplOptions.InternalCall), ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)] [System.Runtime.InteropServices.ComVisible(true)] public static extern void StructureToPtr(Object structure, IntPtr ptr, bool fDeleteOld); - [System.Security.SecurityCritical] public static void StructureToPtr<T>(T structure, IntPtr ptr, bool fDeleteOld) { StructureToPtr((object)structure, ptr, fDeleteOld); @@ -1002,14 +879,12 @@ namespace System.Runtime.InteropServices //==================================================================== // Marshals data from a native memory block to a preallocated structure class. //==================================================================== - [System.Security.SecurityCritical] // auto-generated_required [System.Runtime.InteropServices.ComVisible(true)] public static void PtrToStructure(IntPtr ptr, Object structure) { PtrToStructureHelper(ptr, structure, false); } - [System.Security.SecurityCritical] public static void PtrToStructure<T>(IntPtr ptr, T structure) { PtrToStructure(ptr, (object)structure); @@ -1019,7 +894,6 @@ namespace System.Runtime.InteropServices // Creates a new instance of "structuretype" and marshals data from a // native memory block to it. //==================================================================== - [System.Security.SecurityCritical] // auto-generated_required [System.Runtime.InteropServices.ComVisible(true)] [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable public static Object PtrToStructure(IntPtr ptr, Type structureType) @@ -1027,15 +901,15 @@ namespace System.Runtime.InteropServices if (ptr == IntPtr.Zero) return null; if (structureType == null) - throw new ArgumentNullException("structureType"); + throw new ArgumentNullException(nameof(structureType)); if (structureType.IsGenericType) - throw new ArgumentException(Environment.GetResourceString("Argument_NeedNonGenericType"), "structureType"); + throw new ArgumentException(Environment.GetResourceString("Argument_NeedNonGenericType"), nameof(structureType)); RuntimeType rt = structureType.UnderlyingSystemType as RuntimeType; if (rt == null) - throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"), "type"); + throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"), nameof(structureType)); StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; @@ -1044,7 +918,6 @@ namespace System.Runtime.InteropServices return structure; } - [System.Security.SecurityCritical] public static T PtrToStructure<T>(IntPtr ptr) { return (T)PtrToStructure(ptr, typeof(T)); @@ -1061,27 +934,25 @@ namespace System.Runtime.InteropServices // Freeds all substructures pointed to by the native memory block. // "structureclass" is used to provide layout information. //==================================================================== - [System.Security.SecurityCritical] // auto-generated_required [MethodImplAttribute(MethodImplOptions.InternalCall)] [System.Runtime.InteropServices.ComVisible(true)] public static extern void DestroyStructure(IntPtr ptr, Type structuretype); - [System.Security.SecurityCritical] public static void DestroyStructure<T>(IntPtr ptr) { DestroyStructure(ptr, typeof(T)); } +#if FEATURE_COMINTEROP //==================================================================== // Returns the HInstance for this module. Returns -1 if the module // doesn't have an HInstance. In Memory (Dynamic) Modules won't have // an HInstance. //==================================================================== - [System.Security.SecurityCritical] // auto-generated_required public static IntPtr GetHINSTANCE(Module m) { if (m == null) - throw new ArgumentNullException("m"); + throw new ArgumentNullException(nameof(m)); Contract.EndContractBlock(); RuntimeModule rtModule = m as RuntimeModule; @@ -1093,26 +964,24 @@ namespace System.Runtime.InteropServices } if (rtModule == null) - throw new ArgumentNullException("m",Environment.GetResourceString("Argument_MustBeRuntimeModule")); + throw new ArgumentNullException(nameof(m),Environment.GetResourceString("Argument_MustBeRuntimeModule")); return GetHINSTANCE(rtModule.GetNativeHandle()); } - [System.Security.SecurityCritical] // auto-generated_required [SuppressUnmanagedCodeSecurity] [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode), SuppressUnmanagedCodeSecurity] private extern static IntPtr GetHINSTANCE(RuntimeModule m); +#endif // FEATURE_COMINTEROP //==================================================================== // Throws a CLR exception based on the HRESULT. //==================================================================== - [System.Security.SecurityCritical] // auto-generated_required public static void ThrowExceptionForHR(int errorCode) { if (errorCode < 0) ThrowExceptionForHRInternal(errorCode, IntPtr.Zero); } - [System.Security.SecurityCritical] // auto-generated_required public static void ThrowExceptionForHR(int errorCode, IntPtr errorInfo) { if (errorCode < 0) @@ -1126,7 +995,6 @@ namespace System.Runtime.InteropServices //==================================================================== // Converts the HRESULT to a CLR exception. //==================================================================== - [System.Security.SecurityCritical] // auto-generated_required public static Exception GetExceptionForHR(int errorCode) { if (errorCode < 0) @@ -1134,7 +1002,6 @@ namespace System.Runtime.InteropServices else return null; } - [System.Security.SecurityCritical] // auto-generated_required public static Exception GetExceptionForHR(int errorCode, IntPtr errorInfo) { if (errorCode < 0) @@ -1151,7 +1018,6 @@ namespace System.Runtime.InteropServices // This method is intended for compiler code generators rather // than applications. //==================================================================== - [System.Security.SecurityCritical] // auto-generated_required [ObsoleteAttribute("The GetUnmanagedThunkForManagedMethodPtr method has been deprecated and will be removed in a future release.", false)] [MethodImplAttribute(MethodImplOptions.InternalCall)] public static extern IntPtr GetUnmanagedThunkForManagedMethodPtr(IntPtr pfnMethodToWrap, IntPtr pbSignature, int cbSignature); @@ -1160,7 +1026,6 @@ namespace System.Runtime.InteropServices // This method is intended for compiler code generators rather // than applications. //==================================================================== - [System.Security.SecurityCritical] // auto-generated_required [ObsoleteAttribute("The GetManagedThunkForUnmanagedMethodPtr method has been deprecated and will be removed in a future release.", false)] [MethodImplAttribute(MethodImplOptions.InternalCall)] public static extern IntPtr GetManagedThunkForUnmanagedMethodPtr(IntPtr pfnMethodToWrap, IntPtr pbSignature, int cbSignature); @@ -1171,12 +1036,11 @@ namespace System.Runtime.InteropServices // activity. A fiber cookie can be redeemed for its managed Thread // object by calling the following service. //==================================================================== - [System.Security.SecurityCritical] // auto-generated_required [ObsoleteAttribute("The GetThreadFromFiberCookie method has been deprecated. Use the hosting API to perform this operation.", false)] public static Thread GetThreadFromFiberCookie(int cookie) { if (cookie == 0) - throw new ArgumentException(Environment.GetResourceString("Argument_ArgumentZero"), "cookie"); + throw new ArgumentException(Environment.GetResourceString("Argument_ArgumentZero"), nameof(cookie)); Contract.EndContractBlock(); return InternalGetThreadFromFiberCookie(cookie); @@ -1189,7 +1053,6 @@ namespace System.Runtime.InteropServices //==================================================================== // Memory allocation and deallocation. //==================================================================== - [System.Security.SecurityCritical] // auto-generated_required [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)] public static IntPtr AllocHGlobal(IntPtr cb) { @@ -1214,14 +1077,12 @@ namespace System.Runtime.InteropServices return pNewMem; } - [System.Security.SecurityCritical] // auto-generated_required [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)] public static IntPtr AllocHGlobal(int cb) { return AllocHGlobal((IntPtr)cb); } - [System.Security.SecurityCritical] // auto-generated_required [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] public static void FreeHGlobal(IntPtr hglobal) { @@ -1232,7 +1093,6 @@ namespace System.Runtime.InteropServices } } - [System.Security.SecurityCritical] // auto-generated_required public static IntPtr ReAllocHGlobal(IntPtr pv, IntPtr cb) { IntPtr pNewMem = Win32Native.LocalReAlloc(pv, cb, LMEM_MOVEABLE); @@ -1246,7 +1106,6 @@ namespace System.Runtime.InteropServices //==================================================================== // String convertions. //==================================================================== - [System.Security.SecurityCritical] // auto-generated_required unsafe public static IntPtr StringToHGlobalAnsi(String s) { if (s == null) @@ -1259,7 +1118,7 @@ namespace System.Runtime.InteropServices // Overflow checking if (nb < s.Length) - throw new ArgumentOutOfRangeException("s"); + throw new ArgumentOutOfRangeException(nameof(s)); UIntPtr len = new UIntPtr((uint)nb); IntPtr hglobal = Win32Native.LocalAlloc_NoSafeHandle(LMEM_FIXED, len); @@ -1276,7 +1135,6 @@ namespace System.Runtime.InteropServices } } - [System.Security.SecurityCritical] // auto-generated_required unsafe public static IntPtr StringToHGlobalUni(String s) { if (s == null) @@ -1289,7 +1147,7 @@ namespace System.Runtime.InteropServices // Overflow checking if (nb < s.Length) - throw new ArgumentOutOfRangeException("s"); + throw new ArgumentOutOfRangeException(nameof(s)); UIntPtr len = new UIntPtr((uint)nb); IntPtr hglobal = Win32Native.LocalAlloc_NoSafeHandle(LMEM_FIXED, len); @@ -1309,7 +1167,6 @@ namespace System.Runtime.InteropServices } } - [System.Security.SecurityCritical] // auto-generated_required public static IntPtr StringToHGlobalAuto(String s) { // Ansi platforms are no longer supported @@ -1322,7 +1179,6 @@ namespace System.Runtime.InteropServices // Converts the CLR exception to an HRESULT. This function also sets // up an IErrorInfo for the exception. //==================================================================== - [System.Security.SecurityCritical] // auto-generated_required [MethodImplAttribute(MethodImplOptions.InternalCall)] public static extern int GetHRForException(Exception e); @@ -1332,7 +1188,6 @@ namespace System.Runtime.InteropServices // This function is only used in WinRT and converts ObjectDisposedException // to RO_E_CLOSED //==================================================================== - [System.Security.SecurityCritical] // auto-generated_required [MethodImplAttribute(MethodImplOptions.InternalCall)] internal static extern int GetHRForException_WinRT(Exception e); @@ -1341,7 +1196,6 @@ namespace System.Runtime.InteropServices //==================================================================== // Given a managed object that wraps a UCOMITypeLib, return its name //==================================================================== - [System.Security.SecurityCritical] // auto-generated_required [Obsolete("Use System.Runtime.InteropServices.Marshal.GetTypeLibName(ITypeLib pTLB) instead. http://go.microsoft.com/fwlink/?linkid=14202&ID=0000011.", false)] public static String GetTypeLibName(UCOMITypeLib pTLB) { @@ -1352,11 +1206,10 @@ namespace System.Runtime.InteropServices //==================================================================== // Given a managed object that wraps an ITypeLib, return its name //==================================================================== - [System.Security.SecurityCritical] // auto-generated_required public static String GetTypeLibName(ITypeLib typelib) { if (typelib == null) - throw new ArgumentNullException("typelib"); + throw new ArgumentNullException(nameof(typelib)); Contract.EndContractBlock(); String strTypeLibName = null; @@ -1373,11 +1226,10 @@ namespace System.Runtime.InteropServices // Internal version of GetTypeLibName // Support GUID_ManagedName which aligns with TlbImp //==================================================================== - [System.Security.SecurityCritical] // auto-generated_required internal static String GetTypeLibNameInternal(ITypeLib typelib) { if (typelib == null) - throw new ArgumentNullException("typelib"); + throw new ArgumentNullException(nameof(typelib)); Contract.EndContractBlock(); // Try GUID_ManagedName first @@ -1415,7 +1267,6 @@ namespace System.Runtime.InteropServices //==================================================================== // Given an managed object that wraps an UCOMITypeLib, return its guid //==================================================================== - [System.Security.SecurityCritical] // auto-generated_required [Obsolete("Use System.Runtime.InteropServices.Marshal.GetTypeLibGuid(ITypeLib pTLB) instead. http://go.microsoft.com/fwlink/?linkid=14202&ID=0000011.", false)] public static Guid GetTypeLibGuid(UCOMITypeLib pTLB) { @@ -1425,7 +1276,6 @@ namespace System.Runtime.InteropServices //==================================================================== // Given an managed object that wraps an ITypeLib, return its guid //==================================================================== - [System.Security.SecurityCritical] // auto-generated_required public static Guid GetTypeLibGuid(ITypeLib typelib) { Guid result = new Guid (); @@ -1439,7 +1289,6 @@ namespace System.Runtime.InteropServices //==================================================================== // Given a managed object that wraps a UCOMITypeLib, return its lcid //==================================================================== - [System.Security.SecurityCritical] // auto-generated_required [Obsolete("Use System.Runtime.InteropServices.Marshal.GetTypeLibLcid(ITypeLib pTLB) instead. http://go.microsoft.com/fwlink/?linkid=14202&ID=0000011.", false)] public static int GetTypeLibLcid(UCOMITypeLib pTLB) { @@ -1449,7 +1298,6 @@ namespace System.Runtime.InteropServices //==================================================================== // Given a managed object that wraps an ITypeLib, return its lcid //==================================================================== - [System.Security.SecurityCritical] // auto-generated_required [MethodImplAttribute(MethodImplOptions.InternalCall)] public static extern int GetTypeLibLcid(ITypeLib typelib); @@ -1463,7 +1311,6 @@ namespace System.Runtime.InteropServices //==================================================================== // Given a managed object that wraps an ITypeInfo, return its guid. //==================================================================== - [System.Security.SecurityCritical] // auto-generated internal static Guid GetTypeInfoGuid(ITypeInfo typeInfo) { Guid result = new Guid (); @@ -1478,16 +1325,15 @@ namespace System.Runtime.InteropServices // Given a assembly, return the TLBID that will be generated for the // typelib exported from the assembly. //==================================================================== - [System.Security.SecurityCritical] // auto-generated_required public static Guid GetTypeLibGuidForAssembly(Assembly asm) { if (asm == null) - throw new ArgumentNullException("asm"); + throw new ArgumentNullException(nameof(asm)); Contract.EndContractBlock(); RuntimeAssembly rtAssembly = asm as RuntimeAssembly; if (rtAssembly == null) - throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeAssembly"), "asm"); + throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeAssembly"), nameof(asm)); Guid result = new Guid(); FCallGetTypeLibGuidForAssembly(ref result, rtAssembly); @@ -1504,16 +1350,15 @@ namespace System.Runtime.InteropServices [MethodImplAttribute(MethodImplOptions.InternalCall)] private static extern void _GetTypeLibVersionForAssembly(RuntimeAssembly inputAssembly, out int majorVersion, out int minorVersion); - [System.Security.SecurityCritical] // auto-generated_required public static void GetTypeLibVersionForAssembly(Assembly inputAssembly, out int majorVersion, out int minorVersion) { if (inputAssembly == null) - throw new ArgumentNullException("inputAssembly"); + throw new ArgumentNullException(nameof(inputAssembly)); Contract.EndContractBlock(); RuntimeAssembly rtAssembly = inputAssembly as RuntimeAssembly; if (rtAssembly == null) - throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeAssembly"), "inputAssembly"); + throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeAssembly"), nameof(inputAssembly)); _GetTypeLibVersionForAssembly(rtAssembly, out majorVersion, out minorVersion); } @@ -1521,7 +1366,6 @@ namespace System.Runtime.InteropServices //==================================================================== // Given a managed object that wraps an UCOMITypeInfo, return its name //==================================================================== - [System.Security.SecurityCritical] // auto-generated_required [Obsolete("Use System.Runtime.InteropServices.Marshal.GetTypeInfoName(ITypeInfo pTLB) instead. http://go.microsoft.com/fwlink/?linkid=14202&ID=0000011.", false)] public static String GetTypeInfoName(UCOMITypeInfo pTI) { @@ -1531,11 +1375,10 @@ namespace System.Runtime.InteropServices //==================================================================== // Given a managed object that wraps an ITypeInfo, return its name //==================================================================== - [System.Security.SecurityCritical] // auto-generated_required public static String GetTypeInfoName(ITypeInfo typeInfo) { if (typeInfo == null) - throw new ArgumentNullException("typeInfo"); + throw new ArgumentNullException(nameof(typeInfo)); Contract.EndContractBlock(); String strTypeLibName = null; @@ -1552,11 +1395,10 @@ namespace System.Runtime.InteropServices // Internal version of GetTypeInfoName // Support GUID_ManagedName which aligns with TlbImp //==================================================================== - [System.Security.SecurityCritical] // auto-generated_required internal static String GetTypeInfoNameInternal(ITypeInfo typeInfo, out bool hasManagedName) { if (typeInfo == null) - throw new ArgumentNullException("typeInfo"); + throw new ArgumentNullException(nameof(typeInfo)); Contract.EndContractBlock(); // Try ManagedNameGuid first @@ -1590,7 +1432,6 @@ namespace System.Runtime.InteropServices // Get the corresponding managed name as converted by TlbImp // Used to get the type using GetType() from imported assemblies //==================================================================== - [System.Security.SecurityCritical] // auto-generated_required internal static String GetManagedTypeInfoNameInternal(ITypeLib typeLib, ITypeInfo typeInfo) { bool hasManagedName; @@ -1609,95 +1450,8 @@ namespace System.Runtime.InteropServices [MethodImplAttribute(MethodImplOptions.InternalCall)] private static extern Type GetLoadedTypeForGUID(ref Guid guid); -#if !FEATURE_CORECLR // current implementation requires reflection only load - //==================================================================== - // map ITypeInfo* to Type - //==================================================================== - [System.Security.SecurityCritical] // auto-generated_required - public static Type GetTypeForITypeInfo(IntPtr /* ITypeInfo* */ piTypeInfo) - { - ITypeInfo pTI = null; - ITypeLib pTLB = null; - Type TypeObj = null; - Assembly AsmBldr = null; - TypeLibConverter TlbConverter = null; - int Index = 0; - Guid clsid; - - // If the input ITypeInfo is NULL then return NULL. - if (piTypeInfo == IntPtr.Zero) - return null; - - // Wrap the ITypeInfo in a CLR object. - pTI = (ITypeInfo)GetObjectForIUnknown(piTypeInfo); - - // Check to see if a class exists with the specified GUID. - - clsid = GetTypeInfoGuid(pTI); - TypeObj = GetLoadedTypeForGUID(ref clsid); - - // If we managed to find the type based on the GUID then return it. - if (TypeObj != null) - return TypeObj; - - // There is no type with the specified GUID in the app domain so lets - // try and convert the containing typelib. - try - { - pTI.GetContainingTypeLib(out pTLB, out Index); - } - catch(COMException) - { - pTLB = null; - } - - // Check to see if we managed to get a containing typelib. - if (pTLB != null) - { - // Get the assembly name from the typelib. - AssemblyName AsmName = TypeLibConverter.GetAssemblyNameFromTypelib(pTLB, null, null, null, null, AssemblyNameFlags.None); - String AsmNameString = AsmName.FullName; - - // Check to see if the assembly that will contain the type already exists. - Assembly[] aAssemblies = Thread.GetDomain().GetAssemblies(); - int NumAssemblies = aAssemblies.Length; - for (int i = 0; i < NumAssemblies; i++) - { - if (String.Compare(aAssemblies[i].FullName, - AsmNameString,StringComparison.Ordinal) == 0) - AsmBldr = aAssemblies[i]; - } - - // If we haven't imported the assembly yet then import it. - if (AsmBldr == null) - { - TlbConverter = new TypeLibConverter(); - AsmBldr = TlbConverter.ConvertTypeLibToAssembly(pTLB, - GetTypeLibName(pTLB) + ".dll", 0, new ImporterCallback(), null, null, null, null); - } - - // Load the type object from the imported typelib. - // Call GetManagedTypeInfoNameInternal to align with TlbImp behavior - TypeObj = AsmBldr.GetType(GetManagedTypeInfoNameInternal(pTLB, pTI), true, false); - if (TypeObj != null && !TypeObj.IsVisible) - TypeObj = null; - } - else - { - // If the ITypeInfo does not have a containing typelib then simply - // return Object as the type. - TypeObj = typeof(Object); - } - - return TypeObj; - } -#endif // #if !FEATURE_CORECLR - // This method is identical to Type.GetTypeFromCLSID. Since it's interop specific, we expose it // on Marshal for more consistent API surface. -#if !FEATURE_CORECLR - [System.Security.SecuritySafeCritical] -#endif //!FEATURE_CORECLR public static Type GetTypeFromCLSID(Guid clsid) { return RuntimeType.GetTypeFromCLSIDImpl(clsid, null, false); @@ -1706,7 +1460,6 @@ namespace System.Runtime.InteropServices //==================================================================== // map Type to ITypeInfo* //==================================================================== - [System.Security.SecurityCritical] // auto-generated_required [MethodImplAttribute(MethodImplOptions.InternalCall)] public static extern IntPtr /* ITypeInfo* */ GetITypeInfoForType(Type t); @@ -1715,13 +1468,11 @@ namespace System.Runtime.InteropServices // is the one where the RCW was first seen. Will return null // otherwise. //==================================================================== - [System.Security.SecurityCritical] // auto-generated_required public static IntPtr /* IUnknown* */ GetIUnknownForObject(Object o) { return GetIUnknownForObjectNative(o, false); } - [System.Security.SecurityCritical] // auto-generated_required public static IntPtr /* IUnknown* */ GetIUnknownForObjectInContext(Object o) { return GetIUnknownForObjectNative(o, true); @@ -1737,22 +1488,22 @@ namespace System.Runtime.InteropServices //==================================================================== [MethodImplAttribute(MethodImplOptions.InternalCall)] internal static extern IntPtr /* IUnknown* */ GetRawIUnknownForComObjectNoAddRef(Object o); +#endif // FEATURE_COMINTEROP //==================================================================== // return the IDispatch* for an Object //==================================================================== - [System.Security.SecurityCritical] // auto-generated_required public static IntPtr /* IDispatch */ GetIDispatchForObject(Object o) { - return GetIDispatchForObjectNative(o, false); + throw new PlatformNotSupportedException(); } - + +#if FEATURE_COMINTEROP //==================================================================== // return the IDispatch* for an Object if the current context // is the one where the RCW was first seen. Will return null // otherwise. //==================================================================== - [System.Security.SecurityCritical] // auto-generated_required public static IntPtr /* IUnknown* */ GetIDispatchForObjectInContext(Object o) { return GetIDispatchForObjectNative(o, true); @@ -1765,13 +1516,11 @@ namespace System.Runtime.InteropServices // return the IUnknown* representing the interface for the Object // Object o should support Type T //==================================================================== - [System.Security.SecurityCritical] // auto-generated_required public static IntPtr /* IUnknown* */ GetComInterfaceForObject(Object o, Type T) { return GetComInterfaceForObjectNative(o, T, false, true); } - [System.Security.SecurityCritical] public static IntPtr GetComInterfaceForObject<T, TInterface>(T o) { return GetComInterfaceForObject(o, typeof(TInterface)); @@ -1782,7 +1531,6 @@ namespace System.Runtime.InteropServices // Object o should support Type T, it refer the value of mode to // invoke customized QueryInterface or not //==================================================================== - [System.Security.SecurityCritical] // auto-generated_required public static IntPtr /* IUnknown* */ GetComInterfaceForObject(Object o, Type T, CustomQueryInterfaceMode mode) { bool bEnableCustomizedQueryInterface = ((mode == CustomQueryInterfaceMode.Allow) ? true : false); @@ -1795,7 +1543,6 @@ namespace System.Runtime.InteropServices // is the one where the RCW was first seen. Will return null // otherwise. //==================================================================== - [System.Security.SecurityCritical] // auto-generated_required public static IntPtr /* IUnknown* */ GetComInterfaceForObjectInContext(Object o, Type t) { return GetComInterfaceForObjectNative(o, t, true, true); @@ -1807,7 +1554,6 @@ namespace System.Runtime.InteropServices //==================================================================== // return an Object for IUnknown //==================================================================== - [System.Security.SecurityCritical] // auto-generated_required [MethodImplAttribute(MethodImplOptions.InternalCall)] public static extern Object GetObjectForIUnknown(IntPtr /* IUnknown* */ pUnk); @@ -1818,7 +1564,6 @@ namespace System.Runtime.InteropServices // where you want to be able to call ReleaseComObject on a RCW // and not worry about other active uses of said RCW. //==================================================================== - [System.Security.SecurityCritical] // auto-generated_required [MethodImplAttribute(MethodImplOptions.InternalCall)] public static extern Object GetUniqueObjectForIUnknown(IntPtr unknown); @@ -1828,40 +1573,31 @@ namespace System.Runtime.InteropServices // Type T should be either a COM imported Type or a sub-type of COM // imported Type //==================================================================== - [System.Security.SecurityCritical] // auto-generated_required [MethodImplAttribute(MethodImplOptions.InternalCall)] public static extern Object GetTypedObjectForIUnknown(IntPtr /* IUnknown* */ pUnk, Type t); - [System.Security.SecurityCritical] // auto-generated_required [MethodImplAttribute(MethodImplOptions.InternalCall)] public static extern IntPtr CreateAggregatedObject(IntPtr pOuter, Object o); - [System.Security.SecurityCritical] public static IntPtr CreateAggregatedObject<T>(IntPtr pOuter, T o) { return CreateAggregatedObject(pOuter, (object)o); } - [System.Security.SecurityCritical] // auto-generated_required [MethodImplAttribute(MethodImplOptions.InternalCall)] public static extern void CleanupUnusedObjectsInCurrentContext(); - [System.Security.SecurityCritical] [MethodImplAttribute(MethodImplOptions.InternalCall)] public static extern bool AreComObjectsAvailableForCleanup(); //==================================================================== // check if the object is classic COM component //==================================================================== -#if !FEATURE_CORECLR // with FEATURE_CORECLR, the whole type is SecurityCritical - [System.Security.SecuritySafeCritical] -#endif [MethodImplAttribute(MethodImplOptions.InternalCall)] public static extern bool IsComObject(Object o); #endif // FEATURE_COMINTEROP - [System.Security.SecurityCritical] // auto-generated_required public static IntPtr AllocCoTaskMem(int cb) { IntPtr pNewMem = Win32Native.CoTaskMemAlloc(new UIntPtr((uint)cb)); @@ -1872,7 +1608,6 @@ namespace System.Runtime.InteropServices return pNewMem; } - [System.Security.SecurityCritical] // auto-generated_required unsafe public static IntPtr StringToCoTaskMemUni(String s) { if (s == null) @@ -1885,7 +1620,7 @@ namespace System.Runtime.InteropServices // Overflow checking if (nb < s.Length) - throw new ArgumentOutOfRangeException("s"); + throw new ArgumentOutOfRangeException(nameof(s)); IntPtr hglobal = Win32Native.CoTaskMemAlloc(new UIntPtr((uint)nb)); @@ -1904,7 +1639,6 @@ namespace System.Runtime.InteropServices } } - [System.Security.SecurityCritical] // auto-generated_required unsafe public static IntPtr StringToCoTaskMemUTF8(String s) { const int MAX_UTF8_CHAR_SIZE = 3; @@ -1918,7 +1652,7 @@ namespace System.Runtime.InteropServices // Overflow checking if (nb < s.Length) - throw new ArgumentOutOfRangeException("s"); + throw new ArgumentOutOfRangeException(nameof(s)); IntPtr pMem = Win32Native.CoTaskMemAlloc(new UIntPtr((uint)nb +1)); @@ -1936,14 +1670,12 @@ namespace System.Runtime.InteropServices } } - [System.Security.SecurityCritical] // auto-generated_required public static IntPtr StringToCoTaskMemAuto(String s) { // Ansi platforms are no longer supported return StringToCoTaskMemUni(s); } - [System.Security.SecurityCritical] // auto-generated_required unsafe public static IntPtr StringToCoTaskMemAnsi(String s) { if (s == null) @@ -1956,7 +1688,7 @@ namespace System.Runtime.InteropServices // Overflow checking if (nb < s.Length) - throw new ArgumentOutOfRangeException("s"); + throw new ArgumentOutOfRangeException(nameof(s)); IntPtr hglobal = Win32Native.CoTaskMemAlloc(new UIntPtr((uint)nb)); @@ -1972,7 +1704,6 @@ namespace System.Runtime.InteropServices } } - [System.Security.SecurityCritical] // auto-generated_required public static void FreeCoTaskMem(IntPtr ptr) { if (IsNotWin32Atom(ptr)) { @@ -1980,7 +1711,6 @@ namespace System.Runtime.InteropServices } } - [System.Security.SecurityCritical] // auto-generated_required public static IntPtr ReAllocCoTaskMem(IntPtr pv, int cb) { IntPtr pNewMem = Win32Native.CoTaskMemRealloc(pv, new UIntPtr((uint)cb)); @@ -1994,7 +1724,6 @@ namespace System.Runtime.InteropServices //==================================================================== // BSTR allocation and dealocation. //==================================================================== - [System.Security.SecurityCritical] // auto-generated_required public static void FreeBSTR(IntPtr ptr) { if (IsNotWin32Atom(ptr)) @@ -2003,7 +1732,6 @@ namespace System.Runtime.InteropServices } } - [System.Security.SecurityCritical] // auto-generated_required public static IntPtr StringToBSTR(String s) { if (s == null) @@ -2011,7 +1739,7 @@ namespace System.Runtime.InteropServices // Overflow checking if (s.Length + 1 < s.Length) - throw new ArgumentOutOfRangeException("s"); + throw new ArgumentOutOfRangeException(nameof(s)); IntPtr bstr = Win32Native.SysAllocStringLen(s, s.Length); if (bstr == IntPtr.Zero) @@ -2020,7 +1748,6 @@ namespace System.Runtime.InteropServices return bstr; } - [System.Security.SecurityCritical] // auto-generated_required public static String PtrToStringBSTR(IntPtr ptr) { return PtrToStringUni(ptr, (int)Win32Native.SysStringLen(ptr)); @@ -2031,7 +1758,6 @@ namespace System.Runtime.InteropServices // release the COM component and if the reference hits 0 zombie this object // further usage of this Object might throw an exception //==================================================================== - [System.Security.SecurityCritical] // auto-generated_required public static int ReleaseComObject(Object o) { __ComObject co = null; @@ -2043,7 +1769,7 @@ namespace System.Runtime.InteropServices } catch (InvalidCastException) { - throw new ArgumentException(Environment.GetResourceString("Argument_ObjNotComObject"), "o"); + throw new ArgumentException(Environment.GetResourceString("Argument_ObjNotComObject"), nameof(o)); } return co.ReleaseSelf(); @@ -2057,11 +1783,10 @@ namespace System.Runtime.InteropServices // release the COM component and zombie this object // further usage of this Object might throw an exception //==================================================================== - [System.Security.SecurityCritical] // auto-generated_required public static Int32 FinalReleaseComObject(Object o) { if (o == null) - throw new ArgumentNullException("o"); + throw new ArgumentNullException(nameof(o)); Contract.EndContractBlock(); __ComObject co = null; @@ -2073,7 +1798,7 @@ namespace System.Runtime.InteropServices } catch (InvalidCastException) { - throw new ArgumentException(Environment.GetResourceString("Argument_ObjNotComObject"), "o"); + throw new ArgumentException(Environment.GetResourceString("Argument_ObjNotComObject"), nameof(o)); } co.FinalReleaseSelf(); @@ -2083,39 +1808,14 @@ namespace System.Runtime.InteropServices [MethodImplAttribute(MethodImplOptions.InternalCall)] internal static extern void InternalFinalReleaseComObject(Object o); +#endif // FEATURE_COMINTEROP //==================================================================== // This method retrieves data from the COM object. //==================================================================== - [System.Security.SecurityCritical] // auto-generated_required public static Object GetComObjectData(Object obj, Object key) { - // Validate that the arguments aren't null. - if (obj == null) - throw new ArgumentNullException("obj"); - if (key == null) - throw new ArgumentNullException("key"); - Contract.EndContractBlock(); - - __ComObject comObj = null; - - // Make sure the obj is an __ComObject. - try - { - comObj = (__ComObject)obj; - } - catch (InvalidCastException) - { - throw new ArgumentException(Environment.GetResourceString("Argument_ObjNotComObject"), "obj"); - } - - if (obj.GetType().IsWindowsRuntimeObject) - { - throw new ArgumentException(Environment.GetResourceString("Argument_ObjIsWinRTObject"), "obj"); - } - - // Retrieve the data from the __ComObject. - return comObj.GetData(key); + throw new PlatformNotSupportedException(); } //==================================================================== @@ -2124,55 +1824,29 @@ namespace System.Runtime.InteropServices // true if the data has been added, false if the data could not be // added because there already was data for the specified key. //==================================================================== - [System.Security.SecurityCritical] // auto-generated_required public static bool SetComObjectData(Object obj, Object key, Object data) { - // Validate that the arguments aren't null. The data can validly be null. - if (obj == null) - throw new ArgumentNullException("obj"); - if (key == null) - throw new ArgumentNullException("key"); - Contract.EndContractBlock(); - - __ComObject comObj = null; - - // Make sure the obj is an __ComObject. - try - { - comObj = (__ComObject)obj; - } - catch (InvalidCastException) - { - throw new ArgumentException(Environment.GetResourceString("Argument_ObjNotComObject"), "obj"); - } - - if (obj.GetType().IsWindowsRuntimeObject) - { - throw new ArgumentException(Environment.GetResourceString("Argument_ObjIsWinRTObject"), "obj"); - } - - // Retrieve the data from the __ComObject. - return comObj.SetData(key, data); + throw new PlatformNotSupportedException(); } +#if FEATURE_COMINTEROP //==================================================================== // This method takes the given COM object and wraps it in an object // of the specified type. The type must be derived from __ComObject. //==================================================================== - [System.Security.SecurityCritical] // auto-generated_required public static Object CreateWrapperOfType(Object o, Type t) { // Validate the arguments. if (t == null) - throw new ArgumentNullException("t"); + throw new ArgumentNullException(nameof(t)); if (!t.IsCOMObject) - throw new ArgumentException(Environment.GetResourceString("Argument_TypeNotComObject"), "t"); + throw new ArgumentException(Environment.GetResourceString("Argument_TypeNotComObject"), nameof(t)); if (t.IsGenericType) - throw new ArgumentException(Environment.GetResourceString("Argument_NeedNonGenericType"), "t"); + throw new ArgumentException(Environment.GetResourceString("Argument_NeedNonGenericType"), nameof(t)); Contract.EndContractBlock(); if (t.IsWindowsRuntimeObject) - throw new ArgumentException(Environment.GetResourceString("Argument_TypeIsWinRTType"), "t"); + throw new ArgumentException(Environment.GetResourceString("Argument_TypeIsWinRTType"), nameof(t)); // Check for the null case. if (o == null) @@ -2180,9 +1854,9 @@ namespace System.Runtime.InteropServices // Make sure the object is a COM object. if (!o.GetType().IsCOMObject) - throw new ArgumentException(Environment.GetResourceString("Argument_ObjNotComObject"), "o"); + throw new ArgumentException(Environment.GetResourceString("Argument_ObjNotComObject"), nameof(o)); if (o.GetType().IsWindowsRuntimeObject) - throw new ArgumentException(Environment.GetResourceString("Argument_ObjIsWinRTObject"), "o"); + throw new ArgumentException(Environment.GetResourceString("Argument_ObjIsWinRTObject"), nameof(o)); // Check to see if the type of the object is the requested type. if (o.GetType() == t) @@ -2206,7 +1880,6 @@ namespace System.Runtime.InteropServices return Wrapper; } - [System.Security.SecurityCritical] public static TWrapper CreateWrapperOfType<T, TWrapper>(T o) { return (TWrapper)CreateWrapperOfType(o, typeof(TWrapper)); @@ -2215,7 +1888,6 @@ namespace System.Runtime.InteropServices //==================================================================== // Helper method called from CreateWrapperOfType. //==================================================================== - [System.Security.SecurityCritical] // auto-generated_required [MethodImplAttribute(MethodImplOptions.InternalCall)] private static extern Object InternalCreateWrapperOfType(Object o, Type t); @@ -2223,7 +1895,6 @@ namespace System.Runtime.InteropServices // There may be a thread-based cache of COM components. This service can // force the aggressive release of the current thread's cache. //==================================================================== - [System.Security.SecurityCritical] // auto-generated_required [Obsolete("This API did not perform any operation and will be removed in future versions of the CLR.", false)] public static void ReleaseThreadCache() { @@ -2232,50 +1903,40 @@ namespace System.Runtime.InteropServices //==================================================================== // check if the type is visible from COM. //==================================================================== - [System.Security.SecuritySafeCritical] [MethodImplAttribute(MethodImplOptions.InternalCall)] public static extern bool IsTypeVisibleFromCom(Type t); //==================================================================== // IUnknown Helpers //==================================================================== - [System.Security.SecurityCritical] // auto-generated_required [MethodImplAttribute(MethodImplOptions.InternalCall)] public static extern int /* HRESULT */ QueryInterface(IntPtr /* IUnknown */ pUnk, ref Guid iid, out IntPtr ppv); - [System.Security.SecurityCritical] // auto-generated_required [MethodImplAttribute(MethodImplOptions.InternalCall)] public static extern int /* ULONG */ AddRef(IntPtr /* IUnknown */ pUnk ); - [System.Security.SecurityCritical] // auto-generated_required [MethodImplAttribute(MethodImplOptions.InternalCall)] [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] public static extern int /* ULONG */ Release(IntPtr /* IUnknown */ pUnk ); - [System.Security.SecurityCritical] // auto-generated_required [MethodImplAttribute(MethodImplOptions.InternalCall)] public static extern void GetNativeVariantForObject(Object obj, /* VARIANT * */ IntPtr pDstNativeVariant); - [System.Security.SecurityCritical] public static void GetNativeVariantForObject<T>(T obj, IntPtr pDstNativeVariant) { GetNativeVariantForObject((object)obj, pDstNativeVariant); } - [System.Security.SecurityCritical] // auto-generated_required [MethodImplAttribute(MethodImplOptions.InternalCall)] public static extern Object GetObjectForNativeVariant(/* VARIANT * */ IntPtr pSrcNativeVariant ); - [System.Security.SecurityCritical] public static T GetObjectForNativeVariant<T>(IntPtr pSrcNativeVariant) { return (T)GetObjectForNativeVariant(pSrcNativeVariant); } - [System.Security.SecurityCritical] // auto-generated_required [MethodImplAttribute(MethodImplOptions.InternalCall)] public static extern Object[] GetObjectsForNativeVariants(/* VARIANT * */ IntPtr aSrcNativeVariant, int cVars ); - [System.Security.SecurityCritical] public static T[] GetObjectsForNativeVariants<T>(IntPtr aSrcNativeVariant, int cVars) { object[] objects = GetObjectsForNativeVariants(aSrcNativeVariant, cVars); @@ -2294,14 +1955,12 @@ namespace System.Runtime.InteropServices /// <para>Returns the first valid COM slot that GetMethodInfoForSlot will work on /// This will be 3 for IUnknown based interfaces and 7 for IDispatch based interfaces. </para> /// </summary> - [System.Security.SecurityCritical] // auto-generated_required [MethodImplAttribute(MethodImplOptions.InternalCall)] public static extern int GetStartComSlot(Type t); /// <summary> /// <para>Returns the last valid COM slot that GetMethodInfoForSlot will work on. </para> /// </summary> - [System.Security.SecurityCritical] // auto-generated_required [MethodImplAttribute(MethodImplOptions.InternalCall)] public static extern int GetEndComSlot(Type t); @@ -2312,7 +1971,6 @@ namespace System.Runtime.InteropServices /// For classes, the lookup is done on the default interface that will be /// exposed for the class. </para> /// </summary> - [System.Security.SecurityCritical] // auto-generated_required [MethodImplAttribute(MethodImplOptions.InternalCall)] public static extern MemberInfo GetMethodInfoForComSlot(Type t, int slot, ref ComMemberType memberType); @@ -2320,19 +1978,18 @@ namespace System.Runtime.InteropServices /// <para>Returns the COM slot for a memeber info, taking into account whether /// the exposed interface is IUnknown based or IDispatch based</para> /// </summary> - [System.Security.SecurityCritical] // auto-generated_required public static int GetComSlotForMethodInfo(MemberInfo m) { if (m== null) - throw new ArgumentNullException("m"); + throw new ArgumentNullException(nameof(m)); if (!(m is RuntimeMethodInfo)) - throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeMethodInfo"), "m"); + throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeMethodInfo"), nameof(m)); if (!m.DeclaringType.IsInterface) - throw new ArgumentException(Environment.GetResourceString("Argument_MustBeInterfaceMethod"), "m"); + throw new ArgumentException(Environment.GetResourceString("Argument_MustBeInterfaceMethod"), nameof(m)); if (m.DeclaringType.IsGenericType) - throw new ArgumentException(Environment.GetResourceString("Argument_NeedNonGenericType"), "m"); + throw new ArgumentException(Environment.GetResourceString("Argument_NeedNonGenericType"), nameof(m)); Contract.EndContractBlock(); return InternalGetComSlotForMethodInfo((IRuntimeMethodInfo)m); @@ -2340,6 +1997,7 @@ namespace System.Runtime.InteropServices [MethodImplAttribute(MethodImplOptions.InternalCall)] private static extern int InternalGetComSlotForMethodInfo(IRuntimeMethodInfo m); +#endif // FEATURE_COMINTEROP //==================================================================== // This method generates a GUID for the specified type. If the type @@ -2347,38 +2005,27 @@ namespace System.Runtime.InteropServices // guid GUID is generated based on the fully qualified name of the // type. //==================================================================== - [System.Security.SecurityCritical] // auto-generated_required public static Guid GenerateGuidForType(Type type) { - Guid result = new Guid (); - FCallGenerateGuidForType (ref result, type); - return result; + return type.GUID; } - // The full assembly name is used to compute the GUID, so this should be SxS-safe - [MethodImplAttribute(MethodImplOptions.InternalCall)] - private static extern void FCallGenerateGuidForType(ref Guid result, Type type); - //==================================================================== // This method generates a PROGID for the specified type. If the type // has a PROGID in the metadata then it is returned otherwise a stable // PROGID is generated based on the fully qualified name of the // type. //==================================================================== - [System.Security.SecurityCritical] // auto-generated_required public static String GenerateProgIdForType(Type type) { if (type == null) - throw new ArgumentNullException("type"); + throw new ArgumentNullException(nameof(type)); if (type.IsImport) - throw new ArgumentException(Environment.GetResourceString("Argument_TypeMustNotBeComImport"), "type"); + throw new ArgumentException(Environment.GetResourceString("Argument_TypeMustNotBeComImport"), nameof(type)); if (type.IsGenericType) - throw new ArgumentException(Environment.GetResourceString("Argument_NeedNonGenericType"), "type"); + throw new ArgumentException(Environment.GetResourceString("Argument_NeedNonGenericType"), nameof(type)); Contract.EndContractBlock(); - if (!RegistrationServices.TypeRequiresRegistrationHelper(type)) - throw new ArgumentException(Environment.GetResourceString("Argument_TypeMustBeComCreatable"), "type"); - IList<CustomAttributeData> cas = CustomAttributeData.GetCustomAttributes(type); for (int i = 0; i < cas.Count; i ++) { @@ -2386,10 +2033,10 @@ namespace System.Runtime.InteropServices { // Retrieve the PROGID string from the ProgIdAttribute. IList<CustomAttributeTypedArgument> caConstructorArgs = cas[i].ConstructorArguments; - Contract.Assert(caConstructorArgs.Count == 1, "caConstructorArgs.Count == 1"); + Debug.Assert(caConstructorArgs.Count == 1, "caConstructorArgs.Count == 1"); CustomAttributeTypedArgument progIdConstructorArg = caConstructorArgs[0]; - Contract.Assert(progIdConstructorArg.ArgumentType == typeof(String), "progIdConstructorArg.ArgumentType == typeof(String)"); + Debug.Assert(progIdConstructorArg.ArgumentType == typeof(String), "progIdConstructorArg.ArgumentType == typeof(String)"); String strProgId = (String)progIdConstructorArg.Value; @@ -2404,10 +2051,10 @@ namespace System.Runtime.InteropServices return type.FullName; } +#if FEATURE_COMINTEROP //==================================================================== // This method binds to the specified moniker. //==================================================================== - [System.Security.SecurityCritical] // auto-generated_required public static Object BindToMoniker(String monikerName) { Object obj = null; @@ -2425,7 +2072,6 @@ namespace System.Runtime.InteropServices //==================================================================== // This method gets the currently running object. //==================================================================== - [System.Security.SecurityCritical] // auto-generated_required public static Object GetActiveObject(String progID) { Object obj = null; @@ -2449,32 +2095,26 @@ namespace System.Runtime.InteropServices [DllImport(Microsoft.Win32.Win32Native.OLE32, PreserveSig = false)] [SuppressUnmanagedCodeSecurity] - [System.Security.SecurityCritical] // auto-generated private static extern void CLSIDFromProgIDEx([MarshalAs(UnmanagedType.LPWStr)] String progId, out Guid clsid); [DllImport(Microsoft.Win32.Win32Native.OLE32, PreserveSig = false)] [SuppressUnmanagedCodeSecurity] - [System.Security.SecurityCritical] // auto-generated private static extern void CLSIDFromProgID([MarshalAs(UnmanagedType.LPWStr)] String progId, out Guid clsid); [DllImport(Microsoft.Win32.Win32Native.OLE32, PreserveSig = false)] [SuppressUnmanagedCodeSecurity] - [System.Security.SecurityCritical] // auto-generated private static extern void CreateBindCtx(UInt32 reserved, out IBindCtx ppbc); [DllImport(Microsoft.Win32.Win32Native.OLE32, PreserveSig = false)] [SuppressUnmanagedCodeSecurity] - [System.Security.SecurityCritical] // auto-generated private static extern void MkParseDisplayName(IBindCtx pbc, [MarshalAs(UnmanagedType.LPWStr)] String szUserName, out UInt32 pchEaten, out IMoniker ppmk); [DllImport(Microsoft.Win32.Win32Native.OLE32, PreserveSig = false)] [SuppressUnmanagedCodeSecurity] - [System.Security.SecurityCritical] // auto-generated private static extern void BindMoniker(IMoniker pmk, UInt32 grfOpt, ref Guid iidResult, [MarshalAs(UnmanagedType.Interface)] out Object ppvResult); [DllImport(Microsoft.Win32.Win32Native.OLEAUT32, PreserveSig = false)] [SuppressUnmanagedCodeSecurity] - [System.Security.SecurityCritical] // auto-generated private static extern void GetActiveObject(ref Guid rclsid, IntPtr reserved, [MarshalAs(UnmanagedType.Interface)] out Object ppunk); //======================================================================== @@ -2489,7 +2129,6 @@ namespace System.Runtime.InteropServices //======================================================================== // Private method called from EE upon use of license/ICF2 marshaling. //======================================================================== - [SecurityCritical] private static IntPtr LoadLicenseManager() { Assembly sys = Assembly.Load("System, Version="+ ThisAssembly.Version + @@ -2500,16 +2139,13 @@ namespace System.Runtime.InteropServices return t.TypeHandle.Value; } - [System.Security.SecurityCritical] // auto-generated_required [MethodImplAttribute(MethodImplOptions.InternalCall)] public static extern void ChangeWrapperHandleStrength(Object otp, bool fIsWeak); - [System.Security.SecurityCritical] [MethodImplAttribute(MethodImplOptions.InternalCall)] internal static extern void InitializeWrapperForWinRT(object o, ref IntPtr pUnk); #if FEATURE_COMINTEROP_WINRT_MANAGED_ACTIVATION - [System.Security.SecurityCritical] [MethodImplAttribute(MethodImplOptions.InternalCall)] internal static extern void InitializeManagedWinRTFactoryObject(object o, RuntimeType runtimeClassType); #endif @@ -2517,7 +2153,6 @@ namespace System.Runtime.InteropServices //======================================================================== // Create activation factory and wraps it with a unique RCW //======================================================================== - [System.Security.SecurityCritical] [MethodImplAttribute(MethodImplOptions.InternalCall)] internal static extern object GetNativeActivationFactory(Type type); @@ -2525,11 +2160,9 @@ namespace System.Runtime.InteropServices // Methods allowing retrieval of the IIDs exposed by an underlying WinRT // object, as specified by the object's IInspectable::GetIids() //======================================================================== - [System.Security.SecurityCritical] [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode), SuppressUnmanagedCodeSecurity] private static extern void _GetInspectableIids(ObjectHandleOnStack obj, ObjectHandleOnStack guids); - [System.Security.SecurityCritical] internal static System.Guid[] GetInspectableIids(object obj) { System.Guid[] result = null; @@ -2547,14 +2180,12 @@ namespace System.Runtime.InteropServices // Methods allowing retrieval of the cached WinRT type corresponding to // the specified GUID //======================================================================== - [System.Security.SecurityCritical] [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode), SuppressUnmanagedCodeSecurity] private static extern void _GetCachedWinRTTypeByIid( ObjectHandleOnStack appDomainObj, System.Guid iid, out IntPtr rthHandle); - [System.Security.SecurityCritical] internal static System.Type GetCachedWinRTTypeByIid( System.AppDomain ad, System.Guid iid) @@ -2572,14 +2203,12 @@ namespace System.Runtime.InteropServices // Methods allowing retrieval of the WinRT types cached in the specified // app domain //======================================================================== - [System.Security.SecurityCritical] [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode), SuppressUnmanagedCodeSecurity] private static extern void _GetCachedWinRTTypes( ObjectHandleOnStack appDomainObj, ref int epoch, ObjectHandleOnStack winrtTypes); - [System.Security.SecurityCritical] internal static System.Type[] GetCachedWinRTTypes( System.AppDomain ad, ref int epoch) @@ -2599,7 +2228,6 @@ namespace System.Runtime.InteropServices return result; } - [System.Security.SecurityCritical] internal static System.Type[] GetCachedWinRTTypes( System.AppDomain ad) { @@ -2610,31 +2238,29 @@ namespace System.Runtime.InteropServices #endif // FEATURE_COMINTEROP - [System.Security.SecurityCritical] // auto-generated_required public static Delegate GetDelegateForFunctionPointer(IntPtr ptr, Type t) { // Validate the parameters if (ptr == IntPtr.Zero) - throw new ArgumentNullException("ptr"); + throw new ArgumentNullException(nameof(ptr)); if (t == null) - throw new ArgumentNullException("t"); + throw new ArgumentNullException(nameof(t)); Contract.EndContractBlock(); if ((t as RuntimeType) == null) - throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeType"), "t"); + throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeType"), nameof(t)); if (t.IsGenericType) - throw new ArgumentException(Environment.GetResourceString("Argument_NeedNonGenericType"), "t"); + throw new ArgumentException(Environment.GetResourceString("Argument_NeedNonGenericType"), nameof(t)); Type c = t.BaseType; if (c == null || (c != typeof(Delegate) && c != typeof(MulticastDelegate))) - throw new ArgumentException(Environment.GetResourceString("Arg_MustBeDelegate"), "t"); + throw new ArgumentException(Environment.GetResourceString("Arg_MustBeDelegate"), nameof(t)); return GetDelegateForFunctionPointerInternal(ptr, t); } - [System.Security.SecurityCritical] public static TDelegate GetDelegateForFunctionPointer<TDelegate>(IntPtr ptr) { return (TDelegate)(object)GetDelegateForFunctionPointer(ptr, typeof(TDelegate)); @@ -2643,17 +2269,15 @@ namespace System.Runtime.InteropServices [MethodImplAttribute(MethodImplOptions.InternalCall)] internal static extern Delegate GetDelegateForFunctionPointerInternal(IntPtr ptr, Type t); - [System.Security.SecurityCritical] // auto-generated_required public static IntPtr GetFunctionPointerForDelegate(Delegate d) { if (d == null) - throw new ArgumentNullException("d"); + throw new ArgumentNullException(nameof(d)); Contract.EndContractBlock(); return GetFunctionPointerForDelegateInternal(d); } - [System.Security.SecurityCritical] public static IntPtr GetFunctionPointerForDelegate<TDelegate>(TDelegate d) { return GetFunctionPointerForDelegate((Delegate)(object)d); @@ -2662,47 +2286,39 @@ namespace System.Runtime.InteropServices [MethodImplAttribute(MethodImplOptions.InternalCall)] internal static extern IntPtr GetFunctionPointerForDelegateInternal(Delegate d); -#if FEATURE_LEGACYSURFACE - -#if FEATURE_COMINTEROP - [System.Security.SecurityCritical] // auto-generated_required public static IntPtr SecureStringToBSTR(SecureString s) { if( s == null) { - throw new ArgumentNullException("s"); + throw new ArgumentNullException(nameof(s)); } Contract.EndContractBlock(); - return s.ToBSTR(); - } +#if FEATURE_COMINTEROP + return s.MarshalToBSTR(); +#else + throw new PlatformNotSupportedException(); #endif + } - [System.Security.SecurityCritical] // auto-generated_required public static IntPtr SecureStringToCoTaskMemAnsi(SecureString s) { if( s == null) { - throw new ArgumentNullException("s"); + throw new ArgumentNullException(nameof(s)); } Contract.EndContractBlock(); - return s.ToAnsiStr(false); + return s.MarshalToString(globalAlloc: false, unicode: false); } - [System.Security.SecurityCritical] // auto-generated_required public static IntPtr SecureStringToCoTaskMemUnicode(SecureString s) { - if (s == null) - { - throw new ArgumentNullException("s"); + if( s == null) { + throw new ArgumentNullException(nameof(s)); } Contract.EndContractBlock(); - return s.ToUniStr(false); + return s.MarshalToString(globalAlloc: false, unicode: true); } -#endif // FEATURE_LEGACYSURFACE - - #if FEATURE_COMINTEROP - [System.Security.SecurityCritical] // auto-generated_required public static void ZeroFreeBSTR(IntPtr s) { Win32Native.ZeroMemory(s, (UIntPtr)(Win32Native.SysStringLen(s) * 2)); @@ -2710,97 +2326,51 @@ namespace System.Runtime.InteropServices } #endif - [System.Security.SecurityCritical] // auto-generated_required public static void ZeroFreeCoTaskMemAnsi(IntPtr s) { Win32Native.ZeroMemory(s, (UIntPtr)(Win32Native.lstrlenA(s))); FreeCoTaskMem(s); } - [System.Security.SecurityCritical] // auto-generated_required public static void ZeroFreeCoTaskMemUnicode(IntPtr s) { Win32Native.ZeroMemory(s, (UIntPtr)(Win32Native.lstrlenW(s) * 2)); FreeCoTaskMem(s); } - [System.Security.SecurityCritical] // auto-generated_required unsafe public static void ZeroFreeCoTaskMemUTF8(IntPtr s) { Win32Native.ZeroMemory(s, (UIntPtr)System.StubHelpers.StubHelpers.strlen((sbyte*)s)); FreeCoTaskMem(s); } -#if FEATURE_LEGACYSURFACE - [System.Security.SecurityCritical] // auto-generated_required public static IntPtr SecureStringToGlobalAllocAnsi(SecureString s) { if( s == null) { - throw new ArgumentNullException("s"); + throw new ArgumentNullException(nameof(s)); } Contract.EndContractBlock(); - return s.ToAnsiStr(true); + return s.MarshalToString(globalAlloc: true, unicode: false); } - [System.Security.SecurityCritical] // auto-generated_required public static IntPtr SecureStringToGlobalAllocUnicode(SecureString s) { if( s == null) { - throw new ArgumentNullException("s"); + throw new ArgumentNullException(nameof(s)); } Contract.EndContractBlock(); - return s.ToUniStr(true); + return s.MarshalToString(globalAlloc: true, unicode: true);; } -#endif // FEATURE_LEGACYSURFACE - [System.Security.SecurityCritical] // auto-generated_required public static void ZeroFreeGlobalAllocAnsi(IntPtr s) { Win32Native.ZeroMemory(s, (UIntPtr)(Win32Native.lstrlenA(s))); FreeHGlobal(s); } - [System.Security.SecurityCritical] // auto-generated_required public static void ZeroFreeGlobalAllocUnicode(IntPtr s) { Win32Native.ZeroMemory(s, (UIntPtr)(Win32Native.lstrlenW(s) * 2)); FreeHGlobal(s); } } - -#if FEATURE_COMINTEROP && !FEATURE_CORECLR // current implementation requires reflection only load - //======================================================================== - // Typelib importer callback implementation. - //======================================================================== - internal class ImporterCallback : ITypeLibImporterNotifySink - { - public void ReportEvent(ImporterEventKind EventKind, int EventCode, String EventMsg) - { - } - - [System.Security.SecuritySafeCritical] // overrides transparent public member - public Assembly ResolveRef(Object TypeLib) - { - try - { - // Create the TypeLibConverter. - ITypeLibConverter TLBConv = new TypeLibConverter(); - - // Convert the typelib. - return TLBConv.ConvertTypeLibToAssembly(TypeLib, - Marshal.GetTypeLibName((ITypeLib)TypeLib) + ".dll", - 0, - new ImporterCallback(), - null, - null, - null, - null); - } - catch(Exception) -// catch - { - return null; - } - } - } -#endif // FEATURE_COMINTEROP && !FEATURE_CORECLR } diff --git a/src/mscorlib/src/System/Runtime/InteropServices/NativeBuffer.cs b/src/mscorlib/src/System/Runtime/InteropServices/NativeBuffer.cs deleted file mode 100644 index 94261621c3..0000000000 --- a/src/mscorlib/src/System/Runtime/InteropServices/NativeBuffer.cs +++ /dev/null @@ -1,175 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System.Runtime.CompilerServices; - -namespace System.Runtime.InteropServices -{ - /// <summary> - /// Wrapper for access to the native heap. Dispose to free the memory. Try to use with using statements. - /// Does not allocate zero size buffers, and will free the existing native buffer if capacity is dropped to zero. - /// </summary> - /// <remarks> - /// Suggested use through P/Invoke: define DllImport arguments that take a byte buffer as SafeHandle. - /// - /// Using SafeHandle will ensure that the buffer will not get collected during a P/Invoke. - /// (Notably AddRef and ReleaseRef will be called by the interop layer.) - /// - /// This class is not threadsafe, changing the capacity or disposing on multiple threads risks duplicate heap - /// handles or worse. - /// </remarks> - internal class NativeBuffer : IDisposable - { - [System.Security.SecurityCritical] - private readonly static SafeHandle s_emptyHandle; - [System.Security.SecurityCritical] - private SafeHeapHandle _handle; - private ulong _capacity; - - [System.Security.SecuritySafeCritical] - static NativeBuffer() - { - s_emptyHandle = new EmptySafeHandle(); - } - - /// <summary> - /// Create a buffer with at least the specified initial capacity in bytes. - /// </summary> - public NativeBuffer(ulong initialMinCapacity = 0) - { - EnsureByteCapacity(initialMinCapacity); - } - - protected unsafe void* VoidPointer - { - [MethodImpl(MethodImplOptions.AggressiveInlining)] - [System.Security.SecurityCritical] - get - { - return _handle == null ? null : _handle.DangerousGetHandle().ToPointer(); - } - } - - protected unsafe byte* BytePointer - { - [System.Security.SecurityCritical] - get - { - return (byte*)VoidPointer; - } - } - - /// <summary> - /// Get the handle for the buffer. - /// </summary> - [System.Security.SecuritySafeCritical] - public SafeHandle GetHandle() - { - // Marshalling code will throw on null for SafeHandle - return _handle ?? s_emptyHandle; - } - - /// <summary> - /// The capacity of the buffer in bytes. - /// </summary> - public ulong ByteCapacity - { - get { return _capacity; } - } - - /// <summary> - /// Ensure capacity in bytes is at least the given minimum. - /// </summary> - /// <exception cref="OutOfMemoryException">Thrown if unable to allocate memory when setting.</exception> - /// <exception cref="ArgumentOutOfRangeException">Thrown if attempting to set <paramref name="nameof(minCapacity)"/> to a value that is larger than the maximum addressable memory.</exception> - [System.Security.SecuritySafeCritical] - public void EnsureByteCapacity(ulong minCapacity) - { - if (_capacity < minCapacity) - { - Resize(minCapacity); - _capacity = minCapacity; - } - } - - public unsafe byte this[ulong index] - { - [System.Security.SecuritySafeCritical] - get - { - if (index >= _capacity) throw new ArgumentOutOfRangeException(); - return BytePointer[index]; - } - [System.Security.SecuritySafeCritical] - set - { - if (index >= _capacity) throw new ArgumentOutOfRangeException(); - BytePointer[index] = value; - } - } - - [System.Security.SecuritySafeCritical] - private unsafe void Resize(ulong byteLength) - { - if (byteLength == 0) - { - ReleaseHandle(); - return; - } - - if (_handle == null) - { - _handle = new SafeHeapHandle(byteLength); - } - else - { - _handle.Resize(byteLength); - } - } - - [System.Security.SecuritySafeCritical] - private void ReleaseHandle() - { - if (_handle != null) - { - _capacity = 0; - _handle = null; - } - } - - /// <summary> - /// Release the backing buffer - /// </summary> - [System.Security.SecuritySafeCritical] - public virtual void Free() - { - ReleaseHandle(); - } - - [System.Security.SecuritySafeCritical] - public void Dispose() - { - Free(); - } - - [System.Security.SecurityCritical] - private sealed class EmptySafeHandle : SafeHandle - { - public EmptySafeHandle() : base(IntPtr.Zero, true) { } - - public override bool IsInvalid - { - [System.Security.SecurityCritical] - get - { return true; } - } - - [System.Security.SecurityCritical] - protected override bool ReleaseHandle() - { - return true; - } - } - } -}
\ No newline at end of file diff --git a/src/mscorlib/src/System/Runtime/InteropServices/NativeMethods.cs b/src/mscorlib/src/System/Runtime/InteropServices/NativeMethods.cs index 82cd4fa963..650ea65697 100644 --- a/src/mscorlib/src/System/Runtime/InteropServices/NativeMethods.cs +++ b/src/mscorlib/src/System/Runtime/InteropServices/NativeMethods.cs @@ -31,13 +31,10 @@ namespace System.Runtime.InteropServices { ] internal interface IDispatch { - [System.Security.SecurityCritical] void GetTypeInfoCount(out uint pctinfo); - [System.Security.SecurityCritical] void GetTypeInfo(uint iTInfo, int lcid, out IntPtr info); - [System.Security.SecurityCritical] void GetIDsOfNames( ref Guid iid, [MarshalAs(UnmanagedType.LPArray, ArraySubType = UnmanagedType.LPWStr, SizeParamIndex = 2)] @@ -48,7 +45,6 @@ namespace System.Runtime.InteropServices { [MarshalAs(UnmanagedType.LPArray, ArraySubType = UnmanagedType.I4, SizeParamIndex = 2)] int[] rgDispId); - [System.Security.SecurityCritical] void Invoke( int dispIdMember, ref Guid riid, diff --git a/src/mscorlib/src/System/Runtime/InteropServices/NonPortable.cs b/src/mscorlib/src/System/Runtime/InteropServices/NonPortable.cs index 408f56c8e2..0c8ae7649c 100644 --- a/src/mscorlib/src/System/Runtime/InteropServices/NonPortable.cs +++ b/src/mscorlib/src/System/Runtime/InteropServices/NonPortable.cs @@ -33,6 +33,18 @@ namespace System.Runtime.InteropServices } [System.Security.SecurityCriticalAttribute] + public static Object BindToMoniker(String monikerName) + { + throw new PlatformNotSupportedException(); + } + + [System.Security.SecurityCriticalAttribute] + public static void CleanupUnusedObjectsInCurrentContext() + { + return; + } + + [System.Security.SecurityCriticalAttribute] public static System.IntPtr CreateAggregatedObject<T>(System.IntPtr pOuter, T o) { throw new PlatformNotSupportedException(); @@ -51,6 +63,12 @@ namespace System.Runtime.InteropServices } [System.Security.SecurityCriticalAttribute] + public static void ChangeWrapperHandleStrength(Object otp, bool fIsWeak) + { + throw new PlatformNotSupportedException(); + } + + [System.Security.SecurityCriticalAttribute] public static int FinalReleaseComObject(object o) { throw new PlatformNotSupportedException(); @@ -75,6 +93,16 @@ namespace System.Runtime.InteropServices } [System.Security.SecurityCriticalAttribute] + public static System.IntPtr GetHINSTANCE(System.Reflection.Module m) + { + if (m == null) + { + throw new ArgumentNullException(nameof(m)); + } + return (System.IntPtr) (-1); + } + + [System.Security.SecurityCriticalAttribute] public static System.IntPtr GetIUnknownForObject(object o) { throw new PlatformNotSupportedException(); @@ -93,6 +121,12 @@ namespace System.Runtime.InteropServices } [System.Security.SecurityCriticalAttribute] + public static Object GetTypedObjectForIUnknown(System.IntPtr pUnk, System.Type t) + { + throw new PlatformNotSupportedException(); + } + + [System.Security.SecurityCriticalAttribute] public static object GetObjectForIUnknown(System.IntPtr pUnk) { throw new PlatformNotSupportedException(); diff --git a/src/mscorlib/src/System/Runtime/InteropServices/RegistrationServices.cs b/src/mscorlib/src/System/Runtime/InteropServices/RegistrationServices.cs index 7d3670d877..0105866415 100644 --- a/src/mscorlib/src/System/Runtime/InteropServices/RegistrationServices.cs +++ b/src/mscorlib/src/System/Runtime/InteropServices/RegistrationServices.cs @@ -29,6 +29,7 @@ namespace System.Runtime.InteropServices { using System.Runtime.CompilerServices; using System.Globalization; using System.Runtime.Versioning; + using System.Diagnostics; using System.Diagnostics.Contracts; [Flags] @@ -91,12 +92,11 @@ namespace System.Runtime.InteropServices { #region IRegistrationServices - [System.Security.SecurityCritical] // auto-generated_required public virtual bool RegisterAssembly(Assembly assembly, AssemblyRegistrationFlags flags) { // Validate the arguments. if (assembly == null) - throw new ArgumentNullException("assembly"); + throw new ArgumentNullException(nameof(assembly)); if (assembly.ReflectionOnly) throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_AsmLoadedForReflectionOnly")); @@ -154,12 +154,11 @@ namespace System.Runtime.InteropServices { return false; } - [System.Security.SecurityCritical] // auto-generated_required public virtual bool UnregisterAssembly(Assembly assembly) { // Validate the arguments. if (assembly == null) - throw new ArgumentNullException("assembly"); + throw new ArgumentNullException(nameof(assembly)); if (assembly.ReflectionOnly) throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_AsmLoadedForReflectionOnly")); @@ -214,16 +213,15 @@ namespace System.Runtime.InteropServices { return false; } - [System.Security.SecurityCritical] // auto-generated_required public virtual Type[] GetRegistrableTypesInAssembly(Assembly assembly) { // Validate the arguments. if (assembly == null) - throw new ArgumentNullException("assembly"); + throw new ArgumentNullException(nameof(assembly)); Contract.EndContractBlock(); if (!(assembly is RuntimeAssembly)) - throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeAssembly"), "assembly"); + throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeAssembly"), nameof(assembly)); // Retrieve the list of types in the assembly. Type[] aTypes = assembly.GetExportedTypes(); @@ -246,23 +244,21 @@ namespace System.Runtime.InteropServices { return RetArray; } - [System.Security.SecurityCritical] // auto-generated_required public virtual String GetProgIdForType(Type type) { return Marshal.GenerateProgIdForType(type); } - [System.Security.SecurityCritical] // auto-generated_required public virtual void RegisterTypeForComClients(Type type, ref Guid g) { #if FEATURE_COMINTEROP_MANAGED_ACTIVATION if(type == null) - throw new ArgumentNullException("type"); + throw new ArgumentNullException(nameof(type)); Contract.EndContractBlock(); if((type as RuntimeType) == null) - throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeType"),"type"); + throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeType"),nameof(type)); if(!TypeRequiresRegistration(type)) - throw new ArgumentException(Environment.GetResourceString("Argument_TypeMustBeComCreatable"),"type"); + throw new ArgumentException(Environment.GetResourceString("Argument_TypeMustBeComCreatable"),nameof(type)); // Call the native method to do CoRegisterClassObject RegisterTypeForComClientsNative(type, ref g); @@ -276,13 +272,11 @@ namespace System.Runtime.InteropServices { return s_ManagedCategoryGuid; } - [System.Security.SecurityCritical] // auto-generated_required public virtual bool TypeRequiresRegistration(Type type) { return TypeRequiresRegistrationHelper(type); } - [System.Security.SecuritySafeCritical] // auto-generated public virtual bool TypeRepresentsComType(Type type) { // If the type is not a COM import, then it does not represent a COM type. @@ -296,7 +290,7 @@ namespace System.Runtime.InteropServices { // If the type is derived from a tdImport class and has the same GUID as the // imported class, then it represents a COM type. Type baseComImportType = GetBaseComImportType(type); - Contract.Assert(baseComImportType != null, "baseComImportType != null"); + Debug.Assert(baseComImportType != null, "baseComImportType != null"); if (Marshal.GenerateGuidForType(type) == Marshal.GenerateGuidForType(baseComImportType)) return true; @@ -307,18 +301,17 @@ namespace System.Runtime.InteropServices { #region Public methods not on IRegistrationServices - [System.Security.SecurityCritical] // auto-generated_required [ComVisible(false)] public virtual int RegisterTypeForComClients(Type type, RegistrationClassContext classContext, RegistrationConnectionType flags) { #if FEATURE_COMINTEROP_MANAGED_ACTIVATION if (type == null) - throw new ArgumentNullException("type"); + throw new ArgumentNullException(nameof(type)); Contract.EndContractBlock(); if ((type as RuntimeType) == null) - throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeType"),"type"); + throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeType"),nameof(type)); if (!TypeRequiresRegistration(type)) - throw new ArgumentException(Environment.GetResourceString("Argument_TypeMustBeComCreatable"),"type"); + throw new ArgumentException(Environment.GetResourceString("Argument_TypeMustBeComCreatable"),nameof(type)); // Call the native method to do CoRegisterClassObject return RegisterTypeForComClientsExNative(type, classContext, flags); @@ -327,7 +320,6 @@ namespace System.Runtime.InteropServices { #endif // FEATURE_COMINTEROP_MANAGED_ACTIVATION } - [System.Security.SecurityCritical] // auto-generated_required [ComVisible(false)] public virtual void UnregisterTypeForComClients(int cookie) { @@ -340,7 +332,6 @@ namespace System.Runtime.InteropServices { #region Internal helpers - [System.Security.SecurityCritical] // auto-generated_required internal static bool TypeRequiresRegistrationHelper(Type type) { // If the type is not a class or a value class, then it does not get registered. @@ -365,7 +356,6 @@ namespace System.Runtime.InteropServices { #region Private helpers - [System.Security.SecurityCritical] // auto-generated private void RegisterValueType(Type type, String strAsmName, String strAsmVersion, String strAsmCodeBase, String strRuntimeVersion) { // Retrieve some information that will be used during the registration process. @@ -397,7 +387,6 @@ namespace System.Runtime.InteropServices { } } - [System.Security.SecurityCritical] // auto-generated private void RegisterManagedType(Type type, String strAsmName, String strAsmVersion, String strAsmCodeBase, String strRuntimeVersion) { // @@ -483,7 +472,6 @@ namespace System.Runtime.InteropServices { EnsureManagedCategoryExists(); } - [System.Security.SecurityCritical] // auto-generated private void RegisterComImportedType(Type type, String strAsmName, String strAsmVersion, String strAsmCodeBase, String strRuntimeVersion) { // Retrieve some information that will be used during the registration process. @@ -525,7 +513,6 @@ namespace System.Runtime.InteropServices { } } - [System.Security.SecurityCritical] // auto-generated private bool UnregisterValueType(Type type, String strAsmVersion) { bool bAllVersionsGone = true; @@ -582,7 +569,6 @@ namespace System.Runtime.InteropServices { // Return : // true: All versions are gone. // false: Some versions are still left in registry - [System.Security.SecurityCritical] // auto-generated private bool UnregisterManagedType(Type type,String strAsmVersion) { bool bAllVersionsGone = true; @@ -776,7 +762,6 @@ namespace System.Runtime.InteropServices { // Return: // true: All version information are gone. // false: There are still some version left in registry - [System.Security.SecurityCritical] // auto-generated private bool UnregisterComImportedType(Type type, String strAsmVersion) { bool bAllVersionsGone = true; @@ -846,7 +831,6 @@ namespace System.Runtime.InteropServices { return bAllVersionsGone; } - [System.Security.SecurityCritical] // auto-generated private void RegisterPrimaryInteropAssembly(RuntimeAssembly assembly, String strAsmCodeBase, PrimaryInteropAssemblyAttribute attr) { // Validate that the PIA has a strong name. @@ -874,7 +858,6 @@ namespace System.Runtime.InteropServices { } } - [System.Security.SecurityCritical] // auto-generated private void UnregisterPrimaryInteropAssembly(Assembly assembly, PrimaryInteropAssemblyAttribute attr) { String strTlbId = "{" + Marshal.GetTypeLibGuidForAssembly(assembly).ToString().ToUpper(CultureInfo.InvariantCulture) + "}"; @@ -937,20 +920,12 @@ namespace System.Runtime.InteropServices { private static bool ManagedCategoryExists() { using (RegistryKey componentCategoryKey = Registry.ClassesRoot.OpenSubKey(strComponentCategorySubKey, -#if FEATURE_MACL - RegistryKeyPermissionCheck.ReadSubTree)) -#else false)) -#endif { if (componentCategoryKey == null) return false; using (RegistryKey managedCategoryKey = componentCategoryKey.OpenSubKey(strManagedCategoryGuid, -#if FEATURE_MACL - RegistryKeyPermissionCheck.ReadSubTree)) -#else false)) -#endif { if (managedCategoryKey == null) return false; @@ -966,7 +941,6 @@ namespace System.Runtime.InteropServices { return true; } - [System.Security.SecurityCritical] // auto-generated private void CallUserDefinedRegistrationMethod(Type type, bool bRegister) { bool bFunctionCalled = false; @@ -1069,13 +1043,11 @@ namespace System.Runtime.InteropServices { #if FEATURE_COMINTEROP_MANAGED_ACTIVATION // GUID versioning can be controlled by using the GuidAttribute or // letting the runtime generate it based on type and assembly strong name. - [System.Security.SecurityCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.InternalCall)] private static extern void RegisterTypeForComClientsNative(Type type,ref Guid g); // GUID versioning can be controlled by using the GuidAttribute or // letting the runtime generate it based on type and assembly strong name. - [System.Security.SecurityCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.InternalCall)] private static extern int RegisterTypeForComClientsExNative(Type t, RegistrationClassContext clsContext, RegistrationConnectionType flags); #endif // FEATURE_COMINTEROP_MANAGED_ACTIVATION diff --git a/src/mscorlib/src/System/Runtime/InteropServices/RuntimeEnvironment.cs b/src/mscorlib/src/System/Runtime/InteropServices/RuntimeEnvironment.cs index d722843ae8..a5c058da43 100644 --- a/src/mscorlib/src/System/Runtime/InteropServices/RuntimeEnvironment.cs +++ b/src/mscorlib/src/System/Runtime/InteropServices/RuntimeEnvironment.cs @@ -23,70 +23,31 @@ using Microsoft.Win32; using System.Runtime.Versioning; using StackCrawlMark = System.Threading.StackCrawlMark; -namespace System.Runtime.InteropServices { -[System.Runtime.InteropServices.ComVisible(true)] -#if FEATURE_CORECLR - static -#endif - public class RuntimeEnvironment { +namespace System.Runtime.InteropServices +{ + [System.Runtime.InteropServices.ComVisible(true)] + static public class RuntimeEnvironment { -#if !FEATURE_CORECLR - // This should have been a static class, but wasn't as of v3.5. Clearly, this is - // broken. We'll keep this in V4 for binary compat, but marked obsolete as error - // so migrated source code gets fixed. On Silverlight, this type exists but is - // not public. - [Obsolete("Do not create instances of the RuntimeEnvironment class. Call the static methods directly on this type instead", true)] - public RuntimeEnvironment() - { - // Should not have been instantiable - here for binary compatibility in V4. - } -#endif - - [System.Security.SecurityCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.InternalCall)] internal static extern String GetModuleFileName(); - [System.Security.SecurityCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.InternalCall)] internal static extern String GetDeveloperPath(); - [System.Security.SecurityCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.InternalCall)] internal static extern String GetHostBindingFile(); -#if !FEATURE_CORECLR - [System.Security.SecurityCritical] // auto-generated - [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] - [SuppressUnmanagedCodeSecurity] - internal static extern void _GetSystemVersion(StringHandleOnStack retVer); -#endif //!FEATURE_CORECLR - public static bool FromGlobalAccessCache(Assembly a) { return a.GlobalAssemblyCache; } - -#if !FEATURE_CORECLR - [System.Security.SecuritySafeCritical] // public member -#endif + [MethodImpl (MethodImplOptions.NoInlining)] public static String GetSystemVersion() { -#if FEATURE_CORECLR - return Assembly.GetExecutingAssembly().ImageRuntimeVersion; - -#else // FEATURE_CORECLR - - String ver = null; - _GetSystemVersion(JitHelpers.GetStringHandleOnStack(ref ver)); - return ver; - -#endif // FEATURE_CORECLR - } - - [System.Security.SecuritySafeCritical] // auto-generated + public static String GetRuntimeDirectory() { String dir = GetRuntimeDirectoryImpl(); @@ -94,13 +55,11 @@ namespace System.Runtime.InteropServices { return dir; } - [System.Security.SecurityCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.InternalCall)] internal static extern String GetRuntimeDirectoryImpl(); // Returns the system ConfigurationFile public static String SystemConfigurationFile { - [System.Security.SecuritySafeCritical] // auto-generated get { StringBuilder sb = new StringBuilder(Path.MaxPath); sb.Append(GetRuntimeDirectory()); @@ -115,7 +74,6 @@ namespace System.Runtime.InteropServices { } #if FEATURE_COMINTEROP - [System.Security.SecurityCritical] [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [SuppressUnmanagedCodeSecurity] private static extern IntPtr GetRuntimeInterfaceImpl( @@ -130,7 +88,6 @@ namespace System.Runtime.InteropServices { // Returns unmanaged pointer to requested interface on success. Throws // COMException with failed HR if there is a QI failure. // - [System.Security.SecurityCritical] // do not allow partial trust callers [ComVisible(false)] public static IntPtr GetRuntimeInterfaceAsIntPtr(Guid clsid, Guid riid) { @@ -145,7 +102,6 @@ namespace System.Runtime.InteropServices { // Returns an RCW to requested interface on success. Throws // COMException with failed HR if there is a QI failure. // - [System.Security.SecurityCritical] // do not allow partial trust callers [ComVisible(false)] public static object GetRuntimeInterfaceAsObject(Guid clsid, Guid riid) { @@ -159,7 +115,6 @@ namespace System.Runtime.InteropServices { } } } - #endif // FEATURE_COMINTEROP } } diff --git a/src/mscorlib/src/System/Runtime/InteropServices/SafeBuffer.cs b/src/mscorlib/src/System/Runtime/InteropServices/SafeBuffer.cs index a659daf2b5..eba67ae74e 100644 --- a/src/mscorlib/src/System/Runtime/InteropServices/SafeBuffer.cs +++ b/src/mscorlib/src/System/Runtime/InteropServices/SafeBuffer.cs @@ -75,10 +75,10 @@ using System.Runtime.CompilerServices; using System.Runtime.ConstrainedExecution; using System.Runtime.Versioning; using Microsoft.Win32.SafeHandles; +using System.Diagnostics; using System.Diagnostics.Contracts; - [System.Security.SecurityCritical] public abstract unsafe class SafeBuffer : SafeHandleZeroOrMinusOneIsInvalid { // Steal UIntPtr.MaxValue as our uninitialized value. @@ -101,13 +101,13 @@ using System.Diagnostics.Contracts; public void Initialize(ulong numBytes) { if (numBytes < 0) - throw new ArgumentOutOfRangeException("numBytes", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); + throw new ArgumentOutOfRangeException(nameof(numBytes), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); if (IntPtr.Size == 4 && numBytes > UInt32.MaxValue) - throw new ArgumentOutOfRangeException("numBytes", Environment.GetResourceString("ArgumentOutOfRange_AddressSpace")); + throw new ArgumentOutOfRangeException(nameof(numBytes), Environment.GetResourceString("ArgumentOutOfRange_AddressSpace")); Contract.EndContractBlock(); if (numBytes >= (ulong)Uninitialized) - throw new ArgumentOutOfRangeException("numBytes", Environment.GetResourceString("ArgumentOutOfRange_UIntPtrMax-1")); + throw new ArgumentOutOfRangeException(nameof(numBytes), Environment.GetResourceString("ArgumentOutOfRange_UIntPtrMax-1")); _numBytes = (UIntPtr) numBytes; } @@ -120,16 +120,16 @@ using System.Diagnostics.Contracts; public void Initialize(uint numElements, uint sizeOfEachElement) { if (numElements < 0) - throw new ArgumentOutOfRangeException("numElements", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); + throw new ArgumentOutOfRangeException(nameof(numElements), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); if (sizeOfEachElement < 0) - throw new ArgumentOutOfRangeException("sizeOfEachElement", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); + throw new ArgumentOutOfRangeException(nameof(sizeOfEachElement), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); if (IntPtr.Size == 4 && numElements * sizeOfEachElement > UInt32.MaxValue) throw new ArgumentOutOfRangeException("numBytes", Environment.GetResourceString("ArgumentOutOfRange_AddressSpace")); Contract.EndContractBlock(); if (numElements * sizeOfEachElement >= (ulong)Uninitialized) - throw new ArgumentOutOfRangeException("numElements", Environment.GetResourceString("ArgumentOutOfRange_UIntPtrMax-1")); + throw new ArgumentOutOfRangeException(nameof(numElements), Environment.GetResourceString("ArgumentOutOfRange_UIntPtrMax-1")); _numBytes = checked((UIntPtr) (numElements * sizeOfEachElement)); } @@ -245,11 +245,11 @@ using System.Diagnostics.Contracts; where T : struct { if (array == null) - throw new ArgumentNullException("array", Environment.GetResourceString("ArgumentNull_Buffer")); + throw new ArgumentNullException(nameof(array), Environment.GetResourceString("ArgumentNull_Buffer")); if (index < 0) - throw new ArgumentOutOfRangeException("index", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); + throw new ArgumentOutOfRangeException(nameof(index), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); if (count < 0) - throw new ArgumentOutOfRangeException("count", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); + throw new ArgumentOutOfRangeException(nameof(count), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); if (array.Length - index < count) throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen")); Contract.EndContractBlock(); @@ -317,11 +317,11 @@ using System.Diagnostics.Contracts; where T : struct { if (array == null) - throw new ArgumentNullException("array", Environment.GetResourceString("ArgumentNull_Buffer")); + throw new ArgumentNullException(nameof(array), Environment.GetResourceString("ArgumentNull_Buffer")); if (index < 0) - throw new ArgumentOutOfRangeException("index", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); + throw new ArgumentOutOfRangeException(nameof(index), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); if (count < 0) - throw new ArgumentOutOfRangeException("count", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); + throw new ArgumentOutOfRangeException(nameof(count), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); if (array.Length - index < count) throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen")); Contract.EndContractBlock(); @@ -385,7 +385,7 @@ using System.Diagnostics.Contracts; [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] private static InvalidOperationException NotInitialized() { - Contract.Assert(false, "Uninitialized SafeBuffer! Someone needs to call Initialize before using this instance!"); + Debug.Assert(false, "Uninitialized SafeBuffer! Someone needs to call Initialize before using this instance!"); return new InvalidOperationException(Environment.GetResourceString("InvalidOperation_MustCallInitialize")); } diff --git a/src/mscorlib/src/System/Runtime/InteropServices/SafeHandle.cs b/src/mscorlib/src/System/Runtime/InteropServices/SafeHandle.cs index c26852874d..ed9910e4e4 100644 --- a/src/mscorlib/src/System/Runtime/InteropServices/SafeHandle.cs +++ b/src/mscorlib/src/System/Runtime/InteropServices/SafeHandle.cs @@ -134,10 +134,6 @@ using System.Runtime.Versioning; // we'll do this to ensure we've cut off all attack vectors. Similarly, all // methods have a link demand to ensure untrusted code cannot directly edit // or alter a handle. -[System.Security.SecurityCritical] // auto-generated_required -#if !FEATURE_CORECLR -[SecurityPermission(SecurityAction.InheritanceDemand, UnmanagedCode=true)] -#endif public abstract class SafeHandle : CriticalFinalizerObject, IDisposable { // ! Do not add or rearrange fields as the EE depends on this layout. @@ -182,16 +178,13 @@ public abstract class SafeHandle : CriticalFinalizerObject, IDisposable _fullyInitialized = true; } -#if FEATURE_CORECLR // Migrating InheritanceDemands requires this default ctor, so we can mark it critical protected SafeHandle() { BCLDebug.Assert(false, "SafeHandle's protected default ctor should never be used!"); throw new NotImplementedException(); } -#endif - [System.Security.SecuritySafeCritical] // auto-generated ~SafeHandle() { Dispose(false); @@ -236,19 +229,16 @@ public abstract class SafeHandle : CriticalFinalizerObject, IDisposable get; } - [System.Security.SecurityCritical] // auto-generated [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] public void Close() { Dispose(true); } - [System.Security.SecuritySafeCritical] // auto-generated [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] public void Dispose() { Dispose(true); } - [System.Security.SecurityCritical] // auto-generated [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] protected virtual void Dispose(bool disposing) { @@ -266,7 +256,6 @@ public abstract class SafeHandle : CriticalFinalizerObject, IDisposable // your handle is invalid and you want to record that information. // An example is calling a syscall and getting back ERROR_INVALID_HANDLE. // This method will normally leak handles! - [System.Security.SecurityCritical] // auto-generated [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] [MethodImplAttribute(MethodImplOptions.InternalCall)] public extern void SetHandleAsInvalid(); @@ -295,7 +284,6 @@ public abstract class SafeHandle : CriticalFinalizerObject, IDisposable // when the method is interrupted prior to processing by a thread abort or // when the handle has already been (or is in the process of being) // released. - [System.Security.SecurityCritical] // auto-generated [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)] [MethodImplAttribute(MethodImplOptions.InternalCall)] public extern void DangerousAddRef(ref bool success); @@ -309,7 +297,6 @@ public abstract class SafeHandle : CriticalFinalizerObject, IDisposable // constitutes a potential security hole (via handle recycling) as well as a // correctness problem -- so don't ever expose Dangerous* calls out to // untrusted code. - [System.Security.SecurityCritical] // auto-generated [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] [MethodImplAttribute(MethodImplOptions.InternalCall)] public extern void DangerousRelease(); diff --git a/src/mscorlib/src/System/Runtime/InteropServices/SafeHeapHandle.cs b/src/mscorlib/src/System/Runtime/InteropServices/SafeHeapHandle.cs deleted file mode 100644 index b0c422d0c0..0000000000 --- a/src/mscorlib/src/System/Runtime/InteropServices/SafeHeapHandle.cs +++ /dev/null @@ -1,115 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -namespace System.Runtime.InteropServices -{ - /// <summary> - /// Handle for heap memory that allows tracking of capacity and reallocating. - /// </summary> - [System.Security.SecurityCritical] - internal sealed class SafeHeapHandle : SafeBuffer - { - /// <summary> - /// Allocate a buffer of the given size if requested. - /// </summary> - /// <param name="byteLength">Required size in bytes. Must be less than UInt32.MaxValue for 32 bit or UInt64.MaxValue for 64 bit.</param> - /// <exception cref="OutOfMemoryException">Thrown if the requested memory size cannot be allocated.</exception> - /// <exception cref="ArgumentOutOfRangeException">Thrown if size is greater than the maximum memory size.</exception> - public SafeHeapHandle(ulong byteLength) : base(ownsHandle: true) - { - Resize(byteLength); - } - - public override bool IsInvalid - { - [System.Security.SecurityCritical] - get - { return handle == IntPtr.Zero; } - } - - /// <summary> - /// Resize the buffer to the given size if requested. - /// </summary> - /// <param name="byteLength">Required size in bytes. Must be less than UInt32.MaxValue for 32 bit or UInt64.MaxValue for 64 bit.</param> - /// <exception cref="OutOfMemoryException">Thrown if the requested memory size cannot be allocated.</exception> - /// <exception cref="ArgumentOutOfRangeException">Thrown if size is greater than the maximum memory size.</exception> - public void Resize(ulong byteLength) - { - if (IsClosed) throw new ObjectDisposedException("SafeHeapHandle"); - - ulong originalLength = 0; - if (handle == IntPtr.Zero) - { - handle = Marshal.AllocHGlobal((IntPtr)byteLength); - } - else - { - originalLength = ByteLength; - - // This may or may not be the same handle, may realloc in place. If the - // handle changes Windows will deal with the old handle, trying to free it will - // cause an error. - handle = Marshal.ReAllocHGlobal(pv: handle, cb: (IntPtr)byteLength); - } - - if (handle == IntPtr.Zero) - { - // Only real plausible answer - throw new OutOfMemoryException(); - } - - if (byteLength > originalLength) - { - // Add pressure - ulong addedBytes = byteLength - originalLength; - if (addedBytes > long.MaxValue) - { - GC.AddMemoryPressure(long.MaxValue); - GC.AddMemoryPressure((long)(addedBytes - long.MaxValue)); - } - else - { - GC.AddMemoryPressure((long)addedBytes); - } - } - else - { - // Shrank or did nothing, release pressure if needed - RemoveMemoryPressure(originalLength - byteLength); - } - - Initialize(byteLength); - } - - private void RemoveMemoryPressure(ulong removedBytes) - { - if (removedBytes == 0) return; - - if (removedBytes > long.MaxValue) - { - GC.RemoveMemoryPressure(long.MaxValue); - GC.RemoveMemoryPressure((long)(removedBytes - long.MaxValue)); - } - else - { - GC.RemoveMemoryPressure((long)removedBytes); - } - } - - [System.Security.SecurityCritical] - protected override bool ReleaseHandle() - { - IntPtr handle = this.handle; - this.handle = IntPtr.Zero; - - if (handle != IntPtr.Zero) - { - RemoveMemoryPressure(ByteLength); - Marshal.FreeHGlobal(handle); - } - - return true; - } - } -}
\ No newline at end of file diff --git a/src/mscorlib/src/System/Runtime/InteropServices/StringBuffer.cs b/src/mscorlib/src/System/Runtime/InteropServices/StringBuffer.cs deleted file mode 100644 index 15b1b6ae8e..0000000000 --- a/src/mscorlib/src/System/Runtime/InteropServices/StringBuffer.cs +++ /dev/null @@ -1,402 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -namespace System.Runtime.InteropServices -{ - /// <summary> - /// Native buffer that deals in char size increments. Dispose to free memory. Allows buffers larger - /// than a maximum size string to enable working with very large string arrays. Always makes ordinal - /// comparisons. - /// - /// A more performant replacement for StringBuilder when performing native interop. - /// </summary> - /// <remarks> - /// Suggested use through P/Invoke: define DllImport arguments that take a character buffer as IntPtr. - /// NativeStringBuffer has an implicit conversion to IntPtr. - /// </remarks> - internal class StringBuffer : NativeBuffer - { - private uint _length; - - /// <summary> - /// Instantiate the buffer with capacity for at least the specified number of characters. Capacity - /// includes the trailing null character. - /// </summary> - public StringBuffer(uint initialCapacity = 0) - : base(initialCapacity * (ulong)sizeof(char)) - { - } - - /// <summary> - /// Instantiate the buffer with a copy of the specified string. - /// </summary> - public StringBuffer(string initialContents) - : base(0) - { - // We don't pass the count of bytes to the base constructor, appending will - // initialize to the correct size for the specified initial contents. - if (initialContents != null) - { - Append(initialContents); - } - } - - /// <summary> - /// Instantiate the buffer with a copy of the specified StringBuffer. - /// </summary> - public StringBuffer(StringBuffer initialContents) - : base(0) - { - // We don't pass the count of bytes to the base constructor, appending will - // initialize to the correct size for the specified initial contents. - if (initialContents != null) - { - Append(initialContents); - } - } - - /// <summary> - /// Get/set the character at the given index. - /// </summary> - /// <exception cref="ArgumentOutOfRangeException">Thrown if attempting to index outside of the buffer length.</exception> - public unsafe char this[uint index] - { - [System.Security.SecuritySafeCritical] - get - { - if (index >= _length) throw new ArgumentOutOfRangeException("index"); - return CharPointer[index]; - } - [System.Security.SecuritySafeCritical] - set - { - if (index >= _length) throw new ArgumentOutOfRangeException("index"); - CharPointer[index] = value; - } - } - - /// <summary> - /// Character capacity of the buffer. Includes the count for the trailing null character. - /// </summary> - public uint CharCapacity - { - [System.Security.SecuritySafeCritical] - get - { - ulong byteCapacity = ByteCapacity; - ulong charCapacity = byteCapacity == 0 ? 0 : byteCapacity / sizeof(char); - return charCapacity > uint.MaxValue ? uint.MaxValue : (uint)charCapacity; - } - } - - /// <summary> - /// Ensure capacity in characters is at least the given minimum. Capacity includes space for the trailing - /// null, which is not part of the Length. - /// </summary> - /// <exception cref="OutOfMemoryException">Thrown if unable to allocate memory when setting.</exception> - [System.Security.SecuritySafeCritical] - public void EnsureCharCapacity(uint minCapacity) - { - EnsureByteCapacity(minCapacity * (ulong)sizeof(char)); - } - - /// <summary> - /// The logical length of the buffer in characters. (Does not include the final null, which is auto appended.) Will automatically attempt to increase capacity. - /// This is where the usable data ends. - /// </summary> - /// <exception cref="OutOfMemoryException">Thrown if unable to allocate memory when setting.</exception> - /// <exception cref="ArgumentOutOfRangeException">Thrown if the set size in bytes is uint.MaxValue (as space is implicitly reservced for the trailing null).</exception> - public unsafe uint Length - { - get { return _length; } - [System.Security.SecuritySafeCritical] - set - { - if (value == uint.MaxValue) throw new ArgumentOutOfRangeException("Length"); - - // Null terminate - EnsureCharCapacity(value + 1); - CharPointer[value] = '\0'; - - _length = value; - } - } - - /// <summary> - /// For use when the native api null terminates but doesn't return a length. - /// If no null is found, the length will not be changed. - /// </summary> - [System.Security.SecuritySafeCritical] - public unsafe void SetLengthToFirstNull() - { - char* buffer = CharPointer; - uint capacity = CharCapacity; - for (uint i = 0; i < capacity; i++) - { - if (buffer[i] == '\0') - { - _length = i; - break; - } - } - } - - internal unsafe char* CharPointer - { - [System.Security.SecurityCritical] - get - { - return (char*)VoidPointer; - } - } - - /// <summary> - /// True if the buffer contains the given character. - /// </summary> - [System.Security.SecurityCritical] - public unsafe bool Contains(char value) - { - char* start = CharPointer; - uint length = _length; - - for (uint i = 0; i < length; i++) - { - if (*start++ == value) return true; - } - - return false; - } - - /// <summary> - /// Returns true if the buffer starts with the given string. - /// </summary> - [System.Security.SecuritySafeCritical] - public bool StartsWith(string value) - { - if (value == null) throw new ArgumentNullException("value"); - if (_length < (uint)value.Length) return false; - return SubstringEquals(value, startIndex: 0, count: value.Length); - } - - /// <summary> - /// Returns true if the specified StringBuffer substring equals the given value. - /// </summary> - /// <param name="value">The value to compare against the specified substring.</param> - /// <param name="startIndex">Start index of the sub string.</param> - /// <param name="count">Length of the substring, or -1 to check all remaining.</param> - /// <exception cref="ArgumentOutOfRangeException"> - /// Thrown if <paramref name="startIndex"/> or <paramref name="count"/> are outside the range - /// of the buffer's length. - /// </exception> - [System.Security.SecuritySafeCritical] - public unsafe bool SubstringEquals(string value, uint startIndex = 0, int count = -1) - { - if (value == null) return false; - if (count < -1) throw new ArgumentOutOfRangeException("count"); - if (startIndex > _length) throw new ArgumentOutOfRangeException("startIndex"); - - uint realCount = count == -1 ? _length - startIndex : (uint)count; - if (checked(startIndex + realCount) > _length) throw new ArgumentOutOfRangeException("count"); - - int length = value.Length; - - // Check the substring length against the input length - if (realCount != (uint)length) return false; - - fixed (char* valueStart = value) - { - char* bufferStart = CharPointer + startIndex; - for (int i = 0; i < length; i++) - { - // Note that indexing in this case generates faster code than trying to copy the pointer and increment it - if (*bufferStart++ != valueStart[i]) return false; - } - } - - return true; - } - - /// <summary> - /// Append the given string. - /// </summary> - /// <param name="value">The string to append.</param> - /// <param name="startIndex">The index in the input string to start appending from.</param> - /// <param name="count">The count of characters to copy from the input string, or -1 for all remaining.</param> - /// <exception cref="ArgumentNullException">Thrown if <paramref name="value"/> is null.</exception> - /// <exception cref="ArgumentOutOfRangeException"> - /// Thrown if <paramref name="startIndex"/> or <paramref name="count"/> are outside the range - /// of <paramref name="value"/> characters. - /// </exception> - [System.Security.SecuritySafeCritical] - public void Append(string value, int startIndex = 0, int count = -1) - { - CopyFrom( - bufferIndex: _length, - source: value, - sourceIndex: startIndex, - count: count); - } - - /// <summary> - /// Append the given buffer. - /// </summary> - /// <param name="value">The buffer to append.</param> - /// <param name="startIndex">The index in the input buffer to start appending from.</param> - /// <exception cref="ArgumentNullException">Thrown if <paramref name="value"/> is null.</exception> - /// <exception cref="ArgumentOutOfRangeException"> - /// Thrown if <paramref name="startIndex"/> is outside the range of <paramref name="value"/> characters. - /// </exception> - public void Append(StringBuffer value, uint startIndex = 0) - { - if (value == null) throw new ArgumentNullException("value"); - if (value.Length == 0) return; - value.CopyTo( - bufferIndex: startIndex, - destination: this, - destinationIndex: _length, - count: value.Length); - } - - /// <summary> - /// Append the given buffer. - /// </summary> - /// <param name="value">The buffer to append.</param> - /// <param name="startIndex">The index in the input buffer to start appending from.</param> - /// <param name="count">The count of characters to copy from the buffer string.</param> - /// <exception cref="ArgumentNullException">Thrown if <paramref name="value"/> is null.</exception> - /// <exception cref="ArgumentOutOfRangeException"> - /// Thrown if <paramref name="startIndex"/> or <paramref name="count"/> are outside the range - /// of <paramref name="value"/> characters. - /// </exception> - public void Append(StringBuffer value, uint startIndex, uint count) - { - if (value == null) throw new ArgumentNullException("value"); - if (count == 0) return; - value.CopyTo( - bufferIndex: startIndex, - destination: this, - destinationIndex: _length, - count: count); - } - - /// <summary> - /// Copy contents to the specified buffer. Destination index must be within current destination length. - /// Will grow the destination buffer if needed. - /// </summary> - /// <exception cref="ArgumentOutOfRangeException"> - /// Thrown if <paramref name="bufferIndex"/> or <paramref name="destinationIndex"/> or <paramref name="count"/> are outside the range - /// of <paramref name="value"/> characters. - /// </exception> - /// <exception cref="ArgumentNullException">Thrown if <paramref name="destination"/> is null.</exception> - [System.Security.SecuritySafeCritical] - public unsafe void CopyTo(uint bufferIndex, StringBuffer destination, uint destinationIndex, uint count) - { - if (destination == null) throw new ArgumentNullException("destination"); - if (destinationIndex > destination._length) throw new ArgumentOutOfRangeException("destinationIndex"); - if (bufferIndex >= _length) throw new ArgumentOutOfRangeException("bufferIndex"); - if (_length < checked(bufferIndex + count)) throw new ArgumentOutOfRangeException("count"); - - if (count == 0) return; - uint lastIndex = checked(destinationIndex + count); - if (destination._length < lastIndex) destination.Length = lastIndex; - - Buffer.MemoryCopy( - source: CharPointer + bufferIndex, - destination: destination.CharPointer + destinationIndex, - destinationSizeInBytes: checked((long)(destination.ByteCapacity - (destinationIndex * sizeof(char)))), - sourceBytesToCopy: checked((long)count * sizeof(char))); - } - - /// <summary> - /// Copy contents from the specified string into the buffer at the given index. Start index must be within the current length of - /// the buffer, will grow as necessary. - /// </summary> - /// <exception cref="ArgumentOutOfRangeException"> - /// Thrown if <paramref name="bufferIndex"/> or <paramref name="sourceIndex"/> or <paramref name="count"/> are outside the range - /// of <paramref name="value"/> characters. - /// </exception> - /// <exception cref="ArgumentNullException">Thrown if <paramref name="source"/> is null.</exception> - [System.Security.SecuritySafeCritical] - public unsafe void CopyFrom(uint bufferIndex, string source, int sourceIndex = 0, int count = -1) - { - if (source == null) throw new ArgumentNullException("source"); - if (bufferIndex > _length) throw new ArgumentOutOfRangeException("bufferIndex"); - if (sourceIndex < 0 || sourceIndex >= source.Length) throw new ArgumentOutOfRangeException("sourceIndex"); - if (count == -1) count = source.Length - sourceIndex; - if (count < 0 || source.Length - count < sourceIndex) throw new ArgumentOutOfRangeException("count"); - - if (count == 0) return; - uint lastIndex = bufferIndex + (uint)count; - if (_length < lastIndex) Length = lastIndex; - - fixed (char* content = source) - { - Buffer.MemoryCopy( - source: content + sourceIndex, - destination: CharPointer + bufferIndex, - destinationSizeInBytes: checked((long)(ByteCapacity - (bufferIndex * sizeof(char)))), - sourceBytesToCopy: (long)count * sizeof(char)); - } - } - - /// <summary> - /// Trim the specified values from the end of the buffer. If nothing is specified, nothing is trimmed. - /// </summary> - [System.Security.SecuritySafeCritical] - public unsafe void TrimEnd(char[] values) - { - if (values == null || values.Length == 0 || _length == 0) return; - - char* end = CharPointer + _length - 1; - - while (_length > 0 && Array.IndexOf(values, *end) >= 0) - { - Length = _length - 1; - end--; - } - } - - /// <summary> - /// String representation of the entire buffer. If the buffer is larger than the maximum size string (int.MaxValue) this will throw. - /// </summary> - /// <exception cref="InvalidOperationException">Thrown if the buffer is too big to fit into a string.</exception> - [System.Security.SecuritySafeCritical] - public unsafe override string ToString() - { - if (_length == 0) return string.Empty; - if (_length > int.MaxValue) throw new InvalidOperationException(); - return new string(CharPointer, startIndex: 0, length: (int)_length); - } - - /// <summary> - /// Get the given substring in the buffer. - /// </summary> - /// <param name="count">Count of characters to take, or remaining characters from <paramref name="startIndex"/> if -1.</param> - /// <exception cref="ArgumentOutOfRangeException"> - /// Thrown if <paramref name="startIndex"/> or <paramref name="count"/> are outside the range of the buffer's length - /// or count is greater than the maximum string size (int.MaxValue). - /// </exception> - [System.Security.SecuritySafeCritical] - public unsafe string Substring(uint startIndex, int count = -1) - { - if (startIndex > (_length == 0 ? 0 : _length - 1)) throw new ArgumentOutOfRangeException("startIndex"); - if (count < -1) throw new ArgumentOutOfRangeException("count"); - - uint realCount = count == -1 ? _length - startIndex : (uint)count; - if (realCount > int.MaxValue || checked(startIndex + realCount) > _length) throw new ArgumentOutOfRangeException("count"); - if (realCount == 0) return string.Empty; - - // The buffer could be bigger than will fit into a string, but the substring might fit. As the starting - // index might be bigger than int we need to index ourselves. - return new string(value: CharPointer + startIndex, startIndex: 0, length: (int)realCount); - } - - [System.Security.SecuritySafeCritical] - public override void Free() - { - base.Free(); - _length = 0; - } - } -}
\ No newline at end of file diff --git a/src/mscorlib/src/System/Runtime/InteropServices/TCEAdapterGen/EventProviderWriter.cs b/src/mscorlib/src/System/Runtime/InteropServices/TCEAdapterGen/EventProviderWriter.cs index 58f70e57b7..160a0ab491 100644 --- a/src/mscorlib/src/System/Runtime/InteropServices/TCEAdapterGen/EventProviderWriter.cs +++ b/src/mscorlib/src/System/Runtime/InteropServices/TCEAdapterGen/EventProviderWriter.cs @@ -10,6 +10,7 @@ namespace System.Runtime.InteropServices.TCEAdapterGen { using System.Reflection.Emit; using System.Collections; using System.Threading; + using System.Diagnostics; using System.Diagnostics.Contracts; internal class EventProviderWriter @@ -96,34 +97,34 @@ namespace System.Runtime.InteropServices.TCEAdapterGen { // Find the delegate on the event sink helper. FieldInfo DelegateField = SinkHelperClass.GetField( "m_" + SrcItfMethod.Name + "Delegate" ); - Contract.Assert(DelegateField != null, "Unable to find the field m_" + SrcItfMethod.Name + "Delegate on the sink helper"); + Debug.Assert(DelegateField != null, "Unable to find the field m_" + SrcItfMethod.Name + "Delegate on the sink helper"); // Find the cookie on the event sink helper. FieldInfo CookieField = SinkHelperClass.GetField( "m_dwCookie" ); - Contract.Assert(CookieField != null, "Unable to find the field m_dwCookie on the sink helper"); + Debug.Assert(CookieField != null, "Unable to find the field m_dwCookie on the sink helper"); // Retrieve the sink helper's constructor. ConstructorInfo SinkHelperCons = SinkHelperClass.GetConstructor(EventProviderWriter.DefaultLookup | BindingFlags.NonPublic, null, Array.Empty<Type>(), null ); - Contract.Assert(SinkHelperCons != null, "Unable to find the constructor for the sink helper"); + Debug.Assert(SinkHelperCons != null, "Unable to find the constructor for the sink helper"); // Retrieve the IConnectionPoint.Advise method. MethodInfo CPAdviseMethod = typeof(IConnectionPoint).GetMethod( "Advise" ); - Contract.Assert(CPAdviseMethod != null, "Unable to find the method ConnectionPoint.Advise"); + Debug.Assert(CPAdviseMethod != null, "Unable to find the method ConnectionPoint.Advise"); // Retrieve the ArrayList.Add method. aParamTypes = new Type[1]; aParamTypes[0] = typeof(Object); MethodInfo ArrayListAddMethod = typeof(ArrayList).GetMethod( "Add", aParamTypes, null ); - Contract.Assert(ArrayListAddMethod != null, "Unable to find the method ArrayList.Add"); + Debug.Assert(ArrayListAddMethod != null, "Unable to find the method ArrayList.Add"); // Retrieve the Monitor.Enter() method. MethodInfo MonitorEnterMethod = typeof(Monitor).GetMethod( "Enter", MonitorEnterParamTypes, null ); - Contract.Assert(MonitorEnterMethod != null, "Unable to find the method Monitor.Enter()"); + Debug.Assert(MonitorEnterMethod != null, "Unable to find the method Monitor.Enter()"); // Retrieve the Monitor.Exit() method. aParamTypes[0] = typeof(Object); MethodInfo MonitorExitMethod = typeof(Monitor).GetMethod( "Exit", aParamTypes, null ); - Contract.Assert(MonitorExitMethod != null, "Unable to find the method Monitor.Exit()"); + Debug.Assert(MonitorExitMethod != null, "Unable to find the method Monitor.Exit()"); // Define the add_XXX method. Type[] parameterTypes; @@ -239,51 +240,51 @@ namespace System.Runtime.InteropServices.TCEAdapterGen { // Find the delegate on the event sink helper. FieldInfo DelegateField = SinkHelperClass.GetField( "m_" + SrcItfMethod.Name + "Delegate" ); - Contract.Assert(DelegateField != null, "Unable to find the field m_" + SrcItfMethod.Name + "Delegate on the sink helper"); + Debug.Assert(DelegateField != null, "Unable to find the field m_" + SrcItfMethod.Name + "Delegate on the sink helper"); // Find the cookie on the event sink helper. FieldInfo CookieField = SinkHelperClass.GetField( "m_dwCookie" ); - Contract.Assert(CookieField != null, "Unable to find the field m_dwCookie on the sink helper"); + Debug.Assert(CookieField != null, "Unable to find the field m_dwCookie on the sink helper"); // Retrieve the ArrayList.RemoveAt method. aParamTypes = new Type[1]; aParamTypes[0] = typeof(Int32); MethodInfo ArrayListRemoveMethod = typeof(ArrayList).GetMethod( "RemoveAt", aParamTypes, null ); - Contract.Assert(ArrayListRemoveMethod != null, "Unable to find the method ArrayList.RemoveAt()"); + Debug.Assert(ArrayListRemoveMethod != null, "Unable to find the method ArrayList.RemoveAt()"); // Retrieve the ArrayList.Item property get method. PropertyInfo ArrayListItemProperty = typeof(ArrayList).GetProperty( "Item" ); - Contract.Assert(ArrayListItemProperty != null, "Unable to find the property ArrayList.Item"); + Debug.Assert(ArrayListItemProperty != null, "Unable to find the property ArrayList.Item"); MethodInfo ArrayListItemGetMethod = ArrayListItemProperty.GetGetMethod(); - Contract.Assert(ArrayListItemGetMethod != null, "Unable to find the get method for property ArrayList.Item"); + Debug.Assert(ArrayListItemGetMethod != null, "Unable to find the get method for property ArrayList.Item"); // Retrieve the ArrayList.Count property get method. PropertyInfo ArrayListSizeProperty = typeof(ArrayList).GetProperty( "Count" ); - Contract.Assert(ArrayListSizeProperty != null, "Unable to find the property ArrayList.Count"); + Debug.Assert(ArrayListSizeProperty != null, "Unable to find the property ArrayList.Count"); MethodInfo ArrayListSizeGetMethod = ArrayListSizeProperty.GetGetMethod(); - Contract.Assert(ArrayListSizeGetMethod != null, "Unable to find the get method for property ArrayList.Count"); + Debug.Assert(ArrayListSizeGetMethod != null, "Unable to find the get method for property ArrayList.Count"); // Retrieve the Delegate.Equals() method. aParamTypes[0] = typeof(Delegate); MethodInfo DelegateEqualsMethod = typeof(Delegate).GetMethod( "Equals", aParamTypes, null ); - Contract.Assert(DelegateEqualsMethod != null, "Unable to find the method Delegate.Equlals()"); + Debug.Assert(DelegateEqualsMethod != null, "Unable to find the method Delegate.Equlals()"); // Retrieve the Monitor.Enter() method. MethodInfo MonitorEnterMethod = typeof(Monitor).GetMethod("Enter", MonitorEnterParamTypes, null); - Contract.Assert(MonitorEnterMethod != null, "Unable to find the method Monitor.Enter()"); + Debug.Assert(MonitorEnterMethod != null, "Unable to find the method Monitor.Enter()"); // Retrieve the Monitor.Exit() method. aParamTypes[0] = typeof(Object); MethodInfo MonitorExitMethod = typeof(Monitor).GetMethod( "Exit", aParamTypes, null ); - Contract.Assert(MonitorExitMethod != null, "Unable to find the method Monitor.Exit()"); + Debug.Assert(MonitorExitMethod != null, "Unable to find the method Monitor.Exit()"); // Retrieve the ConnectionPoint.Unadvise() method. MethodInfo CPUnadviseMethod = typeof(IConnectionPoint).GetMethod( "Unadvise" ); - Contract.Assert(CPUnadviseMethod != null, "Unable to find the method ConnectionPoint.Unadvise()"); + Debug.Assert(CPUnadviseMethod != null, "Unable to find the method ConnectionPoint.Unadvise()"); // Retrieve the Marshal.ReleaseComObject() method. MethodInfo ReleaseComObjectMethod = typeof(Marshal).GetMethod( "ReleaseComObject" ); - Contract.Assert(ReleaseComObjectMethod != null, "Unable to find the method Marshal.ReleaseComObject()"); + Debug.Assert(ReleaseComObjectMethod != null, "Unable to find the method Marshal.ReleaseComObject()"); // Define the remove_XXX method. Type[] parameterTypes; @@ -463,7 +464,7 @@ namespace System.Runtime.InteropServices.TCEAdapterGen { { // Retrieve the constructor info for the array list's default constructor. ConstructorInfo DefaultArrayListCons = typeof(ArrayList).GetConstructor(EventProviderWriter.DefaultLookup, null, Array.Empty<Type>(), null ); - Contract.Assert(DefaultArrayListCons != null, "Unable to find the constructor for class ArrayList"); + Debug.Assert(DefaultArrayListCons != null, "Unable to find the constructor for class ArrayList"); // Temp byte array for Guid ubyte[] rgByteGuid = new ubyte[16]; @@ -472,11 +473,11 @@ namespace System.Runtime.InteropServices.TCEAdapterGen { Type[] aParamTypes = new Type[1]; aParamTypes[0] = typeof(Byte[]); ConstructorInfo ByteArrayGUIDCons = typeof(Guid).GetConstructor(EventProviderWriter.DefaultLookup, null, aParamTypes, null ); - Contract.Assert(ByteArrayGUIDCons != null, "Unable to find the constructor for GUID that accepts a string as argument"); + Debug.Assert(ByteArrayGUIDCons != null, "Unable to find the constructor for GUID that accepts a string as argument"); // Retrieve the IConnectionPointContainer.FindConnectionPoint() method. MethodInfo CPCFindCPMethod = typeof(IConnectionPointContainer).GetMethod( "FindConnectionPoint" ); - Contract.Assert(CPCFindCPMethod != null, "Unable to find the method ConnectionPointContainer.FindConnectionPoint()"); + Debug.Assert(CPCFindCPMethod != null, "Unable to find the method ConnectionPointContainer.FindConnectionPoint()"); // Define the Init method itself. MethodBuilder Meth = OutputTypeBuilder.DefineMethod( @@ -553,7 +554,7 @@ namespace System.Runtime.InteropServices.TCEAdapterGen { { // Retrieve the constructor info for the base class's constructor. ConstructorInfo DefaultBaseClsCons = typeof(Object).GetConstructor(BindingFlags.Instance | BindingFlags.Public, null, Array.Empty<Type>(), null ); - Contract.Assert(DefaultBaseClsCons != null, "Unable to find the object's public default constructor"); + Debug.Assert(DefaultBaseClsCons != null, "Unable to find the object's public default constructor"); // Define the default constructor. MethodAttributes ctorAttributes = MethodAttributes.SpecialName | (DefaultBaseClsCons.Attributes & MethodAttributes.MemberAccessMask); @@ -584,37 +585,37 @@ namespace System.Runtime.InteropServices.TCEAdapterGen { { // Find the cookie on the event sink helper. FieldInfo CookieField = SinkHelperClass.GetField( "m_dwCookie" ); - Contract.Assert(CookieField != null, "Unable to find the field m_dwCookie on the sink helper"); + Debug.Assert(CookieField != null, "Unable to find the field m_dwCookie on the sink helper"); // Retrieve the ArrayList.Item property get method. PropertyInfo ArrayListItemProperty = typeof(ArrayList).GetProperty( "Item" ); - Contract.Assert(ArrayListItemProperty != null, "Unable to find the property ArrayList.Item"); + Debug.Assert(ArrayListItemProperty != null, "Unable to find the property ArrayList.Item"); MethodInfo ArrayListItemGetMethod = ArrayListItemProperty.GetGetMethod(); - Contract.Assert(ArrayListItemGetMethod != null, "Unable to find the get method for property ArrayList.Item"); + Debug.Assert(ArrayListItemGetMethod != null, "Unable to find the get method for property ArrayList.Item"); // Retrieve the ArrayList.Count property get method. PropertyInfo ArrayListSizeProperty = typeof(ArrayList).GetProperty( "Count" ); - Contract.Assert(ArrayListSizeProperty != null, "Unable to find the property ArrayList.Count"); + Debug.Assert(ArrayListSizeProperty != null, "Unable to find the property ArrayList.Count"); MethodInfo ArrayListSizeGetMethod = ArrayListSizeProperty.GetGetMethod(); - Contract.Assert(ArrayListSizeGetMethod != null, "Unable to find the get method for property ArrayList.Count"); + Debug.Assert(ArrayListSizeGetMethod != null, "Unable to find the get method for property ArrayList.Count"); // Retrieve the ConnectionPoint.Unadvise() method. MethodInfo CPUnadviseMethod = typeof(IConnectionPoint).GetMethod( "Unadvise" ); - Contract.Assert(CPUnadviseMethod != null, "Unable to find the method ConnectionPoint.Unadvise()"); + Debug.Assert(CPUnadviseMethod != null, "Unable to find the method ConnectionPoint.Unadvise()"); // Retrieve the Marshal.ReleaseComObject() method. MethodInfo ReleaseComObjectMethod = typeof(Marshal).GetMethod( "ReleaseComObject" ); - Contract.Assert(ReleaseComObjectMethod != null, "Unable to find the method Marshal.ReleaseComObject()"); + Debug.Assert(ReleaseComObjectMethod != null, "Unable to find the method Marshal.ReleaseComObject()"); // Retrieve the Monitor.Enter() method. MethodInfo MonitorEnterMethod = typeof(Monitor).GetMethod("Enter", MonitorEnterParamTypes, null); - Contract.Assert(MonitorEnterMethod != null, "Unable to find the method Monitor.Enter()"); + Debug.Assert(MonitorEnterMethod != null, "Unable to find the method Monitor.Enter()"); // Retrieve the Monitor.Exit() method. Type[] aParamTypes = new Type[1]; aParamTypes[0] = typeof(Object); MethodInfo MonitorExitMethod = typeof(Monitor).GetMethod( "Exit", aParamTypes, null ); - Contract.Assert(MonitorExitMethod != null, "Unable to find the method Monitor.Exit()"); + Debug.Assert(MonitorExitMethod != null, "Unable to find the method Monitor.Exit()"); // Define the Finalize method itself. MethodBuilder Meth = OutputTypeBuilder.DefineMethod( "Finalize", MethodAttributes.Public | MethodAttributes.Virtual, null, null ); @@ -743,7 +744,7 @@ namespace System.Runtime.InteropServices.TCEAdapterGen { { // Retrieve the method info for GC.SuppressFinalize(). MethodInfo SuppressFinalizeMethod = typeof(GC).GetMethod("SuppressFinalize"); - Contract.Assert(SuppressFinalizeMethod != null, "Unable to find the GC.SuppressFinalize"); + Debug.Assert(SuppressFinalizeMethod != null, "Unable to find the GC.SuppressFinalize"); // Define the Finalize method itself. MethodBuilder Meth = OutputTypeBuilder.DefineMethod( "Dispose", MethodAttributes.Public | MethodAttributes.Virtual, null, null ); diff --git a/src/mscorlib/src/System/Runtime/InteropServices/TCEAdapterGen/EventSinkHelperWriter.cs b/src/mscorlib/src/System/Runtime/InteropServices/TCEAdapterGen/EventSinkHelperWriter.cs index 0367e79bdd..862419cc98 100644 --- a/src/mscorlib/src/System/Runtime/InteropServices/TCEAdapterGen/EventSinkHelperWriter.cs +++ b/src/mscorlib/src/System/Runtime/InteropServices/TCEAdapterGen/EventSinkHelperWriter.cs @@ -8,6 +8,7 @@ namespace System.Runtime.InteropServices.TCEAdapterGen { using System.Reflection; using System.Reflection.Emit; using System.Collections; + using System.Diagnostics; using System.Diagnostics.Contracts; internal class EventSinkHelperWriter { @@ -65,7 +66,7 @@ namespace System.Runtime.InteropServices.TCEAdapterGen { // Retrieve the delegate type from the add_XXX method. MethodInfo AddMeth = m_EventItfType.GetMethod( "add_" + aMethods[cMethods].Name ); ParameterInfo[] aParams = AddMeth.GetParameters(); - Contract.Assert(aParams.Length == 1, "All event interface methods must take a single delegate derived type and have a void return type"); + Debug.Assert(aParams.Length == 1, "All event interface methods must take a single delegate derived type and have a void return type"); Type DelegateCls = aParams[0].ParameterType; // Define the delegate instance field. @@ -119,7 +120,7 @@ namespace System.Runtime.InteropServices.TCEAdapterGen { { // Retrieve the method info for the invoke method on the delegate. MethodInfo DelegateInvokeMethod = DelegateCls.GetMethod( "Invoke" ); - Contract.Assert(DelegateInvokeMethod != null, "Unable to find method Delegate.Invoke()"); + Debug.Assert(DelegateInvokeMethod != null, "Unable to find method Delegate.Invoke()"); // Retrieve the return type. Type ReturnType = Method.ReturnType; @@ -229,7 +230,7 @@ namespace System.Runtime.InteropServices.TCEAdapterGen { if ( ReturnType == typeof(IntPtr) ) il.Emit( OpCodes.Ldc_I4_0 ); else - Contract.Assert(false, "Unexpected type for Primitive type."); + Debug.Assert(false, "Unexpected type for Primitive type."); break; } } @@ -254,7 +255,7 @@ namespace System.Runtime.InteropServices.TCEAdapterGen { { // Retrieve the constructor info for the base classe's constructor. ConstructorInfo DefaultBaseClsCons = typeof(Object).GetConstructor(BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public, null, Array.Empty<Type>(), null ); - Contract.Assert(DefaultBaseClsCons != null, "Unable to find the constructor for class " + m_InputType.Name); + Debug.Assert(DefaultBaseClsCons != null, "Unable to find the constructor for class " + m_InputType.Name); // Define the default constructor. MethodBuilder Cons = OutputTypeBuilder.DefineMethod( ".ctor", diff --git a/src/mscorlib/src/System/Runtime/InteropServices/TypeLibConverter.cs b/src/mscorlib/src/System/Runtime/InteropServices/TypeLibConverter.cs deleted file mode 100644 index e6b148a0a5..0000000000 --- a/src/mscorlib/src/System/Runtime/InteropServices/TypeLibConverter.cs +++ /dev/null @@ -1,595 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -/*============================================================================= -** -** -** -** Purpose: Component that implements the ITypeLibConverter interface and -** does the actual work of converting a typelib to metadata and -** vice versa. -** -** -=============================================================================*/ -#if !FEATURE_CORECLR // current implementation requires reflection only load -namespace System.Runtime.InteropServices { - - using System; - using System.Diagnostics.Contracts; - using System.Collections; - using System.Collections.Generic; - using System.Threading; - using System.Runtime.InteropServices.TCEAdapterGen; - using System.IO; - using System.Reflection; - using System.Reflection.Emit; - using System.Configuration.Assemblies; - using Microsoft.Win32; - using System.Runtime.CompilerServices; - using System.Globalization; - using System.Security; - using System.Security.Permissions; - using System.Runtime.InteropServices.ComTypes; - using System.Runtime.Versioning; - using WORD = System.UInt16; - using DWORD = System.UInt32; - using _TYPELIBATTR = System.Runtime.InteropServices.ComTypes.TYPELIBATTR; - - [Guid("F1C3BF79-C3E4-11d3-88E7-00902754C43A")] - [ClassInterface(ClassInterfaceType.None)] -[System.Runtime.InteropServices.ComVisible(true)] - public sealed class TypeLibConverter : ITypeLibConverter - { - private const String s_strTypeLibAssemblyTitlePrefix = "TypeLib "; - private const String s_strTypeLibAssemblyDescPrefix = "Assembly generated from typelib "; - private const int MAX_NAMESPACE_LENGTH = 1024; - - - // - // ITypeLibConverter interface. - // - - [System.Security.SecuritySafeCritical] // auto-generated - [SecurityPermissionAttribute(SecurityAction.Demand, Flags=SecurityPermissionFlag.UnmanagedCode)] - public AssemblyBuilder ConvertTypeLibToAssembly([MarshalAs(UnmanagedType.Interface)] Object typeLib, - String asmFileName, - int flags, - ITypeLibImporterNotifySink notifySink, - byte[] publicKey, - StrongNameKeyPair keyPair, - bool unsafeInterfaces) - { - return ConvertTypeLibToAssembly(typeLib, - asmFileName, - (unsafeInterfaces - ? TypeLibImporterFlags.UnsafeInterfaces - : 0), - notifySink, - publicKey, - keyPair, - null, - null); - } - - - - - [System.Security.SecuritySafeCritical] // auto-generated - [SecurityPermissionAttribute(SecurityAction.Demand, Flags=SecurityPermissionFlag.UnmanagedCode)] - public AssemblyBuilder ConvertTypeLibToAssembly([MarshalAs(UnmanagedType.Interface)] Object typeLib, - String asmFileName, - TypeLibImporterFlags flags, - ITypeLibImporterNotifySink notifySink, - byte[] publicKey, - StrongNameKeyPair keyPair, - String asmNamespace, - Version asmVersion) - { - // Validate the arguments. - if (typeLib == null) - throw new ArgumentNullException("typeLib"); - if (asmFileName == null) - throw new ArgumentNullException("asmFileName"); - if (notifySink == null) - throw new ArgumentNullException("notifySink"); - if (String.Empty.Equals(asmFileName)) - throw new ArgumentException(Environment.GetResourceString("Arg_InvalidFileName"), "asmFileName"); - if (asmFileName.Length > Path.MaxPath) - throw new ArgumentException(Environment.GetResourceString("IO.PathTooLong"), asmFileName); - if ((flags & TypeLibImporterFlags.PrimaryInteropAssembly) != 0 && publicKey == null && keyPair == null) - throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_PIAMustBeStrongNamed")); - Contract.EndContractBlock(); - - ArrayList eventItfInfoList = null; - - // Determine the AssemblyNameFlags - AssemblyNameFlags asmNameFlags = AssemblyNameFlags.None; - - // Retrieve the assembly name from the typelib. - AssemblyName asmName = GetAssemblyNameFromTypelib(typeLib, asmFileName, publicKey, keyPair, asmVersion, asmNameFlags); - - // Create the dynamic assembly that will contain the converted typelib types. - AssemblyBuilder asmBldr = CreateAssemblyForTypeLib(typeLib, asmFileName, asmName, - (flags & TypeLibImporterFlags.PrimaryInteropAssembly) != 0, - (flags & TypeLibImporterFlags.ReflectionOnlyLoading) != 0, - (flags & TypeLibImporterFlags.NoDefineVersionResource) != 0); - - // Define a dynamic module that will contain the contain the imported types. - String strNonQualifiedAsmFileName = Path.GetFileName(asmFileName); - ModuleBuilder modBldr = asmBldr.DefineDynamicModule(strNonQualifiedAsmFileName, strNonQualifiedAsmFileName); - - // If the namespace hasn't been specified, then use the assembly name. - if (asmNamespace == null) - asmNamespace = asmName.Name; - - // Create a type resolve handler that will also intercept resolve ref messages - // on the sink interface to build up a list of referenced assemblies. - TypeResolveHandler typeResolveHandler = new TypeResolveHandler(modBldr, notifySink); - - // Add a listener for the type resolve events. - AppDomain currentDomain = Thread.GetDomain(); - ResolveEventHandler resolveHandler = new ResolveEventHandler(typeResolveHandler.ResolveEvent); - ResolveEventHandler asmResolveHandler = new ResolveEventHandler(typeResolveHandler.ResolveAsmEvent); - ResolveEventHandler ROAsmResolveHandler = new ResolveEventHandler(typeResolveHandler.ResolveROAsmEvent); - currentDomain.TypeResolve += resolveHandler; - currentDomain.AssemblyResolve += asmResolveHandler; - currentDomain.ReflectionOnlyAssemblyResolve += ROAsmResolveHandler; - - // Convert the types contained in the typelib into metadata and add them to the assembly. - nConvertTypeLibToMetadata(typeLib, asmBldr.InternalAssembly, modBldr.InternalModule, asmNamespace, flags, typeResolveHandler, out eventItfInfoList); - - // Update the COM types in the assembly. - UpdateComTypesInAssembly(asmBldr, modBldr); - - // If there are any event sources then generate the TCE adapters. - if (eventItfInfoList.Count > 0) - new TCEAdapterGenerator().Process(modBldr, eventItfInfoList); - - // Remove the listener for the type resolve events. - currentDomain.TypeResolve -= resolveHandler; - currentDomain.AssemblyResolve -= asmResolveHandler; - currentDomain.ReflectionOnlyAssemblyResolve -= ROAsmResolveHandler; - - // We have finished converting the typelib and now have a fully formed assembly. - return asmBldr; - } - - [System.Security.SecuritySafeCritical] // auto-generated - [SecurityPermissionAttribute(SecurityAction.Demand, Flags=SecurityPermissionFlag.UnmanagedCode)] - [return : MarshalAs(UnmanagedType.Interface)] - public Object ConvertAssemblyToTypeLib(Assembly assembly, String strTypeLibName, TypeLibExporterFlags flags, ITypeLibExporterNotifySink notifySink) - { - RuntimeAssembly rtAssembly; - AssemblyBuilder ab = assembly as AssemblyBuilder; - if (ab != null) - rtAssembly = ab.InternalAssembly; - else - rtAssembly = assembly as RuntimeAssembly; - - return nConvertAssemblyToTypeLib(rtAssembly, strTypeLibName, flags, notifySink); - } - - public bool GetPrimaryInteropAssembly(Guid g, Int32 major, Int32 minor, Int32 lcid, out String asmName, out String asmCodeBase) - { - String strTlbId = "{" + g.ToString().ToUpper(CultureInfo.InvariantCulture) + "}"; - String strVersion = major.ToString("x", CultureInfo.InvariantCulture) + "." + minor.ToString("x", CultureInfo.InvariantCulture); - - // Set the two out values to null before we start. - asmName = null; - asmCodeBase = null; - - // Try to open the HKEY_CLASS_ROOT\TypeLib key. - using (RegistryKey TypeLibKey = Registry.ClassesRoot.OpenSubKey("TypeLib", false)) - { - if (TypeLibKey != null) - { - // Try to open the HKEY_CLASS_ROOT\TypeLib\<TLBID> key. - using (RegistryKey TypeLibSubKey = TypeLibKey.OpenSubKey(strTlbId)) - { - if (TypeLibSubKey != null) - { - // Try to open the HKEY_CLASS_ROOT\TypeLib\<TLBID>\<Major.Minor> key. - using (RegistryKey VersionKey = TypeLibSubKey.OpenSubKey(strVersion, false)) - { - if (VersionKey != null) - { - // Attempt to retrieve the assembly name and codebase under the version key. - asmName = (String)VersionKey.GetValue("PrimaryInteropAssemblyName"); - asmCodeBase = (String)VersionKey.GetValue("PrimaryInteropAssemblyCodeBase"); - } - } - } - } - } - } - - // If the assembly name isn't null, then we found an PIA. - return asmName != null; - } - - - // - // Non native helper methods. - // - - [System.Security.SecurityCritical] // auto-generated - [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable - private static AssemblyBuilder CreateAssemblyForTypeLib(Object typeLib, String asmFileName, AssemblyName asmName, bool bPrimaryInteropAssembly, bool bReflectionOnly, bool bNoDefineVersionResource) - { - // Retrieve the current app domain. - AppDomain currentDomain = Thread.GetDomain(); - - // Retrieve the directory from the assembly file name. - String dir = null; - if (asmFileName != null) - { - dir = Path.GetDirectoryName(asmFileName); - if (String.IsNullOrEmpty(dir)) - dir = null; - } - - AssemblyBuilderAccess aba; - if (bReflectionOnly) - { - aba = AssemblyBuilderAccess.ReflectionOnly; - } - else - { - aba = AssemblyBuilderAccess.RunAndSave; - } - - // Create the dynamic assembly itself. - AssemblyBuilder asmBldr; - - List<CustomAttributeBuilder> assemblyAttributes = new List<CustomAttributeBuilder>(); -#if !FEATURE_CORECLR - // mscorlib.dll must specify the security rules that assemblies it emits are to use, since by - // default all assemblies will follow security rule set level 2, and we want to make that an - // explicit decision. - ConstructorInfo securityRulesCtor = typeof(SecurityRulesAttribute).GetConstructor(new Type[] { typeof(SecurityRuleSet) }); - CustomAttributeBuilder securityRulesAttribute = - new CustomAttributeBuilder(securityRulesCtor, new object[] { SecurityRuleSet.Level2 }); - assemblyAttributes.Add(securityRulesAttribute); -#endif // !FEATURE_CORECLR - - asmBldr = currentDomain.DefineDynamicAssembly(asmName, aba, dir, false, assemblyAttributes); - - // Set the Guid custom attribute on the assembly. - SetGuidAttributeOnAssembly(asmBldr, typeLib); - - // Set the imported from COM attribute on the assembly and return it. - SetImportedFromTypeLibAttrOnAssembly(asmBldr, typeLib); - - // Set the version information on the typelib. - if (bNoDefineVersionResource) - { - SetTypeLibVersionAttribute(asmBldr, typeLib); - } - else - { - SetVersionInformation(asmBldr, typeLib, asmName); - } - - // If we are generating a PIA, then set the PIA custom attribute. - if (bPrimaryInteropAssembly) - SetPIAAttributeOnAssembly(asmBldr, typeLib); - - return asmBldr; - } - - [System.Security.SecurityCritical] // auto-generated - internal static AssemblyName GetAssemblyNameFromTypelib(Object typeLib, String asmFileName, byte[] publicKey, StrongNameKeyPair keyPair, Version asmVersion, AssemblyNameFlags asmNameFlags) - { - // Extract the name of the typelib. - String strTypeLibName = null; - String strDocString = null; - int dwHelpContext = 0; - String strHelpFile = null; - ITypeLib pTLB = (ITypeLib)typeLib; - pTLB.GetDocumentation(-1, out strTypeLibName, out strDocString, out dwHelpContext, out strHelpFile); - - // Retrieve the name to use for the assembly. - if (asmFileName == null) - { - asmFileName = strTypeLibName; - } - else - { - Contract.Assert((asmFileName != null) && (asmFileName.Length > 0), "The assembly file name cannot be an empty string!"); - - String strFileNameNoPath = Path.GetFileName(asmFileName); - String strExtension = Path.GetExtension(asmFileName); - - // Validate that the extension is valid. - bool bExtensionValid = ".dll".Equals(strExtension, StringComparison.OrdinalIgnoreCase); - - // If the extension is not valid then tell the user and quit. - if (!bExtensionValid) - throw new ArgumentException(Environment.GetResourceString("Arg_InvalidFileExtension")); - - // The assembly cannot contain the path nor the extension. - asmFileName = strFileNameNoPath.Substring(0, strFileNameNoPath.Length - ".dll".Length); - } - - // If the version information was not specified, then retrieve it from the typelib. - if (asmVersion == null) - { - int major; - int minor; - Marshal.GetTypeLibVersion(pTLB, out major, out minor); - asmVersion = new Version(major, minor, 0, 0); - } - - // Create the assembly name for the imported typelib's assembly. - AssemblyName AsmName = new AssemblyName(); - AsmName.Init( - asmFileName, - publicKey, - null, - asmVersion, - null, - AssemblyHashAlgorithm.None, - AssemblyVersionCompatibility.SameMachine, - null, - asmNameFlags, - keyPair); - - return AsmName; - } - - private static void UpdateComTypesInAssembly(AssemblyBuilder asmBldr, ModuleBuilder modBldr) - { - // Retrieve the AssemblyBuilderData associated with the assembly builder. - AssemblyBuilderData AsmBldrData = asmBldr.m_assemblyData; - - // Go through the types in the module and add them as public COM types. - Type[] aTypes = modBldr.GetTypes(); - int NumTypes = aTypes.Length; - for (int cTypes = 0; cTypes < NumTypes; cTypes++) - AsmBldrData.AddPublicComType(aTypes[cTypes]); - } - - - [System.Security.SecurityCritical] // auto-generated - private static void SetGuidAttributeOnAssembly(AssemblyBuilder asmBldr, Object typeLib) - { - // Retrieve the GuidAttribute constructor. - Type []aConsParams = new Type[1] {typeof(String)}; - ConstructorInfo GuidAttrCons = typeof(GuidAttribute).GetConstructor(aConsParams); - - // Create an instance of the custom attribute builder. - Object[] aArgs = new Object[1] {Marshal.GetTypeLibGuid((ITypeLib)typeLib).ToString()}; - CustomAttributeBuilder GuidCABuilder = new CustomAttributeBuilder(GuidAttrCons, aArgs); - - // Set the GuidAttribute on the assembly builder. - asmBldr.SetCustomAttribute(GuidCABuilder); - } - - [System.Security.SecurityCritical] // auto-generated - private static void SetImportedFromTypeLibAttrOnAssembly(AssemblyBuilder asmBldr, Object typeLib) - { - // Retrieve the ImportedFromTypeLibAttribute constructor. - Type []aConsParams = new Type[1] {typeof(String)}; - ConstructorInfo ImpFromComAttrCons = typeof(ImportedFromTypeLibAttribute).GetConstructor(aConsParams); - - // Retrieve the name of the typelib. - String strTypeLibName = Marshal.GetTypeLibName((ITypeLib)typeLib); - - // Create an instance of the custom attribute builder. - Object[] aArgs = new Object[1] {strTypeLibName}; - CustomAttributeBuilder ImpFromComCABuilder = new CustomAttributeBuilder(ImpFromComAttrCons, aArgs); - - // Set the ImportedFromTypeLibAttribute on the assembly builder. - asmBldr.SetCustomAttribute(ImpFromComCABuilder); - } - - [System.Security.SecurityCritical] // auto-generated - private static void SetTypeLibVersionAttribute(AssemblyBuilder asmBldr, Object typeLib) - { - Type []aConsParams = new Type[2] {typeof(int), typeof(int)}; - ConstructorInfo TypeLibVerCons = typeof(TypeLibVersionAttribute).GetConstructor(aConsParams); - - // Get the typelib version - int major; - int minor; - Marshal.GetTypeLibVersion((ITypeLib)typeLib, out major, out minor); - - // Create an instance of the custom attribute builder. - Object[] aArgs = new Object[2] {major, minor}; - CustomAttributeBuilder TypeLibVerBuilder = new CustomAttributeBuilder(TypeLibVerCons, aArgs); - - // Set the attribute on the assembly builder. - asmBldr.SetCustomAttribute(TypeLibVerBuilder); - } - - [System.Security.SecurityCritical] // auto-generated - private static void SetVersionInformation(AssemblyBuilder asmBldr, Object typeLib, AssemblyName asmName) - { - // Extract the name of the typelib. - String strTypeLibName = null; - String strDocString = null; - int dwHelpContext = 0; - String strHelpFile = null; - ITypeLib pTLB = (ITypeLib)typeLib; - pTLB.GetDocumentation(-1, out strTypeLibName, out strDocString, out dwHelpContext, out strHelpFile); - - // Generate the product name string from the named of the typelib. - String strProductName = String.Format(CultureInfo.InvariantCulture, Environment.GetResourceString("TypeLibConverter_ImportedTypeLibProductName"), strTypeLibName); - - // Set the OS version information. - asmBldr.DefineVersionInfoResource(strProductName, asmName.Version.ToString(), null, null, null); - - // Set the TypeLibVersion attribute - SetTypeLibVersionAttribute(asmBldr, typeLib); - } - - [System.Security.SecurityCritical] // auto-generated - private static void SetPIAAttributeOnAssembly(AssemblyBuilder asmBldr, Object typeLib) - { - IntPtr pAttr = IntPtr.Zero; - _TYPELIBATTR Attr; - ITypeLib pTLB = (ITypeLib)typeLib; - int Major = 0; - int Minor = 0; - - // Retrieve the PrimaryInteropAssemblyAttribute constructor. - Type []aConsParams = new Type[2] {typeof(int), typeof(int)}; - ConstructorInfo PIAAttrCons = typeof(PrimaryInteropAssemblyAttribute).GetConstructor(aConsParams); - - // Retrieve the major and minor version from the typelib. - try - { - pTLB.GetLibAttr(out pAttr); - Attr = (_TYPELIBATTR)Marshal.PtrToStructure(pAttr, typeof(_TYPELIBATTR)); - Major = Attr.wMajorVerNum; - Minor = Attr.wMinorVerNum; - } - finally - { - // Release the typelib attributes. - if (pAttr != IntPtr.Zero) - pTLB.ReleaseTLibAttr(pAttr); - } - - // Create an instance of the custom attribute builder. - Object[] aArgs = new Object[2] {Major, Minor}; - CustomAttributeBuilder PIACABuilder = new CustomAttributeBuilder(PIAAttrCons, aArgs); - - // Set the PrimaryInteropAssemblyAttribute on the assembly builder. - asmBldr.SetCustomAttribute(PIACABuilder); - } - - - // - // Native helper methods. - // - - [System.Security.SecurityCritical] // auto-generated - [MethodImplAttribute(MethodImplOptions.InternalCall)] - private static extern void nConvertTypeLibToMetadata(Object typeLib, RuntimeAssembly asmBldr, RuntimeModule modBldr, String nameSpace, TypeLibImporterFlags flags, ITypeLibImporterNotifySink notifySink, out ArrayList eventItfInfoList); - - // Must use assembly versioning or GuidAttribute to avoid collisions in typelib export or registration. - [System.Security.SecurityCritical] // auto-generated - [MethodImplAttribute(MethodImplOptions.InternalCall)] - private static extern Object nConvertAssemblyToTypeLib(RuntimeAssembly assembly, String strTypeLibName, TypeLibExporterFlags flags, ITypeLibExporterNotifySink notifySink); - - [System.Security.SecurityCritical] // auto-generated - [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode), SuppressUnmanagedCodeSecurity] - internal extern static void LoadInMemoryTypeByName(RuntimeModule module, String className); - - // - // Helper class called when a resolve type event is fired. - // - - private class TypeResolveHandler : ITypeLibImporterNotifySink - { - public TypeResolveHandler(ModuleBuilder mod, ITypeLibImporterNotifySink userSink) - { - m_Module = mod; - m_UserSink = userSink; - } - - public void ReportEvent(ImporterEventKind eventKind, int eventCode, String eventMsg) - { - m_UserSink.ReportEvent(eventKind, eventCode, eventMsg); - } - - public Assembly ResolveRef(Object typeLib) - { - Contract.Ensures(Contract.Result<Assembly>() != null && Contract.Result<Assembly>() is RuntimeAssembly); - Contract.EndContractBlock(); - - // Call the user sink to resolve the reference. - Assembly asm = m_UserSink.ResolveRef(typeLib); - - if (asm == null) - throw new ArgumentNullException(); - - // Return the resolved assembly. We extract the internal assembly because we are called - // by the VM which accesses fields of the object directly and does not go via those - // delegating properties (the fields are empty if asm is an (external) AssemblyBuilder). - - RuntimeAssembly rtAssembly = asm as RuntimeAssembly; - if (rtAssembly == null) - { - AssemblyBuilder ab = asm as AssemblyBuilder; - if (ab != null) - rtAssembly = ab.InternalAssembly; - } - - if (rtAssembly == null) - throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeAssembly")); - - // Add the assembly to the list of assemblies. - m_AsmList.Add(rtAssembly); - - return rtAssembly; - } - - [System.Security.SecurityCritical] // auto-generated - public Assembly ResolveEvent(Object sender, ResolveEventArgs args) - { - // We need to load the type in the resolve event so that we will deal with - // cases where we are trying to load the CoClass before the interface has - // been loaded. - try - { - LoadInMemoryTypeByName(m_Module.GetNativeHandle(), args.Name); - return m_Module.Assembly; - } - catch (TypeLoadException e) - { - if (e.ResourceId != System.__HResults.COR_E_TYPELOAD) // type not found - throw; - } - - foreach (RuntimeAssembly asm in m_AsmList) - { - try - { - asm.GetType(args.Name, true, false); - return asm; - } - catch (TypeLoadException e) - { - if (e._HResult != System.__HResults.COR_E_TYPELOAD) // type not found - throw; - } - } - - return null; - } - - public Assembly ResolveAsmEvent(Object sender, ResolveEventArgs args) - { - foreach (RuntimeAssembly asm in m_AsmList) - { - if (String.Compare(asm.FullName, args.Name, StringComparison.OrdinalIgnoreCase) == 0) - return asm; - } - - return null; - } - - public Assembly ResolveROAsmEvent(Object sender, ResolveEventArgs args) - { - foreach (RuntimeAssembly asm in m_AsmList) - { - if (String.Compare(asm.FullName, args.Name, StringComparison.OrdinalIgnoreCase) == 0) - return asm; - } - - // We failed to find the referenced assembly in our pre-loaded assemblies, so try to load it based on policy. - string asmName = AppDomain.CurrentDomain.ApplyPolicy(args.Name); - return Assembly.ReflectionOnlyLoad(asmName); - } - - private ModuleBuilder m_Module; - private ITypeLibImporterNotifySink m_UserSink; - private List<RuntimeAssembly> m_AsmList = new List<RuntimeAssembly>(); - } - } -} -#endif // !FEATURE_CORECLR // current implementation requires reflection only load - diff --git a/src/mscorlib/src/System/Runtime/InteropServices/Variant.cs b/src/mscorlib/src/System/Runtime/InteropServices/Variant.cs index 9be1588ac0..c7bbb78ae6 100644 --- a/src/mscorlib/src/System/Runtime/InteropServices/Variant.cs +++ b/src/mscorlib/src/System/Runtime/InteropServices/Variant.cs @@ -11,7 +11,6 @@ namespace System.Runtime.InteropServices { /// to and from COM calls. /// </summary> [StructLayout(LayoutKind.Explicit)] - [System.Security.SecurityCritical] internal struct Variant { #if DEBUG diff --git a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/BindableVectorToCollectionAdapter.cs b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/BindableVectorToCollectionAdapter.cs index 5574f3c251..e3c6a926d3 100644 --- a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/BindableVectorToCollectionAdapter.cs +++ b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/BindableVectorToCollectionAdapter.cs @@ -9,6 +9,7 @@ using System.Runtime; using System.Security; using System.Collections; using System.Collections.Generic; +using System.Diagnostics; using System.Diagnostics.Contracts; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; @@ -27,12 +28,11 @@ namespace System.Runtime.InteropServices.WindowsRuntime { private BindableVectorToCollectionAdapter() { - Contract.Assert(false, "This class is never instantiated"); + Debug.Assert(false, "This class is never instantiated"); } // int Count { get } [Pure] - [SecurityCritical] internal int Count() { IBindableVector _this = JitHelpers.UnsafeCast<IBindableVector>(this); @@ -47,7 +47,6 @@ namespace System.Runtime.InteropServices.WindowsRuntime // bool IsSynchronized { get } [Pure] - [SecurityCritical] internal bool IsSynchronized() { return false; @@ -55,7 +54,6 @@ namespace System.Runtime.InteropServices.WindowsRuntime // object SyncRoot { get } [Pure] - [SecurityCritical] internal object SyncRoot() { return this; @@ -63,11 +61,10 @@ namespace System.Runtime.InteropServices.WindowsRuntime // void CopyTo(Array array, int index) [Pure] - [SecurityCritical] internal void CopyTo(Array array, int arrayIndex) { if (array == null) - throw new ArgumentNullException("array"); + throw new ArgumentNullException(nameof(array)); // ICollection expects the destination array to be single-dimensional. if (array.Rank != 1) @@ -79,7 +76,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime int destLen = array.GetLength(0); if (arrayIndex < destLB) - throw new ArgumentOutOfRangeException("arrayIndex"); + throw new ArgumentOutOfRangeException(nameof(arrayIndex)); // Does the dimension in question have sufficient space to copy the expected number of entries? // We perform this check before valid index check to ensure the exception message is in sync with diff --git a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/BindableVectorToListAdapter.cs b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/BindableVectorToListAdapter.cs index 73ebf721ee..d6e50f5164 100644 --- a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/BindableVectorToListAdapter.cs +++ b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/BindableVectorToListAdapter.cs @@ -9,6 +9,7 @@ using System.Runtime; using System.Security; using System.Collections; using System.Collections.Generic; +using System.Diagnostics; using System.Diagnostics.Contracts; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; @@ -27,33 +28,30 @@ namespace System.Runtime.InteropServices.WindowsRuntime { private BindableVectorToListAdapter() { - Contract.Assert(false, "This class is never instantiated"); + Debug.Assert(false, "This class is never instantiated"); } // object this[int index] { get } - [SecurityCritical] internal object Indexer_Get(int index) { if (index < 0) - throw new ArgumentOutOfRangeException("index"); + throw new ArgumentOutOfRangeException(nameof(index)); IBindableVector _this = JitHelpers.UnsafeCast<IBindableVector>(this); return GetAt(_this, (uint)index); } // object this[int index] { set } - [SecurityCritical] internal void Indexer_Set(int index, object value) { if (index < 0) - throw new ArgumentOutOfRangeException("index"); + throw new ArgumentOutOfRangeException(nameof(index)); IBindableVector _this = JitHelpers.UnsafeCast<IBindableVector>(this); SetAt(_this, (uint)index, value); } // int Add(object value) - [SecurityCritical] internal int Add(object value) { IBindableVector _this = JitHelpers.UnsafeCast<IBindableVector>(this); @@ -69,7 +67,6 @@ namespace System.Runtime.InteropServices.WindowsRuntime } // bool Contains(object item) - [SecurityCritical] internal bool Contains(object item) { IBindableVector _this = JitHelpers.UnsafeCast<IBindableVector>(this); @@ -79,7 +76,6 @@ namespace System.Runtime.InteropServices.WindowsRuntime } // void Clear() - [SecurityCritical] internal void Clear() { IBindableVector _this = JitHelpers.UnsafeCast<IBindableVector>(this); @@ -88,7 +84,6 @@ namespace System.Runtime.InteropServices.WindowsRuntime // bool IsFixedSize { get } [Pure] - [SecurityCritical] internal bool IsFixedSize() { return false; @@ -96,14 +91,12 @@ namespace System.Runtime.InteropServices.WindowsRuntime // bool IsReadOnly { get } [Pure] - [SecurityCritical] internal bool IsReadOnly() { return false; } // int IndexOf(object item) - [SecurityCritical] internal int IndexOf(object item) { IBindableVector _this = JitHelpers.UnsafeCast<IBindableVector>(this); @@ -123,18 +116,16 @@ namespace System.Runtime.InteropServices.WindowsRuntime } // void Insert(int index, object item) - [SecurityCritical] internal void Insert(int index, object item) { if (index < 0) - throw new ArgumentOutOfRangeException("index"); + throw new ArgumentOutOfRangeException(nameof(index)); IBindableVector _this = JitHelpers.UnsafeCast<IBindableVector>(this); InsertAtHelper(_this, (uint)index, item); } // bool Remove(object item) - [SecurityCritical] internal void Remove(object item) { IBindableVector _this = JitHelpers.UnsafeCast<IBindableVector>(this); @@ -154,11 +145,10 @@ namespace System.Runtime.InteropServices.WindowsRuntime } // void RemoveAt(int index) - [SecurityCritical] internal void RemoveAt(int index) { if (index < 0) - throw new ArgumentOutOfRangeException("index"); + throw new ArgumentOutOfRangeException(nameof(index)); IBindableVector _this = JitHelpers.UnsafeCast<IBindableVector>(this); RemoveAtHelper(_this, (uint)index); @@ -178,7 +168,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime catch (Exception ex) { if (__HResults.E_BOUNDS == ex._HResult) - throw new ArgumentOutOfRangeException("index"); + throw new ArgumentOutOfRangeException(nameof(index)); throw; } @@ -196,7 +186,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime catch (Exception ex) { if (__HResults.E_BOUNDS == ex._HResult) - throw new ArgumentOutOfRangeException("index"); + throw new ArgumentOutOfRangeException(nameof(index)); throw; } @@ -214,7 +204,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime catch (Exception ex) { if (__HResults.E_BOUNDS == ex._HResult) - throw new ArgumentOutOfRangeException("index"); + throw new ArgumentOutOfRangeException(nameof(index)); throw; } @@ -232,7 +222,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime catch (Exception ex) { if (__HResults.E_BOUNDS == ex._HResult) - throw new ArgumentOutOfRangeException("index"); + throw new ArgumentOutOfRangeException(nameof(index)); throw; } diff --git a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/CLRIPropertyValueImpl.cs b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/CLRIPropertyValueImpl.cs index c88f13dd0b..702e0c9e52 100644 --- a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/CLRIPropertyValueImpl.cs +++ b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/CLRIPropertyValueImpl.cs @@ -184,7 +184,6 @@ namespace System.Runtime.InteropServices.WindowsRuntime } [Pure] - [SecuritySafeCritical] public Point GetPoint() { if (this.Type != PropertyType.Point) @@ -195,7 +194,6 @@ namespace System.Runtime.InteropServices.WindowsRuntime } [Pure] - [SecuritySafeCritical] public Size GetSize() { if (this.Type != PropertyType.Size) @@ -206,7 +204,6 @@ namespace System.Runtime.InteropServices.WindowsRuntime } [Pure] - [SecuritySafeCritical] public Rect GetRect() { if (this.Type != PropertyType.Rect) @@ -328,7 +325,6 @@ namespace System.Runtime.InteropServices.WindowsRuntime } [Pure] - [SecuritySafeCritical] public Point[] GetPointArray() { if (this.Type != PropertyType.PointArray) @@ -339,7 +335,6 @@ namespace System.Runtime.InteropServices.WindowsRuntime } [Pure] - [SecuritySafeCritical] public Size[] GetSizeArray() { if (this.Type != PropertyType.SizeArray) @@ -351,7 +346,6 @@ namespace System.Runtime.InteropServices.WindowsRuntime } [Pure] - [SecuritySafeCritical] public Rect[] GetRectArray() { if (this.Type != PropertyType.RectArray) @@ -505,7 +499,6 @@ namespace System.Runtime.InteropServices.WindowsRuntime // Unbox the data stored in the property value to a structurally equivilent type [Pure] - [SecurityCritical] private unsafe T Unbox<T>(Type expectedBoxedType) where T : struct { Contract.Requires(expectedBoxedType != null); Contract.Requires(Marshal.SizeOf(expectedBoxedType) == Marshal.SizeOf(typeof(T))); @@ -526,7 +519,6 @@ namespace System.Runtime.InteropServices.WindowsRuntime // Convert the array stored in the property value to a structurally equivilent array type [Pure] - [SecurityCritical] private unsafe T[] UnboxArray<T>(Type expectedArrayElementType) where T : struct { Contract.Requires(expectedArrayElementType != null); Contract.Requires(Marshal.SizeOf(expectedArrayElementType) == Marshal.SizeOf(typeof(T))); diff --git a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/CLRIReferenceImpl.cs b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/CLRIReferenceImpl.cs index e379d38cf3..9705b61148 100644 --- a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/CLRIReferenceImpl.cs +++ b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/CLRIReferenceImpl.cs @@ -6,6 +6,7 @@ using System; using System.Collections; +using System.Diagnostics; using System.Diagnostics.Contracts; using System.Reflection; using System.Security; @@ -55,7 +56,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime { Contract.Requires(wrapper != null); IReference<T> reference = (IReference<T>) wrapper; - Contract.Assert(reference != null, "CLRIReferenceImpl::UnboxHelper - QI'ed for IReference<"+typeof(T)+">, but that failed."); + Debug.Assert(reference != null, "CLRIReferenceImpl::UnboxHelper - QI'ed for IReference<"+typeof(T)+">, but that failed."); return reference.Value; } } @@ -216,7 +217,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime { Contract.Requires(wrapper != null); IReferenceArray<T> reference = (IReferenceArray<T>)wrapper; - Contract.Assert(reference != null, "CLRIReferenceArrayImpl::UnboxHelper - QI'ed for IReferenceArray<" + typeof(T) + ">, but that failed."); + Debug.Assert(reference != null, "CLRIReferenceArrayImpl::UnboxHelper - QI'ed for IReferenceArray<" + typeof(T) + ">, but that failed."); T[] marshaled = reference.Value; return marshaled; } @@ -229,7 +230,6 @@ namespace System.Runtime.InteropServices.WindowsRuntime internal static readonly Type s_rectType = Type.GetType("Windows.Foundation.Rect, " + AssemblyRef.SystemRuntimeWindowsRuntime); internal static readonly Type s_sizeType = Type.GetType("Windows.Foundation.Size, " + AssemblyRef.SystemRuntimeWindowsRuntime); - [SecuritySafeCritical] internal static Object CreateIReference(Object obj) { Contract.Requires(obj != null, "Null should not be boxed."); @@ -302,11 +302,10 @@ namespace System.Runtime.InteropServices.WindowsRuntime return Activator.CreateInstance(specificType, new Object[] { propType.Value, obj }); } - Contract.Assert(false, "We should not see non-WinRT type here"); + Debug.Assert(false, "We should not see non-WinRT type here"); return null; } - [SecuritySafeCritical] internal static Object CreateIReferenceArray(Array obj) { Contract.Requires(obj != null); @@ -315,7 +314,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime Type type = obj.GetType().GetElementType(); - Contract.Assert(obj.Rank == 1 && obj.GetLowerBound(0) == 0 && !type.IsArray); + Debug.Assert(obj.Rank == 1 && obj.GetLowerBound(0) == 0 && !type.IsArray); if (type == typeof(int)) return new CLRIReferenceArrayImpl<int>(PropertyType.Int32Array, (int[])obj); diff --git a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/ConstantSplittableMap.cs b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/ConstantSplittableMap.cs index af1381c366..a5abb4f23e 100644 --- a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/ConstantSplittableMap.cs +++ b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/ConstantSplittableMap.cs @@ -45,7 +45,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime internal ConstantSplittableMap(IReadOnlyDictionary<TKey, TValue> data) { if (data == null) - throw new ArgumentNullException("data"); + throw new ArgumentNullException(nameof(data)); Contract.EndContractBlock(); this.firstItemIndex = 0; @@ -56,7 +56,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime internal ConstantSplittableMap(IMapView<TKey, TValue> data) { if (data == null) - throw new ArgumentNullException("data"); + throw new ArgumentNullException(nameof(data)); if (((UInt32)Int32.MaxValue) < data.Size) { diff --git a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/CustomPropertyImpl.cs b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/CustomPropertyImpl.cs index 04fe1bf9b2..d575201bb9 100644 --- a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/CustomPropertyImpl.cs +++ b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/CustomPropertyImpl.cs @@ -7,6 +7,7 @@ using System; using System.Security; using System.Reflection; +using System.Diagnostics; using System.Diagnostics.Contracts; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; @@ -29,7 +30,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime public CustomPropertyImpl(PropertyInfo propertyInfo) { if (propertyInfo == null) - throw new ArgumentNullException("propertyInfo"); + throw new ArgumentNullException(nameof(propertyInfo)); m_property = propertyInfo; } @@ -88,7 +89,6 @@ namespace System.Runtime.InteropServices.WindowsRuntime InvokeInternal(target, new object[] { indexValue, value }, false); } - [SecuritySafeCritical] private object InvokeInternal(object target, object[] args, bool getValue) { // Forward to the right object if we are dealing with a proxy @@ -123,7 +123,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime // We can safely skip access check because this is only used in full trust scenarios. // And we have already verified that the property accessor is public. - Contract.Assert(AppDomain.CurrentDomain.PermissionSet.IsUnrestricted()); + Debug.Assert(AppDomain.CurrentDomain.PermissionSet.IsUnrestricted()); return rtMethod.UnsafeInvoke(target, BindingFlags.Default, null, args, null); } diff --git a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/DictionaryKeyCollection.cs b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/DictionaryKeyCollection.cs index c1586ee9ce..c33e002e0e 100644 --- a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/DictionaryKeyCollection.cs +++ b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/DictionaryKeyCollection.cs @@ -18,7 +18,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime public DictionaryKeyCollection(IDictionary<TKey, TValue> dictionary) { if (dictionary == null) - throw new ArgumentNullException("dictionary"); + throw new ArgumentNullException(nameof(dictionary)); this.dictionary = dictionary; } @@ -26,9 +26,9 @@ namespace System.Runtime.InteropServices.WindowsRuntime public void CopyTo(TKey[] array, int index) { if (array == null) - throw new ArgumentNullException("array"); + throw new ArgumentNullException(nameof(array)); if (index < 0) - throw new ArgumentOutOfRangeException("index"); + throw new ArgumentOutOfRangeException(nameof(index)); if (array.Length <= index && this.Count > 0) throw new ArgumentException(Environment.GetResourceString("Arg_IndexOutOfRangeException")); if (array.Length - index < dictionary.Count) @@ -90,7 +90,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime public DictionaryKeyEnumerator(IDictionary<TKey, TValue> dictionary) { if (dictionary == null) - throw new ArgumentNullException("dictionary"); + throw new ArgumentNullException(nameof(dictionary)); this.dictionary = dictionary; this.enumeration = dictionary.GetEnumerator(); diff --git a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/DictionaryToMapAdapter.cs b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/DictionaryToMapAdapter.cs index fa021b7f3d..24e5777768 100644 --- a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/DictionaryToMapAdapter.cs +++ b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/DictionaryToMapAdapter.cs @@ -10,6 +10,7 @@ using System.Reflection; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; +using System.Diagnostics; using System.Diagnostics.Contracts; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; @@ -28,11 +29,10 @@ namespace System.Runtime.InteropServices.WindowsRuntime { private DictionaryToMapAdapter() { - Contract.Assert(false, "This class is never instantiated"); + Debug.Assert(false, "This class is never instantiated"); } // V Lookup(K key) - [SecurityCritical] internal V Lookup<K, V>(K key) { IDictionary<K, V> _this = JitHelpers.UnsafeCast<IDictionary<K, V>>(this); @@ -50,7 +50,6 @@ namespace System.Runtime.InteropServices.WindowsRuntime } // uint Size { get } - [SecurityCritical] internal uint Size<K, V>() { IDictionary<K, V> _this = JitHelpers.UnsafeCast<IDictionary<K, V>>(this); @@ -58,7 +57,6 @@ namespace System.Runtime.InteropServices.WindowsRuntime } // bool HasKey(K key) - [SecurityCritical] internal bool HasKey<K, V>(K key) { IDictionary<K, V> _this = JitHelpers.UnsafeCast<IDictionary<K, V>>(this); @@ -66,11 +64,10 @@ namespace System.Runtime.InteropServices.WindowsRuntime } // IMapView<K, V> GetView() - [SecurityCritical] internal IReadOnlyDictionary<K, V> GetView<K, V>() { IDictionary<K, V> _this = JitHelpers.UnsafeCast<IDictionary<K, V>>(this); - Contract.Assert(_this != null); + Debug.Assert(_this != null); // Note: This dictionary is not really read-only - you could QI for a modifiable // dictionary. We gain some perf by doing this. We believe this is acceptable. @@ -83,7 +80,6 @@ namespace System.Runtime.InteropServices.WindowsRuntime } // bool Insert(K key, V value) - [SecurityCritical] internal bool Insert<K, V>(K key, V value) { IDictionary<K, V> _this = JitHelpers.UnsafeCast<IDictionary<K, V>>(this); @@ -93,7 +89,6 @@ namespace System.Runtime.InteropServices.WindowsRuntime } // void Remove(K key) - [SecurityCritical] internal void Remove<K, V>(K key) { IDictionary<K, V> _this = JitHelpers.UnsafeCast<IDictionary<K, V>>(this); @@ -108,7 +103,6 @@ namespace System.Runtime.InteropServices.WindowsRuntime } // void Clear() - [SecurityCritical] internal void Clear<K, V>() { IDictionary<K, V> _this = JitHelpers.UnsafeCast<IDictionary<K, V>>(this); diff --git a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/DictionaryValueCollection.cs b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/DictionaryValueCollection.cs index 03e897a917..fcc7755d67 100644 --- a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/DictionaryValueCollection.cs +++ b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/DictionaryValueCollection.cs @@ -21,7 +21,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime { public DictionaryValueCollection(IDictionary<TKey, TValue> dictionary) { if (dictionary == null) - throw new ArgumentNullException("dictionary"); + throw new ArgumentNullException(nameof(dictionary)); this.dictionary = dictionary; } @@ -29,9 +29,9 @@ namespace System.Runtime.InteropServices.WindowsRuntime { public void CopyTo(TValue[] array, int index) { if (array == null) - throw new ArgumentNullException("array"); + throw new ArgumentNullException(nameof(array)); if (index < 0) - throw new ArgumentOutOfRangeException("index"); + throw new ArgumentOutOfRangeException(nameof(index)); if (array.Length <= index && this.Count > 0) throw new ArgumentException(Environment.GetResourceString("Arg_IndexOutOfRangeException")); if (array.Length - index < dictionary.Count) @@ -97,7 +97,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime { public DictionaryValueEnumerator(IDictionary<TKey, TValue> dictionary) { if (dictionary == null) - throw new ArgumentNullException("dictionary"); + throw new ArgumentNullException(nameof(dictionary)); this.dictionary = dictionary; this.enumeration = dictionary.GetEnumerator(); diff --git a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/EnumeratorToIteratorAdapter.cs b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/EnumeratorToIteratorAdapter.cs index 7329d31ae8..3f9d516162 100644 --- a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/EnumeratorToIteratorAdapter.cs +++ b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/EnumeratorToIteratorAdapter.cs @@ -7,6 +7,7 @@ using System; using System.Collections; using System.Collections.Generic; +using System.Diagnostics; using System.Diagnostics.Contracts; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; @@ -25,11 +26,10 @@ namespace System.Runtime.InteropServices.WindowsRuntime { private EnumerableToIterableAdapter() { - Contract.Assert(false, "This class is never instantiated"); + Debug.Assert(false, "This class is never instantiated"); } // This method is invoked when First is called on a managed implementation of IIterable<T>. - [System.Security.SecurityCritical] internal IIterator<T> First_Stub<T>() { IEnumerable<T> _this = JitHelpers.UnsafeCast<IEnumerable<T>>(this); @@ -41,7 +41,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime { private EnumerableToBindableIterableAdapter() { - Contract.Assert(false, "This class is never instantiated"); + Debug.Assert(false, "This class is never instantiated"); } internal sealed class NonGenericToGenericEnumerator : IEnumerator<object> @@ -58,7 +58,6 @@ namespace System.Runtime.InteropServices.WindowsRuntime } // This method is invoked when First is called on a managed implementation of IBindableIterable. - [System.Security.SecurityCritical] internal IBindableIterator First_Stub() { IEnumerable _this = JitHelpers.UnsafeCast<IEnumerable>(this); diff --git a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/IClosable.cs b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/IClosable.cs index 847147ade8..4c6169a4e8 100644 --- a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/IClosable.cs +++ b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/IClosable.cs @@ -7,6 +7,7 @@ using System; using System.Security; using System.Collections; +using System.Diagnostics; using System.Diagnostics.Contracts; using System.Runtime.CompilerServices; @@ -27,10 +28,9 @@ namespace System.Runtime.InteropServices.WindowsRuntime { private IDisposableToIClosableAdapter() { - Contract.Assert(false, "This class is never instantiated"); + Debug.Assert(false, "This class is never instantiated"); } - [SecurityCritical] public void Close() { IDisposable _this = JitHelpers.UnsafeCast<IDisposable>(this); @@ -39,15 +39,13 @@ namespace System.Runtime.InteropServices.WindowsRuntime } // Adapter class which converts IDisposable.Dispose calls into IClosable.Close - [SecurityCritical] internal sealed class IClosableToIDisposableAdapter { private IClosableToIDisposableAdapter() { - Contract.Assert(false, "This class is never instantiated"); + Debug.Assert(false, "This class is never instantiated"); } - [SecurityCritical] private void Dispose() { IClosable _this = JitHelpers.UnsafeCast<IClosable>(this); diff --git a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/ICustomPropertyProvider.cs b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/ICustomPropertyProvider.cs index 143a33e4c7..3bbde35a3c 100644 --- a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/ICustomPropertyProvider.cs +++ b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/ICustomPropertyProvider.cs @@ -50,7 +50,6 @@ namespace System.Runtime.InteropServices.WindowsRuntime // Creates a ICustomProperty implementation for Jupiter // Called from ICustomPropertyProvider_GetIndexedProperty from within runtime // - [System.Security.SecurityCritical] static internal unsafe ICustomProperty CreateIndexedProperty(object target, string propertyName, TypeNameNative *pIndexedParamType) { Contract.Requires(target != null); @@ -87,7 +86,6 @@ namespace System.Runtime.InteropServices.WindowsRuntime return new CustomPropertyImpl(propertyInfo); } - [System.Security.SecurityCritical] static internal unsafe void GetType(object target, TypeNameNative *pIndexedParamType) { IGetProxyTarget proxy = target as IGetProxyTarget; @@ -207,7 +205,6 @@ namespace System.Runtime.InteropServices.WindowsRuntime // // ICustomQueryInterface methods // - [System.Security.SecurityCritical] public CustomQueryInterfaceResult GetInterface([In]ref Guid iid, out IntPtr ppv) { ppv = IntPtr.Zero; @@ -441,7 +438,6 @@ namespace System.Runtime.InteropServices.WindowsRuntime } } - [SecuritySafeCritical] private IBindableVector GetIBindableVectorNoThrow() { if ((_flags & InterfaceForwardingSupport.IBindableVector) != 0) @@ -450,7 +446,6 @@ namespace System.Runtime.InteropServices.WindowsRuntime return null; } - [SecuritySafeCritical] private IVector_Raw<T1> GetVectorOfT() { if ((_flags & InterfaceForwardingSupport.IVector) != 0) @@ -517,7 +512,6 @@ namespace System.Runtime.InteropServices.WindowsRuntime public bool MoveNext() { return _iterator.MoveNext(); } } - [SecuritySafeCritical] private IBindableVectorView GetIBindableVectorViewNoThrow() { if ((_flags & InterfaceForwardingSupport.IBindableVectorView) != 0) @@ -526,7 +520,6 @@ namespace System.Runtime.InteropServices.WindowsRuntime return null; } - [SecuritySafeCritical] private IVectorView<T2> GetVectorViewOfT() { if ((_flags & InterfaceForwardingSupport.IVectorView) != 0) diff --git a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/IMapViewToIReadOnlyDictionaryAdapter.cs b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/IMapViewToIReadOnlyDictionaryAdapter.cs index 3600a3ae70..a7424da3fb 100644 --- a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/IMapViewToIReadOnlyDictionaryAdapter.cs +++ b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/IMapViewToIReadOnlyDictionaryAdapter.cs @@ -28,15 +28,14 @@ namespace System.Runtime.InteropServices.WindowsRuntime { private IMapViewToIReadOnlyDictionaryAdapter() { - Contract.Assert(false, "This class is never instantiated"); + Debug.Assert(false, "This class is never instantiated"); } // V this[K key] { get } - [SecurityCritical] internal V Indexer_Get<K, V>(K key) { if (key == null) - throw new ArgumentNullException("key"); + throw new ArgumentNullException(nameof(key)); Contract.EndContractBlock(); IMapView<K, V> _this = JitHelpers.UnsafeCast<IMapView<K, V>>(this); @@ -44,7 +43,6 @@ namespace System.Runtime.InteropServices.WindowsRuntime } // IEnumerable<K> Keys { get } - [SecurityCritical] internal IEnumerable<K> Keys<K, V>() { IMapView<K, V> _this = JitHelpers.UnsafeCast<IMapView<K, V>>(this); @@ -53,7 +51,6 @@ namespace System.Runtime.InteropServices.WindowsRuntime } // IEnumerable<V> Values { get } - [SecurityCritical] internal IEnumerable<V> Values<K, V>() { IMapView<K, V> _this = JitHelpers.UnsafeCast<IMapView<K, V>>(this); @@ -63,22 +60,20 @@ namespace System.Runtime.InteropServices.WindowsRuntime // bool ContainsKey(K key) [Pure] - [SecurityCritical] internal bool ContainsKey<K, V>(K key) { if (key == null) - throw new ArgumentNullException("key"); + throw new ArgumentNullException(nameof(key)); IMapView<K, V> _this = JitHelpers.UnsafeCast<IMapView<K, V>>(this); return _this.HasKey(key); } // bool TryGetValue(TKey key, out TValue value) - [SecurityCritical] internal bool TryGetValue<K, V>(K key, out V value) { if (key == null) - throw new ArgumentNullException("key"); + throw new ArgumentNullException(nameof(key)); IMapView<K, V> _this = JitHelpers.UnsafeCast<IMapView<K, V>>(this); @@ -137,7 +132,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime public ReadOnlyDictionaryKeyCollection(IReadOnlyDictionary<TKey, TValue> dictionary) { if (dictionary == null) - throw new ArgumentNullException("dictionary"); + throw new ArgumentNullException(nameof(dictionary)); this.dictionary = dictionary; } @@ -146,9 +141,9 @@ namespace System.Runtime.InteropServices.WindowsRuntime public void CopyTo(TKey[] array, int index) { if (array == null) - throw new ArgumentNullException("array"); + throw new ArgumentNullException(nameof(array)); if (index < 0) - throw new ArgumentOutOfRangeException("index"); + throw new ArgumentOutOfRangeException(nameof(index)); if (array.Length <= index && this.Count > 0) throw new ArgumentException(Environment.GetResourceString("Arg_IndexOutOfRangeException")); if (array.Length - index < dictionary.Count) @@ -192,7 +187,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime public ReadOnlyDictionaryKeyEnumerator(IReadOnlyDictionary<TKey, TValue> dictionary) { if (dictionary == null) - throw new ArgumentNullException("dictionary"); + throw new ArgumentNullException(nameof(dictionary)); this.dictionary = dictionary; this.enumeration = dictionary.GetEnumerator(); @@ -232,7 +227,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime public ReadOnlyDictionaryValueCollection(IReadOnlyDictionary<TKey, TValue> dictionary) { if (dictionary == null) - throw new ArgumentNullException("dictionary"); + throw new ArgumentNullException(nameof(dictionary)); this.dictionary = dictionary; } @@ -241,9 +236,9 @@ namespace System.Runtime.InteropServices.WindowsRuntime public void CopyTo(TValue[] array, int index) { if (array == null) - throw new ArgumentNullException("array"); + throw new ArgumentNullException(nameof(array)); if (index < 0) - throw new ArgumentOutOfRangeException("index"); + throw new ArgumentOutOfRangeException(nameof(index)); if (array.Length <= index && this.Count > 0) throw new ArgumentException(Environment.GetResourceString("Arg_IndexOutOfRangeException")); if (array.Length - index < dictionary.Count) @@ -291,7 +286,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime public ReadOnlyDictionaryValueEnumerator(IReadOnlyDictionary<TKey, TValue> dictionary) { if (dictionary == null) - throw new ArgumentNullException("dictionary"); + throw new ArgumentNullException(nameof(dictionary)); this.dictionary = dictionary; this.enumeration = dictionary.GetEnumerator(); diff --git a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/IReadOnlyDictionaryToIMapViewAdapter.cs b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/IReadOnlyDictionaryToIMapViewAdapter.cs index d57f8f1f46..b185b41be0 100644 --- a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/IReadOnlyDictionaryToIMapViewAdapter.cs +++ b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/IReadOnlyDictionaryToIMapViewAdapter.cs @@ -28,11 +28,10 @@ namespace System.Runtime.InteropServices.WindowsRuntime { private IReadOnlyDictionaryToIMapViewAdapter() { - Contract.Assert(false, "This class is never instantiated"); + Debug.Assert(false, "This class is never instantiated"); } // V Lookup(K key) - [SecurityCritical] internal V Lookup<K, V>(K key) { IReadOnlyDictionary<K, V> _this = JitHelpers.UnsafeCast<IReadOnlyDictionary<K, V>>(this); @@ -50,7 +49,6 @@ namespace System.Runtime.InteropServices.WindowsRuntime } // uint Size { get } - [SecurityCritical] internal uint Size<K, V>() { IReadOnlyDictionary<K, V> _this = JitHelpers.UnsafeCast<IReadOnlyDictionary<K, V>>(this); @@ -58,7 +56,6 @@ namespace System.Runtime.InteropServices.WindowsRuntime } // bool HasKey(K key) - [SecurityCritical] internal bool HasKey<K, V>(K key) { IReadOnlyDictionary<K, V> _this = JitHelpers.UnsafeCast<IReadOnlyDictionary<K, V>>(this); @@ -66,7 +63,6 @@ namespace System.Runtime.InteropServices.WindowsRuntime } // void Split(out IMapView<K, V> first, out IMapView<K, V> second) - [SecurityCritical] internal void Split<K, V>(out IMapView<K, V> first, out IMapView<K, V> second) { IReadOnlyDictionary<K, V> _this = JitHelpers.UnsafeCast<IReadOnlyDictionary<K, V>>(this); diff --git a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/IReadOnlyListToIVectorViewAdapter.cs b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/IReadOnlyListToIVectorViewAdapter.cs index 95780bcb13..431d16256e 100644 --- a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/IReadOnlyListToIVectorViewAdapter.cs +++ b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/IReadOnlyListToIVectorViewAdapter.cs @@ -28,11 +28,10 @@ namespace System.Runtime.InteropServices.WindowsRuntime { private IReadOnlyListToIVectorViewAdapter() { - Contract.Assert(false, "This class is never instantiated"); + Debug.Assert(false, "This class is never instantiated"); } // T GetAt(uint index) - [SecurityCritical] internal T GetAt<T>(uint index) { IReadOnlyList<T> _this = JitHelpers.UnsafeCast<IReadOnlyList<T>>(this); @@ -50,7 +49,6 @@ namespace System.Runtime.InteropServices.WindowsRuntime } // uint Size { get } - [SecurityCritical] internal uint Size<T>() { IReadOnlyList<T> _this = JitHelpers.UnsafeCast<IReadOnlyList<T>>(this); @@ -58,7 +56,6 @@ namespace System.Runtime.InteropServices.WindowsRuntime } // bool IndexOf(T value, out uint index) - [SecurityCritical] internal bool IndexOf<T>(T value, out uint index) { IReadOnlyList<T> _this = JitHelpers.UnsafeCast<IReadOnlyList<T>>(this); @@ -85,7 +82,6 @@ namespace System.Runtime.InteropServices.WindowsRuntime } // uint GetMany(uint startIndex, T[] items) - [SecurityCritical] internal uint GetMany<T>(uint startIndex, T[] items) { IReadOnlyList<T> _this = JitHelpers.UnsafeCast<IReadOnlyList<T>>(this); @@ -130,7 +126,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime // that Size > Int32.MaxValue: if (((uint)Int32.MaxValue) <= index || index >= (uint)listCapacity) { - Exception e = new ArgumentOutOfRangeException("index", Environment.GetResourceString("ArgumentOutOfRange_IndexLargerThanMaxValue")); + Exception e = new ArgumentOutOfRangeException(nameof(index), Environment.GetResourceString("ArgumentOutOfRange_IndexLargerThanMaxValue")); e.SetErrorCode(__HResults.E_BOUNDS); throw e; } diff --git a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/IRestrictedErrorInfo.cs b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/IRestrictedErrorInfo.cs index 48bcc4f618..9de5e3f36d 100644 --- a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/IRestrictedErrorInfo.cs +++ b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/IRestrictedErrorInfo.cs @@ -8,9 +8,7 @@ using System; namespace System.Runtime.InteropServices.WindowsRuntime { -#if FEATURE_CORECLR [System.Runtime.CompilerServices.FriendAccessAllowed] -#endif [ComImport] [Guid("82BA7092-4C88-427D-A7BC-16DD93FEB67E")] [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] diff --git a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/IVectorViewToIReadOnlyListAdapter.cs b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/IVectorViewToIReadOnlyListAdapter.cs index 72d6fa8cc3..37f21307dc 100644 --- a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/IVectorViewToIReadOnlyListAdapter.cs +++ b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/IVectorViewToIReadOnlyListAdapter.cs @@ -30,15 +30,14 @@ namespace System.Runtime.InteropServices.WindowsRuntime { private IVectorViewToIReadOnlyListAdapter() { - Contract.Assert(false, "This class is never instantiated"); + Debug.Assert(false, "This class is never instantiated"); } // T this[int index] { get } - [SecurityCritical] internal T Indexer_Get<T>(int index) { if (index < 0) - throw new ArgumentOutOfRangeException("index"); + throw new ArgumentOutOfRangeException(nameof(index)); IVectorView<T> _this = JitHelpers.UnsafeCast<IVectorView<T>>(this); @@ -52,14 +51,13 @@ namespace System.Runtime.InteropServices.WindowsRuntime catch (Exception ex) { if (__HResults.E_BOUNDS == ex._HResult) - throw new ArgumentOutOfRangeException("index"); + throw new ArgumentOutOfRangeException(nameof(index)); throw; } } // T this[int index] { get } - [SecurityCritical] internal T Indexer_Get_Variance<T>(int index) where T : class { bool fUseString; diff --git a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/IteratorToEnumeratorAdapter.cs b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/IteratorToEnumeratorAdapter.cs index f1b799aa84..e219a86769 100644 --- a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/IteratorToEnumeratorAdapter.cs +++ b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/IteratorToEnumeratorAdapter.cs @@ -7,6 +7,7 @@ using System; using System.Collections; using System.Collections.Generic; +using System.Diagnostics; using System.Diagnostics.Contracts; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; @@ -28,11 +29,10 @@ namespace System.Runtime.InteropServices.WindowsRuntime { private IterableToEnumerableAdapter() { - Contract.Assert(false, "This class is never instantiated"); + Debug.Assert(false, "This class is never instantiated"); } // This method is invoked when GetEnumerator is called on a WinRT-backed implementation of IEnumerable<T>. - [SecurityCritical] internal IEnumerator<T> GetEnumerator_Stub<T>() { IIterable<T> _this = JitHelpers.UnsafeCast<IIterable<T>>(this); @@ -43,7 +43,6 @@ namespace System.Runtime.InteropServices.WindowsRuntime // and it is possible that the implementation supports IEnumerable<Type>/IEnumerable<string>/IEnumerable<Exception>/ // IEnumerable<array>/IEnumerable<delegate> rather than IEnumerable<T> because T is assignable from Type/string/ // Exception/array/delegate via co-variance. - [SecurityCritical] internal IEnumerator<T> GetEnumerator_Variance_Stub<T>() where T : class { bool fUseString; @@ -70,7 +69,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime { private BindableIterableToEnumerableAdapter() { - Contract.Assert(false, "This class is never instantiated"); + Debug.Assert(false, "This class is never instantiated"); } private sealed class NonGenericToGenericIterator : IIterator<object> @@ -87,7 +86,6 @@ namespace System.Runtime.InteropServices.WindowsRuntime } // This method is invoked when GetEnumerator is called on a WinRT-backed implementation of IEnumerable. - [SecurityCritical] internal IEnumerator GetEnumerator_Stub() { IBindableIterable _this = JitHelpers.UnsafeCast<IBindableIterable>(this); @@ -123,10 +121,10 @@ namespace System.Runtime.InteropServices.WindowsRuntime { // The enumerator has not been advanced to the first element yet. if (!m_isInitialized) - ThrowHelper.ThrowInvalidOperationException(ExceptionResource.InvalidOperation_EnumNotStarted); + ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumNotStarted(); // The enumerator has reached the end of the collection if (!m_hadCurrent) - ThrowHelper.ThrowInvalidOperationException(ExceptionResource.InvalidOperation_EnumEnded); + ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumEnded(); return m_current; } } @@ -137,15 +135,14 @@ namespace System.Runtime.InteropServices.WindowsRuntime { // The enumerator has not been advanced to the first element yet. if (!m_isInitialized) - ThrowHelper.ThrowInvalidOperationException(ExceptionResource.InvalidOperation_EnumNotStarted); + ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumNotStarted(); // The enumerator has reached the end of the collection if (!m_hadCurrent) - ThrowHelper.ThrowInvalidOperationException(ExceptionResource.InvalidOperation_EnumEnded); + ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumEnded(); return m_current; } } - [SecuritySafeCritical] public bool MoveNext() { // If we've passed the end of the iteration, IEnumerable<T> should return false, while @@ -187,7 +184,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime // Translate E_CHANGED_STATE into an InvalidOperationException for an updated enumeration if (Marshal.GetHRForException(e) == __HResults.E_CHANGED_STATE) { - ThrowHelper.ThrowInvalidOperationException(ExceptionResource.InvalidOperation_EnumFailedVersion); + ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumFailedVersion(); } else { diff --git a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/ListToBindableVectorAdapter.cs b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/ListToBindableVectorAdapter.cs index 35dc495d3f..b9fe11557d 100644 --- a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/ListToBindableVectorAdapter.cs +++ b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/ListToBindableVectorAdapter.cs @@ -10,6 +10,7 @@ using System.Reflection; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; +using System.Diagnostics; using System.Diagnostics.Contracts; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; @@ -28,11 +29,10 @@ namespace System.Runtime.InteropServices.WindowsRuntime { private ListToBindableVectorAdapter() { - Contract.Assert(false, "This class is never instantiated"); + Debug.Assert(false, "This class is never instantiated"); } // object GetAt(uint index) - [SecurityCritical] internal object GetAt(uint index) { IList _this = JitHelpers.UnsafeCast<IList>(this); @@ -49,7 +49,6 @@ namespace System.Runtime.InteropServices.WindowsRuntime } // uint Size { get } - [SecurityCritical] internal uint Size() { IList _this = JitHelpers.UnsafeCast<IList>(this); @@ -57,7 +56,6 @@ namespace System.Runtime.InteropServices.WindowsRuntime } // IBindableVectorView GetView() - [SecurityCritical] internal IBindableVectorView GetView() { IList _this = JitHelpers.UnsafeCast<IList>(this); @@ -65,7 +63,6 @@ namespace System.Runtime.InteropServices.WindowsRuntime } // bool IndexOf(object value, out uint index) - [SecurityCritical] internal bool IndexOf(object value, out uint index) { IList _this = JitHelpers.UnsafeCast<IList>(this); @@ -82,7 +79,6 @@ namespace System.Runtime.InteropServices.WindowsRuntime } // void SetAt(uint index, object value) - [SecurityCritical] internal void SetAt(uint index, object value) { IList _this = JitHelpers.UnsafeCast<IList>(this); @@ -99,7 +95,6 @@ namespace System.Runtime.InteropServices.WindowsRuntime } // void InsertAt(uint index, object value) - [SecurityCritical] internal void InsertAt(uint index, object value) { IList _this = JitHelpers.UnsafeCast<IList>(this); @@ -121,7 +116,6 @@ namespace System.Runtime.InteropServices.WindowsRuntime } // void RemoveAt(uint index) - [SecurityCritical] internal void RemoveAt(uint index) { IList _this = JitHelpers.UnsafeCast<IList>(this); @@ -140,7 +134,6 @@ namespace System.Runtime.InteropServices.WindowsRuntime } // void Append(object value) - [SecurityCritical] internal void Append(object value) { IList _this = JitHelpers.UnsafeCast<IList>(this); @@ -148,7 +141,6 @@ namespace System.Runtime.InteropServices.WindowsRuntime } // void RemoveAtEnd() - [SecurityCritical] internal void RemoveAtEnd() { IList _this = JitHelpers.UnsafeCast<IList>(this); @@ -164,7 +156,6 @@ namespace System.Runtime.InteropServices.WindowsRuntime } // void Clear() - [SecurityCritical] internal void Clear() { IList _this = JitHelpers.UnsafeCast<IList>(this); @@ -179,7 +170,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime // that Size > Int32.MaxValue: if (((uint)Int32.MaxValue) <= index || index >= (uint)listCapacity) { - Exception e = new ArgumentOutOfRangeException("index", Environment.GetResourceString("ArgumentOutOfRange_IndexLargerThanMaxValue")); + Exception e = new ArgumentOutOfRangeException(nameof(index), Environment.GetResourceString("ArgumentOutOfRange_IndexLargerThanMaxValue")); e.SetErrorCode(__HResults.E_BOUNDS); throw e; } diff --git a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/ListToBindableVectorViewAdapter.cs b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/ListToBindableVectorViewAdapter.cs index f760576aaa..2e2ea9b876 100644 --- a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/ListToBindableVectorViewAdapter.cs +++ b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/ListToBindableVectorViewAdapter.cs @@ -25,7 +25,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime internal ListToBindableVectorViewAdapter(IList list) { if (list == null) - throw new ArgumentNullException("list"); + throw new ArgumentNullException(nameof(list)); Contract.EndContractBlock(); @@ -38,7 +38,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime // that Size > Int32.MaxValue: if (((uint)Int32.MaxValue) <= index || index >= (uint)listCapacity) { - Exception e = new ArgumentOutOfRangeException("index", Environment.GetResourceString("ArgumentOutOfRange_IndexLargerThanMaxValue")); + Exception e = new ArgumentOutOfRangeException(nameof(index), Environment.GetResourceString("ArgumentOutOfRange_IndexLargerThanMaxValue")); e.SetErrorCode(__HResults.E_BOUNDS); throw e; } diff --git a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/ListToVectorAdapter.cs b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/ListToVectorAdapter.cs index 77f3a9464f..b73f4d7a99 100644 --- a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/ListToVectorAdapter.cs +++ b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/ListToVectorAdapter.cs @@ -10,6 +10,7 @@ using System.Reflection; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; +using System.Diagnostics; using System.Diagnostics.Contracts; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; @@ -28,11 +29,10 @@ namespace System.Runtime.InteropServices.WindowsRuntime { private ListToVectorAdapter() { - Contract.Assert(false, "This class is never instantiated"); + Debug.Assert(false, "This class is never instantiated"); } // T GetAt(uint index) - [SecurityCritical] internal T GetAt<T>(uint index) { IList<T> _this = JitHelpers.UnsafeCast<IList<T>>(this); @@ -49,7 +49,6 @@ namespace System.Runtime.InteropServices.WindowsRuntime } // uint Size { get } - [SecurityCritical] internal uint Size<T>() { IList<T> _this = JitHelpers.UnsafeCast<IList<T>>(this); @@ -57,11 +56,10 @@ namespace System.Runtime.InteropServices.WindowsRuntime } // IVectorView<T> GetView() - [SecurityCritical] internal IReadOnlyList<T> GetView<T>() { IList<T> _this = JitHelpers.UnsafeCast<IList<T>>(this); - Contract.Assert(_this != null); + Debug.Assert(_this != null); // Note: This list is not really read-only - you could QI for a modifiable // list. We gain some perf by doing this. We believe this is acceptable. @@ -74,7 +72,6 @@ namespace System.Runtime.InteropServices.WindowsRuntime } // bool IndexOf(T value, out uint index) - [SecurityCritical] internal bool IndexOf<T>(T value, out uint index) { IList<T> _this = JitHelpers.UnsafeCast<IList<T>>(this); @@ -91,7 +88,6 @@ namespace System.Runtime.InteropServices.WindowsRuntime } // void SetAt(uint index, T value) - [SecurityCritical] internal void SetAt<T>(uint index, T value) { IList<T> _this = JitHelpers.UnsafeCast<IList<T>>(this); @@ -108,7 +104,6 @@ namespace System.Runtime.InteropServices.WindowsRuntime } // void InsertAt(uint index, T value) - [SecurityCritical] internal void InsertAt<T>(uint index, T value) { IList<T> _this = JitHelpers.UnsafeCast<IList<T>>(this); @@ -130,7 +125,6 @@ namespace System.Runtime.InteropServices.WindowsRuntime } // void RemoveAt(uint index) - [SecurityCritical] internal void RemoveAt<T>(uint index) { IList<T> _this = JitHelpers.UnsafeCast<IList<T>>(this); @@ -149,7 +143,6 @@ namespace System.Runtime.InteropServices.WindowsRuntime } // void Append(T value) - [SecurityCritical] internal void Append<T>(T value) { IList<T> _this = JitHelpers.UnsafeCast<IList<T>>(this); @@ -157,7 +150,6 @@ namespace System.Runtime.InteropServices.WindowsRuntime } // void RemoveAtEnd() - [SecurityCritical] internal void RemoveAtEnd<T>() { IList<T> _this = JitHelpers.UnsafeCast<IList<T>>(this); @@ -173,7 +165,6 @@ namespace System.Runtime.InteropServices.WindowsRuntime } // void Clear() - [SecurityCritical] internal void Clear<T>() { IList<T> _this = JitHelpers.UnsafeCast<IList<T>>(this); @@ -181,7 +172,6 @@ namespace System.Runtime.InteropServices.WindowsRuntime } // uint GetMany(uint startIndex, T[] items) - [SecurityCritical] internal uint GetMany<T>(uint startIndex, T[] items) { IList<T> _this = JitHelpers.UnsafeCast<IList<T>>(this); @@ -189,7 +179,6 @@ namespace System.Runtime.InteropServices.WindowsRuntime } // void ReplaceAll(T[] items) - [SecurityCritical] internal void ReplaceAll<T>(T[] items) { IList<T> _this = JitHelpers.UnsafeCast<IList<T>>(this); @@ -212,7 +201,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime // that Size > Int32.MaxValue: if (((uint)Int32.MaxValue) <= index || index >= (uint)listCapacity) { - Exception e = new ArgumentOutOfRangeException("index", Environment.GetResourceString("ArgumentOutOfRange_IndexLargerThanMaxValue")); + Exception e = new ArgumentOutOfRangeException(nameof(index), Environment.GetResourceString("ArgumentOutOfRange_IndexLargerThanMaxValue")); e.SetErrorCode(__HResults.E_BOUNDS); throw e; } diff --git a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/ManagedActivationFactory.cs b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/ManagedActivationFactory.cs index 3e93428d26..2d08cab0ee 100644 --- a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/ManagedActivationFactory.cs +++ b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/ManagedActivationFactory.cs @@ -33,16 +33,15 @@ namespace System.Runtime.InteropServices.WindowsRuntime { private Type m_type; - [SecurityCritical] internal ManagedActivationFactory(Type type) { if (type == null) - throw new ArgumentNullException("type"); + throw new ArgumentNullException(nameof(type)); // Check whether the type is "exported to WinRT", i.e. it is declared in a managed .winmd and is decorated // with at least one ActivatableAttribute or StaticAttribute. if (!(type is RuntimeType) || !type.IsExportedToWindowsRuntime) - throw new ArgumentException(Environment.GetResourceString("Argument_TypeNotActivatableViaWindowsRuntime", type), "type"); + throw new ArgumentException(Environment.GetResourceString("Argument_TypeNotActivatableViaWindowsRuntime", type), nameof(type)); m_type = type; } diff --git a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/MapToCollectionAdapter.cs b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/MapToCollectionAdapter.cs index 395bef93d5..f11260eb4a 100644 --- a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/MapToCollectionAdapter.cs +++ b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/MapToCollectionAdapter.cs @@ -8,6 +8,7 @@ using System; using System.Security; using System.Collections; using System.Collections.Generic; +using System.Diagnostics; using System.Diagnostics.Contracts; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; @@ -29,12 +30,11 @@ namespace System.Runtime.InteropServices.WindowsRuntime { private MapToCollectionAdapter() { - Contract.Assert(false, "This class is never instantiated"); + Debug.Assert(false, "This class is never instantiated"); } // int Count { get } [Pure] - [SecurityCritical] internal int Count<K, V>() { object _this = JitHelpers.UnsafeCast<object>(this); @@ -66,14 +66,12 @@ namespace System.Runtime.InteropServices.WindowsRuntime } // bool IsReadOnly { get } - [SecurityCritical] internal bool IsReadOnly<K, V>() { return false; } // void Add(T item) - [SecurityCritical] internal void Add<K, V>(KeyValuePair<K, V> item) { object _this = JitHelpers.UnsafeCast<object>(this); @@ -91,7 +89,6 @@ namespace System.Runtime.InteropServices.WindowsRuntime } // void Clear() - [SecurityCritical] internal void Clear<K, V>() { object _this = JitHelpers.UnsafeCast<object>(this); @@ -109,7 +106,6 @@ namespace System.Runtime.InteropServices.WindowsRuntime } // bool Contains(T item) - [SecurityCritical] internal bool Contains<K, V>(KeyValuePair<K, V> item) { object _this = JitHelpers.UnsafeCast<object>(this); @@ -135,14 +131,13 @@ namespace System.Runtime.InteropServices.WindowsRuntime } // void CopyTo(T[] array, int arrayIndex) - [SecurityCritical] internal void CopyTo<K, V>(KeyValuePair<K, V>[] array, int arrayIndex) { if (array == null) - throw new ArgumentNullException("array"); + throw new ArgumentNullException(nameof(array)); if (arrayIndex < 0) - throw new ArgumentOutOfRangeException("arrayIndex"); + throw new ArgumentOutOfRangeException(nameof(arrayIndex)); if (array.Length <= arrayIndex && Count<K, V>() > 0) throw new ArgumentException(Environment.GetResourceString("Argument_IndexOutOfArrayBounds")); @@ -160,7 +155,6 @@ namespace System.Runtime.InteropServices.WindowsRuntime } // bool Remove(T item) - [SecurityCritical] internal bool Remove<K, V>(KeyValuePair<K, V> item) { object _this = JitHelpers.UnsafeCast<object>(this); diff --git a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/MapToDictionaryAdapter.cs b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/MapToDictionaryAdapter.cs index d7897ced9f..981972ca9f 100644 --- a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/MapToDictionaryAdapter.cs +++ b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/MapToDictionaryAdapter.cs @@ -8,6 +8,7 @@ using System; using System.Security; using System.Collections; using System.Collections.Generic; +using System.Diagnostics; using System.Diagnostics.Contracts; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; @@ -26,15 +27,14 @@ namespace System.Runtime.InteropServices.WindowsRuntime { private MapToDictionaryAdapter() { - Contract.Assert(false, "This class is never instantiated"); + Debug.Assert(false, "This class is never instantiated"); } // V this[K key] { get } - [SecurityCritical] internal V Indexer_Get<K, V>(K key) { if (key == null) - throw new ArgumentNullException("key"); + throw new ArgumentNullException(nameof(key)); Contract.EndContractBlock(); @@ -43,11 +43,10 @@ namespace System.Runtime.InteropServices.WindowsRuntime } // V this[K key] { set } - [SecurityCritical] internal void Indexer_Set<K, V>(K key, V value) { if (key == null) - throw new ArgumentNullException("key"); + throw new ArgumentNullException(nameof(key)); Contract.EndContractBlock(); @@ -56,7 +55,6 @@ namespace System.Runtime.InteropServices.WindowsRuntime } // ICollection<K> Keys { get } - [SecurityCritical] internal ICollection<K> Keys<K, V>() { IMap<K, V> _this = JitHelpers.UnsafeCast<IMap<K, V>>(this); @@ -65,7 +63,6 @@ namespace System.Runtime.InteropServices.WindowsRuntime } // ICollection<V> Values { get } - [SecurityCritical] internal ICollection<V> Values<K, V>() { IMap<K, V> _this = JitHelpers.UnsafeCast<IMap<K, V>>(this); @@ -75,22 +72,20 @@ namespace System.Runtime.InteropServices.WindowsRuntime // bool ContainsKey(K key) [Pure] - [SecurityCritical] internal bool ContainsKey<K, V>(K key) { if (key == null) - throw new ArgumentNullException("key"); + throw new ArgumentNullException(nameof(key)); IMap<K, V> _this = JitHelpers.UnsafeCast<IMap<K, V>>(this); return _this.HasKey(key); } // void Add(K key, V value) - [SecurityCritical] internal void Add<K, V>(K key, V value) { if (key == null) - throw new ArgumentNullException("key"); + throw new ArgumentNullException(nameof(key)); if (ContainsKey<K, V>(key)) throw new ArgumentException(Environment.GetResourceString("Argument_AddingDuplicate")); @@ -102,11 +97,10 @@ namespace System.Runtime.InteropServices.WindowsRuntime } // bool Remove(TKey key) - [SecurityCritical] internal bool Remove<K, V>(K key) { if (key == null) - throw new ArgumentNullException("key"); + throw new ArgumentNullException(nameof(key)); IMap<K, V> _this = JitHelpers.UnsafeCast<IMap<K, V>>(this); if (!_this.HasKey(key)) @@ -128,11 +122,10 @@ namespace System.Runtime.InteropServices.WindowsRuntime } // bool TryGetValue(TKey key, out TValue value) - [SecurityCritical] internal bool TryGetValue<K, V>(K key, out V value) { if (key == null) - throw new ArgumentNullException("key"); + throw new ArgumentNullException(nameof(key)); IMap<K, V> _this = JitHelpers.UnsafeCast<IMap<K, V>>(this); if (!_this.HasKey(key)) diff --git a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/MapViewToReadOnlyCollectionAdapter.cs b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/MapViewToReadOnlyCollectionAdapter.cs index 58427fbd71..a3715da0b0 100644 --- a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/MapViewToReadOnlyCollectionAdapter.cs +++ b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/MapViewToReadOnlyCollectionAdapter.cs @@ -8,6 +8,7 @@ using System; using System.Security; using System.Collections; using System.Collections.Generic; +using System.Diagnostics; using System.Diagnostics.Contracts; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; @@ -29,12 +30,11 @@ namespace System.Runtime.InteropServices.WindowsRuntime { private MapViewToReadOnlyCollectionAdapter() { - Contract.Assert(false, "This class is never instantiated"); + Debug.Assert(false, "This class is never instantiated"); } // int Count { get } [Pure] - [SecurityCritical] internal int Count<K, V>() { object _this = JitHelpers.UnsafeCast<object>(this); diff --git a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/NativeMethods.cs b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/NativeMethods.cs index b8cd65efa6..4380369754 100644 --- a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/NativeMethods.cs +++ b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/NativeMethods.cs @@ -22,30 +22,25 @@ namespace System.Runtime.InteropServices.WindowsRuntime internal static class UnsafeNativeMethods { [DllImport("api-ms-win-core-winrt-error-l1-1-1.dll", PreserveSig = false)] - [SecurityCritical] [SuppressUnmanagedCodeSecurity] internal static extern IRestrictedErrorInfo GetRestrictedErrorInfo(); [DllImport("api-ms-win-core-winrt-error-l1-1-1.dll")] - [SecurityCritical] [SuppressUnmanagedCodeSecurity] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool RoOriginateLanguageException(int error, [MarshalAs(UnmanagedType.HString)]string message, IntPtr languageException); [DllImport("api-ms-win-core-winrt-error-l1-1-1.dll", PreserveSig = false)] - [SecurityCritical] [SuppressUnmanagedCodeSecurity] internal static extern void RoReportUnhandledError(IRestrictedErrorInfo error); [DllImport("api-ms-win-core-winrt-string-l1-1-0.dll", CallingConvention = CallingConvention.StdCall)] - [SecurityCritical] [SuppressUnmanagedCodeSecurity] internal static unsafe extern int WindowsCreateString([MarshalAs(UnmanagedType.LPWStr)] string sourceString, int length, [Out] IntPtr *hstring); [DllImport("api-ms-win-core-winrt-string-l1-1-0.dll", CallingConvention = CallingConvention.StdCall)] - [SecurityCritical] [SuppressUnmanagedCodeSecurity] internal static unsafe extern int WindowsCreateStringReference(char *sourceString, int length, @@ -53,12 +48,10 @@ namespace System.Runtime.InteropServices.WindowsRuntime [Out] IntPtr *hstring); [DllImport("api-ms-win-core-winrt-string-l1-1-0.dll", CallingConvention = CallingConvention.StdCall)] - [SecurityCritical] [SuppressUnmanagedCodeSecurity] internal static extern int WindowsDeleteString(IntPtr hstring); [DllImport("api-ms-win-core-winrt-string-l1-1-0.dll", CallingConvention = CallingConvention.StdCall)] - [SecurityCritical] [SuppressUnmanagedCodeSecurity] internal static unsafe extern char* WindowsGetStringRawBuffer(IntPtr hstring, [Out] uint *length); } diff --git a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/RuntimeClass.cs b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/RuntimeClass.cs index 5dd7d00579..cd3c53ab4e 100644 --- a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/RuntimeClass.cs +++ b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/RuntimeClass.cs @@ -57,15 +57,12 @@ namespace System.Runtime.InteropServices.WindowsRuntime { // // Support for ToString/GetHashCode/Equals override // - [System.Security.SecurityCritical] [MethodImpl(MethodImplOptions.InternalCall)] internal extern IntPtr GetRedirectedGetHashCodeMD(); - [System.Security.SecurityCritical] [MethodImpl(MethodImplOptions.InternalCall)] internal extern int RedirectGetHashCode(IntPtr pMD); - [System.Security.SecuritySafeCritical] public override int GetHashCode() { IntPtr pMD = GetRedirectedGetHashCodeMD(); @@ -74,15 +71,12 @@ namespace System.Runtime.InteropServices.WindowsRuntime { return RedirectGetHashCode(pMD); } - [System.Security.SecurityCritical] [MethodImpl(MethodImplOptions.InternalCall)] internal extern IntPtr GetRedirectedToStringMD(); - [System.Security.SecurityCritical] [MethodImpl(MethodImplOptions.InternalCall)] internal extern string RedirectToString(IntPtr pMD); - [System.Security.SecuritySafeCritical] public override string ToString() { // Check whether the type implements IStringable. @@ -102,15 +96,12 @@ namespace System.Runtime.InteropServices.WindowsRuntime { } } - [System.Security.SecurityCritical] [MethodImpl(MethodImplOptions.InternalCall)] internal extern IntPtr GetRedirectedEqualsMD(); - [System.Security.SecurityCritical] [MethodImpl(MethodImplOptions.InternalCall)] internal extern bool RedirectEquals(object obj, IntPtr pMD); - [System.Security.SecuritySafeCritical] public override bool Equals(object obj) { IntPtr pMD = GetRedirectedEqualsMD(); diff --git a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/VectorToCollectionAdapter.cs b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/VectorToCollectionAdapter.cs index 5eeb0afcfc..898f1a68a0 100644 --- a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/VectorToCollectionAdapter.cs +++ b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/VectorToCollectionAdapter.cs @@ -8,6 +8,7 @@ using System; using System.Security; using System.Collections; using System.Collections.Generic; +using System.Diagnostics; using System.Diagnostics.Contracts; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; @@ -26,12 +27,11 @@ namespace System.Runtime.InteropServices.WindowsRuntime { private VectorToCollectionAdapter() { - Contract.Assert(false, "This class is never instantiated"); + Debug.Assert(false, "This class is never instantiated"); } // int Count { get } [Pure] - [SecurityCritical] internal int Count<T>() { IVector<T> _this = JitHelpers.UnsafeCast<IVector<T>>(this); @@ -45,14 +45,12 @@ namespace System.Runtime.InteropServices.WindowsRuntime } // bool IsReadOnly { get } - [SecurityCritical] internal bool IsReadOnly<T>() { return false; } // void Add(T item) - [SecurityCritical] internal void Add<T>(T item) { IVector<T> _this = JitHelpers.UnsafeCast<IVector<T>>(this); @@ -60,7 +58,6 @@ namespace System.Runtime.InteropServices.WindowsRuntime } // void Clear() - [SecurityCritical] internal void Clear<T>() { IVector<T> _this = JitHelpers.UnsafeCast<IVector<T>>(this); @@ -68,7 +65,6 @@ namespace System.Runtime.InteropServices.WindowsRuntime } // bool Contains(T item) - [SecurityCritical] internal bool Contains<T>(T item) { IVector<T> _this = JitHelpers.UnsafeCast<IVector<T>>(this); @@ -78,14 +74,13 @@ namespace System.Runtime.InteropServices.WindowsRuntime } // void CopyTo(T[] array, int arrayIndex) - [SecurityCritical] internal void CopyTo<T>(T[] array, int arrayIndex) { if (array == null) - throw new ArgumentNullException("array"); + throw new ArgumentNullException(nameof(array)); if (arrayIndex < 0) - throw new ArgumentOutOfRangeException("arrayIndex"); + throw new ArgumentOutOfRangeException(nameof(arrayIndex)); if (array.Length <= arrayIndex && Count<T>() > 0) throw new ArgumentException(Environment.GetResourceString("Argument_IndexOutOfArrayBounds")); @@ -104,7 +99,6 @@ namespace System.Runtime.InteropServices.WindowsRuntime } // bool Remove(T item) - [SecurityCritical] internal bool Remove<T>(T item) { IVector<T> _this = JitHelpers.UnsafeCast<IVector<T>>(this); diff --git a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/VectorToListAdapter.cs b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/VectorToListAdapter.cs index f27cc95176..3e3324864d 100644 --- a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/VectorToListAdapter.cs +++ b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/VectorToListAdapter.cs @@ -8,6 +8,7 @@ using System; using System.Security; using System.Collections; using System.Collections.Generic; +using System.Diagnostics; using System.Diagnostics.Contracts; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; @@ -26,33 +27,30 @@ namespace System.Runtime.InteropServices.WindowsRuntime { private VectorToListAdapter() { - Contract.Assert(false, "This class is never instantiated"); + Debug.Assert(false, "This class is never instantiated"); } // T this[int index] { get } - [SecurityCritical] internal T Indexer_Get<T>(int index) { if (index < 0) - throw new ArgumentOutOfRangeException("index"); + throw new ArgumentOutOfRangeException(nameof(index)); IVector<T> _this = JitHelpers.UnsafeCast<IVector<T>>(this); return GetAt(_this, (uint)index); } // T this[int index] { set } - [SecurityCritical] internal void Indexer_Set<T>(int index, T value) { if (index < 0) - throw new ArgumentOutOfRangeException("index"); + throw new ArgumentOutOfRangeException(nameof(index)); IVector<T> _this = JitHelpers.UnsafeCast<IVector<T>>(this); SetAt(_this, (uint)index, value); } // int IndexOf(T item) - [SecurityCritical] internal int IndexOf<T>(T item) { IVector<T> _this = JitHelpers.UnsafeCast<IVector<T>>(this); @@ -72,22 +70,20 @@ namespace System.Runtime.InteropServices.WindowsRuntime } // void Insert(int index, T item) - [SecurityCritical] internal void Insert<T>(int index, T item) { if (index < 0) - throw new ArgumentOutOfRangeException("index"); + throw new ArgumentOutOfRangeException(nameof(index)); IVector<T> _this = JitHelpers.UnsafeCast<IVector<T>>(this); InsertAtHelper<T>(_this, (uint)index, item); } // void RemoveAt(int index) - [SecurityCritical] internal void RemoveAt<T>(int index) { if (index < 0) - throw new ArgumentOutOfRangeException("index"); + throw new ArgumentOutOfRangeException(nameof(index)); IVector<T> _this = JitHelpers.UnsafeCast<IVector<T>>(this); RemoveAtHelper<T>(_this, (uint)index); @@ -107,7 +103,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime catch (Exception ex) { if (__HResults.E_BOUNDS == ex._HResult) - throw new ArgumentOutOfRangeException("index"); + throw new ArgumentOutOfRangeException(nameof(index)); throw; } @@ -125,7 +121,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime catch (Exception ex) { if (__HResults.E_BOUNDS == ex._HResult) - throw new ArgumentOutOfRangeException("index"); + throw new ArgumentOutOfRangeException(nameof(index)); throw; } @@ -143,7 +139,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime catch (Exception ex) { if (__HResults.E_BOUNDS == ex._HResult) - throw new ArgumentOutOfRangeException("index"); + throw new ArgumentOutOfRangeException(nameof(index)); throw; } @@ -161,7 +157,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime catch (Exception ex) { if (__HResults.E_BOUNDS == ex._HResult) - throw new ArgumentOutOfRangeException("index"); + throw new ArgumentOutOfRangeException(nameof(index)); throw; } diff --git a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/VectorViewToReadOnlyCollectionAdapter.cs b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/VectorViewToReadOnlyCollectionAdapter.cs index 4b4ae5d6fc..6b7785d2dc 100644 --- a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/VectorViewToReadOnlyCollectionAdapter.cs +++ b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/VectorViewToReadOnlyCollectionAdapter.cs @@ -8,6 +8,7 @@ using System; using System.Security; using System.Collections; using System.Collections.Generic; +using System.Diagnostics; using System.Diagnostics.Contracts; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; @@ -26,12 +27,11 @@ namespace System.Runtime.InteropServices.WindowsRuntime { private VectorViewToReadOnlyCollectionAdapter() { - Contract.Assert(false, "This class is never instantiated"); + Debug.Assert(false, "This class is never instantiated"); } // int Count { get } [Pure] - [SecurityCritical] internal int Count<T>() { IVectorView<T> _this = JitHelpers.UnsafeCast<IVectorView<T>>(this); diff --git a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/WindowsRuntimeBufferHelper.cs b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/WindowsRuntimeBufferHelper.cs index 0d59895bc4..a786880fab 100644 --- a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/WindowsRuntimeBufferHelper.cs +++ b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/WindowsRuntimeBufferHelper.cs @@ -19,7 +19,6 @@ namespace System.Runtime.InteropServices.WindowsRuntime { internal static class WindowsRuntimeBufferHelper { - [SecurityCritical] [DllImport(JitHelpers.QCall)] [SuppressUnmanagedCodeSecurity] [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] @@ -27,7 +26,6 @@ internal static class WindowsRuntimeBufferHelper { [FriendAccessAllowed] - [SecurityCritical] [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] internal unsafe static void StoreOverlappedInCCW(Object windowsRuntimeBuffer, NativeOverlapped* overlapped) { diff --git a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/WindowsRuntimeMarshal.cs b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/WindowsRuntimeMarshal.cs index 038efd5013..a7ad4912de 100644 --- a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/WindowsRuntimeMarshal.cs +++ b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/WindowsRuntimeMarshal.cs @@ -6,6 +6,7 @@ using System; using System.Collections.Generic; +using System.Diagnostics; using System.Diagnostics.Contracts; using System.Reflection; using System.Runtime.CompilerServices; @@ -23,15 +24,14 @@ namespace System.Runtime.InteropServices.WindowsRuntime // delegate. It then stores the corresponding token in a dictionary for easy access by RemoveEventHandler // later. Note that the dictionary is indexed by the remove method that will be used for RemoveEventHandler // so the removeMethod given here must match the remove method supplied there exactly. - [SecurityCritical] public static void AddEventHandler<T>(Func<T, EventRegistrationToken> addMethod, Action<EventRegistrationToken> removeMethod, T handler) { if (addMethod == null) - throw new ArgumentNullException("addMethod"); + throw new ArgumentNullException(nameof(addMethod)); if (removeMethod == null) - throw new ArgumentNullException("removeMethod"); + throw new ArgumentNullException(nameof(removeMethod)); Contract.EndContractBlock(); // Managed code allows adding a null event handler, the effect is a no-op. To match this behavior @@ -54,11 +54,10 @@ namespace System.Runtime.InteropServices.WindowsRuntime // Remove the delegate handler from the Windows Runtime style event registration by looking for // its token, previously stored via AddEventHandler<T> - [SecurityCritical] public static void RemoveEventHandler<T>(Action<EventRegistrationToken> removeMethod, T handler) { if (removeMethod == null) - throw new ArgumentNullException("removeMethod"); + throw new ArgumentNullException(nameof(removeMethod)); Contract.EndContractBlock(); // Managed code allows removing a null event handler, the effect is a no-op. To match this behavior @@ -79,11 +78,10 @@ namespace System.Runtime.InteropServices.WindowsRuntime ManagedEventRegistrationImpl.RemoveEventHandler<T>(removeMethod, handler); } - [SecurityCritical] public static void RemoveAllEventHandlers(Action<EventRegistrationToken> removeMethod) { if (removeMethod == null) - throw new ArgumentNullException("removeMethod"); + throw new ArgumentNullException(nameof(removeMethod)); Contract.EndContractBlock(); // Delegate to managed event registration implementation or native event registration implementation @@ -220,7 +218,6 @@ namespace System.Runtime.InteropServices.WindowsRuntime ConditionalWeakTable<object, Dictionary<MethodInfo, Dictionary<object, EventRegistrationTokenList>>> s_eventRegistrations = new ConditionalWeakTable<object, Dictionary<MethodInfo, Dictionary<object, EventRegistrationTokenList>>>(); - [SecurityCritical] internal static void AddEventHandler<T>(Func<T, EventRegistrationToken> addMethod, Action<EventRegistrationToken> removeMethod, T handler) @@ -280,7 +277,6 @@ namespace System.Runtime.InteropServices.WindowsRuntime } } - [SecurityCritical] internal static void RemoveEventHandler<T>(Action<EventRegistrationToken> removeMethod, T handler) { Contract.Requires(removeMethod != null); @@ -322,7 +318,6 @@ namespace System.Runtime.InteropServices.WindowsRuntime BCLDebug.Log("INTEROP", "[WinRT_Eventing] Event unsubscribed for managed instance = " + instance + ", handler = " + handler + ", token = " + token.m_value + "\n"); } - [SecurityCritical] internal static void RemoveAllEventHandlers(Action<EventRegistrationToken> removeMethod) { Contract.Requires(removeMethod != null); @@ -538,11 +533,10 @@ namespace System.Runtime.InteropServices.WindowsRuntime private volatile static MyReaderWriterLock s_eventCacheRWLock = new MyReaderWriterLock(); // Get InstanceKey to use in the cache - [SecuritySafeCritical] private static object GetInstanceKey(Action<EventRegistrationToken> removeMethod) { object target = removeMethod.Target; - Contract.Assert(target == null || Marshal.IsComObject(target), "Must be null or a RCW"); + Debug.Assert(target == null || Marshal.IsComObject(target), "Must be null or a RCW"); if (target == null) return removeMethod.Method.DeclaringType; @@ -550,7 +544,6 @@ namespace System.Runtime.InteropServices.WindowsRuntime return (object) Marshal.GetRawIUnknownForComObjectNoAddRef(target); } - [SecurityCritical] internal static void AddEventHandler<T>(Func<T, EventRegistrationToken> addMethod, Action<EventRegistrationToken> removeMethod, T handler) @@ -685,7 +678,6 @@ namespace System.Runtime.InteropServices.WindowsRuntime } } - [SecurityCritical] internal static void RemoveEventHandler<T>(Action<EventRegistrationToken> removeMethod, T handler) { object instanceKey = GetInstanceKey(removeMethod); @@ -721,7 +713,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime // Note that inside TryGetValueWithValueEquality we assumes that any delegate // with the same value equality would have the same hash code object key = registrationTokens.FindEquivalentKeyUnsafe(handler, out tokens); - Contract.Assert((key != null && tokens != null) || (key == null && tokens == null), + Debug.Assert((key != null && tokens != null) || (key == null && tokens == null), "key and tokens must be both null or non-null"); if (tokens == null) { @@ -762,7 +754,6 @@ namespace System.Runtime.InteropServices.WindowsRuntime removeMethod(token); } - [SecurityCritical] internal static void RemoveAllEventHandlers(Action<EventRegistrationToken> removeMethod) { object instanceKey = GetInstanceKey(removeMethod); @@ -908,7 +899,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime internal void ReleaseReaderLock() { EnterMyLock(); - Contract.Assert(owners > 0, "ReleasingReaderLock: releasing lock and no read lock taken"); + Debug.Assert(owners > 0, "ReleasingReaderLock: releasing lock and no read lock taken"); --owners; ExitAndWakeUpAppropriateWaiters(); } @@ -916,7 +907,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime internal void ReleaseWriterLock() { EnterMyLock(); - Contract.Assert(owners == -1, "Calling ReleaseWriterLock when no write lock is held"); + Debug.Assert(owners == -1, "Calling ReleaseWriterLock when no write lock is held"); owners++; ExitAndWakeUpAppropriateWaiters(); } @@ -928,8 +919,8 @@ namespace System.Runtime.InteropServices.WindowsRuntime /// set 'waitEvent' /// </summary> private void LazyCreateEvent(ref EventWaitHandle waitEvent, bool makeAutoResetEvent) { - Contract.Assert(myLock != 0, "Lock must be held"); - Contract.Assert(waitEvent == null, "Wait event must be null"); + Debug.Assert(myLock != 0, "Lock must be held"); + Debug.Assert(waitEvent == null, "Wait event must be null"); ExitMyLock(); EventWaitHandle newEvent; @@ -948,7 +939,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime /// </summary> private void WaitOnEvent(EventWaitHandle waitEvent, ref uint numWaiters, int millisecondsTimeout) { - Contract.Assert(myLock != 0, "Lock must be held"); + Debug.Assert(myLock != 0, "Lock must be held"); waitEvent.Reset(); numWaiters++; @@ -976,7 +967,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime /// </summary> private void ExitAndWakeUpAppropriateWaiters() { - Contract.Assert(myLock != 0, "Lock must be held"); + Debug.Assert(myLock != 0, "Lock must be held"); if (owners == 0 && numWriteWaiters > 0) { @@ -1012,7 +1003,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime } private void ExitMyLock() { - Contract.Assert(myLock != 0, "Exiting spin lock that is not held"); + Debug.Assert(myLock != 0, "Exiting spin lock that is not held"); myLock = 0; } }; @@ -1044,7 +1035,6 @@ namespace System.Runtime.InteropServices.WindowsRuntime throw new AggregateException(exceptions.ToArray()); } - [SecurityCritical] internal static unsafe string HStringToString(IntPtr hstring) { Contract.Requires(Environment.IsWinRTSupported); @@ -1092,7 +1082,6 @@ namespace System.Runtime.InteropServices.WindowsRuntime private static bool s_haveBlueErrorApis = true; - [SecurityCritical] private static bool RoOriginateLanguageException(int error, string message, IntPtr languageException) { if (s_haveBlueErrorApis) @@ -1110,7 +1099,6 @@ namespace System.Runtime.InteropServices.WindowsRuntime return false; } - [SecurityCritical] private static void RoReportUnhandledError(IRestrictedErrorInfo error) { if (s_haveBlueErrorApis) @@ -1134,7 +1122,6 @@ namespace System.Runtime.InteropServices.WindowsRuntime /// </summary> /// <returns>true if the error was reported, false if not (ie running on Win8)</returns> [FriendAccessAllowed] - [SecuritySafeCritical] internal static bool ReportUnhandledError(Exception e) { // Only report to the WinRT global exception handler in modern apps @@ -1200,14 +1187,12 @@ namespace System.Runtime.InteropServices.WindowsRuntime #if FEATURE_COMINTEROP_WINRT_MANAGED_ACTIVATION // Get an IActivationFactory * for a managed type - [SecurityCritical] internal static IntPtr GetActivationFactoryForType(Type type) { ManagedActivationFactory activationFactory = GetManagedActivationFactory(type); return Marshal.GetComInterfaceForObject(activationFactory, typeof(IActivationFactory)); } - [SecurityCritical] internal static ManagedActivationFactory GetManagedActivationFactory(Type type) { ManagedActivationFactory activationFactory = new ManagedActivationFactory(type); @@ -1224,7 +1209,6 @@ namespace System.Runtime.InteropServices.WindowsRuntime // holds the IWinRTClassActivator* that is used for the process private static IntPtr s_pClassActivator = IntPtr.Zero; - [SecurityCritical] internal static IntPtr GetClassActivatorForApplication(string appBase) { if (s_pClassActivator == IntPtr.Zero) @@ -1268,11 +1252,10 @@ namespace System.Runtime.InteropServices.WindowsRuntime // factories from other apartments and make transiton to those apartments and cause // deadlocks and create objects in incorrect apartments // - [SecurityCritical] public static IActivationFactory GetActivationFactory(Type type) { if (type == null) - throw new ArgumentNullException("type"); + throw new ArgumentNullException(nameof(type)); if (type.IsWindowsRuntimeObject && type.IsImport) { @@ -1291,14 +1274,13 @@ namespace System.Runtime.InteropServices.WindowsRuntime // HSTRING marshaling methods: - [SecurityCritical] public static IntPtr StringToHString(String s) { if (!Environment.IsWinRTSupported) throw new PlatformNotSupportedException(Environment.GetResourceString("PlatformNotSupported_WinRT")); if (s == null) - throw new ArgumentNullException("s"); + throw new ArgumentNullException(nameof(s)); unsafe { @@ -1309,7 +1291,6 @@ namespace System.Runtime.InteropServices.WindowsRuntime } } - [SecurityCritical] public static String PtrToStringHString(IntPtr ptr) { if (!Environment.IsWinRTSupported) @@ -1320,7 +1301,6 @@ namespace System.Runtime.InteropServices.WindowsRuntime return HStringToString(ptr); } - [SecurityCritical] public static void FreeHString(IntPtr ptr) { if (!Environment.IsWinRTSupported) diff --git a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/WindowsRuntimeMetadata.cs b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/WindowsRuntimeMetadata.cs index e2ad203583..9ca959c528 100644 --- a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/WindowsRuntimeMetadata.cs +++ b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/WindowsRuntimeMetadata.cs @@ -19,18 +19,16 @@ namespace System.Runtime.InteropServices.WindowsRuntime public static class WindowsRuntimeMetadata { // Wrapper for Win8 API RoResolveNamespace with default Windows SDK path as installed .winmd files in %WINDIR%\system32\WinMetadata. - [System.Security.SecurityCritical] public static IEnumerable<string> ResolveNamespace(string namespaceName, IEnumerable<string> packageGraphFilePaths) { return ResolveNamespace(namespaceName, null, packageGraphFilePaths); } // Wrapper for Win8 API RoResolveNamespace. - [System.Security.SecurityCritical] public static IEnumerable<string> ResolveNamespace(string namespaceName, string windowsSdkFilePath, IEnumerable<string> packageGraphFilePaths) { if (namespaceName == null) - throw new ArgumentNullException("namespaceName"); + throw new ArgumentNullException(nameof(namespaceName)); Contract.EndContractBlock(); string[] packageGraphFilePathsArray = null; @@ -58,7 +56,6 @@ namespace System.Runtime.InteropServices.WindowsRuntime return retFileNames; } - [System.Security.SecurityCritical] [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [SuppressUnmanagedCodeSecurity] private extern static void nResolveNamespace( diff --git a/src/mscorlib/src/System/Runtime/Loader/AssemblyLoadContext.cs b/src/mscorlib/src/System/Runtime/Loader/AssemblyLoadContext.cs index 75529868bd..e158a5aa8a 100644 --- a/src/mscorlib/src/System/Runtime/Loader/AssemblyLoadContext.cs +++ b/src/mscorlib/src/System/Runtime/Loader/AssemblyLoadContext.cs @@ -17,7 +17,6 @@ using System.Threading; namespace System.Runtime.Loader { - [System.Security.SecuritySafeCritical] public abstract class AssemblyLoadContext { [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] @@ -62,7 +61,6 @@ namespace System.Runtime.Loader InitializeLoadContext(fRepresentsTPALoadContext); } - [System.Security.SecuritySafeCritical] void InitializeLoadContext(bool fRepresentsTPALoadContext) { // Initialize the VM side of AssemblyLoadContext if not already done. @@ -83,6 +81,17 @@ namespace System.Runtime.Loader [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [SuppressUnmanagedCodeSecurity] private static extern void LoadFromPath(IntPtr ptrNativeAssemblyLoadContext, string ilPath, string niPath, ObjectHandleOnStack retAssembly); + + [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] + [SuppressUnmanagedCodeSecurity] + private static extern void GetLoadedAssembliesInternal(ObjectHandleOnStack assemblies); + + public static Assembly[] GetLoadedAssemblies() + { + Assembly[] assemblies = null; + GetLoadedAssembliesInternal(JitHelpers.GetObjectHandleOnStack(ref assemblies)); + return assemblies; + } // These are helpers that can be used by AssemblyLoadContext derivations. // They are used to load assemblies in DefaultContext. @@ -90,12 +99,12 @@ namespace System.Runtime.Loader { if (assemblyPath == null) { - throw new ArgumentNullException("assemblyPath"); + throw new ArgumentNullException(nameof(assemblyPath)); } - if (Path.IsRelative(assemblyPath)) + if (PathInternal.IsPartiallyQualified(assemblyPath)) { - throw new ArgumentException( Environment.GetResourceString("Argument_AbsolutePathRequired"), "assemblyPath"); + throw new ArgumentException( Environment.GetResourceString("Argument_AbsolutePathRequired"), nameof(assemblyPath)); } RuntimeAssembly loadedAssembly = null; @@ -107,17 +116,17 @@ namespace System.Runtime.Loader { if (nativeImagePath == null) { - throw new ArgumentNullException("nativeImagePath"); + throw new ArgumentNullException(nameof(nativeImagePath)); } - if (Path.IsRelative(nativeImagePath)) + if (PathInternal.IsPartiallyQualified(nativeImagePath)) { - throw new ArgumentException( Environment.GetResourceString("Argument_AbsolutePathRequired"), "nativeImagePath"); + throw new ArgumentException( Environment.GetResourceString("Argument_AbsolutePathRequired"), nameof(nativeImagePath)); } - if (assemblyPath != null && Path.IsRelative(assemblyPath)) + if (assemblyPath != null && PathInternal.IsPartiallyQualified(assemblyPath)) { - throw new ArgumentException(Environment.GetResourceString("Argument_AbsolutePathRequired"), "assemblyPath"); + throw new ArgumentException(Environment.GetResourceString("Argument_AbsolutePathRequired"), nameof(assemblyPath)); } // Basic validation has succeeded - lets try to load the NI image. @@ -136,7 +145,7 @@ namespace System.Runtime.Loader { if (assembly == null) { - throw new ArgumentNullException("assembly"); + throw new ArgumentNullException(nameof(assembly)); } int iAssemblyStreamLength = (int)assembly.Length; @@ -291,15 +300,15 @@ namespace System.Runtime.Loader { if (unmanagedDllPath == null) { - throw new ArgumentNullException("unmanagedDllPath"); + throw new ArgumentNullException(nameof(unmanagedDllPath)); } if (unmanagedDllPath.Length == 0) { - throw new ArgumentException(Environment.GetResourceString("Argument_EmptyPath"), "unmanagedDllPath"); + throw new ArgumentException(Environment.GetResourceString("Argument_EmptyPath"), nameof(unmanagedDllPath)); } - if (Path.IsRelative(unmanagedDllPath)) + if (PathInternal.IsPartiallyQualified(unmanagedDllPath)) { - throw new ArgumentException(Environment.GetResourceString("Argument_AbsolutePathRequired"), "unmanagedDllPath"); + throw new ArgumentException(Environment.GetResourceString("Argument_AbsolutePathRequired"), nameof(unmanagedDllPath)); } return InternalLoadUnmanagedDllFromPath(unmanagedDllPath); @@ -355,7 +364,7 @@ namespace System.Runtime.Loader { if (context == null) { - throw new ArgumentNullException("context"); + throw new ArgumentNullException(nameof(context)); } // Try to override the default assembly load context @@ -378,10 +387,10 @@ namespace System.Runtime.Loader { if (assemblyPath == null) { - throw new ArgumentNullException("assemblyPath"); + throw new ArgumentNullException(nameof(assemblyPath)); } - - String fullPath = Path.GetFullPathInternal(assemblyPath); + + string fullPath = Path.GetFullPath(assemblyPath); return nGetFileInformation(fullPath); } @@ -394,7 +403,7 @@ namespace System.Runtime.Loader { if (assembly == null) { - throw new ArgumentNullException("assembly"); + throw new ArgumentNullException(nameof(assembly)); } AssemblyLoadContext loadContextForAssembly = null; @@ -459,16 +468,43 @@ namespace System.Runtime.Loader // Synchronization primitive for controlling initialization of Default load context private static readonly object s_initLock = new Object(); + + // Occurs when an Assembly is loaded + public static event AssemblyLoadEventHandler AssemblyLoad + { + add { AppDomain.CurrentDomain.AssemblyLoad += value; } + remove { AppDomain.CurrentDomain.AssemblyLoad -= value; } + } + + // Occurs when resolution of type fails + public static event ResolveEventHandler TypeResolve + { + add { AppDomain.CurrentDomain.TypeResolve += value; } + remove { AppDomain.CurrentDomain.TypeResolve -= value; } + } + + // Occurs when resolution of resource fails + public static event ResolveEventHandler ResourceResolve + { + add { AppDomain.CurrentDomain.ResourceResolve += value; } + remove { AppDomain.CurrentDomain.ResourceResolve -= value; } + } + + // Occurs when resolution of assembly fails + // This event is fired after resolve events of AssemblyLoadContext fails + public static event ResolveEventHandler AssemblyResolve + { + add { AppDomain.CurrentDomain.AssemblyResolve += value; } + remove { AppDomain.CurrentDomain.AssemblyResolve -= value; } + } } - [System.Security.SecuritySafeCritical] class AppPathAssemblyLoadContext : AssemblyLoadContext { internal AppPathAssemblyLoadContext() : base(true) { } - [System.Security.SecuritySafeCritical] protected override Assembly Load(AssemblyName assemblyName) { // We were loading an assembly into TPA ALC that was not found on TPA list. As a result we are here. @@ -476,6 +512,18 @@ namespace System.Runtime.Loader return null; } } + + internal class IndividualAssemblyLoadContext : AssemblyLoadContext + { + internal IndividualAssemblyLoadContext() : base(false) + { + } + + protected override Assembly Load(AssemblyName assemblyName) + { + return null; + } + } } #endif // FEATURE_HOST_ASSEMBLY_RESOLVER diff --git a/src/mscorlib/src/System/Runtime/MemoryFailPoint.cs b/src/mscorlib/src/System/Runtime/MemoryFailPoint.cs index 6e35568310..bd87d9027c 100644 --- a/src/mscorlib/src/System/Runtime/MemoryFailPoint.cs +++ b/src/mscorlib/src/System/Runtime/MemoryFailPoint.cs @@ -22,6 +22,7 @@ using System.Runtime.CompilerServices; using System.Runtime.ConstrainedExecution; using System.Security.Permissions; using System.Runtime.Versioning; +using System.Diagnostics; using System.Diagnostics.Contracts; /* @@ -143,7 +144,6 @@ namespace System.Runtime private ulong _reservedMemory; // The size of this request (from user) private bool _mustSubtractReservation; // Did we add data to SharedStatics? - [System.Security.SecuritySafeCritical] // auto-generated static MemoryFailPoint() { GetMemorySettings(out GCSegmentSize, out TopOfMemory); @@ -153,13 +153,13 @@ namespace System.Runtime // have scenarios for this in partial trust in the future, but // we're doing this just to restrict this in case the code below // is somehow incorrect. - [System.Security.SecurityCritical] // auto-generated_required public MemoryFailPoint(int sizeInMegabytes) { if (sizeInMegabytes <= 0) - throw new ArgumentOutOfRangeException("sizeInMegabytes", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); + throw new ArgumentOutOfRangeException(nameof(sizeInMegabytes), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); Contract.EndContractBlock(); +#if !FEATURE_PAL // Remove this when CheckForAvailableMemory is able to provide legitimate estimates ulong size = ((ulong)sizeInMegabytes) << 20; _reservedMemory = size; @@ -283,7 +283,7 @@ namespace System.Runtime break; default: - Contract.Assert(false, "Fell through switch statement!"); + Debug.Assert(false, "Fell through switch statement!"); break; } } @@ -302,9 +302,9 @@ namespace System.Runtime SharedStatics.AddMemoryFailPointReservation((long) size); _mustSubtractReservation = true; } +#endif } - [System.Security.SecurityCritical] // auto-generated private static void CheckForAvailableMemory(out ulong availPageFile, out ulong totalAddressSpaceFree) { bool r; @@ -321,7 +321,6 @@ namespace System.Runtime // returns whether there is enough space. In all cases, we update // our last known free address space, hopefully avoiding needing to // probe again. - [System.Security.SecurityCritical] // auto-generated private static unsafe bool CheckForFreeAddressSpace(ulong size, bool shouldThrow) { // Start walking the address space at 0. VirtualAlloc may wrap @@ -348,7 +347,6 @@ namespace System.Runtime // of pages. If we didn't have enough address space, we still return // a positive value < size, to help potentially avoid the overhead of // this check if we use a MemoryFailPoint with a smaller size next. - [System.Security.SecurityCritical] // auto-generated private static unsafe ulong MemFreeAfterAddress(void * address, ulong size) { if (size >= TopOfMemory) @@ -375,11 +373,9 @@ namespace System.Runtime return largestFreeRegion; } - [System.Security.SecurityCritical] // auto-generated [MethodImpl(MethodImplOptions.InternalCall)] private static extern void GetMemorySettings(out ulong maxGCSegmentSize, out ulong topOfMemory); - [System.Security.SecuritySafeCritical] // destructors should be safe to call ~MemoryFailPoint() { Dispose(false); @@ -392,14 +388,12 @@ namespace System.Runtime // future create an allocation context and release it in the Dispose // method. While the finalizer will eventually free this block of // memory, apps will help their performance greatly by calling Dispose. - [System.Security.SecuritySafeCritical] // auto-generated public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } - [System.Security.SecurityCritical] // auto-generated [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] private void Dispose(bool disposing) { diff --git a/src/mscorlib/src/System/Runtime/ProfileOptimization.cs b/src/mscorlib/src/System/Runtime/ProfileOptimization.cs index c877d2106d..1e42308ecc 100644 --- a/src/mscorlib/src/System/Runtime/ProfileOptimization.cs +++ b/src/mscorlib/src/System/Runtime/ProfileOptimization.cs @@ -27,22 +27,18 @@ namespace System.Runtime { public static class ProfileOptimization { [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] - [SecurityCritical] [SuppressUnmanagedCodeSecurity] internal static extern void InternalSetProfileRoot(string directoryPath); [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] - [SecurityCritical] [SuppressUnmanagedCodeSecurity] internal static extern void InternalStartProfile(string profile, IntPtr ptrNativeAssemblyLoadContext); - [SecurityCritical] public static void SetProfileRoot(string directoryPath) { InternalSetProfileRoot(directoryPath); } - [SecurityCritical] public static void StartProfile(string profile) { InternalStartProfile(profile, IntPtr.Zero); diff --git a/src/mscorlib/src/System/Runtime/Reliability/CriticalFinalizerObject.cs b/src/mscorlib/src/System/Runtime/Reliability/CriticalFinalizerObject.cs index 2524aaaecb..eb5a186b65 100644 --- a/src/mscorlib/src/System/Runtime/Reliability/CriticalFinalizerObject.cs +++ b/src/mscorlib/src/System/Runtime/Reliability/CriticalFinalizerObject.cs @@ -22,15 +22,9 @@ using System.Runtime.InteropServices; namespace System.Runtime.ConstrainedExecution { -#if !FEATURE_CORECLR - [SecurityPermission(SecurityAction.InheritanceDemand, UnmanagedCode=true)] -#endif [System.Runtime.InteropServices.ComVisible(true)] public abstract class CriticalFinalizerObject { - #if FEATURE_CORECLR - [System.Security.SecuritySafeCritical] // auto-generated - #endif [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)] protected CriticalFinalizerObject() { diff --git a/src/mscorlib/src/System/Runtime/Remoting/ObjectHandle.cs b/src/mscorlib/src/System/Runtime/Remoting/ObjectHandle.cs index d10df9d57b..5555670498 100644 --- a/src/mscorlib/src/System/Runtime/Remoting/ObjectHandle.cs +++ b/src/mscorlib/src/System/Runtime/Remoting/ObjectHandle.cs @@ -14,23 +14,14 @@ ** ===========================================================*/ -namespace System.Runtime.Remoting{ - +namespace System.Runtime.Remoting +{ using System; - using System.Security.Permissions; using System.Runtime.InteropServices; - using System.Runtime.Remoting; -#if FEATURE_REMOTING - using System.Runtime.Remoting.Activation; - using System.Runtime.Remoting.Lifetime; -#endif [ClassInterface(ClassInterfaceType.AutoDual)] [System.Runtime.InteropServices.ComVisible(true)] public class ObjectHandle: -#if FEATURE_REMOTING - MarshalByRefObject, -#endif IObjectHandle { private Object WrappedObject; @@ -48,34 +39,5 @@ namespace System.Runtime.Remoting{ { return WrappedObject; } - - // ObjectHandle has a finite lifetime. For now the default - // lifetime is being used, this can be changed in this method to - // specify a custom lifetime. -#if FEATURE_REMOTING - [System.Security.SecurityCritical] // auto-generated_required - public override Object InitializeLifetimeService() - { - BCLDebug.Trace("REMOTE", "ObjectHandle.InitializeLifetimeService"); - - // - // If the wrapped object has implemented InitializeLifetimeService to return null, - // we don't want to go to the base class (which will result in a lease being - // requested from the MarshalByRefObject, which starts up the LeaseManager, - // which starts up the ThreadPool, adding three threads to the process. - // We check if the wrapped object is a MarshalByRef object, and call InitializeLifetimeServices on it - // and if it returns null, we return null. Otherwise we fall back to the old behavior. - // - - MarshalByRefObject mbr = WrappedObject as MarshalByRefObject; - if (mbr != null) { - Object o = mbr.InitializeLifetimeService(); - if (o == null) - return null; - } - ILease lease = (ILease)base.InitializeLifetimeService(); - return lease; - } -#endif // FEATURE_REMOTING } } diff --git a/src/mscorlib/src/System/Runtime/Serialization/FormatterConverter.cs b/src/mscorlib/src/System/Runtime/Serialization/FormatterConverter.cs index 7df221c9cd..b710ed0b3a 100644 --- a/src/mscorlib/src/System/Runtime/Serialization/FormatterConverter.cs +++ b/src/mscorlib/src/System/Runtime/Serialization/FormatterConverter.cs @@ -25,7 +25,7 @@ namespace System.Runtime.Serialization { public Object Convert(Object value, Type type) { if (value==null) { - throw new ArgumentNullException("value"); + throw new ArgumentNullException(nameof(value)); } Contract.EndContractBlock(); return System.Convert.ChangeType(value, type, CultureInfo.InvariantCulture); @@ -33,7 +33,7 @@ namespace System.Runtime.Serialization { public Object Convert(Object value, TypeCode typeCode) { if (value==null) { - throw new ArgumentNullException("value"); + throw new ArgumentNullException(nameof(value)); } Contract.EndContractBlock(); return System.Convert.ChangeType(value, typeCode, CultureInfo.InvariantCulture); @@ -41,7 +41,7 @@ namespace System.Runtime.Serialization { public bool ToBoolean(Object value) { if (value==null) { - throw new ArgumentNullException("value"); + throw new ArgumentNullException(nameof(value)); } Contract.EndContractBlock(); return System.Convert.ToBoolean(value, CultureInfo.InvariantCulture); @@ -49,7 +49,7 @@ namespace System.Runtime.Serialization { public char ToChar(Object value) { if (value==null) { - throw new ArgumentNullException("value"); + throw new ArgumentNullException(nameof(value)); } Contract.EndContractBlock(); return System.Convert.ToChar(value, CultureInfo.InvariantCulture); @@ -58,7 +58,7 @@ namespace System.Runtime.Serialization { [CLSCompliant(false)] public sbyte ToSByte(Object value) { if (value==null) { - throw new ArgumentNullException("value"); + throw new ArgumentNullException(nameof(value)); } Contract.EndContractBlock(); return System.Convert.ToSByte(value, CultureInfo.InvariantCulture); @@ -66,7 +66,7 @@ namespace System.Runtime.Serialization { public byte ToByte(Object value) { if (value==null) { - throw new ArgumentNullException("value"); + throw new ArgumentNullException(nameof(value)); } Contract.EndContractBlock(); return System.Convert.ToByte(value, CultureInfo.InvariantCulture); @@ -74,7 +74,7 @@ namespace System.Runtime.Serialization { public short ToInt16(Object value) { if (value==null) { - throw new ArgumentNullException("value"); + throw new ArgumentNullException(nameof(value)); } Contract.EndContractBlock(); return System.Convert.ToInt16(value, CultureInfo.InvariantCulture); @@ -83,7 +83,7 @@ namespace System.Runtime.Serialization { [CLSCompliant(false)] public ushort ToUInt16(Object value) { if (value==null) { - throw new ArgumentNullException("value"); + throw new ArgumentNullException(nameof(value)); } Contract.EndContractBlock(); return System.Convert.ToUInt16(value, CultureInfo.InvariantCulture); @@ -91,7 +91,7 @@ namespace System.Runtime.Serialization { public int ToInt32(Object value) { if (value==null) { - throw new ArgumentNullException("value"); + throw new ArgumentNullException(nameof(value)); } Contract.EndContractBlock(); return System.Convert.ToInt32(value, CultureInfo.InvariantCulture); @@ -100,7 +100,7 @@ namespace System.Runtime.Serialization { [CLSCompliant(false)] public uint ToUInt32(Object value) { if (value==null) { - throw new ArgumentNullException("value"); + throw new ArgumentNullException(nameof(value)); } Contract.EndContractBlock(); return System.Convert.ToUInt32(value, CultureInfo.InvariantCulture); @@ -108,7 +108,7 @@ namespace System.Runtime.Serialization { public long ToInt64(Object value) { if (value==null) { - throw new ArgumentNullException("value"); + throw new ArgumentNullException(nameof(value)); } Contract.EndContractBlock(); return System.Convert.ToInt64(value, CultureInfo.InvariantCulture); @@ -117,7 +117,7 @@ namespace System.Runtime.Serialization { [CLSCompliant(false)] public ulong ToUInt64(Object value) { if (value==null) { - throw new ArgumentNullException("value"); + throw new ArgumentNullException(nameof(value)); } Contract.EndContractBlock(); return System.Convert.ToUInt64(value, CultureInfo.InvariantCulture); @@ -125,7 +125,7 @@ namespace System.Runtime.Serialization { public float ToSingle(Object value) { if (value==null) { - throw new ArgumentNullException("value"); + throw new ArgumentNullException(nameof(value)); } Contract.EndContractBlock(); return System.Convert.ToSingle(value, CultureInfo.InvariantCulture); @@ -133,7 +133,7 @@ namespace System.Runtime.Serialization { public double ToDouble(Object value) { if (value==null) { - throw new ArgumentNullException("value"); + throw new ArgumentNullException(nameof(value)); } Contract.EndContractBlock(); return System.Convert.ToDouble(value, CultureInfo.InvariantCulture); @@ -141,7 +141,7 @@ namespace System.Runtime.Serialization { public Decimal ToDecimal(Object value) { if (value==null) { - throw new ArgumentNullException("value"); + throw new ArgumentNullException(nameof(value)); } Contract.EndContractBlock(); return System.Convert.ToDecimal(value, CultureInfo.InvariantCulture); @@ -149,7 +149,7 @@ namespace System.Runtime.Serialization { public DateTime ToDateTime(Object value) { if (value==null) { - throw new ArgumentNullException("value"); + throw new ArgumentNullException(nameof(value)); } Contract.EndContractBlock(); return System.Convert.ToDateTime(value, CultureInfo.InvariantCulture); @@ -157,7 +157,7 @@ namespace System.Runtime.Serialization { public String ToString(Object value) { if (value==null) { - throw new ArgumentNullException("value"); + throw new ArgumentNullException(nameof(value)); } Contract.EndContractBlock(); return System.Convert.ToString(value, CultureInfo.InvariantCulture); diff --git a/src/mscorlib/src/System/Runtime/Serialization/FormatterServices.cs b/src/mscorlib/src/System/Runtime/Serialization/FormatterServices.cs index c6f27b5b2a..27c3f15136 100644 --- a/src/mscorlib/src/System/Runtime/Serialization/FormatterServices.cs +++ b/src/mscorlib/src/System/Runtime/Serialization/FormatterServices.cs @@ -29,16 +29,15 @@ namespace System.Runtime.Serialization { using System.IO; using System.Text; using System.Globalization; + using System.Diagnostics; using System.Diagnostics.Contracts; [System.Runtime.InteropServices.ComVisible(true)] public static class FormatterServices { #if FEATURE_SERIALIZATION internal static Dictionary<MemberHolder, MemberInfo[]> m_MemberInfoTable = new Dictionary<MemberHolder, MemberInfo[]>(32); - [System.Security.SecurityCritical] private static bool unsafeTypeForwardersIsEnabled = false; - [System.Security.SecurityCritical] private static volatile bool unsafeTypeForwardersIsEnabledInitialized = false; private static Object s_FormatterServicesSyncObject = null; @@ -56,7 +55,6 @@ namespace System.Runtime.Serialization { } } - [SecuritySafeCritical] static FormatterServices() { // Static initialization touches security critical types, so we need an @@ -100,7 +98,7 @@ namespace System.Runtime.Serialization { FieldInfo [] typeFields; RuntimeType parentType; - Contract.Assert((object)type != null, "[GetAllSerializableMembers]type!=null"); + Debug.Assert((object)type != null, "[GetAllSerializableMembers]type!=null"); if (type.IsInterface) { return new MemberInfo[0]; @@ -186,7 +184,6 @@ namespace System.Runtime.Serialization { // be included, properties must have both a getter and a setter. N.B.: A class // which implements ISerializable or has a serialization surrogate may not use all of these members // (or may have additional members). - [System.Security.SecurityCritical] // auto-generated_required public static MemberInfo[] GetSerializableMembers(Type type) { return GetSerializableMembers(type, new StreamingContext(StreamingContextStates.All)); } @@ -194,12 +191,11 @@ namespace System.Runtime.Serialization { // Get all of the Serializable Members for a particular class. If we're not cloning, this is all // non-transient, non-static fields. If we are cloning, include the transient fields as well since // we know that we're going to live inside of the same context. - [System.Security.SecurityCritical] // auto-generated_required public static MemberInfo[] GetSerializableMembers(Type type, StreamingContext context) { MemberInfo[] members; if ((object)type==null) { - throw new ArgumentNullException("type"); + throw new ArgumentNullException(nameof(type)); } Contract.EndContractBlock(); @@ -230,14 +226,9 @@ namespace System.Runtime.Serialization { static readonly Type[] advancedTypes = new Type[]{ typeof(System.DelegateSerializationHolder), -#if FEATURE_REMOTING - typeof(System.Runtime.Remoting.ObjRef), - typeof(System.Runtime.Remoting.IEnvoyInfo), - typeof(System.Runtime.Remoting.Lifetime.ISponsor), -#endif }; - - public static void CheckTypeSecurity(Type t, TypeFilterLevel securityLevel) { + + public static void CheckTypeSecurity(Type t, TypeFilterLevel securityLevel) { if (securityLevel == TypeFilterLevel.Low){ for(int i=0;i<advancedTypes.Length;i++){ if (advancedTypes[i].IsAssignableFrom(t)) @@ -254,10 +245,9 @@ namespace System.Runtime.Serialization { // will not create an unitialized string because it is non-sensical to create an empty // instance of an immutable type. // - [System.Security.SecurityCritical] // auto-generated_required public static Object GetUninitializedObject(Type type) { if ((object)type == null) { - throw new ArgumentNullException("type"); + throw new ArgumentNullException(nameof(type)); } Contract.EndContractBlock(); @@ -268,44 +258,33 @@ namespace System.Runtime.Serialization { return nativeGetUninitializedObject((RuntimeType)type); } - [System.Security.SecurityCritical] // auto-generated_required public static Object GetSafeUninitializedObject(Type type) { if ((object)type == null) { - throw new ArgumentNullException("type"); + throw new ArgumentNullException(nameof(type)); } Contract.EndContractBlock(); - + if (!(type is RuntimeType)) { throw new SerializationException(Environment.GetResourceString("Serialization_InvalidType", type.ToString())); } -#if FEATURE_REMOTING - if (Object.ReferenceEquals(type, typeof(System.Runtime.Remoting.Messaging.ConstructionCall)) || - Object.ReferenceEquals(type, typeof(System.Runtime.Remoting.Messaging.LogicalCallContext)) || - Object.ReferenceEquals(type, typeof(System.Runtime.Remoting.Contexts.SynchronizationAttribute))) - return nativeGetUninitializedObject((RuntimeType)type); -#endif - try { - return nativeGetSafeUninitializedObject((RuntimeType)type); + try { + return nativeGetSafeUninitializedObject((RuntimeType)type); } - catch(SecurityException e) { + catch(SecurityException e) { throw new SerializationException(Environment.GetResourceString("Serialization_Security", type.FullName), e); - } + } } - [System.Security.SecurityCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.InternalCall)] private static extern Object nativeGetSafeUninitializedObject(RuntimeType type); - [System.Security.SecurityCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.InternalCall)] private static extern Object nativeGetUninitializedObject(RuntimeType type); #if FEATURE_SERIALIZATION - [System.Security.SecurityCritical] [MethodImplAttribute(MethodImplOptions.InternalCall)] private static extern bool GetEnableUnsafeTypeForwarders(); - [SecuritySafeCritical] internal static bool UnsafeTypeForwardersIsEnabled() { if (!unsafeTypeForwardersIsEnabledInitialized) @@ -318,7 +297,6 @@ namespace System.Runtime.Serialization { } #endif private static Binder s_binder = Type.DefaultBinder; - [System.Security.SecurityCritical] internal static void SerializationSetValue(MemberInfo fi, Object target, Object value) { Contract.Requires(fi != null); @@ -345,18 +323,17 @@ namespace System.Runtime.Serialization { // Fill in the members of obj with the data contained in data. // Returns the number of members populated. // - [System.Security.SecurityCritical] // auto-generated_required public static Object PopulateObjectMembers(Object obj, MemberInfo[] members, Object[] data) { if (obj==null) { - throw new ArgumentNullException("obj"); + throw new ArgumentNullException(nameof(obj)); } if (members==null) { - throw new ArgumentNullException("members"); + throw new ArgumentNullException(nameof(members)); } if (data==null) { - throw new ArgumentNullException("data"); + throw new ArgumentNullException(nameof(data)); } if (members.Length!=data.Length) { @@ -372,7 +349,7 @@ namespace System.Runtime.Serialization { mi = members[i]; if (mi==null) { - throw new ArgumentNullException("members", Environment.GetResourceString("ArgumentNull_NullMember", i)); + throw new ArgumentNullException(nameof(members), Environment.GetResourceString("ArgumentNull_NullMember", i)); } //If we find an empty, it means that the value was never set during deserialization. @@ -400,15 +377,14 @@ namespace System.Runtime.Serialization { // extract (must be FieldInfos or PropertyInfos). For each supplied member, extract the matching value and // return it in a Object[] of the same size. // - [System.Security.SecurityCritical] // auto-generated_required public static Object[] GetObjectData(Object obj, MemberInfo[] members) { if (obj==null) { - throw new ArgumentNullException("obj"); + throw new ArgumentNullException(nameof(obj)); } if (members==null) { - throw new ArgumentNullException("members"); + throw new ArgumentNullException(nameof(members)); } Contract.EndContractBlock(); @@ -421,11 +397,11 @@ namespace System.Runtime.Serialization { mi=members[i]; if (mi==null) { - throw new ArgumentNullException("members", Environment.GetResourceString("ArgumentNull_NullMember", i)); + throw new ArgumentNullException(nameof(members), Environment.GetResourceString("ArgumentNull_NullMember", i)); } if (mi.MemberType==MemberTypes.Field) { - Contract.Assert(mi is RuntimeFieldInfo || mi is SerializationFieldInfo, + Debug.Assert(mi is RuntimeFieldInfo || mi is SerializationFieldInfo, "[FormatterServices.GetObjectData]mi is RuntimeFieldInfo || mi is SerializationFieldInfo."); RtFieldInfo rfi = mi as RtFieldInfo; @@ -443,12 +419,11 @@ namespace System.Runtime.Serialization { return data; } - [System.Security.SecurityCritical] // auto-generated_required [System.Runtime.InteropServices.ComVisible(false)] public static ISerializationSurrogate GetSurrogateForCyclicalReference(ISerializationSurrogate innerSurrogate) { if (innerSurrogate == null) - throw new ArgumentNullException("innerSurrogate"); + throw new ArgumentNullException(nameof(innerSurrogate)); Contract.EndContractBlock(); return new SurrogateForCyclicalReference(innerSurrogate); } @@ -459,10 +434,9 @@ namespace System.Runtime.Serialization { **Arguments: **Exceptions: ==============================================================================*/ - [System.Security.SecurityCritical] // auto-generated_required public static Type GetTypeFromAssembly(Assembly assem, String name) { if (assem==null) - throw new ArgumentNullException("assem"); + throw new ArgumentNullException(nameof(assem)); Contract.EndContractBlock(); return assem.GetType(name, false, false); } @@ -499,7 +473,7 @@ namespace System.Runtime.Serialization { internal static string GetClrAssemblyName(Type type, out bool hasTypeForwardedFrom) { if ((object)type == null) { - throw new ArgumentNullException("type"); + throw new ArgumentNullException(nameof(type)); } object[] typeAttributes = type.GetCustomAttributes(typeof(TypeForwardedFromAttribute), false); @@ -566,17 +540,15 @@ namespace System.Runtime.Serialization { internal SurrogateForCyclicalReference(ISerializationSurrogate innerSurrogate) { if (innerSurrogate == null) - throw new ArgumentNullException("innerSurrogate"); + throw new ArgumentNullException(nameof(innerSurrogate)); this.innerSurrogate = innerSurrogate; } - [System.Security.SecurityCritical] // auto-generated public void GetObjectData(Object obj, SerializationInfo info, StreamingContext context) { innerSurrogate.GetObjectData(obj, info, context); } - [System.Security.SecurityCritical] // auto-generated public Object SetObjectData(Object obj, SerializationInfo info, StreamingContext context, ISurrogateSelector selector) { return innerSurrogate.SetObjectData(obj, info, context, selector); diff --git a/src/mscorlib/src/System/Runtime/Serialization/IObjectReference.cs b/src/mscorlib/src/System/Runtime/Serialization/IObjectReference.cs index f1a1bc0590..42662a10f6 100644 --- a/src/mscorlib/src/System/Runtime/Serialization/IObjectReference.cs +++ b/src/mscorlib/src/System/Runtime/Serialization/IObjectReference.cs @@ -22,7 +22,6 @@ namespace System.Runtime.Serialization { // Interface does not need to be marked with the serializable attribute [System.Runtime.InteropServices.ComVisible(true)] public interface IObjectReference { - [System.Security.SecurityCritical] // auto-generated_required Object GetRealObject(StreamingContext context); } } diff --git a/src/mscorlib/src/System/Runtime/Serialization/ISerializable.cs b/src/mscorlib/src/System/Runtime/Serialization/ISerializable.cs index e59fa65043..fc283d41f1 100644 --- a/src/mscorlib/src/System/Runtime/Serialization/ISerializable.cs +++ b/src/mscorlib/src/System/Runtime/Serialization/ISerializable.cs @@ -22,7 +22,6 @@ namespace System.Runtime.Serialization { [System.Runtime.InteropServices.ComVisible(true)] public interface ISerializable { - [System.Security.SecurityCritical] // auto-generated_required void GetObjectData(SerializationInfo info, StreamingContext context); } diff --git a/src/mscorlib/src/System/Runtime/Serialization/ISerializationSurrogate.cs b/src/mscorlib/src/System/Runtime/Serialization/ISerializationSurrogate.cs index 9bb30d99e0..226bbdcc75 100644 --- a/src/mscorlib/src/System/Runtime/Serialization/ISerializationSurrogate.cs +++ b/src/mscorlib/src/System/Runtime/Serialization/ISerializationSurrogate.cs @@ -24,13 +24,11 @@ namespace System.Runtime.Serialization { // Returns a SerializationInfo completely populated with all of the data needed to reinstantiate the // the object at the other end of serialization. // - [System.Security.SecurityCritical] // auto-generated_required void GetObjectData(Object obj, SerializationInfo info, StreamingContext context); // Reinflate the object using all of the information in data. The information in // members is used to find the particular field or property which needs to be set. // - [System.Security.SecurityCritical] // auto-generated_required Object SetObjectData(Object obj, SerializationInfo info, StreamingContext context, ISurrogateSelector selector); } } diff --git a/src/mscorlib/src/System/Runtime/Serialization/ISurrogateSelector.cs b/src/mscorlib/src/System/Runtime/Serialization/ISurrogateSelector.cs index 01b960f86b..87b7845894 100644 --- a/src/mscorlib/src/System/Runtime/Serialization/ISurrogateSelector.cs +++ b/src/mscorlib/src/System/Runtime/Serialization/ISurrogateSelector.cs @@ -22,16 +22,13 @@ namespace System.Runtime.Serialization { // Interface does not need to be marked with the serializable attribute // Specifies the next ISurrogateSelector to be examined for surrogates if the current // instance doesn't have a surrogate for the given type and assembly in the given context. - [System.Security.SecurityCritical] // auto-generated_required void ChainSelector(ISurrogateSelector selector); // Returns the appropriate surrogate for the given type in the given context. - [System.Security.SecurityCritical] // auto-generated_required ISerializationSurrogate GetSurrogate(Type type, StreamingContext context, out ISurrogateSelector selector); // Return the next surrogate in the chain. Returns null if no more exist. - [System.Security.SecurityCritical] // auto-generated_required ISurrogateSelector GetNextSelector(); } } diff --git a/src/mscorlib/src/System/Runtime/Serialization/SafeSerializationManager.cs b/src/mscorlib/src/System/Runtime/Serialization/SafeSerializationManager.cs new file mode 100644 index 0000000000..585d367605 --- /dev/null +++ b/src/mscorlib/src/System/Runtime/Serialization/SafeSerializationManager.cs @@ -0,0 +1,446 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. +using System; +using System.Collections; +using System.Collections.Generic; +using System.Diagnostics.Contracts; +using System.Reflection; +using System.Security; + +namespace System.Runtime.Serialization +{ + // + // #SafeSerialization + // + // Types which are serializable via the ISerializable interface have a problem when it comes to allowing + // transparent subtypes which can allow themselves to serialize since the GetObjectData method is + // SecurityCritical. + // + // For instance, System.Exception implements ISerializable, however it is also desirable to have + // transparent exceptions with their own fields that need to be serialized. (For instance, in transparent + // assemblies such as the DLR and F#, or even in partial trust application code). Since overriding + // GetObjectData requires that the overriding method be security critical, this won't work directly. + // + // SafeSerializationManager solves this problem by allowing any partial trust code to contribute + // individual chunks of serializable data to be included in the serialized version of the derived class. + // These chunks are then deserialized back out of the serialized type and notified that they should + // populate the fields of the deserialized object when serialization is complete. This allows partial + // trust or transparent code to participate in serialization of an ISerializable type without having to + // override GetObjectData or implement the ISerializable constructor. + // + // On the serialization side, SafeSerializationManager has an event SerializeObjectState which it will + // fire in response to serialization in order to gather the units of serializable data that should be + // stored with the rest of the object during serialization. Methods which respond to these events + // create serializable objects which implement the ISafeSerializationData interface and add them to the + // collection of other serialized data by calling AddSerializedState on the SafeSerializationEventArgs + // passed into the event. + // + // By using an event rather than a virtual method on the base ISerializable object, we allow multiple + // potentially untrusted subclasses to participate in serialization, without each one having to ensure + // that it calls up to the base type in order for the whole system to work. (For instance Exception : + // TrustedException : UntrustedException, in this scenario UntrustedException would be able to override + // the virtual method an prevent TrustedException from ever seeing the method call, either accidentally + // or maliciously). + // + // Further, by only allowing additions of new chunks of serialization state rather than exposing the + // whole underlying list, we avoid exposing potentially sensitive serialized state to any of the + // potentially untrusted subclasses. + // + // At deserialization time, SafeSerializationManager performs the reverse operation. It deserializes the + // chunks of serialized state, and then notifies them that the object they belong to is deserialized by + // calling their CompleteSerialization method. In repsonse to this call, the state objects populate the + // fields of the object being deserialized with the state that they held. + // + // From a security perspective, the chunks of serialized state can only contain data that the specific + // subclass itself had access to read (otherwise it wouldn't be able to populate the type with that + // data), as opposed to having access to far more data in the SerializationInfo that GetObjectData uses. + // Similarly, at deserialization time, the serialized state can only modify fields that the type itself + // has access to (again, as opposed to the full SerializationInfo which could be modified). + // + // Individual types which wish to participate in safe serialization do so by containing an instance of a + // SafeSerializationManager and exposing its serialization event. During GetObjectData, the + // SafeSerializationManager is serialized just like any other field of the containing type. However, at + // the end of serialization it is called back one last time to CompleteSerialization. + // + // In CompleteSerialization, if the SafeSerializationManager detects that it has extra chunks of + // data to handle, it substitutes the root type being serialized (formerly the real type hosting the + // SafeSerializationManager) with itself. This allows it to gain more control over the deserialization + // process. It also saves away an extra bit of state in the serialization info indicating the real type + // of object that should be recreated during deserialization. + // + // At this point the serialized state looks like this: + // Data: + // realSerializedData1 + // ... + // realSerializedDataN + // safeSerializationData -> this is the serialization data member of the parent type + // m_serializedState -> list of saved serialized states from subclasses responding to the safe + // serialization event + // RealTypeSerializationName -> type which is using safe serialization + // Type: + // SafeSerializationManager + // + // That is, the serialized data claims to be of type SafeSerializationManager, however contains only the + // data from the real object being serialized along with one bit of safe serialization metadata. + // + // At deserialization time, since the serialized data claims to be of type SafeSerializationManager, the + // root object being created is an instance of the SafeSerializationManager class. However, it detects + // that this isn't a real SafeSerializationManager (by looking for the real type field in the metadata), + // and simply saves away the SerializationInfo and the real type being deserialized. + // + // Since SafeSerializationManager implements IObjectReference, the next step of deserialization is the + // GetRealObject callback. This callback is the one responsible for getting the + // SafeSerializationManager out of the way and instead creating an instance of the actual type which was + // serialized. + // + // It does this by first creating an instance of the real type being deserialzed (saved away in the + // deserialzation constructor), but not running any of its constructors. Instead, it walks the + // inheritance hierarchy (moving toward the most derived type) looking for the last full trust type to + // implement the standard ISerializable constructor before any type does not implement the constructor. + // It is this last type's deserialization constructor which is then invoked, passing in the saved + // SerializationInfo. Once the constructors are run, we return this object as the real deserialized + // object. + // + // The reason that we do this walk is so that ISerializable types can protect themselves from malicious + // input during deserialization by making their deserialization constructors unavailable to partial + // trust code. By not requiring every type have a copy of this constructor, partial trust code can + // participate in safe serialization and not be required to have access to the parent's constructor. + // + // It should be noted however, that this heuristic means that if a full trust type does derive from + // a transparent or partial trust type using this safe serialization mechanism, that full trust type + // will not have its constructor called. Further, the protection of not invoking partial trust + // deserialization constructors only comes into play if SafeSerializationManager is in control of + // deserialization, which means there must be at least one (even empty) safe serialization event + // handler registered. + // + // Another interesting note is that at this point there are now two SafeSerializationManagers alive for + // this deserialization. The first object is the one which is controlling the deserialization and was + // created as the root object of the deserialization. The second one is the object which contains the + // serialized data chunks and is a data member of the real object being deserialized. For this reason, + // the data objects cannot be notified that the deserialization is complete during GetRealObject since + // the ISafeSerializationData objects are not members of the active SafeSerializationManager instance. + // + // The next step is the OnDeserialized callback, which comes to SafeSerializableObject since it was + // pretending to be the root object of the deserialization. It responds to this callback by calling + // any existing OnDeserialized callback on the real type that was deserialized. + // + // The real type needs to call its data member SafeSerializationData object's CompleteDeserialization + // method in response to the OnDeserialized call. This CompleteDeserialization call will then iterate + // through the ISafeSerializationData objects calling each of their CompleteDeserialization methods so + // that they can plug the nearly-complete object with their saved data. + // + // The reason for having a new ISafeSerializationData interface which is basically identical to + // IDeserializationCallback is that IDeserializationCallback will be called on the stored data chunks + // by the serialization code when they are deserialized, and that's not a desirable behavior. + // Essentially, we need to change the meaning of the object parameter to mean "parent object which + // participated in safe serialization", rather than "this object". + // + // Implementing safe serialization on an ISerialiable type is relatively straight forward. (For an + // example, see System.Exception): + // + // 1. Include a data member of type SafeSerializationManager: + // + // private SafeSerializationManager m_safeSerializationManager; + // + // 2. Add a protected SerializeObjectState event, which passes through to the SafeSerializationManager: + // + // protected event EventHandler<SafeSerializationEventArgs> SerializeObjectState + // { + // add { m_safeSerializationManager.SerializeObjectState += value; } + // remove { m_safeSerializationManager.SerializeObjectState -= value; } + // } + // + // 3. Serialize the safe serialization object in GetObjectData, and call its CompleteSerialization method: + // + // { + // info.AddValue("m_safeSerializationManager", m_safeSerializationManager, typeof(SafeSerializationManager)); + // m_safeSerializationManager.CompleteSerialization(this, info, context); + // } + // + // 4. Add an OnDeserialized handler if one doesn't already exist, and call CompleteDeserialization in it: + // + // [OnDeserialized] + // private void OnDeserialized(StreamingContext context) + // { + // m_safeSerializationManager.CompleteDeserialization(this); + // } + // + // On the client side, using safe serialization is also pretty easy. For example: + // + // [Serializable] + // public class TransparentException : Exception + // { + // [Serializable] + // private struct TransparentExceptionState : ISafeSerializationData + // { + // public string m_extraData; + // + // void ISafeSerializationData.CompleteDeserialization(object obj) + // { + // TransparentException exception = obj as TransparentException; + // exception.m_state = this; + // } + // } + // + // [NonSerialized] + // private TransparentExceptionState m_state = new TransparentExceptionState(); + // + // public TransparentException() + // { + // SerializeObjectState += delegate(object exception, SafeSerializationEventArgs eventArgs) + // { + // eventArgs.AddSerializedState(m_state); + // }; + // } + // + // public string ExtraData + // { + // get { return m_state.m_extraData; } + // set { m_state.m_extraData = value; } + // } + // } + // + + // SafeSerializationEventArgs are provided to the delegates which do safe serialization. Each delegate + // serializes its own state into an IDeserializationCallback instance which must, itself, be serializable. + // These indivdiual states are then added to the SafeSerializationEventArgs in order to be saved away when + // the original ISerializable type is serialized. + public sealed class SafeSerializationEventArgs : EventArgs + { + private StreamingContext m_streamingContext; + private List<object> m_serializedStates = new List<object>(); + + internal SafeSerializationEventArgs(StreamingContext streamingContext) + { + m_streamingContext = streamingContext; + } + + public void AddSerializedState(ISafeSerializationData serializedState) + { + if (serializedState == null) + throw new ArgumentNullException(nameof(serializedState)); + if (!serializedState.GetType().IsSerializable) + throw new ArgumentException(Environment.GetResourceString("Serialization_NonSerType", serializedState.GetType(), serializedState.GetType().Assembly.FullName)); + + m_serializedStates.Add(serializedState); + } + + internal IList<object> SerializedStates + { + get { return m_serializedStates; } + } + + public StreamingContext StreamingContext + { + get { return m_streamingContext; } + } + } + + // Interface to be supported by objects which are stored in safe serialization stores + public interface ISafeSerializationData + { + // CompleteDeserialization is called when the object to which the extra serialized data was attached + // has completed its deserialization, and now needs to be populated with the extra data stored in + // this object. + void CompleteDeserialization(object deserialized); + } +#if FEATURE_SERIALIZATION + // Helper class to implement safe serialization. Concrete ISerializable types which want to allow + // transparent subclasses code to participate in serialization should contain an instance of + // SafeSerializationManager and wire up to it as described in code:#SafeSerialization. + [Serializable] + internal sealed class SafeSerializationManager : IObjectReference, ISerializable + { + // Saved states to store in the serialization stream. This is typed as object rather than + // ISafeSerializationData because ISafeSerializationData can't be marked serializable. + private IList<object> m_serializedStates; + + // This is the SerializationInfo that is used when the SafeSerializationManager type has replaced + // itself as the target of serialziation. It is not used directly by the safe serialization code, + // but just held onto so that the real object being deserialzed can use it later. + private SerializationInfo m_savedSerializationInfo; + + // Real object that we've deserialized - this is stored when we complete construction and calling + // the deserialization .ctors on it and is used when we need to notify the stored safe + // deserialization data that they should populate the object with their fields. + private object m_realObject; + + // Real type that should be deserialized + private RuntimeType m_realType; + + // Event fired when we need to collect state to serialize into the parent object + internal event EventHandler<SafeSerializationEventArgs> SerializeObjectState; + + // Name that is used to store the real type being deserialized in the main SerializationInfo + private const string RealTypeSerializationName = "CLR_SafeSerializationManager_RealType"; + + internal SafeSerializationManager() + { + } + + private SafeSerializationManager(SerializationInfo info, StreamingContext context) + { + // We need to determine if we're being called to really deserialize a SafeSerializationManager, + // or if we're being called because we've intercepted the deserialization callback for the real + // object being deserialized. We use the presence of the RealTypeSerializationName field in the + // serialization info to indicate that this is the interception callback and we just need to + // safe the info. If that field is not present, then we should be in a real deserialization + // construction. + RuntimeType realType = info.GetValueNoThrow(RealTypeSerializationName, typeof(RuntimeType)) as RuntimeType; + + if (realType == null) + { + m_serializedStates = info.GetValue("m_serializedStates", typeof(List<object>)) as List<object>; + } + else + { + m_realType = realType; + m_savedSerializationInfo = info; + } + } + + // Determine if the serialization manager is in an active state - that is if any code is hooked up + // to use it for serialization + internal bool IsActive + { + get { return SerializeObjectState != null; } + } + + // CompleteSerialization is called by the base ISerializable in its GetObjectData method. It is + // responsible for gathering up the serialized object state of any delegates that wish to add their + // own state to the serialized object. + internal void CompleteSerialization(object serializedObject, + SerializationInfo info, + StreamingContext context) + { + Contract.Requires(serializedObject != null); + Contract.Requires(info != null); + Contract.Requires(typeof(ISerializable).IsAssignableFrom(serializedObject.GetType())); + Contract.Requires(serializedObject.GetType().IsAssignableFrom(info.ObjectType)); + + // Clear out any stale state + m_serializedStates = null; + + // We only want to kick in our special serialization sauce if someone wants to participate in + // it, otherwise if we have no delegates registered there's no reason for us to get in the way + // of the regular serialization machinery. + EventHandler<SafeSerializationEventArgs> serializeObjectStateEvent = SerializeObjectState; + if (serializeObjectStateEvent != null) + { + // Get any extra data to add to our serialization state now + SafeSerializationEventArgs eventArgs = new SafeSerializationEventArgs(context); + serializeObjectStateEvent(serializedObject, eventArgs); + m_serializedStates = eventArgs.SerializedStates; + + // Replace the type to be deserialized by the standard serialization code paths with + // ourselves, which allows us to control the deserialization process. + info.AddValue(RealTypeSerializationName, serializedObject.GetType(), typeof(RuntimeType)); + info.SetType(typeof(SafeSerializationManager)); + } + } + + // CompleteDeserialization is called by the base ISerializable object's OnDeserialized handler to + // finish the deserialization of the object by notifying the saved states that they should + // re-populate their portions of the deserialized object. + internal void CompleteDeserialization(object deserializedObject) + { + Contract.Requires(deserializedObject != null); + + if (m_serializedStates != null) + { + foreach (ISafeSerializationData serializedState in m_serializedStates) + { + serializedState.CompleteDeserialization(deserializedObject); + } + } + } + + void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context) + { + info.AddValue("m_serializedStates", m_serializedStates, typeof(List<IDeserializationCallback>)); + } + + // GetRealObject intercepts the deserialization process in order to allow deserializing part of the + // object's inheritance heirarchy using standard ISerializable constructors, and the remaining + // portion using the saved serialization states. + object IObjectReference.GetRealObject(StreamingContext context) + { + // If we've already deserialized the real object, use that rather than deserializing it again + if (m_realObject != null) + { + return m_realObject; + } + + // If we don't have a real type to deserialize, then this is really a SafeSerializationManager + // and we don't need to rebuild the object that we're standing in for. + if (m_realType == null) + { + return this; + } + + // Look for the last type in GetRealType's inheritance hierarchy which implements a critical + // deserialization constructor. This will be the object that we use as the deserialization + // construction type to initialize via standard ISerializable semantics + + // First build up the chain starting at the type below Object and working to the real type we + // serialized. + Stack inheritanceChain = new Stack(); + RuntimeType currentType = m_realType; + do + { + inheritanceChain.Push(currentType); + currentType = currentType.BaseType as RuntimeType; + } + while (currentType != typeof(object)); + + // Now look for the first type that does not implement the ISerializable .ctor. When we find + // that, previousType will point at the last type that did implement the .ctor. We require that + // the .ctor we invoke also be non-transparent + RuntimeConstructorInfo serializationCtor = null; + RuntimeType previousType = null; + do + { + previousType = currentType; + currentType = inheritanceChain.Pop() as RuntimeType; + serializationCtor = currentType.GetSerializationCtor(); + } + while (serializationCtor != null && serializationCtor.IsSecurityCritical); + + // previousType is the last type that did implement the deserialization .ctor before the first + // type that did not, so we'll grab it's .ctor to use for deserialization. + BCLDebug.Assert(previousType != null, "We should have at least one inheritance from the base type"); + serializationCtor = ObjectManager.GetConstructor(previousType); + + // Allocate an instance of the final type and run the selected .ctor on that instance to get the + // standard ISerializable initialization done. + object deserialized = FormatterServices.GetUninitializedObject(m_realType); + serializationCtor.SerializationInvoke(deserialized, m_savedSerializationInfo, context); + m_savedSerializationInfo = null; + m_realType = null; + + // Save away the real object that was deserialized so that we can fill it in later, and return + // it back as the object that should result from the final deserialization. + m_realObject = deserialized; + return deserialized; + } + + [OnDeserialized] + private void OnDeserialized(StreamingContext context) + { + // We only need to complete deserialization if we were hooking the deserialization process. If + // we have not deserialized an object in the GetRealObject call, then there's nothing more for + // us to do here. + if (m_realObject != null) + { + // Fire the real object's OnDeserialized method if they registered one. Since we replaced + // ourselves as the target of the deserialization, OnDeserialized on the target won't + // automatically get triggered unless we do it manually. + SerializationEvents cache = SerializationEventsCache.GetSerializationEventsForType(m_realObject.GetType()); + cache.InvokeOnDeserialized(m_realObject, context); + m_realObject = null; + } + } + } +#endif +} diff --git a/src/mscorlib/src/System/Runtime/Serialization/SerializationFieldInfo.cs b/src/mscorlib/src/System/Runtime/Serialization/SerializationFieldInfo.cs index 5e7851bc57..82536ce3b4 100644 --- a/src/mscorlib/src/System/Runtime/Serialization/SerializationFieldInfo.cs +++ b/src/mscorlib/src/System/Runtime/Serialization/SerializationFieldInfo.cs @@ -21,11 +21,9 @@ namespace System.Runtime.Serialization { using System; using System.Reflection; using System.Globalization; + using System.Diagnostics; using System.Diagnostics.Contracts; using System.Threading; -#if FEATURE_REMOTING - using System.Runtime.Remoting.Metadata; -#endif //FEATURE_REMOTING internal sealed class SerializationFieldInfo : FieldInfo { @@ -38,8 +36,8 @@ namespace System.Runtime.Serialization { public override int MetadataToken { get { return m_field.MetadataToken; } } internal SerializationFieldInfo(RuntimeFieldInfo field, String namePrefix) { - Contract.Assert(field!=null, "[SerializationFieldInfo.ctor]field!=null"); - Contract.Assert(namePrefix!=null, "[SerializationFieldInfo.ctor]namePrefix!=null"); + Debug.Assert(field!=null, "[SerializationFieldInfo.ctor]field!=null"); + Debug.Assert(namePrefix!=null, "[SerializationFieldInfo.ctor]namePrefix!=null"); m_field = field; m_serializationName = String.Concat(namePrefix, FakeNameSeparatorString, m_field.Name); @@ -91,7 +89,6 @@ namespace System.Runtime.Serialization { return m_field.GetValue(obj); } - [System.Security.SecurityCritical] internal Object InternalGetValue(Object obj) { RtFieldInfo field = m_field as RtFieldInfo; if (field != null) @@ -107,7 +104,6 @@ namespace System.Runtime.Serialization { m_field.SetValue(obj, value, invokeAttr, binder, culture); } - [System.Security.SecurityCritical] internal void InternalSetValue(Object obj, Object value, BindingFlags invokeAttr, Binder binder, CultureInfo culture) { RtFieldInfo field = m_field as RtFieldInfo; if (field != null) @@ -136,31 +132,5 @@ namespace System.Runtime.Serialization { return m_field.Attributes; } } - -#if FEATURE_REMOTING - #region Legacy Remoting Cache - private RemotingFieldCachedData m_cachedData; - - internal RemotingFieldCachedData RemotingCache - { - get - { - // This grabs an internal copy of m_cachedData and uses - // that instead of looking at m_cachedData directly because - // the cache may get cleared asynchronously. This prevents - // us from having to take a lock. - RemotingFieldCachedData cache = m_cachedData; - if (cache == null) - { - cache = new RemotingFieldCachedData(this); - RemotingFieldCachedData ret = Interlocked.CompareExchange(ref m_cachedData, cache, null); - if (ret != null) - cache = ret; - } - return cache; - } - } - #endregion -#endif //FEATURE_REMOTING } } diff --git a/src/mscorlib/src/System/Runtime/Serialization/SerializationInfo.cs b/src/mscorlib/src/System/Runtime/Serialization/SerializationInfo.cs index 94e6825b51..55909c85fd 100644 --- a/src/mscorlib/src/System/Runtime/Serialization/SerializationInfo.cs +++ b/src/mscorlib/src/System/Runtime/Serialization/SerializationInfo.cs @@ -18,15 +18,11 @@ namespace System.Runtime.Serialization using System.Collections.Generic; using System.Reflection; using System.Runtime.Remoting; -#if FEATURE_REMOTING - using System.Runtime.Remoting.Proxies; -#endif using System.Globalization; + using System.Diagnostics; using System.Diagnostics.Contracts; using System.Security; -#if FEATURE_CORECLR using System.Runtime.CompilerServices; -#endif [System.Runtime.InteropServices.ComVisible(true)] public sealed class SerializationInfo @@ -61,12 +57,12 @@ namespace System.Runtime.Serialization { if ((object)type == null) { - throw new ArgumentNullException("type"); + throw new ArgumentNullException(nameof(type)); } if (converter == null) { - throw new ArgumentNullException("converter"); + throw new ArgumentNullException(nameof(converter)); } Contract.EndContractBlock(); @@ -96,7 +92,7 @@ namespace System.Runtime.Serialization { if (null == value) { - throw new ArgumentNullException("value"); + throw new ArgumentNullException(nameof(value)); } Contract.EndContractBlock(); @@ -111,12 +107,11 @@ namespace System.Runtime.Serialization { return m_assemName; } - [SecuritySafeCritical] set { if (null == value) { - throw new ArgumentNullException("value"); + throw new ArgumentNullException(nameof(value)); } Contract.EndContractBlock(); if (this.requireSameTokenInPartialTrust) @@ -128,12 +123,11 @@ namespace System.Runtime.Serialization } } - [SecuritySafeCritical] public void SetType(Type type) { if ((object)type == null) { - throw new ArgumentNullException("type"); + throw new ArgumentNullException(nameof(type)); } Contract.EndContractBlock(); @@ -170,15 +164,8 @@ namespace System.Runtime.Serialization } } - [SecuritySafeCritical] internal static void DemandForUnsafeAssemblyNameAssignments(string originalAssemblyName, string newAssemblyName) { -#if !FEATURE_CORECLR - if (!IsAssemblyNameAssignmentSafe(originalAssemblyName, newAssemblyName)) - { - CodeAccessPermission.Demand(PermissionType.SecuritySerialization); - } -#endif } internal static bool IsAssemblyNameAssignmentSafe(string originalAssemblyName, string newAssemblyName) @@ -242,7 +229,7 @@ namespace System.Runtime.Serialization private void ExpandArrays() { int newSize; - Contract.Assert(m_members.Length == m_currMember, "[SerializationInfo.ExpandArrays]m_members.Length == m_currMember"); + Debug.Assert(m_members.Length == m_currMember, "[SerializationInfo.ExpandArrays]m_members.Length == m_currMember"); newSize = (m_currMember * 2); @@ -280,12 +267,12 @@ namespace System.Runtime.Serialization { if (null == name) { - throw new ArgumentNullException("name"); + throw new ArgumentNullException(nameof(name)); } if ((object)type == null) { - throw new ArgumentNullException("type"); + throw new ArgumentNullException(nameof(type)); } Contract.EndContractBlock(); @@ -416,19 +403,14 @@ namespace System.Runtime.Serialization **Exceptions: None. All error checking is done with asserts. Although public in coreclr, ** it's not exposed in a contract and is only meant to be used by corefx. ==============================================================================*/ -#if FEATURE_CORECLR // This should not be used by clients: exposing out this functionality would allow children // to overwrite their parent's values. It is public in order to give corefx access to it for // its ObjectManager implementation, but it should not be exposed out of a contract. - public -#else - internal -#endif - void UpdateValue(String name, Object value, Type type) + public void UpdateValue(String name, Object value, Type type) { - Contract.Assert(null != name, "[SerializationInfo.UpdateValue]name!=null"); - Contract.Assert(null != value, "[SerializationInfo.UpdateValue]value!=null"); - Contract.Assert(null != (object)type, "[SerializationInfo.UpdateValue]type!=null"); + Debug.Assert(null != name, "[SerializationInfo.UpdateValue]name!=null"); + Debug.Assert(null != value, "[SerializationInfo.UpdateValue]value!=null"); + Debug.Assert(null != (object)type, "[SerializationInfo.UpdateValue]type!=null"); int index = FindElement(name); if (index < 0) @@ -447,7 +429,7 @@ namespace System.Runtime.Serialization { if (null == name) { - throw new ArgumentNullException("name"); + throw new ArgumentNullException(nameof(name)); } Contract.EndContractBlock(); BCLDebug.Trace("SER", "[SerializationInfo.FindElement]Looking for ", name, " CurrMember is: ", m_currMember); @@ -477,11 +459,11 @@ namespace System.Runtime.Serialization throw new SerializationException(Environment.GetResourceString("Serialization_NotFound", name)); } - Contract.Assert(index < m_data.Length, "[SerializationInfo.GetElement]index<m_data.Length"); - Contract.Assert(index < m_types.Length, "[SerializationInfo.GetElement]index<m_types.Length"); + Debug.Assert(index < m_data.Length, "[SerializationInfo.GetElement]index<m_data.Length"); + Debug.Assert(index < m_types.Length, "[SerializationInfo.GetElement]index<m_types.Length"); foundType = m_types[index]; - Contract.Assert((object)foundType != null, "[SerializationInfo.GetElement]foundType!=null"); + Debug.Assert((object)foundType != null, "[SerializationInfo.GetElement]foundType!=null"); return m_data[index]; } @@ -495,11 +477,11 @@ namespace System.Runtime.Serialization return null; } - Contract.Assert(index < m_data.Length, "[SerializationInfo.GetElement]index<m_data.Length"); - Contract.Assert(index < m_types.Length, "[SerializationInfo.GetElement]index<m_types.Length"); + Debug.Assert(index < m_data.Length, "[SerializationInfo.GetElement]index<m_data.Length"); + Debug.Assert(index < m_types.Length, "[SerializationInfo.GetElement]index<m_types.Length"); foundType = m_types[index]; - Contract.Assert((object)foundType != null, "[SerializationInfo.GetElement]foundType!=null"); + Debug.Assert((object)foundType != null, "[SerializationInfo.GetElement]foundType!=null"); return m_data[index]; } @@ -508,13 +490,12 @@ namespace System.Runtime.Serialization // form requested. // - [System.Security.SecuritySafeCritical] // auto-generated public Object GetValue(String name, Type type) { if ((object)type == null) { - throw new ArgumentNullException("type"); + throw new ArgumentNullException(nameof(type)); } Contract.EndContractBlock(); @@ -526,53 +507,36 @@ namespace System.Runtime.Serialization Object value; value = GetElement(name, out foundType); -#if FEATURE_REMOTING - if (RemotingServices.IsTransparentProxy(value)) + + if (Object.ReferenceEquals(foundType, type) || type.IsAssignableFrom(foundType) || value == null) { - RealProxy proxy = RemotingServices.GetRealProxy(value); - if (RemotingServices.ProxyCheckCast(proxy, rt)) - return value; + return value; } - else -#endif - if (Object.ReferenceEquals(foundType, type) || type.IsAssignableFrom(foundType) || value == null) - { - return value; - } - Contract.Assert(m_converter != null, "[SerializationInfo.GetValue]m_converter!=null"); + Debug.Assert(m_converter != null, "[SerializationInfo.GetValue]m_converter!=null"); return m_converter.Convert(value, type); } - [System.Security.SecuritySafeCritical] // auto-generated [System.Runtime.InteropServices.ComVisible(true)] internal Object GetValueNoThrow(String name, Type type) { Type foundType; Object value; - Contract.Assert((object)type != null, "[SerializationInfo.GetValue]type ==null"); - Contract.Assert(type is RuntimeType, "[SerializationInfo.GetValue]type is not a runtime type"); + Debug.Assert((object)type != null, "[SerializationInfo.GetValue]type ==null"); + Debug.Assert(type is RuntimeType, "[SerializationInfo.GetValue]type is not a runtime type"); value = GetElementNoThrow(name, out foundType); if (value == null) return null; -#if FEATURE_REMOTING - if (RemotingServices.IsTransparentProxy(value)) + + if (Object.ReferenceEquals(foundType, type) || type.IsAssignableFrom(foundType) || value == null) { - RealProxy proxy = RemotingServices.GetRealProxy(value); - if (RemotingServices.ProxyCheckCast(proxy, (RuntimeType)type)) - return value; + return value; } - else -#endif - if (Object.ReferenceEquals(foundType, type) || type.IsAssignableFrom(foundType) || value == null) - { - return value; - } - Contract.Assert(m_converter != null, "[SerializationInfo.GetValue]m_converter!=null"); + Debug.Assert(m_converter != null, "[SerializationInfo.GetValue]m_converter!=null"); return m_converter.Convert(value, type); } diff --git a/src/mscorlib/src/System/Runtime/Serialization/SerializationInfoEnumerator.cs b/src/mscorlib/src/System/Runtime/Serialization/SerializationInfoEnumerator.cs index 6b256a6e1f..32c65492e1 100644 --- a/src/mscorlib/src/System/Runtime/Serialization/SerializationInfoEnumerator.cs +++ b/src/mscorlib/src/System/Runtime/Serialization/SerializationInfoEnumerator.cs @@ -14,6 +14,7 @@ ============================================================*/ namespace System.Runtime.Serialization { using System; + using System.Diagnostics; using System.Collections; using System.Diagnostics.Contracts; @@ -66,13 +67,13 @@ namespace System.Runtime.Serialization { bool m_current; internal SerializationInfoEnumerator(String[] members, Object[] info, Type[] types, int numItems) { - Contract.Assert(members!=null, "[SerializationInfoEnumerator.ctor]members!=null"); - Contract.Assert(info!=null, "[SerializationInfoEnumerator.ctor]info!=null"); - Contract.Assert(types!=null, "[SerializationInfoEnumerator.ctor]types!=null"); - Contract.Assert(numItems>=0, "[SerializationInfoEnumerator.ctor]numItems>=0"); - Contract.Assert(members.Length>=numItems, "[SerializationInfoEnumerator.ctor]members.Length>=numItems"); - Contract.Assert(info.Length>=numItems, "[SerializationInfoEnumerator.ctor]info.Length>=numItems"); - Contract.Assert(types.Length>=numItems, "[SerializationInfoEnumerator.ctor]types.Length>=numItems"); + Debug.Assert(members!=null, "[SerializationInfoEnumerator.ctor]members!=null"); + Debug.Assert(info!=null, "[SerializationInfoEnumerator.ctor]info!=null"); + Debug.Assert(types!=null, "[SerializationInfoEnumerator.ctor]types!=null"); + Debug.Assert(numItems>=0, "[SerializationInfoEnumerator.ctor]numItems>=0"); + Debug.Assert(members.Length>=numItems, "[SerializationInfoEnumerator.ctor]members.Length>=numItems"); + Debug.Assert(info.Length>=numItems, "[SerializationInfoEnumerator.ctor]info.Length>=numItems"); + Debug.Assert(types.Length>=numItems, "[SerializationInfoEnumerator.ctor]types.Length>=numItems"); m_members = members; m_data = info; diff --git a/src/mscorlib/src/System/Runtime/Versioning/BinaryCompatibility.cs b/src/mscorlib/src/System/Runtime/Versioning/BinaryCompatibility.cs deleted file mode 100644 index 99e30b5488..0000000000 --- a/src/mscorlib/src/System/Runtime/Versioning/BinaryCompatibility.cs +++ /dev/null @@ -1,485 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -/*============================================================ -** -** -** -** -** Purpose: This class is used to determine which binary compatibility -** behaviors are enabled at runtime. A type for -** tracking which target Framework an app was built against, or an -** appdomain-wide setting from the host telling us which .NET -** Framework version we should emulate. -** -** -===========================================================*/ -using System; -using System.Diagnostics.Contracts; -using System.Globalization; -using System.Runtime.CompilerServices; - -namespace System.Runtime.Versioning -{ - // Provides a simple way to test whether an application was built against specific .NET Framework - // flavors and versions, with the intent of allowing Framework developers to mimic behavior of older - // Framework releases. This allows us to make behavioral breaking changes in a binary compatible way, - // for an application. This works at the per-AppDomain level, not process nor per-Assembly. - // - // To opt into newer behavior, applications must specify a TargetFrameworkAttribute on their assembly - // saying what version they targeted, or a host must set this when creating an AppDomain. Note - // that command line apps don't have this attribute! - // - // To use this class: - // Developers need to figure out whether they're working on the phone, desktop, or Silverlight, and - // what version they are introducing a breaking change in. Pick one predicate below, and use that - // to decide whether to run the new or old behavior. Example: - // - // if (BinaryCompatibility.TargetsAtLeast_Phone_V7_1) { - // // new behavior for phone 7.1 and other releases where we will integrate this change, like .NET Framework 4.5 - // } - // else { - // // Legacy behavior - // } - // - // If you are making a breaking change in one specific branch that won't be integrated normally to - // all other branches (ie, say you're making breaking changes to Windows Phone 8 after .NET Framework v4.5 - // has locked down for release), then add in specific predicates for each relevant platform. - // - // Maintainers of this class: - // Revisit the table once per release, perhaps at the end of the last coding milestone, to verify a - // default policy saying whether all quirks from a particular flavor & release should be enabled in - // other releases (ie, should all Windows Phone 8.0 quirks be enabled in .NET Framework v5)? - // - // History: - // Here is the order in which releases were made along with some basic integration information. The idea - // is to track what set of compatibility features are present in each other. - // While we cannot guarantee this list is perfectly linear (ie, a feature could be implemented in the last - // few weeks before shipping and make it into only one of three concommittent releases due to triaging), - // this is a good high level summary of code flow. - // - // Desktop Silverlight Windows Phone - // .NET Framework 3.0 -> Silverlight 2 - // .NET Framework 3.5 - // Silverlight 3 - // Silverlight 4 - // .NET Framework 4 Phone 8.0 - // .NET Framework 4.5 Phone 8.1 - // .NET Framework 4.5.1 Phone 8.1 - // - // (Note: Windows Phone 7.0 was built using the .NET Compact Framework, which forked around v1 or v1.1) - // - // Compatibility Policy decisions: - // If we cannot determine that an app was built for a newer .NET Framework (ie, the app has no - // TargetFrameworkAttribute), then quirks will be enabled to emulate older behavior. - // As such, your test code should define the TargetFrameworkAttribute (which VS does for you) - // if you want to see the new behavior! - [FriendAccessAllowed] - internal static class BinaryCompatibility - { - // Use this for new behavior introduced in the phone branch. It will do the right thing for desktop & SL. - [FriendAccessAllowed] - internal static bool TargetsAtLeast_Phone_V7_1 { [FriendAccessAllowed] get { return s_map.TargetsAtLeast_Phone_V7_1; } } - - [FriendAccessAllowed] - internal static bool TargetsAtLeast_Phone_V8_0 { [FriendAccessAllowed] get { return s_map.TargetsAtLeast_Phone_V8_0; } } - - // Use this for new behavior introduced in the Desktop branch. It will do the right thing for Phone & SL. - [FriendAccessAllowed] - internal static bool TargetsAtLeast_Desktop_V4_5 { [FriendAccessAllowed] get { return s_map.TargetsAtLeast_Desktop_V4_5; } } - [FriendAccessAllowed] - internal static bool TargetsAtLeast_Desktop_V4_5_1 { [FriendAccessAllowed] get { return s_map.TargetsAtLeast_Desktop_V4_5_1; } } - [FriendAccessAllowed] - internal static bool TargetsAtLeast_Desktop_V4_5_2 { [FriendAccessAllowed] get { return s_map.TargetsAtLeast_Desktop_V4_5_2; } } - [FriendAccessAllowed] - internal static bool TargetsAtLeast_Desktop_V4_5_3 { [FriendAccessAllowed] get { return s_map.TargetsAtLeast_Desktop_V4_5_3; } } - [FriendAccessAllowed] - internal static bool TargetsAtLeast_Desktop_V4_5_4 { [FriendAccessAllowed] get { return s_map.TargetsAtLeast_Desktop_V4_5_4; } } - - [FriendAccessAllowed] - internal static bool TargetsAtLeast_Desktop_V5_0 { [FriendAccessAllowed] get { return s_map.TargetsAtLeast_Desktop_V5_0; } } - - // Use this for new behavior introduced in the Silverlight branch. It will do the right thing for desktop & Phone. - [FriendAccessAllowed] - internal static bool TargetsAtLeast_Silverlight_V4 { [FriendAccessAllowed] get { return s_map.TargetsAtLeast_Silverlight_V4; } } - [FriendAccessAllowed] - internal static bool TargetsAtLeast_Silverlight_V5 { [FriendAccessAllowed] get { return s_map.TargetsAtLeast_Silverlight_V5; } } - [FriendAccessAllowed] - internal static bool TargetsAtLeast_Silverlight_V6 { [FriendAccessAllowed] get { return s_map.TargetsAtLeast_Silverlight_V6; } } - - [FriendAccessAllowed] - internal static TargetFrameworkId AppWasBuiltForFramework { - [FriendAccessAllowed] - get { - Contract.Ensures(Contract.Result<TargetFrameworkId>() > TargetFrameworkId.NotYetChecked); - - if (s_AppWasBuiltForFramework == TargetFrameworkId.NotYetChecked) - ReadTargetFrameworkId(); - - return s_AppWasBuiltForFramework; - } - } - - // Version number is major * 10000 + minor * 100 + build (ie, 4.5.1.0 would be version 40501). - [FriendAccessAllowed] - internal static int AppWasBuiltForVersion { - [FriendAccessAllowed] - get { - Contract.Ensures(Contract.Result<int>() > 0 || s_AppWasBuiltForFramework == TargetFrameworkId.Unspecified); - - if (s_AppWasBuiltForFramework == TargetFrameworkId.NotYetChecked) - ReadTargetFrameworkId(); - - Contract.Assert(s_AppWasBuiltForFramework != TargetFrameworkId.Unrecognized); - - return s_AppWasBuiltForVersion; - } - } - - #region private - private static TargetFrameworkId s_AppWasBuiltForFramework; - // Version number is major * 10000 + minor * 100 + build (ie, 4.5.1.0 would be version 40501). - private static int s_AppWasBuiltForVersion; - - readonly static BinaryCompatibilityMap s_map = new BinaryCompatibilityMap(); - - // For parsing a target Framework moniker, from the FrameworkName class - private const char c_componentSeparator = ','; - private const char c_keyValueSeparator = '='; - private const char c_versionValuePrefix = 'v'; - private const String c_versionKey = "Version"; - private const String c_profileKey = "Profile"; - - /// <summary> - /// BinaryCompatibilityMap is basically a bitvector. There is a boolean field for each of the - /// properties in BinaryCompatibility - /// </summary> - private sealed class BinaryCompatibilityMap - { - // A bit for each property - internal bool TargetsAtLeast_Phone_V7_1; - internal bool TargetsAtLeast_Phone_V8_0; - internal bool TargetsAtLeast_Phone_V8_1; - internal bool TargetsAtLeast_Desktop_V4_5; - internal bool TargetsAtLeast_Desktop_V4_5_1; - internal bool TargetsAtLeast_Desktop_V4_5_2; - internal bool TargetsAtLeast_Desktop_V4_5_3; - internal bool TargetsAtLeast_Desktop_V4_5_4; - internal bool TargetsAtLeast_Desktop_V5_0; - internal bool TargetsAtLeast_Silverlight_V4; - internal bool TargetsAtLeast_Silverlight_V5; - internal bool TargetsAtLeast_Silverlight_V6; - - internal BinaryCompatibilityMap() - { - AddQuirksForFramework(AppWasBuiltForFramework, AppWasBuiltForVersion); - } - - // The purpose of this method is to capture information about integrations & behavioral compatibility - // between our multiple different release vehicles. IE, if a behavior shows up in Silverlight version 5, - // does it show up in the .NET Framework version 4.5 and Windows Phone 8? - // Version number is major * 10000 + minor * 100 + build (ie, 4.5.1.0 would be version 40501). - private void AddQuirksForFramework(TargetFrameworkId builtAgainstFramework, int buildAgainstVersion) - { - Contract.Requires(buildAgainstVersion > 0 || builtAgainstFramework == TargetFrameworkId.Unspecified); - - switch (builtAgainstFramework) - { - case TargetFrameworkId.NetFramework: - case TargetFrameworkId.NetCore: // Treat Windows 8 tailored apps as normal desktop apps - same product - if (buildAgainstVersion >= 50000) - TargetsAtLeast_Desktop_V5_0 = true; - - // Potential 4.5 servicing releases - if (buildAgainstVersion >= 40504) - TargetsAtLeast_Desktop_V4_5_4 = true; - if (buildAgainstVersion >= 40503) - TargetsAtLeast_Desktop_V4_5_3 = true; - if (buildAgainstVersion >= 40502) - TargetsAtLeast_Desktop_V4_5_2 = true; - if (buildAgainstVersion >= 40501) - TargetsAtLeast_Desktop_V4_5_1 = true; - - if (buildAgainstVersion >= 40500) - { - TargetsAtLeast_Desktop_V4_5 = true; - // On XX/XX/XX we integrated all changes from the phone V7_1 into the branch from which contains Desktop V4_5, thus - // Any application built for V4_5 (or above) should have all the quirks for Phone V7_1 turned on. - AddQuirksForFramework(TargetFrameworkId.Phone, 70100); - // All Silverlight 5 behavior should be in the .NET Framework version 4.5 - AddQuirksForFramework(TargetFrameworkId.Silverlight, 50000); - } - break; - - case TargetFrameworkId.Phone: - if (buildAgainstVersion >= 80000) - { - // This is for Apollo apps. For Apollo apps we don't want to enable any of the 4.5 or 4.5.1 quirks - TargetsAtLeast_Phone_V8_0 = true; - //TargetsAtLeast_Desktop_V4_5 = true; - } - if (buildAgainstVersion >= 80100) - { - // For WindowsPhone 8.1 and SL 8.1 scenarios we want to enable both 4.5 and 4.5.1 quirks. - TargetsAtLeast_Desktop_V4_5 = true; - TargetsAtLeast_Desktop_V4_5_1 = true; - } - - if (buildAgainstVersion >= 710) - TargetsAtLeast_Phone_V7_1 = true; - break; - - case TargetFrameworkId.Silverlight: - if (buildAgainstVersion >= 40000) - TargetsAtLeast_Silverlight_V4 = true; - - if (buildAgainstVersion >= 50000) - TargetsAtLeast_Silverlight_V5 = true; - - if (buildAgainstVersion >= 60000) - { - TargetsAtLeast_Silverlight_V6 = true; - } - break; - - case TargetFrameworkId.Unspecified: - break; - - case TargetFrameworkId.NotYetChecked: - case TargetFrameworkId.Unrecognized: - Contract.Assert(false, "Bad framework kind"); - break; - default: - Contract.Assert(false, "Error: we introduced a new Target Framework but did not update our binary compatibility map"); - break; - } - } - } - - #region String Parsing - - // If this doesn't work, perhaps we could fall back to parsing the metadata version number. - private static bool ParseTargetFrameworkMonikerIntoEnum(String targetFrameworkMoniker, out TargetFrameworkId targetFramework, out int targetFrameworkVersion) - { - Contract.Requires(!String.IsNullOrEmpty(targetFrameworkMoniker)); - - targetFramework = TargetFrameworkId.NotYetChecked; - targetFrameworkVersion = 0; - - String identifier = null; - String profile = null; - ParseFrameworkName(targetFrameworkMoniker, out identifier, out targetFrameworkVersion, out profile); - - switch (identifier) - { - case ".NETFramework": - targetFramework = TargetFrameworkId.NetFramework; - break; - - case ".NETPortable": - targetFramework = TargetFrameworkId.Portable; - break; - - case ".NETCore": - targetFramework = TargetFrameworkId.NetCore; - break; - - case "WindowsPhone": - if (targetFrameworkVersion >= 80100) - { - // A TFM of the form WindowsPhone,Version=v8.1 corresponds to SL 8.1 scenario - // and gets the same quirks as WindowsPhoneApp\v8.1 store apps. - targetFramework = TargetFrameworkId.Phone; - } - else - { - // There is no TFM for Apollo or below and hence we assign the targetFramework to Unspecified. - targetFramework = TargetFrameworkId.Unspecified; - } - break; - - case "WindowsPhoneApp": - targetFramework = TargetFrameworkId.Phone; - break; - - case "Silverlight": - targetFramework = TargetFrameworkId.Silverlight; - // Windows Phone 7 is Silverlight,Version=v4.0,Profile=WindowsPhone - // Windows Phone 7.1 is Silverlight,Version=v4.0,Profile=WindowsPhone71 - if (!String.IsNullOrEmpty(profile)) - { - if (profile == "WindowsPhone") - { - targetFramework = TargetFrameworkId.Phone; - targetFrameworkVersion = 70000; - } - else if (profile == "WindowsPhone71") - { - targetFramework = TargetFrameworkId.Phone; - targetFrameworkVersion = 70100; - } - else if (profile == "WindowsPhone8") - { - targetFramework = TargetFrameworkId.Phone; - targetFrameworkVersion = 80000; - } - else if (profile.StartsWith("WindowsPhone", StringComparison.Ordinal)) - { - Contract.Assert(false, "This is a phone app, but we can't tell what version this is!"); - targetFramework = TargetFrameworkId.Unrecognized; - targetFrameworkVersion = 70100; - } - else - { - Contract.Assert(false, String.Format(CultureInfo.InvariantCulture, "Unrecognized Silverlight profile \"{0}\". What is this, an XBox app?", profile)); - targetFramework = TargetFrameworkId.Unrecognized; - } - } - break; - - default: - Contract.Assert(false, String.Format(CultureInfo.InvariantCulture, "Unrecognized Target Framework Moniker in our Binary Compatibility class. Framework name: \"{0}\"", targetFrameworkMoniker)); - targetFramework = TargetFrameworkId.Unrecognized; - break; - } - - return true; - } - - // This code was a constructor copied from the FrameworkName class, which is located in System.dll. - // Parses strings in the following format: "<identifier>, Version=[v|V]<version>, Profile=<profile>" - // - The identifier and version is required, profile is optional - // - Only three components are allowed. - // - The version string must be in the System.Version format; an optional "v" or "V" prefix is allowed - private static void ParseFrameworkName(String frameworkName, out String identifier, out int version, out String profile) - { - if (frameworkName == null) - { - throw new ArgumentNullException("frameworkName"); - } - if (frameworkName.Length == 0) - { - throw new ArgumentException(Environment.GetResourceString("Argument_StringZeroLength"), "frameworkName"); - } - Contract.EndContractBlock(); - - String[] components = frameworkName.Split(c_componentSeparator); - version = 0; - - // Identifer and Version are required, Profile is optional. - if (components.Length < 2 || components.Length > 3) - { - throw new ArgumentException(Environment.GetResourceString("Argument_FrameworkNameTooShort"), "frameworkName"); - } - - // - // 1) Parse the "Identifier", which must come first. Trim any whitespace - // - identifier = components[0].Trim(); - - if (identifier.Length == 0) - { - throw new ArgumentException(Environment.GetResourceString("Argument_FrameworkNameInvalid"), "frameworkName"); - } - - bool versionFound = false; - profile = null; - - // - // The required "Version" and optional "Profile" component can be in any order - // - for (int i = 1; i < components.Length; i++) - { - // Get the key/value pair separated by '=' - string[] keyValuePair = components[i].Split(c_keyValueSeparator); - - if (keyValuePair.Length != 2) - { - throw new ArgumentException(Environment.GetResourceString("SR.Argument_FrameworkNameInvalid"), "frameworkName"); - } - - // Get the key and value, trimming any whitespace - string key = keyValuePair[0].Trim(); - string value = keyValuePair[1].Trim(); - - // - // 2) Parse the required "Version" key value - // - if (key.Equals(c_versionKey, StringComparison.OrdinalIgnoreCase)) - { - versionFound = true; - - // Allow the version to include a 'v' or 'V' prefix... - if (value.Length > 0 && (value[0] == c_versionValuePrefix || value[0] == 'V')) - { - value = value.Substring(1); - } - Version realVersion = new Version(value); - // The version class will represent some unset values as -1 internally (instead of 0). - version = realVersion.Major * 10000; - if (realVersion.Minor > 0) - version += realVersion.Minor * 100; - if (realVersion.Build > 0) - version += realVersion.Build; - } - // - // 3) Parse the optional "Profile" key value - // - else if (key.Equals(c_profileKey, StringComparison.OrdinalIgnoreCase)) - { - if (!String.IsNullOrEmpty(value)) - { - profile = value; - } - } - else - { - throw new ArgumentException(Environment.GetResourceString("Argument_FrameworkNameInvalid"), "frameworkName"); - } - } - - if (!versionFound) - { - throw new ArgumentException(Environment.GetResourceString("Argument_FrameworkNameMissingVersion"), "frameworkName"); - } - } - - [System.Security.SecuritySafeCritical] - private static void ReadTargetFrameworkId() - { - String targetFrameworkName = AppDomain.CurrentDomain.GetTargetFrameworkName(); - - var overrideValue = System.Runtime.Versioning.CompatibilitySwitch.GetValueInternal("TargetFrameworkMoniker"); - if (!string.IsNullOrEmpty(overrideValue)) - { - targetFrameworkName = overrideValue; - } - - // Write to a local then to _targetFramework, after writing the version number. - TargetFrameworkId fxId; - int fxVersion = 0; - if (targetFrameworkName == null) - { -#if FEATURE_CORECLR - // if we don't have a value for targetFrameworkName we need to figure out if we should give the newest behavior or not. - if (CompatibilitySwitches.UseLatestBehaviorWhenTFMNotSpecified) - { - fxId = TargetFrameworkId.NetFramework; - fxVersion = 50000; // We are going to default to the latest value for version that we have in our code. - } - else -#endif - fxId = TargetFrameworkId.Unspecified; - } - else if (!ParseTargetFrameworkMonikerIntoEnum(targetFrameworkName, out fxId, out fxVersion)) - fxId = TargetFrameworkId.Unrecognized; - - s_AppWasBuiltForFramework = fxId; - s_AppWasBuiltForVersion = fxVersion; - } - #endregion String Parsing - - #endregion private - } -} diff --git a/src/mscorlib/src/System/Runtime/Versioning/CompatibilitySwitch.cs b/src/mscorlib/src/System/Runtime/Versioning/CompatibilitySwitch.cs index b06c42437c..6bf8f8cf45 100644 --- a/src/mscorlib/src/System/Runtime/Versioning/CompatibilitySwitch.cs +++ b/src/mscorlib/src/System/Runtime/Versioning/CompatibilitySwitch.cs @@ -21,13 +21,11 @@ namespace System.Runtime.Versioning * * These apis are for internal use only for FX assmeblies. It has not been decided if they can be used by OOB components due to EULA restrictions */ - [System.Security.SecurityCritical] public static bool IsEnabled(string compatibilitySwitchName) { return IsEnabledInternalCall(compatibilitySwitchName, true); } - [System.Security.SecurityCritical] public static string GetValue(string compatibilitySwitchName) { // This is used by AppContext.TryGetSwitch to check switch overrides in the Windows Quirk DB @@ -36,19 +34,16 @@ namespace System.Runtime.Versioning return GetValueInternalCall(compatibilitySwitchName, true); } - [System.Security.SecurityCritical] internal static bool IsEnabledInternal(string compatibilitySwitchName) { return IsEnabledInternalCall(compatibilitySwitchName, false); } - [System.Security.SecurityCritical] internal static string GetValueInternal(string compatibilitySwitchName) { return GetValueInternalCall(compatibilitySwitchName, false); } - [System.Security.SecurityCritical] [MethodImpl(MethodImplOptions.InternalCall)] internal static extern string GetAppContextOverridesInternalCall(); diff --git a/src/mscorlib/src/System/Runtime/Versioning/ComponentGuaranteesAttribute.cs b/src/mscorlib/src/System/Runtime/Versioning/ComponentGuaranteesAttribute.cs deleted file mode 100644 index 0f906d518a..0000000000 --- a/src/mscorlib/src/System/Runtime/Versioning/ComponentGuaranteesAttribute.cs +++ /dev/null @@ -1,44 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -/*============================================================ -** -** -** -** Purpose: Tracking whether a component signs up for a -** a strong contract spanning multiple versions. -** -===========================================================*/ -using System; - -namespace System.Runtime.Versioning { - - [Flags] - [Serializable] - public enum ComponentGuaranteesOptions - { - None = 0, - Exchange = 0x1, - Stable = 0x2, - SideBySide = 0x4, - } - - [AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Module | AttributeTargets.Class | - AttributeTargets.Struct | AttributeTargets.Interface | AttributeTargets.Delegate | - AttributeTargets.Enum | AttributeTargets.Method | AttributeTargets.Property | - AttributeTargets.Constructor | AttributeTargets.Event, - AllowMultiple = false, Inherited = false)] - public sealed class ComponentGuaranteesAttribute : Attribute { - private ComponentGuaranteesOptions _guarantees; - - public ComponentGuaranteesAttribute(ComponentGuaranteesOptions guarantees) - { - _guarantees = guarantees; - } - - public ComponentGuaranteesOptions Guarantees { - get { return _guarantees; } - } - } -} diff --git a/src/mscorlib/src/System/Runtime/Versioning/ResourceAttributes.cs b/src/mscorlib/src/System/Runtime/Versioning/ResourceAttributes.cs deleted file mode 100644 index 78a9ddbd07..0000000000 --- a/src/mscorlib/src/System/Runtime/Versioning/ResourceAttributes.cs +++ /dev/null @@ -1,237 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -/*============================================================ -** -** Purpose: Resource annotation rules. -** -===========================================================*/ -using System; -using System.Diagnostics; -using System.Globalization; -using System.Runtime.CompilerServices; -using System.Text; -using Microsoft.Win32; -using System.Diagnostics.Contracts; - -namespace System.Runtime.Versioning -{ - [AttributeUsage(AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Constructor, Inherited = false)] - [Conditional("RESOURCE_ANNOTATION_WORK")] - public sealed class ResourceConsumptionAttribute : Attribute - { - private ResourceScope _consumptionScope; - private ResourceScope _resourceScope; - - public ResourceConsumptionAttribute(ResourceScope resourceScope) - { - _resourceScope = resourceScope; - _consumptionScope = _resourceScope; - } - - public ResourceConsumptionAttribute(ResourceScope resourceScope, ResourceScope consumptionScope) - { - _resourceScope = resourceScope; - _consumptionScope = consumptionScope; - } - - public ResourceScope ResourceScope { - get { return _resourceScope; } - } - - public ResourceScope ConsumptionScope { - get { return _consumptionScope; } - } - } - - [AttributeUsage(AttributeTargets.Method | AttributeTargets.Field | AttributeTargets.Property | AttributeTargets.Constructor, Inherited = false)] - [Conditional("RESOURCE_ANNOTATION_WORK")] - public sealed class ResourceExposureAttribute : Attribute - { - private ResourceScope _resourceExposureLevel; - - public ResourceExposureAttribute(ResourceScope exposureLevel) - { - _resourceExposureLevel = exposureLevel; - } - - public ResourceScope ResourceExposureLevel { - get { return _resourceExposureLevel; } - } - } - - - // Default visibility is Public, which isn't specified in this enum. - // Public == the lack of Private or Assembly - // Does this actually work? Need to investigate that. - [Flags] - public enum ResourceScope - { - None = 0, - // Resource type - Machine = 0x1, - Process = 0x2, - AppDomain = 0x4, - Library = 0x8, - // Visibility - Private = 0x10, // Private to this one class. - Assembly = 0x20, // Assembly-level, like C#'s "internal" - } - - - [Flags] - internal enum SxSRequirements - { - None = 0, - AppDomainID = 0x1, - ProcessID = 0x2, - CLRInstanceID = 0x4, // for multiple CLR's within the process - AssemblyName = 0x8, - TypeName = 0x10 - } - - public static class VersioningHelper - { - // These depend on the exact values given to members of the ResourceScope enum. - private const ResourceScope ResTypeMask = ResourceScope.Machine | ResourceScope.Process | ResourceScope.AppDomain | ResourceScope.Library; - private const ResourceScope VisibilityMask = ResourceScope.Private | ResourceScope.Assembly; - - [System.Security.SecuritySafeCritical] - [MethodImpl(MethodImplOptions.InternalCall)] - private static extern int GetRuntimeId(); - - public static String MakeVersionSafeName(String name, ResourceScope from, ResourceScope to) - { - return MakeVersionSafeName(name, from, to, null); - } - - [System.Security.SecuritySafeCritical] // auto-generated - public static String MakeVersionSafeName(String name, ResourceScope from, ResourceScope to, Type type) - { - ResourceScope fromResType = from & ResTypeMask; - ResourceScope toResType = to & ResTypeMask; - if (fromResType > toResType) - throw new ArgumentException(Environment.GetResourceString("Argument_ResourceScopeWrongDirection", fromResType, toResType), "from"); - - SxSRequirements requires = GetRequirements(to, from); - - if ((requires & (SxSRequirements.AssemblyName | SxSRequirements.TypeName)) != 0 && type == null) - throw new ArgumentNullException("type", Environment.GetResourceString("ArgumentNull_TypeRequiredByResourceScope")); - - // Add in process ID, CLR base address, and appdomain ID's. Also, use a character identifier - // to ensure that these can never accidentally overlap (ie, you create enough appdomains and your - // appdomain ID might equal your process ID). - StringBuilder safeName = new StringBuilder(name); - char separator = '_'; - if ((requires & SxSRequirements.ProcessID) != 0) { - safeName.Append(separator); - safeName.Append('p'); - safeName.Append(Win32Native.GetCurrentProcessId()); - } - if ((requires & SxSRequirements.CLRInstanceID) != 0) { - String clrID = GetCLRInstanceString(); - safeName.Append(separator); - safeName.Append('r'); - safeName.Append(clrID); - } - if ((requires & SxSRequirements.AppDomainID) != 0) { - safeName.Append(separator); - safeName.Append("ad"); - safeName.Append(AppDomain.CurrentDomain.Id); - } - if ((requires & SxSRequirements.TypeName) != 0) { - safeName.Append(separator); - safeName.Append(type.Name); - } - if ((requires & SxSRequirements.AssemblyName) != 0) { - safeName.Append(separator); - safeName.Append(type.Assembly.FullName); - } - return safeName.ToString(); - } - - private static String GetCLRInstanceString() - { - int id = GetRuntimeId(); - return id.ToString(CultureInfo.InvariantCulture); - } - - private static SxSRequirements GetRequirements(ResourceScope consumeAsScope, ResourceScope calleeScope) - { - SxSRequirements requires = SxSRequirements.None; - - switch(calleeScope & ResTypeMask) { - case ResourceScope.Machine: - switch(consumeAsScope & ResTypeMask) { - case ResourceScope.Machine: - // No work - break; - - case ResourceScope.Process: - requires |= SxSRequirements.ProcessID; - break; - - case ResourceScope.AppDomain: - requires |= SxSRequirements.AppDomainID | SxSRequirements.CLRInstanceID | SxSRequirements.ProcessID; - break; - - default: - throw new ArgumentException(Environment.GetResourceString("Argument_BadResourceScopeTypeBits", consumeAsScope), "consumeAsScope"); - } - break; - - case ResourceScope.Process: - if ((consumeAsScope & ResourceScope.AppDomain) != 0) - requires |= SxSRequirements.AppDomainID | SxSRequirements.CLRInstanceID; - break; - - case ResourceScope.AppDomain: - // No work - break; - - default: - throw new ArgumentException(Environment.GetResourceString("Argument_BadResourceScopeTypeBits", calleeScope), "calleeScope"); - } - - switch(calleeScope & VisibilityMask) { - case ResourceScope.None: // Public - implied - switch(consumeAsScope & VisibilityMask) { - case ResourceScope.None: // Public - implied - // No work - break; - - case ResourceScope.Assembly: - requires |= SxSRequirements.AssemblyName; - break; - - case ResourceScope.Private: - requires |= SxSRequirements.TypeName | SxSRequirements.AssemblyName; - break; - - default: - throw new ArgumentException(Environment.GetResourceString("Argument_BadResourceScopeVisibilityBits", consumeAsScope), "consumeAsScope"); - } - break; - - case ResourceScope.Assembly: - if ((consumeAsScope & ResourceScope.Private) != 0) - requires |= SxSRequirements.TypeName; - break; - - case ResourceScope.Private: - // No work - break; - - default: - throw new ArgumentException(Environment.GetResourceString("Argument_BadResourceScopeVisibilityBits", calleeScope), "calleeScope"); - } - - if (consumeAsScope == calleeScope) { - Contract.Assert(requires == SxSRequirements.None, "Computed a strange set of required resource scoping. It's probably wrong."); - } - - return requires; - } - } -} diff --git a/src/mscorlib/src/System/Runtime/Versioning/TargetFrameworkAttribute.cs b/src/mscorlib/src/System/Runtime/Versioning/TargetFrameworkAttribute.cs index dbf98c08d8..600ba3f154 100644 --- a/src/mscorlib/src/System/Runtime/Versioning/TargetFrameworkAttribute.cs +++ b/src/mscorlib/src/System/Runtime/Versioning/TargetFrameworkAttribute.cs @@ -26,7 +26,7 @@ namespace System.Runtime.Versioning { public TargetFrameworkAttribute(String frameworkName) { if (frameworkName == null) - throw new ArgumentNullException("frameworkName"); + throw new ArgumentNullException(nameof(frameworkName)); Contract.EndContractBlock(); _frameworkName = frameworkName; } |