-
Notifications
You must be signed in to change notification settings - Fork 569
Expand file tree
/
Copy pathAssemblyModifierPipeline.cs
More file actions
223 lines (174 loc) · 7.79 KB
/
AssemblyModifierPipeline.cs
File metadata and controls
223 lines (174 loc) · 7.79 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
#nullable enable
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Java.Interop.Tools.Cecil;
using Java.Interop.Tools.JavaCallableWrappers;
using Java.Interop.Tools.TypeNameMappings;
using Microsoft.Android.Build.Tasks;
using Microsoft.Build.Framework;
using Microsoft.Build.Utilities;
using Mono.Cecil;
using MonoDroid.Tuner;
using Xamarin.Android.Tools;
using PackageNamingPolicyEnum = Java.Interop.Tools.TypeNameMappings.PackageNamingPolicy;
namespace Xamarin.Android.Tasks;
/// <summary>
/// This task runs additional "linker steps" that are not part of ILLink. These steps
/// are run *after* the linker has run. Additionally, this task is run by
/// LinkAssembliesNoShrink to modify assemblies when ILLink is not used.
/// </summary>
public class AssemblyModifierPipeline : AndroidTask
{
public override string TaskPrefix => "AMP";
public string ApplicationJavaClass { get; set; } = "";
public string CodeGenerationTarget { get; set; } = "";
public bool Debug { get; set; }
[Required]
public ITaskItem [] DestinationFiles { get; set; } = [];
public bool Deterministic { get; set; }
public bool EnableMarshalMethods { get; set; }
public bool ErrorOnCustomJavaObject { get; set; }
public string? PackageNamingPolicy { get; set; }
/// <summary>
/// Defaults to false, enables Mono.Cecil to load symbols
/// </summary>
public bool ReadSymbols { get; set; }
/// <summary>
/// These are used so we have the full list of SearchDirectories
/// </summary>
[Required]
public ITaskItem [] ResolvedAssemblies { get; set; } = [];
[Required]
public ITaskItem [] ResolvedUserAssemblies { get; set; } = [];
[Required]
public ITaskItem [] SourceFiles { get; set; } = [];
/// <summary>
/// $(TargetName) would be "AndroidApp1" with no extension
/// </summary>
[Required]
public string TargetName { get; set; } = "";
protected JavaPeerStyle codeGenerationTarget;
public override bool RunTask ()
{
codeGenerationTarget = MonoAndroidHelper.ParseCodeGenerationTarget (CodeGenerationTarget);
JavaNativeTypeManager.PackageNamingPolicy = Enum.TryParse (PackageNamingPolicy, out PackageNamingPolicyEnum pnp) ? pnp : PackageNamingPolicyEnum.LowercaseCrc64;
if (SourceFiles.Length != DestinationFiles.Length)
throw new ArgumentException ("source and destination count mismatch");
var readerParameters = new ReaderParameters {
ReadSymbols = ReadSymbols,
};
Dictionary<AndroidTargetArch, Dictionary<string, ITaskItem>> perArchAssemblies = MonoAndroidHelper.GetPerArchAssemblies (ResolvedAssemblies, [], validate: false);
AssemblyPipeline? pipeline = null;
var currentArch = AndroidTargetArch.None;
for (int i = 0; i < SourceFiles.Length; i++) {
ITaskItem source = SourceFiles [i];
AndroidTargetArch sourceArch = MonoAndroidHelper.GetRequiredValidArchitecture (source);
ITaskItem destination = DestinationFiles [i];
AndroidTargetArch destinationArch = MonoAndroidHelper.GetRequiredValidArchitecture (destination);
if (sourceArch != destinationArch) {
throw new InvalidOperationException ($"Internal error: assembly '{sourceArch}' targets architecture '{sourceArch}', while destination assembly '{destination}' targets '{destinationArch}' instead");
}
// Each architecture must have a different set of context classes, or otherwise only the first instance of the assembly may be rewritten.
if (currentArch != sourceArch) {
currentArch = sourceArch;
pipeline?.Dispose ();
var resolver = new DirectoryAssemblyResolver (this.CreateTaskLogger (), loadDebugSymbols: ReadSymbols, loadReaderParameters: readerParameters);
// Add SearchDirectories and pre-load ResolvedAssemblies into the resolver cache.
// Pre-loading ensures the correct TFM version is cached before any Cecil lazy
// reference resolution can find wrong-TFM copies from search directories (e.g.,
// a net11.0 copy in a referencing project's output directory).
foreach (var kvp in perArchAssemblies [sourceArch]) {
ITaskItem assembly = kvp.Value;
var path = Path.GetFullPath (Path.GetDirectoryName (assembly.ItemSpec));
if (!resolver.SearchDirectories.Contains (path)) {
resolver.SearchDirectories.Add (path);
}
if (resolver.Load (assembly.ItemSpec) == null) {
Log.LogDebugMessage ($"Could not pre-load assembly '{assembly.ItemSpec}' into resolver cache.");
}
}
// Set up the FixAbstractMethodsStep and AddKeepAlivesStep
var context = new MSBuildLinkContext (resolver, Log);
pipeline = new AssemblyPipeline (resolver);
BuildPipeline (pipeline, context);
}
Directory.CreateDirectory (Path.GetDirectoryName (destination.ItemSpec));
RunPipeline (pipeline!, source, destination);
}
pipeline?.Dispose ();
return !Log.HasLoggedErrors;
}
protected virtual void BuildPipeline (AssemblyPipeline pipeline, MSBuildLinkContext context)
{
// FindJavaObjectsStep
var findJavaObjectsStep = new FindJavaObjectsStep (Log) {
ApplicationJavaClass = ApplicationJavaClass,
ErrorOnCustomJavaObject = ErrorOnCustomJavaObject,
};
findJavaObjectsStep.Initialize (context);
pipeline.Steps.Add (findJavaObjectsStep);
// SaveChangedAssemblyStep
var writerParameters = new WriterParameters {
DeterministicMvid = Deterministic,
};
var saveChangedAssemblyStep = new SaveChangedAssemblyStep (Log, writerParameters);
pipeline.Steps.Add (saveChangedAssemblyStep);
// FindTypeMapObjectsStep - this must be run after the assembly has been saved, as saving changes the MVID
var findTypeMapObjectsStep = new FindTypeMapObjectsStep (Log) {
ErrorOnCustomJavaObject = ErrorOnCustomJavaObject,
Debug = Debug,
};
findTypeMapObjectsStep.Initialize (context);
pipeline.Steps.Add (findTypeMapObjectsStep);
}
void RunPipeline (AssemblyPipeline pipeline, ITaskItem source, ITaskItem destination)
{
var assembly = pipeline.Resolver.GetAssembly (source.ItemSpec);
var context = new StepContext (source, destination) {
CodeGenerationTarget = codeGenerationTarget,
EnableMarshalMethods = EnableMarshalMethods,
IsAndroidAssembly = MonoAndroidHelper.IsAndroidAssembly (source),
IsDebug = Debug,
IsFrameworkAssembly = MonoAndroidHelper.IsFrameworkAssembly (source),
IsMainAssembly = Path.GetFileNameWithoutExtension (source.ItemSpec) == TargetName,
IsUserAssembly = ResolvedUserAssemblies.Any (a => a.ItemSpec == source.ItemSpec),
};
pipeline.Run (assembly, context);
}
}
class SaveChangedAssemblyStep : IAssemblyModifierPipelineStep
{
public TaskLoggingHelper Log { get; set; }
public WriterParameters WriterParameters { get; set; }
public SaveChangedAssemblyStep (TaskLoggingHelper log, WriterParameters writerParameters)
{
Log = log;
WriterParameters = writerParameters;
}
public void ProcessAssembly (AssemblyDefinition assembly, StepContext context)
{
if (context.IsAssemblyModified) {
Log.LogDebugMessage ($"Saving modified assembly: {context.Destination.ItemSpec}");
Directory.CreateDirectory (Path.GetDirectoryName (context.Destination.ItemSpec));
WriterParameters.WriteSymbols = assembly.MainModule.HasSymbols;
assembly.Write (context.Destination.ItemSpec, WriterParameters);
} else {
// If we didn't write a modified file, copy the original to the destination
CopyIfChanged (context.Source, context.Destination);
}
// We just saved the assembly, so it is no longer modified
context.IsAssemblyModified = false;
}
void CopyIfChanged (ITaskItem source, ITaskItem destination)
{
if (MonoAndroidHelper.CopyAssemblyAndSymbols (source.ItemSpec, destination.ItemSpec)) {
Log.LogDebugMessage ($"Copied: {destination.ItemSpec}");
} else {
Log.LogDebugMessage ($"Skipped unchanged file: {destination.ItemSpec}");
// NOTE: We still need to update the timestamp on this file, or this target would run again
File.SetLastWriteTimeUtc (destination.ItemSpec, DateTime.UtcNow);
}
}
}