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
479 none, start, resume, _break, stop, restart, selectThread, selectFrame, stepInto, stepOver, stepUntil, stepOut, runToCursor;
480 property bool breaksOnInternalBreakpoint { get { return (this == stepInto || this == stepOver || this == stepUntil); } };
484 none, run, _continue, next, until, advance, step, finish;
485 property bool suspendInternalBreakpoints { get { return (this == until || this == advance || this == step || this == finish); } };
488 FileDialog debuggerFileDialog { type = selectDir };
490 static DualPipe vgTargetHandle;
491 static File vgLogFile;
492 static char vgLogPath[MAX_LOCATION];
493 static DualPipe gdbHandle;
494 static DebugEvaluationData eval { };
496 static int targetProcessId;
498 static bool gdbReady;
499 static bool breakpointError;
503 Semaphore serialSemaphore { };
509 bool sentBreakInsert;
510 bool ignoreBreakpoints;
518 int activeFrameLevel;
527 GdbExecution gdbExecution;
528 DebuggerUserAction userAction;
531 DebuggerAction breakType;
533 //DebuggerCommand lastCommand; // THE COMPILER COMPILES STUFF THAT DOES NOT EXIST???
535 GdbDataStop stopItem;
536 GdbDataBreakpoint bpItem;
539 List<Breakpoint> sysBPs { };
540 Breakpoint bpRunToCursor;
541 Breakpoint intBpEntry;
542 Breakpoint intBpMain;
543 Breakpoint intBpWinMain;
547 CompilerConfig currentCompiler;
548 ProjectConfig prjConfig;
551 CodeEditor codeEditor;
553 ValgrindLogThread vgLogThread { debugger = this };
554 ValgrindTargetThread vgTargetThread { debugger = this };
555 GdbThread gdbThread { debugger = this };
558 Map<String, bool> projectsLibraryLoaded { };
562 delay = 0.0, userData = this;
566 bool monitor = false;
567 DebuggerEvent curEvent = event;
568 GdbDataStop stopItem = this.stopItem;
569 Breakpoint bpUser = null;
570 Breakpoint bpInternal = null;
578 this.stopItem = null;
582 DynamicString bpReport { };
584 for(bp : sysBPs; bp.inserted)
586 bpReport.concatx(",", bp.type, "(", s=bp.CopyLocationString(false), ")");
589 if(bpRunToCursor && bpRunToCursor.inserted)
591 Breakpoint bp = bpRunToCursor;
592 bpReport.concatx(",", bp.type, "(", s=bp.CopyLocationString(false), ")");
595 for(bp : ide.workspace.breakpoints; bp.inserted)
597 bpReport.concatx(",", bp.type, "(", s=bp.CopyLocationString(false), ")");
601 _dpl2(_dpct, dplchan::debuggerBreakpoints, 0, "gdbTimer::DelayExpired: ", s+1);
606 Breakpoint bp = GetBreakpointById(stopItem.bkptno, &isInternal);
608 _dpl2(_dpct, dplchan::debuggerBreakpoints, 0, "gdb stopped by a breakpoint: ", bp.type, "(", s=bp.CopyLocationString(false), ")"); delete s;
616 if(curEvent && curEvent != exit)
618 _dpl(0, "No stop item");
626 Restart(currentCompiler, prjConfig, bitDepth, usingValgrind);
635 GdbCommand(false, "-stack-select-frame %d", activeFrameLevel);
636 for(activeFrame = stackFrames.first; activeFrame; activeFrame = activeFrame.next)
637 if(activeFrame.level == activeFrameLevel)
643 // GdbCommand(false, "-break-info %s", bpItem.number);
655 Breakpoint bp = stopItem ? GetBreakpointById(stopItem.bkptno, &isInternal) : null;
656 if(bp && bp.inserted && bp.bp.addr)
658 if(bp.type.isInternal)
662 if(stopItem && stopItem.frame)
664 if(bpInternal && bpRunToCursor && bpRunToCursor.inserted && !strcmp(bpRunToCursor.bp.addr, bp.bp.addr))
665 bpUser = bpRunToCursor;
668 for(item : (bpInternal ? ide.workspace.breakpoints : sysBPs); item.inserted)
670 if(item.bp && item.bp.addr && !strcmp(item.bp.addr, bp.bp.addr))
682 _dpl2(_dpct, dplchan::debuggerProblem, 0, "Invalid stopItem!");
683 if(bpUser && strcmp(stopItem.frame.addr, bpUser.bp.addr))
687 _dpl2(_dpct, dplchan::debuggerProblem, 0, "Breakpoint bkptno(", stopItem.bkptno, ") invalid or not found!");
688 if((bpUser && !ignoreBreakpoints) || (bpInternal && userAction.breaksOnInternalBreakpoint))
690 hitThread = stopItem.threadid;
694 signalThread = stopItem.threadid;
698 case locationReached:
700 ignoreBreakpoints = false;
702 case valgrindStartPause:
703 GdbExecContinue(true);
711 if(curEvent == signal)
715 ide.outputView.debugBox.Logf($"Signal received: %s - %s\n", stopItem.name, stopItem.meaning);
716 ide.outputView.debugBox.Logf(" %s:%d\n", (s = CopySystemPath(stopItem.frame.file)), stopItem.frame.line);
717 ide.outputView.Show();
718 ide.callStackView.Show();
721 else if(curEvent == breakEvent)
723 ide.threadsView.Show();
724 ide.callStackView.Show();
725 ide.callStackView.Activate();
727 else if(curEvent == hit)
729 if(BreakpointHit(stopItem, bpInternal, bpUser))
731 ide.AdjustDebugMenus();
732 if(bpUser && bpUser.type == runToCursor)
734 ignoreBreakpoints = false;
735 UnsetBreakpoint(bpUser);
736 delete bpRunToCursor;
741 if(breakType == advance && bpInternal && (bpInternal.type == internalMain || bpInternal.type == internalEntry))
744 GdbExecAdvance(breakString, 0);
749 GdbExecContinue(false);
755 if(monitor && curEvent.canBeMonitored)
758 activeThread = stopItem.threadid;
759 GdbCommand(false, "-thread-list-ids");
760 InternalSelectFrame(activeFrameLevel);
761 GoToStackFrameLine(activeFrameLevel, true, false);
763 ide.ShowCodeEditor();
764 ide.AdjustDebugMenus();
765 ideMainFrame.Activate(); // TOFIX: ide.Activate() is not reliable (app inactive)
778 #ifdef GDB_DEBUG_CONSOLE
779 char lastGdbOutput[GdbGetLineSize];
781 #if defined(__unix__)
782 ProgramThread progThread { };
786 #define _ChangeUserAction(value) ChangeUserAction(__FILE__, __LINE__, value)
787 void ChangeUserAction(char * file, int line, DebuggerUserAction value)
789 bool same = value == userAction;
790 __dpl2(file, line, _dpct, dplchan::debuggerUserAction, 0, userAction, /*same ? " *** == *** " : */" -> ", value);
794 #define _ChangeUserAction(value) userAction = value
798 #define _ChangeState(value) ChangeState(__FILE__, __LINE__, value)
799 void ChangeState(char * file, int line, DebuggerState value)
801 #define _ChangeState(value) ChangeState(value)
802 void ChangeState(DebuggerState value)
805 bool same = value == state;
807 __dpl2(file, line, _dpct, dplchan::debuggerState, 0, state, same ? " *** == *** " : " -> ", value);
810 if(!same) ide.AdjustDebugMenus();
815 _dpl2(_dpct, dplchan::debuggerCall, 0, "Debugger::CleanUp");
817 stackFrames.Free(Frame::Free);
827 waitingForPID = false;
832 sentBreakInsert = false;
833 ignoreBreakpoints = false;
836 activeFrameLevel = 0;
853 bpRunToCursor = null;
855 delete currentCompiler;
858 WatchesReleaseCodeEditor();
861 projectsLibraryLoaded.Free();
863 /*GdbThread gdbThread
869 _dpl2(_dpct, dplchan::debuggerCall, 0, "Debugger::constructor");
870 ideProcessId = Process_GetCurrentProcessId();
872 sysBPs.Add((intBpEntry = Breakpoint { type = internalEntry, enabled = false, level = -1 }));
873 sysBPs.Add((intBpMain = Breakpoint { type = internalMain, function = "main", enabled = true, level = -1 }));
874 #if defined(__WIN32__)
875 sysBPs.Add((intBpWinMain = Breakpoint { type = internalWinMain, function = "WinMain", enabled = true, level = -1 }));
877 sysBPs.Add(Breakpoint { type = internalModulesLoaded, enabled = true, level = -1 });
878 sysBPs.Add(Breakpoint { type = internalModuleLoad, function = "InternalModuleLoadBreakpoint", enabled = true, level = -1 });
883 _dpl2(_dpct, dplchan::debuggerCall, 0, "Debugger::destructor");
891 property bool isActive { get { return state == running || state == stopped; } }
892 property bool isPrepared { get { return state == loaded || state == running || state == stopped; } }
896 _dpl2(_dpct, dplchan::debuggerCall, 0, "Debugger::Resume");
897 _ChangeUserAction(resume);
898 GdbExecContinue(true);
903 _dpl2(_dpct, dplchan::debuggerCall, 0, "Debugger::Break");
904 _ChangeUserAction(_break);
908 GdbDebugBreak(false);
914 _dpl2(_dpct, dplchan::debuggerCall, 0, "Debugger::Stop");
915 _ChangeUserAction(stop);
922 GdbDebugBreak(false);
936 void Restart(CompilerConfig compiler, ProjectConfig config, int bitDepth, bool useValgrind)
938 _dpl2(_dpct, dplchan::debuggerCall, 0, "Debugger::Restart");
939 _ChangeUserAction(restart);
940 if(StartSession(compiler, config, bitDepth, useValgrind, true, false) == loaded)
944 bool GoToCodeLine(char * location)
947 _dpl2(_dpct, dplchan::debuggerCall, 0, "Debugger::GoToCodeLine(", location, ")");
948 codloc = CodeLocation::ParseCodeLocation(location);
951 CodeEditor editor = (CodeEditor)ide.OpenFile(codloc.absoluteFile, normal, true, null, no, normal, false);
954 EditBox editBox = editor.editBox;
955 editBox.GoToLineNum(codloc.line - 1);
956 editBox.GoToPosition(editBox.line, codloc.line - 1, 0);
963 bool GoToStackFrameLine(int stackLevel, bool askForLocation, bool fromCallStack)
965 _dpl2(_dpct, dplchan::debuggerCall, 0, "Debugger::GoToStackFrameLine(", stackLevel, ", ", askForLocation, ")");
968 char filePath[MAX_LOCATION];
969 char sourceDir[MAX_LOCATION];
971 CodeEditor editor = null;
972 if(stackLevel == -1) // this (the two lines) is part of that fix that I would not put in for some time
974 for(frame = stackFrames.first; frame; frame = frame.next)
975 if(frame.level == stackLevel)
980 ide.callStackView.Show();
982 if(frame.absoluteFile)
983 editor = (CodeEditor)ide.OpenFile(frame.absoluteFile, normal, true, null, no, normal, false);
984 if(!editor && frame.file)
985 frame.absoluteFile = ide.workspace.GetAbsolutePathFromRelative(frame.file);
986 if(!frame.absoluteFile && askForLocation && frame.file)
989 char title[MAX_LOCATION];
990 snprintf(title, sizeof(title), $"Provide source file location for %s", (s = CopySystemPath(frame.file)));
991 title[sizeof(title)-1] = 0;
993 if(SourceDirDialog(title, ide.workspace.projectDir, frame.file, sourceDir))
995 AddSourceDir(sourceDir);
996 frame.absoluteFile = ide.workspace.GetAbsolutePathFromRelative(frame.file);
999 if(!editor && frame.absoluteFile)
1000 editor = (CodeEditor)ide.OpenFile(frame.absoluteFile, normal, true, null, no, normal, false);
1002 ide.RepositionWindows(false);
1004 if(editor && frame.line)
1006 EditBox editBox = editor.editBox;
1007 editBox.GoToLineNum(frame.line - 1);
1008 editBox.GoToPosition(editBox.line, frame.line - 1, 0);
1016 void SelectThread(int thread)
1018 _dpl2(_dpct, dplchan::debuggerCall, 0, "Debugger::SelectThread(", thread, ")");
1019 _ChangeUserAction(selectThread);
1020 if(state == stopped)
1022 if(thread != activeThread)
1024 activeFrameLevel = -1;
1025 ide.callStackView.Clear();
1026 GdbCommand(false, "-thread-select %d", thread);
1028 InternalSelectFrame(activeFrameLevel);
1029 GoToStackFrameLine(activeFrameLevel, true, false);
1033 ide.callStackView.Show();
1037 void SelectFrame(int frame)
1039 //_dpl2(_dpct, dplchan::debuggerCall, 0, "Debugger::SelectFrame(", frame, ")");
1040 _ChangeUserAction(selectFrame);
1041 if(state == stopped)
1043 if(frame != activeFrameLevel)
1045 InternalSelectFrame(frame);
1052 void InternalSelectFrame(int frame)
1054 //_dpl2(_dpct, dplchan::debuggerCall, 0, "Debugger::InternalSelectFrame(", frame, ")");
1055 activeFrameLevel = frame; // there is no active frame number in the gdb reply
1056 GdbCommand(false, "-stack-select-frame %d", activeFrameLevel);
1057 for(activeFrame = stackFrames.first; activeFrame; activeFrame = activeFrame.next)
1058 if(activeFrame.level == activeFrameLevel)
1062 void HandleExit(char * reason, char * code)
1064 bool returnedExitCode = false;
1065 char verboseExitCode[128];
1067 _dpl2(_dpct, dplchan::debuggerCall, 0, "Debugger::HandleExit(", reason, ", ", code, ")");
1068 _ChangeState(loaded); // this state change seems to be superfluous, might be in case of gdb crash
1069 targetProcessId = 0;
1073 snprintf(verboseExitCode, sizeof(verboseExitCode), $" with exit code %s", code);
1074 verboseExitCode[sizeof(verboseExitCode)-1] = 0;
1077 verboseExitCode[0] = '\0';
1081 // ClearBreakDisplay();
1085 for(wh : ide.workspace.watches)
1087 if(wh.type) FreeType(wh.type);
1090 ide.watchesView.UpdateWatch(wh);
1094 #if defined(__unix__)
1097 progThread.terminate = true;
1100 fifoFile.CloseInput();
1110 char program[MAX_LOCATION];
1111 GetSystemPathBuffer(program, targetFile);
1113 ide.outputView.debugBox.Logf($"The program %s has exited%s.\n", program, verboseExitCode);
1114 else if(!strcmp(reason, "exited-normally"))
1115 ide.outputView.debugBox.Logf($"The program %s has exited normally%s.\n", program, verboseExitCode);
1116 else if(!strcmp(reason, "exited"))
1117 ide.outputView.debugBox.Logf($"The program %s has exited%s.\n", program, verboseExitCode);
1118 else if(!strcmp(reason, "exited-signalled"))
1119 ide.outputView.debugBox.Logf($"The program %s has exited with a signal%s.\n", program, verboseExitCode);
1121 ide.outputView.debugBox.Logf($"The program %s has exited (gdb provided an unknown reason)%s.\n", program, verboseExitCode);
1126 DebuggerState StartSession(CompilerConfig compiler, ProjectConfig config, int bitDepth, bool useValgrind, bool restart, bool ignoreBreakpoints)
1128 DebuggerState result = none;
1129 _dpl2(_dpct, dplchan::debuggerCall, 0, "Debugger::StartSession(restart(", restart, "), ignoreBreakpoints(", ignoreBreakpoints, ")");
1130 if(restart && state == running && targetProcessId)
1132 breakType = DebuggerAction::restart;
1133 GdbDebugBreak(false);
1137 if(restart && state == stopped)
1139 if(needReset && state == loaded)
1140 GdbExit(); // this reset is to get a clean state with all the breakpoints until a better state can be maintained on program exit
1142 if(result == none || result == terminated)
1144 ide.outputView.ShowClearSelectTab(debug);
1145 ide.outputView.debugBox.Logf($"Starting debug mode\n");
1152 for(bp : ide.workspace.breakpoints)
1158 if(GdbInit(compiler, config, bitDepth, useValgrind))
1163 this.ignoreBreakpoints = ignoreBreakpoints;
1168 void Start(CompilerConfig compiler, ProjectConfig config, int bitDepth, bool useValgrind)
1170 _dpl2(_dpct, dplchan::debuggerCall, 0, "Debugger::Start()");
1171 _ChangeUserAction(start);
1172 if(StartSession(compiler, config, bitDepth, useValgrind, true, false) == loaded)
1176 void StepInto(CompilerConfig compiler, ProjectConfig config, int bitDepth, bool useValgrind)
1178 _dpl2(_dpct, dplchan::debuggerCall, 0, "Debugger::StepInto()");
1179 _ChangeUserAction(stepInto);
1180 switch(StartSession(compiler, config, bitDepth, useValgrind, false, false))
1182 case loaded: GdbExecRun(); break;
1183 case stopped: GdbExecStep(); break;
1187 void StepOver(CompilerConfig compiler, ProjectConfig config, int bitDepth, bool useValgrind, bool ignoreBreakpoints)
1189 _dpl2(_dpct, dplchan::debuggerCall, 0, "Debugger::StepOver()");
1190 _ChangeUserAction(stepOver);
1191 switch(StartSession(compiler, config, bitDepth, useValgrind, false, ignoreBreakpoints))
1193 case loaded: GdbExecRun(); break;
1194 case stopped: GdbExecNext(); break;
1198 void StepUntil(CompilerConfig compiler, ProjectConfig config, int bitDepth, bool useValgrind, bool ignoreBreakpoints)
1200 _dpl2(_dpct, dplchan::debuggerCall, 0, "Debugger::StepUntil()");
1201 _ChangeUserAction(stepUntil);
1202 switch(StartSession(compiler, config, bitDepth, useValgrind, false, ignoreBreakpoints))
1204 case loaded: GdbExecRun(); break;
1205 case stopped: GdbExecUntil(null, 0); break;
1209 void StepOut(bool ignoreBreakpoints)
1211 _dpl2(_dpct, dplchan::debuggerCall, 0, "Debugger::StepOut()");
1212 _ChangeUserAction(stepOut);
1213 if(state == stopped)
1215 this.ignoreBreakpoints = ignoreBreakpoints;
1219 GdbExecContinue(true);
1223 void RunToCursor(CompilerConfig compiler, ProjectConfig config, int bitDepth, bool useValgrind, char * absoluteFilePath, int lineNumber, bool ignoreBreakpoints, bool atSameLevel, bool oldImplementation)
1225 char relativeFilePath[MAX_LOCATION];
1226 _dpl2(_dpct, dplchan::debuggerCall, 0, "Debugger::RunToCursor()");
1227 _ChangeUserAction(runToCursor);
1228 if(!ide.projectView.project.GetRelativePath(absoluteFilePath, relativeFilePath))
1229 strcpy(relativeFilePath, absoluteFilePath);
1231 if(bpRunToCursor && bpRunToCursor.inserted && symbols)
1233 UnsetBreakpoint(bpRunToCursor);
1234 delete bpRunToCursor;
1237 StartSession(compiler, config, bitDepth, useValgrind, false, ignoreBreakpoints);
1240 if(oldImplementation)
1242 bpRunToCursor = Breakpoint { };
1243 bpRunToCursor.absoluteFilePath = absoluteFilePath;
1244 bpRunToCursor.relativeFilePath = relativeFilePath;
1245 bpRunToCursor.line = lineNumber;
1246 bpRunToCursor.type = runToCursor;
1247 bpRunToCursor.enabled = true;
1248 bpRunToCursor.level = atSameLevel ? frameCount - activeFrameLevel -1 : -1;
1253 breakType = advance;
1254 breakString = PrintString(relativeFilePath, ":", lineNumber);
1257 else if(state == stopped)
1259 if(oldImplementation)
1260 GdbExecContinue(true);
1264 GdbExecUntil(absoluteFilePath, lineNumber);
1266 GdbExecAdvance(absoluteFilePath, lineNumber);
1271 void GetCallStackCursorLine(bool * error, int * lineCursor, int * lineTopFrame)
1273 //_dpl2(_dpct, dplchan::debuggerCall, 0, "Debugger::GetCallStackCursorLine()");
1274 if(activeFrameLevel == -1)
1282 *error = signalOn && activeThread == signalThread;
1283 *lineCursor = activeFrameLevel - ((frameCount > 192 && activeFrameLevel > 191) ? frameCount - 192 - 1 : 0) + 1;
1284 *lineTopFrame = activeFrameLevel ? 1 : 0;
1288 int GetMarginIconsLineNumbers(char * fileName, int lines[], bool enabled[], int max, bool * error, int * lineCursor, int * lineTopFrame)
1290 char winFilePath[MAX_LOCATION];
1291 char * absoluteFilePath = GetSlashPathBuffer(winFilePath, fileName);
1293 Iterator<Breakpoint> it { ide.workspace.breakpoints };
1294 //_dpl2(_dpct, dplchan::debuggerCall, 0, "Debugger::GetMarginIconsLineNumbers()");
1295 while(it.Next() && count < max)
1297 Breakpoint bp = it.data;
1300 if(bp.absoluteFilePath && bp.absoluteFilePath[0] && !fstrcmp(bp.absoluteFilePath, absoluteFilePath))
1302 lines[count] = bp.line;
1303 enabled[count] = bp.enabled;
1308 if(activeFrameLevel == -1)
1316 *error = signalOn && activeThread == signalThread;
1317 if(activeFrame && activeFrame.absoluteFile && !fstrcmp(absoluteFilePath, activeFrame.absoluteFile))
1318 *lineCursor = activeFrame.line;
1321 if(activeFrame && stopItem && stopItem.frame && activeFrame.level == stopItem.frame.level)
1323 else if(stopItem && stopItem.frame && stopItem.frame.absoluteFile && !fstrcmp(absoluteFilePath, stopItem.frame.absoluteFile))
1324 *lineTopFrame = stopItem.frame.line;
1328 if(*lineTopFrame == *lineCursor && *lineTopFrame)
1334 void ChangeWatch(DataRow row, char * expression)
1336 Watch wh = (Watch)row.tag;
1337 //_dpl2(_dpct, dplchan::debuggerCall, 0, "Debugger::ChangeWatch(", expression, ")");
1340 delete wh.expression;
1342 wh.expression = CopyString(expression);
1345 Iterator<Watch> it { ide.workspace.watches };
1347 ide.workspace.watches.Delete(it.pointer);
1353 row.tag = (int64)wh;
1354 ide.workspace.watches.Add(wh);
1356 wh.expression = CopyString(expression);
1358 ide.workspace.Save();
1359 //if(expression && state == stopped)
1364 void MoveIcons(char * fileName, int lineNumber, int move, bool start)
1366 char winFilePath[MAX_LOCATION];
1367 char * absoluteFilePath = GetSlashPathBuffer(winFilePath, fileName);
1370 //_dpl2(_dpct, dplchan::debuggerCall, 0, "Debugger::MoveIcons()");
1371 for(bpLink = ide.workspace.breakpoints.first; bpLink; bpLink = next)
1373 Breakpoint bp = (Breakpoint)bpLink.data;
1376 if(bp.type == user && bp.absoluteFilePath && !fstrcmp(bp.absoluteFilePath, absoluteFilePath))
1378 if(bp.line > lineNumber || (bp.line == lineNumber && start))
1380 if(move < 0 && (bp.line < lineNumber - move))
1381 ide.workspace.RemoveBreakpoint(bp);
1385 ide.breakpointsView.UpdateBreakpoint(bp.row);
1386 ide.workspace.Save();
1392 // moving code cursors is futile, on next step, stop, hit, cursors will be offset anyways
1395 bool SourceDirDialog(char * title, char * startDir, char * test, char * sourceDir)
1399 String srcDir = null;
1401 _dpl2(_dpct, dplchan::debuggerCall, 0, "Debugger::SourceDirDialog()");
1402 debuggerFileDialog.text = title;
1403 debuggerFileDialog.currentDirectory = startDir;
1404 debuggerFileDialog.master = ide;
1406 while(debuggerFileDialog.Modal())
1408 strcpy(sourceDir, debuggerFileDialog.filePath);
1409 if(!fstrcmp(ide.workspace.projectDir, sourceDir) &&
1410 MessageBox { type = yesNo, master = ide,
1411 contents = $"This is the project directory.\nWould you like to try again?",
1412 text = $"Invalid Source Directory" }.Modal() == no)
1416 for(dir : ide.workspace.sourceDirs)
1418 if(!fstrcmp(dir, sourceDir))
1426 MessageBox { type = yesNo, master = ide,
1427 contents = $"This source directory is already specified.\nWould you like to try again?",
1428 text = $"Invalid Source Directory" }.Modal() == no)
1434 char file[MAX_LOCATION];
1435 strcpy(file, sourceDir);
1436 PathCat(file, test);
1437 result = FileExists(file);
1439 MessageBox { type = yesNo, master = ide,
1440 contents = $"Unable to locate source file.\nWould you like to try again?",
1441 text = $"Invalid Source Directory" }.Modal() == no)
1455 void AddSourceDir(char * sourceDir)
1457 _dpl2(_dpct, dplchan::debuggerCall, 0, "Debugger::AddSourceDir(", sourceDir, ")");
1458 ide.workspace.sourceDirs.Add(CopyString(sourceDir));
1459 ide.workspace.Save();
1463 DebuggerState oldState = state;
1468 GdbDebugBreak(true);
1471 GdbCommand(false, "-environment-directory \"%s\"", sourceDir);
1474 if(oldState == running)
1475 GdbExecContinue(false);
1479 void ToggleBreakpoint(char * fileName, int lineNumber, Project prj)
1481 char winFilePath[MAX_LOCATION];
1482 char * absoluteFilePath = GetSlashPathBuffer(winFilePath, fileName);
1483 char absolutePath[MAX_LOCATION];
1484 char relativePath[MAX_LOCATION];
1485 char sourceDir[MAX_LOCATION];
1486 Breakpoint bp = null;
1488 _dpl2(_dpct, dplchan::debuggerBreakpoints, 0, "Debugger::ToggleBreakpoint(", fileName, ":", lineNumber, ")");
1489 strcpy(absolutePath, absoluteFilePath);
1490 for(i : ide.workspace.breakpoints; i.type == user && i.absoluteFilePath && !fstrcmp(i.absoluteFilePath, absolutePath) && i.line == lineNumber)
1499 ide.workspace.RemoveBreakpoint(bp);
1507 // FIXED: This is how it should have been... Source locations are only for files not in project
1508 // if(IsPathInsideOf(absolutePath, ide.workspace.projectDir))
1509 // MakePathRelative(absolutePath, ide.workspace.projectDir, relativePath);
1510 bool result = false;
1512 result = prj.GetRelativePath(absolutePath, relativePath);
1514 result = ide.projectView.project.GetRelativePath(absolutePath, relativePath);
1515 //if(ide.projectView.project.GetRelativePath(absolutePath, relativePath));
1519 char title[MAX_LOCATION];
1520 char directory[MAX_LOCATION];
1521 StripLastDirectory(absolutePath, directory);
1522 snprintf(title, sizeof(title), $"Provide source files location directory for %s", absolutePath);
1523 title[sizeof(title)-1] = 0;
1526 String srcDir = null;
1527 for(dir : ide.workspace.sourceDirs)
1529 if(IsPathInsideOf(absolutePath, dir))
1531 MakePathRelative(absoluteFilePath, dir, relativePath);
1539 if(SourceDirDialog(title, directory, null, sourceDir))
1541 if(IsPathInsideOf(absolutePath, sourceDir))
1543 AddSourceDir(sourceDir);
1544 MakePathRelative(absoluteFilePath, sourceDir, relativePath);
1547 else if(MessageBox { type = yesNo, master = ide,
1548 contents = $"You must provide a valid source directory in order to place a breakpoint in this file.\nWould you like to try again?",
1549 text = $"Invalid Source Directory" }.Modal() == no)
1552 else if(MessageBox { type = yesNo, master = ide,
1553 contents = $"You must provide a source directory in order to place a breakpoint in this file.\nWould you like to try again?",
1554 text = $"No Source Directory Provided" }.Modal() == no)
1558 ide.workspace.bpCount++;
1559 bp = { line = lineNumber, type = user, enabled = true, level = -1, project = prj };
1560 ide.workspace.breakpoints.Add(bp);
1561 bp.absoluteFilePath = absolutePath;
1562 bp.relativeFilePath = relativePath;
1563 ide.breakpointsView.AddBreakpoint(bp);
1568 DebuggerState oldState = state;
1573 GdbDebugBreak(true);
1576 SetBreakpoint(bp, false);
1579 if(oldState == running)
1580 GdbExecContinue(false);
1583 ide.workspace.Save();
1586 void UpdateRemovedBreakpoint(Breakpoint bp)
1588 _dpl2(_dpct, dplchan::debuggerCall, 0, "Debugger::UpdateRemovedBreakpoint()");
1589 if(targeted && bp.inserted)
1591 DebuggerState oldState = state;
1596 GdbDebugBreak(true);
1599 UnsetBreakpoint(bp);
1602 if(oldState == running)
1603 GdbExecContinue(false);
1609 void ParseFrame(Frame frame, char * string)
1612 Array<char *> frameTokens { minAllocSize = 50 };
1613 Array<char *> argsTokens { minAllocSize = 50 };
1614 Array<char *> argumentTokens { minAllocSize = 50 };
1615 DebugListItem item { };
1618 //_dpl2(_dpct, dplchan::debuggerCall, 0, "Debugger::ParseFrame()");
1619 TokenizeList(string, ',', frameTokens);
1620 for(i = 0; i < frameTokens.count; i++)
1622 if(TokenizeListItem(frameTokens[i], item))
1624 StripQuotes(item.value, item.value);
1625 if(!strcmp(item.name, "level"))
1626 frame.level = atoi(item.value);
1627 else if(!strcmp(item.name, "addr"))
1628 frame.addr = item.value;
1629 else if(!strcmp(item.name, "func"))
1630 frame.func = item.value;
1631 else if(!strcmp(item.name, "args"))
1633 if(!strcmp(item.value, "[]"))
1634 frame.argsCount = 0;
1637 item.value = StripBrackets(item.value);
1638 TokenizeList(item.value, ',', argsTokens);
1639 for(j = 0; j < argsTokens.count; j++)
1641 argsTokens[j] = StripCurlies(argsTokens[j]);
1642 TokenizeList(argsTokens[j], ',', argumentTokens);
1643 for(k = 0; k < argumentTokens.count; k++)
1646 frame.args.Add(arg);
1647 if(TokenizeListItem(argumentTokens[k], item))
1649 if(!strcmp(item.name, "name"))
1651 StripQuotes(item.value, item.value);
1652 arg.name = item.value;
1654 else if(!strcmp(item.name, "value"))
1656 StripQuotes(item.value, item.value);
1657 arg.val = item.value;
1660 _dpl2(_dpct, dplchan::gdbProtoUnknown, 0, "frame args item (", item.name, "=", item.value, ") is unheard of");
1663 _dpl(0, "Bad frame args item");
1665 argumentTokens.RemoveAll();
1667 frame.argsCount = argsTokens.count;
1668 argsTokens.RemoveAll();
1671 else if(!strcmp(item.name, "from"))
1672 frame.from = item.value;
1673 else if(!strcmp(item.name, "file"))
1674 frame.file = item.value;
1675 else if(!strcmp(item.name, "line"))
1676 frame.line = atoi(item.value);
1677 else if(!strcmp(item.name, "fullname"))
1678 frame.absoluteFile = item.value;
1680 // GDB 6.3 on OS X is giving "fullname" and "dir", all in absolute, but file name only in 'file'
1681 String path = ide.workspace.GetPathWorkspaceRelativeOrAbsolute(item.value);
1682 if(strcmp(frame.file, path))
1685 frame.absoluteFile = ide.workspace.GetAbsolutePathFromRelative(frame.file);
1690 _dpl2(_dpct, dplchan::gdbProtoUnknown, 0, "frame member (", item.name, "=", item.value, ") is unheard of");
1693 _dpl(0, "Bad frame");
1698 delete argumentTokens;
1702 Breakpoint GetBreakpointById(int id, bool * isInternal)
1704 Breakpoint bp = null;
1705 //_dpl2(_dpct, dplchan::debuggerBreakpoints, 0, "Debugger::GetBreakpointById(", id, ")");
1707 *isInternal = false;
1710 for(i : sysBPs; i.bp && i.bp.id == id)
1717 if(!bp && bpRunToCursor && bpRunToCursor.bp && bpRunToCursor.bp.id == id)
1721 for(i : ide.workspace.breakpoints; i.bp && i.bp.id == id)
1731 GdbDataBreakpoint ParseBreakpoint(char * string, Array<char *> outTokens)
1734 GdbDataBreakpoint bp { };
1735 DebugListItem item { };
1736 Array<char *> bpTokens { minAllocSize = 16 };
1737 _dpl2(_dpct, dplchan::debuggerCall, 0, "Debugger::ParseBreakpoint()");
1738 string = StripCurlies(string);
1739 TokenizeList(string, ',', bpTokens);
1740 for(i = 0; i < bpTokens.count; i++)
1742 if(TokenizeListItem(bpTokens[i], item))
1744 StripQuotes(item.value, item.value);
1745 if(!strcmp(item.name, "number"))
1747 if(!strchr(item.value, '.'))
1748 bp.id = atoi(item.value);
1749 bp.number = item.value;
1751 else if(!strcmp(item.name, "type"))
1752 bp.type = item.value;
1753 else if(!strcmp(item.name, "disp"))
1754 bp.disp = item.value;
1755 else if(!strcmp(item.name, "enabled"))
1756 bp.enabled = (!strcmpi(item.value, "y"));
1757 else if(!strcmp(item.name, "addr"))
1759 if(outTokens && !strcmp(item.value, "<MULTIPLE>"))
1762 Array<GdbDataBreakpoint> bpArray = bp.multipleBPs = { };
1763 while(outTokens.count > ++c)
1765 GdbDataBreakpoint multBp = ParseBreakpoint(outTokens[c], null);
1766 bpArray.Add(multBp);
1770 bp.addr = item.value;
1772 else if(!strcmp(item.name, "func"))
1773 bp.func = item.value;
1774 else if(!strcmp(item.name, "file"))
1775 bp.file = item.value;
1776 else if(!strcmp(item.name, "fullname"))
1777 bp.fullname = item.value;
1778 else if(!strcmp(item.name, "line"))
1779 bp.line = atoi(item.value);
1780 else if(!strcmp(item.name, "at"))
1782 else if(!strcmp(item.name, "times"))
1783 bp.times = atoi(item.value);
1784 else if(!strcmp(item.name, "original-location") || !strcmp(item.name, "thread-groups"))
1785 _dpl2(_dpct, dplchan::gdbProtoIgnored, 0, "breakpoint member (", item.name, "=", item.value, ") is ignored");
1787 _dpl2(_dpct, dplchan::gdbProtoUnknown, 0, "breakpoint member (", item.name, "=", item.value, ") is unheard of");
1793 void ShowDebuggerViews()
1795 //_dpl2(_dpct, dplchan::debuggerCall, 0, "Debugger::ShowDebuggerViews()");
1796 ide.outputView.Show();
1797 ide.outputView.SelectTab(debug);
1798 ide.threadsView.Show();
1799 ide.callStackView.Show();
1800 ide.watchesView.Show();
1804 void HideDebuggerViews()
1806 //_dpl2(_dpct, dplchan::debuggerCall, 0, "Debugger::HideDebuggerViews()");
1807 ide.RepositionWindows(true);
1810 void ::GdbCommand(bool focus, char * format, ...)
1814 // TODO: Improve this limit
1815 static char string[MAX_F_STRING*4];
1817 va_start(args, format);
1818 vsnprintf(string, sizeof(string), format, args);
1819 string[sizeof(string)-1] = 0;
1823 ide.debugger.serialSemaphore.TryWait();
1825 #ifdef GDB_DEBUG_CONSOLE
1826 _dpl2(_dpct, dplchan::gdbCommand, 0, string);
1828 #ifdef GDB_DEBUG_OUTPUT
1829 ide.outputView.gdbBox.Logf("cmd: %s\n", string);
1831 #ifdef GDB_DEBUG_GUI
1833 ide.gdbDialog.AddCommand(string);
1836 strcat(string,"\n");
1837 gdbHandle.Puts(string);
1840 Process_ShowWindows(targetProcessId);
1843 ide.debugger.serialSemaphore.Wait();
1848 bool ValidateBreakpoint(Breakpoint bp)
1850 _dpl2(_dpct, dplchan::debuggerCall, 0, "Debugger::ValidateBreakpoint()");
1851 if(modules && bp.line && bp.bp)
1853 if(bp.bp.line != bp.line)
1859 ide.outputView.debugBox.Logf("WOULD HAVE -- Invalid breakpoint disabled: %s:%d\n", bp.relativeFilePath, bp.line);
1861 //UnsetBreakpoint(bp);
1862 //bp.enabled = false;
1868 ide.outputView.debugBox.Logf("Debugger Error: ValidateBreakpoint error\n");
1869 bp.line = bp.bp.line;
1876 void BreakpointsMaintenance()
1878 //_dpl2(_dpct, dplchan::debuggerBreakpoints, 0, "Debugger::BreakpointsMaintenance()");
1881 if(gdbExecution.suspendInternalBreakpoints)
1883 for(bp : sysBPs; bp.inserted)
1884 UnsetBreakpoint(bp);
1888 DirExpression objDir = ide.project.GetObjDir(currentCompiler, prjConfig, bitDepth);
1889 for(bp : sysBPs; !bp.inserted)
1891 bool insert = false;
1892 if(bp.type == internalModulesLoaded)
1894 char path[MAX_LOCATION];
1895 char name[MAX_LOCATION];
1896 char fixedModuleName[MAX_FILENAME];
1899 bool moduleLoadBlock = false;
1901 ReplaceSpaces(fixedModuleName, ide.project.moduleName);
1902 snprintf(name, sizeof(name),"%s.main.ec", fixedModuleName);
1903 name[sizeof(name)-1] = 0;
1904 strcpy(path, ide.workspace.projectDir);
1905 PathCatSlash(path, objDir.dir);
1906 PathCatSlash(path, name);
1907 f = FileOpen(path, read);
1910 for(lineNumber = 1; !f.Eof(); lineNumber++)
1912 if(f.GetLine(line, sizeof(line) - 1))
1914 bool moduleLoadLine;
1915 TrimLSpaces(line, line);
1916 moduleLoadLine = !strncmp(line, "eModule_Load", strlen("eModule_Load"));
1917 if(!moduleLoadBlock && moduleLoadLine)
1918 moduleLoadBlock = true;
1919 else if(moduleLoadBlock && !moduleLoadLine && strlen(line) > 0)
1925 char relative[MAX_LOCATION];
1926 bp.absoluteFilePath = path;
1927 MakePathRelative(path, ide.workspace.projectDir, relative);
1928 bp.relativeFilePath = relative;
1929 bp.line = lineNumber;
1935 else if(bp.type == internalModuleLoad)
1939 for(prj : ide.workspace.projects)
1941 if(!strcmp(prj.moduleName, "ecere"))
1943 ProjectNode node = prj.topNode.Find("instance.c", false);
1946 char path[MAX_LOCATION];
1947 char relative[MAX_LOCATION];
1948 node.GetFullFilePath(path);
1949 bp.absoluteFilePath = path;
1950 MakePathRelative(path, prj.topNode.path, relative);
1951 bp.relativeFilePath = relative;
1962 SetBreakpoint(bp, false);
1967 if(userAction != runToCursor && bpRunToCursor && bpRunToCursor.inserted)
1968 UnsetBreakpoint(bpRunToCursor);
1969 if(bpRunToCursor && !bpRunToCursor.inserted)
1970 SetBreakpoint(bpRunToCursor, false);
1972 if(ignoreBreakpoints)
1974 for(bp : ide.workspace.breakpoints; bp.inserted)
1975 UnsetBreakpoint(bp);
1979 for(bp : ide.workspace.breakpoints; !bp.inserted && bp.type == user)
1983 if(!SetBreakpoint(bp, false))
1984 SetBreakpoint(bp, true);
1992 bp.bp = GdbDataBreakpoint { };
1999 void UnsetBreakpoint(Breakpoint bp)
2001 char * s; _dpl2(_dpct, dplchan::debuggerBreakpoints, 0, "Debugger::UnsetBreakpoint(", s=bp.CopyLocationString(false), ") -- ", bp.type); delete s;
2002 if(symbols && bp.inserted)
2004 GdbCommand(false, "-break-delete %s", bp.bp.number);
2005 bp.inserted = false;
2010 bool SetBreakpoint(Breakpoint bp, bool removePath)
2012 char * s; _dpl2(_dpct, dplchan::debuggerBreakpoints, 0, "Debugger::SetBreakpoint(", s=bp.CopyLocationString(false), ", ", removePath ? "**** removePath(true) ****" : "", ") -- ", bp.type); delete s;
2013 breakpointError = false;
2014 if(symbols && bp.enabled && (!bp.project || bp.project == ide.project || projectsLibraryLoaded[bp.project.name]))
2016 char * location = bp.CopyLocationString(removePath);
2017 sentBreakInsert = true;
2018 GdbCommand(false, "-break-insert %s", location);
2020 if(!breakpointError)
2022 if(bpItem && bpItem.multipleBPs && bpItem.multipleBPs.count)
2025 GdbDataBreakpoint first = null;
2026 for(n : bpItem.multipleBPs)
2028 if(!fstrcmp(n.fullname, bp.absoluteFilePath))
2038 GdbCommand(false, "-break-disable %s", n.number);
2042 _dpl2(_dpct, dplchan::debuggerProblem, 0, "Debugger::SetBreakpoint -- error breakpoint already disabled.");
2047 bpItem.addr = first.addr;
2048 bpItem.func = first.func;
2049 bpItem.file = first.file;
2050 bpItem.fullname = first.fullname;
2051 bpItem.line = first.line;
2052 //bpItem.thread-groups = first.thread-groups;
2053 bpItem.multipleBPs.Free();
2054 delete bpItem.multipleBPs;
2057 _dpl2(_dpct, dplchan::debuggerProblem, 0, "Debugger::SetBreakpoint -- error multiple breakpoints all disabled.");
2059 _dpl2(_dpct, dplchan::debuggerProblem, 0, "Debugger::SetBreakpoint -- error multiple breakpoints in exact same file not supported.");
2063 bp.inserted = (bp.bp && bp.bp.number && strcmp(bp.bp.number, "0"));
2065 ValidateBreakpoint(bp);
2068 return !breakpointError;
2073 _dpl2(_dpct, dplchan::debuggerCall, 0, "Debugger::GdbGetStack()");
2075 stackFrames.Free(Frame::Free);
2076 GdbCommand(false, "-stack-info-depth");
2078 GdbCommand(false, "-stack-info-depth 192");
2079 if(frameCount && frameCount <= 192)
2080 GdbCommand(false, "-stack-list-frames 0 %d", Min(frameCount-1, 191));
2083 GdbCommand(false, "-stack-list-frames 0 %d", Min(frameCount-1, 95));
2084 GdbCommand(false, "-stack-list-frames %d %d", Max(frameCount - 96, 96), frameCount - 1);
2086 GdbCommand(false, "");
2091 _dpl2(_dpct, dplchan::debuggerCall, 0, "Debugger::GdbTargetSet()");
2094 char escaped[MAX_LOCATION];
2095 strescpy(escaped, targetFile);
2096 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
2103 const char *vgdbCommand = "/usr/bin/vgdb"; // TODO: vgdb command config option
2104 //GdbCommand(false, "-target-select remote | %s --pid=%d", "vgdb", targetProcessId);
2105 printf("target remote | %s --pid=%d\n", vgdbCommand, targetProcessId);
2106 GdbCommand(false, "target remote | %s --pid=%d", vgdbCommand, targetProcessId); // TODO: vgdb command config option
2109 GdbCommand(false, "info target"); //GDB/MI Missing Implementation -file-list-symbol-files and -file-list-exec-sections
2111 /*for(prj : ide.workspace.projects; prj != ide.workspace.projects.firstIterator.data)
2112 GdbCommand(false, "-environment-directory \"%s\"", prj.topNode.path);*/
2114 for(dir : ide.workspace.sourceDirs; dir && dir[0])
2116 bool interference = false;
2117 for(prj : ide.workspace.projects)
2119 if(!fstrcmp(prj.topNode.path, dir))
2121 interference = true;
2125 if(!interference && dir[0])
2126 GdbCommand(false, "-environment-directory \"%s\"", dir);
2134 /*void GdbTargetRelease()
2138 BreakpointsDeleteAll();
2139 GdbCommand(false, "file"); //GDB/MI Missing Implementation -target-detach
2145 void GdbDebugBreak(bool internal)
2147 _dpl2(_dpct, dplchan::debuggerCall, 0, "Debugger::GdbDebugBreak()");
2151 breakType = DebuggerAction::internal;
2153 if(ide) ide.Update(null);
2155 if(Process_Break(targetProcessId)) //GdbCommand(false, "-exec-interrupt");
2156 serialSemaphore.Wait();
2159 _ChangeState(loaded);
2160 targetProcessId = 0;
2165 ide.outputView.debugBox.Logf("Debugger Error: GdbDebugBreak with not target id should never happen\n");
2170 _dpl2(_dpct, dplchan::debuggerCall, 0, "Debugger::GdbExecRun()");
2175 ShowDebuggerViews();
2177 GdbExecContinue(true);
2179 GdbCommand(true, "-exec-run");
2182 void GdbExecContinue(bool focus)
2184 _dpl2(_dpct, dplchan::debuggerCall, 0, "Debugger::GdbExecContinue()");
2187 GdbCommand(focus, "-exec-continue");
2192 _dpl2(_dpct, dplchan::debuggerCall, 0, "Debugger::GdbExecNext()");
2193 gdbExecution = next;
2195 GdbCommand(true, "-exec-next");
2198 void GdbExecUntil(char * absoluteFilePath, int lineNumber)
2200 char relativeFilePath[MAX_LOCATION];
2201 _dpl2(_dpct, dplchan::debuggerCall, 0, "Debugger::GdbExecUntil()");
2202 gdbExecution = until;
2204 if(absoluteFilePath)
2206 if(!ide.projectView.project.GetRelativePath(absoluteFilePath, relativeFilePath))
2207 strcpy(relativeFilePath, absoluteFilePath);
2208 GdbCommand(true, "-exec-until %s:%d", relativeFilePath, lineNumber);
2211 GdbCommand(true, "-exec-until");
2214 void GdbExecAdvance(char * absoluteFilePathOrLocation, int lineNumber)
2216 char relativeFilePath[MAX_LOCATION];
2217 _dpl2(_dpct, dplchan::debuggerCall, 0, "Debugger::GdbExecAdvance()");
2218 gdbExecution = advance;
2222 if(!ide.projectView.project.GetRelativePath(absoluteFilePathOrLocation, relativeFilePath))
2223 strcpy(relativeFilePath, absoluteFilePathOrLocation);
2224 GdbCommand(true, "advance %s:%d", relativeFilePath, lineNumber); // should use -exec-advance -- GDB/MI implementation missing
2227 GdbCommand(true, "advance %s", absoluteFilePathOrLocation); // should use -exec-advance -- GDB/MI implementation missing
2232 _dpl2(_dpct, dplchan::debuggerCall, 0, "Debugger::GdbExecStep()");
2233 gdbExecution = step;
2235 GdbCommand(true, "-exec-step");
2238 void GdbExecFinish()
2240 _dpl2(_dpct, dplchan::debuggerCall, 0, "Debugger::GdbExecFinish()");
2241 gdbExecution = finish;
2243 GdbCommand(true, "-exec-finish");
2246 void GdbExecCommon()
2248 //_dpl2(_dpct, dplchan::debuggerCall, 0, "Debugger::GdbExecCommon()");
2249 BreakpointsMaintenance();
2252 #ifdef GDB_DEBUG_GUI
2253 void SendGDBCommand(char * command)
2255 //_dpl2(_dpct, dplchan::debuggerCall, 0, "Debugger::SendGDBCommand()");
2256 DebuggerState oldState = state;
2261 GdbDebugBreak(true);
2264 GdbCommand(false, command);
2267 if(oldState == running)
2268 GdbExecContinue(false);
2272 void ClearBreakDisplay()
2274 //_dpl2(_dpct, dplchan::debuggerCall, 0, "Debugger::ClearBreakDisplay()");
2276 activeFrameLevel = -1;
2286 stackFrames.Free(Frame::Free);
2287 ide.callStackView.Clear();
2288 ide.threadsView.Clear();
2294 _dpl2(_dpct, dplchan::debuggerCall, 0, "Debugger::GdbAbortExec()");
2296 GdbCommand(false, "-interpreter-exec console \"kill\""); // should use -exec-abort -- GDB/MI implementation incomplete
2300 bool GdbInit(CompilerConfig compiler, ProjectConfig config, int bitDepth, bool useValgrind)
2303 char oldDirectory[MAX_LOCATION];
2304 char tempPath[MAX_LOCATION];
2305 char command[MAX_F_STRING*4];
2306 Project project = ide.project;
2307 DirExpression targetDirExp = project.GetTargetDir(compiler, config, bitDepth);
2308 PathBackup pathBackup { };
2310 _dpl2(_dpct, dplchan::debuggerCall, 0, "Debugger::GdbInit()");
2311 if(currentCompiler != compiler)
2313 delete currentCompiler;
2314 currentCompiler = compiler;
2315 incref currentCompiler;
2318 this.bitDepth = bitDepth;
2319 usingValgrind = useValgrind;
2321 _ChangeState(loaded);
2323 sentBreakInsert = false;
2324 breakpointError = false;
2325 ignoreBreakpoints = false;
2330 projectsLibraryLoaded.Free();
2332 ide.outputView.ShowClearSelectTab(debug);
2333 ide.outputView.debugBox.Logf($"Starting debug mode\n");
2335 #ifdef GDB_DEBUG_OUTPUT
2336 ide.outputView.gdbBox.Logf("run: Starting GDB\n");
2339 strcpy(tempPath, ide.workspace.projectDir);
2340 PathCatSlash(tempPath, targetDirExp.dir);
2342 targetDir = CopyString(tempPath);
2343 project.CatTargetFileName(tempPath, compiler, config);
2345 targetFile = CopyString(tempPath);
2347 GetWorkingDir(oldDirectory, MAX_LOCATION);
2348 if(ide.workspace.debugDir && ide.workspace.debugDir[0])
2350 char temp[MAX_LOCATION];
2351 strcpy(temp, ide.workspace.projectDir);
2352 PathCatSlash(temp, ide.workspace.debugDir);
2353 ChangeWorkingDir(temp);
2356 ChangeWorkingDir(ide.workspace.projectDir);
2358 ide.SetPath(true, compiler, config, bitDepth);
2360 // TODO: This pollutes the environment, but at least it works
2361 // It shouldn't really affect the IDE as the PATH gets restored and other variables set for testing will unlikely cause problems
2362 // What is the proper solution for this? DualPipeOpenEnv?
2363 // gdb set environment commands don't seem to take effect
2364 for(e : ide.workspace.environmentVars)
2366 SetEnvironment(e.name, e.string);
2371 char * clArgs = ide.workspace.commandLineArgs;
2372 const char *valgrindCommand = "valgrind"; // TODO: valgrind command config option //TODO: valgrind options
2373 ValgrindLeakCheck vgLeakCheck = ide.workspace.vgLeakCheck;
2374 int vgRedzoneSize = ide.workspace.vgRedzoneSize;
2375 bool vgTrackOrigins = ide.workspace.vgTrackOrigins;
2376 vgLogFile = CreateTemporaryFile(vgLogPath, "ecereidevglog");
2380 vgLogThread.Create();
2384 ide.outputView.debugBox.Logf($"Debugger Fatal Error: Couldn't open temporary log file for Valgrind output\n");
2387 if(result && !CheckCommandAvailable(valgrindCommand))
2389 ide.outputView.debugBox.Logf($"Debugger Fatal Error: Command %s for Valgrind is not available.\n", valgrindCommand);
2394 char * vgRedzoneSizeFlag = vgRedzoneSize == -1 ? "" : PrintString(" --redzone-size=", vgRedzoneSize);
2395 sprintf(command, "%s --vgdb=yes --vgdb-error=0 --log-file=%s --leak-check=%s%s --track-origins=%s %s%s%s",
2396 valgrindCommand, vgLogPath, (char*)vgLeakCheck, vgRedzoneSizeFlag, vgTrackOrigins ? "yes" : "no", targetFile, clArgs ? " " : "", clArgs ? clArgs : "");
2397 if(vgRedzoneSize != -1)
2398 delete vgRedzoneSizeFlag;
2399 vgTargetHandle = DualPipeOpen(PipeOpenMode { output = true, /*error = true, */input = true }, command);
2402 ide.outputView.debugBox.Logf($"Debugger Fatal Error: Couldn't start Valgrind\n");
2408 incref vgTargetHandle;
2409 vgTargetThread.Create();
2411 targetProcessId = vgTargetHandle.GetProcessID();
2412 waitingForPID = false;
2413 if(!targetProcessId)
2415 ide.outputView.debugBox.Logf($"Debugger Fatal Error: Couldn't get Valgrind process ID\n");
2422 serialSemaphore.Wait();
2430 (compiler.targetPlatform == win32 && bitDepth == 64) ? "x86_64-w64-mingw32-gdb" :
2431 (compiler.targetPlatform == win32 && bitDepth == 32) ? "i686-w64-mingw32-gdb" :
2433 if(!CheckCommandAvailable(command))
2435 ide.outputView.debugBox.Logf($"Debugger Fatal Error: Command %s for GDB is not available.\n", command);
2440 strcat(command, " -n -silent --interpreter=mi2"); //-async //\"%s\"
2442 gdbHandle = DualPipeOpen(PipeOpenMode { output = true, /*error = true, */input = true }, command);
2445 ide.outputView.debugBox.Logf($"Debugger Fatal Error: Couldn't start GDB\n");
2455 gdbProcessId = gdbHandle.GetProcessID();
2458 ide.outputView.debugBox.Logf($"Debugger Fatal Error: Couldn't get GDB process ID\n");
2465 serialSemaphore.Wait();
2468 GdbCommand(false, "-gdb-set verbose off");
2469 //GdbCommand(false, "-gdb-set exec-done-display on");
2470 GdbCommand(false, "-gdb-set step-mode off");
2471 GdbCommand(false, "-gdb-set unwindonsignal on");
2472 //GdbCommand(false, "-gdb-set shell on");
2473 GdbCommand(false, "set print elements 992");
2474 GdbCommand(false, "-gdb-set backtrace limit 100000");
2478 //_ChangeState(terminated);
2484 #if defined(__unix__)
2486 CreateTemporaryDir(progFifoDir, "ecereide");
2487 strcpy(progFifoPath, progFifoDir);
2488 PathCat(progFifoPath, "ideprogfifo");
2489 if(!mkfifo(progFifoPath, 0600))
2491 //fileCreated = true;
2496 ide.outputView.debugBox.Logf(createFIFOMsg, progFifoPath);
2503 progThread.terminate = false;
2504 progThread.Create();
2508 #if defined(__WIN32__)
2509 GdbCommand(false, "-gdb-set new-console on");
2512 #if defined(__unix__)
2514 GdbCommand(false, "-inferior-tty-set %s", progFifoPath);
2518 GdbCommand(false, "-gdb-set args %s", ide.workspace.commandLineArgs ? ide.workspace.commandLineArgs : "");
2520 for(e : ide.workspace.environmentVars)
2522 GdbCommand(false, "set environment %s=%s", e.name, e.string);
2527 ChangeWorkingDir(oldDirectory);
2533 delete targetDirExp;
2539 _dpl2(_dpct, dplchan::debuggerCall, 0, "Debugger::GdbExit()");
2540 if(gdbHandle && gdbProcessId)
2543 GdbCommand(false, "-gdb-exit");
2558 _ChangeState(terminated); // this state change seems to be superfluous, is it safety for something?
2564 for(bp : ide.workspace.breakpoints)
2566 bp.inserted = false;
2572 bp.inserted = false;
2577 bpRunToCursor.inserted = false;
2578 delete bpRunToCursor.bp;
2581 ide.outputView.debugBox.Logf($"Debugging stopped\n");
2582 ClearBreakDisplay();
2585 #if defined(__unix__)
2586 if(!usingValgrind && FileExists(progFifoPath)) //fileCreated)
2588 progThread.terminate = true;
2591 fifoFile.CloseInput();
2597 DeleteFile(progFifoPath);
2598 progFifoPath[0] = '\0';
2604 bool WatchesLinkCodeEditor()
2606 bool goodFrame = activeFrame && activeFrame.absoluteFile;
2607 //_dpl2(_dpct, dplchan::debuggerCall, 0, "Debugger::WatchesLinkCodeEditor()");
2608 if(codeEditor && (!goodFrame || fstrcmp(codeEditor.fileName, activeFrame.absoluteFile)))
2609 WatchesReleaseCodeEditor();
2611 if(!codeEditor && goodFrame)
2613 codeEditor = (CodeEditor)ide.OpenFile(activeFrame.absoluteFile, normal, false, null, no, normal, false);
2616 codeEditor.inUseDebug = true;
2620 return codeEditor != null;
2623 void WatchesReleaseCodeEditor()
2625 //_dpl2(_dpct, dplchan::debuggerCall, 0, "Debugger::WatchesReleaseCodeEditor()");
2628 codeEditor.inUseDebug = false;
2629 if(!codeEditor.visible)
2630 codeEditor.Destroy(0);
2635 bool ResolveWatch(Watch wh)
2637 bool result = false;
2639 _dpl2(_dpct, dplchan::debuggerWatches, 0, "Debugger::ResolveWatch()");
2651 char watchmsg[MAX_F_STRING];
2652 if(state == stopped && !codeEditor)
2653 wh.value = CopyString($"No source file found for selected frame");
2654 //if(codeEditor && state == stopped || state != stopped)
2657 Module backupPrivateModule;
2658 Context backupContext;
2659 Class backupThisClass;
2663 backupPrivateModule = GetPrivateModule();
2664 backupContext = GetCurrentContext();
2665 backupThisClass = GetThisClass();
2668 SetPrivateModule(codeEditor.privateModule);
2669 SetCurrentContext(codeEditor.globalContext);
2670 SetTopContext(codeEditor.globalContext);
2671 SetGlobalContext(codeEditor.globalContext);
2672 SetGlobalData(&codeEditor.globalData);
2675 exp = ParseExpressionString(wh.expression);
2677 if(exp && !parseError)
2679 char expString[4096];
2681 PrintExpression(exp, expString);
2683 if(GetPrivateModule())
2686 DebugFindCtxTree(codeEditor.ast, activeFrame.line, 0);
2687 ProcessExpressionType(exp);
2689 wh.type = exp.expType;
2692 DebugComputeExpression(exp);
2693 if(ExpressionIsError(exp))
2695 GDBFallBack(exp, expString);
2698 /*if(exp.hasAddress)
2700 char temp[MAX_F_STRING];
2701 sprintf(temp, "0x%x", exp.address);
2702 wh.address = CopyString(temp);
2703 // wh.address = CopyStringf("0x%x", exp.address);
2708 Type dataType = exp.expType;
2711 char temp[MAX_F_STRING];
2712 switch(dataType.kind)
2715 sprintf(temp, "%i", exp.val.c);
2718 sprintf(temp, "%i", exp.val.s);
2723 sprintf(temp, "%i", exp.val.i);
2726 sprintf(temp, "%i", exp.val.i64);
2729 sprintf(temp, "%i", exp.val.p);
2734 long v = (long)exp.val.f;
2735 sprintf(temp, "%i", v);
2740 long v = (long)exp.val.d;
2741 sprintf(temp, "%i", v);
2746 wh.intVal = CopyString(temp);
2747 switch(dataType.kind)
2750 sprintf(temp, "0x%x", exp.val.c);
2753 sprintf(temp, "0x%x", exp.val.s);
2757 sprintf(temp, "0x%x", exp.val.i);
2760 sprintf(temp, "0x%x", exp.val.i64);
2763 sprintf(temp, "0x%x", exp.val.i64);
2766 sprintf(temp, "0x%x", exp.val.p);
2771 long v = (long)exp.val.f;
2772 sprintf(temp, "0x%x", v);
2777 long v = (long)exp.val.d;
2778 sprintf(temp, "0x%x", v);
2783 wh.hexVal = CopyString(temp);
2784 switch(dataType.kind)
2787 sprintf(temp, "0o%o", exp.val.c);
2790 sprintf(temp, "0o%o", exp.val.s);
2794 sprintf(temp, "0o%o", exp.val.i);
2797 sprintf(temp, "0o%o", exp.val.i64);
2800 sprintf(temp, "0o%o", exp.val.i64);
2803 sprintf(temp, "0o%o", exp.val.p);
2808 long v = (long)exp.val.f;
2809 sprintf(temp, "0o%o", v);
2814 long v = (long)exp.val.d;
2815 sprintf(temp, "0o%o", v);
2820 wh.octVal = CopyString(temp);
2823 // WHATS THIS HERE ?
2824 if(exp.type == constantExp && exp.constant)
2825 wh.constant = CopyString(exp.constant);
2831 case symbolErrorExp:
2832 snprintf(watchmsg, sizeof(watchmsg), $"Symbol \"%s\" not found", exp.identifier.string);
2834 case structMemberSymbolErrorExp:
2835 // todo get info as in next case (ExpClassMemberSymbolError)
2836 snprintf(watchmsg, sizeof(watchmsg), $"Error: Struct member not found for \"%s\"", wh.expression);
2838 case classMemberSymbolErrorExp:
2841 Expression memberExp = exp.member.exp;
2842 Identifier memberID = exp.member.member;
2843 Type type = memberExp.expType;
2846 _class = (memberID && memberID.classSym) ? memberID.classSym.registered : ((type.kind == classType && type._class) ? type._class.registered : null);
2849 char string[256] = "";
2851 PrintTypeNoConst(type, string, false, true);
2852 classSym = FindClass(string);
2853 _class = classSym ? classSym.registered : null;
2856 snprintf(watchmsg, sizeof(watchmsg), $"Member \"%s\" not found in class \"%s\"", memberID ? memberID.string : "", _class.name);
2858 snprintf(watchmsg, sizeof(watchmsg), "Member \"%s\" not found in unregistered class? (Should never get this message)", memberID ? memberID.string : "");
2861 snprintf(watchmsg, sizeof(watchmsg), "Member \"%s\" not found in no type? (Should never get this message)", memberID ? memberID.string : "");
2864 case memoryErrorExp:
2865 // Need to ensure when set to memoryErrorExp, constant is set
2866 snprintf(watchmsg, sizeof(watchmsg), $"Memory can't be read at %s", /*(exp.type == constantExp) ? */exp.constant /*: null*/);
2868 case dereferenceErrorExp:
2869 snprintf(watchmsg, sizeof(watchmsg), $"Dereference failure for \"%s\"", wh.expression);
2871 case unknownErrorExp:
2872 snprintf(watchmsg, sizeof(watchmsg), $"Unknown error for \"%s\"", wh.expression);
2874 case noDebuggerErrorExp:
2875 snprintf(watchmsg, sizeof(watchmsg), $"Debugger required for symbol evaluation in \"%s\"", wh.expression);
2877 case debugStateErrorExp:
2878 snprintf(watchmsg, sizeof(watchmsg), $"Incorrect debugger state for symbol evaluation in \"%s\"", wh.expression);
2881 snprintf(watchmsg, sizeof(watchmsg), $"Null type for \"%s\"", wh.expression);
2885 // Temporary Code for displaying Strings
2886 if((exp.expType && ((exp.expType.kind == pointerType ||
2887 exp.expType.kind == arrayType) && exp.expType.type.kind == charType)) ||
2888 (wh.type && wh.type.kind == classType && wh.type._class &&
2889 wh.type._class.registered && wh.type._class.registered.type == normalClass &&
2890 !strcmp(wh.type._class.registered.name, "String")))
2893 if(exp.expType.kind != arrayType || exp.hasAddress)
2899 //char temp[MAX_F_STRING * 32];
2901 ExpressionType evalError = dummyExp;
2902 /*if(exp.expType.kind == arrayType)
2903 sprintf(temp, "(char*)0x%x", exp.address);
2905 sprintf(temp, "(char*)%s", exp.constant);*/
2907 //evaluation = Debugger::EvaluateExpression(temp, &evalError);
2908 // address = strtoul(exp.constant, null, 0);
2909 address = _strtoui64(exp.constant, null, 0);
2910 //_dpl(0, "0x", address);
2911 // snprintf(value, sizeof(value), "0x%08x ", address);
2913 if(address > 0xFFFFFFFFLL)
2914 snprintf(value, sizeof(value), (GetRuntimePlatform() == win32) ? "0x%016I64x " : "0x%016llx ", address);
2916 snprintf(value, sizeof(value), (GetRuntimePlatform() == win32) ? "0x%08I64x " : "0x%08llx ", address);
2917 value[sizeof(value)-1] = 0;
2920 strcat(value, $"Null string");
2924 len = strlen(value);
2926 while(!string && size > 2)
2928 string = GdbReadMemory(address, size);
2931 if(string && string[0])
2934 if(UTF8Validate(string))
2939 for(c = 0; (ch = string[c]) && c<4096; c++)
2942 value[len++] = '\0';
2947 ISO8859_1toUTF8(string, value + len, 4096 - len - 30);
2948 strcat(value, ") (ISO8859-1)");
2955 strcat(value, $"Empty string");
2959 strcat(value, $"Couldn't read memory");
2961 wh.value = CopyString(value);
2964 else if(wh.type && wh.type.kind == classType && wh.type._class &&
2965 wh.type._class.registered && wh.type._class.registered.type == enumClass)
2967 uint64 value = strtoul(exp.constant, null, 0);
2968 Class enumClass = eSystem_FindClass(GetPrivateModule(), wh.type._class.registered.name);
2969 EnumClassData enumeration = (EnumClassData)enumClass.data;
2971 for(item = enumeration.values.first; item; item = item.next)
2972 if((int)item.data == value)
2975 wh.value = CopyString(item.name);
2977 wh.value = CopyString($"Invalid Enum Value");
2980 else if(wh.type && (wh.type.kind == charType || (wh.type.kind == classType && wh.type._class &&
2981 wh.type._class.registered && !strcmp(wh.type._class.registered.fullName, "ecere::com::unichar"))) )
2988 if(exp.constant[0] == '\'')
2990 if((int)((byte *)exp.constant)[1] > 127)
2993 value = UTF8GetChar(exp.constant + 1, &nb);
2994 if(nb < 2) value = exp.constant[1];
2995 signedValue = value;
2999 signedValue = exp.constant[1];
3001 // Precomp Syntax error with boot strap here:
3002 byte b = (byte)(char)signedValue;
3003 value = (unichar) b;
3009 if(wh.type.kind == charType && wh.type.isSigned)
3011 signedValue = (int)(char)strtol(exp.constant, null, 0);
3013 // Precomp Syntax error with boot strap here:
3014 byte b = (byte)(char)signedValue;
3015 value = (unichar) b;
3020 value = (uint)strtoul(exp.constant, null, 0);
3021 signedValue = (int)value;
3025 UTF32toUTF8Len(&value, 1, charString, 5);
3027 snprintf(string, sizeof(string), "\'\\0' (0)");
3028 else if(value == '\t')
3029 snprintf(string, sizeof(string), "\'\\t' (%d)", value);
3030 else if(value == '\n')
3031 snprintf(string, sizeof(string), "\'\\n' (%d)", value);
3032 else if(value == '\r')
3033 snprintf(string, sizeof(string), "\'\\r' (%d)", value);
3034 else if(wh.type.kind == charType && wh.type.isSigned)
3035 snprintf(string, sizeof(string), "\'%s\' (%d)", charString, signedValue);
3036 else if(value > 256 || wh.type.kind != charType)
3038 if(value > 0x10FFFF || !GetCharCategory(value))
3039 snprintf(string, sizeof(string), $"Invalid Unicode Keypoint (0x%08X)", value);
3041 snprintf(string, sizeof(string), "\'%s\' (U+%04X)", charString, value);
3044 snprintf(string, sizeof(string), "\'%s\' (%d)", charString, value);
3045 string[sizeof(string)-1] = 0;
3047 wh.value = CopyString(string);
3052 wh.value = CopyString(exp.constant);
3059 wh.value = PrintHexUInt64(exp.address);
3064 char tempString[256];
3065 if(exp.member.memberType == propertyMember)
3066 snprintf(watchmsg, sizeof(watchmsg), $"Missing property evaluation support for \"%s\"", wh.expression);
3068 snprintf(watchmsg, sizeof(watchmsg), $"Evaluation failed for \"%s\" of type \"%s\"", wh.expression,
3069 exp.type.OnGetString(tempString, null, null));
3075 snprintf(watchmsg, sizeof(watchmsg), $"Invalid expression: \"%s\"", wh.expression);
3076 if(exp) FreeExpression(exp);
3079 SetPrivateModule(backupPrivateModule);
3080 SetCurrentContext(backupContext);
3081 SetTopContext(backupContext);
3082 SetGlobalContext(backupContext);
3083 SetThisClass(backupThisClass);
3086 // wh.value = CopyString("No source file found for selected frame");
3088 watchmsg[sizeof(watchmsg)-1] = 0;
3090 wh.value = CopyString(watchmsg);
3092 ide.watchesView.UpdateWatch(wh);
3096 void EvaluateWatches()
3098 _dpl2(_dpct, dplchan::debuggerWatches, 0, "Debugger::EvaluateWatches()");
3099 WatchesLinkCodeEditor();
3100 if(state == stopped)
3102 for(wh : ide.workspace.watches)
3107 char * ::GdbEvaluateExpression(char * expression)
3109 _dpl2(_dpct, dplchan::debuggerWatches, 0, "Debugger::GdbEvaluateExpression(", expression, ")");
3112 GdbCommand(false, "-data-evaluate-expression \"%s\"", expression);
3114 ide.outputView.debugBox.Logf("Debugger Error: GdbEvaluateExpression\n");
3118 // to be removed... use GdbReadMemory that returns a byte array instead
3119 char * ::GdbReadMemoryString(uint64 address, int size, char format, int rows, int cols)
3121 _dpl2(_dpct, dplchan::debuggerCall, 0, "Debugger::GdbReadMemoryString(", address, ")");
3126 _dpl(0, "GdbReadMemoryString called with size = 0!");
3128 // GdbCommand(false, "-data-read-memory 0x%08x %c, %d, %d, %d", address, format, size, rows, cols);
3129 if(GetRuntimePlatform() == win32)
3130 GdbCommand(false, "-data-read-memory 0x%016I64x %c, %d, %d, %d", address, format, size, rows, cols);
3132 GdbCommand(false, "-data-read-memory 0x%016llx %c, %d, %d, %d", address, format, size, rows, cols);
3134 ide.outputView.debugBox.Logf("Debugger Error: GdbReadMemoryString\n");
3138 byte * ::GdbReadMemory(uint64 address, int bytes)
3140 _dpl2(_dpct, dplchan::debuggerCall, 0, "Debugger::GdbReadMemory(", address, ")");
3143 //GdbCommand(false, "-data-read-memory 0x%08x %c, 1, 1, %d", address, 'u', bytes);
3144 if(GetRuntimePlatform() == win32)
3145 GdbCommand(false, "-data-read-memory 0x%016I64x %c, 1, 1, %d", address, 'u', bytes);
3147 GdbCommand(false, "-data-read-memory 0x%016llx %c, 1, 1, %d", address, 'u', bytes);
3150 _dpl(0, "GdbReadMemory called with bytes = 0!");
3153 ide.outputView.debugBox.Logf("Debugger Error: GdbReadMemory\n");
3154 else if(eval.result && strcmp(eval.result, "N/A"))
3156 byte * result = new byte[bytes];
3157 byte * string = eval.result;
3161 result[c++] = (byte)strtol(string, &string, 10);
3177 bool BreakpointHit(GdbDataStop stopItem, Breakpoint bpInternal, Breakpoint bpUser)
3180 char * s1 = null; char * s2 = null;
3181 _dpl2(_dpct, dplchan::debuggerCall, 0, "Debugger::BreakpointHit(",
3182 "bpInternal(", bpInternal ? s1=bpInternal.CopyLocationString(false) : null, "), ",
3183 "bpUser(", bpUser ? s2=bpUser.CopyLocationString(false) : null, ")) -- ",
3184 "ignoreBreakpoints(", ignoreBreakpoints, "), ",
3185 "hitCursorBreakpoint(", bpUser && bpUser.type == runToCursor, ")");
3186 delete s1; delete s2;
3190 bool conditionMet = true;
3191 if(bpUser.condition)
3193 if(WatchesLinkCodeEditor())
3194 conditionMet = ResolveWatch(bpUser.condition);
3196 conditionMet = false;
3211 if(stopItem.frame.line && bpUser.line != stopItem.frame.line)
3213 // updating user breakpoint on hit location difference
3214 // todo, print something?
3215 bpUser.line = stopItem.frame.line;
3216 ide.breakpointsView.UpdateBreakpoint(bpUser.row);
3217 ide.workspace.Save();
3220 ide.breakpointsView.UpdateBreakpoint(bpUser.row);
3225 if(bpInternal.type == internalModulesLoaded)
3227 if(userAction == stepOver)
3229 if((bpInternal.type == internalEntry && ((intBpMain && intBpMain.inserted) || (intBpWinMain && intBpWinMain.inserted))) ||
3230 (bpInternal.type == internalMain && intBpWinMain && intBpWinMain.inserted))
3233 if(!bpUser && !userAction.breaksOnInternalBreakpoint)
3235 if(userAction == stepOut)
3236 StepOut(ignoreBreakpoints);
3242 if(!bpUser && !bpInternal)
3248 void ValgrindTargetThreadExit()
3250 ide.outputView.debugBox.Logf($"ValgrindTargetThreadExit\n");
3253 vgTargetHandle.Wait();
3254 delete vgTargetHandle;
3256 HandleExit(null, null);
3259 void GdbThreadExit()
3261 _dpl2(_dpct, dplchan::debuggerCall, 0, "Debugger::GdbThreadExit()");
3262 if(state != terminated)
3264 _ChangeState(terminated);
3265 targetProcessId = 0;
3266 ClearBreakDisplay();
3272 serialSemaphore.Release();
3277 ide.outputView.debugBox.Logf($"Debugger Fatal Error: GDB lost\n");
3278 ide.outputView.debugBox.Logf($"Debugging stopped\n");
3280 HideDebuggerViews();
3282 //_ChangeState(terminated);
3286 void GdbThreadMain(char * output)
3290 Array<char *> outTokens { minAllocSize = 50 };
3291 Array<char *> subTokens { minAllocSize = 50 };
3292 DebugListItem item { };
3293 DebugListItem item2 { };
3294 bool setWaitingForPID = false;
3296 #if defined(GDB_DEBUG_CONSOLE) || defined(GDB_DEBUG_GUI)
3297 #ifdef GDB_DEBUG_CONSOLE
3298 _dpl2(_dpct, dplchan::gdbOutput, 0, output);
3300 #ifdef GDB_DEBUG_OUTPUT
3302 int len = strlen(output);
3310 for(c = 0; c < len / 1024; c++)
3312 strncpy(tmp, start, 1024);
3313 ide.outputView.gdbBox.Logf("out: %s\n", tmp);
3316 ide.outputView.gdbBox.Logf("out: %s\n", start);
3320 ide.outputView.gdbBox.Logf("out: %s\n", output);
3324 #ifdef GDB_DEBUG_CONSOLE
3325 strcpy(lastGdbOutput, output);
3327 #ifdef GDB_DEBUG_GUI
3328 if(ide.gdbDialog) ide.gdbDialog.AddOutput(output);
3335 if(strstr(output, "No debugging symbols found") || strstr(output, "(no debugging symbols found)"))
3338 ide.outputView.debugBox.Logf($"Target doesn't contain debug information!\n");
3341 if(!entryPoint && (t = strstr(output, "Entry point:")))
3343 char * addr = t + strlen("Entry point:");
3345 if(*t++ == ' ' && *t++ == '0' && *t == 'x')
3348 while(isxdigit(*++t));
3350 for(bp : sysBPs; bp.type == internalEntry)
3353 bp.enabled = entryPoint = true;
3361 if(TokenizeList(output, ',', outTokens) && !strcmp(outTokens[0], "^done"))
3363 //if(outTokens.count == 1)
3368 _ChangeState(loaded);
3369 targetProcessId = 0;
3370 if(outTokens.count > 1 && TokenizeListItem(outTokens[1], item))
3372 if(!strcmp(item.name, "reason"))
3374 char * reason = item.value;
3375 StripQuotes(reason, reason);
3376 if(!strcmp(reason, "exited-normally") || !strcmp(reason, "exited") || !strcmp(reason, "exited-signalled"))
3379 if(outTokens.count > 2 && TokenizeListItem(outTokens[2], item2))
3381 StripQuotes(item2.value, item2.value);
3382 if(!strcmp(item2.name, "exit-code"))
3383 exitCode = item2.value;
3389 HandleExit(reason, exitCode);
3393 _dpl2(_dpct, dplchan::gdbProtoUnknown, 0, "kill reply (", item.name, "=", item.value, ") is unheard of");
3396 HandleExit(null, null);
3399 if(outTokens.count > 1 && TokenizeListItem(outTokens[1], item))
3401 if(!strcmp(item.name, "bkpt"))
3403 sentBreakInsert = false;
3408 bpItem = ParseBreakpoint(item.value, outTokens);
3409 //breakType = bpValidation;
3411 else if(!strcmp(item.name, "depth"))
3413 StripQuotes(item.value, item.value);
3414 frameCount = atoi(item.value);
3416 stackFrames.Free(Frame::Free);
3418 else if(!strcmp(item.name, "stack"))
3421 if(stackFrames.count)
3422 ide.callStackView.Logf("...\n");
3425 item.value = StripBrackets(item.value);
3426 TokenizeList(item.value, ',', subTokens);
3427 for(i = 0; i < subTokens.count; i++)
3429 if(TokenizeListItem(subTokens[i], item))
3431 if(!strcmp(item.name, "frame"))
3434 stackFrames.Add(frame);
3435 item.value = StripCurlies(item.value);
3436 ParseFrame(frame, item.value);
3437 if(frame.file && frame.from)
3438 _dpl2(_dpct, dplchan::gdbProtoUnknown, 0, "unexpected frame file and from members present");
3442 if(activeFrameLevel == -1)
3444 if(ide.projectView.IsModuleInProject(frame.file));
3446 if(frame.level != 0)
3448 //stopItem.frame = frame;
3449 breakType = selectFrame;
3452 activeFrame = frame;
3453 activeFrameLevel = frame.level;
3456 ide.callStackView.Logf("%3d ", frame.level);
3457 if(!strncmp(frame.func, "__ecereMethod_", strlen("__ecereMethod_")))
3458 ide.callStackView.Logf($"%s Method, %s:%d\n", &frame.func[strlen("__ecereMethod_")], (s = CopySystemPath(frame.file)), frame.line);
3459 else if(!strncmp(frame.func, "__ecereProp_", strlen("__ecereProp_")))
3460 ide.callStackView.Logf($"%s Property, %s:%d\n", &frame.func[strlen("__ecereProp_")], (s = CopySystemPath(frame.file)), frame.line);
3461 else if(!strncmp(frame.func, "__ecereConstructor_", strlen("__ecereConstructor_")))
3462 ide.callStackView.Logf($"%s Constructor, %s:%d\n", &frame.func[strlen("__ecereConstructor_")], (s = CopySystemPath(frame.file)), frame.line);
3463 else if(!strncmp(frame.func, "__ecereDestructor_", strlen("__ecereDestructor_")))
3464 ide.callStackView.Logf($"%s Destructor, %s:%d\n", &frame.func[strlen("__ecereDestructor_")], (s = CopySystemPath(frame.file)), frame.line);
3466 ide.callStackView.Logf($"%s Function, %s:%d\n", frame.func, (s = CopySystemPath(frame.file)), frame.line);
3471 ide.callStackView.Logf("%3d ", frame.level);
3476 ide.callStackView.Logf($"inside %s, %s\n", frame.func, (s = CopySystemPath(frame.from)));
3480 ide.callStackView.Logf("%s\n", frame.func);
3482 ide.callStackView.Logf($"unknown source\n");
3486 _dpl2(_dpct, dplchan::gdbProtoUnknown, 0, "stack content (", item.name, "=", item.value, ") is unheard of");
3489 if(activeFrameLevel == -1)
3491 activeFrameLevel = 0;
3492 activeFrame = stackFrames.first;
3494 ide.callStackView.Home();
3496 subTokens.RemoveAll();
3498 /*else if(!strcmp(item.name, "frame"))
3501 item.value = StripCurlies(item.value);
3502 ParseFrame(&frame, item.value);
3504 else if(!strcmp(item.name, "thread-ids"))
3506 ide.threadsView.Clear();
3507 item.value = StripCurlies(item.value);
3508 TokenizeList(item.value, ',', subTokens);
3509 for(i = subTokens.count - 1; ; i--)
3511 if(TokenizeListItem(subTokens[i], item))
3513 if(!strcmp(item.name, "thread-id"))
3516 StripQuotes(item.value, item.value);
3517 value = atoi(item.value);
3518 ide.threadsView.Logf("%3d \n", value);
3521 _dpl2(_dpct, dplchan::gdbProtoUnknown, 0, "threads content (", item.name, "=", item.value, ") is unheard of");
3526 ide.threadsView.Home();
3528 subTokens.RemoveAll();
3529 //if(!strcmp(outTokens[2], "number-of-threads"))
3531 else if(!strcmp(item.name, "new-thread-id"))
3533 StripQuotes(item.value, item.value);
3534 activeThread = atoi(item.value);
3536 else if(!strcmp(item.name, "value"))
3538 StripQuotes(item.value, item.value);
3539 eval.result = CopyString(item.value);
3540 eval.active = false;
3542 else if(!strcmp(item.name, "addr"))
3544 for(i = 2; i < outTokens.count; i++)
3546 if(TokenizeListItem(outTokens[i], item))
3548 if(!strcmp(item.name, "total-bytes"))
3550 StripQuotes(item.value, item.value);
3551 eval.bytes = atoi(item.value);
3553 else if(!strcmp(item.name, "next-row"))
3555 StripQuotes(item.value, item.value);
3556 eval.nextBlockAddress = _strtoui64(item.value, null, 0);
3558 else if(!strcmp(item.name, "memory"))
3562 //StripQuotes(item.value, item.value);
3563 item.value = StripBrackets(item.value);
3564 // this should be treated as a list...
3565 item.value = StripCurlies(item.value);
3566 TokenizeList(item.value, ',', subTokens);
3567 for(j = 0; j < subTokens.count; j++)
3569 if(TokenizeListItem(subTokens[j], item))
3571 if(!strcmp(item.name, "data"))
3573 item.value = StripBrackets(item.value);
3574 StripQuotes2(item.value, item.value);
3575 eval.result = CopyString(item.value);
3576 eval.active = false;
3580 subTokens.RemoveAll();
3585 else if(!strcmp(item.name, "source-path") || !strcmp(item.name, "BreakpointTable"))
3586 _dpl2(_dpct, dplchan::gdbProtoIgnored, 0, "command reply (", item.name, "=", item.value, ") is ignored");
3588 _dpl2(_dpct, dplchan::gdbProtoUnknown, 0, "command reply (", item.name, "=", item.value, ") is unheard of");
3591 else if(!strcmp(outTokens[0], "^running"))
3593 waitingForPID = true;
3594 setWaitingForPID = true;
3595 ClearBreakDisplay();
3597 else if(!strcmp(outTokens[0], "^exit"))
3599 _ChangeState(terminated);
3600 // ide.outputView.debugBox.Logf("Exit\n");
3601 // ide.Update(null);
3603 serialSemaphore.Release();
3605 else if(!strcmp(outTokens[0], "^error"))
3609 sentBreakInsert = false;
3610 breakpointError = true;
3613 if(outTokens.count > 1 && TokenizeListItem(outTokens[1], item))
3615 if(!strcmp(item.name, "msg"))
3617 StripQuotes(item.value, item.value);
3620 eval.active = false;
3622 if(strstr(item.value, "No symbol") && strstr(item.value, "in current context"))
3623 eval.error = symbolNotFound;
3624 else if(strstr(item.value, "Cannot access memory at address"))
3625 eval.error = memoryCantBeRead;
3627 eval.error = unknown;
3629 else if(!strcmp(item.value, "Previous frame inner to this frame (corrupt stack?)"))
3632 else if(!strncmp(item.value, "Cannot access memory at address", 31))
3635 else if(!strcmp(item.value, "Cannot find bounds of current function"))
3637 _ChangeState(stopped);
3638 gdbHandle.Printf("-exec-continue\n");
3640 else if(!strcmp(item.value, "ptrace: No such process."))
3642 _ChangeState(loaded);
3643 targetProcessId = 0;
3645 else if(!strcmp(item.value, "Function \\\"WinMain\\\" not defined."))
3648 else if(!strcmp(item.value, "You can't do that without a process to debug."))
3650 _ChangeState(loaded);
3651 targetProcessId = 0;
3653 else if(strstr(item.value, "No such file or directory."))
3655 _ChangeState(loaded);
3656 targetProcessId = 0;
3658 else if(strstr(item.value, "During startup program exited with code "))
3660 _ChangeState(loaded);
3661 targetProcessId = 0;
3666 if(strlen(item.value) < MAX_F_STRING)
3669 ide.outputView.debugBox.Logf("GDB: %s\n", (s = CopyUnescapedString(item.value)));
3673 ide.outputView.debugBox.Logf("GDB: %s\n", item.value);
3679 _dpl2(_dpct, dplchan::gdbProtoUnknown, 0, "error content (", item.name, "=", item.value, ") is unheard of");
3682 _dpl2(_dpct, dplchan::gdbProtoUnknown, 0, "result-record: ", outTokens[0]);
3683 outTokens.RemoveAll();
3686 _dpl2(_dpct, dplchan::gdbProtoUnknown, 0, "status-async-output: ", outTokens[0]);
3689 if(TokenizeList(output, ',', outTokens))
3691 if(!strcmp(outTokens[0], "=library-loaded"))
3692 FGODetectLoadedLibraryForAddedProjectIssues(outTokens);
3693 else if(!strcmp(outTokens[0], "=thread-group-created") || !strcmp(outTokens[0], "=thread-group-added") ||
3694 !strcmp(outTokens[0], "=thread-group-started") || !strcmp(outTokens[0], "=thread-group-exited") ||
3695 !strcmp(outTokens[0], "=thread-created") || !strcmp(outTokens[0], "=thread-exited") ||
3696 !strcmp(outTokens[0], "=cmd-param-changed") || !strcmp(outTokens[0], "=library-unloaded") ||
3697 !strcmp(outTokens[0], "=breakpoint-modified"))
3698 _dpl2(_dpct, dplchan::gdbProtoIgnored, 0, outTokens[0], outTokens.count>1 ? outTokens[1] : "",
3699 outTokens.count>2 ? outTokens[2] : "", outTokens.count>3 ? outTokens[3] : "",
3700 outTokens.count>4 ? outTokens[4] : "", outTokens.count>5 ? outTokens[5] : "",
3701 outTokens.count>6 ? outTokens[6] : "", outTokens.count>7 ? outTokens[7] : "",
3702 outTokens.count>8 ? outTokens[8] : "", outTokens.count>9 ? outTokens[9] : "");
3704 _dpl2(_dpct, dplchan::gdbProtoUnknown, 0, "notify-async-output: ", outTokens[0]);
3706 outTokens.RemoveAll();
3710 if(TokenizeList(output, ',', outTokens))
3712 if(!strcmp(outTokens[0],"*running"))
3714 waitingForPID = true;
3715 setWaitingForPID = true;
3717 else if(!strcmp(outTokens[0], "*stopped"))
3720 _ChangeState(stopped);
3722 for(tk = 1; tk < outTokens.count; tk++)
3724 if(TokenizeListItem(outTokens[tk], item))
3726 if(!strcmp(item.name, "reason"))
3728 char * reason = item.value;
3729 StripQuotes(reason, reason);
3730 if(!strcmp(reason, "exited-normally") || !strcmp(reason, "exited") || !strcmp(reason, "exited-signalled"))
3733 if(outTokens.count > tk+1 && TokenizeListItem(outTokens[tk+1], item2))
3736 StripQuotes(item2.value, item2.value);
3737 if(!strcmp(item2.name, "exit-code"))
3738 exitCode = item2.value;
3744 HandleExit(reason, exitCode);
3747 else if(!strcmp(reason, "breakpoint-hit") ||
3748 !strcmp(reason, "function-finished") ||
3749 !strcmp(reason, "end-stepping-range") ||
3750 !strcmp(reason, "location-reached") ||
3751 !strcmp(reason, "signal-received"))
3755 if(stopItem) _dpl(0, "problem");
3757 stopItem = GdbDataStop { };
3758 stopItem.reason = r == 'b' ? breakpointHit : r == 'f' ? functionFinished : r == 'e' ? endSteppingRange : r == 'l' ? locationReached : signalReceived;
3760 for(i = tk+1; i < outTokens.count; i++)
3762 TokenizeListItem(outTokens[i], item);
3763 StripQuotes(item.value, item.value);
3764 if(!strcmp(item.name, "thread-id"))
3765 stopItem.threadid = atoi(item.value);
3766 else if(!strcmp(item.name, "frame"))
3768 item.value = StripCurlies(item.value);
3769 ParseFrame(stopItem.frame, item.value);
3771 else if(stopItem.reason == breakpointHit && !strcmp(item.name, "bkptno"))
3772 stopItem.bkptno = atoi(item.value);
3773 else if(stopItem.reason == functionFinished && !strcmp(item.name, "gdb-result-var"))
3774 stopItem.gdbResultVar = CopyString(item.value);
3775 else if(stopItem.reason == functionFinished && !strcmp(item.name, "return-value"))
3776 stopItem.returnValue = CopyString(item.value);
3777 else if(stopItem.reason == signalReceived && !strcmp(item.name, "signal-name"))
3778 stopItem.name = CopyString(item.value);
3779 else if(stopItem.reason == signalReceived && !strcmp(item.name, "signal-meaning"))
3780 stopItem.meaning = CopyString(item.value);
3781 else if(!strcmp(item.name, "stopped-threads"))
3782 _dpl2(_dpct, dplchan::gdbProtoIgnored, 0, reason, ": Advanced thread debugging not handled");
3783 else if(!strcmp(item.name, "core"))
3784 _dpl2(_dpct, dplchan::gdbProtoIgnored, 0, reason, ": Information (core) not used");
3785 else if(!strcmp(item.name, "disp"))
3786 _dpl2(_dpct, dplchan::gdbProtoIgnored, 0, reason, ": (", item.name, "=", item.value, ")");
3788 _dpl2(_dpct, dplchan::gdbProtoUnknown, 0, "Unknown ", reason, " item name (", item.name, "=", item.value, ")");
3791 if(stopItem.reason == signalReceived && !strcmp(stopItem.name, "SIGTRAP"))
3807 event = r == 'b' ? hit : r == 'f' ? functionEnd : r == 'e' ? stepEnd : r == 'l' ? locationReached : signal;
3811 else if(!strcmp(reason, "watchpoint-trigger"))
3812 _dpl2(_dpct, dplchan::gdbProtoIgnored, 0, "Reason watchpoint trigger not handled");
3813 else if(!strcmp(reason, "read-watchpoint-trigger"))
3814 _dpl2(_dpct, dplchan::gdbProtoIgnored, 0, "Reason read watchpoint trigger not handled");
3815 else if(!strcmp(reason, "access-watchpoint-trigger"))
3816 _dpl2(_dpct, dplchan::gdbProtoIgnored, 0, "Reason access watchpoint trigger not handled");
3817 else if(!strcmp(reason, "watchpoint-scope"))
3818 _dpl2(_dpct, dplchan::gdbProtoIgnored, 0, "Reason watchpoint scope not handled");
3820 _dpl2(_dpct, dplchan::gdbProtoUnknown, 0, "Unknown reason: ", reason);
3828 if(usingValgrind && event == none && !stopItem)
3829 event = valgrindStartPause;
3834 _dpl2(_dpct, dplchan::gdbProtoUnknown, 0, "Unknown exec-async-output: ", outTokens[0]);
3835 outTokens.RemoveAll();
3838 if(!strcmpi(output, "(gdb) "))
3842 char exeFile[MAX_LOCATION];
3843 int oldProcessID = targetProcessId;
3844 GetLastDirectory(targetFile, exeFile);
3846 while(!targetProcessId/*true*/)
3848 targetProcessId = Process_GetChildExeProcessId(gdbProcessId, exeFile);
3849 if(targetProcessId || gdbHandle.Peek()) break;
3854 _ChangeState(running);
3855 else if(!oldProcessID)
3857 ide.outputView.debugBox.Logf($"Debugger Error: No target process ID\n");
3858 // TO VERIFY: The rest of this block has not been thoroughly tested in this particular location
3859 gdbHandle.Printf("-gdb-exit\n");
3861 _ChangeState(terminated); //loaded;
3866 for(bp : ide.workspace.breakpoints)
3867 bp.inserted = false;
3870 bp.inserted = false;
3872 bpRunToCursor.inserted = false;
3874 ide.outputView.debugBox.Logf($"Debugging stopped\n");
3875 ClearBreakDisplay();
3877 #if defined(__unix__)
3878 if(!usingValgrind && FileExists(progFifoPath)) //fileCreated)
3880 progThread.terminate = true;
3883 fifoFile.CloseInput();
3890 DeleteFile(progFifoPath);
3891 progFifoPath[0] = '\0';
3898 serialSemaphore.Release();
3901 _dpl2(_dpct, dplchan::gdbProtoUnknown, 0, $"Unknown prompt", output);
3905 if(!strncmp(output, "&\"warning:", 10))
3908 content = strstr(output, "\"");
3909 StripQuotes(content, content);
3910 content = strstr(content, ":");
3916 ide.outputView.debugBox.LogRaw((s = CopyUnescapedString(content)));
3923 _dpl2(_dpct, dplchan::gdbProtoUnknown, 0, $"Unknown output: ", output);
3925 if(!setWaitingForPID)
3926 waitingForPID = false;
3927 setWaitingForPID = false;
3935 // From GDB Output functions
3936 void FGODetectLoadedLibraryForAddedProjectIssues(Array<char *> outTokens)
3938 char path[MAX_LOCATION] = "";
3939 char file[MAX_FILENAME] = "";
3941 DebugListItem item { };
3942 //_dpl2(_dpct, dplchan::debuggerCall, 0, "Debugger::FGODetectLoadedLibraryForAddedProjectIssues()");
3943 for(token : outTokens)
3945 if(TokenizeListItem(token, item))
3947 if(!strcmp(item.name, "target-name"))
3949 StripQuotes(item.value, path);
3950 MakeSystemPath(path);
3951 GetLastDirectory(path, file);
3953 else if(!strcmp(item.name, "symbols-loaded"))
3955 symbolsLoaded = (atoi(item.value) == 1);
3960 if(path[0] && file[0])
3962 for(prj : ide.workspace.projects; prj != ide.workspace.projects.firstIterator.data)
3966 char prjTargetPath[MAX_LOCATION];
3967 char prjTargetFile[MAX_FILENAME];
3968 DirExpression targetDirExp = prj.GetTargetDir(currentCompiler, prj.config, bitDepth);
3969 strcpy(prjTargetPath, prj.topNode.path);
3970 PathCat(prjTargetPath, targetDirExp.dir);
3971 prjTargetFile[0] = '\0';
3972 prj.CatTargetFileName(prjTargetFile, currentCompiler, prj.config);
3973 PathCat(prjTargetPath, prjTargetFile);
3974 MakeSystemPath(prjTargetPath);
3976 match = !fstrcmp(prjTargetFile, file);
3977 if(!match && (dot = strstr(prjTargetFile, ".so.")))
3979 char * dot3 = strstr(dot+4, ".");
3983 match = !fstrcmp(prjTargetFile, file);
3988 match = !fstrcmp(prjTargetFile, file);
3993 // TODO: nice visual feedback to better warn user. use some ide notification system or other means.
3994 /* -- 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)
3996 ide.outputView.debugBox.Logf($"Attention! No symbols for loaded library %s matched to the %s added project.\n", path, prj.topNode.name);
3998 match = !fstrcmp(prjTargetPath, path);
3999 if(!match && (dot = strstr(prjTargetPath, ".so.")))
4001 char * dot3 = strstr(dot+4, ".");
4005 match = !fstrcmp(prjTargetPath, path);
4010 match = !fstrcmp(prjTargetPath, path);
4014 projectsLibraryLoaded[prj.name] = true;
4016 ide.outputView.debugBox.Logf($"Loaded library %s doesn't match the %s target of the %s added project.\n", path, prjTargetPath, prj.topNode.name);
4023 void FGOBreakpointModified(Array<char *> outTokens)
4025 _dpl2(_dpct, dplchan::debuggerCall, 0, "Debugger::FGOBreakpointModified() -- TODO only if needed: support breakpoint modified");
4027 DebugListItem item { };
4028 if(outTokens.count > 1 && TokenizeListItem(outTokens[1], item))
4030 if(!strcmp(item.name, "bkpt"))
4032 GdbDataBreakpoint modBp = ParseBreakpoint(item.value, outTokens);
4040 ExpressionType ::DebugEvalExpTypeError(char * result)
4042 _dpl2(_dpct, dplchan::debuggerWatches, 0, "Debugger::DebugEvalExpTypeError()");
4047 case symbolNotFound:
4048 return symbolErrorExp;
4049 case memoryCantBeRead:
4050 return memoryErrorExp;
4052 return unknownErrorExp;
4055 char * ::EvaluateExpression(char * expression, ExpressionType * error)
4058 _dpl2(_dpct, dplchan::debuggerWatches, 0, "Debugger::EvaluateExpression(", expression, ")");
4059 if(ide.projectView && ide.debugger.state == stopped)
4061 result = GdbEvaluateExpression(expression);
4062 *error = DebugEvalExpTypeError(result);
4067 *error = noDebuggerErrorExp;
4072 char * ::ReadMemory(uint64 address, int size, char format, ExpressionType * error)
4075 char * result = GdbReadMemoryString(address, size, format, 1, 1);
4076 _dpl2(_dpct, dplchan::debuggerCall, 0, "Debugger::ReadMemory(", address, ")");
4077 if(!result || !strcmp(result, "N/A"))
4078 *error = memoryErrorExp;
4080 *error = DebugEvalExpTypeError(result);
4085 class ValgrindLogThread : Thread
4091 static char output[4096];
4092 Array<char> dynamicBuffer { minAllocSize = 4096 };
4093 File oldValgrindHandle = vgLogFile;
4094 incref oldValgrindHandle;
4097 while(debugger.state != terminated && vgLogFile)
4101 result = vgLogFile.Read(output, 1, sizeof(output));
4103 if(debugger.state == terminated || !vgLogFile/* || vgLogFile.Eof()*/)
4110 for(c = 0; c<result; c++)
4112 if(output[c] == '\n')
4114 int pos = dynamicBuffer.size;
4115 dynamicBuffer.size += c - start;
4116 memcpy(&dynamicBuffer[pos], output + start, c - start);
4117 if(dynamicBuffer.count && dynamicBuffer[dynamicBuffer.count - 1] != '\r')
4118 // COMMENTED OUT DUE TO ISSUE #135, FIXED
4119 //if(dynamicBuffer.array[dynamicBuffer.count - 1] != '\r')
4120 dynamicBuffer.size++;
4121 dynamicBuffer[dynamicBuffer.count - 1] = '\0';
4123 // printf("%s\n", dynamicBuffer.array);
4125 if(strstr(&dynamicBuffer[0], "vgdb me"))
4126 debugger.serialSemaphore.Release();
4127 ide.outputView.debugBox.Logf("%s\n", &dynamicBuffer[0]);
4128 dynamicBuffer.size = 0;
4134 int pos = dynamicBuffer.size;
4135 dynamicBuffer.size += c - start;
4136 memcpy(&dynamicBuffer[pos], output + start, c - start);
4139 else if(debugger.state == stopped)
4142 printf("Got end of file from GDB!\n");
4149 delete dynamicBuffer;
4150 ide.outputView.debugBox.Logf($"ValgrindLogThreadExit\n");
4151 //if(oldValgrindHandle == vgLogFile)
4152 debugger.GdbThreadExit/*ValgrindLogThreadExit*/();
4153 delete oldValgrindHandle;
4159 class ValgrindTargetThread : Thread
4165 static char output[4096];
4166 Array<char> dynamicBuffer { minAllocSize = 4096 };
4167 DualPipe oldValgrindHandle = vgTargetHandle;
4168 incref oldValgrindHandle;
4171 while(debugger.state != terminated && vgTargetHandle && !vgTargetHandle.Eof())
4175 result = vgTargetHandle.Read(output, 1, sizeof(output));
4177 if(debugger.state == terminated || !vgTargetHandle || vgTargetHandle.Eof())
4184 for(c = 0; c<result; c++)
4186 if(output[c] == '\n')
4188 int pos = dynamicBuffer.size;
4189 dynamicBuffer.size += c - start;
4190 memcpy(&dynamicBuffer[pos], output + start, c - start);
4191 if(dynamicBuffer.count && dynamicBuffer[dynamicBuffer.count - 1] != '\r')
4192 // COMMENTED OUT DUE TO ISSUE #135, FIXED
4193 //if(dynamicBuffer.array[dynamicBuffer.count - 1] != '\r')
4194 dynamicBuffer.size++;
4195 dynamicBuffer[dynamicBuffer.count - 1] = '\0';
4197 // printf("%s\n", dynamicBuffer.array);
4199 ide.outputView.debugBox.Logf("%s\n", &dynamicBuffer[0]);
4201 dynamicBuffer.size = 0;
4207 int pos = dynamicBuffer.size;
4208 dynamicBuffer.size += c - start;
4209 memcpy(&dynamicBuffer[pos], output + start, c - start);
4215 printf("Got end of file from GDB!\n");
4219 delete dynamicBuffer;
4220 //if(oldValgrindHandle == vgTargetHandle)
4221 debugger.ValgrindTargetThreadExit();
4222 delete oldValgrindHandle;
4228 class GdbThread : Thread
4234 static char output[4096];
4235 Array<char> dynamicBuffer { minAllocSize = 4096 };
4236 DualPipe oldGdbHandle = gdbHandle;
4237 incref oldGdbHandle;
4240 while(debugger.state != terminated && gdbHandle && !gdbHandle.Eof())
4244 result = gdbHandle.Read(output, 1, sizeof(output));
4246 if(debugger.state == terminated || !gdbHandle || gdbHandle.Eof())
4253 for(c = 0; c<result; c++)
4255 if(output[c] == '\n')
4257 int pos = dynamicBuffer.size;
4258 dynamicBuffer.size += c - start;
4259 memcpy(&dynamicBuffer[pos], output + start, c - start);
4260 if(dynamicBuffer.count && dynamicBuffer[dynamicBuffer.count - 1] != '\r')
4261 // COMMENTED OUT DUE TO ISSUE #135, FIXED
4262 //if(dynamicBuffer.array[dynamicBuffer.count - 1] != '\r')
4263 dynamicBuffer.size++;
4264 dynamicBuffer[dynamicBuffer.count - 1] = '\0';
4266 // _dpl(0, dynamicBuffer.array);
4268 debugger.GdbThreadMain(&dynamicBuffer[0]);
4269 dynamicBuffer.size = 0;
4275 int pos = dynamicBuffer.size;
4276 dynamicBuffer.size += c - start;
4277 memcpy(&dynamicBuffer[pos], output + start, c - start);
4283 _dpl(0, "Got end of file from GDB!");
4287 delete dynamicBuffer;
4288 //if(oldGdbHandle == gdbHandle)
4289 debugger.GdbThreadExit();
4290 delete oldGdbHandle;
4296 static define createFIFOMsg = $"err: Unable to create FIFO %s\n";
4297 static define openFIFOMsg = $"err: Unable to open FIFO %s for read\n";
4299 #if defined(__unix__)
4304 #include <sys/types.h>
4309 class ProgramThread : Thread
4315 bool fileCreated = false;
4317 static char output[1000];
4320 /*if(!mkfifo(progFifoPath, mask))
4327 ide.outputView.debugBox.Logf($"err: Unable to create FIFO %s\n", progFifoPath);
4331 if(FileExists(progFifoPath)) //fileCreated)
4333 fifoFile = FileOpen(progFifoPath, read);
4337 ide.outputView.debugBox.Logf(openFIFOMsg, progFifoPath);
4342 fd = fileno((FILE *)fifoFile.input);
4343 //fcntl(fd, F_SETFL, fcntl(fd, F_GETFL) | O_NONBLOCK);
4347 while(!terminate && fifoFile && !fifoFile.Eof())
4350 struct timeval time;
4358 selectResult = select(fd + 1, &rs, null, null, &time);
4359 if(FD_ISSET(fd, &rs))
4361 int result = (int)read(fd, output, sizeof(output)-1);
4362 if(!result || (result < 0 && errno != EAGAIN))
4366 output[result] = '\0';
4367 if(strcmp(output,"&\"warning: GDB: Failed to set controlling terminal: Invalid argument\\n\"\n"))
4370 ide.outputView.debugBox.Log(output);
4379 //fifoFile.CloseInput();
4382 ide.outputView.debugBox.Log("\n");
4386 if(FileExists(progFifoPath)) //fileCreated)
4388 DeleteFile(progFifoPath);
4389 progFifoPath[0] = '\0';
4397 class Argument : struct
4399 Argument prev, next;
4401 property char * name { set { delete name; if(value) name = CopyString(value); } }
4403 property char * val { set { delete val; if(value) val = CopyString(value); } }
4417 class Frame : struct
4422 property char * addr { set { delete addr; if(value) addr = CopyString(value); } }
4424 property char * func { set { delete func; if(value) func = CopyString(value); } }
4428 property char * from { set { delete from; if(value) from = CopyUnescapedUnixPath(value); } }
4430 property char * file { set { delete file; if(value) file = CopyUnescapedUnixPath(value); } }
4431 char * absoluteFile;
4432 property char * absoluteFile { set { delete absoluteFile; if(value) absoluteFile = CopyUnescapedUnixPath(value); } }
4441 delete absoluteFile;
4442 args.Free(Argument::Free);
4451 class GdbDataStop : struct
4453 DebuggerReason reason;
4468 char * gdbResultVar;
4478 if(reason == signalReceived)
4483 else if(reason == functionFinished)
4485 delete gdbResultVar;
4489 if(frame) frame.Free();
4498 class GdbDataBreakpoint : struct
4502 property char * number { set { delete number; if(value) number = CopyString(value); } }
4504 property char * type { set { delete type; if(value) type = CopyString(value); } }
4506 property char * disp { set { delete disp; if(value) disp = CopyString(value); } }
4509 property char * addr { set { delete addr; if(value) addr = CopyString(value); } }
4511 property char * func { set { delete func; if(value) func = CopyString(value); } }
4513 property char * file { set { delete file; if(value) file = CopyUnescapedUnixPath(value); } }
4515 property char * fullname { set { delete fullname; if(value) fullname = CopyUnescapedUnixPath(value); } }
4518 property char * at { set { delete at; if(value) at = CopyString(value); } }
4521 Array<GdbDataBreakpoint> multipleBPs;
4526 PrintLn("{", "#", number, " T", type, " D", disp, " E", enabled, " H", times, " (", func, ") (", file, ":", line, ") (", fullname, ") (", addr, ") (", at, ")", "}");
4537 if(multipleBPs) multipleBPs.Free();
4541 ~GdbDataBreakpoint()
4547 class Breakpoint : struct
4552 property char * function { set { delete function; if(value) function = CopyString(value); } }
4553 char * relativeFilePath;
4554 property char * relativeFilePath { set { delete relativeFilePath; if(value) relativeFilePath = CopyString(value); } }
4555 char * absoluteFilePath;
4556 property char * absoluteFilePath { set { delete absoluteFilePath; if(value) absoluteFilePath = CopyString(value); } }
4558 property char * location { set { delete location; if(value) location = CopyString(value); } }
4567 BreakpointType type;
4569 GdbDataBreakpoint bp;
4572 void ParseLocation()
4574 char * prjName = null;
4575 char * filePath = null;
4578 char fullPath[MAX_LOCATION];
4580 if(location[0] == '\(' && location[1] && (file = strchr(location+2, '\)')) && file[1])
4582 prjName = new char[file-location];
4583 strncpy(prjName, location+1, file-location-1);
4584 prjName[file-location-1] = '\0';
4589 if((line = strchr(file+1, ':')))
4591 filePath = new char[strlen(file)+1];
4592 strncpy(filePath, file, line-file);
4593 filePath[line-file] = '\0';
4597 filePath = CopyString(file);
4598 property::relativeFilePath = filePath;
4601 for(prj : ide.workspace.projects)
4603 if(!strcmp(prjName, prj.name))
4605 node = prj.topNode.FindWithPath(filePath, false);
4608 node.GetFullFilePath(fullPath);
4609 property::absoluteFilePath = fullPath;
4616 this.line = atoi(line);
4620 node = ide.projectView.project.topNode.Find(filePath, false);
4623 node.GetFullFilePath(fullPath);
4624 property::absoluteFilePath = fullPath;
4626 project = ide.project;
4628 if(!absoluteFilePath)
4629 property::absoluteFilePath = "";
4634 char * CopyLocationString(bool removePath)
4637 char * file = relativeFilePath ? relativeFilePath : absoluteFilePath;
4638 bool removingPath = removePath && file;
4641 char * fileName = new char[MAX_FILENAME];
4642 GetLastDirectory(file, fileName);
4648 location = PrintString(file, ":", function);
4650 location = CopyString(function);
4653 location = PrintString(file, ":", line);
4659 char * CopyUserLocationString()
4662 char * loc = CopyLocationString(false);
4664 for(p : ide.workspace.projects; p != ide.workspace.projects.firstIterator.data)
4666 if(p.topNode.FindByFullPath(absoluteFilePath, false))
4674 location = PrintString("(", prj.name, ")", loc);
4684 if(relativeFilePath && relativeFilePath[0])
4686 char * location = CopyUserLocationString();
4687 f.Printf(" * %d,%d,%d,%d,%s\n", enabled ? 1 : 0, ignore, level, line, location);
4690 f.Printf(" ~ %s\n", condition.expression);
4700 delete relativeFilePath;
4701 delete absoluteFilePath;
4712 class Watch : struct
4723 f.Printf(" ~ %s\n", expression);
4747 class DebugListItem : struct
4753 struct DebugEvaluationData
4758 uint64 nextBlockAddress;
4760 DebuggerEvaluationError error;
4763 class CodeLocation : struct
4766 char * absoluteFile;
4769 CodeLocation ::ParseCodeLocation(char * location)
4773 char * colon = null;
4775 char loc[MAX_LOCATION];
4776 strcpy(loc, location);
4777 for(temp = loc; temp = strstr(temp, ":"); temp++)
4785 int line = atoi(colon);
4788 CodeLocation codloc { line = line };
4789 codloc.file = CopyString(loc);
4790 codloc.absoluteFile = ide.workspace.GetAbsolutePathFromRelative(loc);
4802 delete absoluteFile;
4811 void GDBFallBack(Expression exp, String expString)
4814 ExpressionType evalError = dummyExp;
4815 result = Debugger::EvaluateExpression(expString, &evalError);
4818 exp.constant = result;
4819 exp.type = constantExp;