2
Copyright (C) 2002, 2003, 2004 Jeroen Frijters
4
This software is provided 'as-is', without any express or implied
5
warranty. In no event will the authors be held liable for any damages
6
arising from the use of this software.
8
Permission is granted to anyone to use this software for any purpose,
9
including commercial applications, and to alter it and redistribute it
10
freely, subject to the following restrictions:
12
1. The origin of this software must not be misrepresented; you must not
13
claim that you wrote the original software. If you use this software
14
in a product, an acknowledgment in the product documentation would be
15
appreciated but is not required.
16
2. Altered source versions must be plainly marked as such, and must not be
17
misrepresented as being the original software.
18
3. This notice may not be removed or altered from any source distribution.
25
using System.Collections;
27
using System.Reflection;
28
using System.Runtime.InteropServices;
29
using System.Runtime.CompilerServices;
31
using NetSystem = System;
33
namespace NativeCode.java
41
// NOTE not used, only here to shut up ikvmc during compilation of IKVM.GNU.Classpath.dll
42
public static object getProxyClass0(object o1, object o2)
44
throw new InvalidOperationException();
47
// NOTE not used, only here to shut up ikvmc during compilation of IKVM.GNU.Classpath.dll
48
public static object getProxyData0(object o1, object o2)
50
throw new InvalidOperationException();
53
// NOTE not used, only here to shut up ikvmc during compilation of IKVM.GNU.Classpath.dll
54
public static object generateProxyClass0(object o1, object o2)
56
throw new InvalidOperationException();
62
public static object createObjectArray(object clazz, int dim)
66
// TODO handle ghost types
67
return NetSystem.Array.CreateInstance(VMClass.getWrapperFromClass(clazz).TypeAsArrayType, dim);
69
throw JavaException.NegativeArraySizeException();
73
internal class JavaWrapper
75
private static Type java_lang_Byte = ClassLoaderWrapper.LoadClassCritical("java.lang.Byte").TypeAsTBD;
76
private static Type java_lang_Boolean = ClassLoaderWrapper.LoadClassCritical("java.lang.Boolean").TypeAsTBD;
77
private static Type java_lang_Short = ClassLoaderWrapper.LoadClassCritical("java.lang.Short").TypeAsTBD;
78
private static Type java_lang_Character = ClassLoaderWrapper.LoadClassCritical("java.lang.Character").TypeAsTBD;
79
private static Type java_lang_Integer = ClassLoaderWrapper.LoadClassCritical("java.lang.Integer").TypeAsTBD;
80
private static Type java_lang_Long = ClassLoaderWrapper.LoadClassCritical("java.lang.Long").TypeAsTBD;
81
private static Type java_lang_Float = ClassLoaderWrapper.LoadClassCritical("java.lang.Float").TypeAsTBD;
82
private static Type java_lang_Double = ClassLoaderWrapper.LoadClassCritical("java.lang.Double").TypeAsTBD;
84
internal static object Box(object o)
88
return Activator.CreateInstance(java_lang_Byte, new object[] { o });
92
return Activator.CreateInstance(java_lang_Byte, new object[] { (sbyte)(byte)o });
96
return Activator.CreateInstance(java_lang_Boolean, new object[] { o });
100
return Activator.CreateInstance(java_lang_Short, new object[] { o });
104
return Activator.CreateInstance(java_lang_Short, new object[] { (short)(ushort)o });
108
return Activator.CreateInstance(java_lang_Character, new object[] { o });
112
return Activator.CreateInstance(java_lang_Integer, new object[] { o });
116
return Activator.CreateInstance(java_lang_Integer, new object[] { (int)(uint)o });
120
return Activator.CreateInstance(java_lang_Long, new object[] { o });
124
return Activator.CreateInstance(java_lang_Long, new object[] { (long)(ulong)o });
128
return Activator.CreateInstance(java_lang_Float, new object[] { o });
132
return Activator.CreateInstance(java_lang_Double, new object[] { o });
136
Type enumType = Enum.GetUnderlyingType(o.GetType());
137
if(enumType == typeof(byte) || enumType == typeof(sbyte))
139
return JavaWrapper.Box((sbyte)((IConvertible)o).ToInt32(null));
141
else if(enumType == typeof(short) || enumType == typeof(ushort))
143
return JavaWrapper.Box((short)((IConvertible)o).ToInt32(null));
145
else if(enumType == typeof(int))
147
return JavaWrapper.Box(((IConvertible)o).ToInt32(null));
149
else if(enumType == typeof(uint))
151
return JavaWrapper.Box(unchecked((int)((IConvertible)o).ToUInt32(null)));
153
else if(enumType == typeof(long))
155
return JavaWrapper.Box(((IConvertible)o).ToInt64(null));
157
else if(enumType == typeof(ulong))
159
return JavaWrapper.Box(unchecked((long)((IConvertible)o).ToUInt64(null)));
163
throw new InvalidOperationException();
168
throw new NotImplementedException(o.GetType().FullName);
172
internal static object Unbox(object o)
174
Type type = o.GetType();
175
if(type == java_lang_Byte)
177
return java_lang_Byte.GetMethod("byteValue").Invoke(o, new object[0]);
179
else if(type == java_lang_Boolean)
181
return java_lang_Boolean.GetMethod("booleanValue").Invoke(o, new object[0]);
183
else if(type == java_lang_Short)
185
return java_lang_Short.GetMethod("shortValue").Invoke(o, new object[0]);
187
else if(type == java_lang_Character)
189
return java_lang_Character.GetMethod("charValue").Invoke(o, new object[0]);
191
else if(type == java_lang_Integer)
193
return java_lang_Integer.GetMethod("intValue").Invoke(o, new object[0]);
195
else if(type == java_lang_Long)
197
return java_lang_Long.GetMethod("longValue").Invoke(o, new object[0]);
199
else if(type == java_lang_Float)
201
return java_lang_Float.GetMethod("floatValue").Invoke(o, new object[0]);
203
else if(type == java_lang_Double)
205
return java_lang_Double.GetMethod("doubleValue").Invoke(o, new object[0]);
209
throw JavaException.IllegalArgumentException(type.FullName);
216
public static String GetName(object methodCookie)
218
MethodWrapper wrapper = (MethodWrapper)methodCookie;
222
public static int GetModifiers(object methodCookie)
224
MethodWrapper wrapper = (MethodWrapper)methodCookie;
225
return (int)wrapper.Modifiers;
228
public static object GetReturnType(object methodCookie)
230
MethodWrapper wrapper = (MethodWrapper)methodCookie;
231
return VMClass.getClassFromWrapper(wrapper.ReturnType);
234
public static object[] GetParameterTypes(object methodCookie)
236
MethodWrapper wrapper = (MethodWrapper)methodCookie;
237
TypeWrapper[] parameters = wrapper.GetParameters();
238
object[] parameterClasses = new object[parameters.Length];
239
for(int i = 0; i < parameters.Length; i++)
241
parameterClasses[i] = VMClass.getClassFromWrapper(parameters[i]);
243
return parameterClasses;
246
public static string[] GetExceptionTypes(object methodCookie)
248
MethodWrapper wrapper = (MethodWrapper)methodCookie;
249
wrapper.DeclaringType.Finish();
250
return wrapper.GetExceptions();
253
public static object Invoke(object methodCookie, object o, object[] args)
255
object[] argsCopy = new Object[args != null ? args.Length : 0];
256
MethodWrapper mw = (MethodWrapper)methodCookie;
257
mw.DeclaringType.Finish();
258
TypeWrapper[] argWrappers = mw.GetParameters();
259
for(int i = 0; i < argWrappers.Length; i++)
261
if(argWrappers[i].IsPrimitive)
265
throw JavaException.IllegalArgumentException("primitive wrapper null");
267
argsCopy[i] = JavaWrapper.Unbox(args[i]);
271
argsCopy[i] = args[i];
274
object retval = mw.Invoke(o, argsCopy, false);
275
if(mw.ReturnType.IsPrimitive && mw.ReturnType != PrimitiveTypeWrapper.VOID)
277
retval = JavaWrapper.Box(retval);
285
// HACK this is used by netexp to query the constant value of a field
286
public static object getConstant(object field)
288
// HACK we use reflection to extract the fieldCookie from the java.lang.reflect.Field object
289
FieldWrapper wrapper = (FieldWrapper)field.GetType().GetField("fieldCookie", BindingFlags.Instance | BindingFlags.NonPublic).GetValue(field);
290
return wrapper.GetConstant();
293
public static string GetName(object fieldCookie)
295
FieldWrapper wrapper = (FieldWrapper)fieldCookie;
299
public static int GetModifiers(object fieldCookie)
301
FieldWrapper wrapper = (FieldWrapper)fieldCookie;
302
return (int)wrapper.Modifiers;
305
public static object GetFieldType(object fieldCookie)
307
FieldWrapper wrapper = (FieldWrapper)fieldCookie;
308
return VMClass.getClassFromWrapper(wrapper.FieldTypeWrapper);
311
public static bool isSamePackage(object a, object b)
313
return VMClass.getWrapperFromClass(a).IsInSamePackageAs(VMClass.getWrapperFromClass(b));
316
public static object getClassFromFrame(NetSystem.Diagnostics.StackFrame frame)
318
return VMClass.getClassFromType(frame.GetMethod().DeclaringType);
321
public static object GetValue(object fieldCookie, object o)
323
Profiler.Enter("Field.GetValue");
326
FieldWrapper wrapper = (FieldWrapper)fieldCookie;
327
object val = wrapper.GetValue(o);
328
if(wrapper.FieldTypeWrapper.IsPrimitive)
330
val = JavaWrapper.Box(val);
336
Profiler.Leave("Field.GetValue");
340
public static void SetValue(object fieldCookie, object o, object v)
342
Profiler.Enter("Field.SetValue");
345
FieldWrapper wrapper = (FieldWrapper)fieldCookie;
348
// NOTE Java runs the class initializer when trying to set a final field
349
wrapper.DeclaringType.RunClassInit();
350
// NOTE even if the caller is the class itself, it still isn't legal
351
throw JavaException.IllegalAccessException("Field is final");
353
// TODO enforce accessibility (isAccessible() is false)
354
if(wrapper.FieldTypeWrapper.IsPrimitive)
356
v = JavaWrapper.Unbox(v);
358
wrapper.SetValue(o, v);
362
Profiler.Leave("Field.SetValue");
368
public class VMRuntime
370
public static string getVersion()
372
return typeof(VMRuntime).Assembly.GetName().Version.ToString();
375
public static int nativeLoad(string filename)
377
// TODO native libraries somehow need to be scoped by class loader
378
return JVM.JniProvider.LoadNativeLibrary(filename);
384
public static double pow(double x, double y)
386
return NetSystem.Math.Pow(x, y);
389
public static double exp(double d)
391
return NetSystem.Math.Exp(d);
394
public static double rint(double d)
396
return NetSystem.Math.Round(d);
399
public static double IEEEremainder(double f1, double f2)
401
if(double.IsInfinity(f2) && !double.IsInfinity(f1))
405
return NetSystem.Math.IEEERemainder(f1, f2);
408
public static double sqrt(double d)
410
return NetSystem.Math.Sqrt(d);
413
public static double floor(double d)
415
return NetSystem.Math.Floor(d);
418
public static double ceil(double d)
420
return NetSystem.Math.Ceiling(d);
423
public static double log(double d)
425
return NetSystem.Math.Log(d);
428
public static double sin(double d)
430
return NetSystem.Math.Sin(d);
433
public static double asin(double d)
435
return NetSystem.Math.Asin(d);
438
public static double cos(double d)
440
return NetSystem.Math.Cos(d);
443
public static double acos(double d)
445
return NetSystem.Math.Acos(d);
448
public static double tan(double d)
450
return NetSystem.Math.Tan(d);
453
public static double atan(double d)
455
return NetSystem.Math.Atan(d);
458
public static double atan2(double y, double x)
460
if(double.IsInfinity(y) && double.IsInfinity(x))
462
if(double.IsPositiveInfinity(y))
464
if(double.IsPositiveInfinity(x))
466
return NetSystem.Math.PI / 4.0;
470
return NetSystem.Math.PI * 3.0 / 4.0;
475
if(double.IsPositiveInfinity(x))
477
return - NetSystem.Math.PI / 4.0;
481
return - NetSystem.Math.PI * 3.0 / 4.0;
485
return NetSystem.Math.Atan2(y, x);
491
public static void initIDs()
495
public static double parseDouble(string s)
499
// TODO I doubt that this is correct
500
return double.Parse(s);
502
catch(FormatException x)
504
throw JavaException.NumberFormatException(x.Message);
508
public static string toString(double d, bool isFloat)
513
// TODO this is not correct, we need to use the Java algorithm of converting a float to string
518
if(float.IsNegativeInfinity(f))
522
if(float.IsPositiveInfinity(f))
526
// HACK really lame hack to apprioximate the Java behavior a little bit
527
string s = f.ToString(System.Globalization.CultureInfo.InvariantCulture);
528
if(s.IndexOf('.') == -1)
532
// make sure -0.0 renders correctly
533
if(d == 0.0 && BitConverter.DoubleToInt64Bits(d) < 0)
541
StringBuilder sb = new StringBuilder();
542
DoubleToString.append(sb, d);
543
return sb.ToString();
548
public class VMSecurityManager
550
public static object getClassContext()
552
ArrayList ar = new ArrayList();
553
NetSystem.Diagnostics.StackTrace st = new NetSystem.Diagnostics.StackTrace();
554
for(int i = 0; i < st.FrameCount; i++)
556
NetSystem.Diagnostics.StackFrame frame = st.GetFrame(i);
557
// HACK very insecure
558
// TODO handle reflection scenario
559
if(frame.GetMethod().Name != "getClassContext")
561
ar.Add(VMClass.getClassFromType(frame.GetMethod().DeclaringType));
564
return ar.ToArray(CoreClasses.java.lang.Class.Wrapper.TypeAsArrayType);
567
public static object currentClassLoader()
569
// TODO handle PrivilegedAction
570
NetSystem.Diagnostics.StackTrace st = new NetSystem.Diagnostics.StackTrace();
571
for(int i = 0; i < st.FrameCount; i++)
573
NetSystem.Diagnostics.StackFrame frame = st.GetFrame(i);
574
TypeWrapper wrapper = ClassLoaderWrapper.GetWrapperFromTypeFast(frame.GetMethod().DeclaringType);
575
if(wrapper != null && wrapper.GetClassLoader().GetJavaClassLoader() != null)
577
return wrapper.GetClassLoader().GetJavaClassLoader();
584
public class VMSystem
586
public static void arraycopy_primitive_8(Array src, int srcStart, Array dest, int destStart, int len)
592
Buffer.BlockCopy(src, srcStart << 3, dest, destStart << 3, len << 3);
596
catch(ArgumentNullException)
598
throw JavaException.NullPointerException();
600
catch(OverflowException)
602
throw JavaException.ArrayIndexOutOfBoundsException();
604
catch(ArgumentException)
606
throw JavaException.ArrayIndexOutOfBoundsException();
610
public static void arraycopy_primitive_4(Array src, int srcStart, Array dest, int destStart, int len)
616
Buffer.BlockCopy(src, srcStart << 2, dest, destStart << 2, len << 2);
620
catch(ArgumentNullException)
622
throw JavaException.NullPointerException();
624
catch(OverflowException)
626
throw JavaException.ArrayIndexOutOfBoundsException();
628
catch(ArgumentException)
630
throw JavaException.ArrayIndexOutOfBoundsException();
634
public static void arraycopy_primitive_2(Array src, int srcStart, Array dest, int destStart, int len)
640
Buffer.BlockCopy(src, srcStart << 1, dest, destStart << 1, len << 1);
644
catch(ArgumentNullException)
646
throw JavaException.NullPointerException();
648
catch(OverflowException)
650
throw JavaException.ArrayIndexOutOfBoundsException();
652
catch(ArgumentException)
654
throw JavaException.ArrayIndexOutOfBoundsException();
658
public static void arraycopy_primitive_1(Array src, int srcStart, Array dest, int destStart, int len)
662
Buffer.BlockCopy(src, srcStart, dest, destStart, len);
665
catch(ArgumentNullException)
667
throw JavaException.NullPointerException();
669
catch(OverflowException)
671
throw JavaException.ArrayIndexOutOfBoundsException();
673
catch(ArgumentException)
675
throw JavaException.ArrayIndexOutOfBoundsException();
679
public static void arraycopy(object src, int srcStart, object dest, int destStart, int len)
683
// NOTE side effect of GetTypeHandle call is null check for src and dest (it
684
// throws an ArgumentNullException)
685
// Since constructing a Type object is expensive, we use Type.GetTypeHandle and
686
// hope that it is implemented in a such a way that it is more efficient than
690
RuntimeTypeHandle type_src = Type.GetTypeHandle(src);
691
RuntimeTypeHandle type_dst = Type.GetTypeHandle(dest);
692
if(type_src.Value != type_dst.Value)
698
// since Java strictly defines what happens when an ArrayStoreException occurs during copying
699
// and .NET doesn't, we have to do it by hand
700
Object[] src1 = (Object[])src;
701
Object[] dst1 = (Object[])dest;
702
for(; len > 0; len--)
704
dst1[destStart++] = src1[srcStart++];
708
catch(InvalidCastException)
710
throw JavaException.ArrayStoreException("cast failed");
713
throw JavaException.ArrayIndexOutOfBoundsException();
716
catch(ArgumentNullException)
718
throw JavaException.NullPointerException();
723
Array.Copy((Array)src, srcStart, (Array)dest, destStart, len);
725
catch(ArgumentNullException)
727
throw JavaException.NullPointerException();
729
catch(ArgumentException)
731
throw JavaException.ArrayIndexOutOfBoundsException();
733
catch(InvalidCastException x)
735
if(!src.GetType().IsArray)
737
throw JavaException.ArrayStoreException("source is not an array");
739
if(!dest.GetType().IsArray)
741
throw JavaException.ArrayStoreException("destination is not an array");
743
// this shouldn't happen
744
throw JavaException.ArrayStoreException(x.Message);
748
public static bool isWordsBigEndian()
750
return !BitConverter.IsLittleEndian;
753
public static long currentTimeMillis()
755
const long january_1st_1970 = 62135596800000L;
756
return DateTime.UtcNow.Ticks / 10000L - january_1st_1970;
759
public static void setErr(object printStream)
761
TypeWrapper tw = ClassLoaderWrapper.LoadClassCritical("java.lang.System");
762
FieldWrapper fw = tw.GetFieldWrapper("err", ClassLoaderWrapper.LoadClassCritical("java.io.PrintStream"));
765
public static void setIn(object inputStream)
767
TypeWrapper tw = ClassLoaderWrapper.LoadClassCritical("java.lang.System");
768
FieldWrapper fw = tw.GetFieldWrapper("in", ClassLoaderWrapper.LoadClassCritical("java.io.InputStream"));
769
fw.SetValue(null, inputStream);
772
public static void setOut(object printStream)
774
TypeWrapper tw = ClassLoaderWrapper.LoadClassCritical("java.lang.System");
775
FieldWrapper fw = tw.GetFieldWrapper("out", ClassLoaderWrapper.LoadClassCritical("java.io.PrintStream"));
776
fw.SetValue(null, printStream);
779
public static int identityHashCode(object o)
781
return RuntimeHelpers.GetHashCode(o);
785
public class VMClassLoader
787
public static Assembly findResourceAssembly(string name)
789
Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies();
790
for(int i = 0; i < assemblies.Length; i++)
792
if(!(assemblies[i] is NetSystem.Reflection.Emit.AssemblyBuilder))
794
if(assemblies[i].GetManifestResourceInfo("ikvm:" + name) != null)
796
return assemblies[i];
803
public static object getBootstrapClassLoader()
805
return ClassLoaderWrapper.GetJavaBootstrapClassLoader();
808
public static object getPrimitiveClass(char type)
813
return VMClass.getClassFromType(typeof(bool));
815
return VMClass.getClassFromType(typeof(sbyte));
817
return VMClass.getClassFromType(typeof(char));
819
return VMClass.getClassFromType(typeof(double));
821
return VMClass.getClassFromType(typeof(float));
823
return VMClass.getClassFromType(typeof(int));
825
return VMClass.getClassFromType(typeof(long));
827
return VMClass.getClassFromType(typeof(short));
829
return VMClass.getClassFromType(typeof(void));
831
throw new InvalidOperationException();
835
public static object defineClass(object classLoader, string name, byte[] data, int offset, int length, object protectionDomain)
837
Profiler.Enter("ClassLoader.defineClass");
842
ClassFile classFile = new ClassFile(data, offset, length, name);
843
if(name != null && classFile.Name != name)
845
throw JavaException.NoClassDefFoundError("{0} (wrong name: {1})", name, classFile.Name);
847
TypeWrapper type = ClassLoaderWrapper.GetClassLoaderWrapper(classLoader).DefineClass(classFile);
848
object clazz = VMClass.CreateClassInstance(type);
849
if(protectionDomain != null)
851
// TODO cache the FieldInfo
852
clazz.GetType().GetField("pd", BindingFlags.Instance | BindingFlags.NonPublic).SetValue(clazz, protectionDomain);
856
catch(ClassFile.UnsupportedClassVersionError x)
858
throw JavaException.UnsupportedClassVersionError(x.Message);
860
catch(ClassFile.ClassFormatError x)
862
throw JavaException.ClassFormatError(x.Message);
867
Profiler.Leave("ClassLoader.defineClass");
874
private static Hashtable map = new Hashtable();
875
private delegate object LookupDelegate(object o);
876
private static LookupDelegate createClass;
877
private static LookupDelegate getWrapper;
879
public static void throwException(Exception e)
884
public static object loadArrayClass(string name, object classLoader)
886
ClassLoaderWrapper classLoaderWrapper = ClassLoaderWrapper.GetClassLoaderWrapper(classLoader);
887
TypeWrapper type = classLoaderWrapper.LoadClassByDottedName(name);
888
return getClassFromWrapper(type);
891
public static object loadBootstrapClass(string name, bool initialize)
893
TypeWrapper type = ClassLoaderWrapper.GetBootstrapClassLoader().LoadClassByDottedNameFast(name);
901
return getClassFromWrapper(type);
906
internal static object CreateClassInstance(TypeWrapper wrapper)
908
if(createClass == null)
910
TypeWrapper tw = ClassLoaderWrapper.LoadClassCritical("java.lang.VMClass");
912
createClass = (LookupDelegate)Delegate.CreateDelegate(typeof(LookupDelegate), tw.TypeAsTBD.GetMethod("createClass", BindingFlags.Static | BindingFlags.Public));
913
// HACK to make sure we don't run into any problems creating class objects for classes that
914
// participate in the VMClass static initialization, we first do a bogus call to initialize
915
// the machinery (I ran into this when running ikvmstub on IKVM.GNU.Classpath.dll)
919
object o = map[wrapper];
926
object clazz = createClass(wrapper);
931
map.Add(wrapper, clazz);
937
public static bool IsAssignableFrom(object w1, object w2)
939
return ((TypeWrapper)w2).IsAssignableTo((TypeWrapper)w1);
942
public static bool IsInterface(object wrapper)
944
return ((TypeWrapper)wrapper).IsInterface;
947
public static bool IsArray(object wrapper)
949
return ((TypeWrapper)wrapper).IsArray;
952
public static object GetSuperClassFromWrapper(object wrapper)
954
TypeWrapper baseWrapper = ((TypeWrapper)wrapper).BaseTypeWrapper;
955
if(baseWrapper != null)
957
return getClassFromWrapper(baseWrapper);
962
public static object getComponentClassFromWrapper(object wrapper)
964
TypeWrapper typeWrapper = (TypeWrapper)wrapper;
965
if(typeWrapper.ArrayRank > 0)
967
TypeWrapper elementWrapper = typeWrapper.ElementTypeWrapper;
968
// TODO why are we finishing here? This shouldn't be necessary
969
elementWrapper.Finish();
970
return getClassFromWrapper(elementWrapper);
975
internal static TypeWrapper getWrapperFromClass(object clazz)
977
if(getWrapper == null)
979
TypeWrapper tw = ClassLoaderWrapper.LoadClassCritical("java.lang.VMClass");
981
getWrapper = (LookupDelegate)Delegate.CreateDelegate(typeof(LookupDelegate), tw.TypeAsTBD.GetMethod("getWrapperFromClass", BindingFlags.Static | BindingFlags.Public));
983
return (TypeWrapper)getWrapper(clazz);
986
internal static object getClassFromWrapper(TypeWrapper wrapper)
990
object clazz = map[wrapper];
993
clazz = CreateClassInstance(wrapper);
999
public static object getClassFromType(Type type)
1001
TypeWrapper.AssertFinished(type);
1006
return getClassFromWrapper(ClassLoaderWrapper.GetWrapperFromType(type));
1009
public static string GetName(object wrapper)
1011
TypeWrapper typeWrapper = (TypeWrapper)wrapper;
1012
if(typeWrapper.IsPrimitive)
1014
if(typeWrapper == PrimitiveTypeWrapper.VOID)
1018
else if(typeWrapper == PrimitiveTypeWrapper.BYTE)
1022
else if(typeWrapper == PrimitiveTypeWrapper.BOOLEAN)
1026
else if(typeWrapper == PrimitiveTypeWrapper.SHORT)
1030
else if(typeWrapper == PrimitiveTypeWrapper.CHAR)
1034
else if(typeWrapper == PrimitiveTypeWrapper.INT)
1038
else if(typeWrapper == PrimitiveTypeWrapper.LONG)
1042
else if(typeWrapper == PrimitiveTypeWrapper.FLOAT)
1046
else if(typeWrapper == PrimitiveTypeWrapper.DOUBLE)
1052
throw new InvalidOperationException();
1055
return typeWrapper.Name;
1058
public static void initialize(object cwrapper)
1060
TypeWrapper wrapper = (TypeWrapper)cwrapper;
1062
wrapper.RunClassInit();
1065
public static object getClassLoader0(object wrapper)
1067
return ((TypeWrapper)wrapper).GetClassLoader().GetJavaClassLoader();
1070
public static object getClassLoaderFromType(Type type)
1072
return ClassLoaderWrapper.GetWrapperFromType(type).GetClassLoader().GetJavaClassLoader();
1075
public static object[] GetDeclaredMethods(object cwrapper, bool getMethods, bool publicOnly)
1077
Profiler.Enter("VMClass.GetDeclaredMethods");
1080
TypeWrapper wrapper = (TypeWrapper)cwrapper;
1081
// we need to finish the type otherwise all methods will not be in the method map yet
1083
// we need to look through the array for unloadable types, because we may not let them
1084
// escape into the 'wild'
1085
MethodWrapper[] methods = wrapper.GetMethods();
1086
ArrayList list = new ArrayList();
1087
for(int i = 0; i < methods.Length; i++)
1089
// we don't want to expose "hideFromReflection" methods (one reason is that it would
1090
// mess up the serialVersionUID computation)
1091
if(!methods[i].IsHideFromReflection)
1093
if(methods[i].Name == "<clinit>")
1095
// not reported back
1097
else if(publicOnly && !methods[i].IsPublic)
1099
// caller is only asking for public methods, so we don't return this non-public method
1101
else if((methods[i].Name == "<init>") != getMethods)
1103
if(methods[i].ReturnType.IsUnloadable)
1105
throw JavaException.NoClassDefFoundError(methods[i].ReturnType.Name);
1107
TypeWrapper[] args = methods[i].GetParameters();
1108
for(int j = 0; j < args.Length; j++)
1110
if(args[j].IsUnloadable)
1112
throw JavaException.NoClassDefFoundError(args[j].Name);
1115
list.Add(methods[i]);
1119
return (MethodWrapper[])list.ToArray(typeof(MethodWrapper));
1123
Profiler.Leave("VMClass.GetDeclaredMethods");
1127
public static object[] GetDeclaredFields(object cwrapper, bool publicOnly)
1129
Profiler.Enter("VMClass.GetDeclaredFields");
1132
TypeWrapper wrapper = (TypeWrapper)cwrapper;
1133
// we need to finish the type otherwise all fields will not be in the field map yet
1135
// we need to look through the array for unloadable types, because we may not let them
1136
// escape into the 'wild'
1137
FieldWrapper[] fields = wrapper.GetFields();
1140
ArrayList list = new ArrayList();
1141
for(int i = 0; i < fields.Length; i++)
1143
if(fields[i].IsPublic)
1145
list.Add(fields[i]);
1148
fields = (FieldWrapper[])list.ToArray(typeof(FieldWrapper));
1150
for(int i = 0; i < fields.Length; i++)
1152
if(fields[i].FieldTypeWrapper.IsUnloadable)
1154
throw JavaException.NoClassDefFoundError(fields[i].FieldTypeWrapper.Name);
1161
Profiler.Leave("VMClass.GetDeclaredFields");
1165
public static object[] GetDeclaredClasses(object cwrapper, bool publicOnly)
1167
TypeWrapper wrapper = (TypeWrapper)cwrapper;
1168
// NOTE to get at the InnerClasses we need to finish the type
1170
TypeWrapper[] wrappers = wrapper.InnerClasses;
1173
ArrayList list = new ArrayList();
1174
for(int i = 0; i < wrappers.Length; i++)
1176
if(wrappers[i].IsUnloadable)
1178
throw JavaException.NoClassDefFoundError(wrappers[i].Name);
1180
// because the VM lacks any support for nested visibility control, we
1181
// cannot rely on the publicness of the type here, but instead we have
1182
// to look at the reflective modifiers
1183
wrappers[i].Finish();
1184
if((wrappers[i].ReflectiveModifiers & Modifiers.Public) != 0)
1186
list.Add(wrappers[i]);
1189
wrappers = (TypeWrapper[])list.ToArray(typeof(TypeWrapper));
1191
object[] innerclasses = new object[wrappers.Length];
1192
for(int i = 0; i < innerclasses.Length; i++)
1194
if(wrappers[i].IsUnloadable)
1196
throw JavaException.NoClassDefFoundError(wrappers[i].Name);
1198
innerclasses[i] = getClassFromWrapper(wrappers[i]);
1200
return innerclasses;
1203
public static object GetDeclaringClass(object cwrapper)
1205
TypeWrapper wrapper = (TypeWrapper)cwrapper;
1206
// before we can call DeclaringTypeWrapper, we need to finish the type
1208
TypeWrapper declaring = wrapper.DeclaringTypeWrapper;
1209
if(declaring == null)
1213
if(declaring.IsUnloadable)
1215
throw JavaException.NoClassDefFoundError(declaring.Name);
1217
return getClassFromWrapper(declaring);
1220
public static object[] GetInterfaces(object cwrapper)
1222
TypeWrapper wrapper = (TypeWrapper)cwrapper;
1223
// we need to finish the type otherwise all fields will not be in the field map yet
1224
// TODO this should not be needed (make sure it isn't and remove)
1226
TypeWrapper[] interfaceWrappers = wrapper.Interfaces;
1227
object[] interfaces = new object[interfaceWrappers.Length];
1228
for(int i = 0; i < interfaces.Length; i++)
1230
interfaces[i] = getClassFromWrapper(interfaceWrappers[i]);
1235
public static int GetModifiers(Object cwrapper)
1237
TypeWrapper wrapper = (TypeWrapper)cwrapper;
1238
// NOTE ReflectiveModifiers is only available for finished types
1240
// NOTE we don't return the modifiers from the TypeWrapper, because for inner classes
1241
// the reflected modifiers are different from the physical ones
1242
Modifiers modifiers = wrapper.ReflectiveModifiers;
1243
// only returns public, protected, private, final, static, abstract and interface (as per
1244
// the documentation of Class.getModifiers())
1245
Modifiers mask = Modifiers.Public | Modifiers.Protected | Modifiers.Private | Modifiers.Final |
1246
Modifiers.Static | Modifiers.Abstract | Modifiers.Interface;
1247
return (int)(modifiers & mask);
1254
public class VMObjectStreamClass
1256
public static bool hasClassInitializer(object clazz)
1258
TypeWrapper wrapper = NativeCode.java.lang.VMClass.getWrapperFromClass(clazz);
1260
Type type = wrapper.TypeAsTBD;
1263
if(!type.IsArray && type.TypeInitializer != null)
1265
return !AttributeHelper.IsHideFromReflection(type.TypeInitializer);
1271
Console.WriteLine(type.FullName);
1272
Console.WriteLine(x);
1277
private static FieldWrapper GetFieldWrapperFromField(object field)
1279
// TODO optimize this
1280
return (FieldWrapper)field.GetType().GetField("fieldCookie", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(field);
1283
public static void setDoubleNative(object field, object obj, double val)
1285
GetFieldWrapperFromField(field).SetValue(obj, val);
1288
public static void setFloatNative(object field, object obj, float val)
1290
GetFieldWrapperFromField(field).SetValue(obj, val);
1293
public static void setLongNative(object field, object obj, long val)
1295
GetFieldWrapperFromField(field).SetValue(obj, val);
1298
public static void setIntNative(object field, object obj, int val)
1300
GetFieldWrapperFromField(field).SetValue(obj, val);
1303
public static void setShortNative(object field, object obj, short val)
1305
GetFieldWrapperFromField(field).SetValue(obj, val);
1308
public static void setCharNative(object field, object obj, char val)
1310
GetFieldWrapperFromField(field).SetValue(obj, val);
1313
public static void setByteNative(object field, object obj, sbyte val)
1315
GetFieldWrapperFromField(field).SetValue(obj, val);
1318
public static void setBooleanNative(object field, object obj, bool val)
1320
GetFieldWrapperFromField(field).SetValue(obj, val);
1323
public static void setObjectNative(object field, object obj, object val)
1325
GetFieldWrapperFromField(field).SetValue(obj, val);
1329
public class ObjectInputStream
1331
public static object currentClassLoader(object sm)
1333
// TODO calling currentClassLoader in SecurityManager results in null being returned, so we use our own
1334
// version for now, don't know what the security implications of this are
1336
return NativeCode.java.lang.VMSecurityManager.currentClassLoader();
1339
public static object allocateObject(object ois, object clazz)
1341
Profiler.Enter("ObjectInputStream.allocateObject");
1344
return JniHelper.AllocObject(clazz);
1348
Profiler.Leave("ObjectInputStream.allocateObject");
1352
public static void callConstructor(object ois, object clazz, object obj)
1354
Profiler.Enter("ObjectInputStream.callConstructor");
1357
TypeWrapper type = NativeCode.java.lang.VMClass.getWrapperFromClass(clazz);
1359
MethodWrapper mw = type.GetMethodWrapper(MethodDescriptor.FromNameSig(type.GetClassLoader(), "<init>", "()V"), false);
1362
// TODO what should we do here?
1363
throw new NotImplementedException();
1365
// TODO what about exceptions? (should they be unwrapped?)
1366
mw.Invoke(obj, null, true);
1370
Profiler.Leave("ObjectInputStream.callConstructor");
1378
public class TimeZone
1380
public static string getDefaultTimeZoneId()
1382
NetSystem.TimeZone currentTimeZone = NetSystem.TimeZone.CurrentTimeZone;
1383
NetSystem.TimeSpan timeSpan = currentTimeZone.GetUtcOffset(DateTime.Now);
1385
int hours = timeSpan.Hours;
1386
int mins = timeSpan.Minutes;
1388
return "GMT" + hours + ":" + mins;
1395
public class InetAddress
1397
public static sbyte[] lookupInaddrAny()
1399
return new sbyte[] { 0, 0, 0, 0 };
1402
public static string getLocalHostname()
1404
// TODO error handling
1405
return NetSystem.Net.Dns.GetHostName();
1408
public static sbyte[][] getHostByName(string name)
1410
// TODO error handling
1413
NetSystem.Net.IPHostEntry he = NetSystem.Net.Dns.GetHostByName(name);
1414
NetSystem.Net.IPAddress[] addresses = he.AddressList;
1415
sbyte[][] list = new sbyte[addresses.Length][];
1416
for(int i = 0; i < addresses.Length; i++)
1418
byte[] address = addresses[i].GetAddressBytes();
1419
sbyte[] sb = new sbyte[address.Length];
1420
for(int j = 0; j < sb.Length; j++)
1422
sb[j] = (sbyte)address[j];
1430
throw JavaException.UnknownHostException(x.Message);
1434
public static string getHostByAddr(byte[] address)
1439
s = NetSystem.Net.Dns.GetHostByAddress(string.Format("{0}.{1}.{2}.{3}", address[0], address[1], address[2], address[3])).HostName;
1441
catch(NetSystem.Net.Sockets.SocketException x)
1443
throw JavaException.UnknownHostException(x.Message);
1447
NetSystem.Net.Dns.GetHostByName(s);
1449
catch(NetSystem.Net.Sockets.SocketException)
1451
// FXBUG .NET framework bug
1452
// HACK if GetHostByAddress returns a netbios name, it appends the default DNS suffix, but if the
1453
// machine's netbios name isn't the same as the DNS hostname, this might result in an unresolvable
1454
// name, if that happens we chop of the DNS suffix.
1455
int idx = s.IndexOf('.');
1458
return s.Substring(0, idx);