summaryrefslogtreecommitdiff
path: root/src/mscorlib/src/System/Reflection/Emit/CustomAttributeBuilder.cs
blob: 545657a053a3010e5de03995a5c8ed36b61a8dfb (plain)
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
583
// 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.

/*============================================================
**
** 
** 
**
**
** CustomAttributeBuilder is a helper class to help building custom attribute.
**
** 
===========================================================*/
namespace System.Reflection.Emit {
    
    
    using System;
    using System.Reflection;
    using System.IO;
    using System.Text;
    using System.Security.Permissions;
    using System.Runtime.InteropServices;
    using System.Globalization;
    using System.Diagnostics;
    using System.Diagnostics.Contracts;
    
    [ClassInterface(ClassInterfaceType.None)]
    [ComDefaultInterface(typeof(_CustomAttributeBuilder))]
    [System.Runtime.InteropServices.ComVisible(true)]
    public class CustomAttributeBuilder : _CustomAttributeBuilder
    {
        // public constructor to form the custom attribute with constructor and constructor
        // parameters.
        public CustomAttributeBuilder(ConstructorInfo con, Object[] constructorArgs)
        {
            InitCustomAttributeBuilder(con, constructorArgs,
                                       new PropertyInfo[]{}, new Object[]{},
                                       new FieldInfo[]{}, new Object[]{});
        }
    
        // public constructor to form the custom attribute with constructor, constructor
        // parameters and named properties.
        public CustomAttributeBuilder(ConstructorInfo con, Object[] constructorArgs,
                                      PropertyInfo[] namedProperties, Object[] propertyValues)
        {
            InitCustomAttributeBuilder(con, constructorArgs, namedProperties,
                                       propertyValues, new FieldInfo[]{}, new Object[]{});
        }

        // public constructor to form the custom attribute with constructor and constructor
        // parameters.
        public CustomAttributeBuilder(ConstructorInfo con, Object[] constructorArgs,
                                      FieldInfo[] namedFields, Object[] fieldValues)
        {
            InitCustomAttributeBuilder(con, constructorArgs, new PropertyInfo[]{},
                                       new Object[]{}, namedFields, fieldValues);
        }

        // public constructor to form the custom attribute with constructor and constructor
        // parameters.
        public CustomAttributeBuilder(ConstructorInfo con, Object[] constructorArgs,
                                      PropertyInfo[] namedProperties, Object[] propertyValues,
                                      FieldInfo[] namedFields, Object[] fieldValues)
        {
            InitCustomAttributeBuilder(con, constructorArgs, namedProperties,
                                       propertyValues, namedFields, fieldValues);
        }

        // Check that a type is suitable for use in a custom attribute.
        private bool ValidateType(Type t)
        {
            if (t.IsPrimitive)
            {
                return t != typeof(IntPtr) && t != typeof(UIntPtr);
            }
            if (t == typeof(String) || t == typeof(Type))
            {
                return true;
            }
            if (t.IsEnum)
            {
                switch (Type.GetTypeCode(Enum.GetUnderlyingType(t)))
                {
                    case TypeCode.SByte:
                    case TypeCode.Byte:
                    case TypeCode.Int16:
                    case TypeCode.UInt16:
                    case TypeCode.Int32:
                    case TypeCode.UInt32:
                    case TypeCode.Int64:
                    case TypeCode.UInt64:
                        return true;
                    default:
                        return false;
                }
            }
            if (t.IsArray)
            {
                if (t.GetArrayRank() != 1)
                    return false;
                return ValidateType(t.GetElementType());
            }
            return t == typeof(Object);
        }

        internal void InitCustomAttributeBuilder(ConstructorInfo con, Object[] constructorArgs,
                                                 PropertyInfo[] namedProperties, Object[] propertyValues,
                                                 FieldInfo[] namedFields, Object[] fieldValues)
        {
            if (con == null)
                throw new ArgumentNullException(nameof(con));
            if (constructorArgs == null)
                throw new ArgumentNullException(nameof(constructorArgs));
            if (namedProperties == null)
                throw new ArgumentNullException(nameof(namedProperties));
            if (propertyValues == null)
                throw new ArgumentNullException(nameof(propertyValues));
            if (namedFields == null)
                throw new ArgumentNullException(nameof(namedFields));
            if (fieldValues == null)
                throw new ArgumentNullException(nameof(fieldValues));
            if (namedProperties.Length != propertyValues.Length)
                throw new ArgumentException(Environment.GetResourceString("Arg_ArrayLengthsDiffer"), "namedProperties, propertyValues");
            if (namedFields.Length != fieldValues.Length)
                throw new ArgumentException(Environment.GetResourceString("Arg_ArrayLengthsDiffer"), "namedFields, fieldValues");
            Contract.EndContractBlock();

            if ((con.Attributes & MethodAttributes.Static) == MethodAttributes.Static ||
                (con.Attributes & MethodAttributes.MemberAccessMask) == MethodAttributes.Private)
                throw new ArgumentException(Environment.GetResourceString("Argument_BadConstructor"));

            if ((con.CallingConvention & CallingConventions.Standard) != CallingConventions.Standard)
                throw new ArgumentException(Environment.GetResourceString("Argument_BadConstructorCallConv"));

            // Cache information used elsewhere.
            m_con = con;
            m_constructorArgs = new Object[constructorArgs.Length];
            Array.Copy(constructorArgs, 0, m_constructorArgs, 0, constructorArgs.Length);

            Type[] paramTypes;
            int i;

            // Get the types of the constructor's formal parameters.
            paramTypes = con.GetParameterTypes();

            // Since we're guaranteed a non-var calling convention, the number of arguments must equal the number of parameters.
            if (paramTypes.Length != constructorArgs.Length)
                throw new ArgumentException(Environment.GetResourceString("Argument_BadParameterCountsForConstructor"));

            // Verify that the constructor has a valid signature (custom attributes only support a subset of our type system).
            for (i = 0; i < paramTypes.Length; i++)
                if (!ValidateType(paramTypes[i]))
                    throw new ArgumentException(Environment.GetResourceString("Argument_BadTypeInCustomAttribute"));

            // Now verify that the types of the actual parameters are compatible with the types of the formal parameters.
            for (i = 0; i < paramTypes.Length; i++)
            {
                object constructorArg = constructorArgs[i];
                if (constructorArg == null)
                {
                    if (paramTypes[i].IsValueType)
                    {
                        throw new ArgumentNullException($"{nameof(constructorArgs)}[{i}]");
                    }
                    continue;
                }
                VerifyTypeAndPassedObjectType(paramTypes[i], constructorArg.GetType(), $"{nameof(constructorArgs)}[{i}]");
            }

            // Allocate a memory stream to represent the CA blob in the metadata and a binary writer to help format it.
            MemoryStream stream = new MemoryStream();
            BinaryWriter writer = new BinaryWriter(stream);

            // Write the blob protocol version (currently 1).
            writer.Write((ushort)1);

            // Now emit the constructor argument values (no need for types, they're inferred from the constructor signature).
            for (i = 0; i < constructorArgs.Length; i++)
                EmitValue(writer, paramTypes[i], constructorArgs[i]);

            // Next a short with the count of properties and fields.
            writer.Write((ushort)(namedProperties.Length + namedFields.Length));

            // Emit all the property sets.
            for (i = 0; i < namedProperties.Length; i++)
            {
                // Validate the property.
                PropertyInfo property = namedProperties[i];
                if (property == null)
                    throw new ArgumentNullException("namedProperties[" + i + "]");

                // Allow null for non-primitive types only.
                Type propType = property.PropertyType;
                object propertyValue = propertyValues[i];
                if (propertyValue == null && propType.IsValueType)
                    throw new ArgumentNullException("propertyValues[" + i + "]");

                // Validate property type.
                if (!ValidateType(propType))
                    throw new ArgumentException(Environment.GetResourceString("Argument_BadTypeInCustomAttribute"));

                // Property has to be writable.
                if (!property.CanWrite)
                    throw new ArgumentException(Environment.GetResourceString("Argument_NotAWritableProperty"));

                // Property has to be from the same class or base class as ConstructorInfo.
                if (property.DeclaringType != con.DeclaringType
                    && (!(con.DeclaringType is TypeBuilderInstantiation))
                    && !con.DeclaringType.IsSubclassOf(property.DeclaringType))
                {
                    // Might have failed check because one type is a XXXBuilder
                    // and the other is not. Deal with these special cases
                    // separately.
                    if (!TypeBuilder.IsTypeEqual(property.DeclaringType, con.DeclaringType))
                    {
                        // IsSubclassOf is overloaded to do the right thing if
                        // the constructor is a TypeBuilder, but we still need
                        // to deal with the case where the property's declaring
                        // type is one.
                        if (!(property.DeclaringType is TypeBuilder) ||
                            !con.DeclaringType.IsSubclassOf(((TypeBuilder)property.DeclaringType).BakedRuntimeType))
                            throw new ArgumentException(Environment.GetResourceString("Argument_BadPropertyForConstructorBuilder"));
                    }
                }

                // Make sure the property's type can take the given value.
                // Note that there will be no coersion.
                if (propertyValue != null)
                {
                    VerifyTypeAndPassedObjectType(propType, propertyValue.GetType(), $"{nameof(propertyValues)}[{i}]");
                }

                // First a byte indicating that this is a property.
                writer.Write((byte)CustomAttributeEncoding.Property);

                // Emit the property type, name and value.
                EmitType(writer, propType);
                EmitString(writer, namedProperties[i].Name);
                EmitValue(writer, propType, propertyValue);
            }

            // Emit all the field sets.
            for (i = 0; i < namedFields.Length; i++)
            {
                // Validate the field.
                FieldInfo namedField = namedFields[i];
                if (namedField == null)
                    throw new ArgumentNullException("namedFields[" + i + "]");

                // Allow null for non-primitive types only.
                Type fldType = namedField.FieldType;
                object fieldValue = fieldValues[i];
                if (fieldValue == null && fldType.IsValueType)
                    throw new ArgumentNullException("fieldValues[" + i + "]");

                // Validate field type.
                if (!ValidateType(fldType))
                    throw new ArgumentException(Environment.GetResourceString("Argument_BadTypeInCustomAttribute"));

                // Field has to be from the same class or base class as ConstructorInfo.
                if (namedField.DeclaringType != con.DeclaringType
                    && (!(con.DeclaringType is TypeBuilderInstantiation))
                    && !con.DeclaringType.IsSubclassOf(namedField.DeclaringType))
                {
                    // Might have failed check because one type is a XXXBuilder
                    // and the other is not. Deal with these special cases
                    // separately.
                    if (!TypeBuilder.IsTypeEqual(namedField.DeclaringType, con.DeclaringType))
                    {
                        // IsSubclassOf is overloaded to do the right thing if
                        // the constructor is a TypeBuilder, but we still need
                        // to deal with the case where the field's declaring
                        // type is one.
                        if (!(namedField.DeclaringType is TypeBuilder) ||
                            !con.DeclaringType.IsSubclassOf(((TypeBuilder)namedFields[i].DeclaringType).BakedRuntimeType))
                            throw new ArgumentException(Environment.GetResourceString("Argument_BadFieldForConstructorBuilder"));
                    }
                }

                // Make sure the field's type can take the given value.
                // Note that there will be no coersion.
                if (fieldValue != null)
                {
                    VerifyTypeAndPassedObjectType(fldType, fieldValue.GetType(), $"{nameof(fieldValues)}[{i}]");
                }
                
                // First a byte indicating that this is a field.
                writer.Write((byte)CustomAttributeEncoding.Field);

                // Emit the field type, name and value.
                EmitType(writer, fldType);
                EmitString(writer, namedField.Name);
                EmitValue(writer, fldType, fieldValue);
            }

            // Create the blob array.
            m_blob = ((MemoryStream)writer.BaseStream).ToArray();
        }

        private static void VerifyTypeAndPassedObjectType(Type type, Type passedType, string paramName)
        {
            if (type != typeof(object) && Type.GetTypeCode(passedType) != Type.GetTypeCode(type))
            {
                throw new ArgumentException(Environment.GetResourceString("Argument_ConstantDoesntMatch"));
            }
            if (passedType == typeof(IntPtr) || passedType == typeof(UIntPtr))
            {
                throw new ArgumentException(Environment.GetResourceString("Argument_BadParameterTypeForCAB"), paramName);
            }
        }

        private void EmitType(BinaryWriter writer, Type type)
        {
            if (type.IsPrimitive)
            {
                switch (Type.GetTypeCode(type))
                {
                    case TypeCode.SByte:
                        writer.Write((byte)CustomAttributeEncoding.SByte);
                        break;
                    case TypeCode.Byte:
                        writer.Write((byte)CustomAttributeEncoding.Byte);
                        break;
                    case TypeCode.Char:
                        writer.Write((byte)CustomAttributeEncoding.Char);
                        break;
                    case TypeCode.Boolean:
                        writer.Write((byte)CustomAttributeEncoding.Boolean);
                        break;
                    case TypeCode.Int16:
                        writer.Write((byte)CustomAttributeEncoding.Int16);
                        break;
                    case TypeCode.UInt16:
                        writer.Write((byte)CustomAttributeEncoding.UInt16);
                        break;
                    case TypeCode.Int32:
                        writer.Write((byte)CustomAttributeEncoding.Int32);
                        break;
                    case TypeCode.UInt32:
                        writer.Write((byte)CustomAttributeEncoding.UInt32);
                        break;
                    case TypeCode.Int64:
                        writer.Write((byte)CustomAttributeEncoding.Int64);
                        break;
                    case TypeCode.UInt64:
                        writer.Write((byte)CustomAttributeEncoding.UInt64);
                        break;
                    case TypeCode.Single:
                        writer.Write((byte)CustomAttributeEncoding.Float);
                        break;
                    case TypeCode.Double:
                        writer.Write((byte)CustomAttributeEncoding.Double);
                        break;
                    default:
                        Debug.Assert(false, "Invalid primitive type");
                        break;
                }
            }
            else if (type.IsEnum)
            {
                writer.Write((byte)CustomAttributeEncoding.Enum);
                EmitString(writer, type.AssemblyQualifiedName);
            }
            else if (type == typeof(String))
            {
                writer.Write((byte)CustomAttributeEncoding.String);
            }
            else if (type == typeof(Type))
            {
                writer.Write((byte)CustomAttributeEncoding.Type);
            }
            else if (type.IsArray)
            {
                writer.Write((byte)CustomAttributeEncoding.Array);
                EmitType(writer, type.GetElementType());
            }
            else
            {
                // Tagged object case.
                writer.Write((byte)CustomAttributeEncoding.Object);
            }
        }

        private void EmitString(BinaryWriter writer, String str)
        {
            // Strings are emitted with a length prefix in a compressed format (1, 2 or 4 bytes) as used internally by metadata.
            byte[] utf8Str = Encoding.UTF8.GetBytes(str);
            uint length = (uint)utf8Str.Length;
            if (length <= 0x7f)
            {
                writer.Write((byte)length);
            }
            else if (length <= 0x3fff)
            {
                writer.Write((byte)((length >> 8) | 0x80));
                writer.Write((byte)(length & 0xff));
            }
            else
            {
                writer.Write((byte)((length >> 24) | 0xc0));
                writer.Write((byte)((length >> 16) & 0xff));
                writer.Write((byte)((length >> 8) & 0xff));
                writer.Write((byte)(length & 0xff));
            }
            writer.Write(utf8Str);
        }

        private void EmitValue(BinaryWriter writer, Type type, Object value)
        {
            if (type.IsEnum)
            {
                switch (Type.GetTypeCode(Enum.GetUnderlyingType(type)))
                {
                    case TypeCode.SByte:
                        writer.Write((sbyte)value);
                        break;
                    case TypeCode.Byte:
                        writer.Write((byte)value);
                        break;
                    case TypeCode.Int16:
                        writer.Write((short)value);
                        break;
                    case TypeCode.UInt16:
                        writer.Write((ushort)value);
                        break;
                    case TypeCode.Int32:
                        writer.Write((int)value);
                        break;
                    case TypeCode.UInt32:
                        writer.Write((uint)value);
                        break;
                    case TypeCode.Int64:
                        writer.Write((long)value);
                        break;
                    case TypeCode.UInt64:
                        writer.Write((ulong)value);
                        break;
                    default:
                        Debug.Assert(false, "Invalid enum base type");
                        break;
                }
            }
            else if (type == typeof(String))
            {
                if (value == null)
                    writer.Write((byte)0xff);
                else
                    EmitString(writer, (String)value);
            }
            else if (type == typeof(Type))
            {
                if (value == null)
                    writer.Write((byte)0xff);
                else
                {
                    String typeName = TypeNameBuilder.ToString((Type)value, TypeNameBuilder.Format.AssemblyQualifiedName);
                    if (typeName == null)
                        throw new ArgumentException(Environment.GetResourceString("Argument_InvalidTypeForCA",
                                                                  value.GetType()));
                    EmitString(writer, typeName);
                }
            }
            else if (type.IsArray)
            {
                if (value == null)
                    writer.Write((uint)0xffffffff);
                else
                {
                    Array a = (Array)value;
                    Type et = type.GetElementType();
                    writer.Write(a.Length);
                    for (int i = 0; i < a.Length; i++)
                        EmitValue(writer, et, a.GetValue(i));
                }
            }
            else if (type.IsPrimitive)
            {
                switch (Type.GetTypeCode(type))
                {
                    case TypeCode.SByte:
                        writer.Write((sbyte)value);
                        break;
                    case TypeCode.Byte:
                        writer.Write((byte)value);
                        break;
                    case TypeCode.Char:
                        writer.Write(Convert.ToUInt16((char)value));
                        break;
                    case TypeCode.Boolean:
                        writer.Write((byte)((bool)value ? 1 : 0));
                        break;
                    case TypeCode.Int16:
                        writer.Write((short)value);
                        break;
                    case TypeCode.UInt16:
                        writer.Write((ushort)value);
                        break;
                    case TypeCode.Int32:
                        writer.Write((int)value);
                        break;
                    case TypeCode.UInt32:
                        writer.Write((uint)value);
                        break;
                    case TypeCode.Int64:
                        writer.Write((long)value);
                        break;
                    case TypeCode.UInt64:
                        writer.Write((ulong)value);
                        break;
                    case TypeCode.Single:
                        writer.Write((float)value);
                        break;
                    case TypeCode.Double:
                        writer.Write((double)value);
                        break;
                    default:
                        Debug.Assert(false, "Invalid primitive type");
                        break;
                }
            }
            else if (type == typeof(object))
            {
                // Tagged object case. Type instances aren't actually Type, they're some subclass (such as RuntimeType or
                // TypeBuilder), so we need to canonicalize this case back to Type. If we have a null value we follow the convention
                // used by C# and emit a null typed as a string (it doesn't really matter what type we pick as long as it's a
                // reference type).
                Type ot = value == null ? typeof(String) : value is Type ? typeof(Type) : value.GetType();

                // value cannot be a "System.Object" object.
                // If we allow this we will get into an infinite recursion
                if (ot == typeof(object))
                    throw new ArgumentException(Environment.GetResourceString("Argument_BadParameterTypeForCAB", ot.ToString()));
                
                EmitType(writer, ot);
                EmitValue(writer, ot, value);
            }
            else
            {
                string typename = "null";

                if (value != null)
                    typename = value.GetType().ToString();
                
                throw new ArgumentException(Environment.GetResourceString("Argument_BadParameterTypeForCAB", typename));
            }
        }

          
         

        // return the byte interpretation of the custom attribute
        internal void CreateCustomAttribute(ModuleBuilder mod, int tkOwner)
        {
            CreateCustomAttribute(mod, tkOwner, mod.GetConstructorToken(m_con).Token, false);
        }

        //*************************************************
        // Upon saving to disk, we need to create the memberRef token for the custom attribute's type
        // first of all. So when we snap the in-memory module for on disk, this token will be there.
        // We also need to enforce the use of MemberRef. Because MemberDef token might move. 
        // This function has to be called before we snap the in-memory module for on disk (i.e. Presave on
        // ModuleBuilder.
        //*************************************************
        internal int PrepareCreateCustomAttributeToDisk(ModuleBuilder mod)
        {
            return mod.InternalGetConstructorToken(m_con, true).Token;
        }

        //*************************************************
        // Call this function with toDisk=1, after on disk module has been snapped.
        //*************************************************
        internal void CreateCustomAttribute(ModuleBuilder mod, int tkOwner, int tkAttrib, bool toDisk)
        {
            TypeBuilder.DefineCustomAttribute(mod, tkOwner, tkAttrib, m_blob, toDisk, 
                                                      typeof(System.Diagnostics.DebuggableAttribute) == m_con.DeclaringType);
        }

        internal ConstructorInfo    m_con;
        internal Object[]           m_constructorArgs;
        internal byte[]             m_blob;
    }
}