Ejemplo n.º 1
0
 private Disassembler(MethodBase method, ILStyler styler)
 {
     this._module = method.DeclaringType.Module;
     this._styler = styler;
     if (method.GetMethodBody() != null)
     {
         this._il = method.GetMethodBody().GetILAsByteArray();
     }
 }
Ejemplo n.º 2
0
 /// <summary>
 /// MethodBodyReader constructor
 /// </summary>
 /// <param name="mi">
 /// The System.Reflection defined MethodInfo
 /// </param>
 public MethodBodyReader(MethodInfo mi)
 {
     this.mi = mi;
     if (mi.GetMethodBody() != null)
     {
         il = mi.GetMethodBody().GetILAsByteArray();
         ConstructInstructions(mi.Module);
     }
 }
Ejemplo n.º 3
0
 // Token: 0x06002E89 RID: 11913
 // RVA: 0x0012E9C4 File Offset: 0x0012CBC4
 public Class776(MethodBase methodBase_1)
 {
     this.methodBase_0 = methodBase_1;
     byte[] array = (methodBase_1.GetMethodBody() != null) ? methodBase_1.GetMethodBody().GetILAsByteArray() : null;
     if (array != null)
     {
         this.byte_0 = array;
         this.method_3(methodBase_1.Module);
     }
 }
Ejemplo n.º 4
0
 public MSIL_MethodResolver(System.Reflection.MethodBase Method) : base(Method.DeclaringType.Module)
 {
     System.Reflection.MethodBody body = Method.GetMethodBody();
     if (Method.GetMethodBody() != null)
     {
         foreach (System.Reflection.LocalVariableInfo localsBody in body.LocalVariables)
         {
             System.Reflection.LocalVariableInfo _WAR_local = localsBody;
             _locals.Add(_WAR_local.LocalIndex, _WAR_local);
         }
     }
 }
 /*
      public ILReader(MethodBase enclosingMethod)
      {
      this.m_enclosingMethod = enclosingMethod;
      MethodBody methodBody = m_enclosingMethod.GetMethodBody();
      this.m_byteArray = (methodBody == null) ? new Byte[0] : methodBody.GetILAsByteArray();
      this.m_position = 0;
      }
      */
 public ILReader2(MethodBase enclosingMethod)
 {
     this.m_enclosingMethod = enclosingMethod;
     MethodBody methodBody = m_enclosingMethod.GetMethodBody();
     this.m_byteArray = (methodBody == null) ? new Byte[0] : methodBody.GetILAsByteArray();
     this.m_position = 0;
 }
 public ExceptionDetails(Exception ex, MethodBase info)
 {
     var methodBody = info.GetMethodBody();
     Exception = ex;
     MethodName = info.Name;
     MethodBody = methodBody != null ? methodBody.ToString() : "undefined";
 }
		MethodBodyReader (MethodBase method)
		{
			this.method = method;

			this.body = method.GetMethodBody ();
			if (this.body == null)
				throw new ArgumentException ("Method has no body");

			var bytes = body.GetILAsByteArray ();
			if (bytes == null)
				throw new ArgumentException ("Can not get the body of the method");

			if (!(method is ConstructorInfo))
				method_arguments = method.GetGenericArguments ();

			if (method.DeclaringType != null)
				type_arguments = method.DeclaringType.GetGenericArguments ();

            if (!method.IsStatic)
                this_parameter = new ThisParameter(method.DeclaringType);


            this.parameters = method.GetParameters ();
			this.locals = body.LocalVariables;
			this.module = method.Module;
			this.il = new ByteBuffer (bytes);
			this.instructions = new List<Instruction> ((bytes.Length + 1) / 2);
		}
		public NaiveMethodNameExtractor(Delegate @delegate)
		{
			delegateMethod = @delegate.Method;
			body = delegateMethod.GetMethodBody();
			Debug.Assert(body != null);
			module = delegateMethod.Module;
			stream = new MemoryStream(body.GetILAsByteArray());
			Read();
		}
Ejemplo n.º 9
0
 /// <summary>
 /// Disassemble the bytecode of the specified method or constructor
 /// </summary>
 /// <param name="MethodBase">The method to disassemble</param>
 /// <param name="Resolver">A resolver class used while disassembling the code.
 /// Every token resolution and local variable resolution will be made with this resolver</param>
 /// <returns>The list of intruction contained in the method</returns>
 static public List <Instruction> ReadMethod(System.Reflection.MethodBase MethodBase, Resolver Resolver)
 {
     System.Reflection.MethodBody methodBody = MethodBase.GetMethodBody();
     if (methodBody == null)
     {
         return(new List <Instruction>());
     }
     return(ReadMethod(methodBody.GetILAsByteArray(), Resolver));
 }
Ejemplo n.º 10
0
    protected override void DoInitStackAnalysis(MethodBase aMethod)
    {
      base.DoInitStackAnalysis(aMethod);

      switch (OpCode)
      {
        case Code.Ldloc:
          var xBody = aMethod.GetMethodBody();
          if (xBody != null)
          {
            StackPushTypes[0] = xBody.LocalVariables[Value].LocalType;
            if (StackPushTypes[0].IsEnum)
            {
              StackPushTypes[0] = StackPushTypes[0].GetEnumUnderlyingType();
            }
          }
          return;
        case Code.Ldloca:
          StackPushTypes[0] = typeof(void*);
          return;
        case Code.Ldarga:
          StackPushTypes[0] = typeof (void*);
          return;
        case Code.Ldarg:
          var xArgIndexCorrection = 0;
          if (!aMethod.IsStatic)
          {
            if (Value == 0)
            {
              StackPushTypes[0] = aMethod.DeclaringType;
              if (StackPushTypes[0].IsEnum)
              {
                StackPushTypes[0] = StackPushTypes[0].GetEnumUnderlyingType();
              }
              else
              {
                if (StackPushTypes[0].IsValueType)
                {
                  StackPushTypes[0] = typeof (void*);
                }
              }
              return;
            }
            xArgIndexCorrection = -1;
          }
          var xParams = aMethod.GetParameters();
          StackPushTypes[0] = xParams[Value + xArgIndexCorrection].ParameterType;
          if (StackPushTypes[0].IsEnum)
          {
            StackPushTypes[0] = StackPushTypes[0].GetEnumUnderlyingType();
          }
          return;
        default:
          break;
      }
    }
        public void OnExit(MethodBase method)
        {
            Console.WriteLine("OnExit");

            var mi = (MethodInfo) method;
            var p = method.GetParameters();
            var b = method.GetMethodBody();
            var st = new StackTrace();
            StackFrame sf = st.GetFrame(1); //previous method call
	    }
        /// <summary>
        ///   Get intermediate language of passed method.
        /// </summary>
        /// <param name="methodInfo"> The method info. </param>
        /// <returns> The intermediate language as a byte array. </returns>
        /// <exception cref="ArgumentException">Thrown if methodBody is null.</exception>
        private static IEnumerable<byte> GetIntermediateLanguageFromMethodInfoBase(MethodBase methodInfo)
        {
            var methodBody = methodInfo.GetMethodBody();
            if (methodBody == null)
            {
                throw new ArgumentException("Method Body is null");
            }

            return methodBody.GetILAsByteArray();
        }
Ejemplo n.º 13
0
        static internal byte[] GetBodyAsByteArray(this MethodBase method)
        {
            method.Prepare();
            if (method is DynamicMethod)
            {
                return((method as DynamicMethod).GetILGenerator().GetILAsByteArray());
            }
            var _body = method.GetMethodBody();

            return(_body == null ? null : _body.GetILAsByteArray());
        }
Ejemplo n.º 14
0
        public MethodData(MethodBase method)
        {
            Token = method.MetadataToken;

            MethodBody body = method.GetMethodBody();
            if (body != null)
                SignatureToken = body.LocalSignatureMetadataToken;

            Name = method.DeclaringType.FullName + "::" + method.Name;

        }
Ejemplo n.º 15
0
		/// <summary>
		/// MethodBodyReader constructor
		/// </summary>
		/// <param name="method">The method to read the body from.</param>
		/// <param name="language">Code language to use for text representations of code.</param>
		public MethodBodyReader(MethodBase method, ILanguageInfo language)
		{
			try
			{
				this.method = method;
				this.language = language ?? new DefaultLanguageInfo();
				MethodBody body = method.GetMethodBody();
				if (body != null)
				{
					il = body.GetILAsByteArray();
					ConstructInstructions(method.Module);
				}
			}
			catch (Exception ex)
			{
				throw new InvalidOperationException(String.Format("Failed to read the body of {0}'s {1}.", method.DeclaringType, method), ex);
			}
		}
Ejemplo n.º 16
0
        /// <summary>
        /// Gets the il instructions.
        /// </summary>
        /// <param name="This">This MethodBase.</param>
        /// <returns>A list of instructions.</returns>
        public static ILInstruction[] GetInstructions(this MethodBase This)
        {
            Contract.Requires(This != null);
            var body = This.GetMethodBody();

            if (body == null)
            {
                return(null);
            }

            // make sure opcodes are loaded
            _CheckOpcodeInit();

            var module   = This.Module;
            var il       = body.GetILAsByteArray();
            var position = 0;
            var result   = new List <ILInstruction>();

            while (position < il.Length)
            {
                var instruction = new ILInstruction();

                // get the operation code of the current instruction
                OpCode code;
                ushort value = il[position++];
                if (value != 0xfe)
                {
                    code = _SINGLE_BYTE_OP_CODES[value];
                }
                else
                {
                    value = il[position++];
                    code  = _MULTI_BYTE_OP_CODES[value];
                    value = (ushort)(value | 0xfe00);
                }
                instruction.Code   = code;
                instruction.Offset = position - 1;

                // get the operand of the current operation
                position = _ReadOperand(This, code, position, il, module, instruction);
                result.Add(instruction);
            }
            return(result.ToArray());
        }
        static StackObject *GetMethodBody_35(ILIntepreter __intp, StackObject *__esp, IList <object> __mStack, CLRMethod __method, bool isNewObj)
        {
            ILRuntime.Runtime.Enviorment.AppDomain __domain = __intp.AppDomain;
            StackObject *ptr_of_this_method;
            StackObject *__ret = ILIntepreter.Minus(__esp, 1);

            ptr_of_this_method = ILIntepreter.Minus(__esp, 1);
            System.Reflection.MethodBase instance_of_this_method = (System.Reflection.MethodBase) typeof(System.Reflection.MethodBase).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack));
            __intp.Free(ptr_of_this_method);

            var result_of_this_method = instance_of_this_method.GetMethodBody();

            object obj_result_of_this_method = result_of_this_method;

            if (obj_result_of_this_method is CrossBindingAdaptorType)
            {
                return(ILIntepreter.PushObject(__ret, __mStack, ((CrossBindingAdaptorType)obj_result_of_this_method).ILInstance));
            }
            return(ILIntepreter.PushObject(__ret, __mStack, result_of_this_method));
        }
Ejemplo n.º 18
0
        private MethodBodyReader(MethodBase method)
        {
            _method = method;
            _body = method.GetMethodBody();
            if (_body == null)
                throw new ArgumentException("Method has no body");

            var iLAsByteArray = _body.GetILAsByteArray();
            if (iLAsByteArray == null)
                throw new ArgumentException("Can not get the body of the method");

            if (!(method is ConstructorInfo))
                _methodArguments = method.GetGenericArguments();

            if (method.DeclaringType != null)
                _typeArguments = method.DeclaringType.GetGenericArguments();

            _parameters = method.GetParameters();
            _locals = _body.LocalVariables;
            _module = method.Module;
            _il = new ByteBuffer(iLAsByteArray);
        }
Ejemplo n.º 19
0
        void CopyMethodBody(MethodBase Base, ILGenerator Gen)
        {
            MethodBody Body = Base.GetMethodBody();

            CopyLocals(Gen, Body);

            byte[] Bytes = Body.GetILAsByteArray();
            var ExceptionTrinkets = new List<int>();
            var LabelTargets = new Dictionary<int, Label>();
            var LabelOrigins = new Dictionary<int, Label[]>();

            MineExTrinkets(Body, ExceptionTrinkets);

            // There's a reason we mine these labels. First of all, we need to get the switchmaps. Because
            // there is no way to bang a number of bytes in the IL, we mine the targets of a switch operation
            // and save them to be marked when we walk through the method again to copy the opcodes. Secondly,
            // the microsoft C# compiler sometimes uses the leave.s opcode instead of the leave opcode at the
            // end of a try block. This is all fine, but System.Reflection.Emit forces a leave opcode on the
            // IL when we call BeginCatchBlock() and friends, offering no way to use the leave.s opcode instead.
            // The simple result is that we are left with putting the leave instruction with its 4-byte
            // argument in the IL against our will. This screws over all branch targets with an offset of +3
            // bytes. Consequently, we have to mine *all* branch targets and re-mark them to prevent segfaults
            // and the like in the runtime. This overhead could all have been avoided, had SRE given us just
            // a tiny bit more of control over the IL that was to be emitted.
            MineLabels(Bytes, Gen, LabelOrigins, LabelTargets);

            for(int i = 0; i < Bytes.Length; i++)
            {
                CopyTryCatch(Gen, i, Body, ExceptionTrinkets);
                CopyLabels(Gen, i, LabelTargets);
                CopyOpcode(Bytes, ref i, Gen, Base.Module, ExceptionTrinkets, LabelOrigins);
            }

            // If we do not throw this exception, SRE will do it, but with much less debugging information.
            foreach(int i in LabelTargets.Keys)
                throw new Exception("Unmarked label destined for RVA "+i.ToString("X"));
        }
Ejemplo n.º 20
0
        public DisassembledMethod Disassemble(MethodBase method)
        {
            Contract.Requires(method != null);
            Contract.Requires(CanDisassemble(method));

            var methodBody = method.GetMethodBody();
            if (methodBody == null)
            {
                throw new NotSupportedException(method.DeclaringType +" {" +  method.ToString() + "} "+ method.GetMethodImplementationFlags() );
            }
            Contract.Assert(methodBody!=null);
            // ReSharper disable PossibleNullReferenceException
            var ilBytes = methodBody.GetILAsByteArray();
            // ReSharper restore PossibleNullReferenceException

            Type returnType = method is MethodInfo
                                  ? (method as MethodInfo).ReturnType
                                  : typeof (void);

            var handlingClauses = methodBody.ExceptionHandlingClauses;
            Type[] genericParameters = null;
            if (method.IsGenericMethod)
            {
                genericParameters = method.GetGenericArguments();
            }
            return new DisassembledMethod(
                ilBytes,
                Scan(ilBytes, handlingClauses),
                new ModuleMetadataResolver(method.Module),
                handlingClauses,
                methodBody.LocalVariables,
                returnType,
                method.GetParameters(),
                method.IsGenericMethodDefinition ,
                genericParameters );
        }
Ejemplo n.º 21
0
        private void MapExceptions(MethodBase method, MethodDefinition method_definition)
        {
            var body = method.GetMethodBody();
            if (body == null)
                return;

            var instructions = method.GetInstructions();

            foreach (var clause in body.ExceptionHandlingClauses)
            {
                var handler = new ExceptionHandler((ExceptionHandlerType)clause.Flags)
                {
                    TryStart = OffsetToInstruction(clause.TryOffset, instructions, method_definition),
                    TryEnd = OffsetToInstruction(clause.TryOffset + clause.TryLength, instructions, method_definition),
                    HandlerStart = OffsetToInstruction(clause.HandlerOffset, instructions, method_definition),
                    HandlerEnd = OffsetToInstruction(clause.HandlerOffset + clause.HandlerLength, instructions, method_definition)
                };

                switch (handler.HandlerType)
                {
                    case ExceptionHandlerType.Catch:
                        handler.CatchType = CreateReference(clause.CatchType, method_definition);
                        break;
                    case ExceptionHandlerType.Filter:
                        handler.FilterStart = OffsetToInstruction(clause.FilterOffset, instructions, method_definition);
                        break;
                }

                method_definition.Body.ExceptionHandlers.Add(handler);
            }
        }
Ejemplo n.º 22
0
        private void MapVariables(MethodBase method, MethodDefinition method_definition)
        {
            var body = method.GetMethodBody();
            if (body == null)
                return;

            foreach (var variable in body.LocalVariables)
            {
                var variable_type = CreateReference(variable.LocalType, method_definition);
                method_definition.Body.Variables.Add(new VariableDefinition(variable.IsPinned ? new PinnedType(variable_type) : variable_type));
            }

            method_definition.Body.InitLocals = body.InitLocals;
        }
Ejemplo n.º 23
0
        private void DumpMethod(MethodBase mb, BinaryWriter sw)
        {
            MethodBody mbd = mb.GetMethodBody();
            if (mbd == null)
                return;
            SetOffset(sw, mb.MetadataToken);

            WriteHeader(mbd, sw);

            WriteILCode(mbd, sw);

            WriteSEH(mbd, sw);
        }
Ejemplo n.º 24
0
        private static IEnumerable<Instruction> readIL(MethodBase method, Type genericContext)
        {
            MethodBody body = method.GetMethodBody();
            if (body == null)
                yield break;

            int offset = 0;
            byte[] il = body.GetILAsByteArray();
            while (offset < il.Length)
            {
                int startOffset = offset;
                byte opCodeByte = il[offset];
                short opCodeValue = opCodeByte;
                offset++;

                // If it's an extended opcode then grab the second byte. The 0xFE prefix codes aren't marked as prefix operators though.
                if (opCodeValue == 0xFE || _opCodeList[opCodeValue].OpCodeType == OpCodeType.Prefix)
                {
                    opCodeValue = (short) ((opCodeValue << 8) + il[offset]);
                    offset++;
                }

                OpCode code = _opCodeList[opCodeValue];

                object operand = null;
                switch (code.OperandType)
                {
                    case OperandType.ShortInlineBrTarget:
                    case OperandType.ShortInlineI:
                    case OperandType.ShortInlineVar:
                        operand = il[offset];
                        offset++;
                        break;

                    case OperandType.InlineI:
                    case OperandType.InlineBrTarget:
                        operand = BitConverter.ToInt32(il, offset);
                        offset += 4;
                        break;

                    case OperandType.ShortInlineR: operand = BitConverter.ToSingle(il, offset); offset += 4; break;
                    case OperandType.InlineVar: operand = BitConverter.ToInt16(il, offset); offset += 2; break;
                    case OperandType.InlineI8: operand = BitConverter.ToInt64(il, offset); offset += 8; break;
                    case OperandType.InlineR: operand = BitConverter.ToDouble(il, offset); offset += 8; break;
                    case OperandType.InlineField: operand = method.Module.ResolveField(BitConverter.ToInt32(il, offset), genericContext.GetGenericArguments(), method is ConstructorInfo ? Type.EmptyTypes : method.GetGenericArguments()); offset += 4; break;
                    case OperandType.InlineMethod: operand = method.Module.ResolveMethod(BitConverter.ToInt32(il, offset), genericContext.GetGenericArguments(), method is ConstructorInfo ? Type.EmptyTypes : method.GetGenericArguments()); offset += 4; break;
                    case OperandType.InlineSig: operand = method.Module.ResolveSignature(BitConverter.ToInt32(il, offset)); offset += 4; break;
                    case OperandType.InlineString: operand = method.Module.ResolveString(BitConverter.ToInt32(il, offset)); offset += 4; break;
                    case OperandType.InlineType: operand = method.Module.ResolveType(BitConverter.ToInt32(il, offset), genericContext.GetGenericArguments(), method is ConstructorInfo ? Type.EmptyTypes : method.GetGenericArguments()); offset += 4; break;

                    case OperandType.InlineSwitch:
                        long num = BitConverter.ToInt32(il, offset);
                        offset += 4;
                        var ints = new int[num];
                        for (int i = 0; i < num; i++)
                        {
                            ints[i] = BitConverter.ToInt32(il, offset);
                            offset += 4;
                        }
                        operand = ints;
                        break;

                    case OperandType.InlineTok:
                        operand = method.Module.ResolveMember(BitConverter.ToInt32(il, offset), genericContext.GetGenericArguments(), method is ConstructorInfo ? Type.EmptyTypes : method.GetGenericArguments()); offset += 4; break;
                }

                yield return new Instruction(startOffset, code, operand);
            }
        }
Ejemplo n.º 25
0
			static int GetILSize (MethodBase mi)
			{
				MethodBody body = mi.GetMethodBody ();
				if (body != null)
					return body.GetILAsByteArray ().Length;

				return 0;
			}
Ejemplo n.º 26
0
        protected List<EcmaCil.IL.BaseInstruction> ScanMethodBody_DoIt(MethodBase aMethod, EcmaCil.MethodMeta aMethodMeta, IDictionary<int, int> aILOffsetToInstructionIndex, IDictionary<int, int> aInstructionIndexToILOffset)
        {
            var xResult = new List<EcmaCil.IL.BaseInstruction>(aILOffsetToInstructionIndex.Count);
            var xBody = aMethod.GetMethodBody();
            // Cache for use in field and method resolution
            Type[] xTypeGenArgs = null;
            Type[] xMethodGenArgs = null;
            if (aMethod.DeclaringType.IsGenericType)
            {
                xTypeGenArgs = aMethod.DeclaringType.GetGenericArguments();
            }
            if (aMethod.IsGenericMethod)
            {
                xMethodGenArgs = aMethod.GetGenericArguments();
            }

            // Some methods return no body. Not sure why.. have to investigate
            // They arent abstracts or icalls...
            // MtW: how about externs (pinvoke, etc)
            if (xBody == null)
            {
                return null;
            }

            var xIL = xBody.GetILAsByteArray();
            int xPos = 0;
            var xInstructionIndex = 0;
            var xInitSecondStage = new List<Action>(aILOffsetToInstructionIndex.Count);
            while (xPos < xIL.Length)
            {
                ExceptionHandlingClause xCurrentHandler = null;
                #region Determine current handler
                // todo: add support for nested handlers using a stack or so..
                foreach (ExceptionHandlingClause xHandler in xBody.ExceptionHandlingClauses)
                {
                    if (xHandler.TryOffset > 0)
                    {
                        if (xHandler.TryOffset <= xPos && (xHandler.TryLength + xHandler.TryOffset + 1) > xPos) // + 1 because index should be less than the try
                        {
                            if (xCurrentHandler == null)
                            {
                                xCurrentHandler = xHandler;
                                continue;
                            }
                            else if (xHandler.TryOffset > xCurrentHandler.TryOffset && (xHandler.TryLength + xHandler.TryOffset) < (xCurrentHandler.TryLength + xCurrentHandler.TryOffset))
                            {
                                // only replace if the current found handler is narrower
                                xCurrentHandler = xHandler;
                                continue;
                            }
                        }
                    }
                    if (xHandler.HandlerOffset > 0)
                    {
                        if (xHandler.HandlerOffset <= xPos && (xHandler.HandlerOffset + xHandler.HandlerLength + 1) > xPos)
                        {
                            if (xCurrentHandler == null)
                            {
                                xCurrentHandler = xHandler;
                                continue;
                            }
                            else if (xHandler.HandlerOffset > xCurrentHandler.HandlerOffset && (xHandler.HandlerOffset + xHandler.HandlerLength) < (xCurrentHandler.HandlerOffset + xCurrentHandler.HandlerLength))
                            {
                                // only replace if the current found handler is narrower
                                xCurrentHandler = xHandler;
                                continue;
                            }
                        }
                    }
                    if ((xHandler.Flags & ExceptionHandlingClauseOptions.Filter) > 0)
                    {
                        if (xHandler.FilterOffset > 0)
                        {
                            if (xHandler.FilterOffset <= xPos)
                            {
                                if (xCurrentHandler == null)
                                {
                                    xCurrentHandler = xHandler;
                                    continue;
                                }
                                else if (xHandler.FilterOffset > xCurrentHandler.FilterOffset)
                                {
                                    // only replace if the current found handler is narrower
                                    xCurrentHandler = xHandler;
                                    continue;
                                }
                            }
                        }
                    }
                }
                #endregion
                OpCodeEnum xOpCodeVal;
                OpCode xOpCode;
                int xOpPos = xPos;
                if (xIL[xPos] == 0xFE)
                {
                    xOpCodeVal = (OpCodeEnum)(0xFE00 | xIL[xPos + 1]);
                    xOpCode = mOpCodesHi[xIL[xPos + 1]];
                    xPos = xPos + 2;
                }
                else
                {
                    xOpCodeVal = (OpCodeEnum)xIL[xPos];
                    xOpCode = mOpCodesLo[xIL[xPos]];
                    xPos++;
                }

                EcmaCil.IL.BaseInstruction xILOpCode = null;
                Cil.InstructionBranch xBranch;
                Console.WriteLine(xOpCode.ToString() + " " + xOpCode.OperandType);
                #region switch(xOpCode.OperandType)
                switch (xOpCode.OperandType)
                {
                    // No operand.
                    case OperandType.InlineNone:
                        {
                            #region Inline none options
                            // These shortcut translation regions expand shortcut ops into full ops
                            // This elminates the amount of code required in the assemblers
                            // by allowing them to ignore the shortcuts
                            switch (xOpCodeVal)
                            {
                                case OpCodeEnum.Ldarg_0:
                                    xILOpCode = new Cil.InstructionArgument(EcmaCil.IL.InstructionKindEnum.Ldarg, xInstructionIndex, aMethodMeta.Parameters[0]);
                                    break;
                                case OpCodeEnum.Ldarg_1:
                                    xILOpCode = new Cil.InstructionArgument(EcmaCil.IL.InstructionKindEnum.Ldarg, xInstructionIndex, aMethodMeta.Parameters[1]);
                                    break;
                                case OpCodeEnum.Ldarg_2:
                                    xILOpCode = new Cil.InstructionArgument(EcmaCil.IL.InstructionKindEnum.Ldarg, xInstructionIndex, aMethodMeta.Parameters[2]);
                                    break;
                                case OpCodeEnum.Ldarg_3:
                                    xILOpCode = new Cil.InstructionArgument(EcmaCil.IL.InstructionKindEnum.Ldarg, xInstructionIndex, aMethodMeta.Parameters[3]);
                                    break;
                                case OpCodeEnum.Ldc_I4_0:
                                    xILOpCode = new Cil.InstructionInt32(EcmaCil.IL.InstructionKindEnum.Ldc_I4, xInstructionIndex, 0);
                                    break;
                                case OpCodeEnum.Ldc_I4_1:
                                    xILOpCode = new Cil.InstructionInt32(EcmaCil.IL.InstructionKindEnum.Ldc_I4, xInstructionIndex, 1);
                                    break;
                                case OpCodeEnum.Ldc_I4_2:
                                    xILOpCode = new Cil.InstructionInt32(EcmaCil.IL.InstructionKindEnum.Ldc_I4, xInstructionIndex, 2);
                                    break;
                                case OpCodeEnum.Ldc_I4_3:
                                    xILOpCode = new Cil.InstructionInt32(EcmaCil.IL.InstructionKindEnum.Ldc_I4, xInstructionIndex, 3);
                                    break;
                                case OpCodeEnum.Ldc_I4_4:
                                    xILOpCode = new Cil.InstructionInt32(EcmaCil.IL.InstructionKindEnum.Ldc_I4, xInstructionIndex, 4);
                                    break;
                                case OpCodeEnum.Ldc_I4_5:
                                    xILOpCode = new Cil.InstructionInt32(EcmaCil.IL.InstructionKindEnum.Ldc_I4, xInstructionIndex, 5);
                                    break;
                                case OpCodeEnum.Ldc_I4_6:
                                    xILOpCode = new Cil.InstructionInt32(EcmaCil.IL.InstructionKindEnum.Ldc_I4, xInstructionIndex, 6);
                                    break;
                                case OpCodeEnum.Ldc_I4_7:
                                    xILOpCode = new Cil.InstructionInt32(EcmaCil.IL.InstructionKindEnum.Ldc_I4, xInstructionIndex, 7);
                                    break;
                                case OpCodeEnum.Ldc_I4_8:
                                    xILOpCode = new Cil.InstructionInt32(EcmaCil.IL.InstructionKindEnum.Ldc_I4, xInstructionIndex, 8);
                                    break;
                                case OpCodeEnum.Ldc_I4_M1:
                                    xILOpCode = new Cil.InstructionInt32(EcmaCil.IL.InstructionKindEnum.Ldc_I4, xInstructionIndex, -1);
                                    break;
                                case OpCodeEnum.Ldloc_0:
                                    xILOpCode = new Cil.InstructionLocal(EcmaCil.IL.InstructionKindEnum.Ldloc, xInstructionIndex, aMethodMeta.Body.LocalVariables[0]);
                                    break;
                                case OpCodeEnum.Ldloc_1:
                                    xILOpCode = new Cil.InstructionLocal(EcmaCil.IL.InstructionKindEnum.Ldloc, xInstructionIndex, aMethodMeta.Body.LocalVariables[1]);
                                    break;
                                case OpCodeEnum.Ldloc_2:
                                    xILOpCode = new Cil.InstructionLocal(EcmaCil.IL.InstructionKindEnum.Ldloc, xInstructionIndex, aMethodMeta.Body.LocalVariables[2]);
                                    break;
                                case OpCodeEnum.Ldloc_3:
                                    xILOpCode = new Cil.InstructionLocal(EcmaCil.IL.InstructionKindEnum.Ldloc, xInstructionIndex, aMethodMeta.Body.LocalVariables[3]);
                                    break;
                                case OpCodeEnum.Stloc_0:
                                    xILOpCode = new Cil.InstructionLocal(EcmaCil.IL.InstructionKindEnum.Stloc, xInstructionIndex, aMethodMeta.Body.LocalVariables[0]);
                                    break;
                                case OpCodeEnum.Stloc_1:
                                    xILOpCode = new Cil.InstructionLocal(EcmaCil.IL.InstructionKindEnum.Stloc, xInstructionIndex, aMethodMeta.Body.LocalVariables[1]);
                                    break;
                                case OpCodeEnum.Stloc_2:
                                    xILOpCode = new Cil.InstructionLocal(EcmaCil.IL.InstructionKindEnum.Stloc, xInstructionIndex, aMethodMeta.Body.LocalVariables[2]);
                                    break;
                                case OpCodeEnum.Stloc_3:
                                    xILOpCode = new Cil.InstructionLocal(EcmaCil.IL.InstructionKindEnum.Stloc, xInstructionIndex, aMethodMeta.Body.LocalVariables[3]);
                                    break;
                                default:
                                    xILOpCode = new Cil.InstructionNone((EcmaCil.IL.InstructionKindEnum)xOpCodeVal, xInstructionIndex);
                                    break;
                            }
                            #endregion
                            break;
                        }

                    case OperandType.ShortInlineBrTarget:
                        {
                            #region Inline branch
                            // By calculating target, we assume all branches are within a method
                            // So far at least wtih csc, its true. We check it with CheckBranch
                            // just in case.
                            int xTarget = xPos + 1 + (sbyte)xIL[xPos];
                            CheckBranch(xTarget, xIL.Length);
                            switch (xOpCodeVal)
                            {
                                case OpCodeEnum.Beq_S:
                                    xBranch = new Cil.InstructionBranch(EcmaCil.IL.InstructionKindEnum.Beq, xInstructionIndex);
                                    xILOpCode = xBranch;
                                    xInitSecondStage.Add(delegate
                                    {
                                        xBranch.Target = xResult[aILOffsetToInstructionIndex[xTarget]];
                                    });
                                    break;
                                case OpCodeEnum.Bge_S:
                                    xBranch = new Cil.InstructionBranch(EcmaCil.IL.InstructionKindEnum.Bge, xInstructionIndex);
                                    xILOpCode = xBranch;
                                    xInitSecondStage.Add(delegate
                                    {
                                        xBranch.Target = xResult[aILOffsetToInstructionIndex[xTarget]];
                                    });
                                    break;
                                case OpCodeEnum.Bge_Un_S:
                                    xBranch = new Cil.InstructionBranch(EcmaCil.IL.InstructionKindEnum.Bge_Un, xInstructionIndex);
                                    xILOpCode = xBranch;
                                    xInitSecondStage.Add(delegate
                                    {
                                        xBranch.Target = xResult[aILOffsetToInstructionIndex[xTarget]];
                                    });
                                    break;
                                case OpCodeEnum.Bgt_S:
                                    xBranch = new Cil.InstructionBranch(EcmaCil.IL.InstructionKindEnum.Bgt, xInstructionIndex);
                                    xILOpCode = xBranch;
                                    xInitSecondStage.Add(delegate
                                    {
                                        xBranch.Target = xResult[aILOffsetToInstructionIndex[xTarget]];
                                    });
                                    break;
                                case OpCodeEnum.Bgt_Un_S:
                                    xBranch = new Cil.InstructionBranch(EcmaCil.IL.InstructionKindEnum.Bgt_Un, xInstructionIndex);
                                    xILOpCode = xBranch;
                                    xInitSecondStage.Add(delegate
                                    {
                                        xBranch.Target = xResult[aILOffsetToInstructionIndex[xTarget]];
                                    });
                                    break;
                                case OpCodeEnum.Ble_S:
                                    xBranch = new Cil.InstructionBranch(EcmaCil.IL.InstructionKindEnum.Ble, xInstructionIndex);
                                    xILOpCode = xBranch;
                                    xInitSecondStage.Add(delegate
                                    {
                                        xBranch.Target = xResult[aILOffsetToInstructionIndex[xTarget]];
                                    });
                                    break;
                                case OpCodeEnum.Ble_Un_S:
                                    xBranch = new Cil.InstructionBranch(EcmaCil.IL.InstructionKindEnum.Ble_Un, xInstructionIndex);
                                    xILOpCode = xBranch;
                                    xInitSecondStage.Add(delegate
                                    {
                                        xBranch.Target = xResult[aILOffsetToInstructionIndex[xTarget]];
                                    });
                                    break;
                                case OpCodeEnum.Blt_S:
                                    xBranch = new Cil.InstructionBranch(EcmaCil.IL.InstructionKindEnum.Blt, xInstructionIndex);
                                    xILOpCode = xBranch;
                                    xInitSecondStage.Add(delegate
                                    {
                                        xBranch.Target = xResult[aILOffsetToInstructionIndex[xTarget]];
                                    });
                                    break;
                                case OpCodeEnum.Blt_Un_S:
                                    xBranch = new Cil.InstructionBranch(EcmaCil.IL.InstructionKindEnum.Blt_Un, xInstructionIndex);
                                    xILOpCode = xBranch;
                                    xInitSecondStage.Add(delegate
                                    {
                                        xBranch.Target = xResult[aILOffsetToInstructionIndex[xTarget]];
                                    });
                                    break;
                                case OpCodeEnum.Bne_Un_S:
                                    xBranch = new Cil.InstructionBranch(EcmaCil.IL.InstructionKindEnum.Bne_Un, xInstructionIndex);
                                    xILOpCode = xBranch;
                                    xInitSecondStage.Add(delegate
                                    {
                                        xBranch.Target = xResult[aILOffsetToInstructionIndex[xTarget]];
                                    });
                                    break;
                                case OpCodeEnum.Br_S:
                                    xBranch = new Cil.InstructionBranch(EcmaCil.IL.InstructionKindEnum.Br, xInstructionIndex);
                                    xILOpCode = xBranch;
                                    xInitSecondStage.Add(delegate
                                    {
                                        xBranch.Target = xResult[aILOffsetToInstructionIndex[xTarget]];
                                    });
                                    break;
                                case OpCodeEnum.Brfalse_S:
                                    xBranch = new Cil.InstructionBranch(EcmaCil.IL.InstructionKindEnum.Brfalse, xInstructionIndex);
                                    xILOpCode = xBranch;
                                    xInitSecondStage.Add(delegate
                                    {
                                        xBranch.Target = xResult[aILOffsetToInstructionIndex[xTarget]];
                                    });
                                    break;
                                case OpCodeEnum.Brtrue_S:
                                    xBranch = new Cil.InstructionBranch(EcmaCil.IL.InstructionKindEnum.Brtrue, xInstructionIndex);
                                    xILOpCode = xBranch;
                                    xInitSecondStage.Add(delegate
                                    {
                                        xBranch.Target = xResult[aILOffsetToInstructionIndex[xTarget]];
                                    });
                                    break;
                                case OpCodeEnum.Leave_S:
                                    xBranch = new Cil.InstructionBranch(EcmaCil.IL.InstructionKindEnum.Leave, xInstructionIndex);
                                    xILOpCode = xBranch;
                                    xInitSecondStage.Add(delegate
                                    {
                                        xBranch.Target = xResult[aILOffsetToInstructionIndex[xTarget]];
                                    });
                                    break;
                                default:
                                    xBranch = new Cil.InstructionBranch((EcmaCil.IL.InstructionKindEnum)xOpCodeVal, xInstructionIndex);
                                    xILOpCode = xBranch;
                                    xInitSecondStage.Add(delegate
                                    {
                                        xBranch.Target = xResult[aILOffsetToInstructionIndex[xTarget]];
                                    });
                                    break;
                            }
                            xPos = xPos + 1;
                            break;
                            #endregion
                        }
                    case OperandType.InlineBrTarget:
                        {
                            int xTarget = xPos + 4 + (Int32)ReadInt32(xIL, xPos);
                            CheckBranch(xTarget, xIL.Length);
                            xILOpCode = xBranch = new Cil.InstructionBranch((EcmaCil.IL.InstructionKindEnum)xOpCodeVal, xInstructionIndex);
                            xInitSecondStage.Add(delegate
                            {
                                xBranch.Target = xResult[aILOffsetToInstructionIndex[xTarget]];
                            });
                            xPos = xPos + 4;
                            break;
                        }

                    case OperandType.ShortInlineI:
                        switch (xOpCodeVal)
                        {
                            case OpCodeEnum.Ldc_I4_S:
                                xILOpCode = new Cil.InstructionInt32(EcmaCil.IL.InstructionKindEnum.Ldc_I4, xInstructionIndex, xIL[xPos]);
                                break;
                            default:
                                xILOpCode = new Cil.InstructionInt32((EcmaCil.IL.InstructionKindEnum)xOpCodeVal, xInstructionIndex, xIL[xPos]);
                                break;
                        }
                        xPos = xPos + 1;
                        break;
                    case OperandType.InlineI:
                        xILOpCode = new Cil.InstructionInt32((Cil.InstructionKindEnum)xOpCodeVal, xInstructionIndex, ReadInt32(xIL, xPos));
                        xPos = xPos + 4;
                        break;
                    case OperandType.InlineI8:
                        xILOpCode = new Cil.InstructionInt64((Cil.InstructionKindEnum)xOpCodeVal, xInstructionIndex, ReadInt64(xIL, xPos));
                        xPos = xPos + 8;
                        break;

                    case OperandType.ShortInlineR:
                        // this is not correct:
                        //xILOpCode = new Cil.InstructionSingle(
                        //xILOpCode = new ILOpCodes.OpSingle(xOpCodeVal, xOpPos, xPos + 4, BitConverter.ToSingle(xIL, xPos), xCurrentHandler);
                        //xPos = xPos + 4;
                        //break;
                        throw new NotImplementedException();
                    case OperandType.InlineR:
                        // this is not correct
                        //xILOpCode = new ILOpCodes.OpDouble(xOpCodeVal, xOpPos, xPos + 8, BitConverter.ToDouble(xIL, xPos), xCurrentHandler);
                        //xPos = xPos + 8;
                        //break;
                        throw new NotImplementedException();

                    // The operand is a 32-bit metadata token.
                    case OperandType.InlineField:
                        throw new NotImplementedException();
                    //{
                    //    var xValue = aMethod.Module.ResolveField((int)ReadInt32(xIL, xPos), xTypeGenArgs, xMethodGenArgs);

                    //    xILOpCode = new ILOpCodes.OpField(xOpCodeVal, xOpPos, xPos + 4, xValue, xCurrentHandler);
                    //    xPos = xPos + 4;
                    //    break;
                    //}

                    // The operand is a 32-bit metadata token.
                    case OperandType.InlineMethod:
                        var xTargetMethod = EnqueueMethod(aMethod.DeclaringType.Module.ResolveMethod(ReadInt32(xIL, xPos)), aMethod, "Method Call");
                        xILOpCode = new Cil.InstructionMethod((Cil.InstructionKindEnum)xOpCodeVal, xInstructionIndex, xTargetMethod);
                        xPos = xPos + 4;
                        break; 
                    //{
                    //    var xValue = aMethod.Module.ResolveMethod((int)ReadInt32(xIL, xPos), xTypeGenArgs, xMethodGenArgs);
                    //    xILOpCode = new ILOpCodes.OpMethod(xOpCodeVal, xOpPos, xPos + 4, xValue, xCurrentHandler);
                    //    xPos = xPos + 4;
                    //    break;
                    //}

                    // 32-bit metadata signature token.
                    case OperandType.InlineSig:
                        throw new NotImplementedException();

                    case OperandType.InlineString:
                        xILOpCode = new Cil.InstructionString(Cil.InstructionKindEnum.Ldstr, xInstructionIndex, aMethod.Module.ResolveString(ReadInt32(xIL, xPos)));
                        xPos = xPos + 4;
                        break;

                    case OperandType.InlineSwitch:
                        throw new NotImplementedException();
                    //{
                    //    int xCount = (int)ReadInt32(xIL, xPos);
                    //    xPos = xPos + 4;
                    //    int xNextOpPos = xPos + xCount * 4;
                    //    int[] xBranchLocations = new int[xCount];
                    //    for (int i = 0; i < xCount; i++)
                    //    {
                    //        xBranchLocations[i] = xNextOpPos + (int)ReadInt32(xIL, xPos + i * 4);
                    //        CheckBranch(xBranchLocations[i], xIL.Length);
                    //    }
                    //    xILOpCode = new ILOpCodes.OpSwitch(xOpCodeVal, xOpPos, xPos, xBranchLocations, xCurrentHandler);
                    //    xPos = xNextOpPos;
                    //    break;
                    //}

                    // The operand is a FieldRef, MethodRef, or TypeRef token.
                    case OperandType.InlineTok:
                        throw new NotImplementedException();
                    //xILOpCode = new ILOpCodes.OpToken(xOpCodeVal, xOpPos, xPos + 4, ReadInt32(xIL, xPos), aMethod.Module, xTypeGenArgs, xMethodGenArgs, xCurrentHandler);
                    //                        xPos = xPos + 4;
                    //                        break;

                    // 32-bit metadata token.
                    case OperandType.InlineType:
                        throw new NotImplementedException();
                    //{
                    //    var xValue = aMethod.Module.ResolveType((int)ReadInt32(xIL, xPos), xTypeGenArgs, xMethodGenArgs);
                    //    xILOpCode = new ILOpCodes.OpType(xOpCodeVal, xOpPos, xPos + 4, xValue, xCurrentHandler);
                    //    xPos = xPos + 4;
                    //    break;
                    //}

                    case OperandType.ShortInlineVar:
                        switch (xOpCodeVal)
                        {
                            case OpCodeEnum.Ldloc_S:
                                xILOpCode = new Cil.InstructionLocal(Cil.InstructionKindEnum.Ldloc, xInstructionIndex, aMethodMeta.Body.LocalVariables[xIL[xPos]]);
                                break;
                            case OpCodeEnum.Ldloca_S:
                                xILOpCode = new Cil.InstructionLocal(Cil.InstructionKindEnum.Ldloca, xInstructionIndex, aMethodMeta.Body.LocalVariables[xIL[xPos]]);
                                break;
                            case OpCodeEnum.Ldarg_S:
                                xILOpCode = new Cil.InstructionArgument(Cil.InstructionKindEnum.Ldarg, xInstructionIndex, aMethodMeta.Parameters[xIL[xPos]]);
                                break;
                            case OpCodeEnum.Ldarga_S:
                                xILOpCode = new Cil.InstructionArgument(Cil.InstructionKindEnum.Ldarga, xInstructionIndex, aMethodMeta.Parameters[xIL[xPos]]);
                                break;
                            case OpCodeEnum.Starg_S:
                                xILOpCode = new Cil.InstructionArgument(Cil.InstructionKindEnum.Starg, xInstructionIndex, aMethodMeta.Parameters[xIL[xPos]]);
                                break;
                            case OpCodeEnum.Stloc_S:
                                xILOpCode = new Cil.InstructionLocal(Cil.InstructionKindEnum.Stloc, xInstructionIndex, aMethodMeta.Body.LocalVariables[xIL[xPos]]);
                                break;
                            default:
                                throw new NotImplementedException();
                            //xILOpCode = new ILOpCodes.OpVar(xOpCodeVal, xOpPos, xPos + 1, xIL[xPos], xCurrentHandler);
                            //break;
                        }
                        xPos = xPos + 1;
                        break;
                    case OperandType.InlineVar:
                        //xILOpCode = new ILOpCodes.OpVar(xOpCodeVal, xOpPos, xPos + 2, ReadUInt16(xIL, xPos), xCurrentHandler);
                        //xPos = xPos + 2;
                        throw new NotImplementedException();
                        break;

                    default:
                        throw new Exception("Unknown OperandType");
                }
                #endregion switch(xOpCode.OperandType)
                xResult.Add(xILOpCode);
                xInstructionIndex++;
            }
            foreach (var xAction in xInitSecondStage)
            {
                xAction();
            }
            return xResult;
        }
Ejemplo n.º 27
0
			static int GetILSize (MethodBase mi)
			{
#if NET_2_0
				MethodBody body = mi.GetMethodBody ();
				if (body != null)
					return body.GetILAsByteArray ().Length;
#endif
				return 0;
			}
Ejemplo n.º 28
0
        public static IEnumerable<ILInstruction> GetInstructions(MethodBase methodBase)
        {
            MethodBody methodBody = methodBase.GetMethodBody();

            byte[] bytes;
            if (methodBody != null)
            {
                bytes = methodBody.GetILAsByteArray();
            }
            else
            {
                bytes = new byte[] { };
            }

            int offset = 0;

            while (offset < bytes.Length)
            {
                ILInstruction instruction = new ILInstruction();
                instruction.Offset = offset;

                short code = (short)bytes[offset++];
                if (code == 0xfe)
                {
                    code = (short)(bytes[offset++] | 0xfe00);
                }

                instruction.OpCode = ILOpCodeTranslator.GetOpCode(code);

                switch (instruction.OpCode.OperandType)
                {
                    case OperandType.InlineBrTarget:
                        offset += 4;
                        break;

                    case OperandType.InlineField:
                        offset += 4;
                        break;

                    case OperandType.InlineI:
                        offset += 4;
                        break;

                    case OperandType.InlineI8:
                        offset += 8;
                        break;

                    case OperandType.InlineMethod:
                        int metaDataToken = bytes.GetInt32(offset);

                        Type[] genericMethodArguments = null;
                        if (methodBase.IsGenericMethod == true)
                        {
                            genericMethodArguments = methodBase.GetGenericArguments();
                        }

                        instruction.Data = methodBase.Module.ResolveMethod(metaDataToken, methodBase.DeclaringType.GetGenericArguments(), genericMethodArguments);
                        offset += 4;
                        break;

                    case OperandType.InlineNone:
                        break;

                    case OperandType.InlineR:
                        offset += 8;
                        break;

                    case OperandType.InlineSig:
                        offset += 4;
                        break;

                    case OperandType.InlineString:
                        offset += 4;
                        break;

                    case OperandType.InlineSwitch:
                        int count = bytes.GetInt32(offset) + 1;
                        offset += 4 * count;
                        break;

                    case OperandType.InlineTok:
                        offset += 4;
                        break;

                    case OperandType.InlineType:
                        offset += 4;
                        break;

                    case OperandType.InlineVar:
                        offset += 2;
                        break;

                    case OperandType.ShortInlineBrTarget:
                        offset += 1;
                        break;

                    case OperandType.ShortInlineI:
                        offset += 1;
                        break;

                    case OperandType.ShortInlineR:
                        offset += 4;
                        break;

                    case OperandType.ShortInlineVar:
                        offset += 1;
                        break;

                    default:
                        throw new NotImplementedException();
                }

                yield return instruction;
            }
        }
Ejemplo n.º 29
0
 public override MethodBody GetMethodBody()
 {
     return(MethodBase.GetMethodBody(this.mhandle));
 }
Ejemplo n.º 30
0
        public MethodDetail(RootDetail parent, MethodBase mi)
            : base(parent, mi)
        {
            CodeStringBuilder csb = new CodeStringBuilder(AppendMode.Text);
            csb.AppendMethodName(mi);
            _name = csb.ToString();

            _visibility = VisibilityUtil.GetVisibilityFor(mi);
            _category = "method";

            MethodBody body = null;

            try
            {
                body = mi.GetMethodBody();
            }
            catch (VerificationException)
            {
                // "Operation could destabilize the runtime" on .NET 3.0 WPF PresentationCore.dll
            }

            if (body != null)
            {
                _body = GenericUtility.GetILAsHashedText(mi);
            }

            csb = new CodeStringBuilder();

            AppendAttributesDeclaration(csb);

            MethodInfo bi = null;
            if (mi is MethodInfo)
            {
                bi = ((MethodInfo)mi).GetBaseDefinition();
            }

            csb.Mode = AppendMode.Html;
            csb.AppendVisibility(_visibility);
            csb.AppendText(" ");
            csb.Mode = AppendMode.Both;

            if (mi.IsAbstract)
            {
                if (!mi.DeclaringType.IsInterface)
                {
                    csb.AppendKeyword("abstract ");
                }
            }
            else if (mi.IsVirtual && !mi.IsFinal)
            {
                if (!object.ReferenceEquals(mi, bi))
                {
                    csb.AppendKeyword("override ");
                }
                else
                {
                    csb.AppendKeyword("virtual ");
                }
            }
            else if (mi.IsStatic)
            {
                csb.AppendKeyword("static ");
            }

            if (mi is MethodInfo)
            {
                csb.AppendParameter(((MethodInfo)mi).ReturnParameter);
            }

            csb.AppendText(" ");
            csb.AppendText(_name);
            csb.AppendText("(");

            CodeStringBuilder csbParameters = new CodeStringBuilder(AppendMode.Text);

            foreach (ParameterInfo pi in mi.GetParameters())
            {
                csb.AppendParameter(pi);
                csb.AppendText(", ");

                csbParameters.AppendParameterType(pi);
                csbParameters.AppendText(", ");

                _parameterCount++;
            }

            if (mi.GetParameters().Length > 0)
            {
                csb.RemoveCharsFromEnd(2);
                csbParameters.RemoveCharsFromEnd(2);
            }

            csb.AppendText(")");

            if (mi is MethodInfo)
            {
                csb.AppendGenericRestrictions(mi);
            }

            _declaration = csb.ToString();
            _declarationHtml = csb.ToHtmlString();
            _parameterTypesList = csbParameters.ToString();
        }
Ejemplo n.º 31
0
 private static bool ShouldMapBody(MethodBase method, MethodDefinition method_definition)
 {
     return method_definition.HasBody && method.GetMethodBody() != null;
 }
Ejemplo n.º 32
0
 MSILHandler(System.Reflection.MethodBase method)
 {
     _module = method.DeclaringType.Module;
     _il     = method.GetMethodBody().GetILAsByteArray();
 }
Ejemplo n.º 33
0
        public ILReader(MethodBase InputMethod, FieldInfo[] FieldsInModule, MethodBase[] MethodsInModule, Assembly currentAssm)
        {
            workingAssm = currentAssm;
            MethodOpcodes = new ArrayList();
            InputMeth = InputMethod;
            ExceptionHandlers = new ArrayList();

            if (InputMethod == null)
            {
                Console.WriteLine("Error, input method is not specified, can not continue");
                return;
            }
            methodBody = InputMethod.GetMethodBody();
            curModule = InputMethod.DeclaringType.Module;

            pos = 0;
            pos1 = 0;

            IL = methodBody.GetILAsByteArray();

            IList<ExceptionHandlingClause>  ehClauses = methodBody.ExceptionHandlingClauses;
            foreach( ExceptionHandlingClause ehclause in ehClauses )
            {
                ExceptionHandlers.Add(new ExceptionInstruction(ehclause.TryOffset,ExceptionHandler.Try,null));
                switch (ehclause.Flags)
                {
                    //case 0:
                    case ExceptionHandlingClauseOptions.Clause:
                        ExceptionHandlers.Add(new ExceptionInstruction(ehclause.HandlerOffset,ExceptionHandler.Catch,ehclause.CatchType));
                        ExceptionHandlers.Add(new ExceptionInstruction(ehclause.HandlerOffset+ehclause.HandlerLength,ExceptionHandler.EndException,null));
                    break;
                    //case 1:
                case ExceptionHandlingClauseOptions.Filter:
                    ExceptionHandlers.Add(new ExceptionInstruction(ehclause.FilterOffset,ExceptionHandler.Filter,null));
                        ExceptionHandlers.Add(new ExceptionInstruction(ehclause.HandlerOffset,ExceptionHandler.EndFilter,null));
                        ExceptionHandlers.Add(new ExceptionInstruction(ehclause.HandlerOffset+ehclause.HandlerLength,ExceptionHandler.EndException,null));
                        break;
                    //case 2:
                    case ExceptionHandlingClauseOptions.Finally:
                        ExceptionHandlers.Add(new ExceptionInstruction(ehclause.HandlerOffset,ExceptionHandler.Finally,null));
                        ExceptionHandlers.Add(new ExceptionInstruction(ehclause.HandlerOffset+ehclause.HandlerLength,ExceptionHandler.EndException,null));
                        break;
                    //case 4:
                    case ExceptionHandlingClauseOptions.Fault:
                        ExceptionHandlers.Add(new ExceptionInstruction(ehclause.HandlerOffset,ExceptionHandler.Fault,null));
                        ExceptionHandlers.Add(new ExceptionInstruction(ehclause.HandlerOffset+ehclause.HandlerLength,ExceptionHandler.EndException,null));
                        break;
                }
            }
            // populate opcode
            Opcode Op = GetOpcode();
            while (Op.Name != "")												// This cycles through all the Opcodes
            {
                if (Op.Name != "stfld")
                    MethodOpcodes.Add(Op);
                Op = GetOpcode();
            }
            // sort the stfld opcodes and output
            // this will make the opcode invalid for run.
            // but out purpose is simply compare the assemblies.
            StfldList.Sort(new StringCompare());
            foreach (object i in StfldList)
            {
                Opcode temp = new Opcode("stfld", i);
                MakeLabel(temp, false);
                MethodOpcodes.Add(temp);
            }
        }
Ejemplo n.º 34
0
		public ILToken[] GetTokens(MethodBase method) {
			this.method = method;
			il = method.GetMethodBody().GetILAsByteArray();
			ILToken[] ret = new ILToken[il.Length];
			position = 0;
			this.Module = method.Module;
			while (position < il.Length) {
				var opCode = byteCodes[il[position]];
				var p = this.position;
				if (opCode == OpCodes.Prefix1) {
					opCode = shortCodes[512 + (short)((il[position] << 8) + il[position + 1])];
					++position;
				}
				ret[p] = new ILToken(position, opCode.Size, opCode);
				++this.position;
				p = this.position;
				if ((OpCodeValue)opCode.Value == OpCodeValue.Switch) {
					var count = this.EatUInt32();
					ret[p] = new ILToken(p, 4, count);
					for (int i = 0; i < count; ++i) {
						p = this.position;
						ret[p] = new ILToken(p, 4, this.EatInt32());
					}
				} else
					switch (opCode.OperandType) {
						case OperandType.InlineBrTarget: ret[p] = new ILToken(p, 4, this.EatInt32()); break;
						case OperandType.InlineField: ret[p] = new ILToken(p, 4, parseInlineField()); break;
						case OperandType.InlineI: ret[p] = new ILToken(p, 4, this.EatInt32()); break;
						//case OperandType.InlineI8:
						//  break;
						case OperandType.InlineMethod: ret[p] = new ILToken(p, 4, parseInlineMethod()); break;
						case OperandType.InlineNone: break;
						//case OperandType.InlinePhi:
						//  break;
						case OperandType.InlineR: ret[p] = new ILToken(p, 8, this.EatFloat64()); break;
						//case OperandType.InlineSig:
						//  break;
						case OperandType.InlineString: ret[p] = new ILToken(p, 4, parseInlineString()); break;
						//case OperandType.InlineTok: ret[p] = new ILToken(p, 4, parseInlineTok()); break;
						case OperandType.InlineType: ret[p] = new ILToken(p, 4, parseInlineType()); break;
						//case OperandType.InlineVar: 
						case OperandType.ShortInlineBrTarget: ret[p] = new ILToken(p, 1, (sbyte)this.il[this.position++]); break;

						case OperandType.ShortInlineI: ret[p] = new ILToken(p, 1, (sbyte)this.il[this.position++]); break;
						case OperandType.ShortInlineR: ret[p] = new ILToken(p, 4, this.EatFloat32()); break;
						case OperandType.ShortInlineVar: ret[p] = new ILToken(p, 1, this.il[this.position++]); break;
						case OperandType.InlineSwitch: ret[p] = new ILToken(p, 4, this.EatInt32()); break;
						default:
							ThrowHelper.Method.Throw(this.method, this.position, "Not supported OperandType.{0}.", opCode.OperandType.ToString());
							break;
					}
			}
			return ret;
		}
Ejemplo n.º 35
0
        MethodBodyReader(MethodBase method)
        {
            this.method = method;

            this.body = method.GetMethodBody();
            if (this.body == null)
                throw new ArgumentException();

            var bytes = body.GetILAsByteArray();
            if (bytes == null)
                throw new ArgumentException();

            if (!(method is ConstructorInfo))
                method_arguments = method.GetGenericArguments();

            if (method.DeclaringType != null)
                type_arguments = method.DeclaringType.GetGenericArguments();

            this.parameters = method.GetParameters();
            this.locals = body.LocalVariables;
            this.module = method.Module;
            this.il = new ByteBuffer(bytes);
        }
Ejemplo n.º 36
0
 public static IList<Instruction> GetInstructions(MethodBase method)
 {
     var mb = method.GetMethodBody();
     if (mb == null)
     {
         return new List<Instruction>();
     }
     var reader = new MethodBodyReader(method, mb);
     reader.ReadInstructions();
     return reader.instructions;
 }
Ejemplo n.º 37
0
 /// <summary>
 /// Gets the IL byte array of the method.
 /// </summary>
 /// <param name="mb"></param>
 /// <returns></returns>
 public static byte[] GetMethodBody(MethodBase mb)
 {
     var emptyArray = new byte[0];
     if (mb == null)
         return emptyArray;
     var body = mb.GetMethodBody();
     return body == null ? emptyArray : body.GetILAsByteArray();
 }