Inheritance: FieldReference, IMemberDefinition, IConstantProvider, IMarshalInfoProvider, IVisibilityDefinition
Esempio n. 1
0
 public Field(FieldDefinition fieldDefinition, Class declaringClass, Type type, int structIndex)
 {
     FieldDefinition = fieldDefinition;
     DeclaringClass = declaringClass;
     Type = type;
     StructIndex = structIndex;
 }
Esempio n. 2
0
 public override IWeaver GetWeaver(MethodDefinition method, FieldDefinition mixin)
 {
     if (method.CustomAttributes.Any (a => a.AttributeType.FullName == Constants.AsyncStateMachineAttribute))
         return GetAsyncMethodWeaver (method, mixin);
     return new FakeWeaver ();
     throw new NotImplementedException ();
 }
Esempio n. 3
0
		public AnalyzedFieldNode(FieldDefinition analyzedField)
		{
			if (analyzedField == null)
				throw new ArgumentNullException("analyzedField");
			this.analyzedField = analyzedField;
			this.LazyLoading = true;
		}
Esempio n. 4
0
 public Field(FieldDefinition fieldDefinition, Type declaringType, Type type, int structIndex)
 {
     FieldDefinition = fieldDefinition;
     DeclaringType = declaringType;
     Type = type;
     StructIndex = structIndex;
 }
        private void WeaveInterceptionCall(
            MethodDefinition methodToExtend,
            MethodDefinition decoratedMethodParameter,
            MethodDefinition implementationMethodParameter,
            FieldDefinition interceptorManager)
        {
            methodToExtend.Body.InitLocals = true;
            ILProcessor processor = methodToExtend.Body.GetILProcessor();
            processor.Emit(OpCodes.Nop);

            var decoratedMethodVar = methodToExtend.AddVariableDefinition("__fody$originalMethod", this.methodBaseTypeRef);
            var implementationMethodVar = methodToExtend.AddVariableDefinition("__fody$implementationMethod", this.methodBaseTypeRef);
            var parametersVar = methodToExtend.AddVariableDefinition("__fody$parameters", this.objectArrayTypeRef);

            this.SaveMethodBaseToVariable(processor, decoratedMethodParameter, decoratedMethodVar);
            if (implementationMethodParameter != null)
            {
                this.SaveMethodBaseToVariable(processor, implementationMethodParameter, implementationMethodVar);
            }

            processor.SaveParametersToNewObjectArray(parametersVar, methodToExtend.Parameters.ToArray());

            this.CallInterceptMethod(interceptorManager, processor, decoratedMethodVar, implementationMethodVar, parametersVar);

            HandleInterceptReturnValue(methodToExtend, processor);

            // write method end
            processor.Emit(OpCodes.Ret);
            methodToExtend.Body.OptimizeMacros();
        }
 public StateControllerRemover(MethodSpecificContext methodContext, FieldDefinition stateField = null)
 {
     this.methodContext = methodContext;
     this.theCFG = methodContext.ControlFlowGraph;
     this.stateField = stateField;
     this.stateToStartBlock = new InstructionBlock[this.theCFG.Blocks.Length];
 }
Esempio n. 7
0
        static void InjectLoadHook()
        {
            // only hooking to V2 shouldn't be bad: V1 worlds won't have mod data in them, because 1.3 (and prism) only write as V2
            var loadWorld = typeDef_WorldFile.GetMethod("loadWorld");

            var lwb = loadWorld.Body;
            var lwbproc = lwb.GetILProcessor();

            MethodDefinition invokeLoadWorld;
            var loadWorldDel = context.CreateDelegate("Terraria.PrismInjections", "WorldFile_OnLoadWorldDel", typeSys.Void, out invokeLoadWorld, typeSys.Boolean);

            var onLoadWorld = new FieldDefinition("P_OnLoadWorld", FieldAttributes.Public | FieldAttributes.Static, loadWorldDel);
            typeDef_WorldFile.Fields.Add(onLoadWorld);

            OpCode[] toFind =
            {
                OpCodes.Br_S,
                OpCodes.Ldloc_S,
                OpCodes.Call, // wtf?
                OpCodes.Stloc_S
            };

            Instruction[] toInject =
            {
                Instruction.Create(OpCodes.Ldsfld, onLoadWorld),
                Instruction.Create(OpCodes.Ldarg_0),
                Instruction.Create(OpCodes.Callvirt, invokeLoadWorld)
            };

            var instr = lwb.FindInstrSeqStart(toFind).Next.Next.Next.Next;

            for (int i = 0; i < toInject.Length; i++)
                lwbproc.InsertBefore(instr, toInject[i]);
        }
 public WeakEventWeaver(FieldReference eventDelegate, ModuleImporter moduleimporter)
 {
     _eventDelegate = eventDelegate.Resolve();
     _moduleimporter = moduleimporter;
     _closedGenericEventHandler = moduleimporter.GetClosedEventHandlerT(eventDelegate.FieldType.GetEventArgsType());
     _isGenericHandler = _closedGenericEventHandler.FullName.Equals(eventDelegate.FieldType.FullName);
 }
        //public FieldVisitor(ClassInfo classInfo, string name, string descriptor, string signature, object value, 
        //    bool isFinal, bool isStatic, bool isPrivate)
        //{
        //    Type type = ClrType.FromDescriptor(descriptor);

        //    classInfo.AddField(new FieldInfo(classInfo, name, type, isFinal, isStatic, isPrivate));
        //}

        public FieldVisitor(ClassInfo classInfo, FieldDefinition fieldDefinition)
        {
            //classInfo.AddField();
            //Type type = ClrType.FromName(fieldDefinition.FieldType.FullName);
            Type type = ClrType.FromDescriptor(fieldDefinition.FieldType.FullName);
            classInfo.AddField(new FieldInfo(classInfo, fieldDefinition.Name, type, false, fieldDefinition.IsStatic, fieldDefinition.IsPrivate));
        }
 public YieldFieldsInformation(FieldDefinition stateHolderField, FieldDefinition currentItemField,
     VariableReference returnFlagVariable)
 {
     this.stateHolderField = stateHolderField;
     this.currentItemField = currentItemField;
     this.returnFlagVariable = returnFlagVariable;
 }
Esempio n. 11
0
 protected override void ProcessField(FieldDefinition fieldDef)
 {
     if (fieldDef.IsPublic || fieldDef.IsFamily || fieldDef.IsFamilyOrAssembly) {
         _members.Add(fieldDef);
     }
     base.ProcessField(fieldDef);
 }
Esempio n. 12
0
 public AsyncMethodWeaver(IEngine engine, MethodDefinition method, FieldDefinition actorMixin, FieldDefinition stateMachineMixin)
 {
     _engine = engine;
     _method = method;
     _actorMixin = actorMixin;
     _stateMachineMixin = stateMachineMixin;
 }
 protected override void Visit(FieldDefinition fieldDefinition, Unity.Cecil.Visitor.Context context)
 {
     if (!GenericsUtilities.CheckForMaximumRecursion(this._genericContext.Type))
     {
         base.Visit(fieldDefinition, context);
     }
 }
        public static MethodDefinition AddPropertyGetter(
            PropertyDefinition property
            , MethodAttributes methodAttributes = MethodAttributes.Public | MethodAttributes.HideBySig | MethodAttributes.SpecialName | MethodAttributes.NewSlot | MethodAttributes.Virtual
            , FieldDefinition backingField = null)
        {
            if (backingField == null)
            {
                // TODO: Try and find existing friendly named backingFields first.
                backingField = AddPropertyBackingField(property);
            }

            var methodName = "get_" + property.Name;
            var getter = new MethodDefinition(methodName, methodAttributes, property.PropertyType)
            {
                IsGetter = true,
                Body = {InitLocals = true},
            };

            getter.Body.Variables.Add(new VariableDefinition(property.PropertyType));

            var returnStart = Instruction.Create(OpCodes.Ldloc_0);
            getter.Body.Instructions.Append(
                Instruction.Create(OpCodes.Ldarg_0),
                Instruction.Create(OpCodes.Ldfld, backingField),
                Instruction.Create(OpCodes.Stloc_0),
                Instruction.Create(OpCodes.Br_S, returnStart),
                returnStart,
                Instruction.Create(OpCodes.Ret)
                );        
                
            property.GetMethod = getter;
            property.DeclaringType.Methods.Add(getter);
            return getter;
        }
Esempio n. 15
0
        /// <summary>
        /// Creates a new field in the target assembly, for the specified type.
        /// </summary>
        /// <param name="targetDeclaringType">The target declaring type.</param>
        /// <param name="yourField">Your field.</param>
        /// <param name="attr">The action attribute.</param>
        /// <exception cref="PatchDeclerationException">Thrown if this member collides with another member, and the error cannot be resolved.</exception>
        /// <returns></returns>
        private NewMemberStatus CreateNewField(TypeDefinition targetDeclaringType, FieldDefinition yourField,
			NewMemberAttribute attr)
        {
            if (attr.IsImplicit) {
                Log_implicitly_creating_member("field", yourField);
            } else {
                Log_creating_member("field", yourField);
            }
            var maybeDuplicate = targetDeclaringType.GetField(yourField.Name);
            if (maybeDuplicate != null) {
                Log_duplicate_member("field", yourField, maybeDuplicate);
                if ((DebugOptions & DebugFlags.CreationOverwrites) != 0) {
                    Log_overwriting();
                    return NewMemberStatus.Continue;
                }
                if (attr.IsImplicit) {
                    return NewMemberStatus.InvalidItem;
                }
                throw Errors.Duplicate_member("type", yourField.FullName, maybeDuplicate.FullName);
            }
            var targetField =
                new FieldDefinition(yourField.Name, yourField.Resolve().Attributes, FixTypeReference(yourField.FieldType)) {
                    InitialValue = yourField.InitialValue, //probably for string consts
                    Constant = yourField.Constant
                };
            targetDeclaringType.Fields.Add(targetField);
            return NewMemberStatus.Continue;
        }
        public void Add(FieldDefinition value)
        {
            if (!Contains (value))
                Attach (value);

            List.Add (value);
        }
        internal FieldDefinition GetTargetCecilDefintion(ModuleDefinition module)
        {
            if (_targetCecilDef == null)
                _targetCecilDef = DeclInjectee.GetTargetCecilType(module).FindMatchingField(TargetField, true);

            return _targetCecilDef;
        }
        internal FieldDefinition GetInjecteeCecilDefintion(ModuleDefinition module)
        {
            if (_injecteeCecilDef == null)
                _injecteeCecilDef = DeclInjectee.GetInjecteeCecilType(module).FindMatchingField(InjecteeField, true);

            return _injecteeCecilDef;
        }
Esempio n. 19
0
        static void InjectBuffEffectsCall()
        {
            var updateNpc = typeDef_NPC.GetMethod("RealUpdateNPC");

            MethodDefinition invokeEffects;
            var onBuffEffects = context.CreateDelegate("Terraria.PrismInjections", "NPC_BuffEffectsDel", typeSys.Void, out invokeEffects, typeDef_NPC);

            var buffEffects = new FieldDefinition("P_OnBuffEffects", FieldAttributes.Public | FieldAttributes.Static, onBuffEffects);
            typeDef_NPC.Fields.Add(buffEffects);

            OpCode[] toRem =
            {
                OpCodes.Ldarg_0,
                OpCodes.Ldfld,
                OpCodes.Brfalse
            };

            var unb = updateNpc.Body;
            var unproc = unb.GetILProcessor();

            Instruction instr;
            int start = 0;
            while (true)
            {
                instr = unb.FindInstrSeqStart(toRem, start);

                if (instr.Next.Operand == typeDef_NPC.GetField("soulDrain"))
                    break;
                else
                    start = unb.Instructions.IndexOf(instr) + 1;
            }

            unproc.InsertBefore(instr, Instruction.Create(OpCodes.Ldsfld, buffEffects));
            unproc.EmitWrapperCall(invokeEffects, instr);
        }
Esempio n. 20
0
        public static FieldDefinition InjectField(this TypeDefinition targetType, FieldDefinition sourceField, ReferenceResolver resolver)
        {
            if (sourceField == null)
                throw new ArgumentNullException("sourceField");
            if (resolver == null)
                throw new ArgumentNullException("resolver");

            FieldDefinition newField = null;
            if (Helper.TryGetField(targetType.Fields, sourceField, ref newField))
                return newField;

            TypeReference fieldType = resolver.ReferenceType(sourceField.FieldType, targetType);
            newField = new FieldDefinition(sourceField.Name, sourceField.Attributes, fieldType)
            {
                InitialValue = sourceField.InitialValue,
                DeclaringType = targetType,
            };

            targetType.Fields.Add(newField);

            MetadataBuilderHelper.CopyCustomAttributes(sourceField, newField, resolver);

            if (newField.HasDefault)
                newField.Constant = sourceField.Constant;

            return newField;
        }
Esempio n. 21
0
        static void InjectSaveHook()
        {
            var saveWorld = typeDef_WorldFile.GetMethod("saveWorld", MethodFlags.Public | MethodFlags.Static, typeSys.Boolean, typeSys.Boolean);

            var swb = saveWorld.Body;
            var swbproc = swb.GetILProcessor();

            MethodDefinition invokeSaveWorld;
            var saveWorldDel = context.CreateDelegate("Terraria.PrismInjections", "WorldFile_OnSaveWorldDel", typeSys.Void, out invokeSaveWorld, typeSys.Boolean);

            var onSaveWorld = new FieldDefinition("P_OnSaveWorld", FieldAttributes.Public | FieldAttributes.Static, saveWorldDel);
            typeDef_WorldFile.Fields.Add(onSaveWorld);

            OpCode[] toFind =
            {
                OpCodes.Ldloc_S,
                OpCodes.Call,
                OpCodes.Leave_S
            };

            Instruction[] toInject =
            {
                Instruction.Create(OpCodes.Ldsfld, onSaveWorld),
                Instruction.Create(OpCodes.Ldarg_0),
                Instruction.Create(OpCodes.Callvirt, invokeSaveWorld)
            };

            var instr = swb.FindInstrSeqStart(toFind).Next.Next;

            for (int i = 0; i < toInject.Length; i++)
                swbproc.InsertBefore(instr, toInject[i]);
        }
Esempio n. 22
0
		public FieldKey(TypeKey typeKey, string type, string name, FieldDefinition fieldDefinition)
		{
			this.typeKey = typeKey;
			this.type = type;
			this.name = name;
			this.fieldDefinition = fieldDefinition;
		}
Esempio n. 23
0
        /// <summary>
        /// Thiashd iahsd haishd iashd ihasih iqwhei hqie hwqih eoqwh eoqwihe oashd   
        /// oasihd o oiahsd oihasd oihawoidh aowihd oaihd oiahsoid had asd .as.d as. d  
        /// as.d a sd as.
        /// </summary>
        /// <param name="fieldDefinition"></param>
        /// <param name="declaringType"></param>
        public MyFieldInfo(FieldDefinition fieldDefinition, MyClassInfo declaringType)
            : base()
        {
            this.name = fieldDefinition.Name;

            string[] readableForms = Tools.GetHumanReadableForms(fieldDefinition.FieldType);

            this.typeFullName = readableForms[0];
            this.typeFullNameWithoutRevArrayStrings = readableForms[1];
            this.attributes = GetMyFieldAttributes(fieldDefinition);
            this.declaringType = declaringType;

            if ((fieldDefinition.Attributes & FieldAttributes.HasDefault) != 0)
            {
                try
                {
                    object rawConstant = fieldDefinition.Constant;

                    defaultValue = rawConstant == null ? null : rawConstant.ToString();
                }
                catch (Exception)
                {
                    Logger.Warning("Couldn't obtain default value for field '{0}'.", name);
                }
            }

            this.CheckSupport(fieldDefinition.Attributes);
        }
Esempio n. 24
0
        internal static Instruction CreateInlineFieldInstruction()
        {
            FieldDefinition field = new FieldDefinition("Test", FieldAttributes.Public,
                CecilUtility.Import(typeof(object)));

            return Instruction.Create(OpCodes.Ldfld, field);
        }
Esempio n. 25
0
		public static object GetIcon(FieldDefinition field)
		{
			if (field.IsLiteral)
				return Images.Literal;
			else
				return Images.Field;
		}
/*		FieldDefinition fieldDefinition;
		
		public FieldDefinition FieldDefinition {
			get {
				return fieldDefinition;
			}
		}
		*/
		
		public DomCecilField (FieldDefinition fieldDefinition)
		{
			base.name            = fieldDefinition.Name;
			base.Modifiers       = DomCecilType.GetModifiers (fieldDefinition);
			base.ReturnType      = DomCecilMethod.GetReturnType (fieldDefinition.FieldType);
			DomCecilMethod.AddAttributes (this, fieldDefinition.CustomAttributes);
		}
Esempio n. 27
0
        private static void AddStaticPrototypeCall(MethodDefinition method, FieldDefinition delegateField, FieldDefinition prototypeField)
        {
            Debug.Assert(prototypeField.IsStatic);
            var firstOpcode = method.Body.Instructions.First();
            var il = method.Body.GetILProcessor();

            TypeDefinition delegateType = delegateField.FieldType.Resolve();
            var invokeMethod = delegateType.Methods.Single(m => m.Name == "Invoke");
            int allParamsCount = method.Parameters.Count + (method.IsStatic ? 0 : 1); //all params and maybe this

            var instructions = new[]
            {
                il.Create(OpCodes.Ldsflda, prototypeField),
                il.Create(OpCodes.Ldfld, delegateField),
                il.Create(OpCodes.Brfalse, firstOpcode),

                il.Create(OpCodes.Ldsflda, prototypeField),
                il.Create(OpCodes.Ldfld, delegateField),
            }.Concat(
                Enumerable.Range(0, allParamsCount).Select(i => il.Create(OpCodes.Ldarg, i))
            ).Concat(new[]
            {
                il.Create(OpCodes.Callvirt, invokeMethod),
                il.Create(OpCodes.Ret),
            });

            foreach (var instruction in instructions)
                il.InsertBefore(firstOpcode, instruction);
        }
Esempio n. 28
0
        private void CreateMixinField()
        {
            var actorType = _engine.Get<ActorCore> ();
            _actorMixinField = new FieldDefinition (Constants.MixinFieldName, Constants.MixinFieldAttr, actorType);
            _weavedType.Fields.Add (_actorMixinField);

            var actorCtor = _weavedType.Methods.Single (m => m.IsConstructor);
            var mixinCtor = _engine.GetMethod<Func<ActorCore>> (() => new ActorCore ());

            var ilp = actorCtor.Body.GetILProcessor ();

            var loadThis = ilp.Create (OpCodes.Ldarg_0);
            var callCtor = ilp.Create (OpCodes.Newobj, mixinCtor);
            var saveMixin = ilp.Create (OpCodes.Stfld, _actorMixinField);

            if(actorCtor.Body.Instructions.Count > 0)
            {
                ilp.InsertBefore (actorCtor.Body.Instructions [0], loadThis);
            }
            else
            {
                ilp.Append (loadThis);
            }
            ilp.InsertAfter (loadThis, callCtor);
            ilp.InsertAfter (callCtor, saveMixin);
        }
Esempio n. 29
0
		/// <summary>
		/// Initializes a new instance of the <see cref="Field"/> class.
		/// </summary>
		/// <param name="fieldDefinition">The field definition.</param>
		public Field (FieldDefinition fieldDefinition, Class type, Class _class, InternalType internalType)
		{
			this.type = type;
			this.internalType = internalType;
			this.fieldDefinition = fieldDefinition;
			this._class = _class;
		}
 public ChangeFieldReferencesToPropertyVisitor(FieldDefinition field, PropertyDefinition property)
 {
     if (field == null) throw new ArgumentNullException("field");
       if (property == null) throw new ArgumentNullException("property");
       _field = field;
       _property = property;
 }