Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -330,6 +330,7 @@ The .NET Foundation licenses this file to you under the MIT license.
<IlcArg Include="@(_IlcTrimmedAssemblies->'--trim:%(Identity)')" />
<IlcArg Include="@(_IlcSingleWarnAssemblies->'--singlewarnassembly:%(Identity)')" />
<IlcArg Include="@(_IlcNoSingleWarnAssemblies->'--nosinglewarnassembly:%(Identity)')" />
<IlcArg Include="@(IlcStripNamesAssembly->'--stripnames:%(Identity)')" />
<IlcArg Condition="'$(TrimmerDefaultAction)' == 'copyused' or '$(TrimmerDefaultAction)' == 'copy' or '$(TrimMode)' == 'partial'" Include="--defaultrooting" />
<IlcArg Condition="$(IlcResilient) != 'false'" Include="--resilient" />
<IlcArg Include="@(UnmanagedEntryPointsAssembly->'--generateunmanagedentrypoints:%(Identity)')" />
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Reflection;
using System.Reflection.Runtime.General;
using System.Runtime;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
Expand Down Expand Up @@ -317,6 +318,12 @@ internal DiagnosticMethodInfo GetDiagnosticMethodInfo()
if (isOpenResolver)
{
MethodInfo mi = ReflectionAugments.GetDelegateMethod(this);

// Declaring types with a name that was stripped by the compiler have no information to report,
// which is consistent with the stack trace data of the methods of such types.
if (mi.DeclaringType!.ToRuntimeTypeInfo().IsNameStripped)
return null;

Type? declaringType = mi.DeclaringType;
if (declaringType.IsConstructedGenericType)
declaringType = declaringType.GetGenericTypeDefinition();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -78,16 +78,21 @@ private LowLevelDictionary<string, QHandle> CreateCaseInsensitiveTypeDictionary(
{
TypeDefinition typeDefinition = typeDefinitionHandle.GetTypeDefinition(reader);
NamespaceDefinitionHandle namespaceHandle = typeDefinition.NamespaceOrEnclosingType.ToNamespaceDefinitionHandle(reader);
string typeName = typeDefinition.Name.GetString(reader);

// Types with a name that was stripped by the compiler can't be found by name.
if (typeName.Length == 0)
continue;

string ns = namespaceHandle.ToNamespaceName(reader);
if (ns.Length != 0)
ns += ".";
string fullName = (ns + typeDefinition.Name.GetString(reader)).ToLowerInvariant();
string fullName = (ns + typeName).ToLowerInvariant();
if (!dict.TryGetValue(fullName, out _))
{
dict.Add(fullName, new QHandle(reader, typeDefinitionHandle));
}
}

foreach (TypeForwarderHandle typeForwarderHandle in scopeDefinition.TypeForwarders)
{
TypeForwarder typeForwarder = typeForwarderHandle.GetTypeForwarder(reader);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,10 @@ internal sealed override RuntimeTypeInfo UncachedGetTypeCoreCaseSensitive(string
VersionResilientHashCode.NameHashCode(namespaceName),
VersionResilientHashCode.NameHashCode(name));

// Types with a name that was stripped by the compiler can't be found by name.
if (name.Length == 0)
return null;

MetadataReader reader = Scope.Reader;
ScopeDefinition scopeDefinition = Scope.ScopeDefinition;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,11 +14,11 @@ internal abstract partial class NameFilter

internal sealed partial class NameFilterCaseSensitive : NameFilter
{
public sealed override bool Matches(ConstantStringValueHandle stringHandle, MetadataReader reader) => stringHandle.StringEquals(ExpectedName, reader);
public sealed override bool Matches(ConstantStringValueHandle stringHandle, MetadataReader reader) => CanMatch && stringHandle.StringEquals(ExpectedName, reader);
}

internal sealed partial class NameFilterCaseInsensitive : NameFilter
{
public sealed override bool Matches(ConstantStringValueHandle stringHandle, MetadataReader reader) => stringHandle.GetConstantStringValue(reader).Value.Equals(ExpectedName, StringComparison.OrdinalIgnoreCase);
public sealed override bool Matches(ConstantStringValueHandle stringHandle, MetadataReader reader) => CanMatch && stringHandle.GetConstantStringValue(reader).Value.Equals(ExpectedName, StringComparison.OrdinalIgnoreCase);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,9 @@ protected NameFilter(string expectedName)

public abstract bool Matches(string name);
protected string ExpectedName { get; }

// Nested types with a name that was stripped by the compiler have an empty name. They can't be found by name.
protected bool CanMatch => ExpectedName.Length != 0;
}

internal sealed partial class NameFilterCaseSensitive : NameFilter
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -210,6 +210,10 @@ internal abstract partial class RuntimeTypeInfo
Type? match = null;
foreach (Type ifc in GetInterfaces())
{
// Interfaces with a name that was stripped by the compiler can't be found by name.
if (ifc.ToRuntimeTypeInfo().IsNameStripped)
continue;

string ifcSimpleName = ifc.Name;
bool simpleNameMatches = ignoreCase
? (0 == CultureInfo.InvariantCulture.CompareInfo.Compare(simpleName, ifcSimpleName, CompareOptions.IgnoreCase)) // @todo: This could be expressed simpler but the necessary parts of String api not yet ported.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@

using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Reflection;
using System.Reflection.Runtime.Assemblies;
using System.Reflection.Runtime.General;
Expand Down Expand Up @@ -119,6 +120,12 @@ public sealed override string Namespace
ns = NamespaceDefinition.Name.GetStringOrNull(_reader).EscapeTypeNameIdentifier() ?? string.Empty;
_lazyNamespace = ns;
}

// The types with a name that was stripped are in the global namespace, which doesn't tell them from types
// that have a name in the global namespace.
if (ns.Length == 0 && IsNameStripped)
ThrowNameStripped();

return ns.Length == 0 ? null : ns;
}
}
Expand Down Expand Up @@ -204,10 +211,18 @@ public sealed override string Name
ConstantStringValueHandle nameHandle = _typeDefinition.Name;
string name = nameHandle.GetString(_reader);

if (name.Length == 0)
ThrowNameStripped();

return name.EscapeTypeNameIdentifier();
}
}

internal sealed override bool IsNameStripped => _typeDefinition.Name.StringEquals(string.Empty, _reader);

[DoesNotReturn]
private void ThrowNameStripped() => throw new NotSupportedException(SR.Format(SR.NotSupported_StrippedTypeName, InternalFullNameOfAssembly));

internal sealed override MetadataReader GetMetadataReader() => _reader;

internal sealed override CustomAttributeHandleCollection GetCustomAttributeHandles() => _typeDefinition.CustomAttributes;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -207,6 +207,8 @@ internal sealed override string InternalFullNameOfAssembly
}
}

internal sealed override bool IsNameStripped => GenericTypeDefinitionTypeInfo.IsNameStripped;

public sealed override string Name
{
get
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -169,7 +169,9 @@ private MemberInfo GetDeclaredMemberWithSameMetadataDefinitionAs(MemberInfo memb

private M QueryMemberWithSameMetadataDefinitionAs<M>(MemberPolicies<M> policies, MemberInfo member) where M : MemberInfo
{
QueryResult<M> members = Query<M>(policies, member.Name, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static);
// Nested types with a name that was stripped by the compiler can't be filtered by name, so the metadata definition comparison below does all the work.
BindingFlags flags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static;
QueryResult<M> members = member is Type ? Query<M>(policies, flags) : Query<M>(policies, member.Name, flags);
foreach (M candidate in members)
{
if (candidate.HasSameMetadataDefinitionAs(member))
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -594,6 +594,12 @@ internal virtual RuntimeNamedTypeInfo AnchoringTypeDefinitionForDeclaredMembers
//
internal abstract string InternalFullNameOfAssembly { get; }

//
// Returns true if the compiler stripped the name of this type from the metadata (see IlcStripNamesAssembly).
// Getting the name of such a type throws.
//
internal virtual bool IsNameStripped => false;

//
// Left unsealed as HasElement types must override this.
//
Expand Down Expand Up @@ -729,7 +735,19 @@ internal RuntimeTypeInfo EstablishDebugName()
if (_debugName == null)
{
_debugName = "Constructing..."; // Protect against any inadvertent reentrancy.
_debugName = ToString() ?? "";
try
{
_debugName = ToString() ?? "";
}
catch (NotSupportedException)
{
// The name of the type was stripped (see IlcStripNamesAssembly). Use the address of the MethodTable

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I do not think throwing ToString is a good idea. It will just lead to this sort of "workarounds" to be propagated all over the place.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

My suggestion was to fail fast. Yes, throwing wouldn't cut it because people will add a try catch instead of really thinking about what they're doing.

// relative to the base of its module, which can be looked up in the symbol files. This code is only in debug builds.
RuntimeTypeHandle typeHandle = InternalTypeHandleIfAvailable;
_debugName = typeHandle.IsNull
? "<name stripped>"
: "EETypeRva:0x" + ((nint)typeHandle.Value - RuntimeAugments.GetModuleFromTypeHandle(typeHandle).OsModuleBase).ToString("x");
}
}
#endif
return this;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -295,7 +295,7 @@ internal static unsafe void FailFast(string? message = null, Exception? exceptio
Internal.Console.Error.Write(exception.ToString());
Internal.Console.Error.WriteLine();
}
catch
catch (Exception toStringException)
{
// If ToString() fails (for example, due to OOM), fall back to a simpler message.
try
Expand All @@ -304,7 +304,19 @@ internal static unsafe void FailFast(string? message = null, Exception? exceptio
Internal.Console.Error.Write(exception.GetMethodTable() == Internal.Runtime.MethodTable.Of<OutOfMemoryException>() ? "Out of memory." : exception.GetType().FullName);
Internal.Console.Error.WriteLine();
}
catch { }
catch
{
// The name of the type of the exception might not be available (see IlcStripNamesAssembly).
// Print the reason and the stack trace, which doesn't need the names of types.
try
{
Internal.Console.Error.Write(toStringException.Message);
Internal.Console.Error.WriteLine();
Internal.Console.Error.Write(exception.StackTrace);
Internal.Console.Error.WriteLine();
}
catch { }
}
}
}

Expand All @@ -314,7 +326,15 @@ internal static unsafe void FailFast(string? message = null, Exception? exceptio
var reporter = new EventReporter(reason);
if (exception != null && reason is not RhFailFastReason.AssertionFailure)
{
reporter.AddDescription($"{exception.GetType()}: {exception.Message}");
try
{
reporter.AddDescription($"{exception.GetType()}: {exception.Message}");
}
catch (Exception ex)
{
// The name of the type of the exception might not be available (see IlcStripNamesAssembly)
reporter.AddDescription(ex.Message);
}
reporter.AddStackTrace(exception.StackTrace);
}
else
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -108,6 +108,16 @@ public static unsafe string GetMethodNameFromStartAddressIfAvailable(IntPtr meth
}
}

// Methods of types with a name that was stripped by the compiler have no information to report.
if (IsTypeNameStripped(reader, typeHandle))
{
owningTypeName = null;
genericArgs = null;
methodSignature = null;
hashCodeForLineInfo = 0;
return null;
}

(owningTypeName, genericArgs, string methodName, methodSignature) = MethodNameFormatter.FormatMethodName(reader, typeHandle, methodHandle);
hashCodeForLineInfo = (int)VersionResilientHashCode.CombineTwoValuesIntoHash((uint)((Handle)typeHandle).ToIntToken(), (uint)((Handle)methodHandle).ToIntToken());
return methodName;
Expand Down Expand Up @@ -203,7 +213,8 @@ private static unsafe (string, int) GetLineNumberInfo(IntPtr methodStartAddress,
if (methodStartAddress != IntPtr.Zero && ReflectionExecution.TryGetMethodMetadataFromAddress(methodStartAddress, isFunctionPointer: false,
out MetadataReader reader,
out TypeDefinitionHandle typeHandle,
out MethodHandle methodHandle))
out MethodHandle methodHandle)
&& !IsTypeNameStripped(reader, typeHandle))
{
return CreateDiagnosticMethodInfo(reader, typeHandle, reader.GetMethod(methodHandle).Name);
}
Expand All @@ -223,7 +234,8 @@ private static DiagnosticMethodInfo GetDiagnosticMethodInfoFromFunctionPointerIf
if (ReflectionExecution.TryGetMethodMetadataFromAddress(functionPointer, isFunctionPointer: true,
out MetadataReader reader,
out TypeDefinitionHandle typeHandle,
out MethodHandle methodHandle))
out MethodHandle methodHandle)
&& !IsTypeNameStripped(reader, typeHandle))
{
return CreateDiagnosticMethodInfo(reader, typeHandle, reader.GetMethod(methodHandle).Name);
}
Expand All @@ -246,6 +258,12 @@ private static DiagnosticMethodInfo CreateDiagnosticMethodInfo(MetadataReader re
FormatAssemblyName(reader, owningType));
}

private static bool IsTypeNameStripped(MetadataReader reader, TypeDefinitionHandle typeHandle)
{
// The methods of a type that has its name stripped by the compiler have no information to report.
return reader.ReadStringAsBytes(reader.GetTypeDefinition(typeHandle).Name).IsEmpty;
}

private static string FormatAssemblyName(MetadataReader reader, Handle handle)
{
switch (handle.HandleType)
Expand Down
Loading
Loading