Skip to content
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
#nullable enable

using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;

namespace Microsoft.Android.Runtime;
Expand All @@ -21,12 +20,10 @@ public AggregateTypeMap (SingleUniverseTypeMap[] universes)
_universes = universes;
}

public IEnumerable<Type> GetProxyTypes (string jniName)
public void CollectProxyTypes (string jniName, ref JniProxyCacheBuilder builder)
{
foreach (var universe in _universes) {
foreach (var type in universe.GetProxyTypes (jniName)) {
yield return type;
}
universe.CollectProxyTypes (jniName, ref builder);
}
}

Expand Down
5 changes: 2 additions & 3 deletions src/Mono.Android/Microsoft.Android.Runtime/ITypeMap.cs
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
#nullable enable

using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;

namespace Microsoft.Android.Runtime;
Expand All @@ -15,9 +14,9 @@ namespace Microsoft.Android.Runtime;
interface ITypeMap
{
/// <summary>
/// Returns all proxy types mapped to a JNI name, resolving alias holders.
/// Adds all proxy types mapped to a JNI name, resolving alias holders.
/// </summary>
IEnumerable<Type> GetProxyTypes (string jniName);
void CollectProxyTypes (string jniName, ref JniProxyCacheBuilder builder);

/// <summary>
/// Resolves a managed type to its proxy type (the generated type that
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,28 +27,26 @@ public SingleUniverseTypeMap (IReadOnlyDictionary<string, Type> typeMap, IReadOn
_proxyTypeMap = proxyTypeMap;
}

public IEnumerable<Type> GetProxyTypes (string jniName)
public void CollectProxyTypes (string jniName, ref JniProxyCacheBuilder builder)
{
if (!_typeMap.TryGetValue (jniName, out var mappedType)) {
yield break;
return;
}

// Fast path: non-alias entry
if (mappedType.GetCustomAttribute<JavaPeerProxy> (inherit: false) is not null) {
yield return mappedType;
yield break;
if (builder.TryAdd (mappedType)) {
return;
}

// Slow path: alias holder — follow each alias key
var aliases = mappedType.GetCustomAttribute<JavaPeerAliasesAttribute> (inherit: false);
if (aliases is null) {
yield break;
return;
}

foreach (var key in aliases.Aliases) {
if (_typeMap.TryGetValue (key, out var aliasEntryType) &&
aliasEntryType.GetCustomAttribute<JavaPeerProxy> (inherit: false) is not null) {
yield return aliasEntryType;
if (_typeMap.TryGetValue (key, out var aliasEntryType)) {
builder.TryAdd (aliasEntryType);
}
}
}
Expand Down
110 changes: 94 additions & 16 deletions src/Mono.Android/Microsoft.Android.Runtime/TrimmableTypeMap.cs
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ public class TrimmableTypeMap

readonly ITypeMap _typeMap;
readonly ConcurrentDictionary<Type, JavaPeerProxy> _proxyCache = new ();
readonly ConcurrentDictionary<string, JavaPeerProxy[]> _jniProxyCache = new (StringComparer.Ordinal);
readonly ConcurrentDictionary<string, object> _jniProxyCache = new (StringComparer.Ordinal);
readonly ConcurrentDictionary<(string ClassName, Type TargetType), JavaPeerProxy> _interfaceProxyCache = new ();

TrimmableTypeMap (ITypeMap typeMap)
Expand Down Expand Up @@ -114,7 +114,13 @@ internal static unsafe void RegisterNativeMethods ()
/// </summary>
internal bool TryGetTargetTypes (string jniName, [NotNullWhen (true)] out Type[]? types)
{
var proxies = GetProxiesForJniName (jniName);
var cacheEntry = GetProxyCacheEntryForJniName (jniName);
if (cacheEntry is JavaPeerProxy proxy) {
types = [proxy.TargetType];
return true;
}

var proxies = (JavaPeerProxy[]) cacheEntry;
if (proxies.Length == 0) {
types = null;
return false;
Expand All @@ -128,21 +134,37 @@ internal bool TryGetTargetTypes (string jniName, [NotNullWhen (true)] out Type[]
}

/// <summary>
/// Resolves and caches all proxies for a JNI name. For non-alias entries, returns a
/// single-element array. For alias groups, resolves each alias key and returns the
/// surviving proxies. Returns an empty array when no mapping exists or all aliases were trimmed.
/// Returns the first target type mapped to a JNI name without materializing all target types.
/// </summary>
internal bool TryGetTargetType (string jniName, [NotNullWhen (true)] out Type? type)
{
var cacheEntry = GetProxyCacheEntryForJniName (jniName);
if (cacheEntry is JavaPeerProxy proxy) {
type = proxy.TargetType;
return true;
}

var proxies = (JavaPeerProxy[]) cacheEntry;
if (proxies.Length == 0) {
type = null;
return false;
}

type = proxies [0].TargetType;
return true;
}

/// <summary>
/// Resolves and caches proxies for a JNI name. Non-alias entries are cached directly as
/// <see cref="JavaPeerProxy"/> instances. Alias groups are cached as arrays, and misses as
Comment thread
simonrozsival marked this conversation as resolved.
Resolved
/// an empty array.
/// </summary>
JavaPeerProxy[] GetProxiesForJniName (string jniName)
object GetProxyCacheEntryForJniName (string jniName)
{
return _jniProxyCache.GetOrAdd (jniName, static (name, self) => {
var result = new List<JavaPeerProxy> ();
foreach (var type in self._typeMap.GetProxyTypes (name)) {
var proxy = type.GetCustomAttribute<JavaPeerProxy> (inherit: false);
if (proxy is not null) {
result.Add (proxy);
}
}
return result.Count > 0 ? result.ToArray () : [];
var builder = new JniProxyCacheBuilder ();
self._typeMap.CollectProxyTypes (name, ref builder);
return builder.Build ();
}, this);
Comment thread
simonrozsival marked this conversation as resolved.
Resolved
}

Expand All @@ -153,7 +175,14 @@ JavaPeerProxy[] GetProxiesForJniName (string jniName)
/// </summary>
JavaPeerProxy? GetProxyForJniClass (string className, Type? targetType)
{
var proxies = GetProxiesForJniName (className);
var cacheEntry = GetProxyCacheEntryForJniName (className);
if (cacheEntry is JavaPeerProxy singleProxy) {
return targetType is null || TargetTypeMatches (targetType, singleProxy.TargetType)
? singleProxy
: null;
}

var proxies = (JavaPeerProxy[]) cacheEntry;
if (proxies.Length == 0) {
return null;
}
Expand Down Expand Up @@ -462,7 +491,21 @@ static void OnRegisterNatives (IntPtr jnienv, IntPtr klass, IntPtr nativeClassHa
return;
}

var proxies = s_instance.GetProxiesForJniName (className);
var cacheEntry = s_instance.GetProxyCacheEntryForJniName (className);
if (cacheEntry is JavaPeerProxy singleProxy) {
if (singleProxy is not IAndroidCallableWrapper acw) {
return;
}

// Use the class reference passed from Java (via C++) — not JniType(className)
// which resolves via FindClass and may get a different class from a different ClassLoader.
// Registering natives on that other instance is silently wrong.
using var singleJniType = new JniType (ref classRef, JniObjectReferenceOptions.Copy);
acw.RegisterNatives (singleJniType);
return;
}

var proxies = (JavaPeerProxy[]) cacheEntry;
if (proxies.Length == 0) {
return;
}
Expand Down Expand Up @@ -491,3 +534,38 @@ public MissingJavaPeerProxy () : base ("<missing>", typeof (Java.Lang.Object))
}

}

struct JniProxyCacheBuilder
{
static readonly JavaPeerProxy[] Empty = [];

JavaPeerProxy? first;
List<JavaPeerProxy>? multiple;

public bool TryAdd (Type proxyType)
{
var proxy = proxyType.GetCustomAttribute<JavaPeerProxy> (inherit: false);
if (proxy is null) {
return false;
}

var firstProxy = first;
if (firstProxy is null) {
first = proxy;
return true;
}

multiple ??= new List<JavaPeerProxy> (2) { firstProxy };
multiple.Add (proxy);
return true;
}

public object Build ()
{
if (multiple is not null) {
return multiple.ToArray ();
}

return first is JavaPeerProxy proxy ? proxy : Empty;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -212,9 +212,8 @@ protected override IEnumerable<Type> GetTypesForSimpleReference (string jniSimpl
return builtInType;
}

// TryGetTargetTypes returns a non-empty array when it succeeds.
if (TrimmableTypeMap.Instance.TryGetTargetTypes (jniSimpleReference, out var types)) {
return types [0];
if (TrimmableTypeMap.Instance.TryGetTargetType (jniSimpleReference, out var type)) {
return type;
}

return null;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -127,6 +127,8 @@ public void JavaListAliasGroup_TargetHintSelectsGenericAndNonGenericManagedTypes
}
CollectionAssert.Contains (targetTypes, typeof (JavaList));
CollectionAssert.Contains (targetTypes, typeof (JavaList<>));
Assert.IsTrue (TrimmableTypeMap.Instance.TryGetTargetType ("java/util/ArrayList", out var firstTargetType));
Assert.AreEqual (targetTypes [0], firstTargetType);

var arrayListClass = JniEnvironment.Types.FindClass ("java/util/ArrayList");
try {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,96 @@ public void GetTypeSignature_NullableByteJaggedArray_ReturnsJavaLangByte (Type t
Assert.AreEqual (expected, signature.Name);
}

[Test]
public void GetType_RepeatedJavaToManagedLookup_DoesNotAllocate ()
{
AssumeTrimmableTypeMapEnabled ();

const string jniName = "android/view/View";
const int iterationCount = 1_000;
var typeMap = TrimmableTypeMap.Instance;
Assert.IsTrue (typeMap.TryGetTargetTypes (jniName, out var targetTypes));
Assert.AreEqual (1, targetTypes.Length, "The allocation test requires a non-alias typemap entry.");

var signature = new JniTypeSignature (jniName);
var manager = JniEnvironment.Runtime.TypeManager;
Type result = typeof (void);
for (int i = 0; i < iterationCount; i++) {
result = manager.GetType (signature);
}

long before = GC.GetAllocatedBytesForCurrentThread ();
for (int i = 0; i < iterationCount; i++) {
result = manager.GetType (signature);
}
long allocatedBytes = GC.GetAllocatedBytesForCurrentThread () - before;

Assert.AreEqual (typeof (Android.Views.View), result);
Assert.AreEqual (0L, allocatedBytes, $"Expected {iterationCount} cached lookups to allocate no managed memory.");
}

[Test]
public void TryGetTargetType_MissingEntry_ReturnsFalse ()
{
AssumeTrimmableTypeMapEnabled ();

Assert.IsFalse (TrimmableTypeMap.Instance.TryGetTargetType ("net/dot/android/test/MissingType", out var targetType));
Assert.IsNull (targetType);
}

[Test]
public void JniProxyCache_SingleMappingStoresProxyDirectly ()
{
AssumeTrimmableTypeMapEnabled ();

const string jniName = "android/view/View";
var instance = TrimmableTypeMap.Instance;
var cache = GetJniProxyCache (instance);
cache.TryRemove (jniName, out _);

Assert.IsTrue (instance.TryGetTargetType (jniName, out var targetType));
Assert.AreEqual (typeof (Android.Views.View), targetType);
Assert.IsTrue (cache.TryGetValue (jniName, out var cacheEntry));
Assert.IsInstanceOf<JavaPeerProxy> (cacheEntry);
}

[Test]
public void JniProxyCache_AliasMappingStoresProxyArray ()
{
AssumeTrimmableTypeMapEnabled ();

const string jniName = "java/util/ArrayList";
var instance = TrimmableTypeMap.Instance;
var cache = GetJniProxyCache (instance);
cache.TryRemove (jniName, out _);

Assert.IsTrue (instance.TryGetTargetTypes (jniName, out var targetTypes));
Assert.Greater (targetTypes.Length, 1);
Assert.IsTrue (cache.TryGetValue (jniName, out var cacheEntry));
Assert.IsInstanceOf<JavaPeerProxy[]> (cacheEntry);
}

[Test]
public void JniProxyCache_MissingMappingStoresEmptyProxyArray ()
{
AssumeTrimmableTypeMapEnabled ();

const string jniName = "net/dot/android/test/MissingProxyCacheEntry";
var instance = TrimmableTypeMap.Instance;
var cache = GetJniProxyCache (instance);
cache.TryRemove (jniName, out _);

Assert.IsFalse (instance.TryGetTargetType (jniName, out var targetType));
Assert.IsNull (targetType);
Assert.IsTrue (cache.TryGetValue (jniName, out var cacheEntry));
if (cacheEntry is JavaPeerProxy[] proxies) {
Assert.AreEqual (0, proxies.Length);
return;
}

Assert.Fail ("A missing JNI mapping should be cached as an empty proxy array.");
}

// Verifies the generic-type-definition fallback in GetProxyForManagedType:
// the generator emits one TypeMapAssociation per open generic peer, so a
// closed instantiation like JavaList<string> must resolve through its GTD.
Expand Down Expand Up @@ -350,6 +440,22 @@ static ConcurrentDictionary<Type, JavaPeerProxy> GetProxyCache (TrimmableTypeMap
throw new InvalidOperationException ("Unable to access TrimmableTypeMap proxy cache.");
}

static ConcurrentDictionary<string, object> GetJniProxyCache (TrimmableTypeMap instance)
{
var field = typeof (TrimmableTypeMap).GetField ("_jniProxyCache", BindingFlags.Instance | BindingFlags.NonPublic);
Assert.IsNotNull (field);

var value = field.GetValue (instance);
Assert.IsNotNull (value);

if (value is ConcurrentDictionary<string, object> cache) {
return cache;
}

Assert.Fail ("Unable to access TrimmableTypeMap JNI proxy cache.");
throw new InvalidOperationException ("Unable to access TrimmableTypeMap JNI proxy cache.");
}

static IReadOnlyList<string> GetStaticMethodFallbackTypes (TestableTrimmableTypeMapTypeManager manager, string jniSimpleReference)
{
var fallbacks = manager.GetStaticMethodFallbackTypes (jniSimpleReference);
Expand Down
Loading