internal ArgumentReferenceEmitter(IdentifierExpression identifierExpression, ParameterDefinition parameterDefinition, ILGenerator ilGenerator, IOpCodeIndexer instructionsIndexer)
            : base(ilGenerator, instructionsIndexer) {

            _parameterDefinition = parameterDefinition;
            _identifierExpression = identifierExpression;
            Type = parameterDefinition.ParameterType.GetActualType();
        }
Exemplo n.º 2
0
        public Parameter(ParameterDefinition parameterDefinition, ComponentCache componentCache) : base(parameterDefinition.ParameterType, componentCache)
        {
            Contract.Requires<ArgumentNullException>(parameterDefinition != null);

            parameter = parameterDefinition;
            cache = componentCache;
        }
        private static AssemblyDefinition CreateTestAssembly(OpCode opCode, bool invert)
        {
            var name = new AssemblyNameDefinition("TestConditionalsBoundaryTurtle", new Version(1, 0));
            var assembly = AssemblyDefinition.CreateAssembly(name, "TestClass", ModuleKind.Dll);
            var type = new TypeDefinition("TestConditionalsBoundaryTurtle", "TestClass",
                               TypeAttributes.Class | TypeAttributes.Public);
            var intType = assembly.MainModule.Import(typeof(int));
            var boolType = assembly.MainModule.Import(typeof(bool));
            var method = new MethodDefinition("TestMethod", MethodAttributes.Public, intType);
            var param = new ParameterDefinition("input", ParameterAttributes.In, intType);
            method.Parameters.Add(param);
            var resultVariable = new VariableDefinition(boolType);
            method.Body.Variables.Add(resultVariable);

            var processor = method.Body.GetILProcessor();
            Instruction loadReturnValueInstruction = processor.Create(OpCodes.Ldloc, resultVariable);
            method.Body.Instructions.Add(processor.Create(OpCodes.Ldarg, param));
            method.Body.Instructions.Add(processor.Create(OpCodes.Ldc_I4, 0));
            method.Body.Instructions.Add(processor.Create(opCode));
            if (invert)
            {
                method.Body.Instructions.Add(processor.Create(OpCodes.Ldc_I4, 0));
                method.Body.Instructions.Add(processor.Create(OpCodes.Ceq));
            }
            method.Body.Instructions.Add(processor.Create(OpCodes.Stloc, resultVariable));
            method.Body.Instructions.Add(loadReturnValueInstruction);
            method.Body.Instructions.Add(processor.Create(OpCodes.Ret));

            type.Methods.Add(method);
            assembly.MainModule.Types.Add(type);
            return assembly;
        }
		private bool UseParameter (MethodDefinition method, ParameterDefinition parameter) 
		{
			foreach (Instruction instruction in method.Body.Instructions) {
				switch (instruction.OpCode.Code) {
					case Code.Ldarg_0:
						if (method.Parameters.IndexOf (parameter) == 0)
							return true;
						break;
					case Code.Ldarg_1:
						if (method.Parameters.IndexOf (parameter) == (method.IsStatic? 1 : 0))
							return true;
						break;
					case Code.Ldarg_2:
						if (method.Parameters.IndexOf (parameter) == (method.IsStatic? 2 : 1))
							return true;
						break;
					case Code.Ldarg_3:
						if (method.Parameters.IndexOf (parameter) == (method.IsStatic? 3 : 2))
							return true;
						break;
					case Code.Ldarg_S:
						if (instruction.Operand.Equals (parameter))
							return true;
						break;
					default:
						break;
				}
			}
			return false;
		}
Exemplo n.º 5
0
    public static void LoadArgumentOntoStack(List<Instruction> instructions, ParameterDefinition parameter)
    {
        // Load the argument onto the stack
        instructions.Add(Instruction.Create(OpCodes.Ldarg, parameter));

        var elementType = parameter.ParameterType.GetElementType();

        if (parameter.ParameterType.IsByReference)
        {
            if (elementType.IsGenericParameter)
            {
                // Loads an object reference onto the stack
                instructions.Add(Instruction.Create(OpCodes.Ldobj, elementType));

                // Box the type to an object
                instructions.Add(Instruction.Create(OpCodes.Box, elementType));
            }
            else
            {
                // Loads an object reference onto the stack
                instructions.Add(Instruction.Create(OpCodes.Ldind_Ref));
            }
        }
        else if (elementType.IsGenericParameter)
        {
            // Box the type to an object
            instructions.Add(Instruction.Create(OpCodes.Box, parameter.ParameterType));
        }
    }
Exemplo n.º 6
0
    void InjectAsStreamReader(TypeDefinition targetType, FieldDefinition fieldDefinition)
    {
        AsStreamReaderMethod = new MethodDefinition("AsStreamReader", staticMethodAttributes, StreamReaderTypeReference);
        var streamVariable = new VariableDefinition(StreamTypeReference);
        AsStreamReaderMethod.Body.Variables.Add(streamVariable);
        var pathParam = new ParameterDefinition(ModuleDefinition.TypeSystem.String);
        AsStreamReaderMethod.Parameters.Add(pathParam);
        AsStreamReaderMethod.Body.InitLocals = true;
        var inst = AsStreamReaderMethod.Body.Instructions;

        var skipReturn = Instruction.Create(OpCodes.Nop);

        inst.Add(Instruction.Create(OpCodes.Ldsfld, fieldDefinition));
        inst.Add(Instruction.Create(OpCodes.Ldarg, pathParam));
        inst.Add(Instruction.Create(OpCodes.Callvirt, GetManifestResourceStreamMethod));

        inst.Add(Instruction.Create(OpCodes.Stloc, streamVariable));
        inst.Add(Instruction.Create(OpCodes.Ldloc, streamVariable));
        inst.Add(Instruction.Create(OpCodes.Brtrue_S, skipReturn));

        inst.Add(Instruction.Create(OpCodes.Ldnull));
        inst.Add(Instruction.Create(OpCodes.Ret));
        inst.Add(skipReturn);

        inst.Add(Instruction.Create(OpCodes.Ldloc, streamVariable));
        inst.Add(Instruction.Create(OpCodes.Newobj, StreamReaderConstructorReference));
        inst.Add(Instruction.Create(OpCodes.Ret));
        targetType.Methods.Add(AsStreamReaderMethod);
    }
Exemplo n.º 7
0
    MethodDefinition InjectInterceptedMethod(TypeDefinition targetType, MethodDefinition innerOnPropertyChanging)
    {
        var delegateHolderInjector = new DelegateHolderInjector
                                     {
                                         TargetTypeDefinition=targetType,
                                         OnPropertyChangingMethodReference = innerOnPropertyChanging,
                                         ModuleWeaver = this
                                     };
        delegateHolderInjector.InjectDelegateHolder();
        var method = new MethodDefinition(EventInvokerNames.First(), GetMethodAttributes(targetType), ModuleDefinition.TypeSystem.Void);

        var propertyName = new ParameterDefinition("propertyName", ParameterAttributes.None, ModuleDefinition.TypeSystem.String);
        method.Parameters.Add(propertyName);
        if (InterceptorType == InvokerTypes.Before)
        {
            var before = new ParameterDefinition("before", ParameterAttributes.None, ModuleDefinition.TypeSystem.Object);
            method.Parameters.Add(before);
        }

        var action = new VariableDefinition("firePropertyChanging", ActionTypeReference);
        method.Body.Variables.Add(action);

        var variableDefinition = new VariableDefinition("delegateHolder", delegateHolderInjector.TypeDefinition);
        method.Body.Variables.Add(variableDefinition);

        var instructions = method.Body.Instructions;

        var last = Instruction.Create(OpCodes.Ret);
        instructions.Add(Instruction.Create(OpCodes.Newobj, delegateHolderInjector.ConstructorDefinition));
        instructions.Add(Instruction.Create(OpCodes.Stloc_1));
        instructions.Add(Instruction.Create(OpCodes.Ldloc_1));
        instructions.Add(Instruction.Create(OpCodes.Ldarg_1));
        instructions.Add(Instruction.Create(OpCodes.Stfld, delegateHolderInjector.PropertyName));
        instructions.Add(Instruction.Create(OpCodes.Ldloc_1));
        instructions.Add(Instruction.Create(OpCodes.Ldarg_0));
        instructions.Add(Instruction.Create(OpCodes.Stfld, delegateHolderInjector.Target));
        instructions.Add(Instruction.Create(OpCodes.Ldloc_1));
        instructions.Add(Instruction.Create(OpCodes.Ldftn, delegateHolderInjector.MethodDefinition));
        instructions.Add(Instruction.Create(OpCodes.Newobj, ActionConstructorReference));
        instructions.Add(Instruction.Create(OpCodes.Stloc_0));
        instructions.Add(Instruction.Create(OpCodes.Ldarg_0));
        instructions.Add(Instruction.Create(OpCodes.Ldloc_0));
        instructions.Add(Instruction.Create(OpCodes.Ldloc_1));
        instructions.Add(Instruction.Create(OpCodes.Ldfld, delegateHolderInjector.PropertyName));
        if (InterceptorType == InvokerTypes.Before)
        {
            instructions.Add(Instruction.Create(OpCodes.Ldarg_2));
            instructions.Add(Instruction.Create(OpCodes.Call, InterceptMethod));
        }
        else
        {
            instructions.Add(Instruction.Create(OpCodes.Call, InterceptMethod));
        }

        instructions.Add(last);
        method.Body.InitLocals = true;

        targetType.Methods.Add(method);
        return method;
    }
        private static AssemblyDefinition CreateTestAssembly()
        {
            var name = new AssemblyNameDefinition("TestArithmeticOperatorTurtleAdd", new Version(1, 0));
            var assembly = AssemblyDefinition.CreateAssembly(name, "TestClass", ModuleKind.Dll);
            var type = new TypeDefinition("TestArithmeticOperatorTurtleAdd", "TestClass",
                               TypeAttributes.Class | TypeAttributes.Public);
            var intType = assembly.MainModule.Import(typeof(int));
            var method = new MethodDefinition("TestMethod", MethodAttributes.Public, intType);
            var leftParam = new ParameterDefinition("left", ParameterAttributes.In, intType);
            var rightParam = new ParameterDefinition("right", ParameterAttributes.In, intType);
            method.Parameters.Add(leftParam);
            method.Parameters.Add(rightParam);
            var resultVariable = new VariableDefinition(intType);
            method.Body.Variables.Add(resultVariable);

            var processor = method.Body.GetILProcessor();
            method.Body.Instructions.Add(processor.Create(OpCodes.Ldarg_1));
            method.Body.Instructions.Add(processor.Create(OpCodes.Ldarg_2));
            method.Body.Instructions.Add(processor.Create(OpCodes.Add));
            method.Body.Instructions.Add(processor.Create(OpCodes.Stloc, resultVariable));
            method.Body.Instructions.Add(processor.Create(OpCodes.Ldloc, resultVariable));
            method.Body.Instructions.Add(processor.Create(OpCodes.Ret));

            type.Methods.Add(method);
            assembly.MainModule.Types.Add(type);
            return assembly;
        }
Exemplo n.º 9
0
        public void AddConstructor(TypeDefinition adapterType,
           FieldReference targetField)
        {
            var adapterCtor = adapterType.AddDefaultConstructor();
            var adapterParameter = new ParameterDefinition(_targetDependency);
            adapterCtor.Parameters.Add(adapterParameter);

            // HACK: Remove the ret instruction from the default constructor and replace it with
            // the field setter
            var adapterBody = adapterCtor.Body;
            var adapterInstructions = adapterBody.Instructions.Cast<Instruction>().Where(i => i.OpCode != OpCodes.Ret).ToArray();
            adapterBody.Instructions.Clear();

            // Copy the old instructions
            var IL = adapterBody.CilWorker;
            foreach (var instruction in adapterInstructions)
            {
                IL.Append(instruction);
            }

            IL.Emit(OpCodes.Ldarg_0);
            IL.Emit(OpCodes.Ldarg, adapterParameter);
            IL.Emit(OpCodes.Stfld, targetField);
            IL.Emit(OpCodes.Ret);
        }
Exemplo n.º 10
0
            /// <summary>
            /// Implement IAsyncSetThis.
            /// </summary>
            private static void ImplementISetThis(TypeDefinition type, ReachableContext reachableContext)
            {
                var thisField = type.Fields.FirstOrDefault(x => x.Name.StartsWith("<>") && x.Name.EndsWith("__this"));
                if (thisField == null)
                    return;

                // Add interface
                var intfType = type.Module.Import(new TypeReference(InternalConstants.Dot42InternalNamespace, "IAsyncSetThis", type.Module, type.Module.Assembly.Name));
                type.Interfaces.Add(new InterfaceImpl(intfType));

                // Add "SetThis(object)" method
                var method = new MethodDefinition("SetThis", MethodAttributes.Public, type.Module.TypeSystem.Void);
                method.SetReachable(reachableContext);
                type.Methods.Add(method);
                var valueParam = new ParameterDefinition(type.Module.TypeSystem.Object);
                method.Parameters.Add(valueParam);
                method.Body = new MethodBody(method) { InitLocals = true };
                var seq = new ILSequence();
                seq.Emit(OpCodes.Ldarg_0); // this
                seq.Emit(OpCodes.Ldarg, valueParam);
                seq.Emit(OpCodes.Castclass, thisField.FieldType);
                seq.Emit(OpCodes.Stfld, thisField);
                seq.Emit(OpCodes.Ret);
                seq.AppendTo(method.Body);
            }
    void CreateDisposeBoolMethod()
    {
        DisposeBoolMethod = new MethodDefinition("Dispose", MethodAttributes.HideBySig | MethodAttributes.Private, typeSystem.Void);
        var disposingParameter = new ParameterDefinition("disposing", ParameterAttributes.None, typeSystem.Boolean);
        DisposeBoolMethod.Parameters.Add(disposingParameter);

        var instructions = DisposeBoolMethod.Body.Instructions;
        instructions.Add(TypeProcessor.GetDisposeEscapeInstructions());

        var skipDisposeManaged = Instruction.Create(OpCodes.Nop);
        instructions.Add(
            Instruction.Create(OpCodes.Ldarg, disposingParameter),
            Instruction.Create(OpCodes.Brfalse, skipDisposeManaged),
            Instruction.Create(OpCodes.Ldarg_0),
            Instruction.Create(OpCodes.Call, DisposeManagedMethod),
            skipDisposeManaged,
            Instruction.Create(OpCodes.Ldarg_0),
            Instruction.Create(OpCodes.Call, DisposeUnmanagedMethod)
            );

        instructions.Add(TypeProcessor.GetDisposedInstructions());
        instructions.Add(Instruction.Create(OpCodes.Ret));

        TypeProcessor.TargetType.Methods.Add(DisposeBoolMethod);
    }
        private static AssemblyDefinition CreateTestAssembly()
        {
            var name = new AssemblyNameDefinition("TestBranchConditionTurtle", new Version(1, 0));
            var assembly = AssemblyDefinition.CreateAssembly(name, "TestClass", ModuleKind.Dll);
            var type = new TypeDefinition("TestBranchConditionTurtle", "TestClass",
                               TypeAttributes.Class | TypeAttributes.Public);
            var intType = assembly.MainModule.Import(typeof(int));
            var boolType = assembly.MainModule.Import(typeof(bool));
            var method = new MethodDefinition("TestMethod", MethodAttributes.Public, intType);
            var leftParam = new ParameterDefinition("left", ParameterAttributes.In, intType);
            var rightParam = new ParameterDefinition("right", ParameterAttributes.In, intType);
            method.Parameters.Add(leftParam);
            method.Parameters.Add(rightParam);
            var resultVariable = new VariableDefinition(boolType);
            method.Body.Variables.Add(resultVariable);

            var processor = method.Body.GetILProcessor();
            Instruction loadReturnValueInstruction = processor.Create(OpCodes.Ldloc, resultVariable);
            Instruction storeTrueInReturnValueInstruction = processor.Create(OpCodes.Ldc_I4, -1);
            method.Body.Instructions.Add(processor.Create(OpCodes.Ldarg, leftParam));
            method.Body.Instructions.Add(processor.Create(OpCodes.Ldarg, rightParam));
            method.Body.Instructions.Add(processor.Create(OpCodes.Ceq));
            method.Body.Instructions.Add(processor.Create(OpCodes.Brtrue_S, storeTrueInReturnValueInstruction));
            method.Body.Instructions.Add(processor.Create(OpCodes.Ldc_I4, 0));
            method.Body.Instructions.Add(processor.Create(OpCodes.Stloc, resultVariable));
            method.Body.Instructions.Add(processor.Create(OpCodes.Br_S, loadReturnValueInstruction));
            method.Body.Instructions.Add(storeTrueInReturnValueInstruction);
            method.Body.Instructions.Add(processor.Create(OpCodes.Stloc, resultVariable));
            method.Body.Instructions.Add(loadReturnValueInstruction);
            method.Body.Instructions.Add(processor.Create(OpCodes.Ret));

            type.Methods.Add(method);
            assembly.MainModule.Types.Add(type);
            return assembly;
        }
Exemplo n.º 13
0
        internal static MethodReference MakeHostInstanceGeneric(this MethodReference self,
                                                                params TypeReference[] arguments)
        {
            var genericInstanceType = self.DeclaringType.MakeGenericInstanceType(arguments);
            var reference = new MethodReference(self.Name, self.ReturnType, genericInstanceType)
            {
                HasThis = self.HasThis,
                ExplicitThis = self.ExplicitThis,
                CallingConvention = self.CallingConvention
            };

            foreach (var parameter in self.Parameters)
            {
                // TODO: This won't work with methods that has generic arguments, since the ParameterType needs to be replaced. @asbjornu
                var parameterDefinition = new ParameterDefinition(parameter.Name,
                                                                  parameter.Attributes,
                                                                  parameter.ParameterType);
                reference.Parameters.Add(parameterDefinition);
            }

            foreach (var genericParameter in self.GenericParameters)
                reference.GenericParameters.Add(new GenericParameter(genericParameter.Name, reference));

            return reference;
        }
		public override void Run()
		{
			//Import TerrariaEntity as the base type of Terraria.Entity
			this.Type<Terraria.Entity>().BaseType = SourceDefinition.MainModule.Import(
				this.Type<OTAPI.TerrariaEntity>()
			);

			var switchTiles = this.SourceDefinition.Type("Terraria.Collision").Method("SwitchTiles");
			var iEntity = switchTiles.Module.Import(
				this.Type<IEntity>()
			);

			//Add the sender parameter to the vanilla method
			ParameterDefinition prmSender;
			switchTiles.Parameters.Add(prmSender = new ParameterDefinition("sender", ParameterAttributes.None, iEntity)
			{
				HasDefault = true,
				IsOptional = true,
				Constant = null
			});

			//Update all references to the method so the caller adds themselves (currently they are all senders, woo!)
			this.SourceDefinition.MainModule.ForEachInstruction((mth, ins) =>
			{
				if (ins.OpCode == OpCodes.Call && ins.Operand == switchTiles)
				{
					var cil = mth.Body.GetILProcessor();
					cil.InsertBefore(ins, cil.Create(OpCodes.Ldarg_0));
				}
			});
		}
		public DomCecilParameter (ParameterDefinition parameterDefinition)
		{
			this.parameterDefinition = parameterDefinition;
			base.Name                = parameterDefinition.Name;
//			base.modifiers           = DomCecilType.GetModifiers (parameterDefinition..Attributes);
			base.ReturnType          = DomCecilMethod.GetReturnType (parameterDefinition.ParameterType);
			
			if (parameterDefinition.ParameterType is Mono.Cecil.ReferenceType) {
				this.ParameterModifiers = (parameterDefinition.Attributes & ParameterAttributes.Out) == ParameterAttributes.Out ? ParameterModifiers.Out : ParameterModifiers.Ref;
			} else {
				this.ParameterModifiers = ParameterModifiers.In;
			}
			if ((parameterDefinition.Attributes & ParameterAttributes.Optional) == ParameterAttributes.Optional) 
				this.ParameterModifiers |= ParameterModifiers.Optional;
			
			if ((parameterDefinition.Attributes & ParameterAttributes.HasDefault) == ParameterAttributes.HasDefault) {
				this.DefaultValue = new System.CodeDom.CodePrimitiveExpression (parameterDefinition.Constant);
			}
			
			if (ReturnType.ArrayDimensions > 0) {
				foreach (CustomAttribute customAttribute in parameterDefinition.CustomAttributes) {
					if (customAttribute.Constructor.DeclaringType.FullName == "System.ParamArrayAttribute") 
						this.ParameterModifiers |= ParameterModifiers.Params;
				}
			}
		}
        public static MethodDefinition Execute(PropertyDefinition property_definition, MethodDefinition notify_method, DependencyMap map)
        {
            log.Trace("\t\t\t\t\tAdding collection notification method for " + property_definition.Name);

            // Create method
            TypeReference return_type = property_definition.Module.Import(typeof (void));
            MethodDefinition collection_notification = new MethodDefinition(property_definition.Name + "CollectionNotification", Mono.Cecil.MethodAttributes.Private | Mono.Cecil.MethodAttributes.HideBySig, return_type);

            // Add parameters
            TypeReference sender_type = property_definition.Module.Import(typeof(object));
            TypeReference args_type = property_definition.Module.Import(typeof(NotifyCollectionChangedEventArgs));

            ParameterDefinition sender = new ParameterDefinition("sender", Mono.Cecil.ParameterAttributes.None, sender_type);
            ParameterDefinition args = new ParameterDefinition("args", Mono.Cecil.ParameterAttributes.None, args_type);

            collection_notification.Parameters.Add(sender);
            collection_notification.Parameters.Add(args);

            // Add notifications for dependent properties
            ILProcessor processor = collection_notification.Body.GetILProcessor();
            foreach (var target in map.GetDependenciesFor(property_definition.Name))
            {
                log.Trace("\t\t\t\t\t\tAdding dependency " + target);
                processor.Emit(OpCodes.Ldarg_0);
                processor.Emit(OpCodes.Ldstr, target);
                processor.Emit(OpCodes.Call, notify_method);
            }
            processor.Emit(OpCodes.Ret);

            // Add method to class
            property_definition.DeclaringType.Methods.Add(collection_notification);
            return collection_notification;
        }
Exemplo n.º 17
0
    private static bool CheckForExistingGuard(Collection<Instruction> instructions, ParameterDefinition parameter)
    {
        for (var i = 1; i < instructions.Count - 1; i++)
        {
            if (instructions[i].OpCode == OpCodes.Newobj)
            {
                var newObjectMethodRef = instructions[i].Operand as MethodReference;

                if (newObjectMethodRef == null || instructions[i + 1].OpCode != OpCodes.Throw)
                    continue;

                // Checks for throw new ArgumentNullException("x");
                if (newObjectMethodRef.FullName == ReferenceFinder.ArgumentNullExceptionConstructor.FullName &&
                    instructions[i - 1].OpCode == OpCodes.Ldstr &&
                    (string)(instructions[i - 1].Operand) == parameter.Name)
                    return true;

                // Checks for throw new ArgumentNullException("x", "some message");
                if (newObjectMethodRef.FullName == ReferenceFinder.ArgumentNullExceptionWithMessageConstructor.FullName &&
                    i > 1 &&
                    instructions[i - 2].OpCode == OpCodes.Ldstr &&
                    (string)(instructions[i - 2].Operand) == parameter.Name)
                    return true;
            }
        }

        return false;
    }
Exemplo n.º 18
0
        public Parameter(ParameterReference parameterReference, ComponentCache componentCache) : base(parameterReference.ParameterType, componentCache)
        {
            Contract.Requires<ArgumentNullException>(parameterReference != null);

            parameter = parameterReference.Resolve();
            cache = componentCache;
        }
Exemplo n.º 19
0
 private static XParameterKind GetKind(ParameterDefinition p)
 {
     if (p.IsIn && p.IsOut)
         return XParameterKind.ByReference;
     if (p.IsOut) return XParameterKind.Output;
     return XParameterKind.Input;                
 }
Exemplo n.º 20
0
        public Cecil.MethodReference MethodReference(AnalysisNet.Types.IMethodReference methodReference)
        {
            if (methodsCache.TryGetValue(methodReference, out Cecil.MethodReference cecilMethodReference))
            {
                return(cecilMethodReference);
            }

            Cecil.TypeReference dummyReturnType = Context.CurrentModule.TypeSystem.Void;
            Cecil.TypeReference declaringType   = TypeReference(methodReference.ContainingType);

            string name = methodReference.Name;

            cecilMethodReference = new Cecil.MethodReference(name, dummyReturnType, declaringType)
            {
                HasThis = !methodReference.IsStatic
            };

            if (methodReference.GenericParameterCount > 0)
            {
                cecilMethodReference.CreateGenericParameters(methodReference.GenericParameterCount);
                MapGenericParameters(cecilMethodReference, methodReference);
                // should we add constraints?
                if (methodReference.GenericArguments.Count == 0)
                {
                    Cecil.GenericInstanceMethod instantiated = new Cecil.GenericInstanceMethod(cecilMethodReference);
                    instantiated.GenericArguments.AddRange(cecilMethodReference.GenericParameters);
                    cecilMethodReference = instantiated;
                }
                else
                {
                    IEnumerable <Cecil.TypeReference> arguments    = methodReference.GenericArguments.Select(ga => TypeReference(ga));
                    Cecil.GenericInstanceMethod       instantiated = new Cecil.GenericInstanceMethod(cecilMethodReference);
                    instantiated.GenericArguments.AddRange(arguments);
                    cecilMethodReference = instantiated;
                }
            }

            cecilMethodReference.ReturnType = TypeReference(methodReference.ReturnType);

            foreach (AnalysisNet.Types.IMethodParameterReference parameter in methodReference.Parameters)
            {
                Cecil.ParameterDefinition cecilParam = new Cecil.ParameterDefinition(TypeReference(parameter.Type));
                if (parameter.Kind == AnalysisNet.Types.MethodParameterKind.In)
                {
                    cecilParam.IsIn = true;
                }
                else if (parameter.Kind == AnalysisNet.Types.MethodParameterKind.Out)
                {
                    cecilParam.IsOut = true;
                }

                cecilMethodReference.Parameters.Add(cecilParam);
            }

            cecilMethodReference          = Context.CurrentModule.ImportReference(cecilMethodReference);
            methodsCache[methodReference] = cecilMethodReference;

            return(cecilMethodReference);
        }
Exemplo n.º 21
0
            /// <summary>
            /// Create a CopyFrom method.
            /// </summary>
            private static MethodDefinition CreateCopyFromMethod(ReachableContext reachableContext, TypeDefinition type)
            {
                var typeSystem = type.Module.TypeSystem;
                var method = new MethodDefinition(NameConstants.Struct.CopyFromMethodName, MethodAttributes.Public, type);
                var sourceParam = new ParameterDefinition(type);
                method.Parameters.Add(sourceParam);
                method.DeclaringType = type;

                var body = new MethodBody(method);
                body.InitLocals = true;
                method.Body = body;

                // Prepare code
                var seq = new ILSequence();
                seq.Emit(OpCodes.Nop);

                // Call base CopyFrom
                var baseType = (type.BaseType != null) ? type.BaseType.GetElementType().Resolve() : null;
                if ((baseType != null) && baseType.IsValueType && (baseType.FullName != "System.ValueType"))
                {
                    var baseMethod = new MethodReference(NameConstants.Struct.CopyFromMethodName, baseType, baseType) { HasThis = true };
                    baseMethod.Parameters.Add(new ParameterDefinition(baseType));
                    seq.Emit(OpCodes.Ldarg, sourceParam);
                    seq.Emit(OpCodes.Call, baseMethod);
                }

                // Copy all fields
                foreach (var field in type.Fields.Where(x => !x.IsStatic))
                {
                    // Not need to bother with cloning struct-type fields here, 
                    // as this will be done automatically by one of the Converters.

                    // Prepare for stfld
                    seq.Emit(OpCodes.Ldarg, body.ThisParameter);

                    // Load from source
                    seq.Emit(OpCodes.Ldarg, sourceParam);
                    seq.Emit(OpCodes.Ldfld, field);

                    // Save in this
                    seq.Emit(OpCodes.Stfld, field);
                }

                // Return this
                seq.Emit(OpCodes.Ldarg, body.ThisParameter);
                seq.Emit(OpCodes.Ret);

                // Append ret sequence
                seq.AppendTo(body);

                // Update offsets
                body.ComputeOffsets();

                // Add method
                type.Methods.Add(method);
                method.SetReachable(reachableContext);

                return method;
            }        
Exemplo n.º 22
0
		public SsaVariable(SsaVariable original, string newName)
		{
			Name = newName;
			IsStackLocation = original.IsStackLocation;
			OriginalVariableIndex = original.OriginalVariableIndex;
			Parameter = original.Parameter;
			Variable = original.Variable;
		}
Exemplo n.º 23
0
 /// <summary>
 /// Initializes a new instance of the <see cref="DocumentedParameter"/> class.
 /// </summary>
 /// <param name="definition">The parameter definition.</param>
 /// <param name="comment">The parameter comment.</param>
 /// <param name="metadata">The associated metadata.</param>
 public DocumentedParameter(ParameterDefinition definition, ParamComment comment, IDocumentationMetadata metadata)
     : base(MemberClassification.Parameter,  null, null, null, metadata)
 {
     _definition = definition;
     _comment = comment;
     _isOutParameter = definition.IsOut;
     _isRefParameter = definition.ParameterType is ByReferenceType;
 }
Exemplo n.º 24
0
        public static string ToGlslParamType(ParameterDefinition p)
        {
            var t = p.ParameterType.Resolve().ToGlsl();
            if (p.ParameterType.IsByReference)
                return p.IsOut ? "out " + t : "inout " + t;

            return t;
        }
Exemplo n.º 25
0
		public SsaVariable(SsaVariable original, string newName)
		{
			this.Name = newName;
			this.IsStackLocation = original.IsStackLocation;
			this.OriginalVariableIndex = original.OriginalVariableIndex;
			this.Parameter = original.Parameter;
			this.Variable = original.Variable;
		}
        protected override Mono.Cecil.CustomAttribute GetOutAttribute(ParameterDefinition parameter)
        {
            if (parameter.IsOutParameter())
            {
                return GetInOrOutAttribute(parameter, false);
            }

            return base.GetOutAttribute(parameter);
        }
Exemplo n.º 27
0
        internal MethodDefinition(string name, MethodAttributes attrs)
            : base(name)
        {
            m_attributes = attrs;

            this.HasThis = !this.IsStatic;
            if (!IsStatic)
                m_this = new ParameterDefinition ("this", 0, (ParameterAttributes) 0, null);
        }
Exemplo n.º 28
0
		public static ParameterType From(ParameterDefinition parameter)
		{
			return new ParameterType()
			{
				Name = parameter.ParameterType.Name,
				TypeName = parameter.ParameterType.FullName,
				Type = parameter.ParameterType
			};
		}
Exemplo n.º 29
0
        protected ParameterDefinition CreateParameter()
        {
            ParameterDefinition prm = new ParameterDefinition(MethodDefinition.DeclaringType.Module.Import(TypeSpecificationEditor.SelectedTypeReference));
            prm.Name = ItemName.Text;
            prm.Attributes = (Attributes.Item as ParameterDefinition).Attributes;
            ConstantEditor.CopyStateTo(prm);

            return prm;
        }
Exemplo n.º 30
0
 public static IEnumerable<Instruction> SetInstanceFieldToMethodParameter(FieldDefinition field, ParameterDefinition parameter)
 {
     return new[]
                 {
                     Instruction.Create(OpCodes.Ldarg_0),
                     Instruction.Create(OpCodes.Ldarg_S, parameter), 
                     Instruction.Create(OpCodes.Stfld, field)
                 };
 }
Exemplo n.º 31
0
 private static ParameterDefinition AddParameter(MethodDefinition method, TypeReference typeOfParameter)
 {
     var parameter = new ParameterDefinition(
         typeOfParameter.Name, 
         ParameterAttributes.None,
         typeOfParameter);
     method.Parameters.Add(parameter);
     return parameter;
 }
Exemplo n.º 32
0
        private AnalysisNet.IInstruction ProcessLoadArgument(Cecil.Cil.Instruction op)
        {
            AnalysisNetBytecode.LoadOperation operation = OperationHelper.ToLoadOperation(op.OpCode.Code);
            AnalysisNetTac.Values.IVariable   source    = thisParameter;

            int argIdx = -1;

            switch (op.OpCode.Code)
            {
            case Mono.Cecil.Cil.Code.Ldarg_0: argIdx = 0; break;

            case Mono.Cecil.Cil.Code.Ldarg_1: argIdx = 1; break;

            case Mono.Cecil.Cil.Code.Ldarg_2: argIdx = 2; break;

            case Mono.Cecil.Cil.Code.Ldarg_3: argIdx = 3; break;
            }

            if (argIdx > -1)
            {
                if (thisParameter != null && argIdx == 0)
                {
                    source = thisParameter;
                }
                else
                {
                    int hasThis = thisParameter != null ? 1 : 0;
                    source = parameters[argIdx - hasThis];
                }
            }

            if (op.Operand is Cecil.ParameterDefinition)
            {
                Cecil.ParameterDefinition parameter = op.Operand as Cecil.ParameterDefinition;
                source = parameters[parameter.Index];
            }

            if (source == null)
            {
                throw new Exception("source cannot be null.");
            }

            AnalysisNetBytecode.LoadInstruction instruction = new AnalysisNetBytecode.LoadInstruction((uint)op.Offset, operation, source);
            return(instruction);
        }
Exemplo n.º 33
0
 private AnalysisNet.Types.MethodParameterKind GetMethodParameterKind(Cecil.ParameterDefinition parameterref)
 {
     if (parameterref.IsIn)
     {
         return(AnalysisNet.Types.MethodParameterKind.In);
     }
     else if (parameterref.IsOut)
     {
         return(AnalysisNet.Types.MethodParameterKind.Out);
     }
     else if (parameterref.ParameterType.IsByReference)
     {
         return(AnalysisNet.Types.MethodParameterKind.Ref);
     }
     else
     {
         return(AnalysisNet.Types.MethodParameterKind.Normal);
     }
 }
Exemplo n.º 34
0
        private IDictionary <AnalysisNet.ThreeAddressCode.Values.IVariable, Cecil.ParameterDefinition> CreateParameters(AnalysisNet.Types.MethodDefinition methodDefinition, Mono.Cecil.MethodDefinition methodDef)
        {
            IDictionary <AnalysisNet.ThreeAddressCode.Values.IVariable, Cecil.ParameterDefinition> parameterDefinitions = new Dictionary <AnalysisNet.ThreeAddressCode.Values.IVariable, Cecil.ParameterDefinition>();

            for (int idx = 0; idx < methodDefinition.Parameters.Count; idx++)
            {
                AnalysisNet.Types.MethodParameter methodParameter = methodDefinition.Parameters.ElementAt(idx);
                //if (methodParameter.Name.Equals("this"))
                //    continue;

                Cecil.ParameterDefinition paramDef = new Cecil.ParameterDefinition(ReferenceGenerator.TypeReference(methodParameter.Type));
                if (methodParameter.DefaultValue != null)
                {
                    paramDef.Constant   = methodParameter.DefaultValue.Value;
                    paramDef.HasDefault = true;
                }

                if (methodParameter.Kind == AnalysisNet.Types.MethodParameterKind.In)
                {
                    paramDef.IsIn = true;
                }
                else if (methodParameter.Kind == AnalysisNet.Types.MethodParameterKind.Out)
                {
                    paramDef.IsOut = true;
                }

                methodDef.Parameters.Add(paramDef);

                // map body parameters to cecil parameters
                if (methodDefinition.HasBody && methodDefinition.Body.Parameters.Count > 0)
                {
                    // body parameters contain 'this' while analysis-net's parameters do not
                    int localIdx = (methodDefinition.IsStatic ? 0 : 1) + idx;
                    AnalysisNet.ThreeAddressCode.Values.IVariable localVariable = methodDefinition.Body.Parameters.ElementAt(localIdx);
                    parameterDefinitions[localVariable] = paramDef;
                }
            }

            return(parameterDefinitions);
        }
Exemplo n.º 35
0
    public static bool EqualsReference(this Mono.Cecil.MethodDefinition definition, Mono.Cecil.MethodReference reference)
    {
        bool parameterMatch = (reference.Parameters.Count == definition.Parameters.Count);

        if (parameterMatch)
        {
            for (int i = 0; i < reference.Parameters.Count; i++)
            {
                Mono.Cecil.ParameterDefinition refParam = reference.Parameters  [i];
                Mono.Cecil.ParameterDefinition defParam = definition.Parameters [i];
                if (!refParam.ParameterType.FullName.Equals(defParam.ParameterType.FullName))
                {
                    parameterMatch = false;
                }
            }
        }

        return((reference.CallingConvention.Equals(definition.CallingConvention) &&
                (reference.DeclaringType.FullName.Equals(definition.DeclaringType.FullName)) &&
                (reference.Name.Equals(definition.Name)) &&
                (reference.ReturnType.ReturnType.FullName.Equals(definition.ReturnType.ReturnType.FullName)) &&
                (reference.GenericParameters.Count == definition.GenericParameters.Count) && parameterMatch));
    }
Exemplo n.º 36
0
 public void Remove(ParameterDefinition value)
 {
     List.Remove(value);
 }
Exemplo n.º 37
0
        unsafe void InitToken(ref OpCode code, object token, Dictionary <Mono.Cecil.Cil.Instruction, int> addr)
        {
            switch (code.Code)
            {
            case OpCodeEnum.Leave:
            case OpCodeEnum.Leave_S:
            case OpCodeEnum.Br:
            case OpCodeEnum.Br_S:
            case OpCodeEnum.Brtrue:
            case OpCodeEnum.Brtrue_S:
            case OpCodeEnum.Brfalse:
            case OpCodeEnum.Brfalse_S:
            //比较流程控制
            case OpCodeEnum.Beq:
            case OpCodeEnum.Beq_S:
            case OpCodeEnum.Bne_Un:
            case OpCodeEnum.Bne_Un_S:
            case OpCodeEnum.Bge:
            case OpCodeEnum.Bge_S:
            case OpCodeEnum.Bge_Un:
            case OpCodeEnum.Bge_Un_S:
            case OpCodeEnum.Bgt:
            case OpCodeEnum.Bgt_S:
            case OpCodeEnum.Bgt_Un:
            case OpCodeEnum.Bgt_Un_S:
            case OpCodeEnum.Ble:
            case OpCodeEnum.Ble_S:
            case OpCodeEnum.Ble_Un:
            case OpCodeEnum.Ble_Un_S:
            case OpCodeEnum.Blt:
            case OpCodeEnum.Blt_S:
            case OpCodeEnum.Blt_Un:
            case OpCodeEnum.Blt_Un_S:
                code.TokenInteger = addr[(Mono.Cecil.Cil.Instruction)token];
                break;

            case OpCodeEnum.Ldc_I4:
                code.TokenInteger = (int)token;
                break;

            case OpCodeEnum.Ldc_I4_S:
                code.TokenInteger = (sbyte)token;
                break;

            case OpCodeEnum.Ldc_I8:
                code.TokenLong = (long)token;
                break;

            case OpCodeEnum.Ldc_R4:
            {
                float val = (float)token;
                code.TokenInteger = *(int *)&val;
            }
            break;

            case OpCodeEnum.Ldc_R8:
            {
                double val = (double)token;
                code.TokenLong = *(long *)&val;
            }
            break;

            case OpCodeEnum.Stloc:
            case OpCodeEnum.Stloc_S:
            case OpCodeEnum.Ldloc:
            case OpCodeEnum.Ldloc_S:
            case OpCodeEnum.Ldloca:
            case OpCodeEnum.Ldloca_S:
            {
                Mono.Cecil.Cil.VariableDefinition vd = (Mono.Cecil.Cil.VariableDefinition)token;
                code.TokenInteger = vd.Index;
            }
            break;

            case OpCodeEnum.Ldarg_S:
            case OpCodeEnum.Ldarg:
            case OpCodeEnum.Ldarga:
            case OpCodeEnum.Ldarga_S:
            case OpCodeEnum.Starg:
            case OpCodeEnum.Starg_S:
            {
                Mono.Cecil.ParameterDefinition vd = (Mono.Cecil.ParameterDefinition)token;
                code.TokenInteger = vd.Index;
                if (HasThis)
                {
                    code.TokenInteger++;
                }
            }
            break;

            case OpCodeEnum.Call:
            case OpCodeEnum.Newobj:
            case OpCodeEnum.Ldftn:
            case OpCodeEnum.Ldvirtftn:
            case OpCodeEnum.Callvirt:
            {
                bool invalidToken;
                var  m = appdomain.GetMethod(token, declaringType, this, out invalidToken);
                if (m != null)
                {
                    if (invalidToken)
                    {
                        code.TokenInteger = m.GetHashCode();
                    }
                    else
                    {
                        code.TokenInteger = token.GetHashCode();
                    }
                }
                else
                {
                    //Cannot find method or the method is dummy
                    MethodReference _ref     = (MethodReference)token;
                    int             paramCnt = _ref.HasParameters ? _ref.Parameters.Count : 0;
                    if (_ref.HasThis)
                    {
                        paramCnt++;
                    }
                    code.TokenLong = paramCnt;
                }
            }
            break;

            case OpCodeEnum.Constrained:
            case OpCodeEnum.Box:
            case OpCodeEnum.Unbox_Any:
            case OpCodeEnum.Unbox:
            case OpCodeEnum.Initobj:
            case OpCodeEnum.Isinst:
            case OpCodeEnum.Newarr:
            case OpCodeEnum.Stobj:
            case OpCodeEnum.Ldobj:
            {
                code.TokenInteger = GetTypeTokenHashCode(token);
            }
            break;

            case OpCodeEnum.Stfld:
            case OpCodeEnum.Ldfld:
            case OpCodeEnum.Ldflda:
            {
                code.TokenLong = appdomain.GetStaticFieldIndex(token, declaringType, this);
            }
            break;

            case OpCodeEnum.Stsfld:
            case OpCodeEnum.Ldsfld:
            case OpCodeEnum.Ldsflda:
            {
                code.TokenLong = appdomain.GetStaticFieldIndex(token, declaringType, this);
            }
            break;

            case OpCodeEnum.Ldstr:
            {
                long hashCode = appdomain.CacheString(token);
                code.TokenLong = hashCode;
            }
            break;

            case OpCodeEnum.Ldtoken:
            {
                if (token is FieldReference)
                {
                    code.TokenInteger = 0;
                    code.TokenLong    = appdomain.GetStaticFieldIndex(token, declaringType, this);
                }
                else if (token is TypeReference)
                {
                    code.TokenInteger = 1;
                    code.TokenLong    = GetTypeTokenHashCode(token);
                }
                else
                {
                    throw new NotImplementedException();
                }
            }
            break;

            case OpCodeEnum.Switch:
            {
                PrepareJumpTable(token, addr);
                code.TokenInteger = token.GetHashCode();
            }
            break;
            }
        }
Exemplo n.º 38
0
 static public void Emit(this MethodBody body, OpCode instruction, ParameterDefinition parameter)
 {
     body.Add(Instruction.Create(instruction, parameter));
 }
Exemplo n.º 39
0
 public void Add(ParameterDefinition value)
 {
     List.Add(value);
 }
Exemplo n.º 40
0
 public ParameterDefinitionEventArgs(ParameterDefinition item)
 {
     m_item = item;
 }
Exemplo n.º 41
0
 static public ParameterDefinition Add(this MethodDefinition method, ParameterDefinition parameter)
 {
     method.Parameters.Add(parameter);
     return(parameter);
 }
Exemplo n.º 42
0
 public bool Contains(ParameterDefinition value)
 {
     return(List.Contains(value));
 }
Exemplo n.º 43
0
 public int IndexOf(ParameterDefinition value)
 {
     return(List.IndexOf(value));
 }
Exemplo n.º 44
0
 public virtual void VisitParameterDefinition(ParameterDefinition parameter)
 {
 }
Exemplo n.º 45
0
 public void Insert(int index, ParameterDefinition value)
 {
     List.Insert(index, value);
 }
        internal static MethodDefinition Clone(MethodDefinition meth, ImportContext context)
        {
            MethodDefinition nm = new MethodDefinition(
                meth.Name,
                RVA.Zero,
                meth.Attributes,
                meth.ImplAttributes,
                meth.HasThis,
                meth.ExplicitThis,
                meth.CallingConvention);

            context.GenericContext.Method = nm;

            foreach (GenericParameter p in meth.GenericParameters)
            {
                nm.GenericParameters.Add(GenericParameter.Clone(p, context));
            }

            nm.ReturnType.ReturnType = context.Import(meth.ReturnType.ReturnType);

            if (meth.ReturnType.HasConstant)
            {
                nm.ReturnType.Constant = meth.ReturnType.Constant;
            }

            if (meth.ReturnType.MarshalSpec != null)
            {
                nm.ReturnType.MarshalSpec = meth.ReturnType.MarshalSpec;
            }

            foreach (CustomAttribute ca in meth.ReturnType.CustomAttributes)
            {
                nm.ReturnType.CustomAttributes.Add(CustomAttribute.Clone(ca, context));
            }

            if (meth.PInvokeInfo != null)
            {
                nm.PInvokeInfo = meth.PInvokeInfo;                 // TODO: import module ?
            }
            foreach (ParameterDefinition param in meth.Parameters)
            {
                nm.Parameters.Add(ParameterDefinition.Clone(param, context));
            }
            foreach (MethodReference ov in meth.Overrides)
            {
                nm.Overrides.Add(context.Import(ov));
            }
            foreach (CustomAttribute ca in meth.CustomAttributes)
            {
                nm.CustomAttributes.Add(CustomAttribute.Clone(ca, context));
            }
            foreach (SecurityDeclaration sec in meth.SecurityDeclarations)
            {
                nm.SecurityDeclarations.Add(SecurityDeclaration.Clone(sec));
            }

            if (meth.Body != null)
            {
                nm.Body = MethodBody.Clone(meth.Body, nm, context);
            }

            return(nm);
        }