IKVM11  11
Java SE 11 Virtual Machine for .NET
Loading...
Searching...
No Matches
Universe.cs
Go to the documentation of this file.
1/*
2 Copyright (C) 2009-2013 Jeroen Frijters
3
4 This software is provided 'as-is', without any express or implied
5 warranty. In no event will the authors be held liable for any damages
6 arising from the use of this software.
7
8 Permission is granted to anyone to use this software for any purpose,
9 including commercial applications, and to alter it and redistribute it
10 freely, subject to the following restrictions:
11
12 1. The origin of this software must not be misrepresented; you must not
13 claim that you wrote the original software. If you use this software
14 in a product, an acknowledgment in the product documentation would be
15 appreciated but is not required.
16 2. Altered source versions must be plainly marked as such, and must not be
17 misrepresented as being the original software.
18 3. This notice may not be removed or altered from any source distribution.
19
20 Jeroen Frijters
21 jeroen@frijters.net
22
23*/
24using System;
25using System.Collections.Generic;
26using System.Diagnostics.SymbolStore;
27using System.IO;
28using System.Security;
29using System.Security.Cryptography;
30using System.Text;
31
34
35namespace IKVM.Reflection
36{
37
41 internal sealed class Universe : IDisposable
42 {
43
44 public static readonly string NetCoreLibName = "System.Runtime";
45 public static readonly string NetFxCoreLibName = "mscorlib";
46
47#if NETCOREAPP3_1_OR_GREATER
48
49 public static readonly string DefaultCoreLibName = NetCoreLibName;
50
51#elif NETFRAMEWORK
52
53 public static readonly string DefaultCoreLibName = NetFxCoreLibName;
54
55#endif
56
57#if NETFRAMEWORK
58 internal static readonly bool MonoRuntime = System.Type.GetType("Mono.Runtime") != null;
59 internal static readonly bool CoreRuntime = false;
60#else
61 internal static readonly bool MonoRuntime = false;
62 internal static readonly bool CoreRuntime = true;
63#endif
64
65 readonly string coreLibName;
66 readonly Dictionary<Type, Type> canonicalizedTypes = new Dictionary<Type, Type>();
67 readonly List<AssemblyReader> assemblies = new List<AssemblyReader>();
68 readonly List<AssemblyBuilder> dynamicAssemblies = new List<AssemblyBuilder>();
69 readonly Dictionary<string, Assembly> assembliesByName = new Dictionary<string, Assembly>();
70 readonly Dictionary<System.Type, Type> importedTypes = new Dictionary<System.Type, Type>();
71 Dictionary<ScopedTypeName, Type> missingTypes;
72 bool resolveMissingMembers;
73 readonly bool enableFunctionPointers;
74 readonly bool useNativeFusion;
75 readonly bool returnPseudoCustomAttributes;
76 readonly bool automaticallyProvideDefaultConstructor;
77 HashAlgorithmName pdbChecksumAlgorithm = HashAlgorithmName.SHA256;
78 readonly UniverseOptions options;
79 Func<ModuleBuilder, ISymbolWriter> symbolWriterFactory;
80 Type typeof_System_Object;
81 Type typeof_System_ValueType;
82 Type typeof_System_Enum;
83 Type typeof_System_Void;
84 Type typeof_System_Boolean;
85 Type typeof_System_Char;
86 Type typeof_System_SByte;
87 Type typeof_System_Byte;
88 Type typeof_System_Int16;
89 Type typeof_System_UInt16;
90 Type typeof_System_Int32;
91 Type typeof_System_UInt32;
92 Type typeof_System_Int64;
93 Type typeof_System_UInt64;
94 Type typeof_System_Single;
95 Type typeof_System_Double;
96 Type typeof_System_String;
97 Type typeof_System_IntPtr;
98 Type typeof_System_UIntPtr;
99 Type typeof_System_TypedReference;
100 Type typeof_System_Type;
101 Type typeof_System_Array;
102 Type typeof_System_DateTime;
103 Type typeof_System_DBNull;
104 Type typeof_System_Decimal;
105 Type typeof_System_AttributeUsageAttribute;
106 Type typeof_System_ContextBoundObject;
107 Type typeof_System_MarshalByRefObject;
108 Type typeof_System_Console;
109 Type typeof_System_IO_TextWriter;
110 Type typeof_System_Runtime_InteropServices_DllImportAttribute;
111 Type typeof_System_Runtime_InteropServices_FieldOffsetAttribute;
112 Type typeof_System_Runtime_InteropServices_MarshalAsAttribute;
113 Type typeof_System_Runtime_InteropServices_UnmanagedType;
114 Type typeof_System_Runtime_InteropServices_VarEnum;
115 Type typeof_System_Runtime_InteropServices_PreserveSigAttribute;
116 Type typeof_System_Runtime_InteropServices_CallingConvention;
117 Type typeof_System_Runtime_InteropServices_CharSet;
118 Type typeof_System_Runtime_CompilerServices_DecimalConstantAttribute;
119 Type typeof_System_Reflection_AssemblyCopyrightAttribute;
120 Type typeof_System_Reflection_AssemblyTrademarkAttribute;
121 Type typeof_System_Reflection_AssemblyProductAttribute;
122 Type typeof_System_Reflection_AssemblyCompanyAttribute;
123 Type typeof_System_Reflection_AssemblyDescriptionAttribute;
124 Type typeof_System_Reflection_AssemblyTitleAttribute;
125 Type typeof_System_Reflection_AssemblyInformationalVersionAttribute;
126 Type typeof_System_Reflection_AssemblyFileVersionAttribute;
127 Type typeof_System_Security_Permissions_CodeAccessSecurityAttribute;
128 Type typeof_System_Security_Permissions_PermissionSetAttribute;
129 Type typeof_System_Security_Permissions_SecurityAction;
130 List<ResolveEventHandler> resolvers = new List<ResolveEventHandler>();
131 Predicate<Type> missingTypeIsValueType;
132
137 public Universe(string coreLibName = null) :
138 this(UniverseOptions.None, coreLibName)
139 {
140
141 }
142
148 public Universe(UniverseOptions options, string coreLibName = null)
149 {
150 this.options = options;
151 this.coreLibName = coreLibName ?? DefaultCoreLibName;
152 enableFunctionPointers = (options & UniverseOptions.EnableFunctionPointers) != 0;
153 useNativeFusion = (options & UniverseOptions.DisableFusion) == 0 && GetUseNativeFusion();
154 returnPseudoCustomAttributes = (options & UniverseOptions.DisablePseudoCustomAttributeRetrieval) == 0;
155 automaticallyProvideDefaultConstructor = (options & UniverseOptions.DontProvideAutomaticDefaultConstructor) == 0;
156 resolveMissingMembers = (options & UniverseOptions.ResolveMissingMembers) != 0;
157 }
158
163 public void SetSymbolWriterFactory(Func<ModuleBuilder, ISymbolWriter> factory)
164 {
165 this.symbolWriterFactory = factory;
166 }
167
172 public void SetPdbChecksumAlgorithm(HashAlgorithmName pdbChecksumAlgorithm)
173 {
174 this.pdbChecksumAlgorithm = pdbChecksumAlgorithm;
175 }
176
182 internal ISymbolWriter CreateSymbolWriter(ModuleBuilder module)
183 {
184 return symbolWriterFactory?.Invoke(module);
185 }
186
187 static bool GetUseNativeFusion()
188 {
189 try
190 {
191 return Environment.OSVersion.Platform == PlatformID.Win32NT && !MonoRuntime && !CoreRuntime && Environment.GetEnvironmentVariable("IKVM_DISABLE_FUSION") == null;
192 }
193 catch (SecurityException)
194 {
195 return false;
196 }
197 }
198
202 public string CoreLibName => coreLibName;
203
207 public Assembly CoreLib => Load(coreLibName);
208
215 Type ImportCoreLibType(string ns, string name)
216 {
217 if (CoreLib.__IsMissing)
218 return CoreLib.ResolveType(null, new TypeName(ns, name));
219
220 // We use FindType instead of ResolveType here, because on some versions of mscorlib some of
221 // the special types we use/support are missing and the type properties are defined to
222 // return null in that case.
223 // Note that we don't have to unescape type.Name here, because none of the names contain special characters.
224 return CoreLib.FindType(new TypeName(ns, name));
225 }
226
232 Type ResolvePrimitive(string name)
233 {
234 // Primitive here means that these types have a special metadata encoding, which means that
235 // there can be references to them without referring to them by name explicitly.
236 // We want these types to be usable even when they don't exist in mscorlib or there is no mscorlib loaded.
237 return CoreLib.FindType(new TypeName("System", name)) ?? GetMissingType(null, CoreLib.ManifestModule, null, new TypeName("System", name));
238 }
239
240 internal Type System_Object => typeof_System_Object ??= ResolvePrimitive("Object");
241
242 internal Type System_ValueType => typeof_System_ValueType ??= ResolvePrimitive("ValueType");
243
244 internal Type System_Enum => typeof_System_Enum ??= ResolvePrimitive("Enum");
245
246 internal Type System_Void => typeof_System_Void ??= ResolvePrimitive("Void");
247
248 internal Type System_Boolean => typeof_System_Boolean ??= ResolvePrimitive("Boolean");
249
250 internal Type System_Char => typeof_System_Char ??= ResolvePrimitive("Char");
251
252 internal Type System_SByte => typeof_System_SByte ??= ResolvePrimitive("SByte");
253
254 internal Type System_Byte => typeof_System_Byte ??= ResolvePrimitive("Byte");
255
256 internal Type System_Int16 => typeof_System_Int16 ??= ResolvePrimitive("Int16");
257
258 internal Type System_UInt16 => typeof_System_UInt16 ??= ResolvePrimitive("UInt16");
259
260 internal Type System_Int32 => typeof_System_Int32 ??= ResolvePrimitive("Int32");
261
262 internal Type System_UInt32 => typeof_System_UInt32 ??= ResolvePrimitive("UInt32");
263
264 internal Type System_Int64 => typeof_System_Int64 ??= ResolvePrimitive("Int64");
265
266 internal Type System_UInt64 => typeof_System_UInt64 ??= ResolvePrimitive("UInt64");
267
268 internal Type System_Single => typeof_System_Single ??= ResolvePrimitive("Single");
269
270 internal Type System_Double => typeof_System_Double ??= ResolvePrimitive("Double");
271
272 internal Type System_String => typeof_System_String ??= ResolvePrimitive("String");
273
274 internal Type System_IntPtr => typeof_System_IntPtr ??= ResolvePrimitive("IntPtr");
275
276 internal Type System_UIntPtr => typeof_System_UIntPtr ??= ResolvePrimitive("UIntPtr");
277
278 internal Type System_TypedReference => typeof_System_TypedReference ??= ResolvePrimitive("TypedReference");
279
280 internal Type System_Type => typeof_System_Type ??= ResolvePrimitive("Type");
281
282 internal Type System_Array => typeof_System_Array ??= ResolvePrimitive("Array");
283
284 internal Type System_DateTime => typeof_System_DateTime ??= ImportCoreLibType("System", "DateTime");
285
286 internal Type System_DBNull => typeof_System_DBNull ??= ImportCoreLibType("System", "DBNull");
287
288 internal Type System_Decimal => typeof_System_Decimal ??= ImportCoreLibType("System", "Decimal");
289
290 internal Type System_AttributeUsageAttribute => typeof_System_AttributeUsageAttribute ??= ImportCoreLibType("System", "AttributeUsageAttribute");
291
292 internal Type System_ContextBoundObject => typeof_System_ContextBoundObject ??= ImportCoreLibType("System", "ContextBoundObject");
293
294 internal Type System_MarshalByRefObject => typeof_System_MarshalByRefObject ??= ImportCoreLibType("System", "MarshalByRefObject");
295
296 internal Type System_Console => typeof_System_Console ??= ImportCoreLibType("System", "Console");
297
298 internal Type System_IO_TextWriter => typeof_System_IO_TextWriter ??= ImportCoreLibType("System.IO", "TextWriter");
299
300 internal Type System_Runtime_InteropServices_DllImportAttribute => typeof_System_Runtime_InteropServices_DllImportAttribute ??= ImportCoreLibType("System.Runtime.InteropServices", "DllImportAttribute");
301
302 internal Type System_Runtime_InteropServices_FieldOffsetAttribute => typeof_System_Runtime_InteropServices_FieldOffsetAttribute ??= ImportCoreLibType("System.Runtime.InteropServices", "FieldOffsetAttribute");
303
304 internal Type System_Runtime_InteropServices_MarshalAsAttribute => typeof_System_Runtime_InteropServices_MarshalAsAttribute ??= ImportCoreLibType("System.Runtime.InteropServices", "MarshalAsAttribute");
305
306 internal Type System_Runtime_InteropServices_UnmanagedType => typeof_System_Runtime_InteropServices_UnmanagedType ??= ImportCoreLibType("System.Runtime.InteropServices", "UnmanagedType");
307
308 internal Type System_Runtime_InteropServices_VarEnum => typeof_System_Runtime_InteropServices_VarEnum ??= ImportCoreLibType("System.Runtime.InteropServices", "VarEnum");
309
310 internal Type System_Runtime_InteropServices_PreserveSigAttribute => typeof_System_Runtime_InteropServices_PreserveSigAttribute ??= ImportCoreLibType("System.Runtime.InteropServices", "PreserveSigAttribute");
311
312 internal Type System_Runtime_InteropServices_CallingConvention => typeof_System_Runtime_InteropServices_CallingConvention ??= ImportCoreLibType("System.Runtime.InteropServices", "CallingConvention");
313
314 internal Type System_Runtime_InteropServices_CharSet => typeof_System_Runtime_InteropServices_CharSet ??= ImportCoreLibType("System.Runtime.InteropServices", "CharSet");
315
316 internal Type System_Runtime_CompilerServices_DecimalConstantAttribute => typeof_System_Runtime_CompilerServices_DecimalConstantAttribute ??= ImportCoreLibType("System.Runtime.CompilerServices", "DecimalConstantAttribute");
317
318 internal Type System_Reflection_AssemblyCopyrightAttribute => typeof_System_Reflection_AssemblyCopyrightAttribute ??= ImportCoreLibType("System.Reflection", "AssemblyCopyrightAttribute");
319
320 internal Type System_Reflection_AssemblyTrademarkAttribute => typeof_System_Reflection_AssemblyTrademarkAttribute ??= ImportCoreLibType("System.Reflection", "AssemblyTrademarkAttribute");
321
322 internal Type System_Reflection_AssemblyProductAttribute => typeof_System_Reflection_AssemblyProductAttribute ??= ImportCoreLibType("System.Reflection", "AssemblyProductAttribute");
323
324 internal Type System_Reflection_AssemblyCompanyAttribute => typeof_System_Reflection_AssemblyCompanyAttribute ??= ImportCoreLibType("System.Reflection", "AssemblyCompanyAttribute");
325
326 internal Type System_Reflection_AssemblyDescriptionAttribute => typeof_System_Reflection_AssemblyDescriptionAttribute ??= ImportCoreLibType("System.Reflection", "AssemblyDescriptionAttribute");
327
328 internal Type System_Reflection_AssemblyTitleAttribute => typeof_System_Reflection_AssemblyTitleAttribute ??= ImportCoreLibType("System.Reflection", "AssemblyTitleAttribute");
329
330 internal Type System_Reflection_AssemblyInformationalVersionAttribute => typeof_System_Reflection_AssemblyInformationalVersionAttribute ??= ImportCoreLibType("System.Reflection", "AssemblyInformationalVersionAttribute");
331
332 internal Type System_Reflection_AssemblyFileVersionAttribute => typeof_System_Reflection_AssemblyFileVersionAttribute ??= ImportCoreLibType("System.Reflection", "AssemblyFileVersionAttribute");
333
334 internal Type System_Security_Permissions_CodeAccessSecurityAttribute => typeof_System_Security_Permissions_CodeAccessSecurityAttribute ??= ImportCoreLibType("System.Security.Permissions", "CodeAccessSecurityAttribute");
335
336 internal Type System_Security_Permissions_PermissionSetAttribute => typeof_System_Security_Permissions_PermissionSetAttribute ??= ImportCoreLibType("System.Security.Permissions", "PermissionSetAttribute");
337
338 internal Type System_Security_Permissions_SecurityAction => typeof_System_Security_Permissions_SecurityAction ??= ImportCoreLibType("System.Security.Permissions", "SecurityAction");
339
343 internal bool HasCoreLib
344 {
345 get { return GetLoadedAssembly(coreLibName) != null; }
346 }
347
351 public event ResolveEventHandler AssemblyResolve
352 {
353 add { resolvers.Add(value); }
354 remove { resolvers.Remove(value); }
355 }
356
362 public Type Import(System.Type type)
363 {
364 if (!importedTypes.TryGetValue(type, out var imported))
365 {
366 imported = ImportImpl(type);
367 if (imported != null)
368 importedTypes.Add(type, imported);
369 }
370
371 return imported;
372 }
373
382 Type ImportImpl(System.Type type)
383 {
384 // caller should not attempt to import a custom reflection type
385 if (TypeUtil.GetAssembly(type) == TypeUtil.GetAssembly(typeof(IKVM.Reflection.Type)))
386 throw new ArgumentException("Did you really want to import " + type.FullName + "?");
387
388 // array, pointer, or reference type
389 if (type.HasElementType)
390 {
391 if (type.IsArray)
392 {
393 // type has no rank
394 if (type.Name.EndsWith("[]"))
395 return Import(type.GetElementType()).MakeArrayType();
396 else
397 return Import(type.GetElementType()).MakeArrayType(type.GetArrayRank());
398 }
399
400 // reimport the underlying element type and convert to byref
401 if (type.IsByRef)
402 return Import(type.GetElementType()).MakeByRefType();
403
404 // reimport the underlying element type and convert to pointer
405 if (type.IsPointer)
406 return Import(type.GetElementType()).MakePointerType();
407
408 throw new InvalidOperationException();
409 }
410
411 // type represents a generic parameter of a generic method definition
412 if (type.IsGenericParameter)
413 {
414 if (TypeUtil.GetDeclaringMethod(type) != null)
415 throw new NotImplementedException();
416
417 return Import(type.DeclaringType).GetGenericArguments()[type.GenericParameterPosition];
418 }
419
420 if (TypeUtil.IsGenericType(type) && !TypeUtil.IsGenericTypeDefinition(type))
421 {
422 System.Type[] args = TypeUtil.GetGenericArguments(type);
423 Type[] importedArgs = new Type[args.Length];
424 for (int i = 0; i < args.Length; i++)
425 importedArgs[i] = Import(args[i]);
426
427 return Import(type.GetGenericTypeDefinition()).MakeGenericType(importedArgs);
428 }
429
430 if (TypeUtil.GetAssembly(type) == TypeUtil.GetAssembly(typeof(object)))
431 // make sure mscorlib types always end up in our mscorlib
432 return ResolveType(CoreLib, type.FullName);
433
434 // FXBUG we parse the FullName here, because type.Namespace and type.Name are both broken on the CLR
435 return ResolveType(Import(TypeUtil.GetAssembly(type)), type.FullName);
436 }
437
443 Assembly Import(System.Reflection.Assembly asm)
444 {
445 return Load(asm.FullName);
446 }
447
448 public RawModule OpenRawModule(string path)
449 {
450 path = Path.GetFullPath(path);
451
452 FileStream fs = null;
453 RawModule module;
454
455 try
456 {
457 fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read);
458 module = OpenRawModule(fs, path);
459 if (MetadataOnly == false)
460 fs = null;
461 }
462 finally
463 {
464 fs?.Dispose();
465 }
466
467 return module;
468 }
469
470 public RawModule OpenRawModule(Stream stream, string location)
471 {
472 return OpenRawModule(stream, location, false);
473 }
474
475 public RawModule OpenMappedRawModule(Stream stream, string location)
476 {
477 return OpenRawModule(stream, location, true);
478 }
479
480 RawModule OpenRawModule(Stream stream, string location, bool mapped)
481 {
482 if (!stream.CanRead || !stream.CanSeek || stream.Position != 0)
483 throw new ArgumentException("Stream must support read/seek and current position must be zero.", "stream");
484
485 return new RawModule(new ModuleReader(null, this, stream, location, mapped));
486 }
487
488 public Assembly LoadAssembly(RawModule module)
489 {
490 var refname = module.GetAssemblyName().FullName;
491 var asm = GetLoadedAssembly(refname);
492 if (asm == null)
493 {
494 var asm1 = module.ToAssembly();
495 assemblies.Add(asm1);
496 asm = asm1;
497 }
498
499 return asm;
500 }
501
502 public Assembly LoadFile(string path)
503 {
504 try
505 {
506 using (var module = OpenRawModule(path))
507 return LoadAssembly(module);
508 }
509 catch (IOException e)
510 {
511 throw new FileNotFoundException(e.Message, e);
512 }
513 catch (UnauthorizedAccessException e)
514 {
515 throw new FileNotFoundException(e.Message, e);
516 }
517 }
518
519 static string GetSimpleAssemblyName(string refname)
520 {
521 if (Fusion.ParseAssemblySimpleName(refname, out var pos, out var name) != ParseAssemblyResult.OK)
522 throw new ArgumentException();
523
524 return name;
525 }
526
527 Assembly GetLoadedAssembly(string refname)
528 {
529 if (!assembliesByName.TryGetValue(refname, out var asm) && (options & UniverseOptions.DisableDefaultAssembliesLookup) == 0)
530 {
531 var simpleName = GetSimpleAssemblyName(refname);
532 for (int i = 0; i < assemblies.Count; i++)
533 {
534 if (simpleName.Equals(assemblies[i].Name, StringComparison.OrdinalIgnoreCase) && CompareAssemblyIdentity(coreLibName, refname, false, assemblies[i].FullName, false, out var result))
535 {
536 asm = assemblies[i];
537 assembliesByName.Add(refname, asm);
538 break;
539 }
540 }
541 }
542
543 return asm;
544 }
545
546 Assembly GetDynamicAssembly(string refname)
547 {
548 var simpleName = GetSimpleAssemblyName(refname);
549 foreach (var asm in dynamicAssemblies)
550 if (simpleName.Equals(asm.Name, StringComparison.OrdinalIgnoreCase) && CompareAssemblyIdentity(coreLibName, refname, false, asm.FullName, false, out var result))
551 return asm;
552
553 return null;
554 }
555
556 public Assembly Load(string refname)
557 {
558 return Load(refname, null, true);
559 }
560
561 internal Assembly Load(string refname, Module requestingModule, bool throwOnError)
562 {
563 var asm = GetLoadedAssembly(refname);
564 if (asm != null)
565 return asm;
566
567 if (resolvers.Count == 0)
568 {
569 asm = DefaultResolver(refname, throwOnError);
570 }
571 else
572 {
573 var args = new ResolveEventArgs(refname, requestingModule == null ? null : requestingModule.Assembly);
574 foreach (var evt in resolvers)
575 {
576 asm = evt(this, args);
577 if (asm != null)
578 break;
579 }
580
581 if (asm == null)
582 asm = GetDynamicAssembly(refname);
583 }
584
585 if (asm != null)
586 {
587 // cache assembly by both the lookup name and the resolved name
588 var defname = asm.FullName;
589 assembliesByName[refname] = asm;
590 assembliesByName[defname] = asm;
591 return asm;
592 }
593
594 if (throwOnError)
595 throw new FileNotFoundException(refname);
596
597 return null;
598 }
599
600 Assembly DefaultResolver(string refname, bool throwOnError)
601 {
602 var asm = GetDynamicAssembly(refname);
603 if (asm != null)
604 return asm;
605
606 return null;
607 }
608
609 public Type GetType(string assemblyQualifiedTypeName)
610 {
611 // to be more compatible with Type.GetType(), we could call Assembly.GetCallingAssembly(),
612 // import that assembly and pass it as the context, but implicitly importing is considered evil
613 return GetType(null, assemblyQualifiedTypeName, false, false);
614 }
615
616 public Type GetType(string assemblyQualifiedTypeName, bool throwOnError)
617 {
618 // to be more compatible with Type.GetType(), we could call Assembly.GetCallingAssembly(),
619 // import that assembly and pass it as the context, but implicitly importing is considered evil
620 return GetType(null, assemblyQualifiedTypeName, throwOnError, false);
621 }
622
623 public Type GetType(string assemblyQualifiedTypeName, bool throwOnError, bool ignoreCase)
624 {
625 // to be more compatible with Type.GetType(), we could call Assembly.GetCallingAssembly(),
626 // import that assembly and pass it as the context, but implicitly importing is considered evil
627 return GetType(null, assemblyQualifiedTypeName, throwOnError, ignoreCase);
628 }
629
630 // note that context is slightly different from the calling assembly (System.Type.GetType),
631 // because context is passed to the AssemblyResolve event as the RequestingAssembly
632 public Type GetType(Assembly context, string assemblyQualifiedTypeName, bool throwOnError)
633 {
634 return GetType(context, assemblyQualifiedTypeName, throwOnError, false);
635 }
636
637 // note that context is slightly different from the calling assembly (System.Type.GetType),
638 // because context is passed to the AssemblyResolve event as the RequestingAssembly
639 public Type GetType(Assembly context, string assemblyQualifiedTypeName, bool throwOnError, bool ignoreCase)
640 {
641 TypeNameParser parser = TypeNameParser.Parse(assemblyQualifiedTypeName, throwOnError);
642 if (parser.Error)
643 {
644 return null;
645 }
646 return parser.GetType(this, context == null ? null : context.ManifestModule, throwOnError, assemblyQualifiedTypeName, false, ignoreCase);
647 }
648
649 // this is similar to GetType(Assembly context, string assemblyQualifiedTypeName, bool throwOnError),
650 // but instead it assumes that the type must exist (i.e. if EnableMissingMemberResolution is enabled
651 // it will create a missing type)
652 public Type ResolveType(Assembly context, string assemblyQualifiedTypeName)
653 {
654 TypeNameParser parser = TypeNameParser.Parse(assemblyQualifiedTypeName, false);
655 if (parser.Error)
656 {
657 return null;
658 }
659 return parser.GetType(this, context == null ? null : context.ManifestModule, false, assemblyQualifiedTypeName, true, false);
660 }
661
668 public Type GetBuiltInType(string ns, string name)
669 {
670 if (ns != "System")
671 return null;
672
673 return name switch
674 {
675 "Boolean" => System_Boolean,
676 "Char" => System_Char,
677 "Object" => System_Object,
678 "String" => System_String,
679 "Single" => System_Single,
680 "Double" => System_Double,
681 "SByte" => System_SByte,
682 "Int16" => System_Int16,
683 "Int32" => System_Int32,
684 "Int64" => System_Int64,
685 "IntPtr" => System_IntPtr,
686 "UIntPtr" => System_UIntPtr,
687 "TypedReference" => System_TypedReference,
688 "Byte" => System_Byte,
689 "UInt16" => System_UInt16,
690 "UInt32" => System_UInt32,
691 "UInt64" => System_UInt64,
692 "Void" => System_Void,
693 _ => null,
694 };
695 }
696
701 public Assembly[] GetAssemblies()
702 {
703 var array = new Assembly[assemblies.Count + dynamicAssemblies.Count];
704 for (int i = 0; i < assemblies.Count; i++)
705 array[i] = assemblies[i];
706 for (int i = 0, j = assemblies.Count; j < array.Length; i++, j++)
707 array[j] = dynamicAssemblies[i];
708
709 return array;
710 }
711
712 public bool CompareAssemblyIdentity(string coreLibName, string assemblyIdentity1, bool unified1, string assemblyIdentity2, bool unified2, out AssemblyComparisonResult result)
713 {
714 return useNativeFusion
715 ? Fusion.CompareAssemblyIdentityNative(coreLibName, assemblyIdentity1, unified1, assemblyIdentity2, unified2, out result)
716 : Fusion.CompareAssemblyIdentityPure(coreLibName, assemblyIdentity1, unified1, assemblyIdentity2, unified2, out result);
717 }
718
719 public AssemblyBuilder DefineDynamicAssembly(AssemblyName name, AssemblyBuilderAccess access)
720 {
721 return new AssemblyBuilder(this, name, null, null);
722 }
723
724 public AssemblyBuilder DefineDynamicAssembly(AssemblyName name, AssemblyBuilderAccess access, IEnumerable<CustomAttributeBuilder> assemblyAttributes)
725 {
726 return new AssemblyBuilder(this, name, null, assemblyAttributes);
727 }
728
729 public AssemblyBuilder DefineDynamicAssembly(AssemblyName name, AssemblyBuilderAccess access, string dir)
730 {
731 return new AssemblyBuilder(this, name, dir, null);
732 }
733
734 [Obsolete]
735 public AssemblyBuilder DefineDynamicAssembly(AssemblyName name, AssemblyBuilderAccess access, string dir, PermissionSet requiredPermissions, PermissionSet optionalPermissions, PermissionSet refusedPermissions)
736 {
737 var ab = new AssemblyBuilder(this, name, dir, null);
738 AddLegacyPermissionSet(ab, requiredPermissions, System.Security.Permissions.SecurityAction.RequestMinimum);
739 AddLegacyPermissionSet(ab, optionalPermissions, System.Security.Permissions.SecurityAction.RequestOptional);
740 AddLegacyPermissionSet(ab, refusedPermissions, System.Security.Permissions.SecurityAction.RequestRefuse);
741 return ab;
742 }
743
744 private static void AddLegacyPermissionSet(AssemblyBuilder ab, PermissionSet permissionSet, System.Security.Permissions.SecurityAction action)
745 {
746 if (permissionSet != null)
747 {
748 ab.__AddDeclarativeSecurity(CustomAttributeBuilder.__FromBlob(CustomAttributeBuilder.LegacyPermissionSet, (int)action, Encoding.Unicode.GetBytes(permissionSet.ToXml().ToString())));
749 }
750 }
751
752 internal void RegisterDynamicAssembly(AssemblyBuilder asm)
753 {
754 dynamicAssemblies.Add(asm);
755 }
756
757 internal void RenameAssembly(Assembly assembly, AssemblyName oldName)
758 {
759 List<string> remove = new List<string>();
760 foreach (KeyValuePair<string, Assembly> kv in assembliesByName)
761 {
762 if (kv.Value == assembly)
763 {
764 remove.Add(kv.Key);
765 }
766 }
767 foreach (string key in remove)
768 {
769 assembliesByName.Remove(key);
770 }
771 }
772
773 public void Dispose()
774 {
775 foreach (Assembly asm in assemblies)
776 {
777 foreach (Module mod in asm.GetLoadedModules())
778 {
779 mod.Dispose();
780 }
781 }
782 foreach (AssemblyBuilder asm in dynamicAssemblies)
783 {
784 foreach (Module mod in asm.GetLoadedModules())
785 {
786 mod.Dispose();
787 }
788 }
789 }
790
791 public Assembly CreateMissingAssembly(string assemblyName)
792 {
793 Assembly asm = new MissingAssembly(this, assemblyName);
794 string name = asm.FullName;
795 if (!assembliesByName.ContainsKey(name))
796 {
797 assembliesByName.Add(name, asm);
798 }
799 return asm;
800 }
801
802 [Obsolete("Please set UniverseOptions.ResolveMissingMembers instead.")]
803 public void EnableMissingMemberResolution()
804 {
805 resolveMissingMembers = true;
806 }
807
808 internal bool MissingMemberResolution
809 {
810 get { return resolveMissingMembers; }
811 }
812
813 internal bool EnableFunctionPointers
814 {
815 get { return enableFunctionPointers; }
816 }
817
818 private struct ScopedTypeName : IEquatable<ScopedTypeName>
819 {
820 private readonly object scope;
821 private readonly TypeName name;
822
823 internal ScopedTypeName(object scope, TypeName name)
824 {
825 this.scope = scope;
826 this.name = name;
827 }
828
829 public override bool Equals(object obj)
830 {
831 ScopedTypeName? other = obj as ScopedTypeName?;
832 return other != null && ((IEquatable<ScopedTypeName>)other.Value).Equals(this);
833 }
834
835 public override int GetHashCode()
836 {
837 return scope.GetHashCode() * 7 + name.GetHashCode();
838 }
839
840 bool IEquatable<ScopedTypeName>.Equals(ScopedTypeName other)
841 {
842 return other.scope == scope && other.name == name;
843 }
844 }
845
846 private Type GetMissingType(Module requester, Module module, Type declaringType, TypeName typeName)
847 {
848 if (missingTypes == null)
849 {
850 missingTypes = new Dictionary<ScopedTypeName, Type>();
851 }
852 ScopedTypeName stn = new ScopedTypeName(declaringType ?? (object)module, typeName);
853 Type type;
854 if (!missingTypes.TryGetValue(stn, out type))
855 {
856 type = new MissingType(module, declaringType, typeName.Namespace, typeName.Name);
857 missingTypes.Add(stn, type);
858 }
859 if (ResolvedMissingMember != null && !module.Assembly.__IsMissing)
860 {
861 ResolvedMissingMember(requester, type);
862 }
863 return type;
864 }
865
866 internal Type GetMissingTypeOrThrow(Module requester, Module module, Type declaringType, TypeName typeName)
867 {
868 if (resolveMissingMembers || module.Assembly.__IsMissing)
869 {
870 return GetMissingType(requester, module, declaringType, typeName);
871 }
872 string fullName = TypeNameParser.Escape(typeName.ToString());
873 if (declaringType != null)
874 {
875 fullName = declaringType.FullName + "+" + fullName;
876 }
877 throw new TypeLoadException(String.Format("Type '{0}' not found in assembly '{1}'", fullName, module.Assembly.FullName));
878 }
879
880 internal MethodBase GetMissingMethodOrThrow(Module requester, Type declaringType, string name, MethodSignature signature)
881 {
882 if (resolveMissingMembers)
883 {
884 var method = (MethodBase)new MissingMethod(declaringType, name, signature);
885 if (name == ".ctor")
886 method = new ConstructorInfoImpl((MethodInfo)method);
887
888 if (ResolvedMissingMember != null)
889 ResolvedMissingMember(requester, method);
890
891 return method;
892 }
893
894 throw new MissingMethodException(declaringType.ToString(), name);
895 }
896
897 internal FieldInfo GetMissingFieldOrThrow(Module requester, Type declaringType, string name, FieldSignature signature)
898 {
899 if (resolveMissingMembers)
900 {
901 var field = (FieldInfo)new MissingField(declaringType, name, signature);
902 if (ResolvedMissingMember != null)
903 ResolvedMissingMember(requester, field);
904
905 return field;
906 }
907
908 throw new MissingFieldException(declaringType.ToString(), name);
909 }
910
911 internal PropertyInfo GetMissingPropertyOrThrow(Module requester, Type declaringType, string name, PropertySignature propertySignature)
912 {
913 // HACK we need to check __IsMissing here, because Type doesn't have a FindProperty API
914 // since properties are never resolved, except by custom attributes
915 if (resolveMissingMembers || declaringType.__IsMissing)
916 {
917 var property = (PropertyInfo)new MissingProperty(declaringType, name, propertySignature);
918 if (ResolvedMissingMember != null && !declaringType.__IsMissing)
919 ResolvedMissingMember(requester, property);
920
921 return property;
922 }
923
924 throw new System.MissingMemberException(declaringType.ToString(), name);
925 }
926
927 internal Type CanonicalizeType(Type type)
928 {
929 if (!canonicalizedTypes.TryGetValue(type, out var canon))
930 {
931 canon = type;
932 canonicalizedTypes.Add(canon, canon);
933 }
934
935 return canon;
936 }
937
938 public Type MakeFunctionPointer(__StandAloneMethodSig sig)
939 {
940 return FunctionPointerType.Make(this, sig);
941 }
942
943 public __StandAloneMethodSig MakeStandAloneMethodSig(System.Runtime.InteropServices.CallingConvention callingConvention, Type returnType, CustomModifiers returnTypeCustomModifiers, Type[] parameterTypes, CustomModifiers[] parameterTypeCustomModifiers)
944 {
945 return new __StandAloneMethodSig(true, callingConvention, 0, returnType ?? this.System_Void, Util.Copy(parameterTypes), Type.EmptyTypes,
946 PackedCustomModifiers.CreateFromExternal(returnTypeCustomModifiers, parameterTypeCustomModifiers, Util.NullSafeLength(parameterTypes)));
947 }
948
949 public __StandAloneMethodSig MakeStandAloneMethodSig(CallingConventions callingConvention, Type returnType, CustomModifiers returnTypeCustomModifiers, Type[] parameterTypes, Type[] optionalParameterTypes, CustomModifiers[] parameterTypeCustomModifiers)
950 {
951 return new __StandAloneMethodSig(false, 0, callingConvention, returnType ?? this.System_Void, Util.Copy(parameterTypes), Util.Copy(optionalParameterTypes),
952 PackedCustomModifiers.CreateFromExternal(returnTypeCustomModifiers, parameterTypeCustomModifiers, Util.NullSafeLength(parameterTypes) + Util.NullSafeLength(optionalParameterTypes)));
953 }
954
955 public event ResolvedMissingMemberHandler ResolvedMissingMember;
956
957 public event Predicate<Type> MissingTypeIsValueType
958 {
959 add => missingTypeIsValueType = missingTypeIsValueType == null ? value : throw new InvalidOperationException("Only a single MissingTypeIsValueType handler can be registered.");
960 remove
961 {
962 if (value.Equals(missingTypeIsValueType))
963 missingTypeIsValueType = null;
964 }
965 }
966
967 internal bool ResolveMissingTypeIsValueType(MissingType missingType)
968 {
969 if (missingTypeIsValueType != null)
970 return missingTypeIsValueType(missingType);
971
972 throw new MissingMemberException(missingType);
973 }
974
975 internal bool ReturnPseudoCustomAttributes => returnPseudoCustomAttributes;
976
977 internal bool AutomaticallyProvideDefaultConstructor => automaticallyProvideDefaultConstructor;
978
979 internal bool MetadataOnly => (options & UniverseOptions.MetadataOnly) != 0;
980
981 internal bool WindowsRuntimeProjection => (options & UniverseOptions.DisableWindowsRuntimeProjection) == 0;
982
983 internal bool DecodeVersionInfoAttributeBlobs => (options & UniverseOptions.DecodeVersionInfoAttributeBlobs) != 0;
984
988 internal bool Deterministic => (options & UniverseOptions.DeterministicOutput) != 0;
989
993 internal HashAlgorithmName PdbChecksumAlgorithm => pdbChecksumAlgorithm;
994
995 }
996
997}
IKVM.Reflection.Module Module
IKVM.Reflection.Type Type
IKVM.Reflection.Assembly Assembly
IKVM.Reflection.AssemblyName AssemblyName
IKVM.Reflection.FieldInfo FieldInfo
IKVM.Reflection.PropertyInfo PropertyInfo
IKVM.Reflection.MethodInfo MethodInfo
IKVM.Reflection.MethodBase MethodBase
Represents a method signature from IL metadadata.
override string ToString()
Definition TypeName.cs:72