Inheritance: FieldReference, IMemberDefinition, IConstantProvider, IMarshalInfoProvider, IVisibilityDefinition
Exemple #1
0
        /// <summary>
        /// Set the value of the given dex field.
        /// </summary>
        protected virtual void SetFieldValue(DexLib.FieldDefinition dfield, FieldDefinition field)
        {
            var constant = field.Constant;

            if (constant != null)
            {
                var fieldType = field.FieldType;
                if (fieldType.IsByte())
                {
                    constant = XConvert.ToByte(constant);
                }
                else if (fieldType.IsUInt16())
                {
                    constant = XConvert.ToShort(constant);
                }
                else if (fieldType.IsUInt32())
                {
                    constant = XConvert.ToInt(constant);
                }
                else if (fieldType.IsUInt64())
                {
                    constant = XConvert.ToLong(constant);
                }
            }
            dfield.Value = constant;
        }
/*		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);
		}
Exemple #3
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;
		}
Exemple #4
0
        private Cecil.FieldDefinition CreateFieldDefinition(AnalysisNet.Types.FieldDefinition fieldDefinition)
        {
            Cecil.FieldAttributes fieldAttribute = Cecil.FieldAttributes.Public;
            if (fieldDefinition.IsStatic)
            {
                fieldAttribute |= Cecil.FieldAttributes.Static;
            }

            Cecil.TypeReference   fieldType  = ReferenceGenerator.TypeReference(fieldDefinition.Type);
            Cecil.FieldDefinition cecilField = new Cecil.FieldDefinition(fieldDefinition.Name, fieldAttribute, fieldType);

            if (fieldDefinition.Value != null)
            {
                cecilField.Constant    = fieldDefinition.Value.Value;
                cecilField.HasConstant = true;
            }

            byte[] newArray = new byte[fieldDefinition.InitialValue.Length];
            Array.Copy(fieldDefinition.InitialValue, newArray, newArray.Length);
            cecilField.InitialValue = newArray;

            if (newArray.Length > 0)
            {
                cecilField.Attributes |= Cecil.FieldAttributes.HasFieldRVA;
            }

            return(cecilField);
        }
Exemple #5
0
        /// <summary>
        /// Set the access flags of the created field.
        /// </summary>
        protected virtual void SetAccessFlags(DexLib.FieldDefinition dfield, FieldDefinition field)
        {
            // subclass accesses have already been fixed on an actual use basis.
            if (field.IsPrivate)
            {
                dfield.IsPrivate = true;
            }
            else if (field.IsFamily || field.IsFamilyOrAssembly)
            {
                dfield.IsProtected = true;
            }
            else
            {
                dfield.IsPublic = true;
            }

            if (field.IsInitOnly)
            {
                dfield.IsFinal = true;
            }
            if (field.IsStatic)
            {
                dfield.IsStatic = true;
            }

            if (field.IsCompilerGenerated())
            {
                dfield.IsSynthetic = true;
            }

            dfield.IsVolatile = field.IsUsedInInterlocked || IsVolatile(field);;
        }
 protected override void Visit(FieldDefinition fieldDefinition, Unity.Cecil.Visitor.Context context)
 {
     if (!GenericsUtilities.CheckForMaximumRecursion(this._genericContext.Type))
     {
         base.Visit(fieldDefinition, context);
     }
 }
Exemple #7
0
 public Field(FieldDefinition fieldDefinition, Class declaringClass, Type type, int structIndex)
 {
     FieldDefinition = fieldDefinition;
     DeclaringClass = declaringClass;
     Type = type;
     StructIndex = structIndex;
 }
        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;
        }
 public ChangeFieldReferencesToPropertyVisitor(FieldDefinition field, PropertyDefinition property)
 {
     if (field == null) throw new ArgumentNullException("field");
       if (property == null) throw new ArgumentNullException("property");
       _field = field;
       _property = property;
 }
Exemple #10
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 ();
 }
Exemple #11
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);
        }
 public AsyncMethodWeaver(IEngine engine, MethodDefinition method, FieldDefinition actorMixin, FieldDefinition stateMachineMixin)
 {
     _engine = engine;
     _method = method;
     _actorMixin = actorMixin;
     _stateMachineMixin = stateMachineMixin;
 }
 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 StateControllerRemover(MethodSpecificContext methodContext, FieldDefinition stateField = null)
 {
     this.methodContext = methodContext;
     this.theCFG = methodContext.ControlFlowGraph;
     this.stateField = stateField;
     this.stateToStartBlock = new InstructionBlock[this.theCFG.Blocks.Length];
 }
        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;
        }
Exemple #16
0
        /// <summary>
        /// Default ctor
        /// </summary>
        public static IEnumerable <FieldBuilder> Create(AssemblyCompiler compiler, FieldDefinition field)
        {
            if (field.IsAndroidExtension())
            {
                return new[] { new DexImportFieldBuilder(compiler, field) }
            }
            ;
            if (field.DeclaringType.IsEnum)
            {
                if (!field.IsStatic)
                {
                    throw new ArgumentException("value field should not be implemented this way");
                }
                return(new[] { new EnumFieldBuilder(compiler, field) });
            }

            var fieldBuilder = new FieldBuilder(compiler, field);

            if (!field.IsUsedInInterlocked)
            {
                return new[] { fieldBuilder }
            }
            ;

            return(new[] { fieldBuilder, new FieldInterlockedBuilder(compiler, field, fieldBuilder) });
        }
Exemple #17
0
		public AnalyzedFieldNode(FieldDefinition analyzedField)
		{
			if (analyzedField == null)
				throw new ArgumentNullException("analyzedField");
			this.analyzedField = analyzedField;
			this.LazyLoading = true;
		}
Exemple #18
0
 public LoadFieldValue(FieldDefinition fieldToLoad, DynamicallyAccessedMemberTypes dynamicallyAccessedMemberTypes)
 {
     Kind  = ValueNodeKind.LoadField;
     Field = fieldToLoad;
     DynamicallyAccessedMemberTypes = dynamicallyAccessedMemberTypes;
     SourceContext = fieldToLoad;
 }
Exemple #19
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);
        }
Exemple #20
0
        /// <summary>
        /// Should the given field be included in the APK?
        /// </summary>
        public bool Include(FieldDefinition field)
        {
            switch (compiler.CompilationMode)
            {
            case CompilationMode.Application:
                break;

            case CompilationMode.ClassLibrary:
                if (field.IsPublic || field.IsFamily || field.IsFamilyOrAssembly)
                {
                    return(true);
                }
                break;

            case CompilationMode.All:
                if (IsRoot(field.DeclaringType))
                {
                    return(true);
                }
                break;

            default:
                throw new CompilerException("Unknown compilation mode " + (int)compiler.CompilationMode);
            }
            return(IncludeFieldTesters.Any(x => x.Include(field, this)));
        }
Exemple #21
0
        internal static Instruction CreateInlineFieldInstruction()
        {
            FieldDefinition field = new FieldDefinition("Test", FieldAttributes.Public,
                CecilUtility.Import(typeof(object)));

            return Instruction.Create(OpCodes.Ldfld, field);
        }
Exemple #22
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;
        }
Exemple #23
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 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 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;
        }
Exemple #27
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);
        }
 protected override void ProcessField(FieldDefinition fieldDef)
 {
     if (fieldDef.IsPublic || fieldDef.IsFamily || fieldDef.IsFamilyOrAssembly) {
         _members.Add(fieldDef);
     }
     base.ProcessField(fieldDef);
 }
        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 YieldFieldsInformation(FieldDefinition stateHolderField, FieldDefinition currentItemField,
     VariableReference returnFlagVariable)
 {
     this.stateHolderField = stateHolderField;
     this.currentItemField = currentItemField;
     this.returnFlagVariable = returnFlagVariable;
 }
Exemple #31
0
 public Field(FieldDefinition fieldDefinition, Type declaringType, Type type, int structIndex)
 {
     FieldDefinition = fieldDefinition;
     DeclaringType = declaringType;
     Type = type;
     StructIndex = structIndex;
 }
        internal FieldDefinition GetInjecteeCecilDefintion(ModuleDefinition module)
        {
            if (_injecteeCecilDef == null)
                _injecteeCecilDef = DeclInjectee.GetInjecteeCecilType(module).FindMatchingField(InjecteeField, true);

            return _injecteeCecilDef;
        }
Exemple #33
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);
        }
Exemple #34
0
		public static object GetIcon(FieldDefinition field)
		{
			if (field.IsLiteral)
				return Images.Literal;
			else
				return Images.Field;
		}
Exemple #35
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]);
        }
Exemple #36
0
		public FieldKey(TypeKey typeKey, string type, string name, FieldDefinition fieldDefinition)
		{
			this.typeKey = typeKey;
			this.type = type;
			this.name = name;
			this.fieldDefinition = fieldDefinition;
		}
Exemple #37
0
 public MonoEnumInfo(MonoEnumType type, TargetType field_type, int index, int pos,
                     Cecil.FieldDefinition finfo)
     : base(field_type, finfo.Name, index, finfo.IsStatic,
            MonoFieldInfo.GetAccessibility(finfo),
            pos, 0, finfo.HasConstant)
 {
     FieldInfo = finfo;
 }
Exemple #38
0
 /// <summary>
 /// Should the given field be implemented?
 /// </summary>
 protected override bool ShouldImplementField(Mono.Cecil.FieldDefinition field)
 {
     if (!base.ShouldImplementField(field))
     {
         return(false);
     }
     if (field.IsStatic)
     {
         return(true);
     }
     throw new FrameworkException(
               string.Format("Type {0} should have no non-framework fields ({1})", Type.FullName, field.Name));
 }
Exemple #39
0
        public MonoFieldInfo(IMonoStructType type, TargetType field_type, int pos,
                             Cecil.FieldDefinition finfo)
            : base(field_type, finfo.Name, pos, finfo.IsStatic,
                   GetAccessibility(finfo), pos, 0, finfo.HasConstant)
        {
            FieldInfo = finfo;

            DebuggerTypeProxyAttribute type_proxy;

            MonoSymbolFile.CheckCustomAttributes(finfo,
                                                 out browsable_state,
                                                 out debugger_display,
                                                 out type_proxy,
                                                 out is_compiler_generated);
        }
Exemple #40
0
        private static bool AnalyzeMethodFieldSets(MethodDefinition methodDefinition, XElement entity, XElement newMethodNode)
        {
            bool result = false;

            Mono.Cecil.Cil.MethodBody body = methodDefinition.Body;
            if (null != body)
            {
                foreach (Instruction itemInstruction in body.Instructions)
                {
                    if (itemInstruction.OpCode.Name.StartsWith("stfld") || itemInstruction.OpCode.Name.StartsWith("stsfld"))
                    {
                        Mono.Cecil.Cil.Instruction methodInstruction = itemInstruction as Mono.Cecil.Cil.Instruction;
                        Mono.Cecil.FieldDefinition fieldDefinition   = methodInstruction.Operand as Mono.Cecil.FieldDefinition;
                        if (fieldDefinition != null && fieldDefinition.FieldType.IsValueType)
                        {
                            Mono.Cecil.Cil.Instruction paramInstruction = GetParameterInstructionForField(methodInstruction);
                            if (null != paramInstruction)
                            {
                                bool sucseed = false;
                                int  opValue = GetOperatorValue(paramInstruction, out sucseed);
                                if (sucseed)
                                {
                                    string[] supportByLibrary = _netOfficeSupportTable.GetEnumMemberSupport(fieldDefinition.FieldType.FullName, (int)opValue);
                                    if (null != supportByLibrary)
                                    {
                                        XElement newParameter  = new XElement("Field", new XAttribute("Name", fieldDefinition.Name));
                                        string   componentName = NetOfficeSupportTable.GetLibrary(fieldDefinition.FieldType.FullName);
                                        XElement supportByNode = new XElement("SupportByLibrary", new XAttribute("Api", componentName));
                                        string   memberName    = _netOfficeSupportTable.GetEnumMemberNameFromValue(fieldDefinition.FieldType.FullName, opValue);
                                        supportByNode.Add(new XAttribute("Name", fieldDefinition.FieldType + "." + memberName));
                                        foreach (string item in supportByLibrary)
                                        {
                                            supportByNode.Add(new XElement("Version", item));
                                        }
                                        newParameter.Add(supportByNode);
                                        newMethodNode.Element("FieldSets").Add(newParameter);
                                    }
                                }
                            }
                        }
                    }
                }
            }

            return(result);
        }
        void get_fields()
        {
            lock (this) {
                if (fields != null)
                {
                    return;
                }

                fields = new MonoFieldInfo [TypeDef.Fields.Count];

                for (int i = 0; i < fields.Length; i++)
                {
                    Cecil.FieldDefinition field = TypeDef.Fields [i];
                    TargetType            ftype = File.MonoLanguage.LookupMonoType(field.FieldType);
                    fields [i] = new MonoFieldInfo(this, ftype, i, field);
                }
            }
        }
Exemple #42
0
        private AnalysisNet.Types.TypeDefinition ExtractEnum(Cecil.TypeDefinition typedef)
        {
            string name = typedef.Name;

            AnalysisNet.Types.TypeDefinition type = new AnalysisNet.Types.TypeDefinition(name, AnalysisNet.Types.TypeKind.ValueType, AnalysisNet.Types.TypeDefinitionKind.Enum)
            {
                Base       = ExtractType(typedef.BaseType) as AnalysisNet.Types.IBasicType,
                IsAbstract = typedef.IsAbstract,
                IsSealed   = typedef.IsSealed
            };
            Cecil.FieldDefinition valueField = typedef.Fields.Single(f => f.Name == "value__");
            type.UnderlayingType = ExtractType(valueField.FieldType) as AnalysisNet.Types.IBasicType;

            ExtractCustomAttributes(type.Attributes, typedef.CustomAttributes);
            ExtractConstants(type, type.Fields, typedef.Fields);

            return(type);
        }
Exemple #43
0
        private Cecil.TypeDefinition CreateEnumDefinition(AnalysisNet.Types.TypeDefinition typeDefinition)
        {
            Cecil.TypeDefinition def = CreateClassDefinition(typeDefinition);
            def.IsSealed = true;
            foreach (Cecil.FieldDefinition field in def.Fields)
            {
                field.IsStatic              = true;
                field.IsLiteral             = true;
                field.HasDefault            = true;
                field.FieldType.IsValueType = true;
            }

            Cecil.TypeReference   underlyingType = ReferenceGenerator.TypeReference(typeDefinition.UnderlayingType);
            Cecil.FieldDefinition value__        = new Cecil.FieldDefinition("value__", Cecil.FieldAttributes.RTSpecialName | Cecil.FieldAttributes.SpecialName, underlyingType);
            def.Fields.Insert(0, value__);

            return(def);
        }
Exemple #44
0
        internal static TargetMemberAccessibility GetAccessibility(Cecil.FieldDefinition field)
        {
            switch (field.Attributes & Cecil.FieldAttributes.FieldAccessMask)
            {
            case Cecil.FieldAttributes.Public:
                return(TargetMemberAccessibility.Public);

            case Cecil.FieldAttributes.Family:
            case Cecil.FieldAttributes.FamANDAssem:
                return(TargetMemberAccessibility.Protected);

            case Cecil.FieldAttributes.Assembly:
            case Cecil.FieldAttributes.FamORAssem:
                return(TargetMemberAccessibility.Internal);

            default:
                return(TargetMemberAccessibility.Private);
            }
        }
Exemple #45
0
        private static bool IsVolatile(FieldDefinition field)
        {
            bool isVolatile           = false;
            TypeSpecification modtype = field.FieldType as TypeSpecification;

            while (modtype != null)
            {
                if (modtype.IsRequiredModifier)
                {
                    var req = (RequiredModifierType)modtype;
                    if (req.ModifierType.Name == "IsVolatile")
                    {
                        isVolatile = true;
                        break;
                    }
                }
                modtype = modtype.ElementType as TypeSpecification;
            }
            return(isVolatile);
        }
        private static bool IsDecimalConstant(Mono.Cecil.FieldDefinition field)
        {
            var fieldType = field.FieldType;

            if (fieldType.Name == "Decimal" && fieldType.Namespace == "System")
            {
                if (field.HasCustomAttributes)
                {
                    var attrs = field.CustomAttributes;
                    for (int i = 0; i < attrs.Count; i++)
                    {
                        var attrType = attrs[i].AttributeType;
                        if (attrType.Name == "DecimalConstantAttribute" && attrType.Namespace == "System.Runtime.CompilerServices")
                        {
                            return(true);
                        }
                    }
                }
            }
            return(false);
        }
Exemple #47
0
        public static MonoDevelop.Projects.Dom.Modifiers GetModifiers(Mono.Cecil.FieldDefinition field)
        {
            MonoDevelop.Projects.Dom.Modifiers result = MonoDevelop.Projects.Dom.Modifiers.None;
            if (field.IsStatic)
            {
                result |= Modifiers.Static;
            }

            if (field.IsLiteral)
            {
                result |= Modifiers.Literal;
            }

            if (field.IsInitOnly)
            {
                result |= Modifiers.Readonly;
            }

            if (field.IsPublic)
            {
                result |= Modifiers.Public;
            }
            else if (field.IsPrivate)
            {
                result |= Modifiers.Private;
            }
            else
            {
                result |= Modifiers.Protected;
            }
            if (field.IsSpecialName)
            {
                result |= Modifiers.SpecialName;
            }
            if (field.IsAssembly)
            {
                result |= Modifiers.Internal;
            }
            return(result);
        }
        private static uint GetFieldOffset(Mono.Cecil.FieldDefinition field)
        {
            uint offset = MonoObjectHeaderLength; // Skip this many bytes

            if (field.Offset >= 0)
            {
                // Explicit struct layout
                return(offset + (uint)field.Offset);
            }

            foreach (var typeField in field.DeclaringType.Fields)
            {
                if (typeField == field)
                {
                    return(offset);
                }

                offset += GetTypeStackSize(typeField.FieldType);
            }

            throw new InvalidOperationException($"Somehow, field {field.FullName} was not declared on its declaring type.");
        }
Exemple #49
0
        public bool ProcessFieldDefinition(Mono.Cecil.FieldDefinition fieldToProcess)
        {
            TypeDefinition typeDefinition = fieldToProcess.FieldType as TypeDefinition;

            if (typeDefinition != null)
            {
                IEnumerable <CustomAttribute> fieldsWithDelgateAttributes = typeDefinition.CustomAttributes.Where(x => x.AttributeType.FullName == "Machine.Specifications.DelegateUsageAttribute");

                if (fieldsWithDelgateAttributes.Count() > 0)
                {
                    bool hasAssertAttributes = fieldsWithDelgateAttributes.Any(x => x.ConstructorArguments.Any(y => y.Type.FullName == "Machine.Specifications.DelegateUsage" && (int)y.Value == 3));
                    return(hasAssertAttributes);
                }

                fieldsWithDelgateAttributes = typeDefinition.CustomAttributes.Where(x => x.AttributeType.FullName == "Machine.Specifications.AssertDelegateAttribute");
                if (fieldsWithDelgateAttributes.Count() > 0)
                {
                    return(true);
                }
            }
            return(false);
        }
 protected override bool ShouldImplementField(FieldDefinition field)
 {
     return(false);
 }
 public void AddFieldDefinition(FieldDefinition field)
 {
     Fields [field.token.RID - 1] = field;
 }
Exemple #52
0
 public Field_Common_CLRSharp(Type_Common_CLRSharp type, Mono.Cecil.FieldDefinition field)
 {
     this.field          = field;
     this.FieldType      = type.env.GetType(field.FieldType.FullName);
     this._DeclaringType = type;
 }
Exemple #53
0
 /// <summary>
 /// Set the field type of the given dex field.
 /// </summary>
 protected virtual void SetFieldType(DexLib.FieldDefinition dfield, FieldDefinition field, DexTargetPackage targetPackage)
 {
     dfield.Type = field.FieldType.GetReference(targetPackage, compiler.Module);
 }
Exemple #54
0
 void EmitInstruction(ILGenerator il, OpCode opcode, Cecil.FieldDefinition operand)
 {
     EmitInstruction(il, opcode, (Cecil.FieldReference)operand);
 }
Exemple #55
0
        /// <summary>
        /// Create a method definition for the builder method that builds a custom attribute from an annotation.
        /// </summary>
        private static MethodDefinition CreateBuildMethod(
            ISourceLocation seqp,
            Mono.Cecil.MethodDefinition ctor,
            List <MethodDefinition> paramGetMethods,
            AssemblyCompiler compiler,
            DexTargetPackage targetPackage,
            ClassDefinition attributeClass,
            AttributeAnnotationInterface mapping)
        {
            // Create method definition
            string           name             = CreateBuildMethodName(attributeClass);
            TypeReference    attributeTypeRef = ctor.DeclaringType.GetReference(targetPackage, compiler.Module);
            MethodDefinition method           = new MethodDefinition(attributeClass, name, new Prototype(attributeTypeRef, new Parameter(mapping.AnnotationInterfaceClass, "ann")));

            method.AccessFlags = AccessFlags.Public | AccessFlags.Static | AccessFlags.Synthetic;
            attributeClass.Methods.Add(method);

            // Create method body
            MethodBody body          = new MethodBody(null);
            Register   annotationReg = body.AllocateRegister(RCategory.Argument, RType.Object);
            //body.Instructions.Add(seqp, RCode.Check_cast, mapping.AnnotationInterfaceClass, annotationReg);

            // Allocate attribute
            Register attributeReg = body.AllocateRegister(RCategory.Temp, RType.Object);

            body.Instructions.Add(seqp, RCode.New_instance, attributeClass, attributeReg);

            // Get ctor arguments
            List <Register> ctorArgRegs = new List <Register>();

            foreach (MethodDefinition p in paramGetMethods)
            {
                TypeReference paramType = p.Prototype.ReturnType;
                Register[]    valueRegs = CreateLoadValueSequence(seqp, body, paramType, annotationReg, p);
                ctorArgRegs.AddRange(valueRegs);
            }

            // Invoke ctor
            DexLib.MethodReference dctor = ctor.GetReference(targetPackage, compiler.Module);
            body.Instructions.Add(seqp, RCode.Invoke_direct, dctor, new[] { attributeReg }.Concat(ctorArgRegs).ToArray());

            // Get field values
            foreach (var fieldMap in mapping.FieldToGetMethodMap)
            {
                Mono.Cecil.FieldDefinition field  = fieldMap.Key;
                MethodDefinition           getter = fieldMap.Value;
                Register[]            valueRegs   = CreateLoadValueSequence(seqp, body, getter.Prototype.ReturnType, annotationReg, getter);
                DexLib.FieldReference dfield      = field.GetReference(targetPackage, compiler.Module);
                XModel.XTypeReference xFieldType  = XBuilder.AsTypeReference(compiler.Module, field.FieldType);
                body.Instructions.Add(seqp, xFieldType.IPut(), dfield, valueRegs[0], attributeReg);
            }

            // Get property values
            foreach (var propertyMap in mapping.PropertyToGetMethodMap)
            {
                PropertyDefinition       property   = propertyMap.Key;
                MethodDefinition         getter     = propertyMap.Value;
                Register[]               valueRegs  = CreateLoadValueSequence(seqp, body, getter.Prototype.ReturnType, annotationReg, getter);
                DexLib.MethodReference   dmethod    = property.SetMethod.GetReference(targetPackage, compiler.Module);
                XModel.XMethodDefinition xSetMethod = XBuilder.AsMethodDefinition(compiler.Module, property.SetMethod);
                body.Instructions.Add(seqp, xSetMethod.Invoke(xSetMethod, null), dmethod, new[] { attributeReg }.Concat(valueRegs).ToArray());
            }

            // Return attribute
            body.Instructions.Add(seqp, RCode.Return_object, attributeReg);

            // Register method body
            targetPackage.Record(new CompiledMethod()
            {
                DexMethod = method, RLBody = body
            });

            // Return method
            return(method);
        }
Exemple #56
0
        public static void InstrumentType(Cecil.TypeDefinition type)
        {
            foreach (var method in type.Methods)
            {
                if (!method.HasBody)
                {
                    continue;
                }

                if (method.IsConstructor)
                {
                    continue;
                }

                if (method.IsStatic)
                {
                    continue;
                }

                var fieldName = method.GetHotpatchFieldName();
                if (type.Fields.Any(f => f.Name == fieldName))
                {
                    Debug.LogWarningFormat("{0} already instrumented", method.FullName);
                    continue;
                }

                if (method.HasGenericParameters)
                {
                    Debug.LogWarningFormat("{0} cannot be instrumented - generic parameters", method.FullName);
                    continue;
                }

                if (method.Parameters.Any(p => p.IsOut || p.ParameterType.IsByReference))
                {
                    Debug.LogWarningFormat("{0} cannot be instrumented - out/ref arguments", method.FullName);
                    continue;
                }

                //Create delegate type and static field in class
                var del   = type.Module.Import(typeof(RefEmit.DynamicMethod));
                var field = new Cecil.FieldDefinition(fieldName, Cecil.FieldAttributes.Private, del);
                field.IsStatic = true;
                type.Fields.Add(field);

                //Instrument method code to check for delegate field and call it instead
                var objType       = type.Module.TypeSystem.Object;
                var voidType      = type.Module.TypeSystem.Void;
                var objArrayType  = type.Module.Import(typeof(object[]));
                var dynamicInvoke = type.Module.Import(typeof(RefEmit.DynamicMethod).GetMethod("Invoke", new Type[] { typeof(object), typeof(object[]) }));

                var argArrayVar = new Cecil.Cil.VariableDefinition(objArrayType);
                method.Body.Variables.Add(argArrayVar);

                var ilproc   = method.Body.GetILProcessor();
                var firstins = ilproc.Body.Instructions[0];

                Action <Cecil.Cil.Instruction> emit = (ins) => ilproc.InsertBefore(firstins, ins);

                //var writeLineMethod = typeof(UnityEngine.Debug).GetMethod("Log", new Type[]{typeof(string)});
                //var writeLine = type.Module.Import(writeLineMethod);

                //emit(ilproc.Create(OpCodes.Ldstr, "Hello " + method.FullName));
                //emit(ilproc.Create(OpCodes.Call, writeLine));

                //Check if delegate field is not null
                emit(ilproc.Create(OpCodes.Ldsfld, field));
                emit(ilproc.Create(OpCodes.Ldnull));
                emit(ilproc.Create(OpCodes.Ceq));

                //If null, branch to original function
                emit(ilproc.Create(OpCodes.Brtrue, firstins));

                //Create object[] args array
                emit(ilproc.Create(OpCodes.Ldc_I4, method.Parameters.Count + 1));
                emit(ilproc.Create(OpCodes.Newarr, objType));
                emit(ilproc.Create(OpCodes.Stloc, argArrayVar));

                //Store this at args[0]
                emit(ilproc.Create(OpCodes.Ldloc, argArrayVar));
                emit(ilproc.Create(OpCodes.Ldc_I4_0));   //index[0]
                emit(ilproc.Create(OpCodes.Ldarg_0));    //arg[0] (this)
                emit(ilproc.Create(OpCodes.Stelem_Ref)); //store ref

                for (int i = 0; i < method.Parameters.Count; i++)
                {
                    var p = method.Parameters[i];
                    //Store parameters in args array
                    emit(ilproc.Create(OpCodes.Ldloc, argArrayVar));
                    emit(ilproc.Create(OpCodes.Ldc_I4, i + 1)); //index[i + 1]
                    emit(ilproc.Create(OpCodes.Ldarg, i + 1));  //arg[i + 1]
                    if (p.ParameterType.IsValueType)
                    {
                        emit(ilproc.Create(OpCodes.Box, p.ParameterType));
                    }
                    emit(ilproc.Create(OpCodes.Stelem_Ref)); //store ref
                }

                //Call delegate
                emit(ilproc.Create(OpCodes.Ldsfld, field));
                emit(ilproc.Create(OpCodes.Ldarg_0)); //arg[0] (this)
                emit(ilproc.Create(OpCodes.Ldloc, argArrayVar));
                emit(ilproc.Create(OpCodes.Callvirt, dynamicInvoke));

                //Handle return value
                if (method.ReturnType != voidType)
                {
                    if (method.ReturnType.IsValueType)
                    {
                        emit(ilproc.Create(OpCodes.Unbox_Any, method.ReturnType));
                    }
                }
                else
                {
                    //Discard dynamicInvoke result
                    emit(ilproc.Create(OpCodes.Pop));
                }

                //Return
                emit(ilproc.Create(OpCodes.Ret));
            }
        }
Exemple #57
0
 /// <summary>
 /// Should the given field be implemented?
 /// </summary>
 protected override bool ShouldImplementField(ILFieldDefinition field)
 {
     return(field.Name != NameConstants.Enum.ValueFieldName);
 }
        public static string Disassemble(DomCecilMethod method, bool markup)
        {
            if (method.MethodDefinition.IsPInvokeImpl)
            {
                return(GettextCatalog.GetString("Method is P/Invoke"));
            }
            if (method.MethodDefinition.Body == null)
            {
                IType type = method.DeclaringType;
                return(type == null ||  type.ClassType == ClassType.Interface ? GettextCatalog.GetString("Interface method") : GettextCatalog.GetString("Abstract method"));
            }

            StringBuilder result = new StringBuilder();

            foreach (Instruction instruction in method.MethodDefinition.Body.Instructions)
            {
                if (markup)
                {
                    result.Append("<b>");
                }
                result.Append(GetInstructionOffset(instruction));
                result.Append(markup ? ":</b> " : ": ");
                result.Append(instruction.OpCode);
                if (markup)
                {
                    result.Append("<i>");
                }
                if (instruction.Operand != null)
                {
                    result.Append(' ');
                    if (instruction.Operand is string)
                    {
                        result.Append('"');
                        result.Append(AssemblyBrowserWidget.FormatText(instruction.Operand.ToString()));
                        result.Append('"');
                    }
                    else if (instruction.Operand is Mono.Cecil.Cil.Instruction)
                    {
                        result.Append(GetInstructionOffset((Mono.Cecil.Cil.Instruction)instruction.Operand));
                    }
                    else if (instruction.Operand is Mono.Cecil.TypeDefinition)
                    {
                        AppendLink(result,
                                   new DomCecilType((Mono.Cecil.TypeDefinition)instruction.Operand).HelpUrl,
                                   instruction.Operand.ToString());
                    }
                    else if (instruction.Operand is Mono.Cecil.MethodDefinition)
                    {
                        Mono.Cecil.MethodDefinition md = instruction.Operand as Mono.Cecil.MethodDefinition;
                        AppendLink(result,
                                   new DomCecilMethod(md)
                        {
                            DeclaringType = new DomCecilType(md.DeclaringType)
                        }.HelpUrl,
                                   instruction.Operand.ToString());
                    }
                    else if (instruction.Operand is Mono.Cecil.FieldDefinition)
                    {
                        Mono.Cecil.FieldDefinition fd = instruction.Operand as Mono.Cecil.FieldDefinition;
                        AppendLink(result,
                                   new DomCecilField(fd)
                        {
                            DeclaringType = new DomCecilType(fd.DeclaringType)
                        }.HelpUrl,
                                   instruction.Operand.ToString());
                    }
                    else if (instruction.Operand is Mono.Cecil.PropertyDefinition)
                    {
                        Mono.Cecil.PropertyDefinition pd = instruction.Operand as Mono.Cecil.PropertyDefinition;
                        AppendLink(result,
                                   new DomCecilProperty(pd)
                        {
                            DeclaringType = new DomCecilType(pd.DeclaringType)
                        }.HelpUrl,
                                   instruction.Operand.ToString());
                    }
                    else if (instruction.Operand is Mono.Cecil.TypeReference)
                    {
                        AppendLink(result,
                                   "T:" + ((TypeReference)instruction.Operand).FullName,
                                   instruction.Operand.ToString());
                    }
                    else if (instruction.Operand is Mono.Cecil.MethodReference)
                    {
                        Mono.Cecil.MethodReference mr = instruction.Operand as Mono.Cecil.MethodReference;
                        StringBuilder id            = new StringBuilder(mr.DeclaringType.ToString());
                        bool          isConstructor = mr.Name == ".ctor";
                        if (!isConstructor)
                        {
                            id.Append("." + mr.Name);
                        }
                        id.Append("(");
                        for (int i = 0; i < mr.Parameters.Count; i++)
                        {
                            if (i > 0)
                            {
                                id.Append(',');
                            }
                            id.Append(mr.Parameters[i].ParameterType.FullName);
                        }
                        id.Append(")");
                        AppendLink(result, (isConstructor ? "C:" : "M:") + id, id.ToString());
                    }
                    else if (instruction.Operand is Mono.Cecil.FieldReference)
                    {
                        Mono.Cecil.FieldReference fr = instruction.Operand as Mono.Cecil.FieldReference;
                        string id = fr.DeclaringType + "." + fr.Name;
                        AppendLink(result, "F:" + id, id);
                    }
                    else if (instruction.Operand is Mono.Cecil.PropertyReference)
                    {
                        Mono.Cecil.PropertyReference pr = instruction.Operand as Mono.Cecil.PropertyReference;
                        string id = pr.DeclaringType + "." + pr.Name;
                        AppendLink(result, "P:" + id, id);
                    }
                    else
                    {
                        result.Append(AssemblyBrowserWidget.FormatText(instruction.Operand.ToString()));
                    }
                }
                if (markup)
                {
                    result.Append("</i>");
                }
                result.AppendLine();
            }
            result.AppendLine();
            return(result.ToString());
        }
Exemple #59
0
 /// <summary>
 /// Default ctor
 /// </summary>
 protected FieldBuilder(AssemblyCompiler compiler, FieldDefinition field)
 {
     this.compiler = compiler;
     this.field    = field;
 }