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
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Linq;
using System.Text;
using System.Xml.XPath;
using Mono.Cecil;
#nullable enable
namespace Mono.Linker.Steps
{
public class LinkAttributesParser : ProcessLinkerXmlBase
{
AttributeInfo? _attributeInfo;
public LinkAttributesParser (LinkContext context, Stream documentStream, string xmlDocumentLocation)
: base (context, documentStream, xmlDocumentLocation)
{
}
public LinkAttributesParser (LinkContext context, Stream documentStream, EmbeddedResource resource, AssemblyDefinition resourceAssembly, string xmlDocumentLocation = "<unspecified>")
: base (context, documentStream, resource, resourceAssembly, xmlDocumentLocation)
{
}
public void Parse (AttributeInfo xmlInfo)
{
_attributeInfo = xmlInfo;
bool stripLinkAttributes = _context.IsOptimizationEnabled (CodeOptimizations.RemoveLinkAttributes, _resource?.Assembly);
ProcessXml (stripLinkAttributes, _context.IgnoreLinkAttributes);
}
CustomAttribute[] ProcessAttributes (XPathNavigator nav, ICustomAttributeProvider provider)
{
var builder = new ArrayBuilder<CustomAttribute> ();
foreach (XPathNavigator argumentNav in nav.SelectChildren ("attribute", string.Empty)) {
if (!ShouldProcessElement (argumentNav))
continue;
TypeDefinition? attributeType;
string internalAttribute = GetAttribute (argumentNav, "internal");
if (!string.IsNullOrEmpty (internalAttribute)) {
attributeType = GenerateRemoveAttributeInstancesAttribute ();
if (attributeType == null)
continue;
// TODO: Replace with IsAttributeType check once we have it
if (provider is not TypeDefinition) {
LogWarning ($"Internal attribute '{attributeType.Name}' can only be used on attribute types.", 2048, argumentNav);
continue;
}
} else {
string attributeFullName = GetFullName (argumentNav);
if (string.IsNullOrEmpty (attributeFullName)) {
LogWarning ($"'attribute' element does not contain attribute 'fullname' or it's empty.", 2029, argumentNav);
continue;
}
if (!GetAttributeType (argumentNav, attributeFullName, out attributeType))
continue;
}
CustomAttribute? customAttribute = CreateCustomAttribute (argumentNav, attributeType);
if (customAttribute != null) {
_context.LogMessage ($"Assigning external custom attribute '{FormatCustomAttribute (customAttribute)}' instance to '{provider}'.");
builder.Add (customAttribute);
}
}
return builder.ToArray ();
static string FormatCustomAttribute (CustomAttribute ca)
{
StringBuilder sb = new StringBuilder ();
sb.Append (ca.Constructor.GetDisplayName ());
sb.Append (" { args: ");
for (int i = 0; i < ca.ConstructorArguments.Count; ++i) {
if (i > 0)
sb.Append (", ");
var caa = ca.ConstructorArguments[i];
sb.Append ($"{caa.Type.GetDisplayName ()} {caa.Value}");
}
sb.Append (" }");
return sb.ToString ();
}
}
TypeDefinition? GenerateRemoveAttributeInstancesAttribute ()
{
if (_context.MarkedKnownMembers.RemoveAttributeInstancesAttributeDefinition != null)
return _context.MarkedKnownMembers.RemoveAttributeInstancesAttributeDefinition;
var voidType = BCL.FindPredefinedType ("System", "Void", _context);
if (voidType == null)
return null;
var attributeType = BCL.FindPredefinedType ("System", "Attribute", _context);
if (attributeType == null)
return null;
var objectType = BCL.FindPredefinedType ("System", "Object", _context);
if (objectType == null)
return null;
//
// Generates metadata information for internal type
//
// public sealed class RemoveAttributeInstancesAttribute : Attribute
// {
// public RemoveAttributeInstancesAttribute () {}
// public RemoveAttributeInstancesAttribute (object value1) {}
// }
//
var td = new TypeDefinition ("", "RemoveAttributeInstancesAttribute", TypeAttributes.Public);
td.BaseType = attributeType;
const MethodAttributes ctorAttributes = MethodAttributes.Public | MethodAttributes.HideBySig | MethodAttributes.SpecialName | MethodAttributes.RTSpecialName | MethodAttributes.Final;
var ctor = new MethodDefinition (".ctor", ctorAttributes, voidType);
td.Methods.Add (ctor);
ctor = new MethodDefinition (".ctor", ctorAttributes, voidType);
ctor.Parameters.Add (new ParameterDefinition (objectType));
td.Methods.Add (ctor);
return _context.MarkedKnownMembers.RemoveAttributeInstancesAttributeDefinition = td;
}
CustomAttribute? CreateCustomAttribute (XPathNavigator nav, TypeDefinition attributeType)
{
CustomAttributeArgument[] arguments = ReadCustomAttributeArguments (nav, attributeType);
MethodDefinition? constructor = FindBestMatchingConstructor (attributeType, arguments);
if (constructor == null) {
LogWarning (
$"Could not find matching constructor for custom attribute '{attributeType.GetDisplayName ()}' arguments.",
2022,
nav);
return null;
}
CustomAttribute customAttribute = new CustomAttribute (constructor);
foreach (var argument in arguments)
customAttribute.ConstructorArguments.Add (argument);
ReadCustomAttributeProperties (nav, attributeType, customAttribute);
return customAttribute;
}
MethodDefinition? FindBestMatchingConstructor (TypeDefinition attributeType, CustomAttributeArgument[] args)
{
var methods = attributeType.Methods;
for (int i = 0; i < attributeType.Methods.Count; ++i) {
var m = methods[i];
if (!m.IsInstanceConstructor ())
continue;
var p = m.Parameters;
if (args.Length != p.Count)
continue;
bool match = true;
for (int ii = 0; match && ii != args.Length; ++ii) {
//
// No candidates betterness, only exact matches are supported
//
var parameterType = _context.TryResolve (p[ii].ParameterType);
if (parameterType == null || parameterType != _context.TryResolve (args[ii].Type))
match = false;
}
if (match)
return m;
}
return null;
}
void ReadCustomAttributeProperties (XPathNavigator nav, TypeDefinition attributeType, CustomAttribute customAttribute)
{
foreach (XPathNavigator propertyNav in nav.SelectChildren ("property", string.Empty)) {
string propertyName = GetName (propertyNav);
if (string.IsNullOrEmpty (propertyName)) {
LogWarning ($"Property element does not contain attribute 'name'.", 2051, propertyNav);
continue;
}
PropertyDefinition? property = attributeType.Properties.Where (prop => prop.Name == propertyName).FirstOrDefault ();
if (property == null) {
LogWarning ($"Property '{propertyName}' could not be found.", 2052, propertyNav);
continue;
}
var caa = ReadCustomAttributeArgument (propertyNav, property);
if (caa is null)
continue;
customAttribute.Properties.Add (new CustomAttributeNamedArgument (property.Name, caa.Value));
}
}
CustomAttributeArgument[] ReadCustomAttributeArguments (XPathNavigator nav, TypeDefinition attributeType)
{
var args = new ArrayBuilder<CustomAttributeArgument> ();
foreach (XPathNavigator argumentNav in nav.SelectChildren ("argument", string.Empty)) {
CustomAttributeArgument? caa = ReadCustomAttributeArgument (argumentNav, attributeType);
if (caa is not null)
args.Add (caa.Value);
}
return args.ToArray () ?? Array.Empty<CustomAttributeArgument> ();
}
CustomAttributeArgument? ReadCustomAttributeArgument (XPathNavigator nav, IMemberDefinition memberWithAttribute)
{
TypeReference? typeref = ResolveArgumentType (nav, memberWithAttribute);
if (typeref is null)
return null;
string svalue = nav.Value;
//
// Builds CustomAttributeArgument in the same way as it would be
// represented in the metadata if encoded there. This simplifies
// any custom attributes handling in linker by using same attributes
// value extraction or mathing logic.
//
switch (typeref.MetadataType) {
case MetadataType.Object:
var argumentIterator = nav.SelectChildren ("argument", string.Empty);
if (argumentIterator?.MoveNext () != true) {
_context.LogError ($"Custom attribute argument for 'System.Object' requires nested 'argument' node.", 1043);
return null;
}
var typedef = _context.TryResolve (typeref);
if (typedef == null)
return null;
var boxedValue = ReadCustomAttributeArgument (argumentIterator.Current!, typedef);
if (boxedValue is null)
return null;
return new CustomAttributeArgument (typeref, boxedValue);
case MetadataType.Char:
case MetadataType.Byte:
case MetadataType.SByte:
case MetadataType.Int16:
case MetadataType.UInt16:
case MetadataType.Int32:
case MetadataType.UInt32:
case MetadataType.UInt64:
case MetadataType.Int64:
case MetadataType.String:
return new CustomAttributeArgument (typeref, ConvertStringValue (svalue, typeref));
case MetadataType.ValueType:
var enumType = _context.Resolve (typeref);
if (enumType?.IsEnum != true)
goto default;
var enumField = enumType.Fields.Where (f => f.IsStatic && f.Name == svalue).FirstOrDefault ();
object evalue = enumField?.Constant ?? svalue;
typeref = enumType.GetEnumUnderlyingType ();
return new CustomAttributeArgument (enumType, ConvertStringValue (evalue, typeref));
case MetadataType.Class:
if (!typeref.IsTypeOf ("System", "Type"))
goto default;
TypeReference type = _context.TypeNameResolver.ResolveTypeName (svalue, memberWithAttribute, out _);
if (type == null) {
_context.LogError ($"Could not resolve custom attribute type value '{svalue}'.", 1044, origin: GetMessageOriginForPosition (nav));
return null;
}
return new CustomAttributeArgument (typeref, type);
default:
// No support for null and arrays, consider adding - dotnet/linker/issues/1957
_context.LogError ($"Unexpected attribute argument type '{typeref.GetDisplayName ()}'.", 1045);
return null;
}
TypeReference? ResolveArgumentType (XPathNavigator nav, IMemberDefinition memberWithAttribute)
{
string typeName = GetAttribute (nav, "type");
if (string.IsNullOrEmpty (typeName))
typeName = "System.String";
TypeReference typeref = _context.TypeNameResolver.ResolveTypeName (typeName, memberWithAttribute, out _);
if (typeref == null) {
_context.LogError ($"The type '{typeName}' used with attribute value '{nav.Value}' could not be found.", 1041, origin: GetMessageOriginForPosition (nav));
return null;
}
return typeref;
}
}
object? ConvertStringValue (object value, TypeReference targetType)
{
TypeCode typeCode;
switch (targetType.MetadataType) {
case MetadataType.String:
typeCode = TypeCode.String;
break;
case MetadataType.Char:
typeCode = TypeCode.Char;
break;
case MetadataType.Byte:
typeCode = TypeCode.Byte;
break;
case MetadataType.SByte:
typeCode = TypeCode.SByte;
break;
case MetadataType.Int16:
typeCode = TypeCode.Int16;
break;
case MetadataType.UInt16:
typeCode = TypeCode.UInt16;
break;
case MetadataType.Int32:
typeCode = TypeCode.Int32;
break;
case MetadataType.UInt32:
typeCode = TypeCode.UInt32;
break;
case MetadataType.UInt64:
typeCode = TypeCode.UInt64;
break;
case MetadataType.Int64:
typeCode = TypeCode.Int64;
break;
case MetadataType.Boolean:
typeCode = TypeCode.Boolean;
break;
case MetadataType.Single:
typeCode = TypeCode.Single;
break;
case MetadataType.Double:
typeCode = TypeCode.Double;
break;
default:
throw new NotSupportedException (targetType.ToString ());
}
try {
return Convert.ChangeType (value, typeCode);
} catch {
_context.LogError ($"Cannot convert value '{value}' to type '{targetType.GetDisplayName ()}'.", 1042);
return null;
}
}
bool GetAttributeType (XPathNavigator nav, string attributeFullName, [NotNullWhen (true)] out TypeDefinition? attributeType)
{
string assemblyName = GetAttribute (nav, "assembly");
if (string.IsNullOrEmpty (assemblyName)) {
attributeType = _context.GetType (attributeFullName);
} else {
AssemblyDefinition assembly;
try {
assembly = _context.TryResolve (AssemblyNameReference.Parse (assemblyName));
if (assembly == null) {
LogWarning ($"Could not resolve assembly '{assemblyName}' for attribute '{attributeFullName}'.", 2030, nav);
attributeType = default;
return false;
}
} catch (Exception) {
LogWarning ($"Could not resolve assembly '{assemblyName}' for attribute '{attributeFullName}'.", 2030, nav);
attributeType = default;
return false;
}
attributeType = _context.TryResolve (assembly, attributeFullName);
}
if (attributeType == null) {
LogWarning ($"Attribute type '{attributeFullName}' could not be found.", 2031, nav);
return false;
}
return true;
}
protected override AllowedAssemblies AllowedAssemblySelector {
get {
if (_resource?.Assembly == null)
return AllowedAssemblies.AllAssemblies;
// Corelib XML may contain assembly wildcard to support compiler-injected attribute types
if (_resource?.Assembly.Name.Name == PlatformAssemblies.CoreLib)
return AllowedAssemblies.AllAssemblies;
return AllowedAssemblies.ContainingAssembly;
}
}
protected override void ProcessAssembly (AssemblyDefinition assembly, XPathNavigator nav, bool warnOnUnresolvedTypes)
{
PopulateAttributeInfo (assembly, nav);
ProcessTypes (assembly, nav, warnOnUnresolvedTypes);
}
protected override void ProcessType (TypeDefinition type, XPathNavigator nav)
{
Debug.Assert (ShouldProcessElement (nav));
PopulateAttributeInfo (type, nav);
ProcessTypeChildren (type, nav);
if (!type.HasNestedTypes)
return;
foreach (XPathNavigator nestedTypeNav in nav.SelectChildren ("type", string.Empty)) {
foreach (TypeDefinition nested in type.NestedTypes) {
if (nested.Name == GetAttribute (nestedTypeNav, "name") && ShouldProcessElement (nestedTypeNav))
ProcessType (nested, nestedTypeNav);
}
}
}
protected override void ProcessField (TypeDefinition type, FieldDefinition field, XPathNavigator nav)
{
PopulateAttributeInfo (field, nav);
}
protected override void ProcessMethod (TypeDefinition type, MethodDefinition method, XPathNavigator nav, object? customData)
{
PopulateAttributeInfo (method, nav);
ProcessReturnParameters (method, nav);
ProcessParameters (method, nav);
}
void ProcessParameters (MethodDefinition method, XPathNavigator nav)
{
Debug.Assert (_attributeInfo != null);
foreach (XPathNavigator parameterNav in nav.SelectChildren ("parameter", string.Empty)) {
var attributes = ProcessAttributes (parameterNav, method);
if (attributes != null) {
string paramName = GetAttribute (parameterNav, "name");
foreach (ParameterDefinition parameter in method.Parameters) {
if (paramName == parameter.Name) {
if (parameter.HasCustomAttributes || _attributeInfo.CustomAttributes.ContainsKey (parameter))
LogWarning (
$"More than one value specified for parameter '{paramName}' of method '{method.GetDisplayName ()}'.",
2024, parameterNav);
_attributeInfo.AddCustomAttributes (parameter, attributes);
break;
}
}
}
}
}
void ProcessReturnParameters (MethodDefinition method, XPathNavigator nav)
{
bool firstAppearance = true;
foreach (XPathNavigator returnNav in nav.SelectChildren ("return", string.Empty)) {
if (firstAppearance) {
firstAppearance = false;
PopulateAttributeInfo (method.MethodReturnType, returnNav);
} else {
LogWarning (
$"There is more than one 'return' child element specified for method '{method.GetDisplayName ()}'.",
2023, returnNav);
}
}
}
protected override MethodDefinition? GetMethod (TypeDefinition type, string signature)
{
if (type.HasMethods)
foreach (MethodDefinition method in type.Methods)
if (signature.Replace (" ", "") == GetMethodSignature (method) || signature.Replace (" ", "") == GetMethodSignature (method, true))
return method;
return null;
}
static string GetMethodSignature (MethodDefinition method, bool includeReturnType = false)
{
StringBuilder sb = new StringBuilder ();
if (includeReturnType) {
sb.Append (method.ReturnType.FullName);
}
sb.Append (method.Name);
if (method.HasGenericParameters) {
sb.Append ("<");
for (int i = 0; i < method.GenericParameters.Count; i++) {
if (i > 0)
sb.Append (",");
sb.Append (method.GenericParameters[i].Name);
}
sb.Append (">");
}
sb.Append ("(");
if (method.HasParameters) {
for (int i = 0; i < method.Parameters.Count; i++) {
if (i > 0)
sb.Append (",");
sb.Append (method.Parameters[i].ParameterType.FullName);
}
}
sb.Append (")");
return sb.ToString ();
}
protected override void ProcessProperty (TypeDefinition type, PropertyDefinition property, XPathNavigator nav, object? customData, bool fromSignature)
{
PopulateAttributeInfo (property, nav);
}
protected override void ProcessEvent (TypeDefinition type, EventDefinition @event, XPathNavigator nav, object? customData)
{
PopulateAttributeInfo (@event, nav);
}
void PopulateAttributeInfo (ICustomAttributeProvider provider, XPathNavigator nav)
{
Debug.Assert (_attributeInfo != null);
var attributes = ProcessAttributes (nav, provider);
if (attributes != null)
_attributeInfo.AddCustomAttributes (provider, attributes);
}
}
}
|