Invoke() public abstract method

When overridden in a derived class, invokes the reflected method or constructor with the given parameters.
The parameter is null and the method is not static.-or- The method is not declared or inherited by the class of . -or-A static constructor is invoked, and is neither null nor an instance of the class that declared the constructor. The type of the parameter does not match the signature of the method or constructor reflected by this instance. The array does not have the correct number of arguments. The invoked method or constructor throws an exception. The caller does not have permission to execute the constructor. The type that declares the method is an open generic type. That is, the property returns true for the declaring type.
public abstract Invoke ( object obj, BindingFlags invokeAttr, Binder binder, object parameters, CultureInfo culture ) : object
obj object The object on which to invoke the method or constructor. If a method is static, this argument is ignored. If a constructor is static, this argument must be null or an instance of the class that defines the constructor.
invokeAttr BindingFlags A bitmask that is a combination of 0 or more bit flags from . If is null, this parameter is assigned the value ; thus, whatever you pass in is ignored.
binder Binder An object that enables the binding, coercion of argument types, invocation of members, and retrieval of MemberInfo objects via reflection. If is null, the default binder is used.
parameters object An argument list for the invoked method or constructor. This is an array of objects with the same number, order, and type as the parameters of the method or constructor to be invoked. If there are no parameters, this should be null.If the method or constructor represented by this instance takes a ByRef parameter, there is no special attribute required for that parameter in order to invoke the method or constructor using this function. Any object in this array that is not explicitly initialized with a value will contain the default value for that object type. For reference-type elements, this value is null. For value-type elements, this value is 0, 0.0, or false, depending on the specific element type.
culture CultureInfo An instance of CultureInfo used to govern the coercion of types. If this is null, the CultureInfo for the current thread is used. (This is necessary to convert a String that represents 1000 to a Double value, for example, since 1000 is represented differently by different cultures.)
return object
        static StackObject *Invoke_0(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, 3);

            ptr_of_this_method = ILIntepreter.Minus(__esp, 1);
            System.Object[] @parameters = (System.Object[]) typeof(System.Object[]).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack));
            __intp.Free(ptr_of_this_method);

            ptr_of_this_method = ILIntepreter.Minus(__esp, 2);
            System.Object @obj = (System.Object) typeof(System.Object).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack));
            __intp.Free(ptr_of_this_method);

            ptr_of_this_method = ILIntepreter.Minus(__esp, 3);
            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.Invoke(@obj, @parameters);

            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, true));
            }
            return(ILIntepreter.PushObject(__ret, __mStack, result_of_this_method, true));
        }
        /// <summary>
        /// Gets validation messages for children objects.
        /// </summary>
        /// <returns>A collection of validation messages for any filled in children properties</returns>
        protected List <ValidationError> GetChildrenValidationErrors()
        {
            List <ValidationError> validationErrors = new List <ValidationError>();

            Dictionary <string, PropertyInfo> properties = GetPropertyList(ColumnType.SaveableChildEntities);

            foreach (string key in properties.Keys)
            {
                object currentValue = GetPropertyValue(this, properties[key]);

                if (currentValue != null)
                {
                    System.Reflection.MethodInfo methodInfo = EntityBase.GetValidationMethod(currentValue);

                    if (methodInfo != null)
                    {
                        System.Reflection.MethodBase methodBase = (System.Reflection.MethodBase)methodInfo;

                        validationErrors.AddRange(methodBase.Invoke(currentValue, null) as List <ValidationError>);
                    }
                }
            }

            return(validationErrors);
        }
        private static TestResult RunTest(object instance, MethodBase method)
        {
            var result = new TestResult { Name = method.Name };

            var sw = new Stopwatch();
            sw.Start();
            try
            {
                method.Invoke(instance, null);
                result.WasSuccessful = true;
            }
            catch (Exception ex)
            {
                result.WasSuccessful = false;
                result.Message = ex.ToString();
            }
            finally
            {
                sw.Stop();

                result.Duration = sw.ElapsedMilliseconds;
            }

            return result;
        }
示例#4
0
        private ServiceEntry Create(string serviceId, MethodBase implementationMethod)
        {
            var type = implementationMethod.DeclaringType;

            return new ServiceEntry
            {
                Descriptor = new ServiceDescriptor
                {
                    Id = serviceId
                },
                Func = parameters =>
                {
                    var instance = _serviceFactory.Create(type);

                    var list = new List<object>();
                    foreach (var parameterInfo in implementationMethod.GetParameters())
                    {
                        var value = parameters[parameterInfo.Name];
                        var parameterType = parameterInfo.ParameterType;

                        var parameter = _typeConvertibleService.Convert(value, parameterType);
                        list.Add(parameter);
                    }

                    var result = implementationMethod.Invoke(instance, list.ToArray());

                    return result;
                }
            };
        }
示例#5
0
        private void ExecutePrivate(MethodBase entryPoint, IEnumerable<string> additionalReferences)
        {
            AppDomain.CurrentDomain.AssemblyResolve += (sender, args) => CurrentDomainOnAssemblyResolve(args.Name, additionalReferences);

            Environment.SetEnvironmentVariable("CSharpRunner_ArtifactsPath", artifactsPath);

            entryPoint.Invoke(entryPoint.DeclaringType, null);
        }
        public Task<object> callAsync(MethodBase method, object[] args)
        {
            Func<object> work = () =>
            {
                return method.Invoke(target, UnwrapArgs(method, args));
            };

            if (queue != null)
                return Task.Factory.StartNew<object>(work, new System.Threading.CancellationToken(false), TaskCreationOptions.None, queue);
            else
                return Task.FromResult<object>(work.Invoke());
        }
        public object call(MethodBase method, object[] args)
        {
            Func<object> work = () =>
            {
                return method.Invoke(target, UnwrapArgs(method, args));
            };

            if (queue != null)
            {
                var t = Task.Factory.StartNew<object>(work, new System.Threading.CancellationToken(false), TaskCreationOptions.None, queue);
                t.Wait();
                return t.Result;
            }
            else
                return work.Invoke();
        }
 private static object FastCall(object o, MethodBase method, ParameterInfo[] Parameters, object[] args, Type objType, IReflect objIReflect)
 {
     int upperBound = args.GetUpperBound(0);
     for (int i = 0; i <= upperBound; i++)
     {
         ParameterInfo info = Parameters[i];
         object defaultValue = args[i];
         if ((defaultValue is Missing) && info.IsOptional)
         {
             defaultValue = info.DefaultValue;
         }
         args[i] = ObjectType.CTypeHelper(defaultValue, info.ParameterType);
     }
     VBBinder.SecurityCheckForLateboundCalls(method, objType, objIReflect);
     if (((objType != objIReflect) && !method.IsStatic) && !DoesTargetObjectMatch(o, method))
     {
         return InvokeMemberOnIReflect(objIReflect, method, BindingFlags.InvokeMethod, o, args);
     }
     VerifyObjRefPresentForInstanceCall(o, method);
     return method.Invoke(o, args);
 }
示例#9
0
        public void RunTest(MethodBase method)
        {
            try
            {
                LogTestCaseStart(method.Name);
                teststarted = true;
                method.Invoke(this, null);
                LogTestCasePassed(method.Name);

            }

            catch (TargetInvocationException aex)
            {
                Logger.RecordMessage(aex.InnerException.Message, MessageType.Exception, MessageSeverity.Error);
                LogTestCaseFailed(method.Name);

                throw aex.InnerException;
            }
            finally
            {
                teststarted = false;
            }
        }
示例#10
0
        private object HandleVirtualMethods(MethodBase method, object[] args) {
            var methodName = method.Name;

            // Handle properties if they are CMS properties
            if (methodName.StartsWith("get_")) {
                bool propertyExists;
                var currentPage = (CmsPage)_target;
                var propertyName = methodName.Substring(4);
                var propertyData = currentPage.Property.GetPropertyValue(propertyName, out propertyExists);

                if (propertyExists) {
                    return GetPropertyValue(method, propertyData);
                }
            }

            // Handle everything else that isn't a CMS property
            try {
                return method.Invoke(_target, args);
            }
            catch (Exception exception) {
                throw GetExceptionToRethrow(exception);
            }
        }
示例#11
0
		/// <summary>
		/// Invokes the method if this is something that the LazyInitializer can handle
		/// without the underlying proxied object being instantiated.
		/// </summary>
		/// <param name="method">The name of the method/property to Invoke.</param>
		/// <param name="args">The arguments to pass the method/property.</param>
		/// <param name="proxy">The proxy object that the method is being invoked on.</param>
		/// <returns>
		/// The result of the Invoke if the underlying proxied object is not needed.  If the 
		/// underlying proxied object is needed then it returns the result <see cref="AbstractLazyInitializer.InvokeImplementation"/>
		/// which indicates that the Proxy will need to forward to the real implementation.
		/// </returns>
		public virtual object Invoke(MethodBase method, object[] args, object proxy)
		{
			string methodName = method.Name;
			int paramCount = method.GetParameters().Length;

			if (paramCount == 0)
			{
				if (!overridesEquals && methodName == "GetHashCode")
				{
					return IdentityEqualityComparer.GetHashCode(proxy);
				}
				else if (IsUninitialized && method.Equals(getIdentifierMethod))
				{
					return Identifier;
				}
				else if (methodName == "Finalize")
				{
					return null;
				}
				else if ("get_HibernateLazyInitializer".Equals(methodName))
				{
					return this;
				}
			}
			else if (paramCount == 1)
			{
				if (!overridesEquals && methodName == "Equals")
				{
					return IdentityEqualityComparer.Equals(args[0], proxy);
				}
				else if (method.Equals(setIdentifierMethod))
				{
					Initialize();
					Identifier = args[0];
					return InvokeImplementation;
				}
			}
			else if (paramCount == 2)
			{
				// if the Proxy Engine delegates the call of GetObjectData to the Initializer
				// then we need to handle it.  Castle.DynamicProxy takes care of serializing
				// proxies for us, but other providers might not.
				if (methodName == "GetObjectData")
				{
					SerializationInfo info = (SerializationInfo)args[0];
					StreamingContext context = (StreamingContext)args[1]; // not used !?!

					if (Target == null & Session != null)
					{
						EntityKey key = new EntityKey(Identifier, Session.Factory.GetEntityPersister(EntityName), Session.EntityMode);
						object entity = Session.PersistenceContext.GetEntity(key);
						if (entity != null)
							SetImplementation(entity);
					}

					// let the specific ILazyInitializer write its requirements for deserialization 
					// into the stream.
					AddSerializationInfo(info, context);

					// don't need a return value for proxy.
					return null;
				}
			}

			//if it is a property of an embedded component, invoke on the "identifier"
			if (componentIdType != null && componentIdType.IsMethodOf(method))
			{
				return method.Invoke(Identifier, args);
			}

			return InvokeImplementation;
		}
 public override bool Rewrite(CodeDescriptor decompilee, MethodBase callee, StackElement[] args, IDecompiler stack, IFunctionBuilder builder)
 {
     object[] vargs = args.Select(arg => arg.Sample).ToArray();
     Expression[] eargs = args.Select(arg => arg.Expr).ToArray();
     object sample = null;
     try
     {
         sample = callee.Invoke(vargs);
     }
     catch (Exception)
     {
     }
     Expression result = new BinOp()
     {
         Operation = Kind
     };
     Array.Copy(eargs, result.Children, 2);
     if (sample != null)
         result.ResultType = TypeDescriptor.GetTypeOf(sample);
     else
     {
         Type rtype;
         callee.IsFunction(out rtype);
         result.ResultType = (TypeDescriptor)rtype;
     }
     stack.Push(result, sample);
     return true;
 }
示例#13
0
 /// <summary>
 /// Execute the method via reflection mode
 /// </summary>
 /// <param name="component">Component that the method is defined</param>
 /// <param name="method">Method to be executed</param>
 /// <param name="parameters">Parameters needed to execute the method</param>
 public static object InvoqueMethod(object component, MethodBase method, object[] parameters)
 {
     try
     {
         return method.Invoke(component, parameters);
     }
     catch (Exception e)
     {
         throw e.InnerException;
     }
 }
 private void InvokeSetupMethod(MethodBase method)
 {
     if (method == null) return;
     try
     {
         method.Invoke(_testInstance, new Object[0]);
     }
     catch
     {
         Debug.LogError(string.Format("[{2}] {0}.{1}", _testType, method.Name, "FAIL"));
     }
 }
示例#15
0
        /// <summary>
        /// Invoke an API method, using the node's lacing strategy to build lists of arguments
        /// </summary>
        /// <param name="node">The node.</param>
        /// <param name="args">The incoming Values on the node.</param>
        /// <param name="api_base_type">The API's base type whose method we will invoke.</param>
        /// <param name="pi">An array of parameter info for the method.</param>
        /// <param name="mi">The method info for the method.</param>
        /// <param name="return_type">The expected return type from the method.</param>
        /// <returns></returns>
        public static Value InvokeAPIMethod(dynRevitTransactionNode node, FSharpList<Value> args, Type api_base_type, ParameterInfo[] pi, MethodBase mi, Type return_type)
        {
            //if any argument are a list, honor the lacing strategy
            //compile a list of parameter lists to be used in our method invocation
            List<List<object>> parameters = null;

            switch (node.ArgumentLacing)
            {
                case LacingStrategy.Single:
                    parameters = GetSingleArguments(args, pi);
                    break;
                case LacingStrategy.Shortest:
                    parameters = GetShortestArguments(args, pi);
                    break;
                case LacingStrategy.Longest:
                    parameters = GetLongestArguments(args, pi);
                    break;
                default:
                    parameters = GetSingleArguments(args, pi);
                    break;
            }

            var invocationTargetList = new List<object>();

            if (api_base_type == typeof(Autodesk.Revit.Creation.Document) ||
                api_base_type == typeof(Autodesk.Revit.Creation.FamilyItemFactory) ||
                api_base_type == typeof(Autodesk.Revit.Creation.ItemFactoryBase))
            {
                if (dynRevitSettings.Doc.Document.IsFamilyDocument)
                {
                    invocationTargetList.Add(dynRevitSettings.Doc.Document.FamilyCreate);
                }
                else
                {
                    invocationTargetList.Add(dynRevitSettings.Doc.Document.Create);
                }
            }
            else if (api_base_type == typeof(Autodesk.Revit.Creation.Application))
            {
                invocationTargetList.Add(dynRevitSettings.Revit.Application.Create);
            }
            else
            {
                if (!mi.IsStatic && !mi.IsConstructor)
                {
                    if (args[0].IsList)
                    {
                        invocationTargetList.AddRange(((Value.List)args[0]).Item.Select(x => DynamoTypeConverter.ConvertInput(x, api_base_type)));
                    }
                    else
                    {
                        //the first input will always hold the instance
                        //whose methods you want to invoke
                        invocationTargetList.Add(DynamoTypeConverter.ConvertInput(args[0], api_base_type));
                    }
                }
            }

            //object result = null;
            List<object> results = null;

            //if the method info is for a constructor, then
            //call the constructor for each set of parameters
            //if it's an instance method, then invoke the method for
            //each instance passed in.
            results = mi.IsConstructor ?
                parameters.Select(x => ((ConstructorInfo) mi).Invoke(x.ToArray())).ToList() :
                invocationTargetList.SelectMany(x => parameters.Select(y => mi.Invoke(x, y.ToArray())).ToList()).ToList();

            dynRevitUtils.StoreElements(node, results);

            return ConvertAllResults(results);
        }
		protected static object InvokeAndUnwrapException(MethodBase mb, object obj, object[] args)
		{
#if FIRST_PASS
			return null;
#else
			try
			{
				return mb.Invoke(obj, args);
			}
			catch (TargetInvocationException x)
			{
				throw ikvm.runtime.Util.mapException(x.InnerException);
			}
#endif
		}
示例#17
0
 private bool InvokeMethod(MethodBase mi) {
    if(mi != null) {
       try {
          var ci = mi as ConstructorInfo;
          if(ci != null) {
             _fixtureInstance = ci.Invoke(new object[] { });
          }
          else {
             mi.Invoke(FixtureInstance, new object[0]);
          }
       }
       catch(ThreadAbortException) {
          throw;
       }
       catch(Exception e) {
          ReportException(e, FullName, mi.Name);
          return false;
       }
    }
    return true;
 }
示例#18
0
		public static object InvokeMethod (MethodBase method, object instance, params object[] args)
		{
			return method.Invoke (instance, args);
		}
        private int DeobfString(MethodDefinition searchInMethod, MethodDefinition searchForMethod, 
            MethodBase calledMethod, int fromIndex)
        {
            if (_options.IgnoredMethodFile.IsMatch(searchForMethod)) return 0;
            if (searchInMethod == null || !searchInMethod.HasBody) return 0;
            if (searchInMethod.MetadataToken == searchForMethod.MetadataToken) return 0;
            if (searchForMethod.ReturnType.FullName != "System.String" && searchForMethod.ReturnType.FullName != "System.Object") return 0;

            Mono.Cecil.Cil.MethodBody body = searchInMethod.Body;
            Collection<Instruction> instructions = body.Instructions;

            int deobfCount = 0;
            int errorCount = 0;

            for (int i = fromIndex; i < instructions.Count; i++)
            {
                Instruction ins = instructions[i];
                if (ins.OpCode != OpCodes.Call) continue;
                MethodDefinition operand = Resolve(ins.Operand as MethodReference);
                if (operand == null) continue;
                if (operand.MetadataToken != searchForMethod.MetadataToken) continue;

                int startIndex;
                object[] p = SearchParameters(searchForMethod, i, searchInMethod, out startIndex);
                if (p == null) continue;

                #region invoke method
                object o;
                try
                {
                    o = calledMethod.Invoke(null, p);
                }
                catch(Exception ex)
                {                    
                    o = null;
                    errorCount++;

                    while (ex.InnerException != null)
                        ex = ex.InnerException;
                    string errMsg = String.Format("Error when calling 0x{0:x08} ({1}): {2}",
                        calledMethod.MetadataToken,
                        calledMethod.ToString(),
                        ex.Message
                        );
                    _options.AppendTextInfoLine(errMsg, true);
                }

                if (o != null)
                {
                    if (searchForMethod.ReturnType.FullName != "System.String" && o.GetType().FullName != "System.String")
                        continue;

                    string oStr = (string)o;
                    if (_options.IgnoredMethodFile.IgnoreMethodsReturnPath && (Directory.Exists(oStr) || File.Exists(oStr)))
                        continue;

                    ILProcessor ilp = searchInMethod.Body.GetILProcessor();
                    //int size = 0;
                    for (int j = startIndex; j <= i; j++)
                    {
                        //size += instructions[i_1].GetSize();

                        //there is problem for remove operation, not consider br reference
                        //ilp.Remove(instructions[i_1]);//the instruction move up, so always is startIndex

                        //here we don't want to insert nop, otherwise index will be wrong
                        InsUtils.ToNop(ilp, instructions, j, false);
                    }

                    //insert may break br reference
                    //Instruction insertIns = ilp.Create(OpCodes.Ldstr, (string)o);
                    //int insertSize = insertIns.GetSize();
                    //ilp.InsertBefore(instructions[i_1], insertIns);

                    //set the last instruction so br reference is ok
                    instructions[i].OpCode = OpCodes.Ldstr;
                    instructions[i].Operand = oStr;

                    deobfCount++;
                }

                if (errorCount > this.Options.IgnoredMethodFile.MaxCallError)
                {
                    this.Options.IgnoredMethodFile.Ignore(searchForMethod.ToString());
                    break;
                }

                #endregion invoke method
            }

            if (deobfCount > 0)
            {
                InsUtils.ComputeOffsets(instructions);
            }
            return deobfCount;
        }
        public int DeobfBoolFunction(MethodDefinition searchInMethod, MethodDefinition searchForMethod, MethodBase mb)
        {
            int count = 0;
            
            if (_options.IgnoredMethodFile.IsMatch(searchForMethod)) return count;
            if (searchInMethod == null || !searchInMethod.HasBody) return count;
            if (searchInMethod.MetadataToken == searchForMethod.MetadataToken) return count;
            if (searchForMethod.ReturnType.FullName != "System.Boolean") return count;
            if (searchForMethod.Parameters.Count != 0) return count;

            Mono.Cecil.Cil.MethodBody body = searchInMethod.Body;
            Collection<Instruction> instructions = body.Instructions;

            //bool hasDeobf = false;

            for (int i = 0; i < instructions.Count; i++)
            {
                Instruction ins = instructions[i];
                if (ins.OpCode != OpCodes.Call) continue;
                MethodDefinition operand = ins.Operand as MethodDefinition;
                if (operand == null) continue;
                if (operand.MetadataToken != searchForMethod.MetadataToken) continue;

                #region invoke method
                object o;
                try
                {
                    o = mb.Invoke(null, null);
                }
                catch(Exception ex)
                {
                    o = null;
                    _options.IgnoredMethodFile.Ignore(searchForMethod.ToString());

                    while (ex.InnerException != null)
                        ex = ex.InnerException;
                    string errMsg = String.Format("Error when calling 0x{0:x08} ({1}): {2}",
                        mb.MetadataToken,
                        mb.ToString(),
                        ex.Message
                        );
                    _options.AppendTextInfoLine(errMsg, true);

                }

                if (o != null)
                {
                    if (Convert.ToBoolean(o))
                    {
                        instructions[i].OpCode = OpCodes.Ldc_I4_1;
                    }
                    else
                    {
                        instructions[i].OpCode = OpCodes.Ldc_I4_0;
                    }
                    instructions[i].Operand = null;
                    count++;
                    //hasDeobf = true;
                }
                else
                {
                    break;
                }

                #endregion invoke method
            }

            if (count > 0)
            {
                InsUtils.ComputeOffsets(instructions);
            }
            return count;
        }
示例#21
0
        private static void InitializeLocalExecutor(ILocalExecutor executor, MethodBase methodFromHandle)
        {
            // Check if method expects IBluepathCommunicationFramework object
            var methodParameters = methodFromHandle.GetParameters();
            var communicationFrameworkObjectType = typeof(IBluepathCommunicationFramework);
            int? parameterIndex = -1;
            var parameterFound = false;
            Type returnType = null;

            foreach (var parameter in methodParameters)
            {
                parameterIndex++;
                if (parameter.ParameterType == communicationFrameworkObjectType)
                {
                    parameterFound = true;
                    break;
                }
            }

            if (methodFromHandle is MethodInfo)
            {
                returnType = ((MethodInfo)methodFromHandle).ReturnType;
            }

            executor.InitializeNonGeneric(
                (parameters) => methodFromHandle.Invoke(null, parameters),
                methodParameters.Length,
                parameterFound ? parameterIndex : null,
                methodParameters,
                returnType);
        }
示例#22
0
        //Execution using strongly typed enumerations. Working implementation will be converted native integer values
        //  to allow native MSIL instruction
        public object ExecuteTyped(List <ILInstruction> stream,
                                   IILInstructionResolver resolver = null,
                                   object[] args             = null,
                                   ILVariable[] locals       = null,
                                   ILOperandStack frameStack = null)
        {
            //getArglistHandle(__arglist(1, 2, "s", 8)); <-- can't support dynamic/reflection based invocation
            //  probably best we can do is detect varargs, convert them to object[] and reinterprit msil.
            //  for now will just have to throw excpetion.


            if (resolver is null)
            {
                resolver = ILInstructionResolver.ExecutingAssemblyResolver;
            }

            var resolveField     = resolver.ResolveFieldToken;
            var resolveMember    = resolver.ResolveMemberToken;
            var resolveMethod    = resolver.ResolveMethodToken;
            var resolveSignature = resolver.ResolveSignatureToken;
            var resolveString    = resolver.ResolveStringToken;
            var resolveType      = resolver.ResolveTypeToken;



            var                   stack = frameStack ?? new ILOperandStack();
            ILInstruction         current;
            OpCode                code;
            int                   pos      = -1;
            Dictionary <int, int> jmptable = stream.ToDictionary(x => (int)x.ByteIndex, x => ++ pos);

            pos = -1;
            goto Inc;

ReadNext:
            current = stream[pos];
            code    = current.OpCode;

            short opCodeValue = code.Value;

            switch (opCodeValue)
            {
            case (short)ILOpCodeValues.Nop: break;

            case (short)ILOpCodeValues.Ret: goto Ret;

            case (short)ILOpCodeValues.Stloc_0:
                locals[0].Value = stack.Pop();
                break;

            case (short)ILOpCodeValues.Stloc_1:
                locals[1].Value = stack.Pop();
                break;

            case (short)ILOpCodeValues.Stloc_2:
                locals[2].Value = stack.Pop();
                break;

            case (short)ILOpCodeValues.Stloc_3:
                locals[3].Value = stack.Pop();
                break;

            case unchecked ((short)ILOpCodeValues.Stloc):
                locals[(int)current.Arg].Value = stack.Pop();
                break;

            case (short)ILOpCodeValues.Stloc_S:
                locals[(byte)current.Arg].Value = stack.Pop();
                break;

            case (short)ILOpCodeValues.Stobj:
                throw new NotImplementedException();

            case (short)ILOpCodeValues.Ldloc_0:
                stack.Push(locals[0].Value);
                break;

            case (short)ILOpCodeValues.Ldloc_1:
                stack.Push(locals[1].Value);
                break;

            case (short)ILOpCodeValues.Ldloc_2:
                stack.Push(locals[2].Value);
                break;

            case (short)ILOpCodeValues.Ldloc_3:
                stack.Push(locals[3].Value);
                break;

            case unchecked ((short)ILOpCodeValues.Ldloc):
                stack.Push(locals[(int)current.Arg].Value);
                break;

            case (short)ILOpCodeValues.Ldloc_S:
                stack.Push(locals[(byte)current.Arg].Value);
                break;

            case unchecked ((short)ILOpCodeValues.Ldloca):
                stack.Push(locals[(int)current.Arg]);
                break;

            case (short)ILOpCodeValues.Ldloca_S:
                stack.Push(locals[(byte)current.Arg]);
                break;

            case (short)ILOpCodeValues.Ldarg_0:
                stack.Push(args[0]);
                break;

            case (short)ILOpCodeValues.Ldarg_1:
                stack.Push(args[1]);
                break;

            case (short)ILOpCodeValues.Ldarg_2:
                stack.Push(args[2]);
                break;

            case (short)ILOpCodeValues.Ldarg_3:
                stack.Push(args[3]);
                break;

            case unchecked ((short)ILOpCodeValues.Ldarg):
                stack.Push(args[(int)current.Arg]);
                break;

            case unchecked ((short)ILOpCodeValues.Ldarg_S):
                stack.Push(args[(byte)current.Arg]);
                break;

            case (short)ILOpCodeValues.Ldarga_S:
                stack.Push(args[(byte)current.Arg]);
                break;

            case unchecked ((short)ILOpCodeValues.Ldarga):
                stack.Push(args[(int)current.Arg]);
                break;

            case (short)ILOpCodeValues.Ldc_I4:
                stack.Push((int)current.Arg);
                break;

            case (short)ILOpCodeValues.Ldc_I4_0:
                stack.Push(0);
                break;

            case (short)ILOpCodeValues.Ldc_I4_1:
                stack.Push(1);
                break;

            case (short)ILOpCodeValues.Ldc_I4_2:
                stack.Push(2);
                break;

            case (short)ILOpCodeValues.Ldc_I4_3:
                stack.Push(3);
                break;

            case (short)ILOpCodeValues.Ldc_I4_4:
                stack.Push(4);
                break;

            case (short)ILOpCodeValues.Ldc_I4_5:
                stack.Push(5);
                break;

            case (short)ILOpCodeValues.Ldc_I4_6:
                stack.Push(6);
                break;

            case (short)ILOpCodeValues.Ldc_I4_7:
                stack.Push(7);
                break;

            case (short)ILOpCodeValues.Ldc_I4_8:
                stack.Push(8);
                break;

            case (short)ILOpCodeValues.Ldc_I4_S:
                stack.Push(Convert.ToInt32(current.Arg));
                break;

            case (short)ILOpCodeValues.Ldc_I4_M1:
                stack.Push(-1);
                break;

            case (short)ILOpCodeValues.Ldc_I8:
                stack.Push(Convert.ToInt64(current.Arg));
                break;

            case (short)ILOpCodeValues.Ldc_R4:
                stack.Push(Convert.ToSingle(current.Arg));
                break;

            case (short)ILOpCodeValues.Ldc_R8:
                stack.Push(Convert.ToDouble(current.Arg));
                break;

            case (short)ILOpCodeValues.Box:     // 140: //box
                stack.Push(((object)stack.Pop()));
                break;

            case (short)ILOpCodeValues.Ckfinite:     // 195: //ckfinite
                var ckval = stack.Pop(); stack.Push((ckval is float?float.IsInfinity((float)ckval) : double.IsInfinity((double)ckval)));
                break;

            case (short)ILOpCodeValues.Conv_I1:    // 103: //conv.i1
                stack.Push(unchecked ((sbyte)Convert.ToInt64(stack.Pop())));
                break;

            case (short)ILOpCodeValues.Conv_I2:     //104: //conv.i2
                stack.Push(unchecked ((short)Convert.ToInt64(stack.Pop())));
                break;

            case (short)ILOpCodeValues.Conv_I4:     //105: //conv.i4
                stack.Push(unchecked ((int)Convert.ToInt64(stack.Pop())));
                break;

            case (short)ILOpCodeValues.Conv_I8:     //106: //conv.i8
            {
                var arg = stack.Pop();
                try
                {
                    stack.Push(unchecked (Convert.ToInt64(arg)));
                }
                catch
                {
                    stack.Push(unchecked ((long)Convert.ToUInt64(arg)));
                }
            }

            break;

            case (short)ILOpCodeValues.Conv_Ovf_I1:     //179: //conv.ovf.i1
                stack.Push(checked ((sbyte)Convert.ToInt64(stack.Pop())));
                break;

            case (short)ILOpCodeValues.Conv_Ovf_I1_Un:     //130: //conv.ovf.i1.un
                stack.Push(checked ((sbyte)Convert.ToUInt64(stack.Pop())));
                break;

            case (short)ILOpCodeValues.Conv_Ovf_I2:     //181: //conv.ovf.i2
                stack.Push(checked ((short)Convert.ToInt64(stack.Pop())));
                break;

            case (short)ILOpCodeValues.Conv_Ovf_I2_Un:     //131: //conv.ovf.i2.un
                stack.Push(checked ((short)Convert.ToUInt64(stack.Pop())));
                break;

            case (short)ILOpCodeValues.Conv_Ovf_I4:     //183: //conv.ovf.i4
                stack.Push(checked ((int)Convert.ToInt64(stack.Pop())));
                break;

            case (short)ILOpCodeValues.Conv_Ovf_I4_Un:     //132: //conv.ovf.i4.un
                stack.Push(checked ((int)Convert.ToUInt64(stack.Pop())));
                break;

            case (short)ILOpCodeValues.Conv_Ovf_I8:     //185: //conv.ovf.i8
                stack.Push(checked ((long)Convert.ToInt64(stack.Pop())));
                break;

            case (short)ILOpCodeValues.Conv_Ovf_I8_Un:     //133: //conv.ovf.i8.un
                stack.Push(checked ((long)Convert.ToUInt64(stack.Pop())));
                break;

            case (short)ILOpCodeValues.Conv_Ovf_U1:     //180: //conv.ovf.u1
                stack.Push(checked ((byte)Convert.ToInt64(stack.Pop())));
                break;

            case (short)ILOpCodeValues.Conv_Ovf_U1_Un:     //134: //conv.ovf.u1.un
                stack.Push(checked ((byte)Convert.ToUInt64(stack.Pop())));
                break;

            case (short)ILOpCodeValues.Conv_Ovf_U2:     //182: //conv.ovf.u2
                stack.Push(checked ((ushort)Convert.ToInt64(stack.Pop())));
                break;

            case (short)ILOpCodeValues.Conv_Ovf_U2_Un:     //135: //conv.ovf.u2.un
                stack.Push(checked ((ushort)Convert.ToUInt64(stack.Pop())));
                break;

            case (short)ILOpCodeValues.Conv_Ovf_U4:     //184: //conv.ovf.u4
                stack.Push(checked ((uint)Convert.ToInt64(stack.Pop())));
                break;

            case (short)ILOpCodeValues.Conv_Ovf_U4_Un:     //136: //conv.ovf.u4.un
                stack.Push(checked ((uint)Convert.ToUInt64(stack.Pop())));
                break;

            case (short)ILOpCodeValues.Conv_Ovf_U8:     //186: //conv.ovf.u8
                stack.Push(checked ((ulong)Convert.ToInt64(stack.Pop())));
                break;

            case (short)ILOpCodeValues.Conv_Ovf_U8_Un:     //137: //conv.ovf.u8.un
                stack.Push(checked ((ulong)Convert.ToUInt64(stack.Pop())));
                break;

            case (short)ILOpCodeValues.Conv_R4:     //107: //conv.r4
                stack.Push(Convert.ToSingle(stack.Pop()));
                break;

            case (short)ILOpCodeValues.Conv_R8:     //108: //conv.r8
                stack.Push(Convert.ToDouble(stack.Pop()));
                break;

            case (short)ILOpCodeValues.Conv_R_Un:     //118: //conv.r.un
                stack.Push(Convert.ToSingle(stack.Pop()));
                break;

            case (short)ILOpCodeValues.Conv_U1:     //210: //conv.u1
                stack.Push(unchecked (Convert.ToByte(stack.Pop())));
                break;

            case (short)ILOpCodeValues.Conv_U2:     //209: //conv.u2
                stack.Push(unchecked (Convert.ToUInt16(stack.Pop())));
                break;

            case (short)ILOpCodeValues.Conv_U4:     //109: //conv.u4
                stack.Push(unchecked ((uint)(Convert.ToInt64(stack.Pop()))));
                break;

            case (short)ILOpCodeValues.Conv_U8:     //110: //conv.u8
                stack.Push(unchecked (Convert.ToUInt64(stack.Pop())));
                break;

            case (short)ILOpCodeValues.Neg:     //101: //neg
                stack.Push(-((dynamic)stack.Pop()));
                break;

            case (short)ILOpCodeValues.Newarr:     //141: //newarr
                stack.Push(Array.CreateInstance(((current.Arg is int) ? resolveType((int)current.Arg) : (Type)current.Arg), (int)stack.Pop()));
                break;

            case (short)ILOpCodeValues.Not:     //102: //not
                stack.Push(!((dynamic)stack.Pop()));
                break;

            case (short)ILOpCodeValues.Pop: //38: //pop
                stack.Pop();                // no push
                break;

            case (short)ILOpCodeValues.Shl:     //98: //shl
                stack.Push(((dynamic)stack.Pop()) << ((int)current.Arg));
                break;

            case (short)ILOpCodeValues.Shr:     //99: //shr
                stack.Push(((dynamic)stack.Pop()) >> ((int)current.Arg));
                break;

            case (short)ILOpCodeValues.Shr_Un:     //100: //shr.un
                stack.Push(((dynamic)stack.Pop()) >> ((int)current.Arg));
                break;

            case (short)ILOpCodeValues.Unbox:     //121: //unbox
                stack.Push(Convert.ChangeType(stack.Pop(), resolveType((int)current.Arg)));
                break;

            case (short)ILOpCodeValues.Unbox_Any:     //165: //unbox.any
                stack.Push(Convert.ChangeType(stack.Pop(), resolveType((int)current.Arg)));
                break;

            case (short)ILOpCodeValues.Add:     //: //add
                stack.Push(unchecked ((dynamic)stack.Pop() + (dynamic)stack.Pop()));
                break;

            case (short)ILOpCodeValues.Add_Ovf:     // 214: //add.ovf
                stack.Push(checked ((dynamic)stack.Pop() + (dynamic)stack.Pop()));
                break;

            case (short)ILOpCodeValues.Add_Ovf_Un:     // 215: //add.ovf.un
                stack.Push(checked ((dynamic)stack.Pop() + (dynamic)stack.Pop()));
                break;

            case (short)ILOpCodeValues.And:     //95: //and
                stack.Push(((dynamic)stack.Pop()) & ((dynamic)stack.Pop()));
                break;

            case unchecked ((short)ILOpCodeValues.Ceq):    //: //ceq
            {
                var opa = stack.Pop();
                var opb = stack.Pop();

                if (opa is IConvertible && opb is IConvertible)
                {
                    var compc = ((IComparable)(opa)).CompareTo(Convert.ChangeType(opb, Convert.GetTypeCode(opa)));
                    stack.Push(compc == 0 ? 1 : 0);
                }
                else
                {
                    stack.Push(Convert.ToInt32(((dynamic)opa) == ((dynamic)opb)));
                }
            }

            break;

            case unchecked ((short)ILOpCodeValues.Cgt):    // -510: //cgt
                stack.Push(Convert.ToInt32(((dynamic)stack.Pop()) < ((dynamic)stack.Pop())));
                break;

            case unchecked ((short)ILOpCodeValues.Cgt_Un):    //- 509: //cgt.un
                stack.Push(Convert.ToInt32(((dynamic)stack.Pop()) < ((dynamic)stack.Pop())));
                break;

            case unchecked ((short)ILOpCodeValues.Clt):                                       // -508: //clt
                stack.Push(Convert.ToInt32(((dynamic)stack.Pop()) > ((dynamic)stack.Pop()))); //either swap pop order or sign
                break;

            case unchecked ((short)ILOpCodeValues.Clt_Un):    // -507: //clt.un
                stack.Push(Convert.ToInt32(((dynamic)stack.Pop()) > ((dynamic)stack.Pop())));
                break;

            case unchecked ((short)ILOpCodeValues.Div):    // 91: //div
                stack.Push(((dynamic)stack.Pop()) / ((dynamic)stack.Pop()));
                break;

            case unchecked ((short)ILOpCodeValues.Div_Un):    // 92: //div.un
                stack.Push(((dynamic)stack.Pop()) / ((dynamic)stack.Pop()));
                break;

            case unchecked ((short)ILOpCodeValues.Mul):    // 90: //mul
                stack.Push(unchecked (((dynamic)stack.Pop()) * ((dynamic)stack.Pop())));
                break;

            case unchecked ((short)ILOpCodeValues.Mul_Ovf):    // 216: //mul.ovf
                stack.Push(((dynamic)stack.Pop()) * ((dynamic)stack.Pop()));
                break;

            case unchecked ((short)ILOpCodeValues.Mul_Ovf_Un):    // 217: //mul.ovf.un
                stack.Push(((dynamic)stack.Pop()) * ((dynamic)stack.Pop()));
                break;

            case unchecked ((short)ILOpCodeValues.Or):    // 96: //or
                stack.Push(((dynamic)stack.Pop()) | ((dynamic)stack.Pop()));
                break;

            case unchecked ((short)ILOpCodeValues.Rem):    // 93: //rem
                stack.Push(((dynamic)stack.Pop()) % ((dynamic)stack.Pop()));
                break;

            case unchecked ((short)ILOpCodeValues.Rem_Un):    // 94: //rem.un
                stack.Push(((dynamic)stack.Pop()) % ((dynamic)stack.Pop()));
                break;

            case unchecked ((short)ILOpCodeValues.Sub):    // 89: //sub
                stack.Push(unchecked (((dynamic)stack.Pop()) - ((dynamic)stack.Pop())));
                break;

            case unchecked ((short)ILOpCodeValues.Sub_Ovf):    // 218: //sub.ovf
                stack.Push(((dynamic)stack.Pop()) - ((dynamic)stack.Pop()));
                break;

            case unchecked ((short)ILOpCodeValues.Sub_Ovf_Un):    // 219: //sub.ovf.un
                stack.Push(((dynamic)stack.Pop()) - ((dynamic)stack.Pop()));
                break;

            case unchecked ((short)ILOpCodeValues.Xor):    // 97: //xor
                stack.Push(((dynamic)stack.Pop()) ^ ((dynamic)stack.Pop()));
                break;

            case (short)ILOpCodeValues.Ldstr:
            {
                if (current.Arg is string)
                {
                    stack.Push((string)current.Arg);
                }
                else
                {
                    stack.Push(resolveString((int)current.Arg));
                }
                break;
            }

            case (short)ILOpCodeValues.Newobj:
            {
                var ctor     = (System.Reflection.ConstructorInfo)resolveMethod((int)current.Arg);
                var ctorArgs = new object[ctor.GetParameters().Length];
                for (var i = ctorArgs.Length - 1; i > -1; i--)
                {
                    ctorArgs[i] = stack.Pop();
                }
                //var reversed = ctorArgs.Reverse().ToArray();
                var ctorResult = ctor.Invoke(ctorArgs);
                stack.Push(ctorResult);
                break;
            }

            case (short)ILOpCodeValues.Ldfld:
            {
                var field  = resolveField((int)current.Arg);
                var target = stack.Pop();
                var value  = field.GetValue(target);
                stack.Push(value);
                break;
            }

            case (short)ILOpCodeValues.Ldsfld:
            {
                var field = resolveField((int)current.Arg);
                var value = field.GetValue(null);
                stack.Push(value);
                break;
            }

            case (short)ILOpCodeValues.Stfld:
            {
                var field  = resolveField((int)current.Arg);
                var fo     = stack.Pop();
                var target = stack.Pop();
                field.SetValue(target, fo);
                //stack.Push(value);
                break;
            }

            case (short)ILOpCodeValues.Stsfld:
            {
                var field = resolveField((int)current.Arg);
                var fo    = stack.Pop();
                //var target = stack.Pop();
                field.SetValue(null, fo);
                break;
            }

            case (short)ILOpCodeValues.Ldlen:
            {
                var array = stack.Pop();
                var arr   = (Array)array;
                stack.Push(arr.Length);
                break;
            }

            case (short)ILOpCodeValues.Stelem:
            {
                object el    = stack.Pop();
                int    index = (int)stack.Pop();
                var    array = (Array)stack.Pop();

                array.GetType()
                .GetMethod("SetValue", new[] { typeof(object), typeof(int) })
                .Invoke(array, new object[] { el, index });
                break;
            }

            case (short)ILOpCodeValues.Stelem_I1:
            {
                object el        = stack.Pop();
                int    index     = (int)stack.Pop();
                var    array     = stack.Pop();
                var    arrType   = array.GetType();
                var    arrElType = arrType.GetElementType();
                var    elType    = el.GetType();
                if (elType == arrElType)
                {
                    ((Array)array).SetValue(el, index);
                }
                else if (arrElType == typeof(sbyte))
                {
                    ((sbyte[])array)[index] = (sbyte)(int)el;
                }
                else
                {
                    ((byte[])array)[index] = (byte)(int)el;
                }
                break;
            }

            case (short)ILOpCodeValues.Stelem_I2:
            {
                object el        = stack.Pop();
                int    index     = (int)stack.Pop();
                var    array     = stack.Pop();
                var    arrType   = array.GetType();
                var    arrElType = arrType.GetElementType();
                var    elType    = el.GetType();

                if (elType == arrElType)
                {
                    ((Array)array).SetValue(el, index);
                }
                else if (arrElType == typeof(short))
                {
                    ((Array)array).SetValue((short)(int)el, index);
                }
                else if (arrElType == typeof(short))
                {
                    ((Array)array).SetValue((ushort)(int)el, index);
                }
                else
                {
                    ((Array)array).SetValue(Convert.ChangeType(el, arrElType), index);
                }
                break;
            }

            case (short)ILOpCodeValues.Stelem_I4:
            {
                object el        = stack.Pop();
                int    index     = (int)stack.Pop();
                var    array     = stack.Pop();
                var    arrType   = array.GetType();
                var    arrElType = arrType.GetElementType();
                var    elType    = el.GetType();
                if (elType == arrElType)
                {
                    ((Array)array).SetValue(el, index);
                }
                else if (arrElType == typeof(int))
                {
                    ((int[])array)[index] = (int)el;
                }
                else
                {
                    ((uint[])array)[index] = (uint)el;
                }
                break;
            }

            case (short)ILOpCodeValues.Stelem_I8:
            {
                object el        = stack.Pop();
                int    index     = (int)stack.Pop();
                var    array     = stack.Pop();
                var    arrType   = array.GetType();
                var    arrElType = arrType.GetElementType();
                var    elType    = el.GetType();
                if (elType == arrElType)
                {
                    ((Array)array).SetValue(el, index);
                }
                else if (arrElType == typeof(long))
                {
                    ((long[])array)[index] = (long)el;
                }
                else
                {
                    ((ulong[])array)[index] = (ulong)el;
                }
                break;
            }

            case (short)ILOpCodeValues.Stelem_R4:
            {
                object el        = stack.Pop();
                int    index     = (int)stack.Pop();
                var    array     = stack.Pop();
                var    arrType   = array.GetType();
                var    arrElType = arrType.GetElementType();
                var    elType    = el.GetType();
                if (elType == arrElType)
                {
                    ((Array)array).SetValue(el, index);
                }
                else if (arrElType == typeof(float))
                {
                    ((float[])array)[index] = (float)el;
                }
                //else ((ulong[])array)[index] = (ulong)el;
                break;
            }

            case (short)ILOpCodeValues.Stelem_R8:
            {
                object el        = stack.Pop();
                int    index     = (int)stack.Pop();
                var    array     = stack.Pop();
                var    arrType   = array.GetType();
                var    arrElType = arrType.GetElementType();
                var    elType    = el.GetType();
                if (elType == arrElType)
                {
                    ((Array)array).SetValue(el, index);
                }
                else if (arrElType == typeof(double))
                {
                    ((double[])array)[index] = (double)el;
                }
                //else ((ulong[])array)[index] = (ulong)el;
                break;
            }

            case (short)ILOpCodeValues.Stelem_Ref:
            {
                object val   = stack.Pop();
                int    index = (int)stack.Pop();
                var    array = stack.Pop();
                ((Array)array).SetValue(val, index);
                break;
            }

            case (short)ILOpCodeValues.Ldelem:
            case (short)ILOpCodeValues.Ldelema:
            case (short)ILOpCodeValues.Ldelem_I:
            case (short)ILOpCodeValues.Ldelem_Ref:
            {
                var idx   = (int)stack.Pop();
                var array = (Array)stack.Pop();
                var val   = array.GetValue(idx);
                stack.Push(val);
                break;
            }

            case (short)ILOpCodeValues.Ldelem_I1:
            {
                var idx    = (int)stack.Pop();
                var array  = (Array)stack.Pop();
                var val    = array.GetValue(idx);
                var target = (sbyte)Convert.ToInt32(val);
                stack.Push(target);
                break;
            }

            case (short)ILOpCodeValues.Ldelem_I2:
            {
                var idx    = (int)stack.Pop();
                var array  = (Array)stack.Pop();
                var val    = array.GetValue(idx);
                var target = (short)Convert.ToInt32(val);
                stack.Push(target);
                break;
            }

            case (short)ILOpCodeValues.Ldelem_I4:
            {
                var idx    = (int)stack.Pop();
                var array  = (Array)stack.Pop();
                var val    = array.GetValue(idx);
                var target = Convert.ToInt32(val);
                stack.Push(target);
                break;
            }

            case (short)ILOpCodeValues.Ldelem_I8:
            {
                var idx    = (int)stack.Pop();
                var array  = (Array)stack.Pop();
                var val    = array.GetValue(idx);
                var target = Convert.ToInt64(val);
                stack.Push(target);
                break;
            }

            case (short)ILOpCodeValues.Ldelem_U1:
            {
                var idx    = (int)stack.Pop();
                var array  = (Array)stack.Pop();
                var val    = array.GetValue(idx);
                var target = (byte)Convert.ToUInt32(val);
                stack.Push(target);
                break;
            }

            case (short)ILOpCodeValues.Ldelem_U2:
            {
                var idx    = (int)stack.Pop();
                var array  = (Array)stack.Pop();
                var val    = array.GetValue(idx);
                var target = (ushort)Convert.ToUInt32(val);
                stack.Push(target);
                break;
            }

            case (short)ILOpCodeValues.Ldelem_U4:
            {
                var idx    = (int)stack.Pop();
                var array  = (Array)stack.Pop();
                var val    = array.GetValue(idx);
                var target = Convert.ToUInt32(val);
                stack.Push(target);
                break;
            }

            case (short)ILOpCodeValues.Ldelem_R4:
            {
                var idx    = (int)stack.Pop();
                var array  = (Array)stack.Pop();
                var val    = array.GetValue(idx);
                var target = Convert.ToSingle(val);
                stack.Push(target);
                break;
            }

            case (short)ILOpCodeValues.Ldelem_R8:
            {
                var idx    = (int)stack.Pop();
                var array  = (Array)stack.Pop();
                var val    = array.GetValue(idx);
                var target = Convert.ToDouble(val);
                stack.Push(target);
                break;
            }


            case (short)ILOpCodeValues.Conv_I:
            case (short)ILOpCodeValues.Conv_Ovf_I_Un:
            case (short)ILOpCodeValues.Conv_Ovf_I:
                //Todo: native int operations
                throw new OpCodeNotImplementedException(code);

            case (short)ILOpCodeValues.Dup:
                stack.Push(stack.Peek());
                break;

            //TODO: Implemented scopre validation for branch: (EG, inside try, catch, finally,etc)
            case (short)ILOpCodeValues.Leave_S:
            case (short)ILOpCodeValues.Br_S:     //0x2b:
            {
                var delta     = (int)(sbyte)Convert.ToByte(current.Arg);
                var directpos = (int)stream[pos + 1].ByteIndex + delta;
                pos = jmptable[directpos];
                goto MoveNext;
            }

            case (short)ILOpCodeValues.Leave:
            case (short)ILOpCodeValues.Br:     // 0x38:
            {
                var delta     = Convert.ToInt32(current.Arg);
                var directpos = (int)stream[pos + 1].ByteIndex + delta;
                pos = jmptable[directpos];
                goto MoveNext;
            }

            case (short)ILOpCodeValues.Beq:
            {
                var opa = stack.Pop();
                var opb = stack.Pop();
                if (opa is IConvertible && opb is IConvertible)
                {
                    var compc = ((IComparable)(opa)).CompareTo(Convert.ChangeType(opb, Convert.GetTypeCode(opa)));
                    stack.Push(compc == 0 ? 1 : 0);
                }
                else
                {
                    stack.Push(Convert.ToInt32(((dynamic)opa) == ((dynamic)opb)));
                }
                goto case (short)ILOpCodeValues.Brtrue;
            }

            case (short)ILOpCodeValues.Beq_S:
            {
                var opa = stack.Pop();
                var opb = stack.Pop();

                if (opa is IConvertible && opb is IConvertible)
                {
                    var compc = ((IComparable)(opa)).CompareTo(Convert.ChangeType(opb, Convert.GetTypeCode(opa)));
                    stack.Push(compc == 0 ? 1 : 0);
                }
                else
                {
                    stack.Push(Convert.ToInt32(((dynamic)opa) == ((dynamic)opb)));
                }
                goto case (short)ILOpCodeValues.Brtrue_S;
            }

            case (short)ILOpCodeValues.Brfalse:     //‭00111001‬
            {
                var chk        = stack.Pop();
                int cond       = Convert.ToInt32((chk is IConvertible) ? Convert.ToBoolean(chk) : Convert.ToBoolean(!(chk is null)));
                var condtarget = -1;
                if (cond == 0)
                {
                    condtarget = (int)stream[pos + 1].ByteIndex + Convert.ToInt32(current.Arg);
                    pos        = jmptable[condtarget];
                    goto MoveNext;
                }
                break;
            }

            case (short)ILOpCodeValues.Brfalse_S:
            {
                var chk        = stack.Pop();
                int cond       = Convert.ToInt32((chk is IConvertible) ? Convert.ToBoolean(chk) : Convert.ToBoolean(!(chk is null)));
                var condtarget = -1;
                if (cond == 0)
                {
                    condtarget = (int)stream[pos + 1].ByteIndex + (int)(sbyte)Convert.ToByte(current.Arg);
                    pos        = jmptable[condtarget];
                    goto MoveNext;
                }
                break;
            }

            case (short)ILOpCodeValues.Brtrue:
            {
                var chk        = stack.Pop();
                int cond       = Convert.ToInt32((chk is IConvertible) ? Convert.ToBoolean(chk) : Convert.ToBoolean(!(chk is null)));
                var condtarget = -1;
                if (cond == 1)
                {
                    condtarget = (int)stream[pos + 1].ByteIndex + Convert.ToInt32(current.Arg);
                    pos        = jmptable[condtarget];
                    goto MoveNext;
                }
                break;
            }

            case (short)ILOpCodeValues.Brtrue_S:
            {
                var chk        = stack.Pop();
                int cond       = Convert.ToInt32((chk is IConvertible) ? Convert.ToBoolean(chk) : Convert.ToBoolean(!(chk is null)));
                var condtarget = -1;
                if (cond == 1)
                {
                    condtarget = (int)stream[pos + 1].ByteIndex + (int)(sbyte)Convert.ToByte(current.Arg);
                    pos        = jmptable[condtarget];
                    goto MoveNext;
                }
                break;
            }

            case (short)ILOpCodeValues.Call:
            case (short)ILOpCodeValues.Calli:
            case (short)ILOpCodeValues.Callvirt:
                System.Reflection.MethodBase method = null;
                object resolved = null;
                if (current.Arg is System.Reflection.MethodInfo)
                {
                    method = (System.Reflection.MethodInfo)current.Arg;
                }
                else
                {
                    resolved = resolveMethod((int)current.Arg);
                }


                if (resolved is ConstructorInfo)
                {
                    method = (ConstructorInfo)resolved;
                }
                else
                {
                    method = (System.Reflection.MethodInfo)resolved;
                }

                var parameters = method.GetParameters();
                var methodArgs = new object[parameters.Length];

                for (var i = methodArgs.Length - 1; i >= 0; i--)
                {
                    var val = stack.Pop();
                    if (val is ILVariable)
                    {
                        methodArgs[i] = ((ILVariable)(val)).Value;
                    }
                    else
                    {
                        methodArgs[i] = val;
                    }
                }

                object methodTarget = null;
                if (!method.IsStatic && !method.IsConstructor)
                {
                    methodTarget = stack.Pop();
                }
                if (methodTarget is ILVariable)
                {
                    methodTarget = ((ILVariable)methodTarget).Value;
                }
                //var t = default(RuntimeTypeHandle);
                //var t1 = default(ArgIterator);
                //var tobject = new object[] { t, t };
                //var del = Delegate.CreateDelegate()
                //((ConstructorInfo)method).Invoke( new object[]{ t});
                for (var i = methodArgs.Length - 1; i >= 0; i--)
                {
                    if (methodArgs[i] is IConvertible)
                    {
                        methodArgs[i] = Convert.ChangeType(methodArgs[i], parameters[i].ParameterType);
                    }
                }

                //if the current method is invoking another method then convert the arguments for the inner method.
                if (methodTarget is MethodBase && methodArgs.Length == 2 && methodArgs[1] is Array)
                {
                    var invokeArgs       = (Array)methodArgs[1];
                    var invokeParameters = ((MethodInfo)methodTarget).GetParameters();
                    for (var i = invokeArgs.Length - 1; i >= 0; i--)
                    {
                        var arg = invokeArgs.GetValue(i);
                        if (arg is IConvertible)
                        {
                            invokeArgs.SetValue(Convert.ChangeType(arg, invokeParameters[i].ParameterType), i);
                        }
                    }
                    //if (invokeArgs.GetValue(i) is IConvertible)
                    //    invokeArgs.SetValue(Convert.ChangeType(invokeArgs[i], invokeParameters[i].ParameterType));
                }

                // Roadblock here: Int.CompareTo(object value) -> argument value must be of type int but there is no way to programatically determine the expected destination type.

                var methodresult = (method is MethodInfo) ? method.Invoke(methodTarget, methodArgs) : ((ConstructorInfo)method).Invoke(methodArgs);
                if (code.StackBehaviourPush == StackBehaviour.Varpush)
                {
                    if ((method as MethodInfo)?.ReturnType != typeof(void) || method.IsConstructor)
                    {
                        stack.Push(methodresult);
                    }
                }
                break;

            case unchecked ((short)ILOpCodeValues.Ldobj):
                stack.Push(current.Arg);
                break;

            case (short)ILOpCodeValues.Ldnull:
                stack.Push(null);
                break;

            case unchecked ((short)ILOpCodeValues.Ldftn):
                var ftnToken  = (int)current.Arg;
                var ftnMethod = resolver.ResolveMethodToken(ftnToken);
                stack.Push(ftnMethod.MethodHandle.GetFunctionPointer());
                break;

            case unchecked ((short)ILOpCodeValues.Initobj):

                var newObj = Activator.CreateInstance(resolver.ResolveTypeToken((int)current.Arg));
                var inst   = stack.Pop();
                if (inst is ILVariable ilvar)
                {
                    ilvar.Value         = newObj;
                    locals[ilvar.Index] = ilvar;
                }
                else
                {
                    inst = newObj;
                }

                break;

            case (short)ILOpCodeValues.Ldtoken:
                var metaToken = (int)current.Arg;
                var memToken  = resolver.ResolveMemberToken(metaToken);
                var tokenType = memToken.GetType();


                switch (tokenType.Name)
                {
                case "RtFieldInfo":
                {
                    var fieldInfo = resolver.ResolveFieldToken(metaToken);
                    var handle    = (FieldInfo)fieldInfo;
                    stack.Push(handle.FieldHandle);
                }
                break;

                case "RuntimeType":
                {
                    var type   = resolver.ResolveTypeToken(metaToken);
                    var handle = (Type)type;
                    stack.Push(handle.TypeHandle);
                }

                break;

                default:

                    throw new OpCodeNotImplementedException(code);
                }


                break;

            case (short)ILOpCodeValues.Castclass:

                var targetClassToken = (int)current.Arg;
                var targetType       = resolver.ResolveTypeToken(targetClassToken);

                var listType = typeof(List <>).MakeGenericType(new[] { targetType });
                var instance = Activator.CreateInstance(listType);
                var prop     = listType.GetProperty("Item");
                var src      = stack.Pop();


                var add = listType.GetMethod("Add");
                add.Invoke(instance, new[] { src });
                var get        = listType.GetMethod("get_Item");
                var listresult = get.Invoke(instance, new object[] { 0 });
                stack.Push(listresult);

                break;

            case (short)ILOpCodeValues.Break:
                if (TriggerBreak)
                {
                    System.Diagnostics.Debugger.Break();
                }
                break;

            default:
                throw new OpCodeNotImplementedException(code);
            }


Inc:
            pos++;
MoveNext:
            if (pos < stream.Count)
            {
                goto ReadNext;
            }

Ret:
            var result = (stack.Count > 0) ? stack.Pop() : null;

            if (TriggerBreak)
            {
                System.Diagnostics.Debug.Assert(stack.Count == 0);
            }
            else
            {
                //if (stack.Count > 0) throw new InvalidProgramException("Stack is not empty {stack.Count}");
            }

            return(result);
        }
示例#23
0
        /// <summary>
        /// Intercepts the <see cref="MethodBase"/> in the proxy to return a replaced value.
        /// </summary>
        /// <param name="methodBase">
        /// The <see cref="MethodBase"/> containing information about the current
        /// invoked property.
        /// </param>
        /// <param name="value">
        /// The object to set the <see cref="MethodBase"/> to if it is a setter.
        /// </param>
        /// <returns>
        /// The <see cref="object"/> replacing the original implementation value.
        /// </returns>
        public object Intercept(MethodBase methodBase, object value)
        {
            const string Getter = "get_";
            const string Setter = "set_";
            var name = methodBase.Name;
            var key = name.Substring(4);
            var parameters = value == null ? new object[] { } : new[] { value };

            // Attempt to get the value from the lazy members.
            if (name.StartsWith(Getter))
            {
                if (this.lazyDictionary.ContainsKey(key))
                {
                    return this.lazyDictionary[key].Value;
                }
            }

            // Set the value, remove the old lazy value.
            if (name.StartsWith(Setter))
            {
                if (this.lazyDictionary.ContainsKey(key))
                {
                    this.lazyDictionary.Remove(key);
                }
            }

            return methodBase.Invoke(this.target, parameters);
        }
        ///<summary>
        /// Validate the aspect usage
        ///</summary>
        ///<param name="method">The method that the aspect is applied on</param>
        ///<returns>Returns true if all checks pass</returns>
        public override bool CompileTimeValidate(MethodBase method)
        {
            if (method == null)
            {
                this.RaiseError(1, "The PostCompile aspect can only be applied on methods.", method.AsSignature());

                return false;
            }

            if (!method.IsStatic)
            {
                this.RaiseError(2, "The PostCompile aspect can only be applied on static methods.", method.AsSignature());

                return false;
            }

            if (method.GetParameters().Length > 0)
            {
                this.RaiseError(3, "The PostCompile aspect can only be applied on methods without arguments.", method.AsSignature());

                return false;
            }

            if (method as MethodInfo == null)
            {
                this.RaiseError(4, "The PostCompile aspect can not be applied on constructor/deconstructors", method.AsSignature());

                return false;
            }

            if (((MethodInfo)method).ReturnType != typeof(void))
            {
                this.RaiseError(5, "The PostCompile aspect can only be applied on methods returning nothing.", method.AsSignature());

                return false;
            }

            this.Describe("On compilation, this method will be invoked", method);

            try
            {
                method.Invoke(null, null);
                this.Describe("Last post-compile run succeeded at {0}".F(DateTime.Now), method);
            }
            catch (TargetInvocationException ex) // when this exception is thrown, consider it a success, and optionally check if it has more descriptions to add
            {
                if (ex.InnerException is PostCompileSuccessException)
                {
                    this.Describe("Last post-compile run succeeded at {0}".F(DateTime.Now), method);

                    foreach (var d in (ex.InnerException as PostCompileSuccessException).Descriptions)
                    {
                        this.Describe(d, method);
                    }
                }
                else
                {
                    this.Describe("Last post-compile run failed at {0}".F(DateTime.Now), method);
                    this.Describe(ex.ToString(), method);
                }
            }
            catch (Exception ex)
            {
                this.Describe("Last post-compile run failed at {0}".F(DateTime.Now), method);
                this.Describe(ex.ToString(), method);
            }

            return true;
        }
示例#25
0
        public static object InvokeMethodWithoutTargetInvocationException(MethodBase method, object obj, object[] args)
        {
            if (method == null)
                throw new ArgumentNullException("method");

            try
            {
                return method.Invoke(obj, args);
            }
            catch (TargetInvocationException ex)
            {
                RethrowWithNoStackTraceLoss(ex.InnerException);
                throw;
            }
        }
示例#26
0
        private object NonOwnerInvocationHandler(object target, MethodBase method, object[] parameters)
        {
            object result = null;

            try
            {
                if(method.Name.Equals("set_HotOrNot"))
                {
                    result = method.Invoke(target, parameters);
                }
                else
                {
                    throw new UnauthorizedAccessException("You are not permitted to update another's personal information!");
                }
            }
            catch(ApplicationException ex)
            {
                return ex.StackTrace;
            }

            return result;
        }
示例#27
0
		static object InvokeMethod (MethodBase method, object obj, object [] arguments)
		{
			try {
				return method.Invoke (obj, arguments);
			} catch (TargetInvocationException e) {
				throw e.InnerException;
			}
		}
    public virtual object ExecuteAction(MethodBase targetAction, params object[] arguments)
    {
      if (targetAction == null)
      {
        throw new ArgumentNullException("targetAction");
      }

      if (!targetAction.IsStatic)
      {
        throw new NotSupportedException("Instance methods are not supported");
      }

      return targetAction.Invoke(null, arguments);
    }
        public override bool Rewrite(CodeDescriptor decompilee, MethodBase callee, StackElement[] args, IDecompiler stack, IFunctionBuilder builder)
        {
            Type returnType;
            if (callee.ReturnsSomething(out returnType))
                throw new ArgumentException("The IgnoreOnDecompilation attribute may only be applied to methods returning a void result. Use StaticEvaluation instead.");

            if (_call)
            {
                callee.Invoke(args.Select(a => a.Sample).ToArray());
            }

            return true;
        }
示例#30
0
 public static object Invoke(this MethodBase MethodBase, object Object, params object[] Parameters)
 {
     return(MethodBase.Invoke(Object, Parameters));
 }
        internal static dynamic Invoke(Type targetType, MethodBase minfo, List<FunctionArgument> args,
            SilverScope scope)
        {
            bool isClassMethod = minfo.IsStatic;

            object target = scope.Variables.ContainsKey("self")
                ? scope["self"]
                : isClassMethod ? targetType : targetType.GetConstructor(new Type[] {}).Invoke(null);

            var arguments = new List<object>();
            args.ForEach(arg => {
                dynamic _val = CompilerServices.CompileExpression(arg.Value, scope);
                if (_val is SilverString) {
                    _val = (string) _val;
                }
                if (_val is SilverNumber)
                {
                    _val = SilverNumber.Convert((SilverNumber) _val);
                }
                arguments.Add(_val);
            });

            while (arguments.Count < minfo.GetParameters().Count()) {
                arguments.Add(null);
            }

            if (minfo.IsConstructor) {
                var ctor = (ConstructorInfo) minfo;
                return ctor.Invoke(arguments.ToArray());
            }

            if (target is SilverInstance && !(target is SilverBoxedInstance) &&
                ((SilverInstance) target).BackingObject != null) {
                target = ((SilverInstance) target).BackingObject;
            }

            dynamic val = null;

            if (((MethodInfo) minfo).ReturnType != typeof (void)) {
                val = minfo.Invoke(target, arguments.ToArray());
            }
            else {
                minfo.Invoke(target, arguments.ToArray());
            }

            return val;
        }
示例#32
0
        private static void RunMethod(MethodBase specificTest, object test, FullRunDescription report, bool log)
        {
            try
            {
                specificTest.Invoke(test, new object[] { });
            }
            catch (Exception e)
            {
                if (specificTest.GetCustomAttributes(typeof(ExpectedExceptionAttribute), false).Length == 0)
                {
                    if (CheckContext.DefaulNegated == false)
                    {
                        return;
                    }

                    throw;
                }

                Type expectedType =
                    ((ExpectedExceptionAttribute)
                     specificTest.GetCustomAttributes(typeof(ExpectedExceptionAttribute), false)[0]).ExpectedException;
                if (e.InnerException != null)
                {
                    if (e.InnerException is FluentCheckException)
                    {
                        var fluExc = e.InnerException as FluentCheckException;
                        var desc = GetCheckAndType(fluExc);
                        if (desc != null)
                        {
                            var method = desc.Check;
                            var testedtype = desc.CheckedType;
                            desc.ErrorSampleMessage = fluExc.Message;

                            // are we building a report
                            if (log)
                            {
                                Log(
                                    string.Format(
                                        "Check.That({1} sut).{0} failure message\n****\n{2}\n****",
                                        method.Name,
                                        testedtype.Name,
                                        fluExc.Message));
                            }

                            if (report != null)
                            {
                                report.AddEntry(desc);
                            }

                            if (CheckContext.DefaulNegated == false)
                            {
                                Log(string.Format("(Forced) Negated test '{0}' should have succeeded, but it failed (method {1}).", specificTest.Name, desc.Signature));
                            }
                        }
                        else
                        {
                            Log(string.Format("Failed to parse the method signature {0}", specificTest.Name));
                        }

                        return;
                    }

                    if (report != null)
                    {
                        Log(
                            string.Format(
                                "{0} did not generate a fluent check:\n{1}",
                                specificTest.Name,
                                e.InnerException.Message));
                    }

                    if (e.InnerException.GetType() != expectedType && expectedType != null)
                    {
                        throw;
                    }
                }
                else
                {
                    if (report != null)
                    {
                        Log(string.Format("{0} failed to run:\n{1}", specificTest.Name, e));
                    }

                    throw;
                }
            }
        }
        private void InvokeTestMethod(MethodBase method)
        {
            if (method == null) return;
            string result;
            try
            {
                method.Invoke(_testInstance, new Object[0]);
                result = string.Format("[{2}] {0}.{1}", _testType, method.Name, "PASS");
                Debug.Log(result);
            }
            catch (Exception exception)
            {
                result = string.Format("[{2}] {0}.{1}. {3}", _testType, method.Name, "FAIL", exception);
                Debug.LogError(result);
            }

            _result.Add(result);
        }
示例#34
0
 public static object InvokeWithNamedParameters(this MethodBase self, object obj, IDictionary <string, object> namedParameters)
 {
     return(self.Invoke(obj, MapParameters(self, namedParameters)));
 }
 private object InvocationHandler(object target, MethodBase method, object[] parameters)
 {
     //Console.WriteLine("Before: " + method.Name);
     object result = method.Invoke(target, parameters);
     //Console.WriteLine("After: " + method.Name);
     return result;
 }
        public void ExecuteFrame(ILStackFrameWithDiagnostics frame)
        {
            frame.Reset();
            goto Inc;
ReadNext:
            frame.ReadNext();

            short opCodeValue = frame.Code.Value;

            switch (opCodeValue)
            {
            case (short)ILOpCodeValues.Nop: break;

            case (short)ILOpCodeValues.Ret: goto Ret;

            case (short)ILOpCodeValues.Stloc_0:
                frame.Locals[0].Value = frame.Stack.Pop();
                break;

            case (short)ILOpCodeValues.Stloc_1:
                frame.Locals[1].Value = frame.Stack.Pop();
                break;

            case (short)ILOpCodeValues.Stloc_2:
                frame.Locals[2].Value = frame.Stack.Pop();
                break;

            case (short)ILOpCodeValues.Stloc_3:
                frame.Locals[3].Value = frame.Stack.Pop();
                break;

            case unchecked ((short)ILOpCodeValues.Stloc):
                frame.Locals[(int)frame.Current.Arg].Value = frame.Stack.Pop();
                break;

            case (short)ILOpCodeValues.Stloc_S:
                frame.Locals[(byte)(int)frame.Current.Arg].Value = frame.Stack.Pop();
                break;

            case (short)ILOpCodeValues.Stobj:
                throw new NotImplementedException();

            case (short)ILOpCodeValues.Ldloc_0:
                frame.Stack.Push(frame.Locals[0].Value);
                break;

            case (short)ILOpCodeValues.Ldloc_1:
                frame.Stack.Push(frame.Locals[1].Value);
                break;

            case (short)ILOpCodeValues.Ldloc_2:
                frame.Stack.Push(frame.Locals[2].Value);
                break;

            case (short)ILOpCodeValues.Ldloc_3:
                frame.Stack.Push(frame.Locals[3].Value);
                break;

            case unchecked ((short)ILOpCodeValues.Ldloc):
                frame.Stack.Push(frame.Locals[(int)frame.Current.Arg].Value);
                break;

            case (short)ILOpCodeValues.Ldloc_S:
                frame.Stack.Push(frame.Locals[(byte)(int)frame.Current.Arg].Value);
                break;

            case unchecked ((short)ILOpCodeValues.Ldloca):
                frame.Stack.Push(frame.Locals[(int)frame.Current.Arg].Value);
                break;

            case (short)ILOpCodeValues.Ldloca_S:
                frame.Stack.Push(frame.Locals[(byte)(int)frame.Current.Arg].Value);
                break;

            case (short)ILOpCodeValues.Ldarg_0:
                frame.Stack.Push(frame.Args[0]);
                break;

            case (short)ILOpCodeValues.Ldarg_1:
                frame.Stack.Push(frame.Args[1]);
                break;

            case (short)ILOpCodeValues.Ldarg_2:
                frame.Stack.Push(frame.Args[2]);
                break;

            case (short)ILOpCodeValues.Ldarg_3:
                frame.Stack.Push(frame.Args[3]);
                break;

            case unchecked ((short)ILOpCodeValues.Ldarg):
                frame.Stack.Push(frame.Args[(int)frame.Current.Arg]);
                break;

            case unchecked ((short)ILOpCodeValues.Ldarg_S):
                frame.Stack.Push(frame.Args[(byte)(int)frame.Current.Arg]);
                break;

            case (short)ILOpCodeValues.Ldarga_S:
                frame.Stack.Push(frame.Args[(byte)(int)frame.Current.Arg]);
                break;

            case unchecked ((short)ILOpCodeValues.Ldarga):
                frame.Stack.Push(frame.Args[(int)frame.Current.Arg]);
                break;

            case unchecked ((short)ILOpCodeValues.Starg):
                frame.Args[(int)frame.Current.Arg] = frame.Stack.Pop();
                break;

            case unchecked ((short)ILOpCodeValues.Starg_S):
                frame.Args[(byte)(int)frame.Current.Arg] = frame.Stack.Pop();
                break;

            case (short)ILOpCodeValues.Ldc_I4:
                frame.Stack.Push((int)frame.Current.Arg);
                break;

            case (short)ILOpCodeValues.Ldc_I4_0:
                frame.Stack.Push(0);
                break;

            case (short)ILOpCodeValues.Ldc_I4_1:
                frame.Stack.Push(1);
                break;

            case (short)ILOpCodeValues.Ldc_I4_2:
                frame.Stack.Push(2);
                break;

            case (short)ILOpCodeValues.Ldc_I4_3:
                frame.Stack.Push(3);
                break;

            case (short)ILOpCodeValues.Ldc_I4_4:
                frame.Stack.Push(4);
                break;

            case (short)ILOpCodeValues.Ldc_I4_5:
                frame.Stack.Push(5);
                break;

            case (short)ILOpCodeValues.Ldc_I4_6:
                frame.Stack.Push(6);
                break;

            case (short)ILOpCodeValues.Ldc_I4_7:
                frame.Stack.Push(7);
                break;

            case (short)ILOpCodeValues.Ldc_I4_8:
                frame.Stack.Push(8);
                break;

            case (short)ILOpCodeValues.Ldc_I4_S:
                frame.Stack.Push(Convert.ToInt32(frame.Current.Arg));
                break;

            case (short)ILOpCodeValues.Ldc_I4_M1:
                frame.Stack.Push(-1);
                break;

            case (short)ILOpCodeValues.Ldc_I8:
                frame.Stack.Push(Convert.ToInt64(frame.Current.Arg));
                break;

            case (short)ILOpCodeValues.Ldc_R4:
                frame.Stack.Push(Convert.ToSingle(frame.Current.Arg));
                break;

            case (short)ILOpCodeValues.Ldc_R8:
                frame.Stack.Push(Convert.ToDouble(frame.Current.Arg));
                break;

            case (short)ILOpCodeValues.Box:     // 140: //box
                frame.Stack.Push(((object)frame.Stack.Pop()));
                break;

            case (short)ILOpCodeValues.Ckfinite:     // 195: //ckfinite
                var ckval = frame.Stack.Pop(); frame.Stack.Push((ckval is float?float.IsInfinity((float)ckval) : double.IsInfinity((double)ckval)));
                break;

            case (short)ILOpCodeValues.Conv_I:    // 103: //conv.i1
                frame.Stack.Push(unchecked ((int)Convert.ToInt64(frame.Stack.Pop())));
                break;

            case (short)ILOpCodeValues.Conv_U:    // 103: //conv.i1
                frame.Stack.Push(unchecked ((uint)Convert.ToUInt64(frame.Stack.Pop())));
                break;

            case (short)ILOpCodeValues.Conv_I1:    // 103: //conv.i1
                frame.Stack.Push(unchecked (Convert.ToSByte(frame.Stack.Pop())));
                break;

            case (short)ILOpCodeValues.Conv_I2:     //104: //conv.i2
                frame.Stack.Push(unchecked (Convert.ToInt16(frame.Stack.Pop())));
                break;

            case (short)ILOpCodeValues.Conv_I4:     //105: //conv.i4
                frame.Stack.Push(unchecked (Convert.ToInt32(frame.Stack.Pop())));
                break;

            case (short)ILOpCodeValues.Conv_I8:     //106: //conv.i8
                frame.Stack.Push(unchecked (Convert.ToInt64(frame.Stack.Pop())));
                break;

            case (short)ILOpCodeValues.Conv_Ovf_I1:     //179: //conv.ovf.i1
                frame.Stack.Push(Convert.ToSByte(frame.Stack.Pop()));
                break;

            case (short)ILOpCodeValues.Conv_Ovf_I1_Un:     //130: //conv.ovf.i1.un
                frame.Stack.Push(Convert.ToSByte(frame.Stack.Pop()));
                break;

            case (short)ILOpCodeValues.Conv_Ovf_I2:     //181: //conv.ovf.i2
                frame.Stack.Push(Convert.ToInt16(frame.Stack.Pop()));
                break;

            case (short)ILOpCodeValues.Conv_Ovf_I2_Un:     //131: //conv.ovf.i2.un
                frame.Stack.Push(Convert.ToInt16(frame.Stack.Pop()));
                break;

            case (short)ILOpCodeValues.Conv_Ovf_I4:     //183: //conv.ovf.i4
                frame.Stack.Push(Convert.ToInt32(frame.Stack.Pop()));
                break;

            case (short)ILOpCodeValues.Conv_Ovf_I4_Un:     //132: //conv.ovf.i4.un
                frame.Stack.Push(Convert.ToInt32(frame.Stack.Pop()));
                break;

            case (short)ILOpCodeValues.Conv_Ovf_I8:     //185: //conv.ovf.i8
                frame.Stack.Push(Convert.ToInt64(frame.Stack.Pop()));
                break;

            case (short)ILOpCodeValues.Conv_Ovf_I8_Un:     //133: //conv.ovf.i8.un
                frame.Stack.Push(Convert.ToInt64(frame.Stack.Pop()));
                break;

            case (short)ILOpCodeValues.Conv_Ovf_U1:     //180: //conv.ovf.u1
                frame.Stack.Push(Convert.ToByte(frame.Stack.Pop()));
                break;

            case (short)ILOpCodeValues.Conv_Ovf_U1_Un:     //134: //conv.ovf.u1.un
                frame.Stack.Push(Convert.ToByte(frame.Stack.Pop()));
                break;

            case (short)ILOpCodeValues.Conv_Ovf_U2:     //182: //conv.ovf.u2
                frame.Stack.Push(Convert.ToUInt16(frame.Stack.Pop()));
                break;

            case (short)ILOpCodeValues.Conv_Ovf_U2_Un:     //135: //conv.ovf.u2.un
                frame.Stack.Push(Convert.ToUInt16(frame.Stack.Pop()));
                break;

            case (short)ILOpCodeValues.Conv_Ovf_U4:     //184: //conv.ovf.u4
                frame.Stack.Push(Convert.ToUInt32(frame.Stack.Pop()));
                break;

            case (short)ILOpCodeValues.Conv_Ovf_U4_Un:     //136: //conv.ovf.u4.un
                frame.Stack.Push(Convert.ToUInt32(frame.Stack.Pop()));
                break;

            case (short)ILOpCodeValues.Conv_Ovf_U8:     //186: //conv.ovf.u8
                frame.Stack.Push(Convert.ToUInt64(frame.Stack.Pop()));
                break;

            case (short)ILOpCodeValues.Conv_Ovf_U8_Un:     //137: //conv.ovf.u8.un
                frame.Stack.Push(Convert.ToUInt64(frame.Stack.Pop()));
                break;

            case (short)ILOpCodeValues.Conv_R4:     //107: //conv.r4
                frame.Stack.Push(Convert.ToSingle(frame.Stack.Pop()));
                break;

            case (short)ILOpCodeValues.Conv_R8:     //108: //conv.r8
                frame.Stack.Push(Convert.ToDouble(frame.Stack.Pop()));
                break;

            case (short)ILOpCodeValues.Conv_R_Un:     //118: //conv.r.un
                frame.Stack.Push(Convert.ToSingle(frame.Stack.Pop()));
                break;

            case (short)ILOpCodeValues.Conv_U1:     //210: //conv.u1
                frame.Stack.Push(unchecked (Convert.ToByte(frame.Stack.Pop())));
                break;

            case (short)ILOpCodeValues.Conv_U2:     //209: //conv.u2
                frame.Stack.Push(unchecked (Convert.ToUInt16(frame.Stack.Pop())));
                break;

            case (short)ILOpCodeValues.Conv_U4:     //109: //conv.u4
                frame.Stack.Push(unchecked (Convert.ToUInt32(frame.Stack.Pop())));
                break;

            case (short)ILOpCodeValues.Conv_U8:     //110: //conv.u8
                frame.Stack.Push(unchecked (Convert.ToUInt64(frame.Stack.Pop())));
                break;

            case (short)ILOpCodeValues.Neg:     //101: //neg
                frame.Stack.Push(-((dynamic)frame.Stack.Pop()));
                break;

            case (short)ILOpCodeValues.Newarr:     //141: //newarr
                frame.Stack.Push(Array.CreateInstance(((frame.Current.Arg is int) ? frame.ResolveTypeToken((int)frame.Current.Arg) : (Type)frame.Current.Arg), (int)frame.Stack.Pop()));
                break;

            case (short)ILOpCodeValues.Not:     //102: //not
                frame.Stack.Push(!((dynamic)frame.Stack.Pop()));
                break;

            case (short)ILOpCodeValues.Pop: //38: //pop
                frame.Stack.Pop();          // no push
                break;

            case (short)ILOpCodeValues.Shl:     //98: //shl
                frame.Stack.Push(((dynamic)frame.Stack.Pop()) << ((int)frame.Current.Arg));
                break;

            case (short)ILOpCodeValues.Shr:     //99: //shr
                frame.Stack.Push(((dynamic)frame.Stack.Pop()) >> ((int)frame.Current.Arg));
                break;

            case (short)ILOpCodeValues.Shr_Un:     //100: //shr.un
                frame.Stack.Push(((dynamic)frame.Stack.Pop()) >> ((int)frame.Current.Arg));
                break;

            case (short)ILOpCodeValues.Unbox:     //121: //unbox
                frame.Stack.Push(Convert.ChangeType(frame.Stack.Pop(), frame.ResolveTypeToken((int)frame.Current.Arg)));
                break;

            case (short)ILOpCodeValues.Unbox_Any:     //165: //unbox.any
                frame.Stack.Push(Convert.ChangeType(frame.Stack.Pop(), frame.ResolveTypeToken((int)frame.Current.Arg)));
                break;

            case (short)ILOpCodeValues.Add:     //: //add
                frame.Stack.Push(unchecked (((dynamic)frame.Stack.Pop()) + ((dynamic)frame.Stack.Pop())));
                break;

            case (short)ILOpCodeValues.Add_Ovf:     // 214: //add.ovf
                frame.Stack.Push(((dynamic)frame.Stack.Pop()) + ((dynamic)frame.Stack.Pop()));
                break;

            case (short)ILOpCodeValues.Add_Ovf_Un:     // 215: //add.ovf.un
                frame.Stack.Push(((dynamic)frame.Stack.Pop()) + ((dynamic)frame.Stack.Pop()));
                break;

            case (short)ILOpCodeValues.And:     //95: //and
                frame.Stack.Push(((dynamic)frame.Stack.Pop()) & ((dynamic)frame.Stack.Pop()));
                break;

            case unchecked ((short)ILOpCodeValues.Ceq):    //: //ceq
            {
                var opa = frame.Stack.Pop();
                var opb = frame.Stack.Pop();

                if (opa is IConvertible && opb is IConvertible)
                {
                    var compc = ((IComparable)(opa)).CompareTo(Convert.ChangeType(opb, Convert.GetTypeCode(opa)));
                    frame.Stack.Push(compc == 0 ? 1 : 0);
                }
                else
                {
                    frame.Stack.Push(Convert.ToInt32(((dynamic)opa) == ((dynamic)opb)));
                }
            }

            break;

            case unchecked ((short)ILOpCodeValues.Cgt):    // -510: //cgt
                frame.Stack.Push(Convert.ToInt32(((dynamic)frame.Stack.Pop()) < ((dynamic)frame.Stack.Pop())));
                break;

            case unchecked ((short)ILOpCodeValues.Cgt_Un) - 509:    //cgt.un
                frame.Stack.Push(Convert.ToInt32(((dynamic)frame.Stack.Pop()) < ((dynamic)frame.Stack.Pop())));
                break;

            case unchecked ((short)ILOpCodeValues.Clt):                                                         // -508: //clt
                frame.Stack.Push(Convert.ToInt32(((dynamic)frame.Stack.Pop()) > ((dynamic)frame.Stack.Pop()))); //either swap pop order or sign
                break;

            case unchecked ((short)ILOpCodeValues.Clt_Un):    // -507: //clt.un
                frame.Stack.Push(Convert.ToInt32(((dynamic)frame.Stack.Pop()) > ((dynamic)frame.Stack.Pop())));
                break;

            case unchecked ((short)ILOpCodeValues.Div):    // 91: //div
                frame.Stack.Push(((dynamic)frame.Stack.Pop()) / ((dynamic)frame.Stack.Pop()));
                break;

            case unchecked ((short)ILOpCodeValues.Div_Un):    // 92: //div.un
                frame.Stack.Push(((dynamic)frame.Stack.Pop()) / ((dynamic)frame.Stack.Pop()));
                break;

            case unchecked ((short)ILOpCodeValues.Mul):    // 90: //mul
                frame.Stack.Push(unchecked (((dynamic)frame.Stack.Pop()) * ((dynamic)frame.Stack.Pop())));
                break;

            case unchecked ((short)ILOpCodeValues.Mul_Ovf):    // 216: //mul.ovf
                frame.Stack.Push(((dynamic)frame.Stack.Pop()) * ((dynamic)frame.Stack.Pop()));
                break;

            case unchecked ((short)ILOpCodeValues.Mul_Ovf_Un):    // 217: //mul.ovf.un
                frame.Stack.Push(((dynamic)frame.Stack.Pop()) * ((dynamic)frame.Stack.Pop()));
                break;

            case unchecked ((short)ILOpCodeValues.Or):    // 96: //or
                frame.Stack.Push(((dynamic)frame.Stack.Pop()) | ((dynamic)frame.Stack.Pop()));
                break;

            case unchecked ((short)ILOpCodeValues.Rem):    // 93: //rem
                frame.Stack.Push(((dynamic)frame.Stack.Pop()) % ((dynamic)frame.Stack.Pop()));
                break;

            case unchecked ((short)ILOpCodeValues.Rem_Un):    // 94: //rem.un
                frame.Stack.Push(((dynamic)frame.Stack.Pop()) % ((dynamic)frame.Stack.Pop()));
                break;

            case unchecked ((short)ILOpCodeValues.Sub):    // 89: //sub
                frame.Stack.Push(unchecked (((dynamic)frame.Stack.Pop()) - ((dynamic)frame.Stack.Pop())));
                break;

            case unchecked ((short)ILOpCodeValues.Sub_Ovf):    // 218: //sub.ovf
                frame.Stack.Push(((dynamic)frame.Stack.Pop()) - ((dynamic)frame.Stack.Pop()));
                break;

            case unchecked ((short)ILOpCodeValues.Sub_Ovf_Un):    // 219: //sub.ovf.un
                frame.Stack.Push(((dynamic)frame.Stack.Pop()) - ((dynamic)frame.Stack.Pop()));
                break;

            case unchecked ((short)ILOpCodeValues.Xor):    // 97: //xor
                frame.Stack.Push(((dynamic)frame.Stack.Pop()) ^ ((dynamic)frame.Stack.Pop()));
                break;

            case (short)ILOpCodeValues.Ldstr:
            {
                if (frame.Current.Arg is string)
                {
                    frame.Stack.Push((string)frame.Current.Arg);
                }
                else
                {
                    frame.Stack.Push(frame.ResolveStringToken((int)frame.Current.Arg));
                }
                break;
            }

            case (short)ILOpCodeValues.Newobj:
            {
                var ctor     = (System.Reflection.ConstructorInfo)frame.ResolveMethodToken((int)frame.Current.Arg);
                var ctorArgs = new object[ctor.GetParameters().Length];
                for (var i = ctorArgs.Length - 1; i > -1; i--)
                {
                    ctorArgs[i] = frame.Stack.Pop();
                }
                //var reversed = ctorArgs.Reverse().ToArray();
                var ctorResult = ctor.Invoke(ctorArgs);
                frame.Stack.Push(ctorResult);
                break;
            }

            case (short)ILOpCodeValues.Ldfld:
            {
                var field  = frame.ResolveFieldToken((int)frame.Current.Arg);
                var target = frame.Stack.Pop();
                var value  = field.GetValue(target);
                frame.Stack.Push(value);
                break;
            }

            case (short)ILOpCodeValues.Ldsfld:
            {
                var field = frame.ResolveFieldToken((int)frame.Current.Arg);
                var value = field.GetValue(null);
                frame.Stack.Push(value);
                break;
            }

            case (short)ILOpCodeValues.Stfld:
            {
                var field  = frame.ResolveFieldToken((int)frame.Current.Arg);
                var fo     = frame.Stack.Pop();
                var target = frame.Stack.Pop();
                field.SetValue(target, fo);
                //frame.Stack.Push(value);
                break;
            }

            case (short)ILOpCodeValues.Stsfld:
            {
                var field = frame.ResolveFieldToken((int)frame.Current.Arg);
                var fo    = frame.Stack.Pop();
                //var target = frame.Stack.Pop();
                field.SetValue(null, fo);
                break;
            }

            case (short)ILOpCodeValues.Ldlen:
            {
                var array = frame.Stack.Pop();
                var arr   = (Array)array;
                frame.Stack.Push(arr.Length);
                break;
            }

            case (short)ILOpCodeValues.Stelem:
            {
                object el    = frame.Stack.Pop();
                int    index = (int)frame.Stack.Pop();
                var    array = (Array)frame.Stack.Pop();

                array.GetType()
                .GetMethod("SetValue", new[] { typeof(object), typeof(int) })
                .Invoke(array, new object[] { el, index });
                break;
            }

            case (short)ILOpCodeValues.Stelem_I1:
            {
                object el        = frame.Stack.Pop();
                int    index     = (int)frame.Stack.Pop();
                var    array     = frame.Stack.Pop();
                var    arrType   = array.GetType();
                var    arrElType = arrType.GetElementType();
                var    elType    = el.GetType();
                if (elType == arrElType)
                {
                    ((Array)array).SetValue(el, index);
                }
                else if (arrElType == typeof(sbyte))
                {
                    ((sbyte[])array)[index] = (sbyte)(int)el;
                }
                else
                {
                    ((byte[])array)[index] = (byte)(int)el;
                }
                break;
            }

            case (short)ILOpCodeValues.Stelem_I2:
            {
                object el        = frame.Stack.Pop();
                int    index     = (int)frame.Stack.Pop();
                var    array     = frame.Stack.Pop();
                var    arrType   = array.GetType();
                var    arrElType = arrType.GetElementType();
                var    elType    = el.GetType();

                if (elType == arrElType)
                {
                    ((Array)array).SetValue(el, index);
                }
                else if (arrElType == typeof(short))
                {
                    ((Array)array).SetValue((short)(int)el, index);
                }
                else if (arrElType == typeof(short))
                {
                    ((Array)array).SetValue((ushort)(int)el, index);
                }
                else
                {
                    ((Array)array).SetValue(Convert.ChangeType(el, arrElType), index);
                }
                break;
            }

            case (short)ILOpCodeValues.Stelem_I4:
            {
                object el        = frame.Stack.Pop();
                int    index     = (int)frame.Stack.Pop();
                var    array     = frame.Stack.Pop();
                var    arrType   = array.GetType();
                var    arrElType = arrType.GetElementType();
                var    elType    = el.GetType();
                if (elType == arrElType)
                {
                    ((Array)array).SetValue(el, index);
                }
                else if (arrElType == typeof(int))
                {
                    ((int[])array)[index] = (int)el;
                }
                else
                {
                    ((uint[])array)[index] = (uint)el;
                }
                break;
            }

            case (short)ILOpCodeValues.Stelem_I8:
            {
                object el        = frame.Stack.Pop();
                int    index     = (int)frame.Stack.Pop();
                var    array     = frame.Stack.Pop();
                var    arrType   = array.GetType();
                var    arrElType = arrType.GetElementType();
                var    elType    = el.GetType();
                if (elType == arrElType)
                {
                    ((Array)array).SetValue(el, index);
                }
                else if (arrElType == typeof(long))
                {
                    ((long[])array)[index] = (long)el;
                }
                else
                {
                    ((ulong[])array)[index] = (ulong)el;
                }
                break;
            }

            case (short)ILOpCodeValues.Stelem_R4:
            {
                object el        = frame.Stack.Pop();
                int    index     = (int)frame.Stack.Pop();
                var    array     = frame.Stack.Pop();
                var    arrType   = array.GetType();
                var    arrElType = arrType.GetElementType();
                var    elType    = el.GetType();
                if (elType == arrElType)
                {
                    ((Array)array).SetValue(el, index);
                }
                else if (arrElType == typeof(float))
                {
                    ((float[])array)[index] = (float)el;
                }
                //else ((ulong[])array)[index] = (ulong)el;
                break;
            }

            case (short)ILOpCodeValues.Stelem_R8:
            {
                object el        = frame.Stack.Pop();
                int    index     = (int)frame.Stack.Pop();
                var    array     = frame.Stack.Pop();
                var    arrType   = array.GetType();
                var    arrElType = arrType.GetElementType();
                var    elType    = el.GetType();
                if (elType == arrElType)
                {
                    ((Array)array).SetValue(el, index);
                }
                else if (arrElType == typeof(double))
                {
                    ((double[])array)[index] = (double)el;
                }
                //else ((ulong[])array)[index] = (ulong)el;
                break;
            }

            case (short)ILOpCodeValues.Stelem_Ref:
            {
                object val   = frame.Stack.Pop();
                int    index = (int)frame.Stack.Pop();
                var    array = frame.Stack.Pop();
                ((Array)array).SetValue(val, index);
                break;
            }

            case (short)ILOpCodeValues.Ldelem:
            case (short)ILOpCodeValues.Ldelema:
            case (short)ILOpCodeValues.Ldelem_I:
            case (short)ILOpCodeValues.Ldelem_Ref:
            {
                var idx   = (int)frame.Stack.Pop();
                var array = (Array)frame.Stack.Pop();
                var val   = array.GetValue(idx);
                frame.Stack.Push(val);
                break;
            }

            case (short)ILOpCodeValues.Ldelem_I1:
            {
                var idx    = (int)frame.Stack.Pop();
                var array  = (Array)frame.Stack.Pop();
                var val    = array.GetValue(idx);
                var target = (sbyte)Convert.ToInt32(val);
                frame.Stack.Push(target);
                break;
            }

            case (short)ILOpCodeValues.Ldelem_I2:
            {
                var idx    = (int)frame.Stack.Pop();
                var array  = (Array)frame.Stack.Pop();
                var val    = array.GetValue(idx);
                var target = (short)Convert.ToInt32(val);
                frame.Stack.Push(target);
                break;
            }

            case (short)ILOpCodeValues.Ldelem_I4:
            {
                var idx    = (int)frame.Stack.Pop();
                var array  = (Array)frame.Stack.Pop();
                var val    = array.GetValue(idx);
                var target = Convert.ToInt32(val);
                frame.Stack.Push(target);
                break;
            }

            case (short)ILOpCodeValues.Ldelem_I8:
            {
                var idx    = (int)frame.Stack.Pop();
                var array  = (Array)frame.Stack.Pop();
                var val    = array.GetValue(idx);
                var target = Convert.ToInt64(val);
                frame.Stack.Push(target);
                break;
            }

            case (short)ILOpCodeValues.Ldelem_U1:
            {
                var idx    = (int)frame.Stack.Pop();
                var array  = (Array)frame.Stack.Pop();
                var val    = array.GetValue(idx);
                var target = (byte)Convert.ToUInt32(val);
                frame.Stack.Push(target);
                break;
            }

            case (short)ILOpCodeValues.Ldelem_U2:
            {
                var idx    = (int)frame.Stack.Pop();
                var array  = (Array)frame.Stack.Pop();
                var val    = array.GetValue(idx);
                var target = (ushort)Convert.ToUInt32(val);
                frame.Stack.Push(target);
                break;
            }

            case (short)ILOpCodeValues.Ldelem_U4:
            {
                var idx    = (int)frame.Stack.Pop();
                var array  = (Array)frame.Stack.Pop();
                var val    = array.GetValue(idx);
                var target = Convert.ToUInt32(val);
                frame.Stack.Push(target);
                break;
            }

            case (short)ILOpCodeValues.Ldelem_R4:
            {
                var idx    = (int)frame.Stack.Pop();
                var array  = (Array)frame.Stack.Pop();
                var val    = array.GetValue(idx);
                var target = Convert.ToSingle(val);
                frame.Stack.Push(target);
                break;
            }

            case (short)ILOpCodeValues.Ldelem_R8:
            {
                var idx    = (int)frame.Stack.Pop();
                var array  = (Array)frame.Stack.Pop();
                var val    = array.GetValue(idx);
                var target = Convert.ToDouble(val);
                frame.Stack.Push(target);
                break;
            }



            case (short)ILOpCodeValues.Conv_Ovf_I_Un:
            case (short)ILOpCodeValues.Conv_Ovf_I:
                //Todo: native int operations
                throw new NotImplementedException();

            case (short)ILOpCodeValues.Dup:
                frame.Stack.Push(frame.Stack.Peek());
                break;

            //TODO: Implemented scopre validation for branch: (EG, inside try, catch, finally,etc)
            case (short)ILOpCodeValues.Leave_S:
            case (short)ILOpCodeValues.Br_S:     //0x2b:
            {
                var delta     = (int)(sbyte)Convert.ToByte(frame.Current.Arg);
                var directpos = (int)frame.Stream[frame.Position + 1].ByteIndex + delta;
                frame.Position = frame.JumpTable[directpos];
                goto MoveNext;
            }

            case (short)ILOpCodeValues.Leave:
            case (short)ILOpCodeValues.Br:     // 0x38:
            {
                var delta     = Convert.ToInt32(frame.Current.Arg);
                var directpos = (int)frame.Stream[frame.Position + 1].ByteIndex + delta;
                frame.Position = frame.JumpTable[directpos];
                goto MoveNext;
            }

            case (short)ILOpCodeValues.Beq:
            {
                var opa = frame.Stack.Pop();
                var opb = frame.Stack.Pop();
                if (opa is IConvertible && opb is IConvertible)
                {
                    var compc = ((IComparable)(opa)).CompareTo(Convert.ChangeType(opb, Convert.GetTypeCode(opa)));
                    frame.Stack.Push(compc == 0 ? 1 : 0);
                }
                else
                {
                    frame.Stack.Push(Convert.ToInt32(((dynamic)opa) == ((dynamic)opb)));
                }
                goto case (short)ILOpCodeValues.Brtrue;
            }

            case (short)ILOpCodeValues.Beq_S:
            {
                var opa = frame.Stack.Pop();
                var opb = frame.Stack.Pop();

                if (opa is IConvertible && opb is IConvertible)
                {
                    var compc = ((IComparable)(opa)).CompareTo(Convert.ChangeType(opb, Convert.GetTypeCode(opa)));
                    frame.Stack.Push(compc == 0 ? 1 : 0);
                }
                else
                {
                    frame.Stack.Push(Convert.ToInt32(((dynamic)opa) == ((dynamic)opb)));
                }
                goto case (short)ILOpCodeValues.Brtrue_S;
            }

            case (short)ILOpCodeValues.Brfalse:     //‭00111001‬
            {
                var chk        = frame.Stack.Pop();
                int cond       = Convert.ToInt32((chk is IConvertible) ? Convert.ToBoolean(chk) : Convert.ToBoolean(!(chk is null)));
                var condtarget = -1;
                if (cond == 0)
                {
                    condtarget     = (int)frame.Stream[frame.Position + 1].ByteIndex + Convert.ToInt32(frame.Current.Arg);
                    frame.Position = frame.JumpTable[condtarget];
                    goto MoveNext;
                }
                break;
            }

            case (short)ILOpCodeValues.Brfalse_S:
            {
                var chk        = frame.Stack.Pop();
                int cond       = Convert.ToInt32((chk is IConvertible) ? Convert.ToBoolean(chk) : Convert.ToBoolean(!(chk is null)));
                var condtarget = -1;
                if (cond == 0)
                {
                    condtarget     = (int)frame.Stream[frame.Position + 1].ByteIndex + (int)(sbyte)Convert.ToByte(frame.Current.Arg);
                    frame.Position = frame.JumpTable[condtarget];
                    goto MoveNext;
                }
                break;
            }

            case (short)ILOpCodeValues.Brtrue:
            {
                var chk        = frame.Stack.Pop();
                int cond       = Convert.ToInt32((chk is IConvertible) ? Convert.ToBoolean(chk) : Convert.ToBoolean(!(chk is null)));
                var condtarget = -1;
                if (cond == 1)
                {
                    condtarget     = (int)frame.Stream[frame.Position + 1].ByteIndex + Convert.ToInt32(frame.Current.Arg);
                    frame.Position = frame.JumpTable[condtarget];
                    goto MoveNext;
                }
                break;
            }

            case (short)ILOpCodeValues.Brtrue_S:
            {
                var chk        = frame.Stack.Pop();
                int cond       = Convert.ToInt32((chk is IConvertible) ? Convert.ToBoolean(chk) : Convert.ToBoolean(!(chk is null)));
                var condtarget = -1;
                if (cond == 1)
                {
                    condtarget     = (int)frame.Stream[frame.Position + 1].ByteIndex + (int)(sbyte)Convert.ToByte(frame.Current.Arg);
                    frame.Position = frame.JumpTable[condtarget];
                    goto MoveNext;
                }
                break;
            }

            case (short)ILOpCodeValues.Call:
            case (short)ILOpCodeValues.Callvirt:
                System.Reflection.MethodBase method = null;
                object resolved = null;
                if (frame.Current.Arg is System.Reflection.MethodInfo)
                {
                    method = (System.Reflection.MethodInfo)frame.Current.Arg;
                }
                else
                {
                    resolved = frame.ResolveMethodToken((int)frame.Current.Arg);
                }


                if (resolved is ConstructorInfo)
                {
                    method = (ConstructorInfo)resolved;
                }
                else
                {
                    method = (System.Reflection.MethodInfo)resolved;
                }

                var parameters = method.GetParameters();
                var methodArgs = new object[parameters.Length];

                for (var i = methodArgs.Length - 1; i >= 0; i--)
                {
                    var val = frame.Stack.Pop();
                    if (val is ILVariable)
                    {
                        methodArgs[i] = ((ILVariable)(val)).Value;
                    }
                    else
                    {
                        methodArgs[i] = val;
                    }
                }

                object methodTarget = null;
                if (!method.IsStatic)
                {
                    methodTarget = frame.Stack.Pop();
                }
                if (methodTarget is ILVariable)
                {
                    methodTarget = ((ILVariable)methodTarget).Value;
                }
                //var t = default(RuntimeTypeHandle);
                //var t1 = default(ArgIterator);
                //var tobject = new object[] { t, t };
                //var del = Delegate.CreateDelegate()
                //((ConstructorInfo)method).Invoke( new object[]{ t});
                for (var i = methodArgs.Length - 1; i >= 0; i--)
                {
                    if (methodArgs[i] is IConvertible)
                    {
                        methodArgs[i] = Convert.ChangeType(methodArgs[i], parameters[i].ParameterType);
                    }
                }

                //if the current method is invoking another method then convert the arguments for the inner method.
                if (methodTarget is MethodBase && methodArgs.Length == 2 && methodArgs[1] is Array)
                {
                    var invokeArgs       = (Array)methodArgs[1];
                    var invokeParameters = ((MethodInfo)methodTarget).GetParameters();
                    for (var i = invokeArgs.Length - 1; i >= 0; i--)
                    {
                        var arg = invokeArgs.GetValue(i);
                        if (arg is IConvertible)
                        {
                            invokeArgs.SetValue(Convert.ChangeType(arg, invokeParameters[i].ParameterType), i);
                        }
                    }
                    //if (invokeArgs.GetValue(i) is IConvertible)
                    //    invokeArgs.SetValue(Convert.ChangeType(invokeArgs[i], invokeParameters[i].ParameterType));
                }

                // Roadblock here: Int.CompareTo(object value) -> argument value must be of type int but there is no way to programatically determine the expected destination type.

                var methodresult = (method is MethodInfo) ? method.Invoke(methodTarget, methodArgs) : ((ConstructorInfo)method).Invoke(methodArgs);
                if (frame.Code.StackBehaviourPush == StackBehaviour.Varpush)
                {
                    if ((method as MethodInfo)?.ReturnType != typeof(void) || method.IsConstructor)
                    {
                        frame.Stack.Push(methodresult);
                    }
                }
                break;

            case (short)ILOpCodeValues.Ldnull:
                frame.Stack.Push(null);
                break;

            case unchecked ((short)ILOpCodeValues.Ldftn):
                var ftnToken  = (int)frame.Current.Arg;
                var ftnMethod = frame.ResolveMethodToken(ftnToken);
                frame.Stack.Push(ftnMethod.MethodHandle.GetFunctionPointer());
                break;

            case unchecked ((short)ILOpCodeValues.Initobj):

                var newObj = Activator.CreateInstance(frame.ResolveTypeToken((int)frame.Current.Arg));
                var inst   = frame.Stack.Pop();
                if (inst is ILVariable ilvar)
                {
                    ilvar.Value = newObj;
                    frame.Locals[ilvar.Index] = ilvar;
                }
                else
                {
                    inst = newObj;
                }

                break;

            case (short)ILOpCodeValues.Ldtoken:
                var metaToken = (int)frame.Current.Arg;
                var memToken  = frame.ResolveMemberToken(metaToken);
                var tokenType = memToken.GetType();


                switch (tokenType.Name)
                {
                case "RtFieldInfo":
                {
                    var fieldInfo = frame.ResolveFieldToken(metaToken);
                    var handle    = (FieldInfo)fieldInfo;
                    frame.Stack.Push(handle.FieldHandle);
                }
                break;

                case "RuntimeType":
                {
                    var type   = frame.ResolveTypeToken(metaToken);
                    var handle = (Type)type;
                    frame.Stack.Push(handle.TypeHandle);
                }

                break;

                default:
                    frame.Exception = new NotImplementedException($"{nameof(OpCode)} {frame.Code} token {tokenType.Name}");
                    goto Ret;
                    //throw new NotImplementedException();
                }


                break;

            case (short)ILOpCodeValues.Castclass:

                var targetClassToken = (int)frame.Current.Arg;
                var targetType       = frame.ResolveTypeToken(targetClassToken);

                var listType = typeof(List <>).MakeGenericType(new[] { targetType });
                var instance = Activator.CreateInstance(listType);
                var prop     = listType.GetProperty("Item");
                var src      = frame.Stack.Pop();


                var add = listType.GetMethod("Add");
                add.Invoke(instance, new[] { src });
                var get        = listType.GetMethod("get_Item");
                var listresult = get.Invoke(instance, new object[] { 0 });
                frame.Stack.Push(listresult);

                break;

            case (short)ILOpCodeValues.Break:
                if (frame.TriggerBreak)
                {
                    System.Diagnostics.Debugger.Break();
                }
                break;

            default:
                frame.Exception = new NotImplementedException($"{nameof(OpCode)} {frame.Code} is not implemented");
                goto Ret;
            }

Inc:
            frame.Inc();
MoveNext:
            if (frame.MoveNext())
            {
                goto ReadNext;
            }


Ret:
            frame.ReturnResult = (frame.Stack.Count > 0 && frame.Exception == null) ? frame.Stack.Pop() : null;
        }