public async Task StreamWriteAsyncTest()
        {
            byte[] buffer = GetRandomBuffer(1 * 1024 * 1024);
            MemoryStream stream1 = new MemoryStream(buffer);
            MemoryStream stream2 = new MemoryStream();

            OperationContext tempOperationContext = new OperationContext();
            RESTCommand<NullType> cmd = new RESTCommand<NullType>(TestBase.StorageCredentials, null);
            ExecutionState<NullType> tempExecutionState = new ExecutionState<NullType>(cmd, null, tempOperationContext);

            // Test basic write
            await stream1.WriteToAsync(stream2, null, null, false, tempExecutionState, null, CancellationToken.None);
            stream1.Position = 0;

            TestHelper.AssertStreamsAreEqual(stream1, stream2);

            stream2.Dispose();
            stream2 = new MemoryStream();

            await TestHelper.ExpectedExceptionAsync<ArgumentException>(
                async () => await stream1.WriteToAsync(stream2, 1024, 1024, false, tempExecutionState, null, CancellationToken.None),
                "Parameters copyLength and maxLength cannot be passed simultaneously.");

            stream1.Dispose();
            stream2.Dispose();
        }
Ejemplo n.º 2
0
        public virtual void Start()
        {
            if (_state != ExecutionState.Created)
            {
                var message = String.Format("Start() called on Fiber with state: {0}", _state);
                throw new ThreadStateException(message);
            }

            _state = ExecutionState.Running;
        }
        public void StreamWriteSyncTestCopyLengthBoundary()
        {
            byte[] buffer = GetRandomBuffer(1 * 1024 * 1024);
            MemoryStream stream1 = new MemoryStream(buffer);
            MemoryStream stream2 = new MemoryStream();
            MemoryStream stream3 = new MemoryStream();
            
            OperationContext tempOperationContext = new OperationContext();
            RESTCommand<NullType> cmd = new RESTCommand<NullType>(TestBase.StorageCredentials, null);
            ExecutionState<NullType> tempExecutionState = new ExecutionState<NullType>(cmd, null, tempOperationContext);
            
            // Test write with exact number of bytes
            stream1.WriteToSync(stream2, stream1.Length, null, true, false, tempExecutionState, null);
            stream1.Position = 0;
            stream1.WriteToSync(stream3, stream1.Length, null, true, true, tempExecutionState, null);
            stream1.Position = 0;

            TestHelper.AssertStreamsAreEqual(stream1, stream2);
            TestHelper.AssertStreamsAreEqual(stream1, stream3);

            stream2.Dispose();
            stream2 = new MemoryStream();
            stream3.Dispose();
            stream3 = new MemoryStream();

            // Test write with one less byte
            stream1.WriteToSync(stream2, stream1.Length - 1, null, true, false, tempExecutionState, null);
            stream1.Position = 0;
            stream1.WriteToSync(stream3, stream1.Length - 1, null, true, true, tempExecutionState, null);
            stream1.Position = 0;

            Assert.AreEqual(stream1.Length - 1, stream2.Length);
            Assert.AreEqual(stream1.Length - 1, stream3.Length);
            TestHelper.AssertStreamsAreEqualAtIndex(stream1, stream2, 0, 0, (int)stream1.Length - 1);
            TestHelper.AssertStreamsAreEqualAtIndex(stream1, stream3, 0, 0, (int)stream1.Length - 1);

            stream2.Dispose();
            stream2 = new MemoryStream();
            stream3.Dispose();
            stream3 = new MemoryStream();

            // Test with copyLength greater than length
            TestHelper.ExpectedException<ArgumentOutOfRangeException>(
                () => stream1.WriteToSync(stream2, stream1.Length + 1, null, true, false, tempExecutionState, null),
                "The given stream does not contain the requested number of bytes from its given position.");
            stream1.Position = 0;
            TestHelper.ExpectedException<ArgumentOutOfRangeException>(
                () => stream1.WriteToSync(stream3, stream1.Length + 1, null, true, true, tempExecutionState, null),
                "The given stream does not contain the requested number of bytes from its given position.");
            stream1.Position = 0;

            stream1.Dispose();
            stream2.Dispose();
            stream3.Dispose();
        }
Ejemplo n.º 4
0
        public void Start()
        {
            // Toggle tthese lines to enable/disable concurrent execution.
            if (taskExecutionState == ExecutionState.Started)
                return;

            taskExecutionState = ExecutionState.Started;
            foreach (var task in tasks)
            {
                task.Execute();
            }
        }
		protected virtual void OnExecutionStateChanged(ExecutionState newState){

			if (newState == state) {
				return;
			}

			var oldState = state;
			state = newState;

			var executionStateChanged = ExecutionStateChanged;

			if (executionStateChanged != null) {
				executionStateChanged (this, new ExecutionStateChangedEventArgs (state, oldState));
			}
		}
        public async Task WriteToMultiBufferMemoryStreamTestAsync()
        {
            OperationContext tempOperationContext = new OperationContext();
            RESTCommand<NullType> cmd = new RESTCommand<NullType>(TestBase.StorageCredentials, null);
            ExecutionState<NullType> tempExecutionState = new ExecutionState<NullType>(cmd, null, tempOperationContext);

            byte[] buffer = GetRandomBuffer(1 * 1024 * 1024);
            MemoryStream stream1 = new MemoryStream(buffer);

            MultiBufferMemoryStream stream2 = new MultiBufferMemoryStream(null /* bufferManager */);
            await stream1.WriteToAsync(stream2, null, null, false, tempExecutionState, null, CancellationToken.None);
            stream1.Seek(0, SeekOrigin.Begin);
            stream2.Seek(0, SeekOrigin.Begin);
            TestHelper.AssertStreamsAreEqual(stream1, stream2);

            MultiBufferMemoryStream stream3 = new MultiBufferMemoryStream(null /* bufferManager */);
            await TestHelper.ExpectedExceptionAsync<TimeoutException>(
                () => stream2.FastCopyToAsync(stream3, DateTime.Now.AddMinutes(-1)),
                "Past expiration time should immediately fail");
            stream2.Seek(0, SeekOrigin.Begin);
            stream3.Seek(0, SeekOrigin.Begin);
            await stream2.FastCopyToAsync(stream3, DateTime.Now.AddHours(1));
            stream2.Seek(0, SeekOrigin.Begin);
            stream3.Seek(0, SeekOrigin.Begin);
            TestHelper.AssertStreamsAreEqual(stream2, stream3);

            MultiBufferMemoryStream stream4 = new MultiBufferMemoryStream(null /* bufferManager */, 12345);
            await stream3.FastCopyToAsync(stream4, null);
            stream3.Seek(0, SeekOrigin.Begin);
            stream4.Seek(0, SeekOrigin.Begin);
            TestHelper.AssertStreamsAreEqual(stream3, stream4);

            MemoryStream stream5 = new MemoryStream();
            await stream4.WriteToAsync(stream5, null, null, false, tempExecutionState, null, CancellationToken.None);
            stream4.Seek(0, SeekOrigin.Begin);
            stream5.Seek(0, SeekOrigin.Begin);
            TestHelper.AssertStreamsAreEqual(stream4, stream5);

            TestHelper.AssertStreamsAreEqual(stream1, stream5);
        }
Ejemplo n.º 7
0
        private void OnRun(object sender, RoutedEventArgs e)
        {

            this.RunButton.Click -= OnRun;
            this.RunButton.Content = pausePanel;
            this.RunButton.Click += OnPause;

            execState = ExecutionState.Running;

            _runTimer.Elapsed += OnTimer;
            _runTimer.Start();

        }
Ejemplo n.º 8
0
        private void InvokeTyped(DarksVMContext ctx, MethodBase targetMethod, byte opCode, ref uint sp, out ExecutionState state)
        {
            var parameters = targetMethod.GetParameters();
            var paramCount = parameters.Length;

            if (!targetMethod.IsStatic && opCode != DarksVMConstants.ECALL_NEWOBJ)
            {
                paramCount++;
            }

            Type constrainType = null;

            if (opCode == DarksVMConstants.ECALL_CALLVIRT_CONSTRAINED)
            {
                constrainType = (Type)ctx.Instance.Data.LookupReference(ctx.Stack[sp--].U4);
            }

            var indexOffset = targetMethod.IsStatic || opCode == DarksVMConstants.ECALL_NEWOBJ ? 0 : 1;
            var references  = new IReference[paramCount];
            var types       = new Type[paramCount];

            for (var i = paramCount - 1; i >= 0; i--)
            {
                Type paramType;
                if (!targetMethod.IsStatic && opCode != DarksVMConstants.ECALL_NEWOBJ)
                {
                    if (i == 0)
                    {
                        if (!targetMethod.IsStatic)
                        {
                            var thisSlot = ctx.Stack[sp];
                            if (thisSlot.O is ValueType && !targetMethod.DeclaringType.IsValueType)
                            {
                                Debug.Assert(targetMethod.DeclaringType.IsInterface);
                                Debug.Assert(opCode == DarksVMConstants.ECALL_CALLVIRT);
                                // Interface dispatch on valuetypes => use constrained. invocation
                                constrainType = thisSlot.O.GetType();
                            }
                        }

                        if (constrainType != null)
                        {
                            paramType = constrainType.MakeByRefType();
                        }
                        else if (targetMethod.DeclaringType.IsValueType)
                        {
                            paramType = targetMethod.DeclaringType.MakeByRefType();
                        }
                        else
                        {
                            paramType = targetMethod.DeclaringType;
                        }
                    }
                    else
                    {
                        paramType = parameters[i - 1].ParameterType;
                    }
                }
                else
                {
                    paramType = parameters[i].ParameterType;
                }
                references[i] = PopRef(ctx, paramType, ref sp);
                if (paramType.IsByRef)
                {
                    paramType = paramType.GetElementType();
                }
                types[i] = paramType;
            }

            OpCode callOp;
            Type   retType;

            if (opCode == DarksVMConstants.ECALL_CALL)
            {
                callOp  = System.Reflection.Emit.OpCodes.Call;
                retType = targetMethod is MethodInfo ? ((MethodInfo)targetMethod).ReturnType : typeof(void);
            }
            else if (opCode == DarksVMConstants.ECALL_CALLVIRT ||
                     opCode == DarksVMConstants.ECALL_CALLVIRT_CONSTRAINED)
            {
                callOp  = System.Reflection.Emit.OpCodes.Callvirt;
                retType = targetMethod is MethodInfo ? ((MethodInfo)targetMethod).ReturnType : typeof(void);
            }
            else if (opCode == DarksVMConstants.ECALL_NEWOBJ)
            {
                callOp  = System.Reflection.Emit.OpCodes.Newobj;
                retType = targetMethod.DeclaringType;
            }
            else
            {
                throw new InvalidProgramException();
            }
            var proxy = DirectCall.GetTypedInvocationProxy(targetMethod, callOp, constrainType);

            var result = proxy(ctx, references, types);

            if (retType != typeof(void))
            {
                ctx.Stack[++sp] = DarksVMSlot.FromObject(result, retType);
            }
            else if (opCode == DarksVMConstants.ECALL_NEWOBJ)
            {
                ctx.Stack[++sp] = DarksVMSlot.FromObject(result, retType);
            }

            ctx.Stack.SetTopPosition(sp);
            ctx.Registers[DarksVMConstants.REG_SP].U4 = sp;
            state = ExecutionState.Next;
        }
Ejemplo n.º 9
0
 private BenchmarkAlgorithm(BenchmarkAlgorithm original, Cloner cloner) {
   if (original.ExecutionState == ExecutionState.Started) throw new InvalidOperationException(string.Format("Clone not allowed in execution state \"{0}\".", ExecutionState));
   cloner.RegisterClonedObject(original, this);
   name = original.name;
   description = original.description;
   parameters = cloner.Clone(original.parameters);
   readOnlyParameters = null;
   executionState = original.executionState;
   executionTime = original.executionTime;
   storeAlgorithmInEachRun = original.storeAlgorithmInEachRun;
   runsCounter = original.runsCounter;
   Runs = cloner.Clone(original.runs);
   results = cloner.Clone(original.results);
 }
Ejemplo n.º 10
0
 protected override void Dispose(bool disposing)
 {
     if (disposing)
         _started = ExecutionState.Stopped;
     base.Dispose(disposing);
 }
Ejemplo n.º 11
0
        public void Execute()
        {
            try
            {
                this.OnExecute();
            }
            catch(System.Exception exception)
            {
                this.editorExecutionState = ExecutionState.ERROR;

                Debug.LogException(exception);
            }
        }
Ejemplo n.º 12
0
 protected static void FinishRequestAttempt <T>(ExecutionState <T> executionState)
 {
     executionState.Cmd.CurrentResult.EndTime = DateTime.Now;
     executionState.OperationContext.EndTime  = DateTime.Now;
     Executor.FireRequestCompleted(executionState);
 }
Ejemplo n.º 13
0
 /// <summary>
 /// Allows an application to inform the system that it 
 /// is in use, thereby preventing the system from entering 
 /// the sleeping power state or turning off the display 
 /// while the application is running.
 /// </summary>
 /// <param name="flags">The thread's execution requirements.</param>
 /// <exception cref="Win32Exception">Thrown if the SetThreadExecutionState call fails.</exception>
 internal static void SetThreadExecutionState(ExecutionState flags)
 {
     ExecutionState? ret = PowerManagementNativeMethods.SetThreadExecutionState(flags);
     if (ret == null)
         throw new Win32Exception("SetThreadExecutionState call failed.");
 }
Ejemplo n.º 14
0
        internal void RunInstruction(Instruction i)
        {
            switch (i.Opcode)
            {
            case OpCode.JumpTo:
            {
                /// - JumpTo

                /** Jumps to a named label
                 */
                state.programCounter = FindInstructionPointForLabel(i.Operands[0].StringValue) - 1;

                break;
            }

            case OpCode.RunLine:
            {
                /// - RunLine

                /** Looks up a string from the string table and
                 *  passes it to the client as a line
                 */
                string stringKey = i.Operands[0].StringValue;

                var pause = lineHandler(new Line(stringKey));

                if (pause == Dialogue.HandlerExecutionType.PauseExecution)
                {
                    executionState = ExecutionState.Suspended;
                }

                break;
            }

            case OpCode.RunCommand:
            {
                /// - RunCommand

                /** Passes a string to the client as a custom command
                 */
                var pause = commandHandler(
                    new Command(i.Operands[0].StringValue)
                    );

                if (pause == Dialogue.HandlerExecutionType.PauseExecution)
                {
                    executionState = ExecutionState.Suspended;
                }

                break;
            }

            case OpCode.PushString:
            {
                /// - PushString

                /** Pushes a string value onto the stack. The operand is an index into
                 *  the string table, so that's looked up first.
                 */
                state.PushValue(i.Operands[0].StringValue);

                break;
            }

            case OpCode.PushFloat:
            {
                /// - PushFloat

                /** Pushes a floating point onto the stack.
                 */
                state.PushValue(i.Operands[0].FloatValue);

                break;
            }

            case OpCode.PushBool:
            {
                /// - PushBool

                /** Pushes a boolean value onto the stack.
                 */
                state.PushValue(i.Operands[0].BoolValue);

                break;
            }

            case OpCode.PushNull:
            {
                /// - PushNull

                /** Pushes a null value onto the stack.
                 */
                state.PushValue(Value.NULL);

                break;
            }

            case OpCode.JumpIfFalse:
            {
                /// - JumpIfFalse

                /** Jumps to a named label if the value on the top of the stack
                 *  evaluates to the boolean value 'false'.
                 */
                if (state.PeekValue().AsBool == false)
                {
                    state.programCounter = FindInstructionPointForLabel(i.Operands[0].StringValue) - 1;
                }
                break;
            }

            case OpCode.Jump:
            {        /// - Jump
                /** Jumps to a label whose name is on the stack.
                 */
                var jumpDestination = state.PeekValue().AsString;
                state.programCounter = FindInstructionPointForLabel(jumpDestination) - 1;

                break;
            }

            case OpCode.Pop:
            {
                /// - Pop

                /** Pops a value from the stack.
                 */
                state.PopValue();
                break;
            }

            case OpCode.CallFunc:
            {
                /// - CallFunc

                /** Call a function, whose parameters are expected to
                 *  be on the stack. Pushes the function's return value,
                 *  if it returns one.
                 */
                var functionName = i.Operands[0].StringValue;

                var function = dialogue.library.GetFunction(functionName);
                {
                    var expectedParamCount = function.paramCount;

                    // Expect the compiler to have placed the number of parameters
                    // actually passed at the top of the stack.
                    var actualParamCount = (int)state.PopValue().AsNumber;

                    // If a function indicates -1 parameters, it takes as
                    // many parameters as it was given (i.e. it's a
                    // variadic function)
                    if (expectedParamCount == -1)
                    {
                        expectedParamCount = actualParamCount;
                    }

                    if (expectedParamCount != actualParamCount)
                    {
                        throw new InvalidOperationException($"Function {function.name} expected {expectedParamCount}, but received {actualParamCount}");
                    }

                    Value result;
                    if (actualParamCount == 0)
                    {
                        result = function.Invoke();
                    }
                    else
                    {
                        // Get the parameters, which were pushed in reverse
                        Value[] parameters = new Value[actualParamCount];
                        for (int param = actualParamCount - 1; param >= 0; param--)
                        {
                            parameters[param] = state.PopValue();
                        }

                        // Invoke the function
                        result = function.InvokeWithArray(parameters);
                    }

                    // If the function returns a value, push it
                    if (function.returnsValue)
                    {
                        state.PushValue(result);
                    }
                }

                break;
            }

            case OpCode.PushVariable:
            {
                /// - PushVariable

                /** Get the contents of a variable, push that onto the stack.
                 */
                var variableName = i.Operands[0].StringValue;
                var loadedValue  = dialogue.continuity.GetValue(variableName);
                state.PushValue(loadedValue);

                break;
            }

            case OpCode.StoreVariable:
            {
                /// - StoreVariable

                /** Store the top value on the stack in a variable.
                 */
                var topValue = state.PeekValue();
                var destinationVariableName = i.Operands[0].StringValue;
                dialogue.continuity.SetValue(destinationVariableName, topValue);

                break;
            }

            case OpCode.Stop:
            {
                /// - Stop

                /** Immediately stop execution, and report that fact.
                 */
                nodeCompleteHandler(currentNode.Name);
                dialogueCompleteHandler();
                executionState = ExecutionState.Stopped;

                break;
            }

            case OpCode.RunNode:
            {
                /// - RunNode

                /** Run a node
                 */
                string nodeName;

                if (i.Operands.Count == 0 || string.IsNullOrEmpty(i.Operands[0].StringValue))
                {
                    // Get a string from the stack, and jump to a node with that name.
                    nodeName = state.PeekValue().AsString;
                }
                else
                {
                    // jump straight to the node
                    nodeName = i.Operands[0].StringValue;
                }

                var pause = nodeCompleteHandler(currentNode.Name);

                SetNode(nodeName);

                // Decrement program counter here, because it will
                // be incremented when this function returns, and
                // would mean skipping the first instruction
                state.programCounter -= 1;

                if (pause == Dialogue.HandlerExecutionType.PauseExecution)
                {
                    executionState = ExecutionState.Suspended;
                }

                break;
            }

            case OpCode.AddOption:
            {
                /// - AddOption

                /** Add an option to the current state.
                 */
                if (!state.currentOptions.ContainsKey(i.Operands[0].StringValue))
                {
                    state.currentOptions.Add(
                        i.Operands[0].StringValue,
                        new State.OptionWithFlag(
                            i.Operands[0].StringValue,         // node name
                            i.Operands[1].StringValue,         // display string key
                            false
                            )
                        );
                }

                break;
            }

            case OpCode.ShowOptions:
            {
                /// - ShowOptions

                /** If we have no options to show, immediately stop.
                 */
                if (state.currentOptions.Count == 0)
                {
                    executionState = ExecutionState.Stopped;
                    dialogueCompleteHandler();
                    break;
                }

                // Present the list of options to the user and let them pick
                var optionChoices = new List <OptionSet.Option>();

                var keys = state.currentOptions.Keys.ToList();
                for (int optionIndex = 0; optionIndex < keys.Count; optionIndex++)
                {
                    var option = state.currentOptions[keys[optionIndex]];
                    var line   = new Line(option.Key);

                    if (!option.HasBeenShown)
                    {
                        optionChoices.Add(new OptionSet.Option(line, keys[optionIndex]));
                        state.currentOptions[keys[optionIndex]] = new State.OptionWithFlag(option.Key, option.Value, true);
                    }
                }

                // We can't continue until our client tell us which option to pick
                //executionState = ExecutionState.WaitingOnOptionSelection;

                // Pass the options set to the client, as well as a delegate for them to call when the
                // user has made a selection

                optionsHandler(new OptionSet(optionChoices.ToArray()));

                break;
            }

            default:
            {
                /// - default

                /** Whoa, no idea what OpCode this is. Stop the program
                 * and throw an exception.
                 */
                executionState = ExecutionState.Stopped;
                throw new ArgumentOutOfRangeException(
                          $"Unknown opcode {i.Opcode}"
                          );
            }
            }
        }
Ejemplo n.º 15
0
 public static extern ExecutionState SetThreadExecutionState(ExecutionState esFlags);
Ejemplo n.º 16
0
        /// Resumes execution.inheritdoc
        internal void Continue()
        {
            if (currentNode == null)
            {
                dialogue.LogErrorMessage("Cannot continue running dialogue. No node has been selected.");
                return;
            }

            if (executionState == ExecutionState.WaitingOnOptionSelection)
            {
                dialogue.LogErrorMessage("Cannot continue running dialogue. Still waiting on option selection.");
                return;
            }

            if (lineHandler == null)
            {
                dialogue.LogErrorMessage($"Cannot continue running dialogue. {nameof(lineHandler)} has not been set.");
                return;
            }

            if (optionsHandler == null)
            {
                dialogue.LogErrorMessage($"Cannot continue running dialogue. {nameof(optionsHandler)} has not been set.");
                return;
            }

            if (commandHandler == null)
            {
                dialogue.LogErrorMessage($"Cannot continue running dialogue. {nameof(commandHandler)} has not been set.");
                return;
            }

            if (nodeCompleteHandler == null)
            {
                dialogue.LogErrorMessage($"Cannot continue running dialogue. {nameof(nodeCompleteHandler)} has not been set.");
                return;
            }

            if (nodeCompleteHandler == null)
            {
                dialogue.LogErrorMessage($"Cannot continue running dialogue. {nameof(nodeCompleteHandler)} has not been set.");
                return;
            }

            executionState = ExecutionState.Running;

            // Execute instructions until something forces us to stop
            while (executionState == ExecutionState.Running)
            {
                Instruction currentInstruction = currentNode.Instructions[state.programCounter];

                RunInstruction(currentInstruction);

                state.programCounter++;

                if (state.programCounter >= currentNode.Instructions.Count)
                {
                    nodeCompleteHandler(currentNode.Name);
                    executionState = ExecutionState.Stopped;
                    dialogueCompleteHandler();
                    dialogue.LogDebugMessage("Run complete.");
                }
            }
        }
Ejemplo n.º 17
0
 public void Stop()
 {
     executionState = ExecutionState.Stopped;
 }
Ejemplo n.º 18
0
        /// <summary>
        /// A coroutine method that executes all commands in the Block. Only one running instance of each Block is permitted.
        /// </summary>
        /// <param name="commandIndex">Index of command to start execution at</param>
        /// <param name="onComplete">Delegate function to call when execution completes</param>
        public virtual IEnumerator Execute(int commandIndex = 0, Action onComplete = null)
        {
            if (executionState != ExecutionState.Idle)
            {
                yield break;
            }

            if (!executionInfoSet)
            {
                SetExecutionInfo();
            }

            executionCount++;

            var flowchart = GetFlowchart();

            executionState = ExecutionState.Executing;
            BlockSignals.DoBlockStart(this);

            #if UNITY_EDITOR
            // Select the executing block & the first command
            flowchart.SelectedBlock = this;
            if (commandList.Count > 0)
            {
                flowchart.ClearSelectedCommands();
                flowchart.AddSelectedCommand(commandList[0]);
            }
            #endif

            jumpToCommandIndex = commandIndex;

            int i = 0;
            while (true)
            {
                // Executing commands specify the next command to skip to by setting jumpToCommandIndex using Command.Continue()
                if (jumpToCommandIndex > -1)
                {
                    i = jumpToCommandIndex;
                    jumpToCommandIndex = -1;
                }

                // Skip disabled commands, comments and labels
                while (i < commandList.Count &&
                       (!commandList[i].enabled ||
                        commandList[i].GetType() == typeof(Comment) ||
                        commandList[i].GetType() == typeof(Label)))
                {
                    i = commandList[i].CommandIndex + 1;
                }

                if (i >= commandList.Count)
                {
                    break;
                }

                // The previous active command is needed for if / else / else if commands
                if (activeCommand == null)
                {
                    previousActiveCommandIndex = -1;
                }
                else
                {
                    previousActiveCommandIndex = activeCommand.CommandIndex;
                }

                var command = commandList[i];
                activeCommand = command;

                if (flowchart.IsActive())
                {
                    // Auto select a command in some situations
                    if ((flowchart.SelectedCommands.Count == 0 && i == 0) ||
                        (flowchart.SelectedCommands.Count == 1 && flowchart.SelectedCommands[0].CommandIndex == previousActiveCommandIndex))
                    {
                        flowchart.ClearSelectedCommands();
                        flowchart.AddSelectedCommand(commandList[i]);
                    }
                }

                command.IsExecuting = true;
                // This icon timer is managed by the FlowchartWindow class, but we also need to
                // set it here in case a command starts and finishes execution before the next window update.
                command.ExecutingIconTimer = Time.realtimeSinceStartup + FungusConstants.ExecutingIconFadeTime;
                BlockSignals.DoCommandExecute(this, command, i, commandList.Count);
                command.Execute();

                // Wait until the executing command sets another command to jump to via Command.Continue()
                while (jumpToCommandIndex == -1)
                {
                    yield return(null);
                }

                #if UNITY_EDITOR
                if (flowchart.StepPause > 0f)
                {
                    yield return(new WaitForSeconds(flowchart.StepPause));
                }
                #endif

                command.IsExecuting = false;
            }

            executionState = ExecutionState.Idle;
            activeCommand  = null;
            BlockSignals.DoBlockEnd(this);

            if (onComplete != null)
            {
                onComplete();
            }
        }
Ejemplo n.º 19
0
        private void OnRestart (object sender, RoutedEventArgs e)
        {
            this.RunButton.Click -= OnRestart;
            this.RunButton.Content = pausePanel;
            this.RunButton.Click += OnPause;
            execState = ExecutionState.Running;

            this.Dispatcher.Invoke(() =>
            {
                execState = ExecutionState.Running;
                String st;
                _logProcessor.GetFirstLine(out st);
            });
            
            _runTimer.Elapsed += OnTimer;
            _runTimer.Start();
            
           
        }
Ejemplo n.º 20
0
        protected static void FireResponseReceived <T>(ExecutionState <T> executionState)
        {
            RequestEventArgs args = GenerateRequestEventArgs <T>(executionState);

            executionState.OperationContext.FireResponseReceived(args);
        }
Ejemplo n.º 21
0
        private void MainSlider_OnValueChangedSlider_ValueChanged(object sender,
            RoutedPropertyChangedEventArgs<double> e)
        {
            if (execState != ExecutionState.Stopped && (int)MainSlider.Value != _logProcessor.Index)
            {
                double d = MainSlider.Value;
                int tp = (int)d;
                if (tp < _logProcessor.GetAgentStartStep(_currentAgent))
                {
                    tp = _logProcessor.GetAgentStartStep(_currentAgent);
                    //MainSlider.Value = tp;
                }
                else if (tp > LogProcessor.GetAgentEndStep(_currentAgent))
                {
                    tp = LogProcessor.GetAgentEndStep(_currentAgent);
                    //MainSlider.Value = tp;
                }

                Task.Factory.StartNew(() =>
                {

                    lock (_lockerLogProcessorIndex)
                    {
                        if (_logProcessor.GetNumber < tp || tp < 0)
                        {
                            this.Dispatcher.Invoke(() =>
                            {
                                StatusLabel.Foreground = new SolidColorBrush(Colors.Red);
                                StatusLabel.Content = "Illegal step number!";
                                _statusTime = DateTime.Now;
                            });
                            return;
                        }
                        //ast = null;
                        isFirstLine = true;
                        _move_to = tp;
                        if (execState != ExecutionState.Moving)
                        {
                            _previousState = execState;
                            execState = ExecutionState.Moving;
                        }
                    }
                });
            }
        }
Ejemplo n.º 22
0
        protected static void FireRetrying <T>(ExecutionState <T> executionState)
        {
            RequestEventArgs args = GenerateRequestEventArgs <T>(executionState);

            executionState.OperationContext.FireRetrying(args);
        }
Ejemplo n.º 23
0
 public BatchRun(string name, string description)
   : base(name, description) {
   executionState = ExecutionState.Stopped;
   executionTime = TimeSpan.Zero;
   runsExecutionTime = TimeSpan.Zero;
   repetitions = 10;
   repetitionsCounter = 0;
   Runs = new RunCollection { OptimizerName = Name };
 }
Ejemplo n.º 24
0
        // Block开始执行命令

        /// <summary>
        /// A coroutine method that executes all commands in the Block. Only one running instance of each Block is permitted.
        /// </summary>
        /// <param name="commandIndex">Index of command to start execution at</param>
        /// <param name="onComplete">Delegate function to call when execution completes</param>
        public virtual IEnumerator Execute(int commandIndex = 0, Action onComplete = null)
        {
            if (executionState != ExecutionState.Idle)
            {
                Debug.LogWarning(BlockName + " cannot be executed, it is already running.");
                yield break;
            }

            // 结束回调
            lastOnCompleteAction = onComplete;

            if (!executionInfoSet)
            {
                // 设置Block下的各个Command
                SetExecutionInfo();
            }

            // 此Block运行了几次
            executionCount++;
            var executionCountAtStart = executionCount;

            var flowchart = GetFlowchart();

            // 设置为执行状态
            executionState = ExecutionState.Executing;
            BlockSignals.DoBlockStart(this);

            #if UNITY_EDITOR
            // Select the executing block & the first command
            flowchart.SelectedBlock = this;
            if (commandList.Count > 0)
            {
                flowchart.ClearSelectedCommands();
                flowchart.AddSelectedCommand(commandList[0]);
            }
            #endif

            // 要执行哪个命令
            jumpToCommandIndex = commandIndex;

            int i = 0;
            while (true)
            {
                // 从jumpToCommandIndex确定, 下一个要执行的命令
                // Executing commands specify the next command to skip to by setting jumpToCommandIndex using Command.Continue()

                // 把jumpToCommandIndex传给i
                //  * i: 真正要执行的命令index
                if (jumpToCommandIndex > -1)
                {
                    i = jumpToCommandIndex;
                    jumpToCommandIndex = -1;
                }

                // 跳过,
                // 注释命令,Label命令
                // Skip disabled commands, comments and labels
                while (i < commandList.Count &&
                       (!commandList[i].enabled ||
                        commandList[i].GetType() == typeof(Comment) ||
                        commandList[i].GetType() == typeof(Label)))
                {
                    i = commandList[i].CommandIndex + 1;
                }

                // 到达命令队列末尾
                if (i >= commandList.Count)
                {
                    break;
                }

                // 记录,
                // 前一个命令的index
                // The previous active command is needed for if / else / else if commands
                if (activeCommand == null)
                {
                    previousActiveCommandIndex = -1;
                }
                else
                {
                    previousActiveCommandIndex = activeCommand.CommandIndex;
                }

                // 获取到,
                // 要执行的命令
                var command = commandList[i];
                activeCommand = command;

                if (flowchart.IsActive())
                {
                    // Q: SelectedCommands是?
                    // Auto select a command in some situations
                    if ((flowchart.SelectedCommands.Count == 0 && i == 0) ||
                        (flowchart.SelectedCommands.Count == 1 && flowchart.SelectedCommands[0].CommandIndex == previousActiveCommandIndex))
                    {
                        flowchart.ClearSelectedCommands();
                        flowchart.AddSelectedCommand(commandList[i]);
                    }
                }

                // 标记命令执行
                command.IsExecuting = true;
                // This icon timer is managed by the FlowchartWindow class, but we also need to
                // set it here in case a command starts and finishes execution before the next window update.
                command.ExecutingIconTimer = Time.realtimeSinceStartup + FungusConstants.ExecutingIconFadeTime;

                // 发送消息
                BlockSignals.DoCommandExecute(this, command, i, commandList.Count);

                // 执行命令
                command.Execute();

                // 等待Continue()被调用
                // Wait until the executing command sets another command to jump to via Command.Continue()
                while (jumpToCommandIndex == -1)
                {
                    yield return(null);
                }

                #if UNITY_EDITOR
                if (flowchart.StepPause > 0f)
                {
                    yield return(new WaitForSeconds(flowchart.StepPause));
                }
                #endif

                command.IsExecuting = false;
            }

            // 只有2个状态
            //  * 空闲和执行中
            if (State == ExecutionState.Executing &&
                //ensure we aren't dangling from a previous stopage and stopping a future run
                executionCountAtStart == executionCount)
            {
                // 结束执行
                //  * 回到空闲状态
                ReturnToIdle();
            }
        }
Ejemplo n.º 25
0
 public void Stop()
 {
     if (_started != ExecutionState.Running) return; //??just ignore.  why explode?
     lock (_preQueue)
     {
         _started = ExecutionState.Created;
     }
 }
Ejemplo n.º 26
0
        /// <summary>
        /// Executes the batch text given the text span
        /// </summary>
        /// <param name="batchScript"></param>
        /// <param name="textSpan"></param>
        /// <param name="continueProcessing"></param>
        private void ExecuteBatchTextSpanInternal(string batchScript, TextSpan textSpan, out bool continueProcessing)
        {
            Debug.Assert(!String.IsNullOrEmpty(batchScript));
            continueProcessing = true;

            if (batchScript.Trim().Length <= 0)
            {
                result |= ScriptExecutionResult.Success;
                return;
            }

            Debug.Assert(currentBatch != null);

            if (executionState == ExecutionState.Cancelling)
            {
                result = ScriptExecutionResult.Cancel;
            }
            else
            {
                currentBatch.Reset();
                currentBatch.Text                   = batchScript;
                currentBatch.TextSpan               = textSpan;
                currentBatch.BatchIndex             = currentBatchIndex;
                currentBatch.ExpectedExecutionCount = numBatchExecutionTimes;

                currentBatchIndex++;

                if (conditions != null)
                {
                    currentBatch.IsSuppressProviderMessageHeaders = conditions.IsSuppressProviderMessageHeaders;

                    // TODO this is associated with Dacfx specific situations, so uncomment if need be
                    //currentBatch.IsScriptExecutionTracked = conditions.IsScriptExecutionTracked;
                    if (conditions.IsScriptExecutionTracked)
                    {
                        currentBatch.ScriptTrackingId = scriptTrackingId++;
                    }
                }

                //ExecutingBatch state means currentBatch is valid to use from another thread to Cancel
                executionState = ExecutionState.ExecutingBatch;
            }

            ScriptExecutionResult batchResult = ScriptExecutionResult.Failure;

            if (result != ScriptExecutionResult.Cancel)
            {
                bool isExecutionDiscarded = false;
                try
                {
                    RaiseBatchParserExecutionStarted(currentBatch, textSpan);

                    if (!isLocalParse)
                    {
                        batchResult = DoBatchExecution(currentBatch);
                    }
                    else
                    {
                        batchResult = ScriptExecutionResult.Success;
                    }
                }
                finally
                {
                    isExecutionDiscarded = (executionState == ExecutionState.Discarded);
                    if (executionState == ExecutionState.Cancelling || isExecutionDiscarded)
                    {
                        batchResult = ScriptExecutionResult.Cancel;
                    }
                    else
                    {
                        executionState = ExecutionState.Executing;
                    }
                }

                if (!isExecutionDiscarded)
                {
                    RaiseBatchParserExecutionFinished(currentBatch, batchResult);
                }
            }
            else
            {
                batchResult = ScriptExecutionResult.Cancel;
            }

            //if we're in Cancel or Halt state, do some special actions
            if (batchResult == ScriptExecutionResult.Cancel || batchResult == ScriptExecutionResult.Halted)
            {
                result             = batchResult;
                continueProcessing = false;
                return;
            }
            else
            {
                result |= batchResult;
            }
        }
Ejemplo n.º 27
0
 public virtual void Dispose()
 {
     _state = ExecutionState.Stopped;
     _scheduler.Dispose();
     _subscriptions.Dispose();
 }
Ejemplo n.º 28
0
        /// <summary>
        /// Executes the script (on a separated thread)
        /// </summary>
        private void DoExecute(bool isBatchParser)
        {
            //we should not be in the middle of execution here
            if (executionState == ExecutionState.Executing || executionState == ExecutionState.ExecutingBatch)
            {
                throw new InvalidOperationException(SR.EE_ExecutionNotYetCompleteError);
            }

            executionState                = ExecutionState.Initial;
            result                        = ScriptExecutionResult.Failure;
            currentBatchIndex             = 0;
            currentBatch.ExecutionTimeout = executionTimeout;
            expectedShowPlan              = ShowPlanType.None;

            if (!isLocalParse)
            {
                errorAction = conditions.IsHaltOnError ?
                              OnErrorAction.Exit :
                              OnErrorAction.Ignore;

                CreatePrePostConditionBatches();
            }

            ConfigureBatchEventHandlers(currentBatch, batchEventHandlers, true);

            // do we have a cancel request already?
            lock (stateSyncLock)
            {
                if (executionState == ExecutionState.Cancelling)
                {
                    RaiseScriptExecutionFinished(ScriptExecutionResult.Cancel);
                    return;
                }
                Debug.Assert(executionState == ExecutionState.Initial);
                executionState = ExecutionState.Executing;
            }

            if ((result = ExecutePrePostConditionBatches(preConditionBatches)) == ScriptExecutionResult.Success)
            {
                DoScriptExecution(isBatchParser);
            }

            if (!CheckForDiscardedConnection())
            {
                if (!isLocalParse)
                {
                    if (conditions.IsTransactionWrapped && !conditions.IsParseOnly)
                    {
                        if (result == ScriptExecutionResult.Success)
                        {
                            postConditionBatches.Add(new Batch(ExecutionEngineConditions.CommitTransactionStatement, false, executionTimeout));
                        }
                        else
                        {
                            postConditionBatches.Add(new Batch(ExecutionEngineConditions.RollbackTransactionStatement, false, executionTimeout));
                        }
                    }

                    // no need to update the result value as it has been updated by the DoScriptExecution()
                    ExecutePrePostConditionBatches(postConditionBatches);
                }

                //fire an event that we're done with execution of all batches
                if (result == ScriptExecutionResult.Halted) //remap into failure
                {
                    result = ScriptExecutionResult.Failure;
                }

                RaiseScriptExecutionFinished(result);
            }
        }
        public async Task StreamWriteAsyncTestMaxLengthBoundary()
        {
            byte[] buffer = GetRandomBuffer(1 * 1024 * 1024);
            MemoryStream stream1 = new MemoryStream(buffer);
            MemoryStream stream2 = new MemoryStream();

            OperationContext tempOperationContext = new OperationContext();
            RESTCommand<NullType> cmd = new RESTCommand<NullType>(TestBase.StorageCredentials, null);
            ExecutionState<NullType> tempExecutionState = new ExecutionState<NullType>(cmd, null, tempOperationContext);

            // Test write with exact number of bytes
            await stream1.WriteToAsync(stream2, null, stream1.Length, false, tempExecutionState, null, CancellationToken.None);
            stream1.Position = 0;

            TestHelper.AssertStreamsAreEqual(stream1, stream2);

            stream2.Dispose();
            stream2 = new MemoryStream();

            // Test write with one less byte
            await TestHelper.ExpectedExceptionAsync<InvalidOperationException>(
                async () => await stream1.WriteToAsync(stream2, null, stream1.Length - 1, false, tempExecutionState, null, CancellationToken.None),
                "Stream is longer than the allowed length.");
            stream1.Position = 0;

            stream2.Dispose();
            stream2 = new MemoryStream();

            // Test with count greater than length
            await stream1.WriteToAsync(stream2, null, stream1.Length + 1, false, tempExecutionState, null, CancellationToken.None);
            stream1.Position = 0;

            // Entire stream should have been copied
            TestHelper.AssertStreamsAreEqual(stream1, stream2);

            stream1.Dispose();
            stream2.Dispose();
        }
Ejemplo n.º 30
0
 public override void VisitEndMethodDeclaration(VBSyntax.MethodBlockSyntax node, ExecutionState state)
 {
     CheckState(state);
 }
 public override void VisitEnd(SyntaxNode node, ExecutionState state)
 {
     CheckState(state);
 }
Ejemplo n.º 32
0
        public object EvaluateVariableProperty(string propertyName, Token propertyToken, ExecutionState state)
        {
            switch (propertyName)
            {
            case "forumcategoryid": return(forumCategory.ForumCategoryID);

            case "clientspaceid": return(forumCategory.ClientSpaceID);

            case "categorycode": return(forumCategory.CategoryCode);

            case "name": return(forumCategory.Name);

            case "urltoken": return(forumCategory.URLToken);

            case "datecreated": return(forumCategory.DateCreated);

            case "rank": return(forumCategory.Rank);

            case "internaluseonly": return(forumCategory.InternalUseOnly);

            case "forumlist": return(GetForums());

            default:
                throw new InstructionExecutionException("\"" + propertyName + "\" is not a property of this variable.", propertyToken);
            }
        }
Ejemplo n.º 33
0
 /// <summary>
 /// Stop consuming actions.
 /// </summary>
 public void Stop()
 {
     _timer.Dispose();
     _started = ExecutionState.Stopped;
     _subscriptions.Dispose();
 }
Ejemplo n.º 34
0
 public object Evaluate(ExecutionState state, Token contextToken)
 {
     return("[Page: " + pageID + "]");
 }
Ejemplo n.º 35
0
 private void OnPause(object sender, RoutedEventArgs e)
 {
     this.RunButton.Click -= OnPause;
     execState = ExecutionState.Paused;
     this.RunButton.Content = runIcon;
     this.RunButton.Click += OnRun;
     _runTimer.Elapsed -= OnTimer;
     _runTimer.Stop();
 }
Ejemplo n.º 36
0
 internal static extern uint SetThreadExecutionState(ExecutionState state);
Ejemplo n.º 37
0
        private void OnStop(object sender, RoutedEventArgs e)
        {

            if (execState == ExecutionState.Running)
            {
                this.RunButton.Content = runIcon;
                this.RunButton.Click -= OnPause;
            }
            else if (execState == ExecutionState.Paused)
            {
                this.RunButton.Click -= OnRun;
            }
            this.RunButton.Click += OnRestart;

            if (execState == ExecutionState.Paused || execState == ExecutionState.Running)
            {
                if (execState == ExecutionState.Running)
                {_runTimer.Elapsed -= OnTimer;}

                execState = ExecutionState.Void;
                _runTimer.Stop();

                this.Dispatcher.Invoke(() =>
                {
                    String st;
                    _logProcessor.GetLastLine(out st);
                });
            }
        }
Ejemplo n.º 38
0
        internal static void WriteToAsync <T>(this Stream stream, Stream toStream, long?copyLength, long?maxLength, bool calculateMd5, ExecutionState <T> executionState, StreamDescriptor streamCopyState, Action <ExecutionState <T> > completed)
        {
            AsyncStreamCopier <T> copier = new AsyncStreamCopier <T>(stream, toStream, executionState, GetBufferSize(stream), calculateMd5, streamCopyState);

            copier.StartCopyStream(completed, copyLength, maxLength);
        }
Ejemplo n.º 39
0
 private void UIElement_OnMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
 {
     var item = (sender as Grid);
     Agent tp = (Agent)item.DataContext;
     if (Keyboard.Modifiers.ToString().Contains("Control"))
     {
         if (tp.ID == _currentAgent)
         {
             this.Dispatcher.Invoke(() =>
             {
                 StatusLabel.Foreground = new SolidColorBrush(Colors.Red);
                 StatusLabel.Content = "This is actually the current agent.";
                 _statusTime = DateTime.Now;
             });
         }
         else if (_logProcessor.IsAgentLogAvailable(tp.ID))
         {
             _currentAgent = tp.ID;
             _logProcessor.CurrentAgent = _currentAgent;
             _previousState = execState;
             execState = ExecutionState.Switching;
         }
         else
         {
             this.Dispatcher.Invoke(() =>
             {
                 StatusLabel.Foreground = new SolidColorBrush(Colors.Red);
                 StatusLabel.Content = "Agent #" + tp.ID + " doesn't have the log file";
                 _statusTime = DateTime.Now;
             });
         }
     }
     else
     {
         tp.IsExpanded = !tp.IsExpanded;
     }
 }
Ejemplo n.º 40
0
        internal static void WriteToSync <T>(this Stream stream, Stream toStream, long?copyLength, long?maxLength, bool calculateMd5, bool syncRead, ExecutionState <T> executionState, StreamDescriptor streamCopyState)
        {
            if (copyLength.HasValue && maxLength.HasValue)
            {
                throw new ArgumentException(SR.StreamLengthMismatch);
            }

            if (stream.CanSeek && maxLength.HasValue && stream.Length - stream.Position > maxLength)
            {
                throw new InvalidOperationException(SR.StreamLengthError);
            }

            if (stream.CanSeek && copyLength.HasValue && stream.Length - stream.Position < copyLength)
            {
                throw new ArgumentOutOfRangeException("copyLength", SR.StreamLengthShortError);
            }

            byte[] buffer = new byte[GetBufferSize(stream)];

            if (streamCopyState != null && calculateMd5 && streamCopyState.Md5HashRef == null)
            {
                streamCopyState.Md5HashRef = new MD5Wrapper();
            }

            RegisteredWaitHandle waitHandle     = null;
            ManualResetEvent     completedEvent = null;

            if (!syncRead && executionState.OperationExpiryTime.HasValue)
            {
                completedEvent = new ManualResetEvent(false);
                waitHandle     = ThreadPool.RegisterWaitForSingleObject(
                    completedEvent,
                    StreamExtensions.MaximumCopyTimeCallback <T>,
                    executionState,
                    executionState.RemainingTimeout,
                    true);
            }

            try
            {
                long?bytesRemaining = copyLength;
                int  readCount;
                do
                {
                    if (executionState.OperationExpiryTime.HasValue && DateTime.Now.CompareTo(executionState.OperationExpiryTime.Value) > 0)
                    {
                        throw Exceptions.GenerateTimeoutException(executionState.Cmd != null ? executionState.Cmd.CurrentResult : null, null);
                    }

                    // Determine how many bytes to read this time so that no more than copyLength bytes are read
                    int bytesToRead = MinBytesToRead(bytesRemaining, buffer.Length);

                    if (bytesToRead == 0)
                    {
                        break;
                    }

                    // Read synchronously or asynchronously
                    readCount = syncRead
                                    ? stream.Read(buffer, 0, bytesToRead)
                                    : stream.EndRead(stream.BeginRead(buffer, 0, bytesToRead, null /* Callback */, null /* State */));

                    // Decrement bytes to write from bytes read
                    if (bytesRemaining.HasValue)
                    {
                        bytesRemaining -= readCount;
                    }

                    // Write
                    if (readCount > 0)
                    {
                        toStream.Write(buffer, 0, readCount);

                        // Update the StreamDescriptor after the bytes are successfully committed to the output stream
                        if (streamCopyState != null)
                        {
                            streamCopyState.Length += readCount;

                            if (maxLength.HasValue && streamCopyState.Length > maxLength.Value)
                            {
                                throw new InvalidOperationException(SR.StreamLengthError);
                            }

                            if (streamCopyState.Md5HashRef != null)
                            {
                                streamCopyState.Md5HashRef.UpdateHash(buffer, 0, readCount);
                            }
                        }
                    }
                }while (readCount != 0);

                if (bytesRemaining.HasValue && bytesRemaining != 0)
                {
                    throw new ArgumentOutOfRangeException("copyLength", SR.StreamLengthShortError);
                }
            }
            catch (Exception)
            {
                if (executionState.OperationExpiryTime.HasValue && DateTime.Now.CompareTo(executionState.OperationExpiryTime.Value) > 0)
                {
                    throw Exceptions.GenerateTimeoutException(executionState.Cmd != null ? executionState.Cmd.CurrentResult : null, null);
                }
                else
                {
                    throw;
                }
            }
            finally
            {
                if (waitHandle != null)
                {
                    waitHandle.Unregister(null);
                }

                if (completedEvent != null)
                {
                    completedEvent.Close();
                }
            }

            if (streamCopyState != null && streamCopyState.Md5HashRef != null)
            {
                streamCopyState.Md5        = streamCopyState.Md5HashRef.ComputeHash();
                streamCopyState.Md5HashRef = null;
            }
        }
Ejemplo n.º 41
0
 public BatchRun()
   : base() {
   name = ItemName;
   description = ItemDescription;
   executionState = ExecutionState.Stopped;
   executionTime = TimeSpan.Zero;
   runsExecutionTime = TimeSpan.Zero;
   repetitions = 10;
   repetitionsCounter = 0;
   Runs = new RunCollection { OptimizerName = Name };
 }
Ejemplo n.º 42
0
 public bool Intersects(ExecutionState <G> executionState)
 {
     return(true);
 }
Ejemplo n.º 43
0
 private BatchRun(BatchRun original, Cloner cloner)
   : base(original, cloner) {
   executionState = original.executionState;
   executionTime = original.executionTime;
   runsExecutionTime = original.runsExecutionTime;
   optimizer = cloner.Clone(original.optimizer);
   repetitions = original.repetitions;
   repetitionsCounter = original.repetitionsCounter;
   runs = cloner.Clone(original.runs);
   batchRunAction = original.batchRunAction;
   Initialize();
 }
Ejemplo n.º 44
0
 private void SetState(ExecutionState state)
 {
     this._state = state;
 }
Ejemplo n.º 45
0
 public void Start()
 {
     if (_started == ExecutionState.Running) return; //??just ignore.  why explode?
     InternalStart();
     lock (_preQueue)
     {
         if (_preQueue.Count > 0)
             InternalEnqueue(() => Executor.Execute(_preQueue));
         _started = ExecutionState.Running;
     }
 }
Ejemplo n.º 46
0
        public void Step(ExecutionFrame frame, Stack <VMObject> stack)
        {
            try
            {
                var opcode = (Opcode)Read8();

                frame.VM.ValidateOpcode(opcode);

                switch (opcode)
                {
                case Opcode.NOP:
                {
                    break;
                }

                // args: byte src_reg, byte dest_reg
                case Opcode.MOVE:
                {
                    var src = Read8();
                    var dst = Read8();

                    Expect(src < frame.Registers.Length);
                    Expect(dst < frame.Registers.Length);

                    frame.Registers[dst] = frame.Registers[src];
                    break;
                }

                // args: byte src_reg, byte dest_reg
                case Opcode.COPY:
                {
                    var src = Read8();
                    var dst = Read8();

                    Expect(src < frame.Registers.Length);
                    Expect(dst < frame.Registers.Length);

                    frame.Registers[dst].Copy(frame.Registers[src]);
                    break;
                }

                // args: byte dst_reg, byte type, var length, var data_bytes
                case Opcode.LOAD:
                {
                    var dst  = Read8();
                    var type = (VMType)Read8();
                    var len  = (int)ReadVar(0xFFFF);

                    Expect(dst < frame.Registers.Length);

                    var bytes = ReadBytes(len);
                    frame.Registers[dst].SetValue(bytes, type);

                    break;
                }

                // args: byte src_reg, dst_reg, byte type
                case Opcode.CAST:
                {
                    var src  = Read8();
                    var dst  = Read8();
                    var type = (VMType)Read8();

                    Expect(src < frame.Registers.Length);
                    Expect(dst < frame.Registers.Length);

                    var val = frame.Registers[src];
                    val = VMObject.CastTo(val, type);

                    frame.Registers[dst] = val;
                    break;
                }

                // args: byte src_reg
                case Opcode.PUSH:
                {
                    var src = Read8();
                    Expect(src < frame.Registers.Length);

                    var val = frame.Registers[src];

                    var temp = new VMObject();
                    temp.Copy(val);
                    stack.Push(temp);
                    break;
                }

                // args: byte dest_reg
                case Opcode.POP:
                {
                    var dst = Read8();

                    Expect(stack.Count > 0);
                    Expect(dst < frame.Registers.Length);

                    frame.Registers[dst] = stack.Pop();
                    break;
                }

                // args: byte src_reg, byte dest_reg
                case Opcode.SWAP:
                {
                    var src = Read8();
                    var dst = Read8();

                    Expect(src < frame.Registers.Length);
                    Expect(dst < frame.Registers.Length);

                    var temp = frame.Registers[src];
                    frame.Registers[src] = frame.Registers[dst];
                    frame.Registers[dst] = temp;

                    break;
                }

                // args: ushort offset, byte regCount
                case Opcode.CALL:
                {
                    var count = Read8();
                    var ofs   = Read16();

                    Expect(ofs < this.Script.Length);
                    Expect(count >= 1);
                    Expect(count <= VirtualMachine.MaxRegisterCount);

                    frame.VM.PushFrame(this, InstructionPointer, count);

                    InstructionPointer = ofs;
                    break;
                }

                // args: byte srcReg
                case Opcode.EXTCALL:
                {
                    var src = Read8();
                    Expect(src < frame.Registers.Length);

                    var method = frame.Registers[src].AsString();

                    var state = frame.VM.ExecuteInterop(method);
                    if (state != ExecutionState.Running)
                    {
                        throw new VMException(frame.VM, "VM extcall failed: " + method);
                    }

                    break;
                }

                // args: ushort offset, byte src_reg
                // NOTE: JMP only has offset arg, not the rest
                case Opcode.JMP:
                case Opcode.JMPIF:
                case Opcode.JMPNOT:
                {
                    bool shouldJump;

                    if (opcode == Opcode.JMP)
                    {
                        shouldJump = true;
                    }
                    else
                    {
                        var src = Read8();
                        Expect(src < frame.Registers.Length);

                        shouldJump = frame.Registers[src].AsBool();

                        if (opcode == Opcode.JMPNOT)
                        {
                            shouldJump = !shouldJump;
                        }
                    }

                    var newPos = (short)Read16();

                    Expect(newPos >= 0);
                    Expect(newPos < this.Script.Length);

                    if (shouldJump)
                    {
                        InstructionPointer = (uint)newPos;
                    }

                    break;
                }

                // args: var length, var bytes
                case Opcode.THROW:
                {
                    var len = (int)ReadVar(1024);

                    if (len > 0)
                    {
                        var bytes = ReadBytes(len);
                    }

                    SetState(ExecutionState.Fault);
                    return;
                }

                // args: none
                case Opcode.RET:
                {
                    if (frame.VM.frames.Count > 1)
                    {
                        var temp = frame.VM.PeekFrame();

                        if (temp.Context == this)
                        {
                            InstructionPointer = frame.VM.PopFrame();
                            //Expect(InstructionPointer == this.Script.Length);
                        }
                        else
                        {
                            SetState(ExecutionState.Halt);
                        }
                    }
                    else
                    {
                        SetState(ExecutionState.Halt);
                    }
                    return;
                }

                // args: byte src_a_reg, byte src_b_reg, byte dest_reg
                case Opcode.CAT:
                {
                    var srcA = Read8();
                    var srcB = Read8();
                    var dst  = Read8();

                    Expect(srcA < frame.Registers.Length);
                    Expect(srcB < frame.Registers.Length);
                    Expect(dst < frame.Registers.Length);

                    var A = frame.Registers[srcA];
                    var B = frame.Registers[srcB];

                    if (!A.IsEmpty)
                    {
                        if (B.IsEmpty)
                        {
                            frame.Registers[dst].Copy(A);
                        }
                        else
                        {
                            var bytesA = A.AsByteArray();
                            var bytesB = B.AsByteArray();

                            var result = new byte[bytesA.Length + bytesB.Length];
                            Array.Copy(bytesA, result, bytesA.Length);
                            Array.Copy(bytesB, 0, result, bytesA.Length, bytesB.Length);

                            Expect(A.Type == B.Type);

                            VMType type = A.Type;
                            frame.Registers[dst].SetValue(result, type);
                        }
                    }
                    else
                    {
                        if (B.IsEmpty)
                        {
                            frame.Registers[dst] = new VMObject();
                        }
                        else
                        {
                            frame.Registers[dst].Copy(B);
                        }
                    }

                    break;
                }

                case Opcode.SUBSTR:
                {
                    throw new NotImplementedException();
                }

                // args: byte src_reg, byte dest_reg, var length
                case Opcode.LEFT:
                {
                    var src = Read8();
                    var dst = Read8();
                    var len = (int)ReadVar(0xFFFF);

                    Expect(src < frame.Registers.Length);
                    Expect(dst < frame.Registers.Length);

                    var src_array = frame.Registers[src].AsByteArray();
                    Expect(len <= src_array.Length);

                    var result = new byte[len];

                    Array.Copy(src_array, result, len);

                    frame.Registers[dst].SetValue(result, VMType.Bytes);
                    break;
                }

                // args: byte src_reg, byte dest_reg, byte length
                case Opcode.RIGHT:
                {
                    var src = Read8();
                    var dst = Read8();
                    var len = (int)ReadVar(0xFFFF);

                    Expect(src < frame.Registers.Length);
                    Expect(dst < frame.Registers.Length);

                    var src_array = frame.Registers[src].AsByteArray();
                    Expect(len <= src_array.Length);

                    var ofs = src_array.Length - len;

                    var result = new byte[len];
                    Array.Copy(src_array, ofs, result, 0, len);

                    frame.Registers[dst].SetValue(result, VMType.Bytes);
                    break;
                }

                // args: byte src_reg, byte dest_reg
                case Opcode.SIZE:
                {
                    var src = Read8();
                    var dst = Read8();

                    Expect(src < frame.Registers.Length);
                    Expect(dst < frame.Registers.Length);

                    var src_array = frame.Registers[src].AsByteArray();
                    frame.Registers[dst].SetValue(src_array.Length);
                    break;
                }

                // args: byte src_reg, byte dest_reg
                case Opcode.COUNT:
                {
                    var src = Read8();
                    var dst = Read8();

                    Expect(src < frame.Registers.Length);
                    Expect(dst < frame.Registers.Length);

                    var val = frame.Registers[src];
                    int count;

                    switch (val.Type)
                    {
                    case VMType.Struct:
                    {
                        var children = val.GetChildren();
                        count = children.Count;
                        break;
                    }

                    default: count = 1; break;
                    }

                    frame.Registers[dst].SetValue(count);
                    break;
                }

                // args: byte src_reg, byte dest_reg
                case Opcode.NOT:
                {
                    var src = Read8();
                    var dst = Read8();

                    Expect(src < frame.Registers.Length);
                    Expect(dst < frame.Registers.Length);

                    var val = frame.Registers[src].AsBool();

                    frame.Registers[dst].SetValue(!val);
                    break;
                }

                // args: byte src_a_reg, byte src_b_reg, byte dest_reg
                case Opcode.AND:
                case Opcode.OR:
                case Opcode.XOR:
                {
                    var srcA = Read8();
                    var srcB = Read8();
                    var dst  = Read8();

                    Expect(srcA < frame.Registers.Length);
                    Expect(srcB < frame.Registers.Length);
                    Expect(dst < frame.Registers.Length);

                    var a = frame.Registers[srcA].AsBool();
                    var b = frame.Registers[srcB].AsBool();

                    bool result;
                    switch (opcode)
                    {
                    case Opcode.AND: result = (a && b); break;

                    case Opcode.OR: result = (a || b); break;

                    case Opcode.XOR: result = (a ^ b); break;

                    default:
                    {
                        SetState(ExecutionState.Fault);
                        return;
                    }
                    }

                    frame.Registers[dst].SetValue(result);
                    break;
                }

                // args: byte src_a_reg, byte src_b_reg, byte dest_reg
                case Opcode.EQUAL:
                {
                    var srcA = Read8();
                    var srcB = Read8();
                    var dst  = Read8();

                    Expect(srcA < frame.Registers.Length);
                    Expect(srcB < frame.Registers.Length);
                    Expect(dst < frame.Registers.Length);

                    var a = frame.Registers[srcA];
                    var b = frame.Registers[srcB];

                    var result = a.Equals(b);
                    frame.Registers[dst].SetValue(result);

                    break;
                }

                // args: byte src_a_reg, byte src_b_reg, byte dest_reg
                case Opcode.LT:
                case Opcode.GT:
                case Opcode.LTE:
                case Opcode.GTE:
                {
                    var srcA = Read8();
                    var srcB = Read8();
                    var dst  = Read8();

                    Expect(srcA < frame.Registers.Length);
                    Expect(srcB < frame.Registers.Length);
                    Expect(dst < frame.Registers.Length);

                    var a = frame.Registers[srcA].AsNumber();
                    var b = frame.Registers[srcB].AsNumber();

                    bool result;
                    switch (opcode)
                    {
                    case Opcode.LT: result = (a < b); break;

                    case Opcode.GT: result = (a > b); break;

                    case Opcode.LTE: result = (a <= b); break;

                    case Opcode.GTE: result = (a >= b); break;

                    default:
                    {
                        SetState(ExecutionState.Fault);
                        return;
                    }
                    }

                    frame.Registers[dst].SetValue(result);
                    break;
                }

                // args: byte reg
                case Opcode.INC:
                {
                    var dst = Read8();
                    Expect(dst < frame.Registers.Length);

                    var val = frame.Registers[dst].AsNumber();
                    frame.Registers[dst].SetValue(val + 1);

                    break;
                }

                // args: byte reg
                case Opcode.DEC:
                {
                    var dst = Read8();
                    Expect(dst < frame.Registers.Length);

                    var val = frame.Registers[dst].AsNumber();
                    frame.Registers[dst].SetValue(val - 1);

                    break;
                }

                // args: byte src_reg, byte dest_reg
                case Opcode.SIGN:
                {
                    var src = Read8();
                    var dst = Read8();

                    Expect(src < frame.Registers.Length);
                    Expect(dst < frame.Registers.Length);

                    var val = frame.Registers[src].AsNumber();

                    if (val == 0)
                    {
                        frame.Registers[dst].SetValue(BigInteger.Zero);
                    }
                    else
                    {
                        frame.Registers[dst].SetValue(val < 0 ? -1 : 1);
                    }

                    break;
                }

                // args: byte src_reg, byte dest_reg
                case Opcode.NEGATE:
                {
                    var src = Read8();
                    var dst = Read8();
                    Expect(src < frame.Registers.Length);
                    Expect(dst < frame.Registers.Length);

                    var val = frame.Registers[src].AsNumber();
                    frame.Registers[dst].SetValue(-val);

                    break;
                }

                // args: byte src_reg, byte dest_reg
                case Opcode.ABS:
                {
                    var src = Read8();
                    var dst = Read8();
                    Expect(src < frame.Registers.Length);
                    Expect(dst < frame.Registers.Length);

                    var val = frame.Registers[src].AsNumber();
                    frame.Registers[dst].SetValue(val < 0 ? -val : val);

                    break;
                }

                // args: byte src_a_reg, byte src_b_reg, byte dest_reg
                case Opcode.ADD:
                case Opcode.SUB:
                case Opcode.MUL:
                case Opcode.DIV:
                case Opcode.MOD:
                case Opcode.SHR:
                case Opcode.SHL:
                case Opcode.MIN:
                case Opcode.MAX:
                {
                    var srcA = Read8();
                    var srcB = Read8();
                    var dst  = Read8();

                    Expect(srcA < frame.Registers.Length);
                    Expect(srcB < frame.Registers.Length);
                    Expect(dst < frame.Registers.Length);

                    var a = frame.Registers[srcA].AsNumber();
                    var b = frame.Registers[srcB].AsNumber();

                    BigInteger result;

                    switch (opcode)
                    {
                    case Opcode.ADD: result = a + b; break;

                    case Opcode.SUB: result = a - b; break;

                    case Opcode.MUL: result = a * b; break;

                    case Opcode.DIV: result = a / b; break;

                    case Opcode.MOD: result = a % b; break;

                    case Opcode.SHR: result = a >> (int)b; break;

                    case Opcode.SHL: result = a << (int)b; break;

                    case Opcode.MIN: result = a < b ? a : b; break;

                    case Opcode.MAX: result = a > b ? a : b; break;

                    default:
                    {
                        SetState(ExecutionState.Fault);
                        return;
                    }
                    }

                    frame.Registers[dst].SetValue(result);
                    break;
                }

                // args: byte src_reg, byte dest_reg, byte key
                case Opcode.PUT:
                {
                    var src    = Read8();
                    var dst    = Read8();
                    var keyReg = Read8();

                    Expect(src < frame.Registers.Length);
                    Expect(dst < frame.Registers.Length);
                    Expect(keyReg < frame.Registers.Length);

                    var key   = frame.Registers[keyReg];
                    var value = frame.Registers[src];

                    frame.Registers[dst].SetKey(key, value);

                    break;
                }

                // args: byte src_reg, byte dest_reg, byte key
                case Opcode.GET:
                {
                    var src    = Read8();
                    var dst    = Read8();
                    var keyReg = Read8();

                    Expect(src < frame.Registers.Length);
                    Expect(dst < frame.Registers.Length);
                    Expect(keyReg < frame.Registers.Length);

                    var key = frame.Registers[keyReg];
                    var val = frame.Registers[src].GetKey(key);

                    frame.Registers[dst] = val;

                    break;
                }

                // args: byte dest_reg
                case Opcode.THIS:
                {
                    var dst = Read8();
                    Expect(dst < frame.Registers.Length);

                    frame.Registers[dst].SetValue(this);

                    break;
                }

                // args: byte dest_reg, var key
                case Opcode.CTX:
                {
                    var src = Read8();
                    var dst = Read8();

                    Expect(src < frame.Registers.Length);
                    Expect(dst < frame.Registers.Length);

                    var contextName = frame.Registers[src].AsString();

                    ExecutionContext context = frame.VM.FindContext(contextName);

                    if (context == null)
                    {
                        throw new VMException(frame.VM, $"VM ctx instruction failed: could not find context with name '{contextName}'");
                    }

                    frame.Registers[dst].SetValue(context);

                    break;
                }

                // args: byte src_reg
                case Opcode.SWITCH:
                {
                    var src = Read8();
                    Expect(src < frame.Registers.Length);

                    var context = frame.Registers[src].AsInterop <ExecutionContext>();

                    _state = frame.VM.SwitchContext(context, InstructionPointer);

                    if (_state == ExecutionState.Halt)
                    {
                        _state = ExecutionState.Running;
                        frame.VM.PopFrame();
                    }
                    else
                    {
                        throw new VMException(frame.VM, $"VM switch instruction failed: execution state did not halt");
                    }

                    break;
                }

                default:
                {
                    throw new VMException(frame.VM, $"Unknown VM opcode: {(int)opcode}");
                }
                }
            }
            catch (Exception ex)
            {
                if (ex is TargetInvocationException)
                {
                    ex = ((TargetInvocationException)ex).InnerException;
                }

                Trace.WriteLine(ex.ToString());
                SetState(ExecutionState.Fault);

                if (!(ex is VMException))
                {
                    ex = new VMException(frame.VM, ex.Message);
                }

                if (frame.VM.ThrowOnFault) // enable this when debugging difficult stuff in the VM, should not be activated for production code
                {
                    throw ex;
                }
            }
        }
Ejemplo n.º 47
0
        public void EditorUpdate()
        {
            this.m_editorTimeDelta += Time.deltaTime;

            if(this.m_editorTimeDelta >= this.m_editorStateResetTime)
            {
                this.m_editorTimeDelta = 0;

                if(editorExecutionState != ExecutionState.ERROR)
                {
                    editorExecutionState = ExecutionState.IDLE;
                }
            }

            this.OnShowHideInHierarchy();
            this.OnEditorUpdate();

            foreach(Anchor anchor in anchors)
            {
                anchor.EditorUpdate();
            }
        }
 private static extern ExecutionState SetThreadExecutionState(ExecutionState esFlags);
Ejemplo n.º 49
0
        /// <summary>
        /// Invokes the exposed method by name, if successful 
        /// will invoke all nodes connected via the anchor by the same
        /// name.
        /// </summary>
        /// <param name="methodName"></param>
        public void Fire(string methodName, params object[] args)
        {
            try
            {
                foreach(Expose exposed in GetExposed())
                {
                    if(exposed.exposedName == methodName)
                    {
                        FireExposed(exposed);
                    }
                }

            }
            catch(System.Exception exception)
            {
                this.editorExecutionState = ExecutionState.ERROR;

                Debug.LogException(exception);
            }
        }
Ejemplo n.º 50
0
 public static void Execute <G>(this Instruction <G> instruction, IInstructionExecutor <G> executor, ExecutionState <G> executionState, StackList <ValuePointer <G> > stackRegister, StackList <StackValuePointer <G> > stackPointers)
     where G : IGroupState <G>, new()
 {
     instruction.ExecutionBody(executor, executionState, instruction.Payload, stackRegister, stackPointers);
 }
Ejemplo n.º 51
0
 protected Executable()
 {
     executionState = ExecutionState.Stopped;
     executionTime  = TimeSpan.Zero;
 }
Ejemplo n.º 52
0
        public ICancellableAsyncResult BeginUploadFromStream(Stream source, AccessCondition accessCondition, BlobRequestOptions options, OperationContext operationContext, AsyncCallback callback, object state)
        {
            CommonUtils.AssertNotNull("source", source);
            this.attributes.AssertNoSnapshot();
            if (!source.CanSeek)
            {
                throw new InvalidOperationException();
            }

            long size = source.Length - source.Position;
            if ((size % Constants.PageSize) != 0)
            {
                throw new ArgumentException(SR.InvalidPageSize, "source");
            }

            BlobRequestOptions modifiedOptions = BlobRequestOptions.ApplyDefaults(options, BlobType.PageBlob, this.ServiceClient);

            DateTime? expiryTime = modifiedOptions.MaximumExecutionTime.HasValue
                ? DateTime.Now + modifiedOptions.MaximumExecutionTime.Value
                : (DateTime?)null;

            OperationContext tempOperationContext = new OperationContext();
            ExecutionState<NullType> executionState = new ExecutionState<NullType>(null /* cmd */, modifiedOptions.RetryPolicy, tempOperationContext);
            ChainedAsyncResult<NullType> chainedResult = new ChainedAsyncResult<NullType>(callback, state);

            lock (chainedResult.CancellationLockerObject)
            {
                ICancellableAsyncResult result = this.BeginOpenWrite(
                    size,
                    accessCondition,
                    modifiedOptions,
                    operationContext,
                    ar =>
                    {
                        chainedResult.UpdateCompletedSynchronously(ar.CompletedSynchronously);

                        lock (chainedResult.CancellationLockerObject)
                        {
                            chainedResult.CancelDelegate = null;
                            try
                            {
                                Stream blobStream = this.EndOpenWrite(ar);

                                source.WriteToAsync(
                                    blobStream,
                                    null /* maxLength */,
                                    expiryTime,
                                    false,
                                    executionState,
                                    tempOperationContext,
                                    null /* streamCopyState */,
                                    completedState =>
                                    {
                                        chainedResult.UpdateCompletedSynchronously(executionState.CompletedSynchronously);

                                        try
                                        {
                                            blobStream.Close();
                                            chainedResult.OnComplete(executionState.ExceptionRef);
                                        }
                                        catch (Exception e)
                                        {
                                            chainedResult.OnComplete(e);
                                        }
                                    });

                                chainedResult.CancelDelegate = executionState.Cancel;
                                if (chainedResult.CancelRequested)
                                {
                                    chainedResult.Cancel();
                                }
                            }
                            catch (Exception e)
                            {
                                chainedResult.OnComplete(e);
                            }
                        }
                    },
                    null /* state */);

                chainedResult.CancelDelegate = result.Cancel;
                if (chainedResult.CancelRequested)
                {
                    chainedResult.Cancel();
                }
            }

            return chainedResult;
        }
Ejemplo n.º 53
0
 public BenchmarkAlgorithm() {
   name = ItemName;
   description = ItemDescription;
   parameters = new ParameterCollection();
   readOnlyParameters = null;
   executionState = ExecutionState.Stopped;
   executionTime = TimeSpan.Zero;
   storeAlgorithmInEachRun = false;
   runsCounter = 0;
   Runs = new RunCollection() { OptimizerName = name };
   results = new ResultCollection();
   CreateParameters();
   DiscoverBenchmarks();
   Prepare();
 }
Ejemplo n.º 54
0
 extern static ExecutionState SetThreadExecutionState(ExecutionState esFlags);
Ejemplo n.º 55
0
 protected Executable(Executable original, Cloner cloner)
     : base(original, cloner)
 {
     executionState = original.executionState;
     executionTime  = original.executionTime;
 }
Ejemplo n.º 56
0
        private void InvokeNormal(DarksVMContext ctx, MethodBase targetMethod, byte opCode, ref uint sp, out ExecutionState state)
        {
            var    _sp        = sp;
            var    parameters = targetMethod.GetParameters();
            object self       = null;
            var    args       = new object[parameters.Length];

            if (opCode == DarksVMConstants.ECALL_CALL && targetMethod.IsVirtual)
            {
                var indexOffset = targetMethod.IsStatic ? 0 : 1;
                args = new object[parameters.Length + indexOffset];
                for (var i = parameters.Length - 1; i >= 0; i--)
                {
                    args[i + indexOffset] = PopObject(ctx, parameters[i].ParameterType, ref sp);
                }
                if (!targetMethod.IsStatic)
                {
                    args[0] = PopObject(ctx, targetMethod.DeclaringType, ref sp);
                }

                targetMethod = DirectCall.GetDirectInvocationProxy(targetMethod);
            }
            else
            {
                args = new object[parameters.Length];
                for (var i = parameters.Length - 1; i >= 0; i--)
                {
                    args[i] = PopObject(ctx, parameters[i].ParameterType, ref sp);
                }
                if (!targetMethod.IsStatic && opCode != DarksVMConstants.ECALL_NEWOBJ)
                {
                    self = PopObject(ctx, targetMethod.DeclaringType, ref sp);

                    if (self != null && !targetMethod.DeclaringType.IsInstanceOfType(self))
                    {
                        // ConfuserEx sometimes produce this to circumvent peverify (see ref proxy)
                        // Reflection won't allow it, so use typed invoke
                        InvokeTyped(ctx, targetMethod, opCode, ref _sp, out state);
                        return;
                    }
                }
            }

            object result;

            if (opCode == DarksVMConstants.ECALL_NEWOBJ)
            {
                try
                {
                    result = ((ConstructorInfo)targetMethod).Invoke(args);
                }
                catch (TargetInvocationException ex)
                {
                    EHHelper.Rethrow(ex.InnerException, null);
                    throw;
                }
            }
            else
            {
                if (!targetMethod.IsStatic && self == null)
                {
                    throw new NullReferenceException();
                }

                Type selfType;
                if (self != null && (selfType = self.GetType()).IsArray && targetMethod.Name == "SetValue")
                {
                    Type valueType;
                    if (args[0] == null)
                    {
                        valueType = selfType.GetElementType();
                    }
                    else
                    {
                        valueType = args[0].GetType();
                    }
                    ArrayStoreHelpers.SetValue((Array)self, (int)args[1], args[0], valueType, selfType.GetElementType());
                    result = null;
                }
                else
                {
                    try
                    {
                        result = targetMethod.Invoke(self, args);
                    }
                    catch (TargetInvocationException ex)
                    {
                        DarksVMDispatcher.DoThrow(ctx, ex.InnerException);
                        throw;
                    }
                }
            }

            if (targetMethod is MethodInfo && ((MethodInfo)targetMethod).ReturnType != typeof(void))
            {
                ctx.Stack[++sp] = DarksVMSlot.FromObject(result, ((MethodInfo)targetMethod).ReturnType);
            }
            else if (opCode == DarksVMConstants.ECALL_NEWOBJ)
            {
                ctx.Stack[++sp] = DarksVMSlot.FromObject(result, targetMethod.DeclaringType);
            }

            ctx.Stack.SetTopPosition(sp);
            ctx.Registers[DarksVMConstants.REG_SP].U4 = sp;
            state = ExecutionState.Next;
        }
Ejemplo n.º 57
0
        public ICancellableAsyncResult BeginWritePages(Stream pageData, long startOffset, string contentMD5, AccessCondition accessCondition, BlobRequestOptions options, OperationContext operationContext, AsyncCallback callback, object state)
        {
            BlobRequestOptions modifiedOptions = BlobRequestOptions.ApplyDefaults(options, BlobType.PageBlob, this.ServiceClient);
            bool requiresContentMD5 = (contentMD5 == null) && modifiedOptions.UseTransactionalMD5.Value;
            operationContext = operationContext ?? new OperationContext();
            ChainedAsyncResult<NullType> chainedResult = new ChainedAsyncResult<NullType>(callback, state);

            if (pageData.CanSeek && !requiresContentMD5)
            {
                this.WritePagesHandler(pageData, startOffset, contentMD5, accessCondition, modifiedOptions, operationContext, chainedResult);
            }
            else
            {
                DateTime? expiryTime = modifiedOptions.MaximumExecutionTime.HasValue
                    ? DateTime.Now + modifiedOptions.MaximumExecutionTime.Value
                    : (DateTime?)null;

                OperationContext tempOperationContext = new OperationContext();
                ExecutionState<NullType> executionState = new ExecutionState<NullType>(null /* cmd */, modifiedOptions.RetryPolicy, tempOperationContext);
                chainedResult.CancelDelegate = executionState.Cancel;

                Stream seekableStream;
                Stream writeToStream;
                if (pageData.CanSeek)
                {
                    seekableStream = pageData;
                    writeToStream = Stream.Null;
                }
                else
                {
                    seekableStream = new MemoryStream();
                    writeToStream = seekableStream;
                }

                long startPosition = seekableStream.Position;
                StreamDescriptor streamCopyState = new StreamDescriptor();
                pageData.WriteToAsync(
                    writeToStream,
                    Constants.MaxBlockSize,
                    expiryTime,
                    requiresContentMD5,
                    executionState,
                    tempOperationContext,
                    streamCopyState,
                    _ =>
                    {
                        chainedResult.UpdateCompletedSynchronously(executionState.CompletedSynchronously);

                        if (executionState.ExceptionRef != null)
                        {
                            chainedResult.OnComplete(executionState.ExceptionRef);
                        }
                        else
                        {
                            try
                            {
                                if (requiresContentMD5)
                                {
                                    contentMD5 = streamCopyState.Md5;
                                }

                                seekableStream.Position = startPosition;
                                this.WritePagesHandler(seekableStream, startOffset, contentMD5, accessCondition, modifiedOptions, operationContext, chainedResult);
                            }
                            catch (Exception e)
                            {
                                chainedResult.OnComplete(e);
                            }
                        }
                    });
            }

            return chainedResult;
        }
        public void WriteToMultiBufferMemoryStreamTestAPM()
        {
            using (AutoResetEvent waitHandle = new AutoResetEvent(false))
            {
                byte[]       buffer  = GetRandomBuffer(1 * 1024 * 1024);
                MemoryStream stream1 = new MemoryStream(buffer);

                RESTCommand <NullType>    cmd       = new RESTCommand <NullType>(TestBase.StorageCredentials, null, null);
                ExecutionState <NullType> state     = new ExecutionState <NullType>(cmd, new NoRetry(), new OperationContext());
                StreamDescriptor          copyState = new StreamDescriptor();

                MultiBufferMemoryStream stream2 = new MultiBufferMemoryStream(null /* bufferManager */);
                stream1.WriteToAsync(stream2, default(IBufferManager), null, null, ChecksumRequested.None, state, copyState, CancellationToken.None, _ => waitHandle.Set());
                waitHandle.WaitOne();
                if (state.ExceptionRef != null)
                {
                    throw state.ExceptionRef;
                }

                stream1.Seek(0, SeekOrigin.Begin);
                stream2.Seek(0, SeekOrigin.Begin);
                TestHelper.AssertStreamsAreEqual(stream1, stream2);

                MultiBufferMemoryStream stream3 = new MultiBufferMemoryStream(null /* bufferManager */);
                IAsyncResult            ar      = stream2.BeginFastCopyTo(stream3, DateTime.Now.AddMinutes(-1), _ => waitHandle.Set(), null);
                waitHandle.WaitOne();
                TestHelper.ExpectedException <TimeoutException>(
                    () => stream3.EndFastCopyTo(ar),
                    "Past expiration time should immediately fail");
                stream2.Seek(0, SeekOrigin.Begin);
                stream3.Seek(0, SeekOrigin.Begin);
                ar = stream2.BeginFastCopyTo(stream3, DateTime.Now.AddHours(1), _ => waitHandle.Set(), null);
                waitHandle.WaitOne();
                stream2.EndFastCopyTo(ar);
                stream2.Seek(0, SeekOrigin.Begin);
                stream3.Seek(0, SeekOrigin.Begin);
                TestHelper.AssertStreamsAreEqual(stream2, stream3);

                MultiBufferMemoryStream stream4 = new MultiBufferMemoryStream(null, 12345);
                ar = stream3.BeginFastCopyTo(stream4, null, _ => waitHandle.Set(), null);
                waitHandle.WaitOne();
                stream3.EndFastCopyTo(ar);
                stream3.Seek(0, SeekOrigin.Begin);
                stream4.Seek(0, SeekOrigin.Begin);
                TestHelper.AssertStreamsAreEqual(stream3, stream4);

                state     = new ExecutionState <NullType>(cmd, new NoRetry(), new OperationContext());
                copyState = new StreamDescriptor();

                MemoryStream stream5 = new MemoryStream();

                stream4.WriteToAsync(stream5, default(IBufferManager), null, null, ChecksumRequested.None, state, copyState, CancellationToken.None, _ => waitHandle.Set());
                waitHandle.WaitOne();
                if (state.ExceptionRef != null)
                {
                    throw state.ExceptionRef;
                }

                stream4.Seek(0, SeekOrigin.Begin);
                stream5.Seek(0, SeekOrigin.Begin);
                TestHelper.AssertStreamsAreEqual(stream4, stream5);

                TestHelper.AssertStreamsAreEqual(stream1, stream5);
            }
        }
Ejemplo n.º 59
0
 private void backupWorkData(ExecutionState status, string clientURL, string jobTrackerURL, string mapperName, byte[] mapperCode, long fileSize, long totalSplits, long remainingSplits)
 {
     this.mapperName = mapperName;
     this.mapperCode = mapperCode;
     this.fileSize = fileSize;
     this.totalSplits = totalSplits;
     this.remainingSplits = remainingSplits;
 }
 internal static Task WriteToAsync <T>(this Stream stream, Stream toStream, ExecutionState <T> executionState, CancellationToken cancellationToken)
 {
     return(new AsyncStreamCopier <T>(stream, toStream, executionState, GetBufferSize(stream)).StartCopyStream(null, null, cancellationToken));
 }