Skip to content

Commit

Permalink
Browse files Browse the repository at this point in the history
[Xamarin.Android.Build.Tasks] Don't package empty AOT-d DSOs (#6477)
Fixes: #3932

Profiled AOT tends to produce a number of "empty" `.so` shared
libraries because the profile names only a handful of types from a
handful of assemblies and the AOT compiler in Mono currently doesn't
support not outputting the `.so` in such cases.

This has the unfortunate effect that an application may have a large
number of such empty `.so` libraries and each of them will have to be
opened and loaded before Mono can determine that there's no code in
them and the JIT has to compile the requested types and methods.
Loading every `.so` takes a non-zero amount of time, especially if the
shared libraries aren't unpacked to the filesystem.  I've seen times
between 10-30ms to load a single shared library, which can add up to
a non-trivial amount of time wasted loading empty libraries.

This commit adds code to examine and ignore such `.so` files which
don't include any executable code.  The checks are crafted so that
only AOT-d libraries are considered for rejection.  The check is
kinda/sorta like:

	o=`llvm-readelf -a path/to/lib.so`
	if echo $o | grep mono_aot_file_info && : lib has 'mono_aot_file_info' symbol
	        echo $o | grep FUNC ; then      : lib contains executable code
	    echo "AOT'd file contains code"
	fi

If the `mono_aot_file_info` symbol isn't present, the `.so` is always
included.

Time savings are around 3ms for a Classic Xamarin.Android app and
around 10ms for a sample MAUI app on the Pixel 3 XL phone.  In the
latter case 49 shared libraries out of 120 total are rejected and not
packaged, contributing to (small, each empty DSO is between 7 and 25k)
space savings in the `.apk` in addition to slightly better startup
performance.

Update the `<ApkDiffCheckRegression/>` so that the size difference
threshold for reporting issues with `.apk` diffs is 48KB, not 50KB,
as a 50KB threshold meant that no changes were reported for
`Xamarin.Forms_Performance_Integration-Signed-Release-Profiled-Aot.apkdesc`.
Reducing the threshold to 48KB allowed us to see the result of this
optimization.
  • Loading branch information
grendello committed Nov 22, 2021
1 parent f1fe43b commit db161ae
Show file tree
Hide file tree
Showing 11 changed files with 758 additions and 656 deletions.
1 change: 1 addition & 0 deletions Directory.Build.props
Expand Up @@ -36,6 +36,7 @@
<MonoOptionsVersion>6.12.0.148</MonoOptionsVersion>
<SystemCollectionsImmutableVersion>1.7.1</SystemCollectionsImmutableVersion>
<XliffTasksVersion>1.0.0-beta.20420.1</XliffTasksVersion>
<ELFSharpVersion>2.13.1</ELFSharpVersion>
</PropertyGroup>

<!-- Properties to help us run managed assemblies on various runtimes.
Expand Down
Expand Up @@ -31,7 +31,7 @@ public class ApkDiffCheckRegression : ToolTask
protected override string ToolName => Path.GetFileName (ApkDiffTool);
protected override string GenerateFullPathToTool () => ApkDiffTool;

const int ApkSizeThreshold = 50*1024;
const int ApkSizeThreshold = 48*1024;
const int AssemblySizeThreshold = 50*1024;

StringBuilder logCopy = new StringBuilder ();
Expand Down
1 change: 1 addition & 0 deletions build-tools/create-packs/SignList.xml
Expand Up @@ -10,6 +10,7 @@
<ThirdParty Include="INIFileParser.dll" />
<ThirdParty Include="Irony.dll" />
<ThirdParty Include="K4os.Compression.LZ4.dll" />
<ThirdParty Include="ELFSharp.dll" />
<ThirdParty Include="protobuf-net.dll" />
<ThirdParty Include="SgmlReaderDll.dll" />
<ThirdParty Include="aapt2.exe" />
Expand Down
1 change: 1 addition & 0 deletions build-tools/installers/create-installers.targets
Expand Up @@ -298,6 +298,7 @@
<_MSBuildFiles Include="$(MSBuildSrcDir)\Xamarin.SourceWriter.pdb" />
<_MSBuildFiles Include="$(MSBuildSrcDir)\K4os.Compression.LZ4.dll" />
<_MSBuildFiles Include="$(MSBuildSrcDir)\K4os.Hash.xxHash.dll" />
<_MSBuildFiles Include="$(MSBuildSrcDir)\ELFSharp.dll" />
</ItemGroup>
<ItemGroup>
<_MSBuildTargetsSrcFiles Include="$(MSBuildTargetsSrcDir)\Xamarin.Android.AvailableItems.targets" />
Expand Down
Expand Up @@ -95,12 +95,11 @@ void CopyExtraBuildFiles (string destinationRoot, Context context)
void CopyExtraTestFiles (string destinationRoot, Context context)
{
Directory.CreateDirectory (destinationRoot);
var filesToCopy = new List<string> ();

var testConfigDir = Path.Combine (BuildPaths.XamarinAndroidSourceRoot, "bin", $"Test{context.Configuration}");
if (Directory.Exists (testConfigDir)) {
foreach (var fileMatch in testConfigFiles) {
filesToCopy.AddRange (Directory.GetFiles (testConfigDir, fileMatch));
Utilities.CopyFilesSimple (Directory.GetFiles (testConfigDir, fileMatch), destinationRoot, false);
}
}

Expand Down
86 changes: 86 additions & 0 deletions build-tools/xaprepare/xaprepare/ThirdPartyNotices/ELFSharp.cs
@@ -0,0 +1,86 @@
using System;
using System.Collections.Generic;
using System.IO;

namespace Xamarin.Android.Prepare
{
[TPN]
class KonradKuczynski_ELFSharp_TPN : ThirdPartyNotice
{
static readonly Uri url = new Uri ("https://elfsharp.it/");

public override string LicenseFile => String.Empty;
public override string Name => "KonradKuczynski/ELFSharp";
public override Uri SourceUrl => url;
public override string LicenseText => @"
Copyright (c) 2011 Konrad Kruczyński and other contributors
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
""Software""), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED ""AS IS"", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
This software uses ELF machine constants from the LLVM projects, whose license
is provided below:
==============================================================================
LLVM Release License
==============================================================================
University of Illinois/NCSA
Open Source License
Copyright (c) 2003-2010 University of Illinois at Urbana-Champaign.
All rights reserved.
Developed by:
LLVM Team
University of Illinois at Urbana-Champaign
http://llvm.org
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the ""Software""), to deal with
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software is furnished to do
so, subject to the following conditions:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimers.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimers in the
documentation and/or other materials provided with the distribution.
* Neither the names of the LLVM Team, University of Illinois at
Urbana-Champaign, nor the names of its contributors may be used to
endorse or promote products derived from this Software without specific
prior written permission.
THE SOFTWARE IS PROVIDED ""AS IS"", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS WITH THE
SOFTWARE.
";
public override bool Include (bool includeExternalDeps, bool includeBuildDeps) => includeExternalDeps;
}
}
7 changes: 6 additions & 1 deletion src/Xamarin.Android.Build.Tasks/Tasks/BuildApk.cs
Expand Up @@ -772,7 +772,12 @@ void AddNativeLibrary (ArchiveFileList files, string path, string abi, string ar
Log.LogCodedWarning ("XA4301", path, 0, Properties.Resources.XA4301, item.archivePath);
return;
}
files.Add (item);

if (!ELFHelper.IsEmptyAOTLibrary (Log, item.filePath)) {
files.Add (item);
} else {
Log.LogDebugMessage ($"{item.filePath} is an empty (no executable code) AOT assembly, not including it in the archive");
}
}

// This method is used only for internal warnings which will never be shown to the end user, therefore there's
Expand Down
92 changes: 92 additions & 0 deletions src/Xamarin.Android.Build.Tasks/Utilities/ELFHelper.cs
@@ -0,0 +1,92 @@
using System;
using System.IO;

using ELFSharp;
using ELFSharp.ELF;
using ELFSharp.ELF.Sections;
using Microsoft.Android.Build.Tasks;
using Microsoft.Build.Utilities;

namespace Xamarin.Android.Tasks
{
static class ELFHelper
{
public static bool IsEmptyAOTLibrary (TaskLoggingHelper log, string path)
{
if (String.IsNullOrEmpty (path) || !File.Exists (path)) {
return false;
}

try {
return IsEmptyAOTLibrary (log, path, ELFReader.Load (path));
} catch (Exception ex) {
log.LogWarning ($"Attempt to check whether '{path}' is a valid ELF file failed with exception, ignoring AOT check for the file.");
log.LogWarningFromException (ex, showStackTrace: true);
return false;
}

}

static bool IsEmptyAOTLibrary (TaskLoggingHelper log, string path, IELF elf)
{
ISymbolTable? symtab = GetSymbolTable (elf, ".dynsym");
if (symtab == null) {
// We can't be sure what the DSO is, play safe
return false;
}

bool mono_aot_file_info_found = false;
foreach (var entry in symtab.Entries) {
if (String.Compare ("mono_aot_file_info", entry.Name, StringComparison.Ordinal) == 0 && entry.Type == SymbolType.Object) {
mono_aot_file_info_found = true;
break;
}
}

if (!mono_aot_file_info_found) {
// Not a MonoVM AOT assembly
return false;
}

symtab = GetSymbolTable (elf, ".symtab");
if (symtab == null) {
// The DSO is stripped, we can't tell if there are any functions defined (.text will be present anyway)
// We perhaps **can** take a look at the .text section size, but it's not a solid check...
log.LogDebugMessage ($"{path} is an AOT assembly but without symbol table (stripped?). Including it in the archive.");
return false;
}

foreach (var entry in symtab.Entries) {
if (entry.Type == SymbolType.Function) {
return false;
}
}

return true;
}

static ISymbolTable? GetSymbolTable (IELF elf, string sectionName)
{
ISection? section = GetSection (elf, sectionName);
if (section == null) {
return null;
}

var symtab = section as ISymbolTable;
if (symtab == null) {
return null;
}

return symtab;
}

static ISection? GetSection (IELF elf, string sectionName)
{
if (!elf.TryGetSection (sectionName, out ISection section)) {
return null;
}

return section;
}
}
}
Expand Up @@ -59,6 +59,7 @@
<PackageReference Include="System.Runtime.InteropServices" Version="4.3.0" />
<PackageReference Include="XliffTasks" Version="$(XliffTasksVersion)" PrivateAssets="all" />
<PackageReference Include="K4os.Hash.xxHash" Version="1.0.6" />
<PackageReference Include="ELFSharp" Version="$(ELFSharpVersion)" />
</ItemGroup>

<ItemGroup>
Expand Down

0 comments on commit db161ae

Please sign in to comment.