Skip to content

[Xamarin.Android.Build.Tasks] implement $(AndroidStripILAfterAOT) #8172

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

Merged
merged 14 commits into from
Aug 22, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions Documentation/guides/building-apps/build-properties.md
Original file line number Diff line number Diff line change
Expand Up @@ -1303,6 +1303,20 @@ This is only used when building `system` applications.

Support for this property was added in Xamarin.Android 11.3.

## AndroidStripILAfterAOT

A bool property that specifies whether or not the *method bodies* of AOT compiled methods will be removed.

The default value is `false`, and the method bodies of AOT compiled methods will *not* be removed.

When set to `true`, [`$(AndroidEnableProfiledAot)`](#androidenableprofiledaot) is set to `false` by default.
This means that in Release configuration builds -- in which
[`$(RunAOTCompilation)`](#runaotcompilation) is `true` by default -- AOT is enabled for *everything*.
This can result in increased app sizes. This behavior can be overridden by explicitly setting
`$(AndroidEnableProfiledAot)` to `true` within your project file.

Support for this property was added in .NET 8.

## AndroidSupportedAbis

A string property that contains a
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -123,11 +123,25 @@ They run in a context of an inner build with a single $(RuntimeIdentifier).
LLVMPath="$(_LLVMPath)"
LdName="$(_LdName)"
LdFlags="$(_LdFlags)"
CollectTrimmingEligibleMethods="$(AndroidStripILAfterAOT)"
TrimmingEligibleMethodsOutputDirectory="$(IntermediateOutputPath)tokens"
WorkingDirectory="$(MSBuildProjectDirectory)"
AotArguments="$(AndroidAotAdditionalArguments)">
<Output TaskParameter="CompiledAssemblies" ItemName="_MonoAOTCompiledAssemblies" />
<Output TaskParameter="FileWrites" ItemName="FileWrites" />
</MonoAOTCompiler>
<ILStrip
Condition=" '$(AndroidStripILAfterAOT)' == 'true' "
TrimIndividualMethods="true"
Assemblies="@(_MonoAOTCompiledAssemblies)"
DisableParallelStripping="$(_DisableParallelAot)">
<Output TaskParameter="TrimmedAssemblies" ItemName="_ILStripTrimmedAssemblies" />
</ILStrip>
<Move
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This <Move/> feels absurd to me: @(_ILStripTrimmedAssemblies) is an output parameter, so I would normally intuit/assume that %(_ILStripTrimmedAssemblies.Identity) is the file that was created. However, this <Move/> implies that %(_ILStripTrimmedAssemblies.Identity) has not in fact been created, and instead what was created is %(_ILStripTrimmedAssemblies.TrimmedAssemblyFileName), which must be moved to %(_ILStripTrimmedAssemblies.Identity).

Does this make sense to anyone? Why was <ILStrip/> defined this way?

Copy link
Member

@fanyang-mono fanyang-mono Aug 18, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The goal of ILStrip is to trim IL code away from the assemblies which were AOT'ed. However, not all AOT'ed assemblies might be trimmable. That's why we have _ILStripTrimmedAssemblies. ILStrip also doesn't overwrite existing assemblies with the trimmed ones. It is designed this way, in case %(_ILStripTrimmedAssemblies.Identity) are not the ones that you want to replace with the trimmed ones. They could be the ones which live in other directories. And ILStrip could possibly has no knowledge of that.

Here for System.Private.CoreLib.dll,
%(_ILStripTrimmedAssemblies.Identity) is <a_path>/System.Private.CoreLib.dll
%(_ILStripTrimmedAssemblies.TrimmedAssemblyFileName) is <a_path>/System.Private.CoreLib_trimmed.dll

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@fanyang-mono: how does <ILStrip/> know which method bodies it can remove? I see that the <MonoAOTCompiler/> invocation was updated to add a MonoAOTCompiler.TrimmingEligibleMethodsOutputDirectory property, but how does <ILStrip/> konw about the $(IntermediateOutputPath)tokens directory?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The output _MonoAOTCompiledAssemblies from MonoAOTCompiler has a metadata MethodTokenFile. It stores the trimmable method token for the corresponding assembly.

Condition=" '$(AndroidStripILAfterAOT)' == 'true' "
SourceFiles="@(_ILStripTrimmedAssemblies->'%(TrimmedAssemblyFileName)')"
DestinationFiles="@(_ILStripTrimmedAssemblies)"
/>
<WriteLinesToFile
File="$(_AndroidStampDirectory)_AndroidAot.stamp"
Lines="@(_MonoAOTCompiledAssemblies->'%(LibraryFile)')"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,7 @@
<_AndroidXA1029 Condition=" '$(AotAssemblies)' != '' ">true</_AndroidXA1029>
<_AndroidXA1030 Condition=" '$(RunAOTCompilation)' == 'true' and '$(PublishTrimmed)' == 'false' ">true</_AndroidXA1030>
<AotAssemblies>$(RunAOTCompilation)</AotAssemblies>
<AndroidEnableProfiledAot Condition=" '$(AndroidEnableProfiledAot)' == '' and '$(RunAOTCompilation)' == 'true' ">true</AndroidEnableProfiledAot>
<AndroidEnableProfiledAot Condition=" '$(AndroidEnableProfiledAot)' == '' and '$(RunAOTCompilation)' == 'true' and '$(AndroidStripILAfterAOT)' != 'true' ">true</AndroidEnableProfiledAot>

<!--
Runtime libraries feature switches defaults
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1973,7 +1973,7 @@ because xbuild doesn't support framework reference assemblies.

<!-- Shrink Mono.Android.dll by removing attribute only needed for GenerateJavaStubs -->
<RemoveRegisterAttribute
Condition="'$(AndroidLinkMode)' != 'None' AND '$(AndroidIncludeDebugSymbols)' != 'true'"
Condition="'$(AndroidLinkMode)' != 'None' AND '$(AndroidIncludeDebugSymbols)' != 'true' AND '$(AndroidStripILAfterAOT)' != 'true'"
ShrunkFrameworkAssemblies="@(_ShrunkAssemblies)" />

<MakeDir Directories="$(MonoAndroidIntermediateAssemblyDir)shrunk" />
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,9 @@
</ItemGroup>

<ItemGroup>
<Reference Include="Xamarin.Android.Cecil">
<HintPath>$(MicrosoftAndroidSdkOutDir)Xamarin.Android.Cecil.dll</HintPath>
</Reference>
<PackageReference Include="NodaTime" Version="2.4.5" />
<PackageReference Include="MSBuild.StructuredLogger" Version="2.1.787" />
<PackageReference Include="ICSharpCode.Decompiler" Version="7.2.1.6856" />
Expand Down
39 changes: 39 additions & 0 deletions tests/MSBuildDeviceIntegration/Tests/InstallAndRunTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
using System.Text.RegularExpressions;
using System.Xml.Linq;
using System.Xml.XPath;
using Mono.Cecil;
using NUnit.Framework;
using Xamarin.ProjectTools;

Expand Down Expand Up @@ -1075,5 +1076,43 @@ public void SupportDesugaringStaticInterfaceMethods ()
);
}

[Test]
public void EnableAndroidStripILAfterAOT ([Values (false, true)] bool profiledAOT)
{
var proj = new XamarinAndroidApplicationProject {
ProjectName = nameof (EnableAndroidStripILAfterAOT),
RootNamespace = nameof (EnableAndroidStripILAfterAOT),
IsRelease = true,
EnableDefaultItems = true,
};
proj.SetProperty("AndroidStripILAfterAOT", "true");
proj.SetProperty("AndroidEnableProfiledAot", profiledAOT.ToString ());
// So we can use Mono.Cecil to open assemblies directly
proj.SetProperty ("AndroidEnableAssemblyCompression", "false");

var builder = CreateApkBuilder ();
Assert.IsTrue (builder.Build (proj), "`dotnet build` should succeed");

var apk = Path.Combine (Root, builder.ProjectDirectory, proj.OutputPath, $"{proj.PackageName}-Signed.apk");
FileAssert.Exists (apk);
var helper = new ArchiveAssemblyHelper (apk);
Assert.IsTrue (helper.Exists ($"assemblies/{proj.ProjectName}.dll"), $"{proj.ProjectName}.dll should exist in apk!");
using (var stream = helper.ReadEntry ($"assemblies/{proj.ProjectName}.dll")) {
stream.Position = 0;
using var assembly = AssemblyDefinition.ReadAssembly (stream);
var type = assembly.MainModule.GetType ($"{proj.RootNamespace}.MainActivity");
var method = type.Methods.FirstOrDefault (p => p.Name == "OnCreate");
Assert.IsNotNull (method, $"{proj.RootNamespace}.MainActivity.OnCreate should exist!");
Assert.IsTrue (!method.HasBody || method.Body.Instructions.Count == 0, $"{proj.RootNamespace}.MainActivity.OnCreate should have no body!");
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

HasBody was true and Body.Instructions.Count was 0.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is probably expected, since I only zero'ed out method body and preserved method method header.

}

RunProjectAndAssert (proj, builder);

WaitForPermissionActivity (Path.Combine (Root, builder.ProjectDirectory, "permission-logcat.log"));
bool didLaunch = WaitForActivityToStart (proj.PackageName, "MainActivity",
Path.Combine (Root, builder.ProjectDirectory, "logcat.log"), 30);
Assert.IsTrue(didLaunch, "Activity should have started.");
}

}
}