Example #1
0
        private void ChangeDebugState(DebugState newState)
        {
            _debugState = newState;

            if (DebugStateChanged != null)
            {
                DebugStateChanged(_debugState);
            }
        }
Example #2
0
		void TheDebugger_OnProcessStateChanged(object sender, DebuggerEventArgs e) {
			var dbg = (DnDebugger)sender;
			switch (dbg.ProcessState) {
			case DebuggerProcessState.Starting:
				if (outputLoggerSettings.ShowDebugOutputLog)
					outputService.Select(GUID_OUTPUT_LOGGER_DEBUG);

				debugState?.Dispose();
				debugState = null;

				textPane.Clear();
				dbg.DebugCallbackEvent += DnDebugger_DebugCallbackEvent;
				debugState = new DebugState(dbg);
				break;

			case DebuggerProcessState.Continuing:
			case DebuggerProcessState.Running:
			case DebuggerProcessState.Paused:
				Debug.Assert(debugState != null && debugState.dbg == dbg);
				break;

			case DebuggerProcessState.Terminated:
				Debug.Assert(debugState != null);
				Debug.Assert(debugState?.dbg == dbg);

				if (outputLoggerSettings.ShowProcessExitMessages) {
					int processExitCode;
					if (debugState == null || !NativeMethods.GetExitCodeProcess(debugState.hProcess_debuggee, out processExitCode))
						processExitCode = -1;
					textPane.WriteLine(BoxedTextColor.DebugLogExitProcess,
						string.Format(dnSpy_Debugger_Resources.DebugLogExitProcess,
								GetProcessNameWithPID(debugState?.debuggedProcess),
								processExitCode));
				}

				debugState?.Dispose();
				debugState = null;
				break;
			}
		}
Example #3
0
        private void picNametable_MouseMove(object sender, MouseEventArgs e)
        {
            int xPos = e.X * 512 / (picNametable.Width - 2);
            int yPos = e.Y * 480 / (picNametable.Height - 2);

            _nametableIndex = 0;
            if (xPos >= 256)
            {
                _nametableIndex++;
            }
            if (yPos >= 240)
            {
                _nametableIndex += 2;
            }

            int baseAddress = 0x2000 + _nametableIndex * 0x400;

            _tileX = Math.Min(xPos / 8, 63);
            _tileY = Math.Min(yPos / 8, 59);

            if (_nametableIndex % 2 == 1)
            {
                _tileX -= 32;
            }
            if (_nametableIndex >= 2)
            {
                _tileY -= 30;
            }

            int shift      = (_tileX & 0x02) | ((_tileY & 0x02) << 1);
            int ppuAddress = (baseAddress + _tileX + _tileY * 32);

            if (_currentPpuAddress == ppuAddress)
            {
                return;
            }
            _currentPpuAddress = ppuAddress;

            DebugState state = new DebugState();

            InteropEmu.DebugGetState(ref state);
            int bgAddr = state.PPU.ControlFlags.BackgroundPatternAddr;

            int tileIndex       = _tileData[_nametableIndex][_tileY * 32 + _tileX];
            int attributeData   = _attributeData[_nametableIndex][_tileY * 32 + _tileX];
            int attributeAddr   = baseAddress + 960 + ((_tileY & 0xFC) << 1) + (_tileX >> 2);
            int paletteBaseAddr = ((attributeData >> shift) & 0x03) << 2;

            this.ctrlTilePalette.SelectedPalette = (paletteBaseAddr >> 2);

            this.txtPpuAddress.Text       = _currentPpuAddress.ToString("X4");
            this.txtNametable.Text        = _nametableIndex.ToString();
            this.txtLocation.Text         = _tileX.ToString() + ", " + _tileY.ToString();
            this.txtTileIndex.Text        = tileIndex.ToString("X2");
            this.txtTileAddress.Text      = (bgAddr + tileIndex * 16).ToString("X4");
            this.txtAttributeData.Text    = attributeData.ToString("X2");
            this.txtAttributeAddress.Text = attributeAddr.ToString("X4");
            this.txtPaletteAddress.Text   = (0x3F00 + paletteBaseAddr).ToString("X4");

            Bitmap tile        = new Bitmap(64, 64);
            Bitmap tilePreview = new Bitmap(8, 8);

            using (Graphics g = Graphics.FromImage(tilePreview)) {
                g.DrawImage(_nametableImage, new Rectangle(0, 0, 8, 8), new Rectangle(xPos / 8 * 8, yPos / 8 * 8, 8, 8), GraphicsUnit.Pixel);
            }
            using (Graphics g = Graphics.FromImage(tile)) {
                g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.NearestNeighbor;
                g.SmoothingMode     = System.Drawing.Drawing2D.SmoothingMode.None;
                g.PixelOffsetMode   = System.Drawing.Drawing2D.PixelOffsetMode.Half;
                g.ScaleTransform(8, 8);
                g.DrawImageUnscaled(tilePreview, 0, 0);
            }
            this.picTile.Image = tile;
        }
Example #4
0
        private string GetText(Image <Gray, byte> img, DebugState debugState)
        {
            var str = Utils.ReadTextFromImage(img, debugState);


            if (str == "VI")
            {
                str = "W";
            }
            if (str == "VV")
            {
                str = "W";
            }
            if (str == "VY")
            {
                str = "W";
            }
            if (str == "XV")
            {
                str = "W";
            }
            if (str == "\\N")
            {
                str = "W";
            }
            if (str == "5")
            {
                str = "S";
            }
            if (str == "8")
            {
                str = "S";
            }
            if (str == "3")
            {
                str = "S";
            }
            if (str == "9")
            {
                str = "S";
            }
            if (str == "G")
            {
                str = "S";
            }
            if (str == "$")
            {
                str = "S";
            }
            if (str == "U")
            {
                str = "N";
            }
            if (str == "M")
            {
                str = "N";
            }
            if (str == "H")
            {
                str = "N";
            }
            if (str == "I")
            {
                str = "N";
            }
            if (str == "II")
            {
                str = "N";
            }
            if (str == "fl")
            {
                str = "N";
            }
            if (str == "fi")
            {
                str = "N";
            }
            if (str == "F")
            {
                str = "E";
            }
            if (str == "É")
            {
                str = "E";
            }
            if (str == "=")
            {
                str = "E";
            }

            return(str);
        }
Example #5
0
        private IEnumerable <BlobPack> GetPacksFromImage(Image <Gray, byte> focus, IEnumerable <CvBlob> blobs, DebugState debugState)
        {
            var frame_center = new Point(focus.Width / 2, focus.Height / 2);
            var parts        = new List <BlobPack>();

            foreach (var b in blobs)
            {
                b.BoundingBox.Inflate(2, 2);
                var rotationAngle = Math2.GetPolarHeadingFromLine(new LineSegment2D(Point.Round(b.Centroid), frame_center));

                var rotated_frame       = focus.Rotate(-1 * rotationAngle, new Gray(0));
                var rotated_letter_only = rotated_frame.Copy(new Rectangle(rotated_frame.Width / 2 - 30, 0, 60, 60));

                //  rotated_letter_only = Utils.RemoveBlobs(rotated_letter_only, 1, 3);

                debugState.Add(rotated_letter_only);

                parts.Add(new BlobPack {
                    BlobImage = rotated_letter_only, BlobRationAngle = rotationAngle, BlobBox = b.BoundingBox
                });
            }
            return(parts);
        }
Example #6
0
        private void OnNotificationReceived(NotificationEventArgs e)
        {
            switch (e.NotificationType)
            {
            case ConsoleNotificationType.GameLoaded: {
                if (_cpuType == CpuType.Sa1)
                {
                    CoprocessorType coprocessor = EmuApi.GetRomInfo().CoprocessorType;
                    if (coprocessor != CoprocessorType.SA1)
                    {
                        this.Invoke((MethodInvoker)(() => {
                                this.Close();
                            }));
                        return;
                    }
                }

                if (ConfigManager.Config.Debug.Debugger.BreakOnPowerCycleReset)
                {
                    DebugApi.Step(_cpuType, 1, StepType.PpuStep);
                }

                DebugState state = DebugApi.GetState();
                this.BeginInvoke((MethodInvoker)(() => {
                        DebugWorkspaceManager.ImportDbgFile();
                        LabelManager.RefreshLabels();
                        DebugApi.RefreshDisassembly(_cpuType);
                        UpdateDebugger(state, null);
                        BreakpointManager.SetBreakpoints();
                    }));
                break;
            }

            case ConsoleNotificationType.GameReset:
                if (ConfigManager.Config.Debug.Debugger.BreakOnPowerCycleReset)
                {
                    DebugApi.Step(_cpuType, 1, StepType.PpuStep);
                }
                break;

            case ConsoleNotificationType.PpuFrameDone:
                this.BeginInvoke((MethodInvoker)(() => {
                    UpdateContinueAction();
                }));
                break;

            case ConsoleNotificationType.CodeBreak: {
                BreakEvent evt   = (BreakEvent)Marshal.PtrToStructure(e.Parameter, typeof(BreakEvent));
                DebugState state = DebugApi.GetState();
                int        activeAddress;
                switch (_cpuType)
                {
                case CpuType.Cpu: activeAddress = (int)((state.Cpu.K << 16) | state.Cpu.PC); break;

                case CpuType.Spc: activeAddress = (int)state.Spc.PC; break;

                case CpuType.Sa1: activeAddress = (int)((state.Sa1.K << 16) | state.Sa1.PC); break;

                case CpuType.Gsu: activeAddress = (int)((state.Gsu.ProgramBank << 16) | state.Gsu.R[15]); break;

                default: throw new Exception("Unsupported cpu type");
                }

                this.BeginInvoke((MethodInvoker)(() => {
                        ProcessBreakEvent(evt, state, activeAddress);

                        if (_firstBreak && !ConfigManager.Config.Debug.Debugger.BreakOnOpen)
                        {
                            DebugApi.ResumeExecution();
                        }
                        _firstBreak = false;
                    }));
                break;
            }
            }
        }
Example #7
0
        private void RefreshLog(bool scrollToBottom, bool forceUpdate)
        {
            if (_refreshRunning)
            {
                return;
            }

            //Make sure labels are up to date
            DebugWorkspaceManager.GetWorkspace();

            _refreshRunning = true;
            SetOptions();
            Task.Run(() => {
                //Update trace log in another thread for performance
                DebugState state = new DebugState();
                InteropEmu.DebugGetState(ref state);
                if (_previousCycleCount != state.CPU.CycleCount || forceUpdate)
                {
                    string newTrace     = InteropEmu.DebugGetExecutionTrace((UInt32)_lineCount);
                    _previousCycleCount = state.CPU.CycleCount;
                    _previousTrace      = newTrace;

                    int index            = 0;
                    string line          = null;
                    Func <bool> readLine = () => {
                        if (index < newTrace.Length)
                        {
                            int endOfLineIndex = newTrace.IndexOf('\n', index);
                            line  = newTrace.Substring(index, endOfLineIndex - index);
                            index = endOfLineIndex + 1;
                            return(true);
                        }
                        else
                        {
                            return(false);
                        }
                    };

                    List <int> programCounter = new List <int>(30000);
                    List <string> byteCode    = new List <string>(30000);
                    List <string> lineContent = new List <string>(30000);
                    List <int> indent         = new List <int>(30000);

                    bool showByteCode = false;
                    while (readLine())
                    {
                        string[] parts = line.Split('\x1');
                        programCounter.Add(Int32.Parse(parts[0], System.Globalization.NumberStyles.HexNumber));
                        byteCode.Add(parts[1]);

                        string content = parts[2];
                        while (true)
                        {
                            string str = content.TrimStart();
                            if (str.StartsWith(parts[0]))
                            {
                                content = str.Substring(4);
                            }
                            else if (str.StartsWith(parts[1]))
                            {
                                content      = str.Substring(11);
                                showByteCode = true;
                            }
                            else if (str.StartsWith(parts[1].Replace("$", "")))
                            {
                                content      = str.Substring(8);
                                showByteCode = true;
                            }
                            else
                            {
                                break;
                            }
                        }
                        lineContent.Add(content);
                        indent.Add(0);
                    }
                    this.BeginInvoke((Action)(() => {
                        txtTraceLog.ShowContentNotes = showByteCode;
                        txtTraceLog.ShowSingleContentLineNotes = showByteCode;

                        txtTraceLog.LineIndentations = indent.ToArray();
                        txtTraceLog.LineNumbers = programCounter.ToArray();
                        txtTraceLog.TextLineNotes = byteCode.ToArray();
                        txtTraceLog.TextLines = lineContent.ToArray();

                        if (scrollToBottom)
                        {
                            txtTraceLog.ScrollToLineIndex(txtTraceLog.LineCount - 1);
                        }
                    }));
                }
                _refreshRunning = false;
            });
        }
Example #8
0
        public void DispatchDebugState(IDSFDataObject dataObject, StateType stateType, bool hasErrors, string existingErrors, out ErrorResultTO errors, DateTime?workflowStartTime = null, bool interrogateInputs = false, bool interrogateOutputs = false, bool durationVisible = true)
        {
            errors = new ErrorResultTO();
            if (dataObject != null)
            {
                Guid parentInstanceId;
                Guid.TryParse(dataObject.ParentInstanceID, out parentInstanceId);
                bool hasError     = dataObject.Environment.HasErrors();
                var  errorMessage = String.Empty;
                if (hasError)
                {
                    errorMessage = dataObject.Environment.FetchErrors();
                }
                if (String.IsNullOrEmpty(existingErrors))
                {
                    existingErrors = errorMessage;
                }
                else if (!existingErrors.Contains(errorMessage))
                {
                    existingErrors += Environment.NewLine + errorMessage;
                }
                string name = "localhost";
                Guid   remoteID;
                bool   hasRemote = Guid.TryParse(dataObject.RemoteInvokerID, out remoteID);
                if (hasRemote)
                {
                    var res = ResourceCatalog.Instance.GetResource(GlobalConstants.ServerWorkspaceID, remoteID);
                    if (res != null)
                    {
                        name = remoteID != Guid.Empty ? ResourceCatalog.Instance.GetResource(GlobalConstants.ServerWorkspaceID, remoteID).ResourceName : "localhost";
                    }
                }
                var debugState = new DebugState
                {
                    ID                    = dataObject.OriginalInstanceID,
                    ParentID              = parentInstanceId,
                    WorkspaceID           = dataObject.WorkspaceID,
                    StateType             = stateType,
                    StartTime             = workflowStartTime ?? DateTime.Now,
                    EndTime               = DateTime.Now,
                    ActivityType          = ActivityType.Workflow,
                    DisplayName           = dataObject.ServiceName,
                    IsSimulation          = dataObject.IsOnDemandSimulation,
                    ServerID              = dataObject.ServerID,
                    OriginatingResourceID = dataObject.ResourceID,
                    OriginalInstanceID    = dataObject.OriginalInstanceID,
                    Server                = name,
                    Version               = string.Empty,
                    SessionID             = dataObject.DebugSessionID,
                    EnvironmentID         = dataObject.DebugEnvironmentId,
                    ClientID              = dataObject.ClientID,
                    Name                  = stateType.ToString(),
                    HasError              = hasErrors || hasError,
                    ErrorMessage          = existingErrors,
                    IsDurationVisible     = durationVisible
                };

                if (interrogateInputs)
                {
                    ErrorResultTO invokeErrors;
                    var           defs   = DataListUtil.GenerateDefsFromDataListForDebug(FindServiceShape(dataObject.WorkspaceID, dataObject.ResourceID), enDev2ColumnArgumentDirection.Input);
                    var           inputs = GetDebugValues(defs, dataObject, out invokeErrors);
                    errors.MergeErrors(invokeErrors);
                    debugState.Inputs.AddRange(inputs);
                }
                if (interrogateOutputs)
                {
                    ErrorResultTO invokeErrors;

                    var defs   = DataListUtil.GenerateDefsFromDataListForDebug(FindServiceShape(dataObject.WorkspaceID, dataObject.ResourceID), enDev2ColumnArgumentDirection.Output);
                    var inputs = GetDebugValues(defs, dataObject, out invokeErrors);
                    errors.MergeErrors(invokeErrors);
                    debugState.Outputs.AddRange(inputs);
                }
                if (stateType == StateType.End)
                {
                    debugState.NumberOfSteps = dataObject.NumberOfSteps;
                }

                if (stateType == StateType.Start)
                {
                    debugState.ExecutionOrigin            = dataObject.ExecutionOrigin;
                    debugState.ExecutionOriginDescription = dataObject.ExecutionOriginDescription;
                }

                if (dataObject.IsDebugMode() || (dataObject.RunWorkflowAsync && !dataObject.IsFromWebServer))
                {
                    var debugDispatcher = _getDebugDispatcher();
                    if (debugState.StateType == StateType.End)
                    {
                        while (!debugDispatcher.IsQueueEmpty)
                        {
                            Thread.Sleep(100);
                        }
                        debugDispatcher.Write(debugState, dataObject.RemoteInvoke, dataObject.RemoteInvokerID, dataObject.ParentInstanceID, dataObject.RemoteDebugItems);
                    }
                    else
                    {
                        debugDispatcher.Write(debugState);
                    }
                }
            }
        }
Example #9
0
        private void OnNotificationReceived(NotificationEventArgs e)
        {
            switch (e.NotificationType)
            {
            case ConsoleNotificationType.GameLoaded: {
                if (_cpuType == CpuType.Sa1)
                {
                    CoprocessorType coprocessor = EmuApi.GetRomInfo().CoprocessorType;
                    if (coprocessor != CoprocessorType.SA1)
                    {
                        this.Invoke((MethodInvoker)(() => {
                                this.Close();
                            }));
                        return;
                    }
                }

                if (ConfigManager.Config.Debug.Debugger.BreakOnPowerCycleReset)
                {
                    DebugApi.Step(_cpuType, 1, StepType.PpuStep);
                }

                BreakpointManager.SetBreakpoints();

                DebugState state = DebugApi.GetState();
                this.BeginInvoke((MethodInvoker)(() => {
                        //Refresh workspace here as well as frmMain to ensure workspace
                        //is up-to-date no matter which form is notified first.
                        DebugWorkspaceManager.GetWorkspace();

                        bool isPowerCycle = e.Parameter.ToInt32() != 0;
                        if (!isPowerCycle)
                        {
                            DebugWorkspaceManager.AutoImportSymbols();
                        }
                        LabelManager.RefreshLabels();
                        DebugApi.RefreshDisassembly(_cpuType);
                        UpdateDebugger(state, null);
                    }));
                break;
            }

            case ConsoleNotificationType.GameReset:
                if (ConfigManager.Config.Debug.Debugger.BreakOnPowerCycleReset)
                {
                    DebugApi.Step(_cpuType, 1, StepType.PpuStep);
                }
                break;

            case ConsoleNotificationType.PpuFrameDone:
                this.BeginInvoke((MethodInvoker)(() => {
                    UpdateContinueAction();
                }));
                break;

            case ConsoleNotificationType.CodeBreak: {
                BreakEvent evt = (BreakEvent)Marshal.PtrToStructure(e.Parameter, typeof(BreakEvent));
                RefreshDebugger(evt);
                break;
            }
            }
        }
Example #10
0
 static extern bool ContinueDebugEvent(uint dwProcessId, uint dwThreadId, DebugState dwContinueStatus);
Example #11
0
        private void RefreshLog(bool scrollToBottom)
        {
            if (_refreshRunning)
            {
                return;
            }

            //Make sure labels are up to date
            DebugWorkspaceManager.GetWorkspace();

            _refreshRunning = true;
            SetOptions();
            Task.Run(() => {
                //Update trace log in another thread for performance
                DebugState state = new DebugState();
                InteropEmu.DebugGetState(ref state);
                if (_previousCycleCount != state.CPU.CycleCount)
                {
                    string newTrace     = InteropEmu.DebugGetExecutionTrace((UInt32)_lineCount);
                    _previousCycleCount = state.CPU.CycleCount;
                    _previousTrace      = newTrace;

                    int index            = 0;
                    string line          = null;
                    Func <bool> readLine = () => {
                        if (index < newTrace.Length)
                        {
                            int endOfLineIndex = newTrace.IndexOf('\n', index);
                            line  = newTrace.Substring(index, endOfLineIndex - index);
                            index = endOfLineIndex + 1;
                            return(true);
                        }
                        else
                        {
                            return(false);
                        }
                    };

                    List <int> programCounter = new List <int>(30000);
                    List <string> byteCode    = new List <string>(30000);
                    List <string> lineContent = new List <string>(30000);
                    List <int> indent         = new List <int>(30000);

                    char[] splitter = new char[] { ' ' };
                    while (readLine())
                    {
                        programCounter.Add(Int32.Parse(line.Substring(0, 4), System.Globalization.NumberStyles.HexNumber));
                        byteCode.Add(line.Substring(6, 11));
                        lineContent.Add(line.Substring(19));
                        indent.Add(6);
                    }
                    this.BeginInvoke((Action)(() => {
                        txtTraceLog.ShowContentNotes = chkShowByteCode.Checked;
                        txtTraceLog.ShowSingleContentLineNotes = chkShowByteCode.Checked;

                        txtTraceLog.LineIndentations = indent.ToArray();
                        txtTraceLog.LineNumbers = programCounter.ToArray();
                        txtTraceLog.TextLineNotes = byteCode.ToArray();
                        txtTraceLog.TextLines = lineContent.ToArray();

                        if (scrollToBottom)
                        {
                            txtTraceLog.ScrollToLineIndex(txtTraceLog.LineCount - 1);
                        }
                    }));
                }
                _refreshRunning = false;
            });
        }
 internal void StepOut(ExecutionFrame currentFrame)
 {
     _currentState = DebugState.SteppingOut;
     _stopFrames   = _machine.GetExecutionFrames().Select(x => x.FrameObject).Skip(1).ToArray();
 }
 public void StepIn()
 {
     _currentState = DebugState.SteppingIn;
 }
 public void StepOver(ExecutionFrame currentFrame)
 {
     _currentState = DebugState.SteppingOver;
     _stopFrames   = _machine.GetExecutionFrames().Select(x => x.FrameObject).ToArray();
 }
Example #15
0
        static void WriteDebugItems(string workflowName, string taskName, string result)
        {
            var user = Thread.CurrentPrincipal.Identity.Name.Replace("\\", "-");

            var state = new DebugState
            {
                HasError      = result.Contains("Exception"),
                ID            = Guid.NewGuid(),
                StartTime     = StartTime,
                EndTime       = DateTime.Now,
                ActivityType  = ActivityType.Workflow,
                ExecutingUser = user,
                Server        = "localhost",
                ServerID      = Guid.Empty,
                DisplayName   = workflowName
            };

            if (!string.IsNullOrEmpty(result))
            {
                var data  = DataListUtil.AdjustForEncodingIssues(result);
                var isXml = DataListUtil.IsXml(data, out bool isFragment);
                if (isXml)
                {
                    var xmlData     = XElement.Parse(data);
                    var allChildren = xmlData.Elements();
                    var groupedData = allChildren.GroupBy(element => element.Name);

                    var recSets = groupedData as IGrouping <XName, XElement>[] ?? groupedData.ToArray();
                    foreach (var grouping in recSets)
                    {
                        var debugItem = new DebugItem();
                        foreach (var name in grouping)
                        {
                            if (name.HasElements)
                            {
                                var debugItemResult = ProcessRecordSet(name, name.Elements());
                                debugItem.ResultsList.AddRange(debugItemResult);
                            }
                            else
                            {
                                var debugItemResult = new DebugItemResult
                                {
                                    Variable = DataListUtil.AddBracketsToValueIfNotExist(name.Name.LocalName),
                                    Value    = name.Value,
                                    Operator = "=",
                                    Type     = DebugItemResultType.Variable
                                };
                                debugItem.ResultsList.Add(debugItemResult);
                            }
                        }
                        state.Outputs.Add(debugItem);
                    }
                }
            }
            var js = new Dev2JsonSerializer();

            Thread.Sleep(5000);
            var correlation = GetCorrelationId(WarewolfTaskSchedulerPath + taskName);

            if (!Directory.Exists(OutputPath))
            {
                Directory.CreateDirectory(OutputPath);
            }

            File.WriteAllText(
                $"{OutputPath}DebugItems_{workflowName.Replace("\\", "_")}_{DateTime.Now.ToString("yyyy-MM-dd")}_{correlation}_{user}.txt",
                js.SerializeToBuilder(new List <DebugState> {
                state
            }).ToString());
        }
		static IEnumerable<BinSpan> GetBinSpans(DebugState state) {
			foreach (var node in state.Nodes) {
				foreach (var ann in node.Annotations) {
					var list = ann as IList<BinSpan>;
					if (list == null)
						continue;
					foreach (var binSpan in list)
						yield return binSpan;
				}
			}
			foreach (var binSpan in state.ExtraBinSpans)
				yield return binSpan;
		}
Example #17
0
 /// <summary>
 /// 关闭调试等待计时器
 /// </summary>
 private void StopDebugWaitTimer()
 {
     if (debugWaitTimer != null)
     {
         debugState = DebugState.None;
         debugWaitTimer.Stop();
     }
 }
Example #18
0
        public void Import(string path, bool silent = false)
        {
            RomInfo romInfo = InteropEmu.GetRomInfo();

            _headerSize = (int)romInfo.FilePrgOffset;

            DebugState state = new DebugState();

            InteropEmu.DebugGetState(ref state);
            for (int i = 0; i < state.Cartridge.PrgMemoryType.Length; i++)
            {
                if (state.Cartridge.PrgMemoryType[i] == PrgMemoryType.WorkRam)
                {
                    _workRamStart = Math.Min(_workRamStart, i * 0x100);
                    _workRamEnd   = Math.Max(_workRamEnd, i * 0x100 + 0xFF);
                }
                else if (state.Cartridge.PrgMemoryType[i] == PrgMemoryType.SaveRam)
                {
                    _saveRamStart = Math.Min(_saveRamStart, i * 0x100);
                    _saveRamEnd   = Math.Max(_saveRamEnd, i * 0x100 + 0xFF);
                }
            }

            DbgFileStamp = File.GetLastWriteTime(path);
            string[] fileRows = File.ReadAllLines(path);

            string basePath = Path.GetDirectoryName(path);

            DbgPath = basePath;
            foreach (string row in fileRows)
            {
                try {
                    if (LoadLines(row) || LoadSpans(row) || LoadSymbols(row) || LoadCSymbols(row) || LoadScopes(row) || LoadFiles(row, basePath) || LoadSegments(row))
                    {
                        continue;
                    }
                } catch {
                    _errorCount++;
                }
            }

            LoadFileData(basePath);

            BuildCdlData();

            foreach (LineInfo line in _lines.Values)
            {
                foreach (int spanID in line.SpanIDs)
                {
                    SpanInfo span;
                    if (_spans.TryGetValue(spanID, out span))
                    {
                        SegmentInfo segment;
                        if (_segments.TryGetValue(span.SegmentID, out segment) && !segment.IsRam)
                        {
                            for (int i = 0; i < span.Size; i++)
                            {
                                int prgAddress = segment.FileOffset - _headerSize + span.Offset + i;
                                if (prgAddress >= state.Cartridge.PrgRomSize)
                                {
                                    //Address is outside PRG (probably CHR ROM)
                                    continue;
                                }

                                LineInfo existingLine;
                                if (_linesByPrgAddress.TryGetValue(prgAddress, out existingLine) && existingLine.Type == LineType.External)
                                {
                                    //Give priority to lines that come from C files
                                    continue;
                                }

                                _linesByPrgAddress[prgAddress] = line;
                                if (i == 0 && spanID == line.SpanIDs[0])
                                {
                                    //Mark the first byte of the first span representing this line as the PRG address for this line of code
                                    FileInfo file = _files[line.FileID];
                                    _prgAddressByLine[file.ID.ToString() + "_" + line.LineNumber.ToString()] = prgAddress;
                                }
                            }
                        }
                    }
                }
            }

            LoadLabels();

            int labelCount = 0;

            DebugImportConfig config = ConfigManager.Config.DebugInfo.ImportConfig;

            if (config.DbgImportComments)
            {
                LoadComments();
            }
            List <CodeLabel> labels = new List <CodeLabel>(_romLabels.Count + _ramLabels.Count + _workRamLabels.Count + _saveRamLabels.Count);

            if (config.DbgImportPrgRomLabels)
            {
                labels.AddRange(_romLabels.Values);
                labelCount += _romLabels.Count;
            }
            if (config.DbgImportRamLabels)
            {
                labels.AddRange(_ramLabels.Values);
                labelCount += _ramLabels.Count;
            }
            if (config.DbgImportWorkRamLabels)
            {
                labels.AddRange(_workRamLabels.Values);
                labelCount += _workRamLabels.Count;
            }
            if (config.DbgImportSaveRamLabels)
            {
                labels.AddRange(_saveRamLabels.Values);
                labelCount += _saveRamLabels.Count;
            }

            LabelManager.SetLabels(labels, true);

            if (!silent)
            {
                if (_errorCount > 0)
                {
                    _errorCount -= _filesNotFound.Count;
                    string message = $"Import completed with {labelCount} labels imported";
                    if (_errorCount > 0)
                    {
                        message += $"and {_errorCount} errors - please file a bug report and attach the DBG file you tried to import.";
                    }
                    if (_filesNotFound.Count > 0)
                    {
                        message += Environment.NewLine + Environment.NewLine + "The following files could not be found:";
                        foreach (string file in _filesNotFound)
                        {
                            message += Environment.NewLine + file;
                        }
                    }
                    MessageBox.Show(message, "Mesen", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
                else
                {
                    MessageBox.Show($"Import completed with {labelCount} labels imported.", "Mesen", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }
        }
        public void DispatchDebugState(IDSFDataObject dataObject, StateType stateType, bool hasErrors, string existingErrors, out ErrorResultTO errors, DateTime?workflowStartTime = null, bool interrogateInputs = false, bool interrogateOutputs = false)
        {
            errors = new ErrorResultTO();
            if (dataObject != null)
            {
                Guid parentInstanceId;
                Guid.TryParse(dataObject.ParentInstanceID, out parentInstanceId);
                IDataListCompiler compiler = DataListFactory.CreateDataListCompiler();
                bool hasError     = compiler.HasErrors(dataObject.DataListID);
                var  errorMessage = String.Empty;
                if (hasError)
                {
                    errorMessage = compiler.FetchErrors(dataObject.DataListID);
                }
                if (String.IsNullOrEmpty(existingErrors))
                {
                    existingErrors = errorMessage;
                }
                else
                {
                    existingErrors += Environment.NewLine + errorMessage;
                }
                var debugState = new DebugState
                {
                    ID                    = dataObject.DataListID,
                    ParentID              = parentInstanceId,
                    WorkspaceID           = dataObject.WorkspaceID,
                    StateType             = stateType,
                    StartTime             = workflowStartTime ?? DateTime.Now,
                    EndTime               = DateTime.Now,
                    ActivityType          = ActivityType.Workflow,
                    DisplayName           = dataObject.ServiceName,
                    IsSimulation          = dataObject.IsOnDemandSimulation,
                    ServerID              = dataObject.ServerID,
                    OriginatingResourceID = dataObject.ResourceID,
                    OriginalInstanceID    = dataObject.OriginalInstanceID,
                    Server                = string.Empty,
                    Version               = string.Empty,
                    SessionID             = dataObject.DebugSessionID,
                    EnvironmentID         = dataObject.EnvironmentID,
                    ClientID              = dataObject.ClientID,
                    Name                  = stateType.ToString(),
                    HasError              = hasErrors || hasError,
                    ErrorMessage          = existingErrors,
                };

                if (interrogateInputs)
                {
                    ErrorResultTO invokeErrors;
                    var           com = compiler.FetchBinaryDataList(dataObject.DataListID, out invokeErrors);
                    errors.MergeErrors(invokeErrors);
                    var defs   = compiler.GenerateDefsFromDataListForDebug(FindServiceShape(dataObject.WorkspaceID, dataObject.ResourceID), enDev2ColumnArgumentDirection.Input);
                    var inputs = GetDebugValues(defs, com, out invokeErrors);
                    errors.MergeErrors(invokeErrors);
                    debugState.Inputs.AddRange(inputs);
                }
                if (interrogateOutputs)
                {
                    ErrorResultTO invokeErrors;
                    var           com = compiler.FetchBinaryDataList(dataObject.DataListID, out invokeErrors);
                    errors.MergeErrors(invokeErrors);
                    var defs   = compiler.GenerateDefsFromDataListForDebug(FindServiceShape(dataObject.WorkspaceID, dataObject.ResourceID), enDev2ColumnArgumentDirection.Output);
                    var inputs = GetDebugValues(defs, com, out invokeErrors);
                    errors.MergeErrors(invokeErrors);
                    debugState.Outputs.AddRange(inputs);
                }
                if (stateType == StateType.End)
                {
                    debugState.NumberOfSteps = dataObject.NumberOfSteps;
                }

                if (stateType == StateType.Start)
                {
                    debugState.ExecutionOrigin            = dataObject.ExecutionOrigin;
                    debugState.ExecutionOriginDescription = dataObject.ExecutionOriginDescription;
                }

                if (dataObject.IsDebugMode() || (dataObject.RunWorkflowAsync && !dataObject.IsFromWebServer))
                {
                    var debugDispatcher = GetDebugDispatcher();
                    if (debugState.StateType == StateType.End)
                    {
                        while (!debugDispatcher.IsQueueEmpty)
                        {
                            Thread.Sleep(100);
                        }
                        debugDispatcher.Write(debugState, dataObject.RemoteInvoke, dataObject.RemoteInvokerID, dataObject.ParentInstanceID, dataObject.RemoteDebugItems);
                    }
                    else
                    {
                        debugDispatcher.Write(debugState);
                    }
                }
            }
        }
Example #20
0
 public DebugStateChangedEventArgs(DebugState newState, LuaState ls)
 {
     this.State    = newState;
     this.LuaState = ls;
 }
        private void Debugger_DebugStateChanged(DebugState newState)
        {
            if (_guiController.InvokeRequired)
            {
                _guiController.Invoke(new DebugController.DebugStateChangedHandler(Debugger_DebugStateChanged), newState);
                return;
            }

            _debuggerState = newState;

            if (newState == DebugState.Running)
            {
                _guiController.SetTitleBarPrefix("[Debugging] ");
            }
            else if (newState == DebugState.Paused)
            {
                _guiController.SetTitleBarPrefix("[Break] ");
            }
            else
            {
                _guiController.SetTitleBarPrefix(string.Empty);
                _guiController.HideCallStack();
                _guiController.HideFindSymbolResults();
            }

            foreach (MenuCommand command in _debugToolbarCommands)
            {
                if (command.ID == STOP_COMMAND)
                {
                    command.Enabled = (newState != DebugState.NotRunning);
                    _guiController.SetMenuItemEnabled(this, STOP_COMMAND, command.Enabled);
                }
                else if (command.ID == PAUSE_COMMAND)
                {
                    command.Enabled = (newState == DebugState.Running);
                    _guiController.SetMenuItemEnabled(this, PAUSE_COMMAND, command.Enabled);
                }
                else if (command.ID == STEP_INTO_COMMAND)
                {
                    command.Enabled = (newState == DebugState.Paused);
                    _guiController.SetMenuItemEnabled(this, command.ID, command.Enabled);
                }
                else if (command.ID == RUN_COMMAND)
                {
                    command.Enabled = (newState != DebugState.Running);
                    _guiController.SetMenuItemEnabled(this, command.ID, command.Enabled);
                }
            }
            Factory.ToolBarManager.UpdateItemEnabledStates(_debugToolbarCommands);
        }
Example #22
0
        }/* interpret */

        /*
         * call
         *
         * Call a subroutine. Save PC and FP then load new PC and initialise
         * new stack frame. Note that the caller may legally provide less or
         * more arguments than the function actually has. The call type "ct"
         * can be 0 (z_call_s), 1 (z_call_n) or 2 (direct call).
         *
         */

        internal static void call(zword routine, int argc, int args_offset, int ct)
        {
            long  pc;
            zword value;
            zbyte count;
            int   i;

            if (main.sp < 4)//if (sp - stack < 4)
            {
                Err.runtime_error(ErrorCodes.ERR_STK_OVF);
            }

            FastMem.GET_PC(out pc);

            main.stack[--main.sp] = (zword)(pc >> 9);
            main.stack[--main.sp] = (zword)(pc & 0x1ff);
            main.stack[--main.sp] = (zword)(main.fp - 1); // *--sp = (zword) (fp - stack - 1);
            main.stack[--main.sp] = (zword)(argc | (ct << (main.option_save_quetzal == true ? 12 : 8)));

            main.fp = main.sp;
            main.frame_count++;

            DebugState.Output("Added Frame: {0} -> {1}:{2}:{3}:{4}",
                              main.frame_count,
                              main.stack[main.sp + 0],
                              main.stack[main.sp + 1],
                              main.stack[main.sp + 2],
                              main.stack[main.sp + 3]);

            /* Calculate byte address of routine */

            if (main.h_version <= ZMachine.V3)
            {
                pc = (long)routine << 1;
            }
            else if (main.h_version <= ZMachine.V5)
            {
                pc = (long)routine << 2;
            }
            else if (main.h_version <= ZMachine.V7)
            {
                pc = ((long)routine << 2) + ((long)main.h_functions_offset << 3);
            }
            else /* (h_version <= V8) */
            {
                pc = (long)routine << 3;
            }

            if (pc >= main.story_size)
            {
                Err.runtime_error(ErrorCodes.ERR_ILL_CALL_ADDR);
            }

            FastMem.SET_PC(pc);

            /* Initialise local variables */

            FastMem.CODE_BYTE(out count);

            if (count > 15)
            {
                Err.runtime_error(ErrorCodes.ERR_CALL_NON_RTN);
            }
            if (main.sp < count)
            {
                Err.runtime_error(ErrorCodes.ERR_STK_OVF);
            }

            if (main.option_save_quetzal == true)
            {
                main.stack[main.fp] |= (zword)(count << 8);     /* Save local var count for Quetzal. */
            }
            value = 0;

            for (i = 0; i < count; i++)
            {
                if (main.h_version <= ZMachine.V4)              /* V1 to V4 games provide default */
                {
                    FastMem.CODE_WORD(out value);               /* values for all local variables */
                }
                main.stack[--main.sp] = (zword)((argc-- > 0) ? zargs[args_offset + i] : value);
                //*--sp = (zword) ((argc-- > 0) ? args[i] : value);
            }

            /* Start main loop for direct calls */

            if (ct == 2)
            {
                interpret();
            }
        }/* call */
Example #23
0
        private void RefreshLog(bool scrollToBottom, bool forceUpdate)
        {
            if (_refreshRunning)
            {
                return;
            }

            _refreshRunning = true;
            SetOptions();
            Task.Run(() => {
                //Update trace log in another thread for performance
                DebugState state = DebugApi.GetState();
                if (_previousMasterClock != state.MasterClock || forceUpdate)
                {
                    string newTrace      = DebugApi.GetExecutionTrace((UInt32)_lineCount);
                    _previousMasterClock = state.Cpu.CycleCount;
                    _previousTrace       = newTrace;

                    int index            = 0;
                    string line          = null;
                    Func <bool> readLine = () => {
                        if (index < newTrace.Length)
                        {
                            int endOfLineIndex = newTrace.IndexOf('\n', index);
                            line  = newTrace.Substring(index, endOfLineIndex - index);
                            index = endOfLineIndex + 1;
                            return(true);
                        }
                        else
                        {
                            return(false);
                        }
                    };

                    List <int> lineFlags      = new List <int>(30000);
                    List <int> programCounter = new List <int>(30000);
                    List <string> byteCode    = new List <string>(30000);
                    List <string> lineContent = new List <string>(30000);
                    List <int> indent         = new List <int>(30000);

                    bool showByteCode = false;
                    while (readLine())
                    {
                        string[] parts = line.Split('\x1');
                        lineFlags.Add((int)parts[0][0]);
                        programCounter.Add(Int32.Parse(parts[1], System.Globalization.NumberStyles.HexNumber));
                        byteCode.Add(parts[2]);

                        string content = parts[3];
                        while (true)
                        {
                            string str = content.TrimStart();
                            if (str.StartsWith(parts[1]))
                            {
                                content = str.Substring(parts[1].Length);
                            }
                            else if (str.StartsWith(parts[2]))
                            {
                                content      = str.Substring(parts[2].Length);
                                showByteCode = true;
                            }
                            else if (str.StartsWith(parts[3].Replace("$", "")))
                            {
                                content      = str.Substring(8);
                                showByteCode = true;
                            }
                            else
                            {
                                break;
                            }
                        }
                        lineContent.Add(content.TrimStart());
                    }
                    this.BeginInvoke((Action)(() => {
                        txtTraceLog.ShowContentNotes = showByteCode;
                        txtTraceLog.ShowSingleContentLineNotes = showByteCode;

                        txtTraceLog.DataProvider = new TraceLoggerCodeDataProvider(lineContent, programCounter, byteCode, lineFlags);
                        txtTraceLog.StyleProvider = new TraceLoggerStyleProvider(lineFlags);

                        if (scrollToBottom)
                        {
                            txtTraceLog.ScrollToLineIndex(txtTraceLog.LineCount - 1);
                        }
                    }));
                }
                _refreshRunning = false;
            });
        }
Example #24
0
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);

            _minimumSize = this.MinimumSize;

            if (Program.IsMono)
            {
                //This doesn't work in Mono (menu is blank) - hide it for now
                mnuCode.Visible = false;
            }

            bool debuggerAlreadyRunning = InteropEmu.DebugIsDebuggerRunning();

            ctrlConsoleStatus.OnStateChanged     += ctrlConsoleStatus_OnStateChanged;
            LabelManager.OnLabelUpdated          += LabelManager_OnLabelUpdated;
            BreakpointManager.BreakpointsChanged += BreakpointManager_BreakpointsChanged;
            ctrlProfiler.OnFunctionSelected      += ctrlProfiler_OnFunctionSelected;

            this.UpdateWorkspace();
            this.AutoLoadCdlFiles();
            this.AutoLoadDbgFiles(true);

            this.mnuSplitView.Checked                 = ConfigManager.Config.DebugInfo.SplitView;
            this.mnuPpuPartialDraw.Checked            = ConfigManager.Config.DebugInfo.PpuPartialDraw;
            this.mnuShowEffectiveAddresses.Checked    = ConfigManager.Config.DebugInfo.ShowEffectiveAddresses;
            this.mnuShowCodePreview.Checked           = ConfigManager.Config.DebugInfo.ShowCodePreview;
            this.mnuShowCpuMemoryMapping.Checked      = ConfigManager.Config.DebugInfo.ShowCpuMemoryMapping;
            this.mnuShowPpuMemoryMapping.Checked      = ConfigManager.Config.DebugInfo.ShowPpuMemoryMapping;
            this.mnuAutoLoadDbgFiles.Checked          = ConfigManager.Config.DebugInfo.AutoLoadDbgFiles;
            this.mnuAutoLoadCdlFiles.Checked          = ConfigManager.Config.DebugInfo.AutoLoadCdlFiles;
            this.mnuBreakOnReset.Checked              = ConfigManager.Config.DebugInfo.BreakOnReset;
            this.mnuBreakOnOpen.Checked               = ConfigManager.Config.DebugInfo.BreakOnOpen;
            this.mnuBreakOnUnofficialOpcodes.Checked  = ConfigManager.Config.DebugInfo.BreakOnUnofficialOpcodes;
            this.mnuBreakOnBrk.Checked                = ConfigManager.Config.DebugInfo.BreakOnBrk;
            this.mnuBreakOnDebuggerFocus.Checked      = ConfigManager.Config.DebugInfo.BreakOnDebuggerFocus;
            this.mnuDisplayOpCodesInLowerCase.Checked = ConfigManager.Config.DebugInfo.DisplayOpCodesInLowerCase;

            this.mnuDisassembleVerifiedData.Checked     = ConfigManager.Config.DebugInfo.DisassembleVerifiedData;
            this.mnuDisassembleUnidentifiedData.Checked = ConfigManager.Config.DebugInfo.DisassembleUnidentifiedData;

            this.mnuShowVerifiedData.Checked     = ConfigManager.Config.DebugInfo.ShowVerifiedData;
            this.mnuShowUnidentifiedData.Checked = ConfigManager.Config.DebugInfo.ShowUnidentifiedData;

            this.mnuRefreshWatchWhileRunning.Checked = ConfigManager.Config.DebugInfo.RefreshWatchWhileRunning;

            if (ConfigManager.Config.DebugInfo.WindowWidth > -1)
            {
                this.Width  = ConfigManager.Config.DebugInfo.WindowWidth;
                this.Height = ConfigManager.Config.DebugInfo.WindowHeight;
            }

            ctrlCpuMemoryMapping.Visible = mnuShowCpuMemoryMapping.Checked;
            ctrlPpuMemoryMapping.Visible = mnuShowPpuMemoryMapping.Checked;

            if (ConfigManager.Config.DebugInfo.LeftPanelWidth > 0)
            {
                this.ctrlSplitContainerTop.SplitterDistance = ConfigManager.Config.DebugInfo.LeftPanelWidth;
            }
            if (ConfigManager.Config.DebugInfo.TopPanelHeight > 0)
            {
                this.splitContainer.SplitterDistance = ConfigManager.Config.DebugInfo.TopPanelHeight;
            }

            if (!ConfigManager.Config.DebugInfo.ShowRightPanel)
            {
                ctrlSplitContainerTop.CollapsePanel();
            }
            else
            {
                mnuShowFunctionLabelLists.Checked = true;
            }

            if (!ConfigManager.Config.DebugInfo.ShowBottomPanel)
            {
                splitContainer.CollapsePanel();
            }
            else
            {
                mnuShowBottomPanel.Checked = true;
            }

            _lastCodeWindow = ctrlDebuggerCode;

            this.ctrlDebuggerCode.SetConfig(ConfigManager.Config.DebugInfo.LeftView);
            this.ctrlDebuggerCodeSplit.SetConfig(ConfigManager.Config.DebugInfo.RightView);

            this.toolTip.SetToolTip(this.picWatchHelp, frmBreakpoint.GetConditionTooltip(true));

            _notifListener = new InteropEmu.NotificationListener();
            _notifListener.OnNotification += _notifListener_OnNotification;

            InteropEmu.DebugInitialize();

            _debuggerInitialized = true;

            DebugState state = new DebugState();

            InteropEmu.DebugGetState(ref state);
            _previousCycle = state.CPU.CycleCount;

            //Pause a few frames later to give the debugger a chance to disassemble some code
            _firstBreak = true;
            if (!debuggerAlreadyRunning)
            {
                InteropEmu.SetFlag(EmulationFlags.ForceMaxSpeed, true);
                InteropEmu.DebugStep(5000);
            }
            else
            {
                //Break once to show code and then resume execution
                InteropEmu.DebugStep(1);
            }
            InteropEmu.SetFlag(EmulationFlags.Paused, false);

            UpdateDebuggerFlags();
            UpdateCdlRatios();
            tmrCdlRatios.Start();
        }
Example #25
0
        private double GetGlareShieldSkewAngle(Rectangle focusRect, IndicatorData data, DebugState debugState)
        {
            var topDotRect    = new Rectangle(focusRect.Left - 160, focusRect.Top - 5, 40, 40);
            var bottomDotRect = new Rectangle(focusRect.Left - 170, focusRect.Bottom - 40, 60, 40);

            var topPointBlobs    = GetDotLocationFromFullFrame(data.Frame, focusRect, topDotRect, isTop: true);
            var bottomPointBlobs = GetDotLocationFromFullFrame(data.Frame, focusRect, bottomDotRect, isTop: false);

            double a = double.NaN;

            if (topPointBlobs.Count > 0 && bottomPointBlobs.Count > 0)
            {
                var topPoint    = topPointBlobs.First().Centroid.Add(topDotRect.Location);
                var bottomPoint = bottomPointBlobs.First().Centroid.Add(bottomDotRect.Location);

                a = Math2.GetPolarHeadingFromLine(topPoint, bottomPoint);
                if (a > 180)
                {
                    a  = 360 - a;
                    a *= -1;
                }

                var lineRect = new Rectangle(focusRect.Left - 200, focusRect.Top - 50, 170, focusRect.Bottom + 50 - focusRect.Top);
                var lineImg  = data.Frame.Copy(lineRect);

                var topInLineImg    = new PointF(topPoint.X - lineRect.Location.X, topPoint.Y - lineRect.Location.Y);
                var bottomInLineImg = new PointF(bottomPoint.X - lineRect.Location.X, bottomPoint.Y - lineRect.Location.Y);

                var topRange = lineImg.Convert <Hsv, byte>(); //.InRange(new Hsv(HLow, SLow, VLow), new Hsv(HHigh, SHigh, VHigh));
                CvInvoke.Line(lineImg, topInLineImg.ToPoint(), bottomInLineImg.ToPoint(), new Bgr(Color.Yellow).MCvScalar, 1);
                debugState.Add(lineImg);
                debugState.Add(topRange);

                var dist = Math2.GetDistance(topPoint, bottomPoint);
                if (Math.Abs(a) > 8 || dist < 110 || dist > 120)
                {
                    var biasFrame = Timeline.LatestFrame(f => f.Heading.ForIndicatorUse == null ? double.NaN : ((ExtendedData)f.Heading.ForIndicatorUse).Bias, data.Id);
                    if (biasFrame != null)
                    {
                        a = ((ExtendedData)biasFrame.Heading.ForIndicatorUse).Bias;
                    }
                    else
                    {
                        debugState.SetError("Rejected due to dots angle out of bounds " + a);
                        return(double.NaN);
                    }
                }
            }
            else
            {
                var biasFrame = Timeline.LatestFrame(f => f.Heading.ForIndicatorUse == null ? double.NaN : ((ExtendedData)f.Heading.ForIndicatorUse).Bias, data.Id);
                if (biasFrame != null)
                {
                    a = ((ExtendedData)biasFrame.Heading.ForIndicatorUse).Bias;
                }
                else
                {
                    debugState.SetError("Rejected due to dots angle out of bounds " + a);
                    return(double.NaN);
                }
            }

            ((ExtendedData)Timeline.Data[data.Id].Heading.ForIndicatorUse).Bias = a;
            return(a / 2);
        }
Example #26
0
        public void UpdateDebugger(bool updateActiveAddress = true, bool bringToFront = true)
        {
            if (!_debuggerInitialized)
            {
                return;
            }

            ctrlBreakpoints.RefreshListAddresses();
            ctrlLabelList.UpdateLabelListAddresses();
            ctrlFunctionList.UpdateFunctionList(false);
            UpdateDebuggerFlags();
            UpdateVectorAddresses();

            string newCode = InteropEmu.DebugGetCode(_firstBreak);

            if (newCode != null)
            {
                ctrlDebuggerCode.Code = newCode;
            }

            DebugState state = new DebugState();

            InteropEmu.DebugGetState(ref state);

            lblCyclesElapsedCount.Text = (state.CPU.CycleCount - _previousCycle).ToString();
            _previousCycle             = state.CPU.CycleCount;

            if (UpdateSplitView())
            {
                if (newCode != null || ctrlDebuggerCodeSplit.Code == null)
                {
                    ctrlDebuggerCodeSplit.Code = ctrlDebuggerCode.Code;
                }
                ctrlDebuggerCodeSplit.UpdateCode(true);
            }
            else
            {
                _lastCodeWindow = ctrlDebuggerCode;
            }

            ctrlDebuggerCode.SetActiveAddress(state.CPU.DebugPC);
            ctrlDebuggerCodeSplit.SetActiveAddress(state.CPU.DebugPC);

            if (updateActiveAddress)
            {
                _lastCodeWindow.SelectActiveAddress(state.CPU.DebugPC);
            }

            UpdateLineColors();

            ctrlConsoleStatus.UpdateStatus(ref state);
            ctrlWatch.UpdateWatch();
            ctrlCallstack.UpdateCallstack();

            ctrlCpuMemoryMapping.UpdateCpuRegions(state.Cartridge);
            ctrlPpuMemoryMapping.UpdatePpuRegions(state.Cartridge);

            if (bringToFront)
            {
                this.BringToFront();
            }

            if (_firstBreak)
            {
                InteropEmu.SetFlag(EmulationFlags.ForceMaxSpeed, false);
                if (!ConfigManager.Config.DebugInfo.BreakOnOpen)
                {
                    ResumeExecution();
                }
                _firstBreak = false;
            }
        }
Example #27
0
        double ComputeHeadingFromPacks(int frameId, IEnumerable <BlobPack> packs, Image <Bgr, Byte> compass_frame, DebugState debugState)
        {
            var frame       = Timeline.Data[frameId];
            var my_extended = new ExtendedData();

            frame.Heading.ForIndicatorUse = my_extended;

            var    choices      = new List <Tuple <double, double, string, Image <Gray, byte> > >();
            double unused_angle = 0;

            var p = packs.OrderByDescending(px => px.BlobRationAngle);

            foreach (var pack in packs)
            {
                var b = pack.BlobBox;
                b.Inflate(2, 2);

                var small_angle = pack.BlobRationAngle;
                var str         = ResolveTextFromPreviousFrame(frameId, small_angle);

                if (string.IsNullOrWhiteSpace(str))
                {
                    str = GetText(pack.BlobImage, debugState);
                }

                if (str == "N" || str == "E" || str == "S" || str == "W")
                {
                    small_angle = 360 - Math.Abs(small_angle);
                    double new_heading = 0;
                    switch (str)
                    {
                    case "N":
                        my_extended.LastN = pack.BlobRationAngle;
                        new_heading       = small_angle;
                        CvInvoke.Rectangle(compass_frame, b, new Bgr(Color.Blue).MCvScalar, 1);
                        break;

                    case "E":
                        my_extended.LastE = pack.BlobRationAngle;
                        new_heading       = (small_angle + 90);
                        CvInvoke.Rectangle(compass_frame, b, new Bgr(Color.Yellow).MCvScalar, 1);
                        break;

                    case "S":
                        my_extended.LastS = pack.BlobRationAngle;
                        new_heading       = (small_angle + 180);
                        CvInvoke.Rectangle(compass_frame, b, new Bgr(Color.Red).MCvScalar, 1);
                        break;

                    case "W":
                        my_extended.LastW = pack.BlobRationAngle;
                        new_heading       = (small_angle + 270);
                        CvInvoke.Rectangle(compass_frame, b, new Bgr(Color.Lime).MCvScalar, 1);
                        break;
                    }

                    new_heading = Math2.ClampAngle(new_heading);
                    choices.Add(new Tuple <double, double, string, Image <Gray, byte> >(new_heading, small_angle, str, pack.BlobImage));
                }
                else
                {
                    unused_angle = pack.BlobRationAngle;
                }
            }

            // Fill in exactly one missing quadrant.
            if (choices.Count == 3 && packs.Count() == 4)
            {
                var letters = new List <string>()
                {
                    "N", "E", "S", "W"
                };
                foreach (var c in choices)
                {
                    letters.Remove(c.Item3);
                }

                var o_angle = unused_angle;
                unused_angle = 360 - Math.Abs(unused_angle);

                double new_heading = 0;
                var    str         = letters.First();
                switch (str)
                {
                case "N":
                    my_extended.LastN = o_angle;
                    new_heading       = unused_angle;
                    break;

                case "E":
                    my_extended.LastE = o_angle;
                    new_heading       = (unused_angle + 90);
                    break;

                case "S":
                    my_extended.LastS = o_angle;
                    new_heading       = (unused_angle + 180);
                    break;

                case "W":
                    my_extended.LastW = o_angle;
                    new_heading       = (unused_angle + 270);
                    break;
                }

                new_heading = Math2.ClampAngle(new_heading);
                choices.Add(new Tuple <double, double, string, Image <Gray, byte> >(new_heading, (int)unused_angle, str, null));
            }

            if (choices.Count == 4)
            {
                // Exclude invalid combinations
                if (choices.Where(ct => ct.Item3 == "N").Count() > 1)
                {
                    debugState.SetError("Bad N");
                    return(double.NaN);
                }
                if (choices.Where(ct => ct.Item3 == "E").Count() > 1)
                {
                    debugState.SetError("Bad E");
                    return(double.NaN);
                }
                if (choices.Where(ct => ct.Item3 == "S").Count() > 1)
                {
                    debugState.SetError("Bad S");
                    return(double.NaN);
                }
                if (choices.Where(ct => ct.Item3 == "W").Count() > 1)
                {
                    debugState.SetError("Bad W");
                    return(double.NaN);
                }

                var p1 = Math2.AddAngles(choices[0].Item1, choices[1].Item1);
                var p2 = Math2.AddAngles(choices[2].Item1, choices[3].Item1);
                return(Math2.AddAngles(p1, p2));
            }
            else
            {
                debugState.SetError($"Bad choices {choices.Count}");
            }
            return(double.NaN);
        }
Example #28
0
        public void ApplyChanges()
        {
            if (this._dirty)
            {
                _cpuBinder.UpdateObject();
                _ppuControlBinder.UpdateObject();
                _ppuStatusBinder.UpdateObject();

                DebugState state = _lastState;
                state.CPU = (CPUState)_cpuBinder.Entity;

                if (chkExternal.Checked)
                {
                    state.CPU.IRQFlag |= IRQSource.External;
                }
                if (chkFrameCounter.Checked)
                {
                    state.CPU.IRQFlag |= IRQSource.FrameCounter;
                }
                if (chkDMC.Checked)
                {
                    state.CPU.IRQFlag |= IRQSource.DMC;
                }

                state.PPU.ControlFlags = (PPUControlFlags)_ppuControlBinder.Entity;
                state.PPU.StatusFlags  = (PPUStatusFlags)_ppuStatusBinder.Entity;

                state.PPU.State.Mask    = state.PPU.ControlFlags.GetMask();
                state.PPU.State.Control = state.PPU.ControlFlags.GetControl();
                state.PPU.State.Status  = state.PPU.StatusFlags.GetStatus();

                UInt32 cycle = 0;
                UInt32.TryParse(txtCycle.Text, out cycle);
                state.PPU.Cycle = cycle;

                Int32 scanline = 0;
                Int32.TryParse(txtScanline.Text, out scanline);
                state.PPU.Scanline = scanline;

                UInt32 frameCount = 0;
                UInt32.TryParse(txtFrameCount.Text, out frameCount);
                state.PPU.FrameCount = frameCount;

                Int32 xScroll = 0;
                Int32.TryParse(txtXScroll.Text, out xScroll);
                state.PPU.State.XScroll = (byte)Math.Max(0, Math.Min(xScroll, 7));

                UInt16 vramAddr = 0;
                UInt16.TryParse(txtVRAMAddr.Text, System.Globalization.NumberStyles.HexNumber, null, out vramAddr);
                state.PPU.State.VideoRamAddr = vramAddr;

                UInt16 tmpVramAddr = 0;
                UInt16.TryParse(txtTmpAddr.Text, System.Globalization.NumberStyles.HexNumber, null, out tmpVramAddr);
                state.PPU.State.TmpVideoRamAddr = tmpVramAddr;

                state.PPU.State.WriteToggle = chkWriteToggle.Checked;

                InteropEmu.DebugSetState(state);
                _lastState      = state;
                _dirty          = false;
                btnUndo.Enabled = false;
                OnStateChanged?.Invoke(null, null);
            }
        }
        /// <summary>
        /// Dispatches the error state to the client
        /// </summary>
        /// <param name="xmlRequest">The XML request.</param>
        /// <param name="dataListId">The data list id.</param>
        /// <param name="allErrors">All errors.</param>
        /// <author>Jurie.smit</author>
        /// <date>2013/02/18</date>
        private void DispatchDebugState(dynamic xmlRequest, Guid dataListId, ErrorResultTO allErrors)
        {
            var debugState = new DebugState()
            {
                StartTime = DateTime.Now,
                EndTime = DateTime.Now,
                IsSimulation = false,
                Server = string.Empty,
                Version = string.Empty,
                Name = GetType().Name,
                HasError = true,
                ActivityType = ActivityType.Service,
                StateType = StateType.All,
                ServerID = HostSecurityProvider.Instance.ServerID
            };

            try
            {
                var xmlReader = XmlReader.Create(new StringReader(xmlRequest.XmlString));
                var xmlDoc = XDocument.Load(xmlReader);
                var workSpaceID = (from n in xmlDoc.Descendants("wid")
                                   select n).FirstOrDefault();
                var invokedService = (from n in xmlDoc.Descendants("Service")
                                      select n).FirstOrDefault();
                if (workSpaceID != null)
                {
                    debugState.WorkspaceID = Guid.Parse(workSpaceID.Value);
                }
                if (invokedService != null)
                {
                    debugState.DisplayName = invokedService.Value;
                }

                //ParentID = dataObject.ParentInstanceID
            }
            catch (Exception exception)
            {
                //TODO what if not an xmlRequest ? IDSFDataObject dataObject = new DsfDataObject(xmlRequest, dataListId);
                throw;
            }

            debugState.ErrorMessage = XmlHelper.MakeErrorsUserReadable(allErrors.MakeDisplayReady());

            DebugDispatcher.Instance.Write(debugState);
        }
Example #30
0
        public void Prepare(long firstByteIndex, long lastByteIndex)
        {
            int visibleByteCount = (int)(lastByteIndex - firstByteIndex + 1);

            if (_highlightBreakpoints)
            {
                Breakpoint[] breakpoints = BreakpointManager.Breakpoints.ToArray();
                _breakpointTypes = new BreakpointTypeFlags[visibleByteCount];

                for (int i = 0; i < visibleByteCount; i++)
                {
                    int byteIndex = i + (int)firstByteIndex;
                    foreach (Breakpoint bp in breakpoints)
                    {
                        if (bp.Enabled && bp.Matches((uint)byteIndex, _memoryType))
                        {
                            _breakpointTypes[i] = bp.BreakOnExec ? BreakpointTypeFlags.Execute : (bp.BreakOnWrite ? BreakpointTypeFlags.Write : BreakpointTypeFlags.Read);
                            break;
                        }
                    }
                }
            }
            else
            {
                _breakpointTypes = null;
            }

            _readStamps  = DebugApi.GetMemoryAccessStamps((UInt32)firstByteIndex, (UInt32)visibleByteCount, _memoryType, MemoryOperationType.Read);
            _writeStamps = DebugApi.GetMemoryAccessStamps((UInt32)firstByteIndex, (UInt32)visibleByteCount, _memoryType, MemoryOperationType.Write);
            _execStamps  = DebugApi.GetMemoryAccessStamps((UInt32)firstByteIndex, (UInt32)visibleByteCount, _memoryType, MemoryOperationType.ExecOpCode);

            _readCounts  = DebugApi.GetMemoryAccessCounts((UInt32)firstByteIndex, (UInt32)visibleByteCount, _memoryType, MemoryOperationType.Read);
            _writeCounts = DebugApi.GetMemoryAccessCounts((UInt32)firstByteIndex, (UInt32)visibleByteCount, _memoryType, MemoryOperationType.Write);
            _execCounts  = DebugApi.GetMemoryAccessCounts((UInt32)firstByteIndex, (UInt32)visibleByteCount, _memoryType, MemoryOperationType.ExecOpCode);

            _cdlData = null;
            if (_highlightDataBytes || _highlightCodeBytes)
            {
                switch (_memoryType)
                {
                case SnesMemoryType.CpuMemory:
                case SnesMemoryType.PrgRom:
                    _cdlData = DebugApi.GetCdlData((UInt32)firstByteIndex, (UInt32)visibleByteCount, _memoryType);
                    break;
                }
            }

            //TODO LABELS

            /*_hasLabel = new bool[visibleByteCount];
             * if(_highlightLabelledBytes) {
             *      if(_memoryType == DebugMemoryType.CpuMemory) {
             *              for(long i = 0; i < _hasLabel.Length; i++) {
             *                      _hasLabel[i] = (
             *                              !string.IsNullOrWhiteSpace(LabelManager.GetLabel((UInt16)(i + firstByteIndex))?.Label) ||
             *                              !string.IsNullOrWhiteSpace(LabelManager.GetLabel((uint)(i + firstByteIndex), AddressType.Register)?.Label)
             *                      );
             *              }
             *      } else if(_memoryType == DebugMemoryType.PrgRom || _memoryType == DebugMemoryType.WorkRam || _memoryType == DebugMemoryType.SaveRam) {
             *              for(long i = 0; i < _hasLabel.Length; i++) {
             *                      _hasLabel[i] = !string.IsNullOrWhiteSpace(LabelManager.GetLabel((uint)(firstByteIndex + i), _memoryType.ToAddressType())?.Label);
             *              }
             *      }
             * }*/

            _state = DebugApi.GetState();
        }
Example #31
0
        public void Activity(float dt, BoardController boardController)
        {
            if (mTime >= 1.0f)
            {
                mTime = 0;

                mState = (DebugState) (((int) mState + 1) % 7);

                switch (mState)
                {
                    case DebugState.Idle:
                        Parent.AnimController.PlayAnimation(RoadAnimationNames.kIdle, MirrorMode.None);
                        break;
                    case DebugState.Walk_Left:
                        Parent.AnimController.PlayAnimation(RoadAnimationNames.kWalkRight, MirrorMode.None);
                        break;
                    case DebugState.Walk_Right:
                        Parent.AnimController.PlayAnimation(RoadAnimationNames.kWalkRight, MirrorMode.Horizontal);
                        break;
                    case DebugState.Run_Left:
                        Parent.AnimController.PlayAnimation(RoadAnimationNames.kRunRight, MirrorMode.None);
                        break;
                    case DebugState.Run_Right:
                        Parent.AnimController.PlayAnimation(RoadAnimationNames.kRunRight, MirrorMode.Horizontal);
                        break;
                    case DebugState.Run_Forward:
                        Parent.AnimController.PlayAnimation(RoadAnimationNames.kRunForward, MirrorMode.None);
                        break;
                    case DebugState.Run_Back:
                        Parent.AnimController.PlayAnimation(RoadAnimationNames.kRunBack, MirrorMode.None);
                        break;

                }

            }
            else
            {
                 mTime += dt;
            }

        }
#pragma warning disable S2360 // Optional parameters should not be used, unless they are only used in the same assembly
        internal DebugState GetDebugState(IDSFDataObject dataObject, StateType stateType, ErrorResultTO errors, bool interrogateInputs = false, bool interrogateOutputs = false, bool durationVisible = false)
#pragma warning restore S2360 // Optional parameters should not be used
        {
            var errorMessage = string.Empty;

            if (dataObject.Environment.HasErrors())
            {
                errorMessage = dataObject.Environment.FetchErrors();
            }

            var server    = "localhost";
            var hasRemote = Guid.TryParse(dataObject.RemoteInvokerID, out var remoteID);

            if (hasRemote)
            {
                var res = _lazyCat.GetResource(GlobalConstants.ServerWorkspaceID, remoteID);
                if (res != null)
                {
                    server = remoteID != Guid.Empty ? _lazyCat.GetResource(GlobalConstants.ServerWorkspaceID, remoteID).ResourceName : "localhost";
                }
            }

            Guid.TryParse(dataObject.ParentInstanceID, out var parentInstanceId);

            var debugState = new DebugState
            {
                ID                    = dataObject.OriginalInstanceID,
                ParentID              = parentInstanceId,
                WorkspaceID           = dataObject.WorkspaceID,
                StateType             = stateType,
                StartTime             = dataObject.StartTime,
                EndTime               = DateTime.Now,
                ActivityType          = ActivityType.Workflow,
                DisplayName           = dataObject.ServiceName,
                IsSimulation          = dataObject.IsOnDemandSimulation,
                ServerID              = dataObject.ServerID,
                OriginatingResourceID = dataObject.ResourceID,
                OriginalInstanceID    = dataObject.OriginalInstanceID,
                Server                = server,
                Version               = string.Empty,
                SessionID             = dataObject.DebugSessionID,
                EnvironmentID         = dataObject.DebugEnvironmentId,
                ClientID              = dataObject.ClientID,
                SourceResourceID      = dataObject.SourceResourceID,
                Name                  = stateType.ToString(),
                HasError              = dataObject.Environment.HasErrors(),
                ErrorMessage          = errorMessage,
                IsDurationVisible     = durationVisible
            };

            if (stateType == StateType.End)
            {
                debugState.NumberOfSteps = dataObject.NumberOfSteps;
            }
            if (stateType == StateType.Start)
            {
                debugState.ExecutionOrigin            = dataObject.ExecutionOrigin;
                debugState.ExecutionOriginDescription = dataObject.ExecutionOriginDescription;
            }

            if (interrogateInputs)
            {
                var defs   = DataListUtil.GenerateDefsFromDataListForDebug(FindServiceShape(dataObject.WorkspaceID, dataObject.ResourceID), enDev2ColumnArgumentDirection.Input);
                var inputs = GetDebugValues(defs, dataObject, out var invokeErrors);
                errors.MergeErrors(invokeErrors);
                debugState.Inputs.AddRange(inputs);
            }
            if (interrogateOutputs)
            {
                var defs    = DataListUtil.GenerateDefsFromDataListForDebug(FindServiceShape(dataObject.WorkspaceID, dataObject.ResourceID), enDev2ColumnArgumentDirection.Output);
                var outputs = GetDebugValues(defs, dataObject, out var invokeErrors);
                errors.MergeErrors(invokeErrors);
                debugState.Outputs.AddRange(outputs);
            }

            return(debugState);
        }
Example #33
0
 /// <summary>
 /// 开启调试等待计时器
 /// </summary>
 /// <param name="interval">计时器间隔</param>
 /// <param name="debugState">调试状态</param>
 private void StartDebugWaitTimer(int interval, DebugState debugState)
 {
     this.debugState = debugState;
     debugWaitTimer.Interval = interval;
     debugWaitTimer.Start();
 }
Example #34
0
        public double ReadValue(IndicatorData data, DebugState debugState)
        {
            if (TryFindCircleInFullFrame(data, out var circle))
            {
                var focus          = data.Frame.SafeCopy(Math2.CropCircle(circle, 15));
                var vs_blackimg    = focus.Convert <Hsv, byte>().DynLowInRange(dyn_lower, new Hsv(180, 255, 255)).PyrUp().PyrDown();
                var markedup_frame = vs_blackimg.Convert <Bgr, byte>();
                debugState.Add(focus);
                debugState.Add(vs_blackimg);
                debugState.Add(markedup_frame);

                var cannyEdges3 = new Mat();
                CvInvoke.Canny(vs_blackimg, cannyEdges3, 10, 120);
                Mat dialatedCanny = new Mat();
                CvInvoke.Dilate(cannyEdges3, dialatedCanny, null, new Point(-1, -1), 1, BorderType.Default, new Gray(0).MCvScalar);

                Rectangle center = GetCenterBoxFromImage(focus);
                CvInvoke.Rectangle(markedup_frame, center, new Bgr(Color.Red).MCvScalar, 1);

                var lines = CvInvoke.HoughLinesP(dialatedCanny, 1, Math.PI / 45.0, 20, 16, 0).OrderByDescending(l => l.Length);
                foreach (var line in lines)
                {
                    CvInvoke.Line(markedup_frame, line.P1, line.P2, new Bgr(Color.Red).MCvScalar, 1);

                    if (center.Contains(line.P1) || center.Contains(line.P2))
                    {
                        LineSegment2D needleLine;
                        if (center.Contains(line.P1))
                        {
                            needleLine = new LineSegment2D(line.P2, line.P1);
                        }
                        else
                        {
                            needleLine = new LineSegment2D(line.P1, line.P2);
                        }

                        var angle    = Math2.GetPolarHeadingFromLine(needleLine);
                        var hundreds = Math.Round((angle / 360) * 999);

                        CvInvoke.Line(focus, needleLine.P1, needleLine.P2, new Bgr(Color.Yellow).MCvScalar, 2);

                        var candidates = new List <double>();
                        for (var i = 0; i < 9; i++)
                        {
                            candidates.Add(hundreds + (i * 1000));
                        }

                        var ret = candidates.OrderBy(c => Math.Abs(c - Timeline.Altitude)).First();

                        if (!double.IsNaN(Timeline.Altitude))
                        {
                            var delta = Math.Abs(ret - Timeline.Altitude);
                            if (delta > 400)
                            {
                                debugState.SetError($"Bad value {delta} > 400");
                                return(double.NaN);
                            }
                        }
                        else
                        {
                            return(0);
                        }

                        return(ret);
                    }
                }
            }
            return(double.NaN);
        }
Example #35
0
 static IEnumerable<ILRange> GetILRanges(DebugState state)
 {
     foreach (var node in state.Nodes) {
         foreach (var ann in node.Annotations) {
             var list = ann as IList<ILRange>;
             if (list == null)
                 continue;
             foreach (var range in list)
                 yield return range;
         }
     }
 }
Example #36
0
 // Is the debug console active or not?
 public static void ToggleDebugState()
 {
     if (mDebugState == DebugState.ACTIVE)
     {
         mDebugState = DebugState.HIDDEN;
     }
     else if (mDebugState == DebugState.HIDDEN)
     {
         mDebugState = DebugState.ACTIVE;
     }
 }