Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[nativeaot] run Mono.Android-Tests #9846

Draft
wants to merge 1 commit into
base: main
Choose a base branch
from

Conversation

jonathanpeppers
Copy link
Member

This is WIP, it doesn't even build quite yet.

@jonathanpeppers jonathanpeppers mentioned this pull request Feb 24, 2025
11 tasks
jonathanpeppers added a commit to dotnet/java-interop that referenced this pull request Feb 25, 2025
Context: dotnet/android#9846

When trying to build `Mono.Android-Tests` for NativeAOT, I get many
warnings like this (that are upgraded to errors):

    src\Java.Interop.GenericMarshaler\Java.Interop.GenericMarshaler\JniPeerInstanceMethodsExtensions.cs(10874,17):
    error IL2091: 'T' generic argument does not satisfy 'DynamicallyAccessedMemberTypes.PublicConstructors', 'DynamicallyAccessedMemberTypes.NonPublicConstructors' in 'Java.Interop.JniRuntime.JniValueManager.GetValueMarshaler<T>()'. The generic parameter 'T16' of 'Java.Interop.GenericMarshaler.JniPeerInstanceMethodsExtensions.InvokeGenericVirtualObjectMethod<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16>(JniInstanceMethods, String, IJavaPeerable, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16)' does not have matching annotations. The source value must declare at least the same requirements as those declared on the target location it is assigned to.
    Build failed with 2992 error(s) in 4.8s

To solve this here, we can import:

    <Import Project="..\..\build-tools\trim-analyzers\trim-analyzers.props" />

To see all the warnings *here*, and then I added the missing
attributes to solve the warnings.
jonpryor pushed a commit to dotnet/java-interop that referenced this pull request Feb 26, 2025
Context: dotnet/android#9846

When trying to build `Mono.Android-Tests` for NativeAOT, I get many
warnings like this (that are upgraded to errors):

	src\Java.Interop.GenericMarshaler\Java.Interop.GenericMarshaler\JniPeerInstanceMethodsExtensions.cs(10874,17):
	error IL2091: 'T' generic argument does not satisfy 'DynamicallyAccessedMemberTypes.PublicConstructors', 'DynamicallyAccessedMemberTypes.NonPublicConstructors' in 'Java.Interop.JniRuntime.JniValueManager.GetValueMarshaler<T>()'. The generic parameter 'T16' of 'Java.Interop.GenericMarshaler.JniPeerInstanceMethodsExtensions.InvokeGenericVirtualObjectMethod<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16>(JniInstanceMethods, String, IJavaPeerable, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16)' does not have matching annotations. The source value must declare at least the same requirements as those declared on the target location it is assigned to.
	Build failed with 2992 error(s) in 4.8s

To solve this here, we can import:

	<Import Project="..\..\build-tools\trim-analyzers\trim-analyzers.props" />

To see all the warnings *here*, and then I added the missing
attributes to solve the warnings.
@jonathanpeppers jonathanpeppers force-pushed the dev/peppers/mono.android-tests-nativeaot branch 2 times, most recently from 3e1f3c0 to b4c9a2e Compare February 27, 2025 16:38
jonathanpeppers added a commit to jonathanpeppers/runtime that referenced this pull request Feb 27, 2025
Context: dotnet/android#9846

Trying to build our `Mono.Android-Tests` suite for NativeAOT, it fails
with:

    EXEC Failed to load assembly 'System.IO'

Which is caused by passing:

    --root:System.IO

I couldn't find anything in the Android workload that would cause this.

It appears the `Microsoft.NETCore.Native.targets` have an issue caused
by this specific project:

* When adding to `@(_IlcRootedAssemblies)` it does an `Exists()` check

* So `Exists('System.IO.Compression')` is called. This is *true*
  because there is a folder in the working directory named
  `System.IO.Compression`!

https://github.com/dotnet/android/tree/main/tests/Mono.Android-Tests/Mono.Android-Tests/System.IO.Compression

* `%(FileName)` is then `System.IO` as `.Compression` is stripped as
  the `%(Extension)` metadata.

I believe the fix here is to use `System.IO.File.Exists()` instead of
MSBuild's `Exists()` as it returns `true` for files *and* folders.
jonathanpeppers added a commit to dotnet/runtime that referenced this pull request Feb 27, 2025
Context: dotnet/android#9846

Trying to build our `Mono.Android-Tests` suite for NativeAOT, it fails
with:

    EXEC Failed to load assembly 'System.IO'

Which is caused by passing:

    --root:System.IO

I couldn't find anything in the Android workload that would cause this.

It appears the `Microsoft.NETCore.Native.targets` have an issue caused
by this specific project:

* When adding to `@(_IlcRootedAssemblies)` it does an `Exists()` check

* So `Exists('System.IO.Compression')` is called. This is *true*
  because there is a folder in the working directory named
  `System.IO.Compression`!

https://github.com/dotnet/android/tree/main/tests/Mono.Android-Tests/Mono.Android-Tests/System.IO.Compression

* `%(FileName)` is then `System.IO` as `.Compression` is stripped as
  the `%(Extension)` metadata.

I believe the fix here is to use `System.IO.File.Exists()` instead of
MSBuild's `Exists()` as it returns `true` for files *and* folders.
jonpryor pushed a commit that referenced this pull request Feb 28, 2025
Context: #9846

Running `tests/Mono.Android-Tests` on NativeAOT crashes with:

	E NUnit   : Error: System.NotSupportedException: NotSupported_CodeBase (TaskId:30)
	E NUnit   :    at System.Reflection.Runtime.Assemblies.RuntimeAssemblyInfo.get_CodeBase() + 0x34 (TaskId:30)
	E NUnit   :    at NUnit.Framework.Internal.AssemblyHelper.GetAssemblyPath(Assembly) + 0x10 (TaskId:30)
	E NUnit   :    at NUnit.Framework.Internal.NUnitLiteTestAssemblyBuilder.Build(Assembly, IDictionary) + 0x8c (TaskId:30)
	E NUnit   :    at NUnit.Framework.Internal.NUnitLiteTestAssemblyRunner.Load(Assembly, IDictionary) + 0x28 (TaskId:30)
	E NUnit   :    at Xamarin.Android.UnitTests.NUnit.NUnitTestRunner.Run(IList`1) + 0x1ac (TaskId:30)
	E NUnit   :    at Xamarin.Android.UnitTests.TestInstrumentation`1.RunTests(Bundle&) + 0xc8 (TaskId:30)
	E NUnit   :    at Xamarin.Android.UnitTests.TestInstrumentation`1.OnStart() + 0x48 (TaskId:30)

It appears we can just remove all usage of `Assembly.CodeBase` from
NUnitLite to get past this error.
jonpryor pushed a commit that referenced this pull request Feb 28, 2025
…#9858)

Context: #9846
Context: dbb0b92
Context: d70db5b

While trying to *build* `tests/Mono.Android-Tests` with NativeAOT:

	dotnet-local.cmd build tests/Mono.Android-Tests/Mono.Android-Tests/Mono.Android.NET-Tests.csproj ^
	  -p:TestsFlavor=NativeAOT -p:PublishAot=true -c Release -bl -t:Install

it would fail to build:

	tests\Mono.Android-Tests\Java.Interop-Tests\obj\Release\net10.0-android\generated\src\Net.Dot.Jni.Test.MyJavaInterfaceImpl.cs(19,81):
	error CS1056: Unexpected character '`'

The offending code?

	public partial class MyJavaInterfaceImpl : global::Java.Interop.JavaObjectArray`1, global::Net.Dot.Jni.Test.IJavaInterface {
	}

which is deeply, *deeply*, wrong.

Further investigation showed that the problem was that
`Java.Interop-Tests` was trying to bind Java code, and in this case
was using `generator --codegen-target=JavaInterop1` output.

This is output we've never tried to use before in .NET for Android;
`generator --codegen-target=JavaInterop1` is experimental
(and @jonpryor's playground; see dotnet/java-interop#858), and
shouldn't be used *now* (if ever).

Ultimately, we realized that commit d70db5b was *wrong*, in that it
merged two different things:

 1. Java stub generation's "codegen target", previously settable by
    an MSBuild property `$(_AndroidCodeGenerationTarget)`
    (introduced in dbb0b92)

 2. C# `generator`s "codegen target" or `$(AndroidCodegenTarget)`

The problem was `$(_AndroidCodeGenerationTarget)` was just poorly
named making me think it was the same as `$(AndroidCodegenTarget)`.

Partially revert d70db5b and use the name `$(_AndroidJcwCodegenTarget)`
instead.

NativeAOT now defaults to:

  * `$(_AndroidJcwCodegenTarget)=JavaInterop1`
  * `$(AndroidCodegenTarget)=XAJavaInterop1`
jonpryor pushed a commit that referenced this pull request Mar 3, 2025
Context: #9846

`Mono.Android` has various test failures under NativeAOT such as:

	I NUnit   : CastJavaLangObjectArrayToByteArrayThrows
	E NUnit   :      [FAIL]
	E NUnit   :  :   Expected: <System.InvalidCastException>
	E NUnit   :   But was:  <System.DllNotFoundException> (DllNotFound_Linux, xa-internal-api,
	E NUnit   : dlopen failed: library "xa-internal-api.so" not found
	E NUnit   : dlopen failed: library "libxa-internal-api.so" not found
	E NUnit   : dlopen failed: library "xa-internal-api" not found
	E NUnit   : dlopen failed: library "libxa-internal-api" not found
	E NUnit   : )
	E NUnit   :    at System.Runtime.InteropServices.NativeLibrary.LoadLibErrorTracker.Throw(String) + 0x4c
	E NUnit   :    at Internal.Runtime.CompilerHelpers.InteropHelpers.FixupModuleCell(InteropHelpers.ModuleFixupCell*) + 0x134
	E NUnit   :    at Internal.Runtime.CompilerHelpers.InteropHelpers.ResolvePInvokeSlow(InteropHelpers.MethodFixupCell*) + 0x40
	E NUnit   :    at Android.Runtime.RuntimeNativeMethods.monodroid_TypeManager_get_java_class_name(IntPtr klass) + 0x2c
	E NUnit   :    at Java.Interop.TypeManager.GetClassName(IntPtr) + 0x10
	E NUnit   :    at Android.Runtime.JNIEnv.AssertCompatibleArrayTypes(IntPtr, Type) + 0x58
	E NUnit   :    at Android.Runtime.JNIEnv.GetArray[T](IntPtr array_ptr) + 0x24
	E NUnit   :    at Java.LangTests.ObjectArrayMarshaling.<>c__DisplayClass0_0.<CastJavaLangObjectArrayToByteArrayThrows>b__0() + 0x18
	E NUnit   :    at NUnit.Framework.Assert.Throws(IResolveConstraint, TestDelegate, String, Object[]) + 0xc4
	E NUnit   :    at Java.LangTests.ObjectArrayMarshaling.CastJavaLangObjectArrayToByteArrayThrows() + 0x150
	E NUnit   :    at libMono.Android.NET-Tests!<BaseAddress>+0x152f704
	E NUnit   :    at System.Reflection.DynamicInvokeInfo.Invoke(Object, IntPtr, Object[], BinderBundle, Boolean) + 0x10c

I updated the remaining calls in `JNIEnv.cs` to use
`JniEnvironment.Types.GetJniTypeNameFromClass()` instead.
jonpryor pushed a commit that referenced this pull request Mar 3, 2025
Context: #9846

Mono.Android-Tests running on NativeAOT can have a failure such as:

	I NUnit   : Indexer
	E NUnit   :      [FAIL]
	E NUnit   :  : System.DllNotFoundException : DllNotFound_Linux, xa-internal-api,
	E NUnit   : dlopen failed: library "xa-internal-api.so" not found
	E NUnit   : dlopen failed: library "libxa-internal-api.so" not found
	E NUnit   : dlopen failed: library "xa-internal-api" not found
	E NUnit   : dlopen failed: library "libxa-internal-api" not found
	E NUnit   :    at System.Runtime.InteropServices.NativeLibrary.LoadLibErrorTracker.Throw(String) + 0x4c
	E NUnit   :    at Internal.Runtime.CompilerHelpers.InteropHelpers.FixupModuleCell(InteropHelpers.ModuleFixupCell*) + 0x134
	E NUnit   :    at Internal.Runtime.CompilerHelpers.InteropHelpers.ResolvePInvokeSlow(InteropHelpers.MethodFixupCell*) + 0x40
	E NUnit   :    at Android.Runtime.RuntimeNativeMethods.monodroid_TypeManager_get_java_class_name(IntPtr klass) + 0x2c
	E NUnit   :    at Java.Interop.TypeManager.GetClassName(IntPtr) + 0x10
	E NUnit   :    at Java.Interop.JavaConvert.GetTypeMapping(IntPtr) + 0x28
	E NUnit   :    at Java.Interop.JavaConvert.FromJniHandle(IntPtr handle, JniHandleOwnership transfer, Type targetType) + 0x84
	E NUnit   :    at Android.Runtime.JavaList.InternalGet(Int32, Type) + 0x90
	E NUnit   :    at Java.InteropTests.JavaListTest`1.Indexer() + 0xfc
	E NUnit   :    at libMono.Android.NET-Tests!<BaseAddress>+0x152f744
	E NUnit   :    at System.Reflection.DynamicInvokeInfo.Invoke(Object, IntPtr, Object[], BinderBundle, Boolean) + 0x10c

We can update `JavaConvert.GetTypeMapping()` to use
`JniEnvironment.Types.GetJniTypeNameFromClass()` the same way it is
[done in dotnet/java-interop][0].

With this change the test passes:

	I NUnit   : Indexer
	I NUnit   :      Passed

[0]: https://github.com/dotnet/java-interop/blob/719e615910923bbce10e74b05bcc6b9585d4e176/src/Java.Interop/Java.Interop/JniEnvironment.Types.cs#L214-L220
@jonathanpeppers jonathanpeppers force-pushed the dev/peppers/mono.android-tests-nativeaot branch from 52a9160 to 18bba78 Compare March 3, 2025 18:59
jonathanpeppers added a commit to dotnet/java-interop that referenced this pull request Mar 4, 2025
Context: dotnet/android#9846

When building `Mono.Android.NET-Tests.csproj` for NativeAOT, you end
up with many warnings (that are upgraded to errors):

    external/Java.Interop/tests/Java.Interop-Tests/Java.Interop/JniEnvironmentTests.cs(92,4): error IL2026: Using member 'System.Reflection.Assembly.GetType(String, Boolean)' which has 'RequiresUnreferencedCodeAttribute' can break functionality when trimming application code. Types might be removed by trimming. If the type name is a string literal, consider using Type.GetType instead.
    external/Java.Interop/tests/Java.Interop-Tests/Java.Interop/JniEnvironmentTests.cs(93,4): error IL2026: Using member 'System.Reflection.Assembly.GetType(String, Boolean)' which has 'RequiresUnreferencedCodeAttribute' can break functionality when trimming application code. Types might be removed by trimming. If the type name is a string literal, consider using Type.GetType instead.
    external/Java.Interop/tests/Java.Interop-Tests/Java.Interop/JavaObjectArrayTest.cs(15,11): error IL2091: 'T' generic argument does not satisfy 'DynamicallyAccessedMemberTypes.PublicConstructors', 'DynamicallyAccessedMemberTypes.NonPublicConstructors' in 'Java.Interop.JavaObjectArray<T>'. The generic parameter 'T' of 'Java.InteropTests.JavaObjectArrayContractTest<T>' does not have matching annotations. The source value must declare at least the same requirements as those declared on the target location it is assigned to.
    external/Java.Interop/tests/Java.Interop-Tests/Java.Interop/JavaObjectArrayTest.cs(21,48): error IL2091: 'T' generic argument does not satisfy 'DynamicallyAccessedMemberTypes.PublicConstructors', 'DynamicallyAccessedMemberTypes.NonPublicConstructors' in 'Java.Interop.JavaObjectArray<T>'. The generic parameter 'T' of 'Java.InteropTests.JavaObjectArrayContractTest<T>' does not have matching annotations. The source value must declare at least the same requirements as those declared on the target location it is assigned to.
    external/Java.Interop/tests/Java.Interop-Tests/Java.Interop/JavaObjectArrayTest.cs(22,48): error IL2091: 'T' generic argument does not satisfy 'DynamicallyAccessedMemberTypes.PublicConstructors', 'DynamicallyAccessedMemberTypes.NonPublicConstructors' in 'Java.Interop.JavaObjectArray<T>'. The generic parameter 'T' of 'Java.InteropTests.JavaObjectArrayContractTest<T>' does not have matching annotations. The source value must declare at least the same requirements as those declared on the target location it is assigned to.
    external/Java.Interop/tests/Java.Interop-Tests/Java.Interop/JavaObjectArrayTest.cs(23,44): error IL2091: 'T' generic argument does not satisfy 'DynamicallyAccessedMemberTypes.PublicConstructors', 'DynamicallyAccessedMemberTypes.NonPublicConstructors' in 'Java.Interop.JavaObjectArray<T>'. The generic parameter 'T' of 'Java.InteropTests.JavaObjectArrayContractTest<T>' does not have matching annotations. The source value must declare at least the same requirements as those declared on the target location it is assigned to.
    external/Java.Interop/tests/Java.Interop-Tests/Java.Interop/JavaExceptionTests.cs(105,34): error IL2026: Using member 'System.Reflection.Assembly.GetType(String, Boolean)' which has 'RequiresUnreferencedCodeAttribute' can break functionality when trimming application code. Types might be removed by trimming. If the type name is a string literal, consider using Type.GetType instead.
    external/Java.Interop/tests/Java.Interop-Tests/Java.Interop/JavaExceptionTests.cs(108,34): error IL2072: 'type' argument does not satisfy 'DynamicallyAccessedMemberTypes.PublicConstructors' in call to 'System.Activator.CreateInstance(Type, params Object[])'. The return value of method 'System.Reflection.Assembly.GetType(String, Boolean)' does not have matching annotations. The source value must declare at least the same requirements as those declared on the target location it is assigned to.
    external/Java.Interop/tests/Java.Interop-Tests/Java.Interop/JniEnvironmentTests.cs(99,41): error IL2077: 'target' argument does not satisfy 'DynamicallyAccessedMemberTypes.PublicMethods', 'DynamicallyAccessedMemberTypes.NonPublicMethods' in call to 'System.Delegate.CreateDelegate(Type, Type, String, Boolean, Boolean)'. The field 'Java.InteropTests.JniEnvironmentTests.NativeMethods_type' does not have matching annotations. The source value must declare at least the same requirements as those declared on the target location it is assigned to.
    external/Java.Interop/tests/Java.Interop-Tests/Java.Interop/JniEnvironmentTests.cs(111,35): error IL2077: 'target' argument does not satisfy 'DynamicallyAccessedMemberTypes.PublicMethods', 'DynamicallyAccessedMemberTypes.NonPublicMethods' in call to 'System.Delegate.CreateDelegate(Type, Type, String, Boolean, Boolean)'. The field 'Java.InteropTests.JniEnvironmentTests.NativeMethods_type' does not have matching annotations. The source value must declare at least the same requirements as those declared on the target location it is assigned to.
    external/Java.Interop/tests/Java.Interop-Tests/Java.Interop/JniValueMarshalerContractTests.cs(650,127): error IL2092: 'DynamicallyAccessedMemberTypes' in 'DynamicallyAccessedMembersAttribute' on the parameter 'targetType' of method 'Java.InteropTests.DemoValueTypeValueMarshaler.CreateGenericValue(ref JniObjectReference, JniObjectReferenceOptions, Type)' don't match overridden parameter 'targetType' of method 'Java.Interop.JniValueMarshaler<T>.CreateGenericValue(ref JniObjectReference, JniObjectReferenceOptions, Type)'. All overridden members must have the same 'DynamicallyAccessedMembersAttribute' usage.
    external/Java.Interop/tests/Java.Interop-Tests/Java.Interop/JniRuntimeJniValueManagerContract.cs(28,18): error IL2072: 'type' argument does not satisfy 'DynamicallyAccessedMemberTypes.PublicParameterlessConstructor' in call to 'System.Activator.CreateInstance(Type)'. The return value of method 'Java.InteropTests.JniRuntimeJniValueManagerContract.ValueManagerType.get' does not have matching annotations. The source value must declare at least the same requirements as those declared on the target location it is assigned to.
    external/Java.Interop/tests/Java.Interop-Tests/Java.Interop/JniValueMarshalerContractTests.cs(36,35): error IL2091: 'T' generic argument does not satisfy 'DynamicallyAccessedMemberTypes.PublicConstructors', 'DynamicallyAccessedMemberTypes.NonPublicConstructors' in 'Java.Interop.JniRuntime.JniValueManager.GetValueMarshaler<T>()'. The generic parameter 'T' of 'Java.InteropTests.JniValueMarshalerContractTests<T>' does not have matching annotations. The source value must declare at least the same requirements as those declared on the target location it is assigned to.
    external/Java.Interop/tests/Java.Interop-Tests/Java.Interop/JniValueMarshalerContractTests.cs(224,18): error IL2026: Using member 'Java.Interop.JniValueMarshaler.CreateReturnValueFromManagedExpression(JniValueMarshalerContext, ParameterExpression)' which has 'RequiresUnreferencedCodeAttribute' can break functionality when trimming application code. System.Linq.Expression usage may trim away required code.
    external/Java.Interop/tests/Java.Interop-Tests/Java.Interop/JniValueMarshalerContractTests.cs(224,18): error IL3050: Using member 'Java.Interop.JniValueMarshaler.CreateReturnValueFromManagedExpression(JniValueMarshalerContext, ParameterExpression)' which has 'RequiresDynamicCodeAttribute' can break functionality when AOT compiling. System.Linq.Expression usage may trim away required code.

We can address these here by importing:

    <Import Project="..\..\build-tools\trim-analyzers\trim-analyzers.props" />

And then solving the warnings (that are now errors) by adding missing
attributes.

This might also improve the chances of these tests passing under
NativeAOT, in general.
jonpryor pushed a commit to dotnet/java-interop that referenced this pull request Mar 5, 2025
Context: dotnet/android#9846

When building `Mono.Android.NET-Tests.csproj` for NativeAOT, you end
up with many warnings (that are upgraded to errors):

	external/Java.Interop/tests/Java.Interop-Tests/Java.Interop/JniEnvironmentTests.cs(92,4): error IL2026: Using member 'System.Reflection.Assembly.GetType(String, Boolean)' which has 'RequiresUnreferencedCodeAttribute' can break functionality when trimming application code. Types might be removed by trimming. If the type name is a string literal, consider using Type.GetType instead.
	external/Java.Interop/tests/Java.Interop-Tests/Java.Interop/JniEnvironmentTests.cs(93,4): error IL2026: Using member 'System.Reflection.Assembly.GetType(String, Boolean)' which has 'RequiresUnreferencedCodeAttribute' can break functionality when trimming application code. Types might be removed by trimming. If the type name is a string literal, consider using Type.GetType instead.
	external/Java.Interop/tests/Java.Interop-Tests/Java.Interop/JavaObjectArrayTest.cs(15,11): error IL2091: 'T' generic argument does not satisfy 'DynamicallyAccessedMemberTypes.PublicConstructors', 'DynamicallyAccessedMemberTypes.NonPublicConstructors' in 'Java.Interop.JavaObjectArray<T>'. The generic parameter 'T' of 'Java.InteropTests.JavaObjectArrayContractTest<T>' does not have matching annotations. The source value must declare at least the same requirements as those declared on the target location it is assigned to.
	external/Java.Interop/tests/Java.Interop-Tests/Java.Interop/JavaObjectArrayTest.cs(21,48): error IL2091: 'T' generic argument does not satisfy 'DynamicallyAccessedMemberTypes.PublicConstructors', 'DynamicallyAccessedMemberTypes.NonPublicConstructors' in 'Java.Interop.JavaObjectArray<T>'. The generic parameter 'T' of 'Java.InteropTests.JavaObjectArrayContractTest<T>' does not have matching annotations. The source value must declare at least the same requirements as those declared on the target location it is assigned to.
	external/Java.Interop/tests/Java.Interop-Tests/Java.Interop/JavaObjectArrayTest.cs(22,48): error IL2091: 'T' generic argument does not satisfy 'DynamicallyAccessedMemberTypes.PublicConstructors', 'DynamicallyAccessedMemberTypes.NonPublicConstructors' in 'Java.Interop.JavaObjectArray<T>'. The generic parameter 'T' of 'Java.InteropTests.JavaObjectArrayContractTest<T>' does not have matching annotations. The source value must declare at least the same requirements as those declared on the target location it is assigned to.
	external/Java.Interop/tests/Java.Interop-Tests/Java.Interop/JavaObjectArrayTest.cs(23,44): error IL2091: 'T' generic argument does not satisfy 'DynamicallyAccessedMemberTypes.PublicConstructors', 'DynamicallyAccessedMemberTypes.NonPublicConstructors' in 'Java.Interop.JavaObjectArray<T>'. The generic parameter 'T' of 'Java.InteropTests.JavaObjectArrayContractTest<T>' does not have matching annotations. The source value must declare at least the same requirements as those declared on the target location it is assigned to.
	external/Java.Interop/tests/Java.Interop-Tests/Java.Interop/JavaExceptionTests.cs(105,34): error IL2026: Using member 'System.Reflection.Assembly.GetType(String, Boolean)' which has 'RequiresUnreferencedCodeAttribute' can break functionality when trimming application code. Types might be removed by trimming. If the type name is a string literal, consider using Type.GetType instead.
	external/Java.Interop/tests/Java.Interop-Tests/Java.Interop/JavaExceptionTests.cs(108,34): error IL2072: 'type' argument does not satisfy 'DynamicallyAccessedMemberTypes.PublicConstructors' in call to 'System.Activator.CreateInstance(Type, params Object[])'. The return value of method 'System.Reflection.Assembly.GetType(String, Boolean)' does not have matching annotations. The source value must declare at least the same requirements as those declared on the target location it is assigned to.
	external/Java.Interop/tests/Java.Interop-Tests/Java.Interop/JniEnvironmentTests.cs(99,41): error IL2077: 'target' argument does not satisfy 'DynamicallyAccessedMemberTypes.PublicMethods', 'DynamicallyAccessedMemberTypes.NonPublicMethods' in call to 'System.Delegate.CreateDelegate(Type, Type, String, Boolean, Boolean)'. The field 'Java.InteropTests.JniEnvironmentTests.NativeMethods_type' does not have matching annotations. The source value must declare at least the same requirements as those declared on the target location it is assigned to.
	external/Java.Interop/tests/Java.Interop-Tests/Java.Interop/JniEnvironmentTests.cs(111,35): error IL2077: 'target' argument does not satisfy 'DynamicallyAccessedMemberTypes.PublicMethods', 'DynamicallyAccessedMemberTypes.NonPublicMethods' in call to 'System.Delegate.CreateDelegate(Type, Type, String, Boolean, Boolean)'. The field 'Java.InteropTests.JniEnvironmentTests.NativeMethods_type' does not have matching annotations. The source value must declare at least the same requirements as those declared on the target location it is assigned to.
	external/Java.Interop/tests/Java.Interop-Tests/Java.Interop/JniValueMarshalerContractTests.cs(650,127): error IL2092: 'DynamicallyAccessedMemberTypes' in 'DynamicallyAccessedMembersAttribute' on the parameter 'targetType' of method 'Java.InteropTests.DemoValueTypeValueMarshaler.CreateGenericValue(ref JniObjectReference, JniObjectReferenceOptions, Type)' don't match overridden parameter 'targetType' of method 'Java.Interop.JniValueMarshaler<T>.CreateGenericValue(ref JniObjectReference, JniObjectReferenceOptions, Type)'. All overridden members must have the same 'DynamicallyAccessedMembersAttribute' usage.
	external/Java.Interop/tests/Java.Interop-Tests/Java.Interop/JniRuntimeJniValueManagerContract.cs(28,18): error IL2072: 'type' argument does not satisfy 'DynamicallyAccessedMemberTypes.PublicParameterlessConstructor' in call to 'System.Activator.CreateInstance(Type)'. The return value of method 'Java.InteropTests.JniRuntimeJniValueManagerContract.ValueManagerType.get' does not have matching annotations. The source value must declare at least the same requirements as those declared on the target location it is assigned to.
	external/Java.Interop/tests/Java.Interop-Tests/Java.Interop/JniValueMarshalerContractTests.cs(36,35): error IL2091: 'T' generic argument does not satisfy 'DynamicallyAccessedMemberTypes.PublicConstructors', 'DynamicallyAccessedMemberTypes.NonPublicConstructors' in 'Java.Interop.JniRuntime.JniValueManager.GetValueMarshaler<T>()'. The generic parameter 'T' of 'Java.InteropTests.JniValueMarshalerContractTests<T>' does not have matching annotations. The source value must declare at least the same requirements as those declared on the target location it is assigned to.
	external/Java.Interop/tests/Java.Interop-Tests/Java.Interop/JniValueMarshalerContractTests.cs(224,18): error IL2026: Using member 'Java.Interop.JniValueMarshaler.CreateReturnValueFromManagedExpression(JniValueMarshalerContext, ParameterExpression)' which has 'RequiresUnreferencedCodeAttribute' can break functionality when trimming application code. System.Linq.Expression usage may trim away required code.
	external/Java.Interop/tests/Java.Interop-Tests/Java.Interop/JniValueMarshalerContractTests.cs(224,18): error IL3050: Using member 'Java.Interop.JniValueMarshaler.CreateReturnValueFromManagedExpression(JniValueMarshalerContext, ParameterExpression)' which has 'RequiresDynamicCodeAttribute' can break functionality when AOT compiling. System.Linq.Expression usage may trim away required code.

We can address these here by importing:

	<Import Project="..\..\build-tools\trim-analyzers\trim-analyzers.props" />

And then solving the warnings (that are now errors) by adding missing
attributes.

This might also improve the chances of these tests passing under
NativeAOT, in general.
jonpryor pushed a commit that referenced this pull request Mar 7, 2025
Context: #9846
Context: https://github.com/dotnet/runtime/blob/d09a42b9149e14a37c8ef8363cdb7e17bb922c37/src/libraries/System.Private.CoreLib/src/System/IO/Path.Unix.cs#L83

`System.IO.Path.GetTempPath()` doesn't work under NativeAOT as seen
by the test failure:

	Mono.Android.NET_Tests, Android.RuntimeTests.InputStreamInvokerTest.InputStreamTest / Release
	System.IO.DirectoryNotFoundException : IO_PathNotFound_Path, /tmp/
	   at Interop.ThrowExceptionForIoErrno(Interop.ErrorInfo, String, Boolean) + 0x11
	   at Interop.CheckIo(Int64, String, Boolean) + 0x5d
	   at System.IO.Path.GetTempFileName() + 0x14d
	   at Android.RuntimeTests.InputStreamInvokerTest.InputStreamTest() + 0x18
	   at libMono.Android.NET-Tests!<BaseAddress>+0x1483023
	   at System.Reflection.DynamicInvokeInfo.Invoke(Object, IntPtr, Object[], BinderBundle, Boolean) + 0xf3

On Unix-like systems, the BCL just reads `$TMPDIR` and falls back to
`/tmp/` if it doesn't exist.  `$TMPDIR` is *not* set by default in
Android applications.

To fix this, we can set `$TMPDIR` to `context.getCacheDir()` just as
we do in .NET for Android:

  * https://github.com/dotnet/android/blob/04cd6f40989a8fad30d9a9759aec02d540cc9478/src/java-runtime/java/mono/android/MonoPackageManager.java#L53-L54
  * https://github.com/dotnet/android/blob/04cd6f40989a8fad30d9a9759aec02d540cc9478/src/native/mono/monodroid/monodroid-glue.cc#L1444-L1445

I think we can simply read these values in Java at startup, and call
[`Os.setenv()`][0] to set them.  There does not seem to be a need to
pass these paths into managed code.

The `Android.RuntimeTests.InputStreamInvokerTest.InputStreamTest()`
test now passes with these changes.

I fixed `$HOME` as well, as it will be used by other APIs in the BCL.

[0]: https://developer.android.com/reference/android/system/Os#setenv(java.lang.String,%20java.lang.String,%20boolean)
@jonathanpeppers jonathanpeppers force-pushed the dev/peppers/mono.android-tests-nativeaot branch from 67044a4 to 43ec9de Compare March 7, 2025 22:35
jonpryor pushed a commit that referenced this pull request Mar 7, 2025
Context: #9846
Context: b6c22f3

Running `Mono.Android-Tests` under NativeAOT has the test failure:

	I NUnit   : SynchronizationContext_Is_ThreadingSynchronizationContextCurrent
	E NUnit   : 	[FAIL]
	E NUnit   :  :   Expected: True
	E NUnit   :   But was:  False
	E NUnit   :    at libMono.Android.NET-Tests!<BaseAddress>+0x1482f63
	E NUnit   :    at System.Reflection.DynamicInvokeInfo.Invoke(Object, IntPtr, Object[], BinderBundle, Boolean) + 0xf3

`SynchronizationContext_Is_ThreadingSynchronizationContextCurrent()`
failed because we never called `JNIEnvInit.SetSynchronizationContext()`.

Call `JNIEnvInit.SetSynchronizationContext()`, and…

	F libc    : Fatal signal 6 (SIGABRT), code -1 (SI_QUEUE) in tid 17119 (Thread-11), pid 17058 (droid.NET_Tests)
	I crash_dump64: obtaining output fd from tombstoned, type: kDebuggerdTombstoneProto
	I tombstoned: received crash request for pid 17119
	I crash_dump64: performing dump of process 17058 (target tid = 17119)
	F DEBUG   : *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***
	F DEBUG   : Build fingerprint: 'google/panther/panther:14/AP2A.240905.003/12231197:user/release-keys'
	F DEBUG   : Revision: 'MP1.0'
	F DEBUG   : ABI: 'arm64'
	F DEBUG   : Timestamp: 2025-03-07 15:48:39.677241696-0600
	F DEBUG   : Process uptime: 2s
	F DEBUG   : Cmdline: Mono.Android.NET_Tests
	F DEBUG   : pid: 17058, tid: 17119, name: Thread-11  >>> Mono.Android.NET_Tests <<<
	F DEBUG   : uid: 10582
	F DEBUG   : tagged_addr_ctrl: 0000000000000001 (PR_TAGGED_ADDR_ENABLE)
	F DEBUG   : signal 6 (SIGABRT), code -1 (SI_QUEUE), fault addr --------
	F DEBUG   :     x0  0000000000000000  x1  00000000000042df  x2  0000000000000006  x3  0000007c6b4838f0
	F DEBUG   :     x4  0000000000000000  x5  0000000000000000  x6  0000000000000000  x7  0000007f36a58004
	F DEBUG   :     x8  00000000000000f0  x9  0000007f18a6d350  x10 0000000000000001  x11 0000007f18abe170
	F DEBUG   :     x12 0000000000000004  x13 51c34e921a529271  x14 0000000000000001  x15 0000000000000001
	F DEBUG   :     x16 0000007f18b24fd0  x17 0000007f18b10560  x18 0000007c694dc000  x19 00000000000042a2
	F DEBUG   :     x20 00000000000042df  x21 00000000ffffffff  x22 0000001a580093f8  x23 0000007c6b483e18
	F DEBUG   :     x24 0000000000000010  x25 0000000000000014  x26 0000001a5bc27ab8  x27 0000001a5bc27b40
	F DEBUG   :     x28 0000001a56005b38  x29 0000007c6b483970
	F DEBUG   :     lr  0000007f18aa78b8  sp  0000007c6b4838d0  pc  0000007f18aa78e4  pst 0000000000001000
	F DEBUG   : 2 total frames
	F DEBUG   : backtrace:
	F DEBUG   :       #00 pc 000000000005d8e4  /apex/com.android.runtime/lib64/bionic/libc.so (abort+164) (BuildId: 1d36f8ae6e0af6158793abea7d4f4f2b)
	F DEBUG   :       #1 pc 0000000000034828  /data/app/~~rqTsxkU5NjJYcDmnf-0haw==/Mono.Android.NET_Tests-fIi1xEY1rqvY2p4EDO81Ww==/split_config.arm64_v8a.apk (offset 0xa6c000)

After lots of digging around, we discovered that the problem was that
the `Android.App.Application` static constructor was running
*too early*, which caused an `Android.Runtime.XAPeerMembers` instance
to be constructed *before the runtime had finished initialization*.

Which leads us to a digression: when is static constructor run?
The answer to this depends upon the [`beforefieldinit` flag][0]:

  * When `beforefieldinit` is set, the runtime has lots of
    flexibility over when the static constructor is executed.
    The static constructor could be executed far earlier than one may
    normally expect.

  * When `beforefieldinit` *is not* set, the static constructor
    is executed "immediately" before the type is used.

In C#, if a type does not contain a static constructor, then the
type has `beforefieldinit` set:

	// has beforefieldinit
	partial class Application {
	  static readonly JniPeerMembers _members = new XAPeerMembers ("android/app/Application", typeof (Application));
	}

If a type has a static constructor, then it does not have
`beforefieldinit` set:

	// does not have beforefieldinit
	partial class Application {
	  static readonly JniPeerMembers _members = new XAPeerMembers ("android/app/Application", typeof (Application));

	  static Application()
	  {
	  }
	}

We hit this same scenario in b6c22f3 when using Mono's LLVM toolchain,
and fixed that by using `[MethodImpl(MethodImplOptions.NoInlining)]` on
`SetSynchronizationContext()`, in the hope that doing so would delay
execution of the `Application` static constructor until the invocation
of `SetSynchronizationContext()`.  This worked for b6c22f3, but not
with NativeAOT.

To fix this:

  * Add an empty static constructor to `Android.App.Application` to
    remove the `beforefieldinit` flag from that type.

  * Call `JNIEnvInit.SetSynchronizationContext()` at startup for
    NativeAOT.

With this change in place, no crashes occur at startup and the test
passes.

[0]: https://csharpindepth.com/Articles/BeforeFieldInit
@jonathanpeppers jonathanpeppers force-pushed the dev/peppers/mono.android-tests-nativeaot branch 2 times, most recently from 840cfe0 to f0cb5d1 Compare March 12, 2025 13:52
jonpryor pushed a commit that referenced this pull request Mar 19, 2025
Context: #9846
Context: efbec22
Context: #2266
Context: 684ede6
Context: xamarin/monodroid@eb04c91
Context: dotnet/java-interop@397013e

`Java.Interop.JniRuntime.JniTypeManager` supports bi-directional
mapping between JNI type signatures and managed `Type`s:

  * `GetTypeSignature(Type)` returns the JNI type signature that
    corresponds to the `System.Type`.
  * `GetType(JniTypeSignature)` returns the `Type` that corresponds
    to a JNI type signature.

One can imagine 1:1 *identity relation* between Java and managed
types, in which `GetType(GetTypeSignature(t))==t`:

	static void Identity<T> ()
	{
	  JniRuntime.JniTypeManager tm  = Java.Interop.JniEnvironment.Runtime.TypeManager;
	  JniTypeSignature  sigFromT    = tm.GetTypeSignature (typeof (T));
	  Type?             typefromSig = tm.GetType (sigFromT);
	  if (typeof (T) != typefromSig)
	    throw new Exception ($"Type({typeof (T)}) != .GetType({sigFromT}){{{(typefromSig == null ? "<null>" : typefromSig.ToString ())}}}");
	  JniTypeSignature  sigIdentity = tm.GetTypeSignature (typefromSig!);
	  if (sigFromT != sigIdentity)
	    throw new Exception ($"{sigFromT}) != {sigIdentity}");
	}

This is *not* always true in .NET for Android.

There *is* a required 1:1 relation between Java and managed types for
"normal" user-written `Java.Lang.Object` and `Java.Lang.Throwable`
subclasses, such as:

	partial class MainActivity : Activity {
	}

There *may not* be a 1:1 relation between Java and managed types for:

  * Bindings/projections of Java types; that is, types which have
    `[Register(…, DoNotGenerateAcw=true)]` or
    `[JniTypeSignature(…, GenerateJavaPeer=false)]`.

  * *Arrays* of types.  The same `JniTypeSignature` is generated for
    for `T[]`, `JavaArray<T>`, and other `Java*Array` types.

For example, `Mono.Android.dll` contains *three* "binding aliases"
for `java.util.ArrayList`:

  * `Android.Runtime.JavaList`
  * `Android.Runtime.JavaList<T>`
  * `Java.Util.ArrayList`

Only `Identity<Android.Runtime.JavaList>()` passes on .NET 9.

There are *two* binding aliases for `java.lang.Object`:
`Java.Interop.JavaObject, Java.Interop` and
`Java.Lang.Object, Mono.Android`.  (Plus more in unit tests!)
Only `Identity<Java.Lang.Object>()` passes on .NET 9, and that's
because of special-casing (25d1f00, 7acf328).

Which brings us to 684ede6 and #9846: there are two
additional issues with the improved NativeAOT-compatible typemap:

 1. It ignores assembly names when generating typemaps, and
 2. It doesn't properly deal with binding aliases.

## Assembly Identity is important!

It is not unusual for developers to copy and paste code
"from elsewhere" into their project.  It is likewise not unusual for
developers to *not* rename such copied code, meaning it is quite
possible for the "same" type to be present multiple times in an app:

	// Lib1.dll
	namespace Utilities {
	    class GenericHolder<T> : Java.Lang.Object {
	        public T Value {get; set;}
	    }
	}

	// Lib2.dll
	namespace Utilities {
	    class GenericHolder<T> : Java.Lang.Object {
	        public T Value {get; set;}
	    }
	}

From a C# and .NET perspective, this is fine:
`Utilities.GenericHolder<T>` has `internal` visibility; there is no
conflict here.

…except in pre-2014 Xamarin.Android, in which the package name of the
Java Callable Wrapper (JCW) name was based on the namespace of the
managed type.  *Both* of the above types would have the *same* JCW
name: `utilities.GenericHolder`.  This would promptly error out:

	error : Duplicate managed type found! Mappings between managed types and Java types must be unique.
	First Type: 'Android.Support.V4.App.FragmentManager/IOnBackStackChangedListenerImplementor, Xamarin.Android.Support.v4-r18, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null';
	Second Type: 'Android.Support.V4.App.FragmentManager/IOnBackStackChangedListenerImplementor, Mono.Android.Support.v4'

This scenario was improved in xamarin/monodroid@eb04c91c, which used
an *md5sum* of the namespace and assembly name, ensuring that the two
different `GenericHolder<T>` types would get different Java package
names, as the assembly name was in play.  (This was later changed to
use a CRC64 instead md5sum in dotnet/java-interop@397013ed.)

A problem in 684ede6 is that it would hash the managed type name for
a lookup, but the hash ignored the assembly name.  Consequently when
it countered two different `Java.InteropTests.GenericHolder<T>` types
in two separate assemblies, the assembly name was ignored, resulting
in a duplicate hash.  This would result in build failures:

	Fatal error in IL Linker
	Unhandled exception. System.InvalidOperationException: Duplicate hashes
	   at Microsoft.Android.Sdk.ILLink.TypeMappingStep.<>c__DisplayClass9_0.<EndProcess>g__GenerateHashes|10(UInt64[] hashes, String methodName)
	   at Microsoft.Android.Sdk.ILLink.TypeMappingStep.EndProcess()
	   at Mono.Linker.Steps.BaseStep.Process(LinkContext context)
	   at Mono.Linker.Pipeline.ProcessStep(LinkContext context, IStep step)
	   at Mono.Linker.Pipeline.Process(LinkContext context)
	   at Mono.Linker.Driver.Run(ILogger customLogger)
	   at Mono.Linker.Driver.Main(String[] args)

Fix this by hashing `Type.AssemblyQualifiedName` instead of
`Type.FullName`.

## Binding Aliases

#9846 had a unit test failure in
`JavaObjectExtensionsTests.JavaCast_BaseToGenericWrapper()`:

	System.ArgumentException : Could not determine Java type corresponding to ``Android.Runtime.JavaList`1[[System.Int32, System.Private.CoreLib, Version=10.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]], Mono.Android``. Arg_ParamName_Name, targetType
	   at Java.Interop.JniRuntime.JniValueManager.CreatePeer(JniObjectReference&, JniObjectReferenceOptions, Type) + 0x248
	   at Java.Interop.JniRuntime.JniValueManager.GetPeer(JniObjectReference, Type) + 0x77
	   at Java.Lang.Object.GetObject(IntPtr, JniHandleOwnership, Type) + 0x31
	   at Java.Interop.JavaObjectExtensions._JavaCast[TResult](IJavaObject) + 0x66
	   at Java.InteropTests.JavaObjectExtensionsTests.JavaCast_BaseToGenericWrapper() + 0x62
	   at libMono.Android.NET-Tests!<BaseAddress>+0x1489b83
	   at System.Reflection.DynamicInvokeInfo.Invoke(Object, IntPtr, Object[], BinderBundle, Boolean) + 0xf3

This is due to "binding aliases": there was no type mapping between
`Android.Runtime.JavaList<T>` and `java/util/arrayList`, because the
typemaps were assuming a 1:1 mapping, which isn't the case here.

Update `TypeMappingStep` so that binding aliases are supported.

Given (from `TypeMappingStep.cs`):

	partial class TypeMappingStep {
	  IDictionary<string, List<TypeDefinition>> TypeMappings = new(StringComparer.Ordinal);
	}

Then at the end of trimming, `TypeMappingStep.TypeMappings` will
contain e.g.

	TypeMappingStep.TypeMappings = {
	  ["java/util/ArrayList"]   => new List<TypeDefinition> {
	    typeof (Android.Runtime.JavaList),
	    typeof (Android.Runtime.JavaList<>),
	    typeof (Java.Util.ArrayList),
	  },
	  ["java/lang/Object"]      => new List<TypeDefinition> {
	    typeof (Java.Lang.Object),
	    typeof (Java.Interop.JavaObject),
	  },
	  ["java/lang/Runnable"]    => new List<TypeDefinition> {
	    typeof (Java.Lang.IRunnable),
	    typeof (Java.Lang.IRunnableInvoker),
	  },
	  // …
	};

From `TypeMappingStep.TypeMappings` we produce two typemap "tables".

Java/JNI class name to managed type resembles:

	partial class TypeMapping {

	  static Type? GetTypeByJniNameHashIndex (int index) => index switch {
	    0  => Type.GetTypeFromHandle (typeof (Java.Lang.Byte).RuntimeTypeHandle),           // `java/lang/Byte`         hash=0x01cd624f1e38cc9f
	    32 => Type.GetTypeFromHandle (typeof (Android.Runtime.JavaList).RuntimeTypeHandle),	// `java/util/ArrayList`    hash=0x7b925bdca68a0101
	    56 => Type.GetTypeFromHandle (typeof (Java.Lang.Object).RuntimeTypeHandle),         // `java/lang/Object`       hash=0xbf6d427143271cb3 
	    77 => Type.GetTypeFromHandle (typeof (Java.Lang.IRunnable).RuntimeTypeHandle),      // `java/lang/Runnable`     hash=0xfd2b1a3de667eb51
	    _  => null,
	  };

	  static string? GetJniNameByJniNameHashIndex (int index) => index switch {
	    0  => "java/lang/Byte",         // `Java.Lang.Byte, Mono.Android`           hash=0x01cd624f1e38cc9f
	    32 => "java/util/ArrayList",    // `Android.Runtime.JavaList, Mono.Android` hash=0x7b925bdca68a0101
	    56 => "java/lang/Object",       // `Java.Lang.Object, Mono.Android`         hash=0xbf6d427143271cb3
	    77 => "java/lang/Runnable",     // `Java.Lang.IRunnable, Mono.Android`      hash=0xfd2b1a3de667eb51
	    _  => null,
	  };

	  private static ReadOnlySpan<ulong>  JniNameHashes => new ReadOnlySpan<ulong>(ref s_get_JniNameHashes_data, 78);

	  [StructLayout(LayoutKind.Explicit, Pack=1, Size=624)]
	  private struct HashesArray_624 {
	  }
	  private static HashesArray_624      s_get_JniNameHashes_data = new ulong[78]{ // RVA data; insert hand-waving here
	    0x1cd624f1e38cc9f,   //    0: java/lang/Byte
	    // …
	    0x7b925bdca68a0101,  //   32: java/util/ArrayList
	    // …
	    0xbf6d427143271cb3,  //   56: java/lang/Object
	    // …
	    0xfd2b1a3de667eb51,  //   77: java/lang/Runnable
	    // …
	  };
	}

Note that `TypeMapping.GetTypeByJniNameHashIndex()` and
`TypeMapping.GetJniNameByJniNameHashIndex()` provides values for all
indexes between 0 and the number of hashes within
`s_get_JniNameHashes_data`.  Not all entries are listed for
exposition purposes.

Managed type to JNI resembles:

	partial class TypeMapping {

	  static string? GetJniNameByTypeNameHashIndex (int index) => index switch {
	    0   => "java/lang/IndexOutOfBoundsException", // `Java.Lang.IndexOutOfBoundsException, Mono.Android`    hash=0x0242f4a673f183d1
	    2   => "java/util/ArrayList",                 // `Java.Util.ArrayList, Mono.Android`                    hash=0x07c2b62d20a668dd
	    4   => "java/util/ArrayList",                 // `Android.Runtime.JavaList`1, Mono.Android`             hash=0x132055d1acecc87d
	    30  => "java/lang/Runnable",                  // `Java.Lang.IRunnableInvoker, Mono.Android`             hash=0x386176afae6775ce
	    32  => "mono/java/lang/Runnable",             // `Java.Lang.Runnable, Mono.Android`                     hash=0x408566f4617e204f
	    36  => "java/util/ArrayList",                 // `Android.Runtime.JavaList, Mono.Android`               hash=0x48a63a89cfee545f
	    44  => "java/lang/Object",                    // `Java.Lang.Object, Mono.Android`                       hash=0x5b4a99c45538d0fb
	    51  => "java/lang/Object",                    // `Java.Interop.JavaObject, Java.Interop`                hash=0x88a12107f88ba9a7
	    53  => "java/lang/Byte",                      // `Java.Lang.Byte, Mono.Android`                         hash=0x8ab15b52718902fb
	    96  => "java/lang/Runnable",                  // `Java.Lang.IRunnable, Mono.Android`                    hash=0xef2efa58a51bb883 
	    _   => null,
	  };

	  static string? GetTypeNameByTypeNameHashIndex (int index) => index switch {
	    0   => "Java.Lang.IndexOutOfBoundsException, Mono.Android",   // `java/lang/IndexOutOfBoundsException`  hash=0x0242f4a673f183d1
	    2   => "Java.Util.ArrayList, Mono.Android",                   // `java/util/ArrayList`                  hash=0x07c2b62d20a668dd
	    4   => "Android.Runtime.JavaList`1, Mono.Android",            // `java/util/ArrayList`                  hash=0x132055d1acecc87d
	    30  => "Java.Lang.IRunnableInvoker, Mono.Android",            // `java/lang/Runnable`                   hash=0x386176afae6775ce
	    32  => "Java.Lang.Runnable, Mono.Android",                    // `mono/java/lang/Runnable`              hash=0x408566f4617e204f
	    36  => "Android.Runtime.JavaList, Mono.Android",              // `java/util/ArrayList`                  hash=0x48a63a89cfee545f
	    44  => "Java.Lang.Object, Mono.Android",                      // `java/lang/Object`                     hash=0x5b4a99c45538d0fb
	    51  => "Java.Interop.JavaObject, Java.Interop",               // `java/lang/Object`                     hash=0x88a12107f88ba9a7
	    53  => "Java.Lang.Byte, Mono.Android",                        // `java/lang/Byte`                       hash=0x8ab15b52718902fb
	    96  => "Java.Lang.IRunnable, Mono.Android",                   // `java/lang/Runnable`                   hash=0xef2efa58a51bb883
	    _   => null,
	  };

	  private static ReadOnlySpan<ulong>  TypeNameHashes => new ReadOnlySpan<ulong>(ref s_get_TypeNameHashes_data, 99);

	  [StructLayout(LayoutKind.Explicit, Pack=1, Size=792)]
	  private struct HashesArray_792 {
	  }
	  private static HashesArray_792      s_get_TypeNameHashes_data = new ulong[99] { // RVA data; insert hand-waving here
	    0x242f4a673f183d1,   //    0: Java.Lang.IndexOutOfBoundsException, Mono.Android
	    // …
	    0x7c2b62d20a668dd,   //    2: Java.Util.ArrayList, Mono.Android
	    // …
	    0x132055d1acecc87d,  //    4: Android.Runtime.JavaList`1, Mono.Android
	    // …
	    0x386176afae6775ce,  //   30: Java.Lang.IRunnableInvoker, Mono.Android
	    // …
	    0x408566f4617e204f,  //   32: Java.Lang.Runnable, Mono.Android
	    // …
	    0x48a63a89cfee545f,  //   36: Android.Runtime.JavaList, Mono.Android
	    // …
	    0x5b4a99c45538d0fb,  //   44: Java.Lang.Object, Mono.Android
	    // …
	    0x88a12107f88ba9a7,  //   51: Java.Interop.JavaObject, Java.Interop
	    // …
	    0x8ab15b52718902fb,  //   53: Java.Lang.Byte, Mono.Android
	    // …
	    0xef2efa58a51bb883,  //   96: Java.Lang.IRunnable, Mono.Android
	    // …
	  };
	}

Note that `TypeMapping.GetJniNameByTypeNameHashIndex()` and
`TypeMapping.GetTypeNameByTypeNameHashIndex()` provides values for all
indexes between 0 and the number of hashes within
`s_get_TypeNameHashes_data`.  Not all entries are listed for
exposition purposes.
@jonathanpeppers jonathanpeppers force-pushed the dev/peppers/mono.android-tests-nativeaot branch from f0cb5d1 to 7564132 Compare March 24, 2025 15:51
* Add Categories Export, GCBridge

* Add Mono category

* Setup `TestApkFeeds.props`

/Users/runner/work/1/s/tests/Mono.Android-Tests/Mono.Android-Tests/Mono.Android.NET-Tests.csproj : error NU1102: Unable to find package Microsoft.Android.Runtime.NativeAOT.35.android-arm64 with version (= 35.99.0-ci.dev-peppers-mono-android-tests-nativeaot.229)

[nativeaot] fix default `SynchronizationContext`

Running `Mono.Android-Tests` under NativeAOT has the test failure:

    03-04 23:06:20.021  6191  6211 I NUnit   : SynchronizationContext_Is_ThreadingSynchronizationContextCurrent
    03-04 23:06:20.032  6191  6211 E NUnit   : 	[FAIL]
    03-04 23:06:20.032  6191  6211 E NUnit   :  :   Expected: True
    03-04 23:06:20.032  6191  6211 E NUnit   :   But was:  False
    03-04 23:06:20.032  6191  6211 E NUnit   :    at libMono.Android.NET-Tests!<BaseAddress>+0x1482f63
    03-04 23:06:20.032  6191  6211 E NUnit   :    at System.Reflection.DynamicInvokeInfo.Invoke(Object, IntPtr, Object[], BinderBundle, Boolean) + 0xf3

Initially, if we called `JNIEnvInit.SetSynchronizationContext()` at
startup, this can result in the static ctor for
`Android.App.Application` running *too soon* before
`JNIEnvInit.InitializeJniRuntime()` has completed.

To fix this:

* Add an empty `static ctor` to `Android.App.Application` to remove
  the `beforefieldinit` flag from the type.

* Call `JNIEnvInit.SetSynchronizationContext()` at startup for NativeAOT.

With this change in place, no crashes occur at startup and the test
passes.

* Fix `EmbeddedResources_ShouldBeLocalized` test
@jonathanpeppers jonathanpeppers force-pushed the dev/peppers/mono.android-tests-nativeaot branch from 7564132 to e4ca346 Compare March 26, 2025 15:25
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant