public override int CompareTo(Cil.ISingleEntrySubGraph other)
        {
            PartialCFGBlockLogicalConstruct otherPartial = (other as ILogicalConstruct).FirstBlock as PartialCFGBlockLogicalConstruct;
            if(otherPartial != null)
            {
                if(this.Index == otherPartial.Index)
                {
                    if(this == otherPartial)
                    {
                        return 0;
                    }

                    PartialCFGBlockLogicalConstruct currentPartial = this;
                    while (currentPartial != null && currentPartial.Index == this.Index)
                    {
                        if(currentPartial == otherPartial)
                        {
                            return -1;
                        }

                        if(currentPartial.CFGSuccessors.Count != 1)
                        {
                            break;
                        }

                        IEnumerator<CFGBlockLogicalConstruct> cfgSuccessorsEnumerator = currentPartial.CFGSuccessors.GetEnumerator();
                        cfgSuccessorsEnumerator.MoveNext();
                        currentPartial = cfgSuccessorsEnumerator.Current as PartialCFGBlockLogicalConstruct;
                    }

                    return 1;
                }
            }
            return base.CompareTo(other);
        }
Exemple #2
0
        static uint Sizeof <T>()
        {
            Cil.Sizeof <T>();
            Cil.Ret();

            return(0);
        }
        protected override ControllerTraversalSearchResult TryGetStateEntry(Cil.InstructionBlock theBlock, out Cil.InstructionBlock actualSuccessor)
        {
            actualSuccessor = SkipBranchChain(theBlock);

            if (!IsDisposingBlock(actualSuccessor))
            {
                return ControllerTraversalSearchResult.FoundControllerCandidate;
            }

            toBeRemoved.Add(actualSuccessor);
            if (IsFalseReturnBlock(actualSuccessor.Successors[1])) //more likely to be the near successor
            {
                toBeRemoved.Add(actualSuccessor.Successors[1]);
                actualSuccessor = actualSuccessor.Successors[0];
            }
            else if (IsFalseReturnBlock(actualSuccessor.Successors[0]))
            {
                toBeRemoved.Add(actualSuccessor.Successors[0]);
                actualSuccessor = actualSuccessor.Successors[1];
            }
            else
            {
                return ControllerTraversalSearchResult.PatternFailed;
            }

            return ControllerTraversalSearchResult.FoundStateEntry;
        }
Exemple #4
0
        public void Execute(AdviceSpec spec)
        {
            foreach (Navigator aspectNav in spec.AspectNavigators)
            {
                IMethodDefinition aspectMethod = Narrow.Interceptor(aspectNav, spec);
                foreach (Navigator targetNav in spec.TargetNavigators)
                {
                    Instruction      targetCallInstruction = Narrow.CallInstruction(targetNav, spec);
                    MethodReference  targetMethod          = (MethodReference)targetCallInstruction.Operand;
                    MethodDefinition containerMethod       = Narrow.Method(targetNav.Parent, spec);

                    // Prevent recursive weaving
                    if (targetMethod != aspectMethod &&
                        containerMethod != aspectMethod &&
                        !Cil.BelongsToAspectDng(targetMethod) &&
                        !Cil.BelongsToAspectDng(aspectMethod) &&
                        !Cil.BelongsToAspectDng(containerMethod) &&
                        targetMethod.GenericParameters.Count == 0 &&
                        targetMethod.DeclaringType.GenericParameters.Count == 0)
                    {
                        // Cannot weave on acces to boxed arrays. Methods look like int32[0...,0...]::Get(int32, int32)
                        if (targetMethod.DeclaringType.Name.IndexOf("]") == -1 &&
                            targetMethod.ToString().IndexOf("&") == -1
                            // To prevent base.SameMethod() calls from child types, event if AroundBody already occurred
                            && Cil.GetOriginalMethodName(targetMethod) != Cil.GetOriginalMethodName(containerMethod)
                            )
                        {
                            AddInterceptor(targetCallInstruction, containerMethod, aspectMethod);
                        }
                    }
                }
            }
        }
Exemple #5
0
        public void Execute(AdviceSpec spec)
        {
            foreach (Navigator aspectNav in spec.AspectNavigators)
            {
                IMethodDefinition aspectMethod = Narrow.Interceptor(aspectNav, spec);
                foreach (Navigator targetNav in spec.TargetNavigators)
                {
                    MethodDefinition targetMethod = Narrow.ConcreteMethod(targetNav, spec);

                    // Prevent recursive weaving
                    if (targetMethod != aspectMethod &&
                        !Cil.BelongsToAspectDng(targetMethod) &&
                        !Cil.BelongsToAspectDng(aspectMethod) &&
                        targetMethod.GenericParameters.Count == 0 &&
                        targetMethod.DeclaringType.GenericParameters.Count == 0)
                    {
                        // Cannot keep semantics of "ref" parameters
                        if (targetMethod.ToString().IndexOf("&") == -1)
                        {
                            AddInterceptor(targetMethod, aspectMethod);
                        }
                    }
                }
            }
        }
Exemple #6
0
 static void CopyTo <T>(IntPtr dst, T value)
 {
     Cil.Ldarg(0);
     Cil.Ldarga(1);
     Cil.Sizeof <T>();
     Cil.Cpblk();
 }
Exemple #7
0
        private void Weave(string configFile)
        {
            AspectDngConfig conf = new AspectDngConfig(configFile);

            if (!File.Exists(conf.TargetAssembly))
            {
                throw new ConfigurationException("File doesn't exist: " + conf.TargetAssembly);
            }
            if (!File.Exists(conf.AspectsAssembly))
            {
                throw new ConfigurationException("File doesn't exist: " + conf.AspectsAssembly);
            }

            string backup = CopyToBackup(conf.TargetAssembly);

            if (conf.TargetAssembly == conf.AspectsAssembly || conf.AspectsAssembly == null || conf.AspectsAssembly == "")
            {
                Cil.Init(backup, backup);
            }
            else
            {
                Cil.Init(backup, conf.AspectsAssembly);
            }

            PerformWeave();
            Cil.SaveTo(conf.WeavedAssembly);
        }
Exemple #8
0
        static Hashtable GetInstructions(Cil.MethodBody body)
        {
            Hashtable instructions = new Hashtable (body.Instructions.Count);
            foreach (Cil.Instruction i in body.Instructions)
                instructions.Add (i.Offset, i);

            return instructions;
        }
Exemple #9
0
        static Cil.Instruction GetInstruction(Cil.MethodBody body, Hashtable instructions, int offset)
        {
            Cil.Instruction instr = (Cil.Instruction) instructions [offset];
            if (instr != null)
                return instr;

            return body.Instructions.Outside;
        }
Exemple #10
0
		public void Read (Cil.MethodBody body, IDictionary instructions)
		{
			try {
				ISymbolMethod method = m_reader.GetMethod (new SymbolToken ((int) body.Method.MetadataToken.ToUInt ()));

				ReadSequencePoints (method, instructions);
				ReadScopeAndLocals (method.RootScope, null, body, instructions);
			} catch (COMException) {}
		}
Exemple #11
0
 public void Execute(AdviceSpec spec)
 {
     foreach (Navigator targetNav in spec.TargetNavigators)
     {
         foreach (Navigator aspectNav in spec.AspectNavigators)
         {
             Cil.CopyTo(targetNav.Current, (ICloneable)aspectNav.Current);
         }
     }
 }
Exemple #12
0
        private void DirectWeave(string targetAssemblyPath)
        {
            if (!File.Exists(targetAssemblyPath))
            {
                throw new ConfigurationException("File doesn't exist: " + targetAssemblyPath);
            }

            string backup = CopyToBackup(targetAssemblyPath);

            Cil.Init(backup, backup);
            PerformWeave();
            Cil.SaveTo(targetAssemblyPath);
        }
Exemple #13
0
		static void ReadScopeAndLocals (ISymbolScope scope, Cil.Scope parent, Cil.MethodBody body, IDictionary instructions)
		{
			Cil.Scope s = new Cil.Scope ();
			s.Start = GetInstruction (body, instructions, scope.StartOffset);
			s.End = GetInstruction (body, instructions, scope.EndOffset);

			if (parent != null)
				parent.Scopes.Add (s);
			else
				body.Scopes.Add (s);

			foreach (ISymbolVariable local in scope.GetLocals ()) {
				Cil.VariableDefinition variable = body.Variables [local.AddressField1];
				variable.Name = local.Name;

				s.Variables.Add (variable);
			}

			foreach (ISymbolScope child in scope.GetChildren ())
				ReadScopeAndLocals (child, s, body, instructions);
		}
        public void Cleanup()
        {
            foreach (ToBeWeaved tbw in Map.Values)
            {
                Instruction      fieldAccessInstruction = tbw.TargetCall;
                MethodDefinition containerMethod        = tbw.ContainerMethod;
                FieldReference   field = (FieldReference)fieldAccessInstruction.Operand;

                MethodDefinition tplMethod = Cil.AspectTemplateCall.Clone();
                tplMethod.Name = field.Name + "_" + (IsGetter ? "Getter" : "Setter") + Cil.GetNextId();
                ((TypeDefinition)containerMethod.DeclaringType).Methods.Add(tplMethod);
                tplMethod.Body.InitLocals = true;
                tplMethod.Body.Instructions.Clear(); // remove ret

                // *** Inside interceptor ***
                PopulateInterceptor(tbw, fieldAccessInstruction, field, tplMethod);

                // Do nothing instead of the the previous behavior
                fieldAccessInstruction.OpCode  = OpCodes.Call;
                fieldAccessInstruction.Operand = tplMethod;
            }
        }
Exemple #15
0
        public void Cleanup()
        {
            Hashtable templateMethods             = new Hashtable();
            Hashtable templateMethodsInterceptors = new Hashtable();

            foreach (ToBeWeaved tbw in m_InterceptorsToWeave.Values)
            {
                Instruction      call            = tbw.TargetCall;
                MethodDefinition containerMethod = tbw.ContainerMethod;
                MethodReference  targetMethod    = (MethodReference)call.Operand;

                if (containerMethod != null && containerMethod.DeclaringType != null)
                {
                    MethodDefinition tplMethod = Cil.AspectTemplateCall.Clone();

                    tplMethod.Body.Instructions.Clear(); // remove ret
                    tplMethod.Name = targetMethod.Name + Joinpoints.OperationJoinPoint.WrappedMethodSuffix + "Call_" + Cil.GetNextId();
                    ((TypeDefinition)containerMethod.DeclaringType).Methods.Add(tplMethod);

                    PopulateInterceptor(tbw, call, targetMethod, tplMethod);

                    call.OpCode  = OpCodes.Call;
                    call.Operand = tplMethod;
                }
            }
        }
Exemple #16
0
        public void Cleanup()
        {
            foreach (DictionaryEntry entry in m_InterceptorsToWeave)
            {
                MethodDefinition containerMethod = entry.Key as MethodDefinition;
                TypeDefinition   containerType   = (TypeDefinition)containerMethod.DeclaringType;

                // Methods can be removed. In that case, they don't have a declaring type any more
                if (containerType != null)
                {
                    // Clone and rename the target method
                    MethodDefinition targetMethod = containerMethod.Clone();
                    targetMethod.Name                += Joinpoints.OperationJoinPoint.WrappedMethodSuffix + "Body_" + Cil.GetNextId();
                    targetMethod.IsNewSlot            = false;
                    targetMethod.IsFinal              = false;
                    targetMethod.IsRuntimeSpecialName = targetMethod.IsSpecialName = false;
                    containerType.Methods.Add(targetMethod);

                    // Clear containerMethod
                    containerMethod.Body.InitLocals = true;
                    containerMethod.Body.ExceptionHandlers.Clear();
                    containerMethod.Body.Variables.Clear();
                    containerMethod.Body.Instructions.Clear();

                    // Reify arguments and call interceptors in the original (now target) method
                    EmittingContext    ctx    = new EmittingContext(containerMethod);
                    VariableDefinition tmpObj = null;

                    if (!Cil.IsStatic(targetMethod))
                    {
                        ctx.Emit(OpCodes.Ldarg_0);

                        if (targetMethod.DeclaringType.IsValueType)
                        {
                            ctx.Emit(OpCodes.Ldobj, targetMethod.DeclaringType);
                            ctx.Emit(OpCodes.Box, targetMethod.DeclaringType);

                            // Tmp object to store boxed value types when passed along call interceptors and then unwrapped after calls
                            //tmpObj = new VariableDefinition(new ReferenceType(targetMethod.DeclaringType));
                            tmpObj = new VariableDefinition(Cil.GetTypeReference(typeof(object)));
                            containerMethod.Body.Variables.Add(tmpObj);
                            ctx.Emit(OpCodes.Stloc, tmpObj);
                            ctx.Emit(OpCodes.Ldloc, tmpObj);
                        }
                    }

                    VariableDefinition arrayDef = new VariableDefinition(Cil.GetTypeReference(typeof(object[])));
                    containerMethod.Body.Variables.Add(arrayDef);
                    ParameterDefinitionCollection containerParameters = containerMethod.Parameters;
                    ParameterDefinitionCollection targetParameters    = targetMethod.Parameters;

                    // Instantiate an array of the right size
                    ctx.Emit(OpCodes.Ldc_I4, containerParameters.Count);
                    ctx.Emit(OpCodes.Newarr, Cil.GetTypeReference(typeof(object)));
                    ctx.Emit(OpCodes.Stloc, arrayDef);

                    // Load the array with data coming from the current parameters
                    for (int i = containerParameters.Count - 1; i >= 0; i--)
                    {
                        ParameterDefinition p = containerParameters[i];
                        ctx.Emit(OpCodes.Ldloc, arrayDef);
                        ctx.Emit(OpCodes.Ldc_I4, i);
                        ctx.Emit(OpCodes.Ldarg, p);
                        Cil.BoxIfRequired(p.ParameterType, ctx);
                        ctx.Emit(OpCodes.Stelem_Ref);
                    }

                    // Pass real parameter values (taken from the stack) as the next parameter
                    ctx.Emit(OpCodes.Ldloc, arrayDef);
                    // end of Reify parameters

                    ArrayList interceptors = entry.Value as ArrayList;
                    Cil.InvokeInterceptors(containerMethod, ctx, targetMethod, interceptors);
                    Cil.UnboxIfRequired(targetMethod.ReturnType.ReturnType, ctx);

                    if (!Cil.IsStatic(targetMethod) && targetMethod.DeclaringType.IsValueType)
                    {
                        ctx.Emit(OpCodes.Ldarg_0);
                        ctx.Emit(OpCodes.Ldloc, tmpObj);
                        Cil.UnboxIfRequired(targetMethod.DeclaringType, ctx);
                        ctx.Emit(OpCodes.Stobj, targetMethod.DeclaringType);
                    }

                    // Cast (to satisfy PEVerify)
                    Cil.CastIfRequired(containerMethod.ReturnType.ReturnType, ctx);

                    ctx.Emit(OpCodes.Ret);
                }
            }
        }
Exemple #17
0
        private static void PopulateInterceptor(ToBeWeaved tbw, Instruction call, MethodReference targetMethod, MethodDefinition tplMethod)
        {
            EmittingContext    ctx    = new EmittingContext(tplMethod);
            VariableDefinition tmpObj = null;
            int offset = 0;

            // Interceptor signature must be :
            if (call.OpCode == OpCodes.Newobj)
            {
                // new object -> static ctorDeclaringType interceptor(ctorParametersList);
                tplMethod.ReturnType.ReturnType = targetMethod.DeclaringType;
                ctx.Emit(OpCodes.Ldnull); // create a brand new object, don't initialize an existing one
            }
            else if (Cil.IsStatic(targetMethod))
            {
                // call static method  -> static methodReturnType interceptor(methodParametersList);
                tplMethod.ReturnType.ReturnType = targetMethod.ReturnType.ReturnType;
            }
            else
            {
                //call instance method  -> static methodReturnType interceptor(methodDeclaringType, methodParametersList);
                tplMethod.ReturnType.ReturnType = targetMethod.ReturnType.ReturnType;
                offset = 1;
                ctx.Emit(OpCodes.Ldarg_0); // load "this", which is the first parameter of the tplMethod
                if (!targetMethod.DeclaringType.IsValueType)
                {
                    tplMethod.Parameters.Add(new ParameterDefinition(targetMethod.DeclaringType));
                }
                else
                {
                    tplMethod.Parameters.Add(new ParameterDefinition(new ReferenceType(targetMethod.DeclaringType)));

                    ctx.Emit(OpCodes.Ldobj, targetMethod.DeclaringType);
                    ctx.Emit(OpCodes.Box, targetMethod.DeclaringType);

                    // Tmp object to store boxed value types when passed along call interceptors and then unwrapped after calls
                    //                    tmpObj = new VariableDefinition(new ReferenceType(targetMethod.DeclaringType));
                    tmpObj = new VariableDefinition(Cil.GetTypeReference(typeof(object)));
                    tplMethod.Body.Variables.Add(tmpObj);
                    ctx.Emit(OpCodes.Stloc, tmpObj);
                    ctx.Emit(OpCodes.Ldloc, tmpObj);
                }
            }

            foreach (ParameterDefinition p in targetMethod.Parameters)
            {
                tplMethod.Parameters.Add(new ParameterDefinition(p.ParameterType));
            }

            ParameterDefinitionCollection tplParameters    = tplMethod.Parameters;
            ParameterDefinitionCollection targetParameters = targetMethod.Parameters;

            int nbParams = tplParameters.Count - offset;

            if (nbParams == 0)
            {
                // Load an empty array
                ctx.Emit(OpCodes.Ldnull);
            }
            else
            {
                // Instantiate an array of the right size
                VariableDefinition arrayDef = new VariableDefinition(Cil.GetTypeReference(typeof(object[])));
                tplMethod.Body.Variables.Add(arrayDef);

                ctx.Emit(OpCodes.Ldc_I4, nbParams);
                ctx.Emit(OpCodes.Newarr, Cil.GetTypeReference(typeof(object)));
                ctx.Emit(OpCodes.Stloc, arrayDef);

                // Load the array with data coming from the current parameters
                for (int i = tplParameters.Count - 1; i >= offset; i--)
                {
                    ctx.Emit(OpCodes.Ldloc, arrayDef);
                    ctx.Emit(OpCodes.Ldc_I4, i - offset);
                    ParameterDefinition p = tplParameters[i];
                    ctx.Emit(OpCodes.Ldarg, p);
                    Cil.BoxIfRequired(p.ParameterType, ctx);
                    ctx.Emit(OpCodes.Stelem_Ref);
                }
                ctx.Emit(OpCodes.Ldloc, arrayDef);
            }
            // end of reify parameters

            Cil.InvokeInterceptors(tplMethod, ctx, targetMethod, tbw.Interceptors);

            if (call.OpCode != OpCodes.Newobj)
            {
                Cil.UnboxIfRequired(targetMethod.ReturnType.ReturnType, ctx);
            }

            if (call.OpCode != OpCodes.Newobj && !Cil.IsStatic(targetMethod) && targetMethod.DeclaringType.IsValueType)
            {
                ctx.Emit(OpCodes.Ldarg_0);
                ctx.Emit(OpCodes.Ldloc, tmpObj);
                ctx.Emit(OpCodes.Unbox, targetMethod.DeclaringType);
                ctx.Emit(OpCodes.Ldobj, targetMethod.DeclaringType);
                ctx.Emit(OpCodes.Stobj, targetMethod.DeclaringType);
            }

            // Cast (to satisfy PEVerify)
            Cil.CastIfRequired(tplMethod.ReturnType.ReturnType, ctx);

            ctx.Emit(OpCodes.Ret);
        }
Exemple #18
0
        public void Generuj()
        {
            // Odstraní předešlý a vygeneruje nový požadovaný level

            // Pokud by byl problém s pamětí (ale podle ukazatele v C# tento Dispose moc paměti neušetří)
            //
            //foreach (Control ct in this.form.Controls)
            //{
            //    if (ct.BackColor == Color.Cyan) // všem PictureBoxům k odstranění se nastaví tato barva
            //        ct.Dispose();
            //}

            this.form.Controls.Clear();
            string   levelDesign = Storage.GetLevels()[this.levelNum];
            Standard s; Zrychlovaci zr; Zpomalovaci zp; Propadavaci p;
            Klic     k; Cil c;

            //vyresetování listů kvůli opakovaným restartům
            ScoreBoard.VynulujKlice();
            Blok.solidBlokList.Clear();
            Blok.zrychlovaciBlokList.Clear();
            Blok.zpomalovaciBlokList.Clear();
            Blok.propadavaciBlokList.Clear();
            Blok.klicList.Clear();

            // přidání pauzy a možnosti odejít ze hry
            this.form.Controls.Add(GameSetup.LPause);
            this.form.Controls.Add(GameSetup.LExit);

            // přidání nepřátel
            foreach (Nepritel N in Nepritel.listNepratel)
            {
                form.Controls.Add(N.postavicka);
            }

            // přidání hráče
            this.hrac.postavicka.Top  = this.hracTop;
            this.hrac.postavicka.Left = this.hracLeft;
            form.Controls.Add(hrac.postavicka);

            // přidání bloků podle level designu - jedná se o string, viz. class Storage
            for (int y = 0; y < 16; y++)
            {
                for (int x = 0; x < 32; x++)
                {
                    switch (levelDesign[x + (32 * y)])
                    {
                    case '#':
                        s = new Standard(x, y);
                        form.Controls.Add(s.pbox);
                        s.pbox.BringToFront();
                        break;

                    case 'Z':
                        zr = new Zrychlovaci(x, y);
                        form.Controls.Add(zr.pbox);
                        zr.pbox.BringToFront();
                        break;

                    case 'S':
                        zp = new Zpomalovaci(x, y);
                        form.Controls.Add(zp.pbox);
                        zp.pbox.BringToFront();
                        break;

                    case 'P':
                        p = new Propadavaci(x, y);
                        form.Controls.Add(p.pbox);
                        p.pbox.BringToFront();
                        break;

                    case 'K':
                        k = new Klic(x, y);
                        form.Controls.Add(k.pbox);
                        k.pbox.BringToFront();
                        ScoreBoard.PridejKlic();
                        break;

                    case 'C':
                        c = new Cil(x, y);
                        form.Controls.Add(c.pbox);
                        break;

                    default:
                        break;
                    }
                }
            }
            // přidání skore
            ScoreBoard.Zobraz(this.form, this.hrac);
            ScoreBoard.airBarHodnota    = ScoreBoard.airBarKapacita;
            ScoreBoard.airBar.BackColor = Color.Green;
        }
        private void PopulateInterceptor(ToBeWeaved tbw, Instruction fieldAccessInstruction, FieldReference field, MethodDefinition tplMethod)
        {
            tplMethod.ReturnType.ReturnType = IsGetter ? field.FieldType : Cil.GetTypeReference(typeof(void));

            bool isStaticField = fieldAccessInstruction.OpCode == OpCodes.Stsfld || fieldAccessInstruction.OpCode == OpCodes.Ldsfld;

            // The target object is already on the stack if we access an instance field
            if (!isStaticField)
            {
                if (field.DeclaringType.IsValueType)
                {
                    tplMethod.Parameters.Add(new ParameterDefinition(new ReferenceType(field.DeclaringType)));
                }
                else
                {
                    tplMethod.Parameters.Add(new ParameterDefinition(field.DeclaringType));
                }
            }

            // The value to assign is already on the stack as well
            if (!IsGetter)
            {
                tplMethod.Parameters.Add(new ParameterDefinition(field.FieldType));
            }

            EmittingContext ctx = new EmittingContext(tplMethod);

            VariableDefinition tmpObj = null;

            if (!isStaticField)
            {
                ctx.Emit(OpCodes.Ldarg_0); // load "this", which is the first parameter of the tplMethod

                if (field.DeclaringType.IsValueType)
                {
                    ctx.Emit(OpCodes.Ldobj, field.DeclaringType);
                    ctx.Emit(OpCodes.Box, field.DeclaringType);

                    // Tmp object to store boxed value types when passed along call interceptors and then unwrapped after calls
//                    tmpObj = new VariableDefinition(new ReferenceType(field.DeclaringType));
                    tmpObj = new VariableDefinition(Cil.GetTypeReference(typeof(object)));
                    tplMethod.Body.Variables.Add(tmpObj);
                    ctx.Emit(OpCodes.Stloc, tmpObj);
                    ctx.Emit(OpCodes.Ldloc, tmpObj);
                }

                if (!IsGetter)
                {
                    ctx.Emit(OpCodes.Ldarg, tplMethod.Parameters[1]);
                    Cil.BoxIfRequired(field.FieldType, ctx);
                }
            }
            else     // Static field
            {
                if (!IsGetter)
                {
                    ctx.Emit(OpCodes.Ldarg, tplMethod.Parameters[0]);
                    Cil.BoxIfRequired(field.FieldType, ctx);
                }
            }

            // Pass the field representation as the last parameter
            ctx.Emit(OpCodes.Ldtoken, field);
#if DOTNETTWO
            ctx.Emit(OpCodes.Ldtoken, field.DeclaringType);
            ctx.Emit(OpCodes.Call, Cil.GetGenericFieldFromHandle);
#else
            ctx.Emit(OpCodes.Call, Cil.GetFieldFromHandle);
#endif

            // Create the JoinPoint
            MethodReference joinPointFactory;
            OpCode          opCode = fieldAccessInstruction.OpCode;
            if (opCode == OpCodes.Stsfld)
            {
                joinPointFactory = Cil.StaticFieldSetterJoinPointFactory;
            }
            else if (opCode == OpCodes.Ldsfld)
            {
                joinPointFactory = Cil.StaticFieldGetterJoinPointFactory;
            }
            else if (opCode == OpCodes.Stfld)
            {
                joinPointFactory = Cil.FieldSetterJoinPointFactory;
            }
            else if (opCode == OpCodes.Ldfld)
            {
                joinPointFactory = Cil.FieldGetterJoinPointFactory;
            }
            else
            {
                throw new NotSupportedException("This kind of field accessor is not supported : " + opCode);
            }

            ctx.Emit(OpCodes.Newobj, joinPointFactory);

            // Add each interceptor
            foreach (MethodReference aspectMethod in tbw.Interceptors)
            {
                ctx.Emit(OpCodes.Ldtoken, Cil.TargetMainModule.Import(aspectMethod));
                ctx.Emit(OpCodes.Call, Cil.GetMethodFromHandle);
                ctx.Emit(OpCodes.Call, Cil.AddInterceptorMethod);
            }

            // Invoke "proceed" on the joinpoint
            ctx.Emit(OpCodes.Call, Cil.ProceedMethod);
            Cil.UnboxIfRequired(tplMethod.ReturnType.ReturnType, ctx);

            if (!isStaticField && field.DeclaringType.IsValueType)    // Unbox and update "this"
            {
                ctx.Emit(OpCodes.Ldarg_0);
                ctx.Emit(OpCodes.Ldloc, tmpObj);
                ctx.Emit(OpCodes.Unbox, field.DeclaringType);
                ctx.Emit(OpCodes.Ldobj, field.DeclaringType);
                ctx.Emit(OpCodes.Stobj, field.DeclaringType);
            }

            // Cast (to satisfy PEVerify)
            Cil.CastIfRequired(tplMethod.ReturnType.ReturnType, ctx);

            ctx.Emit(OpCodes.Ret);
        }
Exemple #20
0
        public static int Main(string[] argv)
        {
#if TEST
            AutoTest.TestSuite();
#endif
            int result = 1;
            StringCollection parameters = new StringCollection();
            parameters.AddRange(argv);

            AppDomain.CurrentDomain.AppendPrivatePath(Environment.CurrentDirectory);
            AppDomain.CurrentDomain.AppendPrivatePath(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location));

            try {
                EntryPoint entryPoint = new EntryPoint();

                if (parameters.Contains(DebugOption))   // Handle debug mode
                {
                    AspectDngConfig.Instance.debug = true;
                    parameters.Remove(DebugOption);
                }

                if (parameters.Contains(QueryOption) && parameters.Count >= 3)   // Handle query mode
                {
                    parameters.Remove(QueryOption);
                    Cil.Init(parameters[0], parameters[0]);
                    parameters.RemoveAt(0);

                    string[] array = new string[parameters.Count];
                    parameters.CopyTo(array, 0);
                    string xpath = string.Join(" ", array);
                    Console.WriteLine("\nReal XPath query:\n{0}", xpath);

                    ICollection results = Cil.TargetNavigator.SelectList(xpath);
                    Console.WriteLine("{0} results", results.Count);
                    foreach (Navigator nav in results)
                    {
                        Console.WriteLine("[" + nav.Name + "] " + nav);
                    }
                }
                else if (parameters.Contains(IlmlDumpOption) && parameters.Count == 3)     // Handle ilml mode
                {
                    parameters.Remove(IlmlDumpOption);
                    Cil.Init(parameters[0], parameters[0]);
                    parameters.RemoveAt(0);

                    // Apply XSLT to Assembly
                    XslTransform ilmlDump = new XslTransform();
                    ilmlDump.Load(new XmlTextReader(Assembly.GetExecutingAssembly().GetManifestResourceStream("IlmlDump.xsl")), null, null);
                    XmlTextWriter writer = new XmlTextWriter(parameters[0], Encoding.Unicode);
                    writer.Formatting = Formatting.Indented;
                    ilmlDump.Transform(new Navigator(Cil.TargetAssembly), null, writer, null);
                    writer.Close();
                }
                else     // Handle weave mode
                {
                    long Start = DateTime.Now.Ticks;
                    // Interpret parameters
                    if (parameters.Count > 0)
                    {
                        string firstArg = parameters[0];
                        if (firstArg.EndsWith(".xml"))
                        {
                            Log.Debug("Weaving as specified in " + firstArg);
                            entryPoint.Weave(firstArg);
                            result = 0;
                        }
                        else if (firstArg.EndsWith(".dll") || firstArg.EndsWith(".exe"))
                        {
                            if (parameters.Count == 1)
                            {
                                entryPoint.DirectWeave(firstArg);
                            }
                            else if (parameters.Count == 2)
                            {
                                string secondArg = parameters[1];
                                entryPoint.DirectWeave(firstArg, secondArg);
                            }
                            result = 0;
                        }
                        else
                        {
                            entryPoint.PrintUsage();
                        }
                    }
                    else
                    {
                        entryPoint.PrintUsage();
                    }

                    if (result == 0)
                    {
                        Log.Debug("aspectdng took in {0} millis to weave {1} aspects", (DateTime.Now.Ticks - Start) / 10000, AspectDngConfig.Instance.Advice.Count);
                        Log.Save();
                    }
                }
            } catch (ConfigurationException e) {
                Log.Error(e.Message);
            } catch (AdviceException e) {
                Log.Error(e.Message);
            } catch (Exception e) {
                Log.Error(e.Message);
                Log.Error(e.StackTrace);
            }
            return(result);
        }