Ejemplo n.º 1
0
        /// <inheritdoc />
        public override DispatchResult Execute(ExecutionContext context, CilInstruction instruction)
        {
            var stack = context.ProgramState.Stack;

            // Pop arguments.
            var lengthValue        = (ICliValue)stack.Pop();
            var sourceAddress      = (ICliValue)stack.Pop();
            var destinationAddress = (ICliValue)stack.Pop();

            // Interpret arguments.
            if (!(destinationAddress is IPointerValue destinationPointer) || !(sourceAddress is IPointerValue sourcePointer))
            {
                return(DispatchResult.InvalidProgram());
            }

            if (!lengthValue.IsKnown)
            {
                throw new DispatchException("Number of bytes to copy is unknown.");
            }
            int length = lengthValue.InterpretAsI4().I32;

            // Copy data.
            Span <byte> data    = stackalloc byte[length];
            Span <byte> bitmask = stackalloc byte[length];

            sourcePointer.ReadBytes(0, data, bitmask);
            destinationPointer.WriteBytes(0, data, bitmask);

            return(base.Execute(context, instruction));
        }
Ejemplo n.º 2
0
 /// <inheritdoc />
 protected override DispatchResult Execute(ExecutionContext context, CilInstruction instruction,
                                           FValue left, FValue right)
 {
     left.F64 *= right.F64;
     context.ProgramState.Stack.Push(left);
     return(DispatchResult.Success());
 }
Ejemplo n.º 3
0
        /// <inheritdoc />
        public override DispatchResult Execute(ExecutionContext context, CilInstruction instruction)
        {
            var environment = context.GetService <ICilRuntimeEnvironment>();

            var variables = new IVariable[1];

            if (environment.Architecture.GetWrittenVariables(instruction, variables) != 1)
            {
                throw new DispatchException(
                          $"Architecture returned an incorrect number of variables being written by instruction {instruction}.");
            }

            switch (variables[0])
            {
            case CilVariable cilVariable:
                var value = environment.CliMarshaller.ToCtsValue(
                    (ICliValue)context.ProgramState.Stack.Pop(),
                    cilVariable.Variable.VariableType);

                context.ProgramState.Variables[variables[0]] = value;
                return(base.Execute(context, instruction));

            default:
                return(DispatchResult.InvalidProgram());
            }
        }
Ejemplo n.º 4
0
        private static DispatchResult FindMinimumDistanced(DispatchResult[] Results, ref int Index)
        {
            DispatchResult minResult = new DispatchResult()
            {
                Hit = false, Distance = Number.MaxValue
            };

            for (int i = 0; i < Results.Length; ++i)
            {
                if (!Results[i].Hit)
                {
                    continue;
                }

                if (minResult.Distance < Results[i].Distance)
                {
                    continue;
                }

                minResult = Results[i];
                Index     = i;
            }

            return(minResult);
        }
Ejemplo n.º 5
0
        public void Will_Trap_And_Cache_AmbiguousMatch(string methodName)
        {
            Dispatcher dispatcher = Dispatcher.For(
                typeof(Ambig),
                typeof(Ambig).GetMethod(methodName));

            Assert.AreEqual(2, dispatcher.DispatchTableSize);

            DispatchResult result = dispatcher.Dispatch(new Ambig(), new B(), new B());

            Assert.IsFalse(result.Success);
            Assert.IsTrue(result.AmbiguousMatch);
            Assert.IsTrue(result.IsDynamicInvoke);

            if (methodName == "FF")
            {
                DispatchResult <int> typedResult = result.Typed <int>();

                Assert.IsTrue(typedResult.AmbiguousMatch);
                Assert.AreEqual(0, typedResult.ReturnValue);
                Assert.IsTrue(typedResult.IsDynamicInvoke);
            }

            Assert.AreEqual(3, dispatcher.DispatchTableSize);

            result = dispatcher.Dispatch(new Ambig(), new B(), new B());
            Assert.IsFalse(result.IsDynamicInvoke);
        }
Ejemplo n.º 6
0
 /// <inheritdoc />
 protected override DispatchResult Execute(CilExecutionContext context, CilInstruction instruction,
                                           IntegerValue value, int shiftCount)
 {
     value.RightShift(shiftCount, instruction.OpCode.Code == CilCode.Shr);
     context.ProgramState.Stack.Push((ICliValue)value);
     return(DispatchResult.Success());
 }
Ejemplo n.º 7
0
 /// <inheritdoc />
 protected override DispatchResult Execute(ExecutionContext context, CilInstruction instruction,
                                           IntegerValue value, int shiftCount)
 {
     value.LeftShift(shiftCount);
     context.ProgramState.Stack.Push(value);
     return(DispatchResult.Success());
 }
Ejemplo n.º 8
0
Archivo: Ret.cs Proyecto: lanicon/Echo
        /// <inheritdoc />
        public DispatchResult Execute(CilExecutionContext context, CilInstruction instruction)
        {
            var environment = context.GetService <ICilRuntimeEnvironment>();

            // If the containing method is expected to return a value, the stack should contain exactly one value,
            // and no values otherwise.

            int popCount = environment.Architecture.GetStackPopCount(instruction);

            if (context.ProgramState.Stack.Size != popCount)
            {
                return(DispatchResult.InvalidProgram());
            }

            // Pop result.
            if (popCount == 1)
            {
                context.Result.ReturnValue = context.ProgramState.Stack.Pop();
            }

            return(new DispatchResult
            {
                HasTerminated = true
            });
        }
Ejemplo n.º 9
0
        /// <inheritdoc />
        public override DispatchResult Execute(ExecutionContext context, CilInstruction instruction)
        {
            var stack = context.ProgramState.Stack;

            // Pop arguments.
            var valueValue = (ICliValue)stack.Pop();
            var indexValue = (ICliValue)stack.Pop();
            var arrayValue = (ICliValue)stack.Pop();

            // Check if both array and index are known.
            if (!arrayValue.IsKnown)
            {
                throw new DispatchException($"Destination array value for instruction at offset IL_{instruction.Offset:X4} is unknown.");
            }
            if (!indexValue.IsKnown)
            {
                throw new DispatchException($"Index for instruction at offset IL_{instruction.Offset:X4} is unknown.");
            }

            // Expect an int32 or a native int for index, and extract its value.
            if (indexValue.CliValueType != CliValueType.Int32 && indexValue.CliValueType != CliValueType.NativeInt)
            {
                return(DispatchResult.InvalidProgram());
            }

            int index = indexValue.InterpretAsI4().I32;

            // Expect an O value with a .NET array in it.
            switch (arrayValue)
            {
            case OValue {
                    IsZero: { Value : TrileanValue.True }
            } :
                // Pushed array object is null.
                return(new DispatchResult(new NullReferenceException()));
Ejemplo n.º 10
0
            private void DispatchRequestInternal(Request request, string networkName)
            {
                DispatchResult result = DispatchResult.Expired;

                if (request.Behavior.Expiration == null ||
                    request.Behavior.Expiration >= DateTime.Now)
                {
                    try
                    {
                        result = manager.requestDispatcher.Dispatch(request, networkName);
                    }
                    catch (Exception)
                    {
                        //Any Exception should fail the dispatch request
                        result = DispatchResult.Failed;
                    }

                    if (result == DispatchResult.Failed)
                    {
                        if (!manager.connectionMonitor.IsConnected)
                        {
                            return;
                        }
                        manager.deadLetterQueue.Enqueue(request);
                    }
                }
                manager.requestQueue.Remove(request);

                if (manager.RequestDispatched != null)
                {
                    manager.RequestDispatched(this, new RequestDispatchedEventArgs(request, result));
                }
            }
Ejemplo n.º 11
0
        public static HttpStatusCode ToHttpStatusCode(this DispatchResult result)
        {
            switch (result)
            {
            case DispatchResult.UrlMismatch:
                return(HttpStatusCode.NotFound);

            case DispatchResult.ArgsMismatch:
                return(HttpStatusCode.NotAcceptable);

            case DispatchResult.MethodNotAllowed:
                return(HttpStatusCode.MethodNotAllowed);

            case DispatchResult.NotAuthenticated:
                return(HttpStatusCode.Unauthorized);

            case DispatchResult.NotAuthorized:
                return(HttpStatusCode.Forbidden);

            case DispatchResult.Ambiguous:
                return(HttpStatusCode.Ambiguous);

            case DispatchResult.Success:
                return(HttpStatusCode.OK);

            default:
                throw AssertionHelper.Fail();
            }
        }
Ejemplo n.º 12
0
        /// <inheritdoc />
        public override DispatchResult Execute(CilExecutionContext context, CilInstruction instruction)
        {
            var stack = context.ProgramState.Stack;

            // Pop arguments.
            var indexValue = stack.Pop();
            var arrayValue = stack.Pop();

            // Check if both array and index are known.
            if (!arrayValue.IsKnown || !indexValue.IsKnown)
            {
                stack.Push(GetUnknownElementValue(context, instruction));
                return(base.Execute(context, instruction));
            }

            // Expect an int32 or a native int for index, and extract its value.
            if (indexValue.CliValueType != CliValueType.Int32 && indexValue.CliValueType != CliValueType.NativeInt)
            {
                return(DispatchResult.InvalidProgram());
            }
            int index = indexValue.InterpretAsI4().I32;

            // Obtain element.
            ICliValue elementValue;

            switch (arrayValue)
            {
            case OValue {
                    IsZero: { Value : TrileanValue.True }
            } :
                // Pushed array object is null.
                return(new DispatchResult(new NullReferenceException()));
Ejemplo n.º 13
0
        /// <inheritdoc />
        public DispatchResult Execute(ExecutionContext context, CilInstruction instruction)
        {
            var result = VerifyCondition(context, instruction);

            int newOffset;

            if (result.IsKnown)
            {
                if (result)
                {
                    newOffset = ((ICilLabel)instruction.Operand).Offset;
                }
                else
                {
                    newOffset = instruction.Offset + instruction.Size;
                }
            }
            else
            {
                // TODO: dispatch event, allowing the user to handle unknown branch conditions.
                throw new DispatchException("Branch condition could not be evaluated.");
            }

            var stack = context.ProgramState.Stack;

            for (int i = 0; i < ArgumentCount; i++)
            {
                stack.Pop();
            }

            context.ProgramState.ProgramCounter = newOffset;
            return(DispatchResult.Success());
        }
Ejemplo n.º 14
0
Archivo: Bus.cs Proyecto: Bourl/Zebus
        private void SendMessageProcessingFailedIfNeeded(MessageDispatch dispatch, DispatchResult dispatchResult, TransportMessage failingTransportMessage = null)
        {
            if (dispatchResult.Errors.Count == 0 || dispatchResult.Errors.All(error => error is DomainException))
            {
                return;
            }

            if (failingTransportMessage == null)
            {
                failingTransportMessage = ToTransportMessage(dispatch.Message, MessageId.NextId());
            }

            string jsonMessage;

            try
            {
                jsonMessage = JsonConvert.SerializeObject(dispatch.Message);
            }
            catch (Exception ex)
            {
                jsonMessage = string.Format("Unable to serialize message :{0}{1}", System.Environment.NewLine, ex);
            }
            var errorMessages           = dispatchResult.Errors.Select(error => error.ToString());
            var errorMessage            = string.Join(System.Environment.NewLine + System.Environment.NewLine, errorMessages);
            var messageProcessingFailed = new MessageProcessingFailed(failingTransportMessage, jsonMessage, errorMessage, SystemDateTime.UtcNow, dispatchResult.ErrorHandlerTypes.Select(x => x.FullName).ToArray());
            var peers = _directory.GetPeersHandlingMessage(messageProcessingFailed);

            SendTransportMessage(ToTransportMessage(messageProcessingFailed, MessageId.NextId()), peers);
        }
Ejemplo n.º 15
0
        /// <inheritdoc />
        public override DispatchResult Execute(CilExecutionContext context, CilInstruction instruction)
        {
            var environment = context.GetService <ICilRuntimeEnvironment>();
            var factory     = environment.Module.CorLibTypeFactory;

            var stack        = context.ProgramState.Stack;
            var valueValue   = stack.Pop();
            var pointerValue = (IPointerValue)stack.Pop();

            var marshaller = environment.CliMarshaller;

            switch (instruction.OpCode.Code)
            {
            case CilCode.Stind_I:
                if (pointerValue.Is32Bit)
                {
                    pointerValue.WriteInteger32(0, valueValue.InterpretAsI4());
                }
                else
                {
                    pointerValue.WriteInteger64(0, valueValue.InterpretAsI8());
                }
                break;

            case CilCode.Stind_I1:
                pointerValue.WriteInteger8(0,
                                           (Integer8Value)marshaller.ToCtsValue(valueValue.InterpretAsI1(), factory.SByte));
                break;

            case CilCode.Stind_I2:
                pointerValue.WriteInteger16(0,
                                            (Integer16Value)marshaller.ToCtsValue(valueValue.InterpretAsI2(), factory.Int16));
                break;

            case  CilCode.Stind_I4:
                pointerValue.WriteInteger32(0,
                                            (Integer32Value)marshaller.ToCtsValue(valueValue.InterpretAsI4(), factory.Int32));
                break;

            case CilCode.Stind_I8:
                pointerValue.WriteInteger64(0,
                                            (Integer64Value)marshaller.ToCtsValue(valueValue.InterpretAsI8(), factory.Int64));
                break;

            case CilCode.Stind_R4:
                pointerValue.WriteFloat32(0,
                                          (Float32Value)marshaller.ToCtsValue(valueValue.InterpretAsR4(), factory.Single));
                break;

            case CilCode.Stind_R8:
                pointerValue.WriteFloat64(0,
                                          (Float64Value)marshaller.ToCtsValue(valueValue.InterpretAsR8(), factory.Double));
                break;

            default:
                return(DispatchResult.InvalidProgram());
            }

            return(base.Execute(context, instruction));
        }
Ejemplo n.º 16
0
        public static bool Raycast(Info Info, ref Result Result)
        {
            Vector2 endPoint = Info.Origin + (Info.Direction * Info.Distance);

            DispatchResult[] results = new DispatchResult[Info.Scene.Bodies.Length];

            for (int i = 0; i < Info.Scene.Bodies.Length; ++i)
            {
                Body body = Info.Scene.Bodies[i];

                results[i] = DispatchShape(body, Info, endPoint);
            }

            int            index     = -1;
            DispatchResult minResult = FindMinimumDistanced(results, ref index);

            if (!minResult.Hit)
            {
                return(false);
            }

            Result.Body  = Info.Scene.Bodies[index];
            Result.Point = minResult.Point;

            return(true);
        }
Ejemplo n.º 17
0
 /// <inheritdoc />
 protected override DispatchResult Execute(ExecutionContext context, CilInstruction instruction,
     IntegerValue left, IntegerValue right)
 {
     left.Add(right);
     context.ProgramState.Stack.Push(left);
     return DispatchResult.Success();
 }
Ejemplo n.º 18
0
 /// <inheritdoc />
 protected override DispatchResult Execute(CilExecutionContext context, CilInstruction instruction,
                                           IntegerValue left, IntegerValue right)
 {
     left.Xor(right);
     context.ProgramState.Stack.Push((ICliValue)left);
     return(DispatchResult.Success());
 }
Ejemplo n.º 19
0
        /// <summary>
        /// Converts the provided trilean to an I4 stack value, pushes it onto the stack and returns the success
        /// dispatcher result.
        /// </summary>
        /// <param name="context">The current execution context.</param>
        /// <param name="result">The trilean value.</param>
        /// <returns>The dispatch result.</returns>
        protected static DispatchResult ConvertToI4AndReturnSuccess(CilExecutionContext context, Trilean result)
        {
            var i4Result = new I4Value(result.ToBooleanOrFalse() ? 1 : 0, 0xFFFFFFFEu | (result.IsKnown ? 1u : 0u));

            context.ProgramState.Stack.Push(i4Result);
            return(DispatchResult.Success());
        }
Ejemplo n.º 20
0
        /// <inheritdoc />
        public override DispatchResult Execute(CilExecutionContext context, CilInstruction instruction)
        {
            var environment = context.GetService <ICilRuntimeEnvironment>();

            var variables = new IVariable[1];

            if (environment.Architecture.GetReadVariables(instruction, variables) != 1)
            {
                throw new DispatchException(
                          $"Architecture returned an incorrect number of variables being read from instruction {instruction}.");
            }

            switch (variables[0])
            {
            case CilParameter parameter:
                var value = environment.CliMarshaller.ToCliValue(
                    context.ProgramState.Variables[variables[0]],
                    parameter.Parameter.ParameterType);

                context.ProgramState.Stack.Push(value);
                return(base.Execute(context, instruction));

            default:
                return(DispatchResult.InvalidProgram());
            }
        }
Ejemplo n.º 21
0
        public void FailsWhenNoFactoryTypeIsNull()
        {
            Request r = new Request();

            RequestDispatcher dispatcher = new RequestDispatcher();

            DispatchResult result = dispatcher.Dispatch(r, "Network");
        }
Ejemplo n.º 22
0
        private static DispatchResult TestLineIntersectsLine(Vector2 Line1StartPoint, Vector2 Line1EndPoint, Vector2 Line2StartPoint, Vector2 Line2EndPoint)
        {
            DispatchResult result = new DispatchResult();

            result.Hit = TestLineIntersectsLine(Line1StartPoint, Line1EndPoint, Line2StartPoint, Line2EndPoint, out result.Distance, out result.Point);

            return(result);
        }
Ejemplo n.º 23
0
        private void Dispatch(IMessage message, MessageContext context, MessageDispatcher dispatcher = null)
        {
            _dispatchResult = null;

            var dispatch = new MessageDispatch(context, message, (x, r) => _dispatchResult = r);

            (dispatcher ?? _messageDispatcher).Dispatch(dispatch);
        }
Ejemplo n.º 24
0
        public void Will_Not_Try_To_Invoke_MultiMethod_Recursively()
        {
            Dispatcher dispatcher = Dispatcher.For(typeof(Morph), multiMethod);

            DispatchResult result = dispatcher.Dispatch(morph, new Morph());

            Assert.IsFalse(result.Success);
            Assert.IsTrue(result.NoMatch);
        }
Ejemplo n.º 25
0
Archivo: Ceq.cs Proyecto: lanicon/Echo
        /// <inheritdoc />
        protected override DispatchResult Execute(CilExecutionContext context, CilInstruction instruction,
                                                  FValue left, FValue right)
        {
            // ReSharper disable once CompareOfFloatsByEqualityOperator
            var i4Result = new I4Value(left.F64 == right.F64 ? 1 : 0);

            context.ProgramState.Stack.Push(i4Result);
            return(DispatchResult.Success());
        }
Ejemplo n.º 26
0
        public void Will_Return_NoMatch_If_Method_Target_Is_Null()
        {
            Dispatcher dispatcher = Dispatcher.For(typeof(Circle), multiMethod);

            DispatchResult result = dispatcher.Dispatch(null, new Rectangle());

            Assert.IsTrue(result.NoMatch);
            Assert.IsFalse(result.IsDynamicInvoke);
        }
Ejemplo n.º 27
0
        public void Will_Return_NoMatch_If_Method_Argument_Is_Null()
        {
            Dispatcher dispatcher = Dispatcher.For(typeof(Circle), multiMethod);

            DispatchResult result = dispatcher.Dispatch(new Circle(), new object[] { null });

            Assert.IsTrue(result.NoMatch);
            Assert.IsFalse(result.IsDynamicInvoke);
        }
Ejemplo n.º 28
0
        private static DispatchResult ExecuteDefault(ExecutionContext context, IntegerValue value, IntegerValue left)
        {
            if (value.IsNonZero.IsUnknown)
            {
                value.MarkFullyUnknown();
            }

            context.ProgramState.Stack.Push(left);
            return(DispatchResult.Success());
        }
Ejemplo n.º 29
0
        public void Will_Not_Automatically_Register_Methods_With_Interface_Parameters_In_Cache()
        {
            Dispatcher dispatcher = Dispatcher.For(typeof(Circle), multiMethod);

            // protected new string Intersect(IShape shape)

            DispatchResult result = dispatcher.Dispatch(circle, new Morph());

            Assert.IsTrue(result.IsDynamicInvoke);
        }
Ejemplo n.º 30
0
        /// <inheritdoc />
        public DispatchResult Execute(CilExecutionContext context, CilInstruction instruction)
        {
            var(left, right) = BinaryOperationHelper.PopBinaryOperationArguments(context);

            var result = (left, right) switch
            {
                (IntegerValue a, IntegerValue b) => Execute(context, instruction, a, b),
                (FValue a, FValue b) => Execute(context, instruction, a, b),
                (OValue a, OValue b) => Execute(context, instruction, a, b),
                _ => DispatchResult.InvalidProgram(),
            };
		/// <summary>
		/// It creates an RequestDispatchedEventArgs for the given request and result.
		/// It is used by the RequestDispatched event, fired during the dispatch process.
		/// </summary>
		/// <param name="request">Request tried to be dispatched.</param>
		/// <param name="result">Dispatch process result.</param>
		public RequestDispatchedEventArgs(Request request, DispatchResult result)
		{
			this.request = request;
			this.result = result;
		}