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 6 commits 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
10 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
* 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 43ec9de to 45a5f87 Compare March 10, 2025 13:42
jonathanpeppers and others added 5 commits March 10, 2025 11:25
The current NUnit implementation can result in failures under
NativeAOT:

    Mono.Android.NET_Tests, Xamarin.Android.NetTests.AndroidMessageHandlerNegotiateAuthenticationTests.RequestWithCredentialsSucceeds / Release
    System.NullReferenceException : Arg_NullReferenceException
       at NUnit.Framework.Internal.AsyncInvocationRegion.AsyncTaskInvocationRegion.WaitForPendingOperationsToComplete(Object) + 0x60
       at NUnit.Framework.Internal.Commands.TestMethodCommand.RunAsyncTestMethod(TestExecutionContext) + 0x45

The original code in NUnitLite uses System.Reflection, because it
needed to run in very limited contexts like Silverlight, portable
class libraries, etc.

To solve this, let's just stop using System.Reflection, and just do:

    if (invocationResult is Task task)
    {
        task.Wait();
    }

Or in another case:

    if (exception is AggregateException ae)
        return ae.InnerExceptions;

NUnitLite also called the `Result` property on any `Task<T>`. I simply
removed this functionality, as we have no tests using this feature.
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.

2 participants