public static jlClass getFriendlyClassFromType(Type type) { int rank = 0; while (ReflectUtil.IsVector(type)) { type = type.GetElementType(); rank++; } if (type.DeclaringType != null && AttributeHelper.IsGhostInterface(type.DeclaringType)) { type = type.DeclaringType; } if (!IsVisibleAsClass(type)) { return(null); } TypeWrapper wrapper = ClassLoaderWrapper.GetWrapperFromType(type); if (wrapper == null) { return(null); } if (rank > 0) { wrapper = wrapper.MakeArrayType(rank); } return(wrapper.ClassObject); }
public static java.lang.Class[] getClassContext(object thisSecurityManager) { #if FIRST_PASS return(null); #else List <java.lang.Class> stack = new List <java.lang.Class>(); StackTrace trace = new StackTrace(); for (int i = 0; i < trace.FrameCount; i++) { StackFrame frame = trace.GetFrame(i); MethodBase method = frame.GetMethod(); if (Java_sun_reflect_Reflection.IsHideFromStackWalk(method)) { continue; } Type type = method.DeclaringType; if (type == typeof(java.lang.SecurityManager)) { continue; } stack.Add(ClassLoaderWrapper.GetWrapperFromType(type).ClassObject); } return(stack.ToArray()); #endif }
internal static TypeWrapper GetTypeWrapperFromObject(object o) { TypeWrapper ghostType = GhostTag.GetTag(o); if (ghostType != null) { return(ghostType); } Type t = o.GetType(); if (t.IsPrimitive || (ClassLoaderWrapper.IsRemappedType(t) && !t.IsSealed)) { return(DotNetTypeWrapper.GetWrapperFromDotNetType(t)); } for (; ;) { TypeWrapper tw = ClassLoaderWrapper.GetWrapperFromType(t); // if GetWrapperFromType returns null (or if tw.IsAbstract), that // must mean that the Type of the object is an implementation helper class // (e.g. an AtomicReferenceFieldUpdater or ThreadLocal instrinsic subclass) if (tw != null && (!tw.IsAbstract || tw.IsArray)) { return(tw); } t = t.BaseType; } }
public static java.lang.Class defineClass1(java.lang.ClassLoader thisClassLoader, string name, byte[] b, int off, int len, java.security.ProtectionDomain pd, string source) { // it appears the source argument is only used for trace messages in HotSpot. We'll just ignore it for now. Profiler.Enter("ClassLoader.defineClass"); try { try { ClassLoaderWrapper classLoaderWrapper = ClassLoaderWrapper.GetClassLoaderWrapper(thisClassLoader); ClassFile classFile = new ClassFile(b, off, len, name, classLoaderWrapper.ClassFileParseOptions, null); if (name != null && classFile.Name != name) { #if !FIRST_PASS throw new java.lang.NoClassDefFoundError(name + " (wrong name: " + classFile.Name + ")"); #endif } TypeWrapper type = classLoaderWrapper.DefineClass(classFile, pd); return(type.ClassObject); } catch (RetargetableJavaException x) { throw x.ToJava(); } } finally { Profiler.Leave("ClassLoader.defineClass"); } }
internal static object AnnotationsToMap(ClassLoaderWrapper loader, object[] objAnn) { #if FIRST_PASS return(null); #else java.util.LinkedHashMap map = new java.util.LinkedHashMap(); if (objAnn != null) { foreach (object obj in objAnn) { java.lang.annotation.Annotation a = obj as java.lang.annotation.Annotation; if (a != null) { map.put(a.annotationType(), FreezeOrWrapAttribute(a)); } else if (obj is IKVM.Attributes.DynamicAnnotationAttribute) { a = (java.lang.annotation.Annotation)JVM.NewAnnotation(loader.GetJavaClassLoader(), ((IKVM.Attributes.DynamicAnnotationAttribute)obj).Definition); if (a != null) { map.put(a.annotationType(), a); } } } } return(map); #endif }
public static java.security.ProtectionDomain getProtectionDomain0(java.lang.Class thisClass) { #if FIRST_PASS return(null); #else TypeWrapper wrapper = TypeWrapper.FromClass(thisClass); if (wrapper.IsArray) { return(null); } java.security.ProtectionDomain pd = wrapper.ClassObject.pd; if (pd == null) { // The protection domain for statically compiled code is created lazily (not at java.lang.Class creation time), // to work around boot strap issues. AssemblyClassLoader acl = wrapper.GetClassLoader() as AssemblyClassLoader; if (acl != null) { pd = acl.GetProtectionDomain(); } else if (wrapper is AnonymousTypeWrapper) { // dynamically compiled intrinsified lamdba anonymous types end up here and should get their // protection domain from the host class pd = ClassLoaderWrapper.GetWrapperFromType(wrapper.TypeAsTBD.DeclaringType).ClassObject.pd; } } return(pd); #endif }
private static object EncodeAnnotationValue(CustomAttributeTypedArgument arg) { if (arg.ArgumentType.IsEnum) { // if GetWrapperFromType returns null, we've got an ikvmc synthesized .NET enum nested inside a Java enum TypeWrapper tw = ClassLoaderWrapper.GetWrapperFromType(arg.ArgumentType) ?? ClassLoaderWrapper.GetWrapperFromType(arg.ArgumentType.DeclaringType); return(new object[] { AnnotationDefaultAttribute.TAG_ENUM, EncodeTypeName(tw), Enum.GetName(arg.ArgumentType, arg.Value) }); } else if (arg.Value is Type) { return(new object[] { AnnotationDefaultAttribute.TAG_CLASS, EncodeTypeName(ClassLoaderWrapper.GetWrapperFromType((Type)arg.Value)) }); } else if (arg.ArgumentType.IsArray) { IList <CustomAttributeTypedArgument> array = (IList <CustomAttributeTypedArgument>)arg.Value; object[] arr = new object[array.Count + 1]; arr[0] = AnnotationDefaultAttribute.TAG_ARRAY; for (int i = 0; i < array.Count; i++) { arr[i + 1] = EncodeAnnotationValue(array[i]); } return(arr); } else { return(arg.Value); } }
private static TypeWrapper LoadTypeWrapper(string clazz, [email protected] callerId) { #if FIRST_PASS return null; #else try { TypeWrapper context = TypeWrapper.FromClass(callerId.getCallerClass()); TypeWrapper wrapper = ClassLoaderWrapper.FromCallerID(callerId).LoadClassByDottedName(clazz); java.lang.ClassLoader loader = callerId.getCallerClassLoader(); if(loader != null) { loader.checkPackageAccess(wrapper.ClassObject, callerId.getCallerClass().pd); } if(!wrapper.IsAccessibleFrom(context)) { throw new java.lang.IllegalAccessError("Try to access class " + wrapper.Name + " from class " + context.Name); } wrapper.Finish(); return wrapper; } catch(RetargetableJavaException x) { throw x.ToJava(); } #endif }
public static java.lang.ClassLoader latestUserDefinedLoader() { // testing shows that it is cheaper the get the full stack trace and then look at a few frames than getting the frames individually StackTrace trace = new StackTrace(2, false); for (int i = 0; i < trace.FrameCount; i++) { StackFrame frame = trace.GetFrame(i); MethodBase method = frame.GetMethod(); if (method == null) { continue; } Type type = method.DeclaringType; if (type != null) { TypeWrapper tw = ClassLoaderWrapper.GetWrapperFromType(type); if (tw != null) { ClassLoaderWrapper classLoader = tw.GetClassLoader(); AssemblyClassLoader acl = classLoader as AssemblyClassLoader; if (acl == null || acl.GetAssembly(tw) != typeof(object).Assembly) { java.lang.ClassLoader javaClassLoader = classLoader.GetJavaClassLoader(); if (javaClassLoader != null) { return(javaClassLoader); } } } } } return(null); }
public static java.lang.Class[] getClassContext(object thisSecurityManager) { #if FIRST_PASS return(null); #else List <java.lang.Class> stack = new List <java.lang.Class>(); StackTrace trace = new StackTrace(); for (int i = 0; i < trace.FrameCount; i++) { StackFrame frame = trace.GetFrame(i); MethodBase method = frame.GetMethod(); Type type = method.DeclaringType; // NOTE these checks should be the same as the ones in Reflection.getCallerClass if (Java_sun_reflect_Reflection.IsHideFromJava(method) || type == null || type.Assembly == typeof(object).Assembly || type.Assembly == typeof(Java_java_lang_SecurityManager).Assembly || type.Assembly == jniAssembly || type == typeof(java.lang.reflect.Constructor) || type == typeof(java.lang.reflect.Method)) { continue; } if (type == typeof(java.lang.SecurityManager)) { continue; } stack.Add(ClassLoaderWrapper.GetWrapperFromType(type).ClassObject); } return(stack.ToArray()); #endif }
public static java.net.URL getBootstrapResource(string name) { foreach (java.net.URL url in ClassLoaderWrapper.GetBootstrapClassLoader().GetResources(name)) { return(url); } return(null); }
public static java.util.Enumeration getBootstrapResources(string name) { #if FIRST_PASS return(null); #else return(new ikvm.runtime.EnumerationWrapper(ClassLoaderWrapper.GetBootstrapClassLoader().GetResources(name))); #endif }
internal override void Generate(CodeGenContext context, CodeEmitter ilgen) { FieldWrapper fw = ClassLoaderWrapper.LoadClassCritical(Class).GetFieldWrapper(Name, Sig); fw.Link(); // we don't use fw.EmitSet because we don't want automatic unboxing and whatever ilgen.Emit(OpCodes.Stsfld, fw.GetField()); }
public static int GetGenericClassLoaderId(object classLoader) { #if FIRST_PASS return(0); #else return(ClassLoaderWrapper.GetGenericClassLoaderId(ClassLoaderWrapper.GetClassLoaderWrapper(classLoader))); #endif }
public static string GetGenericClassLoaderName(object classLoader) { #if FIRST_PASS return(null); #else return(((GenericClassLoader)ClassLoaderWrapper.GetClassLoaderWrapper(classLoader)).GetName()); #endif }
// this method is called from <GhostType>.IsInstanceArray() internal static bool IsGhostArrayInstance(object obj, RuntimeTypeHandle typeHandle, int rank) { TypeWrapper tw1 = GhostTag.GetTag(obj); if(tw1 != null) { TypeWrapper tw2 = ClassLoaderWrapper.GetWrapperFromType(Type.GetTypeFromHandle(typeHandle)).MakeArrayType(rank); return tw1.IsAssignableTo(tw2); } return false; }
public static Delegate DynamicCreateDelegate(object obj, Type delegateType, string name, string sig) { #if !WINRT #if FIRST_PASS return(null); #else TypeWrapper tw = TypeWrapper.FromClass(ikvm.runtime.Util.getClassFromObject(obj)); MethodWrapper mw = tw.GetMethodWrapper(name, sig, true); if (mw == null || mw.IsStatic || !mw.IsPublic) { #if NO_REF_EMIT java.lang.invoke.MethodType methodType = MethodHandleUtil.GetDelegateMethodType(delegateType); if (methodType.parameterCount() > MethodHandleUtil.MaxArity) { throw new NotImplementedException(); } java.lang.invoke.MethodHandle exception = java.lang.invoke.MethodHandles.publicLookup() .findConstructor(mw == null || mw.IsStatic ? typeof(java.lang.AbstractMethodError) : typeof(java.lang.IllegalAccessError), java.lang.invoke.MethodType.methodType(typeof(void), typeof(string))) .bindTo(tw.Name + ".Invoke" + sig); return(Delegate.CreateDelegate(delegateType, java.lang.invoke.MethodHandles.dropArguments( java.lang.invoke.MethodHandles.foldArguments(java.lang.invoke.MethodHandles.throwException(methodType.returnType(), exception.type().returnType()), exception), 0, methodType.parameterArray()).vmtarget, "Invoke")); #else MethodInfo invoke = delegateType.GetMethod("Invoke"); ParameterInfo[] parameters = invoke.GetParameters(); Type[] parameterTypes = new Type[parameters.Length + 1]; parameterTypes[0] = typeof(object); for (int i = 0; i < parameters.Length; i++) { parameterTypes[i + 1] = parameters[i].ParameterType; } System.Reflection.Emit.DynamicMethod dm = new System.Reflection.Emit.DynamicMethod("Invoke", invoke.ReturnType, parameterTypes); CodeEmitter ilgen = CodeEmitter.Create(dm); ilgen.Emit(System.Reflection.Emit.OpCodes.Ldstr, tw.Name + ".Invoke" + sig); ClassLoaderWrapper.GetBootstrapClassLoader() .LoadClassByDottedName(mw == null || mw.IsStatic ? "java.lang.AbstractMethodError" : "java.lang.IllegalAccessError") .GetMethodWrapper("<init>", "(Ljava.lang.String;)V", false) .EmitNewobj(ilgen); ilgen.Emit(System.Reflection.Emit.OpCodes.Throw); ilgen.DoEmit(); return(dm.CreateDelegate(delegateType, obj)); #endif } else { mw.ResolveMethod(); return(Delegate.CreateDelegate(delegateType, obj, (MethodInfo)mw.GetMethod())); } #endif #else throw new NotImplementedException(); #endif }
internal static void InlineJsrs(ClassLoaderWrapper classLoader, MethodWrapper mw, ClassFile classFile, ClassFile.Method m) { JsrInliner inliner; do { ClassFile.Method.Instruction[] codeCopy = (ClassFile.Method.Instruction[])m.Instructions.Clone(); InstructionFlags[] flags = new InstructionFlags[codeCopy.Length]; JsrMethodAnalyzer ma = new JsrMethodAnalyzer(mw, classFile, m, classLoader, flags); inliner = new JsrInliner(codeCopy, flags, m, ma); } while (inliner.InlineJsrs()); }
internal void Emit(ClassLoaderWrapper loader, CodeEmitter ilgen) { if (redirect != null) { redirect.Emit(loader, ilgen); } else { body.Emit(loader, ilgen); } }
internal static void Create(ModuleBuilder modb, ClassLoaderWrapper loader) { TypeBuilder tb = modb.DefineType(DotNetTypeWrapper.GenericDelegateInterfaceTypeName, TypeAttributes.Interface | TypeAttributes.Abstract | TypeAttributes.Public); tb.DefineGenericParameters("T")[0].SetBaseTypeConstraint(Types.MulticastDelegate); genericDelegateInterfaceType = tb.CreateType(); genericAttributeAnnotationType = CreateAnnotationType(modb, DotNetTypeWrapper.GenericAttributeAnnotationTypeName); genericAttributeAnnotationMultipleType = CreateAnnotationType(modb, DotNetTypeWrapper.GenericAttributeAnnotationMultipleTypeName); genericAttributeAnnotationReturnValueType = CreateAnnotationType(modb, DotNetTypeWrapper.GenericAttributeAnnotationReturnValueTypeName); CreateEnumEnum(modb, loader); }
public static java.lang.Class findLoadedClass0(java.lang.ClassLoader thisClassLoader, string name) { if (name == null) { return(null); } ClassLoaderWrapper loader = ClassLoaderWrapper.GetClassLoaderWrapper(thisClassLoader); TypeWrapper tw = loader.FindLoadedClass(name); return(tw != null ? tw.ClassObject : null); }
// called from map.xml as a replacement for Class.getClassLoader() in sun.invoke.util.VerifyAccess.isTypeVisible() public static java.lang.ClassLoader Class_getClassLoader(java.lang.Class clazz) { TypeWrapper tw = TypeWrapper.FromClass(clazz); if (ClassLoaderWrapper.GetBootstrapClassLoader().LoadClassByDottedNameFast(tw.Name) == tw) { // if a class is visible from the bootstrap class loader, we have to return null to allow the visibility check to succeed return(null); } return(tw.GetClassLoader().GetJavaClassLoader()); }
public static global::java.net.URL findResource(global::java.lang.ClassLoader _this, string name) { #if !FIRST_PASS AssemblyClassLoader_ wrapper = (AssemblyClassLoader_)ClassLoaderWrapper.GetClassLoaderWrapper(_this); foreach (global::java.net.URL url in wrapper.FindResources(name)) { return(url); } #endif return(null); }
private static void LazyInitSystemPackages() { if (systemPackages == null) { Dictionary <string, string> dict = new Dictionary <string, string>(); string path = VirtualFileSystem.GetAssemblyResourcesPath(JVM.CoreAssembly) + "resources.jar"; foreach (string pkg in ClassLoaderWrapper.GetBootstrapClassLoader().GetPackages()) { dict[pkg.Replace('.', '/') + "/"] = path; } Interlocked.CompareExchange(ref systemPackages, dict, null); } }
private static string GetAssemblyName(TypeWrapper tw) { ClassLoaderWrapper loader = tw.GetClassLoader(); AssemblyClassLoader acl = loader as AssemblyClassLoader; if (acl != null) { return(acl.GetAssembly(tw).FullName); } else { return(((GenericClassLoader)loader).GetName()); } }
internal override void Generate(CodeGenContext context, CodeEmitter ilgen) { if (Type != null) { ilgen.Emit(OpCodes.Ldsfld, StaticCompiler.GetType(context.ClassLoader, Type).GetField(Name, BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic)); } else { FieldWrapper fw = ClassLoaderWrapper.LoadClassCritical(Class).GetFieldWrapper(Name, Sig); fw.Link(); // we don't use fw.EmitGet because we don't want automatic unboxing and whatever ilgen.Emit(OpCodes.Ldsfld, fw.GetField()); } }
public static object DynamicGetfield(object obj, string name, string sig, RuntimeTypeHandle type, string clazz, [email protected] callerID) { Profiler.Count("DynamicGetfield"); FieldWrapper fw = GetFieldWrapper(ClassLoaderWrapper.GetWrapperFromType(obj.GetType()), type, clazz, name, sig, false); java.lang.reflect.Field field = (java.lang.reflect.Field)fw.ToField(false); object val = field.get(obj, callerID); if (fw.FieldTypeWrapper.IsPrimitive) { val = JVM.Unbox(val); } return(val); }
// TODO consider caching this delegate in MethodWrapper private static Delegate CreateMemberNameDelegate(MethodWrapper mw, java.lang.Class caller, bool doDispatch, MethodType type) { #if FIRST_PASS return(null); #else if (mw.IsDynamicOnly) { return(MethodHandleUtil.DynamicMethodBuilder.CreateDynamicOnly(mw, type)); } // HACK this code is duplicated in compiler.cs if (mw.IsProtected && (mw.DeclaringType == CoreClasses.java.lang.Object.Wrapper || mw.DeclaringType == CoreClasses.java.lang.Throwable.Wrapper)) { TypeWrapper thisType = TypeWrapper.FromClass(caller); TypeWrapper cli_System_Object = ClassLoaderWrapper.LoadClassCritical("cli.System.Object"); TypeWrapper cli_System_Exception = ClassLoaderWrapper.LoadClassCritical("cli.System.Exception"); // HACK we may need to redirect finalize or clone from java.lang.Object/Throwable // to a more specific base type. if (thisType.IsAssignableTo(cli_System_Object)) { mw = cli_System_Object.GetMethodWrapper(mw.Name, mw.Signature, true); } else if (thisType.IsAssignableTo(cli_System_Exception)) { mw = cli_System_Exception.GetMethodWrapper(mw.Name, mw.Signature, true); } else if (thisType.IsAssignableTo(CoreClasses.java.lang.Throwable.Wrapper)) { mw = CoreClasses.java.lang.Throwable.Wrapper.GetMethodWrapper(mw.Name, mw.Signature, true); } } TypeWrapper tw = mw.DeclaringType; tw.Finish(); mw.Link(); mw.ResolveMethod(); MethodInfo mi = mw.GetMethod() as MethodInfo; if (mi != null && !mw.HasCallerID && mw.IsStatic && MethodHandleUtil.HasOnlyBasicTypes(mw.GetParameters(), mw.ReturnType) && type.parameterCount() <= MethodHandleUtil.MaxArity) { return(Delegate.CreateDelegate(MethodHandleUtil.CreateMemberWrapperDelegateType(mw.GetParameters(), mw.ReturnType), mi)); } else { // slow path where we emit a DynamicMethod return(MethodHandleUtil.DynamicMethodBuilder.CreateMemberName(mw, type, doDispatch)); } #endif }
public static object DynamicInvokevirtual(object obj, RuntimeTypeHandle type, string clazz, string name, string sig, object[] args, [email protected] callerID) { Profiler.Count("DynamicInvokevirtual"); MethodWrapper mw = GetMethodWrapper(ClassLoaderWrapper.GetWrapperFromType(obj.GetType()), type, clazz, name, sig, false); java.lang.reflect.Method m = (java.lang.reflect.Method)mw.ToMethodOrConstructor(false); object val = m.invoke(obj, BoxArgs(mw, args), callerID); if (mw.ReturnType.IsPrimitive && mw.ReturnType != PrimitiveTypeWrapper.VOID) { val = JVM.Unbox(val); } return(val); }
internal static void Finish(ClassLoaderWrapper loader) { TypeBuilder tb = (TypeBuilder)genericEnumEnumType; TypeWrapper enumTypeWrapper = loader.LoadClassByDottedName("java.lang.Enum"); enumTypeWrapper.Finish(); tb.SetParent(enumTypeWrapper.TypeAsBaseType); CodeEmitter ilgen = CodeEmitter.Create(tb.DefineConstructor(MethodAttributes.Private, CallingConventions.Standard, new Type[] { Types.String, Types.Int32 })); ilgen.Emit(OpCodes.Ldarg_0); ilgen.Emit(OpCodes.Ldarg_1); ilgen.Emit(OpCodes.Ldarg_2); enumTypeWrapper.GetMethodWrapper("<init>", "(Ljava.lang.String;I)V", false).EmitCall(ilgen); ilgen.Emit(OpCodes.Ret); ilgen.DoEmit(); genericEnumEnumType = tb.CreateType(); }
private static void CreateEnumEnum(ModuleBuilder modb, ClassLoaderWrapper loader) { TypeWrapper enumTypeWrapper = loader.LoadClassByDottedName("java.lang.Enum"); enumTypeWrapper.Finish(); TypeBuilder tb = modb.DefineType(DotNetTypeWrapper.GenericEnumEnumTypeName, TypeAttributes.Class | TypeAttributes.Sealed | TypeAttributes.Public, enumTypeWrapper.TypeAsBaseType); GenericTypeParameterBuilder gtpb = tb.DefineGenericParameters("T")[0]; gtpb.SetBaseTypeConstraint(Types.Enum); CodeEmitter ilgen = CodeEmitter.Create(tb.DefineConstructor(MethodAttributes.Private, CallingConventions.Standard, new Type[] { Types.String, Types.Int32 })); ilgen.Emit(OpCodes.Ldarg_0); ilgen.Emit(OpCodes.Ldarg_1); ilgen.Emit(OpCodes.Ldarg_2); enumTypeWrapper.GetMethodWrapper("<init>", "(Ljava.lang.String;I)V", false).EmitCall(ilgen); ilgen.Emit(OpCodes.Ret); genericEnumEnumType = tb.CreateType(); }
public static string getAssemblyName(jlClass c) { TypeWrapper wrapper = TypeWrapper.FromClass(c); ClassLoaderWrapper loader = wrapper.GetClassLoader(); IKVM.Internal.AssemblyClassLoader acl = loader as IKVM.Internal.AssemblyClassLoader; if (acl != null) { return(acl.GetAssembly(wrapper).FullName); } else { return(((GenericClassLoaderWrapper)loader).GetName()); } }
public static void DynamicPutfield(object obj, object val, string name, string sig, RuntimeTypeHandle type, string clazz, [email protected] callerID) { Profiler.Count("DynamicPutfield"); FieldWrapper fw = GetFieldWrapper(ClassLoaderWrapper.GetWrapperFromType(obj.GetType()), type, clazz, name, sig, false); if (fw.IsFinal) { throw new java.lang.IllegalAccessError("Field " + fw.DeclaringType.Name + "." + fw.Name + " is final"); } java.lang.reflect.Field field = (java.lang.reflect.Field)fw.ToField(false); if (fw.FieldTypeWrapper.IsPrimitive) { val = JVM.Box(val); } field.set(obj, val, callerID); }
private static java.lang.invoke.MethodHandle DynamicLoadMethodHandleImpl(int kind, string clazz, string name, string sig, [email protected] callerID) { #if FIRST_PASS return(null); #else java.lang.Class refc = LoadTypeWrapper(clazz, callerID).ClassObject; try { switch ((ClassFile.RefKind)kind) { case ClassFile.RefKind.getStatic: case ClassFile.RefKind.putStatic: case ClassFile.RefKind.getField: case ClassFile.RefKind.putField: java.lang.Class type = ClassLoaderWrapper.FromCallerID(callerID).FieldTypeWrapperFromSig(sig).ClassObject; return(java.lang.invoke.MethodHandleNatives.linkMethodHandleConstant(callerID.getCallerClass(), kind, refc, name, type)); default: java.lang.invoke.MethodType mt = null; DynamicLoadMethodType(ref mt, sig, callerID); // HACK linkMethodHandleConstant is broken for MethodHandle.invoke[Exact] if (kind == (int)ClassFile.RefKind.invokeVirtual && refc == CoreClasses.java.lang.invoke.MethodHandle.Wrapper.ClassObject) { switch (name) { case "invokeExact": return(java.lang.invoke.MethodHandles.exactInvoker(mt)); case "invoke": return(java.lang.invoke.MethodHandles.invoker(mt)); } } java.lang.Class caller = callerID.getCallerClass(); DynamicTypeWrapper.FinishContext.HostCallerID hostCallerID = callerID as DynamicTypeWrapper.FinishContext.HostCallerID; if (hostCallerID != null) { caller = hostCallerID.host.ClassObject; } return(java.lang.invoke.MethodHandleNatives.linkMethodHandleConstant(caller, kind, refc, name, mt)); } } catch (RetargetableJavaException x) { throw x.ToJava(); } #endif }
internal override void Apply(ClassLoaderWrapper loader, TypeBuilder tb, object annotation) { }
internal override void Apply(ClassLoaderWrapper loader, ConstructorBuilder cb, object annotation) { }
internal override void Apply(ClassLoaderWrapper loader, ConstructorBuilder cb, object annotation) { Annotation annot = type.Annotation; foreach (object ann in UnwrapArray(annotation)) { annot.Apply(loader, cb, ann); } }
internal override void Apply(ClassLoaderWrapper loader, PropertyBuilder pb, object annotation) { if (type.IsSubclassOf(Types.SecurityAttribute)) { // you can't add declarative security to a property } else { pb.SetCustomAttribute(MakeCustomAttributeBuilder(loader, annotation)); } }
internal override void Apply(ClassLoaderWrapper loader, AssemblyBuilder ab, object annotation) { if (type.IsSubclassOf(Types.SecurityAttribute)) { #if STATIC_COMPILER ab.__AddDeclarativeSecurity(MakeCustomAttributeBuilder(loader, annotation)); #endif } #if STATIC_COMPILER else if (type == JVM.Import(typeof(System.Runtime.CompilerServices.TypeForwardedToAttribute))) { ab.__AddTypeForwarder((Type)ConvertValue(loader, Types.Type, ((object[])annotation)[3])); } else if (type == JVM.Import(typeof(System.Reflection.AssemblyVersionAttribute))) { string str = (string)ConvertValue(loader, Types.String, ((object[])annotation)[3]); Version version; if (IkvmcCompiler.TryParseVersion(str, out version)) { ab.__SetAssemblyVersion(version); } else { loader.IssueMessage(Message.InvalidCustomAttribute, type.FullName, "The version '" + str + "' is invalid."); } } else if (type == JVM.Import(typeof(System.Reflection.AssemblyCultureAttribute))) { string str = (string)ConvertValue(loader, Types.String, ((object[])annotation)[3]); if (str != "") { ab.__SetAssemblyCulture(str); } } else if (type == JVM.Import(typeof(System.Reflection.AssemblyDelaySignAttribute)) || type == JVM.Import(typeof(System.Reflection.AssemblyKeyFileAttribute)) || type == JVM.Import(typeof(System.Reflection.AssemblyKeyNameAttribute))) { loader.IssueMessage(Message.IgnoredCustomAttribute, type.FullName, "Please use the corresponding compiler switch."); } else if (type == JVM.Import(typeof(System.Reflection.AssemblyAlgorithmIdAttribute))) { // this attribute is currently not exposed as an annotation and isn't very interesting throw new NotImplementedException(); } else if (type == JVM.Import(typeof(System.Reflection.AssemblyFlagsAttribute))) { // this attribute is currently not exposed as an annotation and isn't very interesting throw new NotImplementedException(); } #endif else { ab.SetCustomAttribute(MakeCustomAttributeBuilder(loader, annotation)); } }
internal void Leave(ClassLoaderWrapper prev) { env.classLoader = prev; Leave(); }
private unsafe static void UnloadLibrary(long handle, ClassLoaderWrapper loader) { lock (JniLock) { Tracer.Info(Tracer.Jni, "Unloading library: handle = 0x{0:X}, class loader = {1}", handle, loader); IntPtr p = (IntPtr)handle; IntPtr onunload = ikvm_GetProcAddress(p, "JNI_OnUnload", IntPtr.Size * 2); if (onunload != IntPtr.Zero) { Tracer.Info(Tracer.Jni, "Calling JNI_OnUnload on: handle = 0x{0:X}", handle); JNI.Frame f = new JNI.Frame(); ClassLoaderWrapper prevLoader = f.Enter(loader); try { // TODO on Whidbey we should be able to use Marshal.GetDelegateForFunctionPointer to call OnLoad ikvm_CallOnLoad(onunload, JavaVM.pJavaVM, null); } finally { f.Leave(prevLoader); } } nativeLibraries.Remove(p); loader.UnregisterNativeLibrary(p); ikvm_FreeLibrary((IntPtr)handle); } }
internal DelegateInnerClassTypeWrapper(string name, Type delegateType, ClassLoaderWrapper classLoader) : base(Modifiers.Public | Modifiers.Interface | Modifiers.Abstract, name, null) { #if STATIC_COMPILER || STUB_GENERATOR this.fakeType = FakeTypes.GetDelegateType(delegateType); #elif !FIRST_PASS this.fakeType = typeof([email protected]<>).MakeGenericType(delegateType); #endif MethodInfo invoke = delegateType.GetMethod("Invoke"); ParameterInfo[] parameters = invoke.GetParameters(); TypeWrapper[] argTypeWrappers = new TypeWrapper[parameters.Length]; System.Text.StringBuilder sb = new System.Text.StringBuilder("("); for (int i = 0; i < parameters.Length; i++) { argTypeWrappers[i] = ClassLoaderWrapper.GetWrapperFromType(parameters[i].ParameterType); sb.Append(argTypeWrappers[i].SigName); } TypeWrapper returnType = ClassLoaderWrapper.GetWrapperFromType(invoke.ReturnType); sb.Append(")").Append(returnType.SigName); MethodWrapper invokeMethod = new DynamicOnlyMethodWrapper(this, "Invoke", sb.ToString(), returnType, argTypeWrappers); SetMethods(new MethodWrapper[] { invokeMethod }); SetFields(FieldWrapper.EmptyArray); }
internal static Type GetType(ClassLoaderWrapper loader, string name) { CompilerClassLoader ccl = (CompilerClassLoader)loader; return ccl.GetTypeFromReferencedAssembly(name); }
internal static Type GetTypeForMapXml(ClassLoaderWrapper loader, string name) { Type type = GetType(loader, name); if (type == null) { throw new FatalCompilerErrorException(Message.MapFileTypeNotFound, name); } return type; }
internal override void Apply(ClassLoaderWrapper loader, AssemblyBuilder ab, object annotation) { }
internal override void Apply(ClassLoaderWrapper loader, FieldBuilder fb, object annotation) { }
private static void SetParameters(ClassLoaderWrapper loader, ConstructorBuilder cb, IKVM.Internal.MapXml.Param[] parameters) { if(parameters != null) { for(int i = 0; i < parameters.Length; i++) { ParameterBuilder pb = cb.DefineParameter(i + 1, ParameterAttributes.None, parameters[i].Name); if(parameters[i].Attributes != null) { for(int j = 0; j < parameters[i].Attributes.Length; j++) { AttributeHelper.SetCustomAttribute(loader, pb, parameters[i].Attributes[j]); } } } } }
internal override void Apply(ClassLoaderWrapper loader, PropertyBuilder pb, object annotation) { }
internal static TypeWrapper GetClassForMapXml(ClassLoaderWrapper loader, string name) { TypeWrapper tw = loader.LoadClassByDottedNameFast(name); if (tw == null) { throw new FatalCompilerErrorException(Message.MapFileClassNotFound, name); } return tw; }
internal override void Apply(ClassLoaderWrapper loader, PropertyBuilder pb, object annotation) { Annotation annot = type.Annotation; foreach (object ann in UnwrapArray(annotation)) { annot.Apply(loader, pb, ann); } }
// HACK when we're compiling multiple targets with -sharedclassloader, each target will have its own CompilerClassLoader, // so we need to consider them equivalent (because they represent the same class loader). internal bool IsEquivalentTo(ClassLoaderWrapper other) { if (this == other) { return true; } CompilerClassLoader ccl = other as CompilerClassLoader; if (ccl != null && options.sharedclassloader != null && options.sharedclassloader.Contains(ccl)) { if (!internalsVisibleTo.Contains(ccl)) { AddInternalsVisibleToAttribute(ccl); } return true; } return false; }
private CustomAttributeBuilder MakeCustomAttributeBuilder(ClassLoaderWrapper loader, object annotation) { object[] arr = (object[])annotation; ConstructorInfo defCtor; ConstructorInfo singleOneArgCtor; object ctorArg = null; GetConstructors(type, out defCtor, out singleOneArgCtor); List<PropertyInfo> properties = new List<PropertyInfo>(); List<object> propertyValues = new List<object>(); List<FieldInfo> fields = new List<FieldInfo>(); List<object> fieldValues = new List<object>(); for (int i = 2; i < arr.Length; i += 2) { string name = (string)arr[i]; if (name == "value" && singleOneArgCtor != null) { ctorArg = ConvertValue(loader, singleOneArgCtor.GetParameters()[0].ParameterType, arr[i + 1]); } else { PropertyInfo pi = type.GetProperty(name, BindingFlags.Public | BindingFlags.Instance); if (pi != null) { properties.Add(pi); propertyValues.Add(ConvertValue(loader, pi.PropertyType, arr[i + 1])); } else { FieldInfo fi = type.GetField(name, BindingFlags.Public | BindingFlags.Instance); if (fi != null) { fields.Add(fi); fieldValues.Add(ConvertValue(loader, fi.FieldType, arr[i + 1])); } } } } if (ctorArg == null && defCtor == null) { // TODO required argument is missing } return new CustomAttributeBuilder(ctorArg == null ? defCtor : singleOneArgCtor, ctorArg == null ? new object[0] : new object[] { ctorArg }, properties.ToArray(), propertyValues.ToArray(), fields.ToArray(), fieldValues.ToArray()); }
internal ClassLoaderWrapper Enter(ClassLoaderWrapper loader) { Enter(([email protected])null); ClassLoaderWrapper prev = env.classLoader; env.classLoader = loader; return prev; }
internal override void Apply(ClassLoaderWrapper loader, TypeBuilder tb, object annotation) { if (type == JVM.Import(typeof(System.Runtime.InteropServices.StructLayoutAttribute)) && tb.BaseType != Types.Object) { // we have to handle this explicitly, because if we apply an illegal StructLayoutAttribute, // TypeBuilder.CreateType() will later on throw an exception. #if STATIC_COMPILER loader.IssueMessage(Message.IgnoredCustomAttribute, type.FullName, "Type '" + tb.FullName + "' does not extend cli.System.Object"); #else Tracer.Error(Tracer.Runtime, "StructLayoutAttribute cannot be applied to {0}, because it does not directly extend cli.System.Object", tb.FullName); #endif return; } if (type.IsSubclassOf(Types.SecurityAttribute)) { #if STATIC_COMPILER tb.__AddDeclarativeSecurity(MakeCustomAttributeBuilder(loader, annotation)); #elif STUB_GENERATOR #else SecurityAction action; PermissionSet permSet; if (MakeDeclSecurity(type, annotation, out action, out permSet)) { tb.AddDeclarativeSecurity(action, permSet); } #endif } else { tb.SetCustomAttribute(MakeCustomAttributeBuilder(loader, annotation)); } }
private unsafe static long LoadLibrary(string filename, ClassLoaderWrapper loader) { Tracer.Info(Tracer.Jni, "loadLibrary: {0}, class loader: {1}", filename, loader); lock(JniLock) { IntPtr p = ikvm_LoadLibrary(filename); if(p == IntPtr.Zero) { Tracer.Info(Tracer.Jni, "Library not found: {0}", filename); return 0; } try { foreach(IntPtr tmp in loader.GetNativeLibraries()) { if(tmp == p) { // the library was already loaded by the current class loader, // no need to do anything ikvm_FreeLibrary(p); Tracer.Warning(Tracer.Jni, "Library was already loaded: {0}", filename); return p.ToInt64(); } } if(nativeLibraries.Contains(p)) { string msg = string.Format("Native library {0} already loaded in another classloader", filename); Tracer.Error(Tracer.Jni, "UnsatisfiedLinkError: {0}", msg); throw new java.lang.UnsatisfiedLinkError(msg); } Tracer.Info(Tracer.Jni, "Library loaded: {0}, handle = 0x{1:X}", filename, p.ToInt64()); IntPtr onload = ikvm_GetProcAddress(p, "JNI_OnLoad", IntPtr.Size * 2); if(onload != IntPtr.Zero) { Tracer.Info(Tracer.Jni, "Calling JNI_OnLoad on: {0}", filename); JNI.Frame f = new JNI.Frame(); int version; ClassLoaderWrapper prevLoader = f.Enter(loader); try { // TODO on Whidbey we should be able to use Marshal.GetDelegateForFunctionPointer to call OnLoad version = ikvm_CallOnLoad(onload, JavaVM.pJavaVM, null); Tracer.Info(Tracer.Jni, "JNI_OnLoad returned: 0x{0:X8}", version); } finally { f.Leave(prevLoader); } if(!JNI.IsSupportedJniVersion(version)) { string msg = string.Format("Unsupported JNI version 0x{0:X} required by {1}", version, filename); Tracer.Error(Tracer.Jni, "UnsatisfiedLinkError: {0}", msg); throw new java.lang.UnsatisfiedLinkError(msg); } } nativeLibraries.Add(p); loader.RegisterNativeLibrary(p); return p.ToInt64(); } catch { ikvm_FreeLibrary(p); throw; } } }
internal override void Apply(ClassLoaderWrapper loader, MethodBuilder mb, object annotation) { if (type.IsSubclassOf(Types.SecurityAttribute)) { #if STATIC_COMPILER mb.__AddDeclarativeSecurity(MakeCustomAttributeBuilder(loader, annotation)); #elif STUB_GENERATOR #else SecurityAction action; PermissionSet permSet; if (MakeDeclSecurity(type, annotation, out action, out permSet)) { mb.AddDeclarativeSecurity(action, permSet); } #endif } else { mb.SetCustomAttribute(MakeCustomAttributeBuilder(loader, annotation)); } }
internal override void ApplyReturnValue(ClassLoaderWrapper loader, MethodBuilder mb, ref ParameterBuilder pb, object annotation) { // TODO make sure the descriptor is correct Annotation ann = type.Annotation; object[] arr = (object[])annotation; for (int i = 2; i < arr.Length; i += 2) { if ("value".Equals(arr[i])) { if (pb == null) { pb = mb.DefineParameter(0, ParameterAttributes.None, null); } object[] value = (object[])arr[i + 1]; if (value[0].Equals(AnnotationDefaultAttribute.TAG_ANNOTATION)) { ann.Apply(loader, pb, value); } else { for (int j = 1; j < value.Length; j++) { ann.Apply(loader, pb, value[j]); } } break; } } }
internal override void Apply(ClassLoaderWrapper loader, ParameterBuilder pb, object annotation) { if (type.IsSubclassOf(Types.SecurityAttribute)) { // you can't add declarative security to a parameter } else if (type == JVM.Import(typeof(System.Runtime.InteropServices.DefaultParameterValueAttribute))) { // TODO with the current custom attribute annotation restrictions it is impossible to use this CA, // but if we make it possible, we should also implement it here throw new NotImplementedException(); } else { pb.SetCustomAttribute(MakeCustomAttributeBuilder(loader, annotation)); } }
private static void CreateEnumEnum(ModuleBuilder modb, ClassLoaderWrapper loader) { TypeBuilder tb = modb.DefineType(DotNetTypeWrapper.GenericEnumEnumTypeName, TypeAttributes.Class | TypeAttributes.Sealed | TypeAttributes.Public); GenericTypeParameterBuilder gtpb = tb.DefineGenericParameters("T")[0]; gtpb.SetBaseTypeConstraint(Types.Enum); genericEnumEnumType = tb; }
internal override void Apply(ClassLoaderWrapper loader, MethodBuilder mb, object annotation) { }