diff options
Diffstat (limited to 'src/mscorlib/src/System/Runtime')
171 files changed, 2702 insertions, 4485 deletions
diff --git a/src/mscorlib/src/System/Runtime/CompilerServices/AccessedThroughPropertyAttribute.cs b/src/mscorlib/src/System/Runtime/CompilerServices/AccessedThroughPropertyAttribute.cs deleted file mode 100644 index 34e66beade..0000000000 --- a/src/mscorlib/src/System/Runtime/CompilerServices/AccessedThroughPropertyAttribute.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 -{ - using System; - - [AttributeUsage(AttributeTargets.Field)] - public sealed class AccessedThroughPropertyAttribute : Attribute - { - private readonly string propertyName; - - public AccessedThroughPropertyAttribute(string propertyName) - { - this.propertyName = propertyName; - } - - public string PropertyName - { - get - { - return propertyName; - } - } - } -} - diff --git a/src/mscorlib/src/System/Runtime/CompilerServices/AssemblySettingAttributes.cs b/src/mscorlib/src/System/Runtime/CompilerServices/AssemblySettingAttributes.cs deleted file mode 100644 index 5251122629..0000000000 --- a/src/mscorlib/src/System/Runtime/CompilerServices/AssemblySettingAttributes.cs +++ /dev/null @@ -1,94 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -//////////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////////// - -namespace System.Runtime.CompilerServices -{ - - using System; - using System.Runtime.InteropServices; - - /* - NGenHint is not supported in Whidbey - - [Serializable] - public enum NGenHint - { - Default = 0x0000, // No preference specified - - Eager = 0x0001, // NGen at install time - Lazy = 0x0002, // NGen after install time - Never = 0x0003, // Assembly should not be ngened - } - */ - - [Serializable] - public enum LoadHint - { - Default = 0x0000, // No preference specified - - Always = 0x0001, // Dependency is always loaded - Sometimes = 0x0002, // Dependency is sometimes loaded - //Never = 0x0003, // Dependency is never loaded - } - - [Serializable] - [AttributeUsage(AttributeTargets.Assembly)] - public sealed class DefaultDependencyAttribute : Attribute - { - private LoadHint loadHint; - - public DefaultDependencyAttribute ( - LoadHint loadHintArgument - ) - { - loadHint = loadHintArgument; - } - - public LoadHint LoadHint - { - get - { - return loadHint; - } - } - } - - -[Serializable] -[AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)] - public sealed class DependencyAttribute : Attribute - { - private String dependentAssembly; - private LoadHint loadHint; - - public DependencyAttribute ( - String dependentAssemblyArgument, - LoadHint loadHintArgument - ) - { - dependentAssembly = dependentAssemblyArgument; - loadHint = loadHintArgument; - } - - public String DependentAssembly - { - get - { - return dependentAssembly; - } - } - - public LoadHint LoadHint - { - get - { - return loadHint; - } - } - } -} - diff --git a/src/mscorlib/src/System/Runtime/CompilerServices/AsyncMethodBuilder.cs b/src/mscorlib/src/System/Runtime/CompilerServices/AsyncMethodBuilder.cs index afb0c22778..fc7a7f01a3 100644 --- a/src/mscorlib/src/System/Runtime/CompilerServices/AsyncMethodBuilder.cs +++ b/src/mscorlib/src/System/Runtime/CompilerServices/AsyncMethodBuilder.cs @@ -63,7 +63,7 @@ namespace System.Runtime.CompilerServices // See comment on AsyncMethodBuilderCore.Start // AsyncMethodBuilderCore.Start(ref stateMachine); - if (stateMachine == null) throw new ArgumentNullException(nameof(stateMachine)); + if (stateMachine == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.stateMachine); Contract.EndContractBlock(); // Run the MoveNext method within a copy-on-write ExecutionContext scope. @@ -72,7 +72,6 @@ namespace System.Runtime.CompilerServices Thread currentThread = Thread.CurrentThread; ExecutionContextSwitcher ecs = default(ExecutionContextSwitcher); - RuntimeHelpers.PrepareConstrainedRegions(); try { ExecutionContext.EstablishCopyOnWriteScope(currentThread, ref ecs); @@ -240,15 +239,8 @@ namespace System.Runtime.CompilerServices } } - // This property lazily instantiates the Task in a non-thread-safe manner. - private Task Task - { - get - { - if (m_task == null) m_task = new Task(); - return m_task; - } - } + /// <summary>Lazily instantiate the Task in a non-thread-safe manner.</summary> + private Task Task => m_task ?? (m_task = new Task()); /// <summary> /// Gets an object that may be used to uniquely identify this builder to the debugger. @@ -295,7 +287,7 @@ namespace System.Runtime.CompilerServices // See comment on AsyncMethodBuilderCore.Start // AsyncMethodBuilderCore.Start(ref stateMachine); - if (stateMachine == null) throw new ArgumentNullException(nameof(stateMachine)); + if (stateMachine == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.stateMachine); Contract.EndContractBlock(); // Run the MoveNext method within a copy-on-write ExecutionContext scope. @@ -304,7 +296,6 @@ namespace System.Runtime.CompilerServices Thread currentThread = Thread.CurrentThread; ExecutionContextSwitcher ecs = default(ExecutionContextSwitcher); - RuntimeHelpers.PrepareConstrainedRegions(); try { ExecutionContext.EstablishCopyOnWriteScope(currentThread, ref ecs); @@ -358,7 +349,11 @@ namespace System.Runtime.CompilerServices /// <summary>Gets the <see cref="System.Threading.Tasks.Task"/> for this builder.</summary> /// <returns>The <see cref="System.Threading.Tasks.Task"/> representing the builder's asynchronous operation.</returns> /// <exception cref="System.InvalidOperationException">The builder is not initialized.</exception> - public Task Task { get { return m_builder.Task; } } + public Task Task + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get { return m_builder.Task; } + } /// <summary> /// Completes the <see cref="System.Threading.Tasks.Task"/> in the @@ -449,7 +444,7 @@ namespace System.Runtime.CompilerServices // See comment on AsyncMethodBuilderCore.Start // AsyncMethodBuilderCore.Start(ref stateMachine); - if (stateMachine == null) throw new ArgumentNullException(nameof(stateMachine)); + if (stateMachine == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.stateMachine); Contract.EndContractBlock(); // Run the MoveNext method within a copy-on-write ExecutionContext scope. @@ -458,7 +453,6 @@ namespace System.Runtime.CompilerServices Thread currentThread = Thread.CurrentThread; ExecutionContextSwitcher ecs = default(ExecutionContextSwitcher); - RuntimeHelpers.PrepareConstrainedRegions(); try { ExecutionContext.EstablishCopyOnWriteScope(currentThread, ref ecs); @@ -502,7 +496,7 @@ namespace System.Runtime.CompilerServices { // Force the Task to be initialized prior to the first suspending await so // that the original stack-based builder has a reference to the right Task. - var builtTask = this.Task; + Task builtTask = this.Task; // Box the state machine, then tell the boxed instance to call back into its own builder, // so we can cache the boxed reference. NOTE: The language compiler may choose to use @@ -542,7 +536,7 @@ namespace System.Runtime.CompilerServices { // Force the Task to be initialized prior to the first suspending await so // that the original stack-based builder has a reference to the right Task. - var builtTask = this.Task; + Task<TResult> builtTask = this.Task; // Box the state machine, then tell the boxed instance to call back into its own builder, // so we can cache the boxed reference. NOTE: The language compiler may choose to use @@ -563,15 +557,14 @@ namespace System.Runtime.CompilerServices /// <returns>The <see cref="System.Threading.Tasks.Task{TResult}"/> representing the builder's asynchronous operation.</returns> public Task<TResult> Task { - get - { - // Get and return the task. If there isn't one, first create one and store it. - var task = m_task; - if (task == null) { m_task = task = new Task<TResult>(); } - return task; - } + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get { return m_task ?? InitializeTask(); } } + /// <summary>Initializes the task, which must not yet be initialized.</summary> + [MethodImpl(MethodImplOptions.NoInlining)] + private Task<TResult> InitializeTask() => (m_task = new Task<TResult>()); + /// <summary> /// Completes the <see cref="System.Threading.Tasks.Task{TResult}"/> in the /// <see cref="System.Threading.Tasks.TaskStatus">RanToCompletion</see> state with the specified result. @@ -582,28 +575,49 @@ namespace System.Runtime.CompilerServices { // Get the currently stored task, which will be non-null if get_Task has already been accessed. // If there isn't one, get a task and store it. - var task = m_task; - if (task == null) + if (m_task == null) { m_task = GetTaskForResult(result); Debug.Assert(m_task != null, "GetTaskForResult should never return null"); } - // Slow path: complete the existing task. else { - if (AsyncCausalityTracer.LoggingOn) - AsyncCausalityTracer.TraceOperationCompletion(CausalityTraceLevel.Required, task.Id, AsyncCausalityStatus.Completed); + // Slow path: complete the existing task. + SetExistingTaskResult(result); + } + } - //only log if we have a real task that was previously created - if (System.Threading.Tasks.Task.s_asyncDebuggingEnabled) - { - System.Threading.Tasks.Task.RemoveFromActiveTasks(task.Id); - } + /// <summary>Completes the already initialized task with the specified result.</summary> + /// <param name="result">The result to use to complete the task.</param> + private void SetExistingTaskResult(TResult result) + { + Debug.Assert(m_task != null, "Expected non-null task"); - if (!task.TrySetResult(result)) - { - throw new InvalidOperationException(Environment.GetResourceString("TaskT_TransitionToFinal_AlreadyCompleted")); - } + if (AsyncCausalityTracer.LoggingOn || System.Threading.Tasks.Task.s_asyncDebuggingEnabled) + { + LogExistingTaskCompletion(); + } + + if (!m_task.TrySetResult(result)) + { + ThrowHelper.ThrowInvalidOperationException(ExceptionResource.TaskT_TransitionToFinal_AlreadyCompleted); + } + } + + /// <summary>Handles logging for the successful completion of an operation.</summary> + private void LogExistingTaskCompletion() + { + Debug.Assert(m_task != null); + + if (AsyncCausalityTracer.LoggingOn) + { + AsyncCausalityTracer.TraceOperationCompletion(CausalityTraceLevel.Required, m_task.Id, AsyncCausalityStatus.Completed); + } + + // only log if we have a real task that was previously created + if (System.Threading.Tasks.Task.s_asyncDebuggingEnabled) + { + System.Threading.Tasks.Task.RemoveFromActiveTasks(m_task.Id); } } @@ -620,15 +634,14 @@ namespace System.Runtime.CompilerServices // Get the currently stored task, which will be non-null if get_Task has already been accessed. // If there isn't one, store the supplied completed task. - var task = m_task; - if (task == null) + if (m_task == null) { m_task = completedTask; } else { // Otherwise, complete the task that's there. - SetResult(default(TResult)); + SetExistingTaskResult(default(TResult)); } } @@ -667,7 +680,7 @@ namespace System.Runtime.CompilerServices if (!successfullySet) { - throw new InvalidOperationException(Environment.GetResourceString("TaskT_TransitionToFinal_AlreadyCompleted")); + ThrowHelper.ThrowInvalidOperationException(ExceptionResource.TaskT_TransitionToFinal_AlreadyCompleted); } } @@ -704,6 +717,7 @@ 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> + [MethodImpl(MethodImplOptions.AggressiveInlining)] // method looks long, but for a given TResult it results in a relatively small amount of asm private Task<TResult> GetTaskForResult(TResult result) { Contract.Ensures( @@ -846,9 +860,9 @@ 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(nameof(stateMachine)); + if (stateMachine == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.stateMachine); Contract.EndContractBlock(); - if (m_stateMachine != null) throw new InvalidOperationException(Environment.GetResourceString("AsyncMethodBuilder_InstanceNotInitialized")); + if (m_stateMachine != null) ThrowHelper.ThrowInvalidOperationException(ExceptionResource.AsyncMethodBuilder_InstanceNotInitialized); m_stateMachine = stateMachine; } @@ -1104,12 +1118,12 @@ namespace System.Runtime.CompilerServices return action; } - ///<summary> - /// Given an action, see if it is a contiunation wrapper and has a Task associated with it. If so return it (null otherwise) - ///</summary> + ///<summary> + /// Given an action, see if it is a contiunation wrapper and has a Task associated with it. If so return it (null otherwise) + ///</summary> internal static Task TryGetContinuationTask(Action action) { - if (action != null) + if (action != null) { var asWrapper = action.Target as ContinuationWrapper; if (asWrapper != null) diff --git a/src/mscorlib/src/System/Runtime/CompilerServices/AsyncStateMachineAttribute.cs b/src/mscorlib/src/System/Runtime/CompilerServices/AsyncStateMachineAttribute.cs deleted file mode 100644 index f1fc9ced82..0000000000 --- a/src/mscorlib/src/System/Runtime/CompilerServices/AsyncStateMachineAttribute.cs +++ /dev/null @@ -1,18 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - - -using System; - -namespace System.Runtime.CompilerServices -{ - [Serializable, AttributeUsage(AttributeTargets.Method, Inherited = false, AllowMultiple = false)] - public sealed class AsyncStateMachineAttribute : StateMachineAttribute - { - public AsyncStateMachineAttribute(Type stateMachineType) - : base(stateMachineType) - { - } - } -} diff --git a/src/mscorlib/src/System/Runtime/CompilerServices/CallerFilePathAttribute.cs b/src/mscorlib/src/System/Runtime/CompilerServices/CallerFilePathAttribute.cs deleted file mode 100644 index 330934cf95..0000000000 --- a/src/mscorlib/src/System/Runtime/CompilerServices/CallerFilePathAttribute.cs +++ /dev/null @@ -1,17 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - - -using System; - -namespace System.Runtime.CompilerServices -{ - [AttributeUsage(AttributeTargets.Parameter, Inherited = false)] - public sealed class CallerFilePathAttribute : Attribute - { - public CallerFilePathAttribute() - { - } - } -} diff --git a/src/mscorlib/src/System/Runtime/CompilerServices/CallerLineNumberAttribute.cs b/src/mscorlib/src/System/Runtime/CompilerServices/CallerLineNumberAttribute.cs deleted file mode 100644 index 9c87e8e25f..0000000000 --- a/src/mscorlib/src/System/Runtime/CompilerServices/CallerLineNumberAttribute.cs +++ /dev/null @@ -1,17 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - - -using System; - -namespace System.Runtime.CompilerServices -{ - [AttributeUsage(AttributeTargets.Parameter, Inherited = false)] - public sealed class CallerLineNumberAttribute : Attribute - { - public CallerLineNumberAttribute() - { - } - } -} diff --git a/src/mscorlib/src/System/Runtime/CompilerServices/CallerMemberNameAttribute.cs b/src/mscorlib/src/System/Runtime/CompilerServices/CallerMemberNameAttribute.cs deleted file mode 100644 index 4fc70908fb..0000000000 --- a/src/mscorlib/src/System/Runtime/CompilerServices/CallerMemberNameAttribute.cs +++ /dev/null @@ -1,17 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - - -using System; - -namespace System.Runtime.CompilerServices -{ - [AttributeUsage(AttributeTargets.Parameter, Inherited = false)] - public sealed class CallerMemberNameAttribute : Attribute - { - public CallerMemberNameAttribute() - { - } - } -} diff --git a/src/mscorlib/src/System/Runtime/CompilerServices/CompilationRelaxations.cs b/src/mscorlib/src/System/Runtime/CompilerServices/CompilationRelaxations.cs deleted file mode 100644 index c3679b610c..0000000000 --- a/src/mscorlib/src/System/Runtime/CompilerServices/CompilationRelaxations.cs +++ /dev/null @@ -1,50 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -//////////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////////// - -namespace System.Runtime.CompilerServices -{ - - using System; - - /// IMPORTANT: Keep this in sync with corhdr.h -[Serializable] -[Flags] - public enum CompilationRelaxations : int - { - NoStringInterning = 0x0008, // Start in 0x0008, we had other non public flags in this enum before, - // so we'll start here just in case somebody used them. This flag is only - // valid when set for Assemblies. - }; - -[Serializable] -[AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Module | AttributeTargets.Class | AttributeTargets.Method)] - public class CompilationRelaxationsAttribute : Attribute - { - private int m_relaxations; // The relaxations. - - public CompilationRelaxationsAttribute ( - int relaxations) - { - m_relaxations = relaxations; - } - - public CompilationRelaxationsAttribute ( - CompilationRelaxations relaxations) - { - m_relaxations = (int) relaxations; - } - - public int CompilationRelaxations - { - get - { - return m_relaxations; - } - } - } - -} diff --git a/src/mscorlib/src/System/Runtime/CompilerServices/CompilerGeneratedAttribute.cs b/src/mscorlib/src/System/Runtime/CompilerServices/CompilerGeneratedAttribute.cs deleted file mode 100644 index 1778506c7c..0000000000 --- a/src/mscorlib/src/System/Runtime/CompilerServices/CompilerGeneratedAttribute.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 { - -[Serializable] -[AttributeUsage(AttributeTargets.All, Inherited = true)] - public sealed class CompilerGeneratedAttribute : Attribute - { - public CompilerGeneratedAttribute () {} - } -} - diff --git a/src/mscorlib/src/System/Runtime/CompilerServices/CompilerGlobalScopeAttribute.cs b/src/mscorlib/src/System/Runtime/CompilerServices/CompilerGlobalScopeAttribute.cs deleted file mode 100644 index 1cd830cfca..0000000000 --- a/src/mscorlib/src/System/Runtime/CompilerServices/CompilerGlobalScopeAttribute.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. - -/*============================================================ -** -** -** -** Purpose: Attribute used to communicate to the VS7 debugger -** that a class should be treated as if it has -** global scope. -** -** -===========================================================*/ - - -namespace System.Runtime.CompilerServices -{ - [Serializable] - [AttributeUsage(AttributeTargets.Class)] - public class CompilerGlobalScopeAttribute : Attribute - { - public CompilerGlobalScopeAttribute () {} - } -} - diff --git a/src/mscorlib/src/System/Runtime/CompilerServices/CompilerMarshalOverride.cs b/src/mscorlib/src/System/Runtime/CompilerServices/CompilerMarshalOverride.cs deleted file mode 100644 index a7b4aca480..0000000000 --- a/src/mscorlib/src/System/Runtime/CompilerServices/CompilerMarshalOverride.cs +++ /dev/null @@ -1,23 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -namespace System.Runtime.CompilerServices -{ - // The CLR data marshaler has some behaviors that are incompatible with - // C++. Specifically, C++ treats boolean variables as byte size, whereas - // the marshaller treats them as 4-byte size. Similarly, C++ treats - // wchar_t variables as 4-byte size, whereas the marshaller treats them - // as single byte size under certain conditions. In order to work around - // such issues, the C++ compiler will emit a type that the marshaller will - // marshal using the correct sizes. In addition, the compiler will place - // this modopt onto the variables to indicate that the specified type is - // not the true type. Any compiler that needed to deal with similar - // marshalling incompatibilities could use this attribute as well. - // - // Indicates that the modified instance differs from its true type for - // correct marshalling. - public static class CompilerMarshalOverride - { - } -} diff --git a/src/mscorlib/src/System/Runtime/CompilerServices/ConditionalWeakTable.cs b/src/mscorlib/src/System/Runtime/CompilerServices/ConditionalWeakTable.cs index 4b2648ba6f..f32cc2b510 100644 --- a/src/mscorlib/src/System/Runtime/CompilerServices/ConditionalWeakTable.cs +++ b/src/mscorlib/src/System/Runtime/CompilerServices/ConditionalWeakTable.cs @@ -61,6 +61,7 @@ using System.Collections; using System.Collections.Generic; +using System.Diagnostics; using System.Runtime.InteropServices; using System.Threading; @@ -164,7 +165,6 @@ namespace System.Runtime.CompilerServices { CreateEntry(key, value); } - } } @@ -797,7 +797,7 @@ namespace System.Runtime.CompilerServices } return Resize(newSize); - } + } internal Container Resize(int newSize) { @@ -974,7 +974,7 @@ namespace System.Runtime.CompilerServices { if (_invalid) { - throw new InvalidOperationException(Environment.GetResourceString("CollectionCorrupted")); + throw new InvalidOperationException(SR.InvalidOperation_CollectionCorrupted); } } @@ -1114,7 +1114,7 @@ namespace System.Runtime.CompilerServices { IntPtr handle = _handle; _handle = (IntPtr)0; - nFree(handle); + nFree(handle); } } #endregion diff --git a/src/mscorlib/src/System/Runtime/CompilerServices/CustomConstantAttribute.cs b/src/mscorlib/src/System/Runtime/CompilerServices/CustomConstantAttribute.cs index 1a5dcfdc11..8f4c79cd94 100644 --- a/src/mscorlib/src/System/Runtime/CompilerServices/CustomConstantAttribute.cs +++ b/src/mscorlib/src/System/Runtime/CompilerServices/CustomConstantAttribute.cs @@ -8,7 +8,7 @@ using System.Collections.Generic; namespace System.Runtime.CompilerServices { [Serializable] - [AttributeUsage(AttributeTargets.Field | AttributeTargets.Parameter, Inherited=false)] + [AttributeUsage(AttributeTargets.Field | AttributeTargets.Parameter, Inherited = false)] public abstract class CustomConstantAttribute : Attribute { public abstract Object Value { get; } diff --git a/src/mscorlib/src/System/Runtime/CompilerServices/DateTimeConstantAttribute.cs b/src/mscorlib/src/System/Runtime/CompilerServices/DateTimeConstantAttribute.cs index 148d916be1..7aca42b627 100644 --- a/src/mscorlib/src/System/Runtime/CompilerServices/DateTimeConstantAttribute.cs +++ b/src/mscorlib/src/System/Runtime/CompilerServices/DateTimeConstantAttribute.cs @@ -8,7 +8,7 @@ using System.Diagnostics.Contracts; namespace System.Runtime.CompilerServices { [Serializable] - [AttributeUsage(AttributeTargets.Field | AttributeTargets.Parameter, Inherited=false)] + [AttributeUsage(AttributeTargets.Field | AttributeTargets.Parameter, Inherited = false)] public sealed class DateTimeConstantAttribute : CustomConstantAttribute { public DateTimeConstantAttribute(long ticks) diff --git a/src/mscorlib/src/System/Runtime/CompilerServices/DecimalConstantAttribute.cs b/src/mscorlib/src/System/Runtime/CompilerServices/DecimalConstantAttribute.cs index f05191840d..0e2b6f8418 100644 --- a/src/mscorlib/src/System/Runtime/CompilerServices/DecimalConstantAttribute.cs +++ b/src/mscorlib/src/System/Runtime/CompilerServices/DecimalConstantAttribute.cs @@ -13,7 +13,7 @@ using System.Collections.Generic; namespace System.Runtime.CompilerServices { [Serializable] - [AttributeUsage(AttributeTargets.Field | AttributeTargets.Parameter, Inherited=false)] + [AttributeUsage(AttributeTargets.Field | AttributeTargets.Parameter, Inherited = false)] public sealed class DecimalConstantAttribute : Attribute { [CLSCompliant(false)] @@ -25,7 +25,7 @@ namespace System.Runtime.CompilerServices uint low ) { - dec = new System.Decimal((int) low, (int)mid, (int)hi, (sign != 0), scale); + dec = new System.Decimal((int)low, (int)mid, (int)hi, (sign != 0), scale); } public DecimalConstantAttribute( diff --git a/src/mscorlib/src/System/Runtime/CompilerServices/DisablePrivateReflectionAttribute.cs b/src/mscorlib/src/System/Runtime/CompilerServices/DisablePrivateReflectionAttribute.cs deleted file mode 100644 index 46dae10fdd..0000000000 --- a/src/mscorlib/src/System/Runtime/CompilerServices/DisablePrivateReflectionAttribute.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 -{ - using System; - - [AttributeUsage(AttributeTargets.Assembly, AllowMultiple=false, Inherited=false)] - public sealed class DisablePrivateReflectionAttribute : Attribute - { - public DisablePrivateReflectionAttribute() {} - } -} - diff --git a/src/mscorlib/src/System/Runtime/CompilerServices/DiscardableAttribute.cs b/src/mscorlib/src/System/Runtime/CompilerServices/DiscardableAttribute.cs deleted file mode 100644 index 3fda4624d4..0000000000 --- a/src/mscorlib/src/System/Runtime/CompilerServices/DiscardableAttribute.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 { - - using System; - - // Custom attribute to indicating a TypeDef is a discardable attribute - public class DiscardableAttribute : Attribute - { - public DiscardableAttribute() - { - } - } -} diff --git a/src/mscorlib/src/System/Runtime/CompilerServices/ExtensionAttribute.cs b/src/mscorlib/src/System/Runtime/CompilerServices/ExtensionAttribute.cs deleted file mode 100644 index 6ec8fa04f5..0000000000 --- a/src/mscorlib/src/System/Runtime/CompilerServices/ExtensionAttribute.cs +++ /dev/null @@ -1,13 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. -using System; - -namespace System.Runtime.CompilerServices -{ - /// <summary> - /// Indicates that a method is an extension method, or that a class or assembly contains extension methods. - /// </summary> - [AttributeUsage(AttributeTargets.Method | AttributeTargets.Class | AttributeTargets.Assembly)] - public sealed class ExtensionAttribute : Attribute { } -} diff --git a/src/mscorlib/src/System/Runtime/CompilerServices/FixedAddressValueTypeAttribute.cs b/src/mscorlib/src/System/Runtime/CompilerServices/FixedAddressValueTypeAttribute.cs deleted file mode 100644 index 679e304ad1..0000000000 --- a/src/mscorlib/src/System/Runtime/CompilerServices/FixedAddressValueTypeAttribute.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 -{ - using System; - -[Serializable] -[AttributeUsage(AttributeTargets.Field)] - sealed public class FixedAddressValueTypeAttribute : Attribute - { - } -} diff --git a/src/mscorlib/src/System/Runtime/CompilerServices/FixedBufferAttribute.cs b/src/mscorlib/src/System/Runtime/CompilerServices/FixedBufferAttribute.cs deleted file mode 100644 index a7d01b12c4..0000000000 --- a/src/mscorlib/src/System/Runtime/CompilerServices/FixedBufferAttribute.cs +++ /dev/null @@ -1,43 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -/*============================================================ -** -** -** Purpose: Used by a compiler for generating value types -** in-place within other value types containing a certain -** number of elements of the given (primitive) type. Somewhat -** similar to P/Invoke's ByValTStr attribute. -** Used by C# with this syntax: "fixed int buffer[10];" -** -===========================================================*/ -using System; - -namespace System.Runtime.CompilerServices -{ - [AttributeUsage(AttributeTargets.Field, Inherited=false)] - public sealed class FixedBufferAttribute : Attribute - { - private Type elementType; - private int length; - - public FixedBufferAttribute(Type elementType, int length) - { - this.elementType = elementType; - this.length = length; - } - - public Type ElementType { - get { - return elementType; - } - } - - public int Length { - get { - return length; - } - } - } -} diff --git a/src/mscorlib/src/System/Runtime/CompilerServices/FormattableStringFactory.cs b/src/mscorlib/src/System/Runtime/CompilerServices/FormattableStringFactory.cs deleted file mode 100644 index 4b99a8a5d9..0000000000 --- a/src/mscorlib/src/System/Runtime/CompilerServices/FormattableStringFactory.cs +++ /dev/null @@ -1,58 +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. - -/*============================================================ -** -** Class: FormattableStringFactory -** -** -** Purpose: implementation of the FormattableStringFactory -** class. -** -===========================================================*/ -namespace System.Runtime.CompilerServices -{ - /// <summary> - /// A factory type used by compilers to create instances of the type <see cref="FormattableString"/>. - /// </summary> - public static class FormattableStringFactory - { - /// <summary> - /// Create a <see cref="FormattableString"/> from a composite format string and object - /// array containing zero or more objects to format. - /// </summary> - public static FormattableString Create(string format, params object[] arguments) - { - if (format == null) - { - throw new ArgumentNullException(nameof(format)); - } - - if (arguments == null) - { - throw new ArgumentNullException(nameof(arguments)); - } - - return new ConcreteFormattableString(format, arguments); - } - - private sealed class ConcreteFormattableString : FormattableString - { - private readonly string _format; - private readonly object[] _arguments; - - internal ConcreteFormattableString(string format, object[] arguments) - { - _format = format; - _arguments = arguments; - } - - public override string Format { get { return _format; } } - public override object[] GetArguments() { return _arguments; } - public override int ArgumentCount { get { return _arguments.Length; } } - public override object GetArgument(int index) { return _arguments[index]; } - public override string ToString(IFormatProvider formatProvider) { return string.Format(formatProvider, _format, _arguments); } - } - } -} diff --git a/src/mscorlib/src/System/Runtime/CompilerServices/InternalsVisibleToAttribute.cs b/src/mscorlib/src/System/Runtime/CompilerServices/FriendAccessAllowedAttribute.cs index ee7807a5dd..9d380e1070 100644 --- a/src/mscorlib/src/System/Runtime/CompilerServices/InternalsVisibleToAttribute.cs +++ b/src/mscorlib/src/System/Runtime/CompilerServices/FriendAccessAllowedAttribute.cs @@ -2,40 +2,8 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -//------------------------------------------------------------------------------ -//------------------------------------------------------------------------------ - namespace System.Runtime.CompilerServices { - using System; - - - [AttributeUsage(AttributeTargets.Assembly, AllowMultiple=true, Inherited=false)] - public sealed class InternalsVisibleToAttribute : Attribute - { - private string _assemblyName; - private bool _allInternalsVisible = true; - - public InternalsVisibleToAttribute(string assemblyName) - { - this._assemblyName = assemblyName; - } - - public string AssemblyName - { - get - { - return _assemblyName; - } - } - - public bool AllInternalsVisible - { - get { return _allInternalsVisible; } - set { _allInternalsVisible = value; } - } - } - /// <summary> /// If AllInternalsVisible is not true for a friend assembly, the FriendAccessAllowed attribute /// indicates which internals are shared with that friend assembly. @@ -52,7 +20,7 @@ namespace System.Runtime.CompilerServices AllowMultiple = false, Inherited = false)] [FriendAccessAllowed] - internal sealed class FriendAccessAllowedAttribute : Attribute { + internal sealed class FriendAccessAllowedAttribute : Attribute + { } } - diff --git a/src/mscorlib/src/System/Runtime/CompilerServices/IAsyncStateMachine.cs b/src/mscorlib/src/System/Runtime/CompilerServices/IAsyncStateMachine.cs deleted file mode 100644 index 7fb7ea5395..0000000000 --- a/src/mscorlib/src/System/Runtime/CompilerServices/IAsyncStateMachine.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. - -// =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ -// -// -// -// Represents state machines generated for asynchronous methods. -// -// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- - -namespace System.Runtime.CompilerServices -{ - /// <summary> - /// Represents state machines generated for asynchronous methods. - /// This type is intended for compiler use only. - /// </summary> - public interface IAsyncStateMachine - { - /// <summary>Moves the state machine to its next state.</summary> - void MoveNext(); - /// <summary>Configures the state machine with a heap-allocated replica.</summary> - /// <param name="stateMachine">The heap-allocated replica.</param> - void SetStateMachine(IAsyncStateMachine stateMachine); - } -} diff --git a/src/mscorlib/src/System/Runtime/CompilerServices/ICastable.cs b/src/mscorlib/src/System/Runtime/CompilerServices/ICastable.cs index 7ba9434575..e2b76ed973 100644 --- a/src/mscorlib/src/System/Runtime/CompilerServices/ICastable.cs +++ b/src/mscorlib/src/System/Runtime/CompilerServices/ICastable.cs @@ -61,22 +61,22 @@ namespace System.Runtime.CompilerServices // IsInstanceOfInterface. RuntimeTypeHandle GetImplType(RuntimeTypeHandle interfaceType); } - + /// <summary> /// Helpers that allows VM to call into ICastable methods without having to deal with RuntimeTypeHandle. /// RuntimeTypeHandle is a struct and is always passed in stack in x86, which our VM call helpers don't /// particularly like. /// </summary> - class ICastableHelpers + internal class ICastableHelpers { internal static bool IsInstanceOfInterface(ICastable castable, RuntimeType type, out Exception castError) { return castable.IsInstanceOfInterface(new RuntimeTypeHandle(type), out castError); - } - + } + internal static RuntimeType GetImplType(ICastable castable, RuntimeType interfaceType) { - return castable.GetImplType(new RuntimeTypeHandle(interfaceType)).GetRuntimeType(); - } + return castable.GetImplType(new RuntimeTypeHandle(interfaceType)).GetRuntimeType(); + } } } diff --git a/src/mscorlib/src/System/Runtime/CompilerServices/INotifyCompletion.cs b/src/mscorlib/src/System/Runtime/CompilerServices/INotifyCompletion.cs deleted file mode 100644 index aba0a0691f..0000000000 --- a/src/mscorlib/src/System/Runtime/CompilerServices/INotifyCompletion.cs +++ /dev/null @@ -1,39 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -// =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+= -// -// -// -// Interfaces used to represent instances that notify listeners of their completion via continuations. -// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= - -using System; -using System.Security; - -namespace System.Runtime.CompilerServices -{ - /// <summary> - /// Represents an operation that will schedule continuations when the operation completes. - /// </summary> - public interface INotifyCompletion - { - /// <summary>Schedules the continuation action to be invoked when the instance completes.</summary> - /// <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> - void OnCompleted(Action continuation); - } - - /// <summary> - /// Represents an awaiter used to schedule continuations when an await operation completes. - /// </summary> - public interface ICriticalNotifyCompletion : INotifyCompletion - { - /// <summary>Schedules the continuation action to be invoked when the instance completes.</summary> - /// <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> - void UnsafeOnCompleted(Action continuation); - } -} diff --git a/src/mscorlib/src/System/Runtime/CompilerServices/ITuple.cs b/src/mscorlib/src/System/Runtime/CompilerServices/ITuple.cs deleted file mode 100644 index cafee11f8a..0000000000 --- a/src/mscorlib/src/System/Runtime/CompilerServices/ITuple.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 -{ - /// <summary> - /// This interface is required for types that want to be indexed into by dynamic patterns. - /// </summary> - public interface ITuple - { - /// <summary> - /// The number of positions in this data structure. - /// </summary> - int Length { get; } - - /// <summary> - /// Get the element at position <param name="index"/>. - /// </summary> - object this[int index] { get; } - } -} diff --git a/src/mscorlib/src/System/Runtime/CompilerServices/IndexerNameAttribute.cs b/src/mscorlib/src/System/Runtime/CompilerServices/IndexerNameAttribute.cs deleted file mode 100644 index c32be6f3a2..0000000000 --- a/src/mscorlib/src/System/Runtime/CompilerServices/IndexerNameAttribute.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 -{ - using System; - -[Serializable] -[AttributeUsage(AttributeTargets.Property, Inherited = true)] - public sealed class IndexerNameAttribute: Attribute - { - public IndexerNameAttribute(String indexerName) - {} - } -} diff --git a/src/mscorlib/src/System/Runtime/CompilerServices/IsVolatile.cs b/src/mscorlib/src/System/Runtime/CompilerServices/IsVolatile.cs deleted file mode 100644 index 5287e82b7b..0000000000 --- a/src/mscorlib/src/System/Runtime/CompilerServices/IsVolatile.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 -{ - public static class IsVolatile - { - // no instantiation, please! - } -} - diff --git a/src/mscorlib/src/System/Runtime/CompilerServices/IteratorStateMachineAttribute.cs b/src/mscorlib/src/System/Runtime/CompilerServices/IteratorStateMachineAttribute.cs deleted file mode 100644 index 4bb9b4eb8f..0000000000 --- a/src/mscorlib/src/System/Runtime/CompilerServices/IteratorStateMachineAttribute.cs +++ /dev/null @@ -1,18 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - - -using System; - -namespace System.Runtime.CompilerServices -{ - [Serializable, AttributeUsage(AttributeTargets.Method, Inherited = false, AllowMultiple = false)] - public sealed class IteratorStateMachineAttribute : StateMachineAttribute - { - public IteratorStateMachineAttribute(Type stateMachineType) - : base(stateMachineType) - { - } - } -} diff --git a/src/mscorlib/src/System/Runtime/CompilerServices/MethodImplAttribute.cs b/src/mscorlib/src/System/Runtime/CompilerServices/MethodImplAttribute.cs index b4991110f8..b24018cf78 100644 --- a/src/mscorlib/src/System/Runtime/CompilerServices/MethodImplAttribute.cs +++ b/src/mscorlib/src/System/Runtime/CompilerServices/MethodImplAttribute.cs @@ -2,72 +2,47 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -namespace System.Runtime.CompilerServices { - - using System; - using System.Reflection; - + +using System; +using System.Reflection; + +namespace System.Runtime.CompilerServices +{ // This Enum matchs the miImpl flags defined in corhdr.h. It is used to specify // certain method properties. - - [Serializable] - [Flags] - public enum MethodImplOptions - { - Unmanaged = System.Reflection.MethodImplAttributes.Unmanaged, - ForwardRef = System.Reflection.MethodImplAttributes.ForwardRef, - PreserveSig = System.Reflection.MethodImplAttributes.PreserveSig, - InternalCall = System.Reflection.MethodImplAttributes.InternalCall, - Synchronized = System.Reflection.MethodImplAttributes.Synchronized, - NoInlining = System.Reflection.MethodImplAttributes.NoInlining, - AggressiveInlining = System.Reflection.MethodImplAttributes.AggressiveInlining, - NoOptimization = System.Reflection.MethodImplAttributes.NoOptimization, - // **** If you add something, update internal MethodImplAttribute(MethodImplAttributes methodImplAttributes)! **** - } + // Custom attribute to specify additional method properties. [Serializable] - public enum MethodCodeType + [AttributeUsage(AttributeTargets.Method | AttributeTargets.Constructor, Inherited = false)] + sealed public class MethodImplAttribute : Attribute { - IL = System.Reflection.MethodImplAttributes.IL, - Native = System.Reflection.MethodImplAttributes.Native, - /// <internalonly/> - OPTIL = System.Reflection.MethodImplAttributes.OPTIL, - Runtime = System.Reflection.MethodImplAttributes.Runtime - } - - // Custom attribute to specify additional method properties. -[Serializable] -[AttributeUsage(AttributeTargets.Method | AttributeTargets.Constructor, Inherited = false)] - sealed public class MethodImplAttribute : Attribute - { - internal MethodImplOptions _val; - public MethodCodeType MethodCodeType; + internal MethodImplOptions _val; + public MethodCodeType MethodCodeType; internal MethodImplAttribute(MethodImplAttributes methodImplAttributes) { - MethodImplOptions all = - MethodImplOptions.Unmanaged | MethodImplOptions.ForwardRef | MethodImplOptions.PreserveSig | + MethodImplOptions all = + MethodImplOptions.Unmanaged | MethodImplOptions.ForwardRef | MethodImplOptions.PreserveSig | MethodImplOptions.InternalCall | MethodImplOptions.Synchronized | MethodImplOptions.NoInlining | MethodImplOptions.AggressiveInlining | MethodImplOptions.NoOptimization; _val = ((MethodImplOptions)methodImplAttributes) & all; } - + public MethodImplAttribute(MethodImplOptions methodImplOptions) { _val = methodImplOptions; } - + public MethodImplAttribute(short value) { _val = (MethodImplOptions)value; } - + public MethodImplAttribute() { } - - public MethodImplOptions Value { get {return _val;} } - } + public MethodImplOptions Value { get { return _val; } } + } } diff --git a/src/mscorlib/src/System/Runtime/CompilerServices/ReferenceAssemblyAttribute.cs b/src/mscorlib/src/System/Runtime/CompilerServices/ReferenceAssemblyAttribute.cs deleted file mode 100644 index d5e64a1177..0000000000 --- a/src/mscorlib/src/System/Runtime/CompilerServices/ReferenceAssemblyAttribute.cs +++ /dev/null @@ -1,39 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -/*============================================================ -** -** Attribute: ReferenceAssemblyAttribute -** -** Purpose: Identifies an assembly as being a "reference -** assembly", meaning it contains public surface area but -** no usable implementation. Reference assemblies -** should be loadable for introspection, but not execution. -** -============================================================*/ -namespace System.Runtime.CompilerServices -{ - using System; - - [Serializable] - [AttributeUsage(AttributeTargets.Assembly, AllowMultiple=false)] - public sealed class ReferenceAssemblyAttribute : Attribute - { - private String _description; // Maybe ".NET FX v4.0 SP1, partial trust"? - - public ReferenceAssemblyAttribute() - { - } - - public ReferenceAssemblyAttribute(String description) - { - _description = description; - } - - public String Description - { - get { return _description; } - } - } -} diff --git a/src/mscorlib/src/System/Runtime/CompilerServices/RuntimeCompatibilityAttribute.cs b/src/mscorlib/src/System/Runtime/CompilerServices/RuntimeCompatibilityAttribute.cs deleted file mode 100644 index 40a9b7c568..0000000000 --- a/src/mscorlib/src/System/Runtime/CompilerServices/RuntimeCompatibilityAttribute.cs +++ /dev/null @@ -1,48 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -//////////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////////// -/*============================================================================= -** -** -** -** Purpose: Mark up the program to indicate various legacy or new opt-in behaviors. -** -** -=============================================================================*/ - -namespace System.Runtime.CompilerServices -{ - - using System; - -[Serializable] -[AttributeUsage(AttributeTargets.Assembly, Inherited=false, AllowMultiple=false)] - public sealed class RuntimeCompatibilityAttribute : Attribute - { - // fields - private bool m_wrapNonExceptionThrows; - - // constructors - public RuntimeCompatibilityAttribute() { - // legacy behavior is the default, and m_wrapNonExceptionThrows is implicitly - // false thanks to the CLR's guarantee of zeroed memory. - } - - // properties - - // If a non-CLSCompliant exception (i.e. one that doesn't derive from System.Exception) is - // thrown, should it be wrapped up in a System.Runtime.CompilerServices.RuntimeWrappedException - // instance when presented to catch handlers? - public bool WrapNonExceptionThrows { - get { - return m_wrapNonExceptionThrows; - } - set { - m_wrapNonExceptionThrows = value; - } - } - } -} diff --git a/src/mscorlib/src/System/Runtime/CompilerServices/RuntimeHelpers.cs b/src/mscorlib/src/System/Runtime/CompilerServices/RuntimeHelpers.cs index 509e527ecb..0338b18bee 100644 --- a/src/mscorlib/src/System/Runtime/CompilerServices/RuntimeHelpers.cs +++ b/src/mscorlib/src/System/Runtime/CompilerServices/RuntimeHelpers.cs @@ -9,8 +9,9 @@ // This class defines a set of static methods that provide support for compilers. // // -namespace System.Runtime.CompilerServices { +namespace System.Runtime.CompilerServices +{ using System; using System.Security; using System.Runtime; @@ -32,7 +33,7 @@ namespace System.Runtime.CompilerServices { } [MethodImplAttribute(MethodImplOptions.InternalCall)] - public static extern void InitializeArray(Array array,RuntimeFieldHandle fldHandle); + public static extern void InitializeArray(Array array, RuntimeFieldHandle fldHandle); // GetObjectValue is intended to allow value classes to be manipulated as 'Object' // but have aliasing behavior of a value class. The intent is that you would use @@ -61,7 +62,7 @@ namespace System.Runtime.CompilerServices { [MethodImplAttribute(MethodImplOptions.InternalCall)] private static extern void _RunClassConstructor(RuntimeType type); - public static void RunClassConstructor(RuntimeTypeHandle type) + public static void RunClassConstructor(RuntimeTypeHandle type) { _RunClassConstructor(type.GetRuntimeType()); } @@ -77,24 +78,24 @@ namespace System.Runtime.CompilerServices { [MethodImplAttribute(MethodImplOptions.InternalCall)] private static extern void _RunModuleConstructor(System.Reflection.RuntimeModule module); - public static void RunModuleConstructor(ModuleHandle module) + public static void RunModuleConstructor(ModuleHandle module) { - _RunModuleConstructor(module.GetRuntimeModule()); + _RunModuleConstructor(module.GetRuntimeModule()); } [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode), SuppressUnmanagedCodeSecurity] internal static extern void _CompileMethod(IRuntimeMethodInfo method); - public static void PrepareMethod(RuntimeMethodHandle method){} - public static void PrepareMethod(RuntimeMethodHandle method, RuntimeTypeHandle[] instantiation){} - public static void PrepareContractedDelegate(Delegate d){} - + 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) { if (d == null) { - throw new ArgumentNullException ("d"); + throw new ArgumentNullException("d"); } } @@ -108,8 +109,9 @@ namespace System.Runtime.CompilerServices { { // This offset is baked in by string indexer intrinsic, so there is no harm // in getting it baked in here as well. - [System.Runtime.Versioning.NonVersionable] - get { + [System.Runtime.Versioning.NonVersionable] + get + { // Number of bytes from the address pointed to by a reference to // a String to the first 16-bit character in the String. Skip // over the MethodTable pointer, & String @@ -167,6 +169,14 @@ namespace System.Runtime.CompilerServices { { ((CleanupCode)backoutCode)(userData, exceptionThrown); } + + /// <returns>true if given type is reference type or value type that contains references</returns> + static public bool IsReferenceOrContainsReferences<T>() + { + // The body of this function will be replaced by the EE with unsafe code!!! + // See getILIntrinsicImplementation for how this happens. + throw new InvalidOperationException(); + } } } diff --git a/src/mscorlib/src/System/Runtime/CompilerServices/RuntimeWrappedException.cs b/src/mscorlib/src/System/Runtime/CompilerServices/RuntimeWrappedException.cs index e3b2d2ce62..c050000169 100644 --- a/src/mscorlib/src/System/Runtime/CompilerServices/RuntimeWrappedException.cs +++ b/src/mscorlib/src/System/Runtime/CompilerServices/RuntimeWrappedException.cs @@ -11,29 +11,34 @@ ** =============================================================================*/ -namespace System.Runtime.CompilerServices { - using System; - using System.Runtime.Serialization; - using System.Runtime.Remoting; - using System.Diagnostics.Contracts; - +using System; +using System.Runtime.Serialization; +using System.Runtime.Remoting; +using System.Diagnostics.Contracts; + +namespace System.Runtime.CompilerServices +{ [Serializable] public sealed class RuntimeWrappedException : Exception { private RuntimeWrappedException(Object thrownObject) - : base(Environment.GetResourceString("RuntimeWrappedException")) { - SetErrorCode(System.__HResults.COR_E_RUNTIMEWRAPPED); + : base(SR.RuntimeWrappedException) + { + HResult = System.__HResults.COR_E_RUNTIMEWRAPPED; m_wrappedException = thrownObject; } - - public Object WrappedException { + + public Object WrappedException + { get { return m_wrappedException; } } private Object m_wrappedException; - public override void GetObjectData(SerializationInfo info, StreamingContext context) { - if (info==null) { + public override void GetObjectData(SerializationInfo info, StreamingContext context) + { + if (info == null) + { throw new ArgumentNullException(nameof(info)); } Contract.EndContractBlock(); @@ -42,7 +47,8 @@ namespace System.Runtime.CompilerServices { } internal RuntimeWrappedException(SerializationInfo info, StreamingContext context) - : base(info, context) { + : base(info, context) + { m_wrappedException = info.GetValue("WrappedException", typeof(Object)); } } diff --git a/src/mscorlib/src/System/Runtime/CompilerServices/SpecialNameAttribute.cs b/src/mscorlib/src/System/Runtime/CompilerServices/SpecialNameAttribute.cs deleted file mode 100644 index 38e5538b44..0000000000 --- a/src/mscorlib/src/System/Runtime/CompilerServices/SpecialNameAttribute.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; -using System.Reflection; -using System.Runtime.InteropServices; - -namespace System.Runtime.CompilerServices -{ - [AttributeUsage(AttributeTargets.Class | - AttributeTargets.Method | - AttributeTargets.Property | - AttributeTargets.Field | - AttributeTargets.Event | - AttributeTargets.Struct)] - - - public sealed class SpecialNameAttribute : Attribute - { - public SpecialNameAttribute() { } - } -} - - - diff --git a/src/mscorlib/src/System/Runtime/CompilerServices/StateMachineAttribute.cs b/src/mscorlib/src/System/Runtime/CompilerServices/StateMachineAttribute.cs deleted file mode 100644 index 7c84009e1f..0000000000 --- a/src/mscorlib/src/System/Runtime/CompilerServices/StateMachineAttribute.cs +++ /dev/null @@ -1,20 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - - -using System; - -namespace System.Runtime.CompilerServices -{ - [Serializable, AttributeUsage(AttributeTargets.Method, Inherited = false, AllowMultiple = false)] - public class StateMachineAttribute : Attribute - { - public Type StateMachineType { get; private set; } - - public StateMachineAttribute(Type stateMachineType) - { - this.StateMachineType = stateMachineType; - } - } -} diff --git a/src/mscorlib/src/System/Runtime/CompilerServices/SuppressIldasmAttribute.cs b/src/mscorlib/src/System/Runtime/CompilerServices/SuppressIldasmAttribute.cs deleted file mode 100644 index eb019eecbf..0000000000 --- a/src/mscorlib/src/System/Runtime/CompilerServices/SuppressIldasmAttribute.cs +++ /dev/null @@ -1,19 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -//------------------------------------------------------------------------------ -//------------------------------------------------------------------------------ -namespace System.Runtime.CompilerServices -{ - using System; - - [AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Module)] - public sealed class SuppressIldasmAttribute : Attribute - { - public SuppressIldasmAttribute() - { - } - } -} - diff --git a/src/mscorlib/src/System/Runtime/CompilerServices/SuppressMergeCheckAttribute.cs b/src/mscorlib/src/System/Runtime/CompilerServices/SuppressMergeCheckAttribute.cs deleted file mode 100644 index 6bb36c4bf5..0000000000 --- a/src/mscorlib/src/System/Runtime/CompilerServices/SuppressMergeCheckAttribute.cs +++ /dev/null @@ -1,23 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - - -using System.Runtime.InteropServices; - -namespace System.Runtime.CompilerServices -{ - [AttributeUsage(AttributeTargets.Class | - AttributeTargets.Constructor | - AttributeTargets.Method | - AttributeTargets.Field | - AttributeTargets.Event | - AttributeTargets.Property)] - - internal sealed class SuppressMergeCheckAttribute : Attribute - { - public SuppressMergeCheckAttribute() - {} - } -} - diff --git a/src/mscorlib/src/System/Runtime/CompilerServices/TaskAwaiter.cs b/src/mscorlib/src/System/Runtime/CompilerServices/TaskAwaiter.cs index f01900a5bf..e2fa6caa2d 100644 --- a/src/mscorlib/src/System/Runtime/CompilerServices/TaskAwaiter.cs +++ b/src/mscorlib/src/System/Runtime/CompilerServices/TaskAwaiter.cs @@ -72,7 +72,7 @@ namespace System.Runtime.CompilerServices /// <summary>Gets whether the task being awaited is completed.</summary> /// <remarks>This property is intended for compiler user rather than use directly in code.</remarks> /// <exception cref="System.NullReferenceException">The awaiter was not properly initialized.</exception> - public bool IsCompleted + public bool IsCompleted { get { return m_task.IsCompleted; } } @@ -84,7 +84,7 @@ namespace System.Runtime.CompilerServices /// <remarks>This method is intended for compiler user rather than use directly in code.</remarks> public void OnCompleted(Action continuation) { - OnCompletedInternal(m_task, continuation, continueOnCapturedContext:true, flowExecutionContext:true); + OnCompletedInternal(m_task, continuation, continueOnCapturedContext: true, flowExecutionContext: true); } /// <summary>Schedules the continuation onto the <see cref="System.Threading.Tasks.Task"/> associated with this <see cref="TaskAwaiter"/>.</summary> @@ -94,7 +94,7 @@ namespace System.Runtime.CompilerServices /// <remarks>This method is intended for compiler user rather than use directly in code.</remarks> public void UnsafeOnCompleted(Action continuation) { - OnCompletedInternal(m_task, continuation, continueOnCapturedContext:true, flowExecutionContext:false); + OnCompletedInternal(m_task, continuation, continueOnCapturedContext: true, flowExecutionContext: false); } /// <summary>Ends the await on the completed <see cref="System.Threading.Tasks.Task"/>.</summary> @@ -240,7 +240,7 @@ namespace System.Runtime.CompilerServices etwLog.TaskWaitBegin( (currentTaskAtBegin != null ? currentTaskAtBegin.m_taskScheduler.Id : TaskScheduler.Default.Id), (currentTaskAtBegin != null ? currentTaskAtBegin.Id : 0), - task.Id, TplEtwProvider.TaskWaitBehavior.Asynchronous, + task.Id, TplEtwProvider.TaskWaitBehavior.Asynchronous, (continuationTask != null ? continuationTask.Id : 0)); } @@ -303,7 +303,7 @@ namespace System.Runtime.CompilerServices /// <summary>Gets whether the task being awaited is completed.</summary> /// <remarks>This property is intended for compiler user rather than use directly in code.</remarks> /// <exception cref="System.NullReferenceException">The awaiter was not properly initialized.</exception> - public bool IsCompleted + public bool IsCompleted { get { return m_task.IsCompleted; } } @@ -315,7 +315,7 @@ namespace System.Runtime.CompilerServices /// <remarks>This method is intended for compiler user rather than use directly in code.</remarks> public void OnCompleted(Action continuation) { - TaskAwaiter.OnCompletedInternal(m_task, continuation, continueOnCapturedContext:true, flowExecutionContext:true); + TaskAwaiter.OnCompletedInternal(m_task, continuation, continueOnCapturedContext: true, flowExecutionContext: true); } /// <summary>Schedules the continuation onto the <see cref="System.Threading.Tasks.Task"/> associated with this <see cref="TaskAwaiter"/>.</summary> @@ -325,7 +325,7 @@ namespace System.Runtime.CompilerServices /// <remarks>This method is intended for compiler user rather than use directly in code.</remarks> public void UnsafeOnCompleted(Action continuation) { - TaskAwaiter.OnCompletedInternal(m_task, continuation, continueOnCapturedContext:true, flowExecutionContext:false); + TaskAwaiter.OnCompletedInternal(m_task, continuation, continueOnCapturedContext: true, flowExecutionContext: false); } /// <summary>Ends the await on the completed <see cref="System.Threading.Tasks.Task{TResult}"/>.</summary> @@ -390,7 +390,7 @@ namespace System.Runtime.CompilerServices /// <summary>Gets whether the task being awaited is completed.</summary> /// <remarks>This property is intended for compiler user rather than use directly in code.</remarks> /// <exception cref="System.NullReferenceException">The awaiter was not properly initialized.</exception> - public bool IsCompleted + public bool IsCompleted { get { return m_task.IsCompleted; } } @@ -402,7 +402,7 @@ namespace System.Runtime.CompilerServices /// <remarks>This method is intended for compiler user rather than use directly in code.</remarks> public void OnCompleted(Action continuation) { - TaskAwaiter.OnCompletedInternal(m_task, continuation, m_continueOnCapturedContext, flowExecutionContext:true); + TaskAwaiter.OnCompletedInternal(m_task, continuation, m_continueOnCapturedContext, flowExecutionContext: true); } /// <summary>Schedules the continuation onto the <see cref="System.Threading.Tasks.Task"/> associated with this <see cref="TaskAwaiter"/>.</summary> @@ -412,7 +412,7 @@ namespace System.Runtime.CompilerServices /// <remarks>This method is intended for compiler user rather than use directly in code.</remarks> public void UnsafeOnCompleted(Action continuation) { - TaskAwaiter.OnCompletedInternal(m_task, continuation, m_continueOnCapturedContext, flowExecutionContext:false); + TaskAwaiter.OnCompletedInternal(m_task, continuation, m_continueOnCapturedContext, flowExecutionContext: false); } /// <summary>Ends the await on the completed <see cref="System.Threading.Tasks.Task"/>.</summary> @@ -475,7 +475,7 @@ namespace System.Runtime.CompilerServices /// <summary>Gets whether the task being awaited is completed.</summary> /// <remarks>This property is intended for compiler user rather than use directly in code.</remarks> /// <exception cref="System.NullReferenceException">The awaiter was not properly initialized.</exception> - public bool IsCompleted + public bool IsCompleted { get { return m_task.IsCompleted; } } @@ -487,7 +487,7 @@ namespace System.Runtime.CompilerServices /// <remarks>This method is intended for compiler user rather than use directly in code.</remarks> public void OnCompleted(Action continuation) { - TaskAwaiter.OnCompletedInternal(m_task, continuation, m_continueOnCapturedContext, flowExecutionContext:true); + TaskAwaiter.OnCompletedInternal(m_task, continuation, m_continueOnCapturedContext, flowExecutionContext: true); } /// <summary>Schedules the continuation onto the <see cref="System.Threading.Tasks.Task"/> associated with this <see cref="TaskAwaiter"/>.</summary> @@ -497,7 +497,7 @@ namespace System.Runtime.CompilerServices /// <remarks>This method is intended for compiler user rather than use directly in code.</remarks> public void UnsafeOnCompleted(Action continuation) { - TaskAwaiter.OnCompletedInternal(m_task, continuation, m_continueOnCapturedContext, flowExecutionContext:false); + TaskAwaiter.OnCompletedInternal(m_task, continuation, m_continueOnCapturedContext, flowExecutionContext: false); } /// <summary>Ends the await on the completed <see cref="System.Threading.Tasks.Task{TResult}"/>.</summary> diff --git a/src/mscorlib/src/System/Runtime/CompilerServices/TupleElementNamesAttribute.cs b/src/mscorlib/src/System/Runtime/CompilerServices/TupleElementNamesAttribute.cs deleted file mode 100644 index 65b120e6b4..0000000000 --- a/src/mscorlib/src/System/Runtime/CompilerServices/TupleElementNamesAttribute.cs +++ /dev/null @@ -1,57 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System.Collections.Generic; - -namespace System.Runtime.CompilerServices -{ - /// <summary> - /// Indicates that the use of <see cref="System.ValueTuple"/> on a member is meant to be treated as a tuple with element names. - /// </summary> - [CLSCompliant(false)] - [AttributeUsage(AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.Property | AttributeTargets.ReturnValue | AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Event)] - public sealed class TupleElementNamesAttribute : Attribute - { - private readonly string[] _transformNames; - - /// <summary> - /// Initializes a new instance of the <see - /// cref="TupleElementNamesAttribute"/> class. - /// </summary> - /// <param name="transformNames"> - /// Specifies, in a pre-order depth-first traversal of a type's - /// construction, which <see cref="System.ValueType"/> occurrences are - /// meant to carry element names. - /// </param> - /// <remarks> - /// This constructor is meant to be used on types that contain an - /// instantiation of <see cref="System.ValueType"/> that contains - /// element names. For instance, if <c>C</c> is a generic type with - /// two type parameters, then a use of the constructed type <c>C{<see - /// cref="System.ValueTuple{T1, T2}"/>, <see - /// cref="System.ValueTuple{T1, T2, T3}"/></c> might be intended to - /// treat the first type argument as a tuple with element names and the - /// second as a tuple without element names. In which case, the - /// appropriate attribute specification should use a - /// <c>transformNames</c> value of <c>{ "name1", "name2", null, null, - /// null }</c>. - /// </remarks> - public TupleElementNamesAttribute(string[] transformNames) - { - if (transformNames == null) - { - throw new ArgumentNullException(nameof(transformNames)); - } - - _transformNames = transformNames; - } - - /// <summary> - /// Specifies, in a pre-order depth-first traversal of a type's - /// construction, which <see cref="System.ValueTuple"/> elements are - /// meant to carry element names. - /// </summary> - public IList<string> TransformNames => _transformNames; - } -}
\ No newline at end of file diff --git a/src/mscorlib/src/System/Runtime/CompilerServices/TypeDependencyAttribute.cs b/src/mscorlib/src/System/Runtime/CompilerServices/TypeDependencyAttribute.cs index 2de9c1f785..929cbe7608 100644 --- a/src/mscorlib/src/System/Runtime/CompilerServices/TypeDependencyAttribute.cs +++ b/src/mscorlib/src/System/Runtime/CompilerServices/TypeDependencyAttribute.cs @@ -2,28 +2,26 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -namespace System.Runtime.CompilerServices -{ - using System; - using System.Diagnostics.Contracts; +using System; +using System.Diagnostics.Contracts; +namespace System.Runtime.CompilerServices +{ // We might want to make this inherited someday. But I suspect it shouldn't // be necessary. [AttributeUsage(AttributeTargets.Struct | AttributeTargets.Class | AttributeTargets.Interface, AllowMultiple = true, Inherited = false)] - internal sealed class TypeDependencyAttribute: Attribute + internal sealed class TypeDependencyAttribute : Attribute { - private string typeName; - public TypeDependencyAttribute (string typeName) + public TypeDependencyAttribute(string typeName) { - if(typeName == null) throw new ArgumentNullException(nameof(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 deleted file mode 100644 index 671d1f0071..0000000000 --- a/src/mscorlib/src/System/Runtime/CompilerServices/TypeForwardedFromAttribute.cs +++ /dev/null @@ -1,35 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - - -namespace System.Runtime.CompilerServices -{ - [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Enum | AttributeTargets.Interface | AttributeTargets.Delegate, Inherited = false, AllowMultiple = false)] - public sealed class TypeForwardedFromAttribute : Attribute - { - string assemblyFullName; - - private TypeForwardedFromAttribute() - { - // Disallow default constructor - } - - - public TypeForwardedFromAttribute(string assemblyFullName) - { - if (String.IsNullOrEmpty(assemblyFullName)) - { - throw new ArgumentNullException(nameof(assemblyFullName)); - } - this.assemblyFullName = assemblyFullName; - } - - public string AssemblyFullName - { - get { - return assemblyFullName; - } - } - } -} diff --git a/src/mscorlib/src/System/Runtime/CompilerServices/TypeForwardedToAttribute.cs b/src/mscorlib/src/System/Runtime/CompilerServices/TypeForwardedToAttribute.cs deleted file mode 100644 index 147c103047..0000000000 --- a/src/mscorlib/src/System/Runtime/CompilerServices/TypeForwardedToAttribute.cs +++ /dev/null @@ -1,34 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - - -using System; -using System.Reflection; - -namespace System.Runtime.CompilerServices -{ - using System; - [AttributeUsage(AttributeTargets.Assembly, AllowMultiple=true, Inherited=false)] - public sealed class TypeForwardedToAttribute : Attribute - { - private Type _destination; - - public TypeForwardedToAttribute(Type destination) - { - _destination = destination; - } - - public Type Destination - { - get { - return _destination; - } - } - - } -} - - - - diff --git a/src/mscorlib/src/System/Runtime/CompilerServices/Unsafe.cs b/src/mscorlib/src/System/Runtime/CompilerServices/Unsafe.cs index adfa015161..b184cd9fa8 100644 --- a/src/mscorlib/src/System/Runtime/CompilerServices/Unsafe.cs +++ b/src/mscorlib/src/System/Runtime/CompilerServices/Unsafe.cs @@ -4,6 +4,12 @@ using System.Runtime.Versioning; +#if BIT64 +using nuint = System.UInt64; +#else +using nuint = System.UInt32; +#endif + namespace System.Runtime.CompilerServices { // @@ -37,6 +43,7 @@ namespace System.Runtime.CompilerServices { // 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. + typeof(T).ToString(); // Type token used by the actual method body throw new InvalidOperationException(); } @@ -61,7 +68,19 @@ namespace System.Runtime.CompilerServices { // 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 + typeof(T).ToString(); // Type token used by the actual method body + throw new InvalidOperationException(); + } + + /// <summary> + /// Adds an element offset to the given reference. + /// </summary> + [NonVersionable] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static ref T AddByteOffset<T>(ref T source, nuint byteOffset) + { + // The body of this function will be replaced by the EE with unsafe code!!! + // See getILIntrinsicImplementationForUnsafe for how this happens. throw new InvalidOperationException(); } @@ -89,5 +108,45 @@ namespace System.Runtime.CompilerServices // See getILIntrinsicImplementationForUnsafe for how this happens. throw new InvalidOperationException(); } + + [NonVersionable] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static T ReadUnaligned<T>(void* source) + { + // The body of this function will be replaced by the EE with unsafe code!!! + // See getILIntrinsicImplementationForUnsafe for how this happens. + typeof(T).ToString(); // Type token used by the actual method body + throw new InvalidOperationException(); + } + + [NonVersionable] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static T ReadUnaligned<T>(ref byte source) + { + // The body of this function will be replaced by the EE with unsafe code!!! + // See getILIntrinsicImplementationForUnsafe for how this happens. + typeof(T).ToString(); // Type token used by the actual method body + throw new InvalidOperationException(); + } + + [NonVersionable] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void WriteUnaligned<T>(void* destination, T value) + { + // The body of this function will be replaced by the EE with unsafe code!!! + // See getILIntrinsicImplementationForUnsafe for how this happens. + typeof(T).ToString(); // Type token used by the actual method body + throw new InvalidOperationException(); + } + + [NonVersionable] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void WriteUnaligned<T>(ref byte destination, T value) + { + // The body of this function will be replaced by the EE with unsafe code!!! + // See getILIntrinsicImplementationForUnsafe for how this happens. + typeof(T).ToString(); // Type token used by the actual method body + throw new InvalidOperationException(); + } } } diff --git a/src/mscorlib/src/System/Runtime/CompilerServices/UnsafeValueTypeAttribute.cs b/src/mscorlib/src/System/Runtime/CompilerServices/UnsafeValueTypeAttribute.cs deleted file mode 100644 index bc210ccb71..0000000000 --- a/src/mscorlib/src/System/Runtime/CompilerServices/UnsafeValueTypeAttribute.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 -{ - using System; - -[Serializable] -[AttributeUsage(AttributeTargets.Struct)] - sealed public class UnsafeValueTypeAttribute : Attribute - { - } -} diff --git a/src/mscorlib/src/System/Runtime/CompilerServices/YieldAwaitable.cs b/src/mscorlib/src/System/Runtime/CompilerServices/YieldAwaitable.cs index 92d1b4f95b..f1c7772526 100644 --- a/src/mscorlib/src/System/Runtime/CompilerServices/YieldAwaitable.cs +++ b/src/mscorlib/src/System/Runtime/CompilerServices/YieldAwaitable.cs @@ -144,7 +144,6 @@ namespace System.Runtime.CompilerServices etwLog.TaskWaitContinuationComplete(continuationId); }); - } /// <summary>WaitCallback that invokes the Action supplied as object state.</summary> @@ -157,7 +156,7 @@ namespace System.Runtime.CompilerServices private static void RunAction(object state) { ((Action)state)(); } /// <summary>Ends the await operation.</summary> - public void GetResult() {} // Nop. It exists purely because the compiler pattern demands it. + public void GetResult() { } // Nop. It exists purely because the compiler pattern demands it. } } } diff --git a/src/mscorlib/src/System/Runtime/CompilerServices/jithelpers.cs b/src/mscorlib/src/System/Runtime/CompilerServices/jithelpers.cs index 080e42f46f..b86835f778 100644 --- a/src/mscorlib/src/System/Runtime/CompilerServices/jithelpers.cs +++ b/src/mscorlib/src/System/Runtime/CompilerServices/jithelpers.cs @@ -16,8 +16,8 @@ using System.Diagnostics.Contracts; using System.Runtime.InteropServices; using System.Security; -namespace System.Runtime.CompilerServices { - +namespace System.Runtime.CompilerServices +{ // Wrapper for address of a string variable on stack internal struct StringHandleOnStack { @@ -114,14 +114,14 @@ namespace System.Runtime.CompilerServices { static internal int UnsafeEnumCast<T>(T val) where T : struct // Actually T must be 4 byte (or less) enum { - Debug.Assert(typeof(T).IsEnum - && (Enum.GetUnderlyingType(typeof(T)) == typeof(int) - || Enum.GetUnderlyingType(typeof(T)) == typeof(uint) + Debug.Assert(typeof(T).IsEnum + && (Enum.GetUnderlyingType(typeof(T)) == typeof(int) + || Enum.GetUnderlyingType(typeof(T)) == typeof(uint) || Enum.GetUnderlyingType(typeof(T)) == typeof(short) || Enum.GetUnderlyingType(typeof(T)) == typeof(ushort) || Enum.GetUnderlyingType(typeof(T)) == typeof(byte) || Enum.GetUnderlyingType(typeof(T)) == typeof(sbyte)), - "Error, T must be an 4 byte (or less) enum JitHelpers.UnsafeEnumCast!"); + "Error, T must be an 4 byte (or less) enum JitHelpers.UnsafeEnumCast!"); return UnsafeEnumCastInternal<T>(val); } @@ -134,9 +134,9 @@ namespace System.Runtime.CompilerServices { static internal long UnsafeEnumCastLong<T>(T val) where T : struct // Actually T must be 8 byte enum { - Debug.Assert(typeof(T).IsEnum - && (Enum.GetUnderlyingType(typeof(T)) == typeof(long) - || Enum.GetUnderlyingType(typeof(T)) == typeof(ulong)), + 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!"); return UnsafeEnumCastLongInternal<T>(val); } @@ -213,7 +213,7 @@ namespace System.Runtime.CompilerServices { #if _DEBUG [MethodImplAttribute(MethodImplOptions.InternalCall)] - extern static bool IsAddressInStack(IntPtr ptr); + private extern static bool IsAddressInStack(IntPtr ptr); #endif static internal bool ByRefLessThan<T>(ref T refA, ref T refB) @@ -223,14 +223,6 @@ namespace System.Runtime.CompilerServices { 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!!! diff --git a/src/mscorlib/src/System/Runtime/ExceptionServices/CorruptingExceptionCommon.cs b/src/mscorlib/src/System/Runtime/ExceptionServices/CorruptingExceptionCommon.cs index f04ddf065a..00067748f2 100644 --- a/src/mscorlib/src/System/Runtime/ExceptionServices/CorruptingExceptionCommon.cs +++ b/src/mscorlib/src/System/Runtime/ExceptionServices/CorruptingExceptionCommon.cs @@ -14,9 +14,10 @@ ** =============================================================================*/ -namespace System.Runtime.ExceptionServices { - using System; - +using System; + +namespace System.Runtime.ExceptionServices +{ // This attribute can be applied to methods to indicate that ProcessCorruptedState // Exceptions should be delivered to them. [AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = false)] diff --git a/src/mscorlib/src/System/Runtime/ExceptionServices/ExceptionNotification.cs b/src/mscorlib/src/System/Runtime/ExceptionServices/ExceptionNotification.cs index 1b3e25b8b2..d986ea9c24 100644 --- a/src/mscorlib/src/System/Runtime/ExceptionServices/ExceptionNotification.cs +++ b/src/mscorlib/src/System/Runtime/ExceptionServices/ExceptionNotification.cs @@ -1,22 +1,21 @@ -// Licensed to the .NET Foundation under one or more agreements. +// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /*============================================================================= ** -** File: ExceptionNotification.cs ** ** ** Purpose: Contains definitions for supporting Exception Notifications. ** ** Created: 10/07/2008 ** -** <owner>gkhanna</owner> ** =============================================================================*/ -namespace System.Runtime.ExceptionServices { - using System; - using System.Runtime.ConstrainedExecution; - +using System; +using System.Runtime.ConstrainedExecution; + +namespace System.Runtime.ExceptionServices +{ // Definition of the argument-type passed to the FirstChanceException event handler public class FirstChanceExceptionEventArgs : EventArgs { diff --git a/src/mscorlib/src/System/Runtime/ExceptionServices/ExceptionServicesCommon.cs b/src/mscorlib/src/System/Runtime/ExceptionServices/ExceptionServicesCommon.cs index e8eb6916b7..8d5ced089f 100644 --- a/src/mscorlib/src/System/Runtime/ExceptionServices/ExceptionServicesCommon.cs +++ b/src/mscorlib/src/System/Runtime/ExceptionServices/ExceptionServicesCommon.cs @@ -15,9 +15,10 @@ ** =============================================================================*/ -namespace System.Runtime.ExceptionServices { - using System; - +using System; + +namespace System.Runtime.ExceptionServices +{ // This class defines support for seperating the exception dispatch details // (like stack trace, watson buckets, etc) from the actual managed exception // object. This allows us to track error (via the exception object) independent @@ -34,13 +35,13 @@ namespace System.Runtime.ExceptionServices { private object m_dynamicMethods; private UIntPtr m_IPForWatsonBuckets; private Object m_WatsonBuckets; - + private ExceptionDispatchInfo(Exception exception) { // Copy over the details we need to save. m_Exception = exception; m_remoteStackTrace = exception.RemoteStackTrace; - + // NOTE: don't be tempted to pass the fields for the out params; the containing object // might be relocated during the call so the pointers will no longer be valid. object stackTrace; @@ -50,14 +51,14 @@ namespace System.Runtime.ExceptionServices { m_dynamicMethods = dynamicMethods; m_IPForWatsonBuckets = exception.IPForWatsonBuckets; - m_WatsonBuckets = exception.WatsonBuckets; + m_WatsonBuckets = exception.WatsonBuckets; } internal UIntPtr IPForWatsonBuckets { get { - return m_IPForWatsonBuckets; + return m_IPForWatsonBuckets; } } @@ -65,10 +66,10 @@ namespace System.Runtime.ExceptionServices { { get { - return m_WatsonBuckets; + return m_WatsonBuckets; } } - + internal object BinaryStackTraceArray { get @@ -100,22 +101,21 @@ namespace System.Runtime.ExceptionServices { { if (source == null) { - throw new ArgumentNullException(nameof(source), Environment.GetResourceString("ArgumentNull_Obj")); + throw new ArgumentNullException(nameof(source), SR.ArgumentNull_Obj); } - + return new ExceptionDispatchInfo(source); } - + // Return the exception object represented by this ExceptionDispatchInfo instance public Exception SourceException { - get { - return m_Exception; + return m_Exception; } } - + // When a framework needs to "Rethrow" an exception on a thread different (but not necessarily so) from // where it was thrown, it should invoke this method against the ExceptionDispatchInfo (EDI) // created for the exception in question. @@ -127,7 +127,11 @@ namespace System.Runtime.ExceptionServices { { // Restore the exception dispatch details before throwing the exception. m_Exception.RestoreExceptionDispatchInfo(this); - throw m_Exception; + throw m_Exception; } + + // Throws the source exception, maintaining the original bucketing details and augmenting + // rather than replacing the original stack trace. + public static void Throw(Exception source) => Capture(source).Throw(); } } diff --git a/src/mscorlib/src/System/Runtime/GcSettings.cs b/src/mscorlib/src/System/Runtime/GcSettings.cs index 11143c5ee2..993a24f986 100644 --- a/src/mscorlib/src/System/Runtime/GcSettings.cs +++ b/src/mscorlib/src/System/Runtime/GcSettings.cs @@ -3,12 +3,13 @@ // See the LICENSE file in the project root for more information. -namespace System.Runtime { - using System; - using System.Runtime.CompilerServices; - using System.Runtime.ConstrainedExecution; - using System.Diagnostics.Contracts; +using System; +using System.Runtime.CompilerServices; +using System.Runtime.ConstrainedExecution; +using System.Diagnostics.Contracts; +namespace System.Runtime +{ // These settings are the same format as in clr\src\vm\gcpriv.h // make sure you change that file if you change this file! @@ -22,34 +23,34 @@ namespace System.Runtime { [Serializable] public enum GCLatencyMode { - Batch = 0, + Batch = 0, Interactive = 1, LowLatency = 2, SustainedLowLatency = 3, NoGCRegion = 4 } - public static class GCSettings + public static class GCSettings { - enum SetLatencyModeStatus + private enum SetLatencyModeStatus { Succeeded = 0, NoGCInProgress = 1 // NoGCRegion is in progress, can't change pause mode. }; - + public static GCLatencyMode LatencyMode { - get + get { return (GCLatencyMode)(GC.GetGCLatencyMode()); } // We don't want to allow this API when hosted. - set + set { if ((value < GCLatencyMode.Batch) || (value > GCLatencyMode.SustainedLowLatency)) { - throw new ArgumentOutOfRangeException(Environment.GetResourceString("ArgumentOutOfRange_Enum")); + throw new ArgumentOutOfRangeException(SR.ArgumentOutOfRange_Enum); } Contract.EndContractBlock(); @@ -60,18 +61,18 @@ namespace System.Runtime { public static GCLargeObjectHeapCompactionMode LargeObjectHeapCompactionMode { - get + get { return (GCLargeObjectHeapCompactionMode)(GC.GetLOHCompactionMode()); } // We don't want to allow this API when hosted. - set + set { - if ((value < GCLargeObjectHeapCompactionMode.Default) || + if ((value < GCLargeObjectHeapCompactionMode.Default) || (value > GCLargeObjectHeapCompactionMode.CompactOnce)) { - throw new ArgumentOutOfRangeException(Environment.GetResourceString("ArgumentOutOfRange_Enum")); + throw new ArgumentOutOfRangeException(SR.ArgumentOutOfRange_Enum); } Contract.EndContractBlock(); @@ -79,11 +80,12 @@ namespace System.Runtime { } } - public static bool IsServerGC + public static bool IsServerGC { - get { + 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 fc15f4e1a7..c4beb024b1 100644 --- a/src/mscorlib/src/System/Runtime/InteropServices/ArrayWithOffset.cs +++ b/src/mscorlib/src/System/Runtime/InteropServices/ArrayWithOffset.cs @@ -2,12 +2,13 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -namespace System.Runtime.InteropServices { - using System; - using System.Runtime.CompilerServices; - using System.Runtime.Versioning; +using System; +using System.Runtime.CompilerServices; +using System.Runtime.Versioning; +namespace System.Runtime.InteropServices +{ [Serializable] public struct ArrayWithOffset { @@ -15,30 +16,30 @@ namespace System.Runtime.InteropServices { //{ // throw new Exception(); //} - + public ArrayWithOffset(Object array, int offset) { - m_array = array; + m_array = array; m_offset = offset; - m_count = 0; - m_count = CalculateCount(); + m_count = 0; + m_count = CalculateCount(); } - + public Object GetArray() { return m_array; } - + public int GetOffset() { return m_offset; } - + public override int GetHashCode() { return m_count + m_offset; } - + public override bool Equals(Object obj) { if (obj is ArrayWithOffset) @@ -51,12 +52,12 @@ namespace System.Runtime.InteropServices { { return obj.m_array == m_array && obj.m_offset == m_offset && obj.m_count == m_count; } - + public static bool operator ==(ArrayWithOffset a, ArrayWithOffset b) { return a.Equals(b); } - + public static bool operator !=(ArrayWithOffset a, ArrayWithOffset b) { return !(a == b); @@ -64,10 +65,9 @@ namespace System.Runtime.InteropServices { [MethodImplAttribute(MethodImplOptions.InternalCall)] private extern int CalculateCount(); - + private Object m_array; - private int m_offset; - private int m_count; + private int m_offset; + private int m_count; } - } diff --git a/src/mscorlib/src/System/Runtime/InteropServices/Attributes.cs b/src/mscorlib/src/System/Runtime/InteropServices/Attributes.cs index b5bde22057..ccba51e840 100644 --- a/src/mscorlib/src/System/Runtime/InteropServices/Attributes.cs +++ b/src/mscorlib/src/System/Runtime/InteropServices/Attributes.cs @@ -4,33 +4,14 @@ //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// -namespace System.Runtime.InteropServices{ - using System; - using System.Reflection; - using System.Diagnostics; - using System.Diagnostics.Contracts; - - [AttributeUsage(AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)] - public sealed class UnmanagedFunctionPointerAttribute : Attribute - { - CallingConvention m_callingConvention; - - public UnmanagedFunctionPointerAttribute(CallingConvention callingConvention) { m_callingConvention = callingConvention; } - - public CallingConvention CallingConvention { get { return m_callingConvention; } } - - public CharSet CharSet; - public bool BestFitMapping; - public bool ThrowOnUnmappableChar; - - // This field is ignored and marshaling behaves as if it was true (for historical reasons). - public bool SetLastError; - - // P/Invoke via delegate always preserves signature, HRESULT swapping is not supported. - //public bool PreserveSig; - } +using System; +using System.Reflection; +using System.Diagnostics; +using System.Diagnostics.Contracts; +namespace System.Runtime.InteropServices +{ [AttributeUsage(AttributeTargets.Interface | AttributeTargets.Enum | AttributeTargets.Struct | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)] public sealed class TypeIdentifierAttribute : Attribute { @@ -118,7 +99,6 @@ namespace System.Runtime.InteropServices{ public ClassInterfaceAttribute(ClassInterfaceType classInterfaceType) { _val = classInterfaceType; - } public ClassInterfaceAttribute(short classInterfaceType) { @@ -127,17 +107,6 @@ namespace System.Runtime.InteropServices{ public ClassInterfaceType Value { get { return _val; } } } - [AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Interface | AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Delegate | AttributeTargets.Enum | AttributeTargets.Field | AttributeTargets.Method | AttributeTargets.Property, Inherited = false)] - public sealed class ComVisibleAttribute : Attribute - { - internal bool _val; - public ComVisibleAttribute(bool visibility) - { - _val = visibility; - } - public bool Value { get { return _val; } } - } - [AttributeUsage(AttributeTargets.Method, Inherited = false)] public sealed class LCIDConversionAttribute : Attribute { @@ -146,7 +115,7 @@ namespace System.Runtime.InteropServices{ { _val = lcid; } - public int Value { get {return _val;} } + public int Value { get { return _val; } } } [AttributeUsage(AttributeTargets.Class, Inherited = false)] @@ -157,10 +126,10 @@ namespace System.Runtime.InteropServices{ { _val = progId; } - public String Value { get {return _val;} } + public String Value { get { return _val; } } } - [AttributeUsage(AttributeTargets.Class, Inherited = true)] + [AttributeUsage(AttributeTargets.Class, Inherited = true)] public sealed class ComSourceInterfacesAttribute : Attribute { internal String _val; @@ -184,137 +153,7 @@ namespace System.Runtime.InteropServices{ { _val = sourceInterface1.FullName + "\0" + sourceInterface2.FullName + "\0" + sourceInterface3.FullName + "\0" + sourceInterface4.FullName; } - public String Value { get {return _val;} } - } - - [Serializable] - public enum VarEnum - { - VT_EMPTY = 0, - VT_NULL = 1, - VT_I2 = 2, - VT_I4 = 3, - VT_R4 = 4, - VT_R8 = 5, - VT_CY = 6, - VT_DATE = 7, - VT_BSTR = 8, - VT_DISPATCH = 9, - VT_ERROR = 10, - VT_BOOL = 11, - VT_VARIANT = 12, - VT_UNKNOWN = 13, - VT_DECIMAL = 14, - VT_I1 = 16, - VT_UI1 = 17, - VT_UI2 = 18, - VT_UI4 = 19, - VT_I8 = 20, - VT_UI8 = 21, - VT_INT = 22, - VT_UINT = 23, - VT_VOID = 24, - VT_HRESULT = 25, - VT_PTR = 26, - VT_SAFEARRAY = 27, - VT_CARRAY = 28, - VT_USERDEFINED = 29, - VT_LPSTR = 30, - VT_LPWSTR = 31, - VT_RECORD = 36, - VT_FILETIME = 64, - VT_BLOB = 65, - VT_STREAM = 66, - VT_STORAGE = 67, - VT_STREAMED_OBJECT = 68, - VT_STORED_OBJECT = 69, - VT_BLOB_OBJECT = 70, - VT_CF = 71, - VT_CLSID = 72, - VT_VECTOR = 0x1000, - VT_ARRAY = 0x2000, - VT_BYREF = 0x4000 - } - - [Serializable] - // Note that this enum should remain in-sync with the CorNativeType enum in corhdr.h - public enum UnmanagedType - { - Bool = 0x2, // 4 byte boolean value (true != 0, false == 0) - - I1 = 0x3, // 1 byte signed value - - U1 = 0x4, // 1 byte unsigned value - - I2 = 0x5, // 2 byte signed value - - U2 = 0x6, // 2 byte unsigned value - - I4 = 0x7, // 4 byte signed value - - U4 = 0x8, // 4 byte unsigned value - - I8 = 0x9, // 8 byte signed value - - U8 = 0xa, // 8 byte unsigned value - - R4 = 0xb, // 4 byte floating point - - R8 = 0xc, // 8 byte floating point - - Currency = 0xf, // A currency - - BStr = 0x13, // OLE Unicode BSTR - - LPStr = 0x14, // Ptr to SBCS string - - LPWStr = 0x15, // Ptr to Unicode string - - LPTStr = 0x16, // Ptr to OS preferred (SBCS/Unicode) string - - ByValTStr = 0x17, // OS preferred (SBCS/Unicode) inline string (only valid in structs) - - IUnknown = 0x19, // COM IUnknown pointer. - - IDispatch = 0x1a, // COM IDispatch pointer - - Struct = 0x1b, // Structure - - Interface = 0x1c, // COM interface - - SafeArray = 0x1d, // OLE SafeArray - - ByValArray = 0x1e, // Array of fixed size (only valid in structs) - - SysInt = 0x1f, // Hardware natural sized signed integer - - SysUInt = 0x20, - - VBByRefStr = 0x22, - - AnsiBStr = 0x23, // OLE BSTR containing SBCS characters - - TBStr = 0x24, // Ptr to OS preferred (SBCS/Unicode) BSTR - - VariantBool = 0x25, // OLE defined BOOLEAN (2 bytes, true == -1, false == 0) - - FunctionPtr = 0x26, // Function pointer - - AsAny = 0x28, // Paired with Object type and does runtime marshalling determination - - LPArray = 0x2a, // C style array - - LPStruct = 0x2b, // Pointer to a structure - - CustomMarshaler = 0x2c, - - Error = 0x2d, - - IInspectable = 0x2e, - - HString = 0x2f, // Windows Runtime HSTRING - - LPUTF8Str = 0x30, // UTF8 string + public String Value { get { return _val; } } } [AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Field | AttributeTargets.ReturnValue, Inherited = false)] @@ -403,11 +242,11 @@ namespace System.Runtime.InteropServices{ public UnmanagedType Value { get { return _val; } } // Fields used with SubType = SafeArray. - public VarEnum SafeArraySubType; - public Type SafeArrayUserDefinedSubType; + public VarEnum SafeArraySubType; + public Type SafeArrayUserDefinedSubType; // Field used with iid_is attribute (interface pointers). - public int IidParameterIndex; + public int IidParameterIndex; // Fields used with SubType = ByValArray and LPArray. // Array size = parameter(PI) * PM + C @@ -639,7 +478,6 @@ namespace System.Runtime.InteropServices{ public CallingConvention CallingConvention; public bool BestFitMapping; public bool ThrowOnUnmappableChar; - } [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct, Inherited = false)] diff --git a/src/mscorlib/src/System/Runtime/InteropServices/BStrWrapper.cs b/src/mscorlib/src/System/Runtime/InteropServices/BStrWrapper.cs index d36f8cfa39..77c38139cd 100644 --- a/src/mscorlib/src/System/Runtime/InteropServices/BStrWrapper.cs +++ b/src/mscorlib/src/System/Runtime/InteropServices/BStrWrapper.cs @@ -11,11 +11,12 @@ ** =============================================================================*/ -namespace System.Runtime.InteropServices { - - using System; - using System.Security; +using System; +using System.Security; + +namespace System.Runtime.InteropServices +{ [Serializable] public sealed class BStrWrapper { @@ -29,9 +30,9 @@ namespace System.Runtime.InteropServices { m_WrappedObject = (String)value; } - public String WrappedObject + public String WrappedObject { - get + get { return m_WrappedObject; } diff --git a/src/mscorlib/src/System/Runtime/InteropServices/COMException.cs b/src/mscorlib/src/System/Runtime/InteropServices/COMException.cs index 87e6be6d4e..889a74f6bc 100644 --- a/src/mscorlib/src/System/Runtime/InteropServices/COMException.cs +++ b/src/mscorlib/src/System/Runtime/InteropServices/COMException.cs @@ -12,55 +12,63 @@ ** =============================================================================*/ -namespace System.Runtime.InteropServices { - using System; - using System.Runtime.Serialization; - using System.Globalization; - using System.Security; - using Microsoft.Win32; +using System; +using System.Runtime.Serialization; +using System.Globalization; +using System.Security; +using Microsoft.Win32; +namespace System.Runtime.InteropServices +{ // Exception for COM Interop errors where we don't recognize the HResult. // [Serializable] - public class COMException : ExternalException { - public COMException() - : base(Environment.GetResourceString("Arg_COMException")) + public class COMException : ExternalException + { + public COMException() + : base(SR.Arg_COMException) { - SetErrorCode(__HResults.E_FAIL); + HResult = __HResults.E_FAIL; } - - public COMException(String message) + + public COMException(String message) : base(message) { - SetErrorCode(__HResults.E_FAIL); + HResult = __HResults.E_FAIL; } - - public COMException(String message, Exception inner) - : base(message, inner) { - SetErrorCode(__HResults.E_FAIL); + + public COMException(String message, Exception inner) + : base(message, inner) + { + HResult = __HResults.E_FAIL; } - - public COMException(String message,int errorCode) - : base(message) { - SetErrorCode(errorCode); + + public COMException(String message, int errorCode) + : base(message) + { + HResult = errorCode; } - protected COMException(SerializationInfo info, StreamingContext context) : base(info, context) { + protected COMException(SerializationInfo info, StreamingContext context) : base(info, context) + { } - public override String ToString() { + public override String ToString() + { String message = Message; String s; String _className = GetType().ToString(); s = _className + " (0x" + HResult.ToString("X8", CultureInfo.InvariantCulture) + ")"; - if (!(message == null || message.Length <= 0)) { + if (!(message == null || message.Length <= 0)) + { s = s + ": " + message; } Exception _innerException = InnerException; - if (_innerException!=null) { + if (_innerException != null) + { s = s + " ---> " + _innerException.ToString(); } @@ -70,7 +78,5 @@ namespace System.Runtime.InteropServices { return s; } - - } } diff --git a/src/mscorlib/src/System/Runtime/InteropServices/CallingConvention.cs b/src/mscorlib/src/System/Runtime/InteropServices/CallingConvention.cs deleted file mode 100644 index 2ef1cf496e..0000000000 --- a/src/mscorlib/src/System/Runtime/InteropServices/CallingConvention.cs +++ /dev/null @@ -1,21 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -//////////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////////// -namespace System.Runtime.InteropServices { - - using System; - // Used for the CallingConvention named argument to the DllImport attribute - [Serializable] - public enum CallingConvention - { - Winapi = 1, - Cdecl = 2, - StdCall = 3, - ThisCall = 4, - FastCall = 5, - } - -} diff --git a/src/mscorlib/src/System/Runtime/InteropServices/CharSet.cs b/src/mscorlib/src/System/Runtime/InteropServices/CharSet.cs deleted file mode 100644 index e60d676557..0000000000 --- a/src/mscorlib/src/System/Runtime/InteropServices/CharSet.cs +++ /dev/null @@ -1,23 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -//////////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////////// -namespace System.Runtime.InteropServices { - using System; - // Use this in P/Direct function prototypes to specify - // which character set to use when marshalling Strings. - // Using Ansi will marshal the strings as 1 byte char*'s. - // Using Unicode will marshal the strings as 2 byte wchar*'s. - // Generally you probably want to use Auto, which does the - // right thing 99% of the time. - [Serializable] - public enum CharSet - { - None = 1, // User didn't specify how to marshal strings. - Ansi = 2, // Strings should be marshalled as ANSI 1 byte chars. - Unicode = 3, // Strings should be marshalled as Unicode 2 byte chars. - Auto = 4, // Marshal Strings in the right way for the target system. - } -} diff --git a/src/mscorlib/src/System/Runtime/InteropServices/ComEventsHelper.cs b/src/mscorlib/src/System/Runtime/InteropServices/ComEventsHelper.cs index 82692c1c54..8198d9fd18 100644 --- a/src/mscorlib/src/System/Runtime/InteropServices/ComEventsHelper.cs +++ b/src/mscorlib/src/System/Runtime/InteropServices/ComEventsHelper.cs @@ -10,104 +10,105 @@ ** managed delegates to COM's connection point based events. ** **/ -namespace System.Runtime.InteropServices { - // - // #ComEventsFeature - // - // code:#ComEventsFeature defines two public methods allowing to add/remove .NET delegates handling - // events from COM objects. Those methods are defined as part of code:ComEventsHelper static class - // * code:ComEventsHelper.Combine - will create/reuse-an-existing COM event sink and register the - // specified delegate to be raised when corresponding COM event is raised - // * code:ComEventsHelper.Remove - // - // - // To bind an event handler to the COM object you need to provide the following data: - // * rcw - the instance of the COM object you want to bind to - // * iid - Guid of the source interface you want the sink to implement - // * dispid - dispatch identifier of the event on the source interface you are interested in - // * d - delegate to invoked when corresponding COM event is raised. - // - // #ComEventsArchitecture: - // In COM world, events are handled by so-called event sinks. What these are? COM-based Object Models - // (OMs) define "source" interfaces that need to be implemented by the COM clients to receive events. So, - // event sinks are COM objects implementing a source interfaces. Once an event sink is passed to the COM - // server (through a mechanism known as 'binding/advising to connection point'), COM server will be - // calling source interface methods to "fire events" (advising, connection points, firing events etc. - - // is all COM jargon). - // - // There are few interesting obervations about source interfaces. Usually source interfaces are defined - // as 'dispinterface' - meaning that only late-bound invocations on this interface are allowed. Even - // though it is not illegal to use early bound invocations on source interfaces - the practice is - // discouraged because of versioning concerns. - // - // Notice also that each COM server object might define multiple source interfaces and hence have - // multiple connection points (each CP handles exactly one source interface). COM objects that want to - // fire events are required to implement IConnectionPointContainer interface which is used by the COM - // clients to discovery connection poitns - objects implementing IConnectionPoint interface. Once - // connection point is found - clients can bind to it using IConnectionPoint::Advise (see - // code:ComEventsSink.Advise). - // - // The idea behind code:#ComEventsFeature is to write a "universal event sink" COM component that is - // generic enough to handle all late-bound event firings and invoke corresponding COM delegates (through - // reflection). - // - // When delegate is registered (using code:ComEventsHelper.Combine) we will verify we have corresponding - // event sink created and bound. - // - // But what happens when COM events are fired? code:ComEventsSink.Invoke implements IDispatch::Invoke method - // and this is the entry point that is called. Once our event sink is invoked, we need to find the - // corresponding delegate to invoke . We need to match the dispid of the call that is coming in to a - // dispid of .NET delegate that has been registered for this object. Once this is found we do call the - // delegates using reflection (code:ComEventsMethod.Invoke). - // - // #ComEventsArgsMarshalling - // Notice, that we may not have a delegate registered against every method on the source interface. If we - // were to marshal all the input parameters for methods that do not reach user code - we would end up - // generatic RCWs that are not reachable for user code (the inconvenience it might create is there will - // be RCWs that users can not call Marshal.ReleaseComObject on to explicitly manage the lifetime of these - // COM objects). The above behavior was one of the shortcoimings of legacy TLBIMP's implementation of COM - // event sinking. In our code we will not marshal any data if there is no delegate registered to handle - // the event. (code:ComEventsMethod.Invoke) - // - // #ComEventsFinalization: - // Additional area of interest is when COM sink should be unadvised from the connection point. Legacy - // TLBIMP's implementation of COM event sinks will unadvises the sink when corresponding RCW is GCed. - // This is achieved by rooting the event sinks in a finalizable object stored in RCW's property bag - // (using Marshal.SetComObjectData). Hence, once RCW is no longer reachable - the finalizer is called and - // it would unadvise all the event sinks. We are employing the same strategy here. See storing an - // instance in the RCW at code:ComEventsInfo.FromObject and undadvsing the sinks at - // code:ComEventsInfo.~ComEventsInfo - // - // Classes of interest: - // * code:ComEventsHelpers - defines public methods but there are also a number of internal classes that - // implement the actual COM event sink: - // * code:ComEventsInfo - represents a finalizable container for all event sinks for a particular RCW. - // Lifetime of this instance corresponds to the lifetime of the RCW object - // * code:ComEventsSink - represents a single event sink. Maintains an internal pointer to the next - // instance (in a singly linked list). A collection of code:ComEventsSink is stored at - // code:ComEventsInfo._sinks - // * code:ComEventsMethod - represents a single method from the source interface which has .NET delegates - // attached to it. Maintains an internal pointer to the next instance (in a singly linked list). A - // collection of code:ComEventMethod is stored at code:ComEventsSink._methods - // - // #ComEventsRetValIssue: - // Issue: normally, COM events would not return any value. However, it may happen as described in - // http://support.microsoft.com/kb/810228. Such design might represent a problem for us - e.g. what is - // the return value of a chain of delegates - is it the value of the last call in the chain or the the - // first one? As the above KB article indicates, in cases where OM has events returning values, it is - // suggested that people implement their event sink by explicitly implementing the source interface. This - // means that the problem is already quite complex and we should not be dealing with it - see - // code:ComEventsMethod.Invoke - - using System; - using System.Runtime.Remoting; - +// +// #ComEventsFeature +// +// code:#ComEventsFeature defines two public methods allowing to add/remove .NET delegates handling +// events from COM objects. Those methods are defined as part of code:ComEventsHelper static class +// * code:ComEventsHelper.Combine - will create/reuse-an-existing COM event sink and register the +// specified delegate to be raised when corresponding COM event is raised +// * code:ComEventsHelper.Remove +// +// +// To bind an event handler to the COM object you need to provide the following data: +// * rcw - the instance of the COM object you want to bind to +// * iid - Guid of the source interface you want the sink to implement +// * dispid - dispatch identifier of the event on the source interface you are interested in +// * d - delegate to invoked when corresponding COM event is raised. +// +// #ComEventsArchitecture: +// In COM world, events are handled by so-called event sinks. What these are? COM-based Object Models +// (OMs) define "source" interfaces that need to be implemented by the COM clients to receive events. So, +// event sinks are COM objects implementing a source interfaces. Once an event sink is passed to the COM +// server (through a mechanism known as 'binding/advising to connection point'), COM server will be +// calling source interface methods to "fire events" (advising, connection points, firing events etc. - +// is all COM jargon). +// +// There are few interesting obervations about source interfaces. Usually source interfaces are defined +// as 'dispinterface' - meaning that only late-bound invocations on this interface are allowed. Even +// though it is not illegal to use early bound invocations on source interfaces - the practice is +// discouraged because of versioning concerns. +// +// Notice also that each COM server object might define multiple source interfaces and hence have +// multiple connection points (each CP handles exactly one source interface). COM objects that want to +// fire events are required to implement IConnectionPointContainer interface which is used by the COM +// clients to discovery connection poitns - objects implementing IConnectionPoint interface. Once +// connection point is found - clients can bind to it using IConnectionPoint::Advise (see +// code:ComEventsSink.Advise). +// +// The idea behind code:#ComEventsFeature is to write a "universal event sink" COM component that is +// generic enough to handle all late-bound event firings and invoke corresponding COM delegates (through +// reflection). +// +// When delegate is registered (using code:ComEventsHelper.Combine) we will verify we have corresponding +// event sink created and bound. +// +// But what happens when COM events are fired? code:ComEventsSink.Invoke implements IDispatch::Invoke method +// and this is the entry point that is called. Once our event sink is invoked, we need to find the +// corresponding delegate to invoke . We need to match the dispid of the call that is coming in to a +// dispid of .NET delegate that has been registered for this object. Once this is found we do call the +// delegates using reflection (code:ComEventsMethod.Invoke). +// +// #ComEventsArgsMarshalling +// Notice, that we may not have a delegate registered against every method on the source interface. If we +// were to marshal all the input parameters for methods that do not reach user code - we would end up +// generatic RCWs that are not reachable for user code (the inconvenience it might create is there will +// be RCWs that users can not call Marshal.ReleaseComObject on to explicitly manage the lifetime of these +// COM objects). The above behavior was one of the shortcoimings of legacy TLBIMP's implementation of COM +// event sinking. In our code we will not marshal any data if there is no delegate registered to handle +// the event. (code:ComEventsMethod.Invoke) +// +// #ComEventsFinalization: +// Additional area of interest is when COM sink should be unadvised from the connection point. Legacy +// TLBIMP's implementation of COM event sinks will unadvises the sink when corresponding RCW is GCed. +// This is achieved by rooting the event sinks in a finalizable object stored in RCW's property bag +// (using Marshal.SetComObjectData). Hence, once RCW is no longer reachable - the finalizer is called and +// it would unadvise all the event sinks. We are employing the same strategy here. See storing an +// instance in the RCW at code:ComEventsInfo.FromObject and undadvsing the sinks at +// code:ComEventsInfo.~ComEventsInfo +// +// Classes of interest: +// * code:ComEventsHelpers - defines public methods but there are also a number of internal classes that +// implement the actual COM event sink: +// * code:ComEventsInfo - represents a finalizable container for all event sinks for a particular RCW. +// Lifetime of this instance corresponds to the lifetime of the RCW object +// * code:ComEventsSink - represents a single event sink. Maintains an internal pointer to the next +// instance (in a singly linked list). A collection of code:ComEventsSink is stored at +// code:ComEventsInfo._sinks +// * code:ComEventsMethod - represents a single method from the source interface which has .NET delegates +// attached to it. Maintains an internal pointer to the next instance (in a singly linked list). A +// collection of code:ComEventMethod is stored at code:ComEventsSink._methods +// +// #ComEventsRetValIssue: +// Issue: normally, COM events would not return any value. However, it may happen as described in +// http://support.microsoft.com/kb/810228. Such design might represent a problem for us - e.g. what is +// the return value of a chain of delegates - is it the value of the last call in the chain or the the +// first one? As the above KB article indicates, in cases where OM has events returning values, it is +// suggested that people implement their event sink by explicitly implementing the source interface. This +// means that the problem is already quite complex and we should not be dealing with it - see +// code:ComEventsMethod.Invoke + +using System; +using System.Runtime.Remoting; + +namespace System.Runtime.InteropServices +{ /// <summary> /// The static methods provided in ComEventsHelper allow using .NET delegates to subscribe to events /// raised COM objects. /// </summary> - public static class ComEventsHelper { - + public static class ComEventsHelper + { /// <summary> /// Adds a delegate to the invocation list of events originating from the COM object. /// </summary> @@ -115,21 +116,24 @@ 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> - public static void Combine(object rcw, Guid iid, int dispid, System.Delegate d) { - + public static void Combine(object rcw, Guid iid, int dispid, System.Delegate d) + { rcw = UnwrapIfTransparentProxy(rcw); - lock (rcw) { + lock (rcw) + { ComEventsInfo eventsInfo = ComEventsInfo.FromObject(rcw); ComEventsSink sink = eventsInfo.FindSink(ref iid); - if (sink == null) { + if (sink == null) + { sink = eventsInfo.AddSink(ref iid); } ComEventsMethod method = sink.FindMethod(dispid); - if (method == null) { + if (method == null) + { method = sink.AddMethod(dispid); } @@ -145,12 +149,12 @@ 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> - public static Delegate Remove(object rcw, Guid iid, int dispid, System.Delegate d) { - + public static Delegate Remove(object rcw, Guid iid, int dispid, System.Delegate d) + { rcw = UnwrapIfTransparentProxy(rcw); - lock (rcw) { - + lock (rcw) + { ComEventsInfo eventsInfo = ComEventsInfo.Find(rcw); if (eventsInfo == null) return null; @@ -163,15 +167,18 @@ namespace System.Runtime.InteropServices { method.RemoveDelegate(d); - if (method.Empty) { + if (method.Empty) + { // removed the last event handler for this dispid - need to remove dispid handler method = sink.RemoveMethod(method); } - if (method == null) { + if (method == null) + { // removed last dispid handler for this sink - need to remove the sink sink = eventsInfo.RemoveSink(sink); } - if (sink == null) { + if (sink == null) + { // removed last sink for this rcw - need to remove all traces of event info Marshal.SetComObjectData(rcw, typeof(ComEventsInfo), null); GC.SuppressFinalize(eventsInfo); @@ -186,5 +193,4 @@ namespace System.Runtime.InteropServices { return rcw; } } - } diff --git a/src/mscorlib/src/System/Runtime/InteropServices/ComEventsInfo.cs b/src/mscorlib/src/System/Runtime/InteropServices/ComEventsInfo.cs index 2456ba35bf..0fbe34db8d 100644 --- a/src/mscorlib/src/System/Runtime/InteropServices/ComEventsInfo.cs +++ b/src/mscorlib/src/System/Runtime/InteropServices/ComEventsInfo.cs @@ -11,64 +11,70 @@ ** **/ -namespace System.Runtime.InteropServices { - +namespace System.Runtime.InteropServices +{ using System; using ComTypes = System.Runtime.InteropServices.ComTypes; // see code:ComEventsHelper#ComEventsArchitecture - internal class ComEventsInfo { - - -#region fields + internal class ComEventsInfo + { + #region fields private ComEventsSink _sinks; private object _rcw; -#endregion + #endregion -#region ctor/dtor + #region ctor/dtor - ComEventsInfo(object rcw) { + private ComEventsInfo(object rcw) + { _rcw = rcw; } - ~ComEventsInfo() { + ~ComEventsInfo() + { // see code:ComEventsHelper#ComEventsFinalization _sinks = ComEventsSink.RemoveAll(_sinks); } -#endregion + #endregion -#region static methods + #region static methods - internal static ComEventsInfo Find(object rcw) { + 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) - internal static ComEventsInfo FromObject(object rcw) { + internal static ComEventsInfo FromObject(object rcw) + { ComEventsInfo eventsInfo = Find(rcw); - if (eventsInfo == null) { + if (eventsInfo == null) + { eventsInfo = new ComEventsInfo(rcw); Marshal.SetComObjectData(rcw, typeof(ComEventsInfo), eventsInfo); } return eventsInfo; } -#endregion + #endregion -#region internal methods + #region internal methods - internal ComEventsSink FindSink(ref Guid iid) { + internal ComEventsSink FindSink(ref Guid iid) + { return ComEventsSink.Find(_sinks, ref iid); } // it is caller's responsibility to call this method under lock(rcw) - internal ComEventsSink AddSink(ref Guid iid) { + internal ComEventsSink AddSink(ref Guid iid) + { ComEventsSink sink = new ComEventsSink(_rcw, iid); _sinks = ComEventsSink.Add(_sinks, sink); @@ -76,12 +82,12 @@ namespace System.Runtime.InteropServices { } // it is caller's responsibility to call this method under lock(rcw) - internal ComEventsSink RemoveSink(ComEventsSink sink) { + internal ComEventsSink RemoveSink(ComEventsSink sink) + { _sinks = ComEventsSink.Remove(_sinks, sink); return _sinks; } -#endregion - + #endregion } } diff --git a/src/mscorlib/src/System/Runtime/InteropServices/ComEventsMethod.cs b/src/mscorlib/src/System/Runtime/InteropServices/ComEventsMethod.cs index c2f56b0580..f7e84cabb5 100644 --- a/src/mscorlib/src/System/Runtime/InteropServices/ComEventsMethod.cs +++ b/src/mscorlib/src/System/Runtime/InteropServices/ComEventsMethod.cs @@ -10,6 +10,7 @@ ** managed delegates to COM's connection point based events. ** **/ + using System; using System.Collections.Generic; using System.Text; @@ -18,11 +19,11 @@ using System.Runtime.InteropServices; using System.Reflection; -namespace System.Runtime.InteropServices { - +namespace System.Runtime.InteropServices +{ // see code:ComEventsHelper#ComEventsArchitecture - internal class ComEventsMethod { - + internal class ComEventsMethod + { // This delegate wrapper class handles dynamic invocation of delegates. The reason for the wrapper's // existence is that under certain circumstances we need to coerce arguments to types expected by the // delegates signature. Normally, reflection (Delegate.DynamicInvoke) handles types coercion @@ -30,18 +31,21 @@ namespace System.Runtime.InteropServices { // reflection by design does not do the coercion. Since we need to be compatible with COM interop // handling of this scenario - we are pre-processing delegate's signature by looking for 'ref enums' // and cache the types required for such coercion. - internal class DelegateWrapper { + internal class DelegateWrapper + { private Delegate _d; private bool _once = false; private int _expectedParamsCount; private Type[] _cachedTargetTypes; - public DelegateWrapper(Delegate d) { + public DelegateWrapper(Delegate d) + { _d = d; } - public Delegate Delegate { + public Delegate Delegate + { get { return _d; } set { _d = value; } } @@ -54,42 +58,50 @@ namespace System.Runtime.InteropServices { /// Since multicast delegate's built-in chaining supports only chaining instances of the same type, /// we need to complement this design by using an explicit linked list data structure. /// </summary> - private DelegateWrapper [] _delegateWrappers; + private DelegateWrapper[] _delegateWrappers; private int _dispid; private ComEventsMethod _next; #endregion - + #region ctor - - internal ComEventsMethod(int dispid) { + + internal ComEventsMethod(int dispid) + { _delegateWrappers = null; _dispid = dispid; } - + #endregion - + #region static internal methods - - internal static ComEventsMethod Find(ComEventsMethod methods, int dispid) { - while (methods != null && methods._dispid != dispid) { + + internal static ComEventsMethod Find(ComEventsMethod methods, int dispid) + { + while (methods != null && methods._dispid != dispid) + { methods = methods._next; } return methods; } - internal static ComEventsMethod Add(ComEventsMethod methods, ComEventsMethod method) { + internal static ComEventsMethod Add(ComEventsMethod methods, ComEventsMethod method) + { method._next = methods; return method; } - internal static ComEventsMethod Remove(ComEventsMethod methods, ComEventsMethod method) { - if (methods == method) { + internal static ComEventsMethod Remove(ComEventsMethod methods, ComEventsMethod method) + { + if (methods == method) + { methods = methods._next; - } else { + } + else + { ComEventsMethod current = methods; while (current != null && current._next != method) current = current._next; @@ -100,28 +112,34 @@ namespace System.Runtime.InteropServices { return methods; } -#endregion -#region public properties / methods + #endregion + #region public properties / methods - internal bool Empty { + internal bool Empty + { get { return _delegateWrappers == null || _delegateWrappers.Length == 0; } } - internal void AddDelegate(Delegate d) { + internal void AddDelegate(Delegate d) + { int count = 0; - if (_delegateWrappers != null) { + if (_delegateWrappers != null) + { count = _delegateWrappers.Length; } - for (int i = 0; i < count; i++) { - if (_delegateWrappers[i].Delegate.GetType() == d.GetType()) { + for (int i = 0; i < count; i++) + { + if (_delegateWrappers[i].Delegate.GetType() == d.GetType()) + { _delegateWrappers[i].Delegate = Delegate.Combine(_delegateWrappers[i].Delegate, d); return; } } - DelegateWrapper [] newDelegateWrappers = new DelegateWrapper[count + 1]; - if (count > 0) { + DelegateWrapper[] newDelegateWrappers = new DelegateWrapper[count + 1]; + if (count > 0) + { _delegateWrappers.CopyTo(newDelegateWrappers, 0); } @@ -131,13 +149,15 @@ namespace System.Runtime.InteropServices { _delegateWrappers = newDelegateWrappers; } - internal void RemoveDelegate(Delegate d) { - + internal void RemoveDelegate(Delegate d) + { int count = _delegateWrappers.Length; int removeIdx = -1; - for (int i = 0; i < count; i++) { - if (_delegateWrappers[i].Delegate.GetType() == d.GetType()) { + for (int i = 0; i < count; i++) + { + if (_delegateWrappers[i].Delegate.GetType() == d.GetType()) + { removeIdx = i; break; } @@ -147,25 +167,29 @@ namespace System.Runtime.InteropServices { return; Delegate newDelegate = Delegate.Remove(_delegateWrappers[removeIdx].Delegate, d); - if (newDelegate != null) { + if (newDelegate != null) + { _delegateWrappers[removeIdx].Delegate = newDelegate; return; } // now remove the found entry from the _delegates array - if (count == 1) { + if (count == 1) + { _delegateWrappers = null; return; } - DelegateWrapper [] newDelegateWrappers = new DelegateWrapper[count - 1]; + DelegateWrapper[] newDelegateWrappers = new DelegateWrapper[count - 1]; int j = 0; - while (j < removeIdx) { + while (j < removeIdx) + { newDelegateWrappers[j] = _delegateWrappers[j]; j++; } - while (j < count-1) { + while (j < count - 1) + { newDelegateWrappers[j] = _delegateWrappers[j + 1]; j++; } diff --git a/src/mscorlib/src/System/Runtime/InteropServices/ComEventsSink.cs b/src/mscorlib/src/System/Runtime/InteropServices/ComEventsSink.cs index f2b22e3ceb..08f27dc038 100644 --- a/src/mscorlib/src/System/Runtime/InteropServices/ComEventsSink.cs +++ b/src/mscorlib/src/System/Runtime/InteropServices/ComEventsSink.cs @@ -11,14 +11,15 @@ ** **/ -namespace System.Runtime.InteropServices { - using System; - using System.Diagnostics; +using System; +using System.Diagnostics; +namespace System.Runtime.InteropServices +{ // see code:ComEventsHelper#ComEventsArchitecture internal class ComEventsSink : ICustomQueryInterface { -#region private fields + #region private fields private Guid _iidSourceItf; private ComTypes.IConnectionPoint _connectionPoint; @@ -26,38 +27,43 @@ namespace System.Runtime.InteropServices { private ComEventsMethod _methods; private ComEventsSink _next; -#endregion + #endregion - -#region ctor - internal ComEventsSink(object rcw, Guid iid) { + #region ctor + + internal ComEventsSink(object rcw, Guid iid) + { _iidSourceItf = iid; this.Advise(rcw); - } + } -#endregion + #endregion - -#region static members - internal static ComEventsSink Find(ComEventsSink sinks, ref Guid iid) { + #region static members + internal static ComEventsSink Find(ComEventsSink sinks, ref Guid iid) + { ComEventsSink sink = sinks; - while (sink != null && sink._iidSourceItf != iid) { + while (sink != null && sink._iidSourceItf != iid) + { sink = sink._next; } return sink; } - internal static ComEventsSink Add(ComEventsSink sinks, ComEventsSink sink) { + internal static ComEventsSink Add(ComEventsSink sinks, ComEventsSink sink) + { sink._next = sinks; return sink; } - internal static ComEventsSink RemoveAll(ComEventsSink sinks) { - while (sinks != null) { + internal static ComEventsSink RemoveAll(ComEventsSink sinks) + { + while (sinks != null) + { sinks.Unadvise(); sinks = sinks._next; } @@ -65,18 +71,23 @@ namespace System.Runtime.InteropServices { return null; } - internal static ComEventsSink Remove(ComEventsSink sinks, ComEventsSink sink) { + 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"); - if (sink == sinks) { + if (sink == sinks) + { sinks = sinks._next; - } else { + } + else + { ComEventsSink current = sinks; while (current != null && current._next != sink) current = current._next; - if (current != null) { + if (current != null) + { current._next = sink._next; } } @@ -84,35 +95,40 @@ namespace System.Runtime.InteropServices { sink.Unadvise(); return sinks; - } + } -#endregion + #endregion -#region public methods + #region public methods - public ComEventsMethod RemoveMethod(ComEventsMethod method) { + public ComEventsMethod RemoveMethod(ComEventsMethod method) + { _methods = ComEventsMethod.Remove(_methods, method); return _methods; } - public ComEventsMethod FindMethod(int dispid) { + public ComEventsMethod FindMethod(int dispid) + { return ComEventsMethod.Find(_methods, dispid); } - public ComEventsMethod AddMethod(int dispid) { + public ComEventsMethod AddMethod(int dispid) + { ComEventsMethod method = new ComEventsMethod(dispid); _methods = ComEventsMethod.Add(_methods, method); return method; - } + } -#endregion + #endregion - static Guid IID_IManagedObject = new Guid("{C3FCC19E-A970-11D2-8B5A-00A0C9B7C9C4}"); + private static Guid IID_IManagedObject = new Guid("{C3FCC19E-A970-11D2-8B5A-00A0C9B7C9C4}"); - CustomQueryInterfaceResult ICustomQueryInterface.GetInterface(ref Guid iid, out IntPtr ppv) { + CustomQueryInterfaceResult ICustomQueryInterface.GetInterface(ref Guid iid, out IntPtr ppv) + { ppv = IntPtr.Zero; - if (iid == this._iidSourceItf || iid == typeof(NativeMethods.IDispatch).GUID) { + if (iid == _iidSourceItf || iid == typeof(NativeMethods.IDispatch).GUID) + { ppv = Marshal.GetComInterfaceForObject(this, typeof(NativeMethods.IDispatch), CustomQueryInterfaceMode.Ignore); return CustomQueryInterfaceResult.Handled; } @@ -124,10 +140,11 @@ namespace System.Runtime.InteropServices { return CustomQueryInterfaceResult.NotHandled; } -#region private methods + #region private methods - private void Advise(object rcw) { + private void Advise(object rcw) + { BCLDebug.Assert(_connectionPoint == null, "comevent sink is already advised"); ComTypes.IConnectionPointContainer cpc = (ComTypes.IConnectionPointContainer)rcw; @@ -141,21 +158,26 @@ namespace System.Runtime.InteropServices { _connectionPoint = cp; } - private void Unadvise() { + private void Unadvise() + { BCLDebug.Assert(_connectionPoint != null, "can not unadvise from empty connection point"); - try { + try + { _connectionPoint.Unadvise(_cookie); Marshal.ReleaseComObject(_connectionPoint); - } catch (System.Exception) { + } + catch (System.Exception) + { // swallow all exceptions on unadvise // the host may not be available at this point - } finally { + } + finally + { _connectionPoint = null; } + } - } - -#endregion + #endregion }; } diff --git a/src/mscorlib/src/System/Runtime/InteropServices/ComMemberType.cs b/src/mscorlib/src/System/Runtime/InteropServices/ComMemberType.cs index c61d1b21be..ea99781975 100644 --- a/src/mscorlib/src/System/Runtime/InteropServices/ComMemberType.cs +++ b/src/mscorlib/src/System/Runtime/InteropServices/ComMemberType.cs @@ -4,15 +4,16 @@ //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// -namespace System.Runtime.InteropServices { - using System; +using System; +namespace System.Runtime.InteropServices +{ [Serializable] public enum ComMemberType { - Method = 0, - PropGet = 1, - PropSet = 2 + Method = 0, + PropGet = 1, + PropSet = 2 } } diff --git a/src/mscorlib/src/System/Runtime/InteropServices/ComTypes/IBindCtx.cs b/src/mscorlib/src/System/Runtime/InteropServices/ComTypes/IBindCtx.cs index aac3f59d0f..152f1cd655 100644 --- a/src/mscorlib/src/System/Runtime/InteropServices/ComTypes/IBindCtx.cs +++ b/src/mscorlib/src/System/Runtime/InteropServices/ComTypes/IBindCtx.cs @@ -11,13 +11,13 @@ ** =============================================================================*/ +using System; + namespace System.Runtime.InteropServices.ComTypes { - using System; - [StructLayout(LayoutKind.Sequential)] - public struct BIND_OPTS + public struct BIND_OPTS { public int cbStruct; public int grfFlags; @@ -28,7 +28,7 @@ namespace System.Runtime.InteropServices.ComTypes [Guid("0000000e-0000-0000-C000-000000000046")] [InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)] [ComImport] - public interface IBindCtx + public interface IBindCtx { void RegisterObjectBound([MarshalAs(UnmanagedType.Interface)] Object punk); void RevokeObjectBound([MarshalAs(UnmanagedType.Interface)] Object punk); diff --git a/src/mscorlib/src/System/Runtime/InteropServices/ComTypes/IConnectionPoint.cs b/src/mscorlib/src/System/Runtime/InteropServices/ComTypes/IConnectionPoint.cs index f70973e60d..3933d528a9 100644 --- a/src/mscorlib/src/System/Runtime/InteropServices/ComTypes/IConnectionPoint.cs +++ b/src/mscorlib/src/System/Runtime/InteropServices/ComTypes/IConnectionPoint.cs @@ -11,15 +11,15 @@ ** =============================================================================*/ +using System; + namespace System.Runtime.InteropServices.ComTypes { - using System; - [Guid("B196B286-BAB4-101A-B69C-00AA00341D07")] [InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)] [ComImport] public interface IConnectionPoint - { + { void GetConnectionInterface(out Guid pIID); void GetConnectionPointContainer(out IConnectionPointContainer ppCPC); void Advise([MarshalAs(UnmanagedType.Interface)] Object pUnkSink, out int pdwCookie); diff --git a/src/mscorlib/src/System/Runtime/InteropServices/ComTypes/IConnectionPointContainer.cs b/src/mscorlib/src/System/Runtime/InteropServices/ComTypes/IConnectionPointContainer.cs index fffff3c170..881dd8acfe 100644 --- a/src/mscorlib/src/System/Runtime/InteropServices/ComTypes/IConnectionPointContainer.cs +++ b/src/mscorlib/src/System/Runtime/InteropServices/ComTypes/IConnectionPointContainer.cs @@ -11,11 +11,11 @@ ** =============================================================================*/ +using System; + namespace System.Runtime.InteropServices.ComTypes { - using System; - - [Guid("B196B284-BAB4-101A-B69C-00AA00341D07")] + [Guid("B196B284-BAB4-101A-B69C-00AA00341D07")] [InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)] [ComImport] public interface IConnectionPointContainer diff --git a/src/mscorlib/src/System/Runtime/InteropServices/ComTypes/IEnumConnectionPoints.cs b/src/mscorlib/src/System/Runtime/InteropServices/ComTypes/IEnumConnectionPoints.cs index d667925b7e..32ad1f7f06 100644 --- a/src/mscorlib/src/System/Runtime/InteropServices/ComTypes/IEnumConnectionPoints.cs +++ b/src/mscorlib/src/System/Runtime/InteropServices/ComTypes/IEnumConnectionPoints.cs @@ -11,15 +11,15 @@ ** =============================================================================*/ +using System; + namespace System.Runtime.InteropServices.ComTypes { - using System; - [Guid("B196B285-BAB4-101A-B69C-00AA00341D07")] [InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)] [ComImport] public interface IEnumConnectionPoints - { + { [PreserveSig] int Next(int celt, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 0), Out] IConnectionPoint[] rgelt, IntPtr pceltFetched); [PreserveSig] diff --git a/src/mscorlib/src/System/Runtime/InteropServices/ComTypes/IEnumConnections.cs b/src/mscorlib/src/System/Runtime/InteropServices/ComTypes/IEnumConnections.cs index 8a2b4f0e6f..1acfe54657 100644 --- a/src/mscorlib/src/System/Runtime/InteropServices/ComTypes/IEnumConnections.cs +++ b/src/mscorlib/src/System/Runtime/InteropServices/ComTypes/IEnumConnections.cs @@ -11,15 +11,15 @@ ** =============================================================================*/ +using System; + namespace System.Runtime.InteropServices.ComTypes { - using System; - - [StructLayout(LayoutKind.Sequential, CharSet=CharSet.Unicode)] + [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] public struct CONNECTDATA - { - [MarshalAs(UnmanagedType.Interface)] + { + [MarshalAs(UnmanagedType.Interface)] public Object pUnk; public int dwCookie; } diff --git a/src/mscorlib/src/System/Runtime/InteropServices/ComTypes/IEnumMoniker.cs b/src/mscorlib/src/System/Runtime/InteropServices/ComTypes/IEnumMoniker.cs index 57994b66bc..4513bc86ff 100644 --- a/src/mscorlib/src/System/Runtime/InteropServices/ComTypes/IEnumMoniker.cs +++ b/src/mscorlib/src/System/Runtime/InteropServices/ComTypes/IEnumMoniker.cs @@ -11,14 +11,14 @@ ** =============================================================================*/ +using System; + namespace System.Runtime.InteropServices.ComTypes { - using System; - [Guid("00000102-0000-0000-C000-000000000046")] [InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)] [ComImport] - public interface IEnumMoniker + public interface IEnumMoniker { [PreserveSig] int Next(int celt, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 0), Out] IMoniker[] rgelt, IntPtr pceltFetched); diff --git a/src/mscorlib/src/System/Runtime/InteropServices/ComTypes/IEnumString.cs b/src/mscorlib/src/System/Runtime/InteropServices/ComTypes/IEnumString.cs index f1e9233581..5738a42751 100644 --- a/src/mscorlib/src/System/Runtime/InteropServices/ComTypes/IEnumString.cs +++ b/src/mscorlib/src/System/Runtime/InteropServices/ComTypes/IEnumString.cs @@ -11,14 +11,14 @@ ** =============================================================================*/ +using System; + namespace System.Runtime.InteropServices.ComTypes { - using System; - [Guid("00000101-0000-0000-C000-000000000046")] [InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)] [ComImport] - public interface IEnumString + public interface IEnumString { [PreserveSig] int Next(int celt, [MarshalAs(UnmanagedType.LPArray, ArraySubType = UnmanagedType.LPWStr, SizeParamIndex = 0), Out] String[] rgelt, IntPtr pceltFetched); diff --git a/src/mscorlib/src/System/Runtime/InteropServices/ComTypes/IEnumVARIANT.cs b/src/mscorlib/src/System/Runtime/InteropServices/ComTypes/IEnumVARIANT.cs index ea9b74b7c1..b94ac5e4c9 100644 --- a/src/mscorlib/src/System/Runtime/InteropServices/ComTypes/IEnumVARIANT.cs +++ b/src/mscorlib/src/System/Runtime/InteropServices/ComTypes/IEnumVARIANT.cs @@ -11,17 +11,17 @@ ** =============================================================================*/ +using System; + namespace System.Runtime.InteropServices.ComTypes { - using System; - - [Guid("00020404-0000-0000-C000-000000000046")] + [Guid("00020404-0000-0000-C000-000000000046")] [InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)] [ComImport] public interface IEnumVARIANT { [PreserveSig] - int Next(int celt, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex=0), Out] object[] rgVar, IntPtr pceltFetched); + int Next(int celt, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 0), Out] object[] rgVar, IntPtr pceltFetched); [PreserveSig] int Skip(int celt); diff --git a/src/mscorlib/src/System/Runtime/InteropServices/ComTypes/IMoniker.cs b/src/mscorlib/src/System/Runtime/InteropServices/ComTypes/IMoniker.cs index caee5e7fa3..ea45149b29 100644 --- a/src/mscorlib/src/System/Runtime/InteropServices/ComTypes/IMoniker.cs +++ b/src/mscorlib/src/System/Runtime/InteropServices/ComTypes/IMoniker.cs @@ -11,22 +11,22 @@ ** =============================================================================*/ +using System; + namespace System.Runtime.InteropServices.ComTypes { - using System; - [StructLayout(LayoutKind.Sequential)] - public struct FILETIME + public struct FILETIME { - public int dwLowDateTime; - public int dwHighDateTime; + public int dwLowDateTime; + public int dwHighDateTime; } [Guid("0000000f-0000-0000-C000-000000000046")] [InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)] [ComImport] - public interface IMoniker + public interface IMoniker { // IPersist portion void GetClassID(out Guid pClassID); diff --git a/src/mscorlib/src/System/Runtime/InteropServices/ComTypes/IPersistFile.cs b/src/mscorlib/src/System/Runtime/InteropServices/ComTypes/IPersistFile.cs index a9f118a354..467a9e3a6a 100644 --- a/src/mscorlib/src/System/Runtime/InteropServices/ComTypes/IPersistFile.cs +++ b/src/mscorlib/src/System/Runtime/InteropServices/ComTypes/IPersistFile.cs @@ -11,10 +11,10 @@ ** =============================================================================*/ +using System; + namespace System.Runtime.InteropServices.ComTypes { - using System; - [Guid("0000010b-0000-0000-C000-000000000046")] [InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)] [ComImport] @@ -22,7 +22,7 @@ namespace System.Runtime.InteropServices.ComTypes { // IPersist portion void GetClassID(out Guid pClassID); - + // IPersistFile portion [PreserveSig] int IsDirty(); diff --git a/src/mscorlib/src/System/Runtime/InteropServices/ComTypes/IRunningObjectTable.cs b/src/mscorlib/src/System/Runtime/InteropServices/ComTypes/IRunningObjectTable.cs index bebbdec70c..ffca35ae83 100644 --- a/src/mscorlib/src/System/Runtime/InteropServices/ComTypes/IRunningObjectTable.cs +++ b/src/mscorlib/src/System/Runtime/InteropServices/ComTypes/IRunningObjectTable.cs @@ -11,14 +11,14 @@ ** =============================================================================*/ +using System; + namespace System.Runtime.InteropServices.ComTypes { - using System; - [Guid("00000010-0000-0000-C000-000000000046")] [InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)] [ComImport] - public interface IRunningObjectTable + public interface IRunningObjectTable { int Register(int grfFlags, [MarshalAs(UnmanagedType.Interface)] Object punkObject, IMoniker pmkObjectName); void Revoke(int dwRegister); diff --git a/src/mscorlib/src/System/Runtime/InteropServices/ComTypes/IStream.cs b/src/mscorlib/src/System/Runtime/InteropServices/ComTypes/IStream.cs index 616ecbfa18..1a2d81f7ea 100644 --- a/src/mscorlib/src/System/Runtime/InteropServices/ComTypes/IStream.cs +++ b/src/mscorlib/src/System/Runtime/InteropServices/ComTypes/IStream.cs @@ -11,11 +11,11 @@ ** =============================================================================*/ +using System; + namespace System.Runtime.InteropServices.ComTypes { - using System; - - [StructLayout(LayoutKind.Sequential, CharSet=CharSet.Unicode)] + [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] public struct STATSTG { diff --git a/src/mscorlib/src/System/Runtime/InteropServices/ComTypes/ITypeComp.cs b/src/mscorlib/src/System/Runtime/InteropServices/ComTypes/ITypeComp.cs index f938ba91a7..967746f379 100644 --- a/src/mscorlib/src/System/Runtime/InteropServices/ComTypes/ITypeComp.cs +++ b/src/mscorlib/src/System/Runtime/InteropServices/ComTypes/ITypeComp.cs @@ -11,22 +11,22 @@ ** =============================================================================*/ +using System; + namespace System.Runtime.InteropServices.ComTypes { - using System; - [Serializable] public enum DESCKIND { - DESCKIND_NONE = 0, - DESCKIND_FUNCDESC = DESCKIND_NONE + 1, - DESCKIND_VARDESC = DESCKIND_FUNCDESC + 1, - DESCKIND_TYPECOMP = DESCKIND_VARDESC + 1, - DESCKIND_IMPLICITAPPOBJ = DESCKIND_TYPECOMP + 1, - DESCKIND_MAX = DESCKIND_IMPLICITAPPOBJ + 1 + DESCKIND_NONE = 0, + DESCKIND_FUNCDESC = DESCKIND_NONE + 1, + DESCKIND_VARDESC = DESCKIND_FUNCDESC + 1, + DESCKIND_TYPECOMP = DESCKIND_VARDESC + 1, + DESCKIND_IMPLICITAPPOBJ = DESCKIND_TYPECOMP + 1, + DESCKIND_MAX = DESCKIND_IMPLICITAPPOBJ + 1 } - [StructLayout(LayoutKind.Explicit, CharSet=CharSet.Unicode)] + [StructLayout(LayoutKind.Explicit, CharSet = CharSet.Unicode)] public struct BINDPTR { diff --git a/src/mscorlib/src/System/Runtime/InteropServices/ComTypes/ITypeInfo.cs b/src/mscorlib/src/System/Runtime/InteropServices/ComTypes/ITypeInfo.cs index 7a12605f20..1857fdbb35 100644 --- a/src/mscorlib/src/System/Runtime/InteropServices/ComTypes/ITypeInfo.cs +++ b/src/mscorlib/src/System/Runtime/InteropServices/ComTypes/ITypeInfo.cs @@ -11,61 +11,61 @@ ** =============================================================================*/ +using System; + namespace System.Runtime.InteropServices.ComTypes { - using System; - [Serializable] - public enum TYPEKIND + public enum TYPEKIND { - TKIND_ENUM = 0, - TKIND_RECORD = TKIND_ENUM + 1, - TKIND_MODULE = TKIND_RECORD + 1, + TKIND_ENUM = 0, + TKIND_RECORD = TKIND_ENUM + 1, + TKIND_MODULE = TKIND_RECORD + 1, TKIND_INTERFACE = TKIND_MODULE + 1, - TKIND_DISPATCH = TKIND_INTERFACE + 1, - TKIND_COCLASS = TKIND_DISPATCH + 1, - TKIND_ALIAS = TKIND_COCLASS + 1, - TKIND_UNION = TKIND_ALIAS + 1, - TKIND_MAX = TKIND_UNION + 1 + TKIND_DISPATCH = TKIND_INTERFACE + 1, + TKIND_COCLASS = TKIND_DISPATCH + 1, + TKIND_ALIAS = TKIND_COCLASS + 1, + TKIND_UNION = TKIND_ALIAS + 1, + TKIND_MAX = TKIND_UNION + 1 } -[Serializable] -[Flags()] + [Serializable] + [Flags()] public enum TYPEFLAGS : short { - TYPEFLAG_FAPPOBJECT = 0x1, - TYPEFLAG_FCANCREATE = 0x2, - TYPEFLAG_FLICENSED = 0x4, - TYPEFLAG_FPREDECLID = 0x8, - TYPEFLAG_FHIDDEN = 0x10, - TYPEFLAG_FCONTROL = 0x20, - TYPEFLAG_FDUAL = 0x40, - TYPEFLAG_FNONEXTENSIBLE = 0x80, - TYPEFLAG_FOLEAUTOMATION = 0x100, - TYPEFLAG_FRESTRICTED = 0x200, - TYPEFLAG_FAGGREGATABLE = 0x400, - TYPEFLAG_FREPLACEABLE = 0x800, - TYPEFLAG_FDISPATCHABLE = 0x1000, - TYPEFLAG_FREVERSEBIND = 0x2000, - TYPEFLAG_FPROXY = 0x4000 + TYPEFLAG_FAPPOBJECT = 0x1, + TYPEFLAG_FCANCREATE = 0x2, + TYPEFLAG_FLICENSED = 0x4, + TYPEFLAG_FPREDECLID = 0x8, + TYPEFLAG_FHIDDEN = 0x10, + TYPEFLAG_FCONTROL = 0x20, + TYPEFLAG_FDUAL = 0x40, + TYPEFLAG_FNONEXTENSIBLE = 0x80, + TYPEFLAG_FOLEAUTOMATION = 0x100, + TYPEFLAG_FRESTRICTED = 0x200, + TYPEFLAG_FAGGREGATABLE = 0x400, + TYPEFLAG_FREPLACEABLE = 0x800, + TYPEFLAG_FDISPATCHABLE = 0x1000, + TYPEFLAG_FREVERSEBIND = 0x2000, + TYPEFLAG_FPROXY = 0x4000 } -[Serializable] -[Flags()] + [Serializable] + [Flags()] public enum IMPLTYPEFLAGS { - IMPLTYPEFLAG_FDEFAULT = 0x1, - IMPLTYPEFLAG_FSOURCE = 0x2, - IMPLTYPEFLAG_FRESTRICTED = 0x4, + IMPLTYPEFLAG_FDEFAULT = 0x1, + IMPLTYPEFLAG_FSOURCE = 0x2, + IMPLTYPEFLAG_FRESTRICTED = 0x4, IMPLTYPEFLAG_FDEFAULTVTABLE = 0x8, } - [StructLayout(LayoutKind.Sequential, CharSet=CharSet.Unicode)] + [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] public struct TYPEATTR - { + { // Constant used with the memid fields. - public const int MEMBER_ID_NIL = unchecked((int)0xFFFFFFFF); + public const int MEMBER_ID_NIL = unchecked((int)0xFFFFFFFF); // Actual fields of the TypeAttr struct. public Guid guid; @@ -91,55 +91,55 @@ namespace System.Runtime.InteropServices.ComTypes [StructLayout(LayoutKind.Sequential)] public struct FUNCDESC - { + { public int memid; //MEMBERID memid; public IntPtr lprgscode; // /* [size_is(cScodes)] */ SCODE RPC_FAR *lprgscode; public IntPtr lprgelemdescParam; // /* [size_is(cParams)] */ ELEMDESC __RPC_FAR *lprgelemdescParam; - public FUNCKIND funckind; //FUNCKIND funckind; + public FUNCKIND funckind; //FUNCKIND funckind; public INVOKEKIND invkind; //INVOKEKIND invkind; - public CALLCONV callconv; //CALLCONV callconv; + public CALLCONV callconv; //CALLCONV callconv; public Int16 cParams; //short cParams; public Int16 cParamsOpt; //short cParamsOpt; public Int16 oVft; //short oVft; public Int16 cScodes; //short cScodes; - public ELEMDESC elemdescFunc; //ELEMDESC elemdescFunc; + public ELEMDESC elemdescFunc; //ELEMDESC elemdescFunc; public Int16 wFuncFlags; //WORD wFuncFlags; } -[Serializable] -[Flags()] - public enum IDLFLAG : short + [Serializable] + [Flags()] + public enum IDLFLAG : short { - IDLFLAG_NONE = PARAMFLAG.PARAMFLAG_NONE, - IDLFLAG_FIN = PARAMFLAG.PARAMFLAG_FIN, - IDLFLAG_FOUT = PARAMFLAG.PARAMFLAG_FOUT, - IDLFLAG_FLCID = PARAMFLAG.PARAMFLAG_FLCID, + IDLFLAG_NONE = PARAMFLAG.PARAMFLAG_NONE, + IDLFLAG_FIN = PARAMFLAG.PARAMFLAG_FIN, + IDLFLAG_FOUT = PARAMFLAG.PARAMFLAG_FOUT, + IDLFLAG_FLCID = PARAMFLAG.PARAMFLAG_FLCID, IDLFLAG_FRETVAL = PARAMFLAG.PARAMFLAG_FRETVAL } - [StructLayout(LayoutKind.Sequential, CharSet=CharSet.Unicode)] + [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] public struct IDLDESC { - public IntPtr dwReserved; - public IDLFLAG wIDLFlags; + public IntPtr dwReserved; + public IDLFLAG wIDLFlags; } -[Serializable] -[Flags()] - public enum PARAMFLAG :short + [Serializable] + [Flags()] + public enum PARAMFLAG : short { - PARAMFLAG_NONE = 0, - PARAMFLAG_FIN = 0x1, - PARAMFLAG_FOUT = 0x2, - PARAMFLAG_FLCID = 0x4, + PARAMFLAG_NONE = 0, + PARAMFLAG_FIN = 0x1, + PARAMFLAG_FOUT = 0x2, + PARAMFLAG_FLCID = 0x4, PARAMFLAG_FRETVAL = 0x8, - PARAMFLAG_FOPT = 0x10, + PARAMFLAG_FOPT = 0x10, PARAMFLAG_FHASDEFAULT = 0x20, PARAMFLAG_FHASCUSTDATA = 0x40 } - [StructLayout(LayoutKind.Sequential, CharSet=CharSet.Unicode)] + [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] public struct PARAMDESC { @@ -147,21 +147,21 @@ namespace System.Runtime.InteropServices.ComTypes public PARAMFLAG wParamFlags; } - [StructLayout(LayoutKind.Sequential, CharSet=CharSet.Unicode)] + [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] public struct TYPEDESC - { + { public IntPtr lpValue; public Int16 vt; } - [StructLayout(LayoutKind.Sequential, CharSet=CharSet.Unicode)] + [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] public struct ELEMDESC { public TYPEDESC tdesc; - [System.Runtime.InteropServices.StructLayout(LayoutKind.Explicit, CharSet=CharSet.Unicode)] + [System.Runtime.InteropServices.StructLayout(LayoutKind.Explicit, CharSet = CharSet.Unicode)] public struct DESCUNION { @@ -176,20 +176,20 @@ namespace System.Runtime.InteropServices.ComTypes [Serializable] public enum VARKIND : int { - VAR_PERINSTANCE = 0x0, - VAR_STATIC = 0x1, - VAR_CONST = 0x2, - VAR_DISPATCH = 0x3 + VAR_PERINSTANCE = 0x0, + VAR_STATIC = 0x1, + VAR_CONST = 0x2, + VAR_DISPATCH = 0x3 } - [StructLayout(LayoutKind.Sequential, CharSet=CharSet.Unicode)] + [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] public struct VARDESC { - public int memid; + public int memid; public String lpstrSchema; - [System.Runtime.InteropServices.StructLayout(LayoutKind.Explicit, CharSet=CharSet.Unicode)] + [System.Runtime.InteropServices.StructLayout(LayoutKind.Explicit, CharSet = CharSet.Unicode)] public struct DESCUNION { @@ -206,7 +206,7 @@ namespace System.Runtime.InteropServices.ComTypes public VARKIND varkind; } - [StructLayout(LayoutKind.Sequential, CharSet=CharSet.Unicode)] + [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] public struct DISPPARAMS { @@ -216,7 +216,7 @@ namespace System.Runtime.InteropServices.ComTypes public int cNamedArgs; } - [StructLayout(LayoutKind.Sequential, CharSet=CharSet.Unicode)] + [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] public struct EXCEPINFO { @@ -228,7 +228,7 @@ namespace System.Runtime.InteropServices.ComTypes public int dwHelpContext; public IntPtr pvReserved; public IntPtr pfnDeferredFillIn; - public Int32 scode; + public Int32 scode; } [Serializable] @@ -241,8 +241,8 @@ namespace System.Runtime.InteropServices.ComTypes FUNC_DISPATCH = 4 } -[Serializable] -[Flags] + [Serializable] + [Flags] public enum INVOKEKIND : int { INVOKE_FUNC = 0x1, @@ -254,54 +254,54 @@ namespace System.Runtime.InteropServices.ComTypes [Serializable] public enum CALLCONV : int { - CC_CDECL =1, - CC_MSCPASCAL=2, - CC_PASCAL =CC_MSCPASCAL, - CC_MACPASCAL=3, - CC_STDCALL =4, - CC_RESERVED =5, - CC_SYSCALL =6, - CC_MPWCDECL =7, - CC_MPWPASCAL=8, - CC_MAX =9 + CC_CDECL = 1, + CC_MSCPASCAL = 2, + CC_PASCAL = CC_MSCPASCAL, + CC_MACPASCAL = 3, + CC_STDCALL = 4, + CC_RESERVED = 5, + CC_SYSCALL = 6, + CC_MPWCDECL = 7, + CC_MPWPASCAL = 8, + CC_MAX = 9 } -[Serializable] -[Flags()] + [Serializable] + [Flags()] public enum FUNCFLAGS : short { - FUNCFLAG_FRESTRICTED= 0x1, - FUNCFLAG_FSOURCE = 0x2, - FUNCFLAG_FBINDABLE = 0x4, - FUNCFLAG_FREQUESTEDIT = 0x8, - FUNCFLAG_FDISPLAYBIND = 0x10, - FUNCFLAG_FDEFAULTBIND = 0x20, - FUNCFLAG_FHIDDEN = 0x40, - FUNCFLAG_FUSESGETLASTERROR= 0x80, - FUNCFLAG_FDEFAULTCOLLELEM= 0x100, - FUNCFLAG_FUIDEFAULT = 0x200, - FUNCFLAG_FNONBROWSABLE = 0x400, - FUNCFLAG_FREPLACEABLE = 0x800, - FUNCFLAG_FIMMEDIATEBIND = 0x1000 + FUNCFLAG_FRESTRICTED = 0x1, + FUNCFLAG_FSOURCE = 0x2, + FUNCFLAG_FBINDABLE = 0x4, + FUNCFLAG_FREQUESTEDIT = 0x8, + FUNCFLAG_FDISPLAYBIND = 0x10, + FUNCFLAG_FDEFAULTBIND = 0x20, + FUNCFLAG_FHIDDEN = 0x40, + FUNCFLAG_FUSESGETLASTERROR = 0x80, + FUNCFLAG_FDEFAULTCOLLELEM = 0x100, + FUNCFLAG_FUIDEFAULT = 0x200, + FUNCFLAG_FNONBROWSABLE = 0x400, + FUNCFLAG_FREPLACEABLE = 0x800, + FUNCFLAG_FIMMEDIATEBIND = 0x1000 } -[Serializable] -[Flags()] + [Serializable] + [Flags()] public enum VARFLAGS : short { - VARFLAG_FREADONLY =0x1, - VARFLAG_FSOURCE =0x2, - VARFLAG_FBINDABLE =0x4, - VARFLAG_FREQUESTEDIT =0x8, - VARFLAG_FDISPLAYBIND =0x10, - VARFLAG_FDEFAULTBIND =0x20, - VARFLAG_FHIDDEN =0x40, - VARFLAG_FRESTRICTED =0x80, - VARFLAG_FDEFAULTCOLLELEM =0x100, - VARFLAG_FUIDEFAULT =0x200, - VARFLAG_FNONBROWSABLE =0x400, - VARFLAG_FREPLACEABLE =0x800, - VARFLAG_FIMMEDIATEBIND =0x1000 + VARFLAG_FREADONLY = 0x1, + VARFLAG_FSOURCE = 0x2, + VARFLAG_FBINDABLE = 0x4, + VARFLAG_FREQUESTEDIT = 0x8, + VARFLAG_FDISPLAYBIND = 0x10, + VARFLAG_FDEFAULTBIND = 0x20, + VARFLAG_FHIDDEN = 0x40, + VARFLAG_FRESTRICTED = 0x80, + VARFLAG_FDEFAULTCOLLELEM = 0x100, + VARFLAG_FUIDEFAULT = 0x200, + VARFLAG_FNONBROWSABLE = 0x400, + VARFLAG_FREPLACEABLE = 0x800, + VARFLAG_FIMMEDIATEBIND = 0x1000 } [Guid("00020401-0000-0000-C000-000000000046")] diff --git a/src/mscorlib/src/System/Runtime/InteropServices/ComTypes/ITypeInfo2.cs b/src/mscorlib/src/System/Runtime/InteropServices/ComTypes/ITypeInfo2.cs index a782b9edd6..7bb7138c46 100644 --- a/src/mscorlib/src/System/Runtime/InteropServices/ComTypes/ITypeInfo2.cs +++ b/src/mscorlib/src/System/Runtime/InteropServices/ComTypes/ITypeInfo2.cs @@ -11,10 +11,10 @@ ** =============================================================================*/ +using System; + namespace System.Runtime.InteropServices.ComTypes { - using System; - [Guid("00020412-0000-0000-C000-000000000046")] [InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)] [ComImport] diff --git a/src/mscorlib/src/System/Runtime/InteropServices/ComTypes/ITypeLib.cs b/src/mscorlib/src/System/Runtime/InteropServices/ComTypes/ITypeLib.cs index c39b088c0b..3ed6e42d08 100644 --- a/src/mscorlib/src/System/Runtime/InteropServices/ComTypes/ITypeLib.cs +++ b/src/mscorlib/src/System/Runtime/InteropServices/ComTypes/ITypeLib.cs @@ -11,36 +11,36 @@ ** =============================================================================*/ +using System; + namespace System.Runtime.InteropServices.ComTypes { - using System; - [Serializable] public enum SYSKIND { - SYS_WIN16 = 0, - SYS_WIN32 = SYS_WIN16 + 1, - SYS_MAC = SYS_WIN32 + 1, - SYS_WIN64 = SYS_MAC + 1 + SYS_WIN16 = 0, + SYS_WIN32 = SYS_WIN16 + 1, + SYS_MAC = SYS_WIN32 + 1, + SYS_WIN64 = SYS_MAC + 1 } -[Serializable] -[Flags()] + [Serializable] + [Flags()] public enum LIBFLAGS : short { - LIBFLAG_FRESTRICTED = 0x1, - LIBFLAG_FCONTROL = 0x2, - LIBFLAG_FHIDDEN = 0x4, - LIBFLAG_FHASDISKIMAGE = 0x8 + LIBFLAG_FRESTRICTED = 0x1, + LIBFLAG_FCONTROL = 0x2, + LIBFLAG_FHIDDEN = 0x4, + LIBFLAG_FHASDISKIMAGE = 0x8 } - [StructLayout(LayoutKind.Sequential, CharSet=CharSet.Unicode)] + [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] [Serializable] public struct TYPELIBATTR - { + { public Guid guid; public int lcid; - public SYSKIND syskind; + public SYSKIND syskind; public Int16 wMajorVerNum; public Int16 wMinorVerNum; public LIBFLAGS wLibFlags; @@ -54,12 +54,12 @@ namespace System.Runtime.InteropServices.ComTypes [PreserveSig] int GetTypeInfoCount(); void GetTypeInfo(int index, out ITypeInfo ppTI); - void GetTypeInfoType(int index, out TYPEKIND pTKind); - void GetTypeInfoOfGuid(ref Guid guid, out ITypeInfo ppTInfo); - void GetLibAttr(out IntPtr ppTLibAttr); - void GetTypeComp(out ITypeComp ppTComp); + void GetTypeInfoType(int index, out TYPEKIND pTKind); + void GetTypeInfoOfGuid(ref Guid guid, out ITypeInfo ppTInfo); + void GetLibAttr(out IntPtr ppTLibAttr); + void GetTypeComp(out ITypeComp ppTComp); void GetDocumentation(int index, out String strName, out String strDocString, out int dwHelpContext, out String strHelpFile); - [return : MarshalAs(UnmanagedType.Bool)] + [return: MarshalAs(UnmanagedType.Bool)] bool IsName([MarshalAs(UnmanagedType.LPWStr)] String szNameBuf, int lHashVal); void FindName([MarshalAs(UnmanagedType.LPWStr)] String szNameBuf, int lHashVal, [MarshalAs(UnmanagedType.LPArray), Out] ITypeInfo[] ppTInfo, [MarshalAs(UnmanagedType.LPArray), Out] int[] rgMemId, ref Int16 pcFound); [PreserveSig] diff --git a/src/mscorlib/src/System/Runtime/InteropServices/ComTypes/ITypeLib2.cs b/src/mscorlib/src/System/Runtime/InteropServices/ComTypes/ITypeLib2.cs index 5a7d07c001..48f4fb3782 100644 --- a/src/mscorlib/src/System/Runtime/InteropServices/ComTypes/ITypeLib2.cs +++ b/src/mscorlib/src/System/Runtime/InteropServices/ComTypes/ITypeLib2.cs @@ -11,10 +11,10 @@ ** =============================================================================*/ +using System; + namespace System.Runtime.InteropServices.ComTypes { - using System; - [Guid("00020411-0000-0000-C000-000000000046")] [InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)] [ComImport] @@ -23,12 +23,12 @@ namespace System.Runtime.InteropServices.ComTypes [PreserveSig] new int GetTypeInfoCount(); new void GetTypeInfo(int index, out ITypeInfo ppTI); - new void GetTypeInfoType(int index, out TYPEKIND pTKind); - new void GetTypeInfoOfGuid(ref Guid guid, out ITypeInfo ppTInfo); + new void GetTypeInfoType(int index, out TYPEKIND pTKind); + new void GetTypeInfoOfGuid(ref Guid guid, out ITypeInfo ppTInfo); new void GetLibAttr(out IntPtr ppTLibAttr); - new void GetTypeComp(out ITypeComp ppTComp); + new void GetTypeComp(out ITypeComp ppTComp); new void GetDocumentation(int index, out String strName, out String strDocString, out int dwHelpContext, out String strHelpFile); - [return : MarshalAs(UnmanagedType.Bool)] + [return: MarshalAs(UnmanagedType.Bool)] new bool IsName([MarshalAs(UnmanagedType.LPWStr)] String szNameBuf, int lHashVal); new void FindName([MarshalAs(UnmanagedType.LPWStr)] String szNameBuf, int lHashVal, [MarshalAs(UnmanagedType.LPArray), Out] ITypeInfo[] ppTInfo, [MarshalAs(UnmanagedType.LPArray), Out] int[] rgMemId, ref Int16 pcFound); [PreserveSig] diff --git a/src/mscorlib/src/System/Runtime/InteropServices/CriticalHandle.cs b/src/mscorlib/src/System/Runtime/InteropServices/CriticalHandle.cs index 840270141b..734a494bdb 100644 --- a/src/mscorlib/src/System/Runtime/InteropServices/CriticalHandle.cs +++ b/src/mscorlib/src/System/Runtime/InteropServices/CriticalHandle.cs @@ -130,122 +130,124 @@ using System.IO; namespace System.Runtime.InteropServices { - -// This class should not be serializable - it's a handle. We require unmanaged -// code permission to subclass CriticalHandle to prevent people from writing a -// subclass and suddenly being able to run arbitrary native code with the -// same signature as CloseHandle. This is technically a little redundant, but -// 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. -public abstract class CriticalHandle : CriticalFinalizerObject, IDisposable -{ - // ! Do not add or rearrange fields as the EE depends on this layout. - //------------------------------------------------------------------ + // This class should not be serializable - it's a handle. We require unmanaged + // code permission to subclass CriticalHandle to prevent people from writing a + // subclass and suddenly being able to run arbitrary native code with the + // same signature as CloseHandle. This is technically a little redundant, but + // 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. + public abstract class CriticalHandle : CriticalFinalizerObject, IDisposable + { + // ! Do not add or rearrange fields as the EE depends on this layout. + //------------------------------------------------------------------ #if DEBUG - private String _stackTrace; // Where we allocated this CriticalHandle. + private String _stackTrace; // Where we allocated this CriticalHandle. #endif - protected IntPtr handle; // This must be protected so derived classes can use out params. - private bool _isClosed; // Set by SetHandleAsInvalid or Close/Dispose/finalization. + protected IntPtr handle; // This must be protected so derived classes can use out params. + private bool _isClosed; // Set by SetHandleAsInvalid or Close/Dispose/finalization. - // Creates a CriticalHandle class. Users must then set the Handle property or allow P/Invoke marshaling to set it implicitly. - protected CriticalHandle(IntPtr invalidHandleValue) - { - handle = invalidHandleValue; - _isClosed = false; + // Creates a CriticalHandle class. Users must then set the Handle property or allow P/Invoke marshaling to set it implicitly. + protected CriticalHandle(IntPtr invalidHandleValue) + { + handle = invalidHandleValue; + _isClosed = false; #if DEBUG - if (BCLDebug.SafeHandleStackTracesEnabled) - _stackTrace = Environment.GetStackTrace(null, false); - else - _stackTrace = "For a stack trace showing who allocated this CriticalHandle, set SafeHandleStackTraces to 1 and rerun your app."; + if (BCLDebug.SafeHandleStackTracesEnabled) + _stackTrace = Environment.GetStackTrace(null, false); + else + _stackTrace = "For a stack trace showing who allocated this CriticalHandle, set SafeHandleStackTraces to 1 and rerun your app."; #endif + } + + // Adding an empty default constructor for annotation purposes + private CriticalHandle() { } + + ~CriticalHandle() + { + Dispose(false); + } + + private void Cleanup() + { + if (IsClosed) + return; + _isClosed = true; + + if (IsInvalid) + return; + + // Save last error from P/Invoke in case the implementation of + // ReleaseHandle trashes it (important because this ReleaseHandle could + // occur implicitly as part of unmarshaling another P/Invoke). + int lastError = Marshal.GetLastWin32Error(); + + if (!ReleaseHandle()) + FireCustomerDebugProbe(); + + Marshal.SetLastWin32Error(lastError); + + GC.SuppressFinalize(this); + } + + [MethodImplAttribute(MethodImplOptions.InternalCall)] + private extern void FireCustomerDebugProbe(); + + protected void SetHandle(IntPtr handle) + { + this.handle = handle; + } + + // Returns whether the handle has been explicitly marked as closed + // (Close/Dispose) or invalid (SetHandleAsInvalid). + public bool IsClosed + { + get { return _isClosed; } + } + + // Returns whether the handle looks like an invalid value (i.e. matches one + // of the handle's designated illegal values). CriticalHandle itself doesn't + // know what an invalid handle looks like, so this method is abstract and + // must be provided by a derived type. + public abstract bool IsInvalid + { + get; + } + + public void Close() + { + Dispose(true); + } + + public void Dispose() + { + Dispose(true); + } + + protected virtual void Dispose(bool disposing) + { + Cleanup(); + } + + // This should only be called for cases when you know for a fact that + // 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! + public void SetHandleAsInvalid() + { + _isClosed = true; + GC.SuppressFinalize(this); + } + + // Implement this abstract method in your derived class to specify how to + // free the handle. Be careful not write any code that's subject to faults + // in this method (the runtime will prepare the infrastructure for you so + // that no jit allocations etc. will occur, but don't allocate memory unless + // you can deal with the failure and still free the handle). + // The boolean returned should be true for success and false if a + // catastrophic error occurred and you wish to trigger a diagnostic for + // debugging purposes (the SafeHandleCriticalFailure MDA). + protected abstract bool ReleaseHandle(); } - - // Adding an empty default constructor for annotation purposes - private CriticalHandle(){} - - ~CriticalHandle() - { - Dispose(false); - } - - private void Cleanup() - { - if (IsClosed) - return; - _isClosed = true; - - if (IsInvalid) - return; - - // Save last error from P/Invoke in case the implementation of - // ReleaseHandle trashes it (important because this ReleaseHandle could - // occur implicitly as part of unmarshaling another P/Invoke). - int lastError = Marshal.GetLastWin32Error(); - - if (!ReleaseHandle()) - FireCustomerDebugProbe(); - - Marshal.SetLastWin32Error(lastError); - - GC.SuppressFinalize(this); - } - - [MethodImplAttribute(MethodImplOptions.InternalCall)] - private extern void FireCustomerDebugProbe(); - - protected void SetHandle(IntPtr handle) { - this.handle = handle; - } - - // Returns whether the handle has been explicitly marked as closed - // (Close/Dispose) or invalid (SetHandleAsInvalid). - public bool IsClosed { - get { return _isClosed; } - } - - // Returns whether the handle looks like an invalid value (i.e. matches one - // of the handle's designated illegal values). CriticalHandle itself doesn't - // know what an invalid handle looks like, so this method is abstract and - // must be provided by a derived type. - public abstract bool IsInvalid { - get; - } - - public void Close() { - Dispose(true); - } - - public void Dispose() - { - Dispose(true); - } - - protected virtual void Dispose(bool disposing) - { - Cleanup(); - } - - // This should only be called for cases when you know for a fact that - // 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! - public void SetHandleAsInvalid() - { - _isClosed = true; - GC.SuppressFinalize(this); - } - - // Implement this abstract method in your derived class to specify how to - // free the handle. Be careful not write any code that's subject to faults - // in this method (the runtime will prepare the infrastructure for you so - // that no jit allocations etc. will occur, but don't allocate memory unless - // you can deal with the failure and still free the handle). - // The boolean returned should be true for success and false if a - // catastrophic error occurred and you wish to trigger a diagnostic for - // debugging purposes (the SafeHandleCriticalFailure MDA). - protected abstract bool ReleaseHandle(); -} - } diff --git a/src/mscorlib/src/System/Runtime/InteropServices/CurrencyWrapper.cs b/src/mscorlib/src/System/Runtime/InteropServices/CurrencyWrapper.cs index 304419e5b0..4b436825e8 100644 --- a/src/mscorlib/src/System/Runtime/InteropServices/CurrencyWrapper.cs +++ b/src/mscorlib/src/System/Runtime/InteropServices/CurrencyWrapper.cs @@ -11,10 +11,11 @@ ** =============================================================================*/ -namespace System.Runtime.InteropServices { - - using System; +using System; + +namespace System.Runtime.InteropServices +{ [Serializable] public sealed class CurrencyWrapper { @@ -24,15 +25,15 @@ namespace System.Runtime.InteropServices { } public CurrencyWrapper(Object obj) - { + { if (!(obj is Decimal)) - throw new ArgumentException(Environment.GetResourceString("Arg_MustBeDecimal"), nameof(obj)); + throw new ArgumentException(SR.Arg_MustBeDecimal, nameof(obj)); m_WrappedObject = (Decimal)obj; } - public Decimal WrappedObject + public Decimal WrappedObject { - get + get { return m_WrappedObject; } diff --git a/src/mscorlib/src/System/Runtime/InteropServices/DispatchWrapper.cs b/src/mscorlib/src/System/Runtime/InteropServices/DispatchWrapper.cs index ccf25af0f9..87ec4ed15e 100644 --- a/src/mscorlib/src/System/Runtime/InteropServices/DispatchWrapper.cs +++ b/src/mscorlib/src/System/Runtime/InteropServices/DispatchWrapper.cs @@ -11,11 +11,12 @@ ** =============================================================================*/ -namespace System.Runtime.InteropServices { - - using System; - using System.Security; +using System; +using System.Security; + +namespace System.Runtime.InteropServices +{ [Serializable] public sealed class DispatchWrapper { @@ -32,9 +33,9 @@ namespace System.Runtime.InteropServices { m_WrappedObject = obj; } - public Object WrappedObject + public Object WrappedObject { - get + get { return m_WrappedObject; } diff --git a/src/mscorlib/src/System/Runtime/InteropServices/ErrorWrapper.cs b/src/mscorlib/src/System/Runtime/InteropServices/ErrorWrapper.cs index da02893b1e..73be2c5777 100644 --- a/src/mscorlib/src/System/Runtime/InteropServices/ErrorWrapper.cs +++ b/src/mscorlib/src/System/Runtime/InteropServices/ErrorWrapper.cs @@ -11,10 +11,11 @@ ** =============================================================================*/ -namespace System.Runtime.InteropServices { - - using System; +using System; + +namespace System.Runtime.InteropServices +{ [Serializable] public sealed class ErrorWrapper { @@ -26,18 +27,18 @@ namespace System.Runtime.InteropServices { public ErrorWrapper(Object errorCode) { if (!(errorCode is int)) - throw new ArgumentException(Environment.GetResourceString("Arg_MustBeInt32"), nameof(errorCode)); + throw new ArgumentException(SR.Arg_MustBeInt32, nameof(errorCode)); m_ErrorCode = (int)errorCode; - } + } public ErrorWrapper(Exception e) { m_ErrorCode = Marshal.GetHRForException(e); } - public int ErrorCode + public int ErrorCode { - get + get { return m_ErrorCode; } diff --git a/src/mscorlib/src/System/Runtime/InteropServices/Expando/IExpando.cs b/src/mscorlib/src/System/Runtime/InteropServices/Expando/IExpando.cs index 429ce13918..2bd398b7a9 100644 --- a/src/mscorlib/src/System/Runtime/InteropServices/Expando/IExpando.cs +++ b/src/mscorlib/src/System/Runtime/InteropServices/Expando/IExpando.cs @@ -11,11 +11,12 @@ // // // The IExpando Interface. -namespace System.Runtime.InteropServices.Expando { - - using System; - using System.Reflection; +using System; +using System.Reflection; + +namespace System.Runtime.InteropServices.Expando +{ [Guid("AFBF15E6-C37C-11d2-B88E-00A0C9B471B8")] internal interface IExpando : IReflect { diff --git a/src/mscorlib/src/System/Runtime/InteropServices/ExternalException.cs b/src/mscorlib/src/System/Runtime/InteropServices/ExternalException.cs deleted file mode 100644 index 7e1f395e4e..0000000000 --- a/src/mscorlib/src/System/Runtime/InteropServices/ExternalException.cs +++ /dev/null @@ -1,77 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -/*============================================================================= -** -** -** -** Purpose: Exception base class for all errors from Interop or Structured -** Exception Handling code. -** -** -=============================================================================*/ - -namespace System.Runtime.InteropServices { - - using System; - using System.Globalization; - using System.Runtime.Serialization; - // Base exception for COM Interop errors &; Structured Exception Handler - // exceptions. - // - [Serializable] - public class ExternalException : SystemException { - public ExternalException() - : base(Environment.GetResourceString("Arg_ExternalException")) { - SetErrorCode(__HResults.E_FAIL); - } - - public ExternalException(String message) - : base(message) { - SetErrorCode(__HResults.E_FAIL); - } - - public ExternalException(String message, Exception inner) - : base(message, inner) { - SetErrorCode(__HResults.E_FAIL); - } - - public ExternalException(String message,int errorCode) - : base(message) { - SetErrorCode(errorCode); - } - - protected ExternalException(SerializationInfo info, StreamingContext context) : base(info, context) { - } - - public virtual int ErrorCode { - get { - return HResult; - } - } - - public override String ToString() { - String message = Message; - String s; - String _className = GetType().ToString(); - s = _className + " (0x" + HResult.ToString("X8", CultureInfo.InvariantCulture) + ")"; - - if (!(String.IsNullOrEmpty(message))) { - s = s + ": " + message; - } - - Exception _innerException = InnerException; - - if (_innerException!=null) { - s = s + " ---> " + _innerException.ToString(); - } - - - if (StackTrace != null) - s += Environment.NewLine + StackTrace; - - return s; - } - } -} diff --git a/src/mscorlib/src/System/Runtime/InteropServices/GCHandleCookieTable.cs b/src/mscorlib/src/System/Runtime/InteropServices/GCHandleCookieTable.cs index 304f369879..9e813d9bd9 100644 --- a/src/mscorlib/src/System/Runtime/InteropServices/GCHandleCookieTable.cs +++ b/src/mscorlib/src/System/Runtime/InteropServices/GCHandleCookieTable.cs @@ -91,7 +91,7 @@ namespace System.Runtime.InteropServices } if (cookie == GCHandleCookie.Zero) - throw new OutOfMemoryException(Environment.GetResourceString("OutOfMemory_GCHandleMDA")); + throw new OutOfMemoryException(SR.OutOfMemory_GCHandleMDA); // This handle hasn't been added to the map yet so add it. m_HandleToCookieMap.Add(handle, cookie); diff --git a/src/mscorlib/src/System/Runtime/InteropServices/GcHandle.cs b/src/mscorlib/src/System/Runtime/InteropServices/GcHandle.cs index 598fee0618..dcb9e24258 100644 --- a/src/mscorlib/src/System/Runtime/InteropServices/GcHandle.cs +++ b/src/mscorlib/src/System/Runtime/InteropServices/GcHandle.cs @@ -3,7 +3,7 @@ // See the LICENSE file in the project root for more information. namespace System.Runtime.InteropServices -{ +{ using System; using System.Runtime.CompilerServices; using System.Threading; @@ -113,7 +113,7 @@ namespace System.Runtime.InteropServices #endif InternalFree(GetHandleValue(handle)); } - + // Target property - allows getting / updating of the handle's referent. public Object Target { @@ -122,7 +122,7 @@ namespace System.Runtime.InteropServices ValidateHandle(); return InternalGet(GetHandleValue()); } - + set { ValidateHandle(); @@ -140,7 +140,7 @@ namespace System.Runtime.InteropServices ValidateHandle(); // You can only get the address of pinned handles. - throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_HandleIsNotPinned")); + throw new InvalidOperationException(SR.InvalidOperation_HandleIsNotPinned); } // Get the address. @@ -198,7 +198,7 @@ namespace System.Runtime.InteropServices } #endif return value.m_handle; - } + } public override int GetHashCode() { @@ -208,12 +208,12 @@ namespace System.Runtime.InteropServices public override bool Equals(Object o) { GCHandle hnd; - + // Check that o is a GCHandle first - if(o == null || !(o is GCHandle)) + if (o == null || !(o is GCHandle)) return false; - else - hnd = (GCHandle) o; + else + hnd = (GCHandle)o; return m_handle == hnd.m_handle; } diff --git a/src/mscorlib/src/System/Runtime/InteropServices/HandleRef.cs b/src/mscorlib/src/System/Runtime/InteropServices/HandleRef.cs index b1171025ee..41eb1c24ba 100644 --- a/src/mscorlib/src/System/Runtime/InteropServices/HandleRef.cs +++ b/src/mscorlib/src/System/Runtime/InteropServices/HandleRef.cs @@ -2,14 +2,13 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. + +using System; + namespace System.Runtime.InteropServices { - - using System; - public struct HandleRef { - // ! Do not add or rearrange fields as the EE depends on this layout. //------------------------------------------------------------------ internal Object m_wrapper; @@ -20,22 +19,26 @@ namespace System.Runtime.InteropServices public HandleRef(Object wrapper, IntPtr handle) { m_wrapper = wrapper; - m_handle = handle; + m_handle = handle; } - public Object Wrapper { - get { + public Object Wrapper + { + get + { return m_wrapper; } } - - public IntPtr Handle { - get { + + public IntPtr Handle + { + get + { return m_handle; } } - - + + public static explicit operator IntPtr(HandleRef value) { return value.m_handle; diff --git a/src/mscorlib/src/System/Runtime/InteropServices/ICustomAdapter.cs b/src/mscorlib/src/System/Runtime/InteropServices/ICustomAdapter.cs index 002c48a171..f47d348699 100644 --- a/src/mscorlib/src/System/Runtime/InteropServices/ICustomAdapter.cs +++ b/src/mscorlib/src/System/Runtime/InteropServices/ICustomAdapter.cs @@ -12,11 +12,12 @@ ** =============================================================================*/ -namespace System.Runtime.InteropServices { - using System; +using System; +namespace System.Runtime.InteropServices +{ public interface ICustomAdapter - { - [return:MarshalAs(UnmanagedType.IUnknown)] Object GetUnderlyingObject(); + { + [return: MarshalAs(UnmanagedType.IUnknown)] Object GetUnderlyingObject(); } } diff --git a/src/mscorlib/src/System/Runtime/InteropServices/ICustomFactory.cs b/src/mscorlib/src/System/Runtime/InteropServices/ICustomFactory.cs index 8e7af10b6e..e7bfc47281 100644 --- a/src/mscorlib/src/System/Runtime/InteropServices/ICustomFactory.cs +++ b/src/mscorlib/src/System/Runtime/InteropServices/ICustomFactory.cs @@ -4,13 +4,13 @@ //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// -namespace System.Runtime.InteropServices { - using System; +using System; +namespace System.Runtime.InteropServices +{ public interface ICustomFactory { MarshalByRefObject CreateInstance(Type serverType); } - } diff --git a/src/mscorlib/src/System/Runtime/InteropServices/ICustomMarshaler.cs b/src/mscorlib/src/System/Runtime/InteropServices/ICustomMarshaler.cs index d9ed289145..571d78dfe3 100644 --- a/src/mscorlib/src/System/Runtime/InteropServices/ICustomMarshaler.cs +++ b/src/mscorlib/src/System/Runtime/InteropServices/ICustomMarshaler.cs @@ -12,18 +12,19 @@ ** =============================================================================*/ -namespace System.Runtime.InteropServices { - using System; +using System; +namespace System.Runtime.InteropServices +{ public interface ICustomMarshaler - { - Object MarshalNativeToManaged( IntPtr pNativeData ); + { + Object MarshalNativeToManaged(IntPtr pNativeData); - IntPtr MarshalManagedToNative( Object ManagedObj ); + IntPtr MarshalManagedToNative(Object ManagedObj); - void CleanUpNativeData( IntPtr pNativeData ); + void CleanUpNativeData(IntPtr pNativeData); - void CleanUpManagedData( Object ManagedObj ); + void CleanUpManagedData(Object ManagedObj); int GetNativeDataSize(); } diff --git a/src/mscorlib/src/System/Runtime/InteropServices/ICustomQueryInterface.cs b/src/mscorlib/src/System/Runtime/InteropServices/ICustomQueryInterface.cs index 5675b1f2d6..4f4b10bbf0 100644 --- a/src/mscorlib/src/System/Runtime/InteropServices/ICustomQueryInterface.cs +++ b/src/mscorlib/src/System/Runtime/InteropServices/ICustomQueryInterface.cs @@ -12,18 +12,19 @@ ** =============================================================================*/ -namespace System.Runtime.InteropServices { - using System; +using System; +namespace System.Runtime.InteropServices +{ //==================================================================== // The enum of the return value of IQuerable.GetInterface //==================================================================== [Serializable] public enum CustomQueryInterfaceResult { - Handled = 0, - NotHandled = 1, - Failed = 2, + Handled = 0, + NotHandled = 1, + Failed = 2, } //==================================================================== diff --git a/src/mscorlib/src/System/Runtime/InteropServices/ITypeLibConverter.cs b/src/mscorlib/src/System/Runtime/InteropServices/ITypeLibConverter.cs index afa934caaf..85756cf84f 100644 --- a/src/mscorlib/src/System/Runtime/InteropServices/ITypeLibConverter.cs +++ b/src/mscorlib/src/System/Runtime/InteropServices/ITypeLibConverter.cs @@ -16,9 +16,11 @@ // *** in src/inc/TlbImpExp.idl. // *************************************************************************** -namespace System.Runtime.InteropServices { - - using System; - using System.Reflection; - using System.Reflection.Emit; + +using System; +using System.Reflection; +using System.Reflection.Emit; + +namespace System.Runtime.InteropServices +{ } diff --git a/src/mscorlib/src/System/Runtime/InteropServices/InvalidComObjectException.cs b/src/mscorlib/src/System/Runtime/InteropServices/InvalidComObjectException.cs index 760210bc28..2fae2b6e52 100644 --- a/src/mscorlib/src/System/Runtime/InteropServices/InvalidComObjectException.cs +++ b/src/mscorlib/src/System/Runtime/InteropServices/InvalidComObjectException.cs @@ -11,29 +11,35 @@ ** =============================================================================*/ -namespace System.Runtime.InteropServices { - using System; - using System.Runtime.Serialization; +using System; +using System.Runtime.Serialization; +namespace System.Runtime.InteropServices +{ [Serializable] - public class InvalidComObjectException : SystemException { - public InvalidComObjectException() - : base(Environment.GetResourceString("Arg_InvalidComObjectException")) { - SetErrorCode(__HResults.COR_E_INVALIDCOMOBJECT); + public class InvalidComObjectException : SystemException + { + public InvalidComObjectException() + : base(SR.Arg_InvalidComObjectException) + { + HResult = __HResults.COR_E_INVALIDCOMOBJECT; } - - public InvalidComObjectException(String message) - : base(message) { - SetErrorCode(__HResults.COR_E_INVALIDCOMOBJECT); + + public InvalidComObjectException(String message) + : base(message) + { + HResult = __HResults.COR_E_INVALIDCOMOBJECT; } - - public InvalidComObjectException(String message, Exception inner) - : base(message, inner) { - SetErrorCode(__HResults.COR_E_INVALIDCOMOBJECT); + + public InvalidComObjectException(String message, Exception inner) + : base(message, inner) + { + HResult = __HResults.COR_E_INVALIDCOMOBJECT; } - protected InvalidComObjectException(SerializationInfo info, StreamingContext context) : base(info, context) { + protected InvalidComObjectException(SerializationInfo info, StreamingContext context) : base(info, context) + { } } } diff --git a/src/mscorlib/src/System/Runtime/InteropServices/InvalidOleVariantTypeException.cs b/src/mscorlib/src/System/Runtime/InteropServices/InvalidOleVariantTypeException.cs index 4ca3da5619..5154a028ad 100644 --- a/src/mscorlib/src/System/Runtime/InteropServices/InvalidOleVariantTypeException.cs +++ b/src/mscorlib/src/System/Runtime/InteropServices/InvalidOleVariantTypeException.cs @@ -10,29 +10,35 @@ ** =============================================================================*/ -namespace System.Runtime.InteropServices { - - using System; - using System.Runtime.Serialization; +using System; +using System.Runtime.Serialization; + +namespace System.Runtime.InteropServices +{ [Serializable] - public class InvalidOleVariantTypeException : SystemException { - public InvalidOleVariantTypeException() - : base(Environment.GetResourceString("Arg_InvalidOleVariantTypeException")) { - SetErrorCode(__HResults.COR_E_INVALIDOLEVARIANTTYPE); + public class InvalidOleVariantTypeException : SystemException + { + public InvalidOleVariantTypeException() + : base(SR.Arg_InvalidOleVariantTypeException) + { + HResult = __HResults.COR_E_INVALIDOLEVARIANTTYPE; } - - public InvalidOleVariantTypeException(String message) - : base(message) { - SetErrorCode(__HResults.COR_E_INVALIDOLEVARIANTTYPE); + + public InvalidOleVariantTypeException(String message) + : base(message) + { + HResult = __HResults.COR_E_INVALIDOLEVARIANTTYPE; } - - public InvalidOleVariantTypeException(String message, Exception inner) - : base(message, inner) { - SetErrorCode(__HResults.COR_E_INVALIDOLEVARIANTTYPE); + + public InvalidOleVariantTypeException(String message, Exception inner) + : base(message, inner) + { + HResult = __HResults.COR_E_INVALIDOLEVARIANTTYPE; } - protected InvalidOleVariantTypeException(SerializationInfo info, StreamingContext context) : base(info, context) { + protected InvalidOleVariantTypeException(SerializationInfo info, StreamingContext context) : base(info, context) + { } } } diff --git a/src/mscorlib/src/System/Runtime/InteropServices/LayoutKind.cs b/src/mscorlib/src/System/Runtime/InteropServices/LayoutKind.cs deleted file mode 100644 index f7def3a8e9..0000000000 --- a/src/mscorlib/src/System/Runtime/InteropServices/LayoutKind.cs +++ /dev/null @@ -1,17 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -//////////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////////// -namespace System.Runtime.InteropServices { - using System; - // Used in the StructLayoutAttribute class - [Serializable] - public enum LayoutKind - { - Sequential = 0, // 0x00000008, - Explicit = 2, // 0x00000010, - Auto = 3, // 0x00000000, - } -} diff --git a/src/mscorlib/src/System/Runtime/InteropServices/Marshal.cs b/src/mscorlib/src/System/Runtime/InteropServices/Marshal.cs index 9e9103b9c2..248e0d5778 100644 --- a/src/mscorlib/src/System/Runtime/InteropServices/Marshal.cs +++ b/src/mscorlib/src/System/Runtime/InteropServices/Marshal.cs @@ -13,7 +13,7 @@ =============================================================================*/ namespace System.Runtime.InteropServices -{ +{ using System; using System.Collections.Generic; using System.Reflection; @@ -35,7 +35,7 @@ namespace System.Runtime.InteropServices [Serializable] public enum CustomQueryInterfaceMode { - Ignore = 0, + Ignore = 0, Allow = 1 } @@ -46,7 +46,7 @@ namespace System.Runtime.InteropServices //======================================================================== public static partial class Marshal - { + { //==================================================================== // Defines used inside the Marshal class. //==================================================================== @@ -101,10 +101,10 @@ namespace System.Runtime.InteropServices // The name, title and description of the assembly that will contain // the dynamically generated interop types. //==================================================================== - private const String s_strConvertedTypeInfoAssemblyName = "InteropDynamicTypes"; - private const String s_strConvertedTypeInfoAssemblyTitle = "Interop Dynamic Types"; - private const String s_strConvertedTypeInfoAssemblyDesc = "Type dynamically generated from ITypeInfo's"; - private const String s_strConvertedTypeInfoNameSpace = "InteropDynamicTypes"; + private const String s_strConvertedTypeInfoAssemblyName = "InteropDynamicTypes"; + private const String s_strConvertedTypeInfoAssemblyTitle = "Interop Dynamic Types"; + private const String s_strConvertedTypeInfoAssemblyDesc = "Type dynamically generated from ITypeInfo's"; + private const String s_strConvertedTypeInfoNameSpace = "InteropDynamicTypes"; //==================================================================== @@ -112,22 +112,27 @@ namespace System.Runtime.InteropServices //==================================================================== [MethodImplAttribute(MethodImplOptions.InternalCall)] private static extern int GetSystemMaxDBCSCharSize(); - + unsafe public static String PtrToStringAnsi(IntPtr ptr) { - if (IntPtr.Zero == ptr) { + if (IntPtr.Zero == ptr) + { return null; } - else if (IsWin32Atom(ptr)) { + else if (IsWin32Atom(ptr)) + { return null; } - else { + else + { int nb = Win32Native.lstrlenA(ptr); - if( nb == 0) { + if (nb == 0) + { return string.Empty; } - else { - return new String((sbyte *)ptr); + else + { + return new String((sbyte*)ptr); } } } @@ -139,7 +144,7 @@ namespace System.Runtime.InteropServices if (len < 0) throw new ArgumentException(null, nameof(len)); - return new String((sbyte *)ptr, 0, len); + return new String((sbyte*)ptr, 0, len); } unsafe public static String PtrToStringUni(IntPtr ptr, int len) @@ -149,28 +154,31 @@ namespace System.Runtime.InteropServices if (len < 0) throw new ArgumentException(null, nameof(len)); - return new String((char *)ptr, 0, len); + return new String((char*)ptr, 0, len); } - + public static String PtrToStringAuto(IntPtr ptr, int len) { // Ansi platforms are no longer supported return PtrToStringUni(ptr, len); - } - + } + unsafe public static String PtrToStringUni(IntPtr ptr) { - if (IntPtr.Zero == ptr) { + if (IntPtr.Zero == ptr) + { return null; } - else if (IsWin32Atom(ptr)) { + else if (IsWin32Atom(ptr)) + { return null; - } - else { - return new String((char *)ptr); + } + else + { + return new String((char*)ptr); } } - + public static String PtrToStringAuto(IntPtr ptr) { // Ansi platforms are no longer supported @@ -183,7 +191,7 @@ namespace System.Runtime.InteropServices return PtrToStringUTF8(ptr, nbBytes); } - unsafe public static String PtrToStringUTF8(IntPtr ptr,int byteLen) + unsafe public static String PtrToStringUTF8(IntPtr ptr, int byteLen) { if (byteLen < 0) { @@ -232,9 +240,9 @@ namespace System.Runtime.InteropServices if (t == null) throw new ArgumentNullException(nameof(t)); if (!(t is RuntimeType)) - throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeType"), nameof(t)); + throw new ArgumentException(SR.Argument_MustBeRuntimeType, nameof(t)); if (t.IsGenericType) - throw new ArgumentException(Environment.GetResourceString("Argument_NeedNonGenericType"), nameof(t)); + throw new ArgumentException(SR.Argument_NeedNonGenericType, nameof(t)); Contract.EndContractBlock(); return SizeOfHelper(t, true); @@ -285,13 +293,13 @@ namespace System.Runtime.InteropServices if (t == null) 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), nameof(fieldName)); + throw new ArgumentException(SR.Format(SR.Argument_OffsetOfFieldNotFound, t.FullName), nameof(fieldName)); RtFieldInfo rtField = f as RtFieldInfo; if (rtField == null) - throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeFieldInfo"), nameof(fieldName)); + throw new ArgumentException(SR.Argument_MustBeRuntimeFieldInfo, nameof(fieldName)); return OffsetOfHelper(rtField); } @@ -322,27 +330,27 @@ namespace System.Runtime.InteropServices //==================================================================== // Copy blocks from CLR arrays to native memory. //==================================================================== - public static void Copy(int[] source, int startIndex, IntPtr destination, int length) + public static void Copy(int[] source, int startIndex, IntPtr destination, int length) { CopyToNative(source, startIndex, destination, length); } - public static void Copy(char[] source, int startIndex, IntPtr destination, int length) + public static void Copy(char[] source, int startIndex, IntPtr destination, int length) { CopyToNative(source, startIndex, destination, length); } - public static void Copy(short[] source, int startIndex, IntPtr destination, int length) + public static void Copy(short[] source, int startIndex, IntPtr destination, int length) { CopyToNative(source, startIndex, destination, length); } - public static void Copy(long[] source, int startIndex, IntPtr destination, int length) + public static void Copy(long[] source, int startIndex, IntPtr destination, int length) { CopyToNative(source, startIndex, destination, length); } - public static void Copy(float[] source, int startIndex, IntPtr destination, int length) + public static void Copy(float[] source, int startIndex, IntPtr destination, int length) { CopyToNative(source, startIndex, destination, length); } - public static void Copy(double[] source, int startIndex, IntPtr destination, int length) + public static void Copy(double[] source, int startIndex, IntPtr destination, int length) { CopyToNative(source, startIndex, destination, length); } @@ -360,27 +368,27 @@ namespace System.Runtime.InteropServices //==================================================================== // Copy blocks from native memory to CLR arrays //==================================================================== - public static void Copy(IntPtr source, int[] destination, int startIndex, int length) + public static void Copy(IntPtr source, int[] destination, int startIndex, int length) { CopyToManaged(source, destination, startIndex, length); } - public static void Copy(IntPtr source, char[] destination, int startIndex, int length) + public static void Copy(IntPtr source, char[] destination, int startIndex, int length) { CopyToManaged(source, destination, startIndex, length); } - public static void Copy(IntPtr source, short[] destination, int startIndex, int length) + public static void Copy(IntPtr source, short[] destination, int startIndex, int length) { CopyToManaged(source, destination, startIndex, length); } - public static void Copy(IntPtr source, long[] destination, int startIndex, int length) + public static void Copy(IntPtr source, long[] destination, int startIndex, int length) { CopyToManaged(source, destination, startIndex, length); } - public static void Copy(IntPtr source, float[] destination, int startIndex, int length) + public static void Copy(IntPtr source, float[] destination, int startIndex, int length) { CopyToManaged(source, destination, startIndex, length); } - public static void Copy(IntPtr source, double[] destination, int startIndex, int length) + public static void Copy(IntPtr source, double[] destination, int startIndex, int length) { CopyToManaged(source, destination, startIndex, length); } @@ -400,14 +408,14 @@ namespace System.Runtime.InteropServices //==================================================================== public static byte ReadByte([MarshalAs(UnmanagedType.AsAny), In] Object ptr, int ofs) { - throw new PlatformNotSupportedException(); + throw new PlatformNotSupportedException(); // https://github.com/dotnet/coreclr/issues/10442 } public static unsafe byte ReadByte(IntPtr ptr, int ofs) { try { - byte *addr = (byte *)ptr + ofs; + byte* addr = (byte*)ptr + ofs; return *addr; } catch (NullReferenceException) @@ -419,29 +427,29 @@ namespace System.Runtime.InteropServices public static byte ReadByte(IntPtr ptr) { - return ReadByte(ptr,0); + return ReadByte(ptr, 0); } - public static short ReadInt16([MarshalAs(UnmanagedType.AsAny),In] Object ptr, int ofs) + public static short ReadInt16([MarshalAs(UnmanagedType.AsAny), In] Object ptr, int ofs) { - throw new PlatformNotSupportedException(); + throw new PlatformNotSupportedException(); // https://github.com/dotnet/coreclr/issues/10442 } - + public static unsafe short ReadInt16(IntPtr ptr, int ofs) { try { - byte *addr = (byte *)ptr + ofs; + byte* addr = (byte*)ptr + ofs; if ((unchecked((int)addr) & 0x1) == 0) { // aligned read - return *((short *)addr); + return *((short*)addr); } else { // unaligned read short val; - byte *valPtr = (byte *)&val; + byte* valPtr = (byte*)&val; valPtr[0] = addr[0]; valPtr[1] = addr[1]; return val; @@ -459,26 +467,26 @@ namespace System.Runtime.InteropServices return ReadInt16(ptr, 0); } - public static int ReadInt32([MarshalAs(UnmanagedType.AsAny),In] Object ptr, int ofs) + public static int ReadInt32([MarshalAs(UnmanagedType.AsAny), In] Object ptr, int ofs) { - throw new PlatformNotSupportedException(); + throw new PlatformNotSupportedException(); // https://github.com/dotnet/coreclr/issues/10442 } - + public static unsafe int ReadInt32(IntPtr ptr, int ofs) { try { - byte *addr = (byte *)ptr + ofs; + byte* addr = (byte*)ptr + ofs; if ((unchecked((int)addr) & 0x3) == 0) { // aligned read - return *((int *)addr); + return *((int*)addr); } else { // unaligned read int val; - byte *valPtr = (byte *)&val; + byte* valPtr = (byte*)&val; valPtr[0] = addr[0]; valPtr[1] = addr[1]; valPtr[2] = addr[2]; @@ -492,59 +500,59 @@ namespace System.Runtime.InteropServices throw new AccessViolationException(); } } - + public static int ReadInt32(IntPtr ptr) { - return ReadInt32(ptr,0); + return ReadInt32(ptr, 0); } - - public static IntPtr ReadIntPtr([MarshalAs(UnmanagedType.AsAny),In] Object ptr, int ofs) + + public static IntPtr ReadIntPtr([MarshalAs(UnmanagedType.AsAny), In] Object ptr, int ofs) { - #if BIT64 - return (IntPtr) ReadInt64(ptr, ofs); - #else // 32 +#if BIT64 + return (IntPtr)ReadInt64(ptr, ofs); +#else // 32 return (IntPtr) ReadInt32(ptr, ofs); - #endif +#endif } public static IntPtr ReadIntPtr(IntPtr ptr, int ofs) { - #if BIT64 - return (IntPtr) ReadInt64(ptr, ofs); - #else // 32 +#if BIT64 + return (IntPtr)ReadInt64(ptr, ofs); +#else // 32 return (IntPtr) ReadInt32(ptr, ofs); - #endif +#endif } - + public static IntPtr ReadIntPtr(IntPtr ptr) { - #if BIT64 - return (IntPtr) ReadInt64(ptr, 0); - #else // 32 +#if BIT64 + return (IntPtr)ReadInt64(ptr, 0); +#else // 32 return (IntPtr) ReadInt32(ptr, 0); - #endif +#endif } - public static long ReadInt64([MarshalAs(UnmanagedType.AsAny),In] Object ptr, int ofs) + public static long ReadInt64([MarshalAs(UnmanagedType.AsAny), In] Object ptr, int ofs) { - throw new PlatformNotSupportedException(); + throw new PlatformNotSupportedException(); // https://github.com/dotnet/coreclr/issues/10442 } public static unsafe long ReadInt64(IntPtr ptr, int ofs) { try { - byte *addr = (byte *)ptr + ofs; + byte* addr = (byte*)ptr + ofs; if ((unchecked((int)addr) & 0x7) == 0) { // aligned read - return *((long *)addr); + return *((long*)addr); } else { // unaligned read long val; - byte *valPtr = (byte *)&val; + byte* valPtr = (byte*)&val; valPtr[0] = addr[0]; valPtr[1] = addr[1]; valPtr[2] = addr[2]; @@ -562,13 +570,13 @@ namespace System.Runtime.InteropServices throw new AccessViolationException(); } } - + public static long ReadInt64(IntPtr ptr) { - return ReadInt64(ptr,0); + return ReadInt64(ptr, 0); } - - + + //==================================================================== // Write to memory //==================================================================== @@ -576,7 +584,7 @@ namespace System.Runtime.InteropServices { try { - byte *addr = (byte *)ptr + ofs; + byte* addr = (byte*)ptr + ofs; *addr = val; } catch (NullReferenceException) @@ -586,30 +594,30 @@ namespace System.Runtime.InteropServices } } - public static void WriteByte([MarshalAs(UnmanagedType.AsAny),In,Out] Object ptr, int ofs, byte val) + public static void WriteByte([MarshalAs(UnmanagedType.AsAny), In, Out] Object ptr, int ofs, byte val) { - throw new PlatformNotSupportedException(); + throw new PlatformNotSupportedException(); // https://github.com/dotnet/coreclr/issues/10442 } public static void WriteByte(IntPtr ptr, byte val) { WriteByte(ptr, 0, val); } - + public static unsafe void WriteInt16(IntPtr ptr, int ofs, short val) { try { - byte *addr = (byte *)ptr + ofs; + byte* addr = (byte*)ptr + ofs; if ((unchecked((int)addr) & 0x1) == 0) { // aligned write - *((short *)addr) = val; + *((short*)addr) = val; } else { // unaligned write - byte *valPtr = (byte *)&val; + byte* valPtr = (byte*)&val; addr[0] = valPtr[0]; addr[1] = valPtr[1]; } @@ -621,45 +629,45 @@ namespace System.Runtime.InteropServices } } - public static void WriteInt16([MarshalAs(UnmanagedType.AsAny),In,Out] Object ptr, int ofs, short val) + public static void WriteInt16([MarshalAs(UnmanagedType.AsAny), In, Out] Object ptr, int ofs, short val) { - throw new PlatformNotSupportedException(); + throw new PlatformNotSupportedException(); // https://github.com/dotnet/coreclr/issues/10442 } public static void WriteInt16(IntPtr ptr, short val) { WriteInt16(ptr, 0, val); - } - + } + public static void WriteInt16(IntPtr ptr, int ofs, char val) { WriteInt16(ptr, ofs, (short)val); } - - public static void WriteInt16([In,Out]Object ptr, int ofs, char val) + + public static void WriteInt16([In, Out]Object ptr, int ofs, char val) { WriteInt16(ptr, ofs, (short)val); } - + public static void WriteInt16(IntPtr ptr, char val) { WriteInt16(ptr, 0, (short)val); } - + public static unsafe void WriteInt32(IntPtr ptr, int ofs, int val) { try { - byte *addr = (byte *)ptr + ofs; + byte* addr = (byte*)ptr + ofs; if ((unchecked((int)addr) & 0x3) == 0) { // aligned write - *((int *)addr) = val; + *((int*)addr) = val; } else { // unaligned write - byte *valPtr = (byte *)&val; + byte* valPtr = (byte*)&val; addr[0] = valPtr[0]; addr[1] = valPtr[1]; addr[2] = valPtr[2]; @@ -673,57 +681,57 @@ namespace System.Runtime.InteropServices } } - public static void WriteInt32([MarshalAs(UnmanagedType.AsAny),In,Out] Object ptr, int ofs, int val) + public static void WriteInt32([MarshalAs(UnmanagedType.AsAny), In, Out] Object ptr, int ofs, int val) { - throw new PlatformNotSupportedException(); + throw new PlatformNotSupportedException(); // https://github.com/dotnet/coreclr/issues/10442 } public static void WriteInt32(IntPtr ptr, int val) { - WriteInt32(ptr,0,val); - } - + WriteInt32(ptr, 0, val); + } + public static void WriteIntPtr(IntPtr ptr, int ofs, IntPtr val) { - #if BIT64 - WriteInt64(ptr, ofs, (long)val); - #else // 32 +#if BIT64 + WriteInt64(ptr, ofs, (long)val); +#else // 32 WriteInt32(ptr, ofs, (int)val); - #endif +#endif } - - public static void WriteIntPtr([MarshalAs(UnmanagedType.AsAny),In,Out] Object ptr, int ofs, IntPtr val) + + public static void WriteIntPtr([MarshalAs(UnmanagedType.AsAny), In, Out] Object ptr, int ofs, IntPtr val) { - #if BIT64 - WriteInt64(ptr, ofs, (long)val); - #else // 32 +#if BIT64 + WriteInt64(ptr, ofs, (long)val); +#else // 32 WriteInt32(ptr, ofs, (int)val); - #endif +#endif } - + public static void WriteIntPtr(IntPtr ptr, IntPtr val) { - #if BIT64 - WriteInt64(ptr, 0, (long)val); - #else // 32 +#if BIT64 + WriteInt64(ptr, 0, (long)val); +#else // 32 WriteInt32(ptr, 0, (int)val); - #endif +#endif } public static unsafe void WriteInt64(IntPtr ptr, int ofs, long val) { try { - byte *addr = (byte *)ptr + ofs; + byte* addr = (byte*)ptr + ofs; if ((unchecked((int)addr) & 0x7) == 0) { // aligned write - *((long *)addr) = val; + *((long*)addr) = val; } else { // unaligned write - byte *valPtr = (byte *)&val; + byte* valPtr = (byte*)&val; addr[0] = valPtr[0]; addr[1] = valPtr[1]; addr[2] = valPtr[2]; @@ -741,30 +749,30 @@ namespace System.Runtime.InteropServices } } - public static void WriteInt64([MarshalAs(UnmanagedType.AsAny),In,Out] Object ptr, int ofs, long val) + public static void WriteInt64([MarshalAs(UnmanagedType.AsAny), In, Out] Object ptr, int ofs, long val) { - throw new PlatformNotSupportedException(); + throw new PlatformNotSupportedException(); // https://github.com/dotnet/coreclr/issues/10442 } public static void WriteInt64(IntPtr ptr, long val) { WriteInt64(ptr, 0, val); } - - + + //==================================================================== // GetLastWin32Error //==================================================================== [MethodImplAttribute(MethodImplOptions.InternalCall)] public static extern int GetLastWin32Error(); - + //==================================================================== // SetLastWin32Error //==================================================================== [MethodImplAttribute(MethodImplOptions.InternalCall)] internal static extern void SetLastWin32Error(int error); - + //==================================================================== // GetHRForLastWin32Error @@ -784,18 +792,18 @@ namespace System.Runtime.InteropServices //==================================================================== public static void Prelink(MethodInfo m) { - if (m == null) + if (m == null) throw new ArgumentNullException(nameof(m)); Contract.EndContractBlock(); RuntimeMethodInfo rmi = m as RuntimeMethodInfo; if (rmi == null) - throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeMethodInfo")); + throw new ArgumentException(SR.Argument_MustBeRuntimeMethodInfo); InternalPrelink(rmi); } - + [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode), SuppressUnmanagedCodeSecurity] private static extern void InternalPrelink(IRuntimeMethodInfo m); @@ -806,15 +814,15 @@ namespace System.Runtime.InteropServices Contract.EndContractBlock(); MethodInfo[] mi = c.GetMethods(); - if (mi != null) + if (mi != null) { - for (int i = 0; i < mi.Length; i++) + for (int i = 0; i < mi.Length; i++) { Prelink(mi[i]); } } } - + [MethodImplAttribute(MethodImplOptions.InternalCall)] public static extern int GetExceptionCode(); @@ -844,12 +852,12 @@ namespace System.Runtime.InteropServices { PtrToStructure(ptr, (object)structure); } - + //==================================================================== // Creates a new instance of "structuretype" and marshals data from a // native memory block to it. //==================================================================== - [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable + [System.Security.DynamicSecurityMethod] // Methods containing StackCrawlMark local var has to be marked DynamicSecurityMethod public static Object PtrToStructure(IntPtr ptr, Type structureType) { if (ptr == IntPtr.Zero) return null; @@ -858,12 +866,12 @@ namespace System.Runtime.InteropServices throw new ArgumentNullException(nameof(structureType)); if (structureType.IsGenericType) - throw new ArgumentException(Environment.GetResourceString("Argument_NeedNonGenericType"), nameof(structureType)); + throw new ArgumentException(SR.Argument_NeedNonGenericType, nameof(structureType)); RuntimeType rt = structureType.UnderlyingSystemType as RuntimeType; if (rt == null) - throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"), nameof(structureType)); + throw new ArgumentException(SR.Arg_MustBeType, nameof(structureType)); StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; @@ -917,10 +925,10 @@ namespace System.Runtime.InteropServices } if (rtModule == null) - throw new ArgumentNullException(nameof(m),Environment.GetResourceString("Argument_MustBeRuntimeModule")); + throw new ArgumentNullException(nameof(m), SR.Argument_MustBeRuntimeModule); return GetHINSTANCE(rtModule.GetNativeHandle()); - } + } [SuppressUnmanagedCodeSecurity] [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode), SuppressUnmanagedCodeSecurity] @@ -952,14 +960,14 @@ namespace System.Runtime.InteropServices { if (errorCode < 0) return GetExceptionForHRInternal(errorCode, IntPtr.Zero); - else + else return null; } public static Exception GetExceptionForHR(int errorCode, IntPtr errorInfo) { if (errorCode < 0) return GetExceptionForHRInternal(errorCode, errorInfo); - else + else return null; } @@ -987,7 +995,8 @@ namespace System.Runtime.InteropServices IntPtr pNewMem = Win32Native.LocalAlloc_NoSafeHandle(LMEM_FIXED, unchecked(numBytes)); - if (pNewMem == IntPtr.Zero) { + if (pNewMem == IntPtr.Zero) + { throw new OutOfMemoryException(); } return pNewMem; @@ -997,11 +1006,13 @@ namespace System.Runtime.InteropServices { return AllocHGlobal((IntPtr)cb); } - + public static void FreeHGlobal(IntPtr hglobal) { - if (IsNotWin32Atom(hglobal)) { - if (IntPtr.Zero != Win32Native.LocalFree(hglobal)) { + if (IsNotWin32Atom(hglobal)) + { + if (IntPtr.Zero != Win32Native.LocalFree(hglobal)) + { ThrowExceptionForHR(GetHRForLastWin32Error()); } } @@ -1010,7 +1021,8 @@ namespace System.Runtime.InteropServices public static IntPtr ReAllocHGlobal(IntPtr pv, IntPtr cb) { IntPtr pNewMem = Win32Native.LocalReAlloc(pv, cb, LMEM_MOVEABLE); - if (pNewMem == IntPtr.Zero) { + if (pNewMem == IntPtr.Zero) + { throw new OutOfMemoryException(); } return pNewMem; @@ -1036,18 +1048,18 @@ namespace System.Runtime.InteropServices UIntPtr len = new UIntPtr((uint)nb); IntPtr hglobal = Win32Native.LocalAlloc_NoSafeHandle(LMEM_FIXED, len); - + if (hglobal == IntPtr.Zero) { throw new OutOfMemoryException(); } else { - s.ConvertToAnsi((byte *)hglobal, nb, false, false); + s.ConvertToAnsi((byte*)hglobal, nb, false, false); return hglobal; } } - } + } unsafe public static IntPtr StringToHGlobalUni(String s) { @@ -1065,7 +1077,7 @@ namespace System.Runtime.InteropServices UIntPtr len = new UIntPtr((uint)nb); IntPtr hglobal = Win32Native.LocalAlloc_NoSafeHandle(LMEM_FIXED, len); - + if (hglobal == IntPtr.Zero) { throw new OutOfMemoryException(); @@ -1105,7 +1117,7 @@ namespace System.Runtime.InteropServices [MethodImplAttribute(MethodImplOptions.InternalCall)] internal static extern int GetHRForException_WinRT(Exception e); - internal static readonly Guid ManagedNameGuid = new Guid("{0F21F359-AB84-41E8-9A78-36D110E6D2F9}"); + internal static readonly Guid ManagedNameGuid = new Guid("{0F21F359-AB84-41E8-9A78-36D110E6D2F9}"); //==================================================================== // Given a managed object that wraps an ITypeInfo, return its name @@ -1115,7 +1127,7 @@ namespace System.Runtime.InteropServices if (typeInfo == null) throw new ArgumentNullException(nameof(typeInfo)); Contract.EndContractBlock(); - + String strTypeLibName = null; String strDocString = null; int dwHelpContext = 0; @@ -1162,7 +1174,7 @@ namespace System.Runtime.InteropServices { throw new PlatformNotSupportedException(); } - + #if FEATURE_COMINTEROP //==================================================================== @@ -1263,7 +1275,7 @@ namespace System.Runtime.InteropServices // Overflow checking if (nb < s.Length) throw new ArgumentOutOfRangeException(nameof(s)); - + IntPtr hglobal = Win32Native.CoTaskMemAlloc(new UIntPtr((uint)nb)); if (hglobal == IntPtr.Zero) @@ -1274,7 +1286,7 @@ namespace System.Runtime.InteropServices { fixed (char* firstChar = s) { - String.wstrcpy((char *)hglobal, firstChar, s.Length + 1); + String.wstrcpy((char*)hglobal, firstChar, s.Length + 1); } return hglobal; } @@ -1296,7 +1308,7 @@ namespace System.Runtime.InteropServices if (nb < s.Length) throw new ArgumentOutOfRangeException(nameof(s)); - IntPtr pMem = Win32Native.CoTaskMemAlloc(new UIntPtr((uint)nb +1)); + IntPtr pMem = Win32Native.CoTaskMemAlloc(new UIntPtr((uint)nb + 1)); if (pMem == IntPtr.Zero) { @@ -1316,8 +1328,8 @@ namespace System.Runtime.InteropServices { // Ansi platforms are no longer supported return StringToCoTaskMemUni(s); - } - + } + unsafe public static IntPtr StringToCoTaskMemAnsi(String s) { if (s == null) @@ -1340,7 +1352,7 @@ namespace System.Runtime.InteropServices } else { - s.ConvertToAnsi((byte *)hglobal, nb, false, false); + s.ConvertToAnsi((byte*)hglobal, nb, false, false); return hglobal; } } @@ -1348,7 +1360,8 @@ namespace System.Runtime.InteropServices public static void FreeCoTaskMem(IntPtr ptr) { - if (IsNotWin32Atom(ptr)) { + if (IsNotWin32Atom(ptr)) + { Win32Native.CoTaskMemFree(ptr); } } @@ -1403,7 +1416,7 @@ namespace System.Runtime.InteropServices public static int ReleaseComObject(Object o) { __ComObject co = null; - + // Make sure the obj is an __ComObject. try { @@ -1411,16 +1424,16 @@ namespace System.Runtime.InteropServices } catch (InvalidCastException) { - throw new ArgumentException(Environment.GetResourceString("Argument_ObjNotComObject"), nameof(o)); + throw new ArgumentException(SR.Argument_ObjNotComObject, nameof(o)); } - + return co.ReleaseSelf(); - } + } [MethodImplAttribute(MethodImplOptions.InternalCall)] internal static extern int InternalReleaseComObject(Object o); - + //==================================================================== // release the COM component and zombie this object // further usage of this Object might throw an exception @@ -1440,13 +1453,13 @@ namespace System.Runtime.InteropServices } catch (InvalidCastException) { - throw new ArgumentException(Environment.GetResourceString("Argument_ObjNotComObject"), nameof(o)); + throw new ArgumentException(SR.Argument_ObjNotComObject, nameof(o)); } - + co.FinalReleaseSelf(); return 0; - } + } [MethodImplAttribute(MethodImplOptions.InternalCall)] internal static extern void InternalFinalReleaseComObject(Object o); @@ -1457,7 +1470,7 @@ namespace System.Runtime.InteropServices //==================================================================== public static Object GetComObjectData(Object obj, Object key) { - throw new PlatformNotSupportedException(); + throw new PlatformNotSupportedException(SR.Arg_PlatformNotSupported); } //==================================================================== @@ -1468,7 +1481,7 @@ namespace System.Runtime.InteropServices //==================================================================== public static bool SetComObjectData(Object obj, Object key, Object data) { - throw new PlatformNotSupportedException(); + throw new PlatformNotSupportedException(SR.Arg_PlatformNotSupported); } #if FEATURE_COMINTEROP @@ -1482,13 +1495,13 @@ namespace System.Runtime.InteropServices if (t == null) throw new ArgumentNullException(nameof(t)); if (!t.IsCOMObject) - throw new ArgumentException(Environment.GetResourceString("Argument_TypeNotComObject"), nameof(t)); + throw new ArgumentException(SR.Argument_TypeNotComObject, nameof(t)); if (t.IsGenericType) - throw new ArgumentException(Environment.GetResourceString("Argument_NeedNonGenericType"), nameof(t)); + throw new ArgumentException(SR.Argument_NeedNonGenericType, nameof(t)); Contract.EndContractBlock(); if (t.IsWindowsRuntimeObject) - throw new ArgumentException(Environment.GetResourceString("Argument_TypeIsWinRTType"), nameof(t)); + throw new ArgumentException(SR.Argument_TypeIsWinRTType, nameof(t)); // Check for the null case. if (o == null) @@ -1496,9 +1509,9 @@ namespace System.Runtime.InteropServices // Make sure the object is a COM object. if (!o.GetType().IsCOMObject) - throw new ArgumentException(Environment.GetResourceString("Argument_ObjNotComObject"), nameof(o)); + throw new ArgumentException(SR.Argument_ObjNotComObject, nameof(o)); if (o.GetType().IsWindowsRuntimeObject) - throw new ArgumentException(Environment.GetResourceString("Argument_ObjIsWinRTObject"), nameof(o)); + throw new ArgumentException(SR.Argument_ObjIsWinRTObject, nameof(o)); // Check to see if the type of the object is the requested type. if (o.GetType() == t) @@ -1537,12 +1550,12 @@ namespace System.Runtime.InteropServices // IUnknown Helpers //==================================================================== [MethodImplAttribute(MethodImplOptions.InternalCall)] - public static extern int /* HRESULT */ QueryInterface(IntPtr /* IUnknown */ pUnk, ref Guid iid, out IntPtr ppv); + public static extern int /* HRESULT */ QueryInterface(IntPtr /* IUnknown */ pUnk, ref Guid iid, out IntPtr ppv); [MethodImplAttribute(MethodImplOptions.InternalCall)] - public static extern int /* ULONG */ AddRef(IntPtr /* IUnknown */ pUnk ); + public static extern int /* ULONG */ AddRef(IntPtr /* IUnknown */ pUnk); [MethodImplAttribute(MethodImplOptions.InternalCall)] - public static extern int /* ULONG */ Release(IntPtr /* IUnknown */ pUnk ); + public static extern int /* ULONG */ Release(IntPtr /* IUnknown */ pUnk); [MethodImplAttribute(MethodImplOptions.InternalCall)] public static extern void GetNativeVariantForObject(Object obj, /* VARIANT * */ IntPtr pDstNativeVariant); @@ -1553,7 +1566,7 @@ namespace System.Runtime.InteropServices } [MethodImplAttribute(MethodImplOptions.InternalCall)] - public static extern Object GetObjectForNativeVariant(/* VARIANT * */ IntPtr pSrcNativeVariant ); + public static extern Object GetObjectForNativeVariant(/* VARIANT * */ IntPtr pSrcNativeVariant); public static T GetObjectForNativeVariant<T>(IntPtr pSrcNativeVariant) { @@ -1561,13 +1574,13 @@ namespace System.Runtime.InteropServices } [MethodImplAttribute(MethodImplOptions.InternalCall)] - public static extern Object[] GetObjectsForNativeVariants(/* VARIANT * */ IntPtr aSrcNativeVariant, int cVars ); + public static extern Object[] GetObjectsForNativeVariants(/* VARIANT * */ IntPtr aSrcNativeVariant, int cVars); public static T[] GetObjectsForNativeVariants<T>(IntPtr aSrcNativeVariant, int cVars) { object[] objects = GetObjectsForNativeVariants(aSrcNativeVariant, cVars); T[] result = null; - + if (objects != null) { result = new T[objects.Length]; @@ -1608,28 +1621,28 @@ namespace System.Runtime.InteropServices if (type == null) throw new ArgumentNullException(nameof(type)); if (type.IsImport) - throw new ArgumentException(Environment.GetResourceString("Argument_TypeMustNotBeComImport"), nameof(type)); + throw new ArgumentException(SR.Argument_TypeMustNotBeComImport, nameof(type)); if (type.IsGenericType) - throw new ArgumentException(Environment.GetResourceString("Argument_NeedNonGenericType"), nameof(type)); + throw new ArgumentException(SR.Argument_NeedNonGenericType, nameof(type)); Contract.EndContractBlock(); IList<CustomAttributeData> cas = CustomAttributeData.GetCustomAttributes(type); - for (int i = 0; i < cas.Count; i ++) + for (int i = 0; i < cas.Count; i++) { if (cas[i].Constructor.DeclaringType == typeof(ProgIdAttribute)) { // Retrieve the PROGID string from the ProgIdAttribute. IList<CustomAttributeTypedArgument> caConstructorArgs = cas[i].ConstructorArguments; Debug.Assert(caConstructorArgs.Count == 1, "caConstructorArgs.Count == 1"); - - CustomAttributeTypedArgument progIdConstructorArg = caConstructorArgs[0]; + + CustomAttributeTypedArgument progIdConstructorArg = caConstructorArgs[0]; Debug.Assert(progIdConstructorArg.ArgumentType == typeof(String), "progIdConstructorArg.ArgumentType == typeof(String)"); - + String strProgId = (String)progIdConstructorArg.Value; - + if (strProgId == null) - strProgId = String.Empty; - + strProgId = String.Empty; + return strProgId; } } @@ -1673,10 +1686,10 @@ namespace System.Runtime.InteropServices //======================================================================== private static IntPtr LoadLicenseManager() { - Assembly sys = Assembly.Load("System, Version="+ ThisAssembly.Version + + Assembly sys = Assembly.Load("System, Version=" + ThisAssembly.Version + ", Culture=neutral, PublicKeyToken=" + AssemblyRef.EcmaPublicKeyToken); Type t = sys.GetType("System.ComponentModel.LicenseManager"); - if (t == null || !t.IsVisible) + if (t == null || !t.IsVisible) return IntPtr.Zero; return t.TypeHandle.Value; } @@ -1705,20 +1718,20 @@ namespace System.Runtime.InteropServices // Validate the parameters if (ptr == IntPtr.Zero) throw new ArgumentNullException(nameof(ptr)); - + if (t == null) throw new ArgumentNullException(nameof(t)); Contract.EndContractBlock(); - + if ((t as RuntimeType) == null) - throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeType"), nameof(t)); + throw new ArgumentException(SR.Argument_MustBeRuntimeType, nameof(t)); if (t.IsGenericType) - throw new ArgumentException(Environment.GetResourceString("Argument_NeedNonGenericType"), nameof(t)); - + throw new ArgumentException(SR.Argument_NeedNonGenericType, nameof(t)); + Type c = t.BaseType; if (c == null || (c != typeof(Delegate) && c != typeof(MulticastDelegate))) - throw new ArgumentException(Environment.GetResourceString("Arg_MustBeDelegate"), nameof(t)); + throw new ArgumentException(SR.Arg_MustBeDelegate, nameof(t)); return GetDelegateForFunctionPointerInternal(ptr, t); } @@ -1748,21 +1761,25 @@ namespace System.Runtime.InteropServices [MethodImplAttribute(MethodImplOptions.InternalCall)] internal static extern IntPtr GetFunctionPointerForDelegateInternal(Delegate d); - public static IntPtr SecureStringToBSTR(SecureString s) { - if( s == null) { + public static IntPtr SecureStringToBSTR(SecureString s) + { + if (s == null) + { throw new ArgumentNullException(nameof(s)); } Contract.EndContractBlock(); - + #if FEATURE_COMINTEROP return s.MarshalToBSTR(); #else - throw new PlatformNotSupportedException(); + throw new PlatformNotSupportedException(); // https://github.com/dotnet/coreclr/issues/10443 #endif } - public static IntPtr SecureStringToCoTaskMemAnsi(SecureString s) { - if( s == null) { + public static IntPtr SecureStringToCoTaskMemAnsi(SecureString s) + { + if (s == null) + { throw new ArgumentNullException(nameof(s)); } Contract.EndContractBlock(); @@ -1772,12 +1789,13 @@ namespace System.Runtime.InteropServices public static IntPtr SecureStringToCoTaskMemUnicode(SecureString s) { - if( s == null) { + if (s == null) + { throw new ArgumentNullException(nameof(s)); } Contract.EndContractBlock(); - return s.MarshalToString(globalAlloc: false, unicode: true); + return s.MarshalToString(globalAlloc: false, unicode: true); } #if FEATURE_COMINTEROP @@ -1806,8 +1824,10 @@ namespace System.Runtime.InteropServices FreeCoTaskMem(s); } - public static IntPtr SecureStringToGlobalAllocAnsi(SecureString s) { - if( s == null) { + public static IntPtr SecureStringToGlobalAllocAnsi(SecureString s) + { + if (s == null) + { throw new ArgumentNullException(nameof(s)); } Contract.EndContractBlock(); @@ -1815,21 +1835,25 @@ namespace System.Runtime.InteropServices return s.MarshalToString(globalAlloc: true, unicode: false); } - public static IntPtr SecureStringToGlobalAllocUnicode(SecureString s) { - if( s == null) { + public static IntPtr SecureStringToGlobalAllocUnicode(SecureString s) + { + if (s == null) + { throw new ArgumentNullException(nameof(s)); } Contract.EndContractBlock(); - return s.MarshalToString(globalAlloc: true, unicode: true);; + return s.MarshalToString(globalAlloc: true, unicode: true); ; } - public static void ZeroFreeGlobalAllocAnsi(IntPtr s) { + public static void ZeroFreeGlobalAllocAnsi(IntPtr s) + { Win32Native.ZeroMemory(s, (UIntPtr)(Win32Native.lstrlenA(s))); FreeHGlobal(s); } - public static void ZeroFreeGlobalAllocUnicode(IntPtr s) { + public static void ZeroFreeGlobalAllocUnicode(IntPtr s) + { Win32Native.ZeroMemory(s, (UIntPtr)(Win32Native.lstrlenW(s) * 2)); FreeHGlobal(s); } diff --git a/src/mscorlib/src/System/Runtime/InteropServices/MarshalDirectiveException.cs b/src/mscorlib/src/System/Runtime/InteropServices/MarshalDirectiveException.cs index ec1014ecf8..6fe7574e26 100644 --- a/src/mscorlib/src/System/Runtime/InteropServices/MarshalDirectiveException.cs +++ b/src/mscorlib/src/System/Runtime/InteropServices/MarshalDirectiveException.cs @@ -11,29 +11,35 @@ ** =============================================================================*/ -namespace System.Runtime.InteropServices { - using System; - using System.Runtime.Serialization; +using System; +using System.Runtime.Serialization; +namespace System.Runtime.InteropServices +{ [Serializable] - public class MarshalDirectiveException : SystemException { - public MarshalDirectiveException() - : base(Environment.GetResourceString("Arg_MarshalDirectiveException")) { - SetErrorCode(__HResults.COR_E_MARSHALDIRECTIVE); + public class MarshalDirectiveException : SystemException + { + public MarshalDirectiveException() + : base(SR.Arg_MarshalDirectiveException) + { + HResult = __HResults.COR_E_MARSHALDIRECTIVE; } - - public MarshalDirectiveException(String message) - : base(message) { - SetErrorCode(__HResults.COR_E_MARSHALDIRECTIVE); + + public MarshalDirectiveException(String message) + : base(message) + { + HResult = __HResults.COR_E_MARSHALDIRECTIVE; } - - public MarshalDirectiveException(String message, Exception inner) - : base(message, inner) { - SetErrorCode(__HResults.COR_E_MARSHALDIRECTIVE); + + public MarshalDirectiveException(String message, Exception inner) + : base(message, inner) + { + HResult = __HResults.COR_E_MARSHALDIRECTIVE; } - protected MarshalDirectiveException(SerializationInfo info, StreamingContext context) : base(info, context) { + protected MarshalDirectiveException(SerializationInfo info, StreamingContext context) : base(info, context) + { } } } diff --git a/src/mscorlib/src/System/Runtime/InteropServices/NativeCallableAttribute.cs b/src/mscorlib/src/System/Runtime/InteropServices/NativeCallableAttribute.cs index 706ef80019..d0ab0d9460 100644 --- a/src/mscorlib/src/System/Runtime/InteropServices/NativeCallableAttribute.cs +++ b/src/mscorlib/src/System/Runtime/InteropServices/NativeCallableAttribute.cs @@ -13,7 +13,6 @@ using System.Runtime.CompilerServices; namespace System.Runtime.InteropServices { - [AttributeUsage(AttributeTargets.Method)] public sealed class NativeCallableAttribute : Attribute { diff --git a/src/mscorlib/src/System/Runtime/InteropServices/NativeMethods.cs b/src/mscorlib/src/System/Runtime/InteropServices/NativeMethods.cs index 818034ee34..ddd15c2b95 100644 --- a/src/mscorlib/src/System/Runtime/InteropServices/NativeMethods.cs +++ b/src/mscorlib/src/System/Runtime/InteropServices/NativeMethods.cs @@ -12,17 +12,18 @@ **/ #if FEATURE_COMINTEROP -namespace System.Runtime.InteropServices { - - internal static class NativeMethods { - +namespace System.Runtime.InteropServices +{ + internal static class NativeMethods + { [ System.Security.SuppressUnmanagedCodeSecurity, ComImport, InterfaceType(ComInterfaceType.InterfaceIsIUnknown), Guid("00020400-0000-0000-C000-000000000046") ] - internal interface IDispatch { + internal interface IDispatch + { } } } diff --git a/src/mscorlib/src/System/Runtime/InteropServices/NonPortable.cs b/src/mscorlib/src/System/Runtime/InteropServices/NonPortable.cs index ae974460f7..7b7c5efb90 100644 --- a/src/mscorlib/src/System/Runtime/InteropServices/NonPortable.cs +++ b/src/mscorlib/src/System/Runtime/InteropServices/NonPortable.cs @@ -15,7 +15,7 @@ namespace System.Runtime.InteropServices public static int AddRef(System.IntPtr pUnk) { - throw new PlatformNotSupportedException(); + throw new PlatformNotSupportedException(SR.PlatformNotSupported_ComInterop); } public static bool AreComObjectsAvailableForCleanup() @@ -25,12 +25,12 @@ namespace System.Runtime.InteropServices public static System.IntPtr CreateAggregatedObject(System.IntPtr pOuter, object o) { - throw new PlatformNotSupportedException(); + throw new PlatformNotSupportedException(SR.PlatformNotSupported_ComInterop); } public static Object BindToMoniker(String monikerName) { - throw new PlatformNotSupportedException(); + throw new PlatformNotSupportedException(SR.PlatformNotSupported_ComInterop); } public static void CleanupUnusedObjectsInCurrentContext() @@ -40,42 +40,42 @@ namespace System.Runtime.InteropServices public static System.IntPtr CreateAggregatedObject<T>(System.IntPtr pOuter, T o) { - throw new PlatformNotSupportedException(); + throw new PlatformNotSupportedException(SR.PlatformNotSupported_ComInterop); } public static object CreateWrapperOfType(object o, System.Type t) { - throw new PlatformNotSupportedException(); + throw new PlatformNotSupportedException(SR.PlatformNotSupported_ComInterop); } public static TWrapper CreateWrapperOfType<T, TWrapper>(T o) { - throw new PlatformNotSupportedException(); + throw new PlatformNotSupportedException(SR.PlatformNotSupported_ComInterop); } public static void ChangeWrapperHandleStrength(Object otp, bool fIsWeak) { - throw new PlatformNotSupportedException(); + throw new PlatformNotSupportedException(SR.PlatformNotSupported_ComInterop); } public static int FinalReleaseComObject(object o) { - throw new PlatformNotSupportedException(); + throw new PlatformNotSupportedException(SR.PlatformNotSupported_ComInterop); } public static System.IntPtr GetComInterfaceForObject(object o, System.Type T) { - throw new PlatformNotSupportedException(); + throw new PlatformNotSupportedException(SR.PlatformNotSupported_ComInterop); } public static System.IntPtr GetComInterfaceForObject(object o, System.Type T, System.Runtime.InteropServices.CustomQueryInterfaceMode mode) { - throw new PlatformNotSupportedException(); + throw new PlatformNotSupportedException(SR.PlatformNotSupported_ComInterop); } public static System.IntPtr GetComInterfaceForObject<T, TInterface>(T o) { - throw new PlatformNotSupportedException(); + throw new PlatformNotSupportedException(SR.PlatformNotSupported_ComInterop); } public static System.IntPtr GetHINSTANCE(System.Reflection.Module m) @@ -89,67 +89,67 @@ namespace System.Runtime.InteropServices public static System.IntPtr GetIUnknownForObject(object o) { - throw new PlatformNotSupportedException(); + throw new PlatformNotSupportedException(SR.PlatformNotSupported_ComInterop); } public static void GetNativeVariantForObject(object obj, System.IntPtr pDstNativeVariant) { - throw new PlatformNotSupportedException(); + throw new PlatformNotSupportedException(SR.PlatformNotSupported_ComInterop); } public static void GetNativeVariantForObject<T>(T obj, System.IntPtr pDstNativeVariant) { - throw new PlatformNotSupportedException(); + throw new PlatformNotSupportedException(SR.PlatformNotSupported_ComInterop); } public static Object GetTypedObjectForIUnknown(System.IntPtr pUnk, System.Type t) { - throw new PlatformNotSupportedException(); + throw new PlatformNotSupportedException(SR.PlatformNotSupported_ComInterop); } public static object GetObjectForIUnknown(System.IntPtr pUnk) { - throw new PlatformNotSupportedException(); + throw new PlatformNotSupportedException(SR.PlatformNotSupported_ComInterop); } public static object GetObjectForNativeVariant(System.IntPtr pSrcNativeVariant) { - throw new PlatformNotSupportedException(); + throw new PlatformNotSupportedException(SR.PlatformNotSupported_ComInterop); } public static T GetObjectForNativeVariant<T>(System.IntPtr pSrcNativeVariant) { - throw new PlatformNotSupportedException(); + throw new PlatformNotSupportedException(SR.PlatformNotSupported_ComInterop); } public static object[] GetObjectsForNativeVariants(System.IntPtr aSrcNativeVariant, int cVars) { - throw new PlatformNotSupportedException(); + throw new PlatformNotSupportedException(SR.PlatformNotSupported_ComInterop); } public static T[] GetObjectsForNativeVariants<T>(System.IntPtr aSrcNativeVariant, int cVars) { - throw new PlatformNotSupportedException(); + throw new PlatformNotSupportedException(SR.PlatformNotSupported_ComInterop); } public static int GetStartComSlot(System.Type t) { - throw new PlatformNotSupportedException(); + throw new PlatformNotSupportedException(SR.PlatformNotSupported_ComInterop); } public static System.Type GetTypeFromCLSID(System.Guid clsid) { - throw new PlatformNotSupportedException(); + throw new PlatformNotSupportedException(SR.PlatformNotSupported_ComInterop); } public static string GetTypeInfoName(System.Runtime.InteropServices.ComTypes.ITypeInfo typeInfo) { - throw new PlatformNotSupportedException(); + throw new PlatformNotSupportedException(SR.PlatformNotSupported_ComInterop); } public static object GetUniqueObjectForIUnknown(System.IntPtr unknown) { - throw new PlatformNotSupportedException(); + throw new PlatformNotSupportedException(SR.PlatformNotSupported_ComInterop); } public static bool IsComObject(object o) @@ -159,22 +159,22 @@ namespace System.Runtime.InteropServices public static int QueryInterface(System.IntPtr pUnk, ref System.Guid iid, out System.IntPtr ppv) { - throw new PlatformNotSupportedException(); + throw new PlatformNotSupportedException(SR.PlatformNotSupported_ComInterop); } public static int Release(System.IntPtr pUnk) { - throw new PlatformNotSupportedException(); + throw new PlatformNotSupportedException(SR.PlatformNotSupported_ComInterop); } public static int ReleaseComObject(object o) { - throw new PlatformNotSupportedException(); + throw new PlatformNotSupportedException(SR.PlatformNotSupported_ComInterop); } public static void ZeroFreeBSTR(System.IntPtr s) { - throw new PlatformNotSupportedException(); + throw new PlatformNotSupportedException(SR.PlatformNotSupported_ComInterop); } } @@ -182,14 +182,14 @@ namespace System.Runtime.InteropServices { public DispatchWrapper(object obj) { - throw new PlatformNotSupportedException(); + throw new PlatformNotSupportedException(SR.PlatformNotSupported_ComInterop); } public object WrappedObject { get { - throw new PlatformNotSupportedException(); + throw new PlatformNotSupportedException(SR.PlatformNotSupported_ComInterop); } } } @@ -198,12 +198,12 @@ namespace System.Runtime.InteropServices { public static void Combine(object rcw, System.Guid iid, int dispid, System.Delegate d) { - throw new PlatformNotSupportedException(); + throw new PlatformNotSupportedException(SR.PlatformNotSupported_ComInterop); } public static System.Delegate Remove(object rcw, System.Guid iid, int dispid, System.Delegate d) { - throw new PlatformNotSupportedException(); + throw new PlatformNotSupportedException(SR.PlatformNotSupported_ComInterop); } } } diff --git a/src/mscorlib/src/System/Runtime/InteropServices/PInvokeMap.cs b/src/mscorlib/src/System/Runtime/InteropServices/PInvokeMap.cs index f47165544a..ed289fd14b 100644 --- a/src/mscorlib/src/System/Runtime/InteropServices/PInvokeMap.cs +++ b/src/mscorlib/src/System/Runtime/InteropServices/PInvokeMap.cs @@ -9,40 +9,42 @@ // values are defined in CorHdr.h. // // -namespace System.Runtime.InteropServices { - using System.Runtime.InteropServices; - using System; - + +using System.Runtime.InteropServices; +using System; + +namespace System.Runtime.InteropServices +{ // This Enum matchs the CorPinvokeMap defined in CorHdr.h [Serializable] internal enum PInvokeMap { - NoMangle = 0x0001, // Pinvoke is to use the member name as specified. - CharSetMask = 0x0006, // Heuristic used in data type & name mapping. - CharSetNotSpec = 0x0000, - CharSetAnsi = 0x0002, - CharSetUnicode = 0x0004, - CharSetAuto = 0x0006, - - PinvokeOLE = 0x0020, // Heuristic: pinvoke will return hresult, with return value becoming the retval param. Not relevant for fields. - SupportsLastError = 0x0040, // Information about target function. Not relevant for fields. + NoMangle = 0x0001, // Pinvoke is to use the member name as specified. + CharSetMask = 0x0006, // Heuristic used in data type & name mapping. + CharSetNotSpec = 0x0000, + CharSetAnsi = 0x0002, + CharSetUnicode = 0x0004, + CharSetAuto = 0x0006, + + PinvokeOLE = 0x0020, // Heuristic: pinvoke will return hresult, with return value becoming the retval param. Not relevant for fields. + SupportsLastError = 0x0040, // Information about target function. Not relevant for fields. + + BestFitMask = 0x0030, + BestFitEnabled = 0x0010, + BestFitDisabled = 0x0020, + BestFitUseAsm = 0x0030, + + ThrowOnUnmappableCharMask = 0x3000, + ThrowOnUnmappableCharEnabled = 0x1000, + ThrowOnUnmappableCharDisabled = 0x2000, + ThrowOnUnmappableCharUseAsm = 0x3000, - BestFitMask = 0x0030, - BestFitEnabled = 0x0010, - BestFitDisabled = 0x0020, - BestFitUseAsm = 0x0030, - - ThrowOnUnmappableCharMask = 0x3000, - ThrowOnUnmappableCharEnabled = 0x1000, - ThrowOnUnmappableCharDisabled = 0x2000, - ThrowOnUnmappableCharUseAsm = 0x3000, - // None of the calling convention flags is relevant for fields. - CallConvMask = 0x0700, - CallConvWinapi = 0x0100, // Pinvoke will use native callconv appropriate to target windows platform. - CallConvCdecl = 0x0200, - CallConvStdcall = 0x0300, - CallConvThiscall = 0x0400, // In M9, pinvoke will raise exception. - CallConvFastcall = 0x0500, + CallConvMask = 0x0700, + CallConvWinapi = 0x0100, // Pinvoke will use native callconv appropriate to target windows platform. + CallConvCdecl = 0x0200, + CallConvStdcall = 0x0300, + CallConvThiscall = 0x0400, // In M9, pinvoke will raise exception. + CallConvFastcall = 0x0500, } } diff --git a/src/mscorlib/src/System/Runtime/InteropServices/RuntimeEnvironment.cs b/src/mscorlib/src/System/Runtime/InteropServices/RuntimeEnvironment.cs index 28abe0cb3b..e11e3a437d 100644 --- a/src/mscorlib/src/System/Runtime/InteropServices/RuntimeEnvironment.cs +++ b/src/mscorlib/src/System/Runtime/InteropServices/RuntimeEnvironment.cs @@ -24,18 +24,14 @@ using StackCrawlMark = System.Threading.StackCrawlMark; namespace System.Runtime.InteropServices { - static internal class RuntimeEnvironment { - + static internal class RuntimeEnvironment + { [MethodImplAttribute(MethodImplOptions.InternalCall)] internal static extern String GetModuleFileName(); - [MethodImpl (MethodImplOptions.NoInlining)] public static String GetSystemVersion() { return Assembly.GetExecutingAssembly().ImageRuntimeVersion; } - -#if FEATURE_COMINTEROP -#endif // FEATURE_COMINTEROP } } diff --git a/src/mscorlib/src/System/Runtime/InteropServices/SEHException.cs b/src/mscorlib/src/System/Runtime/InteropServices/SEHException.cs index 72b98738ae..5595fadc43 100644 --- a/src/mscorlib/src/System/Runtime/InteropServices/SEHException.cs +++ b/src/mscorlib/src/System/Runtime/InteropServices/SEHException.cs @@ -11,30 +11,37 @@ ** =============================================================================*/ -namespace System.Runtime.InteropServices { - using System.Runtime.InteropServices; - using System; - using System.Runtime.Serialization; +using System.Runtime.InteropServices; +using System; +using System.Runtime.Serialization; + +namespace System.Runtime.InteropServices +{ // Exception for Structured Exception Handler exceptions. // [Serializable] - public class SEHException : ExternalException { - public SEHException() - : base() { - SetErrorCode(__HResults.E_FAIL); + public class SEHException : ExternalException + { + public SEHException() + : base() + { + HResult = __HResults.E_FAIL; } - - public SEHException(String message) - : base(message) { - SetErrorCode(__HResults.E_FAIL); + + public SEHException(String message) + : base(message) + { + HResult = __HResults.E_FAIL; } - - public SEHException(String message, Exception inner) - : base(message, inner) { - SetErrorCode(__HResults.E_FAIL); + + public SEHException(String message, Exception inner) + : base(message, inner) + { + HResult = __HResults.E_FAIL; } - - protected SEHException(SerializationInfo info, StreamingContext context) : base(info, context) { + + protected SEHException(SerializationInfo info, StreamingContext context) : base(info, context) + { } // Exceptions can be resumable, meaning a filtered exception @@ -48,6 +55,6 @@ namespace System.Runtime.InteropServices { public virtual bool CanResume() { return false; - } + } } } diff --git a/src/mscorlib/src/System/Runtime/InteropServices/SafeArrayRankMismatchException.cs b/src/mscorlib/src/System/Runtime/InteropServices/SafeArrayRankMismatchException.cs index 12bf7e7e47..f39f1f3a41 100644 --- a/src/mscorlib/src/System/Runtime/InteropServices/SafeArrayRankMismatchException.cs +++ b/src/mscorlib/src/System/Runtime/InteropServices/SafeArrayRankMismatchException.cs @@ -10,31 +10,35 @@ ** =============================================================================*/ -namespace System.Runtime.InteropServices { - using System; - using System.Runtime.Serialization; +using System; +using System.Runtime.Serialization; +namespace System.Runtime.InteropServices +{ [Serializable] - public class SafeArrayRankMismatchException : SystemException { - public SafeArrayRankMismatchException() - : base(Environment.GetResourceString("Arg_SafeArrayRankMismatchException")) { - SetErrorCode(__HResults.COR_E_SAFEARRAYRANKMISMATCH); + public class SafeArrayRankMismatchException : SystemException + { + public SafeArrayRankMismatchException() + : base(SR.Arg_SafeArrayRankMismatchException) + { + HResult = __HResults.COR_E_SAFEARRAYRANKMISMATCH; } - - public SafeArrayRankMismatchException(String message) - : base(message) { - SetErrorCode(__HResults.COR_E_SAFEARRAYRANKMISMATCH); - } - - public SafeArrayRankMismatchException(String message, Exception inner) - : base(message, inner) { - SetErrorCode(__HResults.COR_E_SAFEARRAYRANKMISMATCH); + + public SafeArrayRankMismatchException(String message) + : base(message) + { + HResult = __HResults.COR_E_SAFEARRAYRANKMISMATCH; } - protected SafeArrayRankMismatchException(SerializationInfo info, StreamingContext context) : base(info, context) { + public SafeArrayRankMismatchException(String message, Exception inner) + : base(message, inner) + { + HResult = __HResults.COR_E_SAFEARRAYRANKMISMATCH; } + protected SafeArrayRankMismatchException(SerializationInfo info, StreamingContext context) : base(info, context) + { + } } - } diff --git a/src/mscorlib/src/System/Runtime/InteropServices/SafeArrayTypeMismatchException.cs b/src/mscorlib/src/System/Runtime/InteropServices/SafeArrayTypeMismatchException.cs index 050772af2c..2283263422 100644 --- a/src/mscorlib/src/System/Runtime/InteropServices/SafeArrayTypeMismatchException.cs +++ b/src/mscorlib/src/System/Runtime/InteropServices/SafeArrayTypeMismatchException.cs @@ -11,31 +11,35 @@ ** =============================================================================*/ -namespace System.Runtime.InteropServices { - using System; - using System.Runtime.Serialization; +using System; +using System.Runtime.Serialization; +namespace System.Runtime.InteropServices +{ [Serializable] - public class SafeArrayTypeMismatchException : SystemException { - public SafeArrayTypeMismatchException() - : base(Environment.GetResourceString("Arg_SafeArrayTypeMismatchException")) { - SetErrorCode(__HResults.COR_E_SAFEARRAYTYPEMISMATCH); + public class SafeArrayTypeMismatchException : SystemException + { + public SafeArrayTypeMismatchException() + : base(SR.Arg_SafeArrayTypeMismatchException) + { + HResult = __HResults.COR_E_SAFEARRAYTYPEMISMATCH; } - - public SafeArrayTypeMismatchException(String message) - : base(message) { - SetErrorCode(__HResults.COR_E_SAFEARRAYTYPEMISMATCH); - } - - public SafeArrayTypeMismatchException(String message, Exception inner) - : base(message, inner) { - SetErrorCode(__HResults.COR_E_SAFEARRAYTYPEMISMATCH); + + public SafeArrayTypeMismatchException(String message) + : base(message) + { + HResult = __HResults.COR_E_SAFEARRAYTYPEMISMATCH; } - protected SafeArrayTypeMismatchException(SerializationInfo info, StreamingContext context) : base(info, context) { + public SafeArrayTypeMismatchException(String message, Exception inner) + : base(message, inner) + { + HResult = __HResults.COR_E_SAFEARRAYTYPEMISMATCH; } + protected SafeArrayTypeMismatchException(SerializationInfo info, StreamingContext context) : base(info, context) + { + } } - } diff --git a/src/mscorlib/src/System/Runtime/InteropServices/SafeBuffer.cs b/src/mscorlib/src/System/Runtime/InteropServices/SafeBuffer.cs index ee5c3d8e87..aba25e94a3 100644 --- a/src/mscorlib/src/System/Runtime/InteropServices/SafeBuffer.cs +++ b/src/mscorlib/src/System/Runtime/InteropServices/SafeBuffer.cs @@ -66,8 +66,6 @@ // assignments in a static class constructor are under a lock implicitly. -namespace System.Runtime.InteropServices -{ using System; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; @@ -77,12 +75,13 @@ using Microsoft.Win32.SafeHandles; using System.Diagnostics; using System.Diagnostics.Contracts; - +namespace System.Runtime.InteropServices +{ public abstract unsafe class SafeBuffer : SafeHandleZeroOrMinusOneIsInvalid { // Steal UIntPtr.MaxValue as our uninitialized value. - private static readonly UIntPtr Uninitialized = (UIntPtr.Size == 4) ? - ((UIntPtr) UInt32.MaxValue) : ((UIntPtr) UInt64.MaxValue); + private static readonly UIntPtr Uninitialized = (UIntPtr.Size == 4) ? + ((UIntPtr)UInt32.MaxValue) : ((UIntPtr)UInt64.MaxValue); private UIntPtr _numBytes; @@ -100,15 +99,15 @@ using System.Diagnostics.Contracts; public void Initialize(ulong numBytes) { if (numBytes < 0) - throw new ArgumentOutOfRangeException(nameof(numBytes), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); + throw new ArgumentOutOfRangeException(nameof(numBytes), SR.ArgumentOutOfRange_NeedNonNegNum); if (IntPtr.Size == 4 && numBytes > UInt32.MaxValue) - throw new ArgumentOutOfRangeException(nameof(numBytes), Environment.GetResourceString("ArgumentOutOfRange_AddressSpace")); + throw new ArgumentOutOfRangeException(nameof(numBytes), SR.ArgumentOutOfRange_AddressSpace); Contract.EndContractBlock(); if (numBytes >= (ulong)Uninitialized) - throw new ArgumentOutOfRangeException(nameof(numBytes), Environment.GetResourceString("ArgumentOutOfRange_UIntPtrMax-1")); + throw new ArgumentOutOfRangeException(nameof(numBytes), SR.ArgumentOutOfRange_UIntPtrMax); - _numBytes = (UIntPtr) numBytes; + _numBytes = (UIntPtr)numBytes; } /// <summary> @@ -119,18 +118,18 @@ using System.Diagnostics.Contracts; public void Initialize(uint numElements, uint sizeOfEachElement) { if (numElements < 0) - throw new ArgumentOutOfRangeException(nameof(numElements), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); + throw new ArgumentOutOfRangeException(nameof(numElements), SR.ArgumentOutOfRange_NeedNonNegNum); if (sizeOfEachElement < 0) - throw new ArgumentOutOfRangeException(nameof(sizeOfEachElement), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); + throw new ArgumentOutOfRangeException(nameof(sizeOfEachElement), SR.ArgumentOutOfRange_NeedNonNegNum); if (IntPtr.Size == 4 && numElements * sizeOfEachElement > UInt32.MaxValue) - throw new ArgumentOutOfRangeException("numBytes", Environment.GetResourceString("ArgumentOutOfRange_AddressSpace")); + throw new ArgumentOutOfRangeException("numBytes", SR.ArgumentOutOfRange_AddressSpace); Contract.EndContractBlock(); if (numElements * sizeOfEachElement >= (ulong)Uninitialized) - throw new ArgumentOutOfRangeException(nameof(numElements), Environment.GetResourceString("ArgumentOutOfRange_UIntPtrMax-1")); + throw new ArgumentOutOfRangeException(nameof(numElements), SR.ArgumentOutOfRange_UIntPtrMax); - _numBytes = checked((UIntPtr) (numElements * sizeOfEachElement)); + _numBytes = checked((UIntPtr)(numElements * sizeOfEachElement)); } /// <summary> @@ -209,7 +208,8 @@ using System.Diagnostics.Contracts; /// may have to consider alignment.</param> /// <returns>An instance of T read from memory.</returns> [CLSCompliant(false)] - public T Read<T>(ulong byteOffset) where T : struct { + public T Read<T>(ulong byteOffset) where T : struct + { if (_numBytes == Uninitialized) throw NotInitialized(); @@ -240,13 +240,13 @@ using System.Diagnostics.Contracts; where T : struct { if (array == null) - throw new ArgumentNullException(nameof(array), Environment.GetResourceString("ArgumentNull_Buffer")); + throw new ArgumentNullException(nameof(array), SR.ArgumentNull_Buffer); if (index < 0) - throw new ArgumentOutOfRangeException(nameof(index), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); + throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_NeedNonNegNum); if (count < 0) - throw new ArgumentOutOfRangeException(nameof(count), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); + throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); if (array.Length - index < count) - throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen")); + throw new ArgumentException(SR.Argument_InvalidOffLen); Contract.EndContractBlock(); if (_numBytes == Uninitialized) @@ -282,7 +282,8 @@ using System.Diagnostics.Contracts; /// may have to consider alignment.</param> /// <param name="value">The value type to write to memory.</param> [CLSCompliant(false)] - public void Write<T>(ulong byteOffset, T value) where T : struct { + public void Write<T>(ulong byteOffset, T value) where T : struct + { if (_numBytes == Uninitialized) throw NotInitialized(); @@ -310,13 +311,13 @@ using System.Diagnostics.Contracts; where T : struct { if (array == null) - throw new ArgumentNullException(nameof(array), Environment.GetResourceString("ArgumentNull_Buffer")); + throw new ArgumentNullException(nameof(array), SR.ArgumentNull_Buffer); if (index < 0) - throw new ArgumentOutOfRangeException(nameof(index), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); + throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_NeedNonNegNum); if (count < 0) - throw new ArgumentOutOfRangeException(nameof(count), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); + throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); if (array.Length - index < count) - throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen")); + throw new ArgumentException(SR.Argument_InvalidOffLen); Contract.EndContractBlock(); if (_numBytes == Uninitialized) @@ -326,7 +327,7 @@ using System.Diagnostics.Contracts; uint alignedSizeofT = Marshal.AlignedSizeOf<T>(); byte* ptr = (byte*)handle + byteOffset; SpaceCheck(ptr, checked((ulong)(alignedSizeofT * count))); - + bool mustCallRelease = false; RuntimeHelpers.PrepareConstrainedRegions(); try @@ -347,35 +348,37 @@ using System.Diagnostics.Contracts; /// Returns the number of bytes in the memory region. /// </summary> [CLSCompliant(false)] - public ulong ByteLength { - get { + public ulong ByteLength + { + get + { if (_numBytes == Uninitialized) throw NotInitialized(); - return (ulong) _numBytes; + return (ulong)_numBytes; } } /* No indexer. The perf would be misleadingly bad. People should use * AcquirePointer and ReleasePointer instead. */ - + private void SpaceCheck(byte* ptr, ulong sizeInBytes) { if ((ulong)_numBytes < sizeInBytes) NotEnoughRoom(); - if ((ulong)(ptr - (byte*) handle) > ((ulong)_numBytes) - sizeInBytes) + if ((ulong)(ptr - (byte*)handle) > ((ulong)_numBytes) - sizeInBytes) NotEnoughRoom(); } private static void NotEnoughRoom() { - throw new ArgumentException(Environment.GetResourceString("Arg_BufferTooSmall")); + throw new ArgumentException(SR.Arg_BufferTooSmall); } private static InvalidOperationException NotInitialized() { Debug.Assert(false, "Uninitialized SafeBuffer! Someone needs to call Initialize before using this instance!"); - return new InvalidOperationException(Environment.GetResourceString("InvalidOperation_MustCallInitialize")); + return new InvalidOperationException(SR.InvalidOperation_MustCallInitialize); } // FCALL limitations mean we can't have generic FCALL methods. However, we can pass diff --git a/src/mscorlib/src/System/Runtime/InteropServices/SafeHandle.cs b/src/mscorlib/src/System/Runtime/InteropServices/SafeHandle.cs index 591caa2877..6654ec9b00 100644 --- a/src/mscorlib/src/System/Runtime/InteropServices/SafeHandle.cs +++ b/src/mscorlib/src/System/Runtime/InteropServices/SafeHandle.cs @@ -14,276 +14,281 @@ ** ===========================================================*/ -namespace System.Runtime.InteropServices { - -using System; -using System.Reflection; -using System.Threading; -using System.Runtime; -using System.Runtime.CompilerServices; -using System.IO; -using System.Runtime.ConstrainedExecution; -using System.Runtime.Versioning; - -/* - Problems addressed by the SafeHandle class: - 1) Critical finalization - ensure we never leak OS resources in SQL. Done - without running truly arbitrary & unbounded amounts of managed code. - 2) Reduced graph promotion - during finalization, keep object graph small - 3) GC.KeepAlive behavior - P/Invoke vs. finalizer thread race conditions (HandleRef) - 4) Elimination of security race conditions w/ explicit calls to Close (HandleProtector) - 5) Enforcement of the above via the type system - Don't use IntPtr anymore. - 6) Allows the handle lifetime to be controlled externally via a boolean. - - Subclasses of SafeHandle will implement the ReleaseHandle abstract method - used to execute any code required to free the handle. This method will be - prepared as a constrained execution region at instance construction time - (along with all the methods in its statically determinable call graph). This - implies that we won't get any inconvenient jit allocation errors or rude - thread abort interrupts while releasing the handle but the user must still - write careful code to avoid injecting fault paths of their own (see the CER - spec for more details). In particular, any sub-methods you call should be - decorated with a reliability contract of the appropriate level. In most cases - this should be: - ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success) - Also, any P/Invoke methods should use the SuppressUnmanagedCodeSecurity - attribute to avoid a runtime security check that can also inject failures - (even if the check is guaranteed to pass). - - The GC will run ReleaseHandle methods after any normal finalizers have been - run for objects that were collected at the same time. This ensures classes - like FileStream can run a normal finalizer to flush out existing buffered - data. This is key - it means adding this class to a class like FileStream does - not alter our current semantics w.r.t. finalization today. - - Subclasses must also implement the IsInvalid property so that the - infrastructure can tell when critical finalization is actually required. - Again, this method is prepared ahead of time. It's envisioned that direct - subclasses of SafeHandle will provide an IsInvalid implementation that suits - the general type of handle they support (null is invalid, -1 is invalid etc.) - and then these classes will be further derived for specific safe handle types. - - Most classes using SafeHandle should not provide a finalizer. If they do - need to do so (ie, for flushing out file buffers, needing to write some data - back into memory, etc), then they can provide a finalizer that will be - guaranteed to run before the SafeHandle's critical finalizer. - - Note that SafeHandle's ReleaseHandle is called from a constrained execution - region, and is eagerly prepared before we create your class. This means you - should only call methods with an appropriate reliability contract from your - ReleaseHandle method. - - Subclasses are expected to be written as follows (note that - SuppressUnmanagedCodeSecurity should always be used on any P/Invoke methods - invoked as part of ReleaseHandle, in order to switch the security check from - runtime to jit time and thus remove a possible failure path from the - invocation of the method): - - internal sealed MySafeHandleSubclass : SafeHandle { - // Called by P/Invoke when returning SafeHandles - private MySafeHandleSubclass() : base(IntPtr.Zero, true) - { +namespace System.Runtime.InteropServices +{ + using System; + using System.Reflection; + using System.Threading; + using System.Runtime; + using System.Runtime.CompilerServices; + using System.IO; + using System.Runtime.ConstrainedExecution; + using System.Runtime.Versioning; + + /* + Problems addressed by the SafeHandle class: + 1) Critical finalization - ensure we never leak OS resources in SQL. Done + without running truly arbitrary & unbounded amounts of managed code. + 2) Reduced graph promotion - during finalization, keep object graph small + 3) GC.KeepAlive behavior - P/Invoke vs. finalizer thread race conditions (HandleRef) + 4) Elimination of security race conditions w/ explicit calls to Close (HandleProtector) + 5) Enforcement of the above via the type system - Don't use IntPtr anymore. + 6) Allows the handle lifetime to be controlled externally via a boolean. + + Subclasses of SafeHandle will implement the ReleaseHandle abstract method + used to execute any code required to free the handle. This method will be + prepared as a constrained execution region at instance construction time + (along with all the methods in its statically determinable call graph). This + implies that we won't get any inconvenient jit allocation errors or rude + thread abort interrupts while releasing the handle but the user must still + write careful code to avoid injecting fault paths of their own (see the CER + spec for more details). In particular, any sub-methods you call should be + decorated with a reliability contract of the appropriate level. In most cases + this should be: + ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success) + Also, any P/Invoke methods should use the SuppressUnmanagedCodeSecurity + attribute to avoid a runtime security check that can also inject failures + (even if the check is guaranteed to pass). + + The GC will run ReleaseHandle methods after any normal finalizers have been + run for objects that were collected at the same time. This ensures classes + like FileStream can run a normal finalizer to flush out existing buffered + data. This is key - it means adding this class to a class like FileStream does + not alter our current semantics w.r.t. finalization today. + + Subclasses must also implement the IsInvalid property so that the + infrastructure can tell when critical finalization is actually required. + Again, this method is prepared ahead of time. It's envisioned that direct + subclasses of SafeHandle will provide an IsInvalid implementation that suits + the general type of handle they support (null is invalid, -1 is invalid etc.) + and then these classes will be further derived for specific safe handle types. + + Most classes using SafeHandle should not provide a finalizer. If they do + need to do so (ie, for flushing out file buffers, needing to write some data + back into memory, etc), then they can provide a finalizer that will be + guaranteed to run before the SafeHandle's critical finalizer. + + Note that SafeHandle's ReleaseHandle is called from a constrained execution + region, and is eagerly prepared before we create your class. This means you + should only call methods with an appropriate reliability contract from your + ReleaseHandle method. + + Subclasses are expected to be written as follows (note that + SuppressUnmanagedCodeSecurity should always be used on any P/Invoke methods + invoked as part of ReleaseHandle, in order to switch the security check from + runtime to jit time and thus remove a possible failure path from the + invocation of the method): + + internal sealed MySafeHandleSubclass : SafeHandle { + // Called by P/Invoke when returning SafeHandles + private MySafeHandleSubclass() : base(IntPtr.Zero, true) + { + } + + // If & only if you need to support user-supplied handles + internal MySafeHandleSubclass(IntPtr preexistingHandle, bool ownsHandle) : base(IntPtr.Zero, ownsHandle) + { + SetHandle(preexistingHandle); + } + + // Do not provide a finalizer - SafeHandle's critical finalizer will + // call ReleaseHandle for you. + + public override bool IsInvalid { + get { return handle == IntPtr.Zero; } + } + + override protected bool ReleaseHandle() + { + return MyNativeMethods.CloseHandle(handle); + } } - // If & only if you need to support user-supplied handles - internal MySafeHandleSubclass(IntPtr preexistingHandle, bool ownsHandle) : base(IntPtr.Zero, ownsHandle) - { - SetHandle(preexistingHandle); - } + Then elsewhere to create one of these SafeHandles, define a method + with the following type of signature (CreateFile follows this model). + Note that when returning a SafeHandle like this, P/Invoke will call your + class's default constructor. Also, you probably want to define CloseHandle + somewhere, and remember to apply a reliability contract to it. - // Do not provide a finalizer - SafeHandle's critical finalizer will - // call ReleaseHandle for you. + [SuppressUnmanagedCodeSecurity] + internal static class MyNativeMethods { + [DllImport("kernel32")] + private static extern MySafeHandleSubclass CreateHandle(int someState); - public override bool IsInvalid { - get { return handle == IntPtr.Zero; } + [DllImport("kernel32", SetLastError=true), ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] + private static extern bool CloseHandle(IntPtr handle); } - override protected bool ReleaseHandle() - { - return MyNativeMethods.CloseHandle(handle); - } - } - - Then elsewhere to create one of these SafeHandles, define a method - with the following type of signature (CreateFile follows this model). - Note that when returning a SafeHandle like this, P/Invoke will call your - class's default constructor. Also, you probably want to define CloseHandle - somewhere, and remember to apply a reliability contract to it. - - [SuppressUnmanagedCodeSecurity] - internal static class MyNativeMethods { - [DllImport("kernel32")] - private static extern MySafeHandleSubclass CreateHandle(int someState); - - [DllImport("kernel32", SetLastError=true), ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] - private static extern bool CloseHandle(IntPtr handle); - } - - Drawbacks with this implementation: - 1) Requires some magic to run the critical finalizer. - 2) Requires more memory than just an IntPtr. - 3) If you use DangerousAddRef and forget to call DangerousRelease, you can leak a SafeHandle. Use CER's & don't do that. - */ - - -// This class should not be serializable - it's a handle. We require unmanaged -// code permission to subclass SafeHandle to prevent people from writing a -// subclass and suddenly being able to run arbitrary native code with the -// same signature as CloseHandle. This is technically a little redundant, but -// 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. -public abstract class SafeHandle : CriticalFinalizerObject, IDisposable -{ - // ! Do not add or rearrange fields as the EE depends on this layout. - //------------------------------------------------------------------ + Drawbacks with this implementation: + 1) Requires some magic to run the critical finalizer. + 2) Requires more memory than just an IntPtr. + 3) If you use DangerousAddRef and forget to call DangerousRelease, you can leak a SafeHandle. Use CER's & don't do that. + */ + + + // This class should not be serializable - it's a handle. We require unmanaged + // code permission to subclass SafeHandle to prevent people from writing a + // subclass and suddenly being able to run arbitrary native code with the + // same signature as CloseHandle. This is technically a little redundant, but + // 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. + public abstract class SafeHandle : CriticalFinalizerObject, IDisposable + { + // ! Do not add or rearrange fields as the EE depends on this layout. + //------------------------------------------------------------------ #if DEBUG - // FxCop thinks this field is marshaled and so it raises a CA2101 error unless - // we specify this. In practice this is never presented to Win32. - [MarshalAs(UnmanagedType.LPWStr)] - private String _stackTrace; // Where we allocated this SafeHandle. + // FxCop thinks this field is marshaled and so it raises a CA2101 error unless + // we specify this. In practice this is never presented to Win32. + [MarshalAs(UnmanagedType.LPWStr)] + private String _stackTrace; // Where we allocated this SafeHandle. #endif - protected IntPtr handle; // this must be protected so derived classes can use out params. - private int _state; // Combined ref count and closed/disposed flags (so we can atomically modify them). - private bool _ownsHandle; // Whether we can release this handle. + protected IntPtr handle; // this must be protected so derived classes can use out params. + private int _state; // Combined ref count and closed/disposed flags (so we can atomically modify them). + private bool _ownsHandle; // Whether we can release this handle. #pragma warning disable 414 - private bool _fullyInitialized; // Whether constructor completed. + private bool _fullyInitialized; // Whether constructor completed. #pragma warning restore 414 - // Creates a SafeHandle class. Users must then set the Handle property. - // To prevent the SafeHandle from being freed, write a subclass that - // doesn't define a finalizer. - protected SafeHandle(IntPtr invalidHandleValue, bool ownsHandle) - { - handle = invalidHandleValue; - _state = 4; // Ref count 1 and not closed or disposed. - _ownsHandle = ownsHandle; + // Creates a SafeHandle class. Users must then set the Handle property. + // To prevent the SafeHandle from being freed, write a subclass that + // doesn't define a finalizer. + protected SafeHandle(IntPtr invalidHandleValue, bool ownsHandle) + { + handle = invalidHandleValue; + _state = 4; // Ref count 1 and not closed or disposed. + _ownsHandle = ownsHandle; - if (!ownsHandle) - GC.SuppressFinalize(this); + if (!ownsHandle) + GC.SuppressFinalize(this); #if DEBUG - if (BCLDebug.SafeHandleStackTracesEnabled) - _stackTrace = Environment.GetStackTrace(null, false); - else - _stackTrace = "For a stack trace showing who allocated this SafeHandle, set SafeHandleStackTraces to 1 and rerun your app."; + if (BCLDebug.SafeHandleStackTracesEnabled) + _stackTrace = Environment.GetStackTrace(null, false); + else + _stackTrace = "For a stack trace showing who allocated this SafeHandle, set SafeHandleStackTraces to 1 and rerun your app."; #endif - // Set this last to prevent SafeHandle's finalizer from freeing an - // invalid handle. This means we don't have to worry about - // ThreadAbortExceptions interrupting this constructor or the managed - // constructors on subclasses that call this constructor. - _fullyInitialized = true; - } - - // 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(); - } - - ~SafeHandle() - { - Dispose(false); - } - - [MethodImplAttribute(MethodImplOptions.InternalCall)] - extern void InternalFinalize(); - - protected void SetHandle(IntPtr handle) { - this.handle = handle; + // Set this last to prevent SafeHandle's finalizer from freeing an + // invalid handle. This means we don't have to worry about + // ThreadAbortExceptions interrupting this constructor or the managed + // constructors on subclasses that call this constructor. + _fullyInitialized = true; + } + + // 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(); + } + + ~SafeHandle() + { + Dispose(false); + } + + [MethodImplAttribute(MethodImplOptions.InternalCall)] + private extern void InternalFinalize(); + + protected void SetHandle(IntPtr handle) + { + this.handle = handle; + } + + // This method is necessary for getting an IntPtr out of a SafeHandle. + // Used to tell whether a call to create the handle succeeded by comparing + // the handle against a known invalid value, and for backwards + // compatibility to support the handle properties returning IntPtrs on + // many of our Framework classes. + // Note that this method is dangerous for two reasons: + // 1) If the handle has been marked invalid with SetHandleasInvalid, + // DangerousGetHandle will still return the original handle value. + // 2) The handle returned may be recycled at any point. At best this means + // the handle might stop working suddenly. At worst, if the handle or + // the resource the handle represents is exposed to untrusted code in + // any way, this can lead to a handle recycling security attack (i.e. an + // untrusted caller can query data on the handle you've just returned + // and get back information for an entirely unrelated resource). + public IntPtr DangerousGetHandle() + { + return handle; + } + + public bool IsClosed + { + get { return (_state & 1) == 1; } + } + + public abstract bool IsInvalid + { + get; + } + + public void Close() + { + Dispose(true); + } + + public void Dispose() + { + Dispose(true); + } + + protected virtual void Dispose(bool disposing) + { + if (disposing) + InternalDispose(); + else + InternalFinalize(); + } + + [MethodImplAttribute(MethodImplOptions.InternalCall)] + private extern void InternalDispose(); + + // This should only be called for cases when you know for a fact that + // 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! + [MethodImplAttribute(MethodImplOptions.InternalCall)] + public extern void SetHandleAsInvalid(); + + // Implement this abstract method in your derived class to specify how to + // free the handle. Be careful not write any code that's subject to faults + // in this method (the runtime will prepare the infrastructure for you so + // that no jit allocations etc. will occur, but don't allocate memory unless + // you can deal with the failure and still free the handle). + // The boolean returned should be true for success and false if the runtime + // should fire a SafeHandleCriticalFailure MDA (CustomerDebugProbe) if that + // MDA is enabled. + protected abstract bool ReleaseHandle(); + + // Add a reason why this handle should not be relinquished (i.e. have + // ReleaseHandle called on it). This method has dangerous in the name since + // it must always be used carefully (e.g. called within a CER) to avoid + // leakage of the handle. It returns a boolean indicating whether the + // increment was actually performed to make it easy for program logic to + // back out in failure cases (i.e. is a call to DangerousRelease needed). + // It is passed back via a ref parameter rather than as a direct return so + // that callers need not worry about the atomicity of calling the routine + // and assigning the return value to a variable (the variable should be + // explicitly set to false prior to the call). The only failure cases are + // 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. + [MethodImplAttribute(MethodImplOptions.InternalCall)] + public extern void DangerousAddRef(ref bool success); + + // Partner to DangerousAddRef. This should always be successful when used in + // a correct manner (i.e. matching a successful DangerousAddRef and called + // from a region such as a CER where a thread abort cannot interrupt + // processing). In the same way that unbalanced DangerousAddRef calls can + // cause resource leakage, unbalanced DangerousRelease calls may cause + // invalid handle states to become visible to other threads. This + // 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. + [MethodImplAttribute(MethodImplOptions.InternalCall)] + public extern void DangerousRelease(); } - - // This method is necessary for getting an IntPtr out of a SafeHandle. - // Used to tell whether a call to create the handle succeeded by comparing - // the handle against a known invalid value, and for backwards - // compatibility to support the handle properties returning IntPtrs on - // many of our Framework classes. - // Note that this method is dangerous for two reasons: - // 1) If the handle has been marked invalid with SetHandleasInvalid, - // DangerousGetHandle will still return the original handle value. - // 2) The handle returned may be recycled at any point. At best this means - // the handle might stop working suddenly. At worst, if the handle or - // the resource the handle represents is exposed to untrusted code in - // any way, this can lead to a handle recycling security attack (i.e. an - // untrusted caller can query data on the handle you've just returned - // and get back information for an entirely unrelated resource). - public IntPtr DangerousGetHandle() - { - return handle; - } - - public bool IsClosed { - get { return (_state & 1) == 1; } - } - - public abstract bool IsInvalid { - get; - } - - public void Close() { - Dispose(true); - } - - public void Dispose() { - Dispose(true); - } - - protected virtual void Dispose(bool disposing) - { - if (disposing) - InternalDispose(); - else - InternalFinalize(); - } - - [MethodImplAttribute(MethodImplOptions.InternalCall)] - private extern void InternalDispose(); - - // This should only be called for cases when you know for a fact that - // 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! - [MethodImplAttribute(MethodImplOptions.InternalCall)] - public extern void SetHandleAsInvalid(); - - // Implement this abstract method in your derived class to specify how to - // free the handle. Be careful not write any code that's subject to faults - // in this method (the runtime will prepare the infrastructure for you so - // that no jit allocations etc. will occur, but don't allocate memory unless - // you can deal with the failure and still free the handle). - // The boolean returned should be true for success and false if the runtime - // should fire a SafeHandleCriticalFailure MDA (CustomerDebugProbe) if that - // MDA is enabled. - protected abstract bool ReleaseHandle(); - - // Add a reason why this handle should not be relinquished (i.e. have - // ReleaseHandle called on it). This method has dangerous in the name since - // it must always be used carefully (e.g. called within a CER) to avoid - // leakage of the handle. It returns a boolean indicating whether the - // increment was actually performed to make it easy for program logic to - // back out in failure cases (i.e. is a call to DangerousRelease needed). - // It is passed back via a ref parameter rather than as a direct return so - // that callers need not worry about the atomicity of calling the routine - // and assigning the return value to a variable (the variable should be - // explicitly set to false prior to the call). The only failure cases are - // 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. - [MethodImplAttribute(MethodImplOptions.InternalCall)] - public extern void DangerousAddRef(ref bool success); - - // Partner to DangerousAddRef. This should always be successful when used in - // a correct manner (i.e. matching a successful DangerousAddRef and called - // from a region such as a CER where a thread abort cannot interrupt - // processing). In the same way that unbalanced DangerousAddRef calls can - // cause resource leakage, unbalanced DangerousRelease calls may cause - // invalid handle states to become visible to other threads. This - // 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. - [MethodImplAttribute(MethodImplOptions.InternalCall)] - public extern void DangerousRelease(); -} } diff --git a/src/mscorlib/src/System/Runtime/InteropServices/UnknownWrapper.cs b/src/mscorlib/src/System/Runtime/InteropServices/UnknownWrapper.cs index 1f70108a02..c758ae1b4f 100644 --- a/src/mscorlib/src/System/Runtime/InteropServices/UnknownWrapper.cs +++ b/src/mscorlib/src/System/Runtime/InteropServices/UnknownWrapper.cs @@ -11,10 +11,11 @@ ** =============================================================================*/ -namespace System.Runtime.InteropServices { - - using System; +using System; + +namespace System.Runtime.InteropServices +{ [Serializable] public sealed class UnknownWrapper { @@ -23,9 +24,9 @@ namespace System.Runtime.InteropServices { m_WrappedObject = obj; } - public Object WrappedObject + public Object WrappedObject { - get + get { return m_WrappedObject; } diff --git a/src/mscorlib/src/System/Runtime/InteropServices/VariantWrapper.cs b/src/mscorlib/src/System/Runtime/InteropServices/VariantWrapper.cs index 3f5120af39..50689e08f8 100644 --- a/src/mscorlib/src/System/Runtime/InteropServices/VariantWrapper.cs +++ b/src/mscorlib/src/System/Runtime/InteropServices/VariantWrapper.cs @@ -11,10 +11,11 @@ ** =============================================================================*/ -namespace System.Runtime.InteropServices { - - using System; +using System; + +namespace System.Runtime.InteropServices +{ [Serializable] public sealed class VariantWrapper @@ -24,9 +25,9 @@ namespace System.Runtime.InteropServices { m_WrappedObject = obj; } - public Object WrappedObject + public Object WrappedObject { - get + get { return m_WrappedObject; } diff --git a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/Attributes.cs b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/Attributes.cs index 7fa2420530..d78aae216b 100644 --- a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/Attributes.cs +++ b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/Attributes.cs @@ -90,14 +90,14 @@ namespace System.Runtime.InteropServices.WindowsRuntime [AttributeUsage(AttributeTargets.Parameter, Inherited = false, AllowMultiple = false)] public sealed class ReadOnlyArrayAttribute : Attribute { - public ReadOnlyArrayAttribute() {} + public ReadOnlyArrayAttribute() { } } // Applies to write-only array parameters [AttributeUsage(AttributeTargets.Parameter, Inherited = false, AllowMultiple = false)] public sealed class WriteOnlyArrayAttribute : Attribute { - public WriteOnlyArrayAttribute() {} + public WriteOnlyArrayAttribute() { } } @@ -119,5 +119,4 @@ namespace System.Runtime.InteropServices.WindowsRuntime get { return m_Name; } } } - } diff --git a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/BindableVectorToCollectionAdapter.cs b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/BindableVectorToCollectionAdapter.cs index e3c6a926d3..350920564a 100644 --- a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/BindableVectorToCollectionAdapter.cs +++ b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/BindableVectorToCollectionAdapter.cs @@ -39,7 +39,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime uint size = _this.Size; if (((uint)Int32.MaxValue) < size) { - throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_CollectionBackingListTooLarge")); + throw new InvalidOperationException(SR.InvalidOperation_CollectionBackingListTooLarge); } return (int)size; @@ -68,7 +68,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime // ICollection expects the destination array to be single-dimensional. if (array.Rank != 1) - throw new ArgumentException(Environment.GetResourceString("Arg_RankMultiDimNotSupported")); + throw new ArgumentException(SR.Arg_RankMultiDimNotSupported); int destLB = array.GetLowerBound(0); @@ -87,11 +87,11 @@ namespace System.Runtime.InteropServices.WindowsRuntime // Array items = Array.CreateInstance(typeof(object), new int[] { 1 }, new int[] { -1 }); // list.CopyTo(items, 0); - if(srcLen > (destLen - (arrayIndex - destLB))) - throw new ArgumentException(Environment.GetResourceString("Argument_InsufficientSpaceToCopyCollection")); + if (srcLen > (destLen - (arrayIndex - destLB))) + throw new ArgumentException(SR.Argument_InsufficientSpaceToCopyCollection); - if(arrayIndex - destLB > destLen) - throw new ArgumentException(Environment.GetResourceString("Argument_IndexOutOfArrayBounds")); + if (arrayIndex - destLB > destLen) + throw new ArgumentException(SR.Argument_IndexOutOfArrayBounds); // We need to verify the index as we; IBindableVector _this = JitHelpers.UnsafeCast<IBindableVector>(this); diff --git a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/BindableVectorToListAdapter.cs b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/BindableVectorToListAdapter.cs index d6e50f5164..539b8020b8 100644 --- a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/BindableVectorToListAdapter.cs +++ b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/BindableVectorToListAdapter.cs @@ -60,7 +60,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime uint size = _this.Size; if (((uint)Int32.MaxValue) < size) { - throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_CollectionBackingListTooLarge")); + throw new InvalidOperationException(SR.InvalidOperation_CollectionBackingListTooLarge); } return (int)(size - 1); @@ -109,7 +109,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime if (((uint)Int32.MaxValue) < index) { - throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_CollectionBackingListTooLarge")); + throw new InvalidOperationException(SR.InvalidOperation_CollectionBackingListTooLarge); } return (int)index; @@ -137,7 +137,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime { if (((uint)Int32.MaxValue) < index) { - throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_CollectionBackingListTooLarge")); + throw new InvalidOperationException(SR.InvalidOperation_CollectionBackingListTooLarge); } RemoveAtHelper(_this, index); diff --git a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/CLRIKeyValuePairImpl.cs b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/CLRIKeyValuePairImpl.cs index 3a52d12234..86321e6191 100644 --- a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/CLRIKeyValuePairImpl.cs +++ b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/CLRIKeyValuePairImpl.cs @@ -47,7 +47,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime internal static object UnboxHelper(object wrapper) { Contract.Requires(wrapper != null); - + CLRIKeyValuePairImpl<K, V> reference = (CLRIKeyValuePairImpl<K, V>)wrapper; return reference._pair; } @@ -61,6 +61,5 @@ namespace System.Runtime.InteropServices.WindowsRuntime { return _pair; } - } } diff --git a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/CLRIPropertyValueImpl.cs b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/CLRIPropertyValueImpl.cs index b7dad17a6b..aa0f3ba056 100644 --- a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/CLRIPropertyValueImpl.cs +++ b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/CLRIPropertyValueImpl.cs @@ -25,9 +25,12 @@ namespace System.Runtime.InteropServices.WindowsRuntime _data = data; } - private static Tuple<Type, PropertyType>[] NumericScalarTypes { - get { - if (s_numericScalarTypes == null) { + private static Tuple<Type, PropertyType>[] NumericScalarTypes + { + get + { + if (s_numericScalarTypes == null) + { Tuple<Type, PropertyType>[] numericScalarTypes = new Tuple<Type, PropertyType>[] { new Tuple<Type, PropertyType>(typeof(Byte), PropertyType.UInt8), new Tuple<Type, PropertyType>(typeof(Int16), PropertyType.Int16), @@ -47,14 +50,17 @@ namespace System.Runtime.InteropServices.WindowsRuntime } } - public PropertyType Type { + public PropertyType Type + { [Pure] get { return _type; } } - public bool IsNumericScalar { + public bool IsNumericScalar + { [Pure] - get { + get + { return IsNumericScalarImpl(_type, _data); } } @@ -128,7 +134,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime public char GetChar16() { if (this.Type != PropertyType.Char16) - throw new InvalidCastException(Environment.GetResourceString("InvalidCast_WinRTIPropertyValueElement", this.Type, "Char16"), __HResults.TYPE_E_TYPEMISMATCH); + throw new InvalidCastException(SR.Format(SR.InvalidCast_WinRTIPropertyValueElement, this.Type, "Char16"), __HResults.TYPE_E_TYPEMISMATCH); Contract.EndContractBlock(); return (char)_data; } @@ -137,7 +143,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime public Boolean GetBoolean() { if (this.Type != PropertyType.Boolean) - throw new InvalidCastException(Environment.GetResourceString("InvalidCast_WinRTIPropertyValueElement", this.Type, "Boolean"), __HResults.TYPE_E_TYPEMISMATCH); + throw new InvalidCastException(SR.Format(SR.InvalidCast_WinRTIPropertyValueElement, this.Type, "Boolean"), __HResults.TYPE_E_TYPEMISMATCH); Contract.EndContractBlock(); return (bool)_data; } @@ -160,7 +166,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime public DateTimeOffset GetDateTime() { if (this.Type != PropertyType.DateTime) - throw new InvalidCastException(Environment.GetResourceString("InvalidCast_WinRTIPropertyValueElement", this.Type, "DateTime"), __HResults.TYPE_E_TYPEMISMATCH); + throw new InvalidCastException(SR.Format(SR.InvalidCast_WinRTIPropertyValueElement, this.Type, "DateTime"), __HResults.TYPE_E_TYPEMISMATCH); Contract.EndContractBlock(); return (DateTimeOffset)_data; } @@ -169,7 +175,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime public TimeSpan GetTimeSpan() { if (this.Type != PropertyType.TimeSpan) - throw new InvalidCastException(Environment.GetResourceString("InvalidCast_WinRTIPropertyValueElement", this.Type, "TimeSpan"), __HResults.TYPE_E_TYPEMISMATCH); + throw new InvalidCastException(SR.Format(SR.InvalidCast_WinRTIPropertyValueElement, this.Type, "TimeSpan"), __HResults.TYPE_E_TYPEMISMATCH); Contract.EndContractBlock(); return (TimeSpan)_data; } @@ -178,7 +184,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime public Point GetPoint() { if (this.Type != PropertyType.Point) - throw new InvalidCastException(Environment.GetResourceString("InvalidCast_WinRTIPropertyValueElement", this.Type, "Point"), __HResults.TYPE_E_TYPEMISMATCH); + throw new InvalidCastException(SR.Format(SR.InvalidCast_WinRTIPropertyValueElement, this.Type, "Point"), __HResults.TYPE_E_TYPEMISMATCH); Contract.EndContractBlock(); return Unbox<Point>(IReferenceFactory.s_pointType); @@ -188,9 +194,9 @@ namespace System.Runtime.InteropServices.WindowsRuntime public Size GetSize() { if (this.Type != PropertyType.Size) - throw new InvalidCastException(Environment.GetResourceString("InvalidCast_WinRTIPropertyValueElement", this.Type, "Size"), __HResults.TYPE_E_TYPEMISMATCH); + throw new InvalidCastException(SR.Format(SR.InvalidCast_WinRTIPropertyValueElement, this.Type, "Size"), __HResults.TYPE_E_TYPEMISMATCH); Contract.EndContractBlock(); - + return Unbox<Size>(IReferenceFactory.s_sizeType); } @@ -198,9 +204,9 @@ namespace System.Runtime.InteropServices.WindowsRuntime public Rect GetRect() { if (this.Type != PropertyType.Rect) - throw new InvalidCastException(Environment.GetResourceString("InvalidCast_WinRTIPropertyValueElement", this.Type, "Rect"), __HResults.TYPE_E_TYPEMISMATCH); + throw new InvalidCastException(SR.Format(SR.InvalidCast_WinRTIPropertyValueElement, this.Type, "Rect"), __HResults.TYPE_E_TYPEMISMATCH); Contract.EndContractBlock(); - + return Unbox<Rect>(IReferenceFactory.s_rectType); } @@ -262,7 +268,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime public char[] GetChar16Array() { if (this.Type != PropertyType.Char16Array) - throw new InvalidCastException(Environment.GetResourceString("InvalidCast_WinRTIPropertyValueElement", this.Type, "Char16[]"), __HResults.TYPE_E_TYPEMISMATCH); + throw new InvalidCastException(SR.Format(SR.InvalidCast_WinRTIPropertyValueElement, this.Type, "Char16[]"), __HResults.TYPE_E_TYPEMISMATCH); Contract.EndContractBlock(); return (char[])_data; } @@ -271,7 +277,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime public Boolean[] GetBooleanArray() { if (this.Type != PropertyType.BooleanArray) - throw new InvalidCastException(Environment.GetResourceString("InvalidCast_WinRTIPropertyValueElement", this.Type, "Boolean[]"), __HResults.TYPE_E_TYPEMISMATCH); + throw new InvalidCastException(SR.Format(SR.InvalidCast_WinRTIPropertyValueElement, this.Type, "Boolean[]"), __HResults.TYPE_E_TYPEMISMATCH); Contract.EndContractBlock(); return (bool[])_data; } @@ -286,7 +292,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime public Object[] GetInspectableArray() { if (this.Type != PropertyType.InspectableArray) - throw new InvalidCastException(Environment.GetResourceString("InvalidCast_WinRTIPropertyValueElement", this.Type, "Inspectable[]"), __HResults.TYPE_E_TYPEMISMATCH); + throw new InvalidCastException(SR.Format(SR.InvalidCast_WinRTIPropertyValueElement, this.Type, "Inspectable[]"), __HResults.TYPE_E_TYPEMISMATCH); Contract.EndContractBlock(); return (Object[])_data; } @@ -301,7 +307,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime public DateTimeOffset[] GetDateTimeArray() { if (this.Type != PropertyType.DateTimeArray) - throw new InvalidCastException(Environment.GetResourceString("InvalidCast_WinRTIPropertyValueElement", this.Type, "DateTimeOffset[]"), __HResults.TYPE_E_TYPEMISMATCH); + throw new InvalidCastException(SR.Format(SR.InvalidCast_WinRTIPropertyValueElement, this.Type, "DateTimeOffset[]"), __HResults.TYPE_E_TYPEMISMATCH); Contract.EndContractBlock(); return (DateTimeOffset[])_data; } @@ -310,7 +316,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime public TimeSpan[] GetTimeSpanArray() { if (this.Type != PropertyType.TimeSpanArray) - throw new InvalidCastException(Environment.GetResourceString("InvalidCast_WinRTIPropertyValueElement", this.Type, "TimeSpan[]"), __HResults.TYPE_E_TYPEMISMATCH); + throw new InvalidCastException(SR.Format(SR.InvalidCast_WinRTIPropertyValueElement, this.Type, "TimeSpan[]"), __HResults.TYPE_E_TYPEMISMATCH); Contract.EndContractBlock(); return (TimeSpan[])_data; } @@ -319,9 +325,9 @@ namespace System.Runtime.InteropServices.WindowsRuntime public Point[] GetPointArray() { if (this.Type != PropertyType.PointArray) - throw new InvalidCastException(Environment.GetResourceString("InvalidCast_WinRTIPropertyValueElement", this.Type, "Point[]"), __HResults.TYPE_E_TYPEMISMATCH); + throw new InvalidCastException(SR.Format(SR.InvalidCast_WinRTIPropertyValueElement, this.Type, "Point[]"), __HResults.TYPE_E_TYPEMISMATCH); Contract.EndContractBlock(); - + return UnboxArray<Point>(IReferenceFactory.s_pointType); } @@ -329,7 +335,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime public Size[] GetSizeArray() { if (this.Type != PropertyType.SizeArray) - throw new InvalidCastException(Environment.GetResourceString("InvalidCast_WinRTIPropertyValueElement", this.Type, "Size[]"), __HResults.TYPE_E_TYPEMISMATCH); + throw new InvalidCastException(SR.Format(SR.InvalidCast_WinRTIPropertyValueElement, this.Type, "Size[]"), __HResults.TYPE_E_TYPEMISMATCH); Contract.EndContractBlock(); @@ -340,22 +346,25 @@ namespace System.Runtime.InteropServices.WindowsRuntime public Rect[] GetRectArray() { if (this.Type != PropertyType.RectArray) - throw new InvalidCastException(Environment.GetResourceString("InvalidCast_WinRTIPropertyValueElement", this.Type, "Rect[]"), __HResults.TYPE_E_TYPEMISMATCH); + throw new InvalidCastException(SR.Format(SR.InvalidCast_WinRTIPropertyValueElement, this.Type, "Rect[]"), __HResults.TYPE_E_TYPEMISMATCH); Contract.EndContractBlock(); return UnboxArray<Rect>(IReferenceFactory.s_rectType); } - private T[] CoerceArrayValue<T>(PropertyType unboxType) { + private T[] CoerceArrayValue<T>(PropertyType unboxType) + { // If we contain the type being looked for directly, then take the fast-path - if (Type == unboxType) { + if (Type == unboxType) + { return (T[])_data; } // Make sure we have an array to begin with Array dataArray = _data as Array; - if (dataArray == null) { - throw new InvalidCastException(Environment.GetResourceString("InvalidCast_WinRTIPropertyValueElement", this.Type, typeof(T).MakeArrayType().Name), __HResults.TYPE_E_TYPEMISMATCH); + if (dataArray == null) + { + throw new InvalidCastException(SR.Format(SR.InvalidCast_WinRTIPropertyValueElement, this.Type, typeof (T).MakeArrayType().Name), __HResults.TYPE_E_TYPEMISMATCH); } // Array types are 1024 larger than their equivilent scalar counterpart @@ -365,11 +374,15 @@ namespace System.Runtime.InteropServices.WindowsRuntime // If we do not have the correct array type, then we need to convert the array element-by-element // to a new array of the requested type T[] coercedArray = new T[dataArray.Length]; - for (int i = 0; i < dataArray.Length; ++i) { - try { + for (int i = 0; i < dataArray.Length; ++i) + { + try + { coercedArray[i] = CoerceScalarValue<T>(scalarType, dataArray.GetValue(i)); - } catch (InvalidCastException elementCastException) { - Exception e = new InvalidCastException(Environment.GetResourceString("InvalidCast_WinRTIPropertyValueArrayCoersion", this.Type, typeof(T).MakeArrayType().Name, i, elementCastException.Message), elementCastException); + } + catch (InvalidCastException elementCastException) + { + Exception e = new InvalidCastException(SR.Format(SR.InvalidCast_WinRTIPropertyValueArrayCoersion, this.Type, typeof (T).MakeArrayType().Name, i, elementCastException.Message), elementCastException); e.SetErrorCode(elementCastException._HResult); throw e; } @@ -381,92 +394,117 @@ namespace System.Runtime.InteropServices.WindowsRuntime private T CoerceScalarValue<T>(PropertyType unboxType) { // If we are just a boxed version of the requested type, then take the fast path out - if (Type == unboxType) { + if (Type == unboxType) + { return (T)_data; } return CoerceScalarValue<T>(Type, _data); } - private static T CoerceScalarValue<T>(PropertyType type, object value) { + private static T CoerceScalarValue<T>(PropertyType type, object value) + { // If the property type is neither one of the coercable numeric types nor IInspectable, we // should not attempt coersion, even if the underlying value is technically convertable - if (!IsCoercable(type, value) && type != PropertyType.Inspectable) { - throw new InvalidCastException(Environment.GetResourceString("InvalidCast_WinRTIPropertyValueElement", type, typeof(T).Name), __HResults.TYPE_E_TYPEMISMATCH); + if (!IsCoercable(type, value) && type != PropertyType.Inspectable) + { + throw new InvalidCastException(SR.Format(SR.InvalidCast_WinRTIPropertyValueElement, type, typeof (T).Name), __HResults.TYPE_E_TYPEMISMATCH); } - try { + try + { // Try to coerce: // * String <--> Guid // * Numeric scalars - if (type == PropertyType.String && typeof(T) == typeof(Guid)) { + if (type == PropertyType.String && typeof(T) == typeof(Guid)) + { return (T)(object)Guid.Parse((string)value); } - else if (type == PropertyType.Guid && typeof(T) == typeof(String)) { - return (T)(object)((Guid)value).ToString("D", System.Globalization.CultureInfo.InvariantCulture); + else if (type == PropertyType.Guid && typeof(T) == typeof(String)) + { + return (T)(object)((Guid)value).ToString("D", System.Globalization.CultureInfo.InvariantCulture); } - else { + else + { // Iterate over the numeric scalars, to see if we have a match for one of the known conversions - foreach (Tuple<Type, PropertyType> numericScalar in NumericScalarTypes) { - if (numericScalar.Item1 == typeof(T)) { + foreach (Tuple<Type, PropertyType> numericScalar in NumericScalarTypes) + { + if (numericScalar.Item1 == typeof(T)) + { return (T)Convert.ChangeType(value, typeof(T), System.Globalization.CultureInfo.InvariantCulture); } } } } - catch (FormatException) { - throw new InvalidCastException(Environment.GetResourceString("InvalidCast_WinRTIPropertyValueElement", type, typeof(T).Name), __HResults.TYPE_E_TYPEMISMATCH); + catch (FormatException) + { + throw new InvalidCastException(SR.Format(SR.InvalidCast_WinRTIPropertyValueElement, type, typeof (T).Name), __HResults.TYPE_E_TYPEMISMATCH); } - catch (InvalidCastException) { - throw new InvalidCastException(Environment.GetResourceString("InvalidCast_WinRTIPropertyValueElement", type, typeof(T).Name), __HResults.TYPE_E_TYPEMISMATCH); + catch (InvalidCastException) + { + throw new InvalidCastException(SR.Format(SR.InvalidCast_WinRTIPropertyValueElement, type, typeof (T).Name), __HResults.TYPE_E_TYPEMISMATCH); } - catch (OverflowException) { - throw new InvalidCastException(Environment.GetResourceString("InvalidCast_WinRTIPropertyValueCoersion", type, value, typeof(T).Name), __HResults.DISP_E_OVERFLOW); + catch (OverflowException) + { + throw new InvalidCastException(SR.Format(SR.InvalidCast_WinRTIPropertyValueCoersion, type, value, typeof (T).Name), __HResults.DISP_E_OVERFLOW); } // If the property type is IInspectable, and we have a nested IPropertyValue, then we need // to pass along the request to coerce the value. IPropertyValue ipv = value as IPropertyValue; - if (type == PropertyType.Inspectable && ipv != null) { - if (typeof(T) == typeof(Byte)) { + if (type == PropertyType.Inspectable && ipv != null) + { + if (typeof(T) == typeof(Byte)) + { return (T)(object)ipv.GetUInt8(); } - else if (typeof(T) == typeof(Int16)) { + else if (typeof(T) == typeof(Int16)) + { return (T)(object)ipv.GetInt16(); } - else if (typeof(T) == typeof(UInt16)) { + else if (typeof(T) == typeof(UInt16)) + { return (T)(object)ipv.GetUInt16(); } - else if (typeof(T) == typeof(Int32)) { + else if (typeof(T) == typeof(Int32)) + { return (T)(object)ipv.GetUInt32(); } - else if (typeof(T) == typeof(UInt32)) { + else if (typeof(T) == typeof(UInt32)) + { return (T)(object)ipv.GetUInt32(); } - else if (typeof(T) == typeof(Int64)) { + else if (typeof(T) == typeof(Int64)) + { return (T)(object)ipv.GetInt64(); } - else if (typeof(T) == typeof(UInt64)) { + else if (typeof(T) == typeof(UInt64)) + { return (T)(object)ipv.GetUInt64(); } - else if (typeof(T) == typeof(Single)) { + else if (typeof(T) == typeof(Single)) + { return (T)(object)ipv.GetSingle(); } - else if (typeof(T) == typeof(Double)) { + else if (typeof(T) == typeof(Double)) + { return (T)(object)ipv.GetDouble(); } - else { + else + { BCLDebug.Assert(false, "T in coersion function wasn't understood as a type that can be coerced - make sure that CoerceScalarValue and NumericScalarTypes are in sync"); } } // Otherwise, this is an invalid coersion - throw new InvalidCastException(Environment.GetResourceString("InvalidCast_WinRTIPropertyValueElement", type, typeof(T).Name), __HResults.TYPE_E_TYPEMISMATCH); + throw new InvalidCastException(SR.Format(SR.InvalidCast_WinRTIPropertyValueElement, type, typeof (T).Name), __HResults.TYPE_E_TYPEMISMATCH); } - private static bool IsCoercable(PropertyType type, object data) { + private static bool IsCoercable(PropertyType type, object data) + { // String <--> Guid is allowed - if (type == PropertyType.Guid || type == PropertyType.String) { + if (type == PropertyType.Guid || type == PropertyType.String) + { return true; } @@ -474,13 +512,17 @@ namespace System.Runtime.InteropServices.WindowsRuntime return IsNumericScalarImpl(type, data); } - private static bool IsNumericScalarImpl(PropertyType type, object data) { - if (data.GetType().IsEnum) { + private static bool IsNumericScalarImpl(PropertyType type, object data) + { + if (data.GetType().IsEnum) + { return true; } - foreach (Tuple<Type, PropertyType> numericScalar in NumericScalarTypes) { - if (numericScalar.Item2 == type) { + foreach (Tuple<Type, PropertyType> numericScalar in NumericScalarTypes) + { + if (numericScalar.Item2 == type) + { return true; } } @@ -490,42 +532,50 @@ namespace System.Runtime.InteropServices.WindowsRuntime // Unbox the data stored in the property value to a structurally equivilent type [Pure] - private unsafe T Unbox<T>(Type expectedBoxedType) where T : struct { + private unsafe T Unbox<T>(Type expectedBoxedType) where T : struct + { Contract.Requires(expectedBoxedType != null); Contract.Requires(Marshal.SizeOf(expectedBoxedType) == Marshal.SizeOf(typeof(T))); - if (_data.GetType() != expectedBoxedType) { - throw new InvalidCastException(Environment.GetResourceString("InvalidCast_WinRTIPropertyValueElement", _data.GetType(), expectedBoxedType.Name), __HResults.TYPE_E_TYPEMISMATCH); + if (_data.GetType() != expectedBoxedType) + { + throw new InvalidCastException(SR.Format(SR.InvalidCast_WinRTIPropertyValueElement, _data.GetType(), expectedBoxedType.Name), __HResults.TYPE_E_TYPEMISMATCH); } T unboxed = new T(); - fixed (byte *pData = &JitHelpers.GetPinningHelper(_data).m_data) { + fixed (byte* pData = &JitHelpers.GetPinningHelper(_data).m_data) + { byte* pUnboxed = (byte*)JitHelpers.UnsafeCastToStackPointer(ref unboxed); Buffer.Memcpy(pUnboxed, pData, Marshal.SizeOf(unboxed)); } - + return unboxed; } // Convert the array stored in the property value to a structurally equivilent array type [Pure] - private unsafe T[] UnboxArray<T>(Type expectedArrayElementType) where T : struct { + private unsafe T[] UnboxArray<T>(Type expectedArrayElementType) where T : struct + { Contract.Requires(expectedArrayElementType != null); Contract.Requires(Marshal.SizeOf(expectedArrayElementType) == Marshal.SizeOf(typeof(T))); Array dataArray = _data as Array; - if (dataArray == null || _data.GetType().GetElementType() != expectedArrayElementType) { - throw new InvalidCastException(Environment.GetResourceString("InvalidCast_WinRTIPropertyValueElement", _data.GetType(), expectedArrayElementType.MakeArrayType().Name), __HResults.TYPE_E_TYPEMISMATCH); + if (dataArray == null || _data.GetType().GetElementType() != expectedArrayElementType) + { + throw new InvalidCastException(SR.Format(SR.InvalidCast_WinRTIPropertyValueElement, _data.GetType(), expectedArrayElementType.MakeArrayType().Name), __HResults.TYPE_E_TYPEMISMATCH); } T[] converted = new T[dataArray.Length]; - if (converted.Length > 0) { - fixed (byte * dataPin = &JitHelpers.GetPinningHelper(dataArray).m_data) { - fixed (byte * convertedPin = &JitHelpers.GetPinningHelper(converted).m_data) { - byte *pData = (byte *)Marshal.UnsafeAddrOfPinnedArrayElement(dataArray, 0); - byte *pConverted = (byte *)Marshal.UnsafeAddrOfPinnedArrayElement(converted, 0); + if (converted.Length > 0) + { + fixed (byte* dataPin = &JitHelpers.GetPinningHelper(dataArray).m_data) + { + fixed (byte* convertedPin = &JitHelpers.GetPinningHelper(converted).m_data) + { + byte* pData = (byte*)Marshal.UnsafeAddrOfPinnedArrayElement(dataArray, 0); + byte* pConverted = (byte*)Marshal.UnsafeAddrOfPinnedArrayElement(converted, 0); Buffer.Memcpy(pConverted, pData, checked(Marshal.SizeOf(typeof(T)) * converted.Length)); } diff --git a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/CLRIReferenceImpl.cs b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/CLRIReferenceImpl.cs index 9705b61148..3afd87ab12 100644 --- a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/CLRIReferenceImpl.cs +++ b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/CLRIReferenceImpl.cs @@ -13,7 +13,7 @@ using System.Security; namespace System.Runtime.InteropServices.WindowsRuntime { - internal sealed class CLRIReferenceImpl<T> : CLRIPropertyValueImpl, IReference<T>, IGetProxyTarget + internal sealed class CLRIReferenceImpl<T> : CLRIPropertyValueImpl, IReference<T>, IGetProxyTarget { private T _value; @@ -24,7 +24,8 @@ namespace System.Runtime.InteropServices.WindowsRuntime _value = obj; } - public T Value { + public T Value + { get { return _value; } } @@ -55,16 +56,16 @@ namespace System.Runtime.InteropServices.WindowsRuntime internal static Object UnboxHelper(Object wrapper) { Contract.Requires(wrapper != null); - IReference<T> reference = (IReference<T>) wrapper; - Debug.Assert(reference != null, "CLRIReferenceImpl::UnboxHelper - QI'ed for IReference<"+typeof(T)+">, but that failed."); + IReference<T> reference = (IReference<T>)wrapper; + Debug.Assert(reference != null, "CLRIReferenceImpl::UnboxHelper - QI'ed for IReference<" + typeof(T) + ">, but that failed."); return reference.Value; } } // T can be any WinRT-compatible type internal sealed class CLRIReferenceArrayImpl<T> : CLRIPropertyValueImpl, - IGetProxyTarget, - IReferenceArray<T>, + IGetProxyTarget, + IReferenceArray<T>, IList // Jupiter data binding needs IList/IEnumerable { private T[] _value; @@ -77,10 +78,11 @@ namespace System.Runtime.InteropServices.WindowsRuntime _value = obj; - _list = (IList) _value; + _list = (IList)_value; } - public T[] Value { + public T[] Value + { get { return _value; } } @@ -109,7 +111,8 @@ namespace System.Runtime.InteropServices.WindowsRuntime // IList & ICollection methods. // This enables two-way data binding and index access in Jupiter // - Object IList.this[int index] { + Object IList.this[int index] + { get { return _list[index]; @@ -120,30 +123,30 @@ namespace System.Runtime.InteropServices.WindowsRuntime _list[index] = value; } } - + int IList.Add(Object value) { return _list.Add(value); } - + bool IList.Contains(Object value) { return _list.Contains(value); } - + void IList.Clear() { _list.Clear(); } - bool IList.IsReadOnly - { + bool IList.IsReadOnly + { get { return _list.IsReadOnly; } } - + bool IList.IsFixedSize { get @@ -156,17 +159,17 @@ namespace System.Runtime.InteropServices.WindowsRuntime { return _list.IndexOf(value); } - + void IList.Insert(int index, Object value) { _list.Insert(index, value); } - + void IList.Remove(Object value) { _list.Remove(value); } - + void IList.RemoveAt(int index) { _list.RemoveAt(index); @@ -176,9 +179,9 @@ namespace System.Runtime.InteropServices.WindowsRuntime { _list.CopyTo(array, index); } - + int ICollection.Count - { + { get { return _list.Count; @@ -186,15 +189,15 @@ namespace System.Runtime.InteropServices.WindowsRuntime } Object ICollection.SyncRoot - { + { get { return _list.SyncRoot; } } - + bool ICollection.IsSynchronized - { + { get { return _list.IsSynchronized; @@ -205,7 +208,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime { return (object)_value; } - + // We have T in an IReferenceArray<T>. Need to QI for IReferenceArray<T> with the appropriate GUID, call // the get_Value property, allocate an appropriately-sized managed object, marshal the native object // to the managed object, and free the native method. @@ -238,7 +241,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime Type type = obj.GetType(); if (type.IsArray) - return CreateIReferenceArray((Array) obj); + return CreateIReferenceArray((Array)obj); if (type == typeof(int)) return new CLRIReferenceImpl<int>(PropertyType.Int32, (int)obj); @@ -313,7 +316,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime Contract.Ensures(Contract.Result<Object>() != null); Type type = obj.GetType().GetElementType(); - + Debug.Assert(obj.Rank == 1 && obj.GetLowerBound(0) == 0 && !type.IsArray); if (type == typeof(int)) diff --git a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/ConstantSplittableMap.cs b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/ConstantSplittableMap.cs index 3a896ecbe3..4549a407e0 100644 --- a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/ConstantSplittableMap.cs +++ b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/ConstantSplittableMap.cs @@ -48,9 +48,9 @@ namespace System.Runtime.InteropServices.WindowsRuntime throw new ArgumentNullException(nameof(data)); Contract.EndContractBlock(); - this.firstItemIndex = 0; - this.lastItemIndex = data.Count - 1; - this.items = CreateKeyValueArray(data.Count, data.GetEnumerator()); + firstItemIndex = 0; + lastItemIndex = data.Count - 1; + items = CreateKeyValueArray(data.Count, data.GetEnumerator()); } @@ -61,7 +61,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime this.lastItemIndex = lastItemIndex; } - + private KeyValuePair<TKey, TValue>[] CreateKeyValueArray(Int32 count, IEnumerator<KeyValuePair<TKey, TValue>> data) { KeyValuePair<TKey, TValue>[] kvArray = new KeyValuePair<TKey, TValue>[count]; @@ -76,16 +76,20 @@ namespace System.Runtime.InteropServices.WindowsRuntime } - public int Count { - get { + public int Count + { + get + { return lastItemIndex - firstItemIndex + 1; } } // [CLSCompliant(false)] - public UInt32 Size { - get { + public UInt32 Size + { + get + { return (UInt32)(lastItemIndex - firstItemIndex + 1); } } @@ -98,7 +102,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime if (!found) { - Exception e = new KeyNotFoundException(Environment.GetResourceString("Arg_KeyNotFound")); + Exception e = new KeyNotFoundException(SR.Arg_KeyNotFound); e.SetErrorCode(__HResults.E_BOUNDS); throw e; } @@ -118,17 +122,17 @@ namespace System.Runtime.InteropServices.WindowsRuntime { return ((IEnumerable<IKeyValuePair<TKey, TValue>>)this).GetEnumerator(); } - + public IIterator<IKeyValuePair<TKey, TValue>> First() { return new EnumeratorToIteratorAdapter<IKeyValuePair<TKey, TValue>>(GetEnumerator()); } - + public IEnumerator<IKeyValuePair<TKey, TValue>> GetEnumerator() { return new IKeyValuePairEnumerator(items, firstItemIndex, lastItemIndex); } - + public void Split(out IMapView<TKey, TValue> firstPartition, out IMapView<TKey, TValue> secondPartition) { if (Count < 2) @@ -144,7 +148,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime secondPartition = new ConstantSplittableMap<TKey, TValue>(items, pivot + 1, lastItemIndex); } -#region IReadOnlyDictionary members + #region IReadOnlyDictionary members public bool TryGetValue(TKey key, out TValue value) { @@ -197,16 +201,20 @@ namespace System.Runtime.InteropServices.WindowsRuntime return false; } - public IKeyValuePair<TKey, TValue> Current { - get { - if (_current < _start) throw new InvalidOperationException(Environment.GetResourceString(ResId.InvalidOperation_EnumNotStarted)); - if (_current > _end) throw new InvalidOperationException(Environment.GetResourceString(ResId.InvalidOperation_EnumEnded)); + public IKeyValuePair<TKey, TValue> Current + { + get + { + if (_current < _start) throw new InvalidOperationException(SR.GetResourceString(ResId.InvalidOperation_EnumNotStarted)); + if (_current > _end) throw new InvalidOperationException(SR.GetResourceString(ResId.InvalidOperation_EnumEnded)); return new CLRIKeyValuePairImpl<TKey, TValue>(ref _array[_current]); } } - Object IEnumerator.Current { - get { + Object IEnumerator.Current + { + get + { return Current; } } @@ -222,7 +230,5 @@ namespace System.Runtime.InteropServices.WindowsRuntime } #endregion IKeyValuePair Enumerator - } // internal ConstantSplittableMap<TKey, TValue> - } // namespace System.Runtime.InteropServices.WindowsRuntime diff --git a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/CustomPropertyImpl.cs b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/CustomPropertyImpl.cs index 9f822d5ced..63565a39b8 100644 --- a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/CustomPropertyImpl.cs +++ b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/CustomPropertyImpl.cs @@ -21,8 +21,8 @@ namespace System.Runtime.InteropServices.WindowsRuntime // ICustomProperty implementation - basically a wrapper of PropertyInfo // internal sealed class CustomPropertyImpl : ICustomProperty - { - private PropertyInfo m_property; + { + private PropertyInfo m_property; // // Constructor @@ -46,11 +46,11 @@ namespace System.Runtime.InteropServices.WindowsRuntime return m_property.Name; } } - + public bool CanRead { - get - { + get + { // Return false if the getter is not public return m_property.GetGetMethod() != null; } @@ -58,7 +58,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime public bool CanWrite { - get + get { // Return false if the setter is not public return m_property.GetSetMethod() != null; @@ -105,21 +105,21 @@ namespace System.Runtime.InteropServices.WindowsRuntime // We get non-public accessors just so that we can throw the correct exception. MethodInfo accessor = getValue ? m_property.GetGetMethod(true) : m_property.GetSetMethod(true); - + if (accessor == null) - throw new ArgumentException(System.Environment.GetResourceString(getValue ? "Arg_GetMethNotFnd" : "Arg_SetMethNotFnd")); + throw new ArgumentException(getValue ? SR.Arg_GetMethNotFnd : SR.Arg_SetMethNotFnd); if (!accessor.IsPublic) throw new MethodAccessException( String.Format( CultureInfo.CurrentCulture, - Environment.GetResourceString("Arg_MethodAccessException_WithMethodName"), + SR.Arg_MethodAccessException_WithMethodName, accessor.ToString(), accessor.DeclaringType.FullName)); RuntimeMethodInfo rtMethod = accessor as RuntimeMethodInfo; if (rtMethod == null) - throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeMethodInfo")); + throw new ArgumentException(SR.Argument_MustBeRuntimeMethodInfo); // 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. diff --git a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/DictionaryKeyCollection.cs b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/DictionaryKeyCollection.cs index c33e002e0e..2a34aba717 100644 --- a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/DictionaryKeyCollection.cs +++ b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/DictionaryKeyCollection.cs @@ -30,9 +30,9 @@ namespace System.Runtime.InteropServices.WindowsRuntime if (index < 0) throw new ArgumentOutOfRangeException(nameof(index)); if (array.Length <= index && this.Count > 0) - throw new ArgumentException(Environment.GetResourceString("Arg_IndexOutOfRangeException")); + throw new ArgumentException(SR.Arg_IndexOutOfRangeException); if (array.Length - index < dictionary.Count) - throw new ArgumentException(Environment.GetResourceString("Argument_InsufficientSpaceToCopyCollection")); + throw new ArgumentException(SR.Argument_InsufficientSpaceToCopyCollection); int i = index; foreach (KeyValuePair<TKey, TValue> mapping in dictionary) @@ -41,22 +41,24 @@ namespace System.Runtime.InteropServices.WindowsRuntime } } - public int Count { + public int Count + { get { return dictionary.Count; } } - bool ICollection<TKey>.IsReadOnly { + bool ICollection<TKey>.IsReadOnly + { get { return true; } } void ICollection<TKey>.Add(TKey item) { - throw new NotSupportedException(Environment.GetResourceString("NotSupported_KeyCollectionSet")); + throw new NotSupportedException(SR.NotSupported_KeyCollectionSet); } void ICollection<TKey>.Clear() { - throw new NotSupportedException(Environment.GetResourceString("NotSupported_KeyCollectionSet")); + throw new NotSupportedException(SR.NotSupported_KeyCollectionSet); } public bool Contains(TKey item) @@ -66,7 +68,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime bool ICollection<TKey>.Remove(TKey item) { - throw new NotSupportedException(Environment.GetResourceString("NotSupported_KeyCollectionSet")); + throw new NotSupportedException(SR.NotSupported_KeyCollectionSet); } IEnumerator IEnumerable.GetEnumerator() @@ -93,7 +95,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime throw new ArgumentNullException(nameof(dictionary)); this.dictionary = dictionary; - this.enumeration = dictionary.GetEnumerator(); + enumeration = dictionary.GetEnumerator(); } void IDisposable.Dispose() @@ -106,11 +108,13 @@ namespace System.Runtime.InteropServices.WindowsRuntime return enumeration.MoveNext(); } - Object IEnumerator.Current { + Object IEnumerator.Current + { get { return ((IEnumerator<TKey>)this).Current; } } - public TKey Current { + public TKey Current + { get { return enumeration.Current.Key; } } diff --git a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/DictionaryToMapAdapter.cs b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/DictionaryToMapAdapter.cs index 24e5777768..bb54d49b60 100644 --- a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/DictionaryToMapAdapter.cs +++ b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/DictionaryToMapAdapter.cs @@ -41,7 +41,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime if (!keyFound) { - Exception e = new KeyNotFoundException(Environment.GetResourceString("Arg_KeyNotFound")); + Exception e = new KeyNotFoundException(SR.Arg_KeyNotFound); e.SetErrorCode(__HResults.E_BOUNDS); throw e; } @@ -55,7 +55,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime IDictionary<K, V> _this = JitHelpers.UnsafeCast<IDictionary<K, V>>(this); return (uint)_this.Count; } - + // bool HasKey(K key) internal bool HasKey<K, V>(K key) { @@ -96,7 +96,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime if (!removed) { - Exception e = new KeyNotFoundException(Environment.GetResourceString("Arg_KeyNotFound")); + Exception e = new KeyNotFoundException(SR.Arg_KeyNotFound); e.SetErrorCode(__HResults.E_BOUNDS); throw e; } diff --git a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/DictionaryValueCollection.cs b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/DictionaryValueCollection.cs index fcc7755d67..083b0ffcb1 100644 --- a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/DictionaryValueCollection.cs +++ b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/DictionaryValueCollection.cs @@ -11,7 +11,8 @@ using System.Runtime.InteropServices; using System.Runtime.InteropServices.WindowsRuntime; -namespace System.Runtime.InteropServices.WindowsRuntime { +namespace System.Runtime.InteropServices.WindowsRuntime +{ [Serializable] [DebuggerDisplay("Count = {Count}")] internal sealed class DictionaryValueCollection<TKey, TValue> : ICollection<TValue> @@ -33,9 +34,9 @@ namespace System.Runtime.InteropServices.WindowsRuntime { if (index < 0) throw new ArgumentOutOfRangeException(nameof(index)); if (array.Length <= index && this.Count > 0) - throw new ArgumentException(Environment.GetResourceString("Arg_IndexOutOfRangeException")); + throw new ArgumentException(SR.Arg_IndexOutOfRangeException); if (array.Length - index < dictionary.Count) - throw new ArgumentException(Environment.GetResourceString("Argument_InsufficientSpaceToCopyCollection")); + throw new ArgumentException(SR.Argument_InsufficientSpaceToCopyCollection); int i = index; foreach (KeyValuePair<TKey, TValue> mapping in dictionary) @@ -44,22 +45,24 @@ namespace System.Runtime.InteropServices.WindowsRuntime { } } - public int Count { + public int Count + { get { return dictionary.Count; } } - bool ICollection<TValue>.IsReadOnly { + bool ICollection<TValue>.IsReadOnly + { get { return true; } } void ICollection<TValue>.Add(TValue item) { - throw new NotSupportedException(Environment.GetResourceString("NotSupported_ValueCollectionSet")); + throw new NotSupportedException(SR.NotSupported_ValueCollectionSet); } void ICollection<TValue>.Clear() { - throw new NotSupportedException(Environment.GetResourceString("NotSupported_ValueCollectionSet")); + throw new NotSupportedException(SR.NotSupported_ValueCollectionSet); } public bool Contains(TValue item) @@ -73,7 +76,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime { bool ICollection<TValue>.Remove(TValue item) { - throw new NotSupportedException(Environment.GetResourceString("NotSupported_ValueCollectionSet")); + throw new NotSupportedException(SR.NotSupported_ValueCollectionSet); } IEnumerator IEnumerable.GetEnumerator() @@ -100,7 +103,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime { throw new ArgumentNullException(nameof(dictionary)); this.dictionary = dictionary; - this.enumeration = dictionary.GetEnumerator(); + enumeration = dictionary.GetEnumerator(); } void IDisposable.Dispose() @@ -113,11 +116,13 @@ namespace System.Runtime.InteropServices.WindowsRuntime { return enumeration.MoveNext(); } - Object IEnumerator.Current { + Object IEnumerator.Current + { get { return ((IEnumerator<TValue>)this).Current; } } - public TValue Current { + public TValue Current + { get { return enumeration.Current.Value; } } diff --git a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/EnumeratorToIteratorAdapter.cs b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/EnumeratorToIteratorAdapter.cs index 3f9d516162..75b8480eeb 100644 --- a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/EnumeratorToIteratorAdapter.cs +++ b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/EnumeratorToIteratorAdapter.cs @@ -51,20 +51,20 @@ namespace System.Runtime.InteropServices.WindowsRuntime public NonGenericToGenericEnumerator(IEnumerator enumerator) { this.enumerator = enumerator; } - public object Current { get { return enumerator.Current; } } + public object Current { get { return enumerator.Current; } } public bool MoveNext() { return enumerator.MoveNext(); } - public void Reset() { enumerator.Reset(); } - public void Dispose() { } + public void Reset() { enumerator.Reset(); } + public void Dispose() { } } // This method is invoked when First is called on a managed implementation of IBindableIterable. internal IBindableIterator First_Stub() { IEnumerable _this = JitHelpers.UnsafeCast<IEnumerable>(this); - return new EnumeratorToIteratorAdapter<object>(new NonGenericToGenericEnumerator(_this.GetEnumerator()) ); + return new EnumeratorToIteratorAdapter<object>(new NonGenericToGenericEnumerator(_this.GetEnumerator())); } } - + // Adapter class which holds a managed IEnumerator<T>, exposing it as a Windows Runtime IIterator<T> internal sealed class EnumeratorToIteratorAdapter<T> : IIterator<T>, IBindableIterator { diff --git a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/EventRegistrationTokenTable.cs b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/EventRegistrationTokenTable.cs index 03b17d9261..974da48a42 100644 --- a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/EventRegistrationTokenTable.cs +++ b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/EventRegistrationTokenTable.cs @@ -28,7 +28,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime // static check at construction time if (!typeof(Delegate).IsAssignableFrom(typeof(T))) { - throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_EventTokenTableRequiresDelegate", typeof(T))); + throw new InvalidOperationException(SR.Format(SR.InvalidOperation_EventTokenTableRequiresDelegate, typeof (T))); } } diff --git a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/IClosable.cs b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/IClosable.cs index 4c6169a4e8..d62649e7a7 100644 --- a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/IClosable.cs +++ b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/IClosable.cs @@ -13,7 +13,6 @@ using System.Runtime.CompilerServices; namespace System.Runtime.InteropServices.WindowsRuntime { - // Local definition of Windows.Foundation.IClosable [ComImport] [Guid("30d5a829-7fa4-4026-83bb-d75bae4ea99e")] diff --git a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/ICustomProperty.cs b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/ICustomProperty.cs index 88472a46b8..3ff4ffd098 100644 --- a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/ICustomProperty.cs +++ b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/ICustomProperty.cs @@ -19,34 +19,34 @@ namespace System.Runtime.InteropServices.WindowsRuntime [Pure] get; } - - string Name - { + + string Name + { [Pure] - get; + get; } [Pure] object GetValue(object target); void SetValue(object target, object value); - + [Pure] object GetValue(object target, object indexValue); - + void SetValue(object target, object value, object indexValue); - - bool CanWrite - { + + bool CanWrite + { [Pure] - get; + get; } - bool CanRead - { + bool CanRead + { [Pure] - get; - } + get; + } } } - + diff --git a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/ICustomPropertyProvider.cs b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/ICustomPropertyProvider.cs index 3bbde35a3c..f461327712 100644 --- a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/ICustomPropertyProvider.cs +++ b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/ICustomPropertyProvider.cs @@ -16,7 +16,6 @@ using System.Security; namespace System.Runtime.InteropServices.WindowsRuntime { - // // ICustomProperty Implementation helpers // @@ -32,7 +31,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime Contract.Requires(propertyName != null); IGetProxyTarget proxy = target as IGetProxyTarget; - if (proxy != null) + if (proxy != null) target = proxy.GetTarget(); // Only return public instance/static properties @@ -50,7 +49,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime // Creates a ICustomProperty implementation for Jupiter // Called from ICustomPropertyProvider_GetIndexedProperty from within runtime // - static internal unsafe ICustomProperty CreateIndexedProperty(object target, string propertyName, TypeNameNative *pIndexedParamType) + static internal unsafe ICustomProperty CreateIndexedProperty(object target, string propertyName, TypeNameNative* pIndexedParamType) { Contract.Requires(target != null); Contract.Requires(propertyName != null); @@ -58,7 +57,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime Type indexedParamType = null; SystemTypeMarshaler.ConvertToManaged(pIndexedParamType, ref indexedParamType); - return CreateIndexedProperty(target, propertyName, indexedParamType); + return CreateIndexedProperty(target, propertyName, indexedParamType); } static internal ICustomProperty CreateIndexedProperty(object target, string propertyName, Type indexedParamType) @@ -67,7 +66,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime Contract.Requires(propertyName != null); IGetProxyTarget proxy = target as IGetProxyTarget; - if (proxy != null) + if (proxy != null) target = proxy.GetTarget(); // Only return public instance/static properties @@ -86,25 +85,25 @@ namespace System.Runtime.InteropServices.WindowsRuntime return new CustomPropertyImpl(propertyInfo); } - static internal unsafe void GetType(object target, TypeNameNative *pIndexedParamType) - { + static internal unsafe void GetType(object target, TypeNameNative* pIndexedParamType) + { IGetProxyTarget proxy = target as IGetProxyTarget; - if (proxy != null) + if (proxy != null) target = proxy.GetTarget(); SystemTypeMarshaler.ConvertToNative(target.GetType(), pIndexedParamType); - } + } } [Flags] - enum InterfaceForwardingSupport + internal enum InterfaceForwardingSupport { - None = 0, - IBindableVector = 0x1, // IBindableVector -> IBindableVector - IVector = 0x2, // IBindableVector -> IVector<T> - IBindableVectorView = 0x4, // IBindableVectorView -> IBindableVectorView - IVectorView = 0x8, // IBindableVectorView -> IVectorView<T> - IBindableIterableOrIIterable= 0x10 // IBindableIterable -> IBindableIterable/IIterable<T> + None = 0, + IBindableVector = 0x1, // IBindableVector -> IBindableVector + IVector = 0x2, // IBindableVector -> IVector<T> + IBindableVectorView = 0x4, // IBindableVectorView -> IBindableVectorView + IVectorView = 0x8, // IBindableVectorView -> IVectorView<T> + IBindableIterableOrIIterable = 0x10 // IBindableIterable -> IBindableIterable/IIterable<T> } // @@ -113,9 +112,9 @@ namespace System.Runtime.InteropServices.WindowsRuntime // internal interface IGetProxyTarget { - object GetTarget(); + object GetTarget(); } - + // // Proxy that supports data binding on another object // @@ -164,7 +163,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime // doesn't recognize, and therefore IEnumerable cast won't be able to take advantage of this QI if (target as IList<T1> != null) supportFlags |= InterfaceForwardingSupport.IVector; - + if (target as IBindableVectorView != null) supportFlags |= InterfaceForwardingSupport.IBindableVectorView; @@ -181,8 +180,8 @@ namespace System.Runtime.InteropServices.WindowsRuntime // succeeded, IEnumerable needs to know that if (target as IEnumerable != null) supportFlags |= InterfaceForwardingSupport.IBindableIterableOrIIterable; - - return new ICustomPropertyProviderProxy<T1, T2>(target, supportFlags); + + return new ICustomPropertyProviderProxy<T1, T2>(target, supportFlags); } @@ -213,26 +212,26 @@ namespace System.Runtime.InteropServices.WindowsRuntime { // Reject the QI if target doesn't implement IEnumerable if ((_flags & (InterfaceForwardingSupport.IBindableIterableOrIIterable)) == 0) - return CustomQueryInterfaceResult.Failed; + return CustomQueryInterfaceResult.Failed; } if (iid == typeof(IBindableVector).GUID) { // Reject the QI if target doesn't implement IBindableVector/IVector if ((_flags & (InterfaceForwardingSupport.IBindableVector | InterfaceForwardingSupport.IVector)) == 0) - return CustomQueryInterfaceResult.Failed; + return CustomQueryInterfaceResult.Failed; } if (iid == typeof(IBindableVectorView).GUID) { // Reject the QI if target doesn't implement IBindableVectorView/IVectorView if ((_flags & (InterfaceForwardingSupport.IBindableVectorView | InterfaceForwardingSupport.IVectorView)) == 0) - return CustomQueryInterfaceResult.Failed; + return CustomQueryInterfaceResult.Failed; } - + return CustomQueryInterfaceResult.NotHandled; } - + // // IEnumerable methods // @@ -257,14 +256,14 @@ namespace System.Runtime.InteropServices.WindowsRuntime { // IBindableVector -> IVector<T> return GetVectorOfT().GetAt(index); - } + } } - + [Pure] - uint IBindableVector.Size - { + uint IBindableVector.Size + { get - { + { IBindableVector bindableVector = GetIBindableVectorNoThrow(); if (bindableVector != null) { @@ -275,10 +274,10 @@ namespace System.Runtime.InteropServices.WindowsRuntime { // IBindableVector -> IVector<T> return GetVectorOfT().Size; - } + } } } - + [Pure] IBindableVectorView IBindableVector.GetView() { @@ -292,7 +291,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime { // IBindableVector -> IVector<T> return new IVectorViewToIBindableVectorViewAdapter<T1>(GetVectorOfT().GetView()); - } + } } private sealed class IVectorViewToIBindableVectorViewAdapter<T> : IBindableVectorView @@ -300,8 +299,8 @@ namespace System.Runtime.InteropServices.WindowsRuntime private IVectorView<T> _vectorView; public IVectorViewToIBindableVectorViewAdapter(IVectorView<T> vectorView) - { - this._vectorView = vectorView; + { + _vectorView = vectorView; } [Pure] @@ -309,16 +308,16 @@ namespace System.Runtime.InteropServices.WindowsRuntime { return _vectorView.GetAt(index); } - + [Pure] uint IBindableVectorView.Size - { + { get { return _vectorView.Size; } } - + [Pure] bool IBindableVectorView.IndexOf(object value, out uint index) { @@ -329,9 +328,8 @@ namespace System.Runtime.InteropServices.WindowsRuntime { return new IteratorOfTToIteratorAdapter<T>(_vectorView.First()); } + } - } - [Pure] bool IBindableVector.IndexOf(object value, out uint index) { @@ -345,9 +343,9 @@ namespace System.Runtime.InteropServices.WindowsRuntime { // IBindableVector -> IVector<T> return GetVectorOfT().IndexOf(ConvertTo<T1>(value), out index); - } + } } - + void IBindableVector.SetAt(uint index, object value) { IBindableVector bindableVector = GetIBindableVectorNoThrow(); @@ -360,9 +358,9 @@ namespace System.Runtime.InteropServices.WindowsRuntime { // IBindableVector -> IVector<T> GetVectorOfT().SetAt(index, ConvertTo<T1>(value)); - } + } } - + void IBindableVector.InsertAt(uint index, object value) { IBindableVector bindableVector = GetIBindableVectorNoThrow(); @@ -375,9 +373,9 @@ namespace System.Runtime.InteropServices.WindowsRuntime { // IBindableVector -> IVector<T> GetVectorOfT().InsertAt(index, ConvertTo<T1>(value)); - } + } } - + void IBindableVector.RemoveAt(uint index) { IBindableVector bindableVector = GetIBindableVectorNoThrow(); @@ -390,9 +388,9 @@ namespace System.Runtime.InteropServices.WindowsRuntime { // IBindableVector -> IVector<T> GetVectorOfT().RemoveAt(index); - } + } } - + void IBindableVector.Append(object value) { IBindableVector bindableVector = GetIBindableVectorNoThrow(); @@ -405,9 +403,9 @@ namespace System.Runtime.InteropServices.WindowsRuntime { // IBindableVector -> IVector<T> GetVectorOfT().Append(ConvertTo<T1>(value)); - } - } - + } + } + void IBindableVector.RemoveAtEnd() { IBindableVector bindableVector = GetIBindableVectorNoThrow(); @@ -420,9 +418,9 @@ namespace System.Runtime.InteropServices.WindowsRuntime { // IBindableVector -> IVector<T> GetVectorOfT().RemoveAtEnd(); - } + } } - + void IBindableVector.Clear() { IBindableVector bindableVector = GetIBindableVectorNoThrow(); @@ -435,7 +433,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime { // IBindableVector -> IVector<T> GetVectorOfT().Clear(); - } + } } private IBindableVector GetIBindableVectorNoThrow() @@ -454,7 +452,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime throw new InvalidOperationException(); // We should not go down this path, unless Jupiter pass this out to managed code // and managed code use reflection to do the cast } - + // // IBindableVectorView implementation (forwarding to IBindableVectorView or IVectorView<T>) // @@ -467,10 +465,10 @@ namespace System.Runtime.InteropServices.WindowsRuntime else return GetVectorViewOfT().GetAt(index); } - + [Pure] uint IBindableVectorView.Size - { + { get { IBindableVectorView bindableVectorView = GetIBindableVectorViewNoThrow(); @@ -480,7 +478,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime return GetVectorViewOfT().Size; } } - + [Pure] bool IBindableVectorView.IndexOf(object value, out uint index) { @@ -505,12 +503,12 @@ namespace System.Runtime.InteropServices.WindowsRuntime private IIterator<T> _iterator; public IteratorOfTToIteratorAdapter(IIterator<T> iterator) - { this._iterator = iterator; } + { _iterator = iterator; } public bool HasCurrent { get { return _iterator.HasCurrent; } } - public object Current { get { return (object)_iterator.Current; } } + public object Current { get { return (object)_iterator.Current; } } public bool MoveNext() { return _iterator.MoveNext(); } - } + } private IBindableVectorView GetIBindableVectorViewNoThrow() { @@ -537,9 +535,9 @@ namespace System.Runtime.InteropServices.WindowsRuntime // Throw ArgumentNullException if value is null (otherwise we'll throw NullReferenceException // when casting value to T) ThrowHelper.IfNullAndNullsAreIllegalThenThrow<T>(value, ExceptionArgument.value); - + // No coersion support needed. If we need coersion later, this is the place - return (T) value; + return (T)value; } } } diff --git a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/IIterable.cs b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/IIterable.cs index dbf4771cf6..30ce895423 100644 --- a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/IIterable.cs +++ b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/IIterable.cs @@ -10,6 +10,7 @@ using System.Diagnostics.Contracts; // Windows.Foundation.Collections.IIterable`1 cannot be referenced from managed code because it's hidden // by the metadata adapter. We redeclare the interface manually to be able to talk to native WinRT objects. + namespace System.Runtime.InteropServices.WindowsRuntime { [ComImport] diff --git a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/IMap.cs b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/IMap.cs index 8160e6afc9..1f954a66b0 100644 --- a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/IMap.cs +++ b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/IMap.cs @@ -11,6 +11,7 @@ using System.Diagnostics.Contracts; // Windows.Foundation.Collections.IMap`2, IMapView`2, and IKeyValuePair`2 cannot be referenced from // managed code because they're hidden by the metadata adapter. We redeclare the interfaces manually // to be able to talk to native WinRT objects. + namespace System.Runtime.InteropServices.WindowsRuntime { [ComImport] diff --git a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/IMapViewToIReadOnlyDictionaryAdapter.cs b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/IMapViewToIReadOnlyDictionaryAdapter.cs index a7424da3fb..e06364dcae 100644 --- a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/IMapViewToIReadOnlyDictionaryAdapter.cs +++ b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/IMapViewToIReadOnlyDictionaryAdapter.cs @@ -114,7 +114,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime catch (Exception ex) { if (__HResults.E_BOUNDS == ex._HResult) - throw new KeyNotFoundException(Environment.GetResourceString("Arg_KeyNotFound")); + throw new KeyNotFoundException(SR.Arg_KeyNotFound); throw; } } @@ -145,9 +145,9 @@ namespace System.Runtime.InteropServices.WindowsRuntime if (index < 0) throw new ArgumentOutOfRangeException(nameof(index)); if (array.Length <= index && this.Count > 0) - throw new ArgumentException(Environment.GetResourceString("Arg_IndexOutOfRangeException")); + throw new ArgumentException(SR.Arg_IndexOutOfRangeException); if (array.Length - index < dictionary.Count) - throw new ArgumentException(Environment.GetResourceString("Argument_InsufficientSpaceToCopyCollection")); + throw new ArgumentException(SR.Argument_InsufficientSpaceToCopyCollection); int i = index; foreach (KeyValuePair<TKey, TValue> mapping in dictionary) @@ -190,7 +190,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime throw new ArgumentNullException(nameof(dictionary)); this.dictionary = dictionary; - this.enumeration = dictionary.GetEnumerator(); + enumeration = dictionary.GetEnumerator(); } void IDisposable.Dispose() @@ -203,11 +203,13 @@ namespace System.Runtime.InteropServices.WindowsRuntime return enumeration.MoveNext(); } - Object IEnumerator.Current { + Object IEnumerator.Current + { get { return ((IEnumerator<TKey>)this).Current; } } - public TKey Current { + public TKey Current + { get { return enumeration.Current.Key; } } @@ -240,9 +242,9 @@ namespace System.Runtime.InteropServices.WindowsRuntime if (index < 0) throw new ArgumentOutOfRangeException(nameof(index)); if (array.Length <= index && this.Count > 0) - throw new ArgumentException(Environment.GetResourceString("Arg_IndexOutOfRangeException")); + throw new ArgumentException(SR.Arg_IndexOutOfRangeException); if (array.Length - index < dictionary.Count) - throw new ArgumentException(Environment.GetResourceString("Argument_InsufficientSpaceToCopyCollection")); + throw new ArgumentException(SR.Argument_InsufficientSpaceToCopyCollection); int i = index; foreach (KeyValuePair<TKey, TValue> mapping in dictionary) @@ -289,7 +291,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime throw new ArgumentNullException(nameof(dictionary)); this.dictionary = dictionary; - this.enumeration = dictionary.GetEnumerator(); + enumeration = dictionary.GetEnumerator(); } void IDisposable.Dispose() @@ -302,11 +304,13 @@ namespace System.Runtime.InteropServices.WindowsRuntime return enumeration.MoveNext(); } - Object IEnumerator.Current { + Object IEnumerator.Current + { get { return ((IEnumerator<TValue>)this).Current; } } - public TValue Current { + public TValue Current + { get { return enumeration.Current.Value; } } @@ -315,5 +319,4 @@ namespace System.Runtime.InteropServices.WindowsRuntime enumeration = dictionary.GetEnumerator(); } } // class ReadOnlyDictionaryValueEnumerator<TKey, TValue> - } diff --git a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/IPropertyValue.cs b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/IPropertyValue.cs index 4065406dfa..a2b07b2ea7 100644 --- a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/IPropertyValue.cs +++ b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/IPropertyValue.cs @@ -139,27 +139,25 @@ namespace System.Runtime.InteropServices.WindowsRuntime } // Specify size directly instead of fields to avoid warnings - [StructLayoutAttribute(LayoutKind.Sequential, Size=8)] + [StructLayoutAttribute(LayoutKind.Sequential, Size = 8)] [WindowsRuntimeImport] internal struct Point { - // float X; // float Y; } // Specify size directly instead of fields to avoid warnings - [StructLayoutAttribute(LayoutKind.Sequential, Size=8)] + [StructLayoutAttribute(LayoutKind.Sequential, Size = 8)] [WindowsRuntimeImport] internal struct Size { - // float Width; // float Height; } // Specify size directly instead of fields to avoid warnings - [StructLayoutAttribute(LayoutKind.Sequential, Size=16)] + [StructLayoutAttribute(LayoutKind.Sequential, Size = 16)] [WindowsRuntimeImport] internal struct Rect { @@ -167,5 +165,5 @@ namespace System.Runtime.InteropServices.WindowsRuntime // float Y; // float Width; // float Height; - } + } } diff --git a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/IReadOnlyDictionaryToIMapViewAdapter.cs b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/IReadOnlyDictionaryToIMapViewAdapter.cs index b185b41be0..73daf876cd 100644 --- a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/IReadOnlyDictionaryToIMapViewAdapter.cs +++ b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/IReadOnlyDictionaryToIMapViewAdapter.cs @@ -40,7 +40,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime if (!keyFound) { - Exception e = new KeyNotFoundException(Environment.GetResourceString("Arg_KeyNotFound")); + Exception e = new KeyNotFoundException(SR.Arg_KeyNotFound); e.SetErrorCode(__HResults.E_BOUNDS); throw e; } @@ -54,7 +54,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime IReadOnlyDictionary<K, V> _this = JitHelpers.UnsafeCast<IReadOnlyDictionary<K, V>>(this); return (uint)_this.Count; } - + // bool HasKey(K key) internal bool HasKey<K, V>(K key) { @@ -67,7 +67,8 @@ namespace System.Runtime.InteropServices.WindowsRuntime { IReadOnlyDictionary<K, V> _this = JitHelpers.UnsafeCast<IReadOnlyDictionary<K, V>>(this); - if (_this.Count < 2) { + if (_this.Count < 2) + { first = null; second = null; return; diff --git a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/IReadOnlyListToIVectorViewAdapter.cs b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/IReadOnlyListToIVectorViewAdapter.cs index 431d16256e..5dce7dfc8d 100644 --- a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/IReadOnlyListToIVectorViewAdapter.cs +++ b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/IReadOnlyListToIVectorViewAdapter.cs @@ -35,11 +35,11 @@ namespace System.Runtime.InteropServices.WindowsRuntime internal T GetAt<T>(uint index) { IReadOnlyList<T> _this = JitHelpers.UnsafeCast<IReadOnlyList<T>>(this); - EnsureIndexInt32(index, _this.Count); + EnsureIndexInt32(index, _this.Count); try { - return _this[(int) index]; + return _this[(int)index]; } catch (ArgumentOutOfRangeException ex) { @@ -126,7 +126,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime // that Size > Int32.MaxValue: if (((uint)Int32.MaxValue) <= index || index >= (uint)listCapacity) { - Exception e = new ArgumentOutOfRangeException(nameof(index), Environment.GetResourceString("ArgumentOutOfRange_IndexLargerThanMaxValue")); + Exception e = new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_IndexLargerThanMaxValue); e.SetErrorCode(__HResults.E_BOUNDS); throw e; } diff --git a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/IVector.cs b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/IVector.cs index 6982911a13..e88f4f3b9f 100644 --- a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/IVector.cs +++ b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/IVector.cs @@ -11,6 +11,7 @@ using System.Diagnostics.Contracts; // Windows.Foundation.Collections.IVector`1 and IVectorView`1 cannot be referenced from managed // code because they're hidden by the metadata adapter. We redeclare the interfaces manually // to be able to talk to native WinRT objects. + namespace System.Runtime.InteropServices.WindowsRuntime { [ComImport] diff --git a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/IVectorViewToIReadOnlyListAdapter.cs b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/IVectorViewToIReadOnlyListAdapter.cs index 37f21307dc..76b0fff00d 100644 --- a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/IVectorViewToIReadOnlyListAdapter.cs +++ b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/IVectorViewToIReadOnlyListAdapter.cs @@ -43,7 +43,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime try { - return _this.GetAt((uint) index); + return _this.GetAt((uint)index); // We delegate bounds checking to the underlying collection and if it detected a fault, // we translate it to the right exception: @@ -62,15 +62,15 @@ namespace System.Runtime.InteropServices.WindowsRuntime { bool fUseString; Delegate target = System.StubHelpers.StubHelpers.GetTargetForAmbiguousVariantCall( - this, - typeof(IReadOnlyList<T>).TypeHandle.Value, + this, + typeof(IReadOnlyList<T>).TypeHandle.Value, out fUseString); if (target != null) { return (JitHelpers.UnsafeCast<Indexer_Get_Delegate<T>>(target))(index); } - + if (fUseString) { return JitHelpers.UnsafeCast<T>(Indexer_Get<string>(index)); diff --git a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/IteratorToEnumeratorAdapter.cs b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/IteratorToEnumeratorAdapter.cs index e219a86769..417476dbbe 100644 --- a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/IteratorToEnumeratorAdapter.cs +++ b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/IteratorToEnumeratorAdapter.cs @@ -31,7 +31,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime { Debug.Assert(false, "This class is never instantiated"); } - + // This method is invoked when GetEnumerator is called on a WinRT-backed implementation of IEnumerable<T>. internal IEnumerator<T> GetEnumerator_Stub<T>() { @@ -55,7 +55,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime { return (JitHelpers.UnsafeCast<GetEnumerator_Delegate<T>>(target))(); } - + if (fUseString) { return JitHelpers.UnsafeCast<IEnumerator<T>>(GetEnumerator_Stub<string>()); @@ -79,7 +79,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime public NonGenericToGenericIterator(IBindableIterator iterator) { this.iterator = iterator; } - public object Current { get { return iterator.Current; } } + public object Current { get { return iterator.Current; } } public bool HasCurrent { get { return iterator.HasCurrent; } } public bool MoveNext() { return iterator.MoveNext(); } public int GetMany(object[] items) { throw new NotSupportedException(); } diff --git a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/ListToBindableVectorAdapter.cs b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/ListToBindableVectorAdapter.cs index b9fe11557d..5f12322ea8 100644 --- a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/ListToBindableVectorAdapter.cs +++ b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/ListToBindableVectorAdapter.cs @@ -36,7 +36,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime internal object GetAt(uint index) { IList _this = JitHelpers.UnsafeCast<IList>(this); - EnsureIndexInt32(index, _this.Count); + EnsureIndexInt32(index, _this.Count); try { @@ -119,7 +119,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime internal void RemoveAt(uint index) { IList _this = JitHelpers.UnsafeCast<IList>(this); - EnsureIndexInt32(index, _this.Count); + EnsureIndexInt32(index, _this.Count); try { @@ -146,7 +146,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime IList _this = JitHelpers.UnsafeCast<IList>(this); if (_this.Count == 0) { - Exception e = new InvalidOperationException(Environment.GetResourceString("InvalidOperation_CannotRemoveLastFromEmptyCollection")); + Exception e = new InvalidOperationException(SR.InvalidOperation_CannotRemoveLastFromEmptyCollection); e.SetErrorCode(__HResults.E_BOUNDS); throw e; } @@ -170,7 +170,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime // that Size > Int32.MaxValue: if (((uint)Int32.MaxValue) <= index || index >= (uint)listCapacity) { - Exception e = new ArgumentOutOfRangeException(nameof(index), Environment.GetResourceString("ArgumentOutOfRange_IndexLargerThanMaxValue")); + Exception e = new ArgumentOutOfRangeException(nameof(index), SR.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 2e2ea9b876..fc02bedfa6 100644 --- a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/ListToBindableVectorViewAdapter.cs +++ b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/ListToBindableVectorViewAdapter.cs @@ -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(nameof(index), Environment.GetResourceString("ArgumentOutOfRange_IndexLargerThanMaxValue")); + Exception e = new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_IndexLargerThanMaxValue); e.SetErrorCode(__HResults.E_BOUNDS); throw e; } @@ -61,7 +61,6 @@ namespace System.Runtime.InteropServices.WindowsRuntime try { return list[(int)index]; - } catch (ArgumentOutOfRangeException ex) { diff --git a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/ListToVectorAdapter.cs b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/ListToVectorAdapter.cs index b73f4d7a99..87330e2559 100644 --- a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/ListToVectorAdapter.cs +++ b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/ListToVectorAdapter.cs @@ -36,7 +36,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime internal T GetAt<T>(uint index) { IList<T> _this = JitHelpers.UnsafeCast<IList<T>>(this); - EnsureIndexInt32(index, _this.Count); + EnsureIndexInt32(index, _this.Count); try { @@ -128,7 +128,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime internal void RemoveAt<T>(uint index) { IList<T> _this = JitHelpers.UnsafeCast<IList<T>>(this); - EnsureIndexInt32(index, _this.Count); + EnsureIndexInt32(index, _this.Count); try { @@ -155,7 +155,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime IList<T> _this = JitHelpers.UnsafeCast<IList<T>>(this); if (_this.Count == 0) { - Exception e = new InvalidOperationException(Environment.GetResourceString("InvalidOperation_CannotRemoveLastFromEmptyCollection")); + Exception e = new InvalidOperationException(SR.InvalidOperation_CannotRemoveLastFromEmptyCollection); e.SetErrorCode(__HResults.E_BOUNDS); throw e; } @@ -201,7 +201,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime // that Size > Int32.MaxValue: if (((uint)Int32.MaxValue) <= index || index >= (uint)listCapacity) { - Exception e = new ArgumentOutOfRangeException(nameof(index), Environment.GetResourceString("ArgumentOutOfRange_IndexLargerThanMaxValue")); + Exception e = new ArgumentOutOfRangeException(nameof(index), SR.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 2d08cab0ee..12b13ac79b 100644 --- a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/ManagedActivationFactory.cs +++ b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/ManagedActivationFactory.cs @@ -41,8 +41,8 @@ namespace System.Runtime.InteropServices.WindowsRuntime // 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), nameof(type)); - + throw new ArgumentException(SR.Format(SR.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 f11260eb4a..6b6c1719c3 100644 --- a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/MapToCollectionAdapter.cs +++ b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/MapToCollectionAdapter.cs @@ -46,7 +46,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime if (((uint)Int32.MaxValue) < size) { - throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_CollectionBackingDictionaryTooLarge")); + throw new InvalidOperationException(SR.InvalidOperation_CollectionBackingDictionaryTooLarge); } return (int)size; @@ -58,7 +58,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime if (((uint)Int32.MaxValue) < size) { - throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_CollectionBackingListTooLarge")); + throw new InvalidOperationException(SR.InvalidOperation_CollectionBackingListTooLarge); } return (int)size; @@ -140,10 +140,10 @@ namespace System.Runtime.InteropServices.WindowsRuntime throw new ArgumentOutOfRangeException(nameof(arrayIndex)); if (array.Length <= arrayIndex && Count<K, V>() > 0) - throw new ArgumentException(Environment.GetResourceString("Argument_IndexOutOfArrayBounds")); + throw new ArgumentException(SR.Argument_IndexOutOfArrayBounds); if (array.Length - arrayIndex < Count<K, V>()) - throw new ArgumentException(Environment.GetResourceString("Argument_InsufficientSpaceToCopyCollection")); + throw new ArgumentException(SR.Argument_InsufficientSpaceToCopyCollection); Contract.EndContractBlock(); @@ -175,7 +175,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime if (((uint)Int32.MaxValue) < index) { - throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_CollectionBackingListTooLarge")); + throw new InvalidOperationException(SR.InvalidOperation_CollectionBackingListTooLarge); } VectorToListAdapter.RemoveAtHelper<KeyValuePair<K, V>>(_this_vector, index); diff --git a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/MapToDictionaryAdapter.cs b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/MapToDictionaryAdapter.cs index 981972ca9f..224a266b07 100644 --- a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/MapToDictionaryAdapter.cs +++ b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/MapToDictionaryAdapter.cs @@ -88,7 +88,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime throw new ArgumentNullException(nameof(key)); if (ContainsKey<K, V>(key)) - throw new ArgumentException(Environment.GetResourceString("Argument_AddingDuplicate")); + throw new ArgumentException(SR.Argument_AddingDuplicate); Contract.EndContractBlock(); @@ -110,7 +110,6 @@ namespace System.Runtime.InteropServices.WindowsRuntime { _this.Remove(key); return true; - } catch (Exception ex) { @@ -158,9 +157,8 @@ namespace System.Runtime.InteropServices.WindowsRuntime } catch (Exception ex) { - if (__HResults.E_BOUNDS == ex._HResult) - throw new KeyNotFoundException(Environment.GetResourceString("Arg_KeyNotFound")); + throw new KeyNotFoundException(SR.Arg_KeyNotFound); throw; } } diff --git a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/MapViewToReadOnlyCollectionAdapter.cs b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/MapViewToReadOnlyCollectionAdapter.cs index a3715da0b0..5d509549d3 100644 --- a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/MapViewToReadOnlyCollectionAdapter.cs +++ b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/MapViewToReadOnlyCollectionAdapter.cs @@ -46,7 +46,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime if (((uint)Int32.MaxValue) < size) { - throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_CollectionBackingDictionaryTooLarge")); + throw new InvalidOperationException(SR.InvalidOperation_CollectionBackingDictionaryTooLarge); } return (int)size; @@ -58,7 +58,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime if (((uint)Int32.MaxValue) < size) { - throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_CollectionBackingListTooLarge")); + throw new InvalidOperationException(SR.InvalidOperation_CollectionBackingListTooLarge); } return (int)size; diff --git a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/NativeMethods.cs b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/NativeMethods.cs index 627de8d400..ccae412987 100644 --- a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/NativeMethods.cs +++ b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/NativeMethods.cs @@ -38,14 +38,14 @@ namespace System.Runtime.InteropServices.WindowsRuntime [SuppressUnmanagedCodeSecurity] internal static unsafe extern int WindowsCreateString([MarshalAs(UnmanagedType.LPWStr)] string sourceString, int length, - [Out] IntPtr *hstring); + [Out] IntPtr* hstring); [DllImport("api-ms-win-core-winrt-string-l1-1-0.dll", CallingConvention = CallingConvention.StdCall)] [SuppressUnmanagedCodeSecurity] - internal static unsafe extern int WindowsCreateStringReference(char *sourceString, + internal static unsafe extern int WindowsCreateStringReference(char* sourceString, int length, - [Out] HSTRING_HEADER *hstringHeader, - [Out] IntPtr *hstring); + [Out] HSTRING_HEADER* hstringHeader, + [Out] IntPtr* hstring); [DllImport("api-ms-win-core-winrt-string-l1-1-0.dll", CallingConvention = CallingConvention.StdCall)] [SuppressUnmanagedCodeSecurity] @@ -53,6 +53,6 @@ namespace System.Runtime.InteropServices.WindowsRuntime [DllImport("api-ms-win-core-winrt-string-l1-1-0.dll", CallingConvention = CallingConvention.StdCall)] [SuppressUnmanagedCodeSecurity] - internal static unsafe extern char* WindowsGetStringRawBuffer(IntPtr hstring, [Out] uint *length); + internal static unsafe extern char* WindowsGetStringRawBuffer(IntPtr hstring, [Out] uint* length); } } diff --git a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/PropertyValue.cs b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/PropertyValue.cs index ad64c9917f..8a3e2066cf 100644 --- a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/PropertyValue.cs +++ b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/PropertyValue.cs @@ -17,20 +17,20 @@ namespace System.Runtime.InteropServices.WindowsRuntime internal enum PropertyType { // WARNING: These values have to match enum Windows.Foundation.PropertyType !!! - Empty = 0, - UInt8 = 1, + Empty = 0, + UInt8 = 1, Int16 = 2, UInt16 = 3, - Int32 = 4, - UInt32 = 5, - Int64 = 6, - UInt64 = 7, - Single = 8, - Double = 9, - Char16 = 10, - Boolean = 11, - String = 12, - Inspectable = 13, + Int32 = 4, + UInt32 = 5, + Int64 = 6, + UInt64 = 7, + Single = 8, + Double = 9, + Char16 = 10, + Boolean = 11, + String = 12, + Inspectable = 13, DateTime = 14, TimeSpan = 15, Guid = 16, diff --git a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/RuntimeClass.cs b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/RuntimeClass.cs index cd3c53ab4e..fdc0d22632 100644 --- a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/RuntimeClass.cs +++ b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/RuntimeClass.cs @@ -10,15 +10,15 @@ ** ** ===========================================================*/ -namespace System.Runtime.InteropServices.WindowsRuntime { - - using System; - using System.Runtime.InteropServices; - using System.Runtime.InteropServices.WindowsRuntime; - using System.Runtime.CompilerServices; - using System.Security; +using System; +using System.Runtime.InteropServices; +using System.Runtime.InteropServices.WindowsRuntime; +using System.Runtime.CompilerServices; +using System.Security; +namespace System.Runtime.InteropServices.WindowsRuntime +{ // Local definition of Windows.Foundation.IStringable [ComImport] [Guid("96369f54-8eb6-48f0-abce-c1b211e627c3")] @@ -33,7 +33,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime { internal static string ToString(object obj) { IGetProxyTarget proxy = obj as IGetProxyTarget; - if (proxy != null) + if (proxy != null) obj = proxy.GetTarget(); // Check whether the type implements IStringable. @@ -41,12 +41,12 @@ namespace System.Runtime.InteropServices.WindowsRuntime { if (stringableType != null) { return stringableType.ToString(); - } - + } + return obj.ToString(); - } + } } - + // // Base class for every WinRT class // We'll make it a ComImport and WindowsRuntimeImport in the type loader @@ -57,11 +57,11 @@ namespace System.Runtime.InteropServices.WindowsRuntime { // // Support for ToString/GetHashCode/Equals override // - [MethodImpl(MethodImplOptions.InternalCall)] - internal extern IntPtr GetRedirectedGetHashCodeMD(); - - [MethodImpl(MethodImplOptions.InternalCall)] - internal extern int RedirectGetHashCode(IntPtr pMD); + [MethodImpl(MethodImplOptions.InternalCall)] + internal extern IntPtr GetRedirectedGetHashCodeMD(); + + [MethodImpl(MethodImplOptions.InternalCall)] + internal extern int RedirectGetHashCode(IntPtr pMD); public override int GetHashCode() { @@ -71,10 +71,10 @@ namespace System.Runtime.InteropServices.WindowsRuntime { return RedirectGetHashCode(pMD); } - [MethodImpl(MethodImplOptions.InternalCall)] - internal extern IntPtr GetRedirectedToStringMD(); + [MethodImpl(MethodImplOptions.InternalCall)] + internal extern IntPtr GetRedirectedToStringMD(); - [MethodImpl(MethodImplOptions.InternalCall)] + [MethodImpl(MethodImplOptions.InternalCall)] internal extern string RedirectToString(IntPtr pMD); public override string ToString() @@ -96,11 +96,11 @@ namespace System.Runtime.InteropServices.WindowsRuntime { } } - [MethodImpl(MethodImplOptions.InternalCall)] - internal extern IntPtr GetRedirectedEqualsMD(); + [MethodImpl(MethodImplOptions.InternalCall)] + internal extern IntPtr GetRedirectedEqualsMD(); - [MethodImpl(MethodImplOptions.InternalCall)] - internal extern bool RedirectEquals(object obj, IntPtr pMD); + [MethodImpl(MethodImplOptions.InternalCall)] + internal extern bool RedirectEquals(object obj, IntPtr pMD); public override bool Equals(object obj) { diff --git a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/VectorToCollectionAdapter.cs b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/VectorToCollectionAdapter.cs index 898f1a68a0..3065b83c30 100644 --- a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/VectorToCollectionAdapter.cs +++ b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/VectorToCollectionAdapter.cs @@ -38,7 +38,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime uint size = _this.Size; if (((uint)Int32.MaxValue) < size) { - throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_CollectionBackingListTooLarge")); + throw new InvalidOperationException(SR.InvalidOperation_CollectionBackingListTooLarge); } return (int)size; @@ -83,10 +83,10 @@ namespace System.Runtime.InteropServices.WindowsRuntime throw new ArgumentOutOfRangeException(nameof(arrayIndex)); if (array.Length <= arrayIndex && Count<T>() > 0) - throw new ArgumentException(Environment.GetResourceString("Argument_IndexOutOfArrayBounds")); + throw new ArgumentException(SR.Argument_IndexOutOfArrayBounds); if (array.Length - arrayIndex < Count<T>()) - throw new ArgumentException(Environment.GetResourceString("Argument_InsufficientSpaceToCopyCollection")); + throw new ArgumentException(SR.Argument_InsufficientSpaceToCopyCollection); Contract.EndContractBlock(); @@ -111,7 +111,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime if (((uint)Int32.MaxValue) < index) { - throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_CollectionBackingListTooLarge")); + throw new InvalidOperationException(SR.InvalidOperation_CollectionBackingListTooLarge); } VectorToListAdapter.RemoveAtHelper<T>(_this, index); diff --git a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/VectorToListAdapter.cs b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/VectorToListAdapter.cs index 3e3324864d..56e62a25e7 100644 --- a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/VectorToListAdapter.cs +++ b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/VectorToListAdapter.cs @@ -63,7 +63,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime if (((uint)Int32.MaxValue) < index) { - throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_CollectionBackingListTooLarge")); + throw new InvalidOperationException(SR.InvalidOperation_CollectionBackingListTooLarge); } return (int)index; diff --git a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/VectorViewToReadOnlyCollectionAdapter.cs b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/VectorViewToReadOnlyCollectionAdapter.cs index 6b7785d2dc..84c12f8a5c 100644 --- a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/VectorViewToReadOnlyCollectionAdapter.cs +++ b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/VectorViewToReadOnlyCollectionAdapter.cs @@ -38,7 +38,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime uint size = _this.Size; if (((uint)Int32.MaxValue) < size) { - throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_CollectionBackingListTooLarge")); + throw new InvalidOperationException(SR.InvalidOperation_CollectionBackingListTooLarge); } return (int)size; diff --git a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/WindowsRuntimeBufferHelper.cs b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/WindowsRuntimeBufferHelper.cs index 551ee65153..55c356de93 100644 --- a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/WindowsRuntimeBufferHelper.cs +++ b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/WindowsRuntimeBufferHelper.cs @@ -9,29 +9,26 @@ using System.Security; using System.Threading; -namespace System.Runtime.InteropServices.WindowsRuntime { - -/// <summary> -/// Exposes a helper method that allows <code>WindowsRuntimeBuffer : IBuffer, IBufferInternal</code> which is implemented in -/// <code>System.Runtime.WindowsRuntime.dll</code> to call into the VM. -/// </summary> -[FriendAccessAllowed] -internal static class WindowsRuntimeBufferHelper { - - - [DllImport(JitHelpers.QCall)] - [SuppressUnmanagedCodeSecurity] - private unsafe extern static void StoreOverlappedPtrInCCW(ObjectHandleOnStack windowsRuntimeBuffer, NativeOverlapped* overlapped); - - +namespace System.Runtime.InteropServices.WindowsRuntime +{ + /// <summary> + /// Exposes a helper method that allows <code>WindowsRuntimeBuffer : IBuffer, IBufferInternal</code> which is implemented in + /// <code>System.Runtime.WindowsRuntime.dll</code> to call into the VM. + /// </summary> [FriendAccessAllowed] - internal unsafe static void StoreOverlappedInCCW(Object windowsRuntimeBuffer, NativeOverlapped* overlapped) { - - StoreOverlappedPtrInCCW(JitHelpers.GetObjectHandleOnStack(ref windowsRuntimeBuffer), overlapped); - } - -} // class WindowsRuntimeBufferHelper - + internal static class WindowsRuntimeBufferHelper + { + [DllImport(JitHelpers.QCall)] + [SuppressUnmanagedCodeSecurity] + private unsafe extern static void StoreOverlappedPtrInCCW(ObjectHandleOnStack windowsRuntimeBuffer, NativeOverlapped* overlapped); + + + [FriendAccessAllowed] + internal unsafe static void StoreOverlappedInCCW(Object windowsRuntimeBuffer, NativeOverlapped* overlapped) + { + StoreOverlappedPtrInCCW(JitHelpers.GetObjectHandleOnStack(ref windowsRuntimeBuffer), overlapped); + } + } // class WindowsRuntimeBufferHelper } // namespace // WindowsRuntimeBufferHelper.cs diff --git a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/WindowsRuntimeMarshal.cs b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/WindowsRuntimeMarshal.cs index 57655ec861..0b7ba10d62 100644 --- a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/WindowsRuntimeMarshal.cs +++ b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/WindowsRuntimeMarshal.cs @@ -75,9 +75,9 @@ namespace System.Runtime.InteropServices.WindowsRuntime if (target == null || Marshal.IsComObject(target)) NativeOrStaticEventRegistrationImpl.RemoveEventHandler<T>(removeMethod, handler); else - ManagedEventRegistrationImpl.RemoveEventHandler<T>(removeMethod, handler); + ManagedEventRegistrationImpl.RemoveEventHandler<T>(removeMethod, handler); } - + public static void RemoveAllEventHandlers(Action<EventRegistrationToken> removeMethod) { if (removeMethod == null) @@ -108,7 +108,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime count += ManagedEventRegistrationImpl.s_eventRegistrations.Keys.Count; } } - + if (NativeOrStaticEventRegistrationImpl.s_eventRegistrations != null) { lock (NativeOrStaticEventRegistrationImpl.s_eventRegistrations) @@ -116,7 +116,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime count += NativeOrStaticEventRegistrationImpl.s_eventRegistrations.Count; } } - + return count; } @@ -124,11 +124,11 @@ namespace System.Runtime.InteropServices.WindowsRuntime // Optimized version of List of EventRegistrationToken // It is made a struct to reduce overhead // - internal struct EventRegistrationTokenList + internal struct EventRegistrationTokenList { - private EventRegistrationToken firstToken; // Optimization for common case where there is only one token - private List<EventRegistrationToken> restTokens; // Rest of the tokens - + private EventRegistrationToken firstToken; // Optimization for common case where there is only one token + private List<EventRegistrationToken> restTokens; // Rest of the tokens + internal EventRegistrationTokenList(EventRegistrationToken token) { firstToken = token; @@ -141,18 +141,18 @@ namespace System.Runtime.InteropServices.WindowsRuntime public bool Push(EventRegistrationToken token) { bool needCopy = false; - + if (restTokens == null) { restTokens = new List<EventRegistrationToken>(); needCopy = true; } - + restTokens.Add(token); return needCopy; } - + // Pops the last token // Returns false if no more tokens left, true otherwise public bool Pop(out EventRegistrationToken token) @@ -163,14 +163,14 @@ namespace System.Runtime.InteropServices.WindowsRuntime token = firstToken; return false; } - + int last = restTokens.Count - 1; token = restTokens[last]; restTokens.RemoveAt(last); - + return true; } - + public void CopyTo(List<EventRegistrationToken> tokens) { tokens.Add(firstToken); @@ -183,7 +183,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime // Event registration support for managed objects events & static events // internal static class ManagedEventRegistrationImpl - { + { // Mappings of delegates registered for events -> their registration tokens. // These mappings are stored indexed by the remove method which can be used to undo the registrations. // @@ -208,10 +208,10 @@ namespace System.Runtime.InteropServices.WindowsRuntime // If the delegates aren't alive, it means either they have been unsubscribed, or the object itself is gone, // and in either case, they've been already taken care of. // - internal volatile static - ConditionalWeakTable<object, Dictionary<MethodInfo, Dictionary<object, EventRegistrationTokenList>>> s_eventRegistrations = + internal volatile static + ConditionalWeakTable<object, Dictionary<MethodInfo, Dictionary<object, EventRegistrationTokenList>>> s_eventRegistrations = new ConditionalWeakTable<object, Dictionary<MethodInfo, Dictionary<object, EventRegistrationTokenList>>>(); - + internal static void AddEventHandler<T>(Func<T, EventRegistrationToken> addMethod, Action<EventRegistrationToken> removeMethod, T handler) @@ -239,18 +239,18 @@ namespace System.Runtime.InteropServices.WindowsRuntime if (needCopy) registrationTokens[handler] = tokens; } - + BCLDebug.Log("INTEROP", "[WinRT_Eventing] Event subscribed for managed instance = " + instance + ", handler = " + handler + "\n"); } } - + // Get the event registration token table for an event. These are indexed by the remove method of the event. private static Dictionary<object, EventRegistrationTokenList> GetEventRegistrationTokenTable(object instance, Action<EventRegistrationToken> removeMethod) { Contract.Requires(instance != null); Contract.Requires(removeMethod != null); - Contract.Requires(s_eventRegistrations != null); - + Contract.Requires(s_eventRegistrations != null); + lock (s_eventRegistrations) { Dictionary<MethodInfo, Dictionary<object, EventRegistrationTokenList>> instanceMap = null; @@ -259,14 +259,14 @@ namespace System.Runtime.InteropServices.WindowsRuntime instanceMap = new Dictionary<MethodInfo, Dictionary<object, EventRegistrationTokenList>>(); s_eventRegistrations.Add(instance, instanceMap); } - + Dictionary<object, EventRegistrationTokenList> tokens = null; if (!instanceMap.TryGetValue(removeMethod.Method, out tokens)) { tokens = new Dictionary<object, EventRegistrationTokenList>(); instanceMap.Add(removeMethod.Method, tokens); } - + return tokens; } } @@ -278,19 +278,19 @@ namespace System.Runtime.InteropServices.WindowsRuntime object instance = removeMethod.Target; Dictionary<object, EventRegistrationTokenList> registrationTokens = GetEventRegistrationTokenTable(instance, removeMethod); EventRegistrationToken token; - + lock (registrationTokens) { EventRegistrationTokenList tokens; - + // Failure to find a registration for a token is not an error - it's simply a no-op. if (!registrationTokens.TryGetValue(handler, out tokens)) { - BCLDebug.Log("INTEROP", "[WinRT_Eventing] no registrationTokens found for instance=" + instance + ", handler= " + handler + "\n"); - + BCLDebug.Log("INTEROP", "[WinRT_Eventing] no registrationTokens found for instance=" + instance + ", handler= " + handler + "\n"); + return; } - + // Select a registration token to unregister // We don't care which one but I'm returning the last registered token to be consistent // with native event registration implementation @@ -306,23 +306,23 @@ namespace System.Runtime.InteropServices.WindowsRuntime registrationTokens.Remove(handler); } } - + removeMethod(token); - BCLDebug.Log("INTEROP", "[WinRT_Eventing] Event unsubscribed for managed instance = " + instance + ", handler = " + handler + ", token = " + token.m_value + "\n"); + BCLDebug.Log("INTEROP", "[WinRT_Eventing] Event unsubscribed for managed instance = " + instance + ", handler = " + handler + ", token = " + token.m_value + "\n"); } internal static void RemoveAllEventHandlers(Action<EventRegistrationToken> removeMethod) { - Contract.Requires(removeMethod != null); + Contract.Requires(removeMethod != null); object instance = removeMethod.Target; Dictionary<object, EventRegistrationTokenList> registrationTokens = GetEventRegistrationTokenTable(instance, removeMethod); List<EventRegistrationToken> tokensToRemove = new List<EventRegistrationToken>(); - + lock (registrationTokens) - { + { // Copy all tokens to tokensToRemove array which later we'll call removeMethod on // outside this lock foreach (EventRegistrationTokenList tokens in registrationTokens.Values) @@ -339,9 +339,9 @@ namespace System.Runtime.InteropServices.WindowsRuntime // // Remove all handlers outside the lock // - BCLDebug.Log("INTEROP", "[WinRT_Eventing] Start removing all events for instance = " + instance + "\n"); + BCLDebug.Log("INTEROP", "[WinRT_Eventing] Start removing all events for instance = " + instance + "\n"); CallRemoveMethods(removeMethod, tokensToRemove); - BCLDebug.Log("INTEROP", "[WinRT_Eventing] Finished removing all events for instance = " + instance + "\n"); + BCLDebug.Log("INTEROP", "[WinRT_Eventing] Finished removing all events for instance = " + instance + "\n"); } } @@ -349,15 +349,15 @@ namespace System.Runtime.InteropServices.WindowsRuntime // WinRT event registration implementation code // internal static class NativeOrStaticEventRegistrationImpl - { + { // // Key = (target object, event) // We use a key of object+event to save an extra dictionary // internal struct EventCacheKey { - internal object target; - internal MethodInfo method; + internal object target; + internal MethodInfo method; public override string ToString() { @@ -377,7 +377,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime return key.target.GetHashCode() ^ key.method.GetHashCode(); } } - + // // EventRegistrationTokenListWithCount // @@ -390,9 +390,9 @@ namespace System.Runtime.InteropServices.WindowsRuntime // internal class EventRegistrationTokenListWithCount { - private TokenListCount _tokenListCount; - EventRegistrationTokenList _tokenList; - + private TokenListCount _tokenListCount; + private EventRegistrationTokenList _tokenList; + internal EventRegistrationTokenListWithCount(TokenListCount tokenListCount, EventRegistrationToken token) { _tokenListCount = tokenListCount; @@ -400,30 +400,30 @@ namespace System.Runtime.InteropServices.WindowsRuntime _tokenList = new EventRegistrationTokenList(token); } - + ~EventRegistrationTokenListWithCount() - { + { // Decrement token list count // This is need to correctly keep trace of number of tokens for EventCacheKey // and remove it from cache when the token count drop to 0 // we don't need to take locks for decrement the count - we only need to take a global // lock when we decide to destroy cache for the IUnknown */type instance - BCLDebug.Log("INTEROP", "[WinRT_Eventing] Finalizing EventRegistrationTokenList for " + _tokenListCount.Key + "\n"); + BCLDebug.Log("INTEROP", "[WinRT_Eventing] Finalizing EventRegistrationTokenList for " + _tokenListCount.Key + "\n"); _tokenListCount.Dec(); } - + public void Push(EventRegistrationToken token) { // Since EventRegistrationTokenListWithCount is a reference type, there is no need // to copy back. Ignore the return value _tokenList.Push(token); } - + public bool Pop(out EventRegistrationToken token) { return _tokenList.Pop(out token); } - + public void CopyTo(List<EventRegistrationToken> tokens) { _tokenList.CopyTo(tokens); @@ -438,8 +438,8 @@ namespace System.Runtime.InteropServices.WindowsRuntime // internal class TokenListCount { - private int _count; - private EventCacheKey _key; + private int _count; + private EventCacheKey _key; internal TokenListCount(EventCacheKey key) { @@ -448,14 +448,13 @@ namespace System.Runtime.InteropServices.WindowsRuntime internal EventCacheKey Key { - get { return _key; } } - + internal void Inc() { int newCount = Interlocked.Increment(ref _count); - BCLDebug.Log("INTEROP", "[WinRT_Eventing] Incremented TokenListCount for " + _key + ", Value = " + newCount + "\n"); + BCLDebug.Log("INTEROP", "[WinRT_Eventing] Incremented TokenListCount for " + _key + ", Value = " + newCount + "\n"); } internal void Dec() @@ -466,7 +465,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime try { int newCount = Interlocked.Decrement(ref _count); - BCLDebug.Log("INTEROP", "[WinRT_Eventing] Decremented TokenListCount for " + _key + ", Value = " + newCount + "\n"); + BCLDebug.Log("INTEROP", "[WinRT_Eventing] Decremented TokenListCount for " + _key + ", Value = " + newCount + "\n"); if (newCount == 0) CleanupCache(); } @@ -482,7 +481,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime // because the total token list count has dropped to 0 and we don't have any events subscribed Contract.Requires(s_eventRegistrations != null); - BCLDebug.Log("INTEROP", "[WinRT_Eventing] Removing " + _key + " from cache" + "\n"); + BCLDebug.Log("INTEROP", "[WinRT_Eventing] Removing " + _key + " from cache" + "\n"); s_eventRegistrations.Remove(_key); BCLDebug.Log("INTEROP", "[WinRT_Eventing] s_eventRegistrations size = " + s_eventRegistrations.Count + "\n"); } @@ -520,7 +519,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime // b. The same delegate is subscribed then unsubscribed. We need to make sure give // them the latest token in this case. This is guaranteed by always giving the last token and always use equality to // add/remove event handlers - internal volatile static Dictionary<EventCacheKey, EventCacheEntry> s_eventRegistrations = + internal volatile static Dictionary<EventCacheKey, EventCacheEntry> s_eventRegistrations = new Dictionary<EventCacheKey, EventCacheEntry>(new EventCacheKeyEqualityComparer()); // Prevent add/remove handler code to run at the same with with cache cleanup code @@ -533,11 +532,11 @@ namespace System.Runtime.InteropServices.WindowsRuntime Debug.Assert(target == null || Marshal.IsComObject(target), "Must be null or a RCW"); if (target == null) return removeMethod.Method.DeclaringType; - + // Need the "Raw" IUnknown pointer for the RCW that is not bound to the current context - return (object) Marshal.GetRawIUnknownForComObjectNoAddRef(target); + return (object)Marshal.GetRawIUnknownForComObjectNoAddRef(target); } - + internal static void AddEventHandler<T>(Func<T, EventRegistrationToken> addMethod, Action<EventRegistrationToken> removeMethod, T handler) @@ -552,11 +551,11 @@ namespace System.Runtime.InteropServices.WindowsRuntime EventRegistrationToken token = addMethod(handler); bool tokenAdded = false; - + try { EventRegistrationTokenListWithCount tokens; - + // // The whole add/remove code has to be protected by a reader/writer lock // Add/Remove cannot run at the same time with cache cleanup but Add/Remove can run at the same time @@ -592,8 +591,8 @@ namespace System.Runtime.InteropServices.WindowsRuntime { tokens.Push(token); } - - tokenAdded = true; + + tokenAdded = true; } } finally @@ -601,10 +600,10 @@ namespace System.Runtime.InteropServices.WindowsRuntime s_eventCacheRWLock.ReleaseReaderLock(); } - BCLDebug.Log("INTEROP", "[WinRT_Eventing] Event subscribed for instance = " + instanceKey + ", handler = " + handler + "\n"); + BCLDebug.Log("INTEROP", "[WinRT_Eventing] Event subscribed for instance = " + instanceKey + ", handler = " + handler + "\n"); } - catch(Exception) - { + catch (Exception) + { // If we've already added the token and go there, we don't need to "UNDO" anything if (!tokenAdded) { @@ -613,8 +612,8 @@ namespace System.Runtime.InteropServices.WindowsRuntime removeMethod(token); } - - throw; + + throw; } } @@ -633,18 +632,18 @@ namespace System.Runtime.InteropServices.WindowsRuntime return GetEventRegistrationTokenTableInternal(instance, removeMethod, out tokenListCount, /* createIfNotFound = */ true); } - + // Get the event registration token table for an event. These are indexed by the remove method of the event. private static ConditionalWeakTable<object, EventRegistrationTokenListWithCount> GetEventRegistrationTokenTableInternal(object instance, Action<EventRegistrationToken> removeMethod, out TokenListCount tokenListCount, bool createIfNotFound) { Contract.Requires(instance != null); Contract.Requires(removeMethod != null); - Contract.Requires(s_eventRegistrations != null); + Contract.Requires(s_eventRegistrations != null); EventCacheKey eventCacheKey; eventCacheKey.target = instance; eventCacheKey.method = removeMethod.Method; - + lock (s_eventRegistrations) { EventCacheEntry eventCacheEntry; @@ -656,18 +655,18 @@ namespace System.Runtime.InteropServices.WindowsRuntime tokenListCount = null; return null; } - + BCLDebug.Log("INTEROP", "[WinRT_Eventing] Adding (" + instance + "," + removeMethod.Method + ") into cache" + "\n"); - + eventCacheEntry = new EventCacheEntry(); eventCacheEntry.registrationTable = new ConditionalWeakTable<object, EventRegistrationTokenListWithCount>(); eventCacheEntry.tokenListCount = new TokenListCount(eventCacheKey); - + s_eventRegistrations.Add(eventCacheKey, eventCacheEntry); } - + tokenListCount = eventCacheEntry.tokenListCount; - + return eventCacheEntry.registrationTable; } } @@ -677,7 +676,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime object instanceKey = GetInstanceKey(removeMethod); EventRegistrationToken token; - + // // The whole add/remove code has to be protected by a reader/writer lock // Add/Remove cannot run at the same time with cache cleanup but Add/Remove can run at the same time @@ -691,10 +690,10 @@ namespace System.Runtime.InteropServices.WindowsRuntime { // We have no information regarding this particular instance (IUnknown*/type) - just return // This is necessary to avoid leaking empty dictionary/conditionalWeakTables for this instance - BCLDebug.Log("INTEROP", "[WinRT_Eventing] no registrationTokens found for instance=" + instanceKey + ", handler= " + handler + "\n"); + BCLDebug.Log("INTEROP", "[WinRT_Eventing] no registrationTokens found for instance=" + instanceKey + ", handler= " + handler + "\n"); return; } - + lock (registrationTokens) { EventRegistrationTokenListWithCount tokens; @@ -707,12 +706,12 @@ 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); - Debug.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) { // Failure to find a registration for a token is not an error - it's simply a no-op. - BCLDebug.Log("INTEROP", "[WinRT_Eventing] no token list found for instance=" + instanceKey + ", handler= " + handler + "\n"); + BCLDebug.Log("INTEROP", "[WinRT_Eventing] no token list found for instance=" + instanceKey + ", handler= " + handler + "\n"); return; } @@ -721,7 +720,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime // is created at the same address before the entry for the old one goes away. // See comments above s_eventRegistrations for more details bool moreItems = tokens.Pop(out token); - + // If the last token is removed from token list, we need to remove it from the cache // otherwise FindEquivalentKeyUnsafe may found this empty token list even though there could be other // equivalent keys in there with non-0 token list @@ -733,8 +732,8 @@ namespace System.Runtime.InteropServices.WindowsRuntime // EventRegistrationTokenList registrationTokens.Remove(key); } - - BCLDebug.Log("INTEROP", "[WinRT_Eventing] Event unsubscribed for managed instance = " + instanceKey + ", handler = " + handler + ", token = " + token.m_value + "\n"); + + BCLDebug.Log("INTEROP", "[WinRT_Eventing] Event unsubscribed for managed instance = " + instanceKey + ", handler = " + handler + ", token = " + token.m_value + "\n"); } } finally @@ -745,7 +744,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime // Call removeMethod outside of RW lock // At this point we don't need to worry about race conditions and we can avoid deadlocks // if removeMethod waits on finalizer thread - removeMethod(token); + removeMethod(token); } internal static void RemoveAllEventHandlers(Action<EventRegistrationToken> removeMethod) @@ -753,7 +752,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime object instanceKey = GetInstanceKey(removeMethod); List<EventRegistrationToken> tokensToRemove = new List<EventRegistrationToken>(); - + // // The whole add/remove code has to be protected by a reader/writer lock // Add/Remove cannot run at the same time with cache cleanup but Add/Remove can run at the same time @@ -769,7 +768,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime // This is necessary to avoid leaking empty dictionary/conditionalWeakTables for this instance return; } - + lock (registrationTokens) { // Copy all tokens to tokensToRemove array which later we'll call removeMethod on @@ -782,7 +781,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime // Clear the table - at this point all event handlers are no longer in the cache // but they are not removed yet registrationTokens.Clear(); - BCLDebug.Log("INTEROP", "[WinRT_Eventing] Cache cleared for managed instance = " + instanceKey + "\n"); + BCLDebug.Log("INTEROP", "[WinRT_Eventing] Cache cleared for managed instance = " + instanceKey + "\n"); } } finally @@ -793,18 +792,17 @@ namespace System.Runtime.InteropServices.WindowsRuntime // // Remove all handlers outside the lock // - BCLDebug.Log("INTEROP", "[WinRT_Eventing] Start removing all events for instance = " + instanceKey + "\n"); + BCLDebug.Log("INTEROP", "[WinRT_Eventing] Start removing all events for instance = " + instanceKey + "\n"); CallRemoveMethods(removeMethod, tokensToRemove); - BCLDebug.Log("INTEROP", "[WinRT_Eventing] Finished removing all events for instance = " + instanceKey + "\n"); + BCLDebug.Log("INTEROP", "[WinRT_Eventing] Finished removing all events for instance = " + instanceKey + "\n"); } - + internal class ReaderWriterLockTimedOutException : ApplicationException { } - /// I borrowed Vance's reader writer lock implementation from his blog as ReaderWriterLockSlim is - /// available in System.Core.dll! + /// Discussed @ https://blogs.msdn.microsoft.com/vancem/2006/03/29/analysis-of-reader-writer-lock/ /// /// <summary> /// A reader-writer lock implementation that is intended to be simple, yet very @@ -821,19 +819,19 @@ namespace System.Runtime.InteropServices.WindowsRuntime // Lock specifiation for myLock: This lock protects exactly the local fields associted // instance of MyReaderWriterLock. It does NOT protect the memory associted with the // the events that hang off this lock (eg writeEvent, readEvent upgradeEvent). - int myLock; + private int myLock; // Who owns the lock owners > 0 => readers // owners = -1 means there is one writer. Owners must be >= -1. - int owners; + private int owners; // These variables allow use to avoid Setting events (which is expensive) if we don't have to. - uint numWriteWaiters; // maximum number of threads that can be doing a WaitOne on the writeEvent - uint numReadWaiters; // maximum number of threads that can be doing a WaitOne on the readEvent + private uint numWriteWaiters; // maximum number of threads that can be doing a WaitOne on the writeEvent + private uint numReadWaiters; // maximum number of threads that can be doing a WaitOne on the readEvent // conditions we wait on. - EventWaitHandle writeEvent; // threads waiting to aquire a write lock go here. - EventWaitHandle readEvent; // threads waiting to aquire a read lock go here (will be released in bulk) + private EventWaitHandle writeEvent; // threads waiting to aquire a write lock go here. + private EventWaitHandle readEvent; // threads waiting to aquire a read lock go here (will be released in bulk) internal MyReaderWriterLock() { @@ -843,7 +841,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime internal void AcquireReaderLock(int millisecondsTimeout) { EnterMyLock(); - for (; ; ) + for (;;) { // We can enter a read lock if there are only read-locks have been given out // and a writer is not trying to get in. @@ -869,7 +867,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime internal void AcquireWriterLock(int millisecondsTimeout) { EnterMyLock(); - for (; ; ) + for (;;) { if (owners == 0) { @@ -912,15 +910,16 @@ namespace System.Runtime.InteropServices.WindowsRuntime /// while holding a spin lock). If all goes well, reenter the lock and /// set 'waitEvent' /// </summary> - private void LazyCreateEvent(ref EventWaitHandle waitEvent, bool makeAutoResetEvent) { + private void LazyCreateEvent(ref EventWaitHandle waitEvent, bool makeAutoResetEvent) + { Debug.Assert(myLock != 0, "Lock must be held"); Debug.Assert(waitEvent == null, "Wait event must be null"); ExitMyLock(); EventWaitHandle newEvent; - if (makeAutoResetEvent) + if (makeAutoResetEvent) newEvent = new AutoResetEvent(false); - else + else newEvent = new ManualResetEvent(false); EnterMyLock(); if (waitEvent == null) // maybe someone snuck in. @@ -944,7 +943,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime { if (!waitEvent.WaitOne(millisecondsTimeout, false)) throw new ReaderWriterLockTimedOutException(); - + waitSuccessful = true; } finally @@ -977,18 +976,19 @@ namespace System.Runtime.InteropServices.WindowsRuntime ExitMyLock(); } - private void EnterMyLock() { + private void EnterMyLock() + { if (Interlocked.CompareExchange(ref myLock, 1, 0) != 0) EnterMyLockSpin(); } private void EnterMyLockSpin() { - for (int i = 0; ;i++) + for (int i = 0; ; i++) { if (i < 3 && Environment.ProcessorCount > 1) Thread.SpinWait(20); // Wait a few dozen instructions to let another processor release lock. - else + else Thread.Sleep(0); // Give up my quantum. if (Interlocked.CompareExchange(ref myLock, 1, 0) == 0) @@ -1000,7 +1000,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime Debug.Assert(myLock != 0, "Exiting spin lock that is not held"); myLock = 0; } - }; + }; } // @@ -1008,27 +1008,26 @@ namespace System.Runtime.InteropServices.WindowsRuntime // internal static void CallRemoveMethods(Action<EventRegistrationToken> removeMethod, List<EventRegistrationToken> tokensToRemove) { - List<Exception> exceptions = new List<Exception>(); - + foreach (EventRegistrationToken token in tokensToRemove) { try { removeMethod(token); } - catch(Exception ex) + catch (Exception ex) { exceptions.Add(ex); } - + BCLDebug.Log("INTEROP", "[WinRT_Eventing] Event unsubscribed for token = " + token.m_value + "\n"); - } + } if (exceptions.Count > 0) throw new AggregateException(exceptions.ToArray()); } - + internal static unsafe string HStringToString(IntPtr hstring) { Contract.Requires(Environment.IsWinRTSupported); @@ -1055,13 +1054,13 @@ namespace System.Runtime.InteropServices.WindowsRuntime string message = innerException.Message; if (message == null && messageResource != null) { - message = Environment.GetResourceString(messageResource); + message = SR.GetResourceString(messageResource); } e = new Exception(message, innerException); } else { - string message = (messageResource != null ? Environment.GetResourceString(messageResource) : null); + string message = (messageResource != null ? SR.GetResourceString(messageResource): null); e = new Exception(message); } @@ -1109,7 +1108,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime } private static Guid s_iidIErrorInfo = new Guid(0x1CF2B120, 0x547D, 0x101B, 0x8E, 0x65, 0x08, 0x00, 0x2B, 0x2B, 0xD1, 0x19); - + /// <summary> /// Report that an exception has occurred which went user unhandled. This allows the global error handler /// for the application to be invoked to process the error. @@ -1183,14 +1182,14 @@ namespace System.Runtime.InteropServices.WindowsRuntime // Get an IActivationFactory * for a managed type internal static IntPtr GetActivationFactoryForType(Type type) { - ManagedActivationFactory activationFactory = GetManagedActivationFactory(type); + ManagedActivationFactory activationFactory = GetManagedActivationFactory(type); return Marshal.GetComInterfaceForObject(activationFactory, typeof(IActivationFactory)); - } + } internal static ManagedActivationFactory GetManagedActivationFactory(Type type) { ManagedActivationFactory activationFactory = new ManagedActivationFactory(type); - + // If the type has any associated factory interfaces (i.e. supports non-default activation // or has statics), the CCW for this instance of ManagedActivationFactory must support them. Marshal.InitializeManagedWinRTFactoryObject(activationFactory, (RuntimeType)type); @@ -1235,7 +1234,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime public static IntPtr StringToHString(String s) { if (!Environment.IsWinRTSupported) - throw new PlatformNotSupportedException(Environment.GetResourceString("PlatformNotSupported_WinRT")); + throw new PlatformNotSupportedException(SR.PlatformNotSupported_WinRT); if (s == null) throw new ArgumentNullException(nameof(s)); @@ -1253,7 +1252,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime { if (!Environment.IsWinRTSupported) { - throw new PlatformNotSupportedException(Environment.GetResourceString("PlatformNotSupported_WinRT")); + throw new PlatformNotSupportedException(SR.PlatformNotSupported_WinRT); } return HStringToString(ptr); @@ -1262,7 +1261,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime public static void FreeHString(IntPtr ptr) { if (!Environment.IsWinRTSupported) - throw new PlatformNotSupportedException(Environment.GetResourceString("PlatformNotSupported_WinRT")); + throw new PlatformNotSupportedException(SR.PlatformNotSupported_WinRT); if (ptr != IntPtr.Zero) { diff --git a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/WindowsRuntimeMetadata.cs b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/WindowsRuntimeMetadata.cs index f097c6a0db..0f28d3b080 100644 --- a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/WindowsRuntimeMetadata.cs +++ b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/WindowsRuntimeMetadata.cs @@ -4,22 +4,22 @@ // +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Diagnostics.Contracts; +using System.Reflection; +using System.Reflection.Emit; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using System.Security; + namespace System.Runtime.InteropServices.WindowsRuntime { - using System; - using System.Collections.Generic; - using System.Collections.ObjectModel; - using System.Diagnostics.Contracts; - using System.Reflection; - using System.Reflection.Emit; - using System.Runtime.CompilerServices; - using System.Runtime.InteropServices; - using System.Security; - internal static class WindowsRuntimeMetadata { private static EventHandler<DesignerNamespaceResolveEventArgs> DesignerNamespaceResolve; - + internal static string[] OnDesignerNamespaceResolveEvent(AppDomain appDomain, string namespaceName) { EventHandler<DesignerNamespaceResolveEventArgs> eventHandler = DesignerNamespaceResolve; @@ -42,7 +42,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime { if (String.IsNullOrEmpty(assemblyFile)) { // DesignerNamespaceResolve event returned null or empty file name - that is not allowed - throw new ArgumentException(Environment.GetResourceString("Arg_EmptyOrNullString"), "DesignerNamespaceResolveEventArgs.ResolvedAssemblyFiles"); + throw new ArgumentException(SR.Arg_EmptyOrNullString, "DesignerNamespaceResolveEventArgs.ResolvedAssemblyFiles"); } retAssemblyFiles[retIndex] = assemblyFile; retIndex++; @@ -52,50 +52,11 @@ namespace System.Runtime.InteropServices.WindowsRuntime } } } - + return null; } } - -#if FEATURE_REFLECTION_ONLY_LOAD - public class NamespaceResolveEventArgs : EventArgs - { - private string _NamespaceName; - private Assembly _RequestingAssembly; - private Collection<Assembly> _ResolvedAssemblies; - - public string NamespaceName - { - get - { - return _NamespaceName; - } - } - - public Assembly RequestingAssembly - { - get - { - return _RequestingAssembly; - } - } - public Collection<Assembly> ResolvedAssemblies - { - get - { - return _ResolvedAssemblies; - } - } - - public NamespaceResolveEventArgs(string namespaceName, Assembly requestingAssembly) - { - _NamespaceName = namespaceName; - _RequestingAssembly = requestingAssembly; - _ResolvedAssemblies = new Collection<Assembly>(); - } - } -#endif //FEATURE_REFLECTION_ONLY internal class DesignerNamespaceResolveEventArgs : EventArgs { diff --git a/src/mscorlib/src/System/Runtime/Loader/AssemblyLoadContext.cs b/src/mscorlib/src/System/Runtime/Loader/AssemblyLoadContext.cs index 2be8b13274..de8137f1ec 100644 --- a/src/mscorlib/src/System/Runtime/Loader/AssemblyLoadContext.cs +++ b/src/mscorlib/src/System/Runtime/Loader/AssemblyLoadContext.cs @@ -18,19 +18,18 @@ namespace System.Runtime.Loader { public abstract class AssemblyLoadContext { - [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [SuppressUnmanagedCodeSecurity] private static extern bool CanUseAppPathAssemblyLoadContextInCurrentDomain(); - + [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [SuppressUnmanagedCodeSecurity] private static extern IntPtr InitializeAssemblyLoadContext(IntPtr ptrAssemblyLoadContext, bool fRepresentsTPALoadContext); - + [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [SuppressUnmanagedCodeSecurity] private static extern IntPtr LoadFromStream(IntPtr ptrNativeAssemblyLoadContext, IntPtr ptrAssemblyArray, int iAssemblyArrayLen, IntPtr ptrSymbols, int iSymbolArrayLen, ObjectHandleOnStack retAssembly); - + [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [SuppressUnmanagedCodeSecurity] internal static extern void InternalSetProfileRoot(string directoryPath); @@ -50,8 +49,8 @@ namespace System.Runtime.Loader // Initialize the ALC representing TPA LoadContext InitializeLoadContext(fRepresentsTPALoadContext); } - - void InitializeLoadContext(bool fRepresentsTPALoadContext) + + private void InitializeLoadContext(bool fRepresentsTPALoadContext) { // Initialize the VM side of AssemblyLoadContext if not already done. GCHandle gchALC = GCHandle.Alloc(this); @@ -75,14 +74,14 @@ namespace System.Runtime.Loader [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. public Assembly LoadFromAssemblyPath(string assemblyPath) @@ -94,14 +93,14 @@ namespace System.Runtime.Loader if (PathInternal.IsPartiallyQualified(assemblyPath)) { - throw new ArgumentException( Environment.GetResourceString("Argument_AbsolutePathRequired"), nameof(assemblyPath)); + throw new ArgumentException(SR.Argument_AbsolutePathRequired, nameof(assemblyPath)); } RuntimeAssembly loadedAssembly = null; LoadFromPath(m_pNativeAssemblyLoadContext, assemblyPath, null, JitHelpers.GetObjectHandleOnStack(ref loadedAssembly)); return loadedAssembly; } - + public Assembly LoadFromNativeImagePath(string nativeImagePath, string assemblyPath) { if (nativeImagePath == null) @@ -111,12 +110,12 @@ namespace System.Runtime.Loader if (PathInternal.IsPartiallyQualified(nativeImagePath)) { - throw new ArgumentException( Environment.GetResourceString("Argument_AbsolutePathRequired"), nameof(nativeImagePath)); + throw new ArgumentException(SR.Argument_AbsolutePathRequired, nameof(nativeImagePath)); } if (assemblyPath != null && PathInternal.IsPartiallyQualified(assemblyPath)) { - throw new ArgumentException(Environment.GetResourceString("Argument_AbsolutePathRequired"), nameof(assemblyPath)); + throw new ArgumentException(SR.Argument_AbsolutePathRequired, nameof(assemblyPath)); } // Basic validation has succeeded - lets try to load the NI image. @@ -125,74 +124,79 @@ namespace System.Runtime.Loader LoadFromPath(m_pNativeAssemblyLoadContext, assemblyPath, nativeImagePath, JitHelpers.GetObjectHandleOnStack(ref loadedAssembly)); return loadedAssembly; } - + public Assembly LoadFromStream(Stream assembly) { return LoadFromStream(assembly, null); } - + public Assembly LoadFromStream(Stream assembly, Stream assemblySymbols) { if (assembly == null) { throw new ArgumentNullException(nameof(assembly)); } - + + if (assembly.Length <= 0) + { + throw new BadImageFormatException(SR.BadImageFormat_BadILFormat); + } + int iAssemblyStreamLength = (int)assembly.Length; int iSymbolLength = 0; - + // Allocate the byte[] to hold the assembly byte[] arrAssembly = new byte[iAssemblyStreamLength]; - + // Copy the assembly to the byte array assembly.Read(arrAssembly, 0, iAssemblyStreamLength); - + // Get the symbol stream in byte[] if provided byte[] arrSymbols = null; if (assemblySymbols != null) { iSymbolLength = (int)assemblySymbols.Length; arrSymbols = new byte[iSymbolLength]; - + assemblySymbols.Read(arrSymbols, 0, iSymbolLength); } - + RuntimeAssembly loadedAssembly = null; - unsafe + unsafe { - fixed(byte *ptrAssembly = arrAssembly, ptrSymbols = arrSymbols) + fixed (byte* ptrAssembly = arrAssembly, ptrSymbols = arrSymbols) { LoadFromStream(m_pNativeAssemblyLoadContext, new IntPtr(ptrAssembly), iAssemblyStreamLength, new IntPtr(ptrSymbols), iSymbolLength, JitHelpers.GetObjectHandleOnStack(ref loadedAssembly)); } } - + return loadedAssembly; } - + // Custom AssemblyLoadContext implementations can override this // method to perform custom processing and use one of the protected // helpers above to load the assembly. protected abstract Assembly Load(AssemblyName assemblyName); - + // This method is invoked by the VM when using the host-provided assembly load context // implementation. private static Assembly Resolve(IntPtr gchManagedAssemblyLoadContext, AssemblyName assemblyName) { AssemblyLoadContext context = (AssemblyLoadContext)(GCHandle.FromIntPtr(gchManagedAssemblyLoadContext).Target); - + return context.ResolveUsingLoad(assemblyName); } - + // This method is invoked by the VM to resolve an assembly reference using the Resolving event // after trying assembly resolution via Load override and TPA load context without success. private static Assembly ResolveUsingResolvingEvent(IntPtr gchManagedAssemblyLoadContext, AssemblyName assemblyName) { AssemblyLoadContext context = (AssemblyLoadContext)(GCHandle.FromIntPtr(gchManagedAssemblyLoadContext).Target); - + // Invoke the AssemblyResolve event callbacks if wired up return context.ResolveUsingEvent(assemblyName); } - + private Assembly GetFirstResolvedAssembly(AssemblyName assemblyName) { Assembly resolvedAssembly = null; @@ -202,8 +206,8 @@ namespace System.Runtime.Loader if (assemblyResolveHandler != null) { // Loop through the event subscribers and return the first non-null Assembly instance - Delegate [] arrSubscribers = assemblyResolveHandler.GetInvocationList(); - for(int i = 0; i < arrSubscribers.Length; i++) + Delegate[] arrSubscribers = assemblyResolveHandler.GetInvocationList(); + for (int i = 0; i < arrSubscribers.Length; i++) { resolvedAssembly = ((Func<AssemblyLoadContext, AssemblyName, Assembly>)arrSubscribers[i])(this, assemblyName); if (resolvedAssembly != null) @@ -212,7 +216,7 @@ namespace System.Runtime.Loader } } } - + return resolvedAssembly; } @@ -220,7 +224,7 @@ namespace System.Runtime.Loader { // Get the name of the loaded assembly string loadedSimpleName = null; - + // Derived type's Load implementation is expected to use one of the LoadFrom* methods to get the assembly // which is a RuntimeAssembly instance. However, since Assembly type can be used build any other artifact (e.g. AssemblyBuilder), // we need to check for RuntimeAssembly. @@ -229,49 +233,48 @@ namespace System.Runtime.Loader { loadedSimpleName = rtLoadedAssembly.GetSimpleName(); } - + // The simple names should match at the very least if (String.IsNullOrEmpty(loadedSimpleName) || (!requestedSimpleName.Equals(loadedSimpleName, StringComparison.InvariantCultureIgnoreCase))) - throw new InvalidOperationException(Environment.GetResourceString("Argument_CustomAssemblyLoadContextRequestedNameMismatch")); - + throw new InvalidOperationException(SR.Argument_CustomAssemblyLoadContextRequestedNameMismatch); + return assembly; - } - + private Assembly ResolveUsingLoad(AssemblyName assemblyName) { string simpleName = assemblyName.Name; Assembly assembly = Load(assemblyName); - + if (assembly != null) { assembly = ValidateAssemblyNameWithSimpleName(assembly, simpleName); } - + return assembly; } - + private Assembly ResolveUsingEvent(AssemblyName assemblyName) { string simpleName = assemblyName.Name; - + // Invoke the AssemblyResolve event callbacks if wired up Assembly assembly = GetFirstResolvedAssembly(assemblyName); if (assembly != null) { assembly = ValidateAssemblyNameWithSimpleName(assembly, simpleName); } - + // Since attempt to resolve the assembly via Resolving event is the last option, // throw an exception if we do not find any assembly. if (assembly == null) { - throw new FileNotFoundException(Environment.GetResourceString("IO.FileLoad"), simpleName); + throw new FileNotFoundException(SR.IO_FileLoad, simpleName); } - + return assembly; } - + public Assembly LoadFromAssemblyName(AssemblyName assemblyName) { // Attempt to load the assembly, using the same ordering as static load, in the current load context. @@ -294,23 +297,23 @@ namespace System.Runtime.Loader } if (unmanagedDllPath.Length == 0) { - throw new ArgumentException(Environment.GetResourceString("Argument_EmptyPath"), nameof(unmanagedDllPath)); + throw new ArgumentException(SR.Argument_EmptyPath, nameof(unmanagedDllPath)); } if (PathInternal.IsPartiallyQualified(unmanagedDllPath)) { - throw new ArgumentException(Environment.GetResourceString("Argument_AbsolutePathRequired"), nameof(unmanagedDllPath)); + throw new ArgumentException(SR.Argument_AbsolutePathRequired, nameof(unmanagedDllPath)); } return InternalLoadUnmanagedDllFromPath(unmanagedDllPath); } - + // Custom AssemblyLoadContext implementations can override this // method to perform the load of unmanaged native dll // This function needs to return the HMODULE of the dll it loads protected virtual IntPtr LoadUnmanagedDll(String unmanagedDllName) { //defer to default coreclr policy of loading unmanaged dll - return IntPtr.Zero; + return IntPtr.Zero; } // This method is invoked by the VM when using the host-provided assembly load context @@ -331,7 +334,7 @@ namespace System.Runtime.Loader if (AssemblyLoadContext.CanUseAppPathAssemblyLoadContextInCurrentDomain()) { // Synchronize access to initializing Default ALC - lock(s_initLock) + lock (s_initLock) { if (s_DefaultAssemblyLoadContext == null) { @@ -340,16 +343,11 @@ namespace System.Runtime.Loader } } } - + return s_DefaultAssemblyLoadContext; } } - - // This call opens and closes the file, but does not add the - // assembly to the domain. - [MethodImplAttribute(MethodImplOptions.InternalCall)] - static internal extern AssemblyName nGetFileInformation(String s); - + // Helper to return AssemblyName corresponding to the path of an IL assembly public static AssemblyName GetAssemblyName(string assemblyPath) { @@ -358,14 +356,13 @@ namespace System.Runtime.Loader throw new ArgumentNullException(nameof(assemblyPath)); } - string fullPath = Path.GetFullPath(assemblyPath); - return nGetFileInformation(fullPath); + return AssemblyName.GetAssemblyName(assemblyPath); } - + [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [SuppressUnmanagedCodeSecurity] private static extern IntPtr GetLoadContextForAssembly(RuntimeAssembly assembly); - + // Returns the load context in which the specified assembly has been loaded public static AssemblyLoadContext GetLoadContext(Assembly assembly) { @@ -373,11 +370,11 @@ namespace System.Runtime.Loader { throw new ArgumentNullException(nameof(assembly)); } - + AssemblyLoadContext loadContextForAssembly = null; RuntimeAssembly rtAsm = assembly as RuntimeAssembly; - + // We only support looking up load context for runtime assemblies. if (rtAsm != null) { @@ -397,7 +394,7 @@ namespace System.Runtime.Loader return loadContextForAssembly; } - + // Set the root directory path for profile optimization. public void SetProfileOptimizationRoot(string directoryPath) { @@ -424,7 +421,7 @@ namespace System.Runtime.Loader // Contains the reference to VM's representation of the AssemblyLoadContext private IntPtr m_pNativeAssemblyLoadContext; - + // Each AppDomain contains the reference to its AssemblyLoadContext instance, if one is // specified by the host. By having the field as a static, we are // making it an AppDomain-wide field. @@ -434,36 +431,36 @@ namespace System.Runtime.Loader 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; } + 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; } + 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; } - } + 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; } + add { AppDomain.CurrentDomain.AssemblyResolve += value; } + remove { AppDomain.CurrentDomain.AssemblyResolve -= value; } } } - class AppPathAssemblyLoadContext : AssemblyLoadContext + internal class AppPathAssemblyLoadContext : AssemblyLoadContext { internal AppPathAssemblyLoadContext() : base(true) { diff --git a/src/mscorlib/src/System/Runtime/MemoryFailPoint.cs b/src/mscorlib/src/System/Runtime/MemoryFailPoint.cs index 84b8ba9e1e..f9f87bc928 100644 --- a/src/mscorlib/src/System/Runtime/MemoryFailPoint.cs +++ b/src/mscorlib/src/System/Runtime/MemoryFailPoint.cs @@ -139,7 +139,7 @@ namespace System.Runtime // count of "reserved" memory, and decrement this in Dispose and // in the critical finalizer. See // SharedStatics.MemoryFailPointReservedMemory - + private ulong _reservedMemory; // The size of this request (from user) private bool _mustSubtractReservation; // Did we add data to SharedStatics? @@ -155,7 +155,7 @@ namespace System.Runtime public MemoryFailPoint(int sizeInMegabytes) { if (sizeInMegabytes <= 0) - throw new ArgumentOutOfRangeException(nameof(sizeInMegabytes), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); + throw new ArgumentOutOfRangeException(nameof(sizeInMegabytes), SR.ArgumentOutOfRange_NeedNonNegNum); Contract.EndContractBlock(); #if !FEATURE_PAL // Remove this when CheckForAvailableMemory is able to provide legitimate estimates @@ -168,9 +168,9 @@ namespace System.Runtime // size, not the amount of memory the user wants to allocate. // Consider correcting this to reflect free memory within the GC // heap, and to check both the normal & large object heaps. - ulong segmentSize = (ulong) (Math.Ceiling((double)size / GCSegmentSize) * GCSegmentSize); + ulong segmentSize = (ulong)(Math.Ceiling((double)size / GCSegmentSize) * GCSegmentSize); if (segmentSize >= TopOfMemory) - throw new InsufficientMemoryException(Environment.GetResourceString("InsufficientMemory_MemFailPoint_TooBig")); + throw new InsufficientMemoryException(SR.InsufficientMemory_MemFailPoint_TooBig); ulong requestedSizeRounded = (ulong)(Math.Ceiling((double)sizeInMegabytes / MemoryCheckGranularity) * MemoryCheckGranularity); //re-convert into bytes @@ -191,7 +191,8 @@ namespace System.Runtime // GC.WaitForPendingFinalizers, noting that this method uses a CER // so it can't be aborted, and we have a critical finalizer. It // would probably work, but do some thinking first.) - for(int stage = 0; stage < 3; stage++) { + for (int stage = 0; stage < 3; stage++) + { CheckForAvailableMemory(out availPageFile, out totalAddressSpaceFree); // If we have enough room, then skip some stages. @@ -206,99 +207,109 @@ namespace System.Runtime // Ensure our cached amount of free address space is not stale. long now = Environment.TickCount; // Handle wraparound. if ((now > LastTimeCheckingAddressSpace + CheckThreshold || now < LastTimeCheckingAddressSpace) || - LastKnownFreeAddressSpace < (long) segmentSize) { + LastKnownFreeAddressSpace < (long)segmentSize) + { CheckForFreeAddressSpace(segmentSize, false); } - bool needContiguousVASpace = (ulong) LastKnownFreeAddressSpace < segmentSize; + bool needContiguousVASpace = (ulong)LastKnownFreeAddressSpace < segmentSize; BCLDebug.Trace("MEMORYFAILPOINT", "MemoryFailPoint: Checking for {0} MB, for allocation size of {1} MB, stage {9}. Need page file? {2} Need Address Space? {3} Need Contiguous address space? {4} Avail page file: {5} MB Total free VA space: {6} MB Contiguous free address space (found): {7} MB Space reserved via process's MemoryFailPoints: {8} MB", - segmentSize >> 20, sizeInMegabytes, needPageFile, - needAddressSpace, needContiguousVASpace, - availPageFile >> 20, totalAddressSpaceFree >> 20, + segmentSize >> 20, sizeInMegabytes, needPageFile, + needAddressSpace, needContiguousVASpace, + availPageFile >> 20, totalAddressSpaceFree >> 20, LastKnownFreeAddressSpace >> 20, reserved, stage); if (!needPageFile && !needAddressSpace && !needContiguousVASpace) break; - switch(stage) { - case 0: - // The GC will release empty segments to the OS. This will - // relieve us from having to guess whether there's - // enough memory in either GC heap, and whether - // internal fragmentation will prevent those - // allocations from succeeding. - GC.Collect(); - continue; - - case 1: - // Do this step if and only if the page file is too small. - if (!needPageFile) + switch (stage) + { + case 0: + // The GC will release empty segments to the OS. This will + // relieve us from having to guess whether there's + // enough memory in either GC heap, and whether + // internal fragmentation will prevent those + // allocations from succeeding. + GC.Collect(); continue; - // Attempt to grow the OS's page file. Note that we ignore - // any allocation routines from the host intentionally. - RuntimeHelpers.PrepareConstrainedRegions(); - try { - } - finally { - // This shouldn't overflow due to the if clauses above. - UIntPtr numBytes = new UIntPtr(segmentSize); - unsafe { - void * pMemory = Win32Native.VirtualAlloc(null, numBytes, Win32Native.MEM_COMMIT, Win32Native.PAGE_READWRITE); - if (pMemory != null) { - bool r = Win32Native.VirtualFree(pMemory, UIntPtr.Zero, Win32Native.MEM_RELEASE); - if (!r) - __Error.WinIOError(); + case 1: + // Do this step if and only if the page file is too small. + if (!needPageFile) + continue; + + // Attempt to grow the OS's page file. Note that we ignore + // any allocation routines from the host intentionally. + RuntimeHelpers.PrepareConstrainedRegions(); + try + { + } + finally + { + // This shouldn't overflow due to the if clauses above. + UIntPtr numBytes = new UIntPtr(segmentSize); + unsafe + { + void* pMemory = Win32Native.VirtualAlloc(null, numBytes, Win32Native.MEM_COMMIT, Win32Native.PAGE_READWRITE); + if (pMemory != null) + { + bool r = Win32Native.VirtualFree(pMemory, UIntPtr.Zero, Win32Native.MEM_RELEASE); + if (!r) + __Error.WinIOError(); + } } } - } - continue; - - case 2: - // The call to CheckForAvailableMemory above updated our - // state. - if (needPageFile || needAddressSpace) { - InsufficientMemoryException e = new InsufficientMemoryException(Environment.GetResourceString("InsufficientMemory_MemFailPoint")); + continue; + + case 2: + // The call to CheckForAvailableMemory above updated our + // state. + if (needPageFile || needAddressSpace) + { + InsufficientMemoryException e = new InsufficientMemoryException(SR.InsufficientMemory_MemFailPoint); #if _DEBUG - e.Data["MemFailPointState"] = new MemoryFailPointState(sizeInMegabytes, segmentSize, - needPageFile, needAddressSpace, needContiguousVASpace, - availPageFile >> 20, totalAddressSpaceFree >> 20, - LastKnownFreeAddressSpace >> 20, reserved); + e.Data["MemFailPointState"] = new MemoryFailPointState(sizeInMegabytes, segmentSize, + needPageFile, needAddressSpace, needContiguousVASpace, + availPageFile >> 20, totalAddressSpaceFree >> 20, + LastKnownFreeAddressSpace >> 20, reserved); #endif - throw e; - } + throw e; + } - if (needContiguousVASpace) { - InsufficientMemoryException e = new InsufficientMemoryException(Environment.GetResourceString("InsufficientMemory_MemFailPoint_VAFrag")); + if (needContiguousVASpace) + { + InsufficientMemoryException e = new InsufficientMemoryException(SR.InsufficientMemory_MemFailPoint_VAFrag); #if _DEBUG - e.Data["MemFailPointState"] = new MemoryFailPointState(sizeInMegabytes, segmentSize, - needPageFile, needAddressSpace, needContiguousVASpace, - availPageFile >> 20, totalAddressSpaceFree >> 20, - LastKnownFreeAddressSpace >> 20, reserved); + e.Data["MemFailPointState"] = new MemoryFailPointState(sizeInMegabytes, segmentSize, + needPageFile, needAddressSpace, needContiguousVASpace, + availPageFile >> 20, totalAddressSpaceFree >> 20, + LastKnownFreeAddressSpace >> 20, reserved); #endif - throw e; - } + throw e; + } - break; + break; - default: - Debug.Assert(false, "Fell through switch statement!"); - break; + default: + Debug.Assert(false, "Fell through switch statement!"); + break; } } // Success - we have enough room the last time we checked. // Now update our shared state in a somewhat atomic fashion // and handle a simple race condition with other MemoryFailPoint instances. - AddToLastKnownFreeAddressSpace(-((long) size)); + AddToLastKnownFreeAddressSpace(-((long)size)); if (LastKnownFreeAddressSpace < 0) CheckForFreeAddressSpace(segmentSize, true); - + RuntimeHelpers.PrepareConstrainedRegions(); - try { + try + { } - finally { - SharedStatics.AddMemoryFailPointReservation((long) size); + finally + { + SharedStatics.AddMemoryFailPointReservation((long)size); _mustSubtractReservation = true; } #endif @@ -334,11 +345,11 @@ namespace System.Runtime // this will hurt, as long as we never increment this number in // the Dispose method. If we do an extra bit of checking every // once in a while, but we avoid taking a lock, we may win. - LastKnownFreeAddressSpace = (long) freeSpaceAfterGCHeap; + LastKnownFreeAddressSpace = (long)freeSpaceAfterGCHeap; LastTimeCheckingAddressSpace = Environment.TickCount; if (freeSpaceAfterGCHeap < size && shouldThrow) - throw new InsufficientMemoryException(Environment.GetResourceString("InsufficientMemory_MemFailPoint_VAFrag")); + throw new InsufficientMemoryException(SR.InsufficientMemory_MemFailPoint_VAFrag); return freeSpaceAfterGCHeap >= size; } @@ -346,28 +357,30 @@ 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. - private static unsafe ulong MemFreeAfterAddress(void * address, ulong size) + private static unsafe ulong MemFreeAfterAddress(void* address, ulong size) { if (size >= TopOfMemory) return 0; ulong largestFreeRegion = 0; Win32Native.MEMORY_BASIC_INFORMATION memInfo = new Win32Native.MEMORY_BASIC_INFORMATION(); - UIntPtr sizeOfMemInfo = (UIntPtr) Marshal.SizeOf(memInfo); - - while (((ulong)address) + size < TopOfMemory) { + UIntPtr sizeOfMemInfo = (UIntPtr)Marshal.SizeOf(memInfo); + + while (((ulong)address) + size < TopOfMemory) + { UIntPtr r = Win32Native.VirtualQuery(address, ref memInfo, sizeOfMemInfo); if (r == UIntPtr.Zero) __Error.WinIOError(); ulong regionSize = memInfo.RegionSize.ToUInt64(); - if (memInfo.State == Win32Native.MEM_FREE) { + if (memInfo.State == Win32Native.MEM_FREE) + { if (regionSize >= size) return regionSize; else largestFreeRegion = Math.Max(largestFreeRegion, regionSize); } - address = (void *) ((ulong) address + regionSize); + address = (void*)((ulong)address + regionSize); } return largestFreeRegion; } @@ -398,11 +411,14 @@ namespace System.Runtime // This is just bookkeeping to ensure multiple threads can really // get enough memory, and this does not actually reserve memory // within the GC heap. - if (_mustSubtractReservation) { + if (_mustSubtractReservation) + { RuntimeHelpers.PrepareConstrainedRegions(); - try { + try + { } - finally { + finally + { SharedStatics.AddMemoryFailPointReservation(-((long)_reservedMemory)); _mustSubtractReservation = false; } @@ -465,9 +481,9 @@ namespace System.Runtime public override String ToString() { return String.Format(System.Globalization.CultureInfo.InvariantCulture, "MemoryFailPoint detected insufficient memory to guarantee an operation could complete. Checked for {0} MB, for allocation size of {1} MB. Need page file? {2} Need Address Space? {3} Need Contiguous address space? {4} Avail page file: {5} MB Total free VA space: {6} MB Contiguous free address space (found): {7} MB Space reserved by process's MemoryFailPoints: {8} MB", - _segmentSize >> 20, _allocationSizeInMB, _needPageFile, - _needAddressSpace, _needContiguousVASpace, - _availPageFile >> 20, _totalFreeAddressSpace >> 20, + _segmentSize >> 20, _allocationSizeInMB, _needPageFile, + _needAddressSpace, _needContiguousVASpace, + _availPageFile >> 20, _totalFreeAddressSpace >> 20, _lastKnownFreeAddressSpace >> 20, _reservedMem); } } diff --git a/src/mscorlib/src/System/Runtime/Reliability/PrePrepareMethodAttribute.cs b/src/mscorlib/src/System/Runtime/Reliability/PrePrepareMethodAttribute.cs index 67c934d034..6594562b97 100644 --- a/src/mscorlib/src/System/Runtime/Reliability/PrePrepareMethodAttribute.cs +++ b/src/mscorlib/src/System/Runtime/Reliability/PrePrepareMethodAttribute.cs @@ -16,11 +16,12 @@ ** ** ===========================================================*/ + +using System; +using System.Runtime.InteropServices; + namespace System.Runtime.ConstrainedExecution { - using System; - using System.Runtime.InteropServices; - [AttributeUsage(AttributeTargets.Constructor | AttributeTargets.Method, Inherited = false)] internal sealed class PrePrepareMethodAttribute : Attribute diff --git a/src/mscorlib/src/System/Runtime/Reliability/ReliabilityContractAttribute.cs b/src/mscorlib/src/System/Runtime/Reliability/ReliabilityContractAttribute.cs deleted file mode 100644 index 4a14e5733c..0000000000 --- a/src/mscorlib/src/System/Runtime/Reliability/ReliabilityContractAttribute.cs +++ /dev/null @@ -1,67 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -// -/*============================================================ -** -** -** -** Purpose: Defines a publically documentable contract for -** reliability between a method and its callers, expressing -** what state will remain consistent in the presence of -** failures (ie async exceptions like thread abort) and whether -** the method needs to be called from within a CER. -** -** -===========================================================*/ - -namespace System.Runtime.ConstrainedExecution { - using System.Runtime.InteropServices; - using System; - - // ************************************************************************************************************************** - // - // Note that if you change either of the enums below or the constructors, fields or properties of the custom attribute itself - // you must also change the logic and definitions in vm\ConstrainedExecutionRegion.cpp to match. - // - // ************************************************************************************************************************** - - [Serializable] - public enum Consistency : int - { - MayCorruptProcess = 0, - MayCorruptAppDomain = 1, - MayCorruptInstance = 2, - WillNotCorruptState = 3, - } - - [Serializable] - public enum Cer : int - { - None = 0, - MayFail = 1, // Might fail, but the method will say it failed - Success = 2, - } - - [AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Constructor | AttributeTargets.Method | AttributeTargets.Interface /* | AttributeTargets.Delegate*/, Inherited = false)] - public sealed class ReliabilityContractAttribute : Attribute - { - private Consistency _consistency; - private Cer _cer; - - public ReliabilityContractAttribute(Consistency consistencyGuarantee, Cer cer) - { - _consistency = consistencyGuarantee; - _cer = cer; - } - - public Consistency ConsistencyGuarantee { - get { return _consistency; } - } - - public Cer Cer { - get { return _cer; } - } - } -} diff --git a/src/mscorlib/src/System/Runtime/Remoting/ObjectHandle.cs b/src/mscorlib/src/System/Runtime/Remoting/ObjectHandle.cs index ed3444e15d..e76882d6df 100644 --- a/src/mscorlib/src/System/Runtime/Remoting/ObjectHandle.cs +++ b/src/mscorlib/src/System/Runtime/Remoting/ObjectHandle.cs @@ -14,15 +14,15 @@ ** ===========================================================*/ +using System; +using System.Runtime.InteropServices; + namespace System.Runtime.Remoting { - using System; - using System.Runtime.InteropServices; - - public class ObjectHandle + public class ObjectHandle { private Object WrappedObject; - + private ObjectHandle() { } diff --git a/src/mscorlib/src/System/Runtime/RuntimeImports.cs b/src/mscorlib/src/System/Runtime/RuntimeImports.cs new file mode 100644 index 0000000000..16d41d3951 --- /dev/null +++ b/src/mscorlib/src/System/Runtime/RuntimeImports.cs @@ -0,0 +1,35 @@ +// Licensed to the .NET Foundation under one or more 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; +using System.Runtime.InteropServices; + +#if BIT64 +using nuint = System.UInt64; +#else + using nuint = System.UInt32; +#endif + +namespace System.Runtime +{ + public class RuntimeImports + { + // Non-inlinable wrapper around the QCall that avoids poluting the fast path + // with P/Invoke prolog/epilog. + [MethodImpl(MethodImplOptions.NoInlining)] + internal unsafe static void RhZeroMemory(ref byte b, nuint byteLength) + { + fixed (byte* bytePointer = &b) + { + RhZeroMemory(bytePointer, byteLength); + } + } + + [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] + extern private unsafe static void RhZeroMemory(byte* b, nuint byteLength); + + [MethodImpl(MethodImplOptions.InternalCall)] + internal extern unsafe static void RhBulkMoveWithWriteBarrier(ref byte destination, ref byte source, nuint byteCount); + } +} diff --git a/src/mscorlib/src/System/Runtime/Serialization/FormatterConverter.cs b/src/mscorlib/src/System/Runtime/Serialization/FormatterConverter.cs index 27f7ecf9d2..52e748db89 100644 --- a/src/mscorlib/src/System/Runtime/Serialization/FormatterConverter.cs +++ b/src/mscorlib/src/System/Runtime/Serialization/FormatterConverter.cs @@ -12,42 +12,53 @@ ** ** ============================================================*/ -namespace System.Runtime.Serialization { - using System; - using System.Globalization; - using System.Diagnostics.Contracts; - internal class FormatterConverter : IFormatterConverter { +using System; +using System.Globalization; +using System.Diagnostics.Contracts; - public FormatterConverter() { +namespace System.Runtime.Serialization +{ + internal class FormatterConverter : IFormatterConverter + { + public FormatterConverter() + { } - public Object Convert(Object value, Type type) { - if (value==null) { + public Object Convert(Object value, Type type) + { + if (value == null) + { throw new ArgumentNullException(nameof(value)); } Contract.EndContractBlock(); return System.Convert.ChangeType(value, type, CultureInfo.InvariantCulture); } - public Object Convert(Object value, TypeCode typeCode) { - if (value==null) { + public Object Convert(Object value, TypeCode typeCode) + { + if (value == null) + { throw new ArgumentNullException(nameof(value)); } Contract.EndContractBlock(); return System.Convert.ChangeType(value, typeCode, CultureInfo.InvariantCulture); } - public bool ToBoolean(Object value) { - if (value==null) { + public bool ToBoolean(Object value) + { + if (value == null) + { throw new ArgumentNullException(nameof(value)); } Contract.EndContractBlock(); return System.Convert.ToBoolean(value, CultureInfo.InvariantCulture); } - public char ToChar(Object value) { - if (value==null) { + public char ToChar(Object value) + { + if (value == null) + { throw new ArgumentNullException(nameof(value)); } Contract.EndContractBlock(); @@ -55,24 +66,30 @@ namespace System.Runtime.Serialization { } [CLSCompliant(false)] - public sbyte ToSByte(Object value) { - if (value==null) { + public sbyte ToSByte(Object value) + { + if (value == null) + { throw new ArgumentNullException(nameof(value)); } Contract.EndContractBlock(); return System.Convert.ToSByte(value, CultureInfo.InvariantCulture); } - public byte ToByte(Object value) { - if (value==null) { + public byte ToByte(Object value) + { + if (value == null) + { throw new ArgumentNullException(nameof(value)); } Contract.EndContractBlock(); return System.Convert.ToByte(value, CultureInfo.InvariantCulture); } - public short ToInt16(Object value) { - if (value==null) { + public short ToInt16(Object value) + { + if (value == null) + { throw new ArgumentNullException(nameof(value)); } Contract.EndContractBlock(); @@ -80,16 +97,20 @@ namespace System.Runtime.Serialization { } [CLSCompliant(false)] - public ushort ToUInt16(Object value) { - if (value==null) { + public ushort ToUInt16(Object value) + { + if (value == null) + { throw new ArgumentNullException(nameof(value)); } Contract.EndContractBlock(); return System.Convert.ToUInt16(value, CultureInfo.InvariantCulture); } - public int ToInt32(Object value) { - if (value==null) { + public int ToInt32(Object value) + { + if (value == null) + { throw new ArgumentNullException(nameof(value)); } Contract.EndContractBlock(); @@ -97,16 +118,20 @@ namespace System.Runtime.Serialization { } [CLSCompliant(false)] - public uint ToUInt32(Object value) { - if (value==null) { + public uint ToUInt32(Object value) + { + if (value == null) + { throw new ArgumentNullException(nameof(value)); } Contract.EndContractBlock(); return System.Convert.ToUInt32(value, CultureInfo.InvariantCulture); } - public long ToInt64(Object value) { - if (value==null) { + public long ToInt64(Object value) + { + if (value == null) + { throw new ArgumentNullException(nameof(value)); } Contract.EndContractBlock(); @@ -114,48 +139,60 @@ namespace System.Runtime.Serialization { } [CLSCompliant(false)] - public ulong ToUInt64(Object value) { - if (value==null) { + public ulong ToUInt64(Object value) + { + if (value == null) + { throw new ArgumentNullException(nameof(value)); } Contract.EndContractBlock(); return System.Convert.ToUInt64(value, CultureInfo.InvariantCulture); - } + } - public float ToSingle(Object value) { - if (value==null) { + public float ToSingle(Object value) + { + if (value == null) + { throw new ArgumentNullException(nameof(value)); } Contract.EndContractBlock(); return System.Convert.ToSingle(value, CultureInfo.InvariantCulture); } - public double ToDouble(Object value) { - if (value==null) { + public double ToDouble(Object value) + { + if (value == null) + { throw new ArgumentNullException(nameof(value)); } Contract.EndContractBlock(); return System.Convert.ToDouble(value, CultureInfo.InvariantCulture); } - public Decimal ToDecimal(Object value) { - if (value==null) { + public Decimal ToDecimal(Object value) + { + if (value == null) + { throw new ArgumentNullException(nameof(value)); } Contract.EndContractBlock(); return System.Convert.ToDecimal(value, CultureInfo.InvariantCulture); } - public DateTime ToDateTime(Object value) { - if (value==null) { + public DateTime ToDateTime(Object value) + { + if (value == null) + { throw new ArgumentNullException(nameof(value)); } Contract.EndContractBlock(); return System.Convert.ToDateTime(value, CultureInfo.InvariantCulture); } - public String ToString(Object value) { - if (value==null) { + public String ToString(Object value) + { + if (value == null) + { throw new ArgumentNullException(nameof(value)); } Contract.EndContractBlock(); @@ -163,4 +200,4 @@ namespace System.Runtime.Serialization { } } } - + diff --git a/src/mscorlib/src/System/Runtime/Serialization/FormatterServices.cs b/src/mscorlib/src/System/Runtime/Serialization/FormatterServices.cs index c3f9eb4452..18139324a3 100644 --- a/src/mscorlib/src/System/Runtime/Serialization/FormatterServices.cs +++ b/src/mscorlib/src/System/Runtime/Serialization/FormatterServices.cs @@ -11,25 +11,28 @@ ** ** ============================================================*/ -namespace System.Runtime.Serialization { - - using System; - using System.Reflection; - using System.Collections; - using System.Collections.Generic; - using System.Security; - using System.Runtime.Remoting; - using System.Runtime.CompilerServices; - using System.Runtime.Versioning; - using System.Threading; - using System.IO; - using System.Text; - using System.Globalization; - using System.Diagnostics; - using System.Diagnostics.Contracts; - public static class FormatterServices { - +using System; +using System.Reflection; +using System.Collections; +using System.Collections.Generic; +using System.Security; +using System.Runtime.Remoting; +using System.Runtime.CompilerServices; +using System.Runtime.Versioning; +using System.Threading; +using System.IO; +using System.Text; +using System.Globalization; +using System.Diagnostics; +using System.Diagnostics.Contracts; + +namespace System.Runtime.Serialization +{ + // This class duplicates a class on CoreFX. We are keeping it here -- just this one method -- + // as it was widely invoked by reflection to workaround it being missing in .NET Core 1.0 + internal static class FormatterServices + { // Gets a new instance of the object. The entire object is initalized to 0 and no // constructors have been run. **THIS MEANS THAT THE OBJECT MAY NOT BE IN A STATE // CONSISTENT WITH ITS INTERNAL REQUIREMENTS** This method should only be used for @@ -37,42 +40,24 @@ namespace System.Runtime.Serialization { // will not create an unitialized string because it is non-sensical to create an empty // instance of an immutable type. // - public static Object GetUninitializedObject(Type type) { - if ((object)type == null) { + public static Object GetUninitializedObject(Type type) + { + if ((object)type == null) + { throw new ArgumentNullException(nameof(type)); } Contract.EndContractBlock(); - - if (!(type is RuntimeType)) { - throw new SerializationException(Environment.GetResourceString("Serialization_InvalidType", type.ToString())); + + if (!(type is RuntimeType)) + { + throw new SerializationException(SR.Format(SR.Serialization_InvalidType, type.ToString())); } return nativeGetUninitializedObject((RuntimeType)type); } - + [MethodImplAttribute(MethodImplOptions.InternalCall)] private static extern Object nativeGetUninitializedObject(RuntimeType type); - private static Binder s_binder = Type.DefaultBinder; - - /*============================LoadAssemblyFromString============================ - **Action: Loads an assembly from a given string. The current assembly loading story - ** is quite confusing. If the assembly is in the fusion cache, we can load it - ** using the stringized-name which we transmitted over the wire. If that fails, - ** we try for a lookup of the assembly using the simple name which is the first - ** part of the assembly name. If we can't find it that way, we'll return null - ** as our failure result. - **Returns: The loaded assembly or null if it can't be found. - **Arguments: assemblyName -- The stringized assembly name. - **Exceptions: None - ==============================================================================*/ - internal static Assembly LoadAssemblyFromString(String assemblyName) { - // - // Try using the stringized assembly name to load from the fusion cache. - // - BCLDebug.Trace("SER", "[LoadAssemblyFromString]Looking for assembly: ", assemblyName); - Assembly found = Assembly.Load(assemblyName); - return found; - } } } diff --git a/src/mscorlib/src/System/Runtime/Serialization/IDeserializationCallback.cs b/src/mscorlib/src/System/Runtime/Serialization/IDeserializationCallback.cs deleted file mode 100644 index 2911a4016e..0000000000 --- a/src/mscorlib/src/System/Runtime/Serialization/IDeserializationCallback.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. - -/*============================================================ -** -** Interface: IDeserializationEventListener -** -** -** Purpose: Implemented by any class that wants to indicate that -** it wishes to receive deserialization events. -** -** -===========================================================*/ -namespace System.Runtime.Serialization { - using System; - - // Interface does not need to be marked with the serializable attribute - public interface IDeserializationCallback { - void OnDeserialization(Object sender); - } -} diff --git a/src/mscorlib/src/System/Runtime/Serialization/IFormatterConverter.cs b/src/mscorlib/src/System/Runtime/Serialization/IFormatterConverter.cs deleted file mode 100644 index 0be0db9acd..0000000000 --- a/src/mscorlib/src/System/Runtime/Serialization/IFormatterConverter.cs +++ /dev/null @@ -1,39 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -/*============================================================ -** -** -** -** Purpose: The interface provides the connection between an -** instance of SerializationInfo and the formatter-provided -** class which knows how to parse the data inside the -** SerializationInfo. -** -** -============================================================*/ -namespace System.Runtime.Serialization { - using System; - - [CLSCompliant(false)] - public interface IFormatterConverter { - Object Convert(Object value, Type type); - Object Convert(Object value, TypeCode typeCode); - bool ToBoolean(Object value); - char ToChar(Object value); - sbyte ToSByte(Object value); - byte ToByte(Object value); - short ToInt16(Object value); - ushort ToUInt16(Object value); - int ToInt32(Object value); - uint ToUInt32(Object value); - long ToInt64(Object value); - ulong ToUInt64(Object value); - float ToSingle(Object value); - double ToDouble(Object value); - Decimal ToDecimal(Object value); - DateTime ToDateTime(Object value); - String ToString(Object value); - } -} diff --git a/src/mscorlib/src/System/Runtime/Serialization/IObjectReference.cs b/src/mscorlib/src/System/Runtime/Serialization/IObjectReference.cs deleted file mode 100644 index ef5ee6ade0..0000000000 --- a/src/mscorlib/src/System/Runtime/Serialization/IObjectReference.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. - -/*============================================================ -** -** Interface: IObjectReference -** -** -** Purpose: Implemented by objects that are actually references -** to a different object which can't be discovered until -** this one is completely restored. During the fixup stage, -** any object implementing IObjectReference is asked for it's -** "real" object and that object is inserted into the graph. -** -** -===========================================================*/ -namespace System.Runtime.Serialization { - - using System; - // Interface does not need to be marked with the serializable attribute - public interface IObjectReference { - Object GetRealObject(StreamingContext context); - } -} - - diff --git a/src/mscorlib/src/System/Runtime/Serialization/ISerializable.cs b/src/mscorlib/src/System/Runtime/Serialization/ISerializable.cs deleted file mode 100644 index 816aa0484b..0000000000 --- a/src/mscorlib/src/System/Runtime/Serialization/ISerializable.cs +++ /dev/null @@ -1,30 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -/*============================================================ -** -** Interface: ISerializable -** -** -** Purpose: Implemented by any object that needs to control its -** own serialization. -** -** -===========================================================*/ - -namespace System.Runtime.Serialization { - using System.Runtime.Remoting; - using System.Runtime.Serialization; - using System; - using System.Reflection; - - public interface ISerializable { - void GetObjectData(SerializationInfo info, StreamingContext context); - } - -} - - - - diff --git a/src/mscorlib/src/System/Runtime/Serialization/SafeSerializationManager.cs b/src/mscorlib/src/System/Runtime/Serialization/SafeSerializationManager.cs deleted file mode 100644 index 260e873bc7..0000000000 --- a/src/mscorlib/src/System/Runtime/Serialization/SafeSerializationManager.cs +++ /dev/null @@ -1,240 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. -using 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() {} - - 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); - } - - 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); - } -} diff --git a/src/mscorlib/src/System/Runtime/Serialization/SerializationAttributes.cs b/src/mscorlib/src/System/Runtime/Serialization/SerializationAttributes.cs deleted file mode 100644 index 38abffa66e..0000000000 --- a/src/mscorlib/src/System/Runtime/Serialization/SerializationAttributes.cs +++ /dev/null @@ -1,59 +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: Various Attributes for Serialization -** -** -============================================================*/ -namespace System.Runtime.Serialization -{ - using System; - using System.Diagnostics.Contracts; - using System.Reflection; - - [AttributeUsage(AttributeTargets.Field, Inherited=false)] - public sealed class OptionalFieldAttribute : Attribute - { - int versionAdded = 1; - public OptionalFieldAttribute() { } - - public int VersionAdded - { - get { - return this.versionAdded; - } - set { - if (value < 1) - throw new ArgumentException(Environment.GetResourceString("Serialization_OptionalFieldVersionValue")); - Contract.EndContractBlock(); - this.versionAdded = value; - } - } - } - - [AttributeUsage(AttributeTargets.Method, Inherited=false)] - public sealed class OnSerializingAttribute : Attribute - { - } - - [AttributeUsage(AttributeTargets.Method, Inherited=false)] - public sealed class OnSerializedAttribute : Attribute - { - } - - [AttributeUsage(AttributeTargets.Method, Inherited=false)] - public sealed class OnDeserializingAttribute : Attribute - { - } - - [AttributeUsage(AttributeTargets.Method, Inherited=false)] - public sealed class OnDeserializedAttribute : Attribute - { - } - -} diff --git a/src/mscorlib/src/System/Runtime/Serialization/SerializationException.cs b/src/mscorlib/src/System/Runtime/Serialization/SerializationException.cs deleted file mode 100644 index e9cb79b7af..0000000000 --- a/src/mscorlib/src/System/Runtime/Serialization/SerializationException.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: Thrown when something goes wrong during serialization or -** deserialization. -** -** -=============================================================================*/ - -namespace System.Runtime.Serialization { - - using System; - using System.Runtime.Serialization; - - [Serializable] - public class SerializationException : SystemException { - - private static String _nullMessage = Environment.GetResourceString("Arg_SerializationException"); - - // Creates a new SerializationException with its message - // string set to a default message. - public SerializationException() - : base(_nullMessage) { - SetErrorCode(__HResults.COR_E_SERIALIZATION); - } - - public SerializationException(String message) - : base(message) { - SetErrorCode(__HResults.COR_E_SERIALIZATION); - } - - public SerializationException(String message, Exception innerException) : base (message, innerException) { - SetErrorCode(__HResults.COR_E_SERIALIZATION); - } - - protected SerializationException(SerializationInfo info, StreamingContext context) : base (info, context) { - } - } -} diff --git a/src/mscorlib/src/System/Runtime/Serialization/SerializationInfo.cs b/src/mscorlib/src/System/Runtime/Serialization/SerializationInfo.cs index 45521f2397..7fc3ce27d9 100644 --- a/src/mscorlib/src/System/Runtime/Serialization/SerializationInfo.cs +++ b/src/mscorlib/src/System/Runtime/Serialization/SerializationInfo.cs @@ -11,25 +11,25 @@ ** ** ===========================================================*/ -namespace System.Runtime.Serialization -{ - using System; - using System.Collections.Generic; - using System.Reflection; - using System.Runtime.Remoting; - using System.Globalization; - using System.Diagnostics; - using System.Diagnostics.Contracts; - using System.Security; - using System.Runtime.CompilerServices; +using System; +using System.Collections.Generic; +using System.Reflection; +using System.Runtime.Remoting; +using System.Globalization; +using System.Diagnostics; +using System.Diagnostics.Contracts; +using System.Security; +using System.Runtime.CompilerServices; +namespace System.Runtime.Serialization +{ public sealed class SerializationInfo { private const int defaultSize = 4; private const string s_mscorlibAssemblySimpleName = System.CoreLib.Name; private const string s_mscorlibFileName = s_mscorlibAssemblySimpleName + ".dll"; - + // Even though we have a dictionary, we're still keeping all the arrays around for back-compat. // Otherwise we may run into potentially breaking behaviors like GetEnumerator() not returning entries in the same order they were added. internal String[] m_members; @@ -94,7 +94,7 @@ namespace System.Runtime.Serialization throw new ArgumentNullException(nameof(value)); } Contract.EndContractBlock(); - + m_fullTypeName = value; isFullTypeNameSetExplicit = true; } @@ -113,9 +113,9 @@ namespace System.Runtime.Serialization throw new ArgumentNullException(nameof(value)); } Contract.EndContractBlock(); - if (this.requireSameTokenInPartialTrust) + if (requireSameTokenInPartialTrust) { - DemandForUnsafeAssemblyNameAssignments(this.m_assemName, value); + DemandForUnsafeAssemblyNameAssignments(m_assemName, value); } m_assemName = value; isAssemblyNameSetExplicit = true; @@ -130,7 +130,7 @@ namespace System.Runtime.Serialization } Contract.EndContractBlock(); - if (this.requireSameTokenInPartialTrust) + if (requireSameTokenInPartialTrust) { DemandForUnsafeAssemblyNameAssignments(this.ObjectType.Assembly.FullName, type.Assembly.FullName); } @@ -331,7 +331,7 @@ namespace System.Runtime.Serialization if (m_nameToIndex.ContainsKey(name)) { BCLDebug.Trace("SER", "[SerializationInfo.AddValue]Tried to add ", name, " twice to the SI."); - throw new SerializationException(Environment.GetResourceString("Serialization_SameNameTwice")); + throw new SerializationException(SR.Serialization_SameNameTwice); } m_nameToIndex.Add(name, m_currMember); @@ -382,7 +382,6 @@ namespace System.Runtime.Serialization m_data[index] = value; m_types[index] = type; } - } private int FindElement(String name) @@ -416,7 +415,7 @@ namespace System.Runtime.Serialization int index = FindElement(name); if (index == -1) { - throw new SerializationException(Environment.GetResourceString("Serialization_NotFound", name)); + throw new SerializationException(SR.Format(SR.Serialization_NotFound, name)); } Debug.Assert(index < m_data.Length, "[SerializationInfo.GetElement]index<m_data.Length"); @@ -451,7 +450,6 @@ namespace System.Runtime.Serialization public Object GetValue(String name, Type type) { - if ((object)type == null) { throw new ArgumentNullException(nameof(type)); @@ -460,7 +458,7 @@ namespace System.Runtime.Serialization RuntimeType rt = type as RuntimeType; if (rt == null) - throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeType")); + throw new ArgumentException(SR.Argument_MustBeRuntimeType); Type foundType; Object value; @@ -698,6 +696,5 @@ namespace System.Runtime.Serialization } return m_converter.ToString(value); } - } } diff --git a/src/mscorlib/src/System/Runtime/Serialization/SerializationInfoEnumerator.cs b/src/mscorlib/src/System/Runtime/Serialization/SerializationInfoEnumerator.cs deleted file mode 100644 index 0858dfc19f..0000000000 --- a/src/mscorlib/src/System/Runtime/Serialization/SerializationInfoEnumerator.cs +++ /dev/null @@ -1,145 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -/*============================================================ -** -** -** -** Purpose: A formatter-friendly mechanism for walking all of -** the data in a SerializationInfo. Follows the IEnumerator -** mechanism from Collections. -** -** -============================================================*/ -namespace System.Runtime.Serialization { - using System; - using System.Diagnostics; - using System.Collections; - using System.Diagnostics.Contracts; - - // - // The tuple returned by SerializationInfoEnumerator.Current. - // - public struct SerializationEntry { - private Type m_type; - private Object m_value; - private String m_name; - - public Object Value { - get { - return m_value; - } - } - - public String Name { - get { - return m_name; - } - } - - public Type ObjectType { - get { - return m_type; - } - } - - internal SerializationEntry(String entryName, Object entryValue, Type entryType) { - m_value = entryValue; - m_name = entryName; - m_type = entryType; - } - } - - // - // A simple enumerator over the values stored in the SerializationInfo. - // This does not snapshot the values, it just keeps pointers to the - // member variables of the SerializationInfo that created it. - // - public sealed class SerializationInfoEnumerator : IEnumerator { - String[] m_members; - Object[] m_data; - Type[] m_types; - int m_numItems; - int m_currItem; - bool m_current; - - internal SerializationInfoEnumerator(String[] members, Object[] info, Type[] types, int 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; - m_types = types; - //The MoveNext semantic is much easier if we enforce that [0..m_numItems] are valid entries - //in the enumerator, hence we subtract 1. - m_numItems = numItems-1; - m_currItem = -1; - m_current = false; - } - - public bool MoveNext() { - if (m_currItem<m_numItems) { - m_currItem++; - m_current = true; - } else { - m_current = false; - } - return m_current; - } - - /// <internalonly/> - Object IEnumerator.Current { //Actually returns a SerializationEntry - get { - if (m_current==false) { - throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_EnumOpCantHappen")); - } - return (Object)(new SerializationEntry(m_members[m_currItem], m_data[m_currItem], m_types[m_currItem])); - } - } - - public SerializationEntry Current { //Actually returns a SerializationEntry - get { - if (m_current==false) { - throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_EnumOpCantHappen")); - } - return (new SerializationEntry(m_members[m_currItem], m_data[m_currItem], m_types[m_currItem])); - } - } - - public void Reset() { - m_currItem = -1; - m_current = false; - } - - public String Name { - get { - if (m_current==false) { - throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_EnumOpCantHappen")); - } - return m_members[m_currItem]; - } - } - public Object Value { - get { - if (m_current==false) { - throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_EnumOpCantHappen")); - } - return m_data[m_currItem]; - } - } - public Type ObjectType { - get { - if (m_current==false) { - throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_EnumOpCantHappen")); - } - return m_types[m_currItem]; - } - } - } -} diff --git a/src/mscorlib/src/System/Runtime/Serialization/StreamingContext.cs b/src/mscorlib/src/System/Runtime/Serialization/StreamingContext.cs deleted file mode 100644 index c01a3edc4f..0000000000 --- a/src/mscorlib/src/System/Runtime/Serialization/StreamingContext.cs +++ /dev/null @@ -1,72 +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. - -/*============================================================ -** -** ValueType: StreamingContext -** -** -** Purpose: A value type indicating the source or destination of our streaming. -** -** -===========================================================*/ -namespace System.Runtime.Serialization { - - using System.Runtime.Remoting; - using System; - [Serializable] - public struct StreamingContext { - internal Object m_additionalContext; - internal StreamingContextStates m_state; - - public StreamingContext(StreamingContextStates state) - : this (state, null) { - } - - public StreamingContext(StreamingContextStates state, Object additional) { - m_state = state; - m_additionalContext = additional; - } - - public Object Context { - get { return m_additionalContext; } - } - - public override bool Equals(Object obj) { - if (!(obj is StreamingContext)) { - return false; - } - if (((StreamingContext)obj).m_additionalContext == m_additionalContext && - ((StreamingContext)obj).m_state == m_state) { - return true; - } - return false; - } - - public override int GetHashCode() { - return (int)m_state; - } - - public StreamingContextStates State { - get { return m_state; } - } - } - - // ********************************************************** - // Keep these in sync with the version in vm\runtimehandles.h - // ********************************************************** -[Serializable] -[Flags] - public enum StreamingContextStates { - CrossProcess=0x01, - CrossMachine=0x02, - File =0x04, - Persistence =0x08, - Remoting =0x10, - Other =0x20, - Clone =0x40, - CrossAppDomain =0x80, - All =0xFF, - } -} diff --git a/src/mscorlib/src/System/Runtime/Versioning/NonVersionableAttribute.cs b/src/mscorlib/src/System/Runtime/Versioning/NonVersionableAttribute.cs deleted file mode 100644 index 0a9845d9c2..0000000000 --- a/src/mscorlib/src/System/Runtime/Versioning/NonVersionableAttribute.cs +++ /dev/null @@ -1,33 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -/*============================================================ -** -** Class: NonVersionableAttribute -** -** -** The [NonVersionable] attribute is applied to indicate that the implementation -** of a particular member or layout of a struct cannot be changed for given platform in incompatible way. -** This allows cross-module inlining of methods and data structures whose implementation -** is never changed in ReadyToRun native images. Any changes to such members or types would be -** breaking changes for ReadyToRun. -** -===========================================================*/ -using System; -using System.Diagnostics; - -namespace System.Runtime.Versioning { - - // This Conditional is here to strip the annotations for targets where ReadyToRun is not supported. - // If this attribute is ever made public, this Conditional should be removed. - [Conditional("FEATURE_READYTORUN")] - [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Constructor, - AllowMultiple = false, Inherited = false)] - sealed class NonVersionableAttribute : Attribute { - - public NonVersionableAttribute() - { - } - } -} diff --git a/src/mscorlib/src/System/Runtime/Versioning/TargetFrameworkAttribute.cs b/src/mscorlib/src/System/Runtime/Versioning/TargetFrameworkAttribute.cs deleted file mode 100644 index 600ba3f154..0000000000 --- a/src/mscorlib/src/System/Runtime/Versioning/TargetFrameworkAttribute.cs +++ /dev/null @@ -1,45 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -// -/*============================================================ -** -** -** -** Purpose: Identifies which SKU and version of the .NET -** Framework that a particular library was compiled against. -** Emitted by VS, and can help catch deployment problems. -** -===========================================================*/ -using System; -using System.Diagnostics.Contracts; - -namespace System.Runtime.Versioning { - - [AttributeUsageAttribute(AttributeTargets.Assembly, AllowMultiple = false, Inherited = false)] - public sealed class TargetFrameworkAttribute : Attribute { - private String _frameworkName; // A target framework moniker - private String _frameworkDisplayName; - - // The frameworkName parameter is intended to be the string form of a FrameworkName instance. - public TargetFrameworkAttribute(String frameworkName) - { - if (frameworkName == null) - throw new ArgumentNullException(nameof(frameworkName)); - Contract.EndContractBlock(); - _frameworkName = frameworkName; - } - - // The target framework moniker that this assembly was compiled against. - // Use the FrameworkName class to interpret target framework monikers. - public String FrameworkName { - get { return _frameworkName; } - } - - public String FrameworkDisplayName { - get { return _frameworkDisplayName; } - set { _frameworkDisplayName = value; } - } - } -} |