/
RuntimeType.cs
628 lines (528 loc) · 18.3 KB
/
RuntimeType.cs
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
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
//
// RuntimeType.cs
//
// Authors:
// Marek Safar <marek.safar@gmail.com>
//
// Copyright (C) 2015 Xamarin Inc (http://www.xamarin.com)
//
// 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.Reflection;
using System.Runtime.CompilerServices;
using System.Threading;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Globalization;
#if MONO_COM
using System.Reflection.Emit;
#endif
using System.Diagnostics.Contracts;
using System.Security;
using System.Runtime.Serialization;
namespace System
{
partial class RuntimeType
{
internal Object GenericCache;
internal virtual MonoCMethod GetDefaultConstructor ()
{
// TODO: Requires MonoType
throw new NotSupportedException ();
}
string GetDefaultMemberName ()
{
object [] att = GetCustomAttributes (typeof (DefaultMemberAttribute), true);
return att.Length != 0 ? ((DefaultMemberAttribute) att [0]).MemberName : null;
}
RuntimeConstructorInfo m_serializationCtor;
internal RuntimeConstructorInfo GetSerializationCtor()
{
if (m_serializationCtor == null) {
var s_SICtorParamTypes = new Type[] { typeof(SerializationInfo), typeof(StreamingContext) };
m_serializationCtor = GetConstructor(
BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic,
null,
CallingConventions.Any,
s_SICtorParamTypes,
null) as RuntimeConstructorInfo;
}
return m_serializationCtor;
}
internal Object CreateInstanceSlow(bool publicOnly, bool skipCheckThis, bool fillCache, ref StackCrawlMark stackMark)
{
bool bNeedSecurityCheck = true;
bool bCanBeCached = false;
bool bSecurityCheckOff = false;
if (!skipCheckThis)
CreateInstanceCheckThis();
if (!fillCache)
bSecurityCheckOff = true;
return CreateInstanceMono (!publicOnly);
}
object CreateInstanceMono (bool nonPublic)
{
var ctor = GetDefaultConstructor ();
if (!nonPublic && ctor != null && !ctor.IsPublic) {
ctor = null;
}
if (ctor == null) {
Type elementType = this.GetRootElementType();
if (ReferenceEquals (elementType, typeof (TypedReference)) || ReferenceEquals (elementType, typeof (RuntimeArgumentHandle)))
throw new NotSupportedException (Environment.GetResourceString ("NotSupported_ContainsStackPtr"));
if (IsValueType)
return CreateInstanceInternal (this);
throw new MissingMethodException (Locale.GetText ("Default constructor not found for type " + FullName));
}
// TODO: .net does more checks in unmanaged land in RuntimeTypeHandle::CreateInstance
if (IsAbstract) {
throw new MissingMethodException (Locale.GetText ("Cannot create an abstract class '{0}'.", FullName));
}
return ctor.InternalInvoke (null, null);
}
internal Object CheckValue (Object value, Binder binder, CultureInfo culture, BindingFlags invokeAttr)
{
bool failed = false;
var res = TryConvertToType (value, ref failed);
if (!failed)
return res;
if ((invokeAttr & BindingFlags.ExactBinding) == BindingFlags.ExactBinding)
throw new ArgumentException(String.Format(CultureInfo.CurrentUICulture, Environment.GetResourceString("Arg_ObjObjEx"), value.GetType(), this));
if (binder != null && binder != Type.DefaultBinder)
return binder.ChangeType (value, this, culture);
throw new ArgumentException(String.Format(CultureInfo.CurrentUICulture, Environment.GetResourceString("Arg_ObjObjEx"), value.GetType(), this));
}
object TryConvertToType (object value, ref bool failed)
{
if (IsInstanceOfType (value)) {
return value;
}
if (IsByRef) {
var elementType = GetElementType ();
if (value == null || elementType.IsInstanceOfType (value)) {
return value;
}
}
if (value == null)
return value;
if (IsEnum) {
var type = Enum.GetUnderlyingType (this);
if (type == value.GetType ())
return value;
var res = IsConvertibleToPrimitiveType (value, this);
if (res != null)
return res;
} else if (IsPrimitive) {
var res = IsConvertibleToPrimitiveType (value, this);
if (res != null)
return res;
} else if (IsPointer) {
var vtype = value.GetType ();
if (vtype == typeof (IntPtr) || vtype == typeof (UIntPtr))
return value;
}
failed = true;
return null;
}
// Binder uses some incompatible conversion rules. For example
// int value cannot be used with decimal parameter but in other
// ways it's more flexible than normal convertor, for example
// long value can be used with int based enum
static object IsConvertibleToPrimitiveType (object value, Type targetType)
{
var type = value.GetType ();
if (type.IsEnum) {
type = Enum.GetUnderlyingType (type);
if (type == targetType)
return value;
}
var from = Type.GetTypeCode (type);
var to = Type.GetTypeCode (targetType);
switch (to) {
case TypeCode.Char:
switch (from) {
case TypeCode.Byte:
return (Char) (Byte) value;
case TypeCode.UInt16:
return value;
}
break;
case TypeCode.Int16:
switch (from) {
case TypeCode.Byte:
return (Int16) (Byte) value;
case TypeCode.SByte:
return (Int16) (SByte) value;
}
break;
case TypeCode.UInt16:
switch (from) {
case TypeCode.Byte:
return (UInt16) (Byte) value;
case TypeCode.Char:
return value;
}
break;
case TypeCode.Int32:
switch (from) {
case TypeCode.Byte:
return (Int32) (Byte) value;
case TypeCode.SByte:
return (Int32) (SByte) value;
case TypeCode.Char:
return (Int32) (Char) value;
case TypeCode.Int16:
return (Int32) (Int16) value;
case TypeCode.UInt16:
return (Int32) (UInt16) value;
}
break;
case TypeCode.UInt32:
switch (from) {
case TypeCode.Byte:
return (UInt32) (Byte) value;
case TypeCode.Char:
return (UInt32) (Char) value;
case TypeCode.UInt16:
return (UInt32) (UInt16) value;
}
break;
case TypeCode.Int64:
switch (from) {
case TypeCode.Byte:
return (Int64) (Byte) value;
case TypeCode.SByte:
return (Int64) (SByte) value;
case TypeCode.Int16:
return (Int64) (Int16) value;
case TypeCode.Char:
return (Int64) (Char) value;
case TypeCode.UInt16:
return (Int64) (UInt16) value;
case TypeCode.Int32:
return (Int64) (Int32) value;
case TypeCode.UInt32:
return (Int64) (UInt32) value;
}
break;
case TypeCode.UInt64:
switch (from) {
case TypeCode.Byte:
return (UInt64) (Byte) value;
case TypeCode.Char:
return (UInt64) (Char) value;
case TypeCode.UInt16:
return (UInt64) (UInt16) value;
case TypeCode.UInt32:
return (UInt64) (UInt32) value;
}
break;
case TypeCode.Single:
switch (from) {
case TypeCode.Byte:
return (Single) (Byte) value;
case TypeCode.SByte:
return (Single) (SByte) value;
case TypeCode.Int16:
return (Single) (Int16) value;
case TypeCode.Char:
return (Single) (Char) value;
case TypeCode.UInt16:
return (Single) (UInt16) value;
case TypeCode.Int32:
return (Single) (Int32) value;
case TypeCode.UInt32:
return (Single) (UInt32) value;
case TypeCode.Int64:
return (Single) (Int64) value;
case TypeCode.UInt64:
return (Single) (UInt64) value;
}
break;
case TypeCode.Double:
switch (from) {
case TypeCode.Byte:
return (Double) (Byte) value;
case TypeCode.SByte:
return (Double) (SByte) value;
case TypeCode.Char:
return (Double) (Char) value;
case TypeCode.Int16:
return (Double) (Int16) value;
case TypeCode.UInt16:
return (Double) (UInt16) value;
case TypeCode.Int32:
return (Double) (Int32) value;
case TypeCode.UInt32:
return (Double) (UInt32) value;
case TypeCode.Int64:
return (Double) (Int64) value;
case TypeCode.UInt64:
return (Double) (UInt64) value;
case TypeCode.Single:
return (Double) (Single) value;
}
break;
}
// Everything else is rejected
return null;
}
string GetCachedName (TypeNameKind kind)
{
switch (kind) {
case TypeNameKind.SerializationName:
return ToString ();
default:
throw new NotImplementedException ();
}
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
extern Type make_array_type (int rank);
public override Type MakeArrayType ()
{
return make_array_type (0);
}
public override Type MakeArrayType (int rank)
{
if (rank < 1 || rank > 255)
throw new IndexOutOfRangeException ();
return make_array_type (rank);
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
extern Type make_byref_type ();
public override Type MakeByRefType ()
{
if (IsByRef)
throw new TypeLoadException ("Can not call MakeByRefType on a ByRef type");
return make_byref_type ();
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
static extern Type MakePointerType (Type type);
public override Type MakePointerType ()
{
return MakePointerType (this);
}
public override StructLayoutAttribute StructLayoutAttribute {
get {
return StructLayoutAttribute.GetCustomAttribute (this);
}
}
public override bool ContainsGenericParameters {
get {
if (IsGenericParameter)
return true;
if (IsGenericType) {
foreach (Type arg in GetGenericArguments ())
if (arg.ContainsGenericParameters)
return true;
}
if (HasElementType)
return GetElementType ().ContainsGenericParameters;
return false;
}
}
public override Type[] GetGenericParameterConstraints()
{
if (!IsGenericParameter)
throw new InvalidOperationException(Environment.GetResourceString("Arg_NotGenericParameter"));
Contract.EndContractBlock();
Type[] constraints = GetGenericParameterConstraints_impl ();
if (constraints == null)
constraints = EmptyArray<Type>.Value;
return constraints;
}
internal static object CreateInstanceForAnotherGenericParameter (Type genericType, RuntimeType genericArgument)
{
var gt = (RuntimeType) MakeGenericType (genericType, new Type [] { genericArgument });
var ctor = gt.GetDefaultConstructor ();
return ctor.InternalInvoke (null, null);
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
static extern Type MakeGenericType (Type gt, Type [] types);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern RuntimeMethodInfo[] GetMethodsByName (string name, BindingFlags bindingAttr, bool ignoreCase, Type reflected_type);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
extern RuntimePropertyInfo[] GetPropertiesByName (string name, BindingFlags bindingAttr, bool icase, Type reflected_type);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
extern RuntimeConstructorInfo[] GetConstructors_internal (BindingFlags bindingAttr, Type reflected_type);
public override InterfaceMapping GetInterfaceMap (Type ifaceType)
{
if (IsGenericParameter)
throw new InvalidOperationException(Environment.GetResourceString("Arg_GenericParameter"));
if ((object)ifaceType == null)
throw new ArgumentNullException("ifaceType");
Contract.EndContractBlock();
RuntimeType ifaceRtType = ifaceType as RuntimeType;
if (ifaceRtType == null)
throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeType"), "ifaceType");
InterfaceMapping res;
if (!ifaceType.IsInterface)
throw new ArgumentException (Locale.GetText ("Argument must be an interface."), "ifaceType");
if (IsInterface)
throw new ArgumentException ("'this' type cannot be an interface itself");
res.TargetType = this;
res.InterfaceType = ifaceType;
GetInterfaceMapData (this, ifaceType, out res.TargetMethods, out res.InterfaceMethods);
if (res.TargetMethods == null)
throw new ArgumentException (Locale.GetText ("Interface not found"), "ifaceType");
return res;
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
static extern void GetInterfaceMapData (Type t, Type iface, out MethodInfo[] targets, out MethodInfo[] methods);
public override Guid GUID {
get {
object[] att = GetCustomAttributes(typeof(System.Runtime.InteropServices.GuidAttribute), true);
if (att.Length == 0)
return Guid.Empty;
return new Guid(((System.Runtime.InteropServices.GuidAttribute)att[0]).Value);
}
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern void GetPacking (out int packing, out int size);
#if MONO_COM
private static Dictionary<Guid, Type> clsid_types;
private static AssemblyBuilder clsid_assemblybuilder;
#endif
internal static Type GetTypeFromCLSIDImpl(Guid clsid, String server, bool throwOnError)
{
#if MONO_COM
Type result;
if (clsid_types == null)
{
Dictionary<Guid, Type> new_clsid_types = new Dictionary<Guid, Type> ();
Interlocked.CompareExchange<Dictionary<Guid, Type>>(
ref clsid_types, new_clsid_types, null);
}
lock (clsid_types) {
if (clsid_types.TryGetValue(clsid, out result))
return result;
if (clsid_assemblybuilder == null)
{
AssemblyName assemblyname = new AssemblyName ();
assemblyname.Name = "GetTypeFromCLSIDDummyAssembly";
clsid_assemblybuilder = AppDomain.CurrentDomain.DefineDynamicAssembly (
assemblyname, AssemblyBuilderAccess.Run);
}
ModuleBuilder modulebuilder = clsid_assemblybuilder.DefineDynamicModule (
clsid.ToString ());
TypeBuilder typebuilder = modulebuilder.DefineType ("System.__ComObject",
TypeAttributes.Public | TypeAttributes.Class, typeof(System.__ComObject));
Type[] guidattrtypes = new Type[] { typeof(string) };
CustomAttributeBuilder customattr = new CustomAttributeBuilder (
typeof(GuidAttribute).GetConstructor (guidattrtypes),
new object[] { clsid.ToString () });
typebuilder.SetCustomAttribute (customattr);
customattr = new CustomAttributeBuilder (
typeof(ComImportAttribute).GetConstructor (EmptyTypes),
new object[0] {});
typebuilder.SetCustomAttribute (customattr);
result = typebuilder.CreateType ();
clsid_types.Add(clsid, result);
return result;
}
#else
throw new NotImplementedException ("Unmanaged activation removed");
#endif
}
protected override TypeCode GetTypeCodeImpl ()
{
return GetTypeCodeImplInternal (this);
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
extern static TypeCode GetTypeCodeImplInternal (Type type);
internal static Type GetTypeFromProgIDImpl(String progID, String server, bool throwOnError)
{
throw new NotImplementedException ("Unmanaged activation is not supported");
}
public override string ToString()
{
return getFullName (false, false);
}
bool IsGenericCOMObjectImpl ()
{
return false;
}
[MethodImplAttribute (MethodImplOptions.InternalCall)]
static extern object CreateInstanceInternal (Type type);
public extern override MethodBase DeclaringMethod {
[MethodImplAttribute(MethodImplOptions.InternalCall)]
get;
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern string getFullName(bool full_name, bool assembly_qualified);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
extern Type[] GetGenericArgumentsInternal (bool runtimeArray);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
extern GenericParameterAttributes GetGenericParameterAttributes ();
[MethodImplAttribute(MethodImplOptions.InternalCall)]
extern Type[] GetGenericParameterConstraints_impl ();
[MethodImplAttribute(MethodImplOptions.InternalCall)]
extern int GetGenericParameterPosition ();
[MethodImplAttribute(MethodImplOptions.InternalCall)]
extern RuntimeEventInfo[] GetEvents_internal (string name, BindingFlags bindingAttr, Type reflected_type);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
extern RuntimeFieldInfo[] GetFields_internal (string name, BindingFlags bindingAttr, Type reflected_type);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public extern override Type[] GetInterfaces();
[MethodImplAttribute(MethodImplOptions.InternalCall)]
extern RuntimeType[] GetNestedTypes_internal (string name, BindingFlags bindingAttr);
public override string AssemblyQualifiedName {
get {
return getFullName (true, true);
}
}
public extern override Type DeclaringType {
[MethodImplAttribute(MethodImplOptions.InternalCall)]
get;
}
public override string FullName {
get {
throw new NotImplementedException ();
}
}
public extern override string Name {
[MethodImplAttribute(MethodImplOptions.InternalCall)]
get;
}
public extern override string Namespace {
[MethodImplAttribute(MethodImplOptions.InternalCall)]
get;
}
#if MOBILE
static int get_core_clr_security_level ()
{
return 1;
}
#else
//seclevel { transparent = 0, safe-critical = 1, critical = 2}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public extern int get_core_clr_security_level ();
public override bool IsSecurityTransparent {
get { return get_core_clr_security_level () == 0; }
}
public override bool IsSecurityCritical {
get { return get_core_clr_security_level () > 0; }
}
public override bool IsSecuritySafeCritical {
get { return get_core_clr_security_level () == 1; }
}
#endif
}
}