File: AssemblyClassLoader.cs

package info (click to toggle)
mono-reference-assemblies 3.12.1%2Bdfsg-2
  • links: PTS, VCS
  • area: main
  • in suites: stretch
  • size: 604,240 kB
  • ctags: 625,505
  • sloc: cs: 3,967,741; xml: 2,793,081; ansic: 418,042; java: 60,435; sh: 14,833; makefile: 11,576; sql: 7,956; perl: 1,467; cpp: 1,446; yacc: 1,203; python: 598; asm: 422; sed: 16; php: 1
file content (1347 lines) | stat: -rw-r--r-- 38,543 bytes parent folder | download | duplicates (2)
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
/*
  Copyright (C) 2002-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.IO;
using System.Collections.Generic;
using System.Diagnostics;
using System.Threading;
using System.Runtime.CompilerServices;
using FormatterServices = System.Runtime.Serialization.FormatterServices;
using IKVM.Attributes;
#if STATIC_COMPILER || STUB_GENERATOR
using IKVM.Reflection;
using Type = IKVM.Reflection.Type;
#else
using System.Reflection;
#endif

namespace IKVM.Internal
{
	class AssemblyClassLoader : ClassLoaderWrapper
	{
		private static readonly Dictionary<Assembly, AssemblyClassLoader> assemblyClassLoaders = new Dictionary<Assembly, AssemblyClassLoader>();
		private AssemblyLoader assemblyLoader;
		private string[] references;
		private AssemblyClassLoader[] delegates;
#if !STATIC_COMPILER && !STUB_GENERATOR && !FIRST_PASS
		private JavaClassLoaderConstructionInProgress jclcip;
		private java.security.ProtectionDomain protectionDomain;
		private static Dictionary<string, string> customClassLoaderRedirects;
		private byte hasCustomClassLoader;	/* 0 = unknown, 1 = yes, 2 = no */
#endif
		private Dictionary<int, List<int>> exports;
		private string[] exportedAssemblyNames;
		private AssemblyLoader[] exportedAssemblies;
		private Dictionary<Assembly, AssemblyLoader> exportedLoaders;

		private sealed class AssemblyLoader
		{
			private readonly Assembly assembly;
			private bool[] isJavaModule;
			private Module[] modules;
			private Dictionary<string, string> nameMap;
			private bool hasDotNetModule;
			private AssemblyName[] internalsVisibleTo;
			private string[] jarList;
#if !STATIC_COMPILER && !STUB_GENERATOR && !FIRST_PASS
			private sun.misc.URLClassPath urlClassPath;
#endif

			internal AssemblyLoader(Assembly assembly)
			{
				this.assembly = assembly;
				modules = assembly.GetModules(false);
				isJavaModule = new bool[modules.Length];
				for (int i = 0; i < modules.Length; i++)
				{
					object[] attr = AttributeHelper.GetJavaModuleAttributes(modules[i]);
					if (attr.Length > 0)
					{
						isJavaModule[i] = true;
						foreach (JavaModuleAttribute jma in attr)
						{
							string[] map = jma.GetClassMap();
							if (map != null)
							{
								if (nameMap == null)
								{
									nameMap = new Dictionary<string, string>();
								}
								for (int j = 0; j < map.Length; j += 2)
								{
									string key = map[j];
									string val = map[j + 1];
									// TODO if there is a name clash between modules, this will throw.
									// Figure out how to handle that.
									nameMap.Add(key, val);
								}
							}
							string[] jars = jma.Jars;
							if (jars != null)
							{
								if (jarList == null)
								{
									jarList = jars;
								}
								else
								{
									string[] newList = new string[jarList.Length + jars.Length];
									Array.Copy(jarList, newList, jarList.Length);
									Array.Copy(jars, 0, newList, jarList.Length, jars.Length);
									jarList = newList;
								}
							}
						}
					}
					else
					{
						hasDotNetModule = true;
					}
				}
			}

			internal bool HasJavaModule
			{
				get
				{
					for (int i = 0; i < isJavaModule.Length; i++)
					{
						if (isJavaModule[i])
						{
							return true;
						}
					}
					return false;
				}
			}

			internal Assembly Assembly
			{
				get { return assembly; }
			}

			private Type GetType(string name)
			{
				try
				{
					return assembly.GetType(name);
				}
				catch (ArgumentException)
				{
				}
				catch (FileLoadException x)
				{
					// this can only happen if the assembly was loaded in the ReflectionOnly
					// context and the requested type references a type in another assembly
					// that cannot be found in the ReflectionOnly context
					// TODO figure out what other exceptions Assembly.GetType() can throw
					Tracer.Info(Tracer.Runtime, x.Message);
				}
				return null;
			}

			private Type GetType(Module mod, string name)
			{
				try
				{
					return mod.GetType(name);
				}
				catch (ArgumentException)
				{
				}
				catch (FileLoadException x)
				{
					// this can only happen if the assembly was loaded in the ReflectionOnly
					// context and the requested type references a type in another assembly
					// that cannot be found in the ReflectionOnly context
					// TODO figure out what other exceptions Assembly.GetType() can throw
					Tracer.Info(Tracer.Runtime, x.Message);
				}
				return null;
			}

			private Type GetJavaType(Module mod, string name)
			{
				try
				{
					string n = null;
					if (nameMap != null)
					{
						nameMap.TryGetValue(name, out n);
					}
					Type t = GetType(mod, n != null ? n : name);
					if (t == null)
					{
						n = name.Replace('$', '+');
						if (!ReferenceEquals(n, name))
						{
							t = GetType(n);
						}
					}
					if (t != null
						&& !AttributeHelper.IsHideFromJava(t)
						&& !t.IsArray
						&& !t.IsPointer
						&& !t.IsByRef)
					{
						return t;
					}
				}
				catch (ArgumentException x)
				{
					// we can end up here because we replace the $ with a plus sign
					// (or client code did a Class.forName() on an invalid name)
					Tracer.Info(Tracer.Runtime, x.Message);
				}
				return null;
			}

			internal TypeWrapper DoLoad(string name)
			{
				for (int i = 0; i < modules.Length; i++)
				{
					if (isJavaModule[i])
					{
						Type type = GetJavaType(modules[i], name);
						if (type != null)
						{
							// check the name to make sure that the canonical name was used
							if (CompiledTypeWrapper.GetName(type) == name)
							{
								return CompiledTypeWrapper.newInstance(name, type);
							}
						}
					}
					else
					{
						// TODO should we catch ArgumentException and prohibit array, pointer and byref here?
						Type type = GetType(modules[i], DotNetTypeWrapper.DemangleTypeName(name));
						if (type != null && DotNetTypeWrapper.IsAllowedOutside(type))
						{
							// check the name to make sure that the canonical name was used
							if (DotNetTypeWrapper.GetName(type) == name)
							{
								return DotNetTypeWrapper.Create(type, name);
							}
						}
					}
				}
				if (hasDotNetModule)
				{
					// for fake types, we load the declaring outer type (the real one) and
					// let that generated the manufactured nested classes
					// (note that for generic outer types, we need to duplicate this in ClassLoaderWrapper.LoadGenericClass)
					TypeWrapper outer = null;
					if (name.EndsWith(DotNetTypeWrapper.DelegateInterfaceSuffix))
					{
						outer = DoLoad(name.Substring(0, name.Length - DotNetTypeWrapper.DelegateInterfaceSuffix.Length));
					}
					else if (name.EndsWith(DotNetTypeWrapper.AttributeAnnotationSuffix))
					{
						outer = DoLoad(name.Substring(0, name.Length - DotNetTypeWrapper.AttributeAnnotationSuffix.Length));
					}
					else if (name.EndsWith(DotNetTypeWrapper.AttributeAnnotationReturnValueSuffix))
					{
						outer = DoLoad(name.Substring(0, name.Length - DotNetTypeWrapper.AttributeAnnotationReturnValueSuffix.Length));
					}
					else if (name.EndsWith(DotNetTypeWrapper.AttributeAnnotationMultipleSuffix))
					{
						outer = DoLoad(name.Substring(0, name.Length - DotNetTypeWrapper.AttributeAnnotationMultipleSuffix.Length));
					}
					else if (name.EndsWith(DotNetTypeWrapper.EnumEnumSuffix))
					{
						outer = DoLoad(name.Substring(0, name.Length - DotNetTypeWrapper.EnumEnumSuffix.Length));
					}
					if (outer != null && outer.IsFakeTypeContainer)
					{
						foreach (TypeWrapper tw in outer.InnerClasses)
						{
							if (tw.Name == name)
							{
								return tw;
							}
						}
					}
				}
				return null;
			}

			internal string GetTypeNameAndType(Type type, out bool isJavaType)
			{
				Module mod = type.Module;
				int moduleIndex = -1;
				for (int i = 0; i < modules.Length; i++)
				{
					if (modules[i] == mod)
					{
						moduleIndex = i;
						break;
					}
				}
				if (isJavaModule[moduleIndex])
				{
					isJavaType = true;
					if (AttributeHelper.IsHideFromJava(type))
					{
						return null;
					}
					return CompiledTypeWrapper.GetName(type);
				}
				else
				{
					isJavaType = false;
					if (!DotNetTypeWrapper.IsAllowedOutside(type))
					{
						return null;
					}
					return DotNetTypeWrapper.GetName(type);
				}
			}

			internal TypeWrapper CreateWrapperForAssemblyType(Type type)
			{
				bool isJavaType;
				string name = GetTypeNameAndType(type, out isJavaType);
				if (name == null)
				{
					return null;
				}
				if (isJavaType)
				{
					// since this type was compiled from Java source, we have to look for our
					// attributes
					return CompiledTypeWrapper.newInstance(name, type);
				}
				else
				{
					// since this type was not compiled from Java source, we don't need to
					// look for our attributes, but we do need to filter unrepresentable
					// stuff (and transform some other stuff)
					return DotNetTypeWrapper.Create(type, name);
				}
			}

			internal bool InternalsVisibleTo(AssemblyName otherName)
			{
				if (internalsVisibleTo == null)
				{
					Interlocked.CompareExchange(ref internalsVisibleTo, AttributeHelper.GetInternalsVisibleToAttributes(assembly), null);
				}
				foreach (AssemblyName name in internalsVisibleTo)
				{
					// we match the simple name and PublicKeyToken (because the AssemblyName constructor used
					// by GetInternalsVisibleToAttributes() only sets the PublicKeyToken, even if a PublicKey is specified)
					if (ReflectUtil.MatchNameAndPublicKeyToken(name, otherName))
					{
						return true;
					}
				}
				return false;
			}

#if !STATIC_COMPILER && !STUB_GENERATOR && !FIRST_PASS
			internal java.util.Enumeration FindResources(string name)
			{
				if (urlClassPath == null)
				{
					if (jarList == null)
					{
						return gnu.java.util.EmptyEnumeration.getInstance();
					}
					List<java.net.URL> urls = new List<java.net.URL>();
					foreach (string jar in jarList)
					{
						urls.Add(MakeResourceURL(assembly, jar));
					}
					Interlocked.CompareExchange(ref urlClassPath, new sun.misc.URLClassPath(urls.ToArray()), null);
				}
				return urlClassPath.findResources(name, true);
			}
#endif
		}

		internal AssemblyClassLoader(Assembly assembly)
			: this(assembly, null)
		{
		}

		internal AssemblyClassLoader(Assembly assembly, string[] fixedReferences)
			: base(CodeGenOptions.None, null)
		{
			this.assemblyLoader = new AssemblyLoader(assembly);
			this.references = fixedReferences;
		}

#if STATIC_COMPILER
		internal static void PreloadExportedAssemblies(Assembly assembly)
		{
			if (assembly.GetManifestResourceInfo("ikvm.exports") != null)
			{
				using (Stream stream = assembly.GetManifestResourceStream("ikvm.exports"))
				{
					BinaryReader rdr = new BinaryReader(stream);
					int assemblyCount = rdr.ReadInt32();
					for (int i = 0; i < assemblyCount; i++)
					{
						string assemblyName = rdr.ReadString();
						int typeCount = rdr.ReadInt32();
						if (typeCount != 0)
						{
							for (int j = 0; j < typeCount; j++)
							{
								rdr.ReadInt32();
							}
							try
							{
								StaticCompiler.LoadFile(assembly.Location + "/../" + new AssemblyName(assemblyName).Name + ".dll");
							}
							catch { }
						}
					}
				}
			}
		}
#endif

		private void DoInitializeExports()
		{
			lock (this)
			{
				if (delegates == null)
				{
					if (!(ReflectUtil.IsDynamicAssembly(assemblyLoader.Assembly)) && assemblyLoader.Assembly.GetManifestResourceInfo("ikvm.exports") != null)
					{
						List<string> wildcardExports = new List<string>();
						using (Stream stream = assemblyLoader.Assembly.GetManifestResourceStream("ikvm.exports"))
						{
							BinaryReader rdr = new BinaryReader(stream);
							int assemblyCount = rdr.ReadInt32();
							exports = new Dictionary<int, List<int>>();
							exportedAssemblies = new AssemblyLoader[assemblyCount];
							exportedAssemblyNames = new string[assemblyCount];
							exportedLoaders = new Dictionary<Assembly, AssemblyLoader>();
							for (int i = 0; i < assemblyCount; i++)
							{
								exportedAssemblyNames[i] = String.Intern(rdr.ReadString());
								int typeCount = rdr.ReadInt32();
								if (typeCount == 0 && references == null)
								{
									wildcardExports.Add(exportedAssemblyNames[i]);
								}
								for (int j = 0; j < typeCount; j++)
								{
									int hash = rdr.ReadInt32();
									List<int> assemblies;
									if (!exports.TryGetValue(hash, out assemblies))
									{
										assemblies = new List<int>();
										exports.Add(hash, assemblies);
									}
									assemblies.Add(i);
								}
							}
						}
						if (references == null)
						{
							references = wildcardExports.ToArray();
						}
					}
					else
					{
						AssemblyName[] refNames = assemblyLoader.Assembly.GetReferencedAssemblies();
						references = new string[refNames.Length];
						for (int i = 0; i < references.Length; i++)
						{
							references[i] = refNames[i].FullName;
						}
					}
					Interlocked.Exchange(ref delegates, new AssemblyClassLoader[references.Length]);
				}
			}
		}

		private void LazyInitExports()
		{
			if (delegates == null)
			{
				DoInitializeExports();
			}
		}

		internal Assembly MainAssembly
		{
			get
			{
				return assemblyLoader.Assembly;
			}
		}

		internal Assembly GetAssembly(TypeWrapper wrapper)
		{
			Debug.Assert(wrapper.GetClassLoader() == this);
			while (wrapper.IsFakeNestedType)
			{
				wrapper = wrapper.DeclaringTypeWrapper;
			}
			return wrapper.TypeAsBaseType.Assembly;
		}

		private Assembly LoadAssemblyOrClearName(ref string name, bool exported)
		{
			if (name == null)
			{
				// previous load attemp failed
				return null;
			}
			try
			{
#if STATIC_COMPILER || STUB_GENERATOR
				return StaticCompiler.Load(name);
#else
				return Assembly.Load(name);
#endif
			}
			catch
			{
				// cache failure by clearing out the name the caller uses
				name = null;
				// should we issue a warning error (in ikvmc)?
				return null;
			}
		}

		internal TypeWrapper DoLoad(string name)
		{
			TypeWrapper tw = assemblyLoader.DoLoad(name);
			if (tw != null)
			{
				return RegisterInitiatingLoader(tw);
			}
			LazyInitExports();
			if (exports != null)
			{
				List<int> assemblies;
				if (exports.TryGetValue(JVM.PersistableHash(name), out assemblies))
				{
					foreach (int index in assemblies)
					{
						AssemblyLoader loader = TryGetLoaderByIndex(index);
						if (loader != null)
						{
							tw = loader.DoLoad(name);
							if (tw != null)
							{
								return RegisterInitiatingLoader(tw);
							}
						}
					}
				}
			}
			return null;
		}

		internal string GetTypeNameAndType(Type type, out bool isJavaType)
		{
			return GetLoader(type.Assembly).GetTypeNameAndType(type, out isJavaType);
		}

		private AssemblyLoader TryGetLoaderByIndex(int index)
		{
			AssemblyLoader loader = exportedAssemblies[index];
			if (loader == null)
			{
				Assembly asm = LoadAssemblyOrClearName(ref exportedAssemblyNames[index], true);
				if (asm != null)
				{
					loader = exportedAssemblies[index] = GetLoaderForExportedAssembly(asm);
				}
			}
			return loader;
		}

		internal List<Assembly> GetAllAvailableAssemblies()
		{
			List<Assembly> list = new List<Assembly>();
			list.Add(assemblyLoader.Assembly);
			LazyInitExports();
			if (exportedAssemblies != null)
			{
				for (int i = 0; i < exportedAssemblies.Length; i++)
				{
					AssemblyLoader loader = TryGetLoaderByIndex(i);
					if (loader != null && FromAssembly(loader.Assembly) == this)
					{
						list.Add(loader.Assembly);
					}
				}
			}
			return list;
		}

		private AssemblyLoader GetLoader(Assembly assembly)
		{
			if (assemblyLoader.Assembly == assembly)
			{
				return assemblyLoader;
			}
			return GetLoaderForExportedAssembly(assembly);
		}

		private AssemblyLoader GetLoaderForExportedAssembly(Assembly assembly)
		{
			LazyInitExports();
			AssemblyLoader loader;
			lock (exportedLoaders)
			{
				exportedLoaders.TryGetValue(assembly, out loader);
			}
			if (loader == null)
			{
				loader = new AssemblyLoader(assembly);
				lock (exportedLoaders)
				{
					AssemblyLoader existing;
					if (exportedLoaders.TryGetValue(assembly, out existing))
					{
						// another thread beat us to it
						loader = existing;
					}
					else
					{
						exportedLoaders.Add(assembly, loader);
					}
				}
			}
			return loader;
		}

		internal virtual TypeWrapper GetWrapperFromAssemblyType(Type type)
		{
			//Tracer.Info(Tracer.Runtime, "GetWrapperFromAssemblyType: {0}", type.FullName);
			Debug.Assert(!type.Name.EndsWith("[]"), "!type.IsArray", type.FullName);
			Debug.Assert(AssemblyClassLoader.FromAssembly(type.Assembly) == this);

			TypeWrapper wrapper = GetLoader(type.Assembly).CreateWrapperForAssemblyType(type);
			if (wrapper != null)
			{
				if (type.IsGenericType && !type.IsGenericTypeDefinition)
				{
					// in the case of "magic" implementation generic type instances we'll end up here as well,
					// but then wrapper.GetClassLoader() will return this anyway
					wrapper = wrapper.GetClassLoader().RegisterInitiatingLoader(wrapper);
				}
				else
				{
					wrapper = RegisterInitiatingLoader(wrapper);
				}
				if (wrapper.TypeAsTBD != type && (!wrapper.IsRemapped || wrapper.TypeAsBaseType != type))
				{
					// this really shouldn't happen, it means that we have two different types in our assembly that both
					// have the same Java name
#if STATIC_COMPILER
					throw new FatalCompilerErrorException(Message.AssemblyContainsDuplicateClassNames, type.FullName, wrapper.TypeAsTBD.FullName, wrapper.Name, type.Assembly.FullName);
#else
					string msg = String.Format("\nType \"{0}\" and \"{1}\" both map to the same name \"{2}\".\n", type.FullName, wrapper.TypeAsTBD.FullName, wrapper.Name);
					JVM.CriticalFailure(msg, null);
#endif
				}
				return wrapper;
			}
			return null;
		}

		protected override TypeWrapper LoadClassImpl(string name, bool throwClassNotFoundException)
		{
			TypeWrapper tw = FindLoadedClass(name);
			if (tw != null)
			{
				return tw;
			}
#if !STATIC_COMPILER && !STUB_GENERATOR && !FIRST_PASS
			while (hasCustomClassLoader != 2)
			{
				if (hasCustomClassLoader == 0)
				{
					Type customClassLoader = GetCustomClassLoaderType();
					if (customClassLoader == null)
					{
						hasCustomClassLoader = 2;
						break;
					}
					WaitInitializeJavaClassLoader(customClassLoader);
					hasCustomClassLoader = 1;
				}
				return base.LoadClassImpl(name, throwClassNotFoundException);
			}
#endif
			return LoadBootstrapIfNonJavaAssembly(name)
				?? LoadDynamic(name)
				?? FindOrLoadGenericClass(name, false);
		}

		// this implements ikvm.runtime.AssemblyClassLoader.loadClass(),
		// so unlike the above LoadClassImpl, it doesn't delegate to Java,
		// but otherwise it should be the same algorithm
		internal TypeWrapper LoadClass(string name)
		{
			return FindLoadedClass(name)
				?? LoadBootstrapIfNonJavaAssembly(name)
				?? LoadDynamic(name)
				?? FindOrLoadGenericClass(name, false);
		}

		private TypeWrapper LoadBootstrapIfNonJavaAssembly(string name)
		{
			if (!assemblyLoader.HasJavaModule)
			{
				return GetBootstrapClassLoader().LoadClassByDottedNameFast(name);
			}
			return null;
		}

		private TypeWrapper LoadDynamic(string name)
		{
#if !STATIC_COMPILER && !STUB_GENERATOR && !FIRST_PASS
			string classFile = name.Replace('.', '/') + ".class";
			foreach (Resource res in GetBootstrapClassLoader().FindDelegateResources(classFile))
			{
				return res.Loader.DefineDynamic(name, res.URL);
			}
			foreach (Resource res in FindDelegateResources(classFile))
			{
				return res.Loader.DefineDynamic(name, res.URL);
			}
			foreach (java.net.URL url in FindResources(classFile))
			{
				return DefineDynamic(name, url);
			}
#endif
			return null;
		}

#if !STATIC_COMPILER && !STUB_GENERATOR && !FIRST_PASS
		private TypeWrapper DefineDynamic(string name, java.net.URL url)
		{
			using (java.io.InputStream inp = url.openStream())
			{
				byte[] buf = new byte[inp.available()];
				for (int pos = 0; pos < buf.Length; )
				{
					int read = inp.read(buf, pos, buf.Length - pos);
					if (read <= 0)
					{
						break;
					}
					pos += read;
				}
				return TypeWrapper.FromClass(Java_java_lang_ClassLoader.defineClass1(GetJavaClassLoader(), name, buf, 0, buf.Length, GetProtectionDomain(), null));
			}
		}
#endif

		private TypeWrapper FindReferenced(string name)
		{
			for (int i = 0; i < delegates.Length; i++)
			{
				if (delegates[i] == null)
				{
					Assembly asm = LoadAssemblyOrClearName(ref references[i], false);
					if (asm != null)
					{
						delegates[i] = AssemblyClassLoader.FromAssembly(asm);
					}
				}
				if (delegates[i] != null)
				{
					TypeWrapper tw = delegates[i].DoLoad(name);
					if (tw != null)
					{
						return RegisterInitiatingLoader(tw);
					}
				}
			}
			return null;
		}

#if !STATIC_COMPILER && !STUB_GENERATOR
		private static java.net.URL MakeResourceURL(Assembly asm, string name)
		{
#if FIRST_PASS
			return null;
#else
			return new java.io.File(VirtualFileSystem.GetAssemblyResourcesPath(asm) + name).toURI().toURL();
#endif
		}

		internal IEnumerable<java.net.URL> FindResources(string unmangledName)
		{
			if (ReflectUtil.IsDynamicAssembly(assemblyLoader.Assembly))
			{
				yield break;
			}
			bool found = false;
#if !FIRST_PASS
			java.util.Enumeration urls = assemblyLoader.FindResources(unmangledName);
			while (urls.hasMoreElements())
			{
				found = true;
				yield return (java.net.URL)urls.nextElement();
			}
#endif
			if (!assemblyLoader.HasJavaModule)
			{
				if (unmangledName != "" && assemblyLoader.Assembly.GetManifestResourceInfo(unmangledName) != null)
				{
					found = true;
					yield return MakeResourceURL(assemblyLoader.Assembly, unmangledName);
				}
				foreach (JavaResourceAttribute res in assemblyLoader.Assembly.GetCustomAttributes(typeof(IKVM.Attributes.JavaResourceAttribute), false))
				{
					if (res.JavaName == unmangledName)
					{
						found = true;
						yield return MakeResourceURL(assemblyLoader.Assembly, res.ResourceName);
					}
				}
			}
			string name = JVM.MangleResourceName(unmangledName);
			if (assemblyLoader.Assembly.GetManifestResourceInfo(name) != null)
			{
				found = true;
				yield return MakeResourceURL(assemblyLoader.Assembly, name);
			}
			LazyInitExports();
			if (exports != null)
			{
				List<int> assemblies;
				if (exports.TryGetValue(JVM.PersistableHash(unmangledName), out assemblies))
				{
					foreach (int index in assemblies)
					{
						AssemblyLoader loader = exportedAssemblies[index];
						if (loader == null)
						{
							Assembly asm = LoadAssemblyOrClearName(ref exportedAssemblyNames[index], true);
							if (asm == null)
							{
								continue;
							}
							loader = exportedAssemblies[index] = GetLoaderForExportedAssembly(asm);
						}
#if !FIRST_PASS
						urls = loader.FindResources(unmangledName);
						while (urls.hasMoreElements())
						{
							found = true;
							yield return (java.net.URL)urls.nextElement();
						}
#endif
						if (loader.Assembly.GetManifestResourceInfo(name) != null)
						{
							found = true;
							yield return MakeResourceURL(loader.Assembly, name);
						}
					}
				}
			}
			if (!found && unmangledName.EndsWith(".class", StringComparison.Ordinal) && unmangledName.IndexOf('.') == unmangledName.Length - 6)
			{
				TypeWrapper tw = FindLoadedClass(unmangledName.Substring(0, unmangledName.Length - 6).Replace('/', '.'));
				if (tw != null && tw.GetClassLoader() == this && !tw.IsArray && !tw.IsDynamic)
				{
#if !FIRST_PASS
					yield return new java.io.File(VirtualFileSystem.GetAssemblyClassesPath(assemblyLoader.Assembly) + unmangledName).toURI().toURL();
#endif
				}
			}
		}

		protected struct Resource
		{
			internal readonly java.net.URL URL;
			internal readonly AssemblyClassLoader Loader;

			internal Resource(java.net.URL url, AssemblyClassLoader loader)
			{
				this.URL = url;
				this.Loader = loader;
			}
		}

		protected IEnumerable<Resource> FindDelegateResources(string name)
		{
			LazyInitExports();
			for (int i = 0; i < delegates.Length; i++)
			{
				if (delegates[i] == null)
				{
					Assembly asm = LoadAssemblyOrClearName(ref references[i], false);
					if (asm != null)
					{
						delegates[i] = AssemblyClassLoader.FromAssembly(asm);
					}
				}
				if (delegates[i] != null && delegates[i] != GetBootstrapClassLoader())
				{
					foreach (java.net.URL url in delegates[i].FindResources(name))
					{
						yield return new Resource(url, delegates[i]);
					}
				}
			}
		}

		internal virtual IEnumerable<java.net.URL> GetResources(string name)
		{
			foreach (java.net.URL url in GetBootstrapClassLoader().GetResources(name))
			{
				yield return url;
			}
			foreach (Resource res in FindDelegateResources(name))
			{
				yield return res.URL;
			}
			foreach (java.net.URL url in FindResources(name))
			{
				yield return url;
			}
		}
#endif // !STATIC_COMPILER

#if !STATIC_COMPILER && !FIRST_PASS && !STUB_GENERATOR
		private sealed class JavaClassLoaderConstructionInProgress
		{
			internal readonly Thread Thread = Thread.CurrentThread;
			internal java.lang.ClassLoader javaClassLoader;
			internal int recursion;
		}

		private java.lang.ClassLoader WaitInitializeJavaClassLoader(Type customClassLoader)
		{
			Interlocked.CompareExchange(ref jclcip, new JavaClassLoaderConstructionInProgress(), null);
			JavaClassLoaderConstructionInProgress curr = jclcip;
			if (curr != null)
			{
				if (curr.Thread == Thread.CurrentThread)
				{
					if (curr.javaClassLoader != null)
					{
						// we were recursively invoked during the class loader construction,
						// so we have to return the partialy constructed class loader
						return curr.javaClassLoader;
					}
					curr.recursion++;
					try
					{
						if (javaClassLoader == null)
						{
							InitializeJavaClassLoader(curr, customClassLoader);
						}
					}
					finally
					{
						// We only publish the class loader from the outer most invocation, otherwise
						// an invocation of getClassLoader in the static initializer or constructor
						// of the custom class loader would result in prematurely publishing it.
						if (--curr.recursion == 0)
						{
							lock (this)
							{
								jclcip = null;
								Monitor.PulseAll(this);
							}
						}
					}
				}
				else
				{
					lock (this)
					{
						while (jclcip != null)
						{
							Monitor.Wait(this);
						}
					}
				}
			}
			return javaClassLoader;
		}

		internal override java.lang.ClassLoader GetJavaClassLoader()
		{
			if (javaClassLoader == null)
			{
				return WaitInitializeJavaClassLoader(GetCustomClassLoaderType());
			}
			return javaClassLoader;
		}

		internal virtual java.security.ProtectionDomain GetProtectionDomain()
		{
			if (protectionDomain == null)
			{
				Interlocked.CompareExchange(ref protectionDomain, new java.security.ProtectionDomain(assemblyLoader.Assembly), null);
			}
			return protectionDomain;
		}
#endif

		protected override TypeWrapper FindLoadedClassLazy(string name)
		{
			return DoLoad(name)
				?? FindReferenced(name)
				?? FindOrLoadGenericClass(name, true);
		}

		internal override bool InternalsVisibleToImpl(TypeWrapper wrapper, TypeWrapper friend)
		{
			ClassLoaderWrapper other = friend.GetClassLoader();
			if (this == other)
			{
#if STATIC_COMPILER || STUB_GENERATOR
				return true;
#else
				// we're OK if the type being accessed (wrapper) is a dynamic type
				// or if the dynamic assembly has internal access
				return GetAssembly(wrapper).Equals(GetTypeWrapperFactory().ModuleBuilder.Assembly)
					|| GetTypeWrapperFactory().HasInternalAccess;
#endif
			}
			AssemblyName otherName;
#if STATIC_COMPILER
			CompilerClassLoader ccl = other as CompilerClassLoader;
			if (ccl == null)
			{
				return false;
			}
			otherName = ccl.GetAssemblyName();
#else
			AssemblyClassLoader acl = other as AssemblyClassLoader;
			if (acl == null)
			{
				return false;
			}
			otherName = acl.GetAssembly(friend).GetName();
#endif
			return GetLoader(GetAssembly(wrapper)).InternalsVisibleTo(otherName);
		}

		// this method should not be used with dynamic Java assemblies
		internal static AssemblyClassLoader FromAssembly(Assembly assembly)
		{
			AssemblyClassLoader loader;
			lock (assemblyClassLoaders)
			{
				assemblyClassLoaders.TryGetValue(assembly, out loader);
			}
			if (loader == null)
			{
				loader = Create(assembly);
				lock (assemblyClassLoaders)
				{
					AssemblyClassLoader existing;
					if (assemblyClassLoaders.TryGetValue(assembly, out existing))
					{
						// another thread won the race to create the class loader
						loader = existing;
					}
					else
					{
						assemblyClassLoaders.Add(assembly, loader);
					}
				}
			}
			return loader;
		}

		private static AssemblyClassLoader Create(Assembly assembly)
		{
			// If the assembly is a part of a multi-assembly shared class loader,
			// it will export the __<MainAssembly> type from the main assembly in the group.
			Type forwarder = assembly.GetType("__<MainAssembly>");
			if (forwarder != null)
			{
				Assembly mainAssembly = forwarder.Assembly;
				if (mainAssembly != assembly)
				{
					return FromAssembly(mainAssembly);
				}
			}
#if STATIC_COMPILER
			if (JVM.CoreAssembly == null && CompilerClassLoader.IsCoreAssembly(assembly))
			{
				JVM.CoreAssembly = assembly;
				ClassLoaderWrapper.LoadRemappedTypes();
			}
#endif
			if (assembly == JVM.CoreAssembly)
			{
				// This cast is necessary for ikvmc and a no-op for the runtime.
				// Note that the cast cannot fail, because ikvmc will only return a non AssemblyClassLoader
				// from GetBootstrapClassLoader() when compiling the core assembly and in that case JVM.CoreAssembly
				// will be null.
				return (AssemblyClassLoader)GetBootstrapClassLoader();
			}
			return new AssemblyClassLoader(assembly);
		}

		internal void AddDelegate(AssemblyClassLoader acl)
		{
			LazyInitExports();
			lock (this)
			{
				delegates = ArrayUtil.Concat(delegates, acl);
			}
		}

#if !STATIC_COMPILER && !STUB_GENERATOR
		internal List<KeyValuePair<string, string[]>> GetPackageInfo()
		{
			List<KeyValuePair<string, string[]>> list = new List<KeyValuePair<string, string[]>>();
			foreach (Module m in assemblyLoader.Assembly.GetModules(false))
			{
				object[] attr = m.GetCustomAttributes(typeof(PackageListAttribute), false);
				foreach (PackageListAttribute p in attr)
				{
					list.Add(new KeyValuePair<string, string[]>(p.jar, p.packages));
				}
			}
			return list;
		}
#endif

#if !STATIC_COMPILER && !FIRST_PASS && !STUB_GENERATOR
		private Type GetCustomClassLoaderType()
		{
			LoadCustomClassLoaderRedirects();
			Assembly assembly = assemblyLoader.Assembly;
			string assemblyName = assembly.FullName;
			foreach (KeyValuePair<string, string> kv in customClassLoaderRedirects)
			{
				string asm = kv.Key;
				// FXBUG
				// We only support matching on the assembly's simple name,
				// because there appears to be no viable alternative.
				// There is AssemblyName.ReferenceMatchesDefinition()
				// but it is completely broken.
				if (assemblyName.StartsWith(asm + ","))
				{
					try
					{
						return Type.GetType(kv.Value, true);
					}
					catch (Exception x)
					{
						Tracer.Error(Tracer.Runtime, "Unable to load custom class loader {0} specified in app.config for assembly {1}: {2}", kv.Value, assembly, x);
					}
					break;
				}
			}
			object[] attribs = assembly.GetCustomAttributes(typeof(CustomAssemblyClassLoaderAttribute), false);
			if (attribs.Length == 1)
			{
				return ((CustomAssemblyClassLoaderAttribute)attribs[0]).Type;
			}
			return null;
		}

		private void InitializeJavaClassLoader(JavaClassLoaderConstructionInProgress jclcip, Type customClassLoaderClass)
		{
			Assembly assembly = assemblyLoader.Assembly;
			{
				if (customClassLoaderClass != null)
				{
					try
					{
						if (!customClassLoaderClass.IsPublic && !customClassLoaderClass.Assembly.Equals(assembly))
						{
							throw new Exception("Type not accessible");
						}
						ConstructorInfo customClassLoaderCtor = customClassLoaderClass.GetConstructor(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, null, new Type[] { typeof(Assembly) }, null);
						if (customClassLoaderCtor == null)
						{
							throw new Exception("No constructor");
						}
						if (!customClassLoaderCtor.IsPublic && !customClassLoaderClass.Assembly.Equals(assembly))
						{
							customClassLoaderCtor = null;
							throw new Exception("Constructor not accessible");
						}
						// NOTE we're creating an uninitialized instance of the custom class loader here, so that getClassLoader will return the proper object
						// when it is called during the construction of the custom class loader later on. This still doesn't make it safe to use the custom
						// class loader before it is constructed, but at least the object instance is available and should anyone cache it, they will get the
						// right object to use later on.
						// Note that creating the unitialized instance will (unfortunately) trigger the static initializer. The static initializer can
						// trigger a call to getClassLoader(), which means we can end up here recursively.
						java.lang.ClassLoader newJavaClassLoader = (java.lang.ClassLoader)GetUninitializedObject(customClassLoaderClass);
						if (jclcip.javaClassLoader == null) // check if we weren't invoked recursively and the nested invocation already did the work
						{
							jclcip.javaClassLoader = newJavaClassLoader;
							SetWrapperForClassLoader(jclcip.javaClassLoader, this);
							DoPrivileged(new CustomClassLoaderCtorCaller(customClassLoaderCtor, jclcip.javaClassLoader, assembly));
							Tracer.Info(Tracer.Runtime, "Created custom assembly class loader {0} for assembly {1}", customClassLoaderClass.FullName, assembly);
						}
						else
						{
							// we didn't initialize the object, so there is no need to finalize it
							GC.SuppressFinalize(newJavaClassLoader);
						}
					}
					catch (Exception x)
					{
						Tracer.Error(Tracer.Runtime, "Unable to create custom assembly class loader {0} for {1}: {2}", customClassLoaderClass.FullName, assembly, x);
					}
				}
			}
			if (jclcip.javaClassLoader == null)
			{
				jclcip.javaClassLoader = new ikvm.runtime.AssemblyClassLoader();
				SetWrapperForClassLoader(jclcip.javaClassLoader, this);
			}
			// finally we publish the class loader for other threads to see
			Thread.MemoryBarrier();
			javaClassLoader = jclcip.javaClassLoader;
		}

		// separate method to avoid LinkDemand killing the caller
		// and to bridge transparent -> critical boundary
		[System.Security.SecuritySafeCritical]
		private static object GetUninitializedObject(Type type)
		{
			return FormatterServices.GetUninitializedObject(type);
		}

		private static void LoadCustomClassLoaderRedirects()
		{
			if (customClassLoaderRedirects == null)
			{
				Dictionary<string, string> dict = new Dictionary<string, string>();
				try
				{
					foreach (string key in System.Configuration.ConfigurationManager.AppSettings.AllKeys)
					{
						const string prefix = "ikvm-classloader:";
						if (key.StartsWith(prefix))
						{
							dict[key.Substring(prefix.Length)] = System.Configuration.ConfigurationManager.AppSettings.Get(key);
						}
					}
				}
				catch (Exception x)
				{
					Tracer.Error(Tracer.Runtime, "Error while reading custom class loader redirects: {0}", x);
				}
				finally
				{
					Interlocked.CompareExchange(ref customClassLoaderRedirects, dict, null);
				}
			}
		}

		private sealed class CustomClassLoaderCtorCaller : java.security.PrivilegedAction
		{
			private ConstructorInfo ctor;
			private object classLoader;
			private Assembly assembly;

			internal CustomClassLoaderCtorCaller(ConstructorInfo ctor, object classLoader, Assembly assembly)
			{
				this.ctor = ctor;
				this.classLoader = classLoader;
				this.assembly = assembly;
			}

			public object run()
			{
				ctor.Invoke(classLoader, new object[] { assembly });
				return null;
			}
		}
#endif
	}

	sealed class BootstrapClassLoader : AssemblyClassLoader
	{
		internal BootstrapClassLoader()
			: base(JVM.CoreAssembly, new string[] {
				typeof(object).Assembly.FullName,		// mscorlib
				typeof(System.Uri).Assembly.FullName	// System
			})
		{
		}

		internal override TypeWrapper GetWrapperFromAssemblyType(Type type)
		{
			// we have to special case the fake types here
			if (type.IsGenericType && !type.IsGenericTypeDefinition)
			{
				TypeWrapper outer = ClassLoaderWrapper.GetWrapperFromType(type.GetGenericArguments()[0]);
				foreach (TypeWrapper inner in outer.InnerClasses)
				{
					if (inner.TypeAsTBD == type)
					{
						return inner;
					}
					foreach (TypeWrapper inner2 in inner.InnerClasses)
					{
						if (inner2.TypeAsTBD == type)
						{
							return inner2;
						}
					}
				}
				return null;
			}
			return base.GetWrapperFromAssemblyType(type);
		}

		protected override void CheckProhibitedPackage(string className)
		{
		}

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

		internal override java.security.ProtectionDomain GetProtectionDomain()
		{
			return null;
		}

		internal override IEnumerable<java.net.URL> GetResources(string name)
		{
			foreach (java.net.URL url in FindResources(name))
			{
				yield return url;
			}
			foreach (Resource res in FindDelegateResources(name))
			{
				yield return res.URL;
			}
		}
#endif
	}
}