{
internal static partial class SR
{
- // This method is used to decide if we need to append the exception message parameters to the message when calling SR.Format.
+ // This method is used to decide if we need to append the exception message parameters to the message when calling SR.Format.
// by default it returns false.
[MethodImpl(MethodImplOptions.NoInlining)]
private static bool UsingResourceKeys()
return key!;
}
- // We have a somewhat common potential for infinite
+ // We have a somewhat common potential for infinite
// loops with mscorlib's ResourceManager. If "potentially dangerous"
// code throws an exception, we will get into an infinite loop
// inside the ResourceManager and this "potentially dangerous" code.
// Potentially dangerous code includes the IO package, CultureInfo,
- // parts of the loader, some parts of Reflection, Security (including
+ // parts of the loader, some parts of Reflection, Security (including
// custom user-written permissions that may parse an XML file at
// class load time), assembly load event handlers, etc. Essentially,
// this is not a bounded set of code, and we need to fix the problem.
// Fortunately, this is limited to mscorlib's error lookups and is NOT
// a general problem for all user code using the ResourceManager.
- // The solution is to make sure only one thread at a time can call
- // GetResourceString. Also, since resource lookups can be
+ // The solution is to make sure only one thread at a time can call
+ // GetResourceString. Also, since resource lookups can be
// reentrant, if the same thread comes into GetResourceString
- // twice looking for the exact same resource name before
- // returning, we're going into an infinite loop and we should
- // return a bogus string.
+ // twice looking for the exact same resource name before
+ // returning, we're going into an infinite loop and we should
+ // return a bogus string.
bool lockTaken = false;
try
-// 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.
internal sealed class FlatDataTable
{
- // If a codepoint does not have data, this specifies the default value.
+ // If a codepoint does not have data, this specifies the default value.
private readonly string DefaultValue;
private readonly Func<string, byte[]> GetValueBytesCallback;
-// 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.
var numericIndexTable = new DataTable();
// Create a flat table for Unicode category and BiDi category
var categoriesValueTable = new FlatDataTable(defaultCategoryValues, GetCategoriesValueBytes);
- // Create a flat table.
+ // Create a flat table.
// GetNumericValueBytes() is the callback used to generate the bytes of each item.
var numericValueTable = new FlatDataTable("-1", GetNumericValueBytes);
// Create a flat table for digit values
/// </summary>
private static readonly Dictionary<string, byte> BiDiCategory = new Dictionary<string, byte>
{
- ["L"] = 0, // Left-to-Right
- ["LRE"] = 1, // Left-to-Right Embedding
- ["LRO"] = 2, // Left-to-Right Override
- ["R"] = 3, // Right-to-Left
- ["AL"] = 4, // Right-to-Left Arabic
- ["RLE"] = 5, // Right-to-Left Embedding
- ["RLO"] = 6, // Right-to-Left Override
- ["PDF"] = 7, // Pop Directional Format
- ["EN"] = 8, // European Number
- ["ES"] = 9, // European Number Separator
- ["ET"] = 10, // European Number Terminator
- ["AN"] = 11, // Arabic Number
- ["CS"] = 12, // Common Number Separator
- ["NSM"] = 13, // Non-Spacing Mark
- ["BN"] = 14, // Boundary Neutral
- ["B"] = 15, // Paragraph Separator
- ["S"] = 16, // Segment Separator
- ["WS"] = 17, // Whitespace
- ["ON"] = 18, // Other Neutrals
+ ["L"] = 0, // Left-to-Right
+ ["LRE"] = 1, // Left-to-Right Embedding
+ ["LRO"] = 2, // Left-to-Right Override
+ ["R"] = 3, // Right-to-Left
+ ["AL"] = 4, // Right-to-Left Arabic
+ ["RLE"] = 5, // Right-to-Left Embedding
+ ["RLO"] = 6, // Right-to-Left Override
+ ["PDF"] = 7, // Pop Directional Format
+ ["EN"] = 8, // European Number
+ ["ES"] = 9, // European Number Separator
+ ["ET"] = 10, // European Number Terminator
+ ["AN"] = 11, // Arabic Number
+ ["CS"] = 12, // Common Number Separator
+ ["NSM"] = 13, // Non-Spacing Mark
+ ["BN"] = 14, // Boundary Neutral
+ ["B"] = 15, // Paragraph Separator
+ ["S"] = 16, // Segment Separator
+ ["WS"] = 17, // Whitespace
+ ["ON"] = 18, // Other Neutrals
["LRI"] = 19, // LeftToRightIsolate
["RLI"] = 20, // RightToLeftIsolate
["FSI"] = 21, // FirstStrongIsolate
// 0 Code value
// 1 Character name
// 2 General Category
- //
+ //
// 3 Canonical Combining Classes
// 4 Bidirectional Category
// 5 Character Decomposition Mapping
// we don't need to share this dictionary with the COM activation dictionary
// since there will be no overlap.
private static readonly Dictionary<string, AssemblyLoadContext> s_assemblyLoadContexts = new Dictionary<string, AssemblyLoadContext>(StringComparer.InvariantCultureIgnoreCase);
-
+
private static AssemblyLoadContext GetALC(string assemblyPath)
{
AssemblyLoadContext? alc;
}
AssemblyLoadContext context = GetALC(Marshal.PtrToStringUni((IntPtr)componentPath)!);
-
+
Type winRTType = context.LoadTypeForWinRTTypeNameInContext(typeName);
if (winRTType is null || !winRTType.IsExportedToWindowsRuntime)
/// <returns>true if the error was reported, false if not (ie running on Win8)</returns>
public static bool ReportUnhandledError(Exception? ex)
{
- return WindowsRuntimeMarshal.ReportUnhandledError(ex);
+ return WindowsRuntimeMarshal.ReportUnhandledError(ex);
}
}
}
**
**
**
-** Purpose: This class only exists to provide support for
-** implenting IDispatch on managed objects. It is
+** Purpose: This class only exists to provide support for
+** implenting IDispatch on managed objects. It is
** used to provide OleAut style coercion rules.
**
-**
+**
===========================================================*/
namespace Microsoft.Win32
* Changes a Variant from one type to another, calling the OLE
* Automation VariantChangeTypeEx routine. Note the legal types here are
* restricted to the subset of what can be legally found in a VB
- * Variant and the types that CLR supports explicitly in the
- * CLR Variant class.
+ * Variant and the types that CLR supports explicitly in the
+ * CLR Variant class.
*/
internal static Variant ChangeType(Variant source, Type targetClass, short options, CultureInfo culture)
{
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private extern unsafe ArgIterator(IntPtr arglist, void *ptr);
-
- // create an arg iterator that points just past 'firstArg'.
+
+ // create an arg iterator that points just past 'firstArg'.
// 'arglist' is the value returned by the ARGLIST instruction
// This is much like the C va_start macro
private extern unsafe void FCallGetNextArg(void * result);
// Alternate version of GetNextArg() intended primarily for IJW code
- // generated by VC's "va_arg()" construct.
+ // generated by VC's "va_arg()" construct.
[CLSCompliant(false)]
public TypedReference GetNextArg(RuntimeTypeHandle rth)
{
public void End()
{
}
-
- // How many arguments are left in the list
+
+ // How many arguments are left in the list
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public extern int GetRemainingCount();
-
+
// Gets the type of the current arg, does NOT advance the iterator
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private extern unsafe void* _GetNextArgType();
- public unsafe RuntimeTypeHandle GetNextArgType()
+ public unsafe RuntimeTypeHandle GetNextArgType()
{
return new RuntimeTypeHandle(Type.GetTypeFromHandleUnsafe((IntPtr)_GetNextArgType()));
}
-
+
public override int GetHashCode()
{
return ValueType.GetHashCodeOfPtr(ArgCookie);
}
-
+
// Inherited from object
public override bool Equals(object? o)
{
throw new NotSupportedException(SR.NotSupported_NYI);
}
-#else
+#else
public ArgIterator(RuntimeArgumentHandle arglist)
{
throw new PlatformNotSupportedException(SR.PlatformNotSupported_ArgIterator); // https://github.com/dotnet/coreclr/issues/9204
namespace System
{
// Note that we make a T[] (single-dimensional w/ zero as the lower bound) implement both
- // IList<U> and IReadOnlyList<U>, where T : U dynamically. See the SZArrayHelper class for details.
+ // IList<U> and IReadOnlyList<U>, where T : U dynamically. See the SZArrayHelper class for details.
public abstract partial class Array : ICloneable, IList, IStructuralComparable, IStructuralEquatable
{
// Create instance will create an array
ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_MustBeType, ExceptionArgument.elementType);
// Check to make sure the lengths are all positive. Note that we check this here to give
- // a good exception message if they are not; however we check this again inside the execution
- // engine's low level allocation function after having made a copy of the array to prevent a
- // malicious caller from mutating the array after this check.
+ // a good exception message if they are not; however we check this again inside the execution
+ // engine's low level allocation function after having made a copy of the array to prevent a
+ // malicious caller from mutating the array after this check.
for (int i = 0; i < lengths.Length; i++)
if (lengths[i] < 0)
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.lengths, i, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum);
ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_MustBeType, ExceptionArgument.elementType);
// Check to make sure the lenghts are all positive. Note that we check this here to give
- // a good exception message if they are not; however we check this again inside the execution
- // engine's low level allocation function after having made a copy of the array to prevent a
- // malicious caller from mutating the array after this check.
+ // a good exception message if they are not; however we check this again inside the execution
+ // engine's low level allocation function after having made a copy of the array to prevent a
+ // malicious caller from mutating the array after this check.
for (int i = 0; i < lengths.Length; i++)
if (lengths[i] < 0)
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.lengths, i, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum);
Copy(sourceArray, sourceIndex, destinationArray, destinationIndex, length, false);
}
- // Reliability-wise, this method will either possibly corrupt your
+ // Reliability-wise, this method will either possibly corrupt your
// instance & might fail when called from within a CER, or if the
// reliable flag is true, it will either always succeed or always
// throw an exception with no side effects.
// Provides a strong exception guarantee - either it succeeds, or
// it throws an exception with no side effects. The arrays must be
- // compatible array types based on the array element type - this
+ // compatible array types based on the array element type - this
// method does not support casting, boxing, or primitive widening.
// It will up-cast, assuming the array types are correct.
public static void ConstrainedCopy(Array sourceArray, int sourceIndex, Array destinationArray, int destinationIndex, int length)
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern bool TrySZSort(Array keys, Array? items, int left, int right);
- // if this is an array of value classes and that value class has a default constructor
+ // if this is an array of value classes and that value class has a default constructor
// then this calls this default constructor on every element in the value class array.
// otherwise this is a no-op. Generally this method is called automatically by the compiler
[MethodImplAttribute(MethodImplOptions.InternalCall)]
//----------------------------------------------------------------------------------------
// ! READ THIS BEFORE YOU WORK ON THIS CLASS.
- //
+ //
// The methods on this class must be written VERY carefully to avoid introducing security holes.
// That's because they are invoked with special "this"! The "this" object
// for all of these methods are not SZArrayHelper objects. Rather, they are of type U[]
// where U[] is castable to T[]. No actual SZArrayHelper object is ever instantiated. Thus, you will
- // see a lot of expressions that cast "this" "T[]".
+ // see a lot of expressions that cast "this" "T[]".
//
// This class is needed to allow an SZ array of type T[] to expose IList<T>,
// IList<T.BaseType>, etc., etc. all the way up to IList<Object>. When the following call is
//
// the interface stub dispatcher treats this as a special case, loads up SZArrayHelper,
// finds the corresponding generic method (matched simply by method name), instantiates
- // it for type <T> and executes it.
+ // it for type <T> and executes it.
//
// The "T" will reflect the interface used to invoke the method. The actual runtime "this" will be
// array that is castable to "T[]" (i.e. for primitivs and valuetypes, it will be exactly
Debug.Assert(param != null);
// For ParameterInfo's we need to make sure that we chain through all the MethodInfo's in the inheritance chain that
- // have this ParameterInfo defined. .We pick up all the CustomAttributes for the starting ParameterInfo. We need to pick up only attributes
+ // have this ParameterInfo defined. .We pick up all the CustomAttributes for the starting ParameterInfo. We need to pick up only attributes
// that are marked inherited from the remainder of the MethodInfo's in the inheritance chain.
// For MethodInfo's on an interface we do not do an inheritance walk so the default ParameterInfo attributes are returned.
// For MethodInfo's on a class we walk up the inheritance chain but do not look at the MethodInfo's on the interfaces that the
Debug.Assert(type != null);
// For ParameterInfo's we need to make sure that we chain through all the MethodInfo's in the inheritance chain.
- // We pick up all the CustomAttributes for the starting ParameterInfo. We need to pick up only attributes
+ // We pick up all the CustomAttributes for the starting ParameterInfo. We need to pick up only attributes
// that are marked inherited from the remainder of the ParameterInfo's in the inheritance chain.
// For MethodInfo's on an interface we do not do an inheritance walk. For ParameterInfo's on a
// Class we walk up the inheritance chain but do not look at the MethodInfo's on the interfaces that the class inherits from.
}
else if (usage.Inherited && usage.AllowMultiple)
{
- // we saw this type already add it only if it is inheritable and it does allow multiple
+ // we saw this type already add it only if it is inheritable and it does allow multiple
attributeList.Add(attributes[i]);
}
}
switch (member.MemberType)
{
- case MemberTypes.Method: // We need to climb up the member hierarchy
+ case MemberTypes.Method: // We need to climb up the member hierarchy
return InternalParamIsDefined(element, attributeType, inherit);
case MemberTypes.Constructor:
partial class Buffer
{
// Copies from one primitive array to another primitive array without
- // respecting types. This calls memmove internally. The count and
+ // respecting types. This calls memmove internally. The count and
// offset parameters here are in bytes. If you want to use traditional
// array element indices and counts, use Array.Copy.
[MethodImplAttribute(MethodImplOptions.InternalCall)]
/*============================================================
**
**
-**
+**
**
**
** Purpose: List for exceptions.
**
-**
+**
===========================================================*/
namespace System.Collections
{
result = TryCreateEnumComparer(runtimeType);
}
-
+
return result ?? CreateInstanceForAnotherGenericParameter((RuntimeType)typeof(ObjectComparer<object>), runtimeType);
}
{
Debug.Assert(nullableType != null);
Debug.Assert(nullableType.IsGenericType && nullableType.GetGenericTypeDefinition() == typeof(Nullable<>));
-
+
var embeddedType = (RuntimeType)nullableType.GetGenericArguments()[0];
if (typeof(IComparable<>).MakeGenericType(embeddedType).IsAssignableFrom(embeddedType))
// ends up doing this anyway, we end up avoiding an unnecessary P/Invoke
// and virtual method call.
TypeCode underlyingTypeCode = Type.GetTypeCode(Enum.GetUnderlyingType(enumType));
-
+
// Depending on the enum type, we need to special case the comparers so that we avoid boxing.
// Specialize differently for signed/unsigned types so we avoid problems with large numbers.
switch (underlyingTypeCode)
case TypeCode.UInt64:
return RuntimeTypeHandle.CreateInstanceForAnotherGenericParameter((RuntimeType)typeof(EnumComparer<>), enumType);
}
-
+
return null;
}
{
result = TryCreateEnumEqualityComparer(runtimeType);
}
-
+
return result ?? CreateInstanceForAnotherGenericParameter((RuntimeType)typeof(ObjectEqualityComparer<object>), runtimeType);
}
{
return RuntimeTypeHandle.CreateInstanceForAnotherGenericParameter((RuntimeType)typeof(NullableEqualityComparer<int>), embeddedType);
}
-
+
return null;
}
case TypeCode.UInt16:
return RuntimeTypeHandle.CreateInstanceForAnotherGenericParameter((RuntimeType)typeof(EnumEqualityComparer<>), enumType);
}
-
+
return null;
}
}
/*============================================================
**
-**
-**
+**
+**
**
** Purpose: Read-only wrapper for another generic dictionary.
**
}
//
- // We can't cast array of value type to object[], so we don't support
+ // We can't cast array of value type to object[], so we don't support
// widening of primitive types here.
//
object?[]? objects = array as object[];
#endregion Helper method for our KeyCollection and ValueCollection
}
}
-
{
}
-
+
internal sealed class EventPipeConfiguration
{
private string m_outputFile;
foreach (var parameter in parameters)
{
int pMetadataLength = parameter.GetMetadataLength();
- // The call above may return -1 which means we failed to get the metadata length.
+ // The call above may return -1 which means we failed to get the metadata length.
// We then return a default metadata blob (with parameterCount of 0) to prevent it from generating malformed metadata.
if (pMetadataLength < 0)
{
// Top-level structs don't have a property name, but for simplicity we write a NULL-char to represent the name.
EventPipeMetadataGenerator.WriteToBuffer(pMetadataBlob, blobSize, ref offset, '\0');
-
+
}
else
{
}
// For simplicity when writing a reader, we write a NULL char
- // after the metadata for a top-level struct (for its name) so that
+ // after the metadata for a top-level struct (for its name) so that
// readers don't have do special case the outer-most struct.
ret += sizeof(char);
}
-// Licensed to the .NET Foundation under one or more agreements.
+// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Buffers.Binary;
else if (parameterType == typeof(string))
{
// Try to find null terminator (0x00) from the byte span
- // NOTE: we do this by hand instead of using IndexOf because payload may be unaligned due to
+ // NOTE: we do this by hand instead of using IndexOf because payload may be unaligned due to
// mixture of different types being stored in the same buffer. (see eventpipe.cpp:CopyData)
int byteCount = -1;
for (int j = 1; j < payload.Length; j+=2)
{
s_RuntimeEventSource = new RuntimeEventSource();
}
-
+
private RuntimeEventSource(): base(new Guid(0x49592C0F, 0x5A05, 0x516D, 0xAA, 0x4B, 0xA6, 0x4E, 0x02, 0x02, 0x6C, 0x89), "System.Runtime", EventSourceSettings.EtwSelfDescribingEventFormat)
{
}
{
if (command.Command == EventCommand.Enable)
{
- // NOTE: These counters will NOT be disposed on disable command because we may be introducing
+ // NOTE: These counters will NOT be disposed on disable command because we may be introducing
// a race condition by doing that. We still want to create these lazily so that we aren't adding
// overhead by at all times even when counters aren't enabled.
_gen2GCCounter = _gen2GCCounter ?? new IncrementingPollingCounter("gen-2-gc-count", this, () => GC.CollectionCount(2)) { DisplayName = "Gen 2 GC Count", DisplayRateTimeScale = new TimeSpan(0, 1, 0) };
_exceptionCounter = _exceptionCounter ?? new IncrementingPollingCounter("exception-count", this, () => Exception.GetExceptionCount()) { DisplayName = "Exception Count", DisplayRateTimeScale = new TimeSpan(0, 0, 1) };
_threadPoolThreadCounter = _threadPoolThreadCounter ?? new PollingCounter("threadpool-thread-count", this, () => ThreadPool.ThreadCount) { DisplayName = "ThreadPool Thread Count" };
- _monitorContentionCounter = _monitorContentionCounter ?? new IncrementingPollingCounter("monitor-lock-contention-count", this, () => Monitor.LockContentionCount) { DisplayName = "Monitor Lock Contention Count", DisplayRateTimeScale = new TimeSpan(0, 0, 1) };
+ _monitorContentionCounter = _monitorContentionCounter ?? new IncrementingPollingCounter("monitor-lock-contention-count", this, () => Monitor.LockContentionCount) { DisplayName = "Monitor Lock Contention Count", DisplayRateTimeScale = new TimeSpan(0, 0, 1) };
_threadPoolQueueCounter = _threadPoolQueueCounter ?? new PollingCounter("threadpool-queue-length", this, () => ThreadPool.PendingWorkItemCount) { DisplayName = "ThreadPool Queue Length" };
_completedItemsCounter = _completedItemsCounter ?? new IncrementingPollingCounter("threadpool-completed-items-count", this, () => ThreadPool.CompletedWorkItemCount) { DisplayName = "ThreadPool Completed Work Item Count", DisplayRateTimeScale = new TimeSpan(0, 0, 1) };
_gcTimeCounter = _gcTimeCounter ?? new PollingCounter("time-in-gc", this, () => GC.GetLastGCPercentTimeInGC()) { DisplayName = "% Time in GC since last GC", DisplayUnits = "%" };
return 0;
}
- if (prevSystemUserTime == 0 && prevSystemKernelTime == 0) // These may be 0 when we report CPU usage for the first time, in which case we should just return 0.
+ if (prevSystemUserTime == 0 && prevSystemKernelTime == 0) // These may be 0 when we report CPU usage for the first time, in which case we should just return 0.
{
cpuUsage = 0;
}
{
private static Lazy<string?> eventSourceNameFilter = new Lazy<string?>(() => CompatibilitySwitch.GetValueInternal("EventSourceFilter"));
private static Lazy<string?> eventSourceEventFilter = new Lazy<string?>(() => CompatibilitySwitch.GetValueInternal("EventNameFilter"));
-
+
public XplatEventLogger() {}
private static bool initializedPersistentListener = false;
sb.Append('{');
// If the event has a message, send that as well as a pseudo-field
- if (!string.IsNullOrEmpty(eventMessage))
+ if (!string.IsNullOrEmpty(eventMessage))
{
sb.Append("\\\"EventSource_Message\\\":\\\"");
minimalJsonserializer(eventMessage, sb);
string? eventSourceFilter = eventSourceNameFilter.Value;
if (string.IsNullOrEmpty(eventSourceFilter) || (eventSource.Name.IndexOf(eventSourceFilter, StringComparison.OrdinalIgnoreCase) >= 0))
- {
+ {
EnableEvents(eventSource, EventLevel.LogAlways, EventKeywords.All, null);
}
}
namespace System.Diagnostics
{
- // Defines an interface indicating that a custom debugger notification is requested under specific
- // conditions. Users should implement this interface to be used as an argument to
- // System.Diagnostics.Debugger.CustomNotification.
+ // Defines an interface indicating that a custom debugger notification is requested under specific
+ // conditions. Users should implement this interface to be used as an argument to
+ // System.Diagnostics.Debugger.CustomNotification.
internal interface ICustomDebuggerNotification
{
// Interface does not need to be marked with the serializable attribute
namespace System.Diagnostics
{
// READ ME:
- // Modifying the order or fields of this object may require other changes
- // to the unmanaged definition of the StackFrameHelper class, in
+ // Modifying the order or fields of this object may require other changes
+ // to the unmanaged definition of the StackFrameHelper class, in
// VM\DebugDebugger.h. The binder will catch some of these layout problems.
internal class StackFrameHelper
{
#pragma warning disable 414
// dynamicMethods is an array of System.Resolver objects, used to keep
// DynamicMethodDescs AND collectible LoaderAllocators alive for the lifetime of StackFrameHelper.
- private object? dynamicMethods; // Field is not used from managed.
+ private object? dynamicMethods; // Field is not used from managed.
private IntPtr[]? rgMethodHandle;
private string[]? rgAssemblyPath;
// 0 means capture all frames. For StackTraces from an Exception, the EE always
// captures all frames. For other uses of StackTraces, we can abort stack walking after
- // some limit if we want to by setting this to a non-zero value. In Whidbey this was
+ // some limit if we want to by setting this to a non-zero value. In Whidbey this was
// hard-coded to 512, but some customers complained. There shouldn't be any need to limit
// this as memory/CPU is no longer allocated up front. If there is some reason to provide a
- // limit in the future, then we should expose it in the managed API so applications can
+ // limit in the future, then we should expose it in the managed API so applications can
// override it.
iFrameCount = 0;
}
//
- // Initializes the stack trace helper. If fNeedFileInfo is true, initializes rgFilename,
+ // Initializes the stack trace helper. If fNeedFileInfo is true, initializes rgFilename,
// rgiLineNumber and rgiColumnNumber fields using the portable PDB reader if not already
// done by GetStackFramesInternal (on Windows for old PDB format).
//
return;
}
- Type[] parameterTypes = new Type[]
+ Type[] parameterTypes = new Type[]
{
- typeof(Assembly), typeof(string), typeof(IntPtr), typeof(int), typeof(IntPtr),
- typeof(int), typeof(int), typeof(int),
- typeof(string).MakeByRefType(), typeof(int).MakeByRefType(), typeof(int).MakeByRefType()
+ typeof(Assembly), typeof(string), typeof(IntPtr), typeof(int), typeof(IntPtr),
+ typeof(int), typeof(int), typeof(int),
+ typeof(string).MakeByRefType(), typeof(int).MakeByRefType(), typeof(int).MakeByRefType()
};
MethodInfo? symbolsMethodInfo = symbolsType.GetMethod("GetSourceLineInfo", BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance, null, parameterTypes, null);
if (symbolsMethodInfo == null)
const string PackageName = "System.Diagnostics";
// Check if this method is part of the System.Diagnostics
- // package. If so, increment counter keeping track of
+ // package. If so, increment counter keeping track of
// System.Diagnostics functions
for (int i = 0; i < iNumFrames; i++)
{
** Represents a symbol writer for managed code. Provides methods to
** define documents, sequence points, lexical scopes, and variables.
**
-**
+**
===========================================================*/
using System.Reflection;
** Represents address Kinds used with local variables, parameters, and
** fields.
**
-**
+**
===========================================================*/
-// Only statics, does not need to be marked with the serializable attribute
+// Only statics, does not need to be marked with the serializable attribute
namespace System.Diagnostics.SymbolStore
{
}
// Note: The CLR's Watson bucketization code looks at the caller of the FCALL method
- // to assign blame for crashes. Don't mess with this, such as by making it call
+ // to assign blame for crashes. Don't mess with this, such as by making it call
// another managed helper method, unless you consult with some CLR Watson experts.
[DoesNotReturn]
[MethodImpl(MethodImplOptions.InternalCall)]
// There are multiple entry points to a hosted app. The host could
// use ::ExecuteAssembly() or ::CreateDelegate option:
//
- // ::ExecuteAssembly() -> In this particular case, the runtime invokes the main
+ // ::ExecuteAssembly() -> In this particular case, the runtime invokes the main
// method based on the arguments set by the host, and we return those arguments
//
- // ::CreateDelegate() -> In this particular case, the host is asked to create a
+ // ::CreateDelegate() -> In this particular case, the host is asked to create a
// delegate based on the appDomain, assembly and methodDesc passed to it.
// which the caller uses to invoke the method. In this particular case we do not have
// any information on what arguments would be passed to the delegate.
// Get the WatsonBuckets that were serialized - this is particularly
// done to support exceptions going across AD transitions.
- //
+ //
// We use the no throw version since we could be deserializing a pre-V4
// exception object that may not have this entry. In such a case, we would
// get null.
// If we are constructing a new exception after a cross-appdomain call...
if (context.State == StreamingContextStates.CrossAppDomain)
{
- // ...this new exception may get thrown. It is logically a re-throw, but
- // physically a brand-new exception. Since the stack trace is cleared
- // on a new exception, the "_remoteStackTraceString" is provided to
+ // ...this new exception may get thrown. It is logically a re-throw, but
+ // physically a brand-new exception. Since the stack trace is cleared
+ // on a new exception, the "_remoteStackTraceString" is provided to
// effectively import a stack trace from a "remote" exception. So,
// move the _stackTraceString into the _remoteStackTraceString. Note
- // that if there is an existing _remoteStackTraceString, it will be
- // preserved at the head of the new string, so everything works as
+ // that if there is an existing _remoteStackTraceString, it will be
+ // preserved at the head of the new string, so everything works as
// expected.
// Even if this exception is NOT thrown, things will still work as expected
// because the StackTrace property returns the concatenation of the
#if FEATURE_COMINTEROP
//
// Exception requires anything to be added into Data dictionary is serializable
- // This wrapper is made serializable to satisfy this requirement but does NOT serialize
- // the object and simply ignores it during serialization, because we only need
+ // This wrapper is made serializable to satisfy this requirement but does NOT serialize
+ // the object and simply ignores it during serialization, because we only need
// the exception instance in the app to hold the error object alive.
// Once the exception is serialized to debugger, debugger only needs the error reference string
//
// Using it across process or an AppDomain could be invalid and result
// in AV in the runtime.
//
- // Hence, we set it to zero when deserialization takes place.
+ // Hence, we set it to zero when deserialization takes place.
_ipForWatsonBuckets = UIntPtr.Zero;
}
object? _stackTraceCopy = (dispatchState.StackTrace == null) ? null : DeepCopyStackTrace(dispatchState.StackTrace);
object? _dynamicMethodsCopy = (dispatchState.DynamicMethods == null) ? null : DeepCopyDynamicMethods(dispatchState.DynamicMethods);
- // Finally, restore the information.
+ // Finally, restore the information.
//
// Since EDI can be created at various points during exception dispatch (e.g. at various frames on the stack) for the same exception instance,
// they can have different data to be restored. Thus, to ensure atomicity of restoration from each EDI, perform the restore under a lock.
}
}
- private MethodBase? _exceptionMethod; //Needed for serialization.
+ private MethodBase? _exceptionMethod; //Needed for serialization.
internal string? _message;
private IDictionary? _data;
private Exception? _innerException;
private string? _helpURL;
private object? _stackTrace;
private object? _watsonBuckets;
- private string? _stackTraceString; //Needed for serialization.
+ private string? _stackTraceString; //Needed for serialization.
private string? _remoteStackTraceString;
-#pragma warning disable 414 // Field is not used from managed.
+#pragma warning disable 414 // Field is not used from managed.
// _dynamicMethods is an array of System.Resolver objects, used to keep
// DynamicMethodDescs alive for the lifetime of the exception. We do this because
// the _stackTrace field holds MethodDescs, and a DynamicMethodDesc can be destroyed
private string? _source; // Mainly used by VB.
private UIntPtr _ipForWatsonBuckets; // Used to persist the IP for Watson Bucketing
- private IntPtr _xptrs; // Internal EE stuff
+ private IntPtr _xptrs; // Internal EE stuff
#pragma warning disable 414 // Field is not used from managed.
- private int _xcode = _COMPlusExceptionCode; // Internal EE stuff
+ private int _xcode = _COMPlusExceptionCode; // Internal EE stuff
#pragma warning restore 414
// @MANAGED: HResult is used from within the EE! Rename with care - check VM directory
}
}
- // This piece of infrastructure exists to help avoid deadlocks
- // between parts of mscorlib that might throw an exception while
+ // This piece of infrastructure exists to help avoid deadlocks
+ // between parts of mscorlib that might throw an exception while
// holding a lock that are also used by mscorlib's ResourceManager
// instance. As a special case of code that may throw while holding
// a lock, we also need to fix our asynchronous exceptions to use
- // Win32 resources as well (assuming we ever call a managed
+ // Win32 resources as well (assuming we ever call a managed
// constructor on instances of them). We should grow this set of
// exception messages as we discover problems, then move the resources
// involved to native code.
}
// !!!!!!!!!!!!!!!!!!!!!!!
- // make sure you change the def in vm\gc.h
+ // make sure you change the def in vm\gc.h
// if you change this!
internal enum InternalGCCollectionMode
{
}
// !!!!!!!!!!!!!!!!!!!!!!!
- // make sure you change the def in vm\gc.h
+ // make sure you change the def in vm\gc.h
// if you change this!
public enum GCNotificationStatus
{
return _CollectionCount(generation, 0);
}
- // This method DOES NOT DO ANYTHING in and of itself. It's used to
- // prevent a finalizable object from losing any outstanding references
- // a touch too early. The JIT is very aggressive about keeping an
+ // This method DOES NOT DO ANYTHING in and of itself. It's used to
+ // prevent a finalizable object from losing any outstanding references
+ // a touch too early. The JIT is very aggressive about keeping an
// object's lifetime to as small a window as possible, to the point
// where a 'this' pointer isn't considered live in an instance method
- // unless you read a value from the instance. So for finalizable
- // objects that store a handle or pointer and provide a finalizer that
- // cleans them up, this can cause subtle race conditions with the finalizer
- // thread. This isn't just about handles - it can happen with just
+ // unless you read a value from the instance. So for finalizable
+ // objects that store a handle or pointer and provide a finalizer that
+ // cleans them up, this can cause subtle race conditions with the finalizer
+ // thread. This isn't just about handles - it can happen with just
// about any finalizable resource.
//
// Users should insert a call to this method right after the last line
// be eligible for collection until the call to this method happens.
// Once the call to this method has happened the object may immediately
// become eligible for collection. Here is an example:
- //
- // "...all you really need is one object with a Finalize method, and a
- // second object with a Close/Dispose/Done method. Such as the following
+ //
+ // "...all you really need is one object with a Finalize method, and a
+ // second object with a Close/Dispose/Done method. Such as the following
// contrived example:
//
// class Foo {
// void Problem() { stream.MethodThatSpansGCs(); }
// static void Main() { new Foo().Problem(); }
// }
- //
//
- // In this code, Foo will be finalized in the middle of
+ //
+ // In this code, Foo will be finalized in the middle of
// stream.MethodThatSpansGCs, thus closing a stream still in use."
//
// If we insert a call to GC.KeepAlive(this) at the end of Problem(), then
}
// Indicates that the system should call the Finalize() method on an object
- // for which SuppressFinalize has already been called. The other situation
- // where calling ReRegisterForFinalize is useful is inside a finalizer that
+ // for which SuppressFinalize has already been called. The other situation
+ // where calling ReRegisterForFinalize is useful is inside a finalizer that
// needs to resurrect itself or an object that it references.
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern void _ReRegisterForFinalize(object o);
long size = GetTotalMemory();
if (!forceFullCollection)
return size;
- // If we force a full collection, we will run the finalizers on all
+ // If we force a full collection, we will run the finalizers on all
// existing objects and do a collection until the value stabilizes.
- // The value is "stable" when either the value is within 5% of the
+ // The value is "stable" when either the value is within 5% of the
// previous call to GetTotalMemory, or if we have been sitting
// here for more than x times (we don't want to loop forever here).
int reps = 20; // Number of iterations
}
}
- // Skips zero-initialization of the array if possible. If T contains object references,
+ // Skips zero-initialization of the array if possible. If T contains object references,
// the array is always zero-initialized.
internal static T[] AllocateUninitializedArray<T>(int length)
{
#else
// otherwise small arrays are allocated using `new[]` as that is generally faster.
//
- // The threshold was derived from various simulations.
+ // The threshold was derived from various simulations.
// As it turned out the threshold depends on overal pattern of all allocations and is typically in 200-300 byte range.
// The gradient around the number is shallow (there is no perf cliff) and the exact value of the threshold does not matter a lot.
// So it is 256 bytes including array header.
string? message = null;
if (hResult == System.HResults.COR_E_BADEXEFORMAT)
message = SR.Arg_BadImageFormatException;
- else
+ else
GetMessageForHR(hResult, JitHelpers.GetStringHandleOnStack(ref message));
return string.Format(format, fileName, message);
** and other miscellaneous stuff.
**
**
-**
+**
===========================================================*/
#nullable disable // Code in this file isn't actually executed
// of keeping the JIT-compiler out for generic instantiations.
// Method marked as NoOptimization as we don't want the JIT to
- // inline any methods or take any short-circuit paths since the
- // instantiation closure process is driven by "fixup" references
+ // inline any methods or take any short-circuit paths since the
+ // instantiation closure process is driven by "fixup" references
// left in the final code stream.
[MethodImplAttribute(MethodImplOptions.NoOptimization)]
static CommonlyUsedGenericInstantiations()
{
- // Make absolutely sure we include some of the most common
+ // Make absolutely sure we include some of the most common
// instantiations here in mscorlib's ngen image.
// Note that reference type instantiations are already included
// automatically for us.
WinRT_IEnumerable<float>(null, null, null);
WinRT_IEnumerable<double>(null, null, null);
- // The underlying WinRT types for shared instantiations have to be referenced explicitly.
+ // The underlying WinRT types for shared instantiations have to be referenced explicitly.
// They are not guaranteeed to be created indirectly because of generic code sharing.
WinRT_IEnumerable<string>(null, null, null); typeof(IIterable<string>).ToString(); typeof(IIterator<string>).ToString();
WinRT_IEnumerable<object>(null, null, null); typeof(IIterable<object>).ToString(); typeof(IIterator<object>).ToString();
**
** Purpose: Some floating-point math operations
**
-**
+**
===========================================================*/
//This class contains only static members and doesn't require serialization.
[MethodImpl(MethodImplOptions.InternalCall)]
private static extern double FMod(double x, double y);
-
+
[MethodImpl(MethodImplOptions.InternalCall)]
private static extern unsafe double ModF(double x, double* intptr);
}
[MethodImpl(MethodImplOptions.InternalCall)]
private static extern float FMod(float x, float y);
-
+
[MethodImpl(MethodImplOptions.InternalCall)]
private static extern unsafe float ModF(float x, float* intptr);
}
{
}
- // This constructor is called from a class to generate a
+ // This constructor is called from a class to generate a
// delegate based upon a static method name and the Type object
// for the class defining the method.
protected MulticastDelegate(Type target, string method) : base(target, method)
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public extern Type GetType();
- // Returns a new object instance that is a memberwise copy of this
+ // Returns a new object instance that is a memberwise copy of this
// object. This is always a shallow copy of the instance. The method is protected
// so that other object may only call this method on themselves. It is intended to
// support the ICloneable interface.
// Use the OA variant lib to convert primitive types.
try
{
-#if DISPLAY_DEBUG_INFO
+#if DISPLAY_DEBUG_INFO
Console.WriteLine("Using OAVariantLib.ChangeType() to do the conversion");
-#endif
+#endif
// Specify the LocalBool flag to have BOOL values converted to local language rather
// than 0 or -1.
object RetObj = OAVariantLib.ChangeType(myValue, type, OAVariantLib.LocalBool, cultureInfo).ToObject()!;
-#if DISPLAY_DEBUG_INFO
+#if DISPLAY_DEBUG_INFO
Console.WriteLine("Object returned from ChangeType is of type: " + RetObj.GetType().Name);
#endif
return RetObj;
}
-#if DISPLAY_DEBUG_INFO
+#if DISPLAY_DEBUG_INFO
catch(NotSupportedException e)
#else
catch (NotSupportedException)
-#endif
+#endif
{
-#if DISPLAY_DEBUG_INFO
+#if DISPLAY_DEBUG_INFO
Console.Write("Exception thrown: ");
Console.WriteLine(e);
-#endif
+#endif
throw new COMException(SR.Interop_COM_TypeMismatch, unchecked((int)0x80020005));
}
}
[MethodImpl(MethodImplOptions.InternalCall)]
internal extern void nInit();
-
+
// This call opens and closes the file, but does not add the
// assembly to the domain.
[MethodImpl(MethodImplOptions.InternalCall)]
{
MethodAttributes methAttr = RuntimeMethodHandle.GetAttributes(associateMethodHandle);
- // ECMA MethodSemantics: "All methods for a given Property or Event shall have the same accessibility
+ // ECMA MethodSemantics: "All methods for a given Property or Event shall have the same accessibility
//(ie the MemberAccessMask subfield of their Flags row) and cannot be CompilerControlled [CLS]"
// Consequently, a property may be composed of public and private methods. If the declared type !=
- // the reflected type, the private methods should not be exposed. Note that this implies that the
+ // the reflected type, the private methods should not be exposed. Note that this implies that the
// identity of a property includes it's reflected type.
if ((methAttr & MethodAttributes.MemberAccessMask) == MethodAttributes.Private)
return null;
- // Note this is the first time the property was encountered walking from the most derived class
+ // Note this is the first time the property was encountered walking from the most derived class
// towards the base class. It would seem to follow that any associated methods would not
// be overriden -- but this is not necessarily true. A more derived class may have overriden a
- // virtual method associated with a property in a base class without associating the override with
- // the same or any property in the derived class.
+ // virtual method associated with a property in a base class without associating the override with
+ // the same or any property in the derived class.
if ((methAttr & MethodAttributes.Virtual) != 0)
{
bool declaringTypeIsClass =
for (int i = 0; i < records.Length; i++)
{
- scope.GetCustomAttributeProps(tkCustomAttributeTokens[i],
+ scope.GetCustomAttributeProps(tkCustomAttributeTokens[i],
out records[i].tkCtor.Value, out records[i].blob);
}
PseudoCustomAttribute.GetCustomAttributes(type, caType, out RuntimeType.ListBuilder<Attribute> pcas);
// if we are asked to go up the hierarchy chain we have to do it now and regardless of the
- // attribute usage for the specific attribute because a derived attribute may override the usage...
+ // attribute usage for the specific attribute because a derived attribute may override the usage...
// ... however if the attribute is sealed we can rely on the attribute usage
if (!inherit || (caType.IsSealed && !CustomAttribute.GetAttributeUsage(caType).Inherited))
{
PseudoCustomAttribute.GetCustomAttributes(method, caType, out RuntimeType.ListBuilder<Attribute> pcas);
// if we are asked to go up the hierarchy chain we have to do it now and regardless of the
- // attribute usage for the specific attribute because a derived attribute may override the usage...
+ // attribute usage for the specific attribute because a derived attribute may override the usage...
// ... however if the attribute is sealed we can rely on the attribute usage
if (!inherit || (caType.IsSealed && !CustomAttribute.GetAttributeUsage(caType).Inherited))
{
}
}
- PropertyInfo? property = type is null ?
- attributeType.GetProperty(name) :
+ PropertyInfo? property = type is null ?
+ attributeType.GetProperty(name) :
attributeType.GetProperty(name, type, Type.EmptyTypes);
// Did we get a valid property reference?
{
#region Private Static Data Members
// Here we can avoid the need to take a lock when using Dictionary by rearranging
- // the only method that adds values to the Dictionary. For more details on
+ // the only method that adds values to the Dictionary. For more details on
// Dictionary versus Hashtable thread safety:
// See code:Dictionary#DictionaryVersusHashtableThreadSafety
private static readonly Dictionary<RuntimeType, RuntimeType> s_pca = CreatePseudoCustomAttributeDictionary();
typeof(FieldOffsetAttribute), // field
typeof(SerializableAttribute), // class, struct, enum, delegate
typeof(MarshalAsAttribute), // parameter, field, return-value
- typeof(ComImportAttribute), // class, interface
+ typeof(ComImportAttribute), // class, interface
typeof(NonSerializedAttribute), // field, inherited
typeof(InAttribute), // parameter
typeof(OutAttribute), // parameter
[Conditional("DEBUG")]
private static void VerifyPseudoCustomAttribute(RuntimeType pca)
{
- // If any of these are invariants are no longer true will have to
+ // If any of these are invariants are no longer true will have to
// re-architect the PCA product logic and test cases -- you've been warned!
Debug.Assert(pca.BaseType == typeof(Attribute), "Pseudo CA Error");
AttributeUsageAttribute usage = CustomAttribute.GetAttributeUsage(pca);
// Metadata parameter checking should not have allowed 0 for packing size.
// The runtime later converts a packing size of 0 to 8 so do the same here
- // because it's more useful from a user perspective.
+ // because it's more useful from a user perspective.
if (pack == 0)
pack = 8; // DEFAULT_PACKING_SIZE
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
-// For each dynamic assembly there will be two AssemblyBuilder objects: the "internal"
+// For each dynamic assembly there will be two AssemblyBuilder objects: the "internal"
// AssemblyBuilder object and the "external" AssemblyBuilder object.
-// 1. The "internal" object is the real assembly object that the VM creates and knows about. However,
-// you can perform RefEmit operations on it only if you have its granted permission. From the AppDomain
+// 1. The "internal" object is the real assembly object that the VM creates and knows about. However,
+// you can perform RefEmit operations on it only if you have its granted permission. From the AppDomain
// and other "internal" objects like the "internal" ModuleBuilders and runtime types, you can only
// get the "internal" objects. This is to prevent low-trust code from getting a hold of the dynamic
-// AssemblyBuilder/ModuleBuilder/TypeBuilder/MethodBuilder/etc other people have created by simply
+// AssemblyBuilder/ModuleBuilder/TypeBuilder/MethodBuilder/etc other people have created by simply
// enumerating the AppDomain and inject code in it.
// 2. The "external" object is merely an wrapper of the "internal" object and all operations on it
// are directed to the internal object. This is the one you get by calling DefineDynamicAssembly
namespace System.Reflection.Emit
{
- // When the user calls AppDomain.DefineDynamicAssembly the loader creates a new InternalAssemblyBuilder.
+ // When the user calls AppDomain.DefineDynamicAssembly the loader creates a new InternalAssemblyBuilder.
// This InternalAssemblyBuilder can be retrieved via a call to Assembly.GetAssemblies() by untrusted code.
// In the past, when InternalAssemblyBuilder was AssemblyBuilder, the untrusted user could down cast the
- // Assembly to an AssemblyBuilder and emit code with the elevated permissions of the trusted code which
+ // Assembly to an AssemblyBuilder and emit code with the elevated permissions of the trusted code which
// originally created the AssemblyBuilder via DefineDynamicAssembly. Today, this can no longer happen
// because the Assembly returned via AssemblyGetAssemblies() will be an InternalAssemblyBuilder.
- // Only the caller of DefineDynamicAssembly will get an AssemblyBuilder.
- // There is a 1-1 relationship between InternalAssemblyBuilder and AssemblyBuilder.
+ // Only the caller of DefineDynamicAssembly will get an AssemblyBuilder.
+ // There is a 1-1 relationship between InternalAssemblyBuilder and AssemblyBuilder.
// AssemblyBuilder is composed of its InternalAssemblyBuilder.
- // The AssemblyBuilder data members (e.g. m_foo) were changed to properties which then delegate
- // the access to the composed InternalAssemblyBuilder. This way, AssemblyBuilder simply wraps
- // InternalAssemblyBuilder and still operates on InternalAssemblyBuilder members.
+ // The AssemblyBuilder data members (e.g. m_foo) were changed to properties which then delegate
+ // the access to the composed InternalAssemblyBuilder. This way, AssemblyBuilder simply wraps
+ // InternalAssemblyBuilder and still operates on InternalAssemblyBuilder members.
// This also makes the change transparent to the loader. This is good because most of the complexity
- // of Assembly building is in the loader code so not touching that code reduces the chance of
+ // of Assembly building is in the loader code so not touching that code reduces the chance of
// introducing new bugs.
internal sealed class InternalAssemblyBuilder : RuntimeAssembly
{
#endregion
}
-
+
public sealed class AssemblyBuilder : Assembly
{
[MethodImplAttribute(MethodImplOptions.InternalCall)]
StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
return InternalDefineDynamicAssembly(name, access, ref stackMark, null);
}
-
+
[DynamicSecurityMethod] // Methods containing StackCrawlMark local var has to be marked DynamicSecurityMethod.
public static AssemblyBuilder DefineDynamicAssembly(
AssemblyName name,
#region DefineDynamicModule
/// <summary>
- /// Defines a named dynamic module. It is an error to define multiple
+ /// Defines a named dynamic module. It is an error to define multiple
/// modules within an Assembly with the same name. This dynamic module is
/// a transient module.
/// </summary>
{
return InternalAssembly.GetLoadedModules(getResourceModules);
}
-
+
public override Assembly GetSatelliteAssembly(CultureInfo culture)
{
return InternalAssembly.GetSatelliteAssembly(culture, null);
}
- /// <sumary>
+ /// <sumary>
/// Useful for binding to a very specific version of a satellite assembly
/// </sumary>
public override Assembly GetSatelliteAssembly(CultureInfo culture, Version? version)
public override bool IsCollectible => InternalAssembly.IsCollectible;
#endregion
-
+
/// <param name="name">The name of module for the look up.</param>
/// <returns>Dynamic module with the specified name.</returns>
public ModuleBuilder? GetDynamicModule(string name)
false,
typeof(DebuggableAttribute) == con.DeclaringType);
}
-
+
/// <summary>
/// Use this function if client wishes to build CustomAttribute using CustomAttributeBuilder.
/// </summary>
public ParameterBuilder DefineParameter(int iSequence, ParameterAttributes attributes, string? strParamName)
{
- // Theoretically we shouldn't allow iSequence to be 0 because in reflection ctors don't have
- // return parameters. But we'll allow it for backward compatibility with V2. The attributes
+ // Theoretically we shouldn't allow iSequence to be 0 because in reflection ctors don't have
+ // return parameters. But we'll allow it for backward compatibility with V2. The attributes
// defined on the return parameters won't be very useful but won't do much harm either.
// MD will assert if we try to set the reserved bits explicitly
#endregion
}
}
-
/*============================================================
**
-**
-**
+**
+**
**
**
** CustomAttributeBuilder is a helper class to help building custom attribute.
**
-**
+**
===========================================================*/
using System.Buffers.Binary;
for (i = 0; i < cParams; i++)
sig.AddArgument(parameterTypes[i]);
- // If there is a non-void return type, push one.
+ // If there is a non-void return type, push one.
if (returnType != typeof(void))
stackchange++;
//
//
- // debugger related calls.
+ // debugger related calls.
//
//
public override void UsingNamespace(string ns)
//
// We can destroy the unmanaged part of dynamic method only after the managed part is definitely gone and thus
- // nobody can call the dynamic method anymore. A call to finalizer alone does not guarantee that the managed
+ // nobody can call the dynamic method anymore. A call to finalizer alone does not guarantee that the managed
// part is gone. A malicious code can keep a reference to DynamicMethod in long weak reference that survives finalization,
// or we can be running during shutdown where everything is finalized.
//
- // The unmanaged resolver keeps a reference to the managed resolver in long weak handle. If the long weak handle
- // is null, we can be sure that the managed part of the dynamic method is definitely gone and that it is safe to
- // destroy the unmanaged part. (Note that the managed finalizer has to be on the same object that the long weak handle
- // points to in order for this to work.) Unfortunately, we can not perform the above check when out finalizer
- // is called - the long weak handle won't be cleared yet. Instead, we create a helper scout object that will attempt
+ // The unmanaged resolver keeps a reference to the managed resolver in long weak handle. If the long weak handle
+ // is null, we can be sure that the managed part of the dynamic method is definitely gone and that it is safe to
+ // destroy the unmanaged part. (Note that the managed finalizer has to be on the same object that the long weak handle
+ // points to in order for this to work.) Unfortunately, we can not perform the above check when out finalizer
+ // is called - the long weak handle won't be cleared yet. Instead, we create a helper scout object that will attempt
// to do the destruction after next GC.
//
- // The finalization does not have to be done using CriticalFinalizerObject. We have to go over all DynamicMethodDescs
+ // The finalization does not have to be done using CriticalFinalizerObject. We have to go over all DynamicMethodDescs
// during AppDomain shutdown anyway to avoid leaks e.g. if somebody stores reference to DynamicMethod in static.
//
~DynamicResolver()
// DynamicMethod (just like we do for delegates). However, a user can get to
// the corresponding RTDynamicMethod using Exception.TargetSite, StackFrame.GetMethod, etc.
// If we allowed use of RTDynamicMethod, the creator of the DynamicMethod would
- // not be able to bound access to the DynamicMethod. Hence, we need to ensure that
+ // not be able to bound access to the DynamicMethod. Hence, we need to ensure that
// we do not allow direct use of RTDynamicMethod.
private RTDynamicMethod m_dynMethod = null!;
}
MulticastDelegate d = (MulticastDelegate)Delegate.CreateDelegateNoSecurityCheck(delegateType, null, GetMethodDescriptor());
- // stash this MethodInfo by brute force.
+ // stash this MethodInfo by brute force.
d.StoreDynamicMethod(GetMethodInfo());
return d;
}
}
MulticastDelegate d = (MulticastDelegate)Delegate.CreateDelegateNoSecurityCheck(delegateType, target, GetMethodDescriptor());
- // stash this MethodInfo by brute force.
+ // stash this MethodInfo by brute force.
d.StoreDynamicMethod(GetMethodInfo());
return d;
}
//
// We do not demand any permission here because the caller already has access
- // to the current DynamicMethod object, and it could just as easily emit another
+ // to the current DynamicMethod object, and it could just as easily emit another
// Transparent DynamicMethod to call the current DynamicMethod.
//
}
}
}
-
/*============================================================
**
-**
-**
**
**
-** EnumBuilder is a helper class to build Enum ( a special type ).
**
-**
+**
+** EnumBuilder is a helper class to build Enum ( a special type ).
+**
+**
===========================================================*/
using CultureInfo = System.Globalization.CultureInfo;
public FieldBuilder DefineLiteral(string literalName, object? literalValue)
{
- // Define the underlying field for the enum. It will be a non-static, private field with special name bit set.
+ // Define the underlying field for the enum. It will be a non-static, private field with special name bit set.
FieldBuilder fieldBuilder = m_typeBuilder.DefineField(
literalName,
this,
}
- // Returns true if one or more instance of attributeType is defined on this member.
+ // Returns true if one or more instance of attributeType is defined on this member.
public override bool IsDefined(Type attributeType, bool inherit)
{
return m_typeBuilder.IsDefined(attributeType, inherit);
}
/*****************************************************
- *
+ *
* private/protected functions
- *
+ *
*/
public override Type MakePointerType()
throw new ArgumentException(SR.Argument_ShouldOnlySetVisibilityFlags, nameof(name));
m_typeBuilder = new TypeBuilder(name, visibility | TypeAttributes.Sealed, typeof(System.Enum), null, module, PackingSize.Unspecified, TypeBuilder.UnspecifiedTypeSize, null);
- // Define the underlying field for the enum. It will be a non-static, private field with special name bit set.
+ // Define the underlying field for the enum. It will be a non-static, private field with special name bit set.
m_underlyingField = m_typeBuilder.DefineField("value__", underlyingType, FieldAttributes.Public | FieldAttributes.SpecialName | FieldAttributes.RTSpecialName);
}
/*****************************************************
- *
+ *
* private data members
- *
+ *
*/
internal TypeBuilder m_typeBuilder;
private FieldBuilder m_underlyingField;
/*============================================================
**
-**
-**
+**
+**
**
**
** Eventbuilder is for client to define eevnts for a class
**
-**
+**
===========================================================*/
using System.Runtime.CompilerServices;
namespace System.Reflection.Emit
{
- //
+ //
// A EventBuilder is always associated with a TypeBuilder. The TypeBuilder.DefineEvent
// method will return a new EventBuilder to a client.
- //
+ //
public sealed class EventBuilder
{
- // Constructs a EventBuilder.
+ // Constructs a EventBuilder.
//
internal EventBuilder(
- ModuleBuilder mod, // the module containing this EventBuilder
+ ModuleBuilder mod, // the module containing this EventBuilder
string name, // Event name
EventAttributes attr, // event attribute such as Public, Private, and Protected defined above
//int eventType, // event type
public override object? GetValue(object? obj)
{
- // NOTE!! If this is implemented, make sure that this throws
+ // NOTE!! If this is implemented, make sure that this throws
// a NotSupportedException for Save-only dynamic assemblies.
// Otherwise, it could cause the .cctor to be executed.
public override void SetValue(object? obj, object? val, BindingFlags invokeAttr, Binder? binder, CultureInfo? culture)
{
- // NOTE!! If this is implemented, make sure that this throws
+ // NOTE!! If this is implemented, make sure that this throws
// a NotSupportedException for Save-only dynamic assemblies.
// Otherwise, it could cause the .cctor to be executed.
//
// This file implements the minimum subset of ISymWrapper.dll required to restore
// that functionality. Namely, the SymWriter and SymDocumentWriter objects.
- //
+ //
// Ideally we wouldn't need ISymWrapper.dll on desktop either - it's an ugly piece
// of legacy. We could just use this (or COM-interop code) everywhere, but we might
// have to worry about compatibility.
- //
+ //
// We've now got a real implementation even when no debugger is attached. It's
- // up to the runtime to ensure it doesn't provide us with an insecure writer
+ // up to the runtime to ensure it doesn't provide us with an insecure writer
// (eg. diasymreader) in the no-trust scenarios (no debugger, partial-trust code).
//-----------------------------------------------------------------------------------
internal unsafe class SymWriter : ISymbolWriter
{
//------------------------------------------------------------------------------
- // Creates a SymWriter. The SymWriter is a managed wrapper around the unmanaged
+ // Creates a SymWriter. The SymWriter is a managed wrapper around the unmanaged
// symbol writer provided by the runtime (ildbsymlib or diasymreader.dll).
//------------------------------------------------------------------------------
internal static ISymbolWriter CreateSymWriter()
//------------------------------------------------------------------------------
// Basic ctor. You'd think this ctor would take the unmanaged symwriter object as an argument
- // but to fit in with existing desktop code, the unmanaged writer is passed in
+ // but to fit in with existing desktop code, the unmanaged writer is passed in
// through a subsequent call to InternalSetUnderlyingWriter
//------------------------------------------------------------------------------
private SymWriter()
//------------------------------------------------------------------------------
// InternalSetUnderlyingWriter() wrapper.
//
- // Furnishes the native ISymUnmanagedWriter* pointer.
+ // Furnishes the native ISymUnmanagedWriter* pointer.
//
// The parameter is actually a pointer to a pointer to an ISymUnmanagedWriter. As
// with the real ISymWrapper.dll, ISymWrapper performs *no* Release (or AddRef) on pointers
// front of the signature, but InternalGetSignature returns
// the callinging convention. So we strip it off. This is a
// bit unfortunate, since it means that we need to allocate
- // yet another array of bytes...
+ // yet another array of bytes...
mungedSig = new byte[sigLength - 1];
Buffer.BlockCopy(signature, 1, mungedSig, 0, sigLength - 1);
#endregion
}
}
-
m_parameterTypeRequiredCustomModifiers = parameterTypeRequiredCustomModifiers;
m_parameterTypeOptionalCustomModifiers = parameterTypeOptionalCustomModifiers;
- // m_signature = SignatureHelper.GetMethodSigHelper(mod, callingConvention,
+ // m_signature = SignatureHelper.GetMethodSigHelper(mod, callingConvention,
// returnType, returnTypeRequiredCustomModifiers, returnTypeOptionalCustomModifiers,
// parameterTypes, parameterTypeRequiredCustomModifiers, parameterTypeOptionalCustomModifiers);
// The change also introduced race conditions. Before the code change GetToken is called from
// the MethodBuilder .ctor which is protected by lock(ModuleBuilder.SyncRoot). Now it
// could be called more than once on the the same method introducing duplicate (invalid) tokens.
- // I don't fully understand this change. So I will keep the logic and only fix the recursion and
+ // I don't fully understand this change. So I will keep the logic and only fix the recursion and
// the race condition.
if (m_tkMethod.Token != 0)
internal class LocalSymInfo
{
- // This class tracks the local variable's debugging information
+ // This class tracks the local variable's debugging information
// and namespace information with a given active lexical scope.
#region Internal Data Members
[StructLayout(LayoutKind.Sequential)]
internal readonly struct ExceptionHandler : IEquatable<ExceptionHandler>
{
- // Keep in sync with unmanged structure.
+ // Keep in sync with unmanged structure.
internal readonly int m_exceptionClass;
internal readonly int m_tryStartOffset;
internal readonly int m_tryEndOffset;
#endregion
}
}
-
-
-
-
-
-
-
-
-
-
#endregion
}
}
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
}
else if (!method.Module.Equals(this))
{
- // Use typeRef as parent because the method's declaringType lives in a different assembly
+ // Use typeRef as parent because the method's declaringType lives in a different assembly
tkParent = GetTypeToken(method.DeclaringType).Token;
}
else
private Type? GetTypeNoLock(string className, bool throwOnError, bool ignoreCase)
{
// public API to to a type. The reason that we need this function override from module
- // is because clients might need to get foo[] when foo is being built. For example, if
+ // is because clients might need to get foo[] when foo is being built. For example, if
// foo class contains a data member of type foo[].
- // This API first delegate to the Module.GetType implementation. If succeeded, great!
+ // This API first delegate to the Module.GetType implementation. If succeeded, great!
// If not, we have to look up the current module to find the TypeBuilder to represent the base
// type and form the Type object for "foo[,]".
- // Module.GetType() will verify className.
+ // Module.GetType() will verify className.
Type? baseType = InternalModule.GetType(className, throwOnError, ignoreCase);
if (baseType != null)
return baseType;
public FieldBuilder DefineInitializedData(string name, byte[] data, FieldAttributes attributes)
{
- // This method will define an initialized Data in .sdata.
+ // This method will define an initialized Data in .sdata.
// We will create a fake TypeDef to represent the data with size. This TypeDef
- // will be the signature for the Field.
+ // will be the signature for the Field.
lock (SyncRoot)
{
private FieldBuilder DefineInitializedDataNoLock(string name, byte[] data, FieldAttributes attributes)
{
- // This method will define an initialized Data in .sdata.
+ // This method will define an initialized Data in .sdata.
// We will create a fake TypeDef to represent the data with size. This TypeDef
// will be the signature for the Field.
if (_moduleData._hasGlobalBeenCreated == true)
private FieldBuilder DefineUninitializedDataNoLock(string name, int size, FieldAttributes attributes)
{
- // This method will define an uninitialized Data in .sdata.
+ // This method will define an uninitialized Data in .sdata.
// We will create a fake TypeDef to represent the data with size. This TypeDef
- // will be the signature for the Field.
+ // will be the signature for the Field.
if (_moduleData._hasGlobalBeenCreated)
{
#region GetToken
- // For a generic type definition, we should return the token for the generic type definition itself in two cases:
+ // For a generic type definition, we should return the token for the generic type definition itself in two cases:
// 1. GetTypeToken
// 2. ldtoken (see ILGenerator)
// For all other occasions we should return the generic type instantiated on its formal parameters.
public TypeToken GetTypeToken(string name)
{
- // Return a token for the class relative to the Module.
+ // Return a token for the class relative to the Module.
// Module.GetType() verifies name
- // Unfortunately, we will need to load the Type and then call GetTypeToken in
+ // Unfortunately, we will need to load the Type and then call GetTypeToken in
// order to correctly track the assembly reference information.
return GetTypeToken(InternalModule.GetType(name, false, true)!);
// For all other occasions we should return the method on the generic type instantiated on the formal parameters.
private MethodToken GetMethodTokenNoLock(MethodInfo method, bool getGenericTypeDefinition)
{
- // Return a MemberRef token if MethodInfo is not defined in this module. Or
- // return the MethodDef token.
+ // Return a MemberRef token if MethodInfo is not defined in this module. Or
+ // return the MethodDef token.
if (method == null)
{
throw new ArgumentNullException(nameof(method));
}
// Create signature of method instantiation M<Bar>
- // Create MethodSepc M<Bar> with parent G?.M<S>
+ // Create MethodSepc M<Bar> with parent G?.M<S>
byte[] sigBytes = SignatureHelper.GetMethodSpecSigHelper(
this, methodInfo.GetGenericArguments()).InternalGetSignature(out int sigLength);
ModuleBuilder thisModule = this;
CheckContext(parameterTypes);
// Return a token for the MethodInfo for a method on an Array. This is primarily
- // used to get the LoadElementAddress method.
+ // used to get the LoadElementAddress method.
SignatureHelper sigHelp = SignatureHelper.GetMethodSigHelper(
this, callingConvention, returnType, null, null, parameterTypes, null, null);
byte[] sigBytes = sigHelp.InternalGetSignature(out int length);
CheckContext(returnType, arrayClass);
CheckContext(parameterTypes);
- // GetArrayMethod is useful when you have an array of a type whose definition has not been completed and
- // you want to access methods defined on Array. For example, you might define a type and want to define a
- // method that takes an array of the type as a parameter. In order to access the elements of the array,
+ // GetArrayMethod is useful when you have an array of a type whose definition has not been completed and
+ // you want to access methods defined on Array. For example, you might define a type and want to define a
+ // method that takes an array of the type as a parameter. In order to access the elements of the array,
// you will need to call methods of the Array class.
MethodToken token = GetArrayMethodToken(arrayClass, methodName, callingConvention, returnType, parameterTypes);
public MethodToken GetConstructorToken(ConstructorInfo con)
{
- // Return a token for the ConstructorInfo relative to the Module.
+ // Return a token for the ConstructorInfo relative to the Module.
return InternalGetConstructorToken(con, false);
}
throw new ArgumentNullException(nameof(str));
}
- // Returns a token representing a String constant. If the string
+ // Returns a token representing a String constant. If the string
// value has already been defined, the existing token will be returned.
ModuleBuilder thisModule = this;
return new StringToken(GetStringConstant(JitHelpers.GetQCallModuleOnStack(ref thisModule), str, str.Length));
customBuilder.CreateCustomAttribute(this, 1); // This is hard coding the module token to 1
}
- // This API returns the symbol writer being used to write debug symbols for this
+ // This API returns the symbol writer being used to write debug symbols for this
// module (if any).
- //
- // WARNING: It is unlikely this API can be used correctly by applications in any
+ //
+ // WARNING: It is unlikely this API can be used correctly by applications in any
// reasonable way. It may be called internally from within TypeBuilder.CreateType.
- //
+ //
// Specifically:
// 1. The underlying symbol writer (written in unmanaged code) is not necessarily well
// hardenned and fuzz-tested against malicious API calls. The security of partial-trust
// symbol writing is improved by restricting usage of the writer APIs to the well-structured
- // uses in ModuleBuilder.
- // 2. TypeBuilder.CreateType emits all the symbols for the type. This will effectively
- // overwrite anything someone may have written manually about the type (specifically
- // ISymbolWriter.OpenMethod is specced to clear anything previously written for the
+ // uses in ModuleBuilder.
+ // 2. TypeBuilder.CreateType emits all the symbols for the type. This will effectively
+ // overwrite anything someone may have written manually about the type (specifically
+ // ISymbolWriter.OpenMethod is specced to clear anything previously written for the
// specified method)
- // 3. Someone could technically update the symbols for a method after CreateType is
- // called, but the debugger (which uses these symbols) assumes that they are only
- // updated at TypeBuilder.CreateType time. The changes wouldn't be visible (committed
+ // 3. Someone could technically update the symbols for a method after CreateType is
+ // called, but the debugger (which uses these symbols) assumes that they are only
+ // updated at TypeBuilder.CreateType time. The changes wouldn't be visible (committed
// to the underlying stream) until another type was baked.
- // 4. Access to the writer is supposed to be synchronized (the underlying COM API is
- // not thread safe, and these are only thin wrappers on top of them). Exposing this
- // directly allows the synchronization to be violated. We know that concurrent symbol
+ // 4. Access to the writer is supposed to be synchronized (the underlying COM API is
+ // not thread safe, and these are only thin wrappers on top of them). Exposing this
+ // directly allows the synchronization to be violated. We know that concurrent symbol
// writer access can cause AVs and other problems. The writer APIs should not be callable
- // directly by partial-trust code, but if they could this would be a security hole.
- // Regardless, this is a reliability bug.
+ // directly by partial-trust code, but if they could this would be a security hole.
+ // Regardless, this is a reliability bug.
internal ISymbolWriter? GetSymWriter() => _iSymWriter;
public ISymbolDocumentWriter? DefineDocument(string url, Guid language, Guid languageVendor, Guid documentType)
{
- // url cannot be null but can be an empty string
+ // url cannot be null but can be an empty string
if (url == null)
{
throw new ArgumentNullException(nameof(url));
#endregion
- #endregion
+ #endregion
}
}
/*============================================================
**
-**
-**
+**
+**
**
**
** Propertybuilder is for client to define properties for a class
**
-**
+**
===========================================================*/
using System.Runtime.CompilerServices;
namespace System.Reflection.Emit
{
- //
+ //
// A PropertyBuilder is always associated with a TypeBuilder. The TypeBuilder.DefineProperty
// method will return a new PropertyBuilder to a client.
- //
+ //
public sealed class PropertyBuilder : PropertyInfo
{
- // Constructs a PropertyBuilder.
+ // Constructs a PropertyBuilder.
//
internal PropertyBuilder(
ModuleBuilder mod, // the module containing this PropertyBuilder
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
-//
+//
using System.Text;
using System;
private void AddOneArgTypeHelper(Type clsArgument, Type[]? requiredCustomModifiers, Type[]? optionalCustomModifiers)
{
- // This function will not increase the argument count. It only fills in bytes
+ // This function will not increase the argument count. It only fills in bytes
// in the signature based on clsArgument. This helper is called for return type.
Debug.Assert(clsArgument != null);
if (rid > 0x3FFFFFF)
{
- // token is too big to be compressed
+ // token is too big to be compressed
throw new ArgumentException(SR.Argument_LargeInteger);
}
rid = (rid << 2);
- // TypeDef is encoded with low bits 00
- // TypeRef is encoded with low bits 01
- // TypeSpec is encoded with low bits 10
+ // TypeDef is encoded with low bits 00
+ // TypeRef is encoded with low bits 01
+ // TypeSpec is encoded with low bits 10
if (type == MetadataTokenType.TypeRef)
{
//if type is mdtTypeRef
private unsafe void InternalAddRuntimeType(Type type)
{
- // Add a runtime type into the signature.
+ // Add a runtime type into the signature.
AddElementType(CorElementType.ELEMENT_TYPE_INTERNAL);
{
m_sigDone = true;
- // If we have more than 128 variables, we can't just set the length, we need
- // to compress it. Unfortunately, this means that we need to copy the entire
+ // If we have more than 128 variables, we can't just set the length, we need
+ // to compress it. Unfortunately, this means that we need to copy the entire
// array.
SetNumberOfSignatureElements(false);
}
// Add an argument to the signature. Takes a Type and determines whether it
// is one of the primitive types of which we have special knowledge or a more
- // general class. In the former case, we only add the appropriate short cut encoding,
+ // general class. In the former case, we only add the appropriate short cut encoding,
// otherwise we will calculate proper description for the type.
AddOneArgTypeHelper(argument, requiredCustomModifiers, optionalCustomModifiers);
}
internal byte[] GetSignature(bool appendEndOfSig)
{
- // Chops the internal signature to the appropriate length. Adds the
+ // Chops the internal signature to the appropriate length. Adds the
// end token to the signature and marks the signature as finished so that
// no further tokens can be added. Return the full signature in a trimmed array.
if (!m_sigDone)
m_sigDone = true;
}
- // This case will only happen if the user got the signature through
+ // This case will only happen if the user got the signature through
// InternalGetSignature first and then called GetSignature.
if (m_signature.Length > m_currSig)
{
#endregion
}
}
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
// This is a kind of MethodInfo to represent methods for array type of unbaked type
// Another way to look at this class is as a glorified MethodToken wrapper. At the time of this comment
- // this class is only constructed inside ModuleBuilder.GetArrayMethod and the only interesting thing
+ // this class is only constructed inside ModuleBuilder.GetArrayMethod and the only interesting thing
// passed into it is this MethodToken. The MethodToken was forged using a TypeSpec for an Array type and
- // the name of the method on Array.
+ // the name of the method on Array.
// As none of the methods on Array have CustomModifiers their is no need to pass those around in here.
m_mdMethod = token;
internal static Type? FormCompoundType(string? format, Type baseType, int curIndex)
{
// This function takes a string to describe the compound type, such as "[,][]", and a baseType.
- //
+ //
// Example: [2..4] - one dimension array with lower bound 2 and size of 3
// Example: [3, 5, 6] - three dimension array with lower bound 3, 5, 6
- // Example: [-3, ] [] - one dimensional array of two dimensional array (with lower bound -3 for
+ // Example: [-3, ] [] - one dimensional array of two dimensional array (with lower bound -3 for
// the first dimension)
// Example: []* - pointer to a one dimensional array
// Example: *[] - one dimensional array. The element type is a pointer to the baseType
internal TypeKind m_typeKind;
internal Type m_baseType = null!;
internal int m_cRank; // count of dimension
- // If LowerBound and UpperBound is equal, that means one element.
+ // If LowerBound and UpperBound is equal, that means one element.
// If UpperBound is less than LowerBound, then the size is not specified.
internal int[] m_iaLowerBound;
internal int[] m_iaUpperBound; // count of dimension
#endregion
}
}
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
// D<T,S> : B<S,List<T>,char>
// D<string,int> : B<int,List<string>,char>
- // D<S,T> : B<T,List<S>,char>
- // D<S,string> : B<string,List<S>,char>
+ // D<S,T> : B<T,List<S>,char>
+ // D<S,string> : B<string,List<S>,char>
get
{
Type? typeBldrBase = m_type.BaseType;
#endregion
}
}
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
public override ParameterInfo ReturnParameter { get { throw new NotSupportedException(); } }
public override ICustomAttributeProvider ReturnTypeCustomAttributes { get { throw new NotSupportedException(); } }
public override MethodInfo GetBaseDefinition() { throw new NotSupportedException(); }
- #endregion
+ #endregion
}
internal sealed class ConstructorOnTypeBuilderInstantiation : ConstructorInfo
// for information about this change.
//
// There is a pre-existing race condition in this code with the side effect
- // that the second thread's value clobbers the first in the hashtable. This is
+ // that the second thread's value clobbers the first in the hashtable. This is
// an acceptable race condition since we make no guarantees that this will return the
// same object.
//
- // We're not entirely sure if this cache helps any specific scenarios, so
+ // We're not entirely sure if this cache helps any specific scenarios, so
// long-term, one could investigate whether it's needed. In any case, this
// method isn't expected to be on any critical paths for performance.
if (type.m_hashtable.Contains(Field))
#endregion
}
}
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
{
//
// We can destroy the unmanaged part of collectible type only after the managed part is definitely gone and thus
- // nobody can call/allocate/reference anything related to the collectible assembly anymore. A call to finalizer
+ // nobody can call/allocate/reference anything related to the collectible assembly anymore. A call to finalizer
// alone does not guarantee that the managed part is gone. A malicious code can keep a reference to some object
// in a way that that survives finalization, or we can be running during shutdown where everything is finalized.
//
- // The unmanaged LoaderAllocator keeps a reference to the managed LoaderAllocator in long weak handle. If the long
- // weak handle is null, we can be sure that the managed part of the LoaderAllocator is definitely gone and that it
+ // The unmanaged LoaderAllocator keeps a reference to the managed LoaderAllocator in long weak handle. If the long
+ // weak handle is null, we can be sure that the managed part of the LoaderAllocator is definitely gone and that it
// is safe to destroy the unmanaged part. Unfortunately, we can not perform the above check in a finalizer on the
- // LoaderAllocator, but it can be performed on a helper object.
+ // LoaderAllocator, but it can be performed on a helper object.
//
- // The finalization does not have to be done using CriticalFinalizerObject. We have to go over all LoaderAllocators
+ // The finalization does not have to be done using CriticalFinalizerObject. We have to go over all LoaderAllocators
// during AppDomain shutdown anyway to avoid leaks e.g. if somebody stores reference to LoaderAllocator in a static.
//
internal sealed class LoaderAllocatorScout
#pragma warning restore 169
}
}
-
[Flags()]
internal enum MdSigCallingConvention : byte
{
- CallConvMask = 0x0f, // Calling convention is bottom 4 bits
+ CallConvMask = 0x0f, // Calling convention is bottom 4 bits
Default = 0x00,
C = 0x01,
GenericInst = 0x0a, // generic method instantiation
Generic = 0x10, // Generic method sig with explicit number of type arguments (precedes ordinary parameter count)
- HasThis = 0x20, // Top bit indicates a 'this' parameter
+ HasThis = 0x20, // Top bit indicates a 'this' parameter
ExplicitThis = 0x40, // This parameter is explicitly in the signature
}
}
}
}
-
-
throw new ArgumentNullException(nameof(other));
// Ensure that "other" is a runtime-implemented MemberInfo. Do this check before calling any methods on it!
- if (!(other is TOther))
+ if (!(other is TOther))
return false;
if (MetadataToken != other.MetadataToken)
string typeName = t.FormatTypeName();
- // Legacy: Why use "ByRef" for by ref parameters? What language is this?
+ // Legacy: Why use "ByRef" for by ref parameters? What language is this?
// VB uses "ByRef" but it should precede (not follow) the parameter name.
// Why don't we just use "&"?
if (t.IsByRef)
internal object[] CheckArguments(object[] parameters, Binder? binder,
BindingFlags invokeAttr, CultureInfo? culture, Signature sig)
{
- // copy the arguments in a different array so we detach from any user changes
+ // copy the arguments in a different array so we detach from any user changes
object[] copyOfParameters = new object[parameters.Length];
ParameterInfo[] p = null!;
Type? declaringType = DeclaringType;
//
- // first take care of all the NO_INVOKE cases.
+ // first take care of all the NO_INVOKE cases.
if (declaringType == typeof(void) ||
(declaringType != null && declaringType.ContainsGenericParameters) ||
((CallingConvention & CallingConventions.VarArgs) == CallingConventions.VarArgs))
return m_flags;
}
}
- #endregion
+ #endregion
}
}
{
// This class can only be created from inside the EE.
private RuntimeExceptionHandlingClause() { }
-
+
private RuntimeMethodBody _methodBody = null!;
private ExceptionHandlingClauseOptions _flags;
private int _tryOffset;
private int _handlerLength;
private int _catchMetadataToken;
private int _filterOffset;
-
+
public override ExceptionHandlingClauseOptions Flags => _flags;
public override int TryOffset => _tryOffset;
public override int TryLength => _tryLength;
}
}
}
-
public override IList<ExceptionHandlingClause> ExceptionHandlingClauses => Array.AsReadOnly(_exceptionHandlingClauses);
}
}
-
Type? declaringType = DeclaringType;
//
- // first take care of all the NO_INVOKE cases.
+ // first take care of all the NO_INVOKE cases.
if (ContainsGenericParameters ||
IsDisallowedByRefType(ReturnType) ||
(declaringType != null && declaringType.ContainsGenericParameters) ||
{
Type elementType = ReturnType.GetElementType()!;
if (elementType.IsByRefLike)
- throw new NotSupportedException(SR.NotSupported_ByRefToByRefLikeReturn);
+ throw new NotSupportedException(SR.NotSupported_ByRefToByRefLikeReturn);
if (elementType == typeof(void))
throw new NotSupportedException(SR.NotSupported_ByRefToVoidReturn);
}
{
Signature sig = Signature;
- // get the signature
+ // get the signature
int formalCount = sig.Arguments.Length;
int actualCount = (parameters != null) ? parameters.Length : 0;
int cParamDefs = 0;
// Not all methods have tokens. Arrays, pointers and byRef types do not have tokens as they
- // are generated on the fly by the runtime.
+ // are generated on the fly by the runtime.
if (!MdToken.IsNullToken(tkMethodDef))
{
MetadataImport scope = RuntimeTypeHandle.GetMetadataImport(RuntimeMethodHandle.GetDeclaringType(methodHandle));
cParamDefs = tkParamDefs.Length;
- // Not all parameters have tokens. Parameters may have no token
+ // Not all parameters have tokens. Parameters may have no token
// if they have no name and no attributes.
if (cParamDefs > sigArgCount + 1 /* return type */)
throw new BadImageFormatException(SR.BadImageFormat_ParameterSignatureMismatch);
// Change ownership
MemberImpl = member;
- // The original owner should always be a method, because this method is only used to
+ // The original owner should always be a method, because this method is only used to
// change the owner from a method to a property.
m_originalMember = accessor.MemberImpl as MethodBase;
Debug.Assert(m_originalMember != null);
object? defaultValue = null;
- // Why check the parameter type only for DateTime and only for the ctor arguments?
+ // Why check the parameter type only for DateTime and only for the ctor arguments?
// No check on the parameter type is done for named args and for Decimal.
- // We should move this after MdToken.IsNullToken(m_tkParamDef) and combine it
+ // We should move this after MdToken.IsNullToken(m_tkParamDef) and combine it
// with the other custom attribute logic. But will that be a breaking change?
// For a DateTime parameter on which both an md constant and a ca constant are set,
// which one should win?
}
internal bool EqualsSig(RuntimePropertyInfo target)
{
- //@Asymmetry - Legacy policy is to remove duplicate properties, including hidden properties.
- // The comparison is done by name and by sig. The EqualsSig comparison is expensive
+ //@Asymmetry - Legacy policy is to remove duplicate properties, including hidden properties.
+ // The comparison is done by name and by sig. The EqualsSig comparison is expensive
// but forutnetly it is only called when an inherited property is hidden by name or
- // when an interfaces declare properies with the same signature.
+ // when an interfaces declare properies with the same signature.
// Note that we intentionally don't resolve generic arguments so that we don't treat
// signatures that only match in certain instantiations as duplicates. This has the
// down side of treating overriding and overriden properties as different properties
}
}
- // Now copy over the parameter info's and change their
+ // Now copy over the parameter info's and change their
// owning member info to the current property info.
ParameterInfo[] propParams = new ParameterInfo[numParams];
{
/// <summary>
/// Managed structure used by CrossLoaderAllocatorHeap to isolate per LoaderAllocator
- /// data.
+ /// data.
/// </summary>
[StructLayout(LayoutKind.Sequential)]
internal class LAHashDependentHashTracker
// (! Right now, we get this guarantee for free because (IntPtr)0 == NULL unmanaged handle.
// ! If that assertion ever becomes false, we'll have to add an _isAllocated field
// ! to compensate.)
- //
+ //
//
// IsAllocated == true
// There's a handle allocated underneath. You must call Free() on this eventually
-// 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.
{
return managedView;
}
-
+
managedView = createCallback((T)comObject);
if (!Marshal.SetComObjectData(comObject, key, managedView))
{
using System;
using System.Reflection;
using System.Runtime.Serialization;
-
+
[GuidAttribute("b36b5c63-42ef-38bc-a07e-0b34c98f164a")]
[InterfaceTypeAttribute(ComInterfaceType.InterfaceIsDual)]
[CLSCompliant(false)]
{
//
// This method is intentionally included in CoreCLR to make Exception.get_InnerException "newslot virtual final".
- // Some phone apps include MEF from desktop Silverlight. MEF's ComposablePartException depends on implicit interface
+ // Some phone apps include MEF from desktop Silverlight. MEF's ComposablePartException depends on implicit interface
// implementations of get_InnerException to be provided by the base class. It works only if Exception.get_InnerException
// is virtual.
//
throw new AccessViolationException();
}
- const int Flags =
- (int)AsAnyMarshaler.AsAnyFlags.In |
- (int)AsAnyMarshaler.AsAnyFlags.IsAnsi |
+ const int Flags =
+ (int)AsAnyMarshaler.AsAnyFlags.In |
+ (int)AsAnyMarshaler.AsAnyFlags.IsAnsi |
(int)AsAnyMarshaler.AsAnyFlags.IsBestFit;
MngdNativeArrayMarshaler.MarshalerState nativeArrayMarshalerState = new MngdNativeArrayMarshaler.MarshalerState();
throw new AccessViolationException();
}
- const int Flags =
- (int)AsAnyMarshaler.AsAnyFlags.In |
- (int)AsAnyMarshaler.AsAnyFlags.Out |
- (int)AsAnyMarshaler.AsAnyFlags.IsAnsi |
+ const int Flags =
+ (int)AsAnyMarshaler.AsAnyFlags.In |
+ (int)AsAnyMarshaler.AsAnyFlags.Out |
+ (int)AsAnyMarshaler.AsAnyFlags.IsAnsi |
(int)AsAnyMarshaler.AsAnyFlags.IsBestFit;
MngdNativeArrayMarshaler.MarshalerState nativeArrayMarshalerState = new MngdNativeArrayMarshaler.MarshalerState();
[MethodImpl(MethodImplOptions.InternalCall)]
public static extern /* struct _EXCEPTION_POINTERS* */ IntPtr GetExceptionPointers();
-
+
[MethodImpl(MethodImplOptions.InternalCall)]
public static extern int GetExceptionCode();
/// <summary>
/// Marshals data from a structure class to a native memory block. If the
/// structure contains pointers to allocated blocks and "fDeleteOld" is
- /// true, this routine will call DestroyStructure() first.
+ /// true, this routine will call DestroyStructure() first.
/// </summary>
[MethodImpl(MethodImplOptions.InternalCall), ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
public static extern void StructureToPtr(object structure, IntPtr ptr, bool fDeleteOld);
public static IntPtr AllocHGlobal(IntPtr cb)
{
- // For backwards compatibility on 32 bit platforms, ensure we pass values between
- // int.MaxValue and uint.MaxValue to Windows. If the binary has had the
+ // For backwards compatibility on 32 bit platforms, ensure we pass values between
+ // int.MaxValue and uint.MaxValue to Windows. If the binary has had the
// LARGEADDRESSAWARE bit set in the PE header, it may get 3 or 4 GB of user mode
// address space. It is remotely that those allocations could have succeeded,
// though I couldn't reproduce that. In either case, that means we should continue
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
internal static extern IntPtr LoadByName(string libraryName, QCallAssembly callingAssembly,
- bool hasDllImportSearchPathFlag, uint dllImportSearchPathFlag,
+ bool hasDllImportSearchPathFlag, uint dllImportSearchPathFlag,
bool throwOnError);
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
public WriteOnlyArrayAttribute() { }
}
- // This attribute is applied on the return value to specify the name of the return value.
+ // This attribute is applied on the return value to specify the name of the return value.
// In WindowsRuntime all parameters including return value need to have unique names.
// This is essential in JS as one of the ways to get at the results of a method in JavaScript is via a Dictionary object keyed by parameter name.
[AttributeUsage(AttributeTargets.ReturnValue | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)]
/// This map is backed by a sorted array. Thus, split operations are O(1) and enumerations are fast;
/// however, look-up in the map are O(log n).
/// </summary>
- /// <typeparam name="TKey">Type of objects that act as keys.</typeparam>
+ /// <typeparam name="TKey">Type of objects that act as keys.</typeparam>
/// <typeparam name="TValue">Type of objects that act as entries / values.</typeparam>
[DebuggerDisplay("Count = {Count}")]
internal sealed class ConstantSplittableMap<TKey, TValue> : IMapView<TKey, TValue> where TKey : notnull
target = proxy.GetTarget();
}
- // You can get PropertyInfo for properties with a private getter/public setter (or vice versa)
- // even if you pass BindingFlags.Public only. And in this case, passing binding flags to
+ // You can get PropertyInfo for properties with a private getter/public setter (or vice versa)
+ // even if you pass BindingFlags.Public only. And in this case, passing binding flags to
// GetValue/SetValue won't work as the default binder ignores those values
// Use GetGetMethod/GetSetMethod instead
// That's because they are invoked with special "this"! The "this" object
// for all of these methods are not DictionaryToMapAdapter objects. Rather, they are of type
// IDictionary<K, V>. No actual DictionaryToMapAdapter object is ever instantiated. Thus, you will
- // see a lot of expressions that cast "this" to "IDictionary<K, V>".
+ // see a lot of expressions that cast "this" to "IDictionary<K, V>".
internal sealed class DictionaryToMapAdapter
{
private DictionaryToMapAdapter()
// That's because they are invoked with special "this"! The "this" object
// for all of these methods are not EnumerableToIterableAdapter objects. Rather, they are of type
// IEnumerable<T>. No actual EnumerableToIterableAdapter object is ever instantiated. Thus, you will
- // see a lot of expressions that cast "this" to "IEnumerable<T>".
+ // see a lot of expressions that cast "this" to "IEnumerable<T>".
internal sealed class EnumerableToIterableAdapter
{
private EnumerableToIterableAdapter()
return new EventRegistrationToken(tokenValue);
}
- // Remove the event handler from the table and
+ // Remove the event handler from the table and
// Get the delegate associated with an event registration token if it exists
// If the event registration token is not registered, returns false
public bool RemoveEventHandler(EventRegistrationToken token, [NotNullWhen(true)] out T? handler)
//
// Creates a ICustomProperty implementation for Jupiter
// Called from ICustomPropertyProvider_GetIndexedProperty from within runtime
- //
+ //
internal static unsafe ICustomProperty? CreateIndexedProperty(object target, string propertyName, TypeNameNative* pIndexedParamType)
{
Debug.Assert(target != null);
// This serves two purposes:
//
// 1. Delegate data binding interfaces to another object
- // Note that this proxy implements the native interfaces directly to avoid unnecessary overhead
+ // Note that this proxy implements the native interfaces directly to avoid unnecessary overhead
// (such as the adapter code that addresses behavior differences between IBindableVector & List
// as well as simplify forwarding code (except for IEnumerable)
//
// Verify IEnumerable last because the first few QIs might succeed and we need
// IEnumerable cast to use that cache (instead of having ICustomPropertyProvider to
// forward it manually)
- // For example, if we try to shoot in the dark by trying IVector<IInspectable> and it
+ // For example, if we try to shoot in the dark by trying IVector<IInspectable> and it
// succeeded, IEnumerable needs to know that
if (target is IEnumerable)
supportFlags |= InterfaceForwardingSupport.IBindableIterableOrIIterable;
//
// IGetProxyTarget - unwraps the target object and use it for data binding
- //
+ //
object IGetProxyTarget.GetTarget()
{
return _target;
}
- //
+ //
// ICustomQueryInterface methods
- //
+ //
public CustomQueryInterfaceResult GetInterface([In]ref Guid iid, out IntPtr ppv)
{
ppv = IntPtr.Zero;
//
// IBindableVector implementation (forwards to IBindableVector / IVector<T>)
- //
+ //
object? IBindableVector.GetAt(uint index)
{
IBindableVector? bindableVector = GetIBindableVectorNoThrow();
}
}
}
-
array[i++] = mapping.Key;
}
}
-
+
public int Count {
get { return dictionary.Count; }
}
internal struct Point
{
// float X;
- // float Y;
+ // float Y;
}
// Specify size directly instead of fields to avoid warnings
internal struct Size
{
// float Width;
- // float Height;
+ // float Height;
}
// Specify size directly instead of fields to avoid warnings
// float X;
// float Y;
// float Width;
- // float Height;
+ // float Height;
}
}
// That's because they are invoked with special "this"! The "this" object
// for all of these methods are not IReadOnlyDictionaryToIMapViewAdapter objects. Rather, they are of type
// IReadOnlyDictionary<K, V>. No actual IReadOnlyDictionaryToIMapViewAdapter object is ever instantiated. Thus, you will
- // see a lot of expressions that cast "this" to "IReadOnlyDictionary<K, V>".
+ // see a lot of expressions that cast "this" to "IReadOnlyDictionary<K, V>".
[DebuggerDisplay("Size = {Size}")]
internal sealed class IReadOnlyDictionaryToIMapViewAdapter
{
// That's because they are invoked with special "this"! The "this" object
// for all of these methods are not IReadOnlyListToIVectorViewAdapter objects. Rather, they are of type
// IReadOnlyList<T>. No actual IReadOnlyListToIVectorViewAdapter object is ever instantiated. Thus, you will
- // see a lot of expressions that cast "this" to "IReadOnlyList<T>".
+ // see a lot of expressions that cast "this" to "IReadOnlyList<T>".
[DebuggerDisplay("Size = {Size}")]
internal sealed class IReadOnlyListToIVectorViewAdapter
{
{
IReadOnlyList<T> _this = Unsafe.As<IReadOnlyList<T>>(this);
- // REX spec says "calling GetMany with startIndex equal to the length of the vector
+ // REX spec says "calling GetMany with startIndex equal to the length of the vector
// (last valid index + 1) and any specified capacity will succeed and return zero actual
// elements".
if (startIndex == _this.Count)
// That's because they are invoked with special "this"! The "this" object
// for all of these methods are not IterableToEnumerableAdapter objects. Rather, they are of type
// IIterable<T>. No actual IterableToEnumerableAdapter object is ever instantiated. Thus, you will
- // see a lot of expressions that cast "this" to "IIterable<T>".
+ // see a lot of expressions that cast "this" to "IIterable<T>".
internal sealed class IterableToEnumerableAdapter
{
private IterableToEnumerableAdapter()
// Adapter class which holds a Windows Runtime IIterator<T>, exposing it as a managed IEnumerator<T>
- // There are a few implementation differences between the Iterator and IEnumerator which need to be
- // addressed. Iterator starts at index 0 while IEnumerator starts at index -1 as a result of which
- // the first call to IEnumerator.Current is correct only after calling MoveNext().
+ // There are a few implementation differences between the Iterator and IEnumerator which need to be
+ // addressed. Iterator starts at index 0 while IEnumerator starts at index -1 as a result of which
+ // the first call to IEnumerator.Current is correct only after calling MoveNext().
// Also IEnumerator throws an exception when we call Current after reaching the end of collection.
internal sealed class IteratorToEnumeratorAdapter<T> : IEnumerator<T>
{
// That's because they are invoked with special "this"! The "this" object
// for all of these methods are not ListToBindableVectorAdapter objects. Rather, they are of type
// IList. No actual ListToVectorBindableAdapter object is ever instantiated. Thus, you will
- // see a lot of expressions that cast "this" to "IList".
+ // see a lot of expressions that cast "this" to "IList".
internal sealed class ListToBindableVectorAdapter
{
private ListToBindableVectorAdapter()
// That's because they are invoked with special "this"! The "this" object
// for all of these methods are not ListToVectorAdapter objects. Rather, they are of type
// IList<T>. No actual ListToVectorAdapter object is ever instantiated. Thus, you will
- // see a lot of expressions that cast "this" to "IList<T>".
+ // see a lot of expressions that cast "this" to "IList<T>".
internal sealed class ListToVectorAdapter
{
private ListToVectorAdapter()
}
// Runs the class constructor
- // Currently only Jupiter use this to run class constructor in order to
+ // Currently only Jupiter use this to run class constructor in order to
// initialize DependencyProperty objects and do necessary work
void IManagedActivationFactory.RunClassConstructor()
{
**
** RuntimeClass is the base class of all WinRT types
**
-**
+**
===========================================================*/
using System.Runtime.CompilerServices;
{
//
// Support for ToString/GetHashCode/Equals override
- //
+ //
[MethodImpl(MethodImplOptions.InternalCall)]
internal extern IntPtr GetRedirectedGetHashCodeMD();
[MethodImpl(MethodImplOptions.InternalCall)]
public static extern object GetUniqueObjectForIUnknownWithoutUnboxing(IntPtr unknown);
-
+
[MethodImpl(MethodImplOptions.InternalCall)]
internal static extern void InitializeWrapper(object o, ref IntPtr pUnk);
-
+
/// <summary>
/// Converts the CLR exception to an HRESULT. This function also sets
/// up an IErrorInfo for the exception.
[MethodImpl(MethodImplOptions.InternalCall)]
internal static extern int GetHRForException(Exception e);
-
+
#if FEATURE_COMINTEROP_WINRT_MANAGED_ACTIVATION
[MethodImpl(MethodImplOptions.InternalCall)]
internal static extern void InitializeManagedWinRTFactoryObject(object o, RuntimeType runtimeClassType);
-// 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.
// Determine if the assembly name is for a satellite assembly or not
// This is the same logic as in AssemblyBinder::BindByTpaList in CoreCLR
- // - If the culture name is non-empty and it's not 'neutral'
- // - The culture name is the value of the AssemblyName.Culture.Name
+ // - If the culture name is non-empty and it's not 'neutral'
+ // - The culture name is the value of the AssemblyName.Culture.Name
// (CoreCLR gets this and stores it as the culture name in the internal assembly name)
// AssemblyName.CultureName is just a shortcut to AssemblyName.Culture.Name.
- if (!string.IsNullOrEmpty(assemblyName.CultureName) &&
+ if (!string.IsNullOrEmpty(assemblyName.CultureName) &&
!string.Equals(assemblyName.CultureName, NeutralCultureName, StringComparison.OrdinalIgnoreCase))
{
// Load satellite assembly
// Search resource search paths by appending the culture name and the expected assembly file name.
// Copies the logic in BindSatelliteResourceByResourceRoots in CoreCLR.
- // Note that the runtime will also probe APP_PATHS the same way, but that feature is effectively
+ // Note that the runtime will also probe APP_PATHS the same way, but that feature is effectively
// being deprecated, so we chose to not support the same behavior for components.
foreach (string searchPath in _resourceSearchPaths)
{
return loadedAssembly!;
}
-
+
#if !FEATURE_PAL
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
private static extern IntPtr LoadFromInMemoryModuleInternal(IntPtr ptrNativeAssemblyLoadContext, IntPtr hModule, ObjectHandleOnStack retAssembly);
return IntPtr.Zero;
}
-
+
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
private static extern void LoadTypeForWinRTTypeNameInContextInternal(IntPtr ptrNativeAssemblyLoadContext, string typeName, ObjectHandleOnStack loadedType);
return type!;
}
}
-
+
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
private static extern IntPtr GetLoadContextForAssembly(QCallAssembly assembly);
internal static class CompatibilitySwitch
{
/* This class contains 3 sets of api:
- * 1. internal apis : These apis are supposed to be used by mscorlib.dll and other assemblies which use the <runtime> section in config
- * These apis query for the value of quirk not only in windows quirk DB but also in runtime section of config files,
+ * 1. internal apis : These apis are supposed to be used by mscorlib.dll and other assemblies which use the <runtime> section in config
+ * These apis query for the value of quirk not only in windows quirk DB but also in runtime section of config files,
* registry and environment vars.
* 2. public apis : These apis are supposed to be used by FX assemblies which do not read the runtime section of config files and have
* have their own section in config files or do not use configs at all.
*
* 3. specialized apis: These apis are defined in order to retrieve a specific value defined in CLR Config. That value can have specific look-up rules
* for the order and location of the config sources used.
- *
+ *
* These apis are for internal use only for FX assemblies. It has not been decided if they can be used by OOB components due to EULA restrictions
*/
internal static string? GetValueInternal(string compatibilitySwitchName)
namespace System
{
- // This value type is used for constructing System.ArgIterator.
- //
+ // This value type is used for constructing System.ArgIterator.
+ //
// SECURITY : m_ptr cannot be set to anything other than null by untrusted
- // code.
- //
+ // code.
+ //
// This corresponds to EE VARARGS cookie.
// Cannot be serialized
namespace System
{
- // this is a work around to get the concept of a calli. It's not as fast but it would be interesting to
- // see how it compares to the current implementation.
- // This delegate will disappear at some point in favor of calli
+ // this is a work around to get the concept of a calli. It's not as fast but it would be interesting to
+ // see how it compares to the current implementation.
+ // This delegate will disappear at some point in favor of calli
internal delegate void CtorDelegate(object instance);
{
case MemberListType.CaseSensitive:
{
- // Ensure we always return a list that has
+ // Ensure we always return a list that has
// been merged with the global list.
T[]? cachedList = m_csMemberInfos[name!];
if (cachedList == null)
case MemberListType.CaseInsensitive:
{
- // Ensure we always return a list that has
+ // Ensure we always return a list that has
// been merged with the global list.
T[]? cachedList = m_cisMemberInfos[name!];
if (cachedList == null)
instantiatedHandle, declaringType, m_runtimeTypeCache, methodAttributes, bindingFlags, null);
list.Add(runtimeMethodInfo);
- #endregion
+ #endregion
}
#endregion
}
}
catch (System.TypeLoadException)
{
- // In a reflection emit scenario, we may have a token for a class which
- // has not been baked and hence cannot be loaded.
+ // In a reflection emit scenario, we may have a token for a class which
+ // has not been baked and hence cannot be loaded.
continue;
}
}
else
{
- // Populate associates for this interface
+ // Populate associates for this interface
PopulateEvents(filter, declaringType, csEventInfos, ref list);
}
}
else
{
- // Populate associates for this interface
+ // Populate associates for this interface
PopulateProperties(filter, declaringType, null, null, ref list);
}
#region Duplicate check based on vtable slots
- // The inheritance of properties are defined by the inheritance of their
+ // The inheritance of properties are defined by the inheritance of their
// getters and setters.
// A property on a base type is "overriden" by a property on a sub type
- // if the getter/setter of the latter occupies the same vtable slot as
+ // if the getter/setter of the latter occupies the same vtable slot as
// the getter/setter of the former.
MethodInfo? associateMethod = propertyInfo.GetGetMethod();
// We exclude the types that contain generic parameters because their names cannot be roundtripped.
// We allow generic type definitions (and their refs, ptrs, and arrays) because their names can be roundtriped.
// Theoretically generic types instantiated with generic type definitions can be roundtripped, e.g. List`1<Dictionary`2>.
- // But these kind of types are useless, rare, and hard to identity. We would need to recursively examine all the
+ // But these kind of types are useless, rare, and hard to identity. We would need to recursively examine all the
// generic arguments with the same criteria. We will exclude them unless we see a real user scenario.
if (!m_runtimeType.GetRootElementType().IsGenericTypeDefinition && m_runtimeType.ContainsGenericParameters)
return null;
declaredType = baseType;
// if the original methodHandle was the definition then we don't need to rebind generic method arguments
- // because all RuntimeMethodHandles retrieved off of the canonical method table are definitions. That's
- // why for everything else we need to rebind the generic method arguments.
+ // because all RuntimeMethodHandles retrieved off of the canonical method table are definitions. That's
+ // why for everything else we need to rebind the generic method arguments.
if (!RuntimeMethodHandle.IsGenericMethodDefinition(methodHandle))
{
methodInstantiation = RuntimeMethodHandle.GetMethodInstantiationInternal(methodHandle);
if (allowPrefixLookup && name.EndsWith("*", StringComparison.Ordinal))
{
// We set prefixLookup to true if name ends with a "*".
- // We will also set listType to All so that all members are included in
+ // We will also set listType to All so that all members are included in
// the candidates which are later filtered by FilterApplyPrefixLookup.
name = name.Substring(0, name.Length - 1);
prefixLookup = true;
return false;
}
- // @Asymmetry - Internal, inherited, instance, non-protected, non-virtual, non-abstract members returned
+ // @Asymmetry - Internal, inherited, instance, non-protected, non-virtual, non-abstract members returned
// iff BindingFlags !DeclaredOnly, Instance and Public are present except for fields
if (((bindingFlags & BindingFlags.DeclaredOnly) == 0) && // DeclaredOnly not present
isInherited && // Is inherited Member
(isNonProtectedInternal) && // Is non-protected internal member
- ((bindingFlags & BindingFlags.NonPublic) != 0) && // BindingFlag.NonPublic present
+ ((bindingFlags & BindingFlags.NonPublic) != 0) && // BindingFlag.NonPublic present
(!isStatic) && // Is instance member
- ((bindingFlags & BindingFlags.Instance) != 0)) // BindingFlag.Instance present
+ ((bindingFlags & BindingFlags.Instance) != 0)) // BindingFlag.Instance present
{
MethodInfo? methodInfo = memberInfo as MethodInfo;
}
else
{
- // From our existing code, our policy here is that if a parameterInfo
- // is optional then all subsequent parameterInfos shall be optional.
+ // From our existing code, our policy here is that if a parameterInfo
+ // is optional then all subsequent parameterInfos shall be optional.
// Thus, iff the first parameterInfo is not optional then this MethodInfo is no longer a canidate.
if (!parameterInfos[argumentTypes.Length].IsOptional)
if (parameterInfos.Length == 0)
return false;
- // The last argument of the signature could be a param array.
+ // The last argument of the signature could be a param array.
bool shortByMoreThanOneSuppliedArgument = argumentTypes.Length < parameterInfos.Length - 1;
if (shortByMoreThanOneSuppliedArgument)
// Legacy behavior is to ignore ExactBinding when InvokeMember is specified.
// Why filter by InvokeMember? If the answer is we leave this to the binder then why not leave
// all the rest of this to the binder too? Further, what other semanitc would the binder
- // use for BindingFlags.ExactBinding besides this one? Further, why not include CreateInstance
+ // use for BindingFlags.ExactBinding besides this one? Further, why not include CreateInstance
// in this if statement? That's just InvokeMethod with a constructor, right?
if ((bindingFlags & (BindingFlags.InvokeMethod)) == 0)
{
// GetMethodBase will convert this to the instantiating/unboxing stub if necessary
MethodBase? rtTypeMethodBase = GetMethodBase(reflectedType, classRtMethodHandle);
- // a class may not implement all the methods of an interface (abstract class) so null is a valid value
+ // a class may not implement all the methods of an interface (abstract class) so null is a valid value
Debug.Assert(rtTypeMethodBase is null || rtTypeMethodBase is RuntimeMethodInfo);
im.TargetMethods[i] = (MethodInfo)rtTypeMethodBase!;
}
- return im;
+ return im;
}
#endregion
return RuntimeTypeHandle.IsEquivalentTo(this, otherRtType);
}
#endif // FEATURE_TYPEEQUIVALENCE
-
+
#endregion
#region Name
// "Must specify binding flags describing the invoke operation required."
throw new ArgumentException(SR.Arg_NoAccessSpec, nameof(bindingFlags));
- // Provide a default binding mask if none is provided
+ // Provide a default binding mask if none is provided
if ((bindingFlags & MemberBindingMask) == 0)
{
bindingFlags |= BindingFlags.Instance | BindingFlags.Public;
if ((bindingFlags & BindingFlags.PutRefDispProperty) != 0 && (bindingFlags & ClassicBindingMask & ~BindingFlags.PutRefDispProperty) != 0)
throw new ArgumentException(SR.Arg_COMPropSetPut, nameof(bindingFlags));
-
+
if (name == null)
throw new ArgumentNullException(nameof(name));
[DebuggerHidden]
internal object CreateInstanceDefaultCtor(bool publicOnly, bool skipCheckThis, bool fillCache, bool wrapExceptions)
{
- // Call the cached
+ // Call the cached
ActivatorCache? cacheEntry = GenericCache as ActivatorCache;
if (cacheEntry != null)
{
return _CreateEnum(enumType, value);
}
-#if FEATURE_COMINTEROP
+#if FEATURE_COMINTEROP
[MethodImpl(MethodImplOptions.InternalCall)]
private extern object InvokeDispMethod(
string name, BindingFlags invokeAttr, object target, object?[]? args,
bool[]? byrefModifiers, int culture, string[]? namedParameters);
-#endif // FEATURE_COMINTEROP
+#endif // FEATURE_COMINTEROP
#if FEATURE_COMINTEROP_UNMANAGED_ACTIVATION
[MethodImpl(MethodImplOptions.InternalCall)]
internal static Type GetTypeFromCLSIDImpl(Guid clsid, String? server, bool throwOnError)
{
- throw new NotImplementedException("CoreCLR_REMOVED -- Unmanaged activation removed");
+ throw new NotImplementedException("CoreCLR_REMOVED -- Unmanaged activation removed");
}
#endif // FEATURE_COMINTEROP_UNMANAGED_ACTIVATION
case DispatchWrapperType.Dispatch:
wrapperType = typeof(DispatchWrapper);
break;
- case DispatchWrapperType.Error:
+ case DispatchWrapperType.Error:
wrapperType = typeof(ErrorWrapper);
break;
case DispatchWrapperType.Currency:
{
wrapperCons = wrapperType.GetConstructor(new Type[] {typeof(object) })!;
}
-
+
// Wrap each of the elements of the array.
for (int currElem = 0; currElem < numElems; currElem++)
{
{
private class Table
{
- // Note that m_keys and m_values arrays are immutable to allow lock-free reads. A new instance
+ // Note that m_keys and m_values arrays are immutable to allow lock-free reads. A new instance
// of CerHashtable has to be allocated to grow the size of the hashtable.
internal K[] m_keys;
internal V[] m_values;
// This volatile write has to be last. It is going to publish the result atomically.
//
- // Note that incrementing the count or setting the value does not do any harm without setting the key. The inconsistency will be ignored
+ // Note that incrementing the count or setting the value does not do any harm without setting the key. The inconsistency will be ignored
// and it will go away completely during next rehash.
Volatile.Write(ref keys[index], key);
// All methods that use StackCrawlMark should be marked with this attribute. This attribute
// disables inlining of the calling method to allow stackwalking to find the exact caller.
//
- // This attribute used to indicate that the target method requires space for a security object
- // to be allocated on the callers stack. It is not used for this purpose anymore because of security
+ // This attribute used to indicate that the target method requires space for a security object
+ // to be allocated on the callers stack. It is not used for this purpose anymore because of security
// stackwalks are not ever done in CoreCLR.
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Constructor, AllowMultiple = true, Inherited = false)]
internal sealed class DynamicSecurityMethodAttribute : Attribute
// Leaving it uninitialized would confuse debuggers.
//
// We need to call the String constructor so that the compiler doesn't mark this as a literal.
- // Marking this as a literal would mean that it doesn't show up as a field which we can access
+ // Marking this as a literal would mean that it doesn't show up as a field which we can access
// from native.
#pragma warning disable CS8618 // compiler sees this non-nullable static string as uninitialized
[Intrinsic]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern string FastAllocateString(int length);
- // Is this a string that can be compared quickly (that is it has only characters > 0x80
+ // Is this a string that can be compared quickly (that is it has only characters > 0x80
// and not a - or '
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern bool IsFastSort();
// + 1 for the null character from the user. + 1 for the null character we put in.
nb = checked((strManaged.Length + 1) * Marshal.SystemMaxDBCSCharSize + 1);
- // Use the pre-allocated buffer (allocated by localloc IL instruction) if not NULL,
+ // Use the pre-allocated buffer (allocated by localloc IL instruction) if not NULL,
// otherwise fallback to AllocCoTaskMem
if (pbNativeBuffer == null)
{
byte* pbNativeBuffer = (byte*)pNativeBuffer;
// If we are marshaling into a stack buffer allocated by the ILStub
- // we will use a "1-pass" mode where we convert the string directly into the unmanaged buffer.
+ // we will use a "1-pass" mode where we convert the string directly into the unmanaged buffer.
// else we will allocate the precise native heap memory.
if (pbNativeBuffer != null)
{
nb = (strManaged.Length + 1) * MAX_UTF8_CHAR_SIZE;
// nb is the actual number of bytes written by Encoding.GetBytes.
- // use nb to de-limit the string since we are allocating more than
+ // use nb to de-limit the string since we are allocating more than
// required on stack
nb = strManaged.GetBytesFromEncoding(pbNativeBuffer, nb, Encoding.UTF8);
}
return IntPtr.Zero;
}
- // Convert to string first
+ // Convert to string first
string strManaged = sb.ToString();
- // Get byte count
+ // Get byte count
int nb = Encoding.UTF8.GetByteCount(strManaged);
// EmitConvertSpaceCLRToNative allocates memory
long managedUtcTicks = ManagedUtcTicksAtNativeZero + nativeTicks.UniversalTime;
DateTimeOffset managedUtcDTO = new DateTimeOffset(managedUtcTicks, TimeSpan.Zero);
- // Some Utc times cannot be represented in local time in certain timezones. E.g. 0001-01-01 12:00:00 AM cannot
+ // Some Utc times cannot be represented in local time in certain timezones. E.g. 0001-01-01 12:00:00 AM cannot
// be represented in any timezones with a negative offset from Utc. We throw an ArgumentException in that case.
managedLocalDTO = managedUtcDTO.ToLocalTime(true);
}
if (!Environment.IsWinRTSupported)
throw new PlatformNotSupportedException(SR.PlatformNotSupported_WinRT);
if (managed == null)
- throw new ArgumentNullException(); // We don't have enough information to get the argument name
+ throw new ArgumentNullException(); // We don't have enough information to get the argument name
IntPtr hstring;
int hrCreate = System.Runtime.InteropServices.WindowsRuntime.UnsafeNativeMethods.WindowsCreateString(managed, managed.Length, &hstring);
if (!Environment.IsWinRTSupported)
throw new PlatformNotSupportedException(SR.PlatformNotSupported_WinRT);
if (managed == null)
- throw new ArgumentNullException(); // We don't have enough information to get the argument name
+ throw new ArgumentNullException(); // We don't have enough information to get the argument name
// The string must also be pinned by the caller to ConvertToNativeReference, which also owns
// the HSTRING_HEADER.
}
}
- internal static unsafe void ConvertContentsToNative_KeyValuePair<K, V>(ref KeyValuePair<K, V>[]? managedArray, IntPtr pNativeHome)
+ internal static unsafe void ConvertContentsToNative_KeyValuePair<K, V>(ref KeyValuePair<K, V>[]? managedArray, IntPtr pNativeHome)
{
if (managedArray != null)
{
next = next.m_Next;
}
}
-
+
public static void AddToCleanupList(ref CleanupWorkListElement list, CleanupWorkListElement newElement)
{
if (list == null)
{
private int GetReplaceBufferCapacity(int requiredCapacity)
{
- // This function assumes that required capacity will be less
+ // This function assumes that required capacity will be less
// than the max capacity of the StringBuilder
Diagnostics.Debug.Assert(requiredCapacity <= m_MaxCapacity);
fixed (char* pChunkChars = m_ChunkChars)
{
- // The incoming string buffer is supposed to have been populated by the
+ // The incoming string buffer is supposed to have been populated by the
// P/Invoke-called native function but there's no way to know if that really
// happened, the native function might populate the buffer only in certain
// circumstances (e.g. only if the function succeeds).
//
- // As such, the buffer might contain bogus characters that cannot be converted
+ // As such, the buffer might contain bogus characters that cannot be converted
// to Unicode and in that case conversion should not result in exceptions that
// the managed caller does not expect. Instead, the caller is expected to know
// when the resulting string is not valid and not use it.
}
catch (Exception ex)
{ // BindHandle throws ApplicationException on full CLR and Exception on CoreCLR.
- // We do not let either of these leak and convert them to ArgumentException to
+ // We do not let either of these leak and convert them to ArgumentException to
// indicate that the specified handles are invalid.
if (ex.HResult == HResults.E_HANDLE) // Bad handle
}
/// <summary>
- /// Returns a <see cref="ThreadPoolBoundHandle"/> for the specific handle,
+ /// Returns a <see cref="ThreadPoolBoundHandle"/> for the specific handle,
/// which is bound to the system thread pool.
/// </summary>
/// <param name="handle">
- /// A <see cref="SafeHandle"/> object that holds the operating system handle. The
+ /// A <see cref="SafeHandle"/> object that holds the operating system handle. The
/// handle must have been opened for overlapped I/O on the unmanaged side.
/// </param>
/// <returns>
- /// <see cref="ThreadPoolBoundHandle"/> for <paramref name="handle"/>, which
+ /// <see cref="ThreadPoolBoundHandle"/> for <paramref name="handle"/>, which
/// is bound to the system thread pool.
/// </returns>
/// <exception cref="ArgumentNullException">
/// <para>
/// -or-
/// </para>
- /// <paramref name="handle"/> refers to a handle that has not been opened
+ /// <paramref name="handle"/> refers to a handle that has not been opened
/// for overlapped I/O.
/// <para>
/// -or-
/// <para>
/// -or-
/// </para>
- /// <see cref="ThreadPoolBoundHandle"/> does not take ownership of <paramref name="handle"/>,
+ /// <see cref="ThreadPoolBoundHandle"/> does not take ownership of <paramref name="handle"/>,
/// it remains the responsibility of the caller to call <see cref="SafeHandle.Dispose()"/>.
/// </remarks>
public static ThreadPoolBoundHandle BindHandle(SafeHandle handle)
}
/// <summary>
- /// Returns an unmanaged pointer to a <see cref="NativeOverlapped"/> structure, specifying
- /// a delegate that is invoked when the asynchronous I/O operation is complete, a user-provided
+ /// Returns an unmanaged pointer to a <see cref="NativeOverlapped"/> structure, specifying
+ /// a delegate that is invoked when the asynchronous I/O operation is complete, a user-provided
/// object providing context, and managed objects that serve as buffers.
/// </summary>
/// <param name="callback">
- /// An <see cref="IOCompletionCallback"/> delegate that represents the callback method
+ /// An <see cref="IOCompletionCallback"/> delegate that represents the callback method
/// invoked when the asynchronous I/O operation completes.
/// </param>
/// <param name="state">
- /// A user-provided object that distinguishes this <see cref="NativeOverlapped"/> from other
+ /// A user-provided object that distinguishes this <see cref="NativeOverlapped"/> from other
/// <see cref="NativeOverlapped"/> instances. Can be <see langword="null"/>.
/// </param>
/// <param name="pinData">
- /// An object or array of objects representing the input or output buffer for the operation. Each
+ /// An object or array of objects representing the input or output buffer for the operation. Each
/// object represents a buffer, for example an array of bytes. Can be <see langword="null"/>.
/// </param>
/// <returns>
/// </returns>
/// <remarks>
/// <para>
- /// The unmanaged pointer returned by this method can be passed to the operating system in
- /// overlapped I/O operations. The <see cref="NativeOverlapped"/> structure is fixed in
+ /// The unmanaged pointer returned by this method can be passed to the operating system in
+ /// overlapped I/O operations. The <see cref="NativeOverlapped"/> structure is fixed in
/// physical memory until <see cref="FreeNativeOverlapped(NativeOverlapped*)"/> is called.
/// </para>
/// <para>
- /// The buffer or buffers specified in <paramref name="pinData"/> must be the same as those passed
+ /// The buffer or buffers specified in <paramref name="pinData"/> must be the same as those passed
/// to the unmanaged operating system function that performs the asynchronous I/O.
/// </para>
/// <note>
- /// The buffers specified in <paramref name="pinData"/> are pinned for the duration of
+ /// The buffers specified in <paramref name="pinData"/> are pinned for the duration of
/// the I/O operation.
/// </note>
/// </remarks>
/// </returns>
/// <remarks>
/// <para>
- /// The unmanaged pointer returned by this method can be passed to the operating system in
- /// overlapped I/O operations. The <see cref="NativeOverlapped"/> structure is fixed in
+ /// The unmanaged pointer returned by this method can be passed to the operating system in
+ /// overlapped I/O operations. The <see cref="NativeOverlapped"/> structure is fixed in
/// physical memory until <see cref="FreeNativeOverlapped(NativeOverlapped*)"/> is called.
/// </para>
/// </remarks>
/// <paramref name="preAllocated"/> is <see langword="null"/>.
/// </exception>
/// <exception cref="ArgumentException">
- /// <paramref name="preAllocated"/> is currently in use for another I/O operation.
+ /// <paramref name="preAllocated"/> is currently in use for another I/O operation.
/// </exception>
/// <exception cref="ObjectDisposedException">
- /// This method was called after the <see cref="ThreadPoolBoundHandle"/> was disposed, or
+ /// This method was called after the <see cref="ThreadPoolBoundHandle"/> was disposed, or
/// this method was called after <paramref name="preAllocated"/> was disposed.
/// </exception>
/// <seealso cref="PreAllocatedOverlapped"/>
}
/// <summary>
- /// Frees the unmanaged memory associated with a <see cref="NativeOverlapped"/> structure
+ /// Frees the unmanaged memory associated with a <see cref="NativeOverlapped"/> structure
/// allocated by the <see cref="AllocateNativeOverlapped"/> method.
/// </summary>
/// <param name="overlapped">
/// </param>
/// <remarks>
/// <note type="caution">
- /// You must call the <see cref="FreeNativeOverlapped(NativeOverlapped*)"/> method exactly once
- /// on every <see cref="NativeOverlapped"/> unmanaged pointer allocated using the
- /// <see cref="AllocateNativeOverlapped"/> method.
- /// If you do not call the <see cref="FreeNativeOverlapped(NativeOverlapped*)"/> method, you will
- /// leak memory. If you call the <see cref="FreeNativeOverlapped(NativeOverlapped*)"/> method more
+ /// You must call the <see cref="FreeNativeOverlapped(NativeOverlapped*)"/> method exactly once
+ /// on every <see cref="NativeOverlapped"/> unmanaged pointer allocated using the
+ /// <see cref="AllocateNativeOverlapped"/> method.
+ /// If you do not call the <see cref="FreeNativeOverlapped(NativeOverlapped*)"/> method, you will
+ /// leak memory. If you call the <see cref="FreeNativeOverlapped(NativeOverlapped*)"/> method more
/// than once on the same <see cref="NativeOverlapped"/> unmanaged pointer, memory will be corrupted.
/// </note>
/// </remarks>
/// allocated using the <see cref="AllocateNativeOverlapped(IOCompletionCallback, object, object)"/>.
/// </summary>
/// <param name="overlapped">
- /// An unmanaged pointer to the <see cref="NativeOverlapped"/> structure from which to return the
+ /// An unmanaged pointer to the <see cref="NativeOverlapped"/> structure from which to return the
/// associated user-provided object.
/// </param>
/// <returns>
- /// A user-provided object that distinguishes this <see cref="NativeOverlapped"/>
- /// from other <see cref="NativeOverlapped"/> instances, otherwise, <see langword="null"/> if one was
+ /// A user-provided object that distinguishes this <see cref="NativeOverlapped"/>
+ /// from other <see cref="NativeOverlapped"/> instances, otherwise, <see langword="null"/> if one was
/// not specified when the instance was allocated using <see cref="AllocateNativeOverlapped"/>.
/// </returns>
/// <exception cref="ArgumentNullException">
{
// .NET Native's version of ThreadPoolBoundHandle that wraps the Win32 ThreadPool holds onto
// native resources so it needs to be disposable. To match the contract, we are also disposable.
- // We also implement a disposable state to mimic behavior between this implementation and
+ // We also implement a disposable state to mimic behavior between this implementation and
// .NET Native's version (code written against us, will also work against .NET Native's version).
_isDisposed = true;
}
private DeferredDisposableLifetime<PreAllocatedOverlapped> _lifetime;
/// <summary>
- /// Initializes a new instance of the <see cref="PreAllocatedOverlapped"/> class, specifying
- /// a delegate that is invoked when each asynchronous I/O operation is complete, a user-provided
+ /// Initializes a new instance of the <see cref="PreAllocatedOverlapped"/> class, specifying
+ /// a delegate that is invoked when each asynchronous I/O operation is complete, a user-provided
/// object providing context, and managed objects that serve as buffers.
/// </summary>
/// <param name="callback">
- /// An <see cref="IOCompletionCallback"/> delegate that represents the callback method
+ /// An <see cref="IOCompletionCallback"/> delegate that represents the callback method
/// invoked when each asynchronous I/O operation completes.
/// </param>
/// <param name="state">
/// object from other <see cref="NativeOverlapped"/> instances. Can be <see langword="null"/>.
/// </param>
/// <param name="pinData">
- /// An object or array of objects representing the input or output buffer for the operations. Each
+ /// An object or array of objects representing the input or output buffer for the operations. Each
/// object represents a buffer, for example an array of bytes. Can be <see langword="null"/>.
/// </param>
/// <remarks>
- /// The new <see cref="PreAllocatedOverlapped"/> instance can be passed to
+ /// The new <see cref="PreAllocatedOverlapped"/> instance can be passed to
/// <see cref="ThreadPoolBoundHandle.AllocateNativeOverlapped(PreAllocatedOverlapped)"/>, to produce
/// a <see cref="NativeOverlapped"/> instance that can be passed to the operating system in overlapped
- /// I/O operations. A single <see cref="PreAllocatedOverlapped"/> instance can only be used for
+ /// I/O operations. A single <see cref="PreAllocatedOverlapped"/> instance can only be used for
/// a single native I/O operation at a time. However, the state stored in the <see cref="PreAllocatedOverlapped"/>
/// instance can be reused for subsequent native operations.
/// <note>
}
/// <summary>
- /// Frees the resources associated with this <see cref="PreAllocatedOverlapped"/> instance.
+ /// Frees the resources associated with this <see cref="PreAllocatedOverlapped"/> instance.
/// </summary>
public void Dispose()
{
namespace System.Threading
{
/// <summary>
- /// After much discussion, we decided the Interlocked class doesn't need
- /// any HPA's for synchronization or external threading. They hurt C#'s
- /// codegen for the yield keyword, and arguably they didn't protect much.
- /// Instead, they penalized people (and compilers) for writing threadsafe
+ /// After much discussion, we decided the Interlocked class doesn't need
+ /// any HPA's for synchronization or external threading. They hurt C#'s
+ /// codegen for the yield keyword, and arguably they didn't protect much.
+ /// Instead, they penalized people (and compilers) for writing threadsafe
/// code.
/// </summary>
public static class Interlocked
// Note that getILIntrinsicImplementationForInterlocked() in vm\jitinterface.cpp replaces
// the body of this method with the the following IL:
- // ldarg.0
+ // ldarg.0
// ldarg.1
// ldarg.2
// call System.Threading.Interlocked::CompareExchange(ref Object, Object, Object)
**
**
**
-** Purpose: Synchronizes access to a shared resource or region of code in a multi-threaded
+** Purpose: Synchronizes access to a shared resource or region of code in a multi-threaded
** program.
**
**
// Use a ref bool instead of out to ensure that unverifiable code must
- // initialize this value to something. If we used out, the value
+ // initialize this value to something. If we used out, the value
// could be uninitialized if we threw an exception in our prolog.
// The JIT should inline this method to allow check of lockTaken argument to be optimized out
// in the typical case. Note that the method has to be transparent for inlining to be allowed by the VM.
private static extern bool IsEnteredNative(object obj);
/*========================================================================
- ** Waits for notification from the object (via a Pulse/PulseAll).
+ ** Waits for notification from the object (via a Pulse/PulseAll).
** timeout indicates how long to wait before the method returns.
- ** This method acquires the monitor waithandle for the object
- ** If this thread holds the monitor lock for the object, it releases it.
- ** On exit from the method, it obtains the monitor lock back.
- ** If exitContext is true then the synchronization domain for the context
- ** (if in a synchronized context) is exited before the wait and reacquired
+ ** This method acquires the monitor waithandle for the object
+ ** If this thread holds the monitor lock for the object, it releases it.
+ ** On exit from the method, it obtains the monitor lock back.
+ ** If exitContext is true then the synchronization domain for the context
+ ** (if in a synchronized context) is exited before the wait and reacquired
**
** Exceptions: ArgumentNullException if object is null.
========================================================================*/
}
/*========================================================================
- ** Sends a notification to a single waiting object.
+ ** Sends a notification to a single waiting object.
* Exceptions: SynchronizationLockException if this method is not called inside
* a synchronized block of code.
========================================================================*/
ObjPulse(obj);
}
/*========================================================================
- ** Sends a notification to all waiting objects.
+ ** Sends a notification to all waiting objects.
========================================================================*/
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern void ObjPulseAll(object obj);
**
**
**
-** Purpose: Class for converting information to and from the native
+** Purpose: Class for converting information to and from the native
** overlapped structure used in asynchronous file i/o
**
**
private IOCompletionCallback _ioCompletionCallback;
private ExecutionContext _executionContext;
private uint _errorCode; // Error code
- private uint _numBytes; // No. of bytes transferred
+ private uint _numBytes; // No. of bytes transferred
private NativeOverlapped* _pNativeOverlapped;
internal _IOCompletionCallback(IOCompletionCallback ioCompletionCallback, ExecutionContext executionContext)
sealed internal unsafe class OverlappedData
{
- // ! If you make any change to the layout here, you need to make matching change
+ // ! If you make any change to the layout here, you need to make matching change
// ! to OverlappedDataObject in vm\nativeoverlapped.h
internal IAsyncResult? _asyncResult;
internal object? _callback; // IOCompletionCallback or _IOCompletionCallback
public Overlapped()
{
- // The split between Overlapped and OverlappedData should not be needed. It is required by the implementation of
+ // The split between Overlapped and OverlappedData should not be needed. It is required by the implementation of
// async GC handles currently. It expects OverlappedData to be a sealed type.
_overlappedData = new OverlappedData(this);
}
/*====================================================================
* Packs a managed overlapped class into native Overlapped struct.
- * Roots the iocb and stores it in the ReservedCOR field of native Overlapped
- * Pins the native Overlapped struct and returns the pinned index.
+ * Roots the iocb and stores it in the ReservedCOR field of native Overlapped
+ * Pins the native Overlapped struct and returns the pinned index.
====================================================================*/
[Obsolete("This method is not safe. Use Pack (iocb, userData) instead. http://go.microsoft.com/fwlink/?linkid=14202")]
[CLSCompliant(false)]
}
/*====================================================================
- * Unpacks an unmanaged native Overlapped struct.
+ * Unpacks an unmanaged native Overlapped struct.
* Unpins the native Overlapped struct
====================================================================*/
[CLSCompliant(false)]
if (createSynchronizationContextDelegate == null)
{
Type factoryType = Type.GetType("System.Threading.WinRTSynchronizationContextFactory, System.Runtime.WindowsRuntime", throwOnError: true)!;
-
+
// Create an instance delegate for the Create static method
MethodInfo createMethodInfo = factoryType.GetMethod("Create", BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.Public)!;
createSynchronizationContextDelegate = (Func<object, SynchronizationContext>)Delegate.CreateDelegate(typeof(Func<object, SynchronizationContext>), createMethodInfo);
private static WFD.IAsyncCausalityTracerStatics s_TracerFactory = null!;
- // The loggers that this Tracer knows about.
+ // The loggers that this Tracer knows about.
[Flags]
private enum Loggers : byte
{
internal ThreadHelper(Delegate start)
{
- _start = start;
+ _start = start;
}
internal void SetExecutionContextHelper(ExecutionContext? ec)
private int _priority; // INT32
// The following field is required for interop with the VS Debugger
- // Prior to making any changes to this field, please reach out to the VS Debugger
+ // Prior to making any changes to this field, please reach out to the VS Debugger
// team to make sure that your changes are not going to prevent the debugger
// from working.
private int _managedThreadId; // INT32
private void Create(ParameterizedThreadStart start) =>
SetStartHelper((Delegate)start, 0);
- private void Create(ParameterizedThreadStart start, int maxStackSize) =>
+ private void Create(ParameterizedThreadStart start, int maxStackSize) =>
SetStartHelper((Delegate)start, maxStackSize);
public extern int ManagedThreadId
// The upper bits of t_currentProcessorIdCache are the currentProcessorId. The lower bits of
// the t_currentProcessorIdCache are counting down to get it periodically refreshed.
- // TODO: Consider flushing the currentProcessorIdCache on Wait operations or similar
+ // TODO: Consider flushing the currentProcessorIdCache on Wait operations or similar
// actions that are likely to result in changing the executing core
[ThreadStatic]
private static int t_currentProcessorIdCache;
{
// if the app has already unregistered the wait, there is nothing to cleanup
// we can detect this by checking the handle. Normally, there is no race condition here
- // so no need to protect reading of handle. However, if this object gets
+ // so no need to protect reading of handle. However, if this object gets
// resurrected and then someone does an unregister, it would introduce a race condition
//
// PrepareConstrainedRegions call not needed since finalizer already in Cer
// This will result in a "leak" of sorts (since the handle will not be cleaned up)
// but the process is exiting anyway.
//
- // During AD-unload, we don't finalize live objects until all threads have been
- // aborted out of the AD. Since these locked regions are CERs, we won't abort them
+ // During AD-unload, we don't finalize live objects until all threads have been
+ // aborted out of the AD. Since these locked regions are CERs, we won't abort them
// while the lock is held. So there should be no leak on AD-unload.
//
if (Interlocked.CompareExchange(ref m_lock, 1, 0) == 0)
// The thread pool maintains a per-appdomain managed work queue.
// New thread pool entries are added in the managed queue.
- // The VM is responsible for the actual growing/shrinking of
- // threads.
+ // The VM is responsible for the actual growing/shrinking of
+ // threads.
private static void EnsureInitialized()
{
if (!ThreadPoolGlobals.threadPoolInitialized)
ThreadPoolGlobals.threadPoolInitialized = true;
}
- // Native methods:
+ // Native methods:
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern bool SetMinThreadsNative(int workerThreads, int completionPortThreads);
}
////////////////////////////////////////////////////////////////////////////////
- // This will return a class based upon the progID. This is provided for
- // COM classic support. Program ID's are not used in COM+ because they
- // have been superceded by namespace. (This routine is called this instead
+ // This will return a class based upon the progID. This is provided for
+ // COM classic support. Program ID's are not used in COM+ because they
+ // have been superceded by namespace. (This routine is called this instead
// of getClass() because of the name conflict with the first method above.)
//
// param progID: the progID of the class to retrieve
}
////////////////////////////////////////////////////////////////////////////////
- // This will return a class based upon the CLSID. This is provided for
- // COM classic support.
+ // This will return a class based upon the CLSID. This is provided for
+ // COM classic support.
//
// param CLSID: the CLSID of the class to retrieve
// returns: the class object associated to the CLSID
{
public partial class TypeLoadException : SystemException
{
- // This is called from inside the EE.
+ // This is called from inside the EE.
private TypeLoadException(string? className,
string? assemblyName,
string? messageArg,
_messageArg = messageArg;
_resourceId = resourceId;
- // Set the _message field eagerly; debuggers look at this field to
+ // Set the _message field eagerly; debuggers look at this field to
// display error info. They don't call the Message property.
SetMessageField();
}
IntPtr[] fields = new IntPtr[flds.Length];
// For proper handling of Nullable<T> don't change GetType() to something like 'IsAssignableFrom'
- // Currently we can't make a TypedReference to fields of Nullable<T>, which is fine.
+ // Currently we can't make a TypedReference to fields of Nullable<T>, which is fine.
RuntimeType targetType = (RuntimeType)target.GetType();
for (int i = 0; i < flds.Length; i++)
{
namespace System
{
[Serializable]
- [System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")]
+ [System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")]
public abstract class ValueType
{
public override bool Equals(object? obj)
object thisObj = (object)this;
object? thisResult, thatResult;
- // if there are no GC references in this object we can avoid reflection
+ // if there are no GC references in this object we can avoid reflection
// and do a fast memcmp
if (CanCompareBits(this))
return FastEqualsCheck(thisObj, obj);
}
}
}
-
+
/// <summary>
/// Called from within the EE and is used to handle calls on methods of event interfaces.
/// </summary>
{
ThrowHelper.ThrowArgumentOutOfRange_BadYearMonthDay();
}
-
+
int[] days = IsLeapYear(year) ? s_daysToMonth366 : s_daysToMonth365;
if (day > days[month] - days[month - 1])
{
{
ThrowHelper.ThrowArgumentOutOfRange_BadHourMinuteSecond();
}
-
+
return TimeSpan.TimeToTicks(hour, minute, second);
}
throw GetArgumentOutOfRangeException(ExceptionArgument.year,
ExceptionResource.ArgumentOutOfRange_Year);
}
-
+
[DoesNotReturn]
internal static void ThrowArgumentOutOfRange_BadYearMonthDay()
{