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 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200
|
/*
Copyright (C) 2009-2013 Jeroen Frijters
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
Jeroen Frijters
jeroen@frijters.net
*/
using System;
using System.Collections.Generic;
using System.IO;
using System.Security;
using System.Text;
using System.Diagnostics;
using IKVM.Reflection.Reader;
using IKVM.Reflection.Emit;
namespace IKVM.Reflection
{
public sealed class ResolveEventArgs : EventArgs
{
private readonly string name;
private readonly Assembly requestingAssembly;
public ResolveEventArgs(string name)
: this(name, null)
{
}
public ResolveEventArgs(string name, Assembly requestingAssembly)
{
this.name = name;
this.requestingAssembly = requestingAssembly;
}
public string Name
{
get { return name; }
}
public Assembly RequestingAssembly
{
get { return requestingAssembly; }
}
}
public enum AssemblyComparisonResult
{
Unknown = 0,
EquivalentFullMatch = 1,
EquivalentWeakNamed = 2,
EquivalentFXUnified = 3,
EquivalentUnified = 4,
NonEquivalentVersion = 5,
NonEquivalent = 6,
EquivalentPartialMatch = 7,
EquivalentPartialWeakNamed = 8,
EquivalentPartialUnified = 9,
EquivalentPartialFXUnified = 10,
NonEquivalentPartialVersion = 11,
}
public delegate Assembly ResolveEventHandler(object sender, ResolveEventArgs args);
public delegate void ResolvedMissingMemberHandler(Module requestingModule, MemberInfo member);
/*
* UniverseOptions:
*
* None
* Default behavior, most compatible with System.Reflection[.Emit]
*
* EnableFunctionPointers
* Normally function pointers in signatures are replaced by System.IntPtr
* (for compatibility with System.Reflection), when this option is enabled
* they are represented as first class types (Type.__IsFunctionPointer will
* return true for them).
*
* DisableFusion
* Don't use native Fusion API to resolve assembly names.
*
* DisablePseudoCustomAttributeRetrieval
* Set this option to disable the generaton of pseudo-custom attributes
* when querying custom attributes.
*
* DontProvideAutomaticDefaultConstructor
* Normally TypeBuilder, like System.Reflection.Emit, will provide a default
* constructor for types that meet the requirements. By enabling this
* option this behavior is disabled.
*
* MetadataOnly
* By default, when a module is read in, the stream is kept open to satisfy
* subsequent lazy loading. In MetadataOnly mode only the metadata is read in
* and after that the stream is closed immediately. Subsequent lazy loading
* attempts will fail with an InvalidOperationException.
* APIs that are not available is MetadataOnly mode are:
* - Module.ResolveString()
* - Module.GetSignerCertificate()
* - Module.GetManifestResourceStream()
* - Module.__ReadDataFromRVA()
* - MethodBase.GetMethodBody()
* - FieldInfo.__GetDataFromRVA()
*/
[Flags]
public enum UniverseOptions
{
None = 0,
EnableFunctionPointers = 1,
DisableFusion = 2,
DisablePseudoCustomAttributeRetrieval = 4,
DontProvideAutomaticDefaultConstructor = 8,
MetadataOnly = 16,
ResolveMissingMembers = 32,
SupressReferenceTypeIdentityConversion = 64
}
public sealed class Universe : IDisposable
{
internal static readonly bool MonoRuntime = System.Type.GetType("Mono.Runtime") != null;
private readonly Dictionary<Type, Type> canonicalizedTypes = new Dictionary<Type, Type>();
private readonly List<AssemblyReader> assemblies = new List<AssemblyReader>();
private readonly List<AssemblyBuilder> dynamicAssemblies = new List<AssemblyBuilder>();
private readonly Dictionary<string, Assembly> assembliesByName = new Dictionary<string, Assembly>();
private readonly Dictionary<System.Type, Type> importedTypes = new Dictionary<System.Type, Type>();
private Dictionary<ScopedTypeName, Type> missingTypes;
private bool resolveMissingMembers;
private readonly bool enableFunctionPointers;
private readonly bool useNativeFusion;
private readonly bool returnPseudoCustomAttributes;
private readonly bool automaticallyProvideDefaultConstructor;
private readonly UniverseOptions options;
private Type typeof_System_Object;
private Type typeof_System_ValueType;
private Type typeof_System_Enum;
private Type typeof_System_Void;
private Type typeof_System_Boolean;
private Type typeof_System_Char;
private Type typeof_System_SByte;
private Type typeof_System_Byte;
private Type typeof_System_Int16;
private Type typeof_System_UInt16;
private Type typeof_System_Int32;
private Type typeof_System_UInt32;
private Type typeof_System_Int64;
private Type typeof_System_UInt64;
private Type typeof_System_Single;
private Type typeof_System_Double;
private Type typeof_System_String;
private Type typeof_System_IntPtr;
private Type typeof_System_UIntPtr;
private Type typeof_System_TypedReference;
private Type typeof_System_Type;
private Type typeof_System_Array;
private Type typeof_System_DateTime;
private Type typeof_System_DBNull;
private Type typeof_System_Decimal;
private Type typeof_System_NonSerializedAttribute;
private Type typeof_System_SerializableAttribute;
private Type typeof_System_AttributeUsageAttribute;
private Type typeof_System_Runtime_InteropServices_DllImportAttribute;
private Type typeof_System_Runtime_InteropServices_FieldOffsetAttribute;
private Type typeof_System_Runtime_InteropServices_InAttribute;
private Type typeof_System_Runtime_InteropServices_MarshalAsAttribute;
private Type typeof_System_Runtime_InteropServices_UnmanagedType;
private Type typeof_System_Runtime_InteropServices_VarEnum;
private Type typeof_System_Runtime_InteropServices_OutAttribute;
private Type typeof_System_Runtime_InteropServices_StructLayoutAttribute;
private Type typeof_System_Runtime_InteropServices_OptionalAttribute;
private Type typeof_System_Runtime_InteropServices_PreserveSigAttribute;
private Type typeof_System_Runtime_InteropServices_CallingConvention;
private Type typeof_System_Runtime_InteropServices_CharSet;
private Type typeof_System_Runtime_InteropServices_ComImportAttribute;
private Type typeof_System_Runtime_CompilerServices_DecimalConstantAttribute;
private Type typeof_System_Runtime_CompilerServices_SpecialNameAttribute;
private Type typeof_System_Runtime_CompilerServices_MethodImplAttribute;
private Type typeof_System_Security_SuppressUnmanagedCodeSecurityAttribute;
private Type typeof_System_Reflection_AssemblyCopyrightAttribute;
private Type typeof_System_Reflection_AssemblyTrademarkAttribute;
private Type typeof_System_Reflection_AssemblyProductAttribute;
private Type typeof_System_Reflection_AssemblyCompanyAttribute;
private Type typeof_System_Reflection_AssemblyDescriptionAttribute;
private Type typeof_System_Reflection_AssemblyTitleAttribute;
private Type typeof_System_Reflection_AssemblyInformationalVersionAttribute;
private Type typeof_System_Reflection_AssemblyFileVersionAttribute;
private Type typeof_System_Security_Permissions_CodeAccessSecurityAttribute;
private Type typeof_System_Security_Permissions_PermissionSetAttribute;
private Type typeof_System_Security_Permissions_SecurityAction;
private List<ResolveEventHandler> resolvers = new List<ResolveEventHandler>();
private Predicate<Type> missingTypeIsValueType;
public Universe()
: this(UniverseOptions.None)
{
}
public Universe(UniverseOptions options)
{
this.options = options;
enableFunctionPointers = (options & UniverseOptions.EnableFunctionPointers) != 0;
useNativeFusion = (options & UniverseOptions.DisableFusion) == 0 && GetUseNativeFusion();
returnPseudoCustomAttributes = (options & UniverseOptions.DisablePseudoCustomAttributeRetrieval) == 0;
automaticallyProvideDefaultConstructor = (options & UniverseOptions.DontProvideAutomaticDefaultConstructor) == 0;
resolveMissingMembers = (options & UniverseOptions.ResolveMissingMembers) != 0;
}
private static bool GetUseNativeFusion()
{
try
{
return Environment.OSVersion.Platform == PlatformID.Win32NT
&& !MonoRuntime
&& Environment.GetEnvironmentVariable("IKVM_DISABLE_FUSION") == null;
}
catch (System.Security.SecurityException)
{
return false;
}
}
internal Assembly Mscorlib
{
get { return Load("mscorlib"); }
}
private Type ImportMscorlibType(System.Type type)
{
if (Mscorlib.__IsMissing)
{
return Mscorlib.ResolveType(null, new TypeName(type.Namespace, type.Name));
}
// We use FindType instead of ResolveType here, because on some versions of mscorlib some of
// the special types we use/support are missing and the type properties are defined to
// return null in that case.
// Note that we don't have to unescape type.Name here, because none of the names contain special characters.
return Mscorlib.FindType(new TypeName(type.Namespace, type.Name));
}
private Type ResolvePrimitive(string name)
{
// Primitive here means that these types have a special metadata encoding, which means that
// there can be references to them without referring to them by name explicitly.
// We want these types to be usable even when they don't exist in mscorlib or there is no mscorlib loaded.
return Mscorlib.FindType(new TypeName("System", name)) ?? GetMissingType(null, Mscorlib.ManifestModule, null, new TypeName("System", name));
}
internal Type System_Object
{
get { return typeof_System_Object ?? (typeof_System_Object = ResolvePrimitive("Object")); }
}
internal Type System_ValueType
{
// System.ValueType is not a primitive, but generic type parameters can have a ValueType constraint
// (we also don't want to return null here)
get { return typeof_System_ValueType ?? (typeof_System_ValueType = ResolvePrimitive("ValueType")); }
}
internal Type System_Enum
{
// System.Enum is not a primitive, but we don't want to return null
get { return typeof_System_Enum ?? (typeof_System_Enum = ResolvePrimitive("Enum")); }
}
internal Type System_Void
{
get { return typeof_System_Void ?? (typeof_System_Void = ResolvePrimitive("Void")); }
}
internal Type System_Boolean
{
get { return typeof_System_Boolean ?? (typeof_System_Boolean = ResolvePrimitive("Boolean")); }
}
internal Type System_Char
{
get { return typeof_System_Char ?? (typeof_System_Char = ResolvePrimitive("Char")); }
}
internal Type System_SByte
{
get { return typeof_System_SByte ?? (typeof_System_SByte = ResolvePrimitive("SByte")); }
}
internal Type System_Byte
{
get { return typeof_System_Byte ?? (typeof_System_Byte = ResolvePrimitive("Byte")); }
}
internal Type System_Int16
{
get { return typeof_System_Int16 ?? (typeof_System_Int16 = ResolvePrimitive("Int16")); }
}
internal Type System_UInt16
{
get { return typeof_System_UInt16 ?? (typeof_System_UInt16 = ResolvePrimitive("UInt16")); }
}
internal Type System_Int32
{
get { return typeof_System_Int32 ?? (typeof_System_Int32 = ResolvePrimitive("Int32")); }
}
internal Type System_UInt32
{
get { return typeof_System_UInt32 ?? (typeof_System_UInt32 = ResolvePrimitive("UInt32")); }
}
internal Type System_Int64
{
get { return typeof_System_Int64 ?? (typeof_System_Int64 = ResolvePrimitive("Int64")); }
}
internal Type System_UInt64
{
get { return typeof_System_UInt64 ?? (typeof_System_UInt64 = ResolvePrimitive("UInt64")); }
}
internal Type System_Single
{
get { return typeof_System_Single ?? (typeof_System_Single = ResolvePrimitive("Single")); }
}
internal Type System_Double
{
get { return typeof_System_Double ?? (typeof_System_Double = ResolvePrimitive("Double")); }
}
internal Type System_String
{
get { return typeof_System_String ?? (typeof_System_String = ResolvePrimitive("String")); }
}
internal Type System_IntPtr
{
get { return typeof_System_IntPtr ?? (typeof_System_IntPtr = ResolvePrimitive("IntPtr")); }
}
internal Type System_UIntPtr
{
get { return typeof_System_UIntPtr ?? (typeof_System_UIntPtr = ResolvePrimitive("UIntPtr")); }
}
internal Type System_TypedReference
{
get { return typeof_System_TypedReference ?? (typeof_System_TypedReference = ResolvePrimitive("TypedReference")); }
}
internal Type System_Type
{
// System.Type is not a primitive, but it does have a special encoding in custom attributes
get { return typeof_System_Type ?? (typeof_System_Type = ResolvePrimitive("Type")); }
}
internal Type System_Array
{
// System.Array is not a primitive, but it used as a base type for array types (that are primitives)
get { return typeof_System_Array ?? (typeof_System_Array = ResolvePrimitive("Array")); }
}
internal Type System_DateTime
{
get { return typeof_System_DateTime ?? (typeof_System_DateTime = ImportMscorlibType(typeof(System.DateTime))); }
}
internal Type System_DBNull
{
get { return typeof_System_DBNull ?? (typeof_System_DBNull = ImportMscorlibType(typeof(System.DBNull))); }
}
internal Type System_Decimal
{
get { return typeof_System_Decimal ?? (typeof_System_Decimal = ImportMscorlibType(typeof(System.Decimal))); }
}
internal Type System_NonSerializedAttribute
{
get { return typeof_System_NonSerializedAttribute ?? (typeof_System_NonSerializedAttribute = ImportMscorlibType(typeof(System.NonSerializedAttribute))); }
}
internal Type System_SerializableAttribute
{
get { return typeof_System_SerializableAttribute ?? (typeof_System_SerializableAttribute = ImportMscorlibType(typeof(System.SerializableAttribute))); }
}
internal Type System_AttributeUsageAttribute
{
get { return typeof_System_AttributeUsageAttribute ?? (typeof_System_AttributeUsageAttribute = ImportMscorlibType(typeof(System.AttributeUsageAttribute))); }
}
internal Type System_Runtime_InteropServices_DllImportAttribute
{
get { return typeof_System_Runtime_InteropServices_DllImportAttribute ?? (typeof_System_Runtime_InteropServices_DllImportAttribute = ImportMscorlibType(typeof(System.Runtime.InteropServices.DllImportAttribute))); }
}
internal Type System_Runtime_InteropServices_FieldOffsetAttribute
{
get { return typeof_System_Runtime_InteropServices_FieldOffsetAttribute ?? (typeof_System_Runtime_InteropServices_FieldOffsetAttribute = ImportMscorlibType(typeof(System.Runtime.InteropServices.FieldOffsetAttribute))); }
}
internal Type System_Runtime_InteropServices_InAttribute
{
get { return typeof_System_Runtime_InteropServices_InAttribute ?? (typeof_System_Runtime_InteropServices_InAttribute = ImportMscorlibType(typeof(System.Runtime.InteropServices.InAttribute))); }
}
internal Type System_Runtime_InteropServices_MarshalAsAttribute
{
get { return typeof_System_Runtime_InteropServices_MarshalAsAttribute ?? (typeof_System_Runtime_InteropServices_MarshalAsAttribute = ImportMscorlibType(typeof(System.Runtime.InteropServices.MarshalAsAttribute))); }
}
internal Type System_Runtime_InteropServices_UnmanagedType
{
get { return typeof_System_Runtime_InteropServices_UnmanagedType ?? (typeof_System_Runtime_InteropServices_UnmanagedType = ImportMscorlibType(typeof(System.Runtime.InteropServices.UnmanagedType))); }
}
internal Type System_Runtime_InteropServices_VarEnum
{
get { return typeof_System_Runtime_InteropServices_VarEnum ?? (typeof_System_Runtime_InteropServices_VarEnum = ImportMscorlibType(typeof(System.Runtime.InteropServices.VarEnum))); }
}
internal Type System_Runtime_InteropServices_OutAttribute
{
get { return typeof_System_Runtime_InteropServices_OutAttribute ?? (typeof_System_Runtime_InteropServices_OutAttribute = ImportMscorlibType(typeof(System.Runtime.InteropServices.OutAttribute))); }
}
internal Type System_Runtime_InteropServices_StructLayoutAttribute
{
get { return typeof_System_Runtime_InteropServices_StructLayoutAttribute ?? (typeof_System_Runtime_InteropServices_StructLayoutAttribute = ImportMscorlibType(typeof(System.Runtime.InteropServices.StructLayoutAttribute))); }
}
internal Type System_Runtime_InteropServices_OptionalAttribute
{
get { return typeof_System_Runtime_InteropServices_OptionalAttribute ?? (typeof_System_Runtime_InteropServices_OptionalAttribute = ImportMscorlibType(typeof(System.Runtime.InteropServices.OptionalAttribute))); }
}
internal Type System_Runtime_InteropServices_PreserveSigAttribute
{
get { return typeof_System_Runtime_InteropServices_PreserveSigAttribute ?? (typeof_System_Runtime_InteropServices_PreserveSigAttribute = ImportMscorlibType(typeof(System.Runtime.InteropServices.PreserveSigAttribute))); }
}
internal Type System_Runtime_InteropServices_CallingConvention
{
get { return typeof_System_Runtime_InteropServices_CallingConvention ?? (typeof_System_Runtime_InteropServices_CallingConvention = ImportMscorlibType(typeof(System.Runtime.InteropServices.CallingConvention))); }
}
internal Type System_Runtime_InteropServices_CharSet
{
get { return typeof_System_Runtime_InteropServices_CharSet ?? (typeof_System_Runtime_InteropServices_CharSet = ImportMscorlibType(typeof(System.Runtime.InteropServices.CharSet))); }
}
internal Type System_Runtime_InteropServices_ComImportAttribute
{
get { return typeof_System_Runtime_InteropServices_ComImportAttribute ?? (typeof_System_Runtime_InteropServices_ComImportAttribute = ImportMscorlibType(typeof(System.Runtime.InteropServices.ComImportAttribute))); }
}
internal Type System_Runtime_CompilerServices_DecimalConstantAttribute
{
get { return typeof_System_Runtime_CompilerServices_DecimalConstantAttribute ?? (typeof_System_Runtime_CompilerServices_DecimalConstantAttribute = ImportMscorlibType(typeof(System.Runtime.CompilerServices.DecimalConstantAttribute))); }
}
internal Type System_Runtime_CompilerServices_SpecialNameAttribute
{
get { return typeof_System_Runtime_CompilerServices_SpecialNameAttribute ?? (typeof_System_Runtime_CompilerServices_SpecialNameAttribute = ImportMscorlibType(typeof(System.Runtime.CompilerServices.SpecialNameAttribute))); }
}
internal Type System_Runtime_CompilerServices_MethodImplAttribute
{
get { return typeof_System_Runtime_CompilerServices_MethodImplAttribute ?? (typeof_System_Runtime_CompilerServices_MethodImplAttribute = ImportMscorlibType(typeof(System.Runtime.CompilerServices.MethodImplAttribute))); }
}
internal Type System_Security_SuppressUnmanagedCodeSecurityAttribute
{
get { return typeof_System_Security_SuppressUnmanagedCodeSecurityAttribute ?? (typeof_System_Security_SuppressUnmanagedCodeSecurityAttribute = ImportMscorlibType(typeof(System.Security.SuppressUnmanagedCodeSecurityAttribute))); }
}
internal Type System_Reflection_AssemblyCopyrightAttribute
{
get { return typeof_System_Reflection_AssemblyCopyrightAttribute ?? (typeof_System_Reflection_AssemblyCopyrightAttribute = ImportMscorlibType(typeof(System.Reflection.AssemblyCopyrightAttribute))); }
}
internal Type System_Reflection_AssemblyTrademarkAttribute
{
get { return typeof_System_Reflection_AssemblyTrademarkAttribute ?? (typeof_System_Reflection_AssemblyTrademarkAttribute = ImportMscorlibType(typeof(System.Reflection.AssemblyTrademarkAttribute))); }
}
internal Type System_Reflection_AssemblyProductAttribute
{
get { return typeof_System_Reflection_AssemblyProductAttribute ?? (typeof_System_Reflection_AssemblyProductAttribute = ImportMscorlibType(typeof(System.Reflection.AssemblyProductAttribute))); }
}
internal Type System_Reflection_AssemblyCompanyAttribute
{
get { return typeof_System_Reflection_AssemblyCompanyAttribute ?? (typeof_System_Reflection_AssemblyCompanyAttribute = ImportMscorlibType(typeof(System.Reflection.AssemblyCompanyAttribute))); }
}
internal Type System_Reflection_AssemblyDescriptionAttribute
{
get { return typeof_System_Reflection_AssemblyDescriptionAttribute ?? (typeof_System_Reflection_AssemblyDescriptionAttribute = ImportMscorlibType(typeof(System.Reflection.AssemblyDescriptionAttribute))); }
}
internal Type System_Reflection_AssemblyTitleAttribute
{
get { return typeof_System_Reflection_AssemblyTitleAttribute ?? (typeof_System_Reflection_AssemblyTitleAttribute = ImportMscorlibType(typeof(System.Reflection.AssemblyTitleAttribute))); }
}
internal Type System_Reflection_AssemblyInformationalVersionAttribute
{
get { return typeof_System_Reflection_AssemblyInformationalVersionAttribute ?? (typeof_System_Reflection_AssemblyInformationalVersionAttribute = ImportMscorlibType(typeof(System.Reflection.AssemblyInformationalVersionAttribute))); }
}
internal Type System_Reflection_AssemblyFileVersionAttribute
{
get { return typeof_System_Reflection_AssemblyFileVersionAttribute ?? (typeof_System_Reflection_AssemblyFileVersionAttribute = ImportMscorlibType(typeof(System.Reflection.AssemblyFileVersionAttribute))); }
}
internal Type System_Security_Permissions_CodeAccessSecurityAttribute
{
get { return typeof_System_Security_Permissions_CodeAccessSecurityAttribute ?? (typeof_System_Security_Permissions_CodeAccessSecurityAttribute = ImportMscorlibType(typeof(System.Security.Permissions.CodeAccessSecurityAttribute))); }
}
internal Type System_Security_Permissions_PermissionSetAttribute
{
get { return typeof_System_Security_Permissions_PermissionSetAttribute ?? (typeof_System_Security_Permissions_PermissionSetAttribute = ImportMscorlibType(typeof(System.Security.Permissions.PermissionSetAttribute))); }
}
internal Type System_Security_Permissions_SecurityAction
{
get { return typeof_System_Security_Permissions_SecurityAction ?? (typeof_System_Security_Permissions_SecurityAction = ImportMscorlibType(typeof(System.Security.Permissions.SecurityAction))); }
}
internal bool HasMscorlib
{
get { return GetLoadedAssembly("mscorlib") != null; }
}
public event ResolveEventHandler AssemblyResolve
{
add { resolvers.Add(value); }
remove { resolvers.Remove(value); }
}
public Type Import(System.Type type)
{
Type imported;
if (!importedTypes.TryGetValue(type, out imported))
{
imported = ImportImpl(type);
if (imported != null)
{
importedTypes.Add(type, imported);
}
}
return imported;
}
private Type ImportImpl(System.Type type)
{
if (type.Assembly == typeof(IKVM.Reflection.Type).Assembly)
{
throw new ArgumentException("Did you really want to import " + type.FullName + "?");
}
if (type.HasElementType)
{
if (type.IsArray)
{
if (type.Name.EndsWith("[]"))
{
return Import(type.GetElementType()).MakeArrayType();
}
else
{
return Import(type.GetElementType()).MakeArrayType(type.GetArrayRank());
}
}
else if (type.IsByRef)
{
return Import(type.GetElementType()).MakeByRefType();
}
else if (type.IsPointer)
{
return Import(type.GetElementType()).MakePointerType();
}
else
{
throw new InvalidOperationException();
}
}
else if (type.IsGenericParameter)
{
if (type.DeclaringMethod != null)
{
throw new NotImplementedException();
}
else
{
return Import(type.DeclaringType).GetGenericArguments()[type.GenericParameterPosition];
}
}
else if (type.IsGenericType && !type.IsGenericTypeDefinition)
{
System.Type[] args = type.GetGenericArguments();
Type[] importedArgs = new Type[args.Length];
for (int i = 0; i < args.Length; i++)
{
importedArgs[i] = Import(args[i]);
}
return Import(type.GetGenericTypeDefinition()).MakeGenericType(importedArgs);
}
else if (type.Assembly == typeof(object).Assembly)
{
// make sure mscorlib types always end up in our mscorlib
return ResolveType(Mscorlib, type.FullName);
}
else
{
// FXBUG we parse the FullName here, because type.Namespace and type.Name are both broken on the CLR
return ResolveType(Import(type.Assembly), type.FullName);
}
}
private Assembly Import(System.Reflection.Assembly asm)
{
return Load(asm.FullName);
}
public RawModule OpenRawModule(string path)
{
path = Path.GetFullPath(path);
FileStream fs = null;
RawModule module;
try
{
fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read);
module = OpenRawModule(fs, path);
if (!MetadataOnly)
{
fs = null;
}
}
finally
{
if (fs != null)
{
fs.Close();
}
}
return module;
}
public RawModule OpenRawModule(Stream stream, string location)
{
if (!stream.CanRead || !stream.CanSeek || stream.Position != 0)
{
throw new ArgumentException("Stream must support read/seek and current position must be zero.", "stream");
}
return new RawModule(new ModuleReader(null, this, stream, location));
}
public Assembly LoadAssembly(RawModule module)
{
string refname = module.GetAssemblyName().FullName;
Assembly asm = GetLoadedAssembly(refname);
if (asm == null)
{
AssemblyReader asm1 = module.ToAssembly();
assemblies.Add(asm1);
asm = asm1;
}
return asm;
}
public Assembly LoadFile(string path)
{
try
{
using (RawModule module = OpenRawModule(path))
{
return LoadAssembly(module);
}
}
catch (IOException x)
{
throw new FileNotFoundException(x.Message, x);
}
catch (UnauthorizedAccessException x)
{
throw new FileNotFoundException(x.Message, x);
}
}
private static string GetSimpleAssemblyName(string refname)
{
int pos;
string name;
if (Fusion.ParseAssemblySimpleName(refname, out pos, out name) != ParseAssemblyResult.OK)
{
throw new ArgumentException();
}
return name;
}
private Assembly GetLoadedAssembly(string refname)
{
Assembly asm;
if (!assembliesByName.TryGetValue(refname, out asm))
{
string simpleName = GetSimpleAssemblyName(refname);
for (int i = 0; i < assemblies.Count; i++)
{
AssemblyComparisonResult result;
if (simpleName.Equals(assemblies[i].Name, StringComparison.InvariantCultureIgnoreCase)
&& CompareAssemblyIdentity(refname, false, assemblies[i].FullName, false, out result))
{
asm = assemblies[i];
assembliesByName.Add(refname, asm);
break;
}
}
}
return asm;
}
private Assembly GetDynamicAssembly(string refname)
{
string simpleName = GetSimpleAssemblyName(refname);
foreach (AssemblyBuilder asm in dynamicAssemblies)
{
AssemblyComparisonResult result;
if (simpleName.Equals(asm.Name, StringComparison.InvariantCultureIgnoreCase)
&& CompareAssemblyIdentity(refname, false, asm.FullName, false, out result))
{
return asm;
}
}
return null;
}
public Assembly Load(string refname)
{
return Load(refname, null, true);
}
internal Assembly Load(string refname, Module requestingModule, bool throwOnError)
{
Assembly asm = GetLoadedAssembly(refname);
if (asm != null)
{
return asm;
}
if (resolvers.Count == 0)
{
asm = DefaultResolver(refname, throwOnError);
}
else
{
ResolveEventArgs args = new ResolveEventArgs(refname, requestingModule == null ? null : requestingModule.Assembly);
foreach (ResolveEventHandler evt in resolvers)
{
asm = evt(this, args);
if (asm != null)
{
break;
}
}
if (asm == null)
{
asm = GetDynamicAssembly(refname);
}
}
if (asm != null)
{
string defname = asm.FullName;
if (refname != defname)
{
assembliesByName.Add(refname, asm);
}
return asm;
}
if (throwOnError)
{
throw new FileNotFoundException(refname);
}
return null;
}
private Assembly DefaultResolver(string refname, bool throwOnError)
{
Assembly asm = GetDynamicAssembly(refname);
if (asm != null)
{
return asm;
}
string fileName;
if (throwOnError)
{
try
{
fileName = System.Reflection.Assembly.ReflectionOnlyLoad(refname).Location;
}
catch (System.BadImageFormatException x)
{
throw new BadImageFormatException(x.Message, x);
}
}
else
{
try
{
fileName = System.Reflection.Assembly.ReflectionOnlyLoad(refname).Location;
}
catch (System.BadImageFormatException x)
{
throw new BadImageFormatException(x.Message, x);
}
catch (FileNotFoundException)
{
// we intentionally only swallow the FileNotFoundException, if the file exists but isn't a valid assembly,
// we should throw an exception
return null;
}
}
return LoadFile(fileName);
}
public Type GetType(string assemblyQualifiedTypeName)
{
// to be more compatible with Type.GetType(), we could call Assembly.GetCallingAssembly(),
// import that assembly and pass it as the context, but implicitly importing is considered evil
return GetType(null, assemblyQualifiedTypeName, false, false);
}
public Type GetType(string assemblyQualifiedTypeName, bool throwOnError)
{
// to be more compatible with Type.GetType(), we could call Assembly.GetCallingAssembly(),
// import that assembly and pass it as the context, but implicitly importing is considered evil
return GetType(null, assemblyQualifiedTypeName, throwOnError, false);
}
public Type GetType(string assemblyQualifiedTypeName, bool throwOnError, bool ignoreCase)
{
// to be more compatible with Type.GetType(), we could call Assembly.GetCallingAssembly(),
// import that assembly and pass it as the context, but implicitly importing is considered evil
return GetType(null, assemblyQualifiedTypeName, throwOnError, ignoreCase);
}
// note that context is slightly different from the calling assembly (System.Type.GetType),
// because context is passed to the AssemblyResolve event as the RequestingAssembly
public Type GetType(Assembly context, string assemblyQualifiedTypeName, bool throwOnError)
{
return GetType(context, assemblyQualifiedTypeName, throwOnError, false);
}
// note that context is slightly different from the calling assembly (System.Type.GetType),
// because context is passed to the AssemblyResolve event as the RequestingAssembly
public Type GetType(Assembly context, string assemblyQualifiedTypeName, bool throwOnError, bool ignoreCase)
{
TypeNameParser parser = TypeNameParser.Parse(assemblyQualifiedTypeName, throwOnError);
if (parser.Error)
{
return null;
}
return parser.GetType(this, context == null ? null : context.ManifestModule, throwOnError, assemblyQualifiedTypeName, false, ignoreCase);
}
// this is similar to GetType(Assembly context, string assemblyQualifiedTypeName, bool throwOnError),
// but instead it assumes that the type must exist (i.e. if EnableMissingMemberResolution is enabled
// it will create a missing type)
public Type ResolveType(Assembly context, string assemblyQualifiedTypeName)
{
TypeNameParser parser = TypeNameParser.Parse(assemblyQualifiedTypeName, false);
if (parser.Error)
{
return null;
}
return parser.GetType(this, context == null ? null : context.ManifestModule, false, assemblyQualifiedTypeName, true, false);
}
public Assembly[] GetAssemblies()
{
Assembly[] array = new Assembly[assemblies.Count + dynamicAssemblies.Count];
for (int i = 0; i < assemblies.Count; i++)
{
array[i] = assemblies[i];
}
for (int i = 0, j = assemblies.Count; j < array.Length; i++, j++)
{
array[j] = dynamicAssemblies[i];
}
return array;
}
// this is equivalent to the Fusion CompareAssemblyIdentity API
public bool CompareAssemblyIdentity(string assemblyIdentity1, bool unified1, string assemblyIdentity2, bool unified2, out AssemblyComparisonResult result)
{
return useNativeFusion
? Fusion.CompareAssemblyIdentityNative(assemblyIdentity1, unified1, assemblyIdentity2, unified2, out result)
: Fusion.CompareAssemblyIdentityPure(assemblyIdentity1, unified1, assemblyIdentity2, unified2, out result);
}
public AssemblyBuilder DefineDynamicAssembly(AssemblyName name, AssemblyBuilderAccess access)
{
return DefineDynamicAssemblyImpl(name, access, null, null, null, null);
}
public AssemblyBuilder DefineDynamicAssembly(AssemblyName name, AssemblyBuilderAccess access, IEnumerable<CustomAttributeBuilder> assemblyAttributes)
{
AssemblyBuilder ab = DefineDynamicAssembly(name, access);
foreach (CustomAttributeBuilder cab in assemblyAttributes)
{
ab.SetCustomAttribute(cab);
}
return ab;
}
public AssemblyBuilder DefineDynamicAssembly(AssemblyName name, AssemblyBuilderAccess access, string dir)
{
return DefineDynamicAssemblyImpl(name, access, dir, null, null, null);
}
#if NET_4_0
[Obsolete]
#endif
public AssemblyBuilder DefineDynamicAssembly(AssemblyName name, AssemblyBuilderAccess access, string dir, PermissionSet requiredPermissions, PermissionSet optionalPermissions, PermissionSet refusedPermissions)
{
return DefineDynamicAssemblyImpl(name, access, dir, requiredPermissions, optionalPermissions, refusedPermissions);
}
private AssemblyBuilder DefineDynamicAssemblyImpl(AssemblyName name, AssemblyBuilderAccess access, string dir, PermissionSet requiredPermissions, PermissionSet optionalPermissions, PermissionSet refusedPermissions)
{
AssemblyBuilder asm = new AssemblyBuilder(this, name, dir, requiredPermissions, optionalPermissions, refusedPermissions);
dynamicAssemblies.Add(asm);
return asm;
}
internal void RenameAssembly(Assembly assembly, AssemblyName oldName)
{
List<string> remove = new List<string>();
foreach (KeyValuePair<string, Assembly> kv in assembliesByName)
{
if (kv.Value == assembly)
{
remove.Add(kv.Key);
}
}
foreach (string key in remove)
{
assembliesByName.Remove(key);
}
}
public void Dispose()
{
foreach (Assembly asm in assemblies)
{
foreach (Module mod in asm.GetLoadedModules())
{
mod.Dispose();
}
}
foreach (AssemblyBuilder asm in dynamicAssemblies)
{
foreach (Module mod in asm.GetLoadedModules())
{
mod.Dispose();
}
}
}
public Assembly CreateMissingAssembly(string assemblyName)
{
Assembly asm = new MissingAssembly(this, assemblyName);
string name = asm.FullName;
if (!assembliesByName.ContainsKey(name))
{
assembliesByName.Add(name, asm);
}
return asm;
}
[Obsolete("Please set UniverseOptions.ResolveMissingMembers instead.")]
public void EnableMissingMemberResolution()
{
resolveMissingMembers = true;
}
internal bool MissingMemberResolution
{
get { return resolveMissingMembers; }
}
internal bool EnableFunctionPointers
{
get { return enableFunctionPointers; }
}
private struct ScopedTypeName : IEquatable<ScopedTypeName>
{
private readonly object scope;
private readonly TypeName name;
internal ScopedTypeName(object scope, TypeName name)
{
this.scope = scope;
this.name = name;
}
public override bool Equals(object obj)
{
ScopedTypeName? other = obj as ScopedTypeName?;
return other != null && ((IEquatable<ScopedTypeName>)other.Value).Equals(this);
}
public override int GetHashCode()
{
return scope.GetHashCode() * 7 + name.GetHashCode();
}
bool IEquatable<ScopedTypeName>.Equals(ScopedTypeName other)
{
return other.scope == scope && other.name == name;
}
}
private Type GetMissingType(Module requester, Module module, Type declaringType, TypeName typeName)
{
if (missingTypes == null)
{
missingTypes = new Dictionary<ScopedTypeName, Type>();
}
ScopedTypeName stn = new ScopedTypeName(declaringType ?? (object)module, typeName);
Type type;
if (!missingTypes.TryGetValue(stn, out type))
{
type = new MissingType(module, declaringType, typeName.Namespace, typeName.Name);
missingTypes.Add(stn, type);
}
if (ResolvedMissingMember != null && !module.Assembly.__IsMissing)
{
ResolvedMissingMember(requester, type);
}
return type;
}
internal Type GetMissingTypeOrThrow(Module requester, Module module, Type declaringType, TypeName typeName)
{
if (resolveMissingMembers || module.Assembly.__IsMissing)
{
return GetMissingType(requester, module, declaringType, typeName);
}
string fullName = TypeNameParser.Escape(typeName.ToString());
if (declaringType != null)
{
fullName = declaringType.FullName + "+" + fullName;
}
throw new TypeLoadException(String.Format("Type '{0}' not found in assembly '{1}'", fullName, module.Assembly.FullName));
}
internal MethodBase GetMissingMethodOrThrow(Module requester, Type declaringType, string name, MethodSignature signature)
{
if (resolveMissingMembers)
{
MethodBase method = new MissingMethod(declaringType, name, signature);
if (name == ".ctor")
{
method = new ConstructorInfoImpl((MethodInfo)method);
}
if (ResolvedMissingMember != null)
{
ResolvedMissingMember(requester, method);
}
return method;
}
throw new MissingMethodException(declaringType.ToString(), name);
}
internal FieldInfo GetMissingFieldOrThrow(Module requester, Type declaringType, string name, FieldSignature signature)
{
if (resolveMissingMembers)
{
FieldInfo field = new MissingField(declaringType, name, signature);
if (ResolvedMissingMember != null)
{
ResolvedMissingMember(requester, field);
}
return field;
}
throw new MissingFieldException(declaringType.ToString(), name);
}
internal PropertyInfo GetMissingPropertyOrThrow(Module requester, Type declaringType, string name, PropertySignature propertySignature)
{
// HACK we need to check __IsMissing here, because Type doesn't have a FindProperty API
// since properties are never resolved, except by custom attributes
if (resolveMissingMembers || declaringType.__IsMissing)
{
PropertyInfo property = new MissingProperty(declaringType, name, propertySignature);
if (ResolvedMissingMember != null && !declaringType.__IsMissing)
{
ResolvedMissingMember(requester, property);
}
return property;
}
throw new System.MissingMemberException(declaringType.ToString(), name);
}
internal Type CanonicalizeType(Type type)
{
Type canon;
if (!canonicalizedTypes.TryGetValue(type, out canon))
{
canon = type;
canonicalizedTypes.Add(canon, canon);
}
return canon;
}
public Type MakeFunctionPointer(__StandAloneMethodSig sig)
{
return FunctionPointerType.Make(this, sig);
}
public __StandAloneMethodSig MakeStandAloneMethodSig(System.Runtime.InteropServices.CallingConvention callingConvention, Type returnType, CustomModifiers returnTypeCustomModifiers, Type[] parameterTypes, CustomModifiers[] parameterTypeCustomModifiers)
{
return new __StandAloneMethodSig(true, callingConvention, 0, returnType ?? this.System_Void, Util.Copy(parameterTypes), Type.EmptyTypes,
PackedCustomModifiers.CreateFromExternal(returnTypeCustomModifiers, parameterTypeCustomModifiers, Util.NullSafeLength(parameterTypes)));
}
public __StandAloneMethodSig MakeStandAloneMethodSig(CallingConventions callingConvention, Type returnType, CustomModifiers returnTypeCustomModifiers, Type[] parameterTypes, Type[] optionalParameterTypes, CustomModifiers[] parameterTypeCustomModifiers)
{
return new __StandAloneMethodSig(false, 0, callingConvention, returnType ?? this.System_Void, Util.Copy(parameterTypes), Util.Copy(optionalParameterTypes),
PackedCustomModifiers.CreateFromExternal(returnTypeCustomModifiers, parameterTypeCustomModifiers, Util.NullSafeLength(parameterTypes) + Util.NullSafeLength(optionalParameterTypes)));
}
public event ResolvedMissingMemberHandler ResolvedMissingMember;
public event Predicate<Type> MissingTypeIsValueType
{
add
{
if (missingTypeIsValueType != null)
{
throw new InvalidOperationException("Only a single MissingTypeIsValueType handler can be registered.");
}
missingTypeIsValueType = value;
}
remove
{
if (value.Equals(missingTypeIsValueType))
{
missingTypeIsValueType = null;
}
}
}
internal bool ResolveMissingTypeIsValueType(MissingType missingType)
{
if (missingTypeIsValueType != null)
{
return missingTypeIsValueType(missingType);
}
throw new MissingMemberException(missingType);
}
internal bool ReturnPseudoCustomAttributes
{
get { return returnPseudoCustomAttributes; }
}
internal bool AutomaticallyProvideDefaultConstructor
{
get { return automaticallyProvideDefaultConstructor; }
}
internal bool MetadataOnly
{
get { return (options & UniverseOptions.MetadataOnly) != 0; }
}
internal bool SupressReferenceTypeIdentityConversion
{
get { return (options & UniverseOptions.SupressReferenceTypeIdentityConversion) != 0; }
}
}
}
|