Example #1
0
 internal static bool Emit(DynamicTypeWrapper.FinishContext context, TypeWrapper wrapper, CodeEmitter ilgen, ClassFile classFile, int i, ClassFile.Method.Instruction[] code, InstructionFlags[] flags)
 {
     if (i >= 3
         && (flags[i - 0] & InstructionFlags.BranchTarget) == 0
         && (flags[i - 1] & InstructionFlags.BranchTarget) == 0
         && (flags[i - 2] & InstructionFlags.BranchTarget) == 0
         && (flags[i - 3] & InstructionFlags.BranchTarget) == 0
         && code[i - 1].NormalizedOpCode == NormalizedByteCode.__ldc
         && code[i - 2].NormalizedOpCode == NormalizedByteCode.__ldc
         && code[i - 3].NormalizedOpCode == NormalizedByteCode.__ldc)
     {
         // we now have a structural match, now we need to make sure that the argument values are what we expect
         TypeWrapper tclass = classFile.GetConstantPoolClassType(code[i - 3].Arg1);
         TypeWrapper vclass = classFile.GetConstantPoolClassType(code[i - 2].Arg1);
         string fieldName = classFile.GetConstantPoolConstantString(code[i - 1].Arg1);
         if (tclass == wrapper && !vclass.IsUnloadable && !vclass.IsPrimitive && !vclass.IsNonPrimitiveValueType)
         {
             FieldWrapper field = wrapper.GetFieldWrapper(fieldName, vclass.SigName);
             if (field != null && !field.IsStatic && field.IsVolatile && field.DeclaringType == wrapper && field.FieldTypeWrapper == vclass)
             {
                 // everything matches up, now call the actual emitter
                 DoEmit(context, wrapper, ilgen, field);
                 return true;
             }
         }
     }
     return false;
 }
        private IList<Test> GetFixtures(Assembly assembly, IList names)
        {
            var fixtures = new List<Test>();
            var testTypes = GetCandidateFixtureTypes(assembly, names);
            int testcases = 0;
            foreach (Type testType in testTypes)
            {
                var typeInfo = new TypeWrapper(testType);

                try
                {
                    if (_unitySuiteBuilder.CanBuildFrom(typeInfo))
                    {
                        Test fixture = _unitySuiteBuilder.BuildFrom(typeInfo);
                        fixtures.Add(fixture);
                        testcases += fixture.TestCaseCount;
                    }
                }
                catch (Exception ex)
                {
                    Debug.LogException(ex);
                }
            }


            return fixtures;
        }
Example #3
0
        internal static bool IsEnabled(TypeWrapper tw)
        {
            string className = tw.Name;

            // match class name
            for (OptionNode n = classes; n != null; n = n.next)
            {
                if (n.name == className)
                {
                    return n.enabled;
                }
            }

            // match package name
            if (packages != null)
            {
                int len = className.Length;
                while (len > 0 && className[--len] != '.') ;

                do
                {
                    for (OptionNode n = packages; n != null; n = n.next)
                    {
                        if (String.Compare(n.name, 0, className, 0, len, false, CultureInfo.InvariantCulture) == 0 && len == n.name.Length)
                        {
                            return n.enabled;
                        }
                    }
                    while (len > 0 && className[--len] != '.') ;
                } while (len > 0);
            }

            return tw.GetClassLoader() == ClassLoaderWrapper.GetBootstrapClassLoader() ? sysAsserts : userAsserts;
        }
Example #4
0
		internal static ConstructorInfo AddAutomagicSerialization(TypeWrapper wrapper)
		{
			ConstructorInfo serializationCtor = null;
			if (wrapper.GetClassLoader().NoAutomagicSerialization)
			{
				// do nothing
			}
			else if ((wrapper.Modifiers & IKVM.Attributes.Modifiers.Enum) != 0)
			{
				MarkSerializable(wrapper);
			}
			else if (wrapper.IsSubTypeOf(serializable) && IsSafeForAutomagicSerialization(wrapper))
			{
				if (wrapper.IsSubTypeOf(externalizable))
				{
					MethodWrapper ctor = wrapper.GetMethodWrapper("<init>", "()V", false);
					if (ctor != null && ctor.IsPublic)
					{
						MarkSerializable(wrapper);
						ctor.Link();
						serializationCtor = AddConstructor(wrapper.TypeAsBuilder, ctor, null, true);
						if (!wrapper.BaseTypeWrapper.IsSubTypeOf(serializable))
						{
							AddGetObjectData(wrapper);
						}
						if (wrapper.BaseTypeWrapper.GetMethodWrapper("readResolve", "()Ljava.lang.Object;", true) != null)
						{
							RemoveReadResolve(wrapper);
						}
					}
				}
				else if (wrapper.BaseTypeWrapper.IsSubTypeOf(serializable))
				{
					ConstructorInfo baseCtor = wrapper.GetBaseSerializationConstructor();
					if (baseCtor != null && (baseCtor.IsFamily || baseCtor.IsFamilyOrAssembly))
					{
						MarkSerializable(wrapper);
						serializationCtor = AddConstructor(wrapper.TypeAsBuilder, null, baseCtor, false);
						AddReadResolve(wrapper);
					}
				}
				else
				{
					MethodWrapper baseCtor = wrapper.BaseTypeWrapper.GetMethodWrapper("<init>", "()V", false);
					if (baseCtor != null && baseCtor.IsAccessibleFrom(wrapper.BaseTypeWrapper, wrapper, wrapper))
					{
						MarkSerializable(wrapper);
						AddGetObjectData(wrapper);
#if STATIC_COMPILER
						// because the base type can be a __WorkaroundBaseClass__, we may need to replace the constructor
						baseCtor = ((AotTypeWrapper)wrapper).ReplaceMethodWrapper(baseCtor);
#endif
						baseCtor.Link();
						serializationCtor = AddConstructor(wrapper.TypeAsBuilder, baseCtor, null, true);
						AddReadResolve(wrapper);
					}
				}
			}
			return serializationCtor;
		}
Example #5
0
		static ProxyGenerator()
		{
			ClassLoaderWrapper bootClassLoader = ClassLoaderWrapper.GetBootstrapClassLoader();
			proxyClass = bootClassLoader.LoadClassByDottedNameFast("java.lang.reflect.Proxy");
			errorClass = bootClassLoader.LoadClassByDottedNameFast("java.lang.Error");
			runtimeExceptionClass = bootClassLoader.LoadClassByDottedNameFast("java.lang.RuntimeException");
			undeclaredThrowableExceptionConstructor = bootClassLoader.LoadClassByDottedNameFast("java.lang.reflect.UndeclaredThrowableException").GetMethodWrapper("<init>", "(Ljava.lang.Throwable;)V", false);
			undeclaredThrowableExceptionConstructor.Link();
			invocationHandlerField = proxyClass.GetFieldWrapper("h", "Ljava.lang.reflect.InvocationHandler;");
			invocationHandlerField.Link();
			javaLangReflectMethod = bootClassLoader.LoadClassByDottedNameFast("java.lang.reflect.Method");
			javaLangNoSuchMethodException = bootClassLoader.LoadClassByDottedNameFast("java.lang.NoSuchMethodException");
			javaLangNoClassDefFoundErrorConstructor = bootClassLoader.LoadClassByDottedNameFast("java.lang.NoClassDefFoundError").GetMethodWrapper("<init>", "(Ljava.lang.String;)V", false);
			javaLangNoClassDefFoundErrorConstructor.Link();
			javaLangThrowable_getMessage = bootClassLoader.LoadClassByDottedNameFast("java.lang.Throwable").GetMethodWrapper("getMessage", "()Ljava.lang.String;", false);
			javaLangThrowable_getMessage.Link();
			javaLangClass_getMethod = CoreClasses.java.lang.Class.Wrapper.GetMethodWrapper("getMethod", "(Ljava.lang.String;[Ljava.lang.Class;)Ljava.lang.reflect.Method;", false);
			javaLangClass_getMethod.Link();
			invocationHandlerClass = bootClassLoader.LoadClassByDottedNameFast("java.lang.reflect.InvocationHandler");
			invokeMethod = invocationHandlerClass.GetMethodWrapper("invoke", "(Ljava.lang.Object;Ljava.lang.reflect.Method;[Ljava.lang.Object;)Ljava.lang.Object;", false);
			proxyConstructor = proxyClass.GetMethodWrapper("<init>", "(Ljava.lang.reflect.InvocationHandler;)V", false);
			proxyConstructor.Link();
			hashCodeMethod = CoreClasses.java.lang.Object.Wrapper.GetMethodWrapper("hashCode", "()I", false);
			equalsMethod = CoreClasses.java.lang.Object.Wrapper.GetMethodWrapper("equals", "(Ljava.lang.Object;)Z", false);
			toStringMethod = CoreClasses.java.lang.Object.Wrapper.GetMethodWrapper("toString", "()Ljava.lang.String;", false);
		}
Example #6
0
File: Meta.cs Project: vc3/ExoWeb
 internal Meta(ScriptEngine engine, ModelInstance instance)
     : base(engine, engine.Object.InstancePrototype)
 {
     this.PopulateFunctions();
     this.instance = instance;
     this.typeWrapper = new TypeWrapper(engine, instance.Type);
 }
		private static bool HasJavaMethods(TypeWrapper tw)
		{
			foreach (MethodWrapper mw in tw.GetMethods())
			{
				if (!mw.IsHideFromReflection && !mw.IsClassInitializer)
				{
					return true;
				}
			}
			return false;
		}
Example #8
0
        public void WriteTypeName(TypeWrapper type)
        {
            if (this._builder.Length > 0)
                this._builder.Append(" ");

            string typeName = type.GetDisplayName(false);
            if (typeName == "Void")
                typeName = "void";

            WriteValue(typeName);
        }
		private static bool HasJavaMethods(TypeWrapper tw)
		{
			foreach (MethodWrapper mw in tw.GetMethods())
			{
				if (!mw.IsHideFromReflection && mw.Name != StringConstants.CLINIT)
				{
					return true;
				}
			}
			return false;
		}
        public string GenerateSyntax(TypeWrapper type)
        {
            var syntax = new SyntaxWriter(this._version);

            if (type.IsPublic)
                syntax.WriteToken("public");

            if (type.IsEnum)
            {
                syntax.WriteToken("enum");
                syntax.WriteTypeName(type);
            }
            else
            {
                if (type.IsSealed)
                    syntax.WriteToken("sealed");
                if (type.IsAbstract)
                    syntax.WriteToken("abstract");
                if (type.IsStatic)
                    syntax.WriteToken("static");

                if (type.IsClass)
                    syntax.WriteToken("class");
                else if (type.IsInterface)
                    syntax.WriteToken("interface");
                else if (type.IsValueType)
                    syntax.WriteToken("struct");

                syntax.WriteTypeName(type);

                var baseType = type.BaseType;
                if (baseType != null)
                {
                    syntax.WriteRaw(" :");
                    syntax.WriteTypeName(baseType);
                }

                var interfaces = type.GetInterfaces();
                if (interfaces.Count > 0)
                {
                    syntax.WriteNewLineWithTab();

                    syntax.BeginCommaDelimitedList();
                    foreach (var face in interfaces.OrderBy(x => x.Name))
                    {
                        syntax.WriteTypeName(face);
                    }
                    syntax.EndCommaDelimitedList();
                }
            }

            return syntax.CurrentSyntax;
        }
		private static void WriteModifiers(BigEndianStream bes, TypeWrapper tw)
		{
			Modifiers mods = tw.ReflectiveModifiers & (Modifiers.Public | Modifiers.Final | Modifiers.Interface | Modifiers.Abstract);
			if ((mods & Modifiers.Interface) != 0)
			{
				mods &= ~Modifiers.Abstract;
				if (HasJavaMethods(tw))
				{
					mods |= Modifiers.Abstract;
				}
			}
			bes.WriteUInt32((uint)mods);
		}
 public void Test_ToStringShouldReturnTypeToString()
 {
     //---------------Set up test pack-------------------
     var type = MockRepository.GenerateMock<Type>();
     var expectedToString = GetRandomString();
     type.Stub(type1 => type1.ToString()).Return(expectedToString);
     TypeWrapper wrapper = new TypeWrapper(type);
     //---------------Assert Precondition----------------
     Assert.AreEqual(expectedToString, type.ToString());
     //---------------Execute Test ----------------------
     var toString = wrapper.ToString();
     //---------------Test Result -----------------------
     Assert.AreEqual(expectedToString, toString);
 }
Example #13
0
 static Boxer()
 {
     ClassLoaderWrapper bootClassLoader = ClassLoaderWrapper.GetBootstrapClassLoader();
     javaLangByte = bootClassLoader.LoadClassByDottedNameFast("java.lang.Byte");
     byteValue = javaLangByte.GetMethodWrapper("byteValue", "()B", false);
     byteValue.Link();
     valueOfByte = javaLangByte.GetMethodWrapper("valueOf", "(B)Ljava.lang.Byte;", false);
     valueOfByte.Link();
     javaLangBoolean = bootClassLoader.LoadClassByDottedNameFast("java.lang.Boolean");
     booleanValue = javaLangBoolean.GetMethodWrapper("booleanValue", "()Z", false);
     booleanValue.Link();
     valueOfBoolean = javaLangBoolean.GetMethodWrapper("valueOf", "(Z)Ljava.lang.Boolean;", false);
     valueOfBoolean.Link();
     javaLangShort = bootClassLoader.LoadClassByDottedNameFast("java.lang.Short");
     shortValue = javaLangShort.GetMethodWrapper("shortValue", "()S", false);
     shortValue.Link();
     valueOfShort = javaLangShort.GetMethodWrapper("valueOf", "(S)Ljava.lang.Short;", false);
     valueOfShort.Link();
     javaLangCharacter = bootClassLoader.LoadClassByDottedNameFast("java.lang.Character");
     charValue = javaLangCharacter.GetMethodWrapper("charValue", "()C", false);
     charValue.Link();
     valueOfCharacter = javaLangCharacter.GetMethodWrapper("valueOf", "(C)Ljava.lang.Character;", false);
     valueOfCharacter.Link();
     javaLangInteger = bootClassLoader.LoadClassByDottedNameFast("java.lang.Integer");
     intValue = javaLangInteger.GetMethodWrapper("intValue", "()I", false);
     intValue.Link();
     valueOfInteger = javaLangInteger.GetMethodWrapper("valueOf", "(I)Ljava.lang.Integer;", false);
     valueOfInteger.Link();
     javaLangFloat = bootClassLoader.LoadClassByDottedNameFast("java.lang.Float");
     floatValue = javaLangFloat.GetMethodWrapper("floatValue", "()F", false);
     floatValue.Link();
     valueOfFloat = javaLangFloat.GetMethodWrapper("valueOf", "(F)Ljava.lang.Float;", false);
     valueOfFloat.Link();
     javaLangLong = bootClassLoader.LoadClassByDottedNameFast("java.lang.Long");
     longValue = javaLangLong.GetMethodWrapper("longValue", "()J", false);
     longValue.Link();
     valueOfLong = javaLangLong.GetMethodWrapper("valueOf", "(J)Ljava.lang.Long;", false);
     valueOfLong.Link();
     javaLangDouble = bootClassLoader.LoadClassByDottedNameFast("java.lang.Double");
     doubleValue = javaLangDouble.GetMethodWrapper("doubleValue", "()D", false);
     doubleValue.Link();
     valueOfDouble = javaLangDouble.GetMethodWrapper("valueOf", "(D)Ljava.lang.Double;", false);
     valueOfDouble.Link();
 }
		internal static long Compute(TypeWrapper tw)
		{
			MemoryStream mem = new MemoryStream();
			BigEndianStream bes = new BigEndianStream(mem);
			WriteClassName(bes, tw);
			WriteModifiers(bes, tw);
			WriteInterfaces(bes, tw);
			WriteFields(bes, tw);
			WriteStaticInitializer(bes, tw);
			WriteConstructors(bes, tw);
			WriteMethods(bes, tw);
			byte[] buf = sha1.ComputeHash(mem.ToArray());
			long hash = 0;
			for (int i = 7; i >= 0; i--)
			{
				hash <<= 8;
				hash |= buf[i];
			}
			return hash;
		}
Example #15
0
		internal static void Create(CompilerClassLoader loader, string proxy)
		{
			string[] interfaces = proxy.Split(',');
			TypeWrapper[] wrappers = new TypeWrapper[interfaces.Length];
			for (int i = 0; i < interfaces.Length; i++)
			{
				try
				{
					wrappers[i] = loader.LoadClassByDottedNameFast(interfaces[i]);
				}
				catch (RetargetableJavaException)
				{
				}
				if (wrappers[i] == null)
				{
					StaticCompiler.IssueMessage(Message.UnableToCreateProxy, proxy, "unable to load interface " + interfaces[i]);
					return;
				}
			}
			Create(loader, proxy, wrappers);
		}
Example #16
0
	private static void DoEmit(DynamicTypeWrapper.FinishContext context, TypeWrapper wrapper, CodeEmitter ilgen, FieldWrapper field)
	{
		ConstructorBuilder cb;
		bool exists;
		lock (map)
		{
			exists = map.TryGetValue(field, out cb);
		}
		if (!exists)
		{
			// note that we don't need to lock here, because we're running as part of FinishCore, which is already protected by a lock
			TypeWrapper arfuTypeWrapper = ClassLoaderWrapper.LoadClassCritical("ikvm.internal.IntrinsicAtomicReferenceFieldUpdater");
			TypeBuilder tb = wrapper.TypeAsBuilder.DefineNestedType("__<ARFU>_" + field.Name + field.Signature.Replace('.', '/'), TypeAttributes.NestedPrivate | TypeAttributes.Sealed, arfuTypeWrapper.TypeAsBaseType);
			EmitCompareAndSet("compareAndSet", tb, field.GetField());
			EmitGet(tb, field.GetField());
			EmitSet("set", tb, field.GetField());

			cb = tb.DefineConstructor(MethodAttributes.Assembly, CallingConventions.Standard, Type.EmptyTypes);
			lock (map)
			{
				map.Add(field, cb);
			}
			CodeEmitter ctorilgen = CodeEmitter.Create(cb);
			ctorilgen.Emit(OpCodes.Ldarg_0);
			MethodWrapper basector = arfuTypeWrapper.GetMethodWrapper("<init>", "()V", false);
			basector.Link();
			basector.EmitCall(ctorilgen);
			ctorilgen.Emit(OpCodes.Ret);
			context.RegisterPostFinishProc(delegate
			{
				arfuTypeWrapper.Finish();
				tb.CreateType();
			});
		}
		ilgen.LazyEmitPop();
		ilgen.LazyEmitPop();
		ilgen.LazyEmitPop();
		ilgen.Emit(OpCodes.Newobj, cb);
	}
 public static IAsymmetricCipherKeyPairGenerator CreateGenerator(SecureRandom random, TypeWrapper kpGen,
                                                                 int keystrength)
 {
     var keypairGen = kpGen.Instance<IAsymmetricCipherKeyPairGenerator>();
     //var random = SecureRandomUtils.GetInstance(Model.RandomGenerator, Model.RandomGeneratorArgument);
     if (keypairGen is DsaKeyPairGenerator)
     {
         DsaParametersGenerator pGen = new DsaParametersGenerator();
         pGen.Init(keystrength, 80, random); //TODO:
         DsaParameters parameters = pGen.GenerateParameters();
         DsaKeyGenerationParameters genParam = new DsaKeyGenerationParameters(random, parameters);
         keypairGen.Init(genParam);
         return keypairGen;
     }
     if (keypairGen is ECKeyPairGenerator)
     {
         keypairGen.Init(new KeyGenerationParameters(random, keystrength));
         return keypairGen;
     }
     keypairGen.Init(new KeyGenerationParameters(random, keystrength));
     return keypairGen;
 }
Example #18
0
		private static bool IsSafeForAutomagicSerialization(TypeWrapper wrapper)
		{
			if (wrapper.TypeAsBaseType.IsSerializable)
			{
				return false;
			}
			if (wrapper.IsSubTypeOf(iserializable))
			{
				return false;
			}
			if (wrapper.IsSubTypeOf(iobjectreference))
			{
				return false;
			}
			if (wrapper.GetMethodWrapper("GetObjectData", "(Lcli.System.Runtime.Serialization.SerializationInfo;Lcli.System.Runtime.Serialization.StreamingContext;)V", false) != null)
			{
				return false;
			}
			if (wrapper.GetMethodWrapper("<init>", "(Lcli.System.Runtime.Serialization.SerializationInfo;Lcli.System.Runtime.Serialization.StreamingContext;)V", false) != null)
			{
				return false;
			}
			return true;
		}
Example #19
0
 public static string getSigName(java.lang.Class thisClass)
 {
     return(TypeWrapper.FromClass(thisClass).SigName);
 }
Example #20
0
    public static java.lang.Class getSuperclass(java.lang.Class thisClass)
    {
        TypeWrapper super = TypeWrapper.FromClass(thisClass).BaseTypeWrapper;

        return(super != null ? super.ClassObject : null);
    }
Example #21
0
 public static bool desiredAssertionStatus0(java.lang.Class clazz)
 {
     return(IKVM.Runtime.Assertions.IsEnabled(TypeWrapper.FromClass(clazz)));
 }
Example #22
0
        internal static string TypeNameMangleImpl(Dictionary <string, TypeWrapper> dict, string name, TypeWrapper tw)
        {
            // the CLR maximum type name length is 1023 characters,
            // but we need to leave some room for the suffix that we
            // may need to append to make the name unique
            const int MaxLength = 1000;

            if (name.Length > MaxLength)
            {
                name = name.Substring(0, MaxLength) + "/truncated";
            }
            string mangledTypeName = TypeNameUtil.ReplaceIllegalCharacters(name);

            // FXBUG the CLR (both 1.1 and 2.0) doesn't like type names that end with a single period,
            // it loses the trailing period in the name that gets passed in the TypeResolve event.
            if (dict.ContainsKey(mangledTypeName) || mangledTypeName.EndsWith("."))
            {
#if STATIC_COMPILER
                Tracer.Warning(Tracer.Compiler, "Class name clash: {0}", mangledTypeName);
#endif
                // Java class names cannot contain slashes (since they are converted into periods),
                // so we take advantage of that fact to create a unique name.
                string baseName   = mangledTypeName;
                int    instanceId = 0;
                do
                {
                    mangledTypeName = baseName + "/" + (++instanceId);
                } while (dict.ContainsKey(mangledTypeName));
            }
            dict.Add(mangledTypeName, tw);
            return(mangledTypeName);
        }
 public bool TryGetType(string key, out TypeWrapper typeWrapper)
 {
     return(this.typeDictionary.TryGetValue(key, out typeWrapper));
 }
Example #24
0
        internal static Delegate CreateMemberName(MethodWrapper mw, MethodType type, bool doDispatch)
        {
            FinishTypes(type);
            TypeWrapper tw    = mw.DeclaringType;
            Type        owner = tw.TypeAsBaseType;

#if NET_4_0
            if (!doDispatch && !mw.IsStatic)
            {
                // on .NET 4 we can only do a non-virtual invocation of a virtual method if we skip verification,
                // and to skip verification we need to inject the dynamic method in a critical assembly

                // TODO instead of injecting in mscorlib, we should use DynamicMethodUtils.Create()
                owner = typeof(object);
            }
#endif
            DynamicMethodBuilder dm = new DynamicMethodBuilder("MemberName:" + mw.DeclaringType.Name + "::" + mw.Name + mw.Signature, type, null,
                                                               mw.HasCallerID ? DynamicCallerIDProvider.Instance : null, null, owner, true);
            for (int i = 0, count = type.parameterCount(); i < count; i++)
            {
                if (i == 0 && !mw.IsStatic && (tw.IsGhost || tw.IsNonPrimitiveValueType || tw.IsRemapped) && (!mw.IsConstructor || tw != CoreClasses.java.lang.String.Wrapper))
                {
                    if (tw.IsGhost || tw.IsNonPrimitiveValueType)
                    {
                        dm.LoadFirstArgAddress(tw);
                    }
                    else
                    {
                        Debug.Assert(tw.IsRemapped);
                        // TODO this must be checked
                        dm.Ldarg(0);
                        if (mw.IsConstructor)
                        {
                            dm.EmitCastclass(tw.TypeAsBaseType);
                        }
                        else if (tw != CoreClasses.cli.System.Object.Wrapper)
                        {
                            dm.EmitCheckcast(tw);
                        }
                    }
                }
                else
                {
                    dm.Ldarg(i);
                    TypeWrapper argType = TypeWrapper.FromClass(type.parameterType(i));
                    if (!argType.IsPrimitive)
                    {
                        if (argType.IsUnloadable)
                        {
                        }
                        else if (argType.IsNonPrimitiveValueType)
                        {
                            dm.Unbox(argType);
                        }
                        else if (argType.IsGhost)
                        {
                            dm.UnboxGhost(argType);
                        }
                        else
                        {
                            dm.EmitCheckcast(argType);
                        }
                    }
                }
            }
            if (mw.HasCallerID)
            {
                dm.LoadCallerID();
            }
            // special case for Object.clone() and Object.finalize()
            if (mw.IsFinalizeOrClone)
            {
                if (doDispatch)
                {
                    mw.EmitCallvirtReflect(dm.ilgen);
                }
                else
                {
                    // we can re-use the implementations from cli.System.Object (even though the object may not in-fact extend cli.System.Object)
                    CoreClasses.cli.System.Object.Wrapper.GetMethodWrapper(mw.Name, mw.Signature, false).EmitCall(dm.ilgen);
                }
            }
            else if (doDispatch && !mw.IsStatic)
            {
                dm.Callvirt(mw);
            }
            else
            {
                dm.Call(mw);
            }
            TypeWrapper retType = TypeWrapper.FromClass(type.returnType());
            if (retType.IsUnloadable)
            {
            }
            else if (retType.IsNonPrimitiveValueType)
            {
                dm.Box(retType);
            }
            else if (retType.IsGhost)
            {
                dm.BoxGhost(retType);
            }
            else if (retType == PrimitiveTypeWrapper.BYTE)
            {
                dm.CastByte();
            }
            dm.Ret();
            return(dm.CreateDelegate());
        }
		internal static void EmitThrowNoSuchMethodErrorForGetter(CodeEmitter ilgen, TypeWrapper type, bool isStatic)
		{
			// HACK the branch around the throw is to keep the verifier happy
			CodeEmitterLabel label = ilgen.DefineLabel();
			ilgen.Emit(OpCodes.Ldc_I4_0);
			ilgen.Emit(OpCodes.Brtrue_S, label);
			ilgen.EmitThrow("java.lang.NoSuchMethodError");
			ilgen.MarkLabel(label);
			if (!isStatic)
			{
				ilgen.Emit(OpCodes.Pop);
			}
			ilgen.Emit(OpCodes.Ldloc, ilgen.DeclareLocal(type.TypeAsLocalOrStackType));
		}
Example #26
0
 internal void EmitCheckcast(TypeWrapper tw)
 {
     tw.EmitCheckcast(ilgen);
 }
Example #27
0
    private static void ResolveMethod(MemberName self, java.lang.Class caller)
    {
        bool          invokeSpecial     = self.getReferenceKind() == MethodHandleNatives.Constants.REF_invokeSpecial;
        bool          newInvokeSpecial  = self.getReferenceKind() == MethodHandleNatives.Constants.REF_newInvokeSpecial;
        bool          searchBaseClasses = !newInvokeSpecial;
        MethodWrapper mw = TypeWrapper.FromClass(self.getDeclaringClass()).GetMethodWrapper(self.getName(), self.getSignature().Replace('/', '.'), searchBaseClasses);

        if (mw == null)
        {
            if (self.getReferenceKind() == MethodHandleNatives.Constants.REF_invokeInterface)
            {
                mw = TypeWrapper.FromClass(self.getDeclaringClass()).GetInterfaceMethod(self.getName(), self.getSignature().Replace('/', '.'));
                if (mw == null)
                {
                    mw = CoreClasses.java.lang.Object.Wrapper.GetMethodWrapper(self.getName(), self.getSignature().Replace('/', '.'), false);
                }
                if (mw != null && mw.IsConstructor)
                {
                    throw new java.lang.IncompatibleClassChangeError("Found interface " + self.getDeclaringClass().getName() + ", but class was expected");
                }
            }
            if (mw == null)
            {
                string msg = String.Format(invokeSpecial ? "{0}: method {1}{2} not found" : "{0}.{1}{2}", self.getDeclaringClass().getName(), self.getName(), self.getSignature());
                throw new java.lang.NoSuchMethodError(msg);
            }
        }
        if (mw.IsStatic != IsReferenceKindStatic(self.getReferenceKind()))
        {
            string msg = String.Format(mw.IsStatic ? "Expecting non-static method {0}.{1}{2}" : "Expected static method {0}.{1}{2}", mw.DeclaringType.Name, self.getName(), self.getSignature());
            throw new java.lang.IncompatibleClassChangeError(msg);
        }
        if (self.getReferenceKind() == MethodHandleNatives.Constants.REF_invokeVirtual && mw.DeclaringType.IsInterface)
        {
            throw new java.lang.IncompatibleClassChangeError("Found interface " + mw.DeclaringType.Name + ", but class was expected");
        }
        if (!mw.IsPublic && self.getReferenceKind() == MethodHandleNatives.Constants.REF_invokeInterface)
        {
            throw new java.lang.IncompatibleClassChangeError("private interface method requires invokespecial, not invokeinterface: method " + self.getDeclaringClass().getName() + "." + self.getName() + self.getSignature());
        }
        if (mw.IsConstructor && mw.DeclaringType == CoreClasses.java.lang.String.Wrapper)
        {
            self.vmtarget = CreateMemberNameDelegate(mw, caller, false, self.getMethodType().changeReturnType(CoreClasses.java.lang.String.Wrapper.ClassObject));
        }
        else if (!mw.IsConstructor || invokeSpecial || newInvokeSpecial)
        {
            MethodType methodType = self.getMethodType();
            if (!mw.IsStatic)
            {
                methodType = methodType.insertParameterTypes(0, mw.DeclaringType.ClassObject);
                if (newInvokeSpecial)
                {
                    methodType = methodType.changeReturnType(java.lang.Void.TYPE);
                }
            }
            self.vmtarget = CreateMemberNameDelegate(mw, caller, self.hasReceiverTypeDispatch(), methodType);
        }
        SetModifiers(self, mw);
        self._flags(self._flags() | (mw.IsConstructor ? MethodHandleNatives.Constants.MN_IS_CONSTRUCTOR : MethodHandleNatives.Constants.MN_IS_METHOD));
        if (self.getReferenceKind() == MethodHandleNatives.Constants.REF_invokeVirtual && (mw.IsPrivate || mw.IsFinal || mw.IsConstructor))
        {
            int flags = self._flags();
            flags -= MethodHandleNatives.Constants.REF_invokeVirtual << MethodHandleNatives.Constants.MN_REFERENCE_KIND_SHIFT;
            flags += MethodHandleNatives.Constants.REF_invokeSpecial << MethodHandleNatives.Constants.MN_REFERENCE_KIND_SHIFT;
            self._flags(flags);
        }
        if (mw.HasCallerID || DynamicTypeWrapper.RequiresDynamicReflectionCallerClass(mw.DeclaringType.Name, mw.Name, mw.Signature))
        {
            self._flags(self._flags() | MemberName.CALLER_SENSITIVE);
        }
    }
Example #28
0
 internal void BoxGhost(TypeWrapper tw)
 {
     tw.EmitConvSignatureTypeToStackType(ilgen);
 }
Example #29
0
 internal void UnboxGhost(TypeWrapper tw)
 {
     tw.EmitConvStackTypeToSignatureType(ilgen, null);
 }
Example #30
0
 internal void Box(TypeWrapper tw)
 {
     tw.EmitBox(ilgen);
 }
Example #31
0
 internal void Unbox(TypeWrapper tw)
 {
     tw.EmitUnbox(ilgen);
 }
		internal CompiledPropertyFieldWrapper(TypeWrapper declaringType, PropertyInfo property, ExModifiers modifiers)
			: base(declaringType, ClassLoaderWrapper.GetWrapperFromType(property.PropertyType), property.Name, ClassLoaderWrapper.GetWrapperFromType(property.PropertyType).SigName, modifiers, null)
		{
			this.property = property;
		}
Example #33
0
        internal sealed override TypeWrapper DefineClassImpl(Dictionary <string, TypeWrapper> types, TypeWrapper host, ClassFile f, ClassLoaderWrapper classLoader, ProtectionDomain protectionDomain)
        {
#if STATIC_COMPILER
            AotTypeWrapper type = new AotTypeWrapper(f, (CompilerClassLoader)classLoader);
            type.CreateStep1();
            types[f.Name] = type;
            return(type);
#elif FIRST_PASS
            return(null);
#else
            // this step can throw a retargettable exception, if the class is incorrect
            DynamicTypeWrapper type = new DynamicTypeWrapper(host, f, classLoader, protectionDomain);
            // This step actually creates the TypeBuilder. It is not allowed to throw any exceptions,
            // if an exception does occur, it is due to a programming error in the IKVM or CLR runtime
            // and will cause a CriticalFailure and exit the process.
            type.CreateStep1();
            type.CreateStep2();
            if (types == null)
            {
                // we're defining an anonymous class, so we don't need any locking
                TieClassAndWrapper(type, protectionDomain);
                return(type);
            }
            lock (types)
            {
                // in very extreme conditions another thread may have beaten us to it
                // and loaded (not defined) a class with the same name, in that case
                // we'll leak the the Reflection.Emit defined type. Also see the comment
                // in ClassLoaderWrapper.RegisterInitiatingLoader().
                TypeWrapper race;
                types.TryGetValue(f.Name, out race);
                if (race == null)
                {
                    types[f.Name] = type;
                    TieClassAndWrapper(type, protectionDomain);
                }
                else
                {
                    throw new LinkageError("duplicate class definition: " + f.Name);
                }
            }
            return(type);
#endif // STATIC_COMPILER
        }
		// constructor for type 1 access stubs
		internal CompiledAccessStubFieldWrapper(TypeWrapper wrapper, PropertyInfo property, TypeWrapper propertyType)
			: this(wrapper, property, null, propertyType, GetModifiers(property), MemberFlags.HideFromReflection | MemberFlags.AccessStub)
		{
		}
Example #35
0
        private void SerializeValue(IDataAdapter data, object target)
        {
            objectsCache.Add(target, maxObjId++);
            TypeWrapper wrapper = TypeCache.GetWrapper(target.GetType());

            if (wrapper.TrySerialize(target, data, this))
            {
                return;
            }

            for (int i = 0; i < wrapper.Properties.Count; i++)
            {
                PropertyWrapper property = wrapper.Properties[i];

                if (property.IsPrivate)
                {
                    if (!settings.SerializePrivateProperties)
                    {
                        continue;
                    }

                    havePrivateProperties = true;
                }

                bool isReadOnly;
                if (property.ConstructorArg != -1 || // will be used in constructor
                    settings.SerializeReadOnly)
                {
                    isReadOnly = false; // always serialize
                }
                else
                {
                    isReadOnly = !property.CanWrite;
                }

                object value = property.GetValue(target);
                if (value != null)
                {
                    SerializeValue(property.MemberType, value, data, new Info(property), isReadOnly);
                }
                else if (settings.SerializeNull)
                {
                    data.AddNullValue(property.Name, property.Location != NanoLocation.SubNode);
                }
            }

            for (int i = 0; i < wrapper.Fields.Count; i++)
            {
                FieldWrapper field = wrapper.Fields[i];

                if (!settings.IgnoreNotSerialized && field.Info.IsNotSerialized)
                {
                    continue;
                }

                object value = field.GetValue(target);
                if (value != null)
                {
                    SerializeValue(field.MemberType, value, data, new Info(field), false);
                }
                else if (settings.SerializeNull)
                {
                    data.AddNullValue(field.Name, field.Location != NanoLocation.SubNode);
                }
            }
        }
		private CompiledAccessStubFieldWrapper(TypeWrapper wrapper, PropertyInfo property, FieldInfo field, TypeWrapper propertyType, Modifiers modifiers, MemberFlags flags)
			: base(wrapper, propertyType, property.Name, propertyType.SigName, modifiers, field, flags)
		{
			this.getter = property.GetGetMethod(true);
			this.setter = property.GetSetMethod(true);
		}
 public void Add(string key, TypeWrapper typeWrapper)
 {
     this.typeDictionary.Add(key, typeWrapper);
     this.types.Add(typeWrapper);
 }
		internal static MethodWrapper Create(TypeWrapper declaringType, string name, string sig, MethodBase method, TypeWrapper returnType, TypeWrapper[] parameterTypes, Modifiers modifiers, MemberFlags flags)
		{
			Debug.Assert(declaringType != null && name!= null && sig != null && method != null);

			if(declaringType.IsGhost)
			{
				// HACK since our caller isn't aware of the ghost issues, we'll handle the method swapping
				if(method.DeclaringType.IsValueType)
				{
					Type[] types = new Type[parameterTypes.Length];
					for(int i = 0; i < types.Length; i++)
					{
						types[i] = parameterTypes[i].TypeAsSignatureType;
					}
					method = declaringType.TypeAsBaseType.GetMethod(method.Name, types);
				}
				return new GhostMethodWrapper(declaringType, name, sig, method, returnType, parameterTypes, modifiers, flags);
			}
			else if(method is ConstructorInfo)
			{
				return new SmartConstructorMethodWrapper(declaringType, name, sig, (ConstructorInfo)method, parameterTypes, modifiers, flags);
			}
			else
			{
				return new SmartCallMethodWrapper(declaringType, name, sig, (MethodInfo)method, returnType, parameterTypes, modifiers, flags, SimpleOpCode.Call, method.IsStatic ? SimpleOpCode.Call : SimpleOpCode.Callvirt);
			}
		}
Example #39
0
 private static void doLoad(object thisNativeLibrary, string name)
 {
     java.lang.ClassLoader.NativeLibrary lib = (java.lang.ClassLoader.NativeLibrary)thisNativeLibrary;
     lib.handle = IKVM.Runtime.JniHelper.LoadLibrary(name, TypeWrapper.FromClass(java.lang.ClassLoader.NativeLibrary.getFromClass()).GetClassLoader());
     lib.loaded = true;
 }
		internal void Link()
		{
			lock(this)
			{
				if(parameterTypeWrappers != null)
				{
					return;
				}
			}
			ClassLoaderWrapper loader = this.DeclaringType.GetClassLoader();
			TypeWrapper ret = loader.RetTypeWrapperFromSigNoThrow(Signature);
			TypeWrapper[] parameters = loader.ArgTypeWrapperListFromSigNoThrow(Signature);
			lock(this)
			{
				try
				{
					// critical code in the finally block to avoid Thread.Abort interrupting the thread
				}
				finally
				{
					if(parameterTypeWrappers == null)
					{
						Debug.Assert(returnTypeWrapper == null || returnTypeWrapper == PrimitiveTypeWrapper.VOID);
						returnTypeWrapper = ret;
						parameterTypeWrappers = parameters;
						UpdateNonPublicTypeInSignatureFlag();
						if(method == null)
						{
							try
							{
								DoLinkMethod();
							}
							catch
							{
								// HACK if linking fails, we unlink to make sure
								// that the next link attempt will fail again
								returnTypeWrapper = null;
								parameterTypeWrappers = null;
								throw;
							}
						}
					}
				}
			}
		}
Example #41
0
    public static java.lang.Class forName0(string name, bool initialize, java.lang.ClassLoader loader)
    {
#if FIRST_PASS
        return(null);
#else
        //Console.WriteLine("forName: " + name + ", loader = " + loader);
        TypeWrapper tw = null;
        if (name.IndexOf(',') > 0)
        {
            // we essentially require full trust before allowing arbitrary types to be loaded,
            // hence we do the "createClassLoader" permission check
            java.lang.SecurityManager sm = java.lang.System.getSecurityManager();
            if (sm != null)
            {
                sm.checkPermission(new java.lang.RuntimePermission("createClassLoader"));
            }
            Type type = Type.GetType(name);
            if (type != null)
            {
                tw = ClassLoaderWrapper.GetWrapperFromType(type);
            }
            if (tw == null)
            {
                java.lang.Throwable.suppressFillInStackTrace = true;
                throw new java.lang.ClassNotFoundException(name);
            }
        }
        else
        {
            try
            {
                ClassLoaderWrapper classLoaderWrapper = ClassLoaderWrapper.GetClassLoaderWrapper(loader);
                tw = classLoaderWrapper.LoadClassByDottedName(name);
            }
            catch (ClassNotFoundException x)
            {
                java.lang.Throwable.suppressFillInStackTrace = true;
                throw new java.lang.ClassNotFoundException(x.Message);
            }
            catch (ClassLoadingException x)
            {
                throw x.InnerException;
            }
            catch (RetargetableJavaException x)
            {
                throw x.ToJava();
            }
        }
        if (initialize && !tw.IsArray)
        {
            try
            {
                tw.Finish();
            }
            catch (RetargetableJavaException x)
            {
                throw x.ToJava();
            }
            tw.RunClassInit();
        }
        return(tw.ClassObject);
#endif
    }
Example #42
0
 public static bool isPrimitive(java.lang.Class thisClass)
 {
     return(TypeWrapper.FromClass(thisClass).IsPrimitive);
 }
Example #43
0
    public static java.lang.Class getComponentType(java.lang.Class thisClass)
    {
        TypeWrapper tw = TypeWrapper.FromClass(thisClass);

        return(tw.IsArray ? tw.ElementTypeWrapper.ClassObject : null);
    }
Example #44
0
 private static bool IsNonVectorArray(TypeWrapper tw)
 {
     return(!tw.IsArray && tw.TypeAsBaseType.IsArray);
 }
Example #45
0
 public static java.lang.ClassLoader getClassLoader0(java.lang.Class thisClass)
 {
     return(TypeWrapper.FromClass(thisClass).GetClassLoader().GetJavaClassLoader());
 }
Example #46
0
 private static void AddToExportList(TypeWrapper c)
 {
     todo[c.Name] = c;
 }
Example #47
0
        private static void AssertReverseRelationshipHasIgnoreAttribute(TypeWrapper reverseClassType, string relName)
        {
            var singleRelProp = reverseClassType.GetProperty(relName);

            Assert.IsTrue(singleRelProp.HasIgnoreAttribute, relName + " on " + reverseClassType.Name + " should have an ignore attribute");
        }
Example #48
0
 internal StubTypeWrapper(Modifiers modifiers, string name, TypeWrapper baseWrapper, bool remapped)
     : base(TypeFlags.None, modifiers, name)
 {
     this.remapped    = remapped;
     this.baseWrapper = baseWrapper;
 }
		private bool InPracticeInternalsVisibleTo(TypeWrapper caller)
		{
#if !STATIC_COMPILER
			if (DeclaringType.TypeAsTBD.Assembly.Equals(caller.TypeAsTBD.Assembly))
			{
				// both the caller and the declaring type are in the same assembly
				// so we know that the internals are visible
				// (this handles the case where we're running in dynamic mode)
				return true;
			}
#endif
#if CLASSGC
			if (DeclaringType is DynamicTypeWrapper)
			{
				// if we are dynamic, we can just become friends with the caller
				DeclaringType.GetClassLoader().GetTypeWrapperFactory().AddInternalsVisibleTo(caller.TypeAsTBD.Assembly);
				return true;
			}
#endif
			return DeclaringType.InternalsVisibleTo(caller);
		}
Example #50
0
        private static void AssertRelationshipIsForOwnerClass(TypeWrapper ownerClassType, TypeWrapper reverseClassType, string reveresRelationshipName)
        {
            var reversePropInfo = reverseClassType.GetProperty(reveresRelationshipName);

            Assert.IsNotNull(reversePropInfo, reveresRelationshipName + " on " + reverseClassType.Name + " should not be null");
            Assert.AreSame(ownerClassType.UnderlyingType, reversePropInfo.RelatedClassType.UnderlyingType);
        }
		internal ConstantFieldWrapper(TypeWrapper declaringType, TypeWrapper fieldType, string name, string sig, Modifiers modifiers, FieldInfo field, object constant, MemberFlags flags)
			: base(declaringType, fieldType, name, sig, modifiers, field, flags)
		{
			Debug.Assert(IsStatic);
            Debug.Assert(constant == null || constant.GetType().IsPrimitive || constant is string);
			this.constant = constant;
		}
Example #52
0
        private static void AssertReverseRelationshipNotForOwnerClass(TypeWrapper ownerClassType, TypeWrapper reverseClassType, string reveresRelationshipName)
        {
            var reversePropInfo = reverseClassType.GetProperty(reveresRelationshipName);

            Assert.IsNotNull(reversePropInfo, "No Reverse Relationship found with the name");
            Assert.AreNotSame(ownerClassType, reversePropInfo.RelatedClassType);
        }
		// constructor for type 2 access stubs
		internal CompiledAccessStubFieldWrapper(TypeWrapper wrapper, PropertyInfo property, FieldInfo field, TypeWrapper propertyType)
			: this(wrapper, property, field, propertyType, AttributeHelper.GetModifiersAttribute(property).Modifiers, MemberFlags.AccessStub)
		{
		}
Example #54
0
 private static bool IsSafeForGetClassOptimization(TypeWrapper tw)
 {
     // because of ghost arrays, we don't optimize if both types are either java.lang.Object or an array
     return(tw != CoreClasses.java.lang.Object.Wrapper && !tw.IsArray);
 }
			internal GhostMethodWrapper(TypeWrapper declaringType, string name, string sig, MethodBase method, TypeWrapper returnType, TypeWrapper[] parameterTypes, Modifiers modifiers, MemberFlags flags)
				: base(declaringType, name, sig, method, returnType, parameterTypes, modifiers, flags)
			{
				// make sure we weren't handed the ghostMethod in the wrapper value type
				Debug.Assert(method == null || method.DeclaringType.IsInterface);
			}
Example #56
0
        private static bool Unsafe_putObjectImpl(EmitIntrinsicContext eic, bool membarrier)
        {
            TypeWrapper tw = eic.GetStackTypeWrapper(0, 2);

            if (IsSupportedArrayTypeForUnsafeOperation(tw) &&
                eic.GetStackTypeWrapper(0, 0).IsAssignableTo(tw.ElementTypeWrapper))
            {
                CodeEmitterLocal value = eic.Emitter.AllocTempLocal(tw.ElementTypeWrapper.TypeAsLocalOrStackType);
                CodeEmitterLocal index = eic.Emitter.AllocTempLocal(Types.Int32);
                CodeEmitterLocal array = eic.Emitter.AllocTempLocal(tw.TypeAsLocalOrStackType);
                eic.Emitter.Emit(OpCodes.Stloc, value);
                eic.Emitter.Emit(OpCodes.Conv_Ovf_I4);
                eic.Emitter.Emit(OpCodes.Stloc, index);
                eic.Emitter.Emit(OpCodes.Stloc, array);
                EmitConsumeUnsafe(eic);
                eic.Emitter.Emit(OpCodes.Ldloc, array);
                eic.Emitter.Emit(OpCodes.Ldloc, index);
                eic.Emitter.Emit(OpCodes.Ldloc, value);
                eic.Emitter.ReleaseTempLocal(array);
                eic.Emitter.ReleaseTempLocal(index);
                eic.Emitter.ReleaseTempLocal(value);
                eic.Emitter.Emit(OpCodes.Stelem_Ref);
                if (membarrier)
                {
                    eic.Emitter.EmitMemoryBarrier();
                }
                eic.NonLeaf = false;
                return(true);
            }
            if ((eic.Flags[eic.OpcodeIndex] & InstructionFlags.BranchTarget) != 0 ||
                (eic.Flags[eic.OpcodeIndex - 1] & InstructionFlags.BranchTarget) != 0)
            {
                return(false);
            }
            if ((eic.Match(-1, NormalizedByteCode.__aload) || eic.Match(-1, NormalizedByteCode.__aconst_null)) &&
                eic.Match(-2, NormalizedByteCode.__getstatic))
            {
                FieldWrapper fw = GetUnsafeField(eic, eic.GetFieldref(-2));
                if (fw != null &&
                    (!fw.IsFinal || (!fw.IsStatic && eic.Caller.Name == "<init>") || (fw.IsStatic && eic.Caller.Name == "<clinit>")) &&
                    fw.IsAccessibleFrom(fw.DeclaringType, eic.Caller.DeclaringType, fw.DeclaringType) &&
                    eic.GetStackTypeWrapper(0, 0).IsAssignableTo(fw.FieldTypeWrapper) &&
                    (fw.IsStatic || fw.DeclaringType == eic.GetStackTypeWrapper(0, 2)))
                {
                    CodeEmitterLocal value = eic.Emitter.AllocTempLocal(fw.FieldTypeWrapper.TypeAsLocalOrStackType);
                    eic.Emitter.Emit(OpCodes.Stloc, value);
                    eic.Emitter.Emit(OpCodes.Pop);                              // discard offset field
                    if (fw.IsStatic)
                    {
                        eic.Emitter.Emit(OpCodes.Pop);                          // discard object
                        EmitConsumeUnsafe(eic);
                    }
                    else
                    {
                        CodeEmitterLocal obj = eic.Emitter.AllocTempLocal(fw.DeclaringType.TypeAsLocalOrStackType);
                        eic.Emitter.Emit(OpCodes.Stloc, obj);
                        EmitConsumeUnsafe(eic);
                        eic.Emitter.Emit(OpCodes.Ldloc, obj);
                        eic.Emitter.ReleaseTempLocal(obj);
                    }
                    eic.Emitter.Emit(OpCodes.Ldloc, value);
                    eic.Emitter.ReleaseTempLocal(value);
                    // note that we assume the CLR memory model where all writes are ordered,
                    // so we don't need a volatile store or a memory barrier and putOrderedObject
                    // is typically used with a volatile field, so to avoid the memory barrier,
                    // we don't use FieldWrapper.EmitSet(), but emit the store directly
                    eic.Emitter.Emit(fw.IsStatic ? OpCodes.Stsfld : OpCodes.Stfld, fw.GetField());
                    if (membarrier)
                    {
                        eic.Emitter.EmitMemoryBarrier();
                    }
                    eic.NonLeaf = false;
                    return(true);
                }
            }
            return(false);
        }
		internal MethodWrapper(TypeWrapper declaringType, string name, string sig, MethodBase method, TypeWrapper returnType, TypeWrapper[] parameterTypes, Modifiers modifiers, MemberFlags flags)
			: base(declaringType, name, sig, modifiers, flags)
		{
			Profiler.Count("MethodWrapper");
			this.method = method;
			Debug.Assert(((returnType == null) == (parameterTypes == null)) || (returnType == PrimitiveTypeWrapper.VOID));
			this.returnTypeWrapper = returnType;
			this.parameterTypeWrappers = parameterTypes;
			if (Intrinsics.IsIntrinsic(this))
			{
				SetIntrinsicFlag();
			}
			UpdateNonPublicTypeInSignatureFlag();
		}
Example #58
0
        private static bool Unsafe_compareAndSwapObject(EmitIntrinsicContext eic)
        {
            TypeWrapper tw = eic.GetStackTypeWrapper(0, 3);

            if (IsSupportedArrayTypeForUnsafeOperation(tw) &&
                eic.GetStackTypeWrapper(0, 0).IsAssignableTo(tw.ElementTypeWrapper) &&
                eic.GetStackTypeWrapper(0, 1).IsAssignableTo(tw.ElementTypeWrapper))
            {
                Type             type   = tw.TypeAsLocalOrStackType.GetElementType();
                CodeEmitterLocal update = eic.Emitter.AllocTempLocal(type);
                CodeEmitterLocal expect = eic.Emitter.AllocTempLocal(type);
                CodeEmitterLocal index  = eic.Emitter.AllocTempLocal(Types.Int32);
                CodeEmitterLocal obj    = eic.Emitter.AllocTempLocal(tw.TypeAsLocalOrStackType);
                eic.Emitter.Emit(OpCodes.Stloc, update);
                eic.Emitter.Emit(OpCodes.Stloc, expect);
                eic.Emitter.Emit(OpCodes.Conv_Ovf_I4);
                eic.Emitter.Emit(OpCodes.Stloc, index);
                eic.Emitter.Emit(OpCodes.Stloc, obj);
                EmitConsumeUnsafe(eic);
                eic.Emitter.Emit(OpCodes.Ldloc, obj);
                eic.Emitter.Emit(OpCodes.Ldloc, index);
                eic.Emitter.Emit(OpCodes.Ldelema, type);
                eic.Emitter.Emit(OpCodes.Ldloc, update);
                eic.Emitter.Emit(OpCodes.Ldloc, expect);
                eic.Emitter.Emit(OpCodes.Call, AtomicReferenceFieldUpdaterEmitter.MakeCompareExchange(type));
                eic.Emitter.Emit(OpCodes.Ldloc, expect);
                eic.Emitter.Emit(OpCodes.Ceq);
                eic.Emitter.ReleaseTempLocal(obj);
                eic.Emitter.ReleaseTempLocal(index);
                eic.Emitter.ReleaseTempLocal(expect);
                eic.Emitter.ReleaseTempLocal(update);
                eic.NonLeaf = false;
                return(true);
            }
            if ((eic.Flags[eic.OpcodeIndex] & InstructionFlags.BranchTarget) != 0 ||
                (eic.Flags[eic.OpcodeIndex - 1] & InstructionFlags.BranchTarget) != 0 ||
                (eic.Flags[eic.OpcodeIndex - 2] & InstructionFlags.BranchTarget) != 0)
            {
                return(false);
            }
            if ((eic.Match(-1, NormalizedByteCode.__aload) || eic.Match(-1, NormalizedByteCode.__aconst_null)) &&
                (eic.Match(-2, NormalizedByteCode.__aload) || eic.Match(-2, NormalizedByteCode.__aconst_null)) &&
                eic.Match(-3, NormalizedByteCode.__getstatic))
            {
                FieldWrapper fw = GetUnsafeField(eic, eic.GetFieldref(-3));
                if (fw != null &&
                    fw.IsAccessibleFrom(fw.DeclaringType, eic.Caller.DeclaringType, fw.DeclaringType) &&
                    eic.GetStackTypeWrapper(0, 0).IsAssignableTo(fw.FieldTypeWrapper) &&
                    eic.GetStackTypeWrapper(0, 1).IsAssignableTo(fw.FieldTypeWrapper) &&
                    (fw.IsStatic || fw.DeclaringType == eic.GetStackTypeWrapper(0, 3)))
                {
                    Type             type   = fw.FieldTypeWrapper.TypeAsLocalOrStackType;
                    CodeEmitterLocal update = eic.Emitter.AllocTempLocal(type);
                    CodeEmitterLocal expect = eic.Emitter.AllocTempLocal(type);
                    eic.Emitter.Emit(OpCodes.Stloc, update);
                    eic.Emitter.Emit(OpCodes.Stloc, expect);
                    eic.Emitter.Emit(OpCodes.Pop);                                      // discard index
                    if (fw.IsStatic)
                    {
                        eic.Emitter.Emit(OpCodes.Pop);                                  // discard obj
                        EmitConsumeUnsafe(eic);
                        eic.Emitter.Emit(OpCodes.Ldsflda, fw.GetField());
                    }
                    else
                    {
                        CodeEmitterLocal obj = eic.Emitter.AllocTempLocal(eic.Caller.DeclaringType.TypeAsLocalOrStackType);
                        eic.Emitter.Emit(OpCodes.Stloc, obj);
                        EmitConsumeUnsafe(eic);
                        eic.Emitter.Emit(OpCodes.Ldloc, obj);
                        eic.Emitter.ReleaseTempLocal(obj);
                        eic.Emitter.Emit(OpCodes.Ldflda, fw.GetField());
                    }
                    eic.Emitter.Emit(OpCodes.Ldloc, update);
                    eic.Emitter.Emit(OpCodes.Ldloc, expect);
                    eic.Emitter.Emit(OpCodes.Call, AtomicReferenceFieldUpdaterEmitter.MakeCompareExchange(type));
                    eic.Emitter.Emit(OpCodes.Ldloc, expect);
                    eic.Emitter.Emit(OpCodes.Ceq);
                    eic.Emitter.ReleaseTempLocal(expect);
                    eic.Emitter.ReleaseTempLocal(update);
                    eic.NonLeaf = false;
                    return(true);
                }
            }
            return(false);
        }
		protected MemberWrapper(TypeWrapper declaringType, string name, string sig, Modifiers modifiers, MemberFlags flags)
		{
			Debug.Assert(declaringType != null);
			this.declaringType = declaringType;
			this.name = String.Intern(name);
			this.sig = String.Intern(sig);
			this.modifiers = modifiers;
			this.flags = flags;
		}
Example #60
0
        public static TDelegate CompileLambda <TDelegate>(params object[] expressions) /*TODO: add in C# v7.3: where TDelegate : Delegate*/
        {
            var typeWrapper = new TypeWrapper(typeof(TDelegate));

            return((TDelegate)(object)typeWrapper.CompileLambda(expressions));
        }