Repository navigation
Description
Description
ILLink does not retain an external TypeMapAttribute entry when its trim target is used only by a reachable reference-type castclass instruction. The same program works correctly with NativeAOT/ILC.
This was discovered while investigating dotnet/android#13286, but it reproduces in a standalone net11.0 console application without Android.
Minimal reproduction
TypeMapCastRepro.csproj:
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net11.0</TargetFramework>
<PublishTrimmed>true</PublishTrimmed>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
</Project>Program.cs:
using System.Runtime.InteropServices;
[assembly: TypeMap<Repro.TypeMapGroup> (
"cast-target",
typeof (Repro.MappedType),
typeof (Repro.CastTarget))]
namespace Repro;
static class Program
{
static int Main (string [] args)
{
_ = (CastTarget?) (args.Length == 0 ? null : new object ());
var typeMap = TypeMapping.GetOrCreateExternalTypeMapping<TypeMapGroup> ();
if (!typeMap.TryGetValue ("cast-target", out Type? mappedType)) {
Console.WriteLine ("MISSING: castclass did not retain the external type-map entry.");
return 1;
}
Console.WriteLine ($"PRESENT: castclass retained {mappedType.FullName}.");
return mappedType.FullName == "Repro.MappedType" ? 0 : 2;
}
}
sealed class TypeMapGroup;
sealed class CastTarget;
sealed class MappedType;The command-line argument check prevents the cast operand from being statically known as null. With no arguments, the cast safely receives null; passing any argument intentionally supplies an incompatible object and proves that the castclass remains.
CoreCLR/ILLink result
Using .NET SDK 11.0.100-rc.2.26504.105 on osx-arm64:
dotnet publish -c Release -r osx-arm64 --self-contained true \
-p:PublishAot=false -o out/coreclr
./out/coreclr/TypeMapCastReproOutput and exit code:
MISSING: castclass did not retain the external type-map entry.
exit code: 1
Inspection of the linked application confirms:
Mainstill containscastclass Repro.CastTarget.Repro.CastTargetremains.Repro.MappedTypeis removed.- The assembly-level
TypeMapAttributeentry is removed.
NativeAOT/ILC result
dotnet publish -c Release -r osx-arm64 --self-contained true \
-p:PublishAot=true -o out/nativeaot
./out/nativeaot/TypeMapCastReproOutput and exit code:
PRESENT: castclass retained Repro.MappedType.
exit code: 0
Expected behavior
The External Type Map specification explicitly includes both isinst and castclass as operations that retain an entry whose trim target is the instruction operand:
The CoreCLR/ILLink result should match NativeAOT/ILC and retain the cast-target entry and MappedType.
Suspected root cause
TypeMapHandler initially stores the entry in _unmarkedExternalTypeMapEntries, keyed by CastTarget. It must later receive ProcessType(CastTarget) to mark the attribute and its target.
MarkStep.MarkInstruction has explicit TypeMap notification only for Code.Isinst:
runtime/src/tools/illink/src/linker/Linker.Steps/MarkStep.cs
Lines 4097 to 4135 in 5233491
| case OperandType.InlineType: | |
| var operand = (TypeReference)instruction.Operand; | |
| requiresReflectionMethodBodyScanner |= InstructionRequiresReflectionMethodBodyScannerForTypeAccess(instruction); | |
| switch (instruction.OpCode.Code) | |
| { | |
| case Code.Newarr: | |
| if (Context.TryResolve(operand) is TypeDefinition typeDefinition) | |
| { | |
| MarkRelevantToVariantCasting(typeDefinition); | |
| } | |
| break; | |
| case Code.Isinst: | |
| if (operand is TypeSpecification || operand is GenericParameter) | |
| break; | |
| if (!Context.CanApplyOptimization(CodeOptimizations.UnusedTypeChecks, method.DeclaringType.Module.Assembly)) | |
| break; | |
| TypeDefinition? type = Context.Resolve(operand); | |
| if (type == null) | |
| return; | |
| if (type.IsInterface) | |
| break; | |
| _typeMapHandler.ProcessType(type); | |
| if (!Annotations.IsInstantiated(type)) | |
| { | |
| _pending_isinst_instr.Add((type, method.Body, instruction)); | |
| return; | |
| } | |
| break; | |
| } | |
| origin = new MessageOrigin(origin, instruction.Offset); | |
| MarkType(operand, new DependencyInfo(DependencyKind.InstructionTypeRef, method), origin); | |
| break; |
case Code.Isinst:
...
_typeMapHandler.ProcessType(type);There is no Code.Castclass case. castclass falls through to ordinary MarkType(operand, ...), which preserves CastTarget but does not notify TypeMapHandler. The deferred external map entry therefore remains unmarked.
NativeAOT handles both instructions through the same ImportCasting path and creates the necessary type-symbol dependency:
runtime/src/coreclr/tools/aot/ILCompiler.Compiler/IL/ILImporter.Scanner.cs
Lines 319 to 330 in 5233491
| private void ImportCasting(ILOpcode opcode, int token) | |
| { | |
| TypeDesc type = (TypeDesc)_methodIL.GetObject(token); | |
| if (type.IsRuntimeDeterminedSubtype) | |
| { | |
| _dependencies.Add(GetGenericLookupHelper(ReadyToRunHelperId.TypeHandleForCasting, type), "IsInst/CastClass"); | |
| } | |
| else | |
| { | |
| _dependencies.Add(_compilation.ComputeConstantLookup(ReadyToRunHelperId.TypeHandleForCasting, type), "IsInst/CastClass"); | |
| } |
The ILLink hook was introduced in #116555. The implementation and test suite cover isinst and value-type unboxing, but there does not appear to be a reference-type castclass retention test.
A likely fix is to process direct castclass and isinst targets before entering the isinst-specific unused-type-check optimization. Simply sharing the existing body unchanged would be incorrect because it could add castclass instructions to _pending_isinst_instr, whose cleanup rewrites type checks to pop; ldnull.
The existing isinst notification is also currently conditional on the UnusedTypeChecks optimization being enabled and skips interfaces before notifying TypeMapHandler; both conditions appear narrower than the External Type Map specification.
Related issues
- AndroidTypeMapImplementation trimmable removes types that are used in type casts android#13286 — original Android failure
- illink: TypeMapAssociation attribute always trimmed if there's a TypeMap attribute for the same type. #127004 and ILLink: TypeMapAttribute entry incorrectly trimmed when target type's MarkInstantiated is poisoned by TypeMapAssociationAttribute #127504 — related TypeMap retention/order bugs, fixed by Fix illink TypeMap proxy retention. Fixes #127004. #127005, but with different triggering conditions
Metadata
Metadata
Assignees
Labels
Type
Projects
- StatusShow more project fieldsNo status
Activity
dotnet-policy-service commentedon Oct 28, 2026
Tagging subscribers to this area: @agocke, @dotnet/illink
See info in area-owners.md if you want to be subscribed.