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 */
24 using System;
25 using System.Collections.Generic;
26 using System.IO;
27 using System.Security;
28 using System.Text;
29 using System.Diagnostics;
30 using IKVM.Reflection.Reader;
31 using IKVM.Reflection.Emit;
32 
33 namespace IKVM.Reflection
34 {
35 	public sealed class ResolveEventArgs : EventArgs
36 	{
37 		private readonly string name;
38 		private readonly Assembly requestingAssembly;
39 
ResolveEventArgs(string name)40 		public ResolveEventArgs(string name)
41 			: this(name, null)
42 		{
43 		}
44 
ResolveEventArgs(string name, Assembly requestingAssembly)45 		public ResolveEventArgs(string name, Assembly requestingAssembly)
46 		{
47 			this.name = name;
48 			this.requestingAssembly = requestingAssembly;
49 		}
50 
51 		public string Name
52 		{
53 			get { return name; }
54 		}
55 
56 		public Assembly RequestingAssembly
57 		{
58 			get { return requestingAssembly; }
59 		}
60 	}
61 
62 	public enum AssemblyComparisonResult
63 	{
64 		Unknown = 0,
65 		EquivalentFullMatch = 1,
66 		EquivalentWeakNamed = 2,
67 		EquivalentFXUnified = 3,
68 		EquivalentUnified = 4,
69 		NonEquivalentVersion = 5,
70 		NonEquivalent = 6,
71 		EquivalentPartialMatch = 7,
72 		EquivalentPartialWeakNamed = 8,
73 		EquivalentPartialUnified = 9,
74 		EquivalentPartialFXUnified = 10,
75 		NonEquivalentPartialVersion = 11,
76 	}
77 
ResolveEventHandler(object sender, ResolveEventArgs args)78 	public delegate Assembly ResolveEventHandler(object sender, ResolveEventArgs args);
79 
ResolvedMissingMemberHandler(Module requestingModule, MemberInfo member)80 	public delegate void ResolvedMissingMemberHandler(Module requestingModule, MemberInfo member);
81 
82 	/*
83 	 * UniverseOptions:
84 	 *
85 	 *   None
86 	 *		Default behavior, most compatible with System.Reflection[.Emit]
87 	 *
88 	 *   EnableFunctionPointers
89 	 *		Normally function pointers in signatures are replaced by System.IntPtr
90 	 *		(for compatibility with System.Reflection), when this option is enabled
91 	 *		they are represented as first class types (Type.__IsFunctionPointer will
92 	 *		return true for them).
93 	 *
94 	 *   DisableFusion
95 	 *      Don't use native Fusion API to resolve assembly names.
96 	 *
97 	 *   DisablePseudoCustomAttributeRetrieval
98 	 *      Set this option to disable the generaton of pseudo-custom attributes
99 	 *      when querying custom attributes.
100 	 *
101 	 *   DontProvideAutomaticDefaultConstructor
102 	 *      Normally TypeBuilder, like System.Reflection.Emit, will provide a default
103 	 *      constructor for types that meet the requirements. By enabling this
104 	 *      option this behavior is disabled.
105 	 *
106 	 *   MetadataOnly
107 	 *      By default, when a module is read in, the stream is kept open to satisfy
108 	 *      subsequent lazy loading. In MetadataOnly mode only the metadata is read in
109 	 *      and after that the stream is closed immediately. Subsequent lazy loading
110 	 *      attempts will fail with an InvalidOperationException.
111 	 *      APIs that are not available is MetadataOnly mode are:
112 	 *      - Module.ResolveString()
113 	 *      - Module.GetSignerCertificate()
114 	 *      - Module.GetManifestResourceStream()
115 	 *      - Module.__ReadDataFromRVA()
116 	 *      - MethodBase.GetMethodBody()
117 	 *      - FieldInfo.__GetDataFromRVA()
118 	 *
119 	 *   DeterministicOutput
120 	 *      The generated output file will depend only on the input. In other words,
121 	 *      the PE file header time stamp will be set to zero and the module version
122 	 *      id will be based on a SHA1 of the contents, instead of a random guid.
123 	 *      This option can not be used in combination with PDB file generation.
124 	 */
125 
126 	[Flags]
127 	public enum UniverseOptions
128 	{
129 		None = 0,
130 		EnableFunctionPointers = 1,
131 		DisableFusion = 2,
132 		DisablePseudoCustomAttributeRetrieval = 4,
133 		DontProvideAutomaticDefaultConstructor = 8,
134 		MetadataOnly = 16,
135 		ResolveMissingMembers = 32,
136 		DisableWindowsRuntimeProjection = 64,
137 		DecodeVersionInfoAttributeBlobs = 128,
138 		DeterministicOutput = 256,
139 		DisableDefaultAssembliesLookup = 512,
140 	}
141 
142 	public sealed class Universe : IDisposable
143 	{
144 		internal static readonly bool MonoRuntime = System.Type.GetType("Mono.Runtime") != null;
145 		private readonly Dictionary<Type, Type> canonicalizedTypes = new Dictionary<Type, Type>();
146 		private readonly List<AssemblyReader> assemblies = new List<AssemblyReader>();
147 		private readonly List<AssemblyBuilder> dynamicAssemblies = new List<AssemblyBuilder>();
148 		private readonly Dictionary<string, Assembly> assembliesByName = new Dictionary<string, Assembly>();
149 		private readonly Dictionary<System.Type, Type> importedTypes = new Dictionary<System.Type, Type>();
150 		private Dictionary<ScopedTypeName, Type> missingTypes;
151 		private bool resolveMissingMembers;
152 		private readonly bool enableFunctionPointers;
153 		private readonly bool useNativeFusion;
154 		private readonly bool returnPseudoCustomAttributes;
155 		private readonly bool automaticallyProvideDefaultConstructor;
156 		private readonly UniverseOptions options;
157 		private Type typeof_System_Object;
158 		private Type typeof_System_ValueType;
159 		private Type typeof_System_Enum;
160 		private Type typeof_System_Void;
161 		private Type typeof_System_Boolean;
162 		private Type typeof_System_Char;
163 		private Type typeof_System_SByte;
164 		private Type typeof_System_Byte;
165 		private Type typeof_System_Int16;
166 		private Type typeof_System_UInt16;
167 		private Type typeof_System_Int32;
168 		private Type typeof_System_UInt32;
169 		private Type typeof_System_Int64;
170 		private Type typeof_System_UInt64;
171 		private Type typeof_System_Single;
172 		private Type typeof_System_Double;
173 		private Type typeof_System_String;
174 		private Type typeof_System_IntPtr;
175 		private Type typeof_System_UIntPtr;
176 		private Type typeof_System_TypedReference;
177 		private Type typeof_System_Type;
178 		private Type typeof_System_Array;
179 		private Type typeof_System_DateTime;
180 		private Type typeof_System_DBNull;
181 		private Type typeof_System_Decimal;
182 		private Type typeof_System_AttributeUsageAttribute;
183 		private Type typeof_System_Runtime_InteropServices_DllImportAttribute;
184 		private Type typeof_System_Runtime_InteropServices_FieldOffsetAttribute;
185 		private Type typeof_System_Runtime_InteropServices_MarshalAsAttribute;
186 		private Type typeof_System_Runtime_InteropServices_UnmanagedType;
187 		private Type typeof_System_Runtime_InteropServices_VarEnum;
188 		private Type typeof_System_Runtime_InteropServices_PreserveSigAttribute;
189 		private Type typeof_System_Runtime_InteropServices_CallingConvention;
190 		private Type typeof_System_Runtime_InteropServices_CharSet;
191 		private Type typeof_System_Runtime_CompilerServices_DecimalConstantAttribute;
192 		private Type typeof_System_Reflection_AssemblyCopyrightAttribute;
193 		private Type typeof_System_Reflection_AssemblyTrademarkAttribute;
194 		private Type typeof_System_Reflection_AssemblyProductAttribute;
195 		private Type typeof_System_Reflection_AssemblyCompanyAttribute;
196 		private Type typeof_System_Reflection_AssemblyDescriptionAttribute;
197 		private Type typeof_System_Reflection_AssemblyTitleAttribute;
198 		private Type typeof_System_Reflection_AssemblyInformationalVersionAttribute;
199 		private Type typeof_System_Reflection_AssemblyFileVersionAttribute;
200 		private Type typeof_System_Security_Permissions_CodeAccessSecurityAttribute;
201 		private Type typeof_System_Security_Permissions_PermissionSetAttribute;
202 		private Type typeof_System_Security_Permissions_SecurityAction;
203 		private List<ResolveEventHandler> resolvers = new List<ResolveEventHandler>();
204 		private Predicate<Type> missingTypeIsValueType;
205 
Universe()206 		public Universe()
207 			: this(UniverseOptions.None)
208 		{
209 		}
210 
Universe(UniverseOptions options)211 		public Universe(UniverseOptions options)
212 		{
213 			this.options = options;
214 			enableFunctionPointers = (options & UniverseOptions.EnableFunctionPointers) != 0;
215 			useNativeFusion = (options & UniverseOptions.DisableFusion) == 0 && GetUseNativeFusion();
216 			returnPseudoCustomAttributes = (options & UniverseOptions.DisablePseudoCustomAttributeRetrieval) == 0;
217 			automaticallyProvideDefaultConstructor = (options & UniverseOptions.DontProvideAutomaticDefaultConstructor) == 0;
218 			resolveMissingMembers = (options & UniverseOptions.ResolveMissingMembers) != 0;
219 		}
220 
GetUseNativeFusion()221 		private static bool GetUseNativeFusion()
222 		{
223 			try
224 			{
225 				return Environment.OSVersion.Platform == PlatformID.Win32NT
226 					&& !MonoRuntime
227 					&& Environment.GetEnvironmentVariable("IKVM_DISABLE_FUSION") == null;
228 			}
229 			catch (System.Security.SecurityException)
230 			{
231 				return false;
232 			}
233 		}
234 
235 		internal Assembly Mscorlib
236 		{
237 			get { return Load("mscorlib"); }
238 		}
239 
ImportMscorlibType(string ns, string name)240 		private Type ImportMscorlibType(string ns, string name)
241 		{
242 			if (Mscorlib.__IsMissing)
243 			{
244 				return Mscorlib.ResolveType(null, new TypeName(ns, name));
245 			}
246 			// We use FindType instead of ResolveType here, because on some versions of mscorlib some of
247 			// the special types we use/support are missing and the type properties are defined to
248 			// return null in that case.
249 			// Note that we don't have to unescape type.Name here, because none of the names contain special characters.
250 			return Mscorlib.FindType(new TypeName(ns, name));
251 		}
252 
ResolvePrimitive(string name)253 		private Type ResolvePrimitive(string name)
254 		{
255 			// Primitive here means that these types have a special metadata encoding, which means that
256 			// there can be references to them without referring to them by name explicitly.
257 			// We want these types to be usable even when they don't exist in mscorlib or there is no mscorlib loaded.
258 			return Mscorlib.FindType(new TypeName("System", name)) ?? GetMissingType(null, Mscorlib.ManifestModule, null, new TypeName("System", name));
259 		}
260 
261 		internal Type System_Object
262 		{
263 			get { return typeof_System_Object ?? (typeof_System_Object = ResolvePrimitive("Object")); }
264 		}
265 
266 		internal Type System_ValueType
267 		{
268 			// System.ValueType is not a primitive, but generic type parameters can have a ValueType constraint
269 			// (we also don't want to return null here)
270 			get { return typeof_System_ValueType ?? (typeof_System_ValueType = ResolvePrimitive("ValueType")); }
271 		}
272 
273 		internal Type System_Enum
274 		{
275 			// System.Enum is not a primitive, but we don't want to return null
276 			get { return typeof_System_Enum ?? (typeof_System_Enum = ResolvePrimitive("Enum")); }
277 		}
278 
279 		internal Type System_Void
280 		{
281 			get { return typeof_System_Void ?? (typeof_System_Void = ResolvePrimitive("Void")); }
282 		}
283 
284 		internal Type System_Boolean
285 		{
286 			get { return typeof_System_Boolean ?? (typeof_System_Boolean = ResolvePrimitive("Boolean")); }
287 		}
288 
289 		internal Type System_Char
290 		{
291 			get { return typeof_System_Char ?? (typeof_System_Char = ResolvePrimitive("Char")); }
292 		}
293 
294 		internal Type System_SByte
295 		{
296 			get { return typeof_System_SByte ?? (typeof_System_SByte = ResolvePrimitive("SByte")); }
297 		}
298 
299 		internal Type System_Byte
300 		{
301 			get { return typeof_System_Byte ?? (typeof_System_Byte = ResolvePrimitive("Byte")); }
302 		}
303 
304 		internal Type System_Int16
305 		{
306 			get { return typeof_System_Int16 ?? (typeof_System_Int16 = ResolvePrimitive("Int16")); }
307 		}
308 
309 		internal Type System_UInt16
310 		{
311 			get { return typeof_System_UInt16 ?? (typeof_System_UInt16 = ResolvePrimitive("UInt16")); }
312 		}
313 
314 		internal Type System_Int32
315 		{
316 			get { return typeof_System_Int32 ?? (typeof_System_Int32 = ResolvePrimitive("Int32")); }
317 		}
318 
319 		internal Type System_UInt32
320 		{
321 			get { return typeof_System_UInt32 ?? (typeof_System_UInt32 = ResolvePrimitive("UInt32")); }
322 		}
323 
324 		internal Type System_Int64
325 		{
326 			get { return typeof_System_Int64 ?? (typeof_System_Int64 = ResolvePrimitive("Int64")); }
327 		}
328 
329 		internal Type System_UInt64
330 		{
331 			get { return typeof_System_UInt64 ?? (typeof_System_UInt64 = ResolvePrimitive("UInt64")); }
332 		}
333 
334 		internal Type System_Single
335 		{
336 			get { return typeof_System_Single ?? (typeof_System_Single = ResolvePrimitive("Single")); }
337 		}
338 
339 		internal Type System_Double
340 		{
341 			get { return typeof_System_Double ?? (typeof_System_Double = ResolvePrimitive("Double")); }
342 		}
343 
344 		internal Type System_String
345 		{
346 			get { return typeof_System_String ?? (typeof_System_String = ResolvePrimitive("String")); }
347 		}
348 
349 		internal Type System_IntPtr
350 		{
351 			get { return typeof_System_IntPtr ?? (typeof_System_IntPtr = ResolvePrimitive("IntPtr")); }
352 		}
353 
354 		internal Type System_UIntPtr
355 		{
356 			get { return typeof_System_UIntPtr ?? (typeof_System_UIntPtr = ResolvePrimitive("UIntPtr")); }
357 		}
358 
359 		internal Type System_TypedReference
360 		{
361 			get { return typeof_System_TypedReference ?? (typeof_System_TypedReference = ResolvePrimitive("TypedReference")); }
362 		}
363 
364 		internal Type System_Type
365 		{
366 			// System.Type is not a primitive, but it does have a special encoding in custom attributes
367 			get { return typeof_System_Type ?? (typeof_System_Type = ResolvePrimitive("Type")); }
368 		}
369 
370 		internal Type System_Array
371 		{
372 			// System.Array is not a primitive, but it used as a base type for array types (that are primitives)
373 			get { return typeof_System_Array ?? (typeof_System_Array = ResolvePrimitive("Array")); }
374 		}
375 
376 		internal Type System_DateTime
377 		{
378 			get { return typeof_System_DateTime ?? (typeof_System_DateTime = ImportMscorlibType("System", "DateTime")); }
379 		}
380 
381 		internal Type System_DBNull
382 		{
383 			get { return typeof_System_DBNull ?? (typeof_System_DBNull = ImportMscorlibType("System", "DBNull")); }
384 		}
385 
386 		internal Type System_Decimal
387 		{
388 			get { return typeof_System_Decimal ?? (typeof_System_Decimal = ImportMscorlibType("System", "Decimal")); }
389 		}
390 
391 		internal Type System_AttributeUsageAttribute
392 		{
393 			get { return typeof_System_AttributeUsageAttribute ?? (typeof_System_AttributeUsageAttribute = ImportMscorlibType("System", "AttributeUsageAttribute")); }
394 		}
395 
396 		internal Type System_Runtime_InteropServices_DllImportAttribute
397 		{
398 			get { return typeof_System_Runtime_InteropServices_DllImportAttribute ?? (typeof_System_Runtime_InteropServices_DllImportAttribute = ImportMscorlibType("System.Runtime.InteropServices", "DllImportAttribute")); }
399 		}
400 
401 		internal Type System_Runtime_InteropServices_FieldOffsetAttribute
402 		{
403 			get { return typeof_System_Runtime_InteropServices_FieldOffsetAttribute ?? (typeof_System_Runtime_InteropServices_FieldOffsetAttribute = ImportMscorlibType("System.Runtime.InteropServices", "FieldOffsetAttribute")); }
404 		}
405 
406 		internal Type System_Runtime_InteropServices_MarshalAsAttribute
407 		{
408 			get { return typeof_System_Runtime_InteropServices_MarshalAsAttribute ?? (typeof_System_Runtime_InteropServices_MarshalAsAttribute = ImportMscorlibType("System.Runtime.InteropServices", "MarshalAsAttribute")); }
409 		}
410 
411 		internal Type System_Runtime_InteropServices_UnmanagedType
412 		{
413 			get { return typeof_System_Runtime_InteropServices_UnmanagedType ?? (typeof_System_Runtime_InteropServices_UnmanagedType = ImportMscorlibType("System.Runtime.InteropServices", "UnmanagedType")); }
414 		}
415 
416 		internal Type System_Runtime_InteropServices_VarEnum
417 		{
418 			get { return typeof_System_Runtime_InteropServices_VarEnum ?? (typeof_System_Runtime_InteropServices_VarEnum = ImportMscorlibType("System.Runtime.InteropServices", "VarEnum")); }
419 		}
420 
421 		internal Type System_Runtime_InteropServices_PreserveSigAttribute
422 		{
423 			get { return typeof_System_Runtime_InteropServices_PreserveSigAttribute ?? (typeof_System_Runtime_InteropServices_PreserveSigAttribute = ImportMscorlibType("System.Runtime.InteropServices", "PreserveSigAttribute")); }
424 		}
425 
426 		internal Type System_Runtime_InteropServices_CallingConvention
427 		{
428 			get { return typeof_System_Runtime_InteropServices_CallingConvention ?? (typeof_System_Runtime_InteropServices_CallingConvention = ImportMscorlibType("System.Runtime.InteropServices", "CallingConvention")); }
429 		}
430 
431 		internal Type System_Runtime_InteropServices_CharSet
432 		{
433 			get { return typeof_System_Runtime_InteropServices_CharSet ?? (typeof_System_Runtime_InteropServices_CharSet = ImportMscorlibType("System.Runtime.InteropServices", "CharSet")); }
434 		}
435 
436 		internal Type System_Runtime_CompilerServices_DecimalConstantAttribute
437 		{
438 			get { return typeof_System_Runtime_CompilerServices_DecimalConstantAttribute ?? (typeof_System_Runtime_CompilerServices_DecimalConstantAttribute = ImportMscorlibType("System.Runtime.CompilerServices", "DecimalConstantAttribute")); }
439 		}
440 
441 		internal Type System_Reflection_AssemblyCopyrightAttribute
442 		{
443 			get { return typeof_System_Reflection_AssemblyCopyrightAttribute ?? (typeof_System_Reflection_AssemblyCopyrightAttribute = ImportMscorlibType("System.Reflection", "AssemblyCopyrightAttribute")); }
444 		}
445 
446 		internal Type System_Reflection_AssemblyTrademarkAttribute
447 		{
448 			get { return typeof_System_Reflection_AssemblyTrademarkAttribute ?? (typeof_System_Reflection_AssemblyTrademarkAttribute = ImportMscorlibType("System.Reflection", "AssemblyTrademarkAttribute")); }
449 		}
450 
451 		internal Type System_Reflection_AssemblyProductAttribute
452 		{
453 			get { return typeof_System_Reflection_AssemblyProductAttribute ?? (typeof_System_Reflection_AssemblyProductAttribute = ImportMscorlibType("System.Reflection", "AssemblyProductAttribute")); }
454 		}
455 
456 		internal Type System_Reflection_AssemblyCompanyAttribute
457 		{
458 			get { return typeof_System_Reflection_AssemblyCompanyAttribute ?? (typeof_System_Reflection_AssemblyCompanyAttribute = ImportMscorlibType("System.Reflection", "AssemblyCompanyAttribute")); }
459 		}
460 
461 		internal Type System_Reflection_AssemblyDescriptionAttribute
462 		{
463 			get { return typeof_System_Reflection_AssemblyDescriptionAttribute ?? (typeof_System_Reflection_AssemblyDescriptionAttribute = ImportMscorlibType("System.Reflection", "AssemblyDescriptionAttribute")); }
464 		}
465 
466 		internal Type System_Reflection_AssemblyTitleAttribute
467 		{
468 			get { return typeof_System_Reflection_AssemblyTitleAttribute ?? (typeof_System_Reflection_AssemblyTitleAttribute = ImportMscorlibType("System.Reflection", "AssemblyTitleAttribute")); }
469 		}
470 
471 		internal Type System_Reflection_AssemblyInformationalVersionAttribute
472 		{
473 			get { return typeof_System_Reflection_AssemblyInformationalVersionAttribute ?? (typeof_System_Reflection_AssemblyInformationalVersionAttribute = ImportMscorlibType("System.Reflection", "AssemblyInformationalVersionAttribute")); }
474 		}
475 
476 		internal Type System_Reflection_AssemblyFileVersionAttribute
477 		{
478 			get { return typeof_System_Reflection_AssemblyFileVersionAttribute ?? (typeof_System_Reflection_AssemblyFileVersionAttribute = ImportMscorlibType("System.Reflection", "AssemblyFileVersionAttribute")); }
479 		}
480 
481 		internal Type System_Security_Permissions_CodeAccessSecurityAttribute
482 		{
483 			get { return typeof_System_Security_Permissions_CodeAccessSecurityAttribute ?? (typeof_System_Security_Permissions_CodeAccessSecurityAttribute = ImportMscorlibType("System.Security.Permissions", "CodeAccessSecurityAttribute")); }
484 		}
485 
486 		internal Type System_Security_Permissions_PermissionSetAttribute
487 		{
488 			get { return typeof_System_Security_Permissions_PermissionSetAttribute ?? (typeof_System_Security_Permissions_PermissionSetAttribute = ImportMscorlibType("System.Security.Permissions", "PermissionSetAttribute")); }
489 		}
490 
491 		internal Type System_Security_Permissions_SecurityAction
492 		{
493 			get { return typeof_System_Security_Permissions_SecurityAction ?? (typeof_System_Security_Permissions_SecurityAction = ImportMscorlibType("System.Security.Permissions", "SecurityAction")); }
494 		}
495 
496 		internal bool HasMscorlib
497 		{
498 			get { return GetLoadedAssembly("mscorlib") != null; }
499 		}
500 
501 		public event ResolveEventHandler AssemblyResolve
502 		{
503 			add { resolvers.Add(value); }
504 			remove { resolvers.Remove(value); }
505 		}
506 
Import(System.Type type)507 		public Type Import(System.Type type)
508 		{
509 			Type imported;
510 			if (!importedTypes.TryGetValue(type, out imported))
511 			{
512 				imported = ImportImpl(type);
513 				if (imported != null)
514 				{
515 					importedTypes.Add(type, imported);
516 				}
517 			}
518 			return imported;
519 		}
520 
ImportImpl(System.Type type)521 		private Type ImportImpl(System.Type type)
522 		{
523 			if (type.Assembly == typeof(IKVM.Reflection.Type).Assembly)
524 			{
525 				throw new ArgumentException("Did you really want to import " + type.FullName + "?");
526 			}
527 			if (type.HasElementType)
528 			{
529 				if (type.IsArray)
530 				{
531 					if (type.Name.EndsWith("[]"))
532 					{
533 						return Import(type.GetElementType()).MakeArrayType();
534 					}
535 					else
536 					{
537 						return Import(type.GetElementType()).MakeArrayType(type.GetArrayRank());
538 					}
539 				}
540 				else if (type.IsByRef)
541 				{
542 					return Import(type.GetElementType()).MakeByRefType();
543 				}
544 				else if (type.IsPointer)
545 				{
546 					return Import(type.GetElementType()).MakePointerType();
547 				}
548 				else
549 				{
550 					throw new InvalidOperationException();
551 				}
552 			}
553 			else if (type.IsGenericParameter)
554 			{
555 				if (type.DeclaringMethod != null)
556 				{
557 					throw new NotImplementedException();
558 				}
559 				else
560 				{
561 					return Import(type.DeclaringType).GetGenericArguments()[type.GenericParameterPosition];
562 				}
563 			}
564 			else if (type.IsGenericType && !type.IsGenericTypeDefinition)
565 			{
566 				System.Type[] args = type.GetGenericArguments();
567 				Type[] importedArgs = new Type[args.Length];
568 				for (int i = 0; i < args.Length; i++)
569 				{
570 					importedArgs[i] = Import(args[i]);
571 				}
572 				return Import(type.GetGenericTypeDefinition()).MakeGenericType(importedArgs);
573 			}
574 			else if (type.Assembly == typeof(object).Assembly)
575 			{
576 				// make sure mscorlib types always end up in our mscorlib
577 				return ResolveType(Mscorlib, type.FullName);
578 			}
579 			else
580 			{
581 				// FXBUG we parse the FullName here, because type.Namespace and type.Name are both broken on the CLR
582 				return ResolveType(Import(type.Assembly), type.FullName);
583 			}
584 		}
585 
Import(System.Reflection.Assembly asm)586 		private Assembly Import(System.Reflection.Assembly asm)
587 		{
588 			return Load(asm.FullName);
589 		}
590 
OpenRawModule(string path)591 		public RawModule OpenRawModule(string path)
592 		{
593 			path = Path.GetFullPath(path);
594 			FileStream fs = null;
595 			RawModule module;
596 			try
597 			{
598 				fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read);
599 				module = OpenRawModule(fs, path);
600 				if (!MetadataOnly)
601 				{
602 					fs = null;
603 				}
604 			}
605 			finally
606 			{
607 				if (fs != null)
608 				{
609 					fs.Close();
610 				}
611 			}
612 			return module;
613 		}
614 
OpenRawModule(Stream stream, string location)615 		public RawModule OpenRawModule(Stream stream, string location)
616 		{
617 			return OpenRawModule(stream, location, false);
618 		}
619 
OpenMappedRawModule(Stream stream, string location)620 		public RawModule OpenMappedRawModule(Stream stream, string location)
621 		{
622 			return OpenRawModule(stream, location, true);
623 		}
624 
OpenRawModule(Stream stream, string location, bool mapped)625 		private RawModule OpenRawModule(Stream stream, string location, bool mapped)
626 		{
627 			if (!stream.CanRead || !stream.CanSeek || stream.Position != 0)
628 			{
629 				throw new ArgumentException("Stream must support read/seek and current position must be zero.", "stream");
630 			}
631 			return new RawModule(new ModuleReader(null, this, stream, location, mapped));
632 		}
633 
LoadAssembly(RawModule module)634 		public Assembly LoadAssembly(RawModule module)
635 		{
636 			string refname = module.GetAssemblyName().FullName;
637 			Assembly asm = GetLoadedAssembly(refname);
638 			if (asm == null)
639 			{
640 				AssemblyReader asm1 = module.ToAssembly();
641 				assemblies.Add(asm1);
642 				asm = asm1;
643 			}
644 			return asm;
645 		}
646 
LoadFile(string path)647 		public Assembly LoadFile(string path)
648 		{
649 			try
650 			{
651 				using (RawModule module = OpenRawModule(path))
652 				{
653 					return LoadAssembly(module);
654 				}
655 			}
656 			catch (IOException x)
657 			{
658 				throw new FileNotFoundException(x.Message, x);
659 			}
660 			catch (UnauthorizedAccessException x)
661 			{
662 				throw new FileNotFoundException(x.Message, x);
663 			}
664 		}
665 
GetSimpleAssemblyName(string refname)666 		private static string GetSimpleAssemblyName(string refname)
667 		{
668 			int pos;
669 			string name;
670 			if (Fusion.ParseAssemblySimpleName(refname, out pos, out name) != ParseAssemblyResult.OK)
671 			{
672 				throw new ArgumentException();
673 			}
674 			return name;
675 		}
676 
GetLoadedAssembly(string refname)677 		private Assembly GetLoadedAssembly(string refname)
678 		{
679 			Assembly asm;
680 			if (!assembliesByName.TryGetValue(refname, out asm) && (options & UniverseOptions.DisableDefaultAssembliesLookup) == 0)
681 			{
682 				string simpleName = GetSimpleAssemblyName(refname);
683 				for (int i = 0; i < assemblies.Count; i++)
684 				{
685 					AssemblyComparisonResult result;
686 					if (simpleName.Equals(assemblies[i].Name, StringComparison.OrdinalIgnoreCase)
687 						&& CompareAssemblyIdentity(refname, false, assemblies[i].FullName, false, out result))
688 					{
689 						asm = assemblies[i];
690 						assembliesByName.Add(refname, asm);
691 						break;
692 					}
693 				}
694 			}
695 			return asm;
696 		}
697 
GetDynamicAssembly(string refname)698 		private Assembly GetDynamicAssembly(string refname)
699 		{
700 			string simpleName = GetSimpleAssemblyName(refname);
701 			foreach (AssemblyBuilder asm in dynamicAssemblies)
702 			{
703 				AssemblyComparisonResult result;
704 				if (simpleName.Equals(asm.Name, StringComparison.OrdinalIgnoreCase)
705 					&& CompareAssemblyIdentity(refname, false, asm.FullName, false, out result))
706 				{
707 					return asm;
708 				}
709 			}
710 			return null;
711 		}
712 
Load(string refname)713 		public Assembly Load(string refname)
714 		{
715 			return Load(refname, null, true);
716 		}
717 
Load(string refname, Module requestingModule, bool throwOnError)718 		internal Assembly Load(string refname, Module requestingModule, bool throwOnError)
719 		{
720 			Assembly asm = GetLoadedAssembly(refname);
721 			if (asm != null)
722 			{
723 				return asm;
724 			}
725 			if (resolvers.Count == 0)
726 			{
727 				asm = DefaultResolver(refname, throwOnError);
728 			}
729 			else
730 			{
731 				ResolveEventArgs args = new ResolveEventArgs(refname, requestingModule == null ? null : requestingModule.Assembly);
732 				foreach (ResolveEventHandler evt in resolvers)
733 				{
734 					asm = evt(this, args);
735 					if (asm != null)
736 					{
737 						break;
738 					}
739 				}
740 				if (asm == null)
741 				{
742 					asm = GetDynamicAssembly(refname);
743 				}
744 			}
745 			if (asm != null)
746 			{
747 				string defname = asm.FullName;
748 				if (refname != defname)
749 				{
750 					assembliesByName.Add(refname, asm);
751 				}
752 				return asm;
753 			}
754 			if (throwOnError)
755 			{
756 				throw new FileNotFoundException(refname);
757 			}
758 			return null;
759 		}
760 
DefaultResolver(string refname, bool throwOnError)761 		public Assembly DefaultResolver(string refname, bool throwOnError)
762 		{
763 			Assembly asm = GetDynamicAssembly(refname);
764 			if (asm != null)
765 			{
766 				return asm;
767 			}
768 #if CORECLR
769 			return null;
770 #else
771 			string fileName;
772 			if (throwOnError)
773 			{
774 				try
775 				{
776 					fileName = System.Reflection.Assembly.ReflectionOnlyLoad(refname).Location;
777 				}
778 				catch (System.BadImageFormatException x)
779 				{
780 					throw new BadImageFormatException(x.Message, x);
781 				}
782 			}
783 			else
784 			{
785 				try
786 				{
787 					fileName = System.Reflection.Assembly.ReflectionOnlyLoad(refname).Location;
788 				}
789 				catch (System.BadImageFormatException x)
790 				{
791 					throw new BadImageFormatException(x.Message, x);
792 				}
793 				catch (FileNotFoundException)
794 				{
795 					// we intentionally only swallow the FileNotFoundException, if the file exists but isn't a valid assembly,
796 					// we should throw an exception
797 					return null;
798 				}
799 			}
800 			return LoadFile(fileName);
801 #endif
802 		}
803 
GetType(string assemblyQualifiedTypeName)804 		public Type GetType(string assemblyQualifiedTypeName)
805 		{
806 			// to be more compatible with Type.GetType(), we could call Assembly.GetCallingAssembly(),
807 			// import that assembly and pass it as the context, but implicitly importing is considered evil
808 			return GetType(null, assemblyQualifiedTypeName, false, false);
809 		}
810 
GetType(string assemblyQualifiedTypeName, bool throwOnError)811 		public Type GetType(string assemblyQualifiedTypeName, bool throwOnError)
812 		{
813 			// to be more compatible with Type.GetType(), we could call Assembly.GetCallingAssembly(),
814 			// import that assembly and pass it as the context, but implicitly importing is considered evil
815 			return GetType(null, assemblyQualifiedTypeName, throwOnError, false);
816 		}
817 
GetType(string assemblyQualifiedTypeName, bool throwOnError, bool ignoreCase)818 		public Type GetType(string assemblyQualifiedTypeName, bool throwOnError, bool ignoreCase)
819 		{
820 			// to be more compatible with Type.GetType(), we could call Assembly.GetCallingAssembly(),
821 			// import that assembly and pass it as the context, but implicitly importing is considered evil
822 			return GetType(null, assemblyQualifiedTypeName, throwOnError, ignoreCase);
823 		}
824 
825 		// note that context is slightly different from the calling assembly (System.Type.GetType),
826 		// because context is passed to the AssemblyResolve event as the RequestingAssembly
GetType(Assembly context, string assemblyQualifiedTypeName, bool throwOnError)827 		public Type GetType(Assembly context, string assemblyQualifiedTypeName, bool throwOnError)
828 		{
829 			return GetType(context, assemblyQualifiedTypeName, throwOnError, false);
830 		}
831 
832 		// note that context is slightly different from the calling assembly (System.Type.GetType),
833 		// because context is passed to the AssemblyResolve event as the RequestingAssembly
GetType(Assembly context, string assemblyQualifiedTypeName, bool throwOnError, bool ignoreCase)834 		public Type GetType(Assembly context, string assemblyQualifiedTypeName, bool throwOnError, bool ignoreCase)
835 		{
836 			TypeNameParser parser = TypeNameParser.Parse(assemblyQualifiedTypeName, throwOnError);
837 			if (parser.Error)
838 			{
839 				return null;
840 			}
841 			return parser.GetType(this, context == null ? null : context.ManifestModule, throwOnError, assemblyQualifiedTypeName, false, ignoreCase);
842 		}
843 
844 		// this is similar to GetType(Assembly context, string assemblyQualifiedTypeName, bool throwOnError),
845 		// but instead it assumes that the type must exist (i.e. if EnableMissingMemberResolution is enabled
846 		// it will create a missing type)
ResolveType(Assembly context, string assemblyQualifiedTypeName)847 		public Type ResolveType(Assembly context, string assemblyQualifiedTypeName)
848 		{
849 			TypeNameParser parser = TypeNameParser.Parse(assemblyQualifiedTypeName, false);
850 			if (parser.Error)
851 			{
852 				return null;
853 			}
854 			return parser.GetType(this, context == null ? null : context.ManifestModule, false, assemblyQualifiedTypeName, true, false);
855 		}
856 
GetBuiltInType(string ns, string name)857 		public Type GetBuiltInType(string ns, string name)
858 		{
859 			if (ns != "System")
860 			{
861 				return null;
862 			}
863 			switch (name)
864 			{
865 				case "Boolean":
866 					return System_Boolean;
867 				case "Char":
868 					return System_Char;
869 				case "Object":
870 					return System_Object;
871 				case "String":
872 					return System_String;
873 				case "Single":
874 					return System_Single;
875 				case "Double":
876 					return System_Double;
877 				case "SByte":
878 					return System_SByte;
879 				case "Int16":
880 					return System_Int16;
881 				case "Int32":
882 					return System_Int32;
883 				case "Int64":
884 					return System_Int64;
885 				case "IntPtr":
886 					return System_IntPtr;
887 				case "UIntPtr":
888 					return System_UIntPtr;
889 				case "TypedReference":
890 					return System_TypedReference;
891 				case "Byte":
892 					return System_Byte;
893 				case "UInt16":
894 					return System_UInt16;
895 				case "UInt32":
896 					return System_UInt32;
897 				case "UInt64":
898 					return System_UInt64;
899 				case "Void":
900 					return System_Void;
901 				default:
902 					return null;
903 			}
904 		}
905 
GetAssemblies()906 		public Assembly[] GetAssemblies()
907 		{
908 			Assembly[] array = new Assembly[assemblies.Count + dynamicAssemblies.Count];
909 			for (int i = 0; i < assemblies.Count; i++)
910 			{
911 				array[i] = assemblies[i];
912 			}
913 			for (int i = 0, j = assemblies.Count; j < array.Length; i++, j++)
914 			{
915 				array[j] = dynamicAssemblies[i];
916 			}
917 			return array;
918 		}
919 
920 		// this is equivalent to the Fusion CompareAssemblyIdentity API
CompareAssemblyIdentity(string assemblyIdentity1, bool unified1, string assemblyIdentity2, bool unified2, out AssemblyComparisonResult result)921 		public bool CompareAssemblyIdentity(string assemblyIdentity1, bool unified1, string assemblyIdentity2, bool unified2, out AssemblyComparisonResult result)
922 		{
923 #if CORECLR
924 			return Fusion.CompareAssemblyIdentityPure(assemblyIdentity1, unified1, assemblyIdentity2, unified2, out result);
925 #else
926 			return useNativeFusion
927 				? Fusion.CompareAssemblyIdentityNative(assemblyIdentity1, unified1, assemblyIdentity2, unified2, out result)
928 				: Fusion.CompareAssemblyIdentityPure(assemblyIdentity1, unified1, assemblyIdentity2, unified2, out result);
929 #endif
930 		}
931 
DefineDynamicAssembly(AssemblyName name, AssemblyBuilderAccess access)932 		public AssemblyBuilder DefineDynamicAssembly(AssemblyName name, AssemblyBuilderAccess access)
933 		{
934 			return new AssemblyBuilder(this, name, null, null);
935 		}
936 
DefineDynamicAssembly(AssemblyName name, AssemblyBuilderAccess access, IEnumerable<CustomAttributeBuilder> assemblyAttributes)937 		public AssemblyBuilder DefineDynamicAssembly(AssemblyName name, AssemblyBuilderAccess access, IEnumerable<CustomAttributeBuilder> assemblyAttributes)
938 		{
939 			return new AssemblyBuilder(this, name, null, assemblyAttributes);
940 		}
941 
DefineDynamicAssembly(AssemblyName name, AssemblyBuilderAccess access, string dir)942 		public AssemblyBuilder DefineDynamicAssembly(AssemblyName name, AssemblyBuilderAccess access, string dir)
943 		{
944 			return new AssemblyBuilder(this, name, dir, null);
945 		}
946 
947 #if !CORECLR
948 #if NET_4_0
949 		[Obsolete]
950 #endif
DefineDynamicAssembly(AssemblyName name, AssemblyBuilderAccess access, string dir, PermissionSet requiredPermissions, PermissionSet optionalPermissions, PermissionSet refusedPermissions)951 		public AssemblyBuilder DefineDynamicAssembly(AssemblyName name, AssemblyBuilderAccess access, string dir, PermissionSet requiredPermissions, PermissionSet optionalPermissions, PermissionSet refusedPermissions)
952 		{
953 			AssemblyBuilder ab = new AssemblyBuilder(this, name, dir, null);
954 			AddLegacyPermissionSet(ab, requiredPermissions, System.Security.Permissions.SecurityAction.RequestMinimum);
955 			AddLegacyPermissionSet(ab, optionalPermissions, System.Security.Permissions.SecurityAction.RequestOptional);
956 			AddLegacyPermissionSet(ab, refusedPermissions, System.Security.Permissions.SecurityAction.RequestRefuse);
957 			return ab;
958 		}
959 
AddLegacyPermissionSet(AssemblyBuilder ab, PermissionSet permissionSet, System.Security.Permissions.SecurityAction action)960 		private static void AddLegacyPermissionSet(AssemblyBuilder ab, PermissionSet permissionSet, System.Security.Permissions.SecurityAction action)
961 		{
962 			if (permissionSet != null)
963 			{
964 				ab.__AddDeclarativeSecurity(CustomAttributeBuilder.__FromBlob(CustomAttributeBuilder.LegacyPermissionSet, (int)action, Encoding.Unicode.GetBytes(permissionSet.ToXml().ToString())));
965 			}
966 		}
967 #endif
968 
RegisterDynamicAssembly(AssemblyBuilder asm)969 		internal void RegisterDynamicAssembly(AssemblyBuilder asm)
970 		{
971 			dynamicAssemblies.Add(asm);
972  		}
973 
RenameAssembly(Assembly assembly, AssemblyName oldName)974 		internal void RenameAssembly(Assembly assembly, AssemblyName oldName)
975 		{
976 			List<string> remove = new List<string>();
977 			foreach (KeyValuePair<string, Assembly> kv in assembliesByName)
978 			{
979 				if (kv.Value == assembly)
980 				{
981 					remove.Add(kv.Key);
982 				}
983 			}
984 			foreach (string key in remove)
985 			{
986 				assembliesByName.Remove(key);
987 			}
988 		}
989 
Dispose()990 		public void Dispose()
991 		{
992 			foreach (Assembly asm in assemblies)
993 			{
994 				foreach (Module mod in asm.GetLoadedModules())
995 				{
996 					mod.Dispose();
997 				}
998 			}
999 			foreach (AssemblyBuilder asm in dynamicAssemblies)
1000 			{
1001 				foreach (Module mod in asm.GetLoadedModules())
1002 				{
1003 					mod.Dispose();
1004 				}
1005 			}
1006 		}
1007 
CreateMissingAssembly(string assemblyName)1008 		public Assembly CreateMissingAssembly(string assemblyName)
1009 		{
1010 			Assembly asm = new MissingAssembly(this, assemblyName);
1011 			string name = asm.FullName;
1012 			if (!assembliesByName.ContainsKey(name))
1013 			{
1014 				assembliesByName.Add(name, asm);
1015 			}
1016 			return asm;
1017 		}
1018 
1019 		[Obsolete("Please set UniverseOptions.ResolveMissingMembers instead.")]
EnableMissingMemberResolution()1020 		public void EnableMissingMemberResolution()
1021 		{
1022 			resolveMissingMembers = true;
1023 		}
1024 
1025 		internal bool MissingMemberResolution
1026 		{
1027 			get { return resolveMissingMembers; }
1028 		}
1029 
1030 		internal bool EnableFunctionPointers
1031 		{
1032 			get { return enableFunctionPointers; }
1033 		}
1034 
1035 		private struct ScopedTypeName : IEquatable<ScopedTypeName>
1036 		{
1037 			private readonly object scope;
1038 			private readonly TypeName name;
1039 
ScopedTypeNameIKVM.Reflection.Universe.ScopedTypeName1040 			internal ScopedTypeName(object scope, TypeName name)
1041 			{
1042 				this.scope = scope;
1043 				this.name = name;
1044 			}
1045 
EqualsIKVM.Reflection.Universe.ScopedTypeName1046 			public override bool Equals(object obj)
1047 			{
1048 				ScopedTypeName? other = obj as ScopedTypeName?;
1049 				return other != null && ((IEquatable<ScopedTypeName>)other.Value).Equals(this);
1050 			}
1051 
GetHashCodeIKVM.Reflection.Universe.ScopedTypeName1052 			public override int GetHashCode()
1053 			{
1054 				return scope.GetHashCode() * 7 + name.GetHashCode();
1055 			}
1056 
EqualsIKVM.Reflection.Universe.ScopedTypeName1057 			bool IEquatable<ScopedTypeName>.Equals(ScopedTypeName other)
1058 			{
1059 				return other.scope == scope && other.name == name;
1060 			}
1061 		}
1062 
GetMissingType(Module requester, Module module, Type declaringType, TypeName typeName)1063 		private Type GetMissingType(Module requester, Module module, Type declaringType, TypeName typeName)
1064 		{
1065 			if (missingTypes == null)
1066 			{
1067 				missingTypes = new Dictionary<ScopedTypeName, Type>();
1068 			}
1069 			ScopedTypeName stn = new ScopedTypeName(declaringType ?? (object)module, typeName);
1070 			Type type;
1071 			if (!missingTypes.TryGetValue(stn, out type))
1072 			{
1073 				type = new MissingType(module, declaringType, typeName.Namespace, typeName.Name);
1074 				missingTypes.Add(stn, type);
1075 			}
1076 			if (ResolvedMissingMember != null && !module.Assembly.__IsMissing)
1077 			{
1078 				ResolvedMissingMember(requester, type);
1079 			}
1080 			return type;
1081 		}
1082 
GetMissingTypeOrThrow(Module requester, Module module, Type declaringType, TypeName typeName)1083 		internal Type GetMissingTypeOrThrow(Module requester, Module module, Type declaringType, TypeName typeName)
1084 		{
1085 			if (resolveMissingMembers || module.Assembly.__IsMissing)
1086 			{
1087 				return GetMissingType(requester, module, declaringType, typeName);
1088 			}
1089 			string fullName = TypeNameParser.Escape(typeName.ToString());
1090 			if (declaringType != null)
1091 			{
1092 				fullName = declaringType.FullName + "+" + fullName;
1093 			}
1094 			throw new TypeLoadException(String.Format("Type '{0}' not found in assembly '{1}'", fullName, module.Assembly.FullName));
1095 		}
1096 
GetMissingMethodOrThrow(Module requester, Type declaringType, string name, MethodSignature signature)1097 		internal MethodBase GetMissingMethodOrThrow(Module requester, Type declaringType, string name, MethodSignature signature)
1098 		{
1099 			if (resolveMissingMembers)
1100 			{
1101 				MethodBase method = new MissingMethod(declaringType, name, signature);
1102 				if (name == ".ctor")
1103 				{
1104 					method = new ConstructorInfoImpl((MethodInfo)method);
1105 				}
1106 				if (ResolvedMissingMember != null)
1107 				{
1108 					ResolvedMissingMember(requester, method);
1109 				}
1110 				return method;
1111 			}
1112 #if CORECLR
1113 			throw new MissingMethodException(declaringType.ToString() + "." + name);
1114 #else
1115 			throw new MissingMethodException(declaringType.ToString(), name);
1116 #endif
1117 		}
1118 
GetMissingFieldOrThrow(Module requester, Type declaringType, string name, FieldSignature signature)1119 		internal FieldInfo GetMissingFieldOrThrow(Module requester, Type declaringType, string name, FieldSignature signature)
1120 		{
1121 			if (resolveMissingMembers)
1122 			{
1123 				FieldInfo field = new MissingField(declaringType, name, signature);
1124 				if (ResolvedMissingMember != null)
1125 				{
1126 					ResolvedMissingMember(requester, field);
1127 				}
1128 				return field;
1129 			}
1130 #if CORECLR
1131 			throw new MissingFieldException(declaringType.ToString() + "." + name);
1132 #else
1133 			throw new MissingFieldException(declaringType.ToString(), name);
1134 #endif
1135 		}
1136 
GetMissingPropertyOrThrow(Module requester, Type declaringType, string name, PropertySignature propertySignature)1137 		internal PropertyInfo GetMissingPropertyOrThrow(Module requester, Type declaringType, string name, PropertySignature propertySignature)
1138 		{
1139 			// HACK we need to check __IsMissing here, because Type doesn't have a FindProperty API
1140 			// since properties are never resolved, except by custom attributes
1141 			if (resolveMissingMembers || declaringType.__IsMissing)
1142 			{
1143 				PropertyInfo property = new MissingProperty(declaringType, name, propertySignature);
1144 				if (ResolvedMissingMember != null && !declaringType.__IsMissing)
1145 				{
1146 					ResolvedMissingMember(requester, property);
1147 				}
1148 				return property;
1149 			}
1150 #if CORECLR
1151 			throw new System.MissingMemberException(declaringType.ToString() + "." + name);
1152 #else
1153 			throw new System.MissingMemberException(declaringType.ToString(), name);
1154 #endif
1155 		}
1156 
CanonicalizeType(Type type)1157 		internal Type CanonicalizeType(Type type)
1158 		{
1159 			Type canon;
1160 			if (!canonicalizedTypes.TryGetValue(type, out canon))
1161 			{
1162 				canon = type;
1163 				canonicalizedTypes.Add(canon, canon);
1164 			}
1165 			return canon;
1166 		}
1167 
MakeFunctionPointer(__StandAloneMethodSig sig)1168 		public Type MakeFunctionPointer(__StandAloneMethodSig sig)
1169 		{
1170 			return FunctionPointerType.Make(this, sig);
1171 		}
1172 
MakeStandAloneMethodSig(System.Runtime.InteropServices.CallingConvention callingConvention, Type returnType, CustomModifiers returnTypeCustomModifiers, Type[] parameterTypes, CustomModifiers[] parameterTypeCustomModifiers)1173 		public __StandAloneMethodSig MakeStandAloneMethodSig(System.Runtime.InteropServices.CallingConvention callingConvention, Type returnType, CustomModifiers returnTypeCustomModifiers, Type[] parameterTypes, CustomModifiers[] parameterTypeCustomModifiers)
1174 		{
1175 			return new __StandAloneMethodSig(true, callingConvention, 0, returnType ?? this.System_Void, Util.Copy(parameterTypes), Type.EmptyTypes,
1176 				PackedCustomModifiers.CreateFromExternal(returnTypeCustomModifiers, parameterTypeCustomModifiers, Util.NullSafeLength(parameterTypes)));
1177 		}
1178 
MakeStandAloneMethodSig(CallingConventions callingConvention, Type returnType, CustomModifiers returnTypeCustomModifiers, Type[] parameterTypes, Type[] optionalParameterTypes, CustomModifiers[] parameterTypeCustomModifiers)1179 		public __StandAloneMethodSig MakeStandAloneMethodSig(CallingConventions callingConvention, Type returnType, CustomModifiers returnTypeCustomModifiers, Type[] parameterTypes, Type[] optionalParameterTypes, CustomModifiers[] parameterTypeCustomModifiers)
1180 		{
1181 			return new __StandAloneMethodSig(false, 0, callingConvention, returnType ?? this.System_Void, Util.Copy(parameterTypes), Util.Copy(optionalParameterTypes),
1182 				PackedCustomModifiers.CreateFromExternal(returnTypeCustomModifiers, parameterTypeCustomModifiers, Util.NullSafeLength(parameterTypes) + Util.NullSafeLength(optionalParameterTypes)));
1183 		}
1184 
1185 		public event ResolvedMissingMemberHandler ResolvedMissingMember;
1186 
1187 		public event Predicate<Type> MissingTypeIsValueType
1188 		{
1189 			add
1190 			{
1191 				if (missingTypeIsValueType != null)
1192 				{
1193 					throw new InvalidOperationException("Only a single MissingTypeIsValueType handler can be registered.");
1194 				}
1195 				missingTypeIsValueType = value;
1196 			}
1197 			remove
1198 			{
1199 				if (value.Equals(missingTypeIsValueType))
1200 				{
1201 					missingTypeIsValueType = null;
1202 				}
1203 			}
1204 		}
1205 
FromAssembly(Assembly assembly)1206 		public static Universe FromAssembly(Assembly assembly)
1207 		{
1208 			return assembly.universe;
1209 		}
1210 
ResolveMissingTypeIsValueType(MissingType missingType)1211 		internal bool ResolveMissingTypeIsValueType(MissingType missingType)
1212 		{
1213 			if (missingTypeIsValueType != null)
1214 			{
1215 				return missingTypeIsValueType(missingType);
1216 			}
1217 			throw new MissingMemberException(missingType);
1218 		}
1219 
1220 		internal bool ReturnPseudoCustomAttributes
1221 		{
1222 			get { return returnPseudoCustomAttributes; }
1223 		}
1224 
1225 		internal bool AutomaticallyProvideDefaultConstructor
1226 		{
1227 			get { return automaticallyProvideDefaultConstructor; }
1228 		}
1229 
1230 		internal bool MetadataOnly
1231 		{
1232 			get { return (options & UniverseOptions.MetadataOnly) != 0; }
1233 		}
1234 
1235 		internal bool WindowsRuntimeProjection
1236 		{
1237 			get { return (options & UniverseOptions.DisableWindowsRuntimeProjection) == 0; }
1238 		}
1239 
1240 		internal bool DecodeVersionInfoAttributeBlobs
1241 		{
1242 			get { return (options & UniverseOptions.DecodeVersionInfoAttributeBlobs) != 0; }
1243 		}
1244 
1245 		internal bool Deterministic
1246 		{
1247 			get { return (options & UniverseOptions.DeterministicOutput) != 0; }
1248 		}
1249 	}
1250 }
1251