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,31 @@ 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;
var proxy = mappedType.GetCustomAttribute<JavaPeerProxy> (inherit: false);
if (proxy is not null) {
builder.Add (proxy);
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)) {
var aliasProxy = aliasEntryType.GetCustomAttribute<JavaPeerProxy> (inherit: false);
if (aliasProxy is not null) {
builder.Add (aliasProxy);
}
}
}
}
Expand Down
131 changes: 100 additions & 31 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 @@ -107,53 +107,80 @@ internal static unsafe void RegisterNativeMethods ()
}
}

internal IEnumerable<Type> GetTargetTypes (string jniName)
{
var cacheEntry = GetProxyCacheEntryForJniName (jniName);
if (cacheEntry is JavaPeerProxy proxy) {
yield return proxy.TargetType;
yield break;
}

foreach (var aliasProxy in GetProxyArrayCacheEntry (cacheEntry)) {
yield return aliasProxy.TargetType;
}
}

/// <summary>
/// Returns all target types mapped to a JNI name. For non-alias entries, returns a
/// single-element array. For alias groups, returns the surviving target types from
/// each alias key. Returns false 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 TryGetTargetTypes (string jniName, [NotNullWhen (true)] out Type[]? types)
internal bool TryGetTargetType (string jniName, [NotNullWhen (true)] out Type? type)
{
var proxies = GetProxiesForJniName (jniName);
var cacheEntry = GetProxyCacheEntryForJniName (jniName);
if (cacheEntry is JavaPeerProxy proxy) {
type = proxy.TargetType;
return true;
}

var proxies = GetProxyArrayCacheEntry (cacheEntry);
if (proxies.Length == 0) {
types = null;
type = null;
return false;
}

types = new Type [proxies.Length];
for (int i = 0; i < proxies.Length; i++) {
types [i] = proxies [i].TargetType;
}
type = proxies [0].TargetType;
return true;
}

/// <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.
/// 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
}

internal static JavaPeerProxy[] GetProxyArrayCacheEntry (object cacheEntry)
{
if (cacheEntry is JavaPeerProxy[] proxies) {
return proxies;
}

throw new InvalidOperationException (
$"Unexpected JNI proxy cache entry type '{cacheEntry.GetType ().FullName}'. " +
$"Expected {nameof (JavaPeerProxy)} or {nameof (JavaPeerProxy)}[].");
}

/// <summary>
/// Resolves the best proxy for a JNI class name, handling both direct entries and alias groups.
/// When targetType is available, finds the proxy whose TargetType matches.
/// When targetType is null, returns the first available proxy.
/// </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 = GetProxyArrayCacheEntry (cacheEntry);
if (proxies.Length == 0) {
return null;
}
Expand All @@ -167,6 +194,23 @@ JavaPeerProxy[] GetProxiesForJniName (string jniName)
}
return null;
}

internal static void RegisterNativeMethods (object cacheEntry, JniType jniType)
{
if (cacheEntry is JavaPeerProxy singleProxy) {
if (singleProxy is IAndroidCallableWrapper acw) {
acw.RegisterNatives (jniType);
}
return;
}

foreach (var proxy in GetProxyArrayCacheEntry (cacheEntry)) {
if (proxy is IAndroidCallableWrapper acw) {
acw.RegisterNatives (jniType);
}
}
}

JavaPeerProxy? GetProxyForManagedType (Type managedType)
{
if (managedType.IsGenericType && !managedType.IsGenericTypeDefinition) {
Expand Down Expand Up @@ -462,20 +506,16 @@ static void OnRegisterNatives (IntPtr jnienv, IntPtr klass, IntPtr nativeClassHa
return;
}

var proxies = s_instance.GetProxiesForJniName (className);
if (proxies.Length == 0) {
var cacheEntry = s_instance.GetProxyCacheEntryForJniName (className);
if (cacheEntry is JavaPeerProxy[] proxies && proxies.Length == 0) {
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 jniType = new JniType (ref classRef, JniObjectReferenceOptions.Copy);
foreach (var proxy in proxies) {
if (proxy is IAndroidCallableWrapper acw) {
acw.RegisterNatives (jniType);
}
}
RegisterNativeMethods (cacheEntry, jniType);
} catch (Exception ex) {
Environment.FailFast ($"TrimmableTypeMap: Failed to register natives for class '{className}'.", ex);
}
Expand All @@ -491,3 +531,32 @@ public MissingJavaPeerProxy () : base ("<missing>", typeof (Java.Lang.Object))
}

}

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

JavaPeerProxy? first;
List<JavaPeerProxy>? multiple;

public void Add (JavaPeerProxy proxy)
{
var firstProxy = first;
if (firstProxy is null) {
first = proxy;
return;
}

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

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 @@ -196,10 +196,8 @@ protected override IEnumerable<Type> GetTypesForSimpleReference (string jniSimpl
yield return builtInType;
}

if (TrimmableTypeMap.Instance.TryGetTargetTypes (jniSimpleReference, out var types)) {
foreach (var type in types) {
yield return type;
}
foreach (var type in TrimmableTypeMap.Instance.GetTargetTypes (jniSimpleReference)) {
yield return type;
}
}

Expand All @@ -212,9 +210,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
@@ -1,4 +1,5 @@
using System;
using System.Collections.Generic;

using Android.Text;
using Android.Runtime;
Expand Down Expand Up @@ -120,13 +121,15 @@ public void JavaListAliasGroup_TargetHintSelectsGenericAndNonGenericManagedTypes
{
AssumeTrimmableTypeMapEnabled ();

Assert.IsTrue (TrimmableTypeMap.Instance.TryGetTargetTypes ("java/util/ArrayList", out var targetTypes));
if (targetTypes is null) {
Assert.Fail ("The java/util/ArrayList alias group was not generated.");
return;
var targetTypes = new List<Type> ();
foreach (var targetType in TrimmableTypeMap.Instance.GetTargetTypes ("java/util/ArrayList")) {
targetTypes.Add (targetType);
}
Assert.IsNotEmpty (targetTypes, "The java/util/ArrayList alias group was not generated.");
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
Loading
Loading