Skip to content
Merged
Show file tree
Hide file tree
Changes from 5 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
Original file line number Diff line number Diff line change
@@ -0,0 +1,154 @@
using NUnit.Framework;
using Xamarin.ProjectTools;

namespace Xamarin.Android.Build.Tests;

[TestFixture]
public class DexUtilsTests
{
const string Annotation = "Landroid/webkit/JavascriptInterface;";
const string ClassName = "Lexample/Target;";
const string Method = "report";

[Test]
public void RuntimeMethodAnnotationMatchesExactClassAndMethod ()
{
const string output = """
Class #0 annotations:
Annotations on field #0 'report'
VISIBILITY_RUNTIME Landroid/webkit/JavascriptInterface;
Annotations on method #1 'other'
VISIBILITY_RUNTIME Landroid/webkit/JavascriptInterface;
Class #0 -
Class descriptor : 'Lexample/Other;'
Class #1 annotations:
Annotations on method #2 'report' parameters
VISIBILITY_RUNTIME Landroid/webkit/JavascriptInterface;
Annotations on method #2 'report'
VISIBILITY_RUNTIME Landroid/webkit/JavascriptInterface;
Class #1 -
Class descriptor : 'Lexample/Target;'
""";

Assert.IsTrue (ContainsAnnotation ("\t" + output.Replace ("\n", " \r\n\t")));
}

[Test]
public void RuntimeMethodAnnotationRejectsFieldAndParameterAnnotations ()
{
const string output = """
Class #0 annotations:
Annotations on field #0 'report'
VISIBILITY_RUNTIME Landroid/webkit/JavascriptInterface;
Annotations on method #1 'report' parameters
VISIBILITY_RUNTIME Landroid/webkit/JavascriptInterface;
Class #0 -
Class descriptor : 'Lexample/Target;'
""";

Assert.IsFalse (ContainsAnnotation (output));
}

[Test]
public void RuntimeMethodAnnotationRejectsOtherClass ()
{
const string output = """
Class #0 annotations:
Annotations on method #1 'report'
VISIBILITY_RUNTIME Landroid/webkit/JavascriptInterface;
Class #0 -
Class descriptor : 'Lexample/Other;'
Class #1 -
Class descriptor : 'Lexample/Target;'
""";

Assert.IsFalse (ContainsAnnotation (output));
}

[Test]
public void RuntimeMethodAnnotationRejectsOtherVisibility ()
{
const string output = """
Class #0 annotations:
Annotations on method #1 'report'
VISIBILITY_BUILD Landroid/webkit/JavascriptInterface;
VISIBILITY_SYSTEM Landroid/webkit/JavascriptInterface;
Class #0 -
Class descriptor : 'Lexample/Target;'
""";

Assert.IsFalse (ContainsAnnotation (output));
}

[Test]
public void RuntimeMethodAnnotationRejectsZeroAnnotations ()
{
const string output = """
Class #0 -
Class descriptor : 'Lexample/Target;'
""";

Assert.IsFalse (ContainsAnnotation (output));
}

[Test]
public void RuntimeMethodAnnotationRejectsTruncatedBlock ()
{
const string output = """
Class #0 annotations:
Annotations on method #1 'report'
VISIBILITY_RUNTIME Landroid/webkit/JavascriptInterface;
""";

Assert.IsFalse (ContainsAnnotation (output));
}

[Test]
public void RuntimeMethodAnnotationDoesNotTransferAcrossMalformedClasses ()
{
const string output = """
Class #0 annotations:
Annotations on method #1 'report'
VISIBILITY_RUNTIME Landroid/webkit/JavascriptInterface;
Class #1 -
Class descriptor : 'Lexample/Target;'
""";

Assert.IsFalse (ContainsAnnotation (output));
}

[Test]
public void RuntimeMethodAnnotationMatchesDescriptorBeforeAnnotation ()
{
const string output = """
Class #0 -
Class descriptor : 'Lexample/Target;'
Class #0 annotations:
Annotations on method #1 'report'
VISIBILITY_RUNTIME Landroid/webkit/JavascriptInterface;
""";

Assert.IsTrue (ContainsAnnotation (output));
}

[Test]
public void RuntimeMethodAnnotationMatchesDuplicateMethodName ()
{
const string output = """
Class #0 annotations:
Annotations on method #1 'report'
VISIBILITY_BUILD Landroid/webkit/JavascriptInterface;
Annotations on method #2 'report'
VISIBILITY_RUNTIME Landroid/webkit/JavascriptInterface;
Class #0 -
Class descriptor : 'Lexample/Target;'
""";

Assert.IsTrue (ContainsAnnotation (output));
}

static bool ContainsAnnotation (string output)
{
return DexUtils.ContainsRuntimeMethodAnnotation (output.Split ('\n'), ClassName, Method, Annotation);
}
}
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
Expand Down Expand Up @@ -103,7 +105,113 @@ public static bool ContainsClassWithMethod (string className, string method, str
return hasType;
}

static void DexDump (DataReceivedEventHandler handler, string dexFile, string androidSdkDirectory)
/// <summary>
/// Runs the dexdump command to see if a method has a runtime-visible annotation
/// </summary>
/// <param name="className">A Java class name of the form 'Landroid/app/ActivityTracker;'</param>
/// <param name="method">A Java method name of the form 'foo'. If overloaded, any overload may match because dexdump annotation headers omit signatures.</param>
/// <param name="annotationType">A Java annotation type of the form 'Landroid/webkit/JavascriptInterface;'</param>
public static bool ContainsRuntimeMethodAnnotation (string className, string method, string annotationType, string dexFile, string androidSdkDirectory)
{
var parser = new RuntimeMethodAnnotationParser (className, method, annotationType);
DataReceivedEventHandler handler = (s, e) => parser.ProcessLine (e.Data);
DexDump (handler, dexFile, androidSdkDirectory, showAnnotations: true);
return parser.ContainsAnnotation;
}

/// <summary>
/// Checks supplied dexdump -a output for a runtime-visible method annotation
/// </summary>
public static bool ContainsRuntimeMethodAnnotation (IEnumerable<string> dexDumpOutput, string className, string method, string annotationType)
{
ArgumentNullException.ThrowIfNull (dexDumpOutput);
var parser = new RuntimeMethodAnnotationParser (className, method, annotationType);
foreach (string line in dexDumpOutput) {
parser.ProcessLine (line);
}
return parser.ContainsAnnotation;
}

sealed class RuntimeMethodAnnotationParser
{
const string classDescriptorPrefix = "Class descriptor : '";
const string classPrefix = "Class #";
const string classAnnotationsSuffix = " annotations:";
const string methodAnnotationPrefix = "Annotations on method ";
readonly string classDescriptor;
readonly string methodAnnotationSuffix;
readonly string runtimeAnnotation;
readonly HashSet<int> annotatedClasses = new HashSet<int> ();
readonly HashSet<int> targetClasses = new HashSet<int> ();
int? annotationClassIndex;
int? descriptorClassIndex;
bool inMethodAnnotations;

public bool ContainsAnnotation { get; private set; }

public RuntimeMethodAnnotationParser (string className, string method, string annotationType)
{
classDescriptor = $"{classDescriptorPrefix}{className}'";
methodAnnotationSuffix = $"'{method}'";
runtimeAnnotation = $"VISIBILITY_RUNTIME {annotationType}";
}

public void ProcessLine (string? data)
{
if (data == null) {
return;
}
string line = data.Trim ();
if (line.StartsWith (classPrefix, StringComparison.Ordinal)) {
if (!TryGetClassIndex (line, out int classIndex)) {
ResetPendingClass ();
return;
}
if (line.EndsWith (classAnnotationsSuffix, StringComparison.Ordinal)) {
ResetPendingClass ();
annotationClassIndex = classIndex;
} else if (line.EndsWith ("-", StringComparison.Ordinal)) {
descriptorClassIndex = classIndex;
} else {
ResetPendingClass ();
}
} else if (line.StartsWith ("Annotations on ", StringComparison.Ordinal)) {
inMethodAnnotations = annotationClassIndex.HasValue &&
line.StartsWith (methodAnnotationPrefix, StringComparison.Ordinal) &&
line.EndsWith (methodAnnotationSuffix, StringComparison.Ordinal);
} else if (annotationClassIndex is int annotatedClassIndex &&
inMethodAnnotations &&
line.Equals (runtimeAnnotation, StringComparison.Ordinal)) {
annotatedClasses.Add (annotatedClassIndex);
ContainsAnnotation |= targetClasses.Contains (annotatedClassIndex);
} else if (line.StartsWith (classDescriptorPrefix, StringComparison.Ordinal)) {
if (descriptorClassIndex is int targetClassIndex &&
line.Equals (classDescriptor, StringComparison.Ordinal)) {
targetClasses.Add (targetClassIndex);
ContainsAnnotation |= annotatedClasses.Contains (targetClassIndex);
}
ResetPendingClass ();
}
}

static bool TryGetClassIndex (string line, out int classIndex)
{
int indexEnd = line.IndexOf (' ', classPrefix.Length);
classIndex = 0;
return indexEnd > classPrefix.Length &&
int.TryParse (line.Substring (classPrefix.Length, indexEnd - classPrefix.Length),
NumberStyles.None, CultureInfo.InvariantCulture, out classIndex);
}

void ResetPendingClass ()
{
annotationClassIndex = null;
descriptorClassIndex = null;
inMethodAnnotations = false;
}
}

static void DexDump (DataReceivedEventHandler handler, string dexFile, string androidSdkDirectory, bool showAnnotations = false)
{
var androidSdk = new AndroidSdkInfo ((l, m) => {
Console.WriteLine ($"{l}: {m}");
Expand All @@ -118,25 +226,34 @@ static void DexDump (DataReceivedEventHandler handler, string dexFile, string an

var psi = new ProcessStartInfo {
FileName = Path.Combine (buildToolsPath, "dexdump"),
Arguments = Path.GetFileName (dexFile),
CreateNoWindow = true,
WindowStyle = ProcessWindowStyle.Hidden,
UseShellExecute = false,
RedirectStandardError = true,
RedirectStandardOutput = true,
WorkingDirectory = Path.GetDirectoryName (dexFile),
};
var errors = new StringBuilder ();
if (showAnnotations) {
psi.ArgumentList.Add ("-a");
}
psi.ArgumentList.Add (Path.GetFileName (dexFile));
using (var p = new Process { StartInfo = psi }) {
p.ErrorDataReceived += handler;
p.ErrorDataReceived += (s, e) => {
if (e.Data != null) {
errors.AppendLine (e.Data);
}
};
p.OutputDataReceived += handler;

p.Start ();
p.BeginErrorReadLine ();
p.BeginOutputReadLine ();
p.WaitForExit ();

if (p.ExitCode != 0)
throw new Exception ($"'{psi.FileName} {psi.Arguments}' exited with code: {p.ExitCode}");
if (p.ExitCode != 0) {
throw new Exception ($"'{psi.FileName} {string.Join (" ", psi.ArgumentList)}' exited with code: {p.ExitCode}{Environment.NewLine}{errors.ToString ().TrimEnd ()}");
}
}
}
}
Expand Down
Loading
Loading