2 public import static "ecere"
3 public import static "ec"
15 #define GDB_DEBUG_CONSOLE
19 extern char * strrchr(const char * s, int c);
22 #define strlen _strlen
32 #include <sys/time.h> // Required on Apple...
46 sprintf(s[0], "%04d", now.year);
47 sprintf(s[1], "%02d", now.month+1);
48 sprintf(s[2], "%02d", now.day);
49 sprintf(s[3], "%02d", now.hour);
50 sprintf(s[4], "%02d", now.minute);
51 sprintf(s[5], "%02d", now.second);
52 time = PrintString("*", s[0], s[1], s[2], "-", s[3], s[4], s[5], "*");
58 // use =0 to disable printing of specific channels
60 static enum dplchan { none, gdbProtoIgnored=0/*1*/, gdbProtoUnknown=2, gdbOutput=0/*3*/, gdbCommand=0/*4*/, debuggerCall=0/*5*/, debuggerProblem=6,
61 debuggerUserAction=7,debuggerState=8, debuggerBreakpoints=9, debuggerWatches=0/*10*/, debuggerTemp=0 };
63 static enum dplchan { none, gdbProtoIgnored=0, gdbProtoUnknown=0, gdbOutput=0, gdbCommand=0, debuggerCall=0, debuggerProblem=0,
64 debuggerUserAction=0,debuggerState=0, debuggerBreakpoints=0, debuggerWatches=0, debuggerTemp=0 };
66 static char * _dpct[] = {
68 "GDB Protocol Ignored",
69 "GDB Protocol ***Unknown***",
73 "Debugger ***Problem***",
74 "Debugger::ChangeUserAction",
75 "Debugger::ChangeState",
78 "-----> Temporary Message",
82 // TODO if(strlen(item.value) < MAX_F_STRING)
86 #define _dpl2(...) __dpl2(__FILE__, __LINE__, ##__VA_ARGS__)
90 static void __dpl2(char * file, int line, char ** channels, int channel, int indent, typed_object object, ...)
92 bool chan = channel && channels && channels[channel];
95 char string[MAX_F_STRING];
97 char * time = PrintNow();
99 //ide.outputView.debugBox.Logf();
100 Logf("%s %s:% 5d: %s%s", time, file, line, chan ? channels[channel] : "", chan && channels[channel][0] ? ": " : "");
101 va_start(args, object);
102 len = PrintStdArgsToBuffer(string, sizeof(string), object, args);
110 #define _dpl(...) __dpl(__FILE__, __LINE__, ##__VA_ARGS__)
111 static void __dpl(char * file, int line, int indent, char * format, ...)
114 char string[MAX_F_STRING];
116 char * time = PrintNow();
117 //static File f = null;
118 va_start(args, format);
119 vsnprintf(string, sizeof(string), format, args);
120 string[sizeof(string)-1] = 0;
123 char * time = PrintNow();
125 logName = PrintString(time, ".log");
127 f = FileOpen(logName, write);
130 /*f.Printf("%s %s:% 5d: ", time, file, line);
131 for(c = 0; c<indent; c++)
133 f.Printf("%s\n", string);*/
134 Logf("%s %s:% 5d: ", time, file, line);
135 for(c = 0; c<indent; c++)
137 Logf("%s\n", string);
142 public char * StripQuotes2(char * string, char * output)
146 bool quoted = false, escaped = false;
148 for(c = 0; ch = string[c]; c++)
152 if(escaped || ch != '\"')
155 escaped = !escaped && ch == '\\';
169 // String Escape Copy
170 static void strescpy(char * d, char * s)
223 static char * CopyUnescapedSystemPath(char * p)
225 char * d = new char[strlen(p) + 1];
227 #if defined(__WIN32__)
228 ChangeCh(d, '/', '\\');
233 static char * CopyUnescapedUnixPath(char * p)
235 char * d = new char[strlen(p) + 1];
237 #if defined(__WIN32__)
238 ChangeCh(d, '\\', '/');
243 static char * CopyUnescapedString(char * s)
245 char * d = new char[strlen(s) + 1];
250 // String Unescape Copy
252 // TOFIX: THIS DOESN'T HANDLE NUMERIC ESCAPE CODES (OCTAL/HEXADECIMAL...)?
253 // Seems very similar to ReadString in pass15.ec (which also misses numeric escape codes :) )
255 static void struscpy(char * d, char * s)
307 static char * StripBrackets(char * string)
309 int length = strlen(string);
310 if(length > 1 && *string == '[' && string[length - 1] == ']')
313 string[length - 1] = '\0';
320 static char * StripCurlies(char * string)
322 int length = strlen(string);
323 if(length > 1 && *string == '{' && string[length - 1] == '}')
326 string[length - 1] = '\0';
333 static int StringGetInt(char * string, int start)
336 int i, len = strlen(string);
338 for(i = start; i < len && i < start + 8; i++)
340 if(string[i] == '0' || string[i] == '1' || string[i] == '2' || string[i] == '3' || string[i] == '4' || string[i] == '5' || string[i] == '6' || string[i] == '7' || string[i] == '8' || string[i] == '9')
341 strncat(number, &string[i], 1);
348 static int TokenizeList(char * string, const char seperator, Array<char *> tokens)
352 bool quoted = false, escaped = false;
353 char * start = string, ch;
355 for(; (ch = *string); string++)
362 if(escaped || ch != '\"')
363 escaped = !escaped && ch == '\\';
369 else if(ch == '{' || ch == '[' || ch == '(' || ch == '<')
371 else if(ch == '}' || ch == ']' || ch == ')' || ch == '>')
373 else if(ch == seperator && !level)
382 //tokens[count] = start;
383 //tokens[count++] = start;
390 static bool TokenizeListItem(char * string, DebugListItem item)
392 char * equal = strstr(string, "=");
406 static bool CheckCommandAvailable(const char * command)
408 bool available = false;
410 char * name = new char[MAX_FILENAME];
411 char * pathVar = new char[maxPathLen];
413 GetEnvironment("PATH", pathVar, maxPathLen);
414 count = TokenizeWith(pathVar, sizeof(paths) / sizeof(char *), paths, pathListSep, false);
415 strcpy(name, command);
419 const char * extensions[] = { "exe", "com", "bat", null };
420 for(e=0; extensions[e]; e++)
422 ChangeExtension(name, extensions[e], name);
424 for(c=0; c<count; c++)
426 FileListing fl { paths[c] };
429 if(fl.stats.attribs.isFile && !fstrcmp(fl.name, name))
447 // define GdbGetLineSize = 1638400;
448 define GdbGetLineSize = 5638400;
449 #if defined(__unix__)
450 char progFifoPath[MAX_LOCATION];
451 char progFifoDir[MAX_LOCATION];
454 enum DebuggerState { none, prompt, loaded, running, stopped, terminated, error };
457 none, hit, breakEvent, signal, stepEnd, functionEnd, exit, valgrindStartPause;
459 property bool canBeMonitored { get { return (this == hit || this == breakEvent || this == signal || this == stepEnd || this == functionEnd); } };
461 enum DebuggerAction { none, internal, restart, stop, selectFrame }; //, bpValidation
464 unknown, endSteppingRange, functionFinished, signalReceived, breakpointHit
465 //watchpointTrigger, readWatchpointTrigger, accessWatchpointTrigger, watchpointScope, locationReached,
466 //exited, exitedNormally, exitedSignalled;
470 none, internalMain, internalWinMain, internalModulesLoaded, user, runToCursor, internalModuleLoad;
472 property bool isInternal { get { return (this == internalMain || this == internalWinMain || this == internalModulesLoaded || this == internalModuleLoad); } };
473 property bool isUser { get { return (this == user || this == runToCursor); } };
475 enum DebuggerEvaluationError { none, symbolNotFound, memoryCantBeRead, unknown };
476 enum DebuggerUserAction { none, start, resume, _break, stop, restart, selectThread, selectFrame, stepInto, stepOver, stepOut, runToCursor };
478 FileDialog debuggerFileDialog { type = selectDir };
480 static DualPipe vgTargetHandle;
481 static File vgLogFile;
482 static char vgLogPath[MAX_LOCATION];
483 static DualPipe gdbHandle;
484 static DebugEvaluationData eval { };
486 static int targetProcessId;
488 static bool gdbReady;
489 static bool breakpointError;
493 Semaphore serialSemaphore { };
499 bool sentBreakInsert;
500 bool ignoreBreakpoints;
501 bool userBreakOnInternalBreakpoint;
502 //bool runToCursorDebugStart;
511 int activeFrameLevel;
520 DebuggerUserAction userAction;
523 DebuggerAction breakType;
524 //DebuggerCommand lastCommand; // THE COMPILER COMPILES STUFF THAT DOES NOT EXIST???
526 GdbDataStop stopItem;
527 GdbDataBreakpoint bpItem;
530 List<Breakpoint> sysBPs { };
531 Breakpoint bpRunToCursor;
535 CompilerConfig currentCompiler;
536 ProjectConfig prjConfig;
539 CodeEditor codeEditor;
541 ValgrindLogThread vgLogThread { debugger = this };
542 ValgrindTargetThread vgTargetThread { debugger = this };
543 GdbThread gdbThread { debugger = this };
546 delay = 0.0, userData = this;
550 bool monitor = false;
551 DebuggerEvent curEvent = event;
552 GdbDataStop stopItem = this.stopItem;
553 Breakpoint bpUser = null;
554 Breakpoint bpInternal = null;
562 this.stopItem = null;
566 DynamicString bpReport { };
568 for(bp : sysBPs; bp.inserted)
570 bpReport.concatx(",", bp.type, "(", s=bp.CopyLocationString(false), ")");
573 if(bpRunToCursor && bpRunToCursor.inserted)
575 Breakpoint bp = bpRunToCursor;
576 bpReport.concatx(",", bp.type, "(", s=bp.CopyLocationString(false), ")");
579 for(bp : ide.workspace.breakpoints; bp.inserted)
581 bpReport.concatx(",", bp.type, "(", s=bp.CopyLocationString(false), ")");
585 _dpl2(_dpct, dplchan::debuggerBreakpoints, 0, "gdbTimer::DelayExpired: ", s+1);
590 Breakpoint bp = GetBreakpointById(stopItem.bkptno, &isInternal);
592 _dpl2(_dpct, dplchan::debuggerBreakpoints, 0, "gdb stopped by a breakpoint: ", bp.type, "(", s=bp.CopyLocationString(false), ")"); delete s;
600 if(curEvent && curEvent != exit)
602 _dpl(0, "No stop item");
610 Restart(currentCompiler, prjConfig, bitDepth, usingValgrind);
619 GdbCommand(false, "-stack-select-frame %d", activeFrameLevel);
620 for(activeFrame = stackFrames.first; activeFrame; activeFrame = activeFrame.next)
621 if(activeFrame.level == activeFrameLevel)
627 // GdbCommand(false, "-break-info %s", bpItem.number);
637 activeThread = stopItem.threadid;
638 GdbCommand(false, "-thread-list-ids");
644 Breakpoint bp = stopItem ? GetBreakpointById(stopItem.bkptno, &isInternal) : null;
645 if(bp && bp.inserted && bp.bp.addr)
647 if(bp.type.isInternal)
651 if(stopItem && stopItem.frame)
653 if(bpInternal && bpRunToCursor && bpRunToCursor.inserted && !strcmp(bpRunToCursor.bp.addr, bp.bp.addr))
654 bpUser = bpRunToCursor;
657 for(item : (bpInternal ? ide.workspace.breakpoints : sysBPs); item.inserted)
659 if(item.bp && item.bp.addr && !strcmp(item.bp.addr, bp.bp.addr))
671 _dpl2(_dpct, dplchan::debuggerProblem, 0, "Invalid stopItem!");
672 if(bpUser && strcmp(stopItem.frame.addr, bpUser.bp.addr))
676 _dpl2(_dpct, dplchan::debuggerProblem, 0, "Breakpoint bkptno(", stopItem.bkptno, ") invalid or not found!");
677 if(bpUser && bpUser.type == runToCursor)
678 ignoreBreakpoints = false;
679 if((bpUser && !ignoreBreakpoints) || (bpInternal && userBreakOnInternalBreakpoint))
681 hitThread = stopItem.threadid;
685 signalThread = stopItem.threadid;
689 ignoreBreakpoints = false;
691 case valgrindStartPause:
692 GdbExecContinue(true);
701 activeThread = stopItem.threadid;
702 GdbCommand(false, "-thread-list-ids");
704 if(activeFrameLevel > 0)
705 GdbCommand(false, "-stack-select-frame %d", activeFrameLevel);
707 WatchesCodeEditorLinkInit();
711 if(curEvent == signal)
715 ide.outputView.debugBox.Logf($"Signal received: %s - %s\n", stopItem.name, stopItem.meaning);
716 ide.outputView.debugBox.Logf(" %s:%d\n", (s = CopySystemPath(stopItem.frame.file)), stopItem.frame.line);
717 ide.outputView.Show();
718 ide.callStackView.Show();
721 else if(curEvent == breakEvent)
723 ide.threadsView.Show();
724 ide.callStackView.Show();
725 ide.callStackView.Activate();
728 if(monitor && curEvent.canBeMonitored)
730 SelectFrame(activeFrameLevel);
731 GoToStackFrameLine(activeFrameLevel, true, false);
732 ide.ShowCodeEditor();
733 ideMainFrame.Activate(); // TOFIX: ide.Activate() is not reliable (app inactive)
738 BreakpointHit(stopItem, bpInternal, bpUser);
745 if(userBreakOnInternalBreakpoint)
746 userBreakOnInternalBreakpoint = false;
751 #ifdef GDB_DEBUG_CONSOLE
752 char lastGdbOutput[GdbGetLineSize];
754 #if defined(__unix__)
755 ProgramThread progThread { };
759 #define _ChangeUserAction(value) ChangeUserAction(__FILE__, __LINE__, value)
760 void ChangeUserAction(char * file, int line, DebuggerUserAction value)
762 bool same = value == userAction;
763 __dpl2(file, line, _dpct, dplchan::debuggerUserAction, 0, userAction, /*same ? " *** == *** " : */" -> ", value);
767 #define _ChangeUserAction(value) userAction = value
771 #define _ChangeState(value) ChangeState(__FILE__, __LINE__, value)
772 void ChangeState(char * file, int line, DebuggerState value)
774 #define _ChangeState(value) ChangeState(value)
775 void ChangeState(DebuggerState value)
778 bool same = value == state;
780 __dpl2(file, line, _dpct, dplchan::debuggerState, 0, state, same ? " *** == *** " : " -> ", value);
783 if(!same && ide) ide.AdjustDebugMenus();
788 _dpl2(_dpct, dplchan::debuggerCall, 0, "Debugger::CleanUp");
790 stackFrames.Free(Frame::Free);
800 waitingForPID = false;
805 sentBreakInsert = false;
806 ignoreBreakpoints = false;
807 userBreakOnInternalBreakpoint = false;
808 //runToCursorDebugStart = false;
811 activeFrameLevel = 0;
828 bpRunToCursor = null;
830 delete currentCompiler;
834 /*GdbThread gdbThread
840 _dpl2(_dpct, dplchan::debuggerCall, 0, "Debugger::constructor");
841 ideProcessId = Process_GetCurrentProcessId();
843 sysBPs.Add(Breakpoint { type = internalMain, function = "main", enabled = true, level = -1 });
844 #if defined(__WIN32__)
845 sysBPs.Add(Breakpoint { type = internalWinMain, function = "WinMain", enabled = true, level = -1 });
847 sysBPs.Add(Breakpoint { type = internalModulesLoaded, enabled = true, level = -1 });
848 sysBPs.Add(Breakpoint { type = internalModuleLoad, function = "InternalModuleLoadBreakpoint", enabled = true, level = -1 });
853 _dpl2(_dpct, dplchan::debuggerCall, 0, "Debugger::destructor");
861 property bool isActive { get { return state == running || state == stopped; } }
862 property bool isPrepared { get { return state == loaded || state == running || state == stopped; } }
866 _dpl2(_dpct, dplchan::debuggerCall, 0, "Debugger::Resume");
867 _ChangeUserAction(resume);
868 GdbExecContinue(true);
873 _dpl2(_dpct, dplchan::debuggerCall, 0, "Debugger::Break");
874 _ChangeUserAction(_break);
878 GdbDebugBreak(false);
884 _dpl2(_dpct, dplchan::debuggerCall, 0, "Debugger::Stop");
885 _ChangeUserAction(stop);
892 GdbDebugBreak(false);
906 void Restart(CompilerConfig compiler, ProjectConfig config, int bitDepth, bool useValgrind)
908 _dpl2(_dpct, dplchan::debuggerCall, 0, "Debugger::Restart");
909 _ChangeUserAction(restart);
910 if(StartSession(compiler, config, bitDepth, useValgrind, true, false, false/*, false*/) == loaded)
914 bool GoToCodeLine(char * location)
917 _dpl2(_dpct, dplchan::debuggerCall, 0, "Debugger::GoToCodeLine(", location, ")");
918 codloc = CodeLocation::ParseCodeLocation(location);
921 CodeEditor editor = (CodeEditor)ide.OpenFile(codloc.absoluteFile, normal, true, null, no, normal, false);
924 EditBox editBox = editor.editBox;
925 editBox.GoToLineNum(codloc.line - 1);
926 editBox.GoToPosition(editBox.line, codloc.line - 1, 0);
933 bool GoToStackFrameLine(int stackLevel, bool askForLocation, bool fromCallStack)
935 _dpl2(_dpct, dplchan::debuggerCall, 0, "Debugger::GoToStackFrameLine(", stackLevel, ", ", askForLocation, ")");
938 char filePath[MAX_LOCATION];
939 char sourceDir[MAX_LOCATION];
941 CodeEditor editor = null;
942 if(stackLevel == -1) // this (the two lines) is part of that fix that I would not put in for some time
944 for(frame = stackFrames.first; frame; frame = frame.next)
945 if(frame.level == stackLevel)
950 ide.callStackView.Show();
952 if(frame.absoluteFile)
953 editor = (CodeEditor)ide.OpenFile(frame.absoluteFile, normal, true, null, no, normal, false);
954 if(!editor && frame.file)
955 frame.absoluteFile = ide.workspace.GetAbsolutePathFromRelative(frame.file);
956 if(!frame.absoluteFile && askForLocation && frame.file)
959 char title[MAX_LOCATION];
960 snprintf(title, sizeof(title), $"Provide source file location for %s", (s = CopySystemPath(frame.file)));
961 title[sizeof(title)-1] = 0;
963 if(SourceDirDialog(title, ide.workspace.projectDir, frame.file, sourceDir))
965 AddSourceDir(sourceDir);
966 frame.absoluteFile = ide.workspace.GetAbsolutePathFromRelative(frame.file);
969 if(!editor && frame.absoluteFile)
970 editor = (CodeEditor)ide.OpenFile(frame.absoluteFile, normal, true, null, no, normal, false);
972 ide.RepositionWindows(false);
974 if(editor && frame.line)
976 EditBox editBox = editor.editBox;
977 editBox.GoToLineNum(frame.line - 1);
978 editBox.GoToPosition(editBox.line, frame.line - 1, 0);
986 void SelectThread(int thread)
988 _dpl2(_dpct, dplchan::debuggerCall, 0, "Debugger::SelectThread(", thread, ")");
989 _ChangeUserAction(selectThread);
992 if(thread != activeThread)
994 activeFrameLevel = -1;
995 ide.callStackView.Clear();
996 GdbCommand(false, "-thread-select %d", thread);
998 // Why was SelectFrame missing here?
999 SelectFrame(activeFrameLevel);
1000 GoToStackFrameLine(activeFrameLevel, true, false);
1001 WatchesCodeEditorLinkRelease();
1002 WatchesCodeEditorLinkInit();
1006 ide.callStackView.Show();
1010 void SelectFrame(int frame)
1012 //_dpl2(_dpct, dplchan::debuggerCall, 0, "Debugger::SelectFrame(", frame, ")");
1013 _ChangeUserAction(selectFrame); // not always user action, right? doesn't matter for now.
1014 if(state == stopped)
1016 if(frame != activeFrameLevel || !codeEditor || !codeEditor.visible)
1018 activeFrameLevel = frame; // there is no active frame number in the gdb reply
1019 GdbCommand(false, "-stack-select-frame %d", activeFrameLevel);
1020 for(activeFrame = stackFrames.first; activeFrame; activeFrame = activeFrame.next)
1021 if(activeFrame.level == activeFrameLevel)
1024 WatchesCodeEditorLinkRelease();
1025 WatchesCodeEditorLinkInit();
1032 void HandleExit(char * reason, char * code)
1034 bool returnedExitCode = false;
1035 char verboseExitCode[128];
1037 _dpl2(_dpct, dplchan::debuggerCall, 0, "Debugger::HandleExit(", reason, ", ", code, ")");
1038 _ChangeState(loaded); // this state change seems to be superfluous, might be in case of gdb crash
1039 targetProcessId = 0;
1043 snprintf(verboseExitCode, sizeof(verboseExitCode), $" with exit code %s", code);
1044 verboseExitCode[sizeof(verboseExitCode)-1] = 0;
1047 verboseExitCode[0] = '\0';
1051 // ClearBreakDisplay();
1055 for(wh : ide.workspace.watches)
1057 if(wh.type) FreeType(wh.type);
1060 ide.watchesView.UpdateWatch(wh);
1064 #if defined(__unix__)
1067 progThread.terminate = true;
1070 fifoFile.CloseInput();
1080 char program[MAX_LOCATION];
1081 GetSystemPathBuffer(program, targetFile);
1083 ide.outputView.debugBox.Logf($"The program %s has exited%s.\n", program, verboseExitCode);
1084 else if(!strcmp(reason, "exited-normally"))
1085 ide.outputView.debugBox.Logf($"The program %s has exited normally%s.\n", program, verboseExitCode);
1086 else if(!strcmp(reason, "exited"))
1087 ide.outputView.debugBox.Logf($"The program %s has exited%s.\n", program, verboseExitCode);
1088 else if(!strcmp(reason, "exited-signalled"))
1089 ide.outputView.debugBox.Logf($"The program %s has exited with a signal%s.\n", program, verboseExitCode);
1091 ide.outputView.debugBox.Logf($"The program %s has exited (gdb provided an unknown reason)%s.\n", program, verboseExitCode);
1096 DebuggerState StartSession(CompilerConfig compiler, ProjectConfig config, int bitDepth, bool useValgrind, bool restart, bool userBreakOnInternalBreakpoint, bool ignoreBreakpoints/*, bool runToCursorDebugStart*/)
1098 DebuggerState result = none;
1099 _dpl2(_dpct, dplchan::debuggerCall, 0, "Debugger::StartSession(restart(", restart, "), userBreakOnInternalBreakpoint(", userBreakOnInternalBreakpoint, "), ignoreBreakpoints(", ignoreBreakpoints, ")"/*, runToCursorDebugStart(", runToCursorDebugStart, ")"*/);
1100 if(restart && state == running && targetProcessId)
1102 breakType = DebuggerAction::restart;
1103 GdbDebugBreak(false);
1107 if(restart && state == stopped)
1109 if(needReset && state == loaded)
1110 GdbExit(); // this reset is to get a clean state with all the breakpoints until a better state can be maintained on program exit
1112 if(result == none || result == terminated)
1114 ide.outputView.ShowClearSelectTab(debug);
1115 ide.outputView.debugBox.Logf($"Starting debug mode\n");
1122 for(bp : ide.workspace.breakpoints)
1128 //this.runToCursorDebugStart = runToCursorDebugStart;
1130 if(GdbInit(compiler, config, bitDepth, useValgrind))
1135 this.ignoreBreakpoints = ignoreBreakpoints;
1136 this.userBreakOnInternalBreakpoint = userBreakOnInternalBreakpoint;
1137 if(result == loaded || result == stopped)
1138 GdbBreakpointsDelete(false, (userAction == stepOver || userAction == stepOut), ignoreBreakpoints);
1143 void Start(CompilerConfig compiler, ProjectConfig config, int bitDepth, bool useValgrind)
1145 _dpl2(_dpct, dplchan::debuggerCall, 0, "Debugger::Start()");
1146 _ChangeUserAction(start);
1147 if(StartSession(compiler, config, bitDepth, useValgrind, true, false, false/*, false*/) == loaded)
1151 void StepInto(CompilerConfig compiler, ProjectConfig config, int bitDepth, bool useValgrind)
1153 _dpl2(_dpct, dplchan::debuggerCall, 0, "Debugger::StepInto()");
1154 _ChangeUserAction(stepInto);
1155 switch(StartSession(compiler, config, bitDepth, useValgrind, false, true, false/*, false*/))
1157 case loaded: GdbExecRun(); break;
1158 case stopped: GdbExecStep(); break;
1162 void StepOver(CompilerConfig compiler, ProjectConfig config, int bitDepth, bool useValgrind, bool ignoreBreakpoints)
1164 _dpl2(_dpct, dplchan::debuggerCall, 0, "Debugger::StepOver()");
1165 _ChangeUserAction(stepOver);
1166 switch(StartSession(compiler, config, bitDepth, useValgrind, false, true, ignoreBreakpoints/*, false*/))
1168 case loaded: GdbExecRun(); break;
1169 case stopped: GdbExecNext(); break;
1173 void StepOut(bool ignoreBreakpoints)
1175 _dpl2(_dpct, dplchan::debuggerCall, 0, "Debugger::StepOut()");
1176 _ChangeUserAction(stepOut);
1177 if(state == stopped)
1179 this.ignoreBreakpoints = ignoreBreakpoints;
1180 GdbBreakpointsDelete(true, true, ignoreBreakpoints);
1184 GdbExecContinue(true);
1188 void RunToCursor(CompilerConfig compiler, ProjectConfig config, int bitDepth, bool useValgrind, char * absoluteFilePath, int lineNumber, bool ignoreBreakpoints, bool atSameLevel)
1190 char relativeFilePath[MAX_LOCATION];
1191 DebuggerState st = state;
1192 _dpl2(_dpct, dplchan::debuggerCall, 0, "Debugger::RunToCursor()");
1193 _ChangeUserAction(runToCursor);
1196 // ide.outputView.ShowClearSelectTab(debug);
1197 // ide.outputView.debugBox.Logf($"Starting debug mode\n");
1199 if(!ide.projectView.project.GetRelativePath(absoluteFilePath, relativeFilePath))
1200 strcpy(relativeFilePath, absoluteFilePath);
1202 if(bpRunToCursor && bpRunToCursor.inserted && symbols)
1204 UnsetBreakpoint(bpRunToCursor);
1205 delete bpRunToCursor;
1208 bpRunToCursor = Breakpoint { };
1209 bpRunToCursor.absoluteFilePath = absoluteFilePath;
1210 bpRunToCursor.relativeFilePath = relativeFilePath;
1211 bpRunToCursor.line = lineNumber;
1212 bpRunToCursor.type = runToCursor;
1213 bpRunToCursor.enabled = true;
1214 bpRunToCursor.level = atSameLevel ? frameCount - activeFrameLevel -1 : -1;
1216 switch(StartSession(compiler, config, bitDepth, useValgrind, false, false, ignoreBreakpoints/*, true*/))
1222 GdbExecContinue(true);
1227 void GetCallStackCursorLine(bool * error, int * lineCursor, int * lineTopFrame)
1229 //_dpl2(_dpct, dplchan::debuggerCall, 0, "Debugger::GetCallStackCursorLine()");
1230 if(activeFrameLevel == -1)
1238 *error = signalOn && activeThread == signalThread;
1239 *lineCursor = activeFrameLevel - ((frameCount > 192 && activeFrameLevel > 191) ? frameCount - 192 - 1 : 0) + 1;
1240 *lineTopFrame = activeFrameLevel ? 1 : 0;
1244 int GetMarginIconsLineNumbers(char * fileName, int lines[], bool enabled[], int max, bool * error, int * lineCursor, int * lineTopFrame)
1246 char winFilePath[MAX_LOCATION];
1247 char * absoluteFilePath = GetSlashPathBuffer(winFilePath, fileName);
1249 Iterator<Breakpoint> it { ide.workspace.breakpoints };
1250 //_dpl2(_dpct, dplchan::debuggerCall, 0, "Debugger::GetMarginIconsLineNumbers()");
1251 while(it.Next() && count < max)
1253 Breakpoint bp = it.data;
1256 if(bp.absoluteFilePath && bp.absoluteFilePath[0] && !fstrcmp(bp.absoluteFilePath, absoluteFilePath))
1258 lines[count] = bp.line;
1259 enabled[count] = bp.enabled;
1264 if(activeFrameLevel == -1)
1272 *error = signalOn && activeThread == signalThread;
1273 if(activeFrame && activeFrame.absoluteFile && !fstrcmp(absoluteFilePath, activeFrame.absoluteFile))
1274 *lineCursor = activeFrame.line;
1277 if(activeFrame && stopItem && stopItem.frame && activeFrame.level == stopItem.frame.level)
1279 else if(stopItem && stopItem.frame && stopItem.frame.absoluteFile && !fstrcmp(absoluteFilePath, stopItem.frame.absoluteFile))
1280 *lineTopFrame = stopItem.frame.line;
1284 if(*lineTopFrame == *lineCursor && *lineTopFrame)
1290 void ChangeWatch(DataRow row, char * expression)
1292 Watch wh = (Watch)row.tag;
1293 //_dpl2(_dpct, dplchan::debuggerCall, 0, "Debugger::ChangeWatch(", expression, ")");
1296 delete wh.expression;
1298 wh.expression = CopyString(expression);
1301 Iterator<Watch> it { ide.workspace.watches };
1303 ide.workspace.watches.Delete(it.pointer);
1309 row.tag = (int64)wh;
1310 ide.workspace.watches.Add(wh);
1312 wh.expression = CopyString(expression);
1314 ide.workspace.Save();
1315 //if(expression && state == stopped)
1320 void MoveIcons(char * fileName, int lineNumber, int move, bool start)
1322 char winFilePath[MAX_LOCATION];
1323 char * absoluteFilePath = GetSlashPathBuffer(winFilePath, fileName);
1326 //_dpl2(_dpct, dplchan::debuggerCall, 0, "Debugger::MoveIcons()");
1327 for(bpLink = ide.workspace.breakpoints.first; bpLink; bpLink = next)
1329 Breakpoint bp = (Breakpoint)bpLink.data;
1332 if(bp.type == user && bp.absoluteFilePath && !fstrcmp(bp.absoluteFilePath, absoluteFilePath))
1334 if(bp.line > lineNumber || (bp.line == lineNumber && start))
1336 if(move < 0 && (bp.line < lineNumber - move))
1337 ide.workspace.RemoveBreakpoint(bp);
1341 ide.breakpointsView.UpdateBreakpoint(bp.row);
1342 ide.workspace.Save();
1348 // moving code cursors is futile, on next step, stop, hit, cursors will be offset anyways
1351 bool SourceDirDialog(char * title, char * startDir, char * test, char * sourceDir)
1355 String srcDir = null;
1357 _dpl2(_dpct, dplchan::debuggerCall, 0, "Debugger::SourceDirDialog()");
1358 debuggerFileDialog.text = title;
1359 debuggerFileDialog.currentDirectory = startDir;
1360 debuggerFileDialog.master = ide;
1362 while(debuggerFileDialog.Modal())
1364 strcpy(sourceDir, debuggerFileDialog.filePath);
1365 if(!fstrcmp(ide.workspace.projectDir, sourceDir) &&
1366 MessageBox { type = yesNo, master = ide,
1367 contents = $"This is the project directory.\nWould you like to try again?",
1368 text = $"Invalid Source Directory" }.Modal() == no)
1372 for(dir : ide.workspace.sourceDirs)
1374 if(!fstrcmp(dir, sourceDir))
1382 MessageBox { type = yesNo, master = ide,
1383 contents = $"This source directory is already specified.\nWould you like to try again?",
1384 text = $"Invalid Source Directory" }.Modal() == no)
1390 char file[MAX_LOCATION];
1391 strcpy(file, sourceDir);
1392 PathCat(file, test);
1393 result = FileExists(file);
1395 MessageBox { type = yesNo, master = ide,
1396 contents = $"Unable to locate source file.\nWould you like to try again?",
1397 text = $"Invalid Source Directory" }.Modal() == no)
1411 void AddSourceDir(char * sourceDir)
1413 _dpl2(_dpct, dplchan::debuggerCall, 0, "Debugger::AddSourceDir(", sourceDir, ")");
1414 ide.workspace.sourceDirs.Add(CopyString(sourceDir));
1415 ide.workspace.Save();
1419 DebuggerState oldState = state;
1424 GdbDebugBreak(true);
1427 GdbCommand(false, "-environment-directory \"%s\"", sourceDir);
1430 if(oldState == running)
1431 GdbExecContinue(false);
1435 void ToggleBreakpoint(char * fileName, int lineNumber, Project prj)
1437 char winFilePath[MAX_LOCATION];
1438 char * absoluteFilePath = GetSlashPathBuffer(winFilePath, fileName);
1439 char absolutePath[MAX_LOCATION];
1440 char relativePath[MAX_LOCATION];
1441 char sourceDir[MAX_LOCATION];
1442 Breakpoint bp = null;
1444 _dpl2(_dpct, dplchan::debuggerBreakpoints, 0, "Debugger::ToggleBreakpoint(", fileName, ":", lineNumber, ")");
1445 strcpy(absolutePath, absoluteFilePath);
1446 for(i : ide.workspace.breakpoints; i.type == user && i.absoluteFilePath && !fstrcmp(i.absoluteFilePath, absolutePath) && i.line == lineNumber)
1455 ide.workspace.RemoveBreakpoint(bp);
1463 // FIXED: This is how it should have been... Source locations are only for files not in project
1464 // if(IsPathInsideOf(absolutePath, ide.workspace.projectDir))
1465 // MakePathRelative(absolutePath, ide.workspace.projectDir, relativePath);
1466 bool result = false;
1468 result = prj.GetRelativePath(absolutePath, relativePath);
1470 result = ide.projectView.project.GetRelativePath(absolutePath, relativePath);
1471 //if(ide.projectView.project.GetRelativePath(absolutePath, relativePath));
1475 char title[MAX_LOCATION];
1476 char directory[MAX_LOCATION];
1477 StripLastDirectory(absolutePath, directory);
1478 snprintf(title, sizeof(title), $"Provide source files location directory for %s", absolutePath);
1479 title[sizeof(title)-1] = 0;
1482 String srcDir = null;
1483 for(dir : ide.workspace.sourceDirs)
1485 if(IsPathInsideOf(absolutePath, dir))
1487 MakePathRelative(absoluteFilePath, dir, relativePath);
1495 if(SourceDirDialog(title, directory, null, sourceDir))
1497 if(IsPathInsideOf(absolutePath, sourceDir))
1499 AddSourceDir(sourceDir);
1500 MakePathRelative(absoluteFilePath, sourceDir, relativePath);
1503 else if(MessageBox { type = yesNo, master = ide,
1504 contents = $"You must provide a valid source directory in order to place a breakpoint in this file.\nWould you like to try again?",
1505 text = $"Invalid Source Directory" }.Modal() == no)
1508 else if(MessageBox { type = yesNo, master = ide,
1509 contents = $"You must provide a source directory in order to place a breakpoint in this file.\nWould you like to try again?",
1510 text = $"No Source Directory Provided" }.Modal() == no)
1514 ide.workspace.bpCount++;
1515 bp = { line = lineNumber, type = user, enabled = true, level = -1 };
1516 ide.workspace.breakpoints.Add(bp);
1517 bp.absoluteFilePath = absolutePath;
1518 bp.relativeFilePath = relativePath;
1519 ide.breakpointsView.AddBreakpoint(bp);
1524 DebuggerState oldState = state;
1529 GdbDebugBreak(true);
1532 SetBreakpoint(bp, false);
1535 if(oldState == running)
1536 GdbExecContinue(false);
1539 ide.workspace.Save();
1542 void UpdateRemovedBreakpoint(Breakpoint bp)
1544 _dpl2(_dpct, dplchan::debuggerCall, 0, "Debugger::UpdateRemovedBreakpoint()");
1545 if(targeted && bp.inserted)
1547 DebuggerState oldState = state;
1552 GdbDebugBreak(true);
1555 UnsetBreakpoint(bp);
1558 if(oldState == running)
1559 GdbExecContinue(false);
1565 void ParseFrame(Frame frame, char * string)
1568 Array<char *> frameTokens { minAllocSize = 50 };
1569 Array<char *> argsTokens { minAllocSize = 50 };
1570 Array<char *> argumentTokens { minAllocSize = 50 };
1571 DebugListItem item { };
1574 //_dpl2(_dpct, dplchan::debuggerCall, 0, "Debugger::ParseFrame()");
1575 TokenizeList(string, ',', frameTokens);
1576 for(i = 0; i < frameTokens.count; i++)
1578 if(TokenizeListItem(frameTokens[i], item))
1580 StripQuotes(item.value, item.value);
1581 if(!strcmp(item.name, "level"))
1582 frame.level = atoi(item.value);
1583 else if(!strcmp(item.name, "addr"))
1584 frame.addr = item.value;
1585 else if(!strcmp(item.name, "func"))
1586 frame.func = item.value;
1587 else if(!strcmp(item.name, "args"))
1589 if(!strcmp(item.value, "[]"))
1590 frame.argsCount = 0;
1593 item.value = StripBrackets(item.value);
1594 TokenizeList(item.value, ',', argsTokens);
1595 for(j = 0; j < argsTokens.count; j++)
1597 argsTokens[j] = StripCurlies(argsTokens[j]);
1598 TokenizeList(argsTokens[j], ',', argumentTokens);
1599 for(k = 0; k < argumentTokens.count; k++)
1602 frame.args.Add(arg);
1603 if(TokenizeListItem(argumentTokens[k], item))
1605 if(!strcmp(item.name, "name"))
1607 StripQuotes(item.value, item.value);
1608 arg.name = item.value;
1610 else if(!strcmp(item.name, "value"))
1612 StripQuotes(item.value, item.value);
1613 arg.val = item.value;
1616 _dpl2(_dpct, dplchan::gdbProtoUnknown, 0, "frame args item (", item.name, "=", item.value, ") is unheard of");
1619 _dpl(0, "Bad frame args item");
1621 argumentTokens.RemoveAll();
1623 frame.argsCount = argsTokens.count;
1624 argsTokens.RemoveAll();
1627 else if(!strcmp(item.name, "from"))
1628 frame.from = item.value;
1629 else if(!strcmp(item.name, "file"))
1630 frame.file = item.value;
1631 else if(!strcmp(item.name, "line"))
1632 frame.line = atoi(item.value);
1633 else if(!strcmp(item.name, "fullname"))
1634 frame.absoluteFile = item.value;
1636 // GDB 6.3 on OS X is giving "fullname" and "dir", all in absolute, but file name only in 'file'
1637 String path = ide.workspace.GetPathWorkspaceRelativeOrAbsolute(item.value);
1638 if(strcmp(frame.file, path))
1641 frame.absoluteFile = ide.workspace.GetAbsolutePathFromRelative(frame.file);
1646 _dpl2(_dpct, dplchan::gdbProtoUnknown, 0, "frame member (", item.name, "=", item.value, ") is unheard of");
1649 _dpl(0, "Bad frame");
1654 delete argumentTokens;
1658 Breakpoint GetBreakpointById(int id, bool * isInternal)
1660 Breakpoint bp = null;
1661 //_dpl2(_dpct, dplchan::debuggerBreakpoints, 0, "Debugger::GetBreakpointById(", id, ")");
1663 *isInternal = false;
1666 for(i : sysBPs; i.bp && i.bp.id == id)
1673 if(!bp && bpRunToCursor && bpRunToCursor.bp && bpRunToCursor.bp.id == id)
1677 for(i : ide.workspace.breakpoints; i.bp && i.bp.id == id)
1687 GdbDataBreakpoint ParseBreakpoint(char * string, Array<char *> outTokens)
1690 GdbDataBreakpoint bp { };
1691 DebugListItem item { };
1692 Array<char *> bpTokens { minAllocSize = 16 };
1693 _dpl2(_dpct, dplchan::debuggerCall, 0, "Debugger::ParseBreakpoint()");
1694 string = StripCurlies(string);
1695 TokenizeList(string, ',', bpTokens);
1696 for(i = 0; i < bpTokens.count; i++)
1698 if(TokenizeListItem(bpTokens[i], item))
1700 StripQuotes(item.value, item.value);
1701 if(!strcmp(item.name, "number"))
1703 if(!strchr(item.value, '.'))
1704 bp.id = atoi(item.value);
1705 bp.number = item.value;
1707 else if(!strcmp(item.name, "type"))
1708 bp.type = item.value;
1709 else if(!strcmp(item.name, "disp"))
1710 bp.disp = item.value;
1711 else if(!strcmp(item.name, "enabled"))
1712 bp.enabled = (!strcmpi(item.value, "y"));
1713 else if(!strcmp(item.name, "addr"))
1715 if(outTokens && !strcmp(item.value, "<MULTIPLE>"))
1718 Array<GdbDataBreakpoint> bpArray = bp.multipleBPs = { };
1719 while(outTokens.count > ++c)
1721 GdbDataBreakpoint multBp = ParseBreakpoint(outTokens[c], null);
1722 bpArray.Add(multBp);
1726 bp.addr = item.value;
1728 else if(!strcmp(item.name, "func"))
1729 bp.func = item.value;
1730 else if(!strcmp(item.name, "file"))
1731 bp.file = item.value;
1732 else if(!strcmp(item.name, "fullname"))
1733 bp.fullname = item.value;
1734 else if(!strcmp(item.name, "line"))
1735 bp.line = atoi(item.value);
1736 else if(!strcmp(item.name, "at"))
1738 else if(!strcmp(item.name, "times"))
1739 bp.times = atoi(item.value);
1740 else if(!strcmp(item.name, "original-location") || !strcmp(item.name, "thread-groups"))
1741 _dpl2(_dpct, dplchan::gdbProtoIgnored, 0, "breakpoint member (", item.name, "=", item.value, ") is ignored");
1743 _dpl2(_dpct, dplchan::gdbProtoUnknown, 0, "breakpoint member (", item.name, "=", item.value, ") is unheard of");
1749 void ShowDebuggerViews()
1751 //_dpl2(_dpct, dplchan::debuggerCall, 0, "Debugger::ShowDebuggerViews()");
1752 ide.outputView.Show();
1753 ide.outputView.SelectTab(debug);
1754 ide.threadsView.Show();
1755 ide.callStackView.Show();
1756 ide.watchesView.Show();
1760 void HideDebuggerViews()
1762 //_dpl2(_dpct, dplchan::debuggerCall, 0, "Debugger::HideDebuggerViews()");
1763 ide.RepositionWindows(true);
1766 void ::GdbCommand(bool focus, char * format, ...)
1770 // TODO: Improve this limit
1771 static char string[MAX_F_STRING*4];
1773 va_start(args, format);
1774 vsnprintf(string, sizeof(string), format, args);
1775 string[sizeof(string)-1] = 0;
1779 ide.debugger.serialSemaphore.TryWait();
1781 #ifdef GDB_DEBUG_CONSOLE
1782 _dpl2(_dpct, dplchan::gdbCommand, 0, string);
1784 #ifdef GDB_DEBUG_OUTPUT
1785 ide.outputView.gdbBox.Logf("cmd: %s\n", string);
1787 #ifdef GDB_DEBUG_GUI
1789 ide.gdbDialog.AddCommand(string);
1792 strcat(string,"\n");
1793 gdbHandle.Puts(string);
1796 Process_ShowWindows(targetProcessId);
1799 ide.debugger.serialSemaphore.Wait();
1804 bool ValidateBreakpoint(Breakpoint bp)
1806 _dpl2(_dpct, dplchan::debuggerCall, 0, "Debugger::ValidateBreakpoint()");
1807 if(modules && bp.line && bp.bp)
1809 if(bp.bp.line != bp.line)
1815 ide.outputView.debugBox.Logf("WOULD HAVE -- Invalid breakpoint disabled: %s:%d\n", bp.relativeFilePath, bp.line);
1817 //UnsetBreakpoint(bp);
1818 //bp.enabled = false;
1824 ide.outputView.debugBox.Logf("Debugger Error: ValidateBreakpoint error\n");
1825 bp.line = bp.bp.line;
1832 void GdbBreakpointsInsert()
1834 //_dpl2(_dpct, dplchan::debuggerBreakpoints, 0, "Debugger::GdbBreakpointsInsert()");
1837 if(userAction != stepOut && (userAction != stepOver || state == loaded))
1839 DirExpression objDir = ide.project.GetObjDir(currentCompiler, prjConfig, bitDepth);
1840 for(bp : sysBPs; !bp.inserted)
1842 bool insert = false;
1843 if(bp.type == internalModulesLoaded)
1845 char path[MAX_LOCATION];
1846 char name[MAX_LOCATION];
1847 char fixedModuleName[MAX_FILENAME];
1850 bool moduleLoadBlock = false;
1852 ReplaceSpaces(fixedModuleName, ide.project.moduleName);
1853 snprintf(name, sizeof(name),"%s.main.ec", fixedModuleName);
1854 name[sizeof(name)-1] = 0;
1855 strcpy(path, ide.workspace.projectDir);
1856 PathCatSlash(path, objDir.dir);
1857 PathCatSlash(path, name);
1858 f = FileOpen(path, read);
1861 for(lineNumber = 1; !f.Eof(); lineNumber++)
1863 if(f.GetLine(line, sizeof(line) - 1))
1865 bool moduleLoadLine;
1866 TrimLSpaces(line, line);
1867 moduleLoadLine = !strncmp(line, "eModule_Load", strlen("eModule_Load"));
1868 if(!moduleLoadBlock && moduleLoadLine)
1869 moduleLoadBlock = true;
1870 else if(moduleLoadBlock && !moduleLoadLine && strlen(line) > 0)
1876 char relative[MAX_LOCATION];
1877 bp.absoluteFilePath = path;
1878 MakePathRelative(path, ide.workspace.projectDir, relative);
1879 bp.relativeFilePath = relative;
1880 bp.line = lineNumber;
1886 else if(bp.type == internalModuleLoad)
1890 for(prj : ide.workspace.projects)
1892 if(!strcmp(prj.moduleName, "ecere"))
1894 ProjectNode node = prj.topNode.Find("instance.c", false);
1897 char path[MAX_LOCATION];
1898 char relative[MAX_LOCATION];
1899 node.GetFullFilePath(path);
1900 bp.absoluteFilePath = path;
1901 MakePathRelative(path, prj.topNode.path, relative);
1902 bp.relativeFilePath = relative;
1913 SetBreakpoint(bp, false);
1918 if(bpRunToCursor && !bpRunToCursor.inserted)
1919 SetBreakpoint(bpRunToCursor, false);
1921 if(!ignoreBreakpoints)
1923 for(bp : ide.workspace.breakpoints; !bp.inserted && bp.type == user)
1927 if(!SetBreakpoint(bp, false))
1928 SetBreakpoint(bp, true);
1936 bp.bp = GdbDataBreakpoint { };
1943 void UnsetBreakpoint(Breakpoint bp)
1945 char * s; _dpl2(_dpct, dplchan::debuggerBreakpoints, 0, "Debugger::UnsetBreakpoint(", s=bp.CopyLocationString(false), ") -- ", bp.type); delete s;
1946 if(symbols && bp.inserted)
1948 GdbCommand(false, "-break-delete %s", bp.bp.number);
1949 bp.inserted = false;
1954 bool SetBreakpoint(Breakpoint bp, bool removePath)
1956 char * s; _dpl2(_dpct, dplchan::debuggerBreakpoints, 0, "Debugger::SetBreakpoint(", s=bp.CopyLocationString(false), ", ", removePath ? "**** removePath(true) ****" : "", ") -- ", bp.type); delete s;
1957 breakpointError = false;
1960 char * location = bp.CopyLocationString(removePath);
1961 sentBreakInsert = true;
1962 GdbCommand(false, "-break-insert %s", location);
1964 if(!breakpointError)
1966 if(bpItem && bpItem.multipleBPs && bpItem.multipleBPs.count)
1969 GdbDataBreakpoint first = null;
1970 for(n : bpItem.multipleBPs)
1972 if(!fstrcmp(n.fullname, bp.absoluteFilePath))
1982 GdbCommand(false, "-break-disable %s", n.number);
1986 _dpl2(_dpct, dplchan::debuggerProblem, 0, "Debugger::SetBreakpoint -- error breakpoint already disabled.");
1991 bpItem.addr = first.addr;
1992 bpItem.func = first.func;
1993 bpItem.file = first.file;
1994 bpItem.fullname = first.fullname;
1995 bpItem.line = first.line;
1996 //bpItem.thread-groups = first.thread-groups;
1997 bpItem.multipleBPs.Free();
1998 delete bpItem.multipleBPs;
2001 _dpl2(_dpct, dplchan::debuggerProblem, 0, "Debugger::SetBreakpoint -- error multiple breakpoints all disabled.");
2003 _dpl2(_dpct, dplchan::debuggerProblem, 0, "Debugger::SetBreakpoint -- error multiple breakpoints in exact same file not supported.");
2007 bp.inserted = (bp.bp && bp.bp.number && strcmp(bp.bp.number, "0"));
2009 ValidateBreakpoint(bp);
2010 /*if(bp == bpRunToCursor)
2011 runToCursorDebugStart = false;*/
2014 return !breakpointError;
2017 void GdbBreakpointsDelete(bool deleteRunToCursor, bool deleteInternalBreakpoints, bool deleteUserBreakpoints)
2019 _dpl2(_dpct, dplchan::debuggerBreakpoints, 0, "Debugger::GdbBreakpointsDelete(deleteRunToCursor(", deleteRunToCursor, "))");
2022 if(deleteInternalBreakpoints)
2025 UnsetBreakpoint(bp);
2027 if(deleteUserBreakpoints)
2029 for(bp : ide.workspace.breakpoints)
2030 UnsetBreakpoint(bp);
2032 if(deleteRunToCursor && bpRunToCursor)
2033 UnsetBreakpoint(bpRunToCursor);
2039 _dpl2(_dpct, dplchan::debuggerCall, 0, "Debugger::GdbGetStack()");
2041 stackFrames.Free(Frame::Free);
2042 GdbCommand(false, "-stack-info-depth");
2044 GdbCommand(false, "-stack-info-depth 192");
2045 if(frameCount && frameCount <= 192)
2046 GdbCommand(false, "-stack-list-frames 0 %d", Min(frameCount-1, 191));
2049 GdbCommand(false, "-stack-list-frames 0 %d", Min(frameCount-1, 95));
2050 GdbCommand(false, "-stack-list-frames %d %d", Max(frameCount - 96, 96), frameCount - 1);
2052 GdbCommand(false, "");
2057 _dpl2(_dpct, dplchan::debuggerCall, 0, "Debugger::GdbTargetSet()");
2060 char escaped[MAX_LOCATION];
2061 strescpy(escaped, targetFile);
2062 GdbCommand(false, "file \"%s\"", escaped); //GDB/MI Missing Implementation -symbol-file, -target-attach
2069 const char *vgdbCommand = "/usr/bin/vgdb"; // TODO: vgdb command config option
2070 //GdbCommand(false, "-target-select remote | %s --pid=%d", "vgdb", targetProcessId);
2071 printf("target remote | %s --pid=%d\n", vgdbCommand, targetProcessId);
2072 GdbCommand(false, "target remote | %s --pid=%d", vgdbCommand, targetProcessId); // TODO: vgdb command config option
2075 /*for(prj : ide.workspace.projects; prj != ide.workspace.projects.firstIterator.data)
2076 GdbCommand(false, "-environment-directory \"%s\"", prj.topNode.path);*/
2078 for(dir : ide.workspace.sourceDirs; dir && dir[0])
2080 bool interference = false;
2081 for(prj : ide.workspace.projects)
2083 if(!fstrcmp(prj.topNode.path, dir))
2085 interference = true;
2089 if(!interference && dir[0])
2090 GdbCommand(false, "-environment-directory \"%s\"", dir);
2098 /*void GdbTargetRelease()
2102 GdbBreakpointsDelete(true, true, true);
2103 GdbCommand(false, "file"); //GDB/MI Missing Implementation -target-detach
2109 void GdbDebugBreak(bool internal)
2111 _dpl2(_dpct, dplchan::debuggerCall, 0, "Debugger::GdbDebugBreak()");
2115 breakType = DebuggerAction::internal;
2117 if(ide) ide.Update(null);
2119 if(Process_Break(targetProcessId)) //GdbCommand(false, "-exec-interrupt");
2120 serialSemaphore.Wait();
2123 _ChangeState(loaded);
2124 targetProcessId = 0;
2129 ide.outputView.debugBox.Logf("Debugger Error: GdbDebugBreak with not target id should never happen\n");
2134 _dpl2(_dpct, dplchan::debuggerCall, 0, "Debugger::GdbExecRun()");
2137 ShowDebuggerViews();
2139 GdbCommand(true, "-exec-continue");
2141 GdbCommand(true, "-exec-run");
2144 void GdbExecContinue(bool focus)
2146 _dpl2(_dpct, dplchan::debuggerCall, 0, "Debugger::GdbExecContinue()");
2148 GdbCommand(focus, "-exec-continue");
2153 _dpl2(_dpct, dplchan::debuggerCall, 0, "Debugger::GdbExecNext()");
2155 GdbCommand(true, "-exec-next");
2160 _dpl2(_dpct, dplchan::debuggerCall, 0, "Debugger::GdbExecStep()");
2162 GdbCommand(true, "-exec-step");
2165 void GdbExecFinish()
2167 _dpl2(_dpct, dplchan::debuggerCall, 0, "Debugger::GdbExecFinish()");
2169 GdbCommand(true, "-exec-finish");
2172 void GdbExecCommon()
2174 //_dpl2(_dpct, dplchan::debuggerCall, 0, "Debugger::GdbExecCommon()");
2175 GdbBreakpointsInsert();
2178 #ifdef GDB_DEBUG_GUI
2179 void SendGDBCommand(char * command)
2181 //_dpl2(_dpct, dplchan::debuggerCall, 0, "Debugger::SendGDBCommand()");
2182 DebuggerState oldState = state;
2187 GdbDebugBreak(true);
2190 GdbCommand(false, command);
2193 if(oldState == running)
2194 GdbExecContinue(false);
2198 void ClearBreakDisplay()
2200 //_dpl2(_dpct, dplchan::debuggerCall, 0, "Debugger::ClearBreakDisplay()");
2202 activeFrameLevel = -1;
2212 stackFrames.Free(Frame::Free);
2213 WatchesCodeEditorLinkRelease();
2214 ide.callStackView.Clear();
2215 ide.threadsView.Clear();
2221 _dpl2(_dpct, dplchan::debuggerCall, 0, "Debugger::GdbAbortExec()");
2223 GdbCommand(false, "-interpreter-exec console \"kill\""); // should use -exec-abort -- GDB/MI implementation incomplete
2227 bool GdbInit(CompilerConfig compiler, ProjectConfig config, int bitDepth, bool useValgrind)
2230 char oldDirectory[MAX_LOCATION];
2231 char tempPath[MAX_LOCATION];
2232 char command[MAX_F_STRING*4];
2233 Project project = ide.project;
2234 DirExpression targetDirExp = project.GetTargetDir(compiler, config, bitDepth);
2235 PathBackup pathBackup { };
2237 _dpl2(_dpct, dplchan::debuggerCall, 0, "Debugger::GdbInit()");
2238 if(currentCompiler != compiler)
2240 delete currentCompiler;
2241 currentCompiler = compiler;
2242 incref currentCompiler;
2245 this.bitDepth = bitDepth;
2246 usingValgrind = useValgrind;
2248 _ChangeState(loaded);
2250 sentBreakInsert = false;
2251 breakpointError = false;
2252 ignoreBreakpoints = false;
2258 ide.outputView.ShowClearSelectTab(debug);
2259 ide.outputView.debugBox.Logf($"Starting debug mode\n");
2261 #ifdef GDB_DEBUG_OUTPUT
2262 ide.outputView.gdbBox.Logf("run: Starting GDB\n");
2265 strcpy(tempPath, ide.workspace.projectDir);
2266 PathCatSlash(tempPath, targetDirExp.dir);
2268 targetDir = CopyString(tempPath);
2269 project.CatTargetFileName(tempPath, compiler, config);
2271 targetFile = CopyString(tempPath);
2273 GetWorkingDir(oldDirectory, MAX_LOCATION);
2274 if(ide.workspace.debugDir && ide.workspace.debugDir[0])
2276 char temp[MAX_LOCATION];
2277 strcpy(temp, ide.workspace.projectDir);
2278 PathCatSlash(temp, ide.workspace.debugDir);
2279 ChangeWorkingDir(temp);
2282 ChangeWorkingDir(ide.workspace.projectDir);
2284 ide.SetPath(true, compiler, config, bitDepth);
2286 // TODO: This pollutes the environment, but at least it works
2287 // It shouldn't really affect the IDE as the PATH gets restored and other variables set for testing will unlikely cause problems
2288 // What is the proper solution for this? DualPipeOpenEnv?
2289 // gdb set environment commands don't seem to take effect
2290 for(e : ide.workspace.environmentVars)
2292 SetEnvironment(e.name, e.string);
2297 char * clArgs = ide.workspace.commandLineArgs;
2298 const char *valgrindCommand = "valgrind"; // TODO: valgrind command config option //TODO: valgrind options
2299 ValgrindLeakCheck vgLeakCheck = ide.workspace.vgLeakCheck;
2300 int vgRedzoneSize = ide.workspace.vgRedzoneSize;
2301 bool vgTrackOrigins = ide.workspace.vgTrackOrigins;
2302 vgLogFile = CreateTemporaryFile(vgLogPath, "ecereidevglog");
2306 vgLogThread.Create();
2310 ide.outputView.debugBox.Logf($"Debugger Fatal Error: Couldn't open temporary log file for Valgrind output\n");
2313 if(result && !CheckCommandAvailable(valgrindCommand))
2315 ide.outputView.debugBox.Logf($"Debugger Fatal Error: Command %s for Valgrind is not available.\n", valgrindCommand);
2320 char * vgRedzoneSizeFlag = vgRedzoneSize == -1 ? "" : PrintString(" --redzone-size=", vgRedzoneSize);
2321 sprintf(command, "%s --vgdb=yes --vgdb-error=0 --log-file=%s --leak-check=%s%s --track-origins=%s %s%s%s",
2322 valgrindCommand, vgLogPath, (char*)vgLeakCheck, vgRedzoneSizeFlag, vgTrackOrigins ? "yes" : "no", targetFile, clArgs ? " " : "", clArgs ? clArgs : "");
2323 if(vgRedzoneSize != -1)
2324 delete vgRedzoneSizeFlag;
2325 vgTargetHandle = DualPipeOpen(PipeOpenMode { output = true, /*error = true, */input = true }, command);
2328 ide.outputView.debugBox.Logf($"Debugger Fatal Error: Couldn't start Valgrind\n");
2334 incref vgTargetHandle;
2335 vgTargetThread.Create();
2337 targetProcessId = vgTargetHandle.GetProcessID();
2338 waitingForPID = false;
2339 if(!targetProcessId)
2341 ide.outputView.debugBox.Logf($"Debugger Fatal Error: Couldn't get Valgrind process ID\n");
2348 serialSemaphore.Wait();
2356 (compiler.targetPlatform == win32 && bitDepth == 64) ? "x86_64-w64-mingw32-gdb" :
2357 (compiler.targetPlatform == win32 && bitDepth == 32) ? "i686-w64-mingw32-gdb" :
2359 if(!CheckCommandAvailable(command))
2361 ide.outputView.debugBox.Logf($"Debugger Fatal Error: Command %s for GDB is not available.\n", command);
2366 strcat(command, " -n -silent --interpreter=mi2"); //-async //\"%s\"
2368 gdbHandle = DualPipeOpen(PipeOpenMode { output = true, /*error = true, */input = true }, command);
2371 ide.outputView.debugBox.Logf($"Debugger Fatal Error: Couldn't start GDB\n");
2381 gdbProcessId = gdbHandle.GetProcessID();
2384 ide.outputView.debugBox.Logf($"Debugger Fatal Error: Couldn't get GDB process ID\n");
2391 serialSemaphore.Wait();
2394 GdbCommand(false, "-gdb-set verbose off");
2395 //GdbCommand(false, "-gdb-set exec-done-display on");
2396 GdbCommand(false, "-gdb-set step-mode off");
2397 GdbCommand(false, "-gdb-set unwindonsignal on");
2398 //GdbCommand(false, "-gdb-set shell on");
2399 GdbCommand(false, "set print elements 992");
2400 GdbCommand(false, "-gdb-set backtrace limit 100000");
2404 //_ChangeState(terminated);
2410 #if defined(__unix__)
2412 CreateTemporaryDir(progFifoDir, "ecereide");
2413 strcpy(progFifoPath, progFifoDir);
2414 PathCat(progFifoPath, "ideprogfifo");
2415 if(!mkfifo(progFifoPath, 0600))
2417 //fileCreated = true;
2422 ide.outputView.debugBox.Logf(createFIFOMsg, progFifoPath);
2429 progThread.terminate = false;
2430 progThread.Create();
2434 #if defined(__WIN32__)
2435 GdbCommand(false, "-gdb-set new-console on");
2438 #if defined(__unix__)
2440 GdbCommand(false, "-inferior-tty-set %s", progFifoPath);
2444 GdbCommand(false, "-gdb-set args %s", ide.workspace.commandLineArgs ? ide.workspace.commandLineArgs : "");
2446 for(e : ide.workspace.environmentVars)
2448 GdbCommand(false, "set environment %s=%s", e.name, e.string);
2453 ChangeWorkingDir(oldDirectory);
2459 delete targetDirExp;
2465 _dpl2(_dpct, dplchan::debuggerCall, 0, "Debugger::GdbExit()");
2466 if(gdbHandle && gdbProcessId)
2468 GdbCommand(false, "-gdb-exit");
2483 _ChangeState(terminated); // this state change seems to be superfluous, is it safety for something?
2489 for(bp : ide.workspace.breakpoints)
2491 bp.inserted = false;
2497 bp.inserted = false;
2502 bpRunToCursor.inserted = false;
2503 delete bpRunToCursor.bp;
2506 ide.outputView.debugBox.Logf($"Debugging stopped\n");
2507 ClearBreakDisplay();
2510 #if defined(__unix__)
2511 if(!usingValgrind && FileExists(progFifoPath)) //fileCreated)
2513 progThread.terminate = true;
2516 fifoFile.CloseInput();
2522 DeleteFile(progFifoPath);
2523 progFifoPath[0] = '\0';
2529 void WatchesCodeEditorLinkInit()
2531 //_dpl2(_dpct, dplchan::debuggerCall, 0, "Debugger::WatchesCodeEditorLinkInit()");
2533 char tempPath[MAX_LOCATION];
2534 char path[MAX_LOCATION];
2536 //void MakeFilePathProjectRelative(char * path, char * relativePath)
2537 if(!ide.projectView.project.GetRelativePath(activeFrame.file, tempPath))
2538 strcpy(tempPath, activeFrame.file);
2540 strcpy(path, ide.workspace.projectDir);
2541 PathCat(path, tempPath);
2542 codeEditor = (CodeEditor)ide.OpenFile(path, Normal, false, null, no, normal, false);
2545 for(srcDir : ide.workspace.sourceDirs)
2547 strcpy(path, srcDir);
2548 PathCat(path, tempPath);
2549 codeEditor = (CodeEditor)ide.OpenFile(path, Normal, false, null, no, normal, false);
2550 if(codeEditor) break;
2555 /*if(activeFrame && !activeFrame.absoluteFile && activeFrame.file)
2556 activeFrame.absoluteFile = ide.workspace.GetAbsolutePathFromRelative(activeFrame.file);*/
2557 if(!activeFrame || !activeFrame.absoluteFile)
2560 codeEditor = (CodeEditor)ide.OpenFile(activeFrame.absoluteFile, normal, false, null, no, normal, false);
2563 codeEditor.inUseDebug = true;
2566 //watchesInit = true;
2569 void WatchesCodeEditorLinkRelease()
2571 //_dpl2(_dpct, dplchan::debuggerCall, 0, "Debugger::WatchesCodeEditorLinkRelease()");
2576 codeEditor.inUseDebug = false;
2577 if(!codeEditor.visible)
2578 codeEditor.Destroy(0);
2584 bool ResolveWatch(Watch wh)
2586 bool result = false;
2588 _dpl2(_dpct, dplchan::debuggerWatches, 0, "Debugger::ResolveWatch()");
2600 char watchmsg[MAX_F_STRING];
2601 if(state == stopped && !codeEditor)
2602 wh.value = CopyString($"No source file found for selected frame");
2603 //if(codeEditor && state == stopped || state != stopped)
2606 Module backupPrivateModule;
2607 Context backupContext;
2608 Class backupThisClass;
2612 backupPrivateModule = GetPrivateModule();
2613 backupContext = GetCurrentContext();
2614 backupThisClass = GetThisClass();
2617 SetPrivateModule(codeEditor.privateModule);
2618 SetCurrentContext(codeEditor.globalContext);
2619 SetTopContext(codeEditor.globalContext);
2620 SetGlobalContext(codeEditor.globalContext);
2621 SetGlobalData(&codeEditor.globalData);
2624 exp = ParseExpressionString(wh.expression);
2626 if(exp && !parseError)
2628 char expString[4096];
2630 PrintExpression(exp, expString);
2632 if(GetPrivateModule())
2635 DebugFindCtxTree(codeEditor.ast, activeFrame.line, 0);
2636 ProcessExpressionType(exp);
2638 wh.type = exp.expType;
2641 DebugComputeExpression(exp);
2642 if(ExpressionIsError(exp))
2644 GDBFallBack(exp, expString);
2647 /*if(exp.hasAddress)
2649 char temp[MAX_F_STRING];
2650 sprintf(temp, "0x%x", exp.address);
2651 wh.address = CopyString(temp);
2652 // wh.address = CopyStringf("0x%x", exp.address);
2657 Type dataType = exp.expType;
2660 char temp[MAX_F_STRING];
2661 switch(dataType.kind)
2664 sprintf(temp, "%i", exp.val.c);
2667 sprintf(temp, "%i", exp.val.s);
2672 sprintf(temp, "%i", exp.val.i);
2675 sprintf(temp, "%i", exp.val.i64);
2678 sprintf(temp, "%i", exp.val.p);
2683 long v = (long)exp.val.f;
2684 sprintf(temp, "%i", v);
2689 long v = (long)exp.val.d;
2690 sprintf(temp, "%i", v);
2695 wh.intVal = CopyString(temp);
2696 switch(dataType.kind)
2699 sprintf(temp, "0x%x", exp.val.c);
2702 sprintf(temp, "0x%x", exp.val.s);
2706 sprintf(temp, "0x%x", exp.val.i);
2709 sprintf(temp, "0x%x", exp.val.i64);
2712 sprintf(temp, "0x%x", exp.val.i64);
2715 sprintf(temp, "0x%x", exp.val.p);
2720 long v = (long)exp.val.f;
2721 sprintf(temp, "0x%x", v);
2726 long v = (long)exp.val.d;
2727 sprintf(temp, "0x%x", v);
2732 wh.hexVal = CopyString(temp);
2733 switch(dataType.kind)
2736 sprintf(temp, "0o%o", exp.val.c);
2739 sprintf(temp, "0o%o", exp.val.s);
2743 sprintf(temp, "0o%o", exp.val.i);
2746 sprintf(temp, "0o%o", exp.val.i64);
2749 sprintf(temp, "0o%o", exp.val.i64);
2752 sprintf(temp, "0o%o", exp.val.p);
2757 long v = (long)exp.val.f;
2758 sprintf(temp, "0o%o", v);
2763 long v = (long)exp.val.d;
2764 sprintf(temp, "0o%o", v);
2769 wh.octVal = CopyString(temp);
2772 // WHATS THIS HERE ?
2773 if(exp.type == constantExp && exp.constant)
2774 wh.constant = CopyString(exp.constant);
2780 case symbolErrorExp:
2781 snprintf(watchmsg, sizeof(watchmsg), $"Symbol \"%s\" not found", exp.identifier.string);
2783 case structMemberSymbolErrorExp:
2784 // todo get info as in next case (ExpClassMemberSymbolError)
2785 snprintf(watchmsg, sizeof(watchmsg), $"Error: Struct member not found for \"%s\"", wh.expression);
2787 case classMemberSymbolErrorExp:
2790 Expression memberExp = exp.member.exp;
2791 Identifier memberID = exp.member.member;
2792 Type type = memberExp.expType;
2795 _class = (memberID && memberID.classSym) ? memberID.classSym.registered : ((type.kind == classType && type._class) ? type._class.registered : null);
2798 char string[256] = "";
2800 PrintTypeNoConst(type, string, false, true);
2801 classSym = FindClass(string);
2802 _class = classSym ? classSym.registered : null;
2805 snprintf(watchmsg, sizeof(watchmsg), $"Member \"%s\" not found in class \"%s\"", memberID ? memberID.string : "", _class.name);
2807 snprintf(watchmsg, sizeof(watchmsg), "Member \"%s\" not found in unregistered class? (Should never get this message)", memberID ? memberID.string : "");
2810 snprintf(watchmsg, sizeof(watchmsg), "Member \"%s\" not found in no type? (Should never get this message)", memberID ? memberID.string : "");
2813 case memoryErrorExp:
2814 // Need to ensure when set to memoryErrorExp, constant is set
2815 snprintf(watchmsg, sizeof(watchmsg), $"Memory can't be read at %s", /*(exp.type == constantExp) ? */exp.constant /*: null*/);
2817 case dereferenceErrorExp:
2818 snprintf(watchmsg, sizeof(watchmsg), $"Dereference failure for \"%s\"", wh.expression);
2820 case unknownErrorExp:
2821 snprintf(watchmsg, sizeof(watchmsg), $"Unknown error for \"%s\"", wh.expression);
2823 case noDebuggerErrorExp:
2824 snprintf(watchmsg, sizeof(watchmsg), $"Debugger required for symbol evaluation in \"%s\"", wh.expression);
2826 case debugStateErrorExp:
2827 snprintf(watchmsg, sizeof(watchmsg), $"Incorrect debugger state for symbol evaluation in \"%s\"", wh.expression);
2830 snprintf(watchmsg, sizeof(watchmsg), $"Null type for \"%s\"", wh.expression);
2834 // Temporary Code for displaying Strings
2835 if((exp.expType && ((exp.expType.kind == pointerType ||
2836 exp.expType.kind == arrayType) && exp.expType.type.kind == charType)) ||
2837 (wh.type && wh.type.kind == classType && wh.type._class &&
2838 wh.type._class.registered && wh.type._class.registered.type == normalClass &&
2839 !strcmp(wh.type._class.registered.name, "String")))
2842 if(exp.expType.kind != arrayType || exp.hasAddress)
2848 //char temp[MAX_F_STRING * 32];
2850 ExpressionType evalError = dummyExp;
2851 /*if(exp.expType.kind == arrayType)
2852 sprintf(temp, "(char*)0x%x", exp.address);
2854 sprintf(temp, "(char*)%s", exp.constant);*/
2856 //evaluation = Debugger::EvaluateExpression(temp, &evalError);
2857 // address = strtoul(exp.constant, null, 0);
2858 address = _strtoui64(exp.constant, null, 0);
2859 //_dpl(0, "0x", address);
2860 // snprintf(value, sizeof(value), "0x%08x ", address);
2862 if(address > 0xFFFFFFFFLL)
2863 snprintf(value, sizeof(value), (GetRuntimePlatform() == win32) ? "0x%016I64x " : "0x%016llx ", address);
2865 snprintf(value, sizeof(value), (GetRuntimePlatform() == win32) ? "0x%08I64x " : "0x%08llx ", address);
2866 value[sizeof(value)-1] = 0;
2869 strcat(value, $"Null string");
2873 len = strlen(value);
2875 while(!string && size > 2)
2877 string = GdbReadMemory(address, size);
2880 if(string && string[0])
2883 if(UTF8Validate(string))
2888 for(c = 0; (ch = string[c]) && c<4096; c++)
2891 value[len++] = '\0';
2896 ISO8859_1toUTF8(string, value + len, 4096 - len - 30);
2897 strcat(value, ") (ISO8859-1)");
2904 strcat(value, $"Empty string");
2908 strcat(value, $"Couldn't read memory");
2910 wh.value = CopyString(value);
2913 else if(wh.type && wh.type.kind == classType && wh.type._class &&
2914 wh.type._class.registered && wh.type._class.registered.type == enumClass)
2916 uint64 value = strtoul(exp.constant, null, 0);
2917 Class enumClass = eSystem_FindClass(GetPrivateModule(), wh.type._class.registered.name);
2918 EnumClassData enumeration = (EnumClassData)enumClass.data;
2920 for(item = enumeration.values.first; item; item = item.next)
2921 if((int)item.data == value)
2924 wh.value = CopyString(item.name);
2926 wh.value = CopyString($"Invalid Enum Value");
2929 else if(wh.type && (wh.type.kind == charType || (wh.type.kind == classType && wh.type._class &&
2930 wh.type._class.registered && !strcmp(wh.type._class.registered.fullName, "ecere::com::unichar"))) )
2937 if(exp.constant[0] == '\'')
2939 if((int)((byte *)exp.constant)[1] > 127)
2942 value = UTF8GetChar(exp.constant + 1, &nb);
2943 if(nb < 2) value = exp.constant[1];
2944 signedValue = value;
2948 signedValue = exp.constant[1];
2950 // Precomp Syntax error with boot strap here:
2951 byte b = (byte)(char)signedValue;
2952 value = (unichar) b;
2958 if(wh.type.kind == charType && wh.type.isSigned)
2960 signedValue = (int)(char)strtol(exp.constant, null, 0);
2962 // Precomp Syntax error with boot strap here:
2963 byte b = (byte)(char)signedValue;
2964 value = (unichar) b;
2969 value = (uint)strtoul(exp.constant, null, 0);
2970 signedValue = (int)value;
2974 UTF32toUTF8Len(&value, 1, charString, 5);
2976 snprintf(string, sizeof(string), "\'\\0' (0)");
2977 else if(value == '\t')
2978 snprintf(string, sizeof(string), "\'\\t' (%d)", value);
2979 else if(value == '\n')
2980 snprintf(string, sizeof(string), "\'\\n' (%d)", value);
2981 else if(value == '\r')
2982 snprintf(string, sizeof(string), "\'\\r' (%d)", value);
2983 else if(wh.type.kind == charType && wh.type.isSigned)
2984 snprintf(string, sizeof(string), "\'%s\' (%d)", charString, signedValue);
2985 else if(value > 256 || wh.type.kind != charType)
2987 if(value > 0x10FFFF || !GetCharCategory(value))
2988 snprintf(string, sizeof(string), $"Invalid Unicode Keypoint (0x%08X)", value);
2990 snprintf(string, sizeof(string), "\'%s\' (U+%04X)", charString, value);
2993 snprintf(string, sizeof(string), "\'%s\' (%d)", charString, value);
2994 string[sizeof(string)-1] = 0;
2996 wh.value = CopyString(string);
3001 wh.value = CopyString(exp.constant);
3008 wh.value = PrintHexUInt64(exp.address);
3013 char tempString[256];
3014 if(exp.member.memberType == propertyMember)
3015 snprintf(watchmsg, sizeof(watchmsg), $"Missing property evaluation support for \"%s\"", wh.expression);
3017 snprintf(watchmsg, sizeof(watchmsg), $"Evaluation failed for \"%s\" of type \"%s\"", wh.expression,
3018 exp.type.OnGetString(tempString, null, null));
3024 snprintf(watchmsg, sizeof(watchmsg), $"Invalid expression: \"%s\"", wh.expression);
3025 if(exp) FreeExpression(exp);
3028 SetPrivateModule(backupPrivateModule);
3029 SetCurrentContext(backupContext);
3030 SetTopContext(backupContext);
3031 SetGlobalContext(backupContext);
3032 SetThisClass(backupThisClass);
3035 // wh.value = CopyString("No source file found for selected frame");
3037 watchmsg[sizeof(watchmsg)-1] = 0;
3039 wh.value = CopyString(watchmsg);
3041 ide.watchesView.UpdateWatch(wh);
3045 void EvaluateWatches()
3047 _dpl2(_dpct, dplchan::debuggerWatches, 0, "Debugger::EvaluateWatches()");
3048 for(wh : ide.workspace.watches)
3052 char * ::GdbEvaluateExpression(char * expression)
3054 _dpl2(_dpct, dplchan::debuggerWatches, 0, "Debugger::GdbEvaluateExpression(", expression, ")");
3057 GdbCommand(false, "-data-evaluate-expression \"%s\"", expression);
3059 ide.outputView.debugBox.Logf("Debugger Error: GdbEvaluateExpression\n");
3063 // to be removed... use GdbReadMemory that returns a byte array instead
3064 char * ::GdbReadMemoryString(uint64 address, int size, char format, int rows, int cols)
3066 _dpl2(_dpct, dplchan::debuggerCall, 0, "Debugger::GdbReadMemoryString(", address, ")");
3071 _dpl(0, "GdbReadMemoryString called with size = 0!");
3073 // GdbCommand(false, "-data-read-memory 0x%08x %c, %d, %d, %d", address, format, size, rows, cols);
3074 if(GetRuntimePlatform() == win32)
3075 GdbCommand(false, "-data-read-memory 0x%016I64x %c, %d, %d, %d", address, format, size, rows, cols);
3077 GdbCommand(false, "-data-read-memory 0x%016llx %c, %d, %d, %d", address, format, size, rows, cols);
3079 ide.outputView.debugBox.Logf("Debugger Error: GdbReadMemoryString\n");
3083 byte * ::GdbReadMemory(uint64 address, int bytes)
3085 _dpl2(_dpct, dplchan::debuggerCall, 0, "Debugger::GdbReadMemory(", address, ")");
3088 //GdbCommand(false, "-data-read-memory 0x%08x %c, 1, 1, %d", address, 'u', bytes);
3089 if(GetRuntimePlatform() == win32)
3090 GdbCommand(false, "-data-read-memory 0x%016I64x %c, 1, 1, %d", address, 'u', bytes);
3092 GdbCommand(false, "-data-read-memory 0x%016llx %c, 1, 1, %d", address, 'u', bytes);
3095 _dpl(0, "GdbReadMemory called with bytes = 0!");
3098 ide.outputView.debugBox.Logf("Debugger Error: GdbReadMemory\n");
3099 else if(eval.result && strcmp(eval.result, "N/A"))
3101 byte * result = new byte[bytes];
3102 byte * string = eval.result;
3106 result[c++] = (byte)strtol(string, &string, 10);
3122 void BreakpointHit(GdbDataStop stopItem, Breakpoint bpInternal, Breakpoint bpUser)
3124 char * s1 = null; char * s2 = null;
3125 _dpl2(_dpct, dplchan::debuggerCall, 0, "Debugger::BreakpointHit(",
3126 "bpInternal(", bpInternal ? s1=bpInternal.CopyLocationString(false) : null, "), ",
3127 "bpUser(", bpUser ? s2=bpUser.CopyLocationString(false) : null, ")) -- ",
3128 "ignoreBreakpoints(", ignoreBreakpoints, "), ",
3129 "hitCursorBreakpoint(", bpUser && bpUser.type == runToCursor, ")");
3130 delete s1; delete s2;
3132 if(bpUser && stopItem.frame.line && bpUser.line != stopItem.frame.line)
3134 // updating user breakpoint on hit location difference
3135 // todo, print something?
3136 bpUser.line = stopItem.frame.line;
3137 ide.breakpointsView.UpdateBreakpoint(bpUser.row);
3138 ide.workspace.Save();
3143 if(bpInternal.type == internalModulesLoaded)
3145 if(!bpUser && !userBreakOnInternalBreakpoint)
3147 if(userAction == stepOut)//if(prevStopItem.reason == functionFinished)
3148 StepOut(ignoreBreakpoints);
3150 GdbExecContinue(false);
3155 bool conditionMet = true;
3156 if(bpUser.condition)
3157 conditionMet = ResolveWatch(bpUser.condition);
3159 if(!ignoreBreakpoints && (bpUser.level == -1 || bpUser.level == frameCount-1) && conditionMet)
3166 GdbExecContinue(false);
3170 GdbExecContinue(false);
3171 ide.breakpointsView.UpdateBreakpoint(bpUser.row);
3172 if(bpUser == bpRunToCursor)
3174 UnsetBreakpoint(bpUser);
3175 delete bpRunToCursor;
3179 if(!bpUser && !bpInternal)
3180 GdbExecContinue(false);
3183 void ValgrindTargetThreadExit()
3185 ide.outputView.debugBox.Logf($"ValgrindTargetThreadExit\n");
3188 vgTargetHandle.Wait();
3189 delete vgTargetHandle;
3191 HandleExit(null, null);
3194 void GdbThreadExit()
3196 _dpl2(_dpct, dplchan::debuggerCall, 0, "Debugger::GdbThreadExit()");
3197 if(state != terminated)
3199 _ChangeState(terminated);
3200 targetProcessId = 0;
3201 ClearBreakDisplay();
3207 serialSemaphore.Release();
3212 ide.outputView.debugBox.Logf($"Debugger Fatal Error: GDB lost\n");
3213 ide.outputView.debugBox.Logf($"Debugging stopped\n");
3215 HideDebuggerViews();
3217 //_ChangeState(terminated);
3221 void GdbThreadMain(char * output)
3224 Array<char *> outTokens { minAllocSize = 50 };
3225 Array<char *> subTokens { minAllocSize = 50 };
3226 DebugListItem item { };
3227 DebugListItem item2 { };
3228 bool setWaitingForPID = false;
3230 #if defined(GDB_DEBUG_CONSOLE) || defined(GDB_DEBUG_GUI)
3231 #ifdef GDB_DEBUG_CONSOLE
3232 _dpl2(_dpct, dplchan::gdbOutput, 0, output);
3234 #ifdef GDB_DEBUG_OUTPUT
3236 int len = strlen(output);
3244 for(c = 0; c < len / 1024; c++)
3246 strncpy(tmp, start, 1024);
3247 ide.outputView.gdbBox.Logf("out: %s\n", tmp);
3250 ide.outputView.gdbBox.Logf("out: %s\n", start);
3254 ide.outputView.gdbBox.Logf("out: %s\n", output);
3258 #ifdef GDB_DEBUG_CONSOLE
3259 strcpy(lastGdbOutput, output);
3261 #ifdef GDB_DEBUG_GUI
3262 if(ide.gdbDialog) ide.gdbDialog.AddOutput(output);
3269 if(strstr(output, "No debugging symbols found") || strstr(output, "(no debugging symbols found)"))
3272 ide.outputView.debugBox.Logf($"Target doesn't contain debug information!\n");
3278 if(TokenizeList(output, ',', outTokens) && !strcmp(outTokens[0], "^done"))
3280 //if(outTokens.count == 1)
3285 _ChangeState(loaded);
3286 targetProcessId = 0;
3287 if(outTokens.count > 1 && TokenizeListItem(outTokens[1], item))
3289 if(!strcmp(item.name, "reason"))
3291 char * reason = item.value;
3292 StripQuotes(reason, reason);
3293 if(!strcmp(reason, "exited-normally") || !strcmp(reason, "exited") || !strcmp(reason, "exited-signalled"))
3296 if(outTokens.count > 2 && TokenizeListItem(outTokens[2], item2))
3298 StripQuotes(item2.value, item2.value);
3299 if(!strcmp(item2.name, "exit-code"))
3300 exitCode = item2.value;
3306 HandleExit(reason, exitCode);
3310 _dpl2(_dpct, dplchan::gdbProtoUnknown, 0, "kill reply (", item.name, "=", item.value, ") is unheard of");
3313 HandleExit(null, null);
3316 if(outTokens.count > 1 && TokenizeListItem(outTokens[1], item))
3318 if(!strcmp(item.name, "bkpt"))
3320 sentBreakInsert = false;
3325 bpItem = ParseBreakpoint(item.value, outTokens);
3326 //breakType = bpValidation;
3328 else if(!strcmp(item.name, "depth"))
3330 StripQuotes(item.value, item.value);
3331 frameCount = atoi(item.value);
3333 stackFrames.Free(Frame::Free);
3335 else if(!strcmp(item.name, "stack"))
3338 if(stackFrames.count)
3339 ide.callStackView.Logf("...\n");
3342 item.value = StripBrackets(item.value);
3343 TokenizeList(item.value, ',', subTokens);
3344 for(i = 0; i < subTokens.count; i++)
3346 if(TokenizeListItem(subTokens[i], item))
3348 if(!strcmp(item.name, "frame"))
3351 stackFrames.Add(frame);
3352 item.value = StripCurlies(item.value);
3353 ParseFrame(frame, item.value);
3354 if(frame.file && frame.from)
3355 _dpl2(_dpct, dplchan::gdbProtoUnknown, 0, "unexpected frame file and from members present");
3359 if(activeFrameLevel == -1)
3361 if(ide.projectView.IsModuleInProject(frame.file));
3363 if(frame.level != 0)
3365 //stopItem.frame = frame;
3366 breakType = selectFrame;
3369 activeFrame = frame;
3370 activeFrameLevel = frame.level;
3373 ide.callStackView.Logf("%3d ", frame.level);
3374 if(!strncmp(frame.func, "__ecereMethod_", strlen("__ecereMethod_")))
3375 ide.callStackView.Logf($"%s Method, %s:%d\n", &frame.func[strlen("__ecereMethod_")], (s = CopySystemPath(frame.file)), frame.line);
3376 else if(!strncmp(frame.func, "__ecereProp_", strlen("__ecereProp_")))
3377 ide.callStackView.Logf($"%s Property, %s:%d\n", &frame.func[strlen("__ecereProp_")], (s = CopySystemPath(frame.file)), frame.line);
3378 else if(!strncmp(frame.func, "__ecereConstructor_", strlen("__ecereConstructor_")))
3379 ide.callStackView.Logf($"%s Constructor, %s:%d\n", &frame.func[strlen("__ecereConstructor_")], (s = CopySystemPath(frame.file)), frame.line);
3380 else if(!strncmp(frame.func, "__ecereDestructor_", strlen("__ecereDestructor_")))
3381 ide.callStackView.Logf($"%s Destructor, %s:%d\n", &frame.func[strlen("__ecereDestructor_")], (s = CopySystemPath(frame.file)), frame.line);
3383 ide.callStackView.Logf($"%s Function, %s:%d\n", frame.func, (s = CopySystemPath(frame.file)), frame.line);
3388 ide.callStackView.Logf("%3d ", frame.level);
3393 ide.callStackView.Logf($"inside %s, %s\n", frame.func, (s = CopySystemPath(frame.from)));
3397 ide.callStackView.Logf("%s\n", frame.func);
3399 ide.callStackView.Logf($"unknown source\n");
3403 _dpl2(_dpct, dplchan::gdbProtoUnknown, 0, "stack content (", item.name, "=", item.value, ") is unheard of");
3406 if(activeFrameLevel == -1)
3408 activeFrameLevel = 0;
3409 activeFrame = stackFrames.first;
3411 ide.callStackView.Home();
3413 subTokens.RemoveAll();
3415 /*else if(!strcmp(item.name, "frame"))
3418 item.value = StripCurlies(item.value);
3419 ParseFrame(&frame, item.value);
3421 else if(!strcmp(item.name, "thread-ids"))
3423 ide.threadsView.Clear();
3424 item.value = StripCurlies(item.value);
3425 TokenizeList(item.value, ',', subTokens);
3426 for(i = subTokens.count - 1; ; i--)
3428 if(TokenizeListItem(subTokens[i], item))
3430 if(!strcmp(item.name, "thread-id"))
3433 StripQuotes(item.value, item.value);
3434 value = atoi(item.value);
3435 ide.threadsView.Logf("%3d \n", value);
3438 _dpl2(_dpct, dplchan::gdbProtoUnknown, 0, "threads content (", item.name, "=", item.value, ") is unheard of");
3443 ide.threadsView.Home();
3445 subTokens.RemoveAll();
3446 //if(!strcmp(outTokens[2], "number-of-threads"))
3448 else if(!strcmp(item.name, "new-thread-id"))
3450 StripQuotes(item.value, item.value);
3451 activeThread = atoi(item.value);
3453 else if(!strcmp(item.name, "value"))
3455 StripQuotes(item.value, item.value);
3456 eval.result = CopyString(item.value);
3457 eval.active = false;
3459 else if(!strcmp(item.name, "addr"))
3461 for(i = 2; i < outTokens.count; i++)
3463 if(TokenizeListItem(outTokens[i], item))
3465 if(!strcmp(item.name, "total-bytes"))
3467 StripQuotes(item.value, item.value);
3468 eval.bytes = atoi(item.value);
3470 else if(!strcmp(item.name, "next-row"))
3472 StripQuotes(item.value, item.value);
3473 eval.nextBlockAddress = _strtoui64(item.value, null, 0);
3475 else if(!strcmp(item.name, "memory"))
3479 //StripQuotes(item.value, item.value);
3480 item.value = StripBrackets(item.value);
3481 // this should be treated as a list...
3482 item.value = StripCurlies(item.value);
3483 TokenizeList(item.value, ',', subTokens);
3484 for(j = 0; j < subTokens.count; j++)
3486 if(TokenizeListItem(subTokens[j], item))
3488 if(!strcmp(item.name, "data"))
3490 item.value = StripBrackets(item.value);
3491 StripQuotes2(item.value, item.value);
3492 eval.result = CopyString(item.value);
3493 eval.active = false;
3497 subTokens.RemoveAll();
3502 else if(!strcmp(item.name, "source-path") || !strcmp(item.name, "BreakpointTable"))
3503 _dpl2(_dpct, dplchan::gdbProtoIgnored, 0, "command reply (", item.name, "=", item.value, ") is ignored");
3505 _dpl2(_dpct, dplchan::gdbProtoUnknown, 0, "command reply (", item.name, "=", item.value, ") is unheard of");
3508 else if(!strcmp(outTokens[0], "^running"))
3510 waitingForPID = true;
3511 setWaitingForPID = true;
3512 ClearBreakDisplay();
3514 else if(!strcmp(outTokens[0], "^exit"))
3516 _ChangeState(terminated);
3517 // ide.outputView.debugBox.Logf("Exit\n");
3518 // ide.Update(null);
3520 serialSemaphore.Release();
3522 else if(!strcmp(outTokens[0], "^error"))
3526 sentBreakInsert = false;
3527 breakpointError = true;
3530 if(outTokens.count > 1 && TokenizeListItem(outTokens[1], item))
3532 if(!strcmp(item.name, "msg"))
3534 StripQuotes(item.value, item.value);
3537 eval.active = false;
3539 if(strstr(item.value, "No symbol") && strstr(item.value, "in current context"))
3540 eval.error = symbolNotFound;
3541 else if(strstr(item.value, "Cannot access memory at address"))
3542 eval.error = memoryCantBeRead;
3544 eval.error = unknown;
3546 else if(!strcmp(item.value, "Previous frame inner to this frame (corrupt stack?)"))
3549 else if(!strncmp(item.value, "Cannot access memory at address", 31))
3552 else if(!strcmp(item.value, "Cannot find bounds of current function"))
3554 _ChangeState(stopped);
3555 gdbHandle.Printf("-exec-continue\n");
3557 else if(!strcmp(item.value, "ptrace: No such process."))
3559 _ChangeState(loaded);
3560 targetProcessId = 0;
3562 else if(!strcmp(item.value, "Function \\\"WinMain\\\" not defined."))
3565 else if(!strcmp(item.value, "You can't do that without a process to debug."))
3567 _ChangeState(loaded);
3568 targetProcessId = 0;
3570 else if(strstr(item.value, "No such file or directory."))
3572 _ChangeState(loaded);
3573 targetProcessId = 0;
3575 else if(strstr(item.value, "During startup program exited with code "))
3577 _ChangeState(loaded);
3578 targetProcessId = 0;
3583 if(strlen(item.value) < MAX_F_STRING)
3586 ide.outputView.debugBox.Logf("GDB: %s\n", (s = CopyUnescapedString(item.value)));
3590 ide.outputView.debugBox.Logf("GDB: %s\n", item.value);
3596 _dpl2(_dpct, dplchan::gdbProtoUnknown, 0, "error content (", item.name, "=", item.value, ") is unheard of");
3599 _dpl2(_dpct, dplchan::gdbProtoUnknown, 0, "result-record: ", outTokens[0]);
3600 outTokens.RemoveAll();
3603 _dpl2(_dpct, dplchan::gdbProtoUnknown, 0, "status-async-output: ", outTokens[0]);
3606 if(TokenizeList(output, ',', outTokens))
3608 if(!strcmp(outTokens[0], "=library-loaded"))
3609 FGODetectLoadedLibraryForAddedProjectIssues(outTokens);
3610 else if(!strcmp(outTokens[0], "=thread-group-created") || !strcmp(outTokens[0], "=thread-group-added") ||
3611 !strcmp(outTokens[0], "=thread-group-started") || !strcmp(outTokens[0], "=thread-group-exited") ||
3612 !strcmp(outTokens[0], "=thread-created") || !strcmp(outTokens[0], "=thread-exited") ||
3613 !strcmp(outTokens[0], "=cmd-param-changed") || !strcmp(outTokens[0], "=library-unloaded") ||
3614 !strcmp(outTokens[0], "=breakpoint-modified"))
3615 _dpl2(_dpct, dplchan::gdbProtoIgnored, 0, outTokens[0], outTokens.count>1 ? outTokens[1] : "",
3616 outTokens.count>2 ? outTokens[2] : "", outTokens.count>3 ? outTokens[3] : "",
3617 outTokens.count>4 ? outTokens[4] : "", outTokens.count>5 ? outTokens[5] : "",
3618 outTokens.count>6 ? outTokens[6] : "", outTokens.count>7 ? outTokens[7] : "",
3619 outTokens.count>8 ? outTokens[8] : "", outTokens.count>9 ? outTokens[9] : "");
3621 _dpl2(_dpct, dplchan::gdbProtoUnknown, 0, "notify-async-output: ", outTokens[0]);
3623 outTokens.RemoveAll();
3627 if(TokenizeList(output, ',', outTokens))
3629 if(!strcmp(outTokens[0],"*running"))
3631 waitingForPID = true;
3632 setWaitingForPID = true;
3634 else if(!strcmp(outTokens[0], "*stopped"))
3637 _ChangeState(stopped);
3639 for(tk = 1; tk < outTokens.count; tk++)
3641 if(TokenizeListItem(outTokens[tk], item))
3643 if(!strcmp(item.name, "reason"))
3645 char * reason = item.value;
3646 StripQuotes(reason, reason);
3647 if(!strcmp(reason, "exited-normally") || !strcmp(reason, "exited") || !strcmp(reason, "exited-signalled"))
3650 if(outTokens.count > tk+1 && TokenizeListItem(outTokens[tk+1], item2))
3653 StripQuotes(item2.value, item2.value);
3654 if(!strcmp(item2.name, "exit-code"))
3655 exitCode = item2.value;
3661 HandleExit(reason, exitCode);
3664 else if(!strcmp(reason, "breakpoint-hit"))
3670 stopItem = GdbDataStop { };
3671 stopItem.reason = breakpointHit;
3673 for(i = tk+1; i < outTokens.count; i++)
3675 TokenizeListItem(outTokens[i], item);
3676 StripQuotes(item.value, item.value);
3677 if(!strcmp(item.name, "bkptno"))
3678 stopItem.bkptno = atoi(item.value);
3679 else if(!strcmp(item.name, "thread-id"))
3680 stopItem.threadid = atoi(item.value);
3681 else if(!strcmp(item.name, "frame"))
3683 item.value = StripCurlies(item.value);
3684 ParseFrame(stopItem.frame, item.value);
3686 else if(!strcmp(item.name, "disp") || !strcmp(item.name, "stopped-threads") || !strcmp(item.name, "core"))
3687 _dpl2(_dpct, dplchan::gdbProtoIgnored, 0, "(", item.name, "=", item.value, ")");
3689 _dpl2(_dpct, dplchan::gdbProtoUnknown, 0, "Unknown breakpoint hit item name (", item.name, "=", item.value, ")");
3694 else if(!strcmp(reason, "end-stepping-range"))
3700 stopItem = GdbDataStop { };
3701 stopItem.reason = endSteppingRange;
3703 for(i = tk+1; i < outTokens.count; i++)
3705 TokenizeListItem(outTokens[i], item);
3706 StripQuotes(item.value, item.value);
3707 if(!strcmp(item.name, "thread-id"))
3708 stopItem.threadid = atoi(item.value);
3709 else if(!strcmp(item.name, "frame"))
3711 item.value = StripCurlies(item.value);
3712 ParseFrame(stopItem.frame, item.value);
3714 else if(!strcmp(item.name, "reason") || !strcmp(item.name, "bkptno"))
3715 _dpl2(_dpct, dplchan::gdbProtoIgnored, 0, "(", item.name, "=", item.value, ")");
3717 _dpl2(_dpct, dplchan::gdbProtoUnknown, 0, "Unknown end of stepping range item name (", item.name, "=", item.value, ")");
3723 else if(!strcmp(reason, "function-finished"))
3729 stopItem = GdbDataStop { };
3730 stopItem.reason = functionFinished;
3732 for(i = tk+1; i < outTokens.count; i++)
3734 TokenizeListItem(outTokens[i], item);
3735 StripQuotes(item.value, item.value);
3736 if(!strcmp(item.name, "thread-id"))
3737 stopItem.threadid = atoi(item.value);
3738 else if(!strcmp(item.name, "frame"))
3740 item.value = StripCurlies(item.value);
3741 ParseFrame(stopItem.frame, item.value);
3743 else if(!strcmp(item.name, "gdb-result-var"))
3744 stopItem.gdbResultVar = CopyString(item.value);
3745 else if(!strcmp(item.name, "return-value"))
3746 stopItem.returnValue = CopyString(item.value);
3748 _dpl2(_dpct, dplchan::gdbProtoUnknown, 0, "Unknown function finished item name (", item.name, "=", item.value, ")");
3751 event = functionEnd;
3754 else if(!strcmp(reason, "signal-received"))
3760 stopItem = GdbDataStop { };
3761 stopItem.reason = signalReceived;
3763 for(i = tk+1; i < outTokens.count; i++)
3765 TokenizeListItem(outTokens[i], item);
3766 StripQuotes(item.value, item.value);
3767 if(!strcmp(item.name, "signal-name"))
3768 stopItem.name = CopyString(item.value);
3769 else if(!strcmp(item.name, "signal-meaning"))
3770 stopItem.meaning = CopyString(item.value);
3771 else if(!strcmp(item.name, "thread-id"))
3772 stopItem.threadid = atoi(item.value);
3773 else if(!strcmp(item.name, "frame"))
3775 item.value = StripCurlies(item.value);
3776 ParseFrame(stopItem.frame, item.value);
3779 _dpl2(_dpct, dplchan::gdbProtoUnknown, 0, "Unknown signal reveived item name (", item.name, "=", item.value, ")");
3781 if(!strcmp(stopItem.name, "SIGTRAP"))
3800 else if(!strcmp(reason, "watchpoint-trigger"))
3801 _dpl2(_dpct, dplchan::gdbProtoIgnored, 0, "Reason watchpoint trigger not handled");
3802 else if(!strcmp(reason, "read-watchpoint-trigger"))
3803 _dpl2(_dpct, dplchan::gdbProtoIgnored, 0, "Reason read watchpoint trigger not handled");
3804 else if(!strcmp(reason, "access-watchpoint-trigger"))
3805 _dpl2(_dpct, dplchan::gdbProtoIgnored, 0, "Reason access watchpoint trigger not handled");
3806 else if(!strcmp(reason, "watchpoint-scope"))
3807 _dpl2(_dpct, dplchan::gdbProtoIgnored, 0, "Reason watchpoint scope not handled");
3808 else if(!strcmp(reason, "location-reached"))
3809 _dpl2(_dpct, dplchan::gdbProtoIgnored, 0, "Reason location reached not handled");
3811 _dpl2(_dpct, dplchan::gdbProtoUnknown, 0, "Unknown reason: ", reason);
3819 if(usingValgrind && event == none && !stopItem)
3820 event = valgrindStartPause;
3825 _dpl2(_dpct, dplchan::gdbProtoUnknown, 0, "Unknown exec-async-output: ", outTokens[0]);
3826 outTokens.RemoveAll();
3829 if(!strcmpi(output, "(gdb) "))
3833 char exeFile[MAX_LOCATION];
3834 int oldProcessID = targetProcessId;
3835 GetLastDirectory(targetFile, exeFile);
3837 while(!targetProcessId/*true*/)
3839 targetProcessId = Process_GetChildExeProcessId(gdbProcessId, exeFile);
3840 if(targetProcessId || gdbHandle.Peek()) break;
3845 _ChangeState(running);
3846 else if(!oldProcessID)
3848 ide.outputView.debugBox.Logf($"Debugger Error: No target process ID\n");
3849 // TO VERIFY: The rest of this block has not been thoroughly tested in this particular location
3850 gdbHandle.Printf("-gdb-exit\n");
3852 _ChangeState(terminated); //loaded;
3857 for(bp : ide.workspace.breakpoints)
3858 bp.inserted = false;
3861 bp.inserted = false;
3863 bpRunToCursor.inserted = false;
3865 ide.outputView.debugBox.Logf($"Debugging stopped\n");
3866 ClearBreakDisplay();
3868 #if defined(__unix__)
3869 if(!usingValgrind && FileExists(progFifoPath)) //fileCreated)
3871 progThread.terminate = true;
3874 fifoFile.CloseInput();
3881 DeleteFile(progFifoPath);
3882 progFifoPath[0] = '\0';
3889 serialSemaphore.Release();
3892 _dpl2(_dpct, dplchan::gdbProtoUnknown, 0, $"Unknown prompt", output);
3896 if(!strncmp(output, "&\"warning:", 10))
3899 content = strstr(output, "\"");
3900 StripQuotes(content, content);
3901 content = strstr(content, ":");
3907 ide.outputView.debugBox.LogRaw((s = CopyUnescapedString(content)));
3914 _dpl2(_dpct, dplchan::gdbProtoUnknown, 0, $"Unknown output: ", output);
3916 if(!setWaitingForPID)
3917 waitingForPID = false;
3918 setWaitingForPID = false;
3926 // From GDB Output functions
3927 void FGODetectLoadedLibraryForAddedProjectIssues(Array<char *> outTokens)
3929 char path[MAX_LOCATION] = "";
3930 char file[MAX_FILENAME] = "";
3932 DebugListItem item { };
3933 //_dpl2(_dpct, dplchan::debuggerCall, 0, "Debugger::FGODetectLoadedLibraryForAddedProjectIssues()");
3934 for(token : outTokens)
3936 if(TokenizeListItem(token, item))
3938 if(!strcmp(item.name, "target-name"))
3940 StripQuotes(item.value, path);
3941 MakeSystemPath(path);
3942 GetLastDirectory(path, file);
3944 else if(!strcmp(item.name, "symbols-loaded"))
3946 symbolsLoaded = (atoi(item.value) == 1);
3951 if(path[0] && file[0])
3953 for(prj : ide.workspace.projects; prj != ide.workspace.projects.firstIterator.data)
3957 char prjTargetPath[MAX_LOCATION];
3958 char prjTargetFile[MAX_FILENAME];
3959 DirExpression targetDirExp = prj.GetTargetDir(currentCompiler, prj.config, bitDepth);
3960 strcpy(prjTargetPath, prj.topNode.path);
3961 PathCat(prjTargetPath, targetDirExp.dir);
3962 prjTargetFile[0] = '\0';
3963 prj.CatTargetFileName(prjTargetFile, currentCompiler, prj.config);
3964 PathCat(prjTargetPath, prjTargetFile);
3965 MakeSystemPath(prjTargetPath);
3967 match = !fstrcmp(prjTargetFile, file);
3968 if(!match && (dot = strstr(prjTargetFile, ".so.")))
3970 char * dot3 = strstr(dot+4, ".");
3974 match = !fstrcmp(prjTargetFile, file);
3979 match = !fstrcmp(prjTargetFile, file);
3984 // TODO: nice visual feedback to better warn user. use some ide notification system or other means.
3985 /* -- this is disabled because we can't trust gdb's symbols-loaded="0" field for =library-loaded (http://sourceware.org/bugzilla/show_bug.cgi?id=10693)
3987 ide.outputView.debugBox.Logf($"Attention! No symbols for loaded library %s matched to the %s added project.\n", path, prj.topNode.name);
3989 match = !fstrcmp(prjTargetPath, path);
3990 if(!match && (dot = strstr(prjTargetPath, ".so.")))
3992 char * dot3 = strstr(dot+4, ".");
3996 match = !fstrcmp(prjTargetPath, path);
4001 match = !fstrcmp(prjTargetPath, path);
4005 ide.outputView.debugBox.Logf($"Loaded library %s doesn't match the %s target of the %s added project.\n", path, prjTargetPath, prj.topNode.name);
4012 void FGOBreakpointModified(Array<char *> outTokens)
4014 _dpl2(_dpct, dplchan::debuggerCall, 0, "Debugger::FGOBreakpointModified() -- TODO only if needed: support breakpoint modified");
4016 DebugListItem item { };
4017 if(outTokens.count > 1 && TokenizeListItem(outTokens[1], item))
4019 if(!strcmp(item.name, "bkpt"))
4021 GdbDataBreakpoint modBp = ParseBreakpoint(item.value, outTokens);
4029 ExpressionType ::DebugEvalExpTypeError(char * result)
4031 _dpl2(_dpct, dplchan::debuggerWatches, 0, "Debugger::DebugEvalExpTypeError()");
4036 case symbolNotFound:
4037 return symbolErrorExp;
4038 case memoryCantBeRead:
4039 return memoryErrorExp;
4041 return unknownErrorExp;
4044 char * ::EvaluateExpression(char * expression, ExpressionType * error)
4047 _dpl2(_dpct, dplchan::debuggerWatches, 0, "Debugger::EvaluateExpression(", expression, ")");
4048 if(ide.projectView && ide.debugger.state == stopped)
4050 result = GdbEvaluateExpression(expression);
4051 *error = DebugEvalExpTypeError(result);
4056 *error = noDebuggerErrorExp;
4061 char * ::ReadMemory(uint64 address, int size, char format, ExpressionType * error)
4064 char * result = GdbReadMemoryString(address, size, format, 1, 1);
4065 _dpl2(_dpct, dplchan::debuggerCall, 0, "Debugger::ReadMemory(", address, ")");
4066 if(!result || !strcmp(result, "N/A"))
4067 *error = memoryErrorExp;
4069 *error = DebugEvalExpTypeError(result);
4074 class ValgrindLogThread : Thread
4080 static char output[4096];
4081 Array<char> dynamicBuffer { minAllocSize = 4096 };
4082 File oldValgrindHandle = vgLogFile;
4083 incref oldValgrindHandle;
4086 while(debugger.state != terminated && vgLogFile)
4090 result = vgLogFile.Read(output, 1, sizeof(output));
4092 if(debugger.state == terminated || !vgLogFile/* || vgLogFile.Eof()*/)
4099 for(c = 0; c<result; c++)
4101 if(output[c] == '\n')
4103 int pos = dynamicBuffer.size;
4104 dynamicBuffer.size += c - start;
4105 memcpy(&dynamicBuffer[pos], output + start, c - start);
4106 if(dynamicBuffer.count && dynamicBuffer[dynamicBuffer.count - 1] != '\r')
4107 // COMMENTED OUT DUE TO ISSUE #135, FIXED
4108 //if(dynamicBuffer.array[dynamicBuffer.count - 1] != '\r')
4109 dynamicBuffer.size++;
4110 dynamicBuffer[dynamicBuffer.count - 1] = '\0';
4112 // printf("%s\n", dynamicBuffer.array);
4114 if(strstr(&dynamicBuffer[0], "vgdb me"))
4115 debugger.serialSemaphore.Release();
4116 ide.outputView.debugBox.Logf("%s\n", &dynamicBuffer[0]);
4117 dynamicBuffer.size = 0;
4123 int pos = dynamicBuffer.size;
4124 dynamicBuffer.size += c - start;
4125 memcpy(&dynamicBuffer[pos], output + start, c - start);
4128 else if(debugger.state == stopped)
4131 printf("Got end of file from GDB!\n");
4138 delete dynamicBuffer;
4139 ide.outputView.debugBox.Logf($"ValgrindLogThreadExit\n");
4140 //if(oldValgrindHandle == vgLogFile)
4141 debugger.GdbThreadExit/*ValgrindLogThreadExit*/();
4142 delete oldValgrindHandle;
4148 class ValgrindTargetThread : Thread
4154 static char output[4096];
4155 Array<char> dynamicBuffer { minAllocSize = 4096 };
4156 DualPipe oldValgrindHandle = vgTargetHandle;
4157 incref oldValgrindHandle;
4160 while(debugger.state != terminated && vgTargetHandle && !vgTargetHandle.Eof())
4164 result = vgTargetHandle.Read(output, 1, sizeof(output));
4166 if(debugger.state == terminated || !vgTargetHandle || vgTargetHandle.Eof())
4173 for(c = 0; c<result; c++)
4175 if(output[c] == '\n')
4177 int pos = dynamicBuffer.size;
4178 dynamicBuffer.size += c - start;
4179 memcpy(&dynamicBuffer[pos], output + start, c - start);
4180 if(dynamicBuffer.count && dynamicBuffer[dynamicBuffer.count - 1] != '\r')
4181 // COMMENTED OUT DUE TO ISSUE #135, FIXED
4182 //if(dynamicBuffer.array[dynamicBuffer.count - 1] != '\r')
4183 dynamicBuffer.size++;
4184 dynamicBuffer[dynamicBuffer.count - 1] = '\0';
4186 // printf("%s\n", dynamicBuffer.array);
4188 ide.outputView.debugBox.Logf("%s\n", &dynamicBuffer[0]);
4190 dynamicBuffer.size = 0;
4196 int pos = dynamicBuffer.size;
4197 dynamicBuffer.size += c - start;
4198 memcpy(&dynamicBuffer[pos], output + start, c - start);
4204 printf("Got end of file from GDB!\n");
4208 delete dynamicBuffer;
4209 //if(oldValgrindHandle == vgTargetHandle)
4210 debugger.ValgrindTargetThreadExit();
4211 delete oldValgrindHandle;
4217 class GdbThread : Thread
4223 static char output[4096];
4224 Array<char> dynamicBuffer { minAllocSize = 4096 };
4225 DualPipe oldGdbHandle = gdbHandle;
4226 incref oldGdbHandle;
4229 while(debugger.state != terminated && gdbHandle && !gdbHandle.Eof())
4233 result = gdbHandle.Read(output, 1, sizeof(output));
4235 if(debugger.state == terminated || !gdbHandle || gdbHandle.Eof())
4242 for(c = 0; c<result; c++)
4244 if(output[c] == '\n')
4246 int pos = dynamicBuffer.size;
4247 dynamicBuffer.size += c - start;
4248 memcpy(&dynamicBuffer[pos], output + start, c - start);
4249 if(dynamicBuffer.count && dynamicBuffer[dynamicBuffer.count - 1] != '\r')
4250 // COMMENTED OUT DUE TO ISSUE #135, FIXED
4251 //if(dynamicBuffer.array[dynamicBuffer.count - 1] != '\r')
4252 dynamicBuffer.size++;
4253 dynamicBuffer[dynamicBuffer.count - 1] = '\0';
4255 // _dpl(0, dynamicBuffer.array);
4257 debugger.GdbThreadMain(&dynamicBuffer[0]);
4258 dynamicBuffer.size = 0;
4264 int pos = dynamicBuffer.size;
4265 dynamicBuffer.size += c - start;
4266 memcpy(&dynamicBuffer[pos], output + start, c - start);
4272 _dpl(0, "Got end of file from GDB!");
4276 delete dynamicBuffer;
4277 //if(oldGdbHandle == gdbHandle)
4278 debugger.GdbThreadExit();
4279 delete oldGdbHandle;
4285 static define createFIFOMsg = $"err: Unable to create FIFO %s\n";
4286 static define openFIFOMsg = $"err: Unable to open FIFO %s for read\n";
4288 #if defined(__unix__)
4293 #include <sys/types.h>
4298 class ProgramThread : Thread
4304 bool fileCreated = false;
4306 static char output[1000];
4309 /*if(!mkfifo(progFifoPath, mask))
4316 ide.outputView.debugBox.Logf($"err: Unable to create FIFO %s\n", progFifoPath);
4320 if(FileExists(progFifoPath)) //fileCreated)
4322 fifoFile = FileOpen(progFifoPath, read);
4326 ide.outputView.debugBox.Logf(openFIFOMsg, progFifoPath);
4331 fd = fileno((FILE *)fifoFile.input);
4332 //fcntl(fd, F_SETFL, fcntl(fd, F_GETFL) | O_NONBLOCK);
4336 while(!terminate && fifoFile && !fifoFile.Eof())
4339 struct timeval time;
4347 selectResult = select(fd + 1, &rs, null, null, &time);
4348 if(FD_ISSET(fd, &rs))
4350 int result = (int)read(fd, output, sizeof(output)-1);
4351 if(!result || (result < 0 && errno != EAGAIN))
4355 output[result] = '\0';
4356 if(strcmp(output,"&\"warning: GDB: Failed to set controlling terminal: Invalid argument\\n\"\n"))
4359 ide.outputView.debugBox.Log(output);
4368 //fifoFile.CloseInput();
4371 ide.outputView.debugBox.Log("\n");
4375 if(FileExists(progFifoPath)) //fileCreated)
4377 DeleteFile(progFifoPath);
4378 progFifoPath[0] = '\0';
4386 class Argument : struct
4388 Argument prev, next;
4390 property char * name { set { delete name; if(value) name = CopyString(value); } }
4392 property char * val { set { delete val; if(value) val = CopyString(value); } }
4406 class Frame : struct
4411 property char * addr { set { delete addr; if(value) addr = CopyString(value); } }
4413 property char * func { set { delete func; if(value) func = CopyString(value); } }
4417 property char * from { set { delete from; if(value) from = CopyUnescapedUnixPath(value); } }
4419 property char * file { set { delete file; if(value) file = CopyUnescapedUnixPath(value); } }
4420 char * absoluteFile;
4421 property char * absoluteFile { set { delete absoluteFile; if(value) absoluteFile = CopyUnescapedUnixPath(value); } }
4430 delete absoluteFile;
4431 args.Free(Argument::Free);
4440 class GdbDataStop : struct
4442 DebuggerReason reason;
4457 char * gdbResultVar;
4467 if(reason == signalReceived)
4472 else if(reason == functionFinished)
4474 delete gdbResultVar;
4478 if(frame) frame.Free();
4487 class GdbDataBreakpoint : struct
4491 property char * number { set { delete number; if(value) number = CopyString(value); } }
4493 property char * type { set { delete type; if(value) type = CopyString(value); } }
4495 property char * disp { set { delete disp; if(value) disp = CopyString(value); } }
4498 property char * addr { set { delete addr; if(value) addr = CopyString(value); } }
4500 property char * func { set { delete func; if(value) func = CopyString(value); } }
4502 property char * file { set { delete file; if(value) file = CopyUnescapedUnixPath(value); } }
4504 property char * fullname { set { delete fullname; if(value) fullname = CopyUnescapedUnixPath(value); } }
4507 property char * at { set { delete at; if(value) at = CopyString(value); } }
4510 Array<GdbDataBreakpoint> multipleBPs;
4515 PrintLn("{", "#", number, " T", type, " D", disp, " E", enabled, " H", times, " (", func, ") (", file, ":", line, ") (", fullname, ") (", addr, ") (", at, ")", "}");
4526 if(multipleBPs) multipleBPs.Free();
4530 ~GdbDataBreakpoint()
4536 class Breakpoint : struct
4541 property char * function { set { delete function; if(value) function = CopyString(value); } }
4542 char * relativeFilePath;
4543 property char * relativeFilePath { set { delete relativeFilePath; if(value) relativeFilePath = CopyString(value); } }
4544 char * absoluteFilePath;
4545 property char * absoluteFilePath { set { delete absoluteFilePath; if(value) absoluteFilePath = CopyString(value); } }
4554 BreakpointType type;
4556 GdbDataBreakpoint bp;
4558 char * CopyLocationString(bool removePath)
4561 char * file = relativeFilePath ? relativeFilePath : absoluteFilePath;
4562 bool removingPath = removePath && file;
4565 char * fileName = new char[MAX_FILENAME];
4566 GetLastDirectory(file, fileName);
4572 location = PrintString(file, ":", function);
4574 location = CopyString(function);
4577 location = PrintString(file, ":", line);
4583 char * CopyUserLocationString()
4586 char * loc = CopyLocationString(false);
4588 for(p : ide.workspace.projects)
4590 if(p.topNode.FindByFullPath(absoluteFilePath, false))
4598 location = PrintString("(", prj.name, ")", loc);
4608 if(relativeFilePath && relativeFilePath[0])
4610 f.Printf(" * %d,%d,%d,%d,%s\n", enabled ? 1 : 0, ignore, level, line, relativeFilePath);
4612 f.Printf(" ~ %s\n", condition.expression);
4622 delete relativeFilePath;
4623 delete absoluteFilePath;
4633 class Watch : struct
4644 f.Printf(" ~ %s\n", expression);
4668 class DebugListItem : struct
4674 struct DebugEvaluationData
4679 uint64 nextBlockAddress;
4681 DebuggerEvaluationError error;
4684 class CodeLocation : struct
4687 char * absoluteFile;
4690 CodeLocation ::ParseCodeLocation(char * location)
4694 char * colon = null;
4696 char loc[MAX_LOCATION];
4697 strcpy(loc, location);
4698 for(temp = loc; temp = strstr(temp, ":"); temp++)
4706 int line = atoi(colon);
4709 CodeLocation codloc { line = line };
4710 codloc.file = CopyString(loc);
4711 codloc.absoluteFile = ide.workspace.GetAbsolutePathFromRelative(loc);
4723 delete absoluteFile;
4732 void GDBFallBack(Expression exp, String expString)
4735 ExpressionType evalError = dummyExp;
4736 result = Debugger::EvaluateExpression(expString, &evalError);
4739 exp.constant = result;
4740 exp.type = constantExp;