-
Notifications
You must be signed in to change notification settings - Fork 566
Expand file tree
/
Copy pathAssemblyModifierPipeline.cs
More file actions
276 lines (218 loc) · 9.56 KB
/
AssemblyModifierPipeline.cs
File metadata and controls
276 lines (218 loc) · 9.56 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
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
#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 assembly modification steps that are not part of ILLink.
///
/// For trimmed builds, this runs after ILLink and includes post-trimming steps
/// (CheckForObsoletePreserveAttribute, StripEmbeddedLibraries, AddKeepAlives,
/// RemoveResourceDesigner) followed by common steps (FindJavaObjects,
/// SaveChangedAssembly, FindTypeMapObjects).
///
/// For non-trimmed builds, LinkAssembliesNoShrink extends this task and overrides
/// BuildAssemblyModificationSteps to add non-trimmed-specific steps instead.
/// </summary>
public class AssemblyModifierPipeline : AndroidTask
{
public override string TaskPrefix => "AMP";
public bool AddKeepAlives { get; set; }
public bool AndroidLinkResources { get; set; }
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 for the current architecture's ResolvedAssemblies
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);
}
}
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)
{
BuildAssemblyModificationSteps (pipeline, context);
// FindJavaObjectsStep
var findJavaObjectsStep = new FindJavaObjectsStep (Log) {
ApplicationJavaClass = ApplicationJavaClass,
ErrorOnCustomJavaObject = ErrorOnCustomJavaObject,
UseMarshalMethods = EnableMarshalMethods,
};
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);
}
/// <summary>
/// Builds the assembly modification steps that run before FindJavaObjects/Save/FindTypeMapObjects.
/// For trimmed builds (default), this adds post-trimming steps.
/// LinkAssembliesNoShrink overrides this for non-trimmed builds.
/// </summary>
protected virtual void BuildAssemblyModificationSteps (AssemblyPipeline pipeline, MSBuildLinkContext context)
{
// CheckForObsoletePreserveAttributeStep
pipeline.Steps.Add (new CheckForObsoletePreserveAttributeStep (Log));
// StripEmbeddedLibrariesStep
pipeline.Steps.Add (new StripEmbeddedLibrariesStep (Log));
// PostTrimmingAddKeepAlivesStep
if (AddKeepAlives) {
var cache = new TypeDefinitionCache ();
// Memoize the corlib resolution so the attempt (and any error logging) happens at most once,
// regardless of how many assemblies/methods need KeepAlive injection.
AssemblyDefinition? corlibAssembly = null;
bool corlibResolutionAttempted = false;
pipeline.Steps.Add (new PostTrimmingAddKeepAlivesStep (cache,
() => {
if (!corlibResolutionAttempted) {
corlibResolutionAttempted = true;
try {
corlibAssembly = pipeline.Resolver.Resolve (AssemblyNameReference.Parse ("System.Private.CoreLib"));
} catch (AssemblyResolutionException ex) {
Log.LogErrorFromException (ex, showStackTrace: false);
}
}
return corlibAssembly;
},
(msg) => Log.LogDebugMessage (msg)));
}
// RemoveResourceDesignerStep
if (AndroidLinkResources) {
var allAssemblies = new List<AssemblyDefinition> (SourceFiles.Length);
foreach (var item in SourceFiles) {
allAssemblies.Add (pipeline.Resolver.GetAssembly (item.ItemSpec));
}
pipeline.Steps.Add (new RemoveResourceDesignerStep (allAssemblies, (msg) => Log.LogDebugMessage (msg)));
}
}
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);
}
}
}