Repository navigation
[Microsoft.Android.Build.Tasks] Add typemap rule generators #12822
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
simonrozsival
merged 6 commits into
main
from
simonrozsival-typemap-proguard-foundation
Sep 22, 2026
Merged
Changes from all commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
f49c3dd
[Microsoft.Android.Build.Tasks] Add typemap rule generators
simonrozsival b3255ec
Fix parallel typemap invalid-record tests
simonrozsival 39eed16
Generate retained rules for Java interfaces
simonrozsival 2435c57
Fix typemap generator diagnostics
simonrozsival e818df0
Fix typemap test cleanup race
simonrozsival 3ceba58
Merge origin/main into typemap ProGuard foundation
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,37 @@ | ||
| --- | ||
| title: .NET for Android error XA4327 | ||
| description: XA4327 error code | ||
| ms.date: 09/18/2026 | ||
| f1_keywords: | ||
| - "XA4327" | ||
| --- | ||
|
|
||
| # .NET for Android error XA4327 | ||
|
|
||
| ## Example message | ||
|
|
||
| ``` | ||
| error XA4327: Could not extract Java type map keys from 'typemaps.arm64-v8a.ll': ... | ||
| ``` | ||
|
|
||
| ## Issue | ||
|
|
||
| The build could not read retained Java class names from a NativeAOT object, | ||
| a CoreCLR LLVM typemap, or linked trimmable typemap assemblies. | ||
| The input is missing, unreadable, malformed, or uses an unsupported representation. | ||
| The diagnostic includes the input and the underlying failure. | ||
|
|
||
| An empty, valid typemap is supported. A failed extraction is not treated as an | ||
| empty typemap, because doing so could remove Java classes required at runtime. | ||
|
|
||
| ## Solution | ||
|
|
||
| Fix the reported input or the earlier task that produces it. If the input was | ||
| generated by .NET for Android, clean and rebuild the application. If the error | ||
| persists, [report an issue](https://github.com/dotnet/android/issues/new/choose) | ||
| with a binary build log and the affected typemap input. | ||
|
|
||
| NativeAOT object extraction also requires the Android NDK's `llvm-readobj` | ||
| and adjacent `llvm-objdump`. | ||
| Install the NDK selected by `GetAndroidDependencies`, or point | ||
| `AndroidNdkDirectory` at a complete installation. |
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,33 @@ | ||
| --- | ||
| title: .NET for Android error XA4328 | ||
| description: XA4328 error code | ||
| ms.date: 09/18/2026 | ||
| f1_keywords: | ||
| - "XA4328" | ||
| --- | ||
|
|
||
| # .NET for Android error XA4328 | ||
|
|
||
| ## Example message | ||
|
|
||
| ``` | ||
| error XA4328: Could not generate typemap ProGuard configuration from 'typemap.keys.txt': Line 1 contains an invalid retained Java class name: 'example/*'. | ||
| ``` | ||
|
|
||
| ## Issue | ||
|
|
||
| The class-only ProGuard generator could not read a retained-keys file, found | ||
| an invalid class name, received no input files, or could not write its output. | ||
| Keys must be UTF-8 Java class names using `/` as the package separator, such as | ||
| `example/Outer$Inner`. Wildcards, ProGuard directives, dotted names, type | ||
| descriptors, and typemap alias suffixes are not valid records. | ||
|
|
||
| A zero-byte input is valid and produces no class keep rules. A missing file is | ||
| an error, not an empty input. | ||
|
|
||
| ## Solution | ||
|
|
||
| Fix the reported input or output path and permissions. For files generated by | ||
| .NET for Android, clean and rebuild. If the error persists, | ||
| [report an issue](https://github.com/dotnet/android/issues/new/choose) with a | ||
| binary build log and the affected keys file. |
14 changes: 14 additions & 0 deletions
14
src/Microsoft.Android.Build.Tasks/Tasks/GenerateTypeMapMemberProguardConfiguration.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,14 @@ | ||
| using System.IO; | ||
|
|
||
| namespace Microsoft.Android.Tasks; | ||
|
|
||
| public class GenerateTypeMapMemberProguardConfiguration : GenerateTypeMapProguardConfiguration | ||
| { | ||
| public override string TaskPrefix => "GTMMPC"; | ||
|
|
||
| protected override void WriteClassRule (TextWriter writer, string name) | ||
| { | ||
| writer.WriteLine ($"-keepclassmembers class {name} {{ *; }}"); | ||
| writer.WriteLine ($"-keepclassmembers interface {name} {{ *; }}"); | ||
| } | ||
| } |
106 changes: 106 additions & 0 deletions
106
src/Microsoft.Android.Build.Tasks/Tasks/GenerateTypeMapProguardConfiguration.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,106 @@ | ||
| using System; | ||
| using System.Collections.Generic; | ||
| using System.Globalization; | ||
| using System.IO; | ||
| using System.Text; | ||
| using Microsoft.Android.Build.Tasks; | ||
| using Microsoft.Build.Framework; | ||
| using Properties = Xamarin.Android.Tasks.Properties; | ||
|
|
||
| namespace Microsoft.Android.Tasks; | ||
|
|
||
| public class GenerateTypeMapProguardConfiguration : AndroidTask | ||
| { | ||
| public override string TaskPrefix => "GTMPC"; | ||
|
|
||
| [Required] | ||
| public ITaskItem [] TypeMapKeyFiles { get; set; } = []; | ||
|
|
||
| [Required] | ||
| public string OutputFile { get; set; } = ""; | ||
|
|
||
| public override bool RunTask () | ||
| { | ||
| var classes = new SortedSet<string> (StringComparer.Ordinal); | ||
| string currentFile = ""; | ||
| try { | ||
| if (TypeMapKeyFiles.Length == 0) { | ||
| Log.LogCodedError ("XA4328", Properties.Resources.XA4328, OutputFile, Properties.Resources.XA4328_NoInputs); | ||
| return !Log.HasLoggedErrors; | ||
| } | ||
|
|
||
| foreach (var file in TypeMapKeyFiles) { | ||
| currentFile = file.ItemSpec; | ||
| using var reader = new StreamReader (currentFile, new UTF8Encoding (false, true), detectEncodingFromByteOrderMarks: false); | ||
| string? name; | ||
| int lineNumber = 0; | ||
| while ((name = reader.ReadLine ()) != null) { | ||
| lineNumber++; | ||
| if (string.IsNullOrWhiteSpace (name)) { | ||
| continue; | ||
| } | ||
| if (!IsClassName (name)) { | ||
| Log.LogCodedError ("XA4328", Properties.Resources.XA4328, currentFile, | ||
| string.Format (CultureInfo.CurrentCulture, Properties.Resources.XA4328_InvalidName, lineNumber, name)); | ||
| return !Log.HasLoggedErrors; | ||
| } | ||
| classes.Add (name.Replace ('/', '.')); | ||
| } | ||
| } | ||
|
|
||
| currentFile = OutputFile; | ||
| var directory = Path.GetDirectoryName (OutputFile); | ||
| if (directory != null && directory.Length > 0) { | ||
| Directory.CreateDirectory (directory); | ||
| } | ||
| using var writer = new StreamWriter (OutputFile, append: false, new UTF8Encoding (false)) { NewLine = "\n" }; | ||
| foreach (var name in classes) { | ||
| WriteClassRule (writer, name); | ||
| } | ||
| } catch (Exception ex) when (ex is IOException || ex is UnauthorizedAccessException || ex is DecoderFallbackException || | ||
| ex is ArgumentException || ex is NotSupportedException) { | ||
| Log.LogCodedError ("XA4328", Properties.Resources.XA4328, currentFile, ex.Message); | ||
| return !Log.HasLoggedErrors; | ||
| } | ||
| return !Log.HasLoggedErrors; | ||
| } | ||
|
|
||
| protected virtual void WriteClassRule (TextWriter writer, string name) | ||
| { | ||
| writer.WriteLine ($"-keep class {name}"); | ||
| writer.WriteLine ($"-keep interface {name}"); | ||
| } | ||
|
|
||
| internal static bool IsClassName (string name) | ||
| { | ||
| bool first = true; | ||
| for (int i = 0; i < name.Length; i++) { | ||
| if (name [i] == '/') { | ||
| if (first) { | ||
| return false; | ||
| } | ||
| first = true; | ||
| continue; | ||
| } | ||
|
|
||
| var category = CharUnicodeInfo.GetUnicodeCategory (name, i); | ||
| bool start = category == UnicodeCategory.UppercaseLetter || | ||
| category == UnicodeCategory.LowercaseLetter || | ||
| category == UnicodeCategory.TitlecaseLetter || | ||
| category == UnicodeCategory.ModifierLetter || | ||
| category == UnicodeCategory.OtherLetter || | ||
| category == UnicodeCategory.LetterNumber || | ||
| category == UnicodeCategory.CurrencySymbol || | ||
| category == UnicodeCategory.ConnectorPunctuation; | ||
| if (!start && (first || (category != UnicodeCategory.DecimalDigitNumber && | ||
| category != UnicodeCategory.NonSpacingMark && category != UnicodeCategory.SpacingCombiningMark))) { | ||
| return false; | ||
| } | ||
| if (char.IsHighSurrogate (name [i])) { | ||
| i++; | ||
| } | ||
| first = false; | ||
| } | ||
| return !first; | ||
| } | ||
| } | ||
159 changes: 159 additions & 0 deletions
159
...ks/Tests/Microsoft.Android.Build.Tasks.Tests/GenerateTypeMapProguardConfigurationTests.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,159 @@ | ||
| using System; | ||
| using System.Collections.Generic; | ||
| using System.IO; | ||
| using System.Text; | ||
| using Microsoft.Build.Framework; | ||
| using Microsoft.Build.Utilities; | ||
| using NUnit.Framework; | ||
| using Microsoft.Android.Tasks; | ||
|
|
||
| namespace Xamarin.Android.Build.Tests; | ||
|
|
||
| [TestFixture] | ||
| [Parallelizable (ParallelScope.Children)] | ||
| public class GenerateTypeMapProguardConfigurationTests : BaseTest | ||
| { | ||
| [Test] | ||
| public void UnionsClassNamesWithoutMemberOrGlobalRules () | ||
| { | ||
| var path = Path.Combine (Root, "temp", TestName); | ||
| Directory.CreateDirectory (path); | ||
| var first = Path.Combine (path, "first.keys"); | ||
| var second = Path.Combine (path, "second.keys"); | ||
| File.WriteAllText (first, "test/Outer$Inner\r\nandroid/app/Activity\r\n\r\ntest/Caf\u00e9\n", new UTF8Encoding (false)); | ||
| File.WriteAllText (second, "test/Outer$Inner\nandroid/app/Activity\ntest/\U00010428Peer\n", new UTF8Encoding (false)); | ||
| var task = new GenerateTypeMapProguardConfiguration { | ||
| BuildEngine = new MockBuildEngine (TestContext.Out), | ||
| TypeMapKeyFiles = [new TaskItem (second), new TaskItem (first)], | ||
| OutputFile = Path.Combine (path, "proguard", "classes.cfg"), | ||
| }; | ||
|
|
||
| Assert.IsTrue (task.Execute ()); | ||
| var expected = | ||
| "-keep class android.app.Activity\n-keep interface android.app.Activity\n" + | ||
| "-keep class test.Caf\u00e9\n-keep interface test.Caf\u00e9\n" + | ||
| "-keep class test.Outer$Inner\n-keep interface test.Outer$Inner\n" + | ||
| "-keep class test.\U00010428Peer\n-keep interface test.\U00010428Peer\n"; | ||
| CollectionAssert.AreEqual (new UTF8Encoding (false).GetBytes (expected), File.ReadAllBytes (task.OutputFile)); | ||
| } | ||
|
|
||
| [TestCase ("test/*", TestName = "RejectsInvalidRecord_Wildcard")] | ||
| [TestCase ("test/Foo { *; }", TestName = "RejectsInvalidRecord_ProguardBlock")] | ||
| [TestCase ("test/Foo[1]", TestName = "RejectsInvalidRecord_AliasSuffix")] | ||
| [TestCase ("test.Foo", TestName = "RejectsInvalidRecord_DottedName")] | ||
| [TestCase ("test//Foo", TestName = "RejectsInvalidRecord_DoubleSlash")] | ||
| [TestCase ("/test/Foo", TestName = "RejectsInvalidRecord_LeadingSlash")] | ||
| [TestCase ("test/Foo/", TestName = "RejectsInvalidRecord_TrailingSlash")] | ||
| [TestCase ("test/1Foo", TestName = "RejectsInvalidRecord_LeadingDigit")] | ||
| [TestCase ("test/Foo;", TestName = "RejectsInvalidRecord_DescriptorTerminator")] | ||
| [TestCase ("test/Foo #comment", TestName = "RejectsInvalidRecord_InlineComment")] | ||
| [TestCase ("-dontshrink", TestName = "RejectsInvalidRecord_Directive")] | ||
| [TestCase ("test/Foo\n-keep class **", TestName = "RejectsInvalidRecord_LineFeedInjection")] | ||
| [TestCase ("test/Foo\r-dontobfuscate", TestName = "RejectsInvalidRecord_CarriageReturnInjection")] | ||
| [TestCase ("\ufefftest/Foo", TestName = "RejectsInvalidRecord_Bom")] | ||
| [TestCase ("test/Foo\u0000", TestName = "RejectsInvalidRecord_NullCharacter")] | ||
| public void RejectsInvalidRecordsWithoutOverwritingOutput (string content) | ||
| { | ||
| var path = Path.Combine (Root, "temp", TestName); | ||
| Directory.CreateDirectory (path); | ||
| var input = Path.Combine (path, "input.keys"); | ||
| var output = Path.Combine (path, "classes.cfg"); | ||
| File.WriteAllText (input, content, new UTF8Encoding (false)); | ||
| File.WriteAllText (output, "previous output"); | ||
| var task = CreateTask (input, output); | ||
|
|
||
| Assert.IsFalse (task.Execute ()); | ||
| Assert.AreEqual ("previous output", File.ReadAllText (output)); | ||
| } | ||
|
|
||
| [Test] | ||
| public void EmptyInputOverwritesOutputAndRefreshesTimestamp () | ||
| { | ||
| var path = Path.Combine (Root, "temp", TestName); | ||
| Directory.CreateDirectory (path); | ||
| var input = Path.Combine (path, "input.keys"); | ||
| var output = Path.Combine (path, "classes.cfg"); | ||
| File.WriteAllText (input, ""); | ||
| File.WriteAllText (output, "stale"); | ||
| var old = DateTime.UtcNow.AddDays (-1); | ||
| File.SetLastWriteTimeUtc (output, old); | ||
| var task = CreateTask (input, output); | ||
|
|
||
| Assert.IsTrue (task.Execute ()); | ||
| Assert.AreEqual (0, new FileInfo (output).Length); | ||
| Assert.Greater (File.GetLastWriteTimeUtc (output), old); | ||
| File.SetLastWriteTimeUtc (output, old); | ||
| Assert.IsTrue (task.Execute ()); | ||
| Assert.Greater (File.GetLastWriteTimeUtc (output), old, "Unchanged output must still be a real incremental output."); | ||
| File.Delete (output); | ||
| Assert.IsTrue (task.Execute ()); | ||
| FileAssert.Exists (output); | ||
| } | ||
|
|
||
| [Test] | ||
| public void MissingInputIsNotAnEmptyMap () | ||
| { | ||
| var path = Path.Combine (Root, "temp", TestName); | ||
| Directory.CreateDirectory (path); | ||
| var task = CreateTask (Path.Combine (path, "missing.keys"), Path.Combine (path, "classes.cfg")); | ||
| Assert.IsFalse (task.Execute ()); | ||
| Assert.IsFalse (File.Exists (task.OutputFile)); | ||
| } | ||
|
|
||
| [Test] | ||
| public void RejectsInvalidUtf8 () | ||
| { | ||
| var path = Path.Combine (Root, "temp", TestName); | ||
| Directory.CreateDirectory (path); | ||
| var input = Path.Combine (path, "input.keys"); | ||
| File.WriteAllBytes (input, [0xff, 0xfe]); | ||
| var task = CreateTask (input, Path.Combine (path, "classes.cfg")); | ||
| Assert.IsFalse (task.Execute ()); | ||
| Assert.IsFalse (File.Exists (task.OutputFile)); | ||
| } | ||
|
|
||
| [Test] | ||
| public void NoInputsReportsOutputPath () | ||
| { | ||
| var path = Path.Combine (Root, "temp", TestName); | ||
| Directory.CreateDirectory (path); | ||
| var output = Path.Combine (path, "classes.cfg"); | ||
| var errors = new List<BuildErrorEventArgs> (); | ||
| var engine = new MockBuildEngine (TestContext.Out, errors); | ||
| var task = new GenerateTypeMapProguardConfiguration { | ||
| BuildEngine = engine, | ||
| OutputFile = output, | ||
| }; | ||
|
|
||
| Assert.IsFalse (task.Execute ()); | ||
| Assert.AreEqual (1, errors.Count); | ||
| Assert.AreEqual ("XA4328", errors [0].Code); | ||
| StringAssert.Contains (output, errors [0].Message); | ||
| } | ||
|
|
||
| [Test] | ||
| public void InvalidOutputPathReportsGenerationError () | ||
| { | ||
| var path = Path.Combine (Root, "temp", TestName); | ||
| Directory.CreateDirectory (path); | ||
| var input = Path.Combine (path, "input.keys"); | ||
| File.WriteAllText (input, "test/Foo"); | ||
| var errors = new List<BuildErrorEventArgs> (); | ||
| var engine = new MockBuildEngine (TestContext.Out, errors); | ||
| var task = new GenerateTypeMapProguardConfiguration { | ||
| BuildEngine = engine, | ||
| TypeMapKeyFiles = [new TaskItem (input)], | ||
| OutputFile = "\0", | ||
| }; | ||
|
|
||
| Assert.IsFalse (task.Execute ()); | ||
| Assert.AreEqual (1, errors.Count); | ||
| Assert.AreEqual ("XA4328", errors [0].Code); | ||
| } | ||
|
|
||
| static GenerateTypeMapProguardConfiguration CreateTask (string input, string output) => new () { | ||
| BuildEngine = new MockBuildEngine (TestContext.Out), | ||
| TypeMapKeyFiles = [new TaskItem (input)], | ||
| OutputFile = output, | ||
| }; | ||
| } |
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.
🤖 💡 Testing — Please add a focused consumer-level test that feeds the generated class and interface rules to R8 (or point to the later layer that does so). The current tests only compare strings produced by this method, so they cannot catch a directive that is well-formed text but rejected by R8 or has different keep semantics—especially the newly added
interfaceforms.Rule: Verify generated configuration with the real consumer.