-
Notifications
You must be signed in to change notification settings - Fork 528
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
[Xamarin.Android.Build.Tasks, monodroid] Marshal Method Classifier (#…
…7123) Context: e1af958 Context: #7163 Changes: dotnet/java-interop@c942ab6...fadbb82 * dotnet/java-interop@fadbb82c: [generator] Add support for @explicitInterface metadata (#1006) * dotnet/java-interop@3e4a3c4f: [Java.Interop.Tools.JavaCallableWrappers] JavaCallableMethodClassifier (#998) dotnet/java-interop@3e4a3c4f reworked how `Java.Interop.Tools.JavaCallableWrappers.JavaCallableWrapperGenerator` can be used to find JNI marshal methods. Update `Xamarin.Android.Build.Tasks.dll` to provide a `JavaCallableMethodClassifier` to `JavaCallableWrapperGenerator`, collecting Cecil `MethodDefinition` instances for JNI marshal methods which can be created at build time via LLVM Marshal Methods. Methods which cannot be created at build time include methods with `[Export]`. Once candidate LLVM marshal methods are found, the marshal method is updated to have the [`UnmanagedCallersOnlyAttribute` attribute][0], and related System.Reflection.Emit-based infrastructure such as the `Get…Handler()` methods and `cb_…` fields are removed. As with e1af958, this feature is *not* enabled by default, and remains a xamarin-android Build time configuration option. [0]:https://docs.microsoft.com/dotnet/api/system.runtime.interopservices.unmanagedcallersonlyattribute?view=net-6.0
- Loading branch information
Showing
11 changed files
with
658 additions
and
32 deletions.
There are no files selected for viewing
Submodule Java.Interop
updated
from c942ab to fadbb8
This file contains 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 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
153 changes: 153 additions & 0 deletions
153
src/Xamarin.Android.Build.Tasks/Utilities/MarshalMethodsAssemblyRewriter.cs
This file contains 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,153 @@ | ||
#if ENABLE_MARSHAL_METHODS | ||
using System; | ||
using System.Collections.Generic; | ||
using System.IO; | ||
|
||
using Java.Interop.Tools.Cecil; | ||
using Microsoft.Android.Build.Tasks; | ||
using Microsoft.Build.Utilities; | ||
using Mono.Cecil; | ||
using Xamarin.Android.Tools; | ||
|
||
namespace Xamarin.Android.Tasks | ||
{ | ||
class MarshalMethodsAssemblyRewriter | ||
{ | ||
IDictionary<string, IList<MarshalMethodEntry>> methods; | ||
ICollection<AssemblyDefinition> uniqueAssemblies; | ||
IDictionary <string, HashSet<string>> assemblyPaths; | ||
TaskLoggingHelper log; | ||
|
||
public MarshalMethodsAssemblyRewriter (IDictionary<string, IList<MarshalMethodEntry>> methods, ICollection<AssemblyDefinition> uniqueAssemblies, IDictionary <string, HashSet<string>> assemblyPaths, TaskLoggingHelper log) | ||
{ | ||
this.methods = methods ?? throw new ArgumentNullException (nameof (methods)); | ||
this.uniqueAssemblies = uniqueAssemblies ?? throw new ArgumentNullException (nameof (uniqueAssemblies)); | ||
this.assemblyPaths = assemblyPaths ?? throw new ArgumentNullException (nameof (assemblyPaths)); | ||
this.log = log ?? throw new ArgumentNullException (nameof (log)); | ||
} | ||
|
||
public void Rewrite (DirectoryAssemblyResolver resolver) | ||
{ | ||
MethodDefinition unmanagedCallersOnlyAttributeCtor = GetUnmanagedCallersOnlyAttributeConstructor (resolver); | ||
var unmanagedCallersOnlyAttributes = new Dictionary<AssemblyDefinition, CustomAttribute> (); | ||
foreach (AssemblyDefinition asm in uniqueAssemblies) { | ||
unmanagedCallersOnlyAttributes.Add (asm, CreateImportedUnmanagedCallersOnlyAttribute (asm, unmanagedCallersOnlyAttributeCtor)); | ||
} | ||
|
||
Console.WriteLine ("Adding the [UnmanagedCallersOnly] attribute to native callback methods and removing unneeded fields+methods"); | ||
foreach (IList<MarshalMethodEntry> methodList in methods.Values) { | ||
foreach (MarshalMethodEntry method in methodList) { | ||
Console.WriteLine ($"\t{method.NativeCallback.FullName} (token: 0x{method.NativeCallback.MetadataToken.RID:x})"); | ||
method.NativeCallback.CustomAttributes.Add (unmanagedCallersOnlyAttributes [method.NativeCallback.Module.Assembly]); | ||
method.Connector.DeclaringType.Methods.Remove (method.Connector); | ||
method.CallbackField?.DeclaringType.Fields.Remove (method.CallbackField); | ||
} | ||
} | ||
|
||
Console.WriteLine (); | ||
Console.WriteLine ("Rewriting assemblies"); | ||
|
||
var newAssemblyPaths = new List<string> (); | ||
foreach (AssemblyDefinition asm in uniqueAssemblies) { | ||
foreach (string path in GetAssemblyPaths (asm)) { | ||
var writerParams = new WriterParameters { | ||
WriteSymbols = (File.Exists (path + ".mdb") || File.Exists (Path.ChangeExtension (path, ".pdb"))), | ||
}; | ||
|
||
string output = $"{path}.new"; | ||
Console.WriteLine ($"\t{asm.Name} => {output}"); | ||
asm.Write (output, writerParams); | ||
newAssemblyPaths.Add (output); | ||
} | ||
} | ||
|
||
// Replace old versions of the assemblies only after we've finished rewriting without issues, otherwise leave the new | ||
// versions around. | ||
foreach (string path in newAssemblyPaths) { | ||
string target = Path.Combine (Path.GetDirectoryName (path), Path.GetFileNameWithoutExtension (path)); | ||
MoveFile (path, target); | ||
|
||
string source = Path.ChangeExtension (path, ".pdb"); | ||
if (File.Exists (source)) { | ||
target = Path.ChangeExtension (Path.Combine (Path.GetDirectoryName (source), Path.GetFileNameWithoutExtension (source)), ".pdb"); | ||
|
||
MoveFile (source, target); | ||
} | ||
|
||
source = $"{path}.mdb"; | ||
if (File.Exists (source)) { | ||
target = Path.ChangeExtension (path, ".mdb"); | ||
MoveFile (source, target); | ||
} | ||
} | ||
|
||
Console.WriteLine (); | ||
Console.WriteLine ("Method tokens:"); | ||
foreach (IList<MarshalMethodEntry> methodList in methods.Values) { | ||
foreach (MarshalMethodEntry method in methodList) { | ||
Console.WriteLine ($"\t{method.NativeCallback.FullName} (token: 0x{method.NativeCallback.MetadataToken.RID:x})"); | ||
} | ||
} | ||
|
||
void MoveFile (string source, string target) | ||
{ | ||
Console.WriteLine ($"Moving '{source}' => '{target}'"); | ||
Files.CopyIfChanged (source, target); | ||
try { | ||
File.Delete (source); | ||
} catch (Exception ex) { | ||
log.LogWarning ($"Unable to delete source file '{source}' when moving it to '{target}'"); | ||
} | ||
} | ||
} | ||
|
||
ICollection<string> GetAssemblyPaths (AssemblyDefinition asm) | ||
{ | ||
if (!assemblyPaths.TryGetValue (asm.Name.Name, out HashSet<string> paths)) { | ||
throw new InvalidOperationException ($"Unable to determine file path for assembly '{asm.Name.Name}'"); | ||
} | ||
|
||
return paths; | ||
} | ||
|
||
MethodDefinition GetUnmanagedCallersOnlyAttributeConstructor (DirectoryAssemblyResolver resolver) | ||
{ | ||
AssemblyDefinition asm = resolver.Resolve ("System.Runtime.InteropServices"); | ||
TypeDefinition unmanagedCallersOnlyAttribute = null; | ||
foreach (ModuleDefinition md in asm.Modules) { | ||
foreach (ExportedType et in md.ExportedTypes) { | ||
if (!et.IsForwarder) { | ||
continue; | ||
} | ||
|
||
if (String.Compare ("System.Runtime.InteropServices.UnmanagedCallersOnlyAttribute", et.FullName, StringComparison.Ordinal) != 0) { | ||
continue; | ||
} | ||
|
||
unmanagedCallersOnlyAttribute = et.Resolve (); | ||
break; | ||
} | ||
} | ||
|
||
if (unmanagedCallersOnlyAttribute == null) { | ||
throw new InvalidOperationException ("Unable to find the System.Runtime.InteropServices.UnmanagedCallersOnlyAttribute type"); | ||
} | ||
|
||
foreach (MethodDefinition md in unmanagedCallersOnlyAttribute.Methods) { | ||
if (!md.IsConstructor) { | ||
continue; | ||
} | ||
|
||
return md; | ||
} | ||
|
||
throw new InvalidOperationException ("Unable to find the System.Runtime.InteropServices.UnmanagedCallersOnlyAttribute type constructor"); | ||
} | ||
|
||
CustomAttribute CreateImportedUnmanagedCallersOnlyAttribute (AssemblyDefinition targetAssembly, MethodDefinition unmanagedCallersOnlyAtributeCtor) | ||
{ | ||
return new CustomAttribute (targetAssembly.MainModule.ImportReference (unmanagedCallersOnlyAtributeCtor)); | ||
} | ||
} | ||
} | ||
#endif |
Oops, something went wrong.