Skip to content

[TrimmableTypeMap] Java peer scanner with SRM + test project #10798

Closed

Description

@simonrozsival

Part of #10789

Overview

Implement the Java peer type scanner using System.Reflection.Metadata (SRM) — no Mono.Cecil. This is the foundation that all code generation builds on.

New project: src/Microsoft.Android.Sdk.TrimmableTypeMap/ — a dedicated assembly separate from Xamarin.Android.Build.Tasks for fast inner dev loop.

What this includes

Scanner (JavaPeerScanner)

  • Open assemblies via PEReader + MetadataReader
  • Find types with [Register] attribute → extract JNI name and DoNotGenerateAcw flag
  • Detect activation constructors: XI style (IntPtr, JniHandleOwnership) first, then JI style (ref JniObjectReference, JniObjectReferenceOptions) — walk up hierarchy if not on type itself
  • Collect marshal methods: methods with [Register(name, sig, connector)] or [Export] attributes
  • Detect component attributes ([Activity], [Service], [BroadcastReceiver], [ContentProvider], [Application], [Instrumentation]) for unconditional marking
  • Detect interface implementors and invoker types (including generic interface instantiations)
  • Handle generic types: open generic definition gets the TypeMap entry
  • Handle [Application(BackupAgent=typeof(...))] and [Application(ManageSpaceActivity=typeof(...))] cross-references → force unconditional
  • Support IJniNameProviderAttribute for custom JNI name resolution
  • Compute CompatJniName (lowercased namespace) for acw-map.txt backward compatibility

Two-phase in-memory architecture (critical for performance)

Both PoCs suffered from O(n²) behavior scanning Mono.Android (~8000 types). The scanner uses:

Phase 1 — Index building (one pass per assembly):

  • TypesByFullName / TypesByJniName dictionaries for O(1) lookups
  • RegisterInfoByType / AttributesByType pre-indexed per type
  • IJniNameProviderAttribute detection and reclassification across assemblies
  • All state stays in memory — MSBuild Inputs/Outputs handles target-level incrementality

Phase 2 — Type analysis (uses cached indices only):

  • ActivationCtorCache — hierarchy walk results shared across types with same base
  • extendsJavaPeerCache — caches ExtendsJavaPeer results and doubles as cycle detection
  • Cross-assembly type resolution via TryResolveType / ResolveRegisterJniName helpers

Performance target: <1s for Mono.Android (~8000 types).

CRC64 polynomial

The scanner uses System.IO.Hashing.Crc64 (ECMA polynomial) instead of the legacy Crc64Helper (Jones polynomial). This is intentional and safe. The CRC64 hash only needs to be self-consistent within a single compilation — the scanner computes the JNI name, the JCW generator uses it, the typemap records it, and acw-map.txt maps it. All consumers read from the same scan pass. See implementation update comment for details.

Data model

JavaPeerInfo {
    JavaName, CompatJniName,
    ManagedTypeName, ManagedTypeNamespace, ManagedTypeShortName,
    AssemblyName, BaseJavaName, ImplementedInterfaceJavaNames,
    IsInterface, IsAbstract, DoNotGenerateAcw,
    IsUnconditional, IsGenericDefinition,
    MarshalMethods[], JavaConstructors[],
    ActivationCtor, InvokerTypeName?
}

MarshalMethodInfo {
    JniName, JniSignature, Connector,
    ManagedMethodName, DeclaringTypeName, DeclaringAssemblyName,
    NativeCallbackName, Parameters[], JniReturnType,
    IsConstructor, ThrownNames, SuperArgumentsString
}

Test projects

Unit tests (tests/Microsoft.Android.Sdk.TrimmableTypeMap.Tests/):

  • Hand-crafted test assembly (~20 types) for TDD inner loop
  • 75 tests covering scanner logic, JNI parsing, edge cases

Integration tests (tests/Microsoft.Android.Sdk.TrimmableTypeMap.IntegrationTests/):

  • Legacy comparison tests: Run both legacy Cecil-based scanner and new SRM scanner on same assemblies, compare results
  • Real Mono.Android.dll (~8000 types) side-by-side comparison
  • UserTypesFixture.dll — user-type edge cases ([Activity], [Service], [Export], nested types, generic types, plain Java.Lang.Object subclasses)
  • 10 tests (type maps + marshal methods for both assemblies)

Type classification rules (spec §15.9)

Type Unconditional? Gets JCW? Gets RegisterNatives?
User class with [Activity]/[Service]/etc ✅ ✅ ✅
Custom view from layout XML ✅ ✅ ✅
User class without component attr Trimmable ✅ ✅
MCW binding (DoNotGenerateAcw=true) Trimmable ❌ ❌
Interface Trimmable ❌ ❌
Invoker Excluded ❌ ❌

Activity

  1. added this to the .NET 11 milestone on Feb 11, 2026
  2. added
    Area: NativeAOT
    Area: CoreCLR
    on Feb 11, 2026
  3. added
    needs-triage
    on Feb 11, 2026
  4. simonrozsival commented on Feb 12, 2026

    @simonrozsival
    MemberAuthor

    Implementation status update (#10805)

    CRC64 polynomial divergence — by design

    The new scanner uses System.IO.Hashing.Crc64 (ECMA polynomial) instead of the legacy Crc64Helper (Jones polynomial 0xad93d23594c935a9). This is intentional and safe.

    The CRC64 hash is only used to generate Java package names for user types that don't have explicit [Register] attributes (e.g., crc64abc123/MyActivity). The hash doesn't need to be consistent between the legacy and trimmable paths — it only needs to be consistent within a single compilation. During build:

    1. The scanner computes crc64{hash}/{TypeName} as the JNI name
    2. The JCW generator creates a .java file with that exact class name
    3. The typemap records the mapping with that exact name
    4. acw-map.txt records the mapping with that exact name

    All consumers use the same computed value from the same scan pass, so the polynomial choice doesn't affect correctness. Side-by-side tests normalize CRC64 hashes (crc64XXXX/Name → crc64.../Name) to verify everything else matches.

    Data model evolved beyond original spec

    The JavaPeerInfo data model now includes additional fields needed by downstream consumers (JCW generation in #10799, acw-map in #10807):

    JavaPeerInfo {
        JavaName, CompatJniName,                        // JNI names (CRC64 + lowercased namespace compat)
        ManagedTypeName, ManagedTypeNamespace,           // Full name + namespace (for JCW file paths)
        ManagedTypeShortName, AssemblyName,              // Short name + assembly
        BaseJavaName,                                    // Base Java type (for JCW extends clause)
        ImplementedInterfaceJavaNames,                   // Interfaces (for JCW implements clause)
        IsInterface, IsAbstract, DoNotGenerateAcw,
        IsUnconditional, IsGenericDefinition,
        MarshalMethods[], JavaConstructors[],            // Methods + constructors (for JCW body)
        ActivationCtor, InvokerTypeName?
    }
    
    MarshalMethodInfo {
        JniName, JniSignature, Connector,               // Connector replaces HasGeneratorCallback
        ManagedMethodName, DeclaringTypeName,
        DeclaringAssemblyName, NativeCallbackName,
        Parameters[], JniReturnType, IsConstructor,
        ThrownNames, SuperArgumentsString               // For [Export] support
    }
    

    Key additions over the original spec:

    • CompatJniName — lowercased namespace version for acw-map.txt backward compatibility with layout XML custom view resolution
    • BaseJavaName / ImplementedInterfaceJavaNames — needed for JCW extends/implements clauses
    • JavaConstructors — needed for JCW Java constructor generation
    • IJniNameProviderAttribute support — custom JNI name resolution from Java.Interop
    • [Export] enrichment — ThrownNames and SuperArgumentsString for JCW generation

    Other spec updates

    • Project renamed: Microsoft.Android.Build.TypeMap → Microsoft.Android.Sdk.TrimmableTypeMap (matches Microsoft.Android.Sdk.ILLink / Microsoft.Android.Sdk.Analysis naming)
    • No disk caching: All intermediate state stays in memory (MSBuild Inputs/Outputs handles target-level incrementality)
    • extendsJavaPeerCache replaces BaseTypeChain — simpler approach that doubles as cycle detection

    Side-by-side test findings

    Tests run on both Mono.Android.dll (~8,000+ types) and a UserTypesFixture.dll (user-type edge cases):

    • Nested type JNI names: Found and fixed — OuterClass+InnerHelper must inherit parent's [Register] prefix, not get an independent CRC64 name
    • [Export] methods: New scanner correctly finds [Export] methods that legacy test helper missed (legacy only extracts [Register] methods)
    • All other fields match exactly: component attributes, marshal method signatures, skip flags, interface detection, invoker resolution
  5. locked and limited conversation to collaborators on Apr 10, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

Area: CoreCLRArea: NativeAOTneeds-triagetrimmable-type-map

Type

No type

Projects

No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions