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
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
|
//
// LinkContext.cs
//
// Author:
// Jb Evain (jbevain@gmail.com)
//
// (C) 2006 Jb Evain
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using Mono.Cecil;
using Mono.Cecil.Cil;
namespace Mono.Linker
{
public class UnintializedContextFactory
{
virtual public AnnotationStore CreateAnnotationStore (LinkContext context) => new AnnotationStore (context);
virtual public MarkingHelpers CreateMarkingHelpers (LinkContext context) => new MarkingHelpers (context);
virtual public Tracer CreateTracer (LinkContext context) => new Tracer (context);
}
public class LinkContext : IDisposable
{
readonly Pipeline _pipeline;
AssemblyAction _coreAction;
AssemblyAction _userAction;
readonly Dictionary<string, AssemblyAction> _actions;
string _outputDirectory;
readonly Dictionary<string, string> _parameters;
bool _linkSymbols;
bool _keepTypeForwarderOnlyAssemblies;
bool _keepMembersForDebugger;
bool _ignoreUnresolved;
readonly AssemblyResolver _resolver;
readonly ReaderParameters _readerParameters;
ISymbolReaderProvider _symbolReaderProvider;
ISymbolWriterProvider _symbolWriterProvider;
readonly AnnotationStore _annotations;
public Pipeline Pipeline {
get { return _pipeline; }
}
public AnnotationStore Annotations {
get { return _annotations; }
}
public bool DeterministicOutput { get; set; }
public string OutputDirectory {
get { return _outputDirectory; }
set { _outputDirectory = value; }
}
public AssemblyAction CoreAction {
get { return _coreAction; }
set { _coreAction = value; }
}
public AssemblyAction UserAction {
get { return _userAction; }
set { _userAction = value; }
}
public bool LinkSymbols {
get { return _linkSymbols; }
set { _linkSymbols = value; }
}
public bool KeepTypeForwarderOnlyAssemblies {
get { return _keepTypeForwarderOnlyAssemblies; }
set { _keepTypeForwarderOnlyAssemblies = value; }
}
public bool KeepMembersForDebugger {
get { return _keepMembersForDebugger; }
set { _keepMembersForDebugger = value; }
}
public bool IgnoreUnresolved {
get { return _ignoreUnresolved; }
set { _ignoreUnresolved = value; }
}
public bool EnableReducedTracing { get; set; }
public bool KeepUsedAttributeTypesOnly { get; set; }
public bool KeepDependencyAttributes { get; set; }
public bool IgnoreDescriptors { get; set; }
public bool IgnoreSubstitutions { get; set; }
public bool StripDescriptors { get; set; }
public bool StripSubstitutions { get; set; }
public Dictionary<string, bool> FeatureSettings { get; private set; }
public List<string> AttributeDefinitions { get; private set; }
public List<PInvokeInfo> PInvokes { get; private set; }
public string PInvokesListFile;
public System.Collections.IDictionary Actions {
get { return _actions; }
}
public AssemblyResolver Resolver {
get { return _resolver; }
}
public ReaderParameters ReaderParameters {
get { return _readerParameters; }
}
public ISymbolReaderProvider SymbolReaderProvider {
get { return _symbolReaderProvider; }
set { _symbolReaderProvider = value; }
}
public ISymbolWriterProvider SymbolWriterProvider {
get { return _symbolWriterProvider; }
set { _symbolWriterProvider = value; }
}
public bool LogMessages { get; set; }
public ILogger Logger { private get; set; } = new ConsoleLogger ();
public MarkingHelpers MarkingHelpers { get; private set; }
public KnownMembers MarkedKnownMembers { get; private set; }
public Tracer Tracer { get; private set; }
public IReflectionPatternRecorder ReflectionPatternRecorder { get; set; }
#if !FEATURE_ILLINK
public string[] ExcludedFeatures { get; set; }
#endif
public CodeOptimizationsSettings Optimizations { get; set; }
public bool AddReflectionAnnotations { get; set; }
public string AssemblyListFile { get; set; }
public LinkContext (Pipeline pipeline)
: this (pipeline, new AssemblyResolver ())
{
}
public LinkContext (Pipeline pipeline, AssemblyResolver resolver)
: this (pipeline, resolver, new ReaderParameters {
AssemblyResolver = resolver
}, new UnintializedContextFactory ())
{
}
public LinkContext (Pipeline pipeline, AssemblyResolver resolver, ReaderParameters readerParameters, UnintializedContextFactory factory)
{
_pipeline = pipeline;
_resolver = resolver;
_resolver.Context = this;
_actions = new Dictionary<string, AssemblyAction> ();
_parameters = new Dictionary<string, string> (StringComparer.Ordinal);
_readerParameters = readerParameters;
SymbolReaderProvider = new DefaultSymbolReaderProvider (false);
if (factory == null)
throw new ArgumentNullException (nameof (factory));
_annotations = factory.CreateAnnotationStore (this);
MarkingHelpers = factory.CreateMarkingHelpers (this);
Tracer = factory.CreateTracer (this);
ReflectionPatternRecorder = new LoggingReflectionPatternRecorder (this);
MarkedKnownMembers = new KnownMembers ();
StripDescriptors = true;
StripSubstitutions = true;
PInvokes = new List<PInvokeInfo> ();
// See https://github.com/mono/linker/issues/612
const CodeOptimizations defaultOptimizations =
CodeOptimizations.BeforeFieldInit |
CodeOptimizations.OverrideRemoval |
CodeOptimizations.UnusedInterfaces |
CodeOptimizations.IPConstantPropagation;
Optimizations = new CodeOptimizationsSettings (defaultOptimizations);
}
public void SetFeatureValue (string feature, bool value)
{
Debug.Assert (!String.IsNullOrEmpty (feature));
if (FeatureSettings == null) {
FeatureSettings = new Dictionary<string, bool> { { feature, value } };
return;
}
FeatureSettings[feature] = value;
}
public void AddAttributeDefinitionFile (string file)
{
if (AttributeDefinitions == null) {
AttributeDefinitions = new List<string> { file };
return;
}
if (AttributeDefinitions.Contains (file))
return;
AttributeDefinitions.Add (file);
}
public TypeDefinition GetType (string fullName)
{
int pos = fullName.IndexOf (",");
fullName = TypeReferenceExtensions.ToCecilName (fullName);
if (pos == -1) {
foreach (AssemblyDefinition asm in GetAssemblies ()) {
var type = asm.MainModule.GetType (fullName);
if (type != null)
return type;
}
return null;
}
string asmname = fullName.Substring (pos + 1);
fullName = fullName.Substring (0, pos);
AssemblyDefinition assembly = Resolve (AssemblyNameReference.Parse (asmname));
return assembly.MainModule.GetType (fullName);
}
public AssemblyDefinition Resolve (string name)
{
if (File.Exists (name)) {
try {
return _resolver.ResolveFromPath (name, _readerParameters);
} catch (Exception e) {
throw new AssemblyResolutionException (new AssemblyNameReference (name, new Version ()), e);
}
}
return Resolve (new AssemblyNameReference (name, new Version ()));
}
public AssemblyDefinition Resolve (IMetadataScope scope)
{
AssemblyNameReference reference = GetReference (scope);
try {
AssemblyDefinition assembly = _resolver.Resolve (reference, _readerParameters);
if (assembly != null)
RegisterAssembly (assembly);
return assembly;
} catch (Exception e) when (!(e is AssemblyResolutionException)) {
throw new AssemblyResolutionException (reference, e);
}
}
public void RegisterAssembly (AssemblyDefinition assembly)
{
if (SeenFirstTime (assembly)) {
SafeReadSymbols (assembly);
SetDefaultAction (assembly);
}
}
protected bool SeenFirstTime (AssemblyDefinition assembly)
{
return !_annotations.HasAction (assembly);
}
public virtual void SafeReadSymbols (AssemblyDefinition assembly)
{
if (assembly.MainModule.HasSymbols)
return;
if (_symbolReaderProvider == null)
throw new ArgumentNullException (nameof (_symbolReaderProvider));
try {
var symbolReader = _symbolReaderProvider.GetSymbolReader (
assembly.MainModule,
_resolver.GetAssemblyFileName (assembly));
if (symbolReader == null)
return;
try {
assembly.MainModule.ReadSymbols (symbolReader);
} catch {
symbolReader.Dispose ();
return;
}
// Add symbol reader to annotations only if we have successfully read it
_annotations.AddSymbolReader (assembly, symbolReader);
} catch { }
}
public virtual ICollection<AssemblyDefinition> ResolveReferences (AssemblyDefinition assembly)
{
List<AssemblyDefinition> references = new List<AssemblyDefinition> ();
if (assembly == null)
return references;
foreach (AssemblyNameReference reference in assembly.MainModule.AssemblyReferences) {
try {
AssemblyDefinition definition = Resolve (reference);
if (definition != null)
references.Add (definition);
} catch (Exception e) {
throw new LoadException ($"Assembly '{assembly.FullName}' reference '{reference.FullName}' could not be resolved", e);
}
}
return references;
}
static AssemblyNameReference GetReference (IMetadataScope scope)
{
AssemblyNameReference reference;
if (scope is ModuleDefinition moduleDefinition) {
AssemblyDefinition asm = moduleDefinition.Assembly;
reference = asm.Name;
} else
reference = (AssemblyNameReference) scope;
return reference;
}
public void SetAction (AssemblyDefinition assembly, AssemblyAction defaultAction)
{
RegisterAssembly (assembly);
if (!_actions.TryGetValue (assembly.Name.Name, out AssemblyAction action))
action = defaultAction;
Annotations.SetAction (assembly, action);
}
protected void SetDefaultAction (AssemblyDefinition assembly)
{
AssemblyNameDefinition name = assembly.Name;
if (_actions.TryGetValue (name.Name, out AssemblyAction action)) {
} else if (IsCore (name)) {
action = _coreAction;
} else {
action = _userAction;
}
_annotations.SetAction (assembly, action);
}
public static bool IsCore (AssemblyNameReference name)
{
switch (name.Name) {
case "mscorlib":
case "Accessibility":
case "Mono.Security":
// WPF
case "PresentationFramework":
case "PresentationCore":
case "WindowsBase":
case "UIAutomationProvider":
case "UIAutomationTypes":
case "PresentationUI":
case "ReachFramework":
case "netstandard":
return true;
default:
return name.Name.StartsWith ("System")
|| name.Name.StartsWith ("Microsoft");
}
}
public virtual AssemblyDefinition[] GetAssemblies ()
{
var cache = _resolver.AssemblyCache;
AssemblyDefinition[] asms = new AssemblyDefinition[cache.Count];
cache.Values.CopyTo (asms, 0);
return asms;
}
public AssemblyDefinition GetLoadedAssembly (string name)
{
if (_resolver.AssemblyCache.TryGetValue (name, out var ad))
return ad;
return null;
}
public void SetCustomData (string key, string value)
{
_parameters[key] = value;
}
public bool HasCustomData (string key)
{
return _parameters.ContainsKey (key);
}
public bool TryGetCustomData (string key, out string value)
{
return _parameters.TryGetValue (key, out value);
}
public void Dispose ()
{
_resolver.Dispose ();
}
#if !FEATURE_ILLINK
public bool IsFeatureExcluded (string featureName)
{
return ExcludedFeatures != null && Array.IndexOf (ExcludedFeatures, featureName) >= 0;
}
#endif
public bool IsOptimizationEnabled (CodeOptimizations optimization, MemberReference context)
{
return Optimizations.IsEnabled (optimization, context?.Module.Assembly);
}
public bool IsOptimizationEnabled (CodeOptimizations optimization, AssemblyDefinition context)
{
return Optimizations.IsEnabled (optimization, context);
}
public void LogMessage (string message)
{
LogMessage (MessageImportance.Normal, message);
}
public void LogMessage (MessageImportance importance, string message)
{
if (LogMessages && Logger != null)
Logger.LogMessage (importance, "{0}", message);
}
public void LogMessage (MessageContainer message)
{
if (LogMessages)
Logger?.LogMessage (message);
}
}
public class CodeOptimizationsSettings
{
readonly Dictionary<string, CodeOptimizations> perAssembly = new Dictionary<string, CodeOptimizations> ();
public CodeOptimizationsSettings (CodeOptimizations globalOptimizations)
{
Global = globalOptimizations;
}
public CodeOptimizations Global { get; set; }
internal bool IsEnabled (CodeOptimizations optimizations, AssemblyDefinition context)
{
return IsEnabled (optimizations, context?.Name.Name);
}
public bool IsEnabled (CodeOptimizations optimizations, string assemblyName)
{
// Only one bit is set
Debug.Assert (optimizations != 0 && (optimizations & (optimizations - 1)) == 0);
if (perAssembly.Count > 0 &&
perAssembly.TryGetValue (assemblyName, out CodeOptimizations assembly)) {
return (assembly & optimizations) != 0;
}
return (Global & optimizations) != 0;
}
public void Enable (CodeOptimizations optimizations, string assemblyContext = null)
{
if (assemblyContext == null) {
Global |= optimizations;
return;
}
if (!perAssembly.ContainsKey (assemblyContext)) {
perAssembly.Add (assemblyContext, optimizations);
return;
}
perAssembly[assemblyContext] |= optimizations;
}
public void Disable (CodeOptimizations optimizations, string assemblyContext = null)
{
if (assemblyContext == null) {
Global &= ~optimizations;
return;
}
if (!perAssembly.ContainsKey (assemblyContext)) {
perAssembly.Add (assemblyContext, 0);
return;
}
perAssembly[assemblyContext] &= ~optimizations;
}
}
[Flags]
public enum CodeOptimizations
{
BeforeFieldInit = 1 << 0,
/// <summary>
/// Option to disable removal of overrides of virtual methods when a type is never instantiated
///
/// Being able to disable this optimization is helpful when trying to troubleshoot problems caused by types created via reflection or from native
/// that do not get an instance constructor marked.
/// </summary>
OverrideRemoval = 1 << 1,
/// <summary>
/// Option to disable delaying marking of instance methods until an instance of that type could exist
/// </summary>
UnreachableBodies = 1 << 2,
/// <summary>
/// Option to clear the initlocals flag on methods
/// </summary>
ClearInitLocals = 1 << 3,
/// <summary>
/// Option to remove .interfaceimpl for interface types that are not used
/// </summary>
UnusedInterfaces = 1 << 4,
/// <summary>
/// Option to do interprocedural constant propagation on return values
/// </summary>
IPConstantPropagation = 1 << 5,
/// <summary>
/// Devirtualizes methods and seals types
/// </summary>
Sealer = 1 << 6
}
}
|