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
33 #include <sys/time.h> // Required on Apple...
47 sprintf(s[0], "%04d", now.year);
48 sprintf(s[1], "%02d", now.month+1);
49 sprintf(s[2], "%02d", now.day);
50 sprintf(s[3], "%02d", now.hour);
51 sprintf(s[4], "%02d", now.minute);
52 sprintf(s[5], "%02d", now.second);
53 time = PrintString("*", s[0], s[1], s[2], "-", s[3], s[4], s[5], "*");
59 // use =0 to disable printing of specific channels
61 static enum dplchan { none, gdbProtoIgnored=0/*1*/, gdbProtoUnknown=2, gdbOutput=0/*3*/, gdbCommand=0/*4*/, debuggerCall=0/*5*/, debuggerProblem=6,
62 debuggerUserAction=7,debuggerState=8, debuggerBreakpoints=9, debuggerWatches=0/*10*/, debuggerTemp=0 };
64 static enum dplchan { none, gdbProtoIgnored=0, gdbProtoUnknown=0, gdbOutput=0, gdbCommand=0, debuggerCall=0, debuggerProblem=0,
65 debuggerUserAction=0,debuggerState=0, debuggerBreakpoints=0, debuggerWatches=0, debuggerTemp=0 };
67 static char * _dpct[] = {
69 "GDB Protocol Ignored",
70 "GDB Protocol ***Unknown***",
74 "Debugger ***Problem***",
75 "Debugger::ChangeUserAction",
76 "Debugger::ChangeState",
79 "-----> Temporary Message",
83 // TODO if(strlen(item.value) < MAX_F_STRING)
87 #define _dpl2(...) __dpl2(__FILE__, __LINE__, ##__VA_ARGS__)
91 static void __dpl2(char * file, int line, char ** channels, int channel, int indent, typed_object object, ...)
93 bool chan = channel && channels && channels[channel];
96 char string[MAX_F_STRING];
98 char * time = PrintNow();
100 //ide.outputView.debugBox.Logf();
101 Logf("%s %s:% 5d: %s%s", time, file, line, chan ? channels[channel] : "", chan && channels[channel][0] ? ": " : "");
102 va_start(args, object);
103 len = PrintStdArgsToBuffer(string, sizeof(string), object, args);
111 #define _dpl(...) __dpl(__FILE__, __LINE__, ##__VA_ARGS__)
112 static void __dpl(char * file, int line, int indent, char * format, ...)
115 char string[MAX_F_STRING];
117 char * time = PrintNow();
118 //static File f = null;
119 va_start(args, format);
120 vsnprintf(string, sizeof(string), format, args);
121 string[sizeof(string)-1] = 0;
124 char * time = PrintNow();
126 logName = PrintString(time, ".log");
128 f = FileOpen(logName, write);
131 /*f.Printf("%s %s:% 5d: ", time, file, line);
132 for(c = 0; c<indent; c++)
134 f.Printf("%s\n", string);*/
135 Logf("%s %s:% 5d: ", time, file, line);
136 for(c = 0; c<indent; c++)
138 Logf("%s\n", string);
143 public char * StripQuotes2(char * string, char * output)
147 bool quoted = false, escaped = false;
149 for(c = 0; ch = string[c]; c++)
153 if(escaped || ch != '\"')
156 escaped = !escaped && ch == '\\';
170 // String Escape Copy
171 static void strescpy(char * d, char * s)
224 static char * CopyUnescapedSystemPath(char * p)
226 char * d = new char[strlen(p) + 1];
228 #if defined(__WIN32__)
229 ChangeCh(d, '/', '\\');
234 static char * CopyUnescapedUnixPath(char * p)
236 char * d = new char[strlen(p) + 1];
238 #if defined(__WIN32__)
239 ChangeCh(d, '\\', '/');
244 static char * CopyUnescapedString(char * s)
246 char * d = new char[strlen(s) + 1];
251 // String Unescape Copy
253 // TOFIX: THIS DOESN'T HANDLE NUMERIC ESCAPE CODES (OCTAL/HEXADECIMAL...)?
254 // Seems very similar to ReadString in pass15.ec (which also misses numeric escape codes :) )
256 static void struscpy(char * d, char * s)
308 static char * StripBrackets(char * string)
310 int length = strlen(string);
311 if(length > 1 && *string == '[' && string[length - 1] == ']')
314 string[length - 1] = '\0';
321 static char * StripCurlies(char * string)
323 int length = strlen(string);
324 if(length > 1 && *string == '{' && string[length - 1] == '}')
327 string[length - 1] = '\0';
334 static int StringGetInt(char * string, int start)
337 int i, len = strlen(string);
339 for(i = start; i < len && i < start + 8; i++)
341 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')
342 strncat(number, &string[i], 1);
349 static int TokenizeList(char * string, const char seperator, Array<char *> tokens)
353 bool quoted = false, escaped = false;
354 char * start = string, ch;
356 for(; (ch = *string); string++)
363 if(escaped || ch != '\"')
364 escaped = !escaped && ch == '\\';
370 else if(ch == '{' || ch == '[' || ch == '(' || ch == '<')
372 else if(ch == '}' || ch == ']' || ch == ')' || ch == '>')
374 else if(ch == seperator && !level)
383 //tokens[count] = start;
384 //tokens[count++] = start;
391 static bool TokenizeListItem(char * string, DebugListItem item)
393 char * equal = strstr(string, "=");
407 static bool CheckCommandAvailable(const char * command)
409 bool available = false;
411 char * name = new char[MAX_FILENAME];
412 char * pathVar = new char[maxPathLen];
414 GetEnvironment("PATH", pathVar, maxPathLen);
415 count = TokenizeWith(pathVar, sizeof(paths) / sizeof(char *), paths, pathListSep, false);
416 strcpy(name, command);
420 const char * extensions[] = { "exe", "com", "bat", null };
421 for(e=0; extensions[e]; e++)
423 ChangeExtension(name, extensions[e], name);
425 for(c=0; c<count; c++)
427 FileListing fl { paths[c] };
430 if(fl.stats.attribs.isFile && !fstrcmp(fl.name, name))
448 // define GdbGetLineSize = 1638400;
449 define GdbGetLineSize = 5638400;
450 #if defined(__unix__)
451 char progFifoPath[MAX_LOCATION];
452 char progFifoDir[MAX_LOCATION];
455 enum DebuggerState { none, prompt, loaded, running, stopped, terminated, error };
458 none, hit, breakEvent, signal, stepEnd, functionEnd, exit, valgrindStartPause, locationReached;
460 property bool canBeMonitored { get { return (this == hit || this == breakEvent || this == signal || this == stepEnd || this == functionEnd || this == locationReached); } };
462 enum DebuggerAction { none, internal, restart, stop, selectFrame, advance }; //, bpValidation
465 unknown, endSteppingRange, functionFinished, signalReceived, breakpointHit, locationReached
466 //watchpointTrigger, readWatchpointTrigger, accessWatchpointTrigger, watchpointScope,
467 //exited, exitedNormally, exitedSignalled;
471 none, internalMain, internalWinMain, internalModulesLoaded, user, runToCursor, internalModuleLoad, internalEntry;
473 property bool isInternal { get { return (this == internalMain || this == internalWinMain || this == internalModulesLoaded || this == internalModuleLoad || this == internalEntry); } };
474 property bool isUser { get { return (this == user || this == runToCursor); } };
476 enum DebuggerEvaluationError { none, symbolNotFound, memoryCantBeRead, unknown };
477 enum DebuggerUserAction { none, start, resume, _break, stop, restart, selectThread, selectFrame, stepInto, stepOver, stepUntil, stepOut, runToCursor };
480 none, run, _continue, next, until, advance, step, finish;
481 property bool suspendInternalBreakpoints { get { return (this == until || this == advance || this == step || this == finish); } };
484 FileDialog debuggerFileDialog { type = selectDir };
486 static DualPipe vgTargetHandle;
487 static File vgLogFile;
488 static char vgLogPath[MAX_LOCATION];
489 static DualPipe gdbHandle;
490 static DebugEvaluationData eval { };
492 static int targetProcessId;
494 static bool gdbReady;
495 static bool breakpointError;
499 Semaphore serialSemaphore { };
505 bool sentBreakInsert;
506 bool ignoreBreakpoints;
507 bool userBreakOnInternalBreakpoint;
508 //bool runToCursorDebugStart;
517 int activeFrameLevel;
526 GdbExecution gdbExecution;
527 DebuggerUserAction userAction;
530 DebuggerAction breakType;
532 //DebuggerCommand lastCommand; // THE COMPILER COMPILES STUFF THAT DOES NOT EXIST???
534 GdbDataStop stopItem;
535 GdbDataBreakpoint bpItem;
538 List<Breakpoint> sysBPs { };
539 Breakpoint bpRunToCursor;
543 CompilerConfig currentCompiler;
544 ProjectConfig prjConfig;
547 CodeEditor codeEditor;
549 ValgrindLogThread vgLogThread { debugger = this };
550 ValgrindTargetThread vgTargetThread { debugger = this };
551 GdbThread gdbThread { debugger = this };
554 Map<String, bool> projectsLibraryLoaded { };
558 delay = 0.0, userData = this;
562 bool monitor = false;
563 DebuggerEvent curEvent = event;
564 GdbDataStop stopItem = this.stopItem;
565 Breakpoint bpUser = null;
566 Breakpoint bpInternal = null;
574 this.stopItem = null;
578 DynamicString bpReport { };
580 for(bp : sysBPs; bp.inserted)
582 bpReport.concatx(",", bp.type, "(", s=bp.CopyLocationString(false), ")");
585 if(bpRunToCursor && bpRunToCursor.inserted)
587 Breakpoint bp = bpRunToCursor;
588 bpReport.concatx(",", bp.type, "(", s=bp.CopyLocationString(false), ")");
591 for(bp : ide.workspace.breakpoints; bp.inserted)
593 bpReport.concatx(",", bp.type, "(", s=bp.CopyLocationString(false), ")");
597 _dpl2(_dpct, dplchan::debuggerBreakpoints, 0, "gdbTimer::DelayExpired: ", s+1);
602 Breakpoint bp = GetBreakpointById(stopItem.bkptno, &isInternal);
604 _dpl2(_dpct, dplchan::debuggerBreakpoints, 0, "gdb stopped by a breakpoint: ", bp.type, "(", s=bp.CopyLocationString(false), ")"); delete s;
612 if(curEvent && curEvent != exit)
614 _dpl(0, "No stop item");
622 Restart(currentCompiler, prjConfig, bitDepth, usingValgrind);
631 GdbCommand(false, "-stack-select-frame %d", activeFrameLevel);
632 for(activeFrame = stackFrames.first; activeFrame; activeFrame = activeFrame.next)
633 if(activeFrame.level == activeFrameLevel)
639 // GdbCommand(false, "-break-info %s", bpItem.number);
651 Breakpoint bp = stopItem ? GetBreakpointById(stopItem.bkptno, &isInternal) : null;
652 if(bp && bp.inserted && bp.bp.addr)
654 if(bp.type.isInternal)
658 if(stopItem && stopItem.frame)
660 if(bpInternal && bpRunToCursor && bpRunToCursor.inserted && !strcmp(bpRunToCursor.bp.addr, bp.bp.addr))
661 bpUser = bpRunToCursor;
664 for(item : (bpInternal ? ide.workspace.breakpoints : sysBPs); item.inserted)
666 if(item.bp && item.bp.addr && !strcmp(item.bp.addr, bp.bp.addr))
678 _dpl2(_dpct, dplchan::debuggerProblem, 0, "Invalid stopItem!");
679 if(bpUser && strcmp(stopItem.frame.addr, bpUser.bp.addr))
683 _dpl2(_dpct, dplchan::debuggerProblem, 0, "Breakpoint bkptno(", stopItem.bkptno, ") invalid or not found!");
684 if((bpUser && !ignoreBreakpoints) || (bpInternal && userBreakOnInternalBreakpoint))
686 hitThread = stopItem.threadid;
690 signalThread = stopItem.threadid;
694 case locationReached:
696 ignoreBreakpoints = false;
698 case valgrindStartPause:
699 GdbExecContinue(true);
706 if(monitor || (bpUser && bpUser.type == runToCursor))
711 activeThread = stopItem.threadid;
712 GdbCommand(false, "-thread-list-ids");
713 if(activeFrameLevel > 0)
714 GdbCommand(false, "-stack-select-frame %d", activeFrameLevel);
716 WatchesCodeEditorLinkInit();
718 ide.AdjustDebugMenus();
721 if(curEvent == signal)
725 ide.outputView.debugBox.Logf($"Signal received: %s - %s\n", stopItem.name, stopItem.meaning);
726 ide.outputView.debugBox.Logf(" %s:%d\n", (s = CopySystemPath(stopItem.frame.file)), stopItem.frame.line);
727 ide.outputView.Show();
728 ide.callStackView.Show();
731 else if(curEvent == breakEvent)
733 ide.threadsView.Show();
734 ide.callStackView.Show();
735 ide.callStackView.Activate();
738 if(monitor && curEvent.canBeMonitored)
740 InternalSelectFrame(activeFrameLevel);
741 GoToStackFrameLine(activeFrameLevel, true, false);
742 ide.ShowCodeEditor();
743 ideMainFrame.Activate(); // TOFIX: ide.Activate() is not reliable (app inactive)
749 if(BreakpointHit(stopItem, bpInternal, bpUser))
751 ide.AdjustDebugMenus();
752 if(bpUser && bpUser.type == runToCursor)
754 ignoreBreakpoints = false;
755 UnsetBreakpoint(bpUser);
756 delete bpRunToCursor;
761 if(breakType == advance && bpInternal && (bpInternal.type == internalMain || bpInternal.type == internalEntry))
764 GdbExecAdvance(breakString, 0);
768 GdbExecContinue(false);
777 if(userBreakOnInternalBreakpoint)
778 userBreakOnInternalBreakpoint = false;
783 #ifdef GDB_DEBUG_CONSOLE
784 char lastGdbOutput[GdbGetLineSize];
786 #if defined(__unix__)
787 ProgramThread progThread { };
791 #define _ChangeUserAction(value) ChangeUserAction(__FILE__, __LINE__, value)
792 void ChangeUserAction(char * file, int line, DebuggerUserAction value)
794 bool same = value == userAction;
795 __dpl2(file, line, _dpct, dplchan::debuggerUserAction, 0, userAction, /*same ? " *** == *** " : */" -> ", value);
799 #define _ChangeUserAction(value) userAction = value
803 #define _ChangeState(value) ChangeState(__FILE__, __LINE__, value)
804 void ChangeState(char * file, int line, DebuggerState value)
806 #define _ChangeState(value) ChangeState(value)
807 void ChangeState(DebuggerState value)
810 bool same = value == state;
812 __dpl2(file, line, _dpct, dplchan::debuggerState, 0, state, same ? " *** == *** " : " -> ", value);
815 if(!same) ide.AdjustDebugMenus();
820 _dpl2(_dpct, dplchan::debuggerCall, 0, "Debugger::CleanUp");
822 stackFrames.Free(Frame::Free);
832 waitingForPID = false;
837 sentBreakInsert = false;
838 ignoreBreakpoints = false;
839 userBreakOnInternalBreakpoint = false;
840 //runToCursorDebugStart = false;
843 activeFrameLevel = 0;
860 bpRunToCursor = null;
862 delete currentCompiler;
867 projectsLibraryLoaded.Free();
869 /*GdbThread gdbThread
875 _dpl2(_dpct, dplchan::debuggerCall, 0, "Debugger::constructor");
876 ideProcessId = Process_GetCurrentProcessId();
878 sysBPs.Add(Breakpoint { type = internalEntry, enabled = false, level = -1 });
879 sysBPs.Add(Breakpoint { type = internalMain, function = "main", enabled = true, level = -1 });
880 #if defined(__WIN32__)
881 sysBPs.Add(Breakpoint { type = internalWinMain, function = "WinMain", enabled = true, level = -1 });
883 sysBPs.Add(Breakpoint { type = internalModulesLoaded, enabled = true, level = -1 });
884 sysBPs.Add(Breakpoint { type = internalModuleLoad, function = "InternalModuleLoadBreakpoint", enabled = true, level = -1 });
889 _dpl2(_dpct, dplchan::debuggerCall, 0, "Debugger::destructor");
897 property bool isActive { get { return state == running || state == stopped; } }
898 property bool isPrepared { get { return state == loaded || state == running || state == stopped; } }
902 _dpl2(_dpct, dplchan::debuggerCall, 0, "Debugger::Resume");
903 _ChangeUserAction(resume);
904 GdbExecContinue(true);
909 _dpl2(_dpct, dplchan::debuggerCall, 0, "Debugger::Break");
910 _ChangeUserAction(_break);
914 GdbDebugBreak(false);
920 _dpl2(_dpct, dplchan::debuggerCall, 0, "Debugger::Stop");
921 _ChangeUserAction(stop);
928 GdbDebugBreak(false);
942 void Restart(CompilerConfig compiler, ProjectConfig config, int bitDepth, bool useValgrind)
944 _dpl2(_dpct, dplchan::debuggerCall, 0, "Debugger::Restart");
945 _ChangeUserAction(restart);
946 if(StartSession(compiler, config, bitDepth, useValgrind, true, false, false/*, false*/) == loaded)
950 bool GoToCodeLine(char * location)
953 _dpl2(_dpct, dplchan::debuggerCall, 0, "Debugger::GoToCodeLine(", location, ")");
954 codloc = CodeLocation::ParseCodeLocation(location);
957 CodeEditor editor = (CodeEditor)ide.OpenFile(codloc.absoluteFile, normal, true, null, no, normal, false);
960 EditBox editBox = editor.editBox;
961 editBox.GoToLineNum(codloc.line - 1);
962 editBox.GoToPosition(editBox.line, codloc.line - 1, 0);
969 bool GoToStackFrameLine(int stackLevel, bool askForLocation, bool fromCallStack)
971 _dpl2(_dpct, dplchan::debuggerCall, 0, "Debugger::GoToStackFrameLine(", stackLevel, ", ", askForLocation, ")");
974 char filePath[MAX_LOCATION];
975 char sourceDir[MAX_LOCATION];
977 CodeEditor editor = null;
978 if(stackLevel == -1) // this (the two lines) is part of that fix that I would not put in for some time
980 for(frame = stackFrames.first; frame; frame = frame.next)
981 if(frame.level == stackLevel)
986 ide.callStackView.Show();
988 if(frame.absoluteFile)
989 editor = (CodeEditor)ide.OpenFile(frame.absoluteFile, normal, true, null, no, normal, false);
990 if(!editor && frame.file)
991 frame.absoluteFile = ide.workspace.GetAbsolutePathFromRelative(frame.file);
992 if(!frame.absoluteFile && askForLocation && frame.file)
995 char title[MAX_LOCATION];
996 snprintf(title, sizeof(title), $"Provide source file location for %s", (s = CopySystemPath(frame.file)));
997 title[sizeof(title)-1] = 0;
999 if(SourceDirDialog(title, ide.workspace.projectDir, frame.file, sourceDir))
1001 AddSourceDir(sourceDir);
1002 frame.absoluteFile = ide.workspace.GetAbsolutePathFromRelative(frame.file);
1005 if(!editor && frame.absoluteFile)
1006 editor = (CodeEditor)ide.OpenFile(frame.absoluteFile, normal, true, null, no, normal, false);
1008 ide.RepositionWindows(false);
1010 if(editor && frame.line)
1012 EditBox editBox = editor.editBox;
1013 editBox.GoToLineNum(frame.line - 1);
1014 editBox.GoToPosition(editBox.line, frame.line - 1, 0);
1022 void SelectThread(int thread)
1024 _dpl2(_dpct, dplchan::debuggerCall, 0, "Debugger::SelectThread(", thread, ")");
1025 _ChangeUserAction(selectThread);
1026 if(state == stopped)
1028 if(thread != activeThread)
1030 activeFrameLevel = -1;
1031 ide.callStackView.Clear();
1032 GdbCommand(false, "-thread-select %d", thread);
1034 InternalSelectFrame(activeFrameLevel);
1035 GoToStackFrameLine(activeFrameLevel, true, false);
1036 WatchesCodeEditorLinkRelease();
1037 WatchesCodeEditorLinkInit();
1041 ide.callStackView.Show();
1045 void SelectFrame(int frame)
1047 //_dpl2(_dpct, dplchan::debuggerCall, 0, "Debugger::SelectFrame(", frame, ")");
1048 _ChangeUserAction(selectFrame);
1049 InternalSelectFrame(frame);
1052 void InternalSelectFrame(int frame)
1054 _dpl2(_dpct, dplchan::debuggerCall, 0, "Debugger::InternalSelectFrame(", frame, ")");
1055 if(state == stopped)
1057 if(frame != activeFrameLevel || !codeEditor || !codeEditor.visible)
1059 activeFrameLevel = frame; // there is no active frame number in the gdb reply
1060 GdbCommand(false, "-stack-select-frame %d", activeFrameLevel);
1061 for(activeFrame = stackFrames.first; activeFrame; activeFrame = activeFrame.next)
1062 if(activeFrame.level == activeFrameLevel)
1065 WatchesCodeEditorLinkRelease();
1066 WatchesCodeEditorLinkInit();
1073 void HandleExit(char * reason, char * code)
1075 bool returnedExitCode = false;
1076 char verboseExitCode[128];
1078 _dpl2(_dpct, dplchan::debuggerCall, 0, "Debugger::HandleExit(", reason, ", ", code, ")");
1079 _ChangeState(loaded); // this state change seems to be superfluous, might be in case of gdb crash
1080 targetProcessId = 0;
1084 snprintf(verboseExitCode, sizeof(verboseExitCode), $" with exit code %s", code);
1085 verboseExitCode[sizeof(verboseExitCode)-1] = 0;
1088 verboseExitCode[0] = '\0';
1092 // ClearBreakDisplay();
1096 for(wh : ide.workspace.watches)
1098 if(wh.type) FreeType(wh.type);
1101 ide.watchesView.UpdateWatch(wh);
1105 #if defined(__unix__)
1108 progThread.terminate = true;
1111 fifoFile.CloseInput();
1121 char program[MAX_LOCATION];
1122 GetSystemPathBuffer(program, targetFile);
1124 ide.outputView.debugBox.Logf($"The program %s has exited%s.\n", program, verboseExitCode);
1125 else if(!strcmp(reason, "exited-normally"))
1126 ide.outputView.debugBox.Logf($"The program %s has exited normally%s.\n", program, verboseExitCode);
1127 else if(!strcmp(reason, "exited"))
1128 ide.outputView.debugBox.Logf($"The program %s has exited%s.\n", program, verboseExitCode);
1129 else if(!strcmp(reason, "exited-signalled"))
1130 ide.outputView.debugBox.Logf($"The program %s has exited with a signal%s.\n", program, verboseExitCode);
1132 ide.outputView.debugBox.Logf($"The program %s has exited (gdb provided an unknown reason)%s.\n", program, verboseExitCode);
1137 DebuggerState StartSession(CompilerConfig compiler, ProjectConfig config, int bitDepth, bool useValgrind, bool restart, bool userBreakOnInternalBreakpoint, bool ignoreBreakpoints/*, bool runToCursorDebugStart*/)
1139 DebuggerState result = none;
1140 _dpl2(_dpct, dplchan::debuggerCall, 0, "Debugger::StartSession(restart(", restart, "), userBreakOnInternalBreakpoint(", userBreakOnInternalBreakpoint, "), ignoreBreakpoints(", ignoreBreakpoints, ")"/*, runToCursorDebugStart(", runToCursorDebugStart, ")"*/);
1141 if(restart && state == running && targetProcessId)
1143 breakType = DebuggerAction::restart;
1144 GdbDebugBreak(false);
1148 if(restart && state == stopped)
1150 if(needReset && state == loaded)
1151 GdbExit(); // this reset is to get a clean state with all the breakpoints until a better state can be maintained on program exit
1153 if(result == none || result == terminated)
1155 ide.outputView.ShowClearSelectTab(debug);
1156 ide.outputView.debugBox.Logf($"Starting debug mode\n");
1163 for(bp : ide.workspace.breakpoints)
1169 //this.runToCursorDebugStart = runToCursorDebugStart;
1171 if(GdbInit(compiler, config, bitDepth, useValgrind))
1176 this.ignoreBreakpoints = ignoreBreakpoints;
1177 this.userBreakOnInternalBreakpoint = userBreakOnInternalBreakpoint;
1182 void Start(CompilerConfig compiler, ProjectConfig config, int bitDepth, bool useValgrind)
1184 _dpl2(_dpct, dplchan::debuggerCall, 0, "Debugger::Start()");
1185 _ChangeUserAction(start);
1186 if(StartSession(compiler, config, bitDepth, useValgrind, true, false, false/*, false*/) == loaded)
1190 void StepInto(CompilerConfig compiler, ProjectConfig config, int bitDepth, bool useValgrind)
1192 _dpl2(_dpct, dplchan::debuggerCall, 0, "Debugger::StepInto()");
1193 _ChangeUserAction(stepInto);
1194 switch(StartSession(compiler, config, bitDepth, useValgrind, false, true, false/*, false*/))
1196 case loaded: GdbExecRun(); break;
1197 case stopped: GdbExecStep(); break;
1201 void StepOver(CompilerConfig compiler, ProjectConfig config, int bitDepth, bool useValgrind, bool ignoreBreakpoints)
1203 _dpl2(_dpct, dplchan::debuggerCall, 0, "Debugger::StepOver()");
1204 _ChangeUserAction(stepOver);
1205 switch(StartSession(compiler, config, bitDepth, useValgrind, false, true, ignoreBreakpoints/*, false*/))
1207 case loaded: GdbExecRun(); break;
1208 case stopped: GdbExecNext(); break;
1212 void StepUntil(CompilerConfig compiler, ProjectConfig config, int bitDepth, bool useValgrind, bool ignoreBreakpoints)
1214 _dpl2(_dpct, dplchan::debuggerCall, 0, "Debugger::StepUntil()");
1215 _ChangeUserAction(stepUntil);
1216 switch(StartSession(compiler, config, bitDepth, useValgrind, false, true, ignoreBreakpoints/*, false*/))
1218 case loaded: GdbExecRun(); break;
1219 case stopped: GdbExecUntil(null, 0); break;
1223 void StepOut(bool ignoreBreakpoints)
1225 _dpl2(_dpct, dplchan::debuggerCall, 0, "Debugger::StepOut()");
1226 _ChangeUserAction(stepOut);
1227 if(state == stopped)
1229 this.ignoreBreakpoints = ignoreBreakpoints;
1233 GdbExecContinue(true);
1237 void RunToCursor(CompilerConfig compiler, ProjectConfig config, int bitDepth, bool useValgrind, char * absoluteFilePath, int lineNumber, bool ignoreBreakpoints, bool atSameLevel, bool oldImplementation)
1239 char relativeFilePath[MAX_LOCATION];
1240 _dpl2(_dpct, dplchan::debuggerCall, 0, "Debugger::RunToCursor()");
1241 _ChangeUserAction(runToCursor);
1242 if(!ide.projectView.project.GetRelativePath(absoluteFilePath, relativeFilePath))
1243 strcpy(relativeFilePath, absoluteFilePath);
1245 if(bpRunToCursor && bpRunToCursor.inserted && symbols)
1247 UnsetBreakpoint(bpRunToCursor);
1248 delete bpRunToCursor;
1251 StartSession(compiler, config, bitDepth, useValgrind, false, false, ignoreBreakpoints/*, true*/);
1254 if(oldImplementation)
1256 bpRunToCursor = Breakpoint { };
1257 bpRunToCursor.absoluteFilePath = absoluteFilePath;
1258 bpRunToCursor.relativeFilePath = relativeFilePath;
1259 bpRunToCursor.line = lineNumber;
1260 bpRunToCursor.type = runToCursor;
1261 bpRunToCursor.enabled = true;
1262 bpRunToCursor.level = atSameLevel ? frameCount - activeFrameLevel -1 : -1;
1267 breakType = advance;
1268 breakString = PrintString(relativeFilePath, ":", lineNumber);
1271 else if(state == stopped)
1273 if(oldImplementation)
1274 GdbExecContinue(true);
1278 GdbExecUntil(absoluteFilePath, lineNumber);
1280 GdbExecAdvance(absoluteFilePath, lineNumber);
1285 void GetCallStackCursorLine(bool * error, int * lineCursor, int * lineTopFrame)
1287 //_dpl2(_dpct, dplchan::debuggerCall, 0, "Debugger::GetCallStackCursorLine()");
1288 if(activeFrameLevel == -1)
1296 *error = signalOn && activeThread == signalThread;
1297 *lineCursor = activeFrameLevel - ((frameCount > 192 && activeFrameLevel > 191) ? frameCount - 192 - 1 : 0) + 1;
1298 *lineTopFrame = activeFrameLevel ? 1 : 0;
1302 int GetMarginIconsLineNumbers(char * fileName, int lines[], bool enabled[], int max, bool * error, int * lineCursor, int * lineTopFrame)
1304 char winFilePath[MAX_LOCATION];
1305 char * absoluteFilePath = GetSlashPathBuffer(winFilePath, fileName);
1307 Iterator<Breakpoint> it { ide.workspace.breakpoints };
1308 //_dpl2(_dpct, dplchan::debuggerCall, 0, "Debugger::GetMarginIconsLineNumbers()");
1309 while(it.Next() && count < max)
1311 Breakpoint bp = it.data;
1314 if(bp.absoluteFilePath && bp.absoluteFilePath[0] && !fstrcmp(bp.absoluteFilePath, absoluteFilePath))
1316 lines[count] = bp.line;
1317 enabled[count] = bp.enabled;
1322 if(activeFrameLevel == -1)
1330 *error = signalOn && activeThread == signalThread;
1331 if(activeFrame && activeFrame.absoluteFile && !fstrcmp(absoluteFilePath, activeFrame.absoluteFile))
1332 *lineCursor = activeFrame.line;
1335 if(activeFrame && stopItem && stopItem.frame && activeFrame.level == stopItem.frame.level)
1337 else if(stopItem && stopItem.frame && stopItem.frame.absoluteFile && !fstrcmp(absoluteFilePath, stopItem.frame.absoluteFile))
1338 *lineTopFrame = stopItem.frame.line;
1342 if(*lineTopFrame == *lineCursor && *lineTopFrame)
1348 void ChangeWatch(DataRow row, char * expression)
1350 Watch wh = (Watch)row.tag;
1351 //_dpl2(_dpct, dplchan::debuggerCall, 0, "Debugger::ChangeWatch(", expression, ")");
1354 delete wh.expression;
1356 wh.expression = CopyString(expression);
1359 Iterator<Watch> it { ide.workspace.watches };
1361 ide.workspace.watches.Delete(it.pointer);
1367 row.tag = (int64)wh;
1368 ide.workspace.watches.Add(wh);
1370 wh.expression = CopyString(expression);
1372 ide.workspace.Save();
1373 //if(expression && state == stopped)
1378 void MoveIcons(char * fileName, int lineNumber, int move, bool start)
1380 char winFilePath[MAX_LOCATION];
1381 char * absoluteFilePath = GetSlashPathBuffer(winFilePath, fileName);
1384 //_dpl2(_dpct, dplchan::debuggerCall, 0, "Debugger::MoveIcons()");
1385 for(bpLink = ide.workspace.breakpoints.first; bpLink; bpLink = next)
1387 Breakpoint bp = (Breakpoint)bpLink.data;
1390 if(bp.type == user && bp.absoluteFilePath && !fstrcmp(bp.absoluteFilePath, absoluteFilePath))
1392 if(bp.line > lineNumber || (bp.line == lineNumber && start))
1394 if(move < 0 && (bp.line < lineNumber - move))
1395 ide.workspace.RemoveBreakpoint(bp);
1399 ide.breakpointsView.UpdateBreakpoint(bp.row);
1400 ide.workspace.Save();
1406 // moving code cursors is futile, on next step, stop, hit, cursors will be offset anyways
1409 bool SourceDirDialog(char * title, char * startDir, char * test, char * sourceDir)
1413 String srcDir = null;
1415 _dpl2(_dpct, dplchan::debuggerCall, 0, "Debugger::SourceDirDialog()");
1416 debuggerFileDialog.text = title;
1417 debuggerFileDialog.currentDirectory = startDir;
1418 debuggerFileDialog.master = ide;
1420 while(debuggerFileDialog.Modal())
1422 strcpy(sourceDir, debuggerFileDialog.filePath);
1423 if(!fstrcmp(ide.workspace.projectDir, sourceDir) &&
1424 MessageBox { type = yesNo, master = ide,
1425 contents = $"This is the project directory.\nWould you like to try again?",
1426 text = $"Invalid Source Directory" }.Modal() == no)
1430 for(dir : ide.workspace.sourceDirs)
1432 if(!fstrcmp(dir, sourceDir))
1440 MessageBox { type = yesNo, master = ide,
1441 contents = $"This source directory is already specified.\nWould you like to try again?",
1442 text = $"Invalid Source Directory" }.Modal() == no)
1448 char file[MAX_LOCATION];
1449 strcpy(file, sourceDir);
1450 PathCat(file, test);
1451 result = FileExists(file);
1453 MessageBox { type = yesNo, master = ide,
1454 contents = $"Unable to locate source file.\nWould you like to try again?",
1455 text = $"Invalid Source Directory" }.Modal() == no)
1469 void AddSourceDir(char * sourceDir)
1471 _dpl2(_dpct, dplchan::debuggerCall, 0, "Debugger::AddSourceDir(", sourceDir, ")");
1472 ide.workspace.sourceDirs.Add(CopyString(sourceDir));
1473 ide.workspace.Save();
1477 DebuggerState oldState = state;
1482 GdbDebugBreak(true);
1485 GdbCommand(false, "-environment-directory \"%s\"", sourceDir);
1488 if(oldState == running)
1489 GdbExecContinue(false);
1493 void ToggleBreakpoint(char * fileName, int lineNumber, Project prj)
1495 char winFilePath[MAX_LOCATION];
1496 char * absoluteFilePath = GetSlashPathBuffer(winFilePath, fileName);
1497 char absolutePath[MAX_LOCATION];
1498 char relativePath[MAX_LOCATION];
1499 char sourceDir[MAX_LOCATION];
1500 Breakpoint bp = null;
1502 _dpl2(_dpct, dplchan::debuggerBreakpoints, 0, "Debugger::ToggleBreakpoint(", fileName, ":", lineNumber, ")");
1503 strcpy(absolutePath, absoluteFilePath);
1504 for(i : ide.workspace.breakpoints; i.type == user && i.absoluteFilePath && !fstrcmp(i.absoluteFilePath, absolutePath) && i.line == lineNumber)
1513 ide.workspace.RemoveBreakpoint(bp);
1521 // FIXED: This is how it should have been... Source locations are only for files not in project
1522 // if(IsPathInsideOf(absolutePath, ide.workspace.projectDir))
1523 // MakePathRelative(absolutePath, ide.workspace.projectDir, relativePath);
1524 bool result = false;
1526 result = prj.GetRelativePath(absolutePath, relativePath);
1528 result = ide.projectView.project.GetRelativePath(absolutePath, relativePath);
1529 //if(ide.projectView.project.GetRelativePath(absolutePath, relativePath));
1533 char title[MAX_LOCATION];
1534 char directory[MAX_LOCATION];
1535 StripLastDirectory(absolutePath, directory);
1536 snprintf(title, sizeof(title), $"Provide source files location directory for %s", absolutePath);
1537 title[sizeof(title)-1] = 0;
1540 String srcDir = null;
1541 for(dir : ide.workspace.sourceDirs)
1543 if(IsPathInsideOf(absolutePath, dir))
1545 MakePathRelative(absoluteFilePath, dir, relativePath);
1553 if(SourceDirDialog(title, directory, null, sourceDir))
1555 if(IsPathInsideOf(absolutePath, sourceDir))
1557 AddSourceDir(sourceDir);
1558 MakePathRelative(absoluteFilePath, sourceDir, relativePath);
1561 else if(MessageBox { type = yesNo, master = ide,
1562 contents = $"You must provide a valid source directory in order to place a breakpoint in this file.\nWould you like to try again?",
1563 text = $"Invalid Source Directory" }.Modal() == no)
1566 else if(MessageBox { type = yesNo, master = ide,
1567 contents = $"You must provide a source directory in order to place a breakpoint in this file.\nWould you like to try again?",
1568 text = $"No Source Directory Provided" }.Modal() == no)
1572 ide.workspace.bpCount++;
1573 bp = { line = lineNumber, type = user, enabled = true, level = -1, project = prj };
1574 ide.workspace.breakpoints.Add(bp);
1575 bp.absoluteFilePath = absolutePath;
1576 bp.relativeFilePath = relativePath;
1577 ide.breakpointsView.AddBreakpoint(bp);
1582 DebuggerState oldState = state;
1587 GdbDebugBreak(true);
1590 SetBreakpoint(bp, false);
1593 if(oldState == running)
1594 GdbExecContinue(false);
1597 ide.workspace.Save();
1600 void UpdateRemovedBreakpoint(Breakpoint bp)
1602 _dpl2(_dpct, dplchan::debuggerCall, 0, "Debugger::UpdateRemovedBreakpoint()");
1603 if(targeted && bp.inserted)
1605 DebuggerState oldState = state;
1610 GdbDebugBreak(true);
1613 UnsetBreakpoint(bp);
1616 if(oldState == running)
1617 GdbExecContinue(false);
1623 void ParseFrame(Frame frame, char * string)
1626 Array<char *> frameTokens { minAllocSize = 50 };
1627 Array<char *> argsTokens { minAllocSize = 50 };
1628 Array<char *> argumentTokens { minAllocSize = 50 };
1629 DebugListItem item { };
1632 //_dpl2(_dpct, dplchan::debuggerCall, 0, "Debugger::ParseFrame()");
1633 TokenizeList(string, ',', frameTokens);
1634 for(i = 0; i < frameTokens.count; i++)
1636 if(TokenizeListItem(frameTokens[i], item))
1638 StripQuotes(item.value, item.value);
1639 if(!strcmp(item.name, "level"))
1640 frame.level = atoi(item.value);
1641 else if(!strcmp(item.name, "addr"))
1642 frame.addr = item.value;
1643 else if(!strcmp(item.name, "func"))
1644 frame.func = item.value;
1645 else if(!strcmp(item.name, "args"))
1647 if(!strcmp(item.value, "[]"))
1648 frame.argsCount = 0;
1651 item.value = StripBrackets(item.value);
1652 TokenizeList(item.value, ',', argsTokens);
1653 for(j = 0; j < argsTokens.count; j++)
1655 argsTokens[j] = StripCurlies(argsTokens[j]);
1656 TokenizeList(argsTokens[j], ',', argumentTokens);
1657 for(k = 0; k < argumentTokens.count; k++)
1660 frame.args.Add(arg);
1661 if(TokenizeListItem(argumentTokens[k], item))
1663 if(!strcmp(item.name, "name"))
1665 StripQuotes(item.value, item.value);
1666 arg.name = item.value;
1668 else if(!strcmp(item.name, "value"))
1670 StripQuotes(item.value, item.value);
1671 arg.val = item.value;
1674 _dpl2(_dpct, dplchan::gdbProtoUnknown, 0, "frame args item (", item.name, "=", item.value, ") is unheard of");
1677 _dpl(0, "Bad frame args item");
1679 argumentTokens.RemoveAll();
1681 frame.argsCount = argsTokens.count;
1682 argsTokens.RemoveAll();
1685 else if(!strcmp(item.name, "from"))
1686 frame.from = item.value;
1687 else if(!strcmp(item.name, "file"))
1688 frame.file = item.value;
1689 else if(!strcmp(item.name, "line"))
1690 frame.line = atoi(item.value);
1691 else if(!strcmp(item.name, "fullname"))
1692 frame.absoluteFile = item.value;
1694 // GDB 6.3 on OS X is giving "fullname" and "dir", all in absolute, but file name only in 'file'
1695 String path = ide.workspace.GetPathWorkspaceRelativeOrAbsolute(item.value);
1696 if(strcmp(frame.file, path))
1699 frame.absoluteFile = ide.workspace.GetAbsolutePathFromRelative(frame.file);
1704 _dpl2(_dpct, dplchan::gdbProtoUnknown, 0, "frame member (", item.name, "=", item.value, ") is unheard of");
1707 _dpl(0, "Bad frame");
1712 delete argumentTokens;
1716 Breakpoint GetBreakpointById(int id, bool * isInternal)
1718 Breakpoint bp = null;
1719 //_dpl2(_dpct, dplchan::debuggerBreakpoints, 0, "Debugger::GetBreakpointById(", id, ")");
1721 *isInternal = false;
1724 for(i : sysBPs; i.bp && i.bp.id == id)
1731 if(!bp && bpRunToCursor && bpRunToCursor.bp && bpRunToCursor.bp.id == id)
1735 for(i : ide.workspace.breakpoints; i.bp && i.bp.id == id)
1745 GdbDataBreakpoint ParseBreakpoint(char * string, Array<char *> outTokens)
1748 GdbDataBreakpoint bp { };
1749 DebugListItem item { };
1750 Array<char *> bpTokens { minAllocSize = 16 };
1751 _dpl2(_dpct, dplchan::debuggerCall, 0, "Debugger::ParseBreakpoint()");
1752 string = StripCurlies(string);
1753 TokenizeList(string, ',', bpTokens);
1754 for(i = 0; i < bpTokens.count; i++)
1756 if(TokenizeListItem(bpTokens[i], item))
1758 StripQuotes(item.value, item.value);
1759 if(!strcmp(item.name, "number"))
1761 if(!strchr(item.value, '.'))
1762 bp.id = atoi(item.value);
1763 bp.number = item.value;
1765 else if(!strcmp(item.name, "type"))
1766 bp.type = item.value;
1767 else if(!strcmp(item.name, "disp"))
1768 bp.disp = item.value;
1769 else if(!strcmp(item.name, "enabled"))
1770 bp.enabled = (!strcmpi(item.value, "y"));
1771 else if(!strcmp(item.name, "addr"))
1773 if(outTokens && !strcmp(item.value, "<MULTIPLE>"))
1776 Array<GdbDataBreakpoint> bpArray = bp.multipleBPs = { };
1777 while(outTokens.count > ++c)
1779 GdbDataBreakpoint multBp = ParseBreakpoint(outTokens[c], null);
1780 bpArray.Add(multBp);
1784 bp.addr = item.value;
1786 else if(!strcmp(item.name, "func"))
1787 bp.func = item.value;
1788 else if(!strcmp(item.name, "file"))
1789 bp.file = item.value;
1790 else if(!strcmp(item.name, "fullname"))
1791 bp.fullname = item.value;
1792 else if(!strcmp(item.name, "line"))
1793 bp.line = atoi(item.value);
1794 else if(!strcmp(item.name, "at"))
1796 else if(!strcmp(item.name, "times"))
1797 bp.times = atoi(item.value);
1798 else if(!strcmp(item.name, "original-location") || !strcmp(item.name, "thread-groups"))
1799 _dpl2(_dpct, dplchan::gdbProtoIgnored, 0, "breakpoint member (", item.name, "=", item.value, ") is ignored");
1801 _dpl2(_dpct, dplchan::gdbProtoUnknown, 0, "breakpoint member (", item.name, "=", item.value, ") is unheard of");
1807 void ShowDebuggerViews()
1809 //_dpl2(_dpct, dplchan::debuggerCall, 0, "Debugger::ShowDebuggerViews()");
1810 ide.outputView.Show();
1811 ide.outputView.SelectTab(debug);
1812 ide.threadsView.Show();
1813 ide.callStackView.Show();
1814 ide.watchesView.Show();
1818 void HideDebuggerViews()
1820 //_dpl2(_dpct, dplchan::debuggerCall, 0, "Debugger::HideDebuggerViews()");
1821 ide.RepositionWindows(true);
1824 void ::GdbCommand(bool focus, char * format, ...)
1828 // TODO: Improve this limit
1829 static char string[MAX_F_STRING*4];
1831 va_start(args, format);
1832 vsnprintf(string, sizeof(string), format, args);
1833 string[sizeof(string)-1] = 0;
1837 ide.debugger.serialSemaphore.TryWait();
1839 #ifdef GDB_DEBUG_CONSOLE
1840 _dpl2(_dpct, dplchan::gdbCommand, 0, string);
1842 #ifdef GDB_DEBUG_OUTPUT
1843 ide.outputView.gdbBox.Logf("cmd: %s\n", string);
1845 #ifdef GDB_DEBUG_GUI
1847 ide.gdbDialog.AddCommand(string);
1850 strcat(string,"\n");
1851 gdbHandle.Puts(string);
1854 Process_ShowWindows(targetProcessId);
1857 ide.debugger.serialSemaphore.Wait();
1862 bool ValidateBreakpoint(Breakpoint bp)
1864 _dpl2(_dpct, dplchan::debuggerCall, 0, "Debugger::ValidateBreakpoint()");
1865 if(modules && bp.line && bp.bp)
1867 if(bp.bp.line != bp.line)
1873 ide.outputView.debugBox.Logf("WOULD HAVE -- Invalid breakpoint disabled: %s:%d\n", bp.relativeFilePath, bp.line);
1875 //UnsetBreakpoint(bp);
1876 //bp.enabled = false;
1882 ide.outputView.debugBox.Logf("Debugger Error: ValidateBreakpoint error\n");
1883 bp.line = bp.bp.line;
1890 void BreakpointsMaintenance()
1892 //_dpl2(_dpct, dplchan::debuggerBreakpoints, 0, "Debugger::BreakpointsMaintenance()");
1895 if(gdbExecution.suspendInternalBreakpoints)
1897 for(bp : sysBPs; bp.inserted)
1898 UnsetBreakpoint(bp);
1902 DirExpression objDir = ide.project.GetObjDir(currentCompiler, prjConfig, bitDepth);
1903 for(bp : sysBPs; !bp.inserted)
1905 bool insert = false;
1906 if(bp.type == internalModulesLoaded)
1908 char path[MAX_LOCATION];
1909 char name[MAX_LOCATION];
1910 char fixedModuleName[MAX_FILENAME];
1913 bool moduleLoadBlock = false;
1915 ReplaceSpaces(fixedModuleName, ide.project.moduleName);
1916 snprintf(name, sizeof(name),"%s.main.ec", fixedModuleName);
1917 name[sizeof(name)-1] = 0;
1918 strcpy(path, ide.workspace.projectDir);
1919 PathCatSlash(path, objDir.dir);
1920 PathCatSlash(path, name);
1921 f = FileOpen(path, read);
1924 for(lineNumber = 1; !f.Eof(); lineNumber++)
1926 if(f.GetLine(line, sizeof(line) - 1))
1928 bool moduleLoadLine;
1929 TrimLSpaces(line, line);
1930 moduleLoadLine = !strncmp(line, "eModule_Load", strlen("eModule_Load"));
1931 if(!moduleLoadBlock && moduleLoadLine)
1932 moduleLoadBlock = true;
1933 else if(moduleLoadBlock && !moduleLoadLine && strlen(line) > 0)
1939 char relative[MAX_LOCATION];
1940 bp.absoluteFilePath = path;
1941 MakePathRelative(path, ide.workspace.projectDir, relative);
1942 bp.relativeFilePath = relative;
1943 bp.line = lineNumber;
1949 else if(bp.type == internalModuleLoad)
1953 for(prj : ide.workspace.projects)
1955 if(!strcmp(prj.moduleName, "ecere"))
1957 ProjectNode node = prj.topNode.Find("instance.c", false);
1960 char path[MAX_LOCATION];
1961 char relative[MAX_LOCATION];
1962 node.GetFullFilePath(path);
1963 bp.absoluteFilePath = path;
1964 MakePathRelative(path, prj.topNode.path, relative);
1965 bp.relativeFilePath = relative;
1976 SetBreakpoint(bp, false);
1981 if(userAction != runToCursor && bpRunToCursor && bpRunToCursor.inserted)
1982 UnsetBreakpoint(bpRunToCursor);
1983 if(bpRunToCursor && !bpRunToCursor.inserted)
1984 SetBreakpoint(bpRunToCursor, false);
1986 if(ignoreBreakpoints)
1988 for(bp : ide.workspace.breakpoints; bp.inserted)
1989 UnsetBreakpoint(bp);
1993 for(bp : ide.workspace.breakpoints; !bp.inserted && bp.type == user)
1997 if(!SetBreakpoint(bp, false))
1998 SetBreakpoint(bp, true);
2006 bp.bp = GdbDataBreakpoint { };
2013 void UnsetBreakpoint(Breakpoint bp)
2015 char * s; _dpl2(_dpct, dplchan::debuggerBreakpoints, 0, "Debugger::UnsetBreakpoint(", s=bp.CopyLocationString(false), ") -- ", bp.type); delete s;
2016 if(symbols && bp.inserted)
2018 GdbCommand(false, "-break-delete %s", bp.bp.number);
2019 bp.inserted = false;
2024 bool SetBreakpoint(Breakpoint bp, bool removePath)
2026 char * s; _dpl2(_dpct, dplchan::debuggerBreakpoints, 0, "Debugger::SetBreakpoint(", s=bp.CopyLocationString(false), ", ", removePath ? "**** removePath(true) ****" : "", ") -- ", bp.type); delete s;
2027 breakpointError = false;
2028 if(symbols && bp.enabled && (!bp.project || bp.project == ide.project || projectsLibraryLoaded[bp.project.name]))
2030 char * location = bp.CopyLocationString(removePath);
2031 sentBreakInsert = true;
2032 GdbCommand(false, "-break-insert %s", location);
2034 if(!breakpointError)
2036 if(bpItem && bpItem.multipleBPs && bpItem.multipleBPs.count)
2039 GdbDataBreakpoint first = null;
2040 for(n : bpItem.multipleBPs)
2042 if(!fstrcmp(n.fullname, bp.absoluteFilePath))
2052 GdbCommand(false, "-break-disable %s", n.number);
2056 _dpl2(_dpct, dplchan::debuggerProblem, 0, "Debugger::SetBreakpoint -- error breakpoint already disabled.");
2061 bpItem.addr = first.addr;
2062 bpItem.func = first.func;
2063 bpItem.file = first.file;
2064 bpItem.fullname = first.fullname;
2065 bpItem.line = first.line;
2066 //bpItem.thread-groups = first.thread-groups;
2067 bpItem.multipleBPs.Free();
2068 delete bpItem.multipleBPs;
2071 _dpl2(_dpct, dplchan::debuggerProblem, 0, "Debugger::SetBreakpoint -- error multiple breakpoints all disabled.");
2073 _dpl2(_dpct, dplchan::debuggerProblem, 0, "Debugger::SetBreakpoint -- error multiple breakpoints in exact same file not supported.");
2077 bp.inserted = (bp.bp && bp.bp.number && strcmp(bp.bp.number, "0"));
2079 ValidateBreakpoint(bp);
2080 /*if(bp == bpRunToCursor)
2081 runToCursorDebugStart = false;*/
2084 return !breakpointError;
2089 _dpl2(_dpct, dplchan::debuggerCall, 0, "Debugger::GdbGetStack()");
2091 stackFrames.Free(Frame::Free);
2092 GdbCommand(false, "-stack-info-depth");
2094 GdbCommand(false, "-stack-info-depth 192");
2095 if(frameCount && frameCount <= 192)
2096 GdbCommand(false, "-stack-list-frames 0 %d", Min(frameCount-1, 191));
2099 GdbCommand(false, "-stack-list-frames 0 %d", Min(frameCount-1, 95));
2100 GdbCommand(false, "-stack-list-frames %d %d", Max(frameCount - 96, 96), frameCount - 1);
2102 GdbCommand(false, "");
2107 _dpl2(_dpct, dplchan::debuggerCall, 0, "Debugger::GdbTargetSet()");
2110 char escaped[MAX_LOCATION];
2111 strescpy(escaped, targetFile);
2112 GdbCommand(false, "file \"%s\"", escaped); //GDB/MI Missing Implementation in 5.1.1 but we now have -file-exec-and-symbols / -file-exec-file / -file-symbol-file
2119 const char *vgdbCommand = "/usr/bin/vgdb"; // TODO: vgdb command config option
2120 //GdbCommand(false, "-target-select remote | %s --pid=%d", "vgdb", targetProcessId);
2121 printf("target remote | %s --pid=%d\n", vgdbCommand, targetProcessId);
2122 GdbCommand(false, "target remote | %s --pid=%d", vgdbCommand, targetProcessId); // TODO: vgdb command config option
2125 GdbCommand(false, "info target"); //GDB/MI Missing Implementation -file-list-symbol-files and -file-list-exec-sections
2127 /*for(prj : ide.workspace.projects; prj != ide.workspace.projects.firstIterator.data)
2128 GdbCommand(false, "-environment-directory \"%s\"", prj.topNode.path);*/
2130 for(dir : ide.workspace.sourceDirs; dir && dir[0])
2132 bool interference = false;
2133 for(prj : ide.workspace.projects)
2135 if(!fstrcmp(prj.topNode.path, dir))
2137 interference = true;
2141 if(!interference && dir[0])
2142 GdbCommand(false, "-environment-directory \"%s\"", dir);
2150 /*void GdbTargetRelease()
2154 BreakpointsDeleteAll();
2155 GdbCommand(false, "file"); //GDB/MI Missing Implementation -target-detach
2161 void GdbDebugBreak(bool internal)
2163 _dpl2(_dpct, dplchan::debuggerCall, 0, "Debugger::GdbDebugBreak()");
2167 breakType = DebuggerAction::internal;
2169 if(ide) ide.Update(null);
2171 if(Process_Break(targetProcessId)) //GdbCommand(false, "-exec-interrupt");
2172 serialSemaphore.Wait();
2175 _ChangeState(loaded);
2176 targetProcessId = 0;
2181 ide.outputView.debugBox.Logf("Debugger Error: GdbDebugBreak with not target id should never happen\n");
2186 _dpl2(_dpct, dplchan::debuggerCall, 0, "Debugger::GdbExecRun()");
2191 ShowDebuggerViews();
2193 GdbExecContinue(true);
2195 GdbCommand(true, "-exec-run");
2198 void GdbExecContinue(bool focus)
2200 _dpl2(_dpct, dplchan::debuggerCall, 0, "Debugger::GdbExecContinue()");
2203 GdbCommand(focus, "-exec-continue");
2208 _dpl2(_dpct, dplchan::debuggerCall, 0, "Debugger::GdbExecNext()");
2209 gdbExecution = next;
2211 GdbCommand(true, "-exec-next");
2214 void GdbExecUntil(char * absoluteFilePath, int lineNumber)
2216 char relativeFilePath[MAX_LOCATION];
2217 _dpl2(_dpct, dplchan::debuggerCall, 0, "Debugger::GdbExecUntil()");
2218 gdbExecution = until;
2220 if(absoluteFilePath)
2222 if(!ide.projectView.project.GetRelativePath(absoluteFilePath, relativeFilePath))
2223 strcpy(relativeFilePath, absoluteFilePath);
2224 GdbCommand(true, "-exec-until %s:%d", relativeFilePath, lineNumber);
2227 GdbCommand(true, "-exec-until");
2230 void GdbExecAdvance(char * absoluteFilePathOrLocation, int lineNumber)
2232 char relativeFilePath[MAX_LOCATION];
2233 _dpl2(_dpct, dplchan::debuggerCall, 0, "Debugger::GdbExecAdvance()");
2234 gdbExecution = advance;
2238 if(!ide.projectView.project.GetRelativePath(absoluteFilePathOrLocation, relativeFilePath))
2239 strcpy(relativeFilePath, absoluteFilePathOrLocation);
2240 GdbCommand(true, "advance %s:%d", relativeFilePath, lineNumber); // should use -exec-advance -- GDB/MI implementation missing
2243 GdbCommand(true, "advance %s", absoluteFilePathOrLocation); // should use -exec-advance -- GDB/MI implementation missing
2248 _dpl2(_dpct, dplchan::debuggerCall, 0, "Debugger::GdbExecStep()");
2249 gdbExecution = step;
2251 GdbCommand(true, "-exec-step");
2254 void GdbExecFinish()
2256 _dpl2(_dpct, dplchan::debuggerCall, 0, "Debugger::GdbExecFinish()");
2257 gdbExecution = finish;
2259 GdbCommand(true, "-exec-finish");
2262 void GdbExecCommon()
2264 //_dpl2(_dpct, dplchan::debuggerCall, 0, "Debugger::GdbExecCommon()");
2265 BreakpointsMaintenance();
2268 #ifdef GDB_DEBUG_GUI
2269 void SendGDBCommand(char * command)
2271 //_dpl2(_dpct, dplchan::debuggerCall, 0, "Debugger::SendGDBCommand()");
2272 DebuggerState oldState = state;
2277 GdbDebugBreak(true);
2280 GdbCommand(false, command);
2283 if(oldState == running)
2284 GdbExecContinue(false);
2288 void ClearBreakDisplay()
2290 //_dpl2(_dpct, dplchan::debuggerCall, 0, "Debugger::ClearBreakDisplay()");
2292 activeFrameLevel = -1;
2302 stackFrames.Free(Frame::Free);
2303 WatchesCodeEditorLinkRelease();
2304 ide.callStackView.Clear();
2305 ide.threadsView.Clear();
2311 _dpl2(_dpct, dplchan::debuggerCall, 0, "Debugger::GdbAbortExec()");
2313 GdbCommand(false, "-interpreter-exec console \"kill\""); // should use -exec-abort -- GDB/MI implementation incomplete
2317 bool GdbInit(CompilerConfig compiler, ProjectConfig config, int bitDepth, bool useValgrind)
2320 char oldDirectory[MAX_LOCATION];
2321 char tempPath[MAX_LOCATION];
2322 char command[MAX_F_STRING*4];
2323 Project project = ide.project;
2324 DirExpression targetDirExp = project.GetTargetDir(compiler, config, bitDepth);
2325 PathBackup pathBackup { };
2327 _dpl2(_dpct, dplchan::debuggerCall, 0, "Debugger::GdbInit()");
2328 if(currentCompiler != compiler)
2330 delete currentCompiler;
2331 currentCompiler = compiler;
2332 incref currentCompiler;
2335 this.bitDepth = bitDepth;
2336 usingValgrind = useValgrind;
2338 _ChangeState(loaded);
2340 sentBreakInsert = false;
2341 breakpointError = false;
2342 ignoreBreakpoints = false;
2347 projectsLibraryLoaded.Free();
2349 ide.outputView.ShowClearSelectTab(debug);
2350 ide.outputView.debugBox.Logf($"Starting debug mode\n");
2352 #ifdef GDB_DEBUG_OUTPUT
2353 ide.outputView.gdbBox.Logf("run: Starting GDB\n");
2356 strcpy(tempPath, ide.workspace.projectDir);
2357 PathCatSlash(tempPath, targetDirExp.dir);
2359 targetDir = CopyString(tempPath);
2360 project.CatTargetFileName(tempPath, compiler, config);
2362 targetFile = CopyString(tempPath);
2364 GetWorkingDir(oldDirectory, MAX_LOCATION);
2365 if(ide.workspace.debugDir && ide.workspace.debugDir[0])
2367 char temp[MAX_LOCATION];
2368 strcpy(temp, ide.workspace.projectDir);
2369 PathCatSlash(temp, ide.workspace.debugDir);
2370 ChangeWorkingDir(temp);
2373 ChangeWorkingDir(ide.workspace.projectDir);
2375 ide.SetPath(true, compiler, config, bitDepth);
2377 // TODO: This pollutes the environment, but at least it works
2378 // It shouldn't really affect the IDE as the PATH gets restored and other variables set for testing will unlikely cause problems
2379 // What is the proper solution for this? DualPipeOpenEnv?
2380 // gdb set environment commands don't seem to take effect
2381 for(e : ide.workspace.environmentVars)
2383 SetEnvironment(e.name, e.string);
2388 char * clArgs = ide.workspace.commandLineArgs;
2389 const char *valgrindCommand = "valgrind"; // TODO: valgrind command config option //TODO: valgrind options
2390 ValgrindLeakCheck vgLeakCheck = ide.workspace.vgLeakCheck;
2391 int vgRedzoneSize = ide.workspace.vgRedzoneSize;
2392 bool vgTrackOrigins = ide.workspace.vgTrackOrigins;
2393 vgLogFile = CreateTemporaryFile(vgLogPath, "ecereidevglog");
2397 vgLogThread.Create();
2401 ide.outputView.debugBox.Logf($"Debugger Fatal Error: Couldn't open temporary log file for Valgrind output\n");
2404 if(result && !CheckCommandAvailable(valgrindCommand))
2406 ide.outputView.debugBox.Logf($"Debugger Fatal Error: Command %s for Valgrind is not available.\n", valgrindCommand);
2411 char * vgRedzoneSizeFlag = vgRedzoneSize == -1 ? "" : PrintString(" --redzone-size=", vgRedzoneSize);
2412 sprintf(command, "%s --vgdb=yes --vgdb-error=0 --log-file=%s --leak-check=%s%s --track-origins=%s %s%s%s",
2413 valgrindCommand, vgLogPath, (char*)vgLeakCheck, vgRedzoneSizeFlag, vgTrackOrigins ? "yes" : "no", targetFile, clArgs ? " " : "", clArgs ? clArgs : "");
2414 if(vgRedzoneSize != -1)
2415 delete vgRedzoneSizeFlag;
2416 vgTargetHandle = DualPipeOpen(PipeOpenMode { output = true, /*error = true, */input = true }, command);
2419 ide.outputView.debugBox.Logf($"Debugger Fatal Error: Couldn't start Valgrind\n");
2425 incref vgTargetHandle;
2426 vgTargetThread.Create();
2428 targetProcessId = vgTargetHandle.GetProcessID();
2429 waitingForPID = false;
2430 if(!targetProcessId)
2432 ide.outputView.debugBox.Logf($"Debugger Fatal Error: Couldn't get Valgrind process ID\n");
2439 serialSemaphore.Wait();
2447 (compiler.targetPlatform == win32 && bitDepth == 64) ? "x86_64-w64-mingw32-gdb" :
2448 (compiler.targetPlatform == win32 && bitDepth == 32) ? "i686-w64-mingw32-gdb" :
2450 if(!CheckCommandAvailable(command))
2452 ide.outputView.debugBox.Logf($"Debugger Fatal Error: Command %s for GDB is not available.\n", command);
2457 strcat(command, " -n -silent --interpreter=mi2"); //-async //\"%s\"
2459 gdbHandle = DualPipeOpen(PipeOpenMode { output = true, /*error = true, */input = true }, command);
2462 ide.outputView.debugBox.Logf($"Debugger Fatal Error: Couldn't start GDB\n");
2472 gdbProcessId = gdbHandle.GetProcessID();
2475 ide.outputView.debugBox.Logf($"Debugger Fatal Error: Couldn't get GDB process ID\n");
2482 serialSemaphore.Wait();
2485 GdbCommand(false, "-gdb-set verbose off");
2486 //GdbCommand(false, "-gdb-set exec-done-display on");
2487 GdbCommand(false, "-gdb-set step-mode off");
2488 GdbCommand(false, "-gdb-set unwindonsignal on");
2489 //GdbCommand(false, "-gdb-set shell on");
2490 GdbCommand(false, "set print elements 992");
2491 GdbCommand(false, "-gdb-set backtrace limit 100000");
2495 //_ChangeState(terminated);
2501 #if defined(__unix__)
2503 CreateTemporaryDir(progFifoDir, "ecereide");
2504 strcpy(progFifoPath, progFifoDir);
2505 PathCat(progFifoPath, "ideprogfifo");
2506 if(!mkfifo(progFifoPath, 0600))
2508 //fileCreated = true;
2513 ide.outputView.debugBox.Logf(createFIFOMsg, progFifoPath);
2520 progThread.terminate = false;
2521 progThread.Create();
2525 #if defined(__WIN32__)
2526 GdbCommand(false, "-gdb-set new-console on");
2529 #if defined(__unix__)
2531 GdbCommand(false, "-inferior-tty-set %s", progFifoPath);
2535 GdbCommand(false, "-gdb-set args %s", ide.workspace.commandLineArgs ? ide.workspace.commandLineArgs : "");
2537 for(e : ide.workspace.environmentVars)
2539 GdbCommand(false, "set environment %s=%s", e.name, e.string);
2544 ChangeWorkingDir(oldDirectory);
2550 delete targetDirExp;
2556 _dpl2(_dpct, dplchan::debuggerCall, 0, "Debugger::GdbExit()");
2557 if(gdbHandle && gdbProcessId)
2560 GdbCommand(false, "-gdb-exit");
2575 _ChangeState(terminated); // this state change seems to be superfluous, is it safety for something?
2581 for(bp : ide.workspace.breakpoints)
2583 bp.inserted = false;
2589 bp.inserted = false;
2594 bpRunToCursor.inserted = false;
2595 delete bpRunToCursor.bp;
2598 ide.outputView.debugBox.Logf($"Debugging stopped\n");
2599 ClearBreakDisplay();
2602 #if defined(__unix__)
2603 if(!usingValgrind && FileExists(progFifoPath)) //fileCreated)
2605 progThread.terminate = true;
2608 fifoFile.CloseInput();
2614 DeleteFile(progFifoPath);
2615 progFifoPath[0] = '\0';
2621 void WatchesCodeEditorLinkInit()
2623 //_dpl2(_dpct, dplchan::debuggerCall, 0, "Debugger::WatchesCodeEditorLinkInit()");
2625 char tempPath[MAX_LOCATION];
2626 char path[MAX_LOCATION];
2628 //void MakeFilePathProjectRelative(char * path, char * relativePath)
2629 if(!ide.projectView.project.GetRelativePath(activeFrame.file, tempPath))
2630 strcpy(tempPath, activeFrame.file);
2632 strcpy(path, ide.workspace.projectDir);
2633 PathCat(path, tempPath);
2634 codeEditor = (CodeEditor)ide.OpenFile(path, Normal, false, null, no, normal, false);
2637 for(srcDir : ide.workspace.sourceDirs)
2639 strcpy(path, srcDir);
2640 PathCat(path, tempPath);
2641 codeEditor = (CodeEditor)ide.OpenFile(path, Normal, false, null, no, normal, false);
2642 if(codeEditor) break;
2647 /*if(activeFrame && !activeFrame.absoluteFile && activeFrame.file)
2648 activeFrame.absoluteFile = ide.workspace.GetAbsolutePathFromRelative(activeFrame.file);*/
2649 if(!activeFrame || !activeFrame.absoluteFile)
2652 codeEditor = (CodeEditor)ide.OpenFile(activeFrame.absoluteFile, normal, false, null, no, normal, false);
2655 codeEditor.inUseDebug = true;
2658 //watchesInit = true;
2661 void WatchesCodeEditorLinkRelease()
2663 //_dpl2(_dpct, dplchan::debuggerCall, 0, "Debugger::WatchesCodeEditorLinkRelease()");
2668 codeEditor.inUseDebug = false;
2669 if(!codeEditor.visible)
2670 codeEditor.Destroy(0);
2676 bool ResolveWatch(Watch wh)
2678 bool result = false;
2680 _dpl2(_dpct, dplchan::debuggerWatches, 0, "Debugger::ResolveWatch()");
2692 char watchmsg[MAX_F_STRING];
2693 if(state == stopped && !codeEditor)
2694 wh.value = CopyString($"No source file found for selected frame");
2695 //if(codeEditor && state == stopped || state != stopped)
2698 Module backupPrivateModule;
2699 Context backupContext;
2700 Class backupThisClass;
2704 backupPrivateModule = GetPrivateModule();
2705 backupContext = GetCurrentContext();
2706 backupThisClass = GetThisClass();
2709 SetPrivateModule(codeEditor.privateModule);
2710 SetCurrentContext(codeEditor.globalContext);
2711 SetTopContext(codeEditor.globalContext);
2712 SetGlobalContext(codeEditor.globalContext);
2713 SetGlobalData(&codeEditor.globalData);
2716 exp = ParseExpressionString(wh.expression);
2718 if(exp && !parseError)
2720 char expString[4096];
2722 PrintExpression(exp, expString);
2724 if(GetPrivateModule())
2727 DebugFindCtxTree(codeEditor.ast, activeFrame.line, 0);
2728 ProcessExpressionType(exp);
2730 wh.type = exp.expType;
2733 DebugComputeExpression(exp);
2734 if(ExpressionIsError(exp))
2736 GDBFallBack(exp, expString);
2739 /*if(exp.hasAddress)
2741 char temp[MAX_F_STRING];
2742 sprintf(temp, "0x%x", exp.address);
2743 wh.address = CopyString(temp);
2744 // wh.address = CopyStringf("0x%x", exp.address);
2749 Type dataType = exp.expType;
2752 char temp[MAX_F_STRING];
2753 switch(dataType.kind)
2756 sprintf(temp, "%i", exp.val.c);
2759 sprintf(temp, "%i", exp.val.s);
2764 sprintf(temp, "%i", exp.val.i);
2767 sprintf(temp, "%i", exp.val.i64);
2770 sprintf(temp, "%i", exp.val.p);
2775 long v = (long)exp.val.f;
2776 sprintf(temp, "%i", v);
2781 long v = (long)exp.val.d;
2782 sprintf(temp, "%i", v);
2787 wh.intVal = CopyString(temp);
2788 switch(dataType.kind)
2791 sprintf(temp, "0x%x", exp.val.c);
2794 sprintf(temp, "0x%x", exp.val.s);
2798 sprintf(temp, "0x%x", exp.val.i);
2801 sprintf(temp, "0x%x", exp.val.i64);
2804 sprintf(temp, "0x%x", exp.val.i64);
2807 sprintf(temp, "0x%x", exp.val.p);
2812 long v = (long)exp.val.f;
2813 sprintf(temp, "0x%x", v);
2818 long v = (long)exp.val.d;
2819 sprintf(temp, "0x%x", v);
2824 wh.hexVal = CopyString(temp);
2825 switch(dataType.kind)
2828 sprintf(temp, "0o%o", exp.val.c);
2831 sprintf(temp, "0o%o", exp.val.s);
2835 sprintf(temp, "0o%o", exp.val.i);
2838 sprintf(temp, "0o%o", exp.val.i64);
2841 sprintf(temp, "0o%o", exp.val.i64);
2844 sprintf(temp, "0o%o", exp.val.p);
2849 long v = (long)exp.val.f;
2850 sprintf(temp, "0o%o", v);
2855 long v = (long)exp.val.d;
2856 sprintf(temp, "0o%o", v);
2861 wh.octVal = CopyString(temp);
2864 // WHATS THIS HERE ?
2865 if(exp.type == constantExp && exp.constant)
2866 wh.constant = CopyString(exp.constant);
2872 case symbolErrorExp:
2873 snprintf(watchmsg, sizeof(watchmsg), $"Symbol \"%s\" not found", exp.identifier.string);
2875 case structMemberSymbolErrorExp:
2876 // todo get info as in next case (ExpClassMemberSymbolError)
2877 snprintf(watchmsg, sizeof(watchmsg), $"Error: Struct member not found for \"%s\"", wh.expression);
2879 case classMemberSymbolErrorExp:
2882 Expression memberExp = exp.member.exp;
2883 Identifier memberID = exp.member.member;
2884 Type type = memberExp.expType;
2887 _class = (memberID && memberID.classSym) ? memberID.classSym.registered : ((type.kind == classType && type._class) ? type._class.registered : null);
2890 char string[256] = "";
2892 PrintTypeNoConst(type, string, false, true);
2893 classSym = FindClass(string);
2894 _class = classSym ? classSym.registered : null;
2897 snprintf(watchmsg, sizeof(watchmsg), $"Member \"%s\" not found in class \"%s\"", memberID ? memberID.string : "", _class.name);
2899 snprintf(watchmsg, sizeof(watchmsg), "Member \"%s\" not found in unregistered class? (Should never get this message)", memberID ? memberID.string : "");
2902 snprintf(watchmsg, sizeof(watchmsg), "Member \"%s\" not found in no type? (Should never get this message)", memberID ? memberID.string : "");
2905 case memoryErrorExp:
2906 // Need to ensure when set to memoryErrorExp, constant is set
2907 snprintf(watchmsg, sizeof(watchmsg), $"Memory can't be read at %s", /*(exp.type == constantExp) ? */exp.constant /*: null*/);
2909 case dereferenceErrorExp:
2910 snprintf(watchmsg, sizeof(watchmsg), $"Dereference failure for \"%s\"", wh.expression);
2912 case unknownErrorExp:
2913 snprintf(watchmsg, sizeof(watchmsg), $"Unknown error for \"%s\"", wh.expression);
2915 case noDebuggerErrorExp:
2916 snprintf(watchmsg, sizeof(watchmsg), $"Debugger required for symbol evaluation in \"%s\"", wh.expression);
2918 case debugStateErrorExp:
2919 snprintf(watchmsg, sizeof(watchmsg), $"Incorrect debugger state for symbol evaluation in \"%s\"", wh.expression);
2922 snprintf(watchmsg, sizeof(watchmsg), $"Null type for \"%s\"", wh.expression);
2926 // Temporary Code for displaying Strings
2927 if((exp.expType && ((exp.expType.kind == pointerType ||
2928 exp.expType.kind == arrayType) && exp.expType.type.kind == charType)) ||
2929 (wh.type && wh.type.kind == classType && wh.type._class &&
2930 wh.type._class.registered && wh.type._class.registered.type == normalClass &&
2931 !strcmp(wh.type._class.registered.name, "String")))
2934 if(exp.expType.kind != arrayType || exp.hasAddress)
2940 //char temp[MAX_F_STRING * 32];
2942 ExpressionType evalError = dummyExp;
2943 /*if(exp.expType.kind == arrayType)
2944 sprintf(temp, "(char*)0x%x", exp.address);
2946 sprintf(temp, "(char*)%s", exp.constant);*/
2948 //evaluation = Debugger::EvaluateExpression(temp, &evalError);
2949 // address = strtoul(exp.constant, null, 0);
2950 address = _strtoui64(exp.constant, null, 0);
2951 //_dpl(0, "0x", address);
2952 // snprintf(value, sizeof(value), "0x%08x ", address);
2954 if(address > 0xFFFFFFFFLL)
2955 snprintf(value, sizeof(value), (GetRuntimePlatform() == win32) ? "0x%016I64x " : "0x%016llx ", address);
2957 snprintf(value, sizeof(value), (GetRuntimePlatform() == win32) ? "0x%08I64x " : "0x%08llx ", address);
2958 value[sizeof(value)-1] = 0;
2961 strcat(value, $"Null string");
2965 len = strlen(value);
2967 while(!string && size > 2)
2969 string = GdbReadMemory(address, size);
2972 if(string && string[0])
2975 if(UTF8Validate(string))
2980 for(c = 0; (ch = string[c]) && c<4096; c++)
2983 value[len++] = '\0';
2988 ISO8859_1toUTF8(string, value + len, 4096 - len - 30);
2989 strcat(value, ") (ISO8859-1)");
2996 strcat(value, $"Empty string");
3000 strcat(value, $"Couldn't read memory");
3002 wh.value = CopyString(value);
3005 else if(wh.type && wh.type.kind == classType && wh.type._class &&
3006 wh.type._class.registered && wh.type._class.registered.type == enumClass)
3008 uint64 value = strtoul(exp.constant, null, 0);
3009 Class enumClass = eSystem_FindClass(GetPrivateModule(), wh.type._class.registered.name);
3010 EnumClassData enumeration = (EnumClassData)enumClass.data;
3012 for(item = enumeration.values.first; item; item = item.next)
3013 if((int)item.data == value)
3016 wh.value = CopyString(item.name);
3018 wh.value = CopyString($"Invalid Enum Value");
3021 else if(wh.type && (wh.type.kind == charType || (wh.type.kind == classType && wh.type._class &&
3022 wh.type._class.registered && !strcmp(wh.type._class.registered.fullName, "ecere::com::unichar"))) )
3029 if(exp.constant[0] == '\'')
3031 if((int)((byte *)exp.constant)[1] > 127)
3034 value = UTF8GetChar(exp.constant + 1, &nb);
3035 if(nb < 2) value = exp.constant[1];
3036 signedValue = value;
3040 signedValue = exp.constant[1];
3042 // Precomp Syntax error with boot strap here:
3043 byte b = (byte)(char)signedValue;
3044 value = (unichar) b;
3050 if(wh.type.kind == charType && wh.type.isSigned)
3052 signedValue = (int)(char)strtol(exp.constant, null, 0);
3054 // Precomp Syntax error with boot strap here:
3055 byte b = (byte)(char)signedValue;
3056 value = (unichar) b;
3061 value = (uint)strtoul(exp.constant, null, 0);
3062 signedValue = (int)value;
3066 UTF32toUTF8Len(&value, 1, charString, 5);
3068 snprintf(string, sizeof(string), "\'\\0' (0)");
3069 else if(value == '\t')
3070 snprintf(string, sizeof(string), "\'\\t' (%d)", value);
3071 else if(value == '\n')
3072 snprintf(string, sizeof(string), "\'\\n' (%d)", value);
3073 else if(value == '\r')
3074 snprintf(string, sizeof(string), "\'\\r' (%d)", value);
3075 else if(wh.type.kind == charType && wh.type.isSigned)
3076 snprintf(string, sizeof(string), "\'%s\' (%d)", charString, signedValue);
3077 else if(value > 256 || wh.type.kind != charType)
3079 if(value > 0x10FFFF || !GetCharCategory(value))
3080 snprintf(string, sizeof(string), $"Invalid Unicode Keypoint (0x%08X)", value);
3082 snprintf(string, sizeof(string), "\'%s\' (U+%04X)", charString, value);
3085 snprintf(string, sizeof(string), "\'%s\' (%d)", charString, value);
3086 string[sizeof(string)-1] = 0;
3088 wh.value = CopyString(string);
3093 wh.value = CopyString(exp.constant);
3100 wh.value = PrintHexUInt64(exp.address);
3105 char tempString[256];
3106 if(exp.member.memberType == propertyMember)
3107 snprintf(watchmsg, sizeof(watchmsg), $"Missing property evaluation support for \"%s\"", wh.expression);
3109 snprintf(watchmsg, sizeof(watchmsg), $"Evaluation failed for \"%s\" of type \"%s\"", wh.expression,
3110 exp.type.OnGetString(tempString, null, null));
3116 snprintf(watchmsg, sizeof(watchmsg), $"Invalid expression: \"%s\"", wh.expression);
3117 if(exp) FreeExpression(exp);
3120 SetPrivateModule(backupPrivateModule);
3121 SetCurrentContext(backupContext);
3122 SetTopContext(backupContext);
3123 SetGlobalContext(backupContext);
3124 SetThisClass(backupThisClass);
3127 // wh.value = CopyString("No source file found for selected frame");
3129 watchmsg[sizeof(watchmsg)-1] = 0;
3131 wh.value = CopyString(watchmsg);
3133 ide.watchesView.UpdateWatch(wh);
3137 void EvaluateWatches()
3139 _dpl2(_dpct, dplchan::debuggerWatches, 0, "Debugger::EvaluateWatches()");
3140 for(wh : ide.workspace.watches)
3144 char * ::GdbEvaluateExpression(char * expression)
3146 _dpl2(_dpct, dplchan::debuggerWatches, 0, "Debugger::GdbEvaluateExpression(", expression, ")");
3149 GdbCommand(false, "-data-evaluate-expression \"%s\"", expression);
3151 ide.outputView.debugBox.Logf("Debugger Error: GdbEvaluateExpression\n");
3155 // to be removed... use GdbReadMemory that returns a byte array instead
3156 char * ::GdbReadMemoryString(uint64 address, int size, char format, int rows, int cols)
3158 _dpl2(_dpct, dplchan::debuggerCall, 0, "Debugger::GdbReadMemoryString(", address, ")");
3163 _dpl(0, "GdbReadMemoryString called with size = 0!");
3165 // GdbCommand(false, "-data-read-memory 0x%08x %c, %d, %d, %d", address, format, size, rows, cols);
3166 if(GetRuntimePlatform() == win32)
3167 GdbCommand(false, "-data-read-memory 0x%016I64x %c, %d, %d, %d", address, format, size, rows, cols);
3169 GdbCommand(false, "-data-read-memory 0x%016llx %c, %d, %d, %d", address, format, size, rows, cols);
3171 ide.outputView.debugBox.Logf("Debugger Error: GdbReadMemoryString\n");
3175 byte * ::GdbReadMemory(uint64 address, int bytes)
3177 _dpl2(_dpct, dplchan::debuggerCall, 0, "Debugger::GdbReadMemory(", address, ")");
3180 //GdbCommand(false, "-data-read-memory 0x%08x %c, 1, 1, %d", address, 'u', bytes);
3181 if(GetRuntimePlatform() == win32)
3182 GdbCommand(false, "-data-read-memory 0x%016I64x %c, 1, 1, %d", address, 'u', bytes);
3184 GdbCommand(false, "-data-read-memory 0x%016llx %c, 1, 1, %d", address, 'u', bytes);
3187 _dpl(0, "GdbReadMemory called with bytes = 0!");
3190 ide.outputView.debugBox.Logf("Debugger Error: GdbReadMemory\n");
3191 else if(eval.result && strcmp(eval.result, "N/A"))
3193 byte * result = new byte[bytes];
3194 byte * string = eval.result;
3198 result[c++] = (byte)strtol(string, &string, 10);
3214 bool BreakpointHit(GdbDataStop stopItem, Breakpoint bpInternal, Breakpoint bpUser)
3217 char * s1 = null; char * s2 = null;
3218 _dpl2(_dpct, dplchan::debuggerCall, 0, "Debugger::BreakpointHit(",
3219 "bpInternal(", bpInternal ? s1=bpInternal.CopyLocationString(false) : null, "), ",
3220 "bpUser(", bpUser ? s2=bpUser.CopyLocationString(false) : null, ")) -- ",
3221 "ignoreBreakpoints(", ignoreBreakpoints, "), ",
3222 "hitCursorBreakpoint(", bpUser && bpUser.type == runToCursor, ")");
3223 delete s1; delete s2;
3225 if(bpUser && stopItem.frame.line && bpUser.line != stopItem.frame.line)
3227 // updating user breakpoint on hit location difference
3228 // todo, print something?
3229 bpUser.line = stopItem.frame.line;
3230 ide.breakpointsView.UpdateBreakpoint(bpUser.row);
3231 ide.workspace.Save();
3236 if(bpInternal.type == internalModulesLoaded)
3238 if(!bpUser && !userBreakOnInternalBreakpoint)
3240 if(userAction == stepOut)//if(prevStopItem.reason == functionFinished)
3241 StepOut(ignoreBreakpoints);
3248 bool conditionMet = true;
3249 bool levelMatch = (bpUser.level == -1 || bpUser.level == frameCount-1);
3250 if(bpUser.condition)
3251 conditionMet = ResolveWatch(bpUser.condition);
3253 if(levelMatch && conditionMet)
3265 ide.breakpointsView.UpdateBreakpoint(bpUser.row);
3268 if(!bpUser && !bpInternal)
3274 void ValgrindTargetThreadExit()
3276 ide.outputView.debugBox.Logf($"ValgrindTargetThreadExit\n");
3279 vgTargetHandle.Wait();
3280 delete vgTargetHandle;
3282 HandleExit(null, null);
3285 void GdbThreadExit()
3287 _dpl2(_dpct, dplchan::debuggerCall, 0, "Debugger::GdbThreadExit()");
3288 if(state != terminated)
3290 _ChangeState(terminated);
3291 targetProcessId = 0;
3292 ClearBreakDisplay();
3298 serialSemaphore.Release();
3303 ide.outputView.debugBox.Logf($"Debugger Fatal Error: GDB lost\n");
3304 ide.outputView.debugBox.Logf($"Debugging stopped\n");
3306 HideDebuggerViews();
3308 //_ChangeState(terminated);
3312 void GdbThreadMain(char * output)
3316 Array<char *> outTokens { minAllocSize = 50 };
3317 Array<char *> subTokens { minAllocSize = 50 };
3318 DebugListItem item { };
3319 DebugListItem item2 { };
3320 bool setWaitingForPID = false;
3322 #if defined(GDB_DEBUG_CONSOLE) || defined(GDB_DEBUG_GUI)
3323 #ifdef GDB_DEBUG_CONSOLE
3324 _dpl2(_dpct, dplchan::gdbOutput, 0, output);
3326 #ifdef GDB_DEBUG_OUTPUT
3328 int len = strlen(output);
3336 for(c = 0; c < len / 1024; c++)
3338 strncpy(tmp, start, 1024);
3339 ide.outputView.gdbBox.Logf("out: %s\n", tmp);
3342 ide.outputView.gdbBox.Logf("out: %s\n", start);
3346 ide.outputView.gdbBox.Logf("out: %s\n", output);
3350 #ifdef GDB_DEBUG_CONSOLE
3351 strcpy(lastGdbOutput, output);
3353 #ifdef GDB_DEBUG_GUI
3354 if(ide.gdbDialog) ide.gdbDialog.AddOutput(output);
3361 if(strstr(output, "No debugging symbols found") || strstr(output, "(no debugging symbols found)"))
3364 ide.outputView.debugBox.Logf($"Target doesn't contain debug information!\n");
3367 if(!entryPoint && (t = strstr(output, "Entry point:")))
3369 char * addr = t + strlen("Entry point:");
3371 if(*t++ == ' ' && *t++ == '0' && *t == 'x')
3374 while(isxdigit(*++t));
3376 for(bp : sysBPs; bp.type == internalEntry)
3379 bp.enabled = entryPoint = true;
3387 if(TokenizeList(output, ',', outTokens) && !strcmp(outTokens[0], "^done"))
3389 //if(outTokens.count == 1)
3394 _ChangeState(loaded);
3395 targetProcessId = 0;
3396 if(outTokens.count > 1 && TokenizeListItem(outTokens[1], item))
3398 if(!strcmp(item.name, "reason"))
3400 char * reason = item.value;
3401 StripQuotes(reason, reason);
3402 if(!strcmp(reason, "exited-normally") || !strcmp(reason, "exited") || !strcmp(reason, "exited-signalled"))
3405 if(outTokens.count > 2 && TokenizeListItem(outTokens[2], item2))
3407 StripQuotes(item2.value, item2.value);
3408 if(!strcmp(item2.name, "exit-code"))
3409 exitCode = item2.value;
3415 HandleExit(reason, exitCode);
3419 _dpl2(_dpct, dplchan::gdbProtoUnknown, 0, "kill reply (", item.name, "=", item.value, ") is unheard of");
3422 HandleExit(null, null);
3425 if(outTokens.count > 1 && TokenizeListItem(outTokens[1], item))
3427 if(!strcmp(item.name, "bkpt"))
3429 sentBreakInsert = false;
3434 bpItem = ParseBreakpoint(item.value, outTokens);
3435 //breakType = bpValidation;
3437 else if(!strcmp(item.name, "depth"))
3439 StripQuotes(item.value, item.value);
3440 frameCount = atoi(item.value);
3442 stackFrames.Free(Frame::Free);
3444 else if(!strcmp(item.name, "stack"))
3447 if(stackFrames.count)
3448 ide.callStackView.Logf("...\n");
3451 item.value = StripBrackets(item.value);
3452 TokenizeList(item.value, ',', subTokens);
3453 for(i = 0; i < subTokens.count; i++)
3455 if(TokenizeListItem(subTokens[i], item))
3457 if(!strcmp(item.name, "frame"))
3460 stackFrames.Add(frame);
3461 item.value = StripCurlies(item.value);
3462 ParseFrame(frame, item.value);
3463 if(frame.file && frame.from)
3464 _dpl2(_dpct, dplchan::gdbProtoUnknown, 0, "unexpected frame file and from members present");
3468 if(activeFrameLevel == -1)
3470 if(ide.projectView.IsModuleInProject(frame.file));
3472 if(frame.level != 0)
3474 //stopItem.frame = frame;
3475 breakType = selectFrame;
3478 activeFrame = frame;
3479 activeFrameLevel = frame.level;
3482 ide.callStackView.Logf("%3d ", frame.level);
3483 if(!strncmp(frame.func, "__ecereMethod_", strlen("__ecereMethod_")))
3484 ide.callStackView.Logf($"%s Method, %s:%d\n", &frame.func[strlen("__ecereMethod_")], (s = CopySystemPath(frame.file)), frame.line);
3485 else if(!strncmp(frame.func, "__ecereProp_", strlen("__ecereProp_")))
3486 ide.callStackView.Logf($"%s Property, %s:%d\n", &frame.func[strlen("__ecereProp_")], (s = CopySystemPath(frame.file)), frame.line);
3487 else if(!strncmp(frame.func, "__ecereConstructor_", strlen("__ecereConstructor_")))
3488 ide.callStackView.Logf($"%s Constructor, %s:%d\n", &frame.func[strlen("__ecereConstructor_")], (s = CopySystemPath(frame.file)), frame.line);
3489 else if(!strncmp(frame.func, "__ecereDestructor_", strlen("__ecereDestructor_")))
3490 ide.callStackView.Logf($"%s Destructor, %s:%d\n", &frame.func[strlen("__ecereDestructor_")], (s = CopySystemPath(frame.file)), frame.line);
3492 ide.callStackView.Logf($"%s Function, %s:%d\n", frame.func, (s = CopySystemPath(frame.file)), frame.line);
3497 ide.callStackView.Logf("%3d ", frame.level);
3502 ide.callStackView.Logf($"inside %s, %s\n", frame.func, (s = CopySystemPath(frame.from)));
3506 ide.callStackView.Logf("%s\n", frame.func);
3508 ide.callStackView.Logf($"unknown source\n");
3512 _dpl2(_dpct, dplchan::gdbProtoUnknown, 0, "stack content (", item.name, "=", item.value, ") is unheard of");
3515 if(activeFrameLevel == -1)
3517 activeFrameLevel = 0;
3518 activeFrame = stackFrames.first;
3520 ide.callStackView.Home();
3522 subTokens.RemoveAll();
3524 /*else if(!strcmp(item.name, "frame"))
3527 item.value = StripCurlies(item.value);
3528 ParseFrame(&frame, item.value);
3530 else if(!strcmp(item.name, "thread-ids"))
3532 ide.threadsView.Clear();
3533 item.value = StripCurlies(item.value);
3534 TokenizeList(item.value, ',', subTokens);
3535 for(i = subTokens.count - 1; ; i--)
3537 if(TokenizeListItem(subTokens[i], item))
3539 if(!strcmp(item.name, "thread-id"))
3542 StripQuotes(item.value, item.value);
3543 value = atoi(item.value);
3544 ide.threadsView.Logf("%3d \n", value);
3547 _dpl2(_dpct, dplchan::gdbProtoUnknown, 0, "threads content (", item.name, "=", item.value, ") is unheard of");
3552 ide.threadsView.Home();
3554 subTokens.RemoveAll();
3555 //if(!strcmp(outTokens[2], "number-of-threads"))
3557 else if(!strcmp(item.name, "new-thread-id"))
3559 StripQuotes(item.value, item.value);
3560 activeThread = atoi(item.value);
3562 else if(!strcmp(item.name, "value"))
3564 StripQuotes(item.value, item.value);
3565 eval.result = CopyString(item.value);
3566 eval.active = false;
3568 else if(!strcmp(item.name, "addr"))
3570 for(i = 2; i < outTokens.count; i++)
3572 if(TokenizeListItem(outTokens[i], item))
3574 if(!strcmp(item.name, "total-bytes"))
3576 StripQuotes(item.value, item.value);
3577 eval.bytes = atoi(item.value);
3579 else if(!strcmp(item.name, "next-row"))
3581 StripQuotes(item.value, item.value);
3582 eval.nextBlockAddress = _strtoui64(item.value, null, 0);
3584 else if(!strcmp(item.name, "memory"))
3588 //StripQuotes(item.value, item.value);
3589 item.value = StripBrackets(item.value);
3590 // this should be treated as a list...
3591 item.value = StripCurlies(item.value);
3592 TokenizeList(item.value, ',', subTokens);
3593 for(j = 0; j < subTokens.count; j++)
3595 if(TokenizeListItem(subTokens[j], item))
3597 if(!strcmp(item.name, "data"))
3599 item.value = StripBrackets(item.value);
3600 StripQuotes2(item.value, item.value);
3601 eval.result = CopyString(item.value);
3602 eval.active = false;
3606 subTokens.RemoveAll();
3611 else if(!strcmp(item.name, "source-path") || !strcmp(item.name, "BreakpointTable"))
3612 _dpl2(_dpct, dplchan::gdbProtoIgnored, 0, "command reply (", item.name, "=", item.value, ") is ignored");
3614 _dpl2(_dpct, dplchan::gdbProtoUnknown, 0, "command reply (", item.name, "=", item.value, ") is unheard of");
3617 else if(!strcmp(outTokens[0], "^running"))
3619 waitingForPID = true;
3620 setWaitingForPID = true;
3621 ClearBreakDisplay();
3623 else if(!strcmp(outTokens[0], "^exit"))
3625 _ChangeState(terminated);
3626 // ide.outputView.debugBox.Logf("Exit\n");
3627 // ide.Update(null);
3629 serialSemaphore.Release();
3631 else if(!strcmp(outTokens[0], "^error"))
3635 sentBreakInsert = false;
3636 breakpointError = true;
3639 if(outTokens.count > 1 && TokenizeListItem(outTokens[1], item))
3641 if(!strcmp(item.name, "msg"))
3643 StripQuotes(item.value, item.value);
3646 eval.active = false;
3648 if(strstr(item.value, "No symbol") && strstr(item.value, "in current context"))
3649 eval.error = symbolNotFound;
3650 else if(strstr(item.value, "Cannot access memory at address"))
3651 eval.error = memoryCantBeRead;
3653 eval.error = unknown;
3655 else if(!strcmp(item.value, "Previous frame inner to this frame (corrupt stack?)"))
3658 else if(!strncmp(item.value, "Cannot access memory at address", 31))
3661 else if(!strcmp(item.value, "Cannot find bounds of current function"))
3663 _ChangeState(stopped);
3664 gdbHandle.Printf("-exec-continue\n");
3666 else if(!strcmp(item.value, "ptrace: No such process."))
3668 _ChangeState(loaded);
3669 targetProcessId = 0;
3671 else if(!strcmp(item.value, "Function \\\"WinMain\\\" not defined."))
3674 else if(!strcmp(item.value, "You can't do that without a process to debug."))
3676 _ChangeState(loaded);
3677 targetProcessId = 0;
3679 else if(strstr(item.value, "No such file or directory."))
3681 _ChangeState(loaded);
3682 targetProcessId = 0;
3684 else if(strstr(item.value, "During startup program exited with code "))
3686 _ChangeState(loaded);
3687 targetProcessId = 0;
3692 if(strlen(item.value) < MAX_F_STRING)
3695 ide.outputView.debugBox.Logf("GDB: %s\n", (s = CopyUnescapedString(item.value)));
3699 ide.outputView.debugBox.Logf("GDB: %s\n", item.value);
3705 _dpl2(_dpct, dplchan::gdbProtoUnknown, 0, "error content (", item.name, "=", item.value, ") is unheard of");
3708 _dpl2(_dpct, dplchan::gdbProtoUnknown, 0, "result-record: ", outTokens[0]);
3709 outTokens.RemoveAll();
3712 _dpl2(_dpct, dplchan::gdbProtoUnknown, 0, "status-async-output: ", outTokens[0]);
3715 if(TokenizeList(output, ',', outTokens))
3717 if(!strcmp(outTokens[0], "=library-loaded"))
3718 FGODetectLoadedLibraryForAddedProjectIssues(outTokens);
3719 else if(!strcmp(outTokens[0], "=thread-group-created") || !strcmp(outTokens[0], "=thread-group-added") ||
3720 !strcmp(outTokens[0], "=thread-group-started") || !strcmp(outTokens[0], "=thread-group-exited") ||
3721 !strcmp(outTokens[0], "=thread-created") || !strcmp(outTokens[0], "=thread-exited") ||
3722 !strcmp(outTokens[0], "=cmd-param-changed") || !strcmp(outTokens[0], "=library-unloaded") ||
3723 !strcmp(outTokens[0], "=breakpoint-modified"))
3724 _dpl2(_dpct, dplchan::gdbProtoIgnored, 0, outTokens[0], outTokens.count>1 ? outTokens[1] : "",
3725 outTokens.count>2 ? outTokens[2] : "", outTokens.count>3 ? outTokens[3] : "",
3726 outTokens.count>4 ? outTokens[4] : "", outTokens.count>5 ? outTokens[5] : "",
3727 outTokens.count>6 ? outTokens[6] : "", outTokens.count>7 ? outTokens[7] : "",
3728 outTokens.count>8 ? outTokens[8] : "", outTokens.count>9 ? outTokens[9] : "");
3730 _dpl2(_dpct, dplchan::gdbProtoUnknown, 0, "notify-async-output: ", outTokens[0]);
3732 outTokens.RemoveAll();
3736 if(TokenizeList(output, ',', outTokens))
3738 if(!strcmp(outTokens[0],"*running"))
3740 waitingForPID = true;
3741 setWaitingForPID = true;
3743 else if(!strcmp(outTokens[0], "*stopped"))
3746 _ChangeState(stopped);
3748 for(tk = 1; tk < outTokens.count; tk++)
3750 if(TokenizeListItem(outTokens[tk], item))
3752 if(!strcmp(item.name, "reason"))
3754 char * reason = item.value;
3755 StripQuotes(reason, reason);
3756 if(!strcmp(reason, "exited-normally") || !strcmp(reason, "exited") || !strcmp(reason, "exited-signalled"))
3759 if(outTokens.count > tk+1 && TokenizeListItem(outTokens[tk+1], item2))
3762 StripQuotes(item2.value, item2.value);
3763 if(!strcmp(item2.name, "exit-code"))
3764 exitCode = item2.value;
3770 HandleExit(reason, exitCode);
3773 else if(!strcmp(reason, "breakpoint-hit") ||
3774 !strcmp(reason, "function-finished") ||
3775 !strcmp(reason, "end-stepping-range") ||
3776 !strcmp(reason, "location-reached") ||
3777 !strcmp(reason, "signal-received"))
3781 if(stopItem) _dpl(0, "problem");
3783 stopItem = GdbDataStop { };
3784 stopItem.reason = r == 'b' ? breakpointHit : r == 'f' ? functionFinished : r == 'e' ? endSteppingRange : r == 'l' ? locationReached : signalReceived;
3786 for(i = tk+1; i < outTokens.count; i++)
3788 TokenizeListItem(outTokens[i], item);
3789 StripQuotes(item.value, item.value);
3790 if(!strcmp(item.name, "thread-id"))
3791 stopItem.threadid = atoi(item.value);
3792 else if(!strcmp(item.name, "frame"))
3794 item.value = StripCurlies(item.value);
3795 ParseFrame(stopItem.frame, item.value);
3797 else if(stopItem.reason == breakpointHit && !strcmp(item.name, "bkptno"))
3798 stopItem.bkptno = atoi(item.value);
3799 else if(stopItem.reason == functionFinished && !strcmp(item.name, "gdb-result-var"))
3800 stopItem.gdbResultVar = CopyString(item.value);
3801 else if(stopItem.reason == functionFinished && !strcmp(item.name, "return-value"))
3802 stopItem.returnValue = CopyString(item.value);
3803 else if(stopItem.reason == signalReceived && !strcmp(item.name, "signal-name"))
3804 stopItem.name = CopyString(item.value);
3805 else if(stopItem.reason == signalReceived && !strcmp(item.name, "signal-meaning"))
3806 stopItem.meaning = CopyString(item.value);
3807 else if(!strcmp(item.name, "stopped-threads"))
3808 _dpl2(_dpct, dplchan::gdbProtoIgnored, 0, reason, ": Advanced thread debugging not handled");
3809 else if(!strcmp(item.name, "core"))
3810 _dpl2(_dpct, dplchan::gdbProtoIgnored, 0, reason, ": Information (core) not used");
3811 else if(!strcmp(item.name, "disp"))
3812 _dpl2(_dpct, dplchan::gdbProtoIgnored, 0, reason, ": (", item.name, "=", item.value, ")");
3814 _dpl2(_dpct, dplchan::gdbProtoUnknown, 0, "Unknown ", reason, " item name (", item.name, "=", item.value, ")");
3817 if(stopItem.reason == signalReceived && !strcmp(stopItem.name, "SIGTRAP"))
3833 event = r == 'b' ? hit : r == 'f' ? functionEnd : r == 'e' ? stepEnd : r == 'l' ? locationReached : signal;
3837 else if(!strcmp(reason, "watchpoint-trigger"))
3838 _dpl2(_dpct, dplchan::gdbProtoIgnored, 0, "Reason watchpoint trigger not handled");
3839 else if(!strcmp(reason, "read-watchpoint-trigger"))
3840 _dpl2(_dpct, dplchan::gdbProtoIgnored, 0, "Reason read watchpoint trigger not handled");
3841 else if(!strcmp(reason, "access-watchpoint-trigger"))
3842 _dpl2(_dpct, dplchan::gdbProtoIgnored, 0, "Reason access watchpoint trigger not handled");
3843 else if(!strcmp(reason, "watchpoint-scope"))
3844 _dpl2(_dpct, dplchan::gdbProtoIgnored, 0, "Reason watchpoint scope not handled");
3846 _dpl2(_dpct, dplchan::gdbProtoUnknown, 0, "Unknown reason: ", reason);
3854 if(usingValgrind && event == none && !stopItem)
3855 event = valgrindStartPause;
3860 _dpl2(_dpct, dplchan::gdbProtoUnknown, 0, "Unknown exec-async-output: ", outTokens[0]);
3861 outTokens.RemoveAll();
3864 if(!strcmpi(output, "(gdb) "))
3868 char exeFile[MAX_LOCATION];
3869 int oldProcessID = targetProcessId;
3870 GetLastDirectory(targetFile, exeFile);
3872 while(!targetProcessId/*true*/)
3874 targetProcessId = Process_GetChildExeProcessId(gdbProcessId, exeFile);
3875 if(targetProcessId || gdbHandle.Peek()) break;
3880 _ChangeState(running);
3881 else if(!oldProcessID)
3883 ide.outputView.debugBox.Logf($"Debugger Error: No target process ID\n");
3884 // TO VERIFY: The rest of this block has not been thoroughly tested in this particular location
3885 gdbHandle.Printf("-gdb-exit\n");
3887 _ChangeState(terminated); //loaded;
3892 for(bp : ide.workspace.breakpoints)
3893 bp.inserted = false;
3896 bp.inserted = false;
3898 bpRunToCursor.inserted = false;
3900 ide.outputView.debugBox.Logf($"Debugging stopped\n");
3901 ClearBreakDisplay();
3903 #if defined(__unix__)
3904 if(!usingValgrind && FileExists(progFifoPath)) //fileCreated)
3906 progThread.terminate = true;
3909 fifoFile.CloseInput();
3916 DeleteFile(progFifoPath);
3917 progFifoPath[0] = '\0';
3924 serialSemaphore.Release();
3927 _dpl2(_dpct, dplchan::gdbProtoUnknown, 0, $"Unknown prompt", output);
3931 if(!strncmp(output, "&\"warning:", 10))
3934 content = strstr(output, "\"");
3935 StripQuotes(content, content);
3936 content = strstr(content, ":");
3942 ide.outputView.debugBox.LogRaw((s = CopyUnescapedString(content)));
3949 _dpl2(_dpct, dplchan::gdbProtoUnknown, 0, $"Unknown output: ", output);
3951 if(!setWaitingForPID)
3952 waitingForPID = false;
3953 setWaitingForPID = false;
3961 // From GDB Output functions
3962 void FGODetectLoadedLibraryForAddedProjectIssues(Array<char *> outTokens)
3964 char path[MAX_LOCATION] = "";
3965 char file[MAX_FILENAME] = "";
3967 DebugListItem item { };
3968 //_dpl2(_dpct, dplchan::debuggerCall, 0, "Debugger::FGODetectLoadedLibraryForAddedProjectIssues()");
3969 for(token : outTokens)
3971 if(TokenizeListItem(token, item))
3973 if(!strcmp(item.name, "target-name"))
3975 StripQuotes(item.value, path);
3976 MakeSystemPath(path);
3977 GetLastDirectory(path, file);
3979 else if(!strcmp(item.name, "symbols-loaded"))
3981 symbolsLoaded = (atoi(item.value) == 1);
3986 if(path[0] && file[0])
3988 for(prj : ide.workspace.projects; prj != ide.workspace.projects.firstIterator.data)
3992 char prjTargetPath[MAX_LOCATION];
3993 char prjTargetFile[MAX_FILENAME];
3994 DirExpression targetDirExp = prj.GetTargetDir(currentCompiler, prj.config, bitDepth);
3995 strcpy(prjTargetPath, prj.topNode.path);
3996 PathCat(prjTargetPath, targetDirExp.dir);
3997 prjTargetFile[0] = '\0';
3998 prj.CatTargetFileName(prjTargetFile, currentCompiler, prj.config);
3999 PathCat(prjTargetPath, prjTargetFile);
4000 MakeSystemPath(prjTargetPath);
4002 match = !fstrcmp(prjTargetFile, file);
4003 if(!match && (dot = strstr(prjTargetFile, ".so.")))
4005 char * dot3 = strstr(dot+4, ".");
4009 match = !fstrcmp(prjTargetFile, file);
4014 match = !fstrcmp(prjTargetFile, file);
4019 // TODO: nice visual feedback to better warn user. use some ide notification system or other means.
4020 /* -- 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)
4022 ide.outputView.debugBox.Logf($"Attention! No symbols for loaded library %s matched to the %s added project.\n", path, prj.topNode.name);
4024 match = !fstrcmp(prjTargetPath, path);
4025 if(!match && (dot = strstr(prjTargetPath, ".so.")))
4027 char * dot3 = strstr(dot+4, ".");
4031 match = !fstrcmp(prjTargetPath, path);
4036 match = !fstrcmp(prjTargetPath, path);
4040 projectsLibraryLoaded[prj.name] = true;
4042 ide.outputView.debugBox.Logf($"Loaded library %s doesn't match the %s target of the %s added project.\n", path, prjTargetPath, prj.topNode.name);
4049 void FGOBreakpointModified(Array<char *> outTokens)
4051 _dpl2(_dpct, dplchan::debuggerCall, 0, "Debugger::FGOBreakpointModified() -- TODO only if needed: support breakpoint modified");
4053 DebugListItem item { };
4054 if(outTokens.count > 1 && TokenizeListItem(outTokens[1], item))
4056 if(!strcmp(item.name, "bkpt"))
4058 GdbDataBreakpoint modBp = ParseBreakpoint(item.value, outTokens);
4066 ExpressionType ::DebugEvalExpTypeError(char * result)
4068 _dpl2(_dpct, dplchan::debuggerWatches, 0, "Debugger::DebugEvalExpTypeError()");
4073 case symbolNotFound:
4074 return symbolErrorExp;
4075 case memoryCantBeRead:
4076 return memoryErrorExp;
4078 return unknownErrorExp;
4081 char * ::EvaluateExpression(char * expression, ExpressionType * error)
4084 _dpl2(_dpct, dplchan::debuggerWatches, 0, "Debugger::EvaluateExpression(", expression, ")");
4085 if(ide.projectView && ide.debugger.state == stopped)
4087 result = GdbEvaluateExpression(expression);
4088 *error = DebugEvalExpTypeError(result);
4093 *error = noDebuggerErrorExp;
4098 char * ::ReadMemory(uint64 address, int size, char format, ExpressionType * error)
4101 char * result = GdbReadMemoryString(address, size, format, 1, 1);
4102 _dpl2(_dpct, dplchan::debuggerCall, 0, "Debugger::ReadMemory(", address, ")");
4103 if(!result || !strcmp(result, "N/A"))
4104 *error = memoryErrorExp;
4106 *error = DebugEvalExpTypeError(result);
4111 class ValgrindLogThread : Thread
4117 static char output[4096];
4118 Array<char> dynamicBuffer { minAllocSize = 4096 };
4119 File oldValgrindHandle = vgLogFile;
4120 incref oldValgrindHandle;
4123 while(debugger.state != terminated && vgLogFile)
4127 result = vgLogFile.Read(output, 1, sizeof(output));
4129 if(debugger.state == terminated || !vgLogFile/* || vgLogFile.Eof()*/)
4136 for(c = 0; c<result; c++)
4138 if(output[c] == '\n')
4140 int pos = dynamicBuffer.size;
4141 dynamicBuffer.size += c - start;
4142 memcpy(&dynamicBuffer[pos], output + start, c - start);
4143 if(dynamicBuffer.count && dynamicBuffer[dynamicBuffer.count - 1] != '\r')
4144 // COMMENTED OUT DUE TO ISSUE #135, FIXED
4145 //if(dynamicBuffer.array[dynamicBuffer.count - 1] != '\r')
4146 dynamicBuffer.size++;
4147 dynamicBuffer[dynamicBuffer.count - 1] = '\0';
4149 // printf("%s\n", dynamicBuffer.array);
4151 if(strstr(&dynamicBuffer[0], "vgdb me"))
4152 debugger.serialSemaphore.Release();
4153 ide.outputView.debugBox.Logf("%s\n", &dynamicBuffer[0]);
4154 dynamicBuffer.size = 0;
4160 int pos = dynamicBuffer.size;
4161 dynamicBuffer.size += c - start;
4162 memcpy(&dynamicBuffer[pos], output + start, c - start);
4165 else if(debugger.state == stopped)
4168 printf("Got end of file from GDB!\n");
4175 delete dynamicBuffer;
4176 ide.outputView.debugBox.Logf($"ValgrindLogThreadExit\n");
4177 //if(oldValgrindHandle == vgLogFile)
4178 debugger.GdbThreadExit/*ValgrindLogThreadExit*/();
4179 delete oldValgrindHandle;
4185 class ValgrindTargetThread : Thread
4191 static char output[4096];
4192 Array<char> dynamicBuffer { minAllocSize = 4096 };
4193 DualPipe oldValgrindHandle = vgTargetHandle;
4194 incref oldValgrindHandle;
4197 while(debugger.state != terminated && vgTargetHandle && !vgTargetHandle.Eof())
4201 result = vgTargetHandle.Read(output, 1, sizeof(output));
4203 if(debugger.state == terminated || !vgTargetHandle || vgTargetHandle.Eof())
4210 for(c = 0; c<result; c++)
4212 if(output[c] == '\n')
4214 int pos = dynamicBuffer.size;
4215 dynamicBuffer.size += c - start;
4216 memcpy(&dynamicBuffer[pos], output + start, c - start);
4217 if(dynamicBuffer.count && dynamicBuffer[dynamicBuffer.count - 1] != '\r')
4218 // COMMENTED OUT DUE TO ISSUE #135, FIXED
4219 //if(dynamicBuffer.array[dynamicBuffer.count - 1] != '\r')
4220 dynamicBuffer.size++;
4221 dynamicBuffer[dynamicBuffer.count - 1] = '\0';
4223 // printf("%s\n", dynamicBuffer.array);
4225 ide.outputView.debugBox.Logf("%s\n", &dynamicBuffer[0]);
4227 dynamicBuffer.size = 0;
4233 int pos = dynamicBuffer.size;
4234 dynamicBuffer.size += c - start;
4235 memcpy(&dynamicBuffer[pos], output + start, c - start);
4241 printf("Got end of file from GDB!\n");
4245 delete dynamicBuffer;
4246 //if(oldValgrindHandle == vgTargetHandle)
4247 debugger.ValgrindTargetThreadExit();
4248 delete oldValgrindHandle;
4254 class GdbThread : Thread
4260 static char output[4096];
4261 Array<char> dynamicBuffer { minAllocSize = 4096 };
4262 DualPipe oldGdbHandle = gdbHandle;
4263 incref oldGdbHandle;
4266 while(debugger.state != terminated && gdbHandle && !gdbHandle.Eof())
4270 result = gdbHandle.Read(output, 1, sizeof(output));
4272 if(debugger.state == terminated || !gdbHandle || gdbHandle.Eof())
4279 for(c = 0; c<result; c++)
4281 if(output[c] == '\n')
4283 int pos = dynamicBuffer.size;
4284 dynamicBuffer.size += c - start;
4285 memcpy(&dynamicBuffer[pos], output + start, c - start);
4286 if(dynamicBuffer.count && dynamicBuffer[dynamicBuffer.count - 1] != '\r')
4287 // COMMENTED OUT DUE TO ISSUE #135, FIXED
4288 //if(dynamicBuffer.array[dynamicBuffer.count - 1] != '\r')
4289 dynamicBuffer.size++;
4290 dynamicBuffer[dynamicBuffer.count - 1] = '\0';
4292 // _dpl(0, dynamicBuffer.array);
4294 debugger.GdbThreadMain(&dynamicBuffer[0]);
4295 dynamicBuffer.size = 0;
4301 int pos = dynamicBuffer.size;
4302 dynamicBuffer.size += c - start;
4303 memcpy(&dynamicBuffer[pos], output + start, c - start);
4309 _dpl(0, "Got end of file from GDB!");
4313 delete dynamicBuffer;
4314 //if(oldGdbHandle == gdbHandle)
4315 debugger.GdbThreadExit();
4316 delete oldGdbHandle;
4322 static define createFIFOMsg = $"err: Unable to create FIFO %s\n";
4323 static define openFIFOMsg = $"err: Unable to open FIFO %s for read\n";
4325 #if defined(__unix__)
4330 #include <sys/types.h>
4335 class ProgramThread : Thread
4341 bool fileCreated = false;
4343 static char output[1000];
4346 /*if(!mkfifo(progFifoPath, mask))
4353 ide.outputView.debugBox.Logf($"err: Unable to create FIFO %s\n", progFifoPath);
4357 if(FileExists(progFifoPath)) //fileCreated)
4359 fifoFile = FileOpen(progFifoPath, read);
4363 ide.outputView.debugBox.Logf(openFIFOMsg, progFifoPath);
4368 fd = fileno((FILE *)fifoFile.input);
4369 //fcntl(fd, F_SETFL, fcntl(fd, F_GETFL) | O_NONBLOCK);
4373 while(!terminate && fifoFile && !fifoFile.Eof())
4376 struct timeval time;
4384 selectResult = select(fd + 1, &rs, null, null, &time);
4385 if(FD_ISSET(fd, &rs))
4387 int result = (int)read(fd, output, sizeof(output)-1);
4388 if(!result || (result < 0 && errno != EAGAIN))
4392 output[result] = '\0';
4393 if(strcmp(output,"&\"warning: GDB: Failed to set controlling terminal: Invalid argument\\n\"\n"))
4396 ide.outputView.debugBox.Log(output);
4405 //fifoFile.CloseInput();
4408 ide.outputView.debugBox.Log("\n");
4412 if(FileExists(progFifoPath)) //fileCreated)
4414 DeleteFile(progFifoPath);
4415 progFifoPath[0] = '\0';
4423 class Argument : struct
4425 Argument prev, next;
4427 property char * name { set { delete name; if(value) name = CopyString(value); } }
4429 property char * val { set { delete val; if(value) val = CopyString(value); } }
4443 class Frame : struct
4448 property char * addr { set { delete addr; if(value) addr = CopyString(value); } }
4450 property char * func { set { delete func; if(value) func = CopyString(value); } }
4454 property char * from { set { delete from; if(value) from = CopyUnescapedUnixPath(value); } }
4456 property char * file { set { delete file; if(value) file = CopyUnescapedUnixPath(value); } }
4457 char * absoluteFile;
4458 property char * absoluteFile { set { delete absoluteFile; if(value) absoluteFile = CopyUnescapedUnixPath(value); } }
4467 delete absoluteFile;
4468 args.Free(Argument::Free);
4477 class GdbDataStop : struct
4479 DebuggerReason reason;
4494 char * gdbResultVar;
4504 if(reason == signalReceived)
4509 else if(reason == functionFinished)
4511 delete gdbResultVar;
4515 if(frame) frame.Free();
4524 class GdbDataBreakpoint : struct
4528 property char * number { set { delete number; if(value) number = CopyString(value); } }
4530 property char * type { set { delete type; if(value) type = CopyString(value); } }
4532 property char * disp { set { delete disp; if(value) disp = CopyString(value); } }
4535 property char * addr { set { delete addr; if(value) addr = CopyString(value); } }
4537 property char * func { set { delete func; if(value) func = CopyString(value); } }
4539 property char * file { set { delete file; if(value) file = CopyUnescapedUnixPath(value); } }
4541 property char * fullname { set { delete fullname; if(value) fullname = CopyUnescapedUnixPath(value); } }
4544 property char * at { set { delete at; if(value) at = CopyString(value); } }
4547 Array<GdbDataBreakpoint> multipleBPs;
4552 PrintLn("{", "#", number, " T", type, " D", disp, " E", enabled, " H", times, " (", func, ") (", file, ":", line, ") (", fullname, ") (", addr, ") (", at, ")", "}");
4563 if(multipleBPs) multipleBPs.Free();
4567 ~GdbDataBreakpoint()
4573 class Breakpoint : struct
4578 property char * function { set { delete function; if(value) function = CopyString(value); } }
4579 char * relativeFilePath;
4580 property char * relativeFilePath { set { delete relativeFilePath; if(value) relativeFilePath = CopyString(value); } }
4581 char * absoluteFilePath;
4582 property char * absoluteFilePath { set { delete absoluteFilePath; if(value) absoluteFilePath = CopyString(value); } }
4584 property char * location { set { delete location; if(value) location = CopyString(value); } }
4593 BreakpointType type;
4595 GdbDataBreakpoint bp;
4598 void ParseLocation()
4600 char * prjName = null;
4601 char * filePath = null;
4604 char fullPath[MAX_LOCATION];
4606 if(location[0] == '\(' && location[1] && (file = strchr(location+2, '\)')) && file[1])
4608 prjName = new char[file-location];
4609 strncpy(prjName, location+1, file-location-1);
4610 prjName[file-location-1] = '\0';
4615 if((line = strchr(file+1, ':')))
4617 filePath = new char[strlen(file)+1];
4618 strncpy(filePath, file, line-file);
4619 filePath[line-file] = '\0';
4623 filePath = CopyString(file);
4624 property::relativeFilePath = filePath;
4627 for(prj : ide.workspace.projects)
4629 if(!strcmp(prjName, prj.name))
4631 node = prj.topNode.FindWithPath(filePath, false);
4634 node.GetFullFilePath(fullPath);
4635 property::absoluteFilePath = fullPath;
4642 this.line = atoi(line);
4646 node = ide.projectView.project.topNode.Find(filePath, false);
4649 node.GetFullFilePath(fullPath);
4650 property::absoluteFilePath = fullPath;
4652 project = ide.project;
4654 if(!absoluteFilePath)
4655 property::absoluteFilePath = "";
4660 char * CopyLocationString(bool removePath)
4663 char * file = relativeFilePath ? relativeFilePath : absoluteFilePath;
4664 bool removingPath = removePath && file;
4667 char * fileName = new char[MAX_FILENAME];
4668 GetLastDirectory(file, fileName);
4674 location = PrintString(file, ":", function);
4676 location = CopyString(function);
4679 location = PrintString(file, ":", line);
4685 char * CopyUserLocationString()
4688 char * loc = CopyLocationString(false);
4690 for(p : ide.workspace.projects; p != ide.workspace.projects.firstIterator.data)
4692 if(p.topNode.FindByFullPath(absoluteFilePath, false))
4700 location = PrintString("(", prj.name, ")", loc);
4710 if(relativeFilePath && relativeFilePath[0])
4712 char * location = CopyUserLocationString();
4713 f.Printf(" * %d,%d,%d,%d,%s\n", enabled ? 1 : 0, ignore, level, line, location);
4716 f.Printf(" ~ %s\n", condition.expression);
4726 delete relativeFilePath;
4727 delete absoluteFilePath;
4738 class Watch : struct
4749 f.Printf(" ~ %s\n", expression);
4773 class DebugListItem : struct
4779 struct DebugEvaluationData
4784 uint64 nextBlockAddress;
4786 DebuggerEvaluationError error;
4789 class CodeLocation : struct
4792 char * absoluteFile;
4795 CodeLocation ::ParseCodeLocation(char * location)
4799 char * colon = null;
4801 char loc[MAX_LOCATION];
4802 strcpy(loc, location);
4803 for(temp = loc; temp = strstr(temp, ":"); temp++)
4811 int line = atoi(colon);
4814 CodeLocation codloc { line = line };
4815 codloc.file = CopyString(loc);
4816 codloc.absoluteFile = ide.workspace.GetAbsolutePathFromRelative(loc);
4828 delete absoluteFile;
4837 void GDBFallBack(Expression exp, String expString)
4840 ExpressionType evalError = dummyExp;
4841 result = Debugger::EvaluateExpression(expString, &evalError);
4844 exp.constant = result;
4845 exp.type = constantExp;