From 20cbff0e5fecfce2bea2c5bc970756fe83201c54 Mon Sep 17 00:00:00 2001 From: Simon Rozsival Date: Thu, 19 Nov 2026 14:08:25 +0100 Subject: [PATCH 1/8] [tests] Add TrimmingTests: on-device trimming and NativeAOT tests MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Context: https://github.com/dotnet/android/issues/13618 Trimming bugs show up only at runtime in a trimmed app, and the existing device tests run inside one large test app, where any test can keep a type alive for another. TrimmingTests builds a purpose-built app for each scenario, launches it on a device, and checks both its result and what trimming kept. ### Cases Each case is a single-file app (`dotnet build Case.cs`) in `tests/TrimmingTests/Cases/` with `#:property`/`#:package` directives; a case that needs Android resources, an `AndroidManifest.xml` or MSBuild items lives in `Cases//` next to them (`Case.targets`). It logs `TRIMMING_TEST_RESULT: PASS` or `FAIL …` on startup. Cases are shielded from the repository's `Directory.Build.*` files and never root anything unless that is what they test. A test calls `BuildAndRun ("Cases/.cs", configuration)` and then `AssertTrimmingExpectations (app)`: * Every configuration builds `SignAndroidPackage` in Release: CoreCLR with `$(TrimMode)`=full, NativeAOT, and CoreCLR with `$(TrimMode)`=partial, the CoreCLR Release default. `[TrimmingConfigurations]` runs a test in all three or in the ones it lists. * The build must have no warnings except the codes the test passes as `expectedWarnings`, with `$(TrimmerSingleWarn)`=false. * The app is installed and launched with `adb`; its result is matched by process ID in a logcat stream started before the launch, so tests in a fixture run in parallel on one device without clearing logcat. * Expectation attributes modelled on dotnet/runtime's `Mono.Linker.Tests.Cases.Expectations` (`[Kept]`, `[Removed]`, `[KeptMember]`, `[Kept|Removed][Type|Member]InAssembly`, `By = Tool.…`) are checked against ILLink's `linked/` assemblies or ILC's mstat file. They take only strings, so they keep nothing themselves. NativeAOT cases build with `JitNoInline=1` because the mstat omits inlined methods, and can check generic instantiations. In partial mode, assemblies ILLink doesn't trim must instead be kept whole. `DotNetCLI` skips arguments that file-based apps reject (`/noconsolelogger`, `/flp1`, `-m`, `-nodeReuse`). The first cases cover generic peer array activation (the bug fixed two commits ago), unused bindings being removed, a C# listener called from Java, Java exception and interface invoker activation, and boxed values. `UnusedBoxingBindings` is ignored for #13635: every app keeps `JavaConvert` and all the `Java.Lang` boxing bindings. ### CI The MSBuild emulator stage gets a `Trimming+Emulator` job in the public pipeline and in `stage-msbuild-emulator-tests.yaml`, running the suite with two workers on one emulator. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- .github/skills/tests/SKILL.md | 3 +- .../skills/tests/references/test-catalog.md | 40 ++ Microsoft.Android.Build.Tasks.slnx | 1 + Microsoft.Android.slnx | 1 + .../automation/azure-pipelines-public.yaml | 52 ++ .../stage-msbuild-emulator-tests.yaml | 61 ++ .../Xamarin.ProjectTools/Common/DotNetCLI.cs | 18 +- tests/TrimmingTests/AssemblyInfo.cs | 4 + .../TrimmingTests/Cases/Directory.Build.props | 2 + .../Cases/Directory.Build.targets | 12 + .../Cases/GenericPeerArrayElement.cs | 70 ++ tests/TrimmingTests/Cases/JavaExceptions.cs | 39 ++ .../Cases/JavaInterfaceInvokers.cs | 54 ++ .../Cases/JavaObjectActivation.cs | 43 ++ .../Expectations.cs | 125 ++++ .../TrimmingTests.Expectations.csproj | 9 + tests/TrimmingTests/Cases/UnusedBindings.cs | 58 ++ .../Cases/UnusedBoxingBindings.cs | 32 + tests/TrimmingTests/Cases/UsedBindings.cs | 63 ++ .../Tests/BindingTrimmingTests.cs | 59 ++ .../Tests/JavaPeerActivationTests.cs | 19 + tests/TrimmingTests/TrimmingExpectations.cs | 628 ++++++++++++++++++ tests/TrimmingTests/TrimmingTestBase.cs | 270 ++++++++ tests/TrimmingTests/TrimmingTests.csproj | 42 ++ 24 files changed, 1698 insertions(+), 7 deletions(-) create mode 100644 tests/TrimmingTests/AssemblyInfo.cs create mode 100644 tests/TrimmingTests/Cases/Directory.Build.props create mode 100644 tests/TrimmingTests/Cases/Directory.Build.targets create mode 100644 tests/TrimmingTests/Cases/GenericPeerArrayElement.cs create mode 100644 tests/TrimmingTests/Cases/JavaExceptions.cs create mode 100644 tests/TrimmingTests/Cases/JavaInterfaceInvokers.cs create mode 100644 tests/TrimmingTests/Cases/JavaObjectActivation.cs create mode 100644 tests/TrimmingTests/Cases/TrimmingTests.Expectations/Expectations.cs create mode 100644 tests/TrimmingTests/Cases/TrimmingTests.Expectations/TrimmingTests.Expectations.csproj create mode 100644 tests/TrimmingTests/Cases/UnusedBindings.cs create mode 100644 tests/TrimmingTests/Cases/UnusedBoxingBindings.cs create mode 100644 tests/TrimmingTests/Cases/UsedBindings.cs create mode 100644 tests/TrimmingTests/Tests/BindingTrimmingTests.cs create mode 100644 tests/TrimmingTests/Tests/JavaPeerActivationTests.cs create mode 100644 tests/TrimmingTests/TrimmingExpectations.cs create mode 100644 tests/TrimmingTests/TrimmingTestBase.cs create mode 100644 tests/TrimmingTests/TrimmingTests.csproj diff --git a/.github/skills/tests/SKILL.md b/.github/skills/tests/SKILL.md index 5af56c6cd52..61dc5b2d290 100644 --- a/.github/skills/tests/SKILL.md +++ b/.github/skills/tests/SKILL.md @@ -47,7 +47,7 @@ Classify the user's request: | `src/Microsoft.Android.Build.Tasks/Tasks/` | Standalone: `Microsoft.Android.Build.Tasks.Tests.csproj` | | `src/Xamarin.Android.Build.Tasks/Utilities/` | Host: `Xamarin.Android.Build.Tests.dll` — grep for test classes referencing the utility | | `src/Xamarin.Android.Build.Tasks/**/*.targets` | Host: `Xamarin.Android.Build.Tests.dll`. Device: `MSBuildDeviceIntegration.dll` | -| `src/Microsoft.Android.Sdk.TrimmableTypeMap/` | On-device: `Mono.Android.NET-Tests.csproj`. Host: `GenerateTrimmableTypeMapTests`, `TrimmableTypeMapIncrementalTests`, `TrimmableTypeMapManifestAliasTests`, `TrimmableTypeMapRidCallbackTests`, `ExtractTypeMapKeysFromNativeAotObjectTests`, `TrimmableTypeMapBuildTests` | +| `src/Microsoft.Android.Sdk.TrimmableTypeMap/` | On-device: `Mono.Android.NET-Tests.csproj`, `TrimmingTests.dll`. Host: `GenerateTrimmableTypeMapTests`, `TrimmableTypeMapIncrementalTests`, `TrimmableTypeMapManifestAliasTests`, `TrimmableTypeMapRidCallbackTests`, `ExtractTypeMapKeysFromNativeAotObjectTests`, `TrimmableTypeMapBuildTests` | | `src/Java.Interop/` | On-device: core JNI tests in `tests/Mono.Android-Tests/Java.Interop-Tests/`, run with `Mono.Android.NET-Tests.csproj` | | `src/Java.Interop.Tools.*/`, `src/generator/`, `src/class-parse/` | Standalone tooling tests under `tests/` | | `src/native/` | On-device runtime tests in `Mono.Android.NET-Tests.csproj` | @@ -65,6 +65,7 @@ Escalate only when the change or focused results require it. | Standalone libraries (`Microsoft.Android.Build.BaseTasks`, `Xamarin.Android.Tools.AndroidSdk`, `Microsoft.Android.Build.Tasks`, Java.Interop tooling, `generator`, `class-parse`) | `dotnet build` + standalone tests | | `src/Xamarin.Android.Build.Tasks` | Focused `Xamarin.Android.Build.Tests.dll` filters on the local SDK; `MSBuildDeviceIntegration.dll` only if install/deploy/run changes | | `src/Mono.Android`, core `src/Java.Interop`, `src/native`, typemaps, hosting | `Mono.Android.NET-Tests` on device for each affected runtime | +| Code reached by reflection or other trimming/AOT-sensitive paths | Add or run a `TrimmingTests.dll` case (CoreCLR full trimming and NativeAOT) | | `Makefile`, `build-tools/`, `eng/`, CI YAML | Run the affected entry point or pipeline command locally | ## Running tests diff --git a/.github/skills/tests/references/test-catalog.md b/.github/skills/tests/references/test-catalog.md index 51ff318d15e..1f8be9cc89b 100644 --- a/.github/skills/tests/references/test-catalog.md +++ b/.github/skills/tests/references/test-catalog.md @@ -112,6 +112,46 @@ Same assembly as above. These test individual MSBuild tasks in isolation with `M --- +## Trimming and AOT Tests (full-build — requires local SDK + device) + +Assembly: `bin/TestDebug/TrimmingTests/${TFM}/TrimmingTests.dll` +Build: Full-build + device/emulator connected +Device: **Yes** (`[Category("UsesDevice")]`) + +Each case is a purpose-built single-file app in `tests/TrimmingTests/Cases/` (`#:property` and `#:package` directives, its own +`ApplicationId`, `#:project TrimmingTests.Expectations/TrimmingTests.Expectations.csproj`, and one `TRIMMING_TEST_RESULT: PASS`/`FAIL` +log line). A case that needs more files lives in `Cases//.cs` next to its `Resources/`, `AndroidManifest.xml`, or a +`Case.targets` with MSBuild items. Cases for reported bugs start with a comment linking the issue or PR; known failures are +`[Ignore]`d (or `Assert.Ignore`d for one configuration) with the link to the open issue. +A test takes `[TrimmingConfigurations] TrimmingConfiguration configuration`, which runs it with CoreCLR full trimming, NativeAOT, and +CoreCLR partial trimming (the CoreCLR Release default, which trims only trimmable assemblies and suppresses trimming warnings), or +only in the configurations it lists, and calls `var app = BuildAndRun ("Cases/.cs", configuration, expectedWarnings: [...])`, which copies the case into its own +directory shielded from the repository's `Directory.Build.*` files, builds it in that configuration, fails on any build +warning whose code is not in `expectedWarnings` (with `TrimmerSingleWarn=false`) or on an expected one that is missing, and then installs +and launches it and requires PASS. + +The test then calls `AssertTrimmingExpectations (app)`, which checks `[Kept]`, `[Removed]`, `[KeptMember]` and +`[Kept|Removed][Type|Member]InAssembly` (optionally `By = Tool.FullTrimming|Tool.PartialTrimming|Tool.NativeAot`, or `Tool.Trimmer` for both ILLink modes) against ILLink's `linked/` assemblies (CoreCLR) +or ILC's mstat file (NativeAOT). In partial mode, expectations on assemblies ILLink doesn't trim (the app's own, unless marked +`IsTrimmable`) are replaced by a check that the whole assembly was kept. On NativeAOT, `*TypeInAssembly` also checks generic instantiations such as +``JavaDictionary`2``. `Cases/Directory.Build.targets` disables JIT inlining for NativeAOT cases, because the mstat omits +inlined methods. + +Tests in a fixture run in parallel (`[Parallelizable (ParallelScope.Children)]`), also on the device: each configuration installs its +own package (`.coreclr`/`.nativeaot`) and results are matched by process ID in a logcat stream started before the launch, so never clear logcat in a test. Expectation attributes take strings only, never `typeof`, so they cannot keep anything themselves. Never root anything in a case +unless rooting is the behavior under test. + +| Test Area | Filter | Notes | +|-----------|--------|-------| +| **trimming** (all) | (no filter) | Every case on CoreCLR full trimming and NativeAOT | +| **Java peer activation** | `--filter "FullyQualifiedName~JavaPeerActivationTests"` | Reflection-based activation of closed generic Java peers | + +```bash +ADB_TARGET='-s emulator-5554' ./dotnet-local.sh test bin/TestDebug/TrimmingTests/${TFM}/TrimmingTests.dll +``` + +--- + ## Device Integration Tests (full-build — requires local SDK + device) Assembly: `bin/TestDebug/MSBuildDeviceIntegration/${TFM}/MSBuildDeviceIntegration.dll` diff --git a/Microsoft.Android.Build.Tasks.slnx b/Microsoft.Android.Build.Tasks.slnx index cadc08424e2..2de2f309012 100644 --- a/Microsoft.Android.Build.Tasks.slnx +++ b/Microsoft.Android.Build.Tasks.slnx @@ -5,6 +5,7 @@ + diff --git a/Microsoft.Android.slnx b/Microsoft.Android.slnx index e1a23adbce9..953988548a4 100644 --- a/Microsoft.Android.slnx +++ b/Microsoft.Android.slnx @@ -57,6 +57,7 @@ + diff --git a/build-tools/automation/azure-pipelines-public.yaml b/build-tools/automation/azure-pipelines-public.yaml index f91af6f8f2a..ce7235d2375 100644 --- a/build-tools/automation/azure-pipelines-public.yaml +++ b/build-tools/automation/azure-pipelines-public.yaml @@ -429,6 +429,58 @@ stages: parameters: condition: true + # Purpose-built apps that check what trimming keeps and removes; see tests/TrimmingTests. + - job: mac_trimming_tests + displayName: "macOS > Tests > Trimming+Emulator" + # NOTE: AcesShared pool cannot boot Android emulators, so these jobs must use hosted images + pool: + name: Azure Pipelines + vmImage: $(HostedMacImageWithEmulator) + os: macOS + timeoutInMinutes: 120 + cancelTimeoutInMinutes: 5 + workspace: + clean: all + steps: + - template: /build-tools/automation/yaml-templates/setup-test-environment-public.yaml + parameters: + jdkMajorVersion: $(DefaultJavaSdkMajorVersion) + useAgentJdkPath: true + installApkDiff: false + use1ESTemplate: false + + - task: DownloadPipelineArtifact@2 + inputs: + artifactName: $(TestAssembliesArtifactName) + downloadPath: $(System.DefaultWorkingDirectory)/bin/Test$(XA.Build.Configuration) + + - template: /build-tools/automation/yaml-templates/run-dotnet-preview.yaml + parameters: + project: Microsoft.Android.slnx + arguments: -t:PrepareOpenJDK -c $(XA.Build.Configuration) --no-restore + displayName: prepare OpenJDK $(XA.Build.Configuration) + continueOnError: false + + - template: /build-tools/automation/yaml-templates/start-stop-emulator.yaml + + # Two tests at a time share the emulator, matching [assembly: LevelOfParallelism (2)]. + - template: /build-tools/automation/yaml-templates/run-nunit-tests.yaml + parameters: + testAssembly: $(System.DefaultWorkingDirectory)/bin/Test$(XA.Build.Configuration)/TrimmingTests/$(DotNetStableTargetFramework)/TrimmingTests.dll + testRunTitle: TrimmingTests On Device - macOS + workers: 2 + timeoutInMinutes: 90 + + - template: /build-tools/automation/yaml-templates/upload-results.yaml + parameters: + artifactName: Test Results - Trimming With Emulator - macOS + xaSourcePath: $(System.DefaultWorkingDirectory) + use1ESTemplate: false + + - template: /build-tools/automation/yaml-templates/fail-on-issue.yaml + parameters: + condition: true + # Android Tools Tests Stage - template: /build-tools/automation/yaml-templates/stage-xamarin-android-tools-tests.yaml@self parameters: diff --git a/build-tools/automation/yaml-templates/stage-msbuild-emulator-tests.yaml b/build-tools/automation/yaml-templates/stage-msbuild-emulator-tests.yaml index 47dd7993601..9400c7717e7 100644 --- a/build-tools/automation/yaml-templates/stage-msbuild-emulator-tests.yaml +++ b/build-tools/automation/yaml-templates/stage-msbuild-emulator-tests.yaml @@ -82,3 +82,64 @@ stages: - template: /build-tools/automation/yaml-templates/fail-on-issue.yaml parameters: condition: ${{ parameters.shouldFailOnIssue }} + + # Purpose-built apps that check what trimming keeps and removes; see tests/TrimmingTests. + - job: ${{ parameters.job_name }}_trimming + displayName: "macOS > Tests > Trimming+Emulator" + pool: + name: Azure Pipelines + vmImage: $(HostedMacImageWithEmulator) + os: macOS + timeoutInMinutes: 120 + cancelTimeoutInMinutes: 5 + workspace: + clean: all + steps: + - template: /build-tools/automation/yaml-templates/setup-test-environment.yaml + parameters: + installApkDiff: false + xaSourcePath: ${{ parameters.xaSourcePath }} + repositoryAlias: ${{ parameters.repositoryAlias }} + commit: ${{ parameters.commit }} + use1ESTemplate: ${{ parameters.use1ESTemplate }} + + - task: DownloadPipelineArtifact@2 + inputs: + artifactName: $(TestAssembliesArtifactName) + downloadPath: ${{ parameters.xaSourcePath }}/bin/Test$(XA.Build.Configuration) + + - template: /build-tools/automation/yaml-templates/run-dotnet-preview.yaml@self + parameters: + project: Microsoft.Android.slnx + arguments: -t:PrepareOpenJDK -c $(XA.Build.Configuration) --no-restore + displayName: prepare OpenJDK $(XA.Build.Configuration) + continueOnError: false + + - template: /build-tools/automation/yaml-templates/start-stop-emulator.yaml + parameters: + xaSourcePath: ${{ parameters.xaSourcePath }} + startContinueOnError: ${{ parameters.emulatorStartContinueOnError }} + + # Two tests at a time share the emulator, matching [assembly: LevelOfParallelism (2)]. + - template: /build-tools/automation/yaml-templates/run-nunit-tests.yaml + parameters: + testAssembly: ${{ parameters.xaSourcePath }}/bin/Test$(XA.Build.Configuration)/TrimmingTests/$(DotNetStableTargetFramework)/TrimmingTests.dll + testRunTitle: TrimmingTests On Device - macOS + workers: 2 + timeoutInMinutes: 90 + + - ${{ if ne(parameters.usesCleanImages, true) }}: + - template: start-stop-emulator.yaml + parameters: + command: stop + xaSourcePath: ${{ parameters.xaSourcePath }} + + - template: /build-tools/automation/yaml-templates/upload-results.yaml + parameters: + artifactName: Test Results - Trimming With Emulator - macOS + xaSourcePath: ${{ parameters.xaSourcePath }} + use1ESTemplate: ${{ parameters.use1ESTemplate }} + + - template: /build-tools/automation/yaml-templates/fail-on-issue.yaml + parameters: + condition: ${{ parameters.shouldFailOnIssue }} diff --git a/src/Xamarin.Android.Build.Tasks/Tests/Xamarin.ProjectTools/Common/DotNetCLI.cs b/src/Xamarin.Android.Build.Tasks/Tests/Xamarin.ProjectTools/Common/DotNetCLI.cs index 2a054c9095d..6f04fd4039e 100644 --- a/src/Xamarin.Android.Build.Tasks/Tests/Xamarin.ProjectTools/Common/DotNetCLI.cs +++ b/src/Xamarin.Android.Build.Tasks/Tests/Xamarin.ProjectTools/Common/DotNetCLI.cs @@ -24,6 +24,8 @@ public class DotNetCLI readonly string projectOrSolution; + bool IsFileBasedApp => projectOrSolution.EndsWith (".cs", StringComparison.OrdinalIgnoreCase); + public DotNetCLI (string projectOrSolution) { this.projectOrSolution = projectOrSolution; @@ -315,13 +317,17 @@ List GetDefaultCommandLineArgs (string verb, string target = null, strin var arguments = new List { verb, $"\"{projectOrSolution}\"", - "/noconsolelogger", - $"/flp1:LogFile=\"{BuildLogFile}\";Encoding=UTF-8;Verbosity={Verbosity}", - $"/bl:\"{Path.Combine (testDir, $"{(string.IsNullOrEmpty (target) ? "msbuild" : target)}.binlog")}\"", - "-m:1", - "-nodeReuse:false", - "/p:_DisableParallelAot=true", }; + // File-based apps (`dotnet build App.cs`) reject file loggers and node options; their console output + // goes to ProcessLogFile instead of BuildLogFile. + if (!IsFileBasedApp) { + arguments.Add ("/noconsolelogger"); + arguments.Add ($"/flp1:LogFile=\"{BuildLogFile}\";Encoding=UTF-8;Verbosity={Verbosity}"); + arguments.Add ("-m:1"); + arguments.Add ("-nodeReuse:false"); + } + arguments.Add ($"/bl:\"{Path.Combine (testDir, $"{(string.IsNullOrEmpty (target) ? "msbuild" : target)}.binlog")}\""); + arguments.Add ("/p:_DisableParallelAot=true"); if (!string.IsNullOrEmpty (target)) { arguments.Add ($"/t:{target}"); } diff --git a/tests/TrimmingTests/AssemblyInfo.cs b/tests/TrimmingTests/AssemblyInfo.cs new file mode 100644 index 00000000000..45d5bad2b68 --- /dev/null +++ b/tests/TrimmingTests/AssemblyInfo.cs @@ -0,0 +1,4 @@ +using NUnit.Framework; + +// Case builds are heavy (full trimming, NativeAOT), so cap how many run at once. +[assembly: LevelOfParallelism (2)] diff --git a/tests/TrimmingTests/Cases/Directory.Build.props b/tests/TrimmingTests/Cases/Directory.Build.props new file mode 100644 index 00000000000..4997511a909 --- /dev/null +++ b/tests/TrimmingTests/Cases/Directory.Build.props @@ -0,0 +1,2 @@ + + diff --git a/tests/TrimmingTests/Cases/Directory.Build.targets b/tests/TrimmingTests/Cases/Directory.Build.targets new file mode 100644 index 00000000000..61baa988c79 --- /dev/null +++ b/tests/TrimmingTests/Cases/Directory.Build.targets @@ -0,0 +1,12 @@ + + + + + + + + + diff --git a/tests/TrimmingTests/Cases/GenericPeerArrayElement.cs b/tests/TrimmingTests/Cases/GenericPeerArrayElement.cs new file mode 100644 index 00000000000..deba631e31c --- /dev/null +++ b/tests/TrimmingTests/Cases/GenericPeerArrayElement.cs @@ -0,0 +1,70 @@ +#:property TargetFramework=net12.0-android +#:property OutputType=Exe +#:property ApplicationId=net.dot.android.trimmingtests.genericpeerarrayelement +#:property SupportedOSPlatformVersion=24 +#:project TrimmingTests.Expectations/TrimmingTests.Expectations.csproj + +// JNIEnv.GetArray () reaches TrimmableTypeMap.CreateInstance () with only a runtime Type. For a closed generic +// peer the runtime reflects over the (IntPtr, JniHandleOwnership) constructor, which nothing else in this app keeps. + +using System; +using System.Collections.Generic; +using Android.App; +using Android.OS; +using Android.Runtime; +using Microsoft.Android.TrimmingTests.Expectations; + +[Activity (Label = "GenericPeerArrayElement", MainLauncher = true)] +public class MainActivity : Activity +{ + protected override void OnCreate (Bundle? savedInstanceState) + { + base.OnCreate (savedInstanceState); + try { + Check ("managed state"); + Check (42); + Android.Util.Log.Info ("TrimmingTests", "TRIMMING_TEST_RESULT: PASS"); + } catch (Exception e) { + Android.Util.Log.Error ("TrimmingTests", $"TRIMMING_TEST_RESULT: FAIL {e}"); + } + } + + static void Check (T value) + { + IntPtr array; + using (var element = new GenericArrayElement { Value = value }) { + array = JNIEnv.NewObjectArray (1, element.Class.Handle, element.Handle); + } + try { + var items = JNIEnv.GetArray> (array); + if (items is not { Length: 1 } || items [0] is not { } item) { + throw new InvalidOperationException ($"Unable to convert the Java array element to {typeof (GenericArrayElement)}."); + } + if (item.GetType () != typeof (GenericArrayElement)) { + throw new InvalidOperationException ($"Expected {typeof (GenericArrayElement)}, got {item.GetType ()}."); + } + // The original peer was disposed, so this must be a new peer from the activation constructor, without its managed state. + if (!EqualityComparer.Default.Equals (item.Value, default)) { + throw new InvalidOperationException ($"Expected a newly activated peer, but Value is '{item.Value}'."); + } + item.Dispose (); + } finally { + JNIEnv.DeleteLocalRef (array); + } + } +} + +public class GenericArrayElement : Java.Lang.Object +{ + public GenericArrayElement () + { + } + + [Kept] + protected GenericArrayElement (IntPtr handle, JniHandleOwnership transfer) + : base (handle, transfer) + { + } + + public T? Value { get; set; } +} diff --git a/tests/TrimmingTests/Cases/JavaExceptions.cs b/tests/TrimmingTests/Cases/JavaExceptions.cs new file mode 100644 index 00000000000..d3a4deaaae5 --- /dev/null +++ b/tests/TrimmingTests/Cases/JavaExceptions.cs @@ -0,0 +1,39 @@ +#:property TargetFramework=net12.0-android +#:property OutputType=Exe +#:property ApplicationId=net.dot.android.trimmingtests.javaexceptions +#:property SupportedOSPlatformVersion=24 +#:project TrimmingTests.Expectations/TrimmingTests.Expectations.csproj + +// A Java exception reaches managed code as its bound exception type, which the runtime activates through the type map. +// The exception the app catches is kept; exception bindings the app never sees are removed. + +using System; +using Android.App; +using Android.OS; +using Microsoft.Android.TrimmingTests.Expectations; + +[assembly: KeptTypeInAssembly ("Mono.Android", "Java.Lang.NumberFormatException")] +[assembly: KeptMemberInAssembly ("Mono.Android", "Java.Lang.NumberFormatException", ".ctor(System.IntPtr,Android.Runtime.JniHandleOwnership)")] + +[assembly: RemovedTypeInAssembly ("Mono.Android", "Java.Lang.ArrayStoreException")] +[assembly: RemovedTypeInAssembly ("Mono.Android", "Java.Util.Zip.DataFormatException")] +[assembly: RemovedTypeInAssembly ("Mono.Android", "Android.Database.Sqlite.SQLiteFullException")] + +[Activity (Label = "JavaExceptions", MainLauncher = true)] +public class MainActivity : Activity +{ + protected override void OnCreate (Bundle? savedInstanceState) + { + base.OnCreate (savedInstanceState); + try { + try { + Java.Lang.Integer.ParseInt ("not a number"); + throw new InvalidOperationException ("Integer.parseInt did not throw."); + } catch (Java.Lang.NumberFormatException e) when (e.GetType () == typeof (Java.Lang.NumberFormatException)) { + } + Android.Util.Log.Info ("TrimmingTests", "TRIMMING_TEST_RESULT: PASS"); + } catch (Exception e) { + Android.Util.Log.Error ("TrimmingTests", $"TRIMMING_TEST_RESULT: FAIL {e}"); + } + } +} diff --git a/tests/TrimmingTests/Cases/JavaInterfaceInvokers.cs b/tests/TrimmingTests/Cases/JavaInterfaceInvokers.cs new file mode 100644 index 00000000000..23cfeeedfdd --- /dev/null +++ b/tests/TrimmingTests/Cases/JavaInterfaceInvokers.cs @@ -0,0 +1,54 @@ +#:property TargetFramework=net12.0-android +#:property OutputType=Exe +#:property ApplicationId=net.dot.android.trimmingtests.javainterfaceinvokers +#:property SupportedOSPlatformVersion=24 +#:project TrimmingTests.Expectations/TrimmingTests.Expectations.csproj + +// Java returns objects the app only knows by a bound interface, so the runtime activates the interface's invoker. +// The invokers and the members the app calls are kept; the interface's other members and unrelated invokers are removed. + +using System; +using Android.App; +using Android.Content; +using Android.OS; +using Microsoft.Android.TrimmingTests.Expectations; + +[assembly: KeptTypeInAssembly ("Mono.Android", "Android.Content.ISharedPreferencesInvoker")] +[assembly: KeptMemberInAssembly ("Mono.Android", "Android.Content.ISharedPreferencesInvoker", + ".ctor(System.IntPtr,Android.Runtime.JniHandleOwnership)", "Edit()", "GetString(System.String,System.String)")] +[assembly: KeptTypeInAssembly ("Mono.Android", "Android.Content.ISharedPreferencesEditorInvoker")] +[assembly: KeptMemberInAssembly ("Mono.Android", "Android.Content.ISharedPreferencesEditorInvoker", + ".ctor(System.IntPtr,Android.Runtime.JniHandleOwnership)", "PutString(System.String,System.String)", "Commit()")] + +[assembly: RemovedMemberInAssembly ("Mono.Android", "Android.Content.ISharedPreferences", + "GetInt(System.String,System.Int32)", "Contains(System.String)")] +[assembly: RemovedMemberInAssembly ("Mono.Android", "Android.Content.ISharedPreferencesInvoker", + "GetInt(System.String,System.Int32)", "Contains(System.String)")] +[assembly: RemovedMemberInAssembly ("Mono.Android", "Android.Content.ISharedPreferencesEditorInvoker", + "PutInt(System.String,System.Int32)", "Clear()")] +[assembly: RemovedTypeInAssembly ("Mono.Android", "Android.Content.ISharedPreferencesOnSharedPreferenceChangeListenerInvoker")] +[assembly: RemovedTypeInAssembly ("Mono.Android", "Android.Text.ITextWatcherInvoker")] + +[Activity (Label = "JavaInterfaceInvokers", MainLauncher = true)] +public class MainActivity : Activity +{ + protected override void OnCreate (Bundle? savedInstanceState) + { + base.OnCreate (savedInstanceState); + try { + var preferences = GetSharedPreferences ("trimming-tests", FileCreationMode.Private) + ?? throw new InvalidOperationException ("GetSharedPreferences returned null."); + var editor = preferences.Edit ()?.PutString ("key", "value") ?? throw new InvalidOperationException ("Edit returned null."); + if (!editor.Commit ()) { + throw new InvalidOperationException ("Commit failed."); + } + var value = preferences.GetString ("key", null); + if (value != "value") { + throw new InvalidOperationException ($"GetString returned '{value}'."); + } + Android.Util.Log.Info ("TrimmingTests", "TRIMMING_TEST_RESULT: PASS"); + } catch (Exception e) { + Android.Util.Log.Error ("TrimmingTests", $"TRIMMING_TEST_RESULT: FAIL {e}"); + } + } +} diff --git a/tests/TrimmingTests/Cases/JavaObjectActivation.cs b/tests/TrimmingTests/Cases/JavaObjectActivation.cs new file mode 100644 index 00000000000..f5e7bb283d9 --- /dev/null +++ b/tests/TrimmingTests/Cases/JavaObjectActivation.cs @@ -0,0 +1,43 @@ +#:property TargetFramework=net12.0-android +#:property OutputType=Exe +#:property ApplicationId=net.dot.android.trimmingtests.javaobjectactivation +#:property SupportedOSPlatformVersion=24 +#:project TrimmingTests.Expectations/TrimmingTests.Expectations.csproj + +// Java returns a java.lang.Integer typed as java.lang.Object, so the runtime has to activate the most derived binding, +// Java.Lang.Integer, through the type map. Unrelated numeric bindings and unused members are removed. + +using System; +using Android.App; +using Android.OS; +using Microsoft.Android.TrimmingTests.Expectations; + +[assembly: KeptTypeInAssembly ("Mono.Android", "Java.Lang.Integer")] +[assembly: KeptMemberInAssembly ("Mono.Android", "Java.Lang.Integer", + ".ctor(System.IntPtr,Android.Runtime.JniHandleOwnership)", "ValueOf(System.Int32)", "IntValue()")] +[assembly: KeptMemberInAssembly ("Mono.Android", "Java.Util.ArrayList", "Get(System.Int32)")] + +[assembly: RemovedMemberInAssembly ("Mono.Android", "Java.Lang.Integer", "ToHexString(System.Int32)", "Reverse(System.Int32)")] +[assembly: RemovedMemberInAssembly ("Mono.Android", "Java.Util.ArrayList", "EnsureCapacity(System.Int32)", "TrimToSize()")] +[assembly: RemovedTypeInAssembly ("Mono.Android", "Java.Math.BigDecimal")] +[assembly: RemovedTypeInAssembly ("Mono.Android", "Java.Util.Concurrent.Atomic.AtomicInteger")] + +[Activity (Label = "JavaObjectActivation", MainLauncher = true)] +public class MainActivity : Activity +{ + protected override void OnCreate (Bundle? savedInstanceState) + { + base.OnCreate (savedInstanceState); + try { + var list = new Java.Util.ArrayList (); + list.Add (Java.Lang.Integer.ValueOf (42)); + var item = list.Get (0); + if (item is not Java.Lang.Integer value || item.GetType () != typeof (Java.Lang.Integer) || value.IntValue () != 42) { + throw new InvalidOperationException ($"ArrayList.get returned {item?.GetType ()}."); + } + Android.Util.Log.Info ("TrimmingTests", "TRIMMING_TEST_RESULT: PASS"); + } catch (Exception e) { + Android.Util.Log.Error ("TrimmingTests", $"TRIMMING_TEST_RESULT: FAIL {e}"); + } + } +} diff --git a/tests/TrimmingTests/Cases/TrimmingTests.Expectations/Expectations.cs b/tests/TrimmingTests/Cases/TrimmingTests.Expectations/Expectations.cs new file mode 100644 index 00000000000..7b36e1fe871 --- /dev/null +++ b/tests/TrimmingTests/Cases/TrimmingTests.Expectations/Expectations.cs @@ -0,0 +1,125 @@ +using System; + +namespace Microsoft.Android.TrimmingTests.Expectations; + +// Naming follows dotnet/runtime's Mono.Linker.Tests.Cases.Expectations. +// +// Expectations must not change what is trimmed: they only take strings, never `typeof`, because a type referenced +// from a kept attribute is kept as well. An argument-free attribute on a member does not keep that member. +// +// Signature formats: +// * types: "Namespace.Name", e.g. "Android.Runtime.JavaDictionary`2", with '/' for nested types; *TypeInAssembly also +// takes a generic instantiation, e.g. "Android.Runtime.JavaDictionary`2", which only +// NativeAOT can check (By = Tool.NativeAot): ILLink keeps or removes the generic definition; +// * methods: "Name(ParameterType,ParameterType)" with parameter types in the same form, generic instances as +// "System.Collections.Generic.IList`1" and generic parameters by name, e.g. +// ".ctor(System.IntPtr,Android.Runtime.JniHandleOwnership)"; +// * fields, properties and events: their name. + +/// The trimming configurations an expectation applies to. +[Flags] +public enum Tool +{ + None = 0, + /// ILLink with TrimMode=full (CoreCLR). + FullTrimming = 1, + /// ILC (NativeAOT). + NativeAot = 2, + /// + /// ILLink with TrimMode=partial (CoreCLR), which trims only trimmable assemblies. Expectations on the other + /// assemblies (such as the app's) don't need this: the harness checks that those assemblies are kept whole instead. + /// + PartialTrimming = 4, + /// ILLink in either mode (CoreCLR). + Trimmer = FullTrimming | PartialTrimming, + All = Trimmer | NativeAot, +} + +public abstract class BaseExpectationAttribute : Attribute +{ + /// The tools this expectation applies to. Use it only where the tools legitimately differ. + public Tool By { get; set; } = Tool.All; +} + +/// The annotated type or member must survive trimming. +[AttributeUsage (AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Interface | AttributeTargets.Enum | AttributeTargets.Delegate | + AttributeTargets.Constructor | AttributeTargets.Method | AttributeTargets.Field | AttributeTargets.Property | AttributeTargets.Event, Inherited = false)] +public sealed class KeptAttribute : BaseExpectationAttribute +{ +} + +/// The annotated type or member must be removed by trimming. +[AttributeUsage (AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Interface | AttributeTargets.Enum | AttributeTargets.Delegate | + AttributeTargets.Constructor | AttributeTargets.Method | AttributeTargets.Field | AttributeTargets.Property | AttributeTargets.Event, Inherited = false)] +public sealed class RemovedAttribute : BaseExpectationAttribute +{ +} + +/// A member of the annotated type that cannot carry itself (for example a compiler-generated one) must survive. +[AttributeUsage (AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Interface | AttributeTargets.Enum, AllowMultiple = true, Inherited = false)] +public sealed class KeptMemberAttribute : BaseExpectationAttribute +{ + public KeptMemberAttribute (string signature) => Signature = signature; + + public string Signature { get; } +} + +/// A type in another assembly of the app, such as Mono.Android, must survive. +[AttributeUsage (AttributeTargets.Assembly | AttributeTargets.Class, AllowMultiple = true)] +public sealed class KeptTypeInAssemblyAttribute : BaseExpectationAttribute +{ + public KeptTypeInAssemblyAttribute (string assemblyName, string typeName) + { + AssemblyName = assemblyName; + TypeName = typeName; + } + + public string AssemblyName { get; } + public string TypeName { get; } +} + +/// A type in another assembly of the app must be removed. +[AttributeUsage (AttributeTargets.Assembly | AttributeTargets.Class, AllowMultiple = true)] +public sealed class RemovedTypeInAssemblyAttribute : BaseExpectationAttribute +{ + public RemovedTypeInAssemblyAttribute (string assemblyName, string typeName) + { + AssemblyName = assemblyName; + TypeName = typeName; + } + + public string AssemblyName { get; } + public string TypeName { get; } +} + +/// Members of a type in another assembly of the app, such as Mono.Android, must survive. +[AttributeUsage (AttributeTargets.Assembly | AttributeTargets.Class, AllowMultiple = true)] +public sealed class KeptMemberInAssemblyAttribute : BaseExpectationAttribute +{ + public KeptMemberInAssemblyAttribute (string assemblyName, string typeName, params string [] memberSignatures) + { + AssemblyName = assemblyName; + TypeName = typeName; + MemberSignatures = memberSignatures; + } + + public string AssemblyName { get; } + public string TypeName { get; } + public string [] MemberSignatures { get; } +} + +/// Members of a type in another assembly of the app must be removed. +[AttributeUsage (AttributeTargets.Assembly | AttributeTargets.Class, AllowMultiple = true)] +public sealed class RemovedMemberInAssemblyAttribute : BaseExpectationAttribute +{ + public RemovedMemberInAssemblyAttribute (string assemblyName, string typeName, params string [] memberSignatures) + { + AssemblyName = assemblyName; + TypeName = typeName; + MemberSignatures = memberSignatures; + } + + public string AssemblyName { get; } + public string TypeName { get; } + public string [] MemberSignatures { get; } +} diff --git a/tests/TrimmingTests/Cases/TrimmingTests.Expectations/TrimmingTests.Expectations.csproj b/tests/TrimmingTests/Cases/TrimmingTests.Expectations/TrimmingTests.Expectations.csproj new file mode 100644 index 00000000000..e724f969702 --- /dev/null +++ b/tests/TrimmingTests/Cases/TrimmingTests.Expectations/TrimmingTests.Expectations.csproj @@ -0,0 +1,9 @@ + + + + + netstandard2.0 + latest + + + diff --git a/tests/TrimmingTests/Cases/UnusedBindings.cs b/tests/TrimmingTests/Cases/UnusedBindings.cs new file mode 100644 index 00000000000..5815527bc2b --- /dev/null +++ b/tests/TrimmingTests/Cases/UnusedBindings.cs @@ -0,0 +1,58 @@ +#:property TargetFramework=net12.0-android +#:property OutputType=Exe +#:property ApplicationId=net.dot.android.trimmingtests.unusedbindings +#:property SupportedOSPlatformVersion=24 +#:project TrimmingTests.Expectations/TrimmingTests.Expectations.csproj + +// An app that is only an Activity: Mono.Android bindings it never uses must be trimmed away. +// It also guards these fixed bugs: +// - https://github.com/dotnet/android/pull/11144: ILLink failed with IL1034 because the app assembly was rooted as an entry +// point; rooting the whole app assembly would also keep UnusedHelper. +// - https://github.com/dotnet/android/pull/11982: NativeAOT apps crashed at startup because the runtime-only assembly's Java +// callable wrapper was missing. +// - https://github.com/dotnet/android/issues/10672: NativeAOT rooted every assembly ILLink kept, so nothing was removed. +// - https://github.com/dotnet/android/issues/10911: the type map kept every binding event Implementor. + +using System; +using Android.App; +using Android.OS; +using Microsoft.Android.TrimmingTests.Expectations; + +// Used by the app. +[assembly: KeptTypeInAssembly ("Mono.Android", "Android.App.Activity")] +[assembly: KeptMemberInAssembly ("Mono.Android", "Android.App.Activity", "OnCreate(Android.OS.Bundle)")] + +// Never used by the app. +[assembly: RemovedTypeInAssembly ("Mono.Android", "Android.Webkit.WebView")] +[assembly: RemovedTypeInAssembly ("Mono.Android", "Android.Bluetooth.BluetoothAdapter")] +[assembly: RemovedTypeInAssembly ("Mono.Android", "Android.Media.MediaPlayer")] +[assembly: RemovedTypeInAssembly ("Mono.Android", "Android.Widget.CalendarView")] +[assembly: RemovedTypeInAssembly ("Mono.Android", "Android.Locations.LocationManager")] +[assembly: RemovedTypeInAssembly ("Mono.Android", "Java.Util.Zip.ZipFile")] +[assembly: RemovedTypeInAssembly ("Mono.Android", "Android.Views.View/IOnClickListenerInvoker")] +[assembly: RemovedTypeInAssembly ("Mono.Android", "Android.Views.View/IOnClickListenerImplementor")] + +// Android instantiates the activity through its compiler-generated default constructor. +[Activity (Label = "UnusedBindings", MainLauncher = true)] +[KeptMember (".ctor()")] +public class MainActivity : Activity +{ + [Kept] + protected override void OnCreate (Bundle? savedInstanceState) + { + base.OnCreate (savedInstanceState); + Android.Util.Log.Info ("TrimmingTests", "TRIMMING_TEST_RESULT: PASS"); + } + + [Removed] + static void Unused () + { + Console.WriteLine ("never called"); + } +} + +[Removed] +class UnusedHelper +{ + public static void Run () => Console.WriteLine ("never called"); +} diff --git a/tests/TrimmingTests/Cases/UnusedBoxingBindings.cs b/tests/TrimmingTests/Cases/UnusedBoxingBindings.cs new file mode 100644 index 00000000000..7e45ad984ed --- /dev/null +++ b/tests/TrimmingTests/Cases/UnusedBoxingBindings.cs @@ -0,0 +1,32 @@ +#:property TargetFramework=net12.0-android +#:property OutputType=Exe +#:property ApplicationId=net.dot.android.trimmingtests.unusedboxingbindings +#:property SupportedOSPlatformVersion=24 +#:project TrimmingTests.Expectations/TrimmingTests.Expectations.csproj + +// An app that never converts between Java boxed values and .NET primitives does not need JavaConvert or the +// Java.Lang boxing bindings. Today every app keeps them: https://github.com/dotnet/android/issues/13635 + +using Android.App; +using Android.OS; +using Microsoft.Android.TrimmingTests.Expectations; + +[assembly: RemovedTypeInAssembly ("Mono.Android", "Java.Interop.JavaConvert")] +[assembly: RemovedTypeInAssembly ("Mono.Android", "Java.Lang.Boolean")] +[assembly: RemovedTypeInAssembly ("Mono.Android", "Java.Lang.Byte")] +[assembly: RemovedTypeInAssembly ("Mono.Android", "Java.Lang.Character")] +[assembly: RemovedTypeInAssembly ("Mono.Android", "Java.Lang.Short")] +[assembly: RemovedTypeInAssembly ("Mono.Android", "Java.Lang.Integer")] +[assembly: RemovedTypeInAssembly ("Mono.Android", "Java.Lang.Long")] +[assembly: RemovedTypeInAssembly ("Mono.Android", "Java.Lang.Float")] +[assembly: RemovedTypeInAssembly ("Mono.Android", "Java.Lang.Double")] + +[Activity (Label = "UnusedBoxingBindings", MainLauncher = true)] +public class MainActivity : Activity +{ + protected override void OnCreate (Bundle? savedInstanceState) + { + base.OnCreate (savedInstanceState); + Android.Util.Log.Info ("TrimmingTests", "TRIMMING_TEST_RESULT: PASS"); + } +} diff --git a/tests/TrimmingTests/Cases/UsedBindings.cs b/tests/TrimmingTests/Cases/UsedBindings.cs new file mode 100644 index 00000000000..887ad3d8c48 --- /dev/null +++ b/tests/TrimmingTests/Cases/UsedBindings.cs @@ -0,0 +1,63 @@ +#:property TargetFramework=net12.0-android +#:property OutputType=Exe +#:property ApplicationId=net.dot.android.trimmingtests.usedbindings +#:property SupportedOSPlatformVersion=24 +#:project TrimmingTests.Expectations/TrimmingTests.Expectations.csproj + +// Using one binding keeps exactly what the app calls: the TextView constructor and the click-listener plumbing that Java +// calls back into, but not the binding's other members or sibling widgets. The app's own Java peer keeps only what Java +// can call (https://github.com/dotnet/android/issues/12270, fixed by https://github.com/dotnet/android/pull/12272: +// every member of every Java peer type used to be kept). + +using System; +using Android.App; +using Android.OS; +using Android.Views; +using Android.Widget; +using Microsoft.Android.TrimmingTests.Expectations; + +[assembly: KeptTypeInAssembly ("Mono.Android", "Android.Widget.TextView")] +[assembly: KeptMemberInAssembly ("Mono.Android", "Android.Widget.TextView", ".ctor(Android.Content.Context)")] +[assembly: KeptMemberInAssembly ("Mono.Android", "Android.Views.View", + "SetOnClickListener(Android.Views.View/IOnClickListener)", "PerformClick()")] +[assembly: KeptTypeInAssembly ("Mono.Android", "Android.Views.View/IOnClickListener")] + +[assembly: RemovedMemberInAssembly ("Mono.Android", "Android.Widget.TextView", + "SetLines(System.Int32)", "SetTextIsSelectable(System.Boolean)")] +[assembly: RemovedTypeInAssembly ("Mono.Android", "Android.Widget.Button")] +[assembly: RemovedTypeInAssembly ("Mono.Android", "Android.Widget.CalendarView")] + +[Activity (Label = "UsedBindings", MainLauncher = true)] +public class MainActivity : Activity +{ + protected override void OnCreate (Bundle? savedInstanceState) + { + base.OnCreate (savedInstanceState); + try { + var listener = new ClickListener (); + var view = new TextView (this); + view.SetOnClickListener (listener); + if (!view.PerformClick () || !listener.Clicked) { + throw new InvalidOperationException ("Java did not call the managed click listener."); + } + Android.Util.Log.Info ("TrimmingTests", "TRIMMING_TEST_RESULT: PASS"); + } catch (Exception e) { + Android.Util.Log.Error ("TrimmingTests", $"TRIMMING_TEST_RESULT: FAIL {e}"); + } + } +} + +[Kept] +class ClickListener : Java.Lang.Object, View.IOnClickListener +{ + public bool Clicked { get; private set; } + + [Kept] + public void OnClick (View? v) => Clicked = true; + + [Removed] + public void UnusedHelper () => Clicked = false; + + [Removed] + public virtual void UnusedVirtual () => Clicked = false; +} diff --git a/tests/TrimmingTests/Tests/BindingTrimmingTests.cs b/tests/TrimmingTests/Tests/BindingTrimmingTests.cs new file mode 100644 index 00000000000..181aa96fc7c --- /dev/null +++ b/tests/TrimmingTests/Tests/BindingTrimmingTests.cs @@ -0,0 +1,59 @@ +#nullable enable +using NUnit.Framework; + +namespace Microsoft.Android.TrimmingTests; + +[TestFixture] +[Category ("UsesDevice")] +[Parallelizable (ParallelScope.Children)] +public class BindingTrimmingTests : TrimmingTestBase +{ + // The app launches, builds without warnings, and only the bindings it uses survive trimming. + [Test] + public void UnusedBindingsAreRemovedWithoutWarnings ([TrimmingConfigurations] TrimmingConfiguration configuration) + { + var app = BuildAndRun ("Cases/UnusedBindings.cs", configuration); + AssertTrimmingExpectations (app); + } + + // Java calls back into a managed click listener on a TextView; the binding members the app uses are kept, the rest are removed. + [Test] + public void UsedBindingMembersAreKeptWithoutWarnings ([TrimmingConfigurations] TrimmingConfiguration configuration) + { + var app = BuildAndRun ("Cases/UsedBindings.cs", configuration); + AssertTrimmingExpectations (app); + } + + // A Java exception is activated as its bound type; unrelated exception bindings are removed. + [Test] + public void JavaExceptionIsActivatedAsBoundTypeWithoutWarnings ([TrimmingConfigurations] TrimmingConfiguration configuration) + { + var app = BuildAndRun ("Cases/JavaExceptions.cs", configuration); + AssertTrimmingExpectations (app); + } + + // Java-implemented interfaces are activated as their invokers; only the invoker members the app calls are kept. + [Test] + public void InterfaceInvokersKeepOnlyUsedMembersWithoutWarnings ([TrimmingConfigurations] TrimmingConfiguration configuration) + { + var app = BuildAndRun ("Cases/JavaInterfaceInvokers.cs", configuration); + AssertTrimmingExpectations (app); + } + + // A java.lang.Integer returned as java.lang.Object is activated as Java.Lang.Integer; unused members are removed. + [Test] + public void JavaObjectIsActivatedAsMostDerivedBindingWithoutWarnings ([TrimmingConfigurations] TrimmingConfiguration configuration) + { + var app = BuildAndRun ("Cases/JavaObjectActivation.cs", configuration); + AssertTrimmingExpectations (app); + } + + // An app that never converts Java boxed values does not keep JavaConvert or the Java.Lang boxing bindings. + [Test] + [Ignore ("https://github.com/dotnet/android/issues/13635: every app keeps JavaConvert and the Java.Lang boxing bindings.")] + public void UnusedBoxingBindingsAreRemovedWithoutWarnings ([TrimmingConfigurations] TrimmingConfiguration configuration) + { + var app = BuildAndRun ("Cases/UnusedBoxingBindings.cs", configuration); + AssertTrimmingExpectations (app); + } +} diff --git a/tests/TrimmingTests/Tests/JavaPeerActivationTests.cs b/tests/TrimmingTests/Tests/JavaPeerActivationTests.cs new file mode 100644 index 00000000000..24b487e582c --- /dev/null +++ b/tests/TrimmingTests/Tests/JavaPeerActivationTests.cs @@ -0,0 +1,19 @@ +#nullable enable +using NUnit.Framework; + +namespace Microsoft.Android.TrimmingTests; + +[TestFixture] +[Category ("UsesDevice")] +[Parallelizable (ParallelScope.Children)] +public class JavaPeerActivationTests : TrimmingTestBase +{ + // The case app converts a Java array of closed generic peers with JNIEnv.GetArray () and reports PASS only if every + // element comes back. The [Kept] activation constructor must survive trimming. + [Test] + public void GetArrayActivatesClosedGenericPeerElementsWithoutWarnings ([TrimmingConfigurations] TrimmingConfiguration configuration) + { + var app = BuildAndRun ("Cases/GenericPeerArrayElement.cs", configuration); + AssertTrimmingExpectations (app); + } +} diff --git a/tests/TrimmingTests/TrimmingExpectations.cs b/tests/TrimmingTests/TrimmingExpectations.cs new file mode 100644 index 00000000000..a83318e4fec --- /dev/null +++ b/tests/TrimmingTests/TrimmingExpectations.cs @@ -0,0 +1,628 @@ +#nullable enable +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.IO; +using System.Linq; +using System.Reflection.Metadata; +using System.Reflection.Metadata.Ecma335; +using System.Reflection.PortableExecutable; + +namespace Microsoft.Android.TrimmingTests; + +/// +/// Checks the expectations declared with the attributes from Cases/TrimmingTests.Expectations (read from the untrimmed +/// case assembly) against the trimmed output of one configuration. +/// +static class TrimmingExpectations +{ + /// Returns the untrimmed path of an app assembly by name, or null when unknown. + /// + /// Whether the configuration trims an assembly. Expectations on an assembly it doesn't trim (the app's own assemblies in + /// partial mode) are replaced by a check that the whole assembly was kept. + /// + public static IReadOnlyList Validate (string caseAssembly, TrimmingConfiguration configuration, ITrimmedOutput output, + Func resolveInputAssembly, Func isTrimmed) + { + var failures = new List (); + // The Tool flags of Microsoft.Android.TrimmingTests.Expectations. + int tool = configuration switch { + TrimmingConfiguration.CoreClrFullTrimming => 1, + TrimmingConfiguration.NativeAot => 2, + TrimmingConfiguration.CoreClrPartialTrimming => 4, + _ => throw new ArgumentOutOfRangeException (nameof (configuration)), + }; + var assembly = AssemblyMetadata.Read (caseAssembly); + var inputs = new Dictionary { [assembly.Name] = assembly }; + + CheckInAssemblyExpectations (assembly.Expectations); + foreach (var type in assembly.Types.Values) { + foreach (var expectation in Applicable (type.Expectations, "KeptAttribute", "RemovedAttribute")) { + Expect (type, expectation.Name == "KeptAttribute"); + } + foreach (var member in type.Members) { + foreach (var expectation in Applicable (member.Expectations, "KeptAttribute", "RemovedAttribute")) { + Expect (member, expectation.Name == "KeptAttribute"); + } + } + foreach (var expectation in Applicable (type.Expectations, "KeptMemberAttribute")) { + var signature = expectation.GetString (0); + var member = type.FindMember (signature); + if (member is null) { + failures.Add ($"[KeptMember (\"{signature}\")] on {type.FullName}: no such member in the input assembly."); + } else { + Expect (member, kept: true); + } + } + CheckInAssemblyExpectations (type.Expectations); + } + foreach (var input in inputs.Values) { + if (input is not null && !isTrimmed (input)) { + ExpectKeptWhole (input); + } + } + return failures; + + void ExpectKeptWhole (AssemblyMetadata input) + { + foreach (var type in input.Types.Values) { + if (!output.IsKept (type)) { + failures.Add ($"{Describe (type)} should have been kept on {configuration}, which doesn't trim '{input.Name}'."); + continue; + } + foreach (var member in type.Members.Where (m => !output.IsKept (m))) { + failures.Add ($"{Describe (member)} should have been kept on {configuration}, which doesn't trim '{input.Name}'."); + } + } + } + + void CheckInAssemblyExpectations (IEnumerable expectations) + { + foreach (var expectation in Applicable (expectations, "KeptTypeInAssemblyAttribute", "RemovedTypeInAssemblyAttribute", + "KeptMemberInAssemblyAttribute", "RemovedMemberInAssemblyAttribute")) { + var name = expectation.Name; + var assemblyName = expectation.GetString (0); + var typeName = expectation.GetString (1); + var input = GetInput (assemblyName); + if (input is null) { + failures.Add ($"[{name}]: unable to find the untrimmed '{assemblyName}' assembly of the app."); + continue; + } + int typeArguments = typeName.IndexOf ('<'); + var definitionName = typeArguments < 0 ? typeName : typeName.Substring (0, typeArguments); + if (!input.Types.TryGetValue (definitionName, out var type)) { + failures.Add ($"[{name}]: no type '{definitionName}' in the untrimmed '{assemblyName}' assembly."); + continue; + } + bool kept = name.StartsWith ("Kept", StringComparison.Ordinal); + if (typeArguments >= 0) { + ExpectInstantiation (type, typeName, kept); + continue; + } + if (name.EndsWith ("TypeInAssemblyAttribute", StringComparison.Ordinal)) { + Expect (type, kept); + continue; + } + foreach (var signature in expectation.GetStrings (2)) { + var member = type.FindMember (signature); + if (member is null) { + failures.Add ($"[{name}]: no member '{signature}' on '{typeName}' in the untrimmed '{assemblyName}' assembly."); + } else { + Expect (member, kept); + } + } + } + } + + IEnumerable Applicable (IEnumerable expectations, params string [] names) + => expectations.Where (e => names.Contains (e.Name) && (e.By & tool) != 0); + + void Expect (object typeOrMember, bool kept) + { + var declaringType = typeOrMember as TypeMetadata ?? ((MemberMetadata) typeOrMember).DeclaringType; + if (GetInput (declaringType.AssemblyName) is { } input && !isTrimmed (input)) { + // ExpectKeptWhole () checks this assembly instead. + return; + } + bool actual; + try { + actual = typeOrMember is TypeMetadata type ? output.IsKept (type) : output.IsKept ((MemberMetadata) typeOrMember); + } catch (NotSupportedException e) { + failures.Add ($"{Describe (typeOrMember)}: {e.Message}"); + return; + } + if (actual != kept) { + failures.Add ($"{Describe (typeOrMember)} should have been {(kept ? "kept" : "removed")} on {configuration}."); + } + } + + void ExpectInstantiation (TypeMetadata definition, string instantiation, bool kept) + { + if (GetInput (definition.AssemblyName) is { } input && !isTrimmed (input)) { + return; + } + var description = $"[{definition.AssemblyName}]{instantiation}"; + try { + if (output.IsKept (definition, instantiation) != kept) { + failures.Add ($"{description} should have been {(kept ? "kept" : "removed")} on {configuration}."); + } + } catch (NotSupportedException e) { + failures.Add ($"{description}: {e.Message}"); + } + } + + AssemblyMetadata? GetInput (string name) + { + if (!inputs.TryGetValue (name, out var input)) { + var path = resolveInputAssembly (name); + input = path is null ? null : AssemblyMetadata.Read (path); + inputs [name] = input; + } + return input; + } + } + + static string Describe (object typeOrMember) + => typeOrMember switch { + TypeMetadata type => $"[{type.AssemblyName}]{type.FullName}", + MemberMetadata member => $"[{member.DeclaringType.AssemblyName}]{member.DeclaringType.FullName}::{member.Signature}", + _ => typeOrMember.ToString () ?? "", + }; +} + +interface ITrimmedOutput +{ + bool IsKept (TypeMetadata type); + bool IsKept (MemberMetadata member); + + /// Whether a generic instantiation of , e.g. X`1<System.Int32>, survived. + bool IsKept (TypeMetadata definition, string instantiation); +} + +/// The assemblies written by ILLink (CoreCLR builds). +sealed class LinkedAssemblies : ITrimmedOutput +{ + readonly string directory; + readonly Dictionary assemblies = new (); + + public LinkedAssemblies (string directory) => this.directory = directory; + + public bool IsKept (TypeMetadata type) => Find (type) is not null; + + public bool IsKept (MemberMetadata member) => Find (member.DeclaringType)?.FindMember (member.Signature) is not null; + + public bool IsKept (TypeMetadata definition, string instantiation) + => throw new NotSupportedException ("ILLink keeps or removes generic definitions, not instantiations; use By = Tool.NativeAot."); + + TypeMetadata? Find (TypeMetadata type) + { + if (!assemblies.TryGetValue (type.AssemblyName, out var assembly)) { + var path = Path.Combine (directory, $"{type.AssemblyName}.dll"); + assembly = File.Exists (path) ? AssemblyMetadata.Read (path) : null; + assemblies [type.AssemblyName] = assembly; + } + return assembly is not null && assembly.Types.TryGetValue (type.FullName, out var linked) ? linked : null; + } +} + +/// +/// The types and methods ILC compiled into a NativeAOT app, read from its mstat file (IlcGenerateMstatFile=true). The mstat +/// is an assembly whose global Methods, DeduplicatedMethods and Types methods ldtoken every compiled +/// method and type, referencing them in their original assemblies. Inlined methods have no body of their own, so the cases +/// build with JitNoInline=1 (see Cases/Directory.Build.targets). +/// +sealed class IlcCompiledOutput : ITrimmedOutput +{ + readonly HashSet types = new (StringComparer.Ordinal); + readonly HashSet instantiations = new (StringComparer.Ordinal); + readonly HashSet methods = new (StringComparer.Ordinal); + + public IlcCompiledOutput (string path) + { + using var stream = File.OpenRead (path); + using var pe = new PEReader (stream); + var reader = pe.GetMetadataReader (); + var provider = new SignatureTypeProvider (reader.GetString (reader.GetAssemblyDefinition ().Name)); + foreach (var handle in reader.MethodDefinitions) { + var method = reader.GetMethodDefinition (handle); + if (reader.GetString (method.Name) is not ("Methods" or "DeduplicatedMethods" or "Types")) { + continue; + } + var il = pe.GetMethodBody (method.RelativeVirtualAddress).GetILReader (); + while (il.RemainingBytes > 0) { + var opCode = (ILOpCode) il.ReadByte (); + switch (opCode) { + case ILOpCode.Ldtoken: + Add (reader, provider, MetadataTokens.EntityHandle (il.ReadInt32 ())); + break; + case ILOpCode.Ldc_i4: + il.ReadInt32 (); + break; + case ILOpCode.Ldc_i4_s: + il.ReadSByte (); + break; + case >= ILOpCode.Ldc_i4_m1 and <= ILOpCode.Ldc_i4_8: + case ILOpCode.Pop: + case ILOpCode.Ret: + break; + default: + throw new InvalidDataException ($"Unexpected IL opcode {opCode} in {path}."); + } + } + } + } + + void Add (MetadataReader reader, SignatureTypeProvider provider, EntityHandle handle) + { + switch (handle.Kind) { + case HandleKind.TypeReference: + case HandleKind.TypeSpecification: + if (GetTypeKey (reader, provider, handle) is { } type) { + types.Add (type); + } + AddInstantiation (reader, provider, handle); + break; + case HandleKind.MethodSpecification: + Add (reader, provider, reader.GetMethodSpecification ((MethodSpecificationHandle) handle).Method); + break; + case HandleKind.MemberReference: + var member = reader.GetMemberReference ((MemberReferenceHandle) handle); + if (member.GetKind () != MemberReferenceKind.Method || GetTypeKey (reader, provider, member.Parent) is not { } declaringType) { + break; + } + var signature = member.DecodeMethodSignature (provider, GenericContext.Empty); + methods.Add ($"{declaringType}::{reader.GetString (member.Name)}({string.Join (",", signature.ParameterTypes.Select (p => p.CanonicalName))})"); + // A type whose code was compiled survives even without a runtime type (for example a static class). + types.Add (declaringType); + AddInstantiation (reader, provider, member.Parent); + break; + } + } + + void AddInstantiation (MetadataReader reader, SignatureTypeProvider provider, EntityHandle handle) + { + if (handle.Kind == HandleKind.TypeSpecification && + provider.GetTypeFromSpecification (reader, GenericContext.Empty, (TypeSpecificationHandle) handle, 0) is GenericInstanceSignatureType { Definition: NamedSignatureType definition } instance) { + instantiations.Add ($"[{definition.Assembly}]{instance.FullName}"); + } + } + + static string? GetTypeKey (MetadataReader reader, SignatureTypeProvider provider, EntityHandle handle) + { + var type = handle.Kind switch { + HandleKind.TypeReference => provider.GetTypeFromReference (reader, (TypeReferenceHandle) handle, 0), + HandleKind.TypeSpecification => provider.GetTypeFromSpecification (reader, GenericContext.Empty, (TypeSpecificationHandle) handle, 0), + _ => null, + }; + if (type is GenericInstanceSignatureType instance) { + type = instance.Definition; + } + return type is NamedSignatureType named ? $"[{named.Assembly}]{named.FullName}" : null; + } + + public bool IsKept (TypeMetadata type) => types.Contains ($"[{type.AssemblyName}]{type.FullName}"); + + public bool IsKept (TypeMetadata definition, string instantiation) => instantiations.Contains ($"[{definition.AssemblyName}]{instantiation}"); + + public bool IsKept (MemberMetadata member) + { + if (member is not MethodMetadata method) { + throw new NotSupportedException ("only types and methods are visible in ILC's compiled output; use By = Tool.Trimmer."); + } + return methods.Contains ($"[{method.DeclaringType.AssemblyName}]{method.DeclaringType.FullName}::{method.Name}({string.Join (",", method.Parameters.Select (p => p.CanonicalName))})"); + } +} + +/// An expectation attribute from Microsoft.Android.TrimmingTests.Expectations. +sealed record ExpectationAttribute (string Name, object? [] Arguments, int By) +{ + public string GetString (int index) + => Arguments [index] as string ?? throw new InvalidOperationException ($"[{Name}] argument {index} must be a string."); + + public string [] GetStrings (int index) + => Arguments [index] as string [] ?? throw new InvalidOperationException ($"[{Name}] argument {index} must be a string array."); +} + +/// The types and members of an assembly, read with System.Reflection.Metadata. +sealed class AssemblyMetadata +{ + const string ExpectationsNamespace = "Microsoft.Android.TrimmingTests.Expectations"; + const int AllTools = 7; + + public string Name { get; } + /// Whether the assembly declares [assembly: AssemblyMetadata ("IsTrimmable", "True")]. + public bool DeclaresIsTrimmable { get; } + public IReadOnlyList Expectations { get; } + /// Types by full name (Namespace.Name, with / separating nested types). + public IReadOnlyDictionary Types { get; } + + AssemblyMetadata (string name, bool declaresIsTrimmable, IReadOnlyList expectations, IReadOnlyDictionary types) + { + Name = name; + DeclaresIsTrimmable = declaresIsTrimmable; + Expectations = expectations; + Types = types; + } + + public static AssemblyMetadata Read (string path) + { + using var stream = File.OpenRead (path); + using var pe = new PEReader (stream); + var reader = pe.GetMetadataReader (); + var name = reader.GetString (reader.GetAssemblyDefinition ().Name); + + var types = new Dictionary (); + foreach (var handle in reader.TypeDefinitions) { + GetType (handle); + } + return new AssemblyMetadata (name, ReadIsTrimmable (reader), ReadExpectations (reader, reader.GetAssemblyDefinition ().GetCustomAttributes ()), + types.Values.ToDictionary (t => t.FullName, StringComparer.Ordinal)); + + TypeMetadata GetType (TypeDefinitionHandle handle) + { + if (types.TryGetValue (handle, out var type)) { + return type; + } + var definition = reader.GetTypeDefinition (handle); + var declaringHandle = definition.GetDeclaringType (); + var declaring = declaringHandle.IsNil ? null : GetType (declaringHandle); + var genericParameters = definition.GetGenericParameters ().Select (p => reader.GetString (reader.GetGenericParameter (p).Name)).ToArray (); + type = new TypeMetadata (name, reader.GetString (definition.Namespace), reader.GetString (definition.Name), declaring, genericParameters, + ReadExpectations (reader, definition.GetCustomAttributes ())); + types.Add (handle, type); + + var provider = new SignatureTypeProvider (name); + foreach (var methodHandle in definition.GetMethods ()) { + var method = reader.GetMethodDefinition (methodHandle); + var methodGenericParameters = method.GetGenericParameters ().Select (p => reader.GetString (reader.GetGenericParameter (p).Name)).ToArray (); + var signature = method.DecodeSignature (provider, new GenericContext (genericParameters, methodGenericParameters)); + type.Members.Add (new MethodMetadata (type, reader.GetString (method.Name), signature.ParameterTypes, methodGenericParameters, + ReadExpectations (reader, method.GetCustomAttributes ()))); + } + foreach (var fieldHandle in definition.GetFields ()) { + var field = reader.GetFieldDefinition (fieldHandle); + type.Members.Add (new MemberMetadata (type, reader.GetString (field.Name), ReadExpectations (reader, field.GetCustomAttributes ()))); + } + foreach (var propertyHandle in definition.GetProperties ()) { + var property = reader.GetPropertyDefinition (propertyHandle); + type.Members.Add (new MemberMetadata (type, reader.GetString (property.Name), ReadExpectations (reader, property.GetCustomAttributes ()))); + } + foreach (var eventHandle in definition.GetEvents ()) { + var @event = reader.GetEventDefinition (eventHandle); + type.Members.Add (new MemberMetadata (type, reader.GetString (@event.Name), ReadExpectations (reader, @event.GetCustomAttributes ()))); + } + return type; + } + } + + static bool ReadIsTrimmable (MetadataReader reader) + { + foreach (var handle in reader.GetAssemblyDefinition ().GetCustomAttributes ()) { + var attribute = reader.GetCustomAttribute (handle); + if (GetAttributeTypeName (reader, attribute.Constructor) != ("System.Reflection", "AssemblyMetadataAttribute")) { + continue; + } + var arguments = attribute.DecodeValue (AttributeTypeProvider.Instance).FixedArguments; + if (arguments is [{ Value: "IsTrimmable" }, { Value: string value }] && string.Equals (value, "True", StringComparison.OrdinalIgnoreCase)) { + return true; + } + } + return false; + } + + static IReadOnlyList ReadExpectations (MetadataReader reader, CustomAttributeHandleCollection handles) + { + List? result = null; + foreach (var handle in handles) { + var attribute = reader.GetCustomAttribute (handle); + var (ns, name) = GetAttributeTypeName (reader, attribute.Constructor); + if (ns != ExpectationsNamespace) { + continue; + } + var value = attribute.DecodeValue (AttributeTypeProvider.Instance); + var arguments = value.FixedArguments + .Select (a => a.Value is ImmutableArray> array ? array.Select (e => e.Value as string ?? throw new InvalidOperationException ($"[{name}] has a null string argument.")).ToArray () : a.Value) + .ToArray (); + int by = value.NamedArguments.Where (a => a.Name == "By").Select (a => Convert.ToInt32 (a.Value)).DefaultIfEmpty (AllTools).First (); + (result ??= new List ()).Add (new ExpectationAttribute (name, arguments, by)); + } + return result ?? []; + } + + static (string Namespace, string Name) GetAttributeTypeName (MetadataReader reader, EntityHandle constructor) + { + var type = constructor.Kind == HandleKind.MemberReference + ? reader.GetMemberReference ((MemberReferenceHandle) constructor).Parent + : reader.GetMethodDefinition ((MethodDefinitionHandle) constructor).GetDeclaringType (); + return type.Kind switch { + HandleKind.TypeReference => (reader.GetString (reader.GetTypeReference ((TypeReferenceHandle) type).Namespace), + reader.GetString (reader.GetTypeReference ((TypeReferenceHandle) type).Name)), + HandleKind.TypeDefinition => (reader.GetString (reader.GetTypeDefinition ((TypeDefinitionHandle) type).Namespace), + reader.GetString (reader.GetTypeDefinition ((TypeDefinitionHandle) type).Name)), + _ => ("", ""), + }; + } + + /// Decodes attribute arguments; the expectations only use strings, string arrays and the int-based Tool enum. + sealed class AttributeTypeProvider : ICustomAttributeTypeProvider + { + public static readonly AttributeTypeProvider Instance = new (); + + public string GetPrimitiveType (PrimitiveTypeCode typeCode) => typeCode.ToString (); + public string GetSystemType () => "System.Type"; + public string GetSZArrayType (string elementType) => elementType + "[]"; + public string GetTypeFromDefinition (MetadataReader reader, TypeDefinitionHandle handle, byte rawTypeKind) => reader.GetString (reader.GetTypeDefinition (handle).Name); + public string GetTypeFromReference (MetadataReader reader, TypeReferenceHandle handle, byte rawTypeKind) => reader.GetString (reader.GetTypeReference (handle).Name); + public string GetTypeFromSerializedName (string name) => name; + public PrimitiveTypeCode GetUnderlyingEnumType (string type) => PrimitiveTypeCode.Int32; + public bool IsSystemType (string type) => type == "System.Type"; + } +} + +sealed class TypeMetadata +{ + public TypeMetadata (string assemblyName, string @namespace, string name, TypeMetadata? declaringType, string [] genericParameters, + IReadOnlyList expectations) + { + AssemblyName = assemblyName; + Namespace = @namespace; + Name = name; + DeclaringType = declaringType; + GenericParameters = genericParameters; + Expectations = expectations; + FullName = declaringType is not null ? $"{declaringType.FullName}/{name}" : @namespace.Length == 0 ? name : $"{@namespace}.{name}"; + } + + public string AssemblyName { get; } + public string Namespace { get; } + public string Name { get; } + public string FullName { get; } + public TypeMetadata? DeclaringType { get; } + public string [] GenericParameters { get; } + public IReadOnlyList Expectations { get; } + public List Members { get; } = new (); + + /// Finds a method by Name(ParameterType,...), or a field, property or event by name. + public MemberMetadata? FindMember (string signature) + => signature.Contains ('(') + ? Members.OfType ().FirstOrDefault (m => m.Signature == signature) + : Members.FirstOrDefault (m => m is not MethodMetadata && m.Name == signature); +} + +class MemberMetadata +{ + public MemberMetadata (TypeMetadata declaringType, string name, IReadOnlyList expectations) + { + DeclaringType = declaringType; + Name = name; + Expectations = expectations; + } + + public TypeMetadata DeclaringType { get; } + public string Name { get; } + public IReadOnlyList Expectations { get; } + public virtual string Signature => Name; +} + +sealed class MethodMetadata : MemberMetadata +{ + public MethodMetadata (TypeMetadata declaringType, string name, ImmutableArray parameters, string [] genericParameters, + IReadOnlyList expectations) + : base (declaringType, name, expectations) + { + Parameters = parameters; + GenericParameters = genericParameters; + } + + public ImmutableArray Parameters { get; } + public string [] GenericParameters { get; } + public override string Signature => $"{Name}({string.Join (",", Parameters.Select (p => p.FullName))})"; +} + +/// A type in a method signature. +abstract record SignatureType +{ + /// Namespace.Name, / for nested types, T for generic parameters, e.g. System.Collections.Generic.IList`1<System.Int32>. + public abstract string FullName { get; } + /// Like , but generic parameters by position (!0, !!0), as in member references. + public abstract string CanonicalName { get; } +} + +sealed record PrimitiveSignatureType (PrimitiveTypeCode Code) : SignatureType +{ + public override string FullName => $"System.{Code}"; + public override string CanonicalName => FullName; +} + +sealed record NamedSignatureType (string Assembly, string Namespace, string Name, NamedSignatureType? DeclaringType) : SignatureType +{ + public override string FullName => DeclaringType is not null ? $"{DeclaringType.FullName}/{Name}" : Namespace.Length == 0 ? Name : $"{Namespace}.{Name}"; + public override string CanonicalName => FullName; +} + +sealed record GenericInstanceSignatureType (SignatureType Definition, ImmutableArray Arguments) : SignatureType +{ + public override string FullName => $"{Definition.FullName}<{string.Join (",", Arguments.Select (a => a.FullName))}>"; + public override string CanonicalName => $"{Definition.CanonicalName}<{string.Join (",", Arguments.Select (a => a.CanonicalName))}>"; +} + +sealed record ArraySignatureType (SignatureType Element, int Rank, bool IsVector) : SignatureType +{ + public override string FullName => Element.FullName + (IsVector ? "[]" : $"[{new string (',', Rank - 1)}]"); + public override string CanonicalName => Element.CanonicalName + (IsVector ? "[]" : $"[{new string (',', Rank - 1)}]"); +} + +sealed record ByReferenceSignatureType (SignatureType Element) : SignatureType +{ + public override string FullName => Element.FullName + "&"; + public override string CanonicalName => Element.CanonicalName + "&"; +} + +sealed record PointerSignatureType (SignatureType Element) : SignatureType +{ + public override string FullName => Element.FullName + "*"; + public override string CanonicalName => Element.CanonicalName + "*"; +} + +sealed record GenericParameterSignatureType (string Name, int Index, bool IsMethodParameter) : SignatureType +{ + public override string FullName => Name; + public override string CanonicalName => IsMethodParameter ? $"!!{Index}" : $"!{Index}"; +} + +sealed record FunctionPointerSignatureType () : SignatureType +{ + public override string FullName => "method"; + public override string CanonicalName => "method"; +} + +sealed record GenericContext (string [] TypeParameters, string [] MethodParameters) +{ + public static readonly GenericContext Empty = new ([], []); +} + +sealed class SignatureTypeProvider : ISignatureTypeProvider +{ + readonly string assemblyName; + + /// The assembly whose metadata is decoded; it declares the types referenced by definition. + public SignatureTypeProvider (string assemblyName) => this.assemblyName = assemblyName; + + public SignatureType GetArrayType (SignatureType elementType, ArrayShape shape) => new ArraySignatureType (elementType, shape.Rank, IsVector: false); + public SignatureType GetByReferenceType (SignatureType elementType) => new ByReferenceSignatureType (elementType); + public SignatureType GetFunctionPointerType (MethodSignature signature) => new FunctionPointerSignatureType (); + public SignatureType GetGenericInstantiation (SignatureType genericType, ImmutableArray typeArguments) => new GenericInstanceSignatureType (genericType, typeArguments); + public SignatureType GetGenericMethodParameter (GenericContext genericContext, int index) + => new GenericParameterSignatureType (index < genericContext.MethodParameters.Length ? genericContext.MethodParameters [index] : $"!!{index}", index, IsMethodParameter: true); + public SignatureType GetGenericTypeParameter (GenericContext genericContext, int index) + => new GenericParameterSignatureType (index < genericContext.TypeParameters.Length ? genericContext.TypeParameters [index] : $"!{index}", index, IsMethodParameter: false); + public SignatureType GetModifiedType (SignatureType modifier, SignatureType unmodifiedType, bool isRequired) => unmodifiedType; + public SignatureType GetPinnedType (SignatureType elementType) => elementType; + public SignatureType GetPointerType (SignatureType elementType) => new PointerSignatureType (elementType); + public SignatureType GetPrimitiveType (PrimitiveTypeCode typeCode) => new PrimitiveSignatureType (typeCode); + public SignatureType GetSZArrayType (SignatureType elementType) => new ArraySignatureType (elementType, 1, IsVector: true); + + public SignatureType GetTypeFromDefinition (MetadataReader reader, TypeDefinitionHandle handle, byte rawTypeKind) + { + var definition = reader.GetTypeDefinition (handle); + var declaring = definition.GetDeclaringType (); + return new NamedSignatureType (assemblyName, reader.GetString (definition.Namespace), reader.GetString (definition.Name), + declaring.IsNil ? null : (NamedSignatureType) GetTypeFromDefinition (reader, declaring, rawTypeKind)); + } + + public SignatureType GetTypeFromReference (MetadataReader reader, TypeReferenceHandle handle, byte rawTypeKind) + { + var reference = reader.GetTypeReference (handle); + var scope = reference.ResolutionScope; + var declaring = scope.Kind == HandleKind.TypeReference + ? (NamedSignatureType) GetTypeFromReference (reader, (TypeReferenceHandle) scope, rawTypeKind) + : null; + var assembly = declaring?.Assembly ?? (scope.Kind == HandleKind.AssemblyReference + ? reader.GetString (reader.GetAssemblyReference ((AssemblyReferenceHandle) scope).Name) + : assemblyName); + return new NamedSignatureType (assembly, reader.GetString (reference.Namespace), reader.GetString (reference.Name), declaring); + } + + public SignatureType GetTypeFromSpecification (MetadataReader reader, GenericContext genericContext, TypeSpecificationHandle handle, byte rawTypeKind) + => reader.GetTypeSpecification (handle).DecodeSignature (this, genericContext); +} diff --git a/tests/TrimmingTests/TrimmingTestBase.cs b/tests/TrimmingTests/TrimmingTestBase.cs new file mode 100644 index 00000000000..3fea3b1a19c --- /dev/null +++ b/tests/TrimmingTests/TrimmingTestBase.cs @@ -0,0 +1,270 @@ +#nullable enable +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text.RegularExpressions; +using System.Threading; +using Microsoft.Build.Logging.StructuredLogger; +using BuildLog = Microsoft.Build.Logging.StructuredLogger.Build; +using NUnit.Framework; +using Xamarin.Android.Build.Tests; +using Xamarin.Android.Tasks; +using Xamarin.Android.Tools; +using Xamarin.ProjectTools; + +namespace Microsoft.Android.TrimmingTests; + +public enum TrimmingConfiguration +{ + /// CoreCLR with ILLink and TrimMode=full: every assembly, including the app's, is trimmed. + CoreClrFullTrimming, + /// NativeAOT: ILC trims and compiles every assembly. + NativeAot, + /// + /// CoreCLR with ILLink and TrimMode=partial, the CoreCLR Release default: only assemblies marked trimmable (such + /// as Mono.Android and the BCL) are trimmed, the app's own assemblies are kept whole, and trimming warnings are suppressed. + /// + CoreClrPartialTrimming, +} + +/// +/// The configurations a test runs in: all of them by default, or the ones listed. +/// +[AttributeUsage (AttributeTargets.Parameter)] +public sealed class TrimmingConfigurationsAttribute : ValuesAttribute +{ + public TrimmingConfigurationsAttribute () + : this (TrimmingConfiguration.CoreClrFullTrimming, TrimmingConfiguration.NativeAot, TrimmingConfiguration.CoreClrPartialTrimming) + { + } + + public TrimmingConfigurationsAttribute (params TrimmingConfiguration [] configurations) + : base (configurations.Cast ().ToArray ()) + { + } +} + +/// A case app that built and ran. +public sealed record TrimmedApp (string CaseFile, TrimmingConfiguration Configuration, BuildLog Build, string IntermediateDirectory); + +/// +/// Builds a single-file case app from Cases/, installs and launches it, and checks its result and its build warnings. +/// Tests check the trimming expectations the case declares with . +/// +/// +/// +/// Each case is a file-based app (#:property directives) purpose-built for one scenario, so nothing else can keep the +/// types and members under test alive. A case must declare #:property ApplicationId=..., reference the expectations +/// with #:project TrimmingTests.Expectations/TrimmingTests.Expectations.csproj, and log exactly one +/// TRIMMING_TEST_RESULT: PASS or TRIMMING_TEST_RESULT: FAIL ... line on startup. Never add trimmer descriptors, +/// rooted assemblies, or [DynamicDependency] to a case unless that is the behavior under test. A case that needs more +/// than one file lives in its own directory, Cases/<Case>/<Case>.cs, next to its Android resources, its +/// AndroidManifest.xml, or a Case.targets with MSBuild items. Cases that reproduce a reported bug link to it. +/// +/// +/// Tests in a fixture may run in parallel ([Parallelizable (ParallelScope.Children)]), also on the device: each test builds in +/// its own directory, installs its own package (ApplicationId plus the configuration), and reads only its app's logcat output. +/// Fixtures run one after another, so the one-time device setup of never runs concurrently. +/// +/// +/// requires a build without warnings, unless the test lists the expected warning codes, and a launch +/// that reports PASS. Tests then call to check [Kept], [Removed] and the +/// other expectation attributes against ILLink's output (CoreCLR) or the methods and types ILC compiled (NativeAOT mstat). +/// +/// +public abstract class TrimmingTestBase : DeviceTest +{ + const string ResultTag = "TRIMMING_TEST_RESULT:"; + const string ExpectationsProject = "TrimmingTests.Expectations"; + + [OneTimeSetUp] + public void AssertDeviceAttached () => AssertHasDevices (); + + /// Builds the case without unexpected warnings, then installs and launches it and requires it to report PASS. + /// The case file relative to the test project, e.g. Cases/GenericPeerArrayElement.cs. + protected TrimmedApp BuildAndRun (string casePath, TrimmingConfiguration configuration, string []? expectedWarnings = null) + { + var caseFile = Path.GetFileName (casePath); + var directory = Path.Combine (Root, "temp", TestName); + var source = CopyCase (casePath, directory); + // Each configuration gets its own package, so concurrent tests can install and run their apps side by side. + var packageName = $"{GetApplicationId (source)}.{configuration.ToString ().ToLowerInvariant ()}"; + var runtimeIdentifier = MonoAndroidHelper.AbiToRid (DeviceAbi); + var artifacts = Path.Combine (directory, "artifacts"); + + // App-only properties become directives: global properties would also apply to the referenced expectations project. + SetProperties (source, new Dictionary { + ["TargetFramework"] = $"{XABuildConfig.LatestDotNetTargetFramework}-android", + ["ApplicationId"] = packageName, + // File-based apps default to PublishAot=true, so always set it explicitly. + ["PublishAot"] = configuration == TrimmingConfiguration.NativeAot ? "true" : "false", + [configuration == TrimmingConfiguration.NativeAot ? "IlcGenerateMstatFile" : "TrimMode"] = configuration switch { + TrimmingConfiguration.NativeAot => "true", + TrimmingConfiguration.CoreClrPartialTrimming => "partial", + _ => "full", + }, + // Report each trimming/AOT warning instead of one IL2104/IL3053 per assembly. + ["TrimmerSingleWarn"] = "false", + // An APK can be installed with `adb install` outside the build, which keeps the build off the device. + ["AndroidPackageFormat"] = "apk", + }); + + var dotnet = new DotNetCLI (source) { ProjectDirectory = directory }; + bool built = dotnet.Build ("SignAndroidPackage", runtimeIdentifier, new [] { "Configuration=Release" }, + new [] { "--artifacts-path", $"\"{artifacts}\"" }); + var binlog = Path.Combine (directory, "SignAndroidPackage.binlog"); + var build = BinaryLog.ReadBuild (binlog); + Assert.IsTrue (built, $"{caseFile} should build. See {dotnet.ProcessLogFile}{Environment.NewLine}" + + string.Join (Environment.NewLine, build.FindChildrenRecursive ().Select (Format).Distinct ())); + AssertWarnings (build, expectedWarnings ?? [], binlog); + + var apk = Directory.GetFiles (artifacts, $"{packageName}-Signed.apk", SearchOption.AllDirectories).SingleOrDefault (); + Assert.IsNotNull (apk, $"{caseFile} should produce {packageName}-Signed.apk under {artifacts}."); + var install = RunAdbCommand ($"install -r \"{apk}\"", timeout: 120); + StringAssert.Contains ("Success", install, $"{caseFile} should install."); + try { + AssertLaunchReportsPass (caseFile, configuration, packageName, directory); + } finally { + RunAdbCommand ($"uninstall {packageName}"); + } + + return new TrimmedApp (caseFile, configuration, build, Path.Combine (artifacts, "obj", caseFile, $"release_{runtimeIdentifier}")); + } + + static string CopyCase (string casePath, string directory) + { + var source = Path.Combine (TestContext.CurrentContext.TestDirectory, casePath); + FileAssert.Exists (source, $"{casePath} should be copied next to the test assembly."); + var cases = Path.Combine (TestContext.CurrentContext.TestDirectory, "Cases"); + var caseDirectory = Path.GetDirectoryName (source) ?? throw new InvalidOperationException ($"{casePath} has no directory."); + if (Directory.Exists (directory)) { + Directory.Delete (directory, recursive: true); + } + Directory.CreateDirectory (directory); + foreach (var file in Directory.GetFiles (cases, "Directory.Build.*")) { + File.Copy (file, Path.Combine (directory, Path.GetFileName (file))); + } + CopyDirectory (Path.Combine (cases, ExpectationsProject), Path.Combine (directory, ExpectationsProject)); + // A case in its own directory (Cases//.cs) brings the files next to it, such as Android resources, + // AndroidManifest.xml, or a Case.targets with MSBuild items. + if (Path.GetFullPath (caseDirectory) == Path.GetFullPath (cases)) { + File.Copy (source, Path.Combine (directory, Path.GetFileName (source))); + } else { + CopyDirectory (caseDirectory, directory); + } + return Path.Combine (directory, Path.GetFileName (source)); + } + + static void CopyDirectory (string source, string destination) + { + foreach (var file in Directory.GetFiles (source, "*", SearchOption.AllDirectories)) { + var target = Path.Combine (destination, Path.GetRelativePath (source, file)); + Directory.CreateDirectory (Path.GetDirectoryName (target) ?? destination); + File.Copy (file, target); + } + } + + static void SetProperties (string source, IDictionary properties) + { + var lines = File.ReadAllLines (source) + .Where (line => !properties.Keys.Any (key => Regex.IsMatch (line, $@"^#:property\s+{Regex.Escape (key)}\s*="))); + File.WriteAllLines (source, properties.Select (p => $"#:property {p.Key}={p.Value}").Concat (lines)); + } + + static void AssertWarnings (BuildLog build, string [] expectedWarnings, string binlog) + { + var warnings = build.FindChildrenRecursive ().Select (w => (w.Code, Text: Format (w))).Distinct ().ToList (); + var unexpected = warnings.Where (w => !expectedWarnings.Contains (w.Code, StringComparer.Ordinal)).Select (w => w.Text).ToList (); + var missing = expectedWarnings.Where (code => !warnings.Any (w => w.Code == code)).ToList (); + Assert.IsEmpty (unexpected, $"Unexpected build warnings (pass their codes as expectedWarnings when intended). See {binlog}"); + Assert.IsEmpty (missing, $"Expected build warnings were not reported. See {binlog}"); + } + + // Streams logcat from before the launch, because the device's log buffer can drop the app's output before a later + // `logcat -d` reads it. Matches only this app's process ID and never clears logcat, so tests can share the device. + static void AssertLaunchReportsPass (string caseFile, TrimmingConfiguration configuration, string packageName, string directory) + { + var activity = RunAdbCommand ($"shell cmd package resolve-activity --brief {packageName}") + .Split ('\n', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries) + .LastOrDefault (); + Assert.IsNotNull (activity, $"{packageName} should have a launcher activity."); + + var logcat = Path.Combine (directory, "logcat.log"); + string? pid = null; + string? result = null; + MonitorAdbLogcat (line => { + // threadtime format: "