-
Notifications
You must be signed in to change notification settings - Fork 571
Replace AssemblyStore compression algorithm LZ4 with Zstd #11730
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
Changes from all commits
Commits
Show all changes
15 commits
Select commit
Hold shift + click to select a range
dbf0f8f
Initial plan
Copilot 6850ac9
Replace AssemblyStore LZ4 compression with Zstd
Copilot ed3ba4c
Update CoreCLR APK size descriptors
simonrozsival d05c82a
Use LibraryImport in Zstd tools
simonrozsival 15c5588
Use BCL ZstandardDecoder in tools
simonrozsival 7b59da5
Inline ZstandardDecoder call
simonrozsival 78d6a04
Address review feedback for Zstd compression changes
Copilot 46e5591
Update CoreCLR apkdesc baselines from CI build 1482888
simonrozsival d9a8b0c
Fix Zstd.Compress doc to match actual compression level
simonrozsival 34136f3
Merge remote-tracking branch 'origin/main' into copilot/replace-lz4-w…
simonrozsival 052e86e
Use BCL ZstandardEncoder in a net11.0 CompressAssemblies task
simonrozsival f5a8bac
Run CompressAssemblies in-process on .NET MSBuild
simonrozsival 1b14216
Keep the two Build.Tasks assemblies independent
simonrozsival 71c0a14
Use file-scoped namespaces in new Build.Tasks files
simonrozsival 1ceb15d
Update CoreCLR apkdesc baseline for Zstd assembly store
simonrozsival File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
39 changes: 39 additions & 0 deletions
39
src/Microsoft.Android.Build.Tasks/Microsoft.Android.Build.Tasks.csproj
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,39 @@ | ||
| <Project Sdk="Microsoft.NET.Sdk"> | ||
| <Import Project="..\..\Configuration.props" /> | ||
|
|
||
| <!-- | ||
| This assembly hosts MSBuild tasks that require .NET (net11.0) APIs that are not available in | ||
| netstandard2.0, so they cannot live in Xamarin.Android.Build.Tasks.dll (which multi-targets | ||
| netstandard2.0 to run on both .NET Framework and .NET MSBuild). Tasks here are imported with | ||
| <UsingTask ... Runtime="NET" TaskFactory="TaskHostFactory" /> so they run out-of-process on .NET. | ||
| Keep this assembly small and self-contained: link only the minimal helpers it needs. | ||
| --> | ||
| <PropertyGroup> | ||
| <TargetFramework>$(DotNetTargetFramework)</TargetFramework> | ||
| <RootNamespace>Microsoft.Android.Tasks</RootNamespace> | ||
| <Nullable>enable</Nullable> | ||
| <WarningsAsErrors>Nullable</WarningsAsErrors> | ||
| <OutputPath>$(MicrosoftAndroidSdkOutDir)</OutputPath> | ||
| <AppendTargetFrameworkToOutputPath>false</AppendTargetFrameworkToOutputPath> | ||
| <SignAssembly>true</SignAssembly> | ||
| <AssemblyOriginatorKeyFile>..\..\product.snk</AssemblyOriginatorKeyFile> | ||
| </PropertyGroup> | ||
|
|
||
| <!-- Microsoft.Build.* references flow transitively from Microsoft.Android.Build.BaseTasks. --> | ||
| <ItemGroup> | ||
| <ProjectReference Include="..\..\external\xamarin-android-tools\src\Microsoft.Android.Build.BaseTasks\Microsoft.Android.Build.BaseTasks.csproj" /> | ||
| </ItemGroup> | ||
|
|
||
| <!-- | ||
| Link the shared Resources so the XA#### messages stay localized. The linked Resources.Designer.cs | ||
| resolves strings via ResourceManager ("Xamarin.Android.Tasks.Properties.Resources"), so pin the | ||
| embedded resource's name to match even though RootNamespace differs. | ||
| --> | ||
| <ItemGroup> | ||
| <Compile Include="..\Xamarin.Android.Build.Tasks\Properties\Resources.Designer.cs" Link="Properties\Resources.Designer.cs" /> | ||
| <EmbeddedResource Include="..\Xamarin.Android.Build.Tasks\Properties\Resources.resx" Link="Properties\Resources.resx"> | ||
| <ManifestResourceName>Xamarin.Android.Tasks.Properties.Resources</ManifestResourceName> | ||
| </EmbeddedResource> | ||
| </ItemGroup> | ||
|
|
||
| </Project> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
99 changes: 99 additions & 0 deletions
99
src/Microsoft.Android.Build.Tasks/Utilities/AssemblyCompressor.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,99 @@ | ||
| #nullable enable | ||
| using System; | ||
| using System.Buffers; | ||
| using System.IO; | ||
| using System.IO.Compression; | ||
|
|
||
| using Microsoft.Build.Utilities; | ||
|
|
||
| namespace Microsoft.Android.Tasks; | ||
|
|
||
| /// <summary> | ||
| /// Compresses assemblies with Zstandard before they are placed in the AssemblyStore. | ||
| /// The native runtime decompresses them at assembly load time. The 12-byte header | ||
| /// (magic / descriptor index / uncompressed length) is read back by the runtime and by | ||
| /// the diagnostic tools; the reader-side helpers live in <c>AssemblyCompression</c> in | ||
| /// Xamarin.Android.Build.Tasks. | ||
| /// </summary> | ||
| static class AssemblyCompressor | ||
| { | ||
| const uint CompressedDataMagic = 0x535A4158; // 'XAZS', little-endian | ||
|
|
||
| static readonly ArrayPool<byte> bytePool = ArrayPool<byte>.Shared; | ||
|
|
||
| enum CompressionResult | ||
| { | ||
| Success, | ||
| EncodingFailed, | ||
| } | ||
|
|
||
| public static bool TryCompress (TaskLoggingHelper log, string sourceAssembly, string destinationAssembly, uint descriptorIndex) | ||
| { | ||
| CompressionResult result = Compress (sourceAssembly, destinationAssembly, descriptorIndex); | ||
|
|
||
| if (result != CompressionResult.Success) { | ||
| log.LogMessage ($"Failed to compress {sourceAssembly}"); | ||
| return false; | ||
| } | ||
|
|
||
| return true; | ||
| } | ||
|
|
||
| static CompressionResult Compress (string sourcePath, string outputFilePath, uint descriptorIndex) | ||
| { | ||
| var outputDirectory = Path.GetDirectoryName (outputFilePath); | ||
| if (string.IsNullOrEmpty (outputDirectory)) | ||
| throw new ArgumentException ("must not be null or empty", nameof (outputFilePath)); | ||
|
|
||
| Directory.CreateDirectory (outputDirectory); | ||
|
|
||
| var fi = new FileInfo (sourcePath); | ||
| if (!fi.Exists) | ||
| throw new InvalidOperationException ($"File '{sourcePath}' does not exist"); | ||
|
|
||
| int fileSize = checked ((int) fi.Length); | ||
|
|
||
| byte[]? sourceBytes = null; | ||
| byte[]? destBytes = null; | ||
| try { | ||
| sourceBytes = bytePool.Rent (fileSize); | ||
| int bytesRead = 0; | ||
| using (var fs = File.Open (sourcePath, FileMode.Open, FileAccess.Read, FileShare.Read)) { | ||
| while (bytesRead < fileSize) { | ||
| int read = fs.Read (sourceBytes, bytesRead, fileSize - bytesRead); | ||
| if (read == 0) | ||
| break; | ||
|
|
||
| bytesRead += read; | ||
| } | ||
| } | ||
|
|
||
| if (bytesRead != fileSize) | ||
| return CompressionResult.EncodingFailed; | ||
|
|
||
| long maxOutputSize = ZstandardEncoder.GetMaxCompressedLength (bytesRead); | ||
| if (maxOutputSize <= 0 || maxOutputSize > int.MaxValue) | ||
| return CompressionResult.EncodingFailed; | ||
|
|
||
| destBytes = bytePool.Rent ((int) maxOutputSize); | ||
| if (!ZstandardEncoder.TryCompress (sourceBytes.AsSpan (0, bytesRead), destBytes, out int encodedLength)) | ||
| return CompressionResult.EncodingFailed; | ||
|
|
||
| using (var fs = File.Open (outputFilePath, FileMode.Create, FileAccess.Write, FileShare.Read)) | ||
| using (var bw = new BinaryWriter (fs)) { | ||
| bw.Write (CompressedDataMagic); // magic | ||
| bw.Write (descriptorIndex); // index into runtime array of descriptors | ||
| bw.Write (checked ((uint) fi.Length)); // file size before compression | ||
| bw.Write (destBytes, 0, encodedLength); | ||
| bw.Flush (); | ||
| } | ||
| } finally { | ||
| if (sourceBytes != null) | ||
| bytePool.Return (sourceBytes); | ||
| if (destBytes != null) | ||
| bytePool.Return (destBytes); | ||
| } | ||
|
|
||
| return CompressionResult.Success; | ||
| } | ||
| } |
70 changes: 70 additions & 0 deletions
70
src/Microsoft.Android.Build.Tasks/Utilities/ReferenceAssemblyChecker.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,70 @@ | ||
| #nullable enable | ||
| using System.IO; | ||
| using System.Reflection.Metadata; | ||
| using System.Reflection.PortableExecutable; | ||
|
|
||
| using Microsoft.Android.Build.Tasks; | ||
| using Microsoft.Build.Framework; | ||
| using Microsoft.Build.Utilities; | ||
| using Properties = Xamarin.Android.Tasks.Properties; | ||
|
|
||
| namespace Microsoft.Android.Tasks; | ||
|
|
||
| /// <summary> | ||
| /// Minimal reference-assembly detection for <see cref="CompressAssemblies"/>. This mirrors | ||
| /// <c>MonoAndroidHelper.LogIfReferenceAssembly</c> in Xamarin.Android.Build.Tasks, but is | ||
| /// duplicated here to keep this net11.0 assembly self-contained. | ||
| /// </summary> | ||
| static class ReferenceAssemblyChecker | ||
| { | ||
| public static bool LogIfReferenceAssembly (ITaskItem assembly, TaskLoggingHelper log) | ||
| { | ||
| if (IsReferenceAssembly (assembly.ItemSpec, log)) { | ||
| log.LogCodedWarning ("XA0107", assembly.ItemSpec, 0, Properties.Resources.XA0107, assembly.ItemSpec); | ||
| return true; | ||
| } | ||
|
|
||
| return false; | ||
| } | ||
|
|
||
| static bool IsReferenceAssembly (string assembly, TaskLoggingHelper log) | ||
| { | ||
| using var stream = File.OpenRead (assembly); | ||
| using var pe = new PEReader (stream); | ||
| if (!pe.HasMetadata) { | ||
| log.LogDebugMessage ($"Skipping non-.NET assembly: {assembly}"); | ||
| return false; | ||
| } | ||
|
|
||
| var reader = pe.GetMetadataReader (); | ||
| var assemblyDefinition = reader.GetAssemblyDefinition (); | ||
| foreach (var handle in assemblyDefinition.GetCustomAttributes ()) { | ||
| var attribute = reader.GetCustomAttribute (handle); | ||
| var attributeName = GetCustomAttributeFullName (reader, attribute); | ||
| if (attributeName == "System.Runtime.CompilerServices.ReferenceAssemblyAttribute") | ||
| return true; | ||
| } | ||
|
|
||
| return false; | ||
| } | ||
|
|
||
| static string? GetCustomAttributeFullName (MetadataReader reader, CustomAttribute attribute) | ||
| { | ||
| switch (attribute.Constructor.Kind) { | ||
| case HandleKind.MemberReference: { | ||
| var ctor = reader.GetMemberReference ((MemberReferenceHandle) attribute.Constructor); | ||
| if (ctor.Parent.Kind != HandleKind.TypeReference) | ||
| return null; | ||
| var type = reader.GetTypeReference ((TypeReferenceHandle) ctor.Parent); | ||
| return reader.GetString (type.Namespace) + "." + reader.GetString (type.Name); | ||
| } | ||
| case HandleKind.MethodDefinition: { | ||
| var ctor = reader.GetMethodDefinition ((MethodDefinitionHandle) attribute.Constructor); | ||
| var type = reader.GetTypeDefinition (ctor.GetDeclaringType ()); | ||
| return reader.GetString (type.Namespace) + "." + reader.GetString (type.Name); | ||
| } | ||
| default: | ||
| return null; | ||
| } | ||
| } | ||
| } | ||
27 changes: 27 additions & 0 deletions
27
src/Microsoft.Android.Build.Tasks/Utilities/TaskItemExtensions.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,27 @@ | ||
| #nullable enable | ||
| using Microsoft.Android.Build.Tasks; | ||
| using Microsoft.Build.Framework; | ||
| using Microsoft.Build.Utilities; | ||
| using Properties = Xamarin.Android.Tasks.Properties; | ||
|
|
||
| namespace Microsoft.Android.Tasks; | ||
|
|
||
| /// <summary> | ||
| /// Minimal <see cref="ITaskItem"/> helpers for <see cref="CompressAssemblies"/>, duplicated | ||
| /// here to keep this net11.0 assembly self-contained (the full versions live in | ||
| /// <c>ITaskItemExtensions</c> in Xamarin.Android.Build.Tasks). | ||
| /// </summary> | ||
| static class TaskItemExtensions | ||
| { | ||
| public static bool TryGetRequiredMetadata (this ITaskItem item, string itemName, string name, TaskLoggingHelper log, out string value) | ||
| { | ||
| value = item.GetMetadata (name); | ||
|
|
||
| if (string.IsNullOrWhiteSpace (value)) { | ||
| log.LogCodedError ("XA4234", Properties.Resources.XA4234, itemName, item.ItemSpec, name); | ||
| return false; | ||
| } | ||
|
|
||
| return true; | ||
| } | ||
| } |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🤖 💡 Code organization —
ReferenceAssemblyChecker(mirrorsMonoAndroidHelper.IsReferenceAssembly/LogIfReferenceAssembly),TaskItemExtensions.TryGetRequiredMetadata(mirrorsITaskItemExtensions), and theCompressedDataMagicconstant are all forked from Xamarin.Android.Build.Tasks. The duplication is honestly documented, but the copies will silently drift if the XA0107/XA4234 logic changes upstream. This csproj already source-linksResources.Designer.csvia<Compile Include="..\Xamarin.Android.Build.Tasks\...\Resources.Designer.cs" Link=... />, so the same<Compile Link>trick could share these small helpers instead of copying them (the magic constant especially is a one-liner worth centralizing). Reasonable to keep as-is given the netstandard2.0 → net11.0 split, but a good follow-up.{Rule: Centralize duplicate algorithms — duplication is a bug farm (Postmortem
#54)}