Welcome to mirror list, hosted at ThFree Co, Russian Federation.

ClassLoaderWrapper.cs « runtime - github.com/mono/ikvm-fork.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: d04d05dd47b5619cc81db854482b941a605389ad (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
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
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
/*
  Copyright (C) 2002-2015 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;
#if STATIC_COMPILER || STUB_GENERATOR
using IKVM.Reflection;
using IKVM.Reflection.Emit;
using Type = IKVM.Reflection.Type;
using ProtectionDomain = System.Object;
#else
using System.Reflection;
using System.Reflection.Emit;
using ProtectionDomain = java.security.ProtectionDomain;
#endif
using System.IO;
using System.Collections.Generic;
using System.Diagnostics;
using System.Threading;
using System.Runtime.CompilerServices;
using IKVM.Attributes;

namespace IKVM.Internal
{
	[Flags]
	enum CodeGenOptions
	{
		None = 0,
		Debug = 1,
		NoStackTraceInfo = 2,
		StrictFinalFieldSemantics = 4,
		NoJNI = 8,
		RemoveAsserts = 16,
		NoAutomagicSerialization = 32,
		DisableDynamicBinding = 64,
		NoRefEmitHelpers = 128,
		RemoveUnusedFields = 256,
	}

	[Flags]
	enum LoadMode
	{
		// These are the modes that should be used
		Find					= ReturnNull,
		LoadOrNull				= Load | ReturnNull,
		LoadOrThrow				= Load | ThrowClassNotFound,
		Link					= Load | ReturnUnloadable | SuppressExceptions,

		// call into Java class loader
		Load					= 0x0001,

		// return value
		DontReturnUnloadable	= 0x0002,	// This is used with a bitwise OR to disable returning unloadable
		ReturnUnloadable		= 0x0004,
		ReturnNull				= 0x0004 | DontReturnUnloadable,
		ThrowClassNotFound		= 0x0008 | DontReturnUnloadable,
		MaskReturn				= ReturnUnloadable | ReturnNull | ThrowClassNotFound,

		// exceptions (not ClassNotFoundException)
		SuppressExceptions		= 0x0010,

		// warnings
		WarnClassNotFound		= 0x0020,
	}

#if !STUB_GENERATOR
	abstract class TypeWrapperFactory
	{
		internal abstract ModuleBuilder ModuleBuilder { get; }
		internal abstract TypeWrapper DefineClassImpl(Dictionary<string, TypeWrapper> types, TypeWrapper host, ClassFile f, ClassLoaderWrapper classLoader, ProtectionDomain protectionDomain);
		internal abstract bool ReserveName(string name);
		internal abstract string AllocMangledName(DynamicTypeWrapper tw);
		internal abstract Type DefineUnloadable(string name);
		internal abstract Type DefineDelegate(int parameterCount, bool returnVoid);
		internal abstract bool HasInternalAccess { get; }
#if CLASSGC
		internal abstract void AddInternalsVisibleTo(Assembly friend);
#endif
	}
#endif // !STUB_GENERATOR

	class ClassLoaderWrapper
	{
		private static readonly object wrapperLock = new object();
		private static readonly Dictionary<Type, TypeWrapper> globalTypeToTypeWrapper = new Dictionary<Type, TypeWrapper>();
#if STATIC_COMPILER || STUB_GENERATOR
		private static ClassLoaderWrapper bootstrapClassLoader;
#else
		private static AssemblyClassLoader bootstrapClassLoader;
#endif
		private static List<GenericClassLoaderWrapper> genericClassLoaders;
#if !STATIC_COMPILER && !FIRST_PASS && !STUB_GENERATOR
		protected java.lang.ClassLoader javaClassLoader;
#endif
#if !STUB_GENERATOR
		private TypeWrapperFactory factory;
#endif // !STUB_GENERATOR
		private readonly Dictionary<string, TypeWrapper> types = new Dictionary<string, TypeWrapper>();
		private readonly Dictionary<string, Thread> defineClassInProgress = new Dictionary<string, Thread>();
		private List<IntPtr> nativeLibraries;
		private readonly CodeGenOptions codegenoptions;
#if CLASSGC
		private Dictionary<Type, TypeWrapper> typeToTypeWrapper;
		private static ConditionalWeakTable<Assembly, ClassLoaderWrapper> dynamicAssemblies;
#endif
		private static readonly Dictionary<Type, string> remappedTypes = new Dictionary<Type, string>();

#if STATIC_COMPILER || STUB_GENERATOR
		// HACK this is used by the ahead-of-time compiler to overrule the bootstrap classloader
		// when we're compiling the core class libraries and by ikvmstub with the -bootstrap option
		internal static void SetBootstrapClassLoader(ClassLoaderWrapper bootstrapClassLoader)
		{
			Debug.Assert(ClassLoaderWrapper.bootstrapClassLoader == null);

			ClassLoaderWrapper.bootstrapClassLoader = bootstrapClassLoader;
		}
#endif

		static ClassLoaderWrapper()
		{
			globalTypeToTypeWrapper[PrimitiveTypeWrapper.BOOLEAN.TypeAsTBD] = PrimitiveTypeWrapper.BOOLEAN;
			globalTypeToTypeWrapper[PrimitiveTypeWrapper.BYTE.TypeAsTBD] = PrimitiveTypeWrapper.BYTE;
			globalTypeToTypeWrapper[PrimitiveTypeWrapper.CHAR.TypeAsTBD] = PrimitiveTypeWrapper.CHAR;
			globalTypeToTypeWrapper[PrimitiveTypeWrapper.DOUBLE.TypeAsTBD] = PrimitiveTypeWrapper.DOUBLE;
			globalTypeToTypeWrapper[PrimitiveTypeWrapper.FLOAT.TypeAsTBD] = PrimitiveTypeWrapper.FLOAT;
			globalTypeToTypeWrapper[PrimitiveTypeWrapper.INT.TypeAsTBD] = PrimitiveTypeWrapper.INT;
			globalTypeToTypeWrapper[PrimitiveTypeWrapper.LONG.TypeAsTBD] = PrimitiveTypeWrapper.LONG;
			globalTypeToTypeWrapper[PrimitiveTypeWrapper.SHORT.TypeAsTBD] = PrimitiveTypeWrapper.SHORT;
			globalTypeToTypeWrapper[PrimitiveTypeWrapper.VOID.TypeAsTBD] = PrimitiveTypeWrapper.VOID;
			LoadRemappedTypes();
		}

		internal static void LoadRemappedTypes()
		{
			// if we're compiling the core, coreAssembly will be null
			Assembly coreAssembly = JVM.CoreAssembly;
			if(coreAssembly != null && remappedTypes.Count ==0)
			{
				RemappedClassAttribute[] remapped = AttributeHelper.GetRemappedClasses(coreAssembly);
				if(remapped.Length > 0)
				{
					foreach(RemappedClassAttribute r in remapped)
					{
						remappedTypes.Add(r.RemappedType, r.Name);
					}
				}
				else
				{
#if STATIC_COMPILER
					throw new FatalCompilerErrorException(Message.CoreClassesMissing);
#else
					JVM.CriticalFailure("Failed to find core classes in core library", null);
#endif
				}
			}
		}

		internal ClassLoaderWrapper(CodeGenOptions codegenoptions, object javaClassLoader)
		{
			this.codegenoptions = codegenoptions;
#if !STATIC_COMPILER && !FIRST_PASS && !STUB_GENERATOR
			this.javaClassLoader = (java.lang.ClassLoader)javaClassLoader;
#endif
		}

		internal static bool IsRemappedType(Type type)
		{
			return remappedTypes.ContainsKey(type);
		}

#if STATIC_COMPILER || STUB_GENERATOR
		internal void SetRemappedType(Type type, TypeWrapper tw)
		{
			lock(types)
			{
				types.Add(tw.Name, tw);
			}
			lock(globalTypeToTypeWrapper)
			{
				globalTypeToTypeWrapper.Add(type, tw);
			}
			remappedTypes.Add(type, tw.Name);
		}
#endif

		// return the TypeWrapper if it is already loaded, this exists for DynamicTypeWrapper.SetupGhosts
		// and implements ClassLoader.findLoadedClass()
		internal TypeWrapper FindLoadedClass(string name)
		{
			if (name.Length > 1 && name[0] == '[')
			{
				return FindOrLoadArrayClass(name, LoadMode.Find);
			}
			TypeWrapper tw;
			lock (types)
			{
				types.TryGetValue(name, out tw);
			}
			return tw ?? FindLoadedClassLazy(name);
		}

		protected virtual TypeWrapper FindLoadedClassLazy(string name)
		{
			return null;
		}

		internal TypeWrapper RegisterInitiatingLoader(TypeWrapper tw)
		{
			Debug.Assert(tw != null);
			Debug.Assert(!tw.IsUnloadable);
			Debug.Assert(!tw.IsPrimitive);

			try
			{
				// critical code in the finally block to avoid Thread.Abort interrupting the thread
			}
			finally
			{
				tw = RegisterInitiatingLoaderCritical(tw);
			}
			return tw;
		}

		private TypeWrapper RegisterInitiatingLoaderCritical(TypeWrapper tw)
		{
			lock(types)
			{
				TypeWrapper existing;
				types.TryGetValue(tw.Name, out existing);
				if(existing != tw)
				{
					if(existing != null)
					{
						// another thread beat us to it, discard the new TypeWrapper and
						// return the previous one
						return existing;
					}
					// NOTE if types.ContainsKey(tw.Name) is true (i.e. the value is null),
					// we currently have a DefineClass in progress on another thread and we've
					// beaten that thread to the punch by loading the class from a parent class
					// loader instead. This is ok as DefineClass will throw a LinkageError when
					// it is done.
					types[tw.Name] = tw;
				}
			}
			return tw;
		}

		internal bool EmitDebugInfo
		{
			get
			{
				return (codegenoptions & CodeGenOptions.Debug) != 0;
			}
		}

		internal bool EmitStackTraceInfo
		{
			get
			{
				// NOTE we're negating the flag here!
				return (codegenoptions & CodeGenOptions.NoStackTraceInfo) == 0;
			}
		}

		internal bool StrictFinalFieldSemantics
		{
			get
			{
				return (codegenoptions & CodeGenOptions.StrictFinalFieldSemantics) != 0;
			}
		}

		internal bool NoJNI
		{
			get
			{
				return (codegenoptions & CodeGenOptions.NoJNI) != 0;
			}
		}

		internal bool RemoveAsserts
		{
			get
			{
				return (codegenoptions & CodeGenOptions.RemoveAsserts) != 0;
			}
		}

		internal bool NoAutomagicSerialization
		{
			get
			{
				return (codegenoptions & CodeGenOptions.NoAutomagicSerialization) != 0;
			}
		}

		internal bool DisableDynamicBinding
		{
			get
			{
				return (codegenoptions & CodeGenOptions.DisableDynamicBinding) != 0;
			}
		}

		internal bool EmitNoRefEmitHelpers
		{
			get
			{
				return (codegenoptions & CodeGenOptions.NoRefEmitHelpers) != 0;
			}
		}

		internal bool RemoveUnusedFields
		{
			get
			{
				return (codegenoptions & CodeGenOptions.RemoveUnusedFields) != 0;
			}
		}

		internal bool WorkaroundAbstractMethodWidening
		{
			get
			{
				// pre-Roslyn C# compiler doesn't like widening access to abstract methods
				return true;
			}
		}

		internal bool WorkaroundInterfaceFields
		{
			get
			{
				// pre-Roslyn C# compiler doesn't allow access to interface fields
				return true;
			}
		}

		internal bool WorkaroundInterfacePrivateMethods
		{
			get
			{
				// pre-Roslyn C# compiler doesn't like interfaces that have non-public methods
				return true;
			}
		}

		internal bool WorkaroundInterfaceStaticMethods
		{
			get
			{
				// pre-Roslyn C# compiler doesn't allow access to interface static methods
				return true;
			}
		}

#if !STATIC_COMPILER && !STUB_GENERATOR
		internal bool RelaxedClassNameValidation
		{
			get
			{
#if FIRST_PASS
				return true;
#else
				return JVM.relaxedVerification && (javaClassLoader == null || java.lang.ClassLoader.isTrustedLoader(javaClassLoader));
#endif
			}
		}
#endif // !STATIC_COMPILER && !STUB_GENERATOR

		protected virtual void CheckProhibitedPackage(string className)
		{
			if (className.StartsWith("java.", StringComparison.Ordinal))
			{
				throw new JavaSecurityException("Prohibited package name: " + className.Substring(0, className.LastIndexOf('.')));
			}
		}

#if !STUB_GENERATOR
		internal TypeWrapper DefineClass(ClassFile f, ProtectionDomain protectionDomain)
		{
#if !STATIC_COMPILER
			string dotnetAssembly = f.IKVMAssemblyAttribute;
			if(dotnetAssembly != null)
			{
				// It's a stub class generated by ikvmstub (or generated by the runtime when getResource was
				// called on a statically compiled class).
				ClassLoaderWrapper loader;
				try
				{
					loader = ClassLoaderWrapper.GetAssemblyClassLoaderByName(dotnetAssembly);
				}
				catch(Exception x)
				{
					// TODO don't catch all exceptions here
					throw new NoClassDefFoundError(f.Name + " (" + x.Message + ")");
				}
				TypeWrapper tw = loader.LoadClassByDottedNameFast(f.Name);
				if(tw == null)
				{
					throw new NoClassDefFoundError(f.Name + " (type not found in " + dotnetAssembly + ")");
				}
				return RegisterInitiatingLoader(tw);
			}
#endif
			CheckProhibitedPackage(f.Name);
			// check if the class already exists if we're an AssemblyClassLoader
			if(FindLoadedClassLazy(f.Name) != null)
			{
				throw new LinkageError("duplicate class definition: " + f.Name);
			}
			TypeWrapper def;
			try
			{
				// critical code in the finally block to avoid Thread.Abort interrupting the thread
			}
			finally
			{
				def = DefineClassCritical(f, protectionDomain);
			}
			return def;
		}

		private TypeWrapper DefineClassCritical(ClassFile f, ProtectionDomain protectionDomain)
		{
			lock(types)
			{
				if(types.ContainsKey(f.Name))
				{
					throw new LinkageError("duplicate class definition: " + f.Name);
				}
				// mark the type as "loading in progress", so that we can detect circular dependencies.
				types.Add(f.Name, null);
				defineClassInProgress.Add(f.Name, Thread.CurrentThread);
			}
			try
			{
				return GetTypeWrapperFactory().DefineClassImpl(types, null, f, this, protectionDomain);
			}
			finally
			{
				lock(types)
				{
					if(types[f.Name] == null)
					{
						// if loading the class fails, we remove the indicator that we're busy loading the class,
						// because otherwise we get a ClassCircularityError if we try to load the class again.
						types.Remove(f.Name);
					}
					defineClassInProgress.Remove(f.Name);
					Monitor.PulseAll(types);
				}
			}
		}

		internal TypeWrapperFactory GetTypeWrapperFactory()
		{
			if(factory == null)
			{
				lock(this)
				{
					try
					{
						// critical code in the finally block to avoid Thread.Abort interrupting the thread
					}
					finally
					{
						if(factory == null)
						{
#if CLASSGC
							if(dynamicAssemblies == null)
							{
								Interlocked.CompareExchange(ref dynamicAssemblies, new ConditionalWeakTable<Assembly, ClassLoaderWrapper>(), null);
							}
							typeToTypeWrapper = new Dictionary<Type, TypeWrapper>();
							DynamicClassLoader instance = DynamicClassLoader.Get(this);
							dynamicAssemblies.Add(instance.ModuleBuilder.Assembly.ManifestModule.Assembly, this);
							this.factory = instance;
#else
							factory = DynamicClassLoader.Get(this);
#endif
						}
					}
				}
			}
			return factory;
		}
#endif // !STUB_GENERATOR

		internal TypeWrapper LoadClassByDottedName(string name)
		{
			return LoadClass(name, LoadMode.LoadOrThrow);
		}

		internal TypeWrapper LoadClassByDottedNameFast(string name)
		{
			return LoadClass(name, LoadMode.LoadOrNull);
		}

		internal TypeWrapper LoadClass(string name, LoadMode mode)
		{
			Profiler.Enter("LoadClass");
			try
			{
				TypeWrapper tw = LoadRegisteredOrPendingClass(name);
				if (tw != null)
				{
					return tw;
				}
				if (name.Length > 1 && name[0] == '[')
				{
					tw = FindOrLoadArrayClass(name, mode);
				}
				else
				{
					tw = LoadClassImpl(name, mode);
				}
				if (tw != null)
				{
					return RegisterInitiatingLoader(tw);
				}
#if STATIC_COMPILER
				if (!(name.Length > 1 && name[0] == '[') && ((mode & LoadMode.WarnClassNotFound) != 0) || WarningLevelHigh)
				{
					IssueMessage(Message.ClassNotFound, name);
				}
#else
				if (!(name.Length > 1 && name[0] == '['))
				{
					Tracer.Error(Tracer.ClassLoading, "Class not found: {0}", name);
				}
#endif
				switch (mode & LoadMode.MaskReturn)
				{
					case LoadMode.ReturnNull:
						return null;
					case LoadMode.ReturnUnloadable:
						return new UnloadableTypeWrapper(name);
					case LoadMode.ThrowClassNotFound:
						throw new ClassNotFoundException(name);
					default:
						throw new InvalidOperationException();
				}
			}
			finally
			{
				Profiler.Leave("LoadClass");
			}
		}

		private TypeWrapper LoadRegisteredOrPendingClass(string name)
		{
			TypeWrapper tw;
			lock (types)
			{
				if (types.TryGetValue(name, out tw) && tw == null)
				{
					Thread defineThread;
					if (defineClassInProgress.TryGetValue(name, out defineThread))
					{
						if (Thread.CurrentThread == defineThread)
						{
							throw new ClassCircularityError(name);
						}
						// the requested class is currently being defined by another thread,
						// so we have to wait on that
						while (defineClassInProgress.ContainsKey(name))
						{
							Monitor.Wait(types);
						}
						// the defineClass may have failed, so we need to use TryGetValue
						types.TryGetValue(name, out tw);
					}
				}
			}
			return tw;
		}

		private TypeWrapper FindOrLoadArrayClass(string name, LoadMode mode)
		{
			int dims = 1;
			while(name[dims] == '[')
			{
				dims++;
				if(dims == name.Length)
				{
					// malformed class name
					return null;
				}
			}
			if(name[dims] == 'L')
			{
				if(!name.EndsWith(";") || name.Length <= dims + 2 || name[dims + 1] == '[')
				{
					// malformed class name
					return null;
				}
				string elemClass = name.Substring(dims + 1, name.Length - dims - 2);
				// NOTE it's important that we're registered as the initiating loader
				// for the element type here
				TypeWrapper type = LoadClass(elemClass, mode | LoadMode.DontReturnUnloadable);
				if(type != null)
				{
					type = CreateArrayType(name, type, dims);
				}
				return type;
			}
			if(name.Length != dims + 1)
			{
				// malformed class name
				return null;
			}
			switch(name[dims])
			{
				case 'B':
					return CreateArrayType(name, PrimitiveTypeWrapper.BYTE, dims);
				case 'C':
					return CreateArrayType(name, PrimitiveTypeWrapper.CHAR, dims);
				case 'D':
					return CreateArrayType(name, PrimitiveTypeWrapper.DOUBLE, dims);
				case 'F':
					return CreateArrayType(name, PrimitiveTypeWrapper.FLOAT, dims);
				case 'I':
					return CreateArrayType(name, PrimitiveTypeWrapper.INT, dims);
				case 'J':
					return CreateArrayType(name, PrimitiveTypeWrapper.LONG, dims);
				case 'S':
					return CreateArrayType(name, PrimitiveTypeWrapper.SHORT, dims);
				case 'Z':
					return CreateArrayType(name, PrimitiveTypeWrapper.BOOLEAN, dims);
				default:
					return null;
			}
		}

		internal TypeWrapper FindOrLoadGenericClass(string name, LoadMode mode)
		{
			// we don't want to expose any failures to load any of the component types
			mode = (mode & LoadMode.MaskReturn) | LoadMode.ReturnNull;

			// we need to handle delegate methods here (for generic delegates)
			// (note that other types with manufactured inner classes such as Attribute and Enum can't be generic)
			if (name.EndsWith(DotNetTypeWrapper.DelegateInterfaceSuffix))
			{
				TypeWrapper outer = FindOrLoadGenericClass(name.Substring(0, name.Length - DotNetTypeWrapper.DelegateInterfaceSuffix.Length), mode);
				if (outer != null && outer.IsFakeTypeContainer)
				{
					foreach (TypeWrapper tw in outer.InnerClasses)
					{
						if (tw.Name == name)
						{
							return tw;
						}
					}
				}
			}
			// generic class name grammar:
			//
			// mangled(open_generic_type_name) "_$$$_" M(parameter_class_name) ( "_$$_" M(parameter_class_name) )* "_$$$$_"
			//
			// mangled() is the normal name mangling algorithm
			// M() is a replacement of "__" with "$$005F$$005F" followed by a replace of "." with "__"
			//
			int pos = name.IndexOf("_$$$_");
			if(pos <= 0 || !name.EndsWith("_$$$$_"))
			{
				return null;
			}
			TypeWrapper def = LoadClass(name.Substring(0, pos), mode);
			if (def == null || !def.TypeAsTBD.IsGenericTypeDefinition)
			{
				return null;
			}
			Type type = def.TypeAsTBD;
			List<string> typeParamNames = new List<string>();
			pos += 5;
			int start = pos;
			int nest = 0;
			for(;;)
			{
				pos = name.IndexOf("_$$", pos);
				if(pos == -1)
				{
					return null;
				}
				if(name.IndexOf("_$$_", pos, 4) == pos)
				{
					if(nest == 0)
					{
						typeParamNames.Add(name.Substring(start, pos - start));
						start = pos + 4;
					}
					pos += 4;
				}
				else if(name.IndexOf("_$$$_", pos, 5) == pos)
				{
					nest++;
					pos += 5;
				}
				else if(name.IndexOf("_$$$$_", pos, 6) == pos)
				{
					if(nest == 0)
					{
						if(pos + 6 != name.Length)
						{
							return null;
						}
						typeParamNames.Add(name.Substring(start, pos - start));
						break;
					}
					nest--;
					pos += 6;
				}
				else
				{
					pos += 3;
				}
			}
			Type[] typeArguments = new Type[typeParamNames.Count];
			for(int i = 0; i < typeArguments.Length; i++)
			{
				string s = (string)typeParamNames[i];
				// only do the unmangling for non-generic types (because we don't want to convert
				// the double underscores in two adjacent _$$$_ or _$$$$_ markers)
				if(s.IndexOf("_$$$_") == -1)
				{
					s = s.Replace("__", ".");
					s = s.Replace("$$005F$$005F", "__");
				}
				int dims = 0;
				while(s.Length > dims && s[dims] == 'A')
				{
					dims++;
				}
				if(s.Length == dims)
				{
					return null;
				}
				TypeWrapper tw;
				switch(s[dims])
				{
					case 'L':
						tw = LoadClass(s.Substring(dims + 1), mode);
						if(tw == null)
						{
							return null;
						}
						tw.Finish();
						break;
					case 'Z':
						tw = PrimitiveTypeWrapper.BOOLEAN;
						break;
					case 'B':
						tw = PrimitiveTypeWrapper.BYTE;
						break;
					case 'S':
						tw = PrimitiveTypeWrapper.SHORT;
						break;
					case 'C':
						tw = PrimitiveTypeWrapper.CHAR;
						break;
					case 'I':
						tw = PrimitiveTypeWrapper.INT;
						break;
					case 'F':
						tw = PrimitiveTypeWrapper.FLOAT;
						break;
					case 'J':
						tw = PrimitiveTypeWrapper.LONG;
						break;
					case 'D':
						tw = PrimitiveTypeWrapper.DOUBLE;
						break;
					default:
						return null;
				}
				if(dims > 0)
				{
					tw = tw.MakeArrayType(dims);
				}
				typeArguments[i] = tw.TypeAsSignatureType;
			}
			try
			{
				type = type.MakeGenericType(typeArguments);
			}
			catch(ArgumentException)
			{
				// one of the typeArguments failed to meet the constraints
				return null;
			}
			TypeWrapper wrapper = GetWrapperFromType(type);
			if(wrapper != null && wrapper.Name != name)
			{
				// the name specified was not in canonical form
				return null;
			}
			return wrapper;
		}

		protected virtual TypeWrapper LoadClassImpl(string name, LoadMode mode)
		{
			TypeWrapper tw = FindOrLoadGenericClass(name, mode);
			if(tw != null)
			{
				return tw;
			}
#if !STATIC_COMPILER && !FIRST_PASS && !STUB_GENERATOR
			if((mode & LoadMode.Load) == 0)
			{
				return null;
			}
			Profiler.Enter("ClassLoader.loadClass");
			try
			{
				java.lang.Class c = GetJavaClassLoader().loadClassInternal(name);
				if(c == null)
				{
					return null;
				}
				TypeWrapper type = TypeWrapper.FromClass(c);
				if(type.Name != name)
				{
					// the class loader is trying to trick us
					return null;
				}
				return type;
			}
			catch(java.lang.ClassNotFoundException x)
			{
				if((mode & LoadMode.MaskReturn) == LoadMode.ThrowClassNotFound)
				{
					throw new ClassLoadingException(ikvm.runtime.Util.mapException(x), name);
				}
				return null;
			}
			catch(java.lang.ThreadDeath)
			{
				throw;
			}
			catch(Exception x)
			{
				if((mode & LoadMode.SuppressExceptions) == 0)
				{
					throw new ClassLoadingException(ikvm.runtime.Util.mapException(x), name);
				}
				if(Tracer.ClassLoading.TraceError)
				{
					java.lang.ClassLoader cl = GetJavaClassLoader();
					if(cl != null)
					{
						System.Text.StringBuilder sb = new System.Text.StringBuilder();
						string sep = "";
						while(cl != null)
						{
							sb.Append(sep).Append(cl);
							sep = " -> ";
							cl = cl.getParent();
						}
						Tracer.Error(Tracer.ClassLoading, "ClassLoader chain: {0}", sb);
					}
					Exception m = ikvm.runtime.Util.mapException(x);
					Tracer.Error(Tracer.ClassLoading, m.ToString() + Environment.NewLine + m.StackTrace);
				}
				return null;
			}
			finally
			{
				Profiler.Leave("ClassLoader.loadClass");
			}
#else
			return null;
#endif
		}

		private static TypeWrapper CreateArrayType(string name, TypeWrapper elementTypeWrapper, int dims)
		{
			Debug.Assert(new String('[', dims) + elementTypeWrapper.SigName == name);
			Debug.Assert(!elementTypeWrapper.IsUnloadable && !elementTypeWrapper.IsVerifierType && !elementTypeWrapper.IsArray);
			Debug.Assert(dims >= 1);
			return elementTypeWrapper.GetClassLoader().RegisterInitiatingLoader(new ArrayTypeWrapper(elementTypeWrapper, name));
		}

#if !STATIC_COMPILER && !STUB_GENERATOR
		internal virtual java.lang.ClassLoader GetJavaClassLoader()
		{
#if FIRST_PASS
			return null;
#else
			return javaClassLoader;
#endif
		}
#endif

		// NOTE this exposes potentially unfinished types
		internal Type[] ArgTypeListFromSig(string sig)
		{
			if(sig[1] == ')')
			{
				return Type.EmptyTypes;
			}
			TypeWrapper[] wrappers = ArgTypeWrapperListFromSig(sig, LoadMode.LoadOrThrow);
			Type[] types = new Type[wrappers.Length];
			for(int i = 0; i < wrappers.Length; i++)
			{
				types[i] = wrappers[i].TypeAsSignatureType;
			}
			return types;
		}

		// NOTE: this will ignore anything following the sig marker (so that it can be used to decode method signatures)
		private TypeWrapper SigDecoderWrapper(ref int index, string sig, LoadMode mode)
		{
			switch(sig[index++])
			{
				case 'B':
					return PrimitiveTypeWrapper.BYTE;
				case 'C':
					return PrimitiveTypeWrapper.CHAR;
				case 'D':
					return PrimitiveTypeWrapper.DOUBLE;
				case 'F':
					return PrimitiveTypeWrapper.FLOAT;
				case 'I':
					return PrimitiveTypeWrapper.INT;
				case 'J':
					return PrimitiveTypeWrapper.LONG;
				case 'L':
				{
					int pos = index;
					index = sig.IndexOf(';', index) + 1;
					return LoadClass(sig.Substring(pos, index - pos - 1), mode);
				}
				case 'S':
					return PrimitiveTypeWrapper.SHORT;
				case 'Z':
					return PrimitiveTypeWrapper.BOOLEAN;
				case 'V':
					return PrimitiveTypeWrapper.VOID;
				case '[':
				{
					// TODO this can be optimized
					string array = "[";
					while(sig[index] == '[')
					{
						index++;
						array += "[";
					}
					switch(sig[index])
					{
						case 'L':
						{
							int pos = index;
							index = sig.IndexOf(';', index) + 1;
							return LoadClass(array + sig.Substring(pos, index - pos), mode);
						}
						case 'B':
						case 'C':
						case 'D':
						case 'F':
						case 'I':
						case 'J':
						case 'S':
						case 'Z':
							return LoadClass(array + sig[index++], mode);
						default:
							throw new InvalidOperationException(sig.Substring(index));
					}
				}
				default:
					throw new InvalidOperationException(sig.Substring(index));
			}
		}

		internal TypeWrapper FieldTypeWrapperFromSig(string sig, LoadMode mode)
		{
			int index = 0;
			return SigDecoderWrapper(ref index, sig, mode);
		}

		internal TypeWrapper RetTypeWrapperFromSig(string sig, LoadMode mode)
		{
			int index = sig.IndexOf(')') + 1;
			return SigDecoderWrapper(ref index, sig, mode);
		}

		internal TypeWrapper[] ArgTypeWrapperListFromSig(string sig, LoadMode mode)
		{
			if(sig[1] == ')')
			{
				return TypeWrapper.EmptyArray;
			}
			List<TypeWrapper> list = new List<TypeWrapper>();
			for(int i = 1; sig[i] != ')';)
			{
				list.Add(SigDecoderWrapper(ref i, sig, mode));
			}
			return list.ToArray();
		}

#if STATIC_COMPILER || STUB_GENERATOR
		internal static ClassLoaderWrapper GetBootstrapClassLoader()
#else
		internal static AssemblyClassLoader GetBootstrapClassLoader()
#endif
		{
			lock(wrapperLock)
			{
				if(bootstrapClassLoader == null)
				{
					bootstrapClassLoader = new BootstrapClassLoader();
				}
				return bootstrapClassLoader;
			}
		}

#if !STATIC_COMPILER && !STUB_GENERATOR
		internal static ClassLoaderWrapper GetClassLoaderWrapper(java.lang.ClassLoader javaClassLoader)
		{
			if(javaClassLoader == null)
			{
				return GetBootstrapClassLoader();
			}
			lock(wrapperLock)
			{
#if FIRST_PASS
				ClassLoaderWrapper wrapper = null;
#else
				ClassLoaderWrapper wrapper = 
#if __MonoCS__
					// MONOBUG the redundant cast to ClassLoaderWrapper is to workaround an mcs bug
					(ClassLoaderWrapper)(object)
#endif
					javaClassLoader.wrapper;
#endif
				if(wrapper == null)
				{
					CodeGenOptions opt = CodeGenOptions.None;
					if(JVM.EmitSymbols)
					{
						opt |= CodeGenOptions.Debug;
					}
#if NET_4_0
					if (!AppDomain.CurrentDomain.IsFullyTrusted)
					{
						opt |= CodeGenOptions.NoAutomagicSerialization;
					}
#endif
					wrapper = new ClassLoaderWrapper(opt, javaClassLoader);
					SetWrapperForClassLoader(javaClassLoader, wrapper);
				}
				return wrapper;
			}
		}
#endif

#if CLASSGC
		internal static ClassLoaderWrapper GetClassLoaderForDynamicJavaAssembly(Assembly asm)
		{
			ClassLoaderWrapper loader;
			dynamicAssemblies.TryGetValue(asm, out loader);
			return loader;
		}
#endif // CLASSGC

		internal static TypeWrapper GetWrapperFromType(Type type)
		{
#if STATIC_COMPILER
			if (type.__ContainsMissingType)
			{
				return new UnloadableTypeWrapper(type);
			}
#endif
			//Tracer.Info(Tracer.Runtime, "GetWrapperFromType: {0}", type.AssemblyQualifiedName);
#if !STATIC_COMPILER
			TypeWrapper.AssertFinished(type);
#endif
			Debug.Assert(!type.IsPointer);
			Debug.Assert(!type.IsByRef);
			TypeWrapper wrapper;
			lock(globalTypeToTypeWrapper)
			{
				globalTypeToTypeWrapper.TryGetValue(type, out wrapper);
			}
			if(wrapper != null)
			{
				return wrapper;
			}
#if STUB_GENERATOR
			if(type.__IsMissing || type.__ContainsMissingType)
			{
				wrapper = new UnloadableTypeWrapper("Missing/" + type.Assembly.FullName);
				globalTypeToTypeWrapper.Add(type, wrapper);
				return wrapper;
			}
#endif
			string remapped;
			if(remappedTypes.TryGetValue(type, out remapped))
			{
				wrapper = LoadClassCritical(remapped);
			}
			else if(ReflectUtil.IsVector(type))
			{
				// it might be an array of a dynamically compiled Java type
				int rank = 1;
				Type elem = type.GetElementType();
				while(ReflectUtil.IsVector(elem))
				{
					rank++;
					elem = elem.GetElementType();
				}
				wrapper = GetWrapperFromType(elem).MakeArrayType(rank);
			}
			else
			{
				Assembly asm = type.Assembly;
#if CLASSGC
				ClassLoaderWrapper loader = null;
				if(dynamicAssemblies != null && dynamicAssemblies.TryGetValue(asm, out loader))
				{
					lock(loader.typeToTypeWrapper)
					{
						TypeWrapper tw;
						if(loader.typeToTypeWrapper.TryGetValue(type, out tw))
						{
							return tw;
						}
						// it must be an anonymous type then
						Debug.Assert(AnonymousTypeWrapper.IsAnonymous(type));
					}
				}
#endif
#if !STATIC_COMPILER && !STUB_GENERATOR
				if(AnonymousTypeWrapper.IsAnonymous(type))
				{
					Dictionary<Type, TypeWrapper> typeToTypeWrapper;
#if CLASSGC
					typeToTypeWrapper = loader != null ? loader.typeToTypeWrapper : globalTypeToTypeWrapper;
#else
					typeToTypeWrapper = globalTypeToTypeWrapper;
#endif
					TypeWrapper tw = new AnonymousTypeWrapper(type);
					lock(typeToTypeWrapper)
					{
						if(!typeToTypeWrapper.TryGetValue(type, out wrapper))
						{
							typeToTypeWrapper.Add(type, wrapper = tw);
						}
					}
					return wrapper;
				}
				if(ReflectUtil.IsReflectionOnly(type))
				{
					// historically we've always returned null for types that don't have a corresponding TypeWrapper (or java.lang.Class)
					return null;
				}
#endif
				// if the wrapper doesn't already exist, that must mean that the type
				// is a .NET type (or a pre-compiled Java class), which means that it
				// was "loaded" by an assembly classloader
				wrapper = AssemblyClassLoader.FromAssembly(asm).GetWrapperFromAssemblyType(type);
			}
#if CLASSGC
			if(type.Assembly.IsDynamic)
			{
				// don't cache types in dynamic assemblies, because they might live in a RunAndCollect assembly
				// TODO we also shouldn't cache generic type instances that have a GCable type parameter
				return wrapper;
			}
#endif
			lock(globalTypeToTypeWrapper)
			{
				try
				{
					// critical code in the finally block to avoid Thread.Abort interrupting the thread
				}
				finally
				{
					globalTypeToTypeWrapper[type] = wrapper;
				}
			}
			return wrapper;
		}

		internal static ClassLoaderWrapper GetGenericClassLoader(TypeWrapper wrapper)
		{
			Type type = wrapper.TypeAsTBD;
			Debug.Assert(type.IsGenericType);
			Debug.Assert(!type.ContainsGenericParameters);

			List<ClassLoaderWrapper> list = new List<ClassLoaderWrapper>();
			list.Add(AssemblyClassLoader.FromAssembly(type.Assembly));
			foreach(Type arg in type.GetGenericArguments())
			{
				ClassLoaderWrapper loader = GetWrapperFromType(arg).GetClassLoader();
				if(!list.Contains(loader) && loader != bootstrapClassLoader)
				{
					list.Add(loader);
				}
			}
			ClassLoaderWrapper[] key = list.ToArray();
			ClassLoaderWrapper matchingLoader = GetGenericClassLoaderByKey(key);
			matchingLoader.RegisterInitiatingLoader(wrapper);
			return matchingLoader;
		}

#if !STATIC_COMPILER && !FIRST_PASS && !STUB_GENERATOR
		internal static object DoPrivileged(java.security.PrivilegedAction action)
		{
			return java.security.AccessController.doPrivileged(action, ikvm.@internal.CallerID.create(typeof(java.lang.ClassLoader).TypeHandle));
		}
#endif

		private static ClassLoaderWrapper GetGenericClassLoaderByKey(ClassLoaderWrapper[] key)
		{
			lock(wrapperLock)
			{
				if(genericClassLoaders == null)
				{
					genericClassLoaders = new List<GenericClassLoaderWrapper>();
				}
				foreach(GenericClassLoaderWrapper loader in genericClassLoaders)
				{
					if(loader.Matches(key))
					{
						return loader;
					}
				}
#if STATIC_COMPILER || STUB_GENERATOR || FIRST_PASS
				GenericClassLoaderWrapper newLoader = new GenericClassLoaderWrapper(key, null);
#else
				java.lang.ClassLoader javaClassLoader = new ikvm.runtime.GenericClassLoader();
				GenericClassLoaderWrapper newLoader = new GenericClassLoaderWrapper(key, javaClassLoader);
				SetWrapperForClassLoader(javaClassLoader, newLoader);
#endif
				genericClassLoaders.Add(newLoader);
				return newLoader;
			}
		}

#if !STATIC_COMPILER && !STUB_GENERATOR
		protected internal static void SetWrapperForClassLoader(java.lang.ClassLoader javaClassLoader, ClassLoaderWrapper wrapper)
		{
#if __MonoCS__ || FIRST_PASS
			typeof(java.lang.ClassLoader).GetField("wrapper", BindingFlags.NonPublic | BindingFlags.Instance).SetValue(javaClassLoader, wrapper);
#else
			javaClassLoader.wrapper = wrapper;
#endif
		}
#endif

#if !STATIC_COMPILER && !STUB_GENERATOR
		internal static ClassLoaderWrapper GetGenericClassLoaderByName(string name)
		{
			Debug.Assert(name.StartsWith("[[") && name.EndsWith("]]"));
			Stack<List<ClassLoaderWrapper>> stack = new Stack<List<ClassLoaderWrapper>>();
			List<ClassLoaderWrapper> list = null;
			for(int i = 0; i < name.Length; i++)
			{
				if(name[i] == '[')
				{
					if(name[i + 1] == '[')
					{
						stack.Push(list);
						list = new List<ClassLoaderWrapper>();
						if(name[i + 2] == '[')
						{
							i++;
						}
					}
					else
					{
						int start = i + 1;
						i = name.IndexOf(']', i);
						list.Add(ClassLoaderWrapper.GetAssemblyClassLoaderByName(name.Substring(start, i - start)));
					}
				}
				else if(name[i] == ']')
				{
					ClassLoaderWrapper loader = GetGenericClassLoaderByKey(list.ToArray());
					list = stack.Pop();
					if(list == null)
					{
						return loader;
					}
					list.Add(loader);
				}
				else
				{
					throw new InvalidOperationException();
				}
			}
			throw new InvalidOperationException();
		}

		internal static ClassLoaderWrapper GetAssemblyClassLoaderByName(string name)
		{
			if(name.StartsWith("[["))
			{
				return GetGenericClassLoaderByName(name);
			}
			return AssemblyClassLoader.FromAssembly(Assembly.Load(name));
		}
#endif

		internal static int GetGenericClassLoaderId(ClassLoaderWrapper wrapper)
		{
			lock(wrapperLock)
			{
				return genericClassLoaders.IndexOf(wrapper as GenericClassLoaderWrapper);
			}
		}

		internal static ClassLoaderWrapper GetGenericClassLoaderById(int id)
		{
			lock(wrapperLock)
			{
				return genericClassLoaders[id];
			}
		}

		internal void SetWrapperForType(Type type, TypeWrapper wrapper)
		{
#if !STATIC_COMPILER
			TypeWrapper.AssertFinished(type);
#endif
			Dictionary<Type, TypeWrapper> dict;
#if CLASSGC
			dict = typeToTypeWrapper ?? globalTypeToTypeWrapper;
#else
			dict = globalTypeToTypeWrapper;
#endif
			lock (dict)
			{
				try
				{
					// critical code in the finally block to avoid Thread.Abort interrupting the thread
				}
				finally
				{
					dict.Add(type, wrapper);
				}
			}
		}

		internal static TypeWrapper LoadClassCritical(string name)
		{
#if STATIC_COMPILER
			TypeWrapper wrapper = GetBootstrapClassLoader().LoadClassByDottedNameFast(name);
			if (wrapper == null)
			{
				throw new FatalCompilerErrorException(Message.CriticalClassNotFound, name);
			}
			return wrapper;
#else
			try
			{
				return GetBootstrapClassLoader().LoadClassByDottedName(name);
			}
			catch(Exception x)
			{
				JVM.CriticalFailure("Loading of critical class failed", x);
				return null;
			}
#endif
		}

		internal void RegisterNativeLibrary(IntPtr p)
		{
			lock(this)
			{
				try
				{
					// critical code in the finally block to avoid Thread.Abort interrupting the thread
				}
				finally
				{
					if(nativeLibraries == null)
					{
						nativeLibraries = new List<IntPtr>();
					}
					nativeLibraries.Add(p);
				}
			}
		}

		internal void UnregisterNativeLibrary(IntPtr p)
		{
			lock(this)
			{
				try
				{
					// critical code in the finally block to avoid Thread.Abort interrupting the thread
				}
				finally
				{
					nativeLibraries.Remove(p);
				}
			}
		}

		internal IntPtr[] GetNativeLibraries()
		{
			lock(this)
			{
				if(nativeLibraries ==  null)
				{
					return new IntPtr[0];
				}
				return nativeLibraries.ToArray();
			}
		}

#if !STATIC_COMPILER && !FIRST_PASS && !STUB_GENERATOR
		public override string ToString()
		{
			object javaClassLoader = GetJavaClassLoader();
			if(javaClassLoader == null)
			{
				return "null";
			}
			return String.Format("{0}@{1:X}", GetWrapperFromType(javaClassLoader.GetType()).Name, javaClassLoader.GetHashCode());
		}
#endif

		internal virtual bool InternalsVisibleToImpl(TypeWrapper wrapper, TypeWrapper friend)
		{
			Debug.Assert(wrapper.GetClassLoader() == this);
			return this == friend.GetClassLoader();
		}

#if !STATIC_COMPILER && !STUB_GENERATOR
		// this method is used by IKVM.Runtime.JNI
		internal static ClassLoaderWrapper FromCallerID(ikvm.@internal.CallerID callerID)
		{
#if FIRST_PASS
			return null;
#else
			return GetClassLoaderWrapper(callerID.getCallerClassLoader());
#endif
		}
#endif

#if STATIC_COMPILER
		internal virtual void IssueMessage(Message msgId, params string[] values)
		{
			// it's not ideal when we end up here (because it means we're emitting a warning that is not associated with a specific output target),
			// but it happens when we're decoding something in a referenced assembly that either doesn't make sense or contains an unloadable type
			StaticCompiler.IssueMessage(msgId, values);
		}
#endif

		internal void CheckPackageAccess(TypeWrapper tw, ProtectionDomain pd)
		{
#if !STATIC_COMPILER && !FIRST_PASS && !STUB_GENERATOR
			if (javaClassLoader != null)
			{
				javaClassLoader.checkPackageAccess(tw.ClassObject, pd);
			}
#endif
		}

#if !STUB_GENERATOR
		internal ClassFileParseOptions ClassFileParseOptions
		{
			get
			{
#if STATIC_COMPILER
				ClassFileParseOptions cfp = ClassFileParseOptions.LocalVariableTable;
				if (EmitStackTraceInfo)
				{
					cfp |= ClassFileParseOptions.LineNumberTable;
				}
				if (bootstrapClassLoader is CompilerClassLoader)
				{
					cfp |= ClassFileParseOptions.TrustedAnnotations;
				}
				if (RemoveAsserts)
				{
					cfp |= ClassFileParseOptions.RemoveAssertions;
				}
				return cfp;
#else
				ClassFileParseOptions cfp = ClassFileParseOptions.LineNumberTable;
				if (EmitDebugInfo)
				{
					cfp |= ClassFileParseOptions.LocalVariableTable;
				}
				if (RelaxedClassNameValidation)
				{
					cfp |= ClassFileParseOptions.RelaxedClassNameValidation;
				}
				if (this == bootstrapClassLoader)
				{
					cfp |= ClassFileParseOptions.TrustedAnnotations;
				}
				return cfp;
#endif
			}
		}
#endif

#if STATIC_COMPILER
		internal virtual bool WarningLevelHigh
		{
			get { return false; }
		}

		internal virtual bool NoParameterReflection
		{
			get { return false; }
		}
#endif
	}

	sealed class GenericClassLoaderWrapper : ClassLoaderWrapper
	{
		private readonly ClassLoaderWrapper[] delegates;

		internal GenericClassLoaderWrapper(ClassLoaderWrapper[] delegates, object javaClassLoader)
			: base(CodeGenOptions.None, javaClassLoader)
		{
			this.delegates = delegates;
		}

		internal bool Matches(ClassLoaderWrapper[] key)
		{
			if(key.Length == delegates.Length)
			{
				for(int i = 0; i < key.Length; i++)
				{
					if(key[i] != delegates[i])
					{
						return false;
					}
				}
				return true;
			}
			return false;
		}

		protected override TypeWrapper FindLoadedClassLazy(string name)
		{
			TypeWrapper tw1 = FindOrLoadGenericClass(name, LoadMode.Find);
			if (tw1 != null)
			{
				return tw1;
			}
			foreach (ClassLoaderWrapper loader in delegates)
			{
				TypeWrapper tw = loader.FindLoadedClass(name);
				if (tw != null && tw.GetClassLoader() == loader)
				{
					return tw;
				}
			}
			return null;
		}

		internal string GetName()
		{
			System.Text.StringBuilder sb = new System.Text.StringBuilder();
			sb.Append('[');
			foreach(ClassLoaderWrapper loader in delegates)
			{
				sb.Append('[');
				GenericClassLoaderWrapper gcl = loader as GenericClassLoaderWrapper;
				if(gcl != null)
				{
					sb.Append(gcl.GetName());
				}
				else
				{
					sb.Append(((AssemblyClassLoader)loader).MainAssembly.FullName);
				}
				sb.Append(']');
			}
			sb.Append(']');
			return sb.ToString();
		}

#if !STATIC_COMPILER && !STUB_GENERATOR
		internal java.util.Enumeration GetResources(string name)
		{
#if FIRST_PASS
			return null;
#else
			java.util.Vector v = new java.util.Vector();
			foreach (java.net.URL url in GetBootstrapClassLoader().GetResources(name))
			{
				v.add(url);
			}
			if (name.EndsWith(".class", StringComparison.Ordinal) && name.IndexOf('.') == name.Length - 6)
			{
				TypeWrapper tw = FindLoadedClass(name.Substring(0, name.Length - 6).Replace('/', '.'));
				if (tw != null && !tw.IsArray && !tw.IsDynamic)
				{
					ClassLoaderWrapper loader = tw.GetClassLoader();
					if (loader is GenericClassLoaderWrapper)
					{
						v.add(new java.net.URL("ikvmres", "gen", ClassLoaderWrapper.GetGenericClassLoaderId(loader), "/" + name));
					}
					else if (loader is AssemblyClassLoader)
					{
						foreach (java.net.URL url in ((AssemblyClassLoader)loader).FindResources(name))
						{
							v.add(url);
						}
					}
				}
			}
			return v.elements();
#endif
		}

		internal java.net.URL FindResource(string name)
		{
#if !FIRST_PASS
			if (name.EndsWith(".class", StringComparison.Ordinal) && name.IndexOf('.') == name.Length - 6)
			{
				TypeWrapper tw = FindLoadedClass(name.Substring(0, name.Length - 6).Replace('/', '.'));
				if (tw != null && tw.GetClassLoader() == this && !tw.IsArray && !tw.IsDynamic)
				{
					return new java.net.URL("ikvmres", "gen", ClassLoaderWrapper.GetGenericClassLoaderId(this), "/" + name);
				}
			}
#endif
			return null;
		}
#endif
	}
}