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
26 #include <string.h> // For memchr
34 #include <sys/time.h> // Required on Apple...
48 sprintf(s[0], "%04d", now.year);
49 sprintf(s[1], "%02d", now.month+1);
50 sprintf(s[2], "%02d", now.day);
51 sprintf(s[3], "%02d", now.hour);
52 sprintf(s[4], "%02d", now.minute);
53 sprintf(s[5], "%02d", now.second);
54 time = PrintString("*", s[0], s[1], s[2], "-", s[3], s[4], s[5], "*");
60 // use =0 to disable printing of specific channels
62 static enum dplchan { none, gdbProtoIgnored=0/*1*/, gdbProtoUnknown=2, gdbOutput=3/*3*/, gdbCommand=4/*4*/, debuggerCall=0/*5*/, debuggerProblem=6,
63 debuggerUserAction=7,debuggerState=8, debuggerBreakpoints=9, debuggerWatches=0/*10*/, debuggerTemp=0 };
64 static const char * _dpct[] = {
66 "GDB Protocol Ignored",
67 "GDB Protocol ***Unknown***",
71 "Debugger ***Problem***",
72 "Debugger::ChangeUserAction",
73 "Debugger::ChangeState",
76 "-----> Temporary Message",
81 static enum dplchan { none, gdbProtoIgnored=0, gdbProtoUnknown=0, gdbOutput=0, gdbCommand=0, debuggerCall=0, debuggerProblem=0,
82 debuggerUserAction=0,debuggerState=0, debuggerBreakpoints=0, debuggerWatches=0, debuggerTemp=0 };
85 // TODO if(strlen(item.value) < MAX_F_STRING)
89 #define _dpl2(...) __dpl2(__FILE__, __LINE__, ##__VA_ARGS__)
90 static void __dpl2(const char * file, int line, const char ** channels, int channel, int indent, typed_object object, ...)
92 bool chan = channel && channels && channels[channel];
95 char string[MAX_F_STRING];
96 char * time = PrintNow();
98 //ide.outputView.debugBox.Logf();
99 Logf("%s %s:% 5d: %s%s", time, file, line, chan ? channels[channel] : "", chan && channels[channel][0] ? ": " : "");
100 va_start(args, object);
101 PrintStdArgsToBuffer(string, sizeof(string), object, args);
112 #define _dpl(...) __dpl(__FILE__, __LINE__, ##__VA_ARGS__)
113 static void __dpl(const char * file, int line, int indent, const char * format, ...)
116 char string[MAX_F_STRING];
118 char * time = PrintNow();
119 //static File f = null;
120 va_start(args, format);
121 vsnprintf(string, sizeof(string), format, args);
122 string[sizeof(string)-1] = 0;
125 char * time = PrintNow();
127 logName = PrintString(time, ".log");
129 f = FileOpen(logName, write);
132 /*f.Printf("%s %s:% 5d: ", time, file, line);
133 for(c = 0; c<indent; c++)
135 f.Printf("%s\n", string);*/
136 Logf("%s %s:% 5d: ", time, file, line);
137 for(c = 0; c<indent; c++)
139 Logf("%s\n", string);
144 public char * StripQuotes2(char * string, char * output)
148 bool quoted = false, escaped = false;
150 for(c = 0; (ch = string[c]); c++)
154 if(escaped || ch != '\"')
157 escaped = !escaped && ch == '\\';
171 // String Escape Copy
172 static void strescpy(char * d, char * s)
180 case '\n': d[k] = '\\'; d[++k] = 'n'; break;
181 case '\t': d[k] = '\\'; d[++k] = 't'; break;
182 case '\a': d[k] = '\\'; d[++k] = 'a'; break;
183 case '\b': d[k] = '\\'; d[++k] = 'b'; break;
184 case '\f': d[k] = '\\'; d[++k] = 'f'; break;
185 case '\r': d[k] = '\\'; d[++k] = 'r'; break;
186 case '\v': d[k] = '\\'; d[++k] = 'v'; break;
187 case '\\': d[k] = '\\'; d[++k] = '\\'; break;
188 case '\"': d[k] = '\\'; d[++k] = '\"'; break;
189 default: d[k] = s[j];
196 /*static char * CopyUnescapedSystemPath(char * p)
199 char * d = new char[len + 1];
200 UnescapeString(d, p, len);
201 #if defined(__WIN32__)
202 ChangeCh(d, '/', '\\');
207 static char * CopyUnescapedUnixPath(char * p)
210 char * d = new char[len + 1];
211 UnescapeString(d, p, len);
212 #if defined(__WIN32__)
213 ChangeCh(d, '\\', '/');
218 static char * CopyUnescapedString(char * s)
221 char * d = new char[len + 1];
222 UnescapeString(d, s, len);
226 static char * StripBrackets(char * string)
228 int length = strlen(string);
229 if(length > 1 && *string == '[' && string[length - 1] == ']')
232 string[length - 1] = '\0';
239 static char * StripCurlies(char * string)
241 int length = strlen(string);
242 if(length > 1 && *string == '{' && string[length - 1] == '}')
245 string[length - 1] = '\0';
252 /*static int StringGetInt(char * string, int start)
255 int i, len = strlen(string);
257 for(i = start; i < len && i < start + 8; i++)
259 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')
260 strncat(number, &string[i], 1);
267 static int TokenizeList(char * string, const char seperator, Array<char *> tokens)
271 bool quoted = false, escaped = false;
272 char * start = string, ch;
274 for(; (ch = *string); string++)
281 if(escaped || ch != '\"')
282 escaped = !escaped && ch == '\\';
288 else if(ch == '{' || ch == '[' || ch == '(' || ch == '<')
290 else if(ch == '}' || ch == ']' || ch == ')' || ch == '>')
292 else if(ch == seperator && !level)
301 //tokens[count] = start;
302 //tokens[count++] = start;
309 static bool TokenizeListItem(char * string, DebugListItem item)
311 char * equal = strstr(string, "=");
323 static bool CheckCommandAvailable(const char * command)
325 bool available = false;
327 char * name = new char[MAX_FILENAME];
328 char * pathVar = new char[maxPathLen];
330 GetEnvironment("PATH", pathVar, maxPathLen);
331 count = TokenizeWith(pathVar, sizeof(paths) / sizeof(char *), paths, pathListSep, false);
332 strcpy(name, command);
336 const char * extensions[] = { "exe", "com", "bat", null };
337 for(e=0; extensions[e]; e++)
339 ChangeExtension(name, extensions[e], name);
341 for(c=0; c<count; c++)
343 FileListing fl { paths[c] };
346 if(fl.stats.attribs.isFile && !fstrcmp(fl.name, name))
365 // define GdbGetLineSize = 1638400;
366 define GdbGetLineSize = 5638400;
367 #if defined(__unix__)
368 char progFifoPath[MAX_LOCATION];
369 char progFifoDir[MAX_LOCATION];
372 enum DebuggerState { none, prompt, loaded, running, stopped, terminated, error };
375 none, hit, breakEvent, signal, stepEnd, functionEnd, exit, valgrindStartPause, locationReached;
377 property bool canBeMonitored { get { return (this == hit || this == breakEvent || this == signal || this == stepEnd || this == functionEnd || this == locationReached); } };
379 enum DebuggerAction { none, internal, restart, stop, selectFrame, advance }; //, bpValidation
382 unknown, endSteppingRange, functionFinished, signalReceived, breakpointHit, locationReached
383 //watchpointTrigger, readWatchpointTrigger, accessWatchpointTrigger, watchpointScope,
384 //exited, exitedNormally, exitedSignalled;
388 none, internalMain, internalWinMain, internalModulesLoaded, user, runToCursor, internalModuleLoad, internalEntry;
390 property bool isInternal { get { return (this == internalMain || this == internalWinMain || this == internalModulesLoaded || this == internalModuleLoad || this == internalEntry); } };
391 property bool isUser { get { return (this == user || this == runToCursor); } };
393 enum DebuggerEvaluationError { none, symbolNotFound, memoryCantBeRead, unknown };
394 enum DebuggerUserAction
396 none, start, resume, _break, stop, restart, selectThread, selectFrame, stepInto, stepOver, stepUntil, stepOut, runToCursor;
397 property bool breaksOnInternalBreakpoint { get { return (this == stepInto || this == stepOver || this == stepUntil); } };
401 none, run, _continue, next, until, advance, step, finish;
402 property bool suspendInternalBreakpoints { get { return (this == until || this == advance || this == step || this == finish); } };
405 FileDialog debuggerFileDialog { type = selectDir };
407 static DualPipe vgTargetHandle;
408 static File vgLogFile;
409 static char vgLogPath[MAX_LOCATION];
410 static DualPipe gdbHandle;
411 static DebugEvaluationData eval { };
413 static int targetProcessId;
415 static bool gdbReady;
416 static bool breakpointError;
420 Semaphore serialSemaphore { };
426 bool sentBreakInsert;
427 bool ignoreBreakpoints;
435 int activeFrameLevel;
444 GdbExecution gdbExecution;
445 DebuggerUserAction userAction;
448 DebuggerAction breakType;
450 //DebuggerCommand lastCommand; // THE COMPILER COMPILES STUFF THAT DOES NOT EXIST???
452 GdbDataStop stopItem;
453 GdbDataBreakpoint bpItem;
456 List<Breakpoint> sysBPs { };
457 Breakpoint bpRunToCursor;
458 Breakpoint intBpEntry;
459 Breakpoint intBpMain;
460 Breakpoint intBpWinMain;
464 CompilerConfig currentCompiler;
465 ProjectConfig prjConfig;
468 CodeEditor codeEditor;
470 ValgrindLogThread vgLogThread { debugger = this };
471 ValgrindTargetThread vgTargetThread { debugger = this };
472 GdbThread gdbThread { debugger = this };
475 Map<String, bool> projectsLibraryLoaded { };
479 delay = 0.0, userData = this;
483 bool monitor = false;
484 DebuggerEvent curEvent = event;
485 GdbDataStop stopItem = this.stopItem;
486 Breakpoint bpUser = null;
487 Breakpoint bpInternal = null;
495 this.stopItem = null;
499 DynamicString bpReport { };
501 for(bp : sysBPs; bp.inserted)
503 bpReport.concatx(",", bp.type, "(", s=bp.CopyLocationString(false), ")");
506 if(bpRunToCursor && bpRunToCursor.inserted)
508 Breakpoint bp = bpRunToCursor;
509 bpReport.concatx(",", bp.type, "(", s=bp.CopyLocationString(false), ")");
512 for(bp : ide.workspace.breakpoints; bp.inserted)
514 bpReport.concatx(",", bp.type, "(", s=bp.CopyLocationString(false), ")");
518 _dpl2(_dpct, dplchan::debuggerBreakpoints, 0, "gdbTimer::DelayExpired: ", s+1);
523 Breakpoint bp = GetBreakpointById(stopItem.bkptno, &isInternal);
526 _dpl2(_dpct, dplchan::debuggerBreakpoints, 0, "gdb stopped by a breakpoint: ", bp.type, "(", s=bp.CopyLocationString(false), ")");
537 if(curEvent && curEvent != exit)
539 _dpl(0, "No stop item");
547 Restart(currentCompiler, prjConfig, bitDepth, usingValgrind);
556 GdbCommand(0, false, "-stack-select-frame %d", activeFrameLevel);
557 for(activeFrame = stackFrames.first; activeFrame; activeFrame = activeFrame.next)
558 if(activeFrame.level == activeFrameLevel)
564 // GdbCommand(0, false, "-break-info %s", bpItem.number);
576 Breakpoint bp = stopItem ? GetBreakpointById(stopItem.bkptno, &isInternal) : null;
577 if(bp && bp.inserted && bp.bp.addr)
579 if(bp.type.isInternal)
583 if(stopItem && stopItem.frame)
585 if(bpInternal && bpRunToCursor && bpRunToCursor.inserted && !strcmp(bpRunToCursor.bp.addr, bp.bp.addr))
586 bpUser = bpRunToCursor;
589 for(item : (bpInternal ? ide.workspace.breakpoints : sysBPs); item.inserted)
591 if(item.bp && item.bp.addr && !strcmp(item.bp.addr, bp.bp.addr))
603 _dpl2(_dpct, dplchan::debuggerProblem, 0, "Invalid stopItem!");
604 if(bpUser && stopItem.frame.addr && strcmp(stopItem.frame.addr, bpUser.bp.addr))
605 _dpl2(_dpct, dplchan::debuggerProblem, 0, "Breakpoint bkptno(", stopItem.bkptno, ") address missmatch!");
608 _dpl2(_dpct, dplchan::debuggerProblem, 0, "Breakpoint bkptno(", stopItem.bkptno, ") invalid or not found!");
609 if((bpUser && !ignoreBreakpoints) || (bpInternal && userAction.breaksOnInternalBreakpoint))
611 hitThread = stopItem.threadid;
615 signalThread = stopItem.threadid;
619 case locationReached:
621 ignoreBreakpoints = false;
623 case valgrindStartPause:
624 GdbExecContinue(true);
632 if(curEvent == signal)
636 ide.outputView.debugBox.Logf($"Signal received: %s - %s\n", stopItem.name, stopItem.meaning);
637 ide.outputView.debugBox.Logf(" %s:%d\n", (s = CopySystemPath(stopItem.frame.file)), stopItem.frame.line);
638 ide.outputView.Show();
639 ide.callStackView.Show();
642 else if(curEvent == breakEvent)
644 ide.threadsView.Show();
645 ide.callStackView.Show();
646 ide.callStackView.Activate();
648 else if(curEvent == hit)
650 if(BreakpointHit(stopItem, bpInternal, bpUser))
652 ide.AdjustDebugMenus();
653 if(bpUser && bpUser.type == runToCursor)
655 ignoreBreakpoints = false;
656 UnsetBreakpoint(bpUser);
657 delete bpRunToCursor;
662 if(breakType == advance && bpInternal && (bpInternal.type == internalMain || bpInternal.type == internalEntry))
665 GdbExecAdvance(breakString, 0);
670 GdbExecContinue(false);
676 if(monitor && curEvent.canBeMonitored)
679 activeThread = stopItem.threadid;
680 GdbCommand(0, false, "-thread-list-ids");
681 InternalSelectFrame(activeFrameLevel);
682 GoToStackFrameLine(activeFrameLevel, true, false);
684 ide.ShowCodeEditor();
685 ide.AdjustDebugMenus();
686 ideMainFrame.Activate(); // TOFIX: ide.Activate() is not reliable (app inactive)
699 #ifdef GDB_DEBUG_CONSOLE
700 char lastGdbOutput[GdbGetLineSize];
702 #if defined(__unix__)
703 ProgramThread progThread { };
707 #define _ChangeUserAction(value) ChangeUserAction(__FILE__, __LINE__, value)
708 void ChangeUserAction(const char * file, int line, DebuggerUserAction value)
711 bool same = value == userAction;
712 __dpl2(file, line, _dpct, dplchan::debuggerUserAction, 0, userAction, /*same ? " *** == *** " : */" -> ", value);
717 #define _ChangeUserAction(value) userAction = value
721 #define _ChangeState(value) ChangeState(__FILE__, __LINE__, value)
722 void ChangeState(const char * file, int line, DebuggerState value)
724 #define _ChangeState(value) ChangeState(value)
725 void ChangeState(DebuggerState value)
728 bool same = value == state;
729 #if 0 //def _DEBUG_INST
730 __dpl2(file, line, _dpct, dplchan::debuggerState, 0, state, same ? " *** == *** " : " -> ", value);
733 if(!same) ide.AdjustDebugMenus();
738 _dpl2(_dpct, dplchan::debuggerCall, 0, "Debugger::CleanUp");
740 stackFrames.Free(Frame::Free);
750 waitingForPID = false;
755 sentBreakInsert = false;
756 ignoreBreakpoints = false;
759 activeFrameLevel = 0;
776 bpRunToCursor = null;
778 delete currentCompiler;
781 WatchesReleaseCodeEditor();
784 projectsLibraryLoaded.Free();
786 /*GdbThread gdbThread
792 _dpl2(_dpct, dplchan::debuggerCall, 0, "Debugger::constructor");
793 ideProcessId = Process_GetCurrentProcessId();
795 sysBPs.Add((intBpEntry = Breakpoint { type = internalEntry, enabled = false, level = -1 }));
796 sysBPs.Add((intBpMain = Breakpoint { type = internalMain, function = "main", enabled = true, level = -1 }));
797 #if defined(__WIN32__)
798 sysBPs.Add((intBpWinMain = Breakpoint { type = internalWinMain, function = "WinMain", enabled = true, level = -1 }));
800 sysBPs.Add(Breakpoint { type = internalModulesLoaded, enabled = true, level = -1 });
801 sysBPs.Add(Breakpoint { type = internalModuleLoad, function = "InternalModuleLoadBreakpoint", enabled = true, level = -1 });
806 _dpl2(_dpct, dplchan::debuggerCall, 0, "Debugger::destructor");
814 property bool isActive { get { return state == running || state == stopped; } }
815 property bool isPrepared { get { return state == loaded || state == running || state == stopped; } }
819 _dpl2(_dpct, dplchan::debuggerCall, 0, "Debugger::Resume");
820 _ChangeUserAction(resume);
821 GdbExecContinue(true);
826 _dpl2(_dpct, dplchan::debuggerCall, 0, "Debugger::Break");
827 _ChangeUserAction(_break);
831 GdbDebugBreak(false);
837 _dpl2(_dpct, dplchan::debuggerCall, 0, "Debugger::Stop");
838 _ChangeUserAction(stop);
845 GdbDebugBreak(false);
859 void Restart(CompilerConfig compiler, ProjectConfig config, int bitDepth, bool useValgrind)
861 _dpl2(_dpct, dplchan::debuggerCall, 0, "Debugger::Restart");
862 _ChangeUserAction(restart);
863 if(StartSession(compiler, config, bitDepth, useValgrind, true, false) == loaded)
867 bool GoToCodeLine(char * location)
870 _dpl2(_dpct, dplchan::debuggerCall, 0, "Debugger::GoToCodeLine(", location, ")");
871 codloc = CodeLocation::ParseCodeLocation(location);
874 CodeEditor editor = (CodeEditor)ide.OpenFile(codloc.absoluteFile, false, true, null, no, normal, false);
877 EditBox editBox = editor.editBox;
878 if(editBox.GoToLineNum(codloc.line - 1))
879 editBox.GoToPosition(editBox.line, codloc.line - 1, 0);
886 bool GoToStackFrameLine(int stackLevel, bool askForLocation, bool fromCallStack)
888 _dpl2(_dpct, dplchan::debuggerCall, 0, "Debugger::GoToStackFrameLine(", stackLevel, ", ", askForLocation, ")");
891 char sourceDir[MAX_LOCATION];
893 CodeEditor editor = null;
894 if(stackLevel == -1) // this (the two lines) is part of that fix that I would not put in for some time
896 for(frame = stackFrames.first; frame; frame = frame.next)
897 if(frame.level == stackLevel)
902 ide.callStackView.Show();
904 if(frame.absoluteFile)
905 editor = (CodeEditor)ide.OpenFile(frame.absoluteFile, false, true, null, no, normal, false);
906 if(!editor && frame.file)
907 frame.absoluteFile = ide.workspace.GetAbsolutePathFromRelative(frame.file);
908 if(!frame.absoluteFile && askForLocation && frame.file)
911 char title[MAX_LOCATION];
912 snprintf(title, sizeof(title), $"Provide source file location for %s", (s = CopySystemPath(frame.file)));
913 title[sizeof(title)-1] = 0;
915 if(SourceDirDialog(title, ide.workspace.projectDir, frame.file, sourceDir))
917 AddSourceDir(sourceDir);
918 frame.absoluteFile = ide.workspace.GetAbsolutePathFromRelative(frame.file);
921 if(!editor && frame.absoluteFile)
922 editor = (CodeEditor)ide.OpenFile(frame.absoluteFile, false, true, null, no, normal, false);
924 ide.RepositionWindows(false);
926 if(editor && frame.line)
928 EditBox editBox = editor.editBox;
929 editBox.GoToLineNum(frame.line - 1);
930 editBox.GoToPosition(editBox.line, frame.line - 1, 0);
938 void SelectThread(int thread)
940 _dpl2(_dpct, dplchan::debuggerCall, 0, "Debugger::SelectThread(", thread, ")");
941 _ChangeUserAction(selectThread);
944 if(thread != activeThread)
946 activeFrameLevel = -1;
947 ide.callStackView.Clear();
948 GdbCommand(0, false, "-thread-select %d", thread);
950 InternalSelectFrame(activeFrameLevel);
951 GoToStackFrameLine(activeFrameLevel, true, false);
955 ide.callStackView.Show();
959 void SelectFrame(int frame)
961 //_dpl2(_dpct, dplchan::debuggerCall, 0, "Debugger::SelectFrame(", frame, ")");
962 _ChangeUserAction(selectFrame);
965 if(frame != activeFrameLevel)
967 InternalSelectFrame(frame);
974 void InternalSelectFrame(int frame)
976 //_dpl2(_dpct, dplchan::debuggerCall, 0, "Debugger::InternalSelectFrame(", frame, ")");
977 activeFrameLevel = frame; // there is no active frame number in the gdb reply
978 GdbCommand(0, false, "-stack-select-frame %d", activeFrameLevel);
979 for(activeFrame = stackFrames.first; activeFrame; activeFrame = activeFrame.next)
980 if(activeFrame.level == activeFrameLevel)
984 void HandleExit(char * reason, char * code)
986 char verboseExitCode[128];
988 _dpl2(_dpct, dplchan::debuggerCall, 0, "Debugger::HandleExit(", reason, ", ", code, ")");
989 _ChangeState(loaded); // this state change seems to be superfluous, might be in case of gdb crash
994 snprintf(verboseExitCode, sizeof(verboseExitCode), $" with exit code %s", code);
995 verboseExitCode[sizeof(verboseExitCode)-1] = 0;
998 verboseExitCode[0] = '\0';
1002 // ClearBreakDisplay();
1006 for(wh : ide.workspace.watches)
1008 if(wh.type) FreeType(wh.type);
1011 ide.watchesView.UpdateWatch(wh);
1015 #if defined(__unix__)
1018 progThread.terminate = true;
1021 fifoFile.CloseInput();
1031 char program[MAX_LOCATION];
1032 GetSystemPathBuffer(program, targetFile);
1034 ide.outputView.debugBox.Logf($"The program %s has exited%s.\n", program, verboseExitCode);
1035 else if(!strcmp(reason, "exited-normally"))
1036 ide.outputView.debugBox.Logf($"The program %s has exited normally%s.\n", program, verboseExitCode);
1037 else if(!strcmp(reason, "exited"))
1038 ide.outputView.debugBox.Logf($"The program %s has exited%s.\n", program, verboseExitCode);
1039 else if(!strcmp(reason, "exited-signalled"))
1040 ide.outputView.debugBox.Logf($"The program %s has exited with a signal%s.\n", program, verboseExitCode);
1042 ide.outputView.debugBox.Logf($"The program %s has exited (gdb provided an unknown reason)%s.\n", program, verboseExitCode);
1047 DebuggerState StartSession(CompilerConfig compiler, ProjectConfig config, int bitDepth, bool useValgrind, bool restart, bool ignoreBreakpoints)
1049 DebuggerState result = none;
1050 _dpl2(_dpct, dplchan::debuggerCall, 0, "Debugger::StartSession(restart(", restart, "), ignoreBreakpoints(", ignoreBreakpoints, ")");
1051 if(restart && state == running && targetProcessId)
1053 breakType = DebuggerAction::restart;
1054 GdbDebugBreak(false);
1058 if(restart && state == stopped)
1060 if(needReset && state == loaded)
1061 GdbExit(); // this reset is to get a clean state with all the breakpoints until a better state can be maintained on program exit
1063 if(result == none || result == terminated)
1065 ide.outputView.ShowClearSelectTab(debug);
1066 ide.outputView.debugBox.Logf($"Starting debug mode\n");
1073 for(bp : ide.workspace.breakpoints)
1079 if(GdbInit(compiler, config, bitDepth, useValgrind))
1084 this.ignoreBreakpoints = ignoreBreakpoints;
1089 void Start(CompilerConfig compiler, ProjectConfig config, int bitDepth, bool useValgrind)
1091 _dpl2(_dpct, dplchan::debuggerCall, 0, "Debugger::Start()");
1092 _ChangeUserAction(start);
1093 if(StartSession(compiler, config, bitDepth, useValgrind, true, false) == loaded)
1097 void StepInto(CompilerConfig compiler, ProjectConfig config, int bitDepth, bool useValgrind)
1099 _dpl2(_dpct, dplchan::debuggerCall, 0, "Debugger::StepInto()");
1100 _ChangeUserAction(stepInto);
1101 switch(StartSession(compiler, config, bitDepth, useValgrind, false, false))
1103 case loaded: GdbExecRun(); break;
1104 case stopped: GdbExecStep(); break;
1108 void StepOver(CompilerConfig compiler, ProjectConfig config, int bitDepth, bool useValgrind, bool ignoreBreakpoints)
1110 _dpl2(_dpct, dplchan::debuggerCall, 0, "Debugger::StepOver()");
1111 _ChangeUserAction(stepOver);
1112 switch(StartSession(compiler, config, bitDepth, useValgrind, false, ignoreBreakpoints))
1114 case loaded: GdbExecRun(); break;
1115 case stopped: GdbExecNext(); break;
1119 void StepUntil(CompilerConfig compiler, ProjectConfig config, int bitDepth, bool useValgrind, bool ignoreBreakpoints)
1121 _dpl2(_dpct, dplchan::debuggerCall, 0, "Debugger::StepUntil()");
1122 _ChangeUserAction(stepUntil);
1123 switch(StartSession(compiler, config, bitDepth, useValgrind, false, ignoreBreakpoints))
1125 case loaded: GdbExecRun(); break;
1126 case stopped: GdbExecUntil(null, 0); break;
1130 void StepOut(bool ignoreBreakpoints)
1132 _dpl2(_dpct, dplchan::debuggerCall, 0, "Debugger::StepOut()");
1133 _ChangeUserAction(stepOut);
1134 if(state == stopped)
1136 this.ignoreBreakpoints = ignoreBreakpoints;
1140 GdbExecContinue(true);
1144 void RunToCursor(CompilerConfig compiler, ProjectConfig config, int bitDepth, bool useValgrind, const char * absoluteFilePath, int lineNumber, bool ignoreBreakpoints, bool atSameLevel, bool oldImplementation)
1146 char relativeFilePath[MAX_LOCATION];
1147 _dpl2(_dpct, dplchan::debuggerCall, 0, "Debugger::RunToCursor()");
1148 _ChangeUserAction(runToCursor);
1149 WorkspaceGetRelativePath(absoluteFilePath, relativeFilePath, null);
1151 if(bpRunToCursor && bpRunToCursor.inserted && symbols)
1153 UnsetBreakpoint(bpRunToCursor);
1154 delete bpRunToCursor;
1157 StartSession(compiler, config, bitDepth, useValgrind, false, ignoreBreakpoints);
1160 if(oldImplementation)
1162 bpRunToCursor = Breakpoint { };
1163 bpRunToCursor.absoluteFilePath = absoluteFilePath;
1164 bpRunToCursor.relativeFilePath = relativeFilePath;
1165 bpRunToCursor.line = lineNumber;
1166 bpRunToCursor.type = runToCursor;
1167 bpRunToCursor.enabled = true;
1168 bpRunToCursor.level = atSameLevel ? frameCount - activeFrameLevel -1 : -1;
1173 breakType = advance;
1174 breakString = PrintString(relativeFilePath, ":", lineNumber);
1177 else if(state == stopped)
1179 if(oldImplementation)
1180 GdbExecContinue(true);
1184 GdbExecUntil(absoluteFilePath, lineNumber);
1186 GdbExecAdvance(absoluteFilePath, lineNumber);
1191 void GetCallStackCursorLine(bool * error, int * lineCursor, int * lineTopFrame)
1193 //_dpl2(_dpct, dplchan::debuggerCall, 0, "Debugger::GetCallStackCursorLine()");
1194 if(activeFrameLevel == -1)
1202 *error = signalOn && activeThread == signalThread;
1203 *lineCursor = activeFrameLevel - ((frameCount > 192 && activeFrameLevel > 191) ? frameCount - 192 - 1 : 0) + 1;
1204 *lineTopFrame = activeFrameLevel ? 1 : 0;
1208 int GetMarginIconsLineNumbers(const char * fileName, int lines[], bool enabled[], int max, bool * error, int * lineCursor, int * lineTopFrame)
1210 char winFilePath[MAX_LOCATION];
1211 char * absoluteFilePath = GetSlashPathBuffer(winFilePath, fileName);
1213 Iterator<Breakpoint> it { ide.workspace.breakpoints };
1214 //_dpl2(_dpct, dplchan::debuggerCall, 0, "Debugger::GetMarginIconsLineNumbers()");
1215 while(it.Next() && count < max)
1217 Breakpoint bp = it.data;
1220 if(bp.absoluteFilePath && bp.absoluteFilePath[0] && !fstrcmp(bp.absoluteFilePath, absoluteFilePath))
1222 lines[count] = bp.line;
1223 enabled[count] = bp.enabled;
1228 if(activeFrameLevel == -1)
1236 *error = signalOn && activeThread == signalThread;
1237 if(activeFrame && activeFrame.absoluteFile && !fstrcmp(absoluteFilePath, activeFrame.absoluteFile))
1238 *lineCursor = activeFrame.line;
1241 if(activeFrame && stopItem && stopItem.frame && activeFrame.level == stopItem.frame.level)
1243 else if(stopItem && stopItem.frame && stopItem.frame.absoluteFile && !fstrcmp(absoluteFilePath, stopItem.frame.absoluteFile))
1244 *lineTopFrame = stopItem.frame.line;
1248 if(*lineTopFrame == *lineCursor && *lineTopFrame)
1254 void ChangeWatch(DataRow row, char * expression)
1256 Watch wh = (Watch)row.tag;
1257 //_dpl2(_dpct, dplchan::debuggerCall, 0, "Debugger::ChangeWatch(", expression, ")");
1260 delete wh.expression;
1262 wh.expression = CopyString(expression);
1265 Iterator<Watch> it { ide.workspace.watches };
1267 ide.workspace.watches.Delete(it.pointer);
1273 row.tag = (int64)wh;
1274 ide.workspace.watches.Add(wh);
1276 wh.expression = CopyString(expression);
1278 ide.workspace.Save();
1279 //if(expression && state == stopped)
1284 void MoveIcons(const char * fileName, int lineNumber, int move, bool start)
1286 char winFilePath[MAX_LOCATION];
1287 const char * absoluteFilePath = GetSlashPathBuffer(winFilePath, fileName);
1290 //_dpl2(_dpct, dplchan::debuggerCall, 0, "Debugger::MoveIcons()");
1291 for(bpLink = ide.workspace.breakpoints.first; bpLink; bpLink = next)
1293 Breakpoint bp = (Breakpoint)bpLink.data;
1296 if(bp.type == user && bp.absoluteFilePath && !fstrcmp(bp.absoluteFilePath, absoluteFilePath))
1298 if(bp.line > lineNumber || (bp.line == lineNumber && start))
1300 if(move < 0 && (bp.line < lineNumber - move))
1301 ide.workspace.RemoveBreakpoint(bp);
1305 ide.breakpointsView.UpdateBreakpoint(bp.row);
1306 ide.workspace.Save();
1312 // moving code cursors is futile, on next step, stop, hit, cursors will be offset anyways
1315 bool SourceDirDialog(const char * title, const char * startDir, const char * test, char * sourceDir)
1318 String srcDir = null;
1320 _dpl2(_dpct, dplchan::debuggerCall, 0, "Debugger::SourceDirDialog()");
1321 debuggerFileDialog.text = title;
1322 debuggerFileDialog.currentDirectory = startDir;
1323 debuggerFileDialog.master = ide;
1325 while(debuggerFileDialog.Modal())
1327 strcpy(sourceDir, debuggerFileDialog.filePath);
1328 if(!fstrcmp(ide.workspace.projectDir, sourceDir) &&
1329 MessageBox { type = yesNo, master = ide,
1330 contents = $"This is the project directory.\nWould you like to try again?",
1331 text = $"Invalid Source Directory" }.Modal() == no)
1335 for(dir : ide.workspace.sourceDirs)
1337 if(!fstrcmp(dir, sourceDir))
1345 MessageBox { type = yesNo, master = ide,
1346 contents = $"This source directory is already specified.\nWould you like to try again?",
1347 text = $"Invalid Source Directory" }.Modal() == no)
1353 char file[MAX_LOCATION];
1354 strcpy(file, sourceDir);
1355 PathCat(file, test);
1356 result = FileExists(file);
1358 MessageBox { type = yesNo, master = ide,
1359 contents = $"Unable to locate source file.\nWould you like to try again?",
1360 text = $"Invalid Source Directory" }.Modal() == no)
1374 void AddSourceDir(const char * sourceDir)
1376 _dpl2(_dpct, dplchan::debuggerCall, 0, "Debugger::AddSourceDir(", sourceDir, ")");
1377 ide.workspace.sourceDirs.Add(CopyString(sourceDir));
1378 ide.workspace.Save();
1382 DebuggerState oldState = state;
1387 GdbDebugBreak(true);
1390 GdbCommand(0, false, "-environment-directory \"%s\"", sourceDir);
1393 if(oldState == running)
1394 GdbExecContinue(false);
1398 void ToggleBreakpoint(const char * fileName, int lineNumber)
1400 char absolutePath[MAX_LOCATION];
1401 Breakpoint bp = null;
1403 _dpl2(_dpct, dplchan::debuggerBreakpoints, 0, "Debugger::ToggleBreakpoint(", fileName, ":", lineNumber, ")");
1405 GetSlashPathBuffer(absolutePath, fileName);
1406 for(i : ide.workspace.breakpoints; i.type == user && i.absoluteFilePath && !fstrcmp(i.absoluteFilePath, absolutePath) && i.line == lineNumber)
1415 ide.workspace.RemoveBreakpoint(bp);
1424 char relativePath[MAX_LOCATION];
1426 WorkspaceGetRelativePath(absolutePath, relativePath, &owner);
1428 if(!owner && !FileExists(absolutePath))
1430 char title[MAX_LOCATION];
1431 char directory[MAX_LOCATION];
1432 char sourceDir[MAX_LOCATION];
1433 StripLastDirectory(absolutePath, directory);
1434 snprintf(title, sizeof(title), $"Provide source files location directory for %s", relativePath);
1435 title[sizeof(title)-1] = 0;
1438 String srcDir = null;
1439 for(dir : ide.workspace.sourceDirs)
1441 if(IsPathInsideOf(absolutePath, dir))
1443 MakePathRelative(absolutePath, dir, relativePath);
1451 if(SourceDirDialog(title, directory, null, sourceDir))
1453 if(IsPathInsideOf(absolutePath, sourceDir))
1455 AddSourceDir(sourceDir);
1456 MakePathRelative(absolutePath, sourceDir, relativePath);
1459 else if(MessageBox { type = yesNo, master = ide,
1460 contents = $"You must provide a valid source directory in order to place a breakpoint in this file.\nWould you like to try again?",
1461 text = $"Invalid Source Directory" }.Modal() == no)
1468 ide.workspace.bpCount++;
1469 bp = { line = lineNumber, type = user, enabled = true, level = -1, project = owner };
1470 ide.workspace.breakpoints.Add(bp);
1471 bp.absoluteFilePath = absolutePath;
1472 bp.relativeFilePath = relativePath;
1473 ide.breakpointsView.AddBreakpoint(bp);
1478 DebuggerState oldState = state;
1483 GdbDebugBreak(true);
1486 if(!SetBreakpoint(bp, false))
1487 SetBreakpoint(bp, true);
1490 if(oldState == running)
1491 GdbExecContinue(false);
1494 ide.workspace.Save();
1497 void UpdateRemovedBreakpoint(Breakpoint bp)
1499 _dpl2(_dpct, dplchan::debuggerCall, 0, "Debugger::UpdateRemovedBreakpoint()");
1500 if(targeted && bp.inserted)
1502 DebuggerState oldState = state;
1507 GdbDebugBreak(true);
1510 UnsetBreakpoint(bp);
1513 if(oldState == running)
1514 GdbExecContinue(false);
1520 void ParseFrame(Frame frame, char * string)
1523 Array<char *> frameTokens { minAllocSize = 50 };
1524 Array<char *> argsTokens { minAllocSize = 50 };
1525 Array<char *> argumentTokens { minAllocSize = 50 };
1526 DebugListItem item { };
1529 //_dpl2(_dpct, dplchan::debuggerCall, 0, "Debugger::ParseFrame()");
1530 TokenizeList(string, ',', frameTokens);
1531 for(i = 0; i < frameTokens.count; i++)
1533 if(TokenizeListItem(frameTokens[i], item))
1535 StripQuotes(item.value, item.value);
1536 if(!strcmp(item.name, "level"))
1537 frame.level = atoi(item.value);
1538 else if(!strcmp(item.name, "addr"))
1539 frame.addr = item.value;
1540 else if(!strcmp(item.name, "func"))
1541 frame.func = item.value;
1542 else if(!strcmp(item.name, "args"))
1544 if(!strcmp(item.value, "[]"))
1545 frame.argsCount = 0;
1548 item.value = StripBrackets(item.value);
1549 TokenizeList(item.value, ',', argsTokens);
1550 for(j = 0; j < argsTokens.count; j++)
1552 argsTokens[j] = StripCurlies(argsTokens[j]);
1553 TokenizeList(argsTokens[j], ',', argumentTokens);
1554 for(k = 0; k < argumentTokens.count; k++)
1557 frame.args.Add(arg);
1558 if(TokenizeListItem(argumentTokens[k], item))
1560 if(!strcmp(item.name, "name"))
1562 StripQuotes(item.value, item.value);
1563 arg.name = item.value;
1565 else if(!strcmp(item.name, "value"))
1567 StripQuotes(item.value, item.value);
1568 arg.val = item.value;
1571 _dpl2(_dpct, dplchan::gdbProtoUnknown, 0, "frame args item (", item.name, "=", item.value, ") is unheard of");
1574 _dpl(0, "Bad frame args item");
1576 argumentTokens.RemoveAll();
1578 frame.argsCount = argsTokens.count;
1579 argsTokens.RemoveAll();
1582 else if(!strcmp(item.name, "from"))
1583 frame.from = item.value;
1584 else if(!strcmp(item.name, "file"))
1585 frame.file = item.value;
1586 else if(!strcmp(item.name, "line"))
1587 frame.line = atoi(item.value);
1588 else if(!strcmp(item.name, "fullname"))
1590 // GDB 6.3 on OS X is giving "fullname" and "dir", all in absolute, but file name only in 'file'
1591 Workspace ws = ide.workspace;
1594 String path = ide.workspace.GetPathWorkspaceRelativeOrAbsolute(item.value);
1595 if(strcmp(frame.file, path))
1599 frame.absoluteFile = item.value;
1602 _dpl2(_dpct, dplchan::gdbProtoUnknown, 0, "frame member (", item.name, "=", item.value, ") is unheard of");
1605 _dpl(0, "Bad frame");
1610 delete argumentTokens;
1614 Breakpoint GetBreakpointById(int id, bool * isInternal)
1616 Breakpoint bp = null;
1617 //_dpl2(_dpct, dplchan::debuggerBreakpoints, 0, "Debugger::GetBreakpointById(", id, ")");
1619 *isInternal = false;
1622 for(i : sysBPs; i.bp && i.bp.id == id)
1629 if(!bp && bpRunToCursor && bpRunToCursor.bp && bpRunToCursor.bp.id == id)
1633 for(i : ide.workspace.breakpoints; i.bp && i.bp.id == id)
1643 GdbDataBreakpoint ParseBreakpoint(char * string, Array<char *> outTokens)
1646 GdbDataBreakpoint bp { };
1647 DebugListItem item { };
1648 Array<char *> bpTokens { minAllocSize = 16 };
1649 _dpl2(_dpct, dplchan::debuggerCall, 0, "Debugger::ParseBreakpoint()");
1650 string = StripCurlies(string);
1651 TokenizeList(string, ',', bpTokens);
1652 for(i = 0; i < bpTokens.count; i++)
1654 if(TokenizeListItem(bpTokens[i], item))
1656 StripQuotes(item.value, item.value);
1657 if(!strcmp(item.name, "number"))
1659 if(!strchr(item.value, '.'))
1660 bp.id = atoi(item.value);
1661 bp.number = item.value;
1663 else if(!strcmp(item.name, "type"))
1664 bp.type = item.value;
1665 else if(!strcmp(item.name, "disp"))
1666 bp.disp = item.value;
1667 else if(!strcmp(item.name, "enabled"))
1668 bp.enabled = (!strcmpi(item.value, "y"));
1669 else if(!strcmp(item.name, "addr"))
1671 if(outTokens && !strcmp(item.value, "<MULTIPLE>"))
1674 Array<GdbDataBreakpoint> bpArray = bp.multipleBPs = { };
1675 while(outTokens.count > ++c)
1677 GdbDataBreakpoint multBp = ParseBreakpoint(outTokens[c], null);
1678 bpArray.Add(multBp);
1682 bp.addr = item.value;
1684 else if(!strcmp(item.name, "func"))
1685 bp.func = item.value;
1686 else if(!strcmp(item.name, "file"))
1687 bp.file = item.value;
1688 else if(!strcmp(item.name, "fullname"))
1689 bp.fullname = item.value;
1690 else if(!strcmp(item.name, "line"))
1691 bp.line = atoi(item.value);
1692 else if(!strcmp(item.name, "at"))
1694 else if(!strcmp(item.name, "times"))
1695 bp.times = atoi(item.value);
1696 else if(!strcmp(item.name, "original-location") || !strcmp(item.name, "thread-groups"))
1697 _dpl2(_dpct, dplchan::gdbProtoIgnored, 0, "breakpoint member (", item.name, "=", item.value, ") is ignored");
1699 _dpl2(_dpct, dplchan::gdbProtoUnknown, 0, "breakpoint member (", item.name, "=", item.value, ") is unheard of");
1707 void ShowDebuggerViews()
1709 //_dpl2(_dpct, dplchan::debuggerCall, 0, "Debugger::ShowDebuggerViews()");
1710 ide.outputView.Show();
1711 ide.outputView.SelectTab(debug);
1712 ide.threadsView.Show();
1713 ide.callStackView.Show();
1714 ide.watchesView.Show();
1718 void HideDebuggerViews()
1720 //_dpl2(_dpct, dplchan::debuggerCall, 0, "Debugger::HideDebuggerViews()");
1721 ide.RepositionWindows(true);
1724 bool ::GdbCommand(Time timeOut, bool focus, const char * format, ...)
1726 bool result = false;
1730 // TODO: Improve this limit
1731 static char string[MAX_F_STRING*4];
1733 va_start(args, format);
1734 vsnprintf(string, sizeof(string), format, args);
1735 string[sizeof(string)-1] = 0;
1739 ide.debugger.serialSemaphore.TryWait();
1741 #ifdef GDB_DEBUG_CONSOLE
1742 _dpl2(_dpct, dplchan::gdbCommand, 0, string);
1744 #ifdef GDB_DEBUG_OUTPUT
1745 ide.outputView.gdbBox.Logf("cmd: %s\n", string);
1747 #ifdef GDB_DEBUG_GUI
1749 ide.gdbDialog.AddCommand(string);
1752 strcat(string,"\n");
1753 gdbHandle.Puts(string);
1756 Process_ShowWindows(targetProcessId);
1762 startTime = GetTime();
1765 if(ide.debugger.serialSemaphore.TryWait())
1772 if(GetTime() - startTime > timeOut)
1780 ide.debugger.serialSemaphore.Wait();
1789 bool ValidateBreakpoint(Breakpoint bp)
1791 _dpl2(_dpct, dplchan::debuggerCall, 0, "Debugger::ValidateBreakpoint()");
1792 if(modules && bp.line && bp.bp)
1794 if(bp.bp.line != bp.line)
1800 ide.outputView.debugBox.Logf("WOULD HAVE -- Invalid breakpoint disabled: %s:%d\n", bp.relativeFilePath, bp.line);
1802 //UnsetBreakpoint(bp);
1803 //bp.enabled = false;
1809 ide.outputView.debugBox.Logf("Debugger Error: ValidateBreakpoint error\n");
1810 bp.line = bp.bp.line;
1817 void BreakpointsMaintenance()
1819 //_dpl2(_dpct, dplchan::debuggerBreakpoints, 0, "Debugger::BreakpointsMaintenance()");
1822 if(gdbExecution.suspendInternalBreakpoints)
1824 for(bp : sysBPs; bp.inserted)
1825 UnsetBreakpoint(bp);
1829 DirExpression objDir = ide.project.GetObjDir(currentCompiler, prjConfig, bitDepth);
1830 for(bp : sysBPs; !bp.inserted)
1832 bool insert = false;
1833 if(bp.type == internalModulesLoaded)
1835 char path[MAX_LOCATION];
1836 char name[MAX_LOCATION];
1837 char fixedModuleName[MAX_FILENAME];
1840 bool moduleLoadBlock = false;
1842 ReplaceSpaces(fixedModuleName, ide.project.moduleName);
1843 snprintf(name, sizeof(name),"%s.main.ec", fixedModuleName);
1844 name[sizeof(name)-1] = 0;
1845 strcpy(path, ide.workspace.projectDir);
1846 PathCatSlash(path, objDir.dir);
1847 PathCatSlash(path, name);
1848 f = FileOpen(path, read);
1851 for(lineNumber = 1; !f.Eof(); lineNumber++)
1853 if(f.GetLine(line, sizeof(line) - 1))
1855 bool moduleLoadLine;
1856 TrimLSpaces(line, line);
1857 moduleLoadLine = !strncmp(line, "eModule_Load", strlen("eModule_Load"));
1858 if(!moduleLoadBlock && moduleLoadLine)
1859 moduleLoadBlock = true;
1860 else if(moduleLoadBlock && !moduleLoadLine && strlen(line) > 0)
1866 char relative[MAX_LOCATION];
1867 bp.absoluteFilePath = path;
1868 MakePathRelative(path, ide.workspace.projectDir, relative);
1869 bp.relativeFilePath = relative;
1870 bp.line = lineNumber;
1876 else if(bp.type == internalModuleLoad)
1880 for(prj : ide.workspace.projects)
1882 if(!strcmp(prj.moduleName, "ecere"))
1884 ProjectNode node = prj.topNode.Find("instance.c", false);
1887 char path[MAX_LOCATION];
1888 char relative[MAX_LOCATION];
1889 node.GetFullFilePath(path);
1890 bp.absoluteFilePath = path;
1891 MakePathRelative(path, prj.topNode.path, relative);
1892 bp.relativeFilePath = relative;
1904 if(!SetBreakpoint(bp, false))
1905 SetBreakpoint(bp, true);
1911 if(userAction != runToCursor && bpRunToCursor && bpRunToCursor.inserted)
1912 UnsetBreakpoint(bpRunToCursor);
1913 if(bpRunToCursor && !bpRunToCursor.inserted)
1915 if(!SetBreakpoint(bpRunToCursor, false))
1916 SetBreakpoint(bpRunToCursor, true);
1919 if(ignoreBreakpoints)
1921 for(bp : ide.workspace.breakpoints; bp.inserted)
1922 UnsetBreakpoint(bp);
1926 for(bp : ide.workspace.breakpoints; !bp.inserted && bp.type == user)
1930 if(!SetBreakpoint(bp, false))
1931 SetBreakpoint(bp, true);
1940 bp.bp = GdbDataBreakpoint { };
1947 void UnsetBreakpoint(Breakpoint bp)
1949 char * s = null; _dpl2(_dpct, dplchan::debuggerBreakpoints, 0, "Debugger::UnsetBreakpoint(", s=bp.CopyLocationString(false), ") -- ", bp.type); delete s;
1950 if(symbols && bp.inserted)
1952 GdbCommand(0, false, "-break-delete %s", bp.bp.number);
1953 bp.inserted = false;
1959 bool SetBreakpoint(Breakpoint bp, bool removePath)
1961 char * s = null; _dpl2(_dpct, dplchan::debuggerBreakpoints, 0, "Debugger::SetBreakpoint(", s=bp.CopyLocationString(false), ", ", removePath ? "**** removePath(true) ****" : "", ") -- ", bp.type); delete s;
1962 breakpointError = false;
1963 if(symbols && bp.enabled && (!bp.project || bp.project.GetTargetType(bp.project.config) == staticLibrary || bp.project == ide.project || projectsLibraryLoaded[bp.project.name]))
1965 sentBreakInsert = true;
1967 GdbCommand(0, false, "-break-insert *%s", bp.address);
1970 char * location = bp.CopyLocationString(removePath);
1971 GdbCommand(0, false, "-break-insert %s", location);
1974 if(!breakpointError)
1976 char * address = null;
1977 if(bpItem && bpItem.multipleBPs && bpItem.multipleBPs.count)
1980 GdbDataBreakpoint first = null;
1981 for(n : bpItem.multipleBPs)
1983 if(!fstrcmp(n.fullname, bp.absoluteFilePath) && !first)
1993 GdbCommand(0, false, "-break-disable %s", n.number);
1997 _dpl2(_dpct, dplchan::debuggerProblem, 0, "Debugger::SetBreakpoint -- error breakpoint already disabled.");
2002 address = CopyString(first.addr);
2003 bpItem.addr = first.addr;
2004 bpItem.func = first.func;
2005 bpItem.file = first.file;
2006 bpItem.fullname = first.fullname;
2007 bpItem.line = first.line;
2008 //bpItem.thread-groups = first.thread-groups;*/
2011 _dpl2(_dpct, dplchan::debuggerProblem, 0, "Debugger::SetBreakpoint -- error multiple breakpoints all disabled.");
2013 _dpl2(_dpct, dplchan::debuggerProblem, 0, "Debugger::SetBreakpoint -- error multiple breakpoints in exact same file not supported.");
2014 bpItem.multipleBPs.Free();
2015 delete bpItem.multipleBPs;
2020 bp.inserted = (bp.bp && bp.bp.number && strcmp(bp.bp.number, "0"));
2022 ValidateBreakpoint(bp);
2026 UnsetBreakpoint(bp);
2027 bp.address = address;
2029 SetBreakpoint(bp, removePath);
2032 return !breakpointError;
2039 _dpl2(_dpct, dplchan::debuggerCall, 0, "Debugger::GdbGetStack()");
2041 stackFrames.Free(Frame::Free);
2042 GdbCommand(0, false, "-stack-info-depth");
2044 GdbCommand(0, false, "-stack-info-depth 192");
2045 if(frameCount && frameCount <= 192)
2046 GdbCommand(0, false, "-stack-list-frames 0 %d", Min(frameCount-1, 191));
2049 GdbCommand(0, false, "-stack-list-frames 0 %d", Min(frameCount-1, 95));
2050 GdbCommand(0, false, "-stack-list-frames %d %d", Max(frameCount - 96, 96), frameCount - 1);
2052 GdbCommand(0, false, "");
2057 _dpl2(_dpct, dplchan::debuggerCall, 0, "Debugger::GdbTargetSet()");
2060 char escaped[MAX_LOCATION];
2061 strescpy(escaped, targetFile);
2062 GdbCommand(0, 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
2069 const char *vgdbCommand = "/usr/bin/vgdb"; // TODO: vgdb command config option
2070 //GdbCommand(0, false, "-target-select remote | %s --pid=%d", "vgdb", targetProcessId);
2071 printf("target remote | %s --pid=%d\n", vgdbCommand, targetProcessId);
2072 GdbCommand(0, false, "target remote | %s --pid=%d", vgdbCommand, targetProcessId); // TODO: vgdb command config option
2075 GdbCommand(0, false, "info target"); //GDB/MI Missing Implementation -file-list-symbol-files and -file-list-exec-sections
2077 /*for(prj : ide.workspace.projects; prj != ide.workspace.projects.firstIterator.data)
2078 GdbCommand(0, false, "-environment-directory \"%s\"", prj.topNode.path);*/
2080 for(dir : ide.workspace.sourceDirs; dir && dir[0])
2082 bool interference = false;
2083 for(prj : ide.workspace.projects)
2085 if(!fstrcmp(prj.topNode.path, dir))
2087 interference = true;
2091 if(!interference && dir[0])
2092 GdbCommand(0, false, "-environment-directory \"%s\"", dir);
2100 /*void GdbTargetRelease()
2104 BreakpointsDeleteAll();
2105 GdbCommand(0, false, "file"); //GDB/MI Missing Implementation -target-detach
2111 void GdbDebugBreak(bool internal)
2113 _dpl2(_dpct, dplchan::debuggerCall, 0, "Debugger::GdbDebugBreak()");
2117 breakType = DebuggerAction::internal;
2119 if(ide) ide.Update(null);
2121 if(Process_Break(targetProcessId)) //GdbCommand(0, false, "-exec-interrupt");
2122 serialSemaphore.Wait();
2125 _ChangeState(loaded);
2126 targetProcessId = 0;
2131 ide.outputView.debugBox.Logf("Debugger Error: GdbDebugBreak with not target id should never happen\n");
2136 _dpl2(_dpct, dplchan::debuggerCall, 0, "Debugger::GdbExecRun()");
2141 ShowDebuggerViews();
2143 GdbExecContinue(true);
2144 else if(!GdbCommand(3, true, "-exec-run"))
2145 gdbExecution = none;
2148 void GdbExecContinue(bool focus)
2150 _dpl2(_dpct, dplchan::debuggerCall, 0, "Debugger::GdbExecContinue()");
2153 GdbCommand(0, focus, "-exec-continue");
2158 _dpl2(_dpct, dplchan::debuggerCall, 0, "Debugger::GdbExecNext()");
2159 gdbExecution = next;
2161 GdbCommand(0, true, "-exec-next");
2164 void ForceUpdateCurrentFrame()
2167 GdbCommand(0, false, "-thread-list-ids");
2168 InternalSelectFrame(activeFrameLevel);
2169 GoToStackFrameLine(activeFrameLevel, true, false);
2171 ide.ShowCodeEditor();
2172 ide.AdjustDebugMenus();
2173 ideMainFrame.Activate(); // TOFIX: ide.Activate() is not reliable (app inactive)
2177 void GdbExecUntil(const char * absoluteFilePath, int lineNumber)
2179 bool forceUpdate = false;
2180 char relativeFilePath[MAX_LOCATION];
2181 _dpl2(_dpct, dplchan::debuggerCall, 0, "Debugger::GdbExecUntil()");
2182 gdbExecution = until;
2184 if(absoluteFilePath)
2186 WorkspaceGetRelativePath(absoluteFilePath, relativeFilePath, null);
2187 if(!GdbCommand(0.1, true, "-exec-until %s:%d", relativeFilePath, lineNumber))
2189 GetLastDirectory(relativeFilePath, relativeFilePath);
2190 if(GdbCommand(1, true, "-exec-until %s:%d", relativeFilePath, lineNumber))
2195 GdbCommand(0, true, "-exec-until");
2197 // This is to handle GDB 6.3 on OS X not giving us *running then *stopped:
2198 // (It may not be ideal, we may need to wait?)
2200 ForceUpdateCurrentFrame();
2203 void GdbExecAdvance(const char * absoluteFilePathOrLocation, int lineNumber)
2205 bool forceUpdate = false;
2206 char relativeFilePath[MAX_LOCATION];
2207 _dpl2(_dpct, dplchan::debuggerCall, 0, "Debugger::GdbExecAdvance()");
2208 gdbExecution = advance;
2212 WorkspaceGetRelativePath(absoluteFilePathOrLocation, relativeFilePath, null);
2213 if(!GdbCommand(0.1, true, "advance %s:%d", relativeFilePath, lineNumber)) // should use -exec-advance -- GDB/MI implementation missing
2215 GetLastDirectory(relativeFilePath, relativeFilePath);
2216 if(GdbCommand(1, true, "advance %s:%d", relativeFilePath, lineNumber))
2222 if(!GdbCommand(0.1, true, "advance %s", absoluteFilePathOrLocation)) // should use -exec-advance -- GDB/MI implementation missing
2224 GetLastDirectory(absoluteFilePathOrLocation, relativeFilePath);
2225 if(GdbCommand(1, true, "advance %s", relativeFilePath))
2230 // This is to handle GDB 6.3 on OS X not giving us *running then *stopped:
2231 // (It may not be ideal, we may need to wait?)
2233 ForceUpdateCurrentFrame();
2238 _dpl2(_dpct, dplchan::debuggerCall, 0, "Debugger::GdbExecStep()");
2239 gdbExecution = step;
2241 GdbCommand(0, true, "-exec-step");
2244 void GdbExecFinish()
2246 _dpl2(_dpct, dplchan::debuggerCall, 0, "Debugger::GdbExecFinish()");
2247 gdbExecution = finish;
2249 GdbCommand(0, true, "-exec-finish");
2252 void GdbExecCommon()
2254 //_dpl2(_dpct, dplchan::debuggerCall, 0, "Debugger::GdbExecCommon()");
2255 BreakpointsMaintenance();
2258 #ifdef GDB_DEBUG_GUI
2259 void SendGDBCommand(const char * command)
2261 //_dpl2(_dpct, dplchan::debuggerCall, 0, "Debugger::SendGDBCommand()");
2262 DebuggerState oldState = state;
2267 GdbDebugBreak(true);
2270 GdbCommand(0, false, command);
2273 if(oldState == running)
2274 GdbExecContinue(false);
2278 void ClearBreakDisplay()
2280 //_dpl2(_dpct, dplchan::debuggerCall, 0, "Debugger::ClearBreakDisplay()");
2282 activeFrameLevel = -1;
2292 stackFrames.Free(Frame::Free);
2293 ide.callStackView.Clear();
2294 ide.threadsView.Clear();
2300 _dpl2(_dpct, dplchan::debuggerCall, 0, "Debugger::GdbAbortExec()");
2302 GdbCommand(0, false, "-interpreter-exec console \"kill\""); // should use -exec-abort -- GDB/MI implementation incomplete
2306 bool GdbInit(CompilerConfig compiler, ProjectConfig config, int bitDepth, bool useValgrind)
2309 char oldDirectory[MAX_LOCATION];
2310 char tempPath[MAX_LOCATION];
2311 char command[MAX_F_STRING*4];
2312 Project project = ide.project;
2313 DirExpression targetDirExp = project.GetTargetDir(compiler, config, bitDepth);
2314 PathBackup pathBackup { };
2315 Map<String, String> envBackup { };
2317 _dpl2(_dpct, dplchan::debuggerCall, 0, "Debugger::GdbInit()");
2318 if(currentCompiler != compiler)
2320 delete currentCompiler;
2321 currentCompiler = compiler;
2322 incref currentCompiler;
2325 this.bitDepth = bitDepth;
2326 usingValgrind = useValgrind;
2328 _ChangeState(loaded);
2330 sentBreakInsert = false;
2331 breakpointError = false;
2332 ignoreBreakpoints = false;
2338 projectsLibraryLoaded.Free();
2340 ide.outputView.ShowClearSelectTab(debug);
2341 ide.outputView.debugBox.Logf($"Starting debug mode\n");
2343 #ifdef GDB_DEBUG_OUTPUT
2344 ide.outputView.gdbBox.Logf("run: Starting GDB\n");
2347 strcpy(tempPath, ide.workspace.projectDir);
2348 PathCatSlash(tempPath, targetDirExp.dir);
2350 targetDir = CopyString(tempPath);
2351 project.CatTargetFileName(tempPath, compiler, config);
2353 targetFile = CopyString(tempPath);
2355 GetWorkingDir(oldDirectory, MAX_LOCATION);
2356 if(ide.workspace.debugDir && ide.workspace.debugDir[0])
2358 char temp[MAX_LOCATION];
2359 strcpy(temp, ide.workspace.projectDir);
2360 PathCatSlash(temp, ide.workspace.debugDir);
2361 ChangeWorkingDir(temp);
2364 ChangeWorkingDir(ide.workspace.projectDir);
2366 ide.SetPath(true, compiler, config, bitDepth);
2368 // TODO: This pollutes the environment, but at least it works
2369 // It shouldn't really affect the IDE as the PATH gets restored and other variables set for testing will unlikely cause problems
2370 // What is the proper solution for this? DualPipeOpenEnv?
2371 // gdb set environment commands don't seem to take effect
2372 for(e : ide.workspace.environmentVars)
2374 // Backing up the environment variables until we use DualPipeOpenEnv()
2375 envBackup[e.name] = CopyString(getenv(e.name));
2376 SetEnvironment(e.name, e.string);
2381 char * clArgs = ide.workspace.commandLineArgs;
2382 const char *valgrindCommand = "valgrind"; // TODO: valgrind command config option //TODO: valgrind options
2383 ValgrindLeakCheck vgLeakCheck = ide.workspace.vgLeakCheck;
2384 int vgRedzoneSize = ide.workspace.vgRedzoneSize;
2385 bool vgTrackOrigins = ide.workspace.vgTrackOrigins;
2386 vgLogFile = CreateTemporaryFile(vgLogPath, "ecereidevglog");
2390 vgLogThread.Create();
2394 ide.outputView.debugBox.Logf($"Debugger Fatal Error: Couldn't open temporary log file for Valgrind output\n");
2397 if(result && !CheckCommandAvailable(valgrindCommand))
2399 ide.outputView.debugBox.Logf($"Debugger Fatal Error: Command %s for Valgrind is not available.\n", valgrindCommand);
2404 char * vgRedzoneSizeFlag = PrintString(" --redzone-size=", vgRedzoneSize);
2405 sprintf(command, "%s --vgdb=yes --vgdb-error=0 --log-file=%s --leak-check=%s%s --track-origins=%s %s%s%s",
2406 valgrindCommand, vgLogPath, (char*)vgLeakCheck, vgRedzoneSize > -1 ? vgRedzoneSizeFlag : "", vgTrackOrigins ? "yes" : "no", targetFile, clArgs ? " " : "", clArgs ? clArgs : "");
2407 delete vgRedzoneSizeFlag;
2408 vgTargetHandle = DualPipeOpen(PipeOpenMode { output = true, /*error = true, */input = true }, command);
2411 ide.outputView.debugBox.Logf($"Debugger Fatal Error: Couldn't start Valgrind\n");
2417 incref vgTargetHandle;
2418 vgTargetThread.Create();
2420 targetProcessId = vgTargetHandle.GetProcessID();
2421 waitingForPID = false;
2422 if(!targetProcessId)
2424 ide.outputView.debugBox.Logf($"Debugger Fatal Error: Couldn't get Valgrind process ID\n");
2431 serialSemaphore.Wait();
2438 if(compiler.targetPlatform == win32)
2441 #if !((defined(__WORDSIZE) && __WORDSIZE == 8) || defined(__x86_64__))
2444 bitDepth == 32 ? "i686-w64-mingw32-gdb" : "gdb"); // x86_64-w64-mingw32-gdb
2447 // We really should have a box to select GDB in the compiler/toolchain options
2448 strcpy(command, "gdb");
2449 if(!CheckCommandAvailable(command))
2451 ide.outputView.debugBox.Logf($"Debugger Fatal Error: Command %s for GDB is not available.\n", command);
2456 strcat(command, " -n -silent --interpreter=mi2"); //-async //\"%s\"
2458 gdbHandle = DualPipeOpen(PipeOpenMode { output = true, /*error = true, */input = true }, command);
2461 ide.outputView.debugBox.Logf($"Debugger Fatal Error: Couldn't start GDB\n");
2471 gdbProcessId = gdbHandle.GetProcessID();
2474 ide.outputView.debugBox.Logf($"Debugger Fatal Error: Couldn't get GDB process ID\n");
2481 serialSemaphore.Wait();
2484 GdbCommand(0, false, "-gdb-set verbose off");
2485 //GdbCommand(0, false, "-gdb-set exec-done-display on");
2486 GdbCommand(0, false, "-gdb-set step-mode off");
2487 GdbCommand(0, false, "-gdb-set unwindonsignal on");
2488 //GdbCommand(0, false, "-gdb-set shell on");
2489 GdbCommand(0, false, "set print elements 992");
2490 GdbCommand(0, false, "-gdb-set backtrace limit 100000");
2494 //_ChangeState(terminated);
2500 #if defined(__unix__)
2502 CreateTemporaryDir(progFifoDir, "ecereide");
2503 strcpy(progFifoPath, progFifoDir);
2504 PathCat(progFifoPath, "ideprogfifo");
2505 if(!mkfifo(progFifoPath, 0600))
2507 //fileCreated = true;
2512 ide.outputView.debugBox.Logf(createFIFOMsg, progFifoPath);
2519 progThread.terminate = false;
2520 progThread.Create();
2524 #if defined(__WIN32__)
2525 GdbCommand(0, false, "-gdb-set new-console on");
2528 #if defined(__unix__)
2530 GdbCommand(0, false, "-inferior-tty-set %s", progFifoPath);
2534 GdbCommand(0, false, "-gdb-set args %s", ide.workspace.commandLineArgs ? ide.workspace.commandLineArgs : "");
2536 for(e : ide.workspace.environmentVars)
2538 GdbCommand(0, false, "set environment %s=%s", e.name, e.string);
2543 ChangeWorkingDir(oldDirectory);
2547 SetEnvironment(&e, e);
2556 delete targetDirExp;
2562 _dpl2(_dpct, dplchan::debuggerCall, 0, "Debugger::GdbExit()");
2563 if(gdbHandle && gdbProcessId)
2566 GdbCommand(0, false, "-gdb-exit");
2575 vgLogFile.CloseInput();
2576 if(vgLogThread.created)
2586 vgTargetThread.Wait();
2596 _ChangeState(terminated); // this state change seems to be superfluous, is it safety for something?
2601 for(bp : ide.workspace.breakpoints)
2607 bpRunToCursor.Reset();
2609 ide.outputView.debugBox.Logf($"Debugging stopped\n");
2611 #if defined(__unix__)
2612 if(!usingValgrind && FileExists(progFifoPath)) //fileCreated)
2614 progThread.terminate = true;
2617 fifoFile.CloseInput();
2623 DeleteFile(progFifoPath);
2624 progFifoPath[0] = '\0';
2633 bool WatchesLinkCodeEditor()
2635 bool goodFrame = activeFrame && activeFrame.absoluteFile;
2636 //_dpl2(_dpct, dplchan::debuggerCall, 0, "Debugger::WatchesLinkCodeEditor()");
2637 if(codeEditor && (!goodFrame || fstrcmp(codeEditor.fileName, activeFrame.absoluteFile)))
2638 WatchesReleaseCodeEditor();
2640 if(!codeEditor && goodFrame)
2642 codeEditor = (CodeEditor)ide.OpenFile(activeFrame.absoluteFile, false, false, null, no, normal, false);
2645 codeEditor.inUseDebug = true;
2649 return codeEditor != null;
2652 void WatchesReleaseCodeEditor()
2654 //_dpl2(_dpct, dplchan::debuggerCall, 0, "Debugger::WatchesReleaseCodeEditor()");
2657 codeEditor.inUseDebug = false;
2658 if(!codeEditor.visible)
2659 codeEditor.Destroy(0);
2664 bool ResolveWatch(Watch wh)
2666 bool result = false;
2668 _dpl2(_dpct, dplchan::debuggerWatches, 0, "Debugger::ResolveWatch()");
2680 char watchmsg[MAX_F_STRING];
2682 if(state == stopped && !codeEditor)
2683 wh.value = CopyString($"No source file found for selected frame");
2684 //if(codeEditor && state == stopped || state != stopped)
2687 Module backupPrivateModule;
2688 Context backupContext;
2689 Class backupThisClass;
2692 backupPrivateModule = GetPrivateModule();
2693 backupContext = GetCurrentContext();
2694 backupThisClass = GetThisClass();
2697 SetPrivateModule(codeEditor.privateModule);
2698 SetCurrentContext(codeEditor.globalContext);
2699 SetTopContext(codeEditor.globalContext);
2700 SetGlobalContext(codeEditor.globalContext);
2701 SetGlobalData(&codeEditor.globalData);
2704 exp = ParseExpressionString(wh.expression);
2706 if(exp && !GetParseError())
2708 char expString[4096];
2710 PrintExpression(exp, expString);
2713 if(codeEditor && activeFrame)
2714 DebugFindCtxTree(codeEditor.ast, activeFrame.line, 0);
2715 ProcessExpressionType(exp);
2717 wh.type = exp.expType;
2720 DebugComputeExpression(exp);
2721 // e.g. Meters * Degrees has no type set yet for some reason
2722 if(!wh.type && exp.expType)
2724 wh.type = exp.expType;
2725 exp.expType.refCount++;
2728 // This makes Degrees { 45 } work
2729 if(exp.type == constantExp && exp.isConstant && exp.expType && exp.expType.kind == classType &&
2730 exp.expType._class && exp.expType._class.registered && exp.expType._class.registered.type == unitClass && exp.expType._class.registered.base.type == unitClass)
2732 ApplyUnitConverters(exp);
2734 else if(exp.type == instanceExp && exp.instance.data)
2736 Symbol s = exp.instance._class ? exp.instance._class.symbol : null;
2737 Class c = s ? s.registered : null;
2741 bool needClass = false;
2742 char * s = ((char * (*)(void *, void *, void *, void *, void *))(void *)c._vTbl[__ecereVMethodID_class_OnGetString])(c, exp.instance.data, tmp, null, &needClass);
2745 FreeExpContents(exp);
2746 exp.type = constantExp;
2747 exp.isConstant = true;
2748 exp.constant = CopyString(s);
2752 else if(exp.expType && exp.expType.kind == classType && exp.expType._class && exp.expType._class.registered && exp.expType._class.registered.type == bitClass)
2754 Class c = exp.expType._class.registered;
2756 bool needClass = false;
2757 Operand op = GetOperand(exp);
2759 char * (* onGetString)(void *, void *, void *, void *, void *) = (void *)c._vTbl[__ecereVMethodID_class_OnGetString];
2762 if(op.type) op.type.refCount++;
2765 case charType: s = onGetString(c, &op.c, tmp, null, &needClass); break;
2766 case shortType: s = onGetString(c, &op.s, tmp, null, &needClass); break;
2767 case intType: s = onGetString(c, &op.i, tmp, null, &needClass); break;
2768 case int64Type: s = onGetString(c, &op.i64, tmp, null, &needClass); break;
2773 FreeExpContents(exp);
2774 exp.type = constantExp;
2775 exp.isConstant = true;
2776 exp.constant = CopyString(s);
2780 else if(exp.expType && exp.expType.kind == classType && exp.expType._class && exp.expType._class.registered && exp.expType._class.registered.type == structClass && exp.hasAddress)
2782 Class c = exp.expType._class.registered;
2783 char structString[1024];
2784 strcpy(structString, "*(struct ");
2785 FullClassNameCat(structString, c.fullName, false);
2786 strcat(structString, " *)");
2787 strcatf(structString, "0x%p", exp.address);
2788 GDBFallBack(exp, structString);
2790 byte * data = GdbReadMemory(exp.address, c.structSize);
2794 bool needClass = false;
2795 char * s = ((char * (*)(void *, void *, void *, void *, void *))(void *)c._vTbl[__ecereVMethodID_class_OnGetString])(c, data, tmp, null, &needClass);
2798 FreeExpContents(exp);
2799 exp.type = constantExp;
2800 exp.isConstant = true;
2801 exp.constant = CopyString(s);
2808 if(ExpressionIsError(exp) && exp.type != functionCallErrorExp)
2810 GDBFallBack(exp, expString);
2813 /*if(exp.hasAddress)
2815 char temp[MAX_F_STRING];
2816 sprintf(temp, "0x%x", exp.address);
2817 wh.address = CopyString(temp);
2818 // wh.address = CopyStringf("0x%x", exp.address);
2823 Type dataType = exp.expType;
2826 char temp[MAX_F_STRING];
2827 switch(dataType.kind)
2830 sprintf(temp, "%i", exp.val.c);
2833 sprintf(temp, "%i", exp.val.s);
2838 sprintf(temp, "%i", exp.val.i);
2841 sprintf(temp, "%i", exp.val.i64);
2844 sprintf(temp, "%i", exp.val.p);
2849 long v = (long)exp.val.f;
2850 sprintf(temp, "%i", v);
2855 long v = (long)exp.val.d;
2856 sprintf(temp, "%i", v);
2861 wh.intVal = CopyString(temp);
2862 switch(dataType.kind)
2865 sprintf(temp, "0x%x", exp.val.c);
2868 sprintf(temp, "0x%x", exp.val.s);
2872 sprintf(temp, "0x%x", exp.val.i);
2875 sprintf(temp, "0x%x", exp.val.i64);
2878 sprintf(temp, "0x%x", exp.val.i64);
2881 sprintf(temp, "0x%x", exp.val.p);
2886 long v = (long)exp.val.f;
2887 sprintf(temp, "0x%x", v);
2892 long v = (long)exp.val.d;
2893 sprintf(temp, "0x%x", v);
2898 wh.hexVal = CopyString(temp);
2899 switch(dataType.kind)
2902 sprintf(temp, "0o%o", exp.val.c);
2905 sprintf(temp, "0o%o", exp.val.s);
2909 sprintf(temp, "0o%o", exp.val.i);
2912 sprintf(temp, "0o%o", exp.val.i64);
2915 sprintf(temp, "0o%o", exp.val.i64);
2918 sprintf(temp, "0o%o", exp.val.p);
2923 long v = (long)exp.val.f;
2924 sprintf(temp, "0o%o", v);
2929 long v = (long)exp.val.d;
2930 sprintf(temp, "0o%o", v);
2935 wh.octVal = CopyString(temp);
2938 // WHATS THIS HERE ?
2939 if(exp.type == constantExp && exp.constant)
2940 wh.constant = CopyString(exp.constant);
2946 case symbolErrorExp:
2947 snprintf(watchmsg, sizeof(watchmsg), $"Symbol \"%s\" not found", exp.identifier.string);
2949 case memberSymbolErrorExp:
2951 Expression memberExp = exp.member.exp;
2952 Identifier memberID = exp.member.member;
2953 Type type = memberExp.expType;
2956 if(type.kind == structType || type.kind == unionType)
2958 char string[1024] = "";
2960 PrintTypeNoConst(type, string, false, true);
2961 snprintf(watchmsg, sizeof(watchmsg), $"Member \"%s\" not found in %s \"%s\"",
2962 memberID ? memberID.string : "", type.kind == unionType ? "union" : "struct", type.name ? type.name : string);
2966 Class _class = (memberID && memberID.classSym) ? memberID.classSym.registered : ((type.kind == classType && type._class) ? type._class.registered : null);
2967 char string[1024] = "";
2971 PrintTypeNoConst(type, string, false, true);
2972 classSym = FindClass(string);
2973 _class = classSym ? classSym.registered : null;
2976 snprintf(watchmsg, sizeof(watchmsg), $"Member \"%s\" not found in class \"%s\"", memberID ? memberID.string : "", _class.name);
2978 // NOTE: This should probably never happen, only classes and struct can be dereferenced, a dereferenceErrorExp should be displayed instead
2979 snprintf(watchmsg, sizeof(watchmsg), $"Member \"%s\" not found in type \"%s\"", memberID ? memberID.string : "", string);
2983 // NOTE: This should probably never happen, the error causing the unresolved expression should be displayed instead
2984 snprintf(watchmsg, sizeof(watchmsg), $"Accessing member \"%s\" from unresolved expression", memberID ? memberID.string : "");
2987 case memberPropertyErrorExp:
2989 Expression memberExp = exp.member.exp;
2990 Identifier memberID = exp.member.member;
2991 Type type = memberExp.expType;
2992 Class _class = (type && memberID) ? (memberID && memberID.classSym) ? memberID.classSym.registered : ((type.kind == classType && type._class) ? type._class.registered : null) : null;
2993 if(_class && memberID && memberID.string)
2994 snprintf(watchmsg, sizeof(watchmsg), $"Missing property evaluation for \"%s\" in class \"%s\"", memberID.string, _class.name);
2996 snprintf(watchmsg, sizeof(watchmsg), $"Missing property evaluation for \"%s\"", wh.expression);
2999 case functionCallErrorExp:
3000 if(exp.call.exp && exp.call.exp.type == identifierExp && exp.call.exp.identifier.string)
3001 snprintf(watchmsg, sizeof(watchmsg), $"Missing function evaluation for call to \"%s\"", exp.call.exp.identifier.string);
3003 snprintf(watchmsg, sizeof(watchmsg), $"Missing function evaluation for \"%s\"", wh.expression);
3005 case memoryErrorExp:
3006 // Need to ensure when set to memoryErrorExp, constant is set
3007 snprintf(watchmsg, sizeof(watchmsg), $"Memory can't be read at %s", /*(exp.type == constantExp) ? */exp.constant /*: null*/);
3009 case dereferenceErrorExp:
3010 snprintf(watchmsg, sizeof(watchmsg), $"Dereferencing error evaluating \"%s\"", wh.expression);
3012 case divideBy0ErrorExp:
3013 snprintf(watchmsg, sizeof(watchmsg), "%s", $"Integer division by 0");
3015 case noDebuggerErrorExp:
3016 snprintf(watchmsg, sizeof(watchmsg), $"Debugger required for symbol evaluation in \"%s\"", wh.expression);
3018 case unknownErrorExp:
3019 // NOTE: This should never happen
3020 snprintf(watchmsg, sizeof(watchmsg), $"Error evaluating \"%s\"", wh.expression);
3023 // NOTE: This should never happen
3024 snprintf(watchmsg, sizeof(watchmsg), $"Null type for \"%s\"", wh.expression);
3027 wh.value = CopyString(exp.string);
3030 // Temporary Code for displaying Strings
3031 if((exp.expType && ((exp.expType.kind == pointerType ||
3032 exp.expType.kind == arrayType) && exp.expType.type.kind == charType)) ||
3033 (wh.type && wh.type.kind == classType && wh.type._class &&
3034 wh.type._class.registered && wh.type._class.registered.type == normalClass &&
3035 !strcmp(wh.type._class.registered.name, "String")))
3038 if(exp.expType.kind != arrayType || exp.hasAddress)
3042 //char temp[MAX_F_STRING * 32];
3044 //ExpressionType evalError = dummyExp;
3045 /*if(exp.expType.kind == arrayType)
3046 sprintf(temp, "(char*)0x%x", exp.address);
3048 sprintf(temp, "(char*)%s", exp.constant);*/
3050 //evaluation = Debugger::EvaluateExpression(temp, &evalError);
3051 // address = strtoul(exp.constant, null, 0);
3052 address = _strtoui64(exp.constant, null, 0);
3053 //_dpl(0, "0x", address);
3054 // snprintf(value, sizeof(value), "0x%08x ", address);
3056 if(address > 0xFFFFFFFFLL)
3057 snprintf(value, sizeof(value), (__runtimePlatform == win32) ? "0x%016I64x " : "0x%016llx ", address);
3059 snprintf(value, sizeof(value), (__runtimePlatform == win32) ? "0x%08I64x " : "0x%08llx ", address);
3060 value[sizeof(value)-1] = 0;
3063 strcat(value, $"Null string");
3066 String string = new char[4097];
3068 bool success = false;
3072 for(start = 0; !done && start + size <= 4096; start += size)
3077 // Try to read 256 bytes at a time, then half if that fails
3078 s = GdbReadMemory(address + start, size);
3082 memcpy(string + start, s, size);
3083 string[start + size] = 0;
3084 if(size == 1 || memchr(s, 0, size))
3098 int len = strlen(value);
3100 if(UTF8Validate(string))
3105 for(c = 0; (ch = string[c]); c++)
3108 value[len++] = '\0';
3113 ISO8859_1toUTF8(string, value + len, strlen(value) - len - 30);
3114 strcat(value, ") (ISO8859-1)");
3118 strcat(value, $"Empty string");
3121 strcat(value, $"Couldn't read memory");
3124 wh.value = CopyString(value);
3127 else if(wh.type && wh.type.kind == classType && wh.type._class &&
3128 wh.type._class.registered && wh.type._class.registered.type == enumClass)
3130 Class enumClass = eSystem_FindClass(GetPrivateModule(), wh.type._class.registered.name);
3131 EnumClassData enumeration = (EnumClassData)enumClass.data;
3135 if(!strcmp(enumClass.dataTypeString, "uint64"))
3137 uint64 v = strtoull(exp.constant, null, 0);
3138 value = *(int64*)&v;
3141 value = strtoll(exp.constant, null, 0);
3143 for(item = enumeration.values.first; item; item = item.next)
3144 if(item.data == value)
3147 wh.value = CopyString(item.name);
3149 wh.value = PrintString($"Invalid Enum Value (", value, ")");
3152 else if(wh.type && (wh.type.kind == charType || (wh.type.kind == classType && wh.type._class &&
3153 wh.type._class.registered && !strcmp(wh.type._class.registered.fullName, "ecere::com::unichar"))) )
3160 if(exp.constant[0] == '\'')
3162 if((int)((byte *)exp.constant)[1] > 127)
3165 value = UTF8GetChar(exp.constant + 1, &nb);
3166 if(nb < 2) value = exp.constant[1];
3167 signedValue = value;
3171 signedValue = exp.constant[1];
3173 // Precomp Syntax error with boot strap here:
3174 byte b = (byte)(char)signedValue;
3175 value = (unichar) b;
3181 if(wh.type.kind == charType && wh.type.isSigned)
3183 signedValue = (int)(char)strtol(exp.constant, null, 0);
3185 // Precomp Syntax error with boot strap here:
3186 byte b = (byte)(char)signedValue;
3187 value = (unichar) b;
3192 value = (uint)strtoul(exp.constant, null, 0);
3193 signedValue = (int)value;
3197 UTF32toUTF8Len(&value, 1, charString, 5);
3199 snprintf(string, sizeof(string), "\'\\0' (0)");
3200 else if(value == '\t')
3201 snprintf(string, sizeof(string), "\'\\t' (%d)", value);
3202 else if(value == '\n')
3203 snprintf(string, sizeof(string), "\'\\n' (%d)", value);
3204 else if(value == '\r')
3205 snprintf(string, sizeof(string), "\'\\r' (%d)", value);
3206 else if(wh.type.kind == charType && wh.type.isSigned)
3207 snprintf(string, sizeof(string), "\'%s\' (%d)", charString, signedValue);
3208 else if(value > 256 || wh.type.kind != charType)
3210 if(value > 0x10FFFF || !GetCharCategory(value))
3211 snprintf(string, sizeof(string), $"Invalid Unicode Keypoint (0x%08X)", value);
3213 snprintf(string, sizeof(string), "\'%s\' (U+%04X)", charString, value);
3216 snprintf(string, sizeof(string), "\'%s\' (%d)", charString, value);
3217 string[sizeof(string)-1] = 0;
3219 wh.value = CopyString(string);
3224 wh.value = CopyString(exp.constant);
3230 bool genericError = true;
3231 if(exp.expType && exp.hasAddress)
3233 bool showAddress = false;
3234 switch(exp.expType.kind)
3246 Symbol s = exp.expType._class;
3249 Class c = s.registered;
3250 if(c.type == noHeadClass || c.type == normalClass)
3258 wh.value = PrintHexUInt64(exp.address);
3260 genericError = false;
3264 // NOTE: This should ideally be handled with a specific error message
3265 snprintf(watchmsg, sizeof(watchmsg), $"Error evaluating \"%s\"", wh.expression);
3271 snprintf(watchmsg, sizeof(watchmsg), $"Invalid expression: \"%s\"", wh.expression);
3272 if(exp) FreeExpression(exp);
3275 SetPrivateModule(backupPrivateModule);
3276 SetCurrentContext(backupContext);
3277 SetTopContext(backupContext);
3278 SetGlobalContext(backupContext);
3279 SetThisClass(backupThisClass);
3282 // wh.value = CopyString("No source file found for selected frame");
3284 watchmsg[sizeof(watchmsg)-1] = 0;
3286 wh.value = CopyString(watchmsg);
3288 ide.watchesView.UpdateWatch(wh);
3292 void EvaluateWatches()
3294 _dpl2(_dpct, dplchan::debuggerWatches, 0, "Debugger::EvaluateWatches()");
3295 WatchesLinkCodeEditor();
3296 if(state == stopped)
3298 for(wh : ide.workspace.watches)
3303 char * ::GdbEvaluateExpression(char * expression)
3305 _dpl2(_dpct, dplchan::debuggerWatches, 0, "Debugger::GdbEvaluateExpression(", expression, ")");
3308 GdbCommand(0, false, "-data-evaluate-expression \"%s\"", expression);
3310 ide.outputView.debugBox.Logf("Debugger Error: GdbEvaluateExpression\n");
3314 // to be removed... use GdbReadMemory that returns a byte array instead
3315 char * ::GdbReadMemoryString(uint64 address, int size, char format, int rows, int cols)
3317 _dpl2(_dpct, dplchan::debuggerCall, 0, "Debugger::GdbReadMemoryString(", address, ")");
3322 _dpl(0, "GdbReadMemoryString called with size = 0!");
3324 GdbCommand(0, false,
3325 (__runtimePlatform == win32) ? "-data-read-memory 0x%016I64x %c, %d, %d, %d" : "-data-read-memory 0x%016llx %c, %d, %d, %d", address, format, size, rows, cols);
3327 ide.outputView.debugBox.Logf("Debugger Error: GdbReadMemoryString\n");
3331 byte * ::GdbReadMemory(uint64 address, int bytes)
3333 _dpl2(_dpct, dplchan::debuggerCall, 0, "Debugger::GdbReadMemory(", address, ")");
3336 GdbCommand(0, false,
3337 (__runtimePlatform == win32) ? "-data-read-memory 0x%016I64x %c, 1, 1, %d" : "-data-read-memory 0x%016llx %c, 1, 1, %d",
3338 address, 'u', bytes);
3341 _dpl(0, "GdbReadMemory called with bytes = 0!");
3344 ide.outputView.debugBox.Logf("Debugger Error: GdbReadMemory\n");
3345 else if(eval.result && strcmp(eval.result, "N/A"))
3347 byte * result = new byte[bytes];
3348 char * string = eval.result;
3352 result[c++] = (byte)strtol(string, &string, 10);
3369 bool BreakpointHit(GdbDataStop stopItem, Breakpoint bpInternal, Breakpoint bpUser)
3372 char * s1 = null; char * s2 = null;
3373 _dpl2(_dpct, dplchan::debuggerCall, 0, "Debugger::BreakpointHit(",
3374 "bpInternal(", bpInternal ? s1=bpInternal.CopyLocationString(false) : null, "), ",
3375 "bpUser(", bpUser ? s2=bpUser.CopyLocationString(false) : null, ")) -- ",
3376 "ignoreBreakpoints(", ignoreBreakpoints, "), ",
3377 "hitCursorBreakpoint(", bpUser && bpUser.type == runToCursor, ")");
3378 delete s1; delete s2;
3382 bool conditionMet = true;
3383 if(bpUser.condition)
3385 if(WatchesLinkCodeEditor())
3386 conditionMet = ResolveWatch(bpUser.condition);
3388 conditionMet = false;
3403 if(stopItem.frame.line && bpUser.line != stopItem.frame.line)
3405 // updating user breakpoint on hit location difference
3406 // todo, print something?
3407 bpUser.line = stopItem.frame.line;
3408 ide.breakpointsView.UpdateBreakpoint(bpUser.row);
3409 ide.workspace.Save();
3412 ide.breakpointsView.UpdateBreakpoint(bpUser.row);
3417 if(bpInternal.type == internalModulesLoaded)
3419 if(userAction == stepOver)
3421 if((bpInternal.type == internalEntry && ((intBpMain && intBpMain.inserted) || (intBpWinMain && intBpWinMain.inserted))) ||
3422 (bpInternal.type == internalMain && intBpWinMain && intBpWinMain.inserted))
3425 if(!bpUser && !userAction.breaksOnInternalBreakpoint)
3427 if(userAction == stepOut)
3428 StepOut(ignoreBreakpoints);
3434 if(!bpUser && !bpInternal)
3440 void ValgrindTargetThreadExit()
3442 _dpl2(_dpct, dplchan::debuggerCall, 0, "Debugger::ValgrindTargetThreadExit()");
3445 vgTargetHandle.Wait();
3446 delete vgTargetHandle;
3448 HandleExit(null, null);
3451 void GdbThreadExit()
3453 _dpl2(_dpct, dplchan::debuggerCall, 0, "Debugger::GdbThreadExit()");
3454 if(state != terminated)
3456 _ChangeState(terminated);
3457 targetProcessId = 0;
3458 ClearBreakDisplay();
3463 serialSemaphore.Release();
3468 ide.outputView.debugBox.Logf($"Debugger Fatal Error: GDB lost\n");
3469 ide.outputView.debugBox.Logf($"Debugging stopped\n");
3471 HideDebuggerViews();
3473 //_ChangeState(terminated);
3477 void GdbThreadMain(char * output)
3481 Array<char *> outTokens { minAllocSize = 50 };
3482 Array<char *> subTokens { minAllocSize = 50 };
3483 DebugListItem item { };
3484 DebugListItem item2 { };
3485 bool setWaitingForPID = false;
3487 #if defined(GDB_DEBUG_CONSOLE) || defined(GDB_DEBUG_GUI)
3488 #ifdef GDB_DEBUG_CONSOLE
3489 // _dpl2(_dpct, dplchan::gdbOutput, 0, output);
3492 #ifdef GDB_DEBUG_OUTPUT
3494 int len = strlen(output);
3502 for(c = 0; c < len / 1024; c++)
3504 strncpy(tmp, start, 1024);
3505 ide.outputView.gdbBox.Logf("out: %s\n", tmp);
3508 ide.outputView.gdbBox.Logf("out: %s\n", start);
3512 ide.outputView.gdbBox.Logf("out: %s\n", output);
3516 #ifdef GDB_DEBUG_CONSOLE
3517 strcpy(lastGdbOutput, output);
3519 #ifdef GDB_DEBUG_GUI
3520 if(ide.gdbDialog) ide.gdbDialog.AddOutput(output);
3527 if(strstr(output, "No debugging symbols found") || strstr(output, "(no debugging symbols found)"))
3530 ide.outputView.debugBox.Logf($"Target doesn't contain debug information!\n");
3533 if(!entryPoint && (t = strstr(output, "Entry point:")))
3535 char * addr = t + strlen("Entry point:");
3537 if(*t++ == ' ' && *t++ == '0' && *t == 'x')
3540 while(isxdigit(*++t));
3542 for(bp : sysBPs; bp.type == internalEntry)
3545 bp.enabled = entryPoint = true;
3553 if(TokenizeList(output, ',', outTokens) && !strcmp(outTokens[0], "^done"))
3555 //if(outTokens.count == 1)
3560 _ChangeState(loaded);
3561 targetProcessId = 0;
3562 if(outTokens.count > 1 && TokenizeListItem(outTokens[1], item))
3564 if(!strcmp(item.name, "reason"))
3566 char * reason = item.value;
3567 StripQuotes(reason, reason);
3568 if(!strcmp(reason, "exited-normally") || !strcmp(reason, "exited") || !strcmp(reason, "exited-signalled"))
3571 if(outTokens.count > 2 && TokenizeListItem(outTokens[2], item2))
3573 StripQuotes(item2.value, item2.value);
3574 if(!strcmp(item2.name, "exit-code"))
3575 exitCode = item2.value;
3581 HandleExit(reason, exitCode);
3585 _dpl2(_dpct, dplchan::gdbProtoUnknown, 0, "kill reply (", item.name, "=", item.value, ") is unheard of");
3588 HandleExit(null, null);
3591 if(outTokens.count > 1 && TokenizeListItem(outTokens[1], item))
3593 if(!strcmp(item.name, "bkpt"))
3595 sentBreakInsert = false;
3601 bpItem = ParseBreakpoint(item.value, outTokens);
3602 //breakType = bpValidation;
3604 else if(!strcmp(item.name, "depth"))
3606 StripQuotes(item.value, item.value);
3607 frameCount = atoi(item.value);
3609 stackFrames.Free(Frame::Free);
3611 else if(!strcmp(item.name, "stack"))
3614 if(stackFrames.count)
3615 ide.callStackView.Logf("...\n");
3618 item.value = StripBrackets(item.value);
3619 TokenizeList(item.value, ',', subTokens);
3620 for(i = 0; i < subTokens.count; i++)
3622 if(TokenizeListItem(subTokens[i], item))
3624 if(!strcmp(item.name, "frame"))
3627 stackFrames.Add(frame);
3628 item.value = StripCurlies(item.value);
3629 ParseFrame(frame, item.value);
3630 if(frame.file && frame.from)
3631 _dpl2(_dpct, dplchan::gdbProtoUnknown, 0, "unexpected frame file and from members present");
3635 if(activeFrameLevel == -1)
3637 if(ide.projectView.IsModuleInProject(frame.file));
3639 if(frame.level != 0)
3641 //stopItem.frame = frame;
3642 breakType = selectFrame;
3645 activeFrame = frame;
3646 activeFrameLevel = frame.level;
3649 ide.callStackView.Logf("%3d ", frame.level);
3650 if(!strncmp(frame.func, "__ecereMethod_", strlen("__ecereMethod_")))
3651 ide.callStackView.Logf($"%s Method, %s:%d\n", &frame.func[strlen("__ecereMethod_")], (s = CopySystemPath(frame.file)), frame.line);
3652 else if(!strncmp(frame.func, "__ecereProp_", strlen("__ecereProp_")))
3653 ide.callStackView.Logf($"%s Property, %s:%d\n", &frame.func[strlen("__ecereProp_")], (s = CopySystemPath(frame.file)), frame.line);
3654 else if(!strncmp(frame.func, "__ecereConstructor_", strlen("__ecereConstructor_")))
3655 ide.callStackView.Logf($"%s Constructor, %s:%d\n", &frame.func[strlen("__ecereConstructor_")], (s = CopySystemPath(frame.file)), frame.line);
3656 else if(!strncmp(frame.func, "__ecereDestructor_", strlen("__ecereDestructor_")))
3657 ide.callStackView.Logf($"%s Destructor, %s:%d\n", &frame.func[strlen("__ecereDestructor_")], (s = CopySystemPath(frame.file)), frame.line);
3659 ide.callStackView.Logf($"%s Function, %s:%d\n", frame.func, (s = CopySystemPath(frame.file)), frame.line);
3664 ide.callStackView.Logf("%3d ", frame.level);
3669 ide.callStackView.Logf($"inside %s, %s\n", frame.func, (s = CopySystemPath(frame.from)));
3673 ide.callStackView.Logf("%s\n", frame.func);
3675 ide.callStackView.Logf($"unknown source\n");
3679 _dpl2(_dpct, dplchan::gdbProtoUnknown, 0, "stack content (", item.name, "=", item.value, ") is unheard of");
3682 if(activeFrameLevel == -1)
3684 activeFrameLevel = 0;
3685 activeFrame = stackFrames.first;
3687 ide.callStackView.Home();
3689 subTokens.RemoveAll();
3691 /*else if(!strcmp(item.name, "frame"))
3694 item.value = StripCurlies(item.value);
3695 ParseFrame(&frame, item.value);
3697 else if(!strcmp(item.name, "thread-ids"))
3699 ide.threadsView.Clear();
3700 item.value = StripCurlies(item.value);
3701 TokenizeList(item.value, ',', subTokens);
3702 for(i = subTokens.count - 1; ; i--)
3704 if(TokenizeListItem(subTokens[i], item))
3706 if(!strcmp(item.name, "thread-id"))
3709 StripQuotes(item.value, item.value);
3710 value = atoi(item.value);
3711 ide.threadsView.Logf("%3d \n", value);
3714 _dpl2(_dpct, dplchan::gdbProtoUnknown, 0, "threads content (", item.name, "=", item.value, ") is unheard of");
3719 ide.threadsView.Home();
3721 subTokens.RemoveAll();
3722 //if(!strcmp(outTokens[2], "number-of-threads"))
3724 else if(!strcmp(item.name, "new-thread-id"))
3726 StripQuotes(item.value, item.value);
3727 activeThread = atoi(item.value);
3729 else if(!strcmp(item.name, "value"))
3731 StripQuotes(item.value, item.value);
3732 eval.result = CopyString(item.value);
3733 eval.active = false;
3735 else if(!strcmp(item.name, "addr"))
3737 for(i = 2; i < outTokens.count; i++)
3739 if(TokenizeListItem(outTokens[i], item))
3741 if(!strcmp(item.name, "total-bytes"))
3743 StripQuotes(item.value, item.value);
3744 eval.bytes = atoi(item.value);
3746 else if(!strcmp(item.name, "next-row"))
3748 StripQuotes(item.value, item.value);
3749 eval.nextBlockAddress = _strtoui64(item.value, null, 0);
3751 else if(!strcmp(item.name, "memory"))
3755 //StripQuotes(item.value, item.value);
3756 item.value = StripBrackets(item.value);
3757 // this should be treated as a list...
3758 item.value = StripCurlies(item.value);
3759 TokenizeList(item.value, ',', subTokens);
3760 for(j = 0; j < subTokens.count; j++)
3762 if(TokenizeListItem(subTokens[j], item))
3764 if(!strcmp(item.name, "data"))
3766 item.value = StripBrackets(item.value);
3767 StripQuotes2(item.value, item.value);
3768 eval.result = CopyString(item.value);
3769 eval.active = false;
3773 subTokens.RemoveAll();
3778 else if(!strcmp(item.name, "source-path") || !strcmp(item.name, "BreakpointTable"))
3779 _dpl2(_dpct, dplchan::gdbProtoIgnored, 0, "command reply (", item.name, "=", item.value, ") is ignored");
3781 _dpl2(_dpct, dplchan::gdbProtoUnknown, 0, "command reply (", item.name, "=", item.value, ") is unheard of");
3784 else if(!strcmp(outTokens[0], "^running"))
3786 waitingForPID = true;
3787 setWaitingForPID = true;
3788 ClearBreakDisplay();
3790 else if(!strcmp(outTokens[0], "^exit"))
3792 _ChangeState(terminated);
3793 // ide.outputView.debugBox.Logf("Exit\n");
3794 // ide.Update(null);
3796 serialSemaphore.Release();
3798 else if(!strcmp(outTokens[0], "^error"))
3802 sentBreakInsert = false;
3803 breakpointError = true;
3806 if(outTokens.count > 1 && TokenizeListItem(outTokens[1], item))
3808 if(!strcmp(item.name, "msg"))
3810 StripQuotes(item.value, item.value);
3813 eval.active = false;
3815 if(strstr(item.value, "No symbol") && strstr(item.value, "in current context"))
3816 eval.error = symbolNotFound;
3817 else if(strstr(item.value, "Cannot access memory at address"))
3818 eval.error = memoryCantBeRead;
3820 eval.error = unknown;
3822 else if(!strcmp(item.value, "Previous frame inner to this frame (corrupt stack?)"))
3825 else if(!strncmp(item.value, "Cannot access memory at address", 31))
3828 else if(!strcmp(item.value, "Cannot find bounds of current function"))
3830 _ChangeState(stopped);
3831 gdbHandle.Printf("-exec-continue\n");
3833 else if(!strcmp(item.value, "ptrace: No such process."))
3835 _ChangeState(loaded);
3836 targetProcessId = 0;
3838 else if(!strcmp(item.value, "Function \\\"WinMain\\\" not defined."))
3841 else if(!strcmp(item.value, "You can't do that without a process to debug."))
3843 _ChangeState(loaded);
3844 targetProcessId = 0;
3846 else if(strstr(item.value, "No such file or directory."))
3848 _ChangeState(loaded);
3849 targetProcessId = 0;
3851 else if(strstr(item.value, "During startup program exited with code "))
3853 _ChangeState(loaded);
3854 targetProcessId = 0;
3859 if(strlen(item.value) < MAX_F_STRING)
3862 ide.outputView.debugBox.Logf("GDB: %s\n", (s = CopyUnescapedString(item.value)));
3866 ide.outputView.debugBox.Logf("GDB: %s\n", item.value);
3872 _dpl2(_dpct, dplchan::gdbProtoUnknown, 0, "error content (", item.name, "=", item.value, ") is unheard of");
3875 _dpl2(_dpct, dplchan::gdbProtoUnknown, 0, "result-record: ", outTokens[0]);
3876 outTokens.RemoveAll();
3879 _dpl2(_dpct, dplchan::gdbProtoUnknown, 0, "status-async-output: ", outTokens[0]);
3882 if(TokenizeList(output, ',', outTokens))
3884 if(!strcmp(outTokens[0], "=library-loaded"))
3885 FGODetectLoadedLibraryForAddedProjectIssues(outTokens, false);
3886 else if(!strcmp(outTokens[0], "=shlibs-added"))
3887 FGODetectLoadedLibraryForAddedProjectIssues(outTokens, true);
3888 else if(!strcmp(outTokens[0], "=thread-group-created") || !strcmp(outTokens[0], "=thread-group-added") ||
3889 !strcmp(outTokens[0], "=thread-group-started") || !strcmp(outTokens[0], "=thread-group-exited") ||
3890 !strcmp(outTokens[0], "=thread-created") || !strcmp(outTokens[0], "=thread-exited") ||
3891 !strcmp(outTokens[0], "=cmd-param-changed") || !strcmp(outTokens[0], "=library-unloaded") ||
3892 !strcmp(outTokens[0], "=breakpoint-modified"))
3893 _dpl2(_dpct, dplchan::gdbProtoIgnored, 0, outTokens[0], outTokens.count>1 ? outTokens[1] : "",
3894 outTokens.count>2 ? outTokens[2] : "", outTokens.count>3 ? outTokens[3] : "",
3895 outTokens.count>4 ? outTokens[4] : "", outTokens.count>5 ? outTokens[5] : "",
3896 outTokens.count>6 ? outTokens[6] : "", outTokens.count>7 ? outTokens[7] : "",
3897 outTokens.count>8 ? outTokens[8] : "", outTokens.count>9 ? outTokens[9] : "");
3899 _dpl2(_dpct, dplchan::gdbProtoUnknown, 0, "notify-async-output: ", outTokens[0]);
3901 outTokens.RemoveAll();
3905 if(TokenizeList(output, ',', outTokens))
3907 if(!strcmp(outTokens[0],"*running"))
3909 waitingForPID = true;
3910 setWaitingForPID = true;
3912 else if(!strcmp(outTokens[0], "*stopped"))
3915 _ChangeState(stopped);
3917 for(tk = 1; tk < outTokens.count; tk++)
3919 if(TokenizeListItem(outTokens[tk], item))
3921 if(!strcmp(item.name, "reason"))
3923 char * reason = item.value;
3924 StripQuotes(reason, reason);
3925 if(!strcmp(reason, "exited-normally") || !strcmp(reason, "exited") || !strcmp(reason, "exited-signalled"))
3928 if(outTokens.count > tk+1 && TokenizeListItem(outTokens[tk+1], item2))
3931 StripQuotes(item2.value, item2.value);
3932 if(!strcmp(item2.name, "exit-code"))
3933 exitCode = item2.value;
3939 HandleExit(reason, exitCode);
3942 else if(!strcmp(reason, "breakpoint-hit") ||
3943 !strcmp(reason, "function-finished") ||
3944 !strcmp(reason, "end-stepping-range") ||
3945 !strcmp(reason, "location-reached") ||
3946 !strcmp(reason, "signal-received"))
3950 if(stopItem) _dpl(0, "problem");
3952 stopItem = GdbDataStop { };
3953 stopItem.reason = r == 'b' ? breakpointHit : r == 'f' ? functionFinished : r == 'e' ? endSteppingRange : r == 'l' ? locationReached : signalReceived;
3955 for(i = tk+1; i < outTokens.count; i++)
3957 TokenizeListItem(outTokens[i], item);
3958 StripQuotes(item.value, item.value);
3959 if(!strcmp(item.name, "thread-id"))
3960 stopItem.threadid = atoi(item.value);
3961 else if(!strcmp(item.name, "frame"))
3963 item.value = StripCurlies(item.value);
3964 ParseFrame(stopItem.frame, item.value);
3966 else if(stopItem.reason == breakpointHit && !strcmp(item.name, "bkptno"))
3967 stopItem.bkptno = atoi(item.value);
3968 else if(stopItem.reason == functionFinished && !strcmp(item.name, "gdb-result-var"))
3969 stopItem.gdbResultVar = CopyString(item.value);
3970 else if(stopItem.reason == functionFinished && !strcmp(item.name, "return-value"))
3971 stopItem.returnValue = CopyString(item.value);
3972 else if(stopItem.reason == signalReceived && !strcmp(item.name, "signal-name"))
3973 stopItem.name = CopyString(item.value);
3974 else if(stopItem.reason == signalReceived && !strcmp(item.name, "signal-meaning"))
3975 stopItem.meaning = CopyString(item.value);
3976 else if(!strcmp(item.name, "stopped-threads"))
3977 _dpl2(_dpct, dplchan::gdbProtoIgnored, 0, reason, ": Advanced thread debugging not handled");
3978 else if(!strcmp(item.name, "core"))
3979 _dpl2(_dpct, dplchan::gdbProtoIgnored, 0, reason, ": Information (core) not used");
3980 else if(!strcmp(item.name, "disp"))
3981 _dpl2(_dpct, dplchan::gdbProtoIgnored, 0, reason, ": (", item.name, "=", item.value, ")");
3983 _dpl2(_dpct, dplchan::gdbProtoUnknown, 0, "Unknown ", reason, " item name (", item.name, "=", item.value, ")");
3986 if(stopItem.reason == signalReceived && !strcmp(stopItem.name, "SIGTRAP"))
4002 event = r == 'b' ? hit : r == 'f' ? functionEnd : r == 'e' ? stepEnd : r == 'l' ? locationReached : signal;
4006 else if(!strcmp(reason, "watchpoint-trigger"))
4007 _dpl2(_dpct, dplchan::gdbProtoIgnored, 0, "Reason watchpoint trigger not handled");
4008 else if(!strcmp(reason, "read-watchpoint-trigger"))
4009 _dpl2(_dpct, dplchan::gdbProtoIgnored, 0, "Reason read watchpoint trigger not handled");
4010 else if(!strcmp(reason, "access-watchpoint-trigger"))
4011 _dpl2(_dpct, dplchan::gdbProtoIgnored, 0, "Reason access watchpoint trigger not handled");
4012 else if(!strcmp(reason, "watchpoint-scope"))
4013 _dpl2(_dpct, dplchan::gdbProtoIgnored, 0, "Reason watchpoint scope not handled");
4015 _dpl2(_dpct, dplchan::gdbProtoUnknown, 0, "Unknown reason: ", reason);
4023 if(usingValgrind && event == none && !stopItem)
4024 event = valgrindStartPause;
4029 _dpl2(_dpct, dplchan::gdbProtoUnknown, 0, "Unknown exec-async-output: ", outTokens[0]);
4030 outTokens.RemoveAll();
4033 if(!strcmpi(output, "(gdb) "))
4037 Time startTime = GetTime();
4038 char exeFile[MAX_LOCATION];
4039 int oldProcessID = targetProcessId;
4040 GetLastDirectory(targetFile, exeFile);
4042 while(!targetProcessId/*true*/)
4044 targetProcessId = Process_GetChildExeProcessId(gdbProcessId, exeFile);
4045 if(targetProcessId) break;
4046 // Can't break on Peek(), GDB is giving us =library and other info before the process is listed in /proc
4047 // if(gdbHandle.Peek()) break;
4049 if(gdbHandle.Peek() && GetTime() - startTime > 2.5) // Give the process 2.5 seconds to show up in /proc
4054 _ChangeState(running);
4055 else if(!oldProcessID)
4057 ide.outputView.debugBox.Logf($"Debugger Error: No target process ID\n");
4058 // TO VERIFY: The rest of this block has not been thoroughly tested in this particular location
4059 gdbHandle.Printf("-gdb-exit\n");
4061 _ChangeState(terminated); //loaded;
4066 for(bp : ide.workspace.breakpoints)
4067 bp.inserted = false;
4070 bp.inserted = false;
4072 bpRunToCursor.inserted = false;
4074 ide.outputView.debugBox.Logf($"Debugging stopped\n");
4075 ClearBreakDisplay();
4077 #if defined(__unix__)
4078 if(!usingValgrind && FileExists(progFifoPath)) //fileCreated)
4080 progThread.terminate = true;
4083 fifoFile.CloseInput();
4090 DeleteFile(progFifoPath);
4091 progFifoPath[0] = '\0';
4098 serialSemaphore.Release();
4101 _dpl2(_dpct, dplchan::gdbProtoUnknown, 0, $"Unknown prompt", output);
4105 if(!strncmp(output, "&\"warning:", 10))
4108 content = strstr(output, "\"");
4109 StripQuotes(content, content);
4110 content = strstr(content, ":");
4116 ide.outputView.debugBox.LogRaw((s = CopyUnescapedString(content)));
4123 _dpl2(_dpct, dplchan::gdbProtoUnknown, 0, $"Unknown output: ", output);
4125 if(!setWaitingForPID)
4126 waitingForPID = false;
4127 setWaitingForPID = false;
4135 // From GDB Output functions
4136 void FGODetectLoadedLibraryForAddedProjectIssues(Array<char *> outTokens, bool shlibs)
4138 char path[MAX_LOCATION] = "";
4139 char file[MAX_FILENAME] = "";
4140 //bool symbolsLoaded = false;
4141 DebugListItem item { };
4142 //_dpl2(_dpct, dplchan::debuggerCall, 0, "Debugger::FGODetectLoadedLibraryForAddedProjectIssues()");
4143 for(token : outTokens)
4145 if(TokenizeListItem(token, item))
4147 if(!strcmp(item.name, "target-name"))
4149 StripQuotes(item.value, path);
4150 MakeSystemPath(path);
4151 GetLastDirectory(path, file);
4153 else if(!strcmp(item.name, "symbols-loaded"))
4155 //symbolsLoaded = (atoi(item.value) == 1);
4157 else if(!strcmp(item.name, "shlib-info"))
4159 DebugListItem subItem { };
4160 Array<char *> tokens { minAllocSize = 50 };
4161 item.value = StripBrackets(item.value);
4162 TokenizeList(item.value, ',', tokens);
4165 if(TokenizeListItem(t, subItem))
4167 if(!strcmp(subItem.name, "path"))
4169 StripQuotes(subItem.value, path);
4170 MakeSystemPath(path);
4171 GetLastDirectory(path, file);
4172 //symbolsLoaded = true;
4183 if(path[0] && file[0])
4185 for(prj : ide.workspace.projects; prj != ide.workspace.projects.firstIterator.data)
4189 char prjTargetPath[MAX_LOCATION];
4190 char prjTargetFile[MAX_FILENAME];
4191 DirExpression targetDirExp = prj.GetTargetDir(currentCompiler, prj.config, bitDepth);
4192 strcpy(prjTargetPath, prj.topNode.path);
4193 PathCat(prjTargetPath, targetDirExp.dir);
4194 delete targetDirExp;
4195 prjTargetFile[0] = '\0';
4196 prj.CatTargetFileName(prjTargetFile, currentCompiler, prj.config);
4197 PathCat(prjTargetPath, prjTargetFile);
4198 MakeSystemPath(prjTargetPath);
4200 match = !fstrcmp(prjTargetFile, file);
4201 if(!match && (dot = strstr(prjTargetFile, ".so.")))
4203 char * dot3 = strstr(dot+4, ".");
4207 match = !fstrcmp(prjTargetFile, file);
4212 match = !fstrcmp(prjTargetFile, file);
4217 // TODO: nice visual feedback to better warn user. use some ide notification system or other means.
4218 /* -- 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)
4220 ide.outputView.debugBox.Logf($"Attention! No symbols for loaded library %s matched to the %s added project.\n", path, prj.topNode.name);
4222 match = !fstrcmp(prjTargetPath, path);
4223 if(!match && (dot = strstr(prjTargetPath, ".so.")))
4225 char * dot3 = strstr(dot+4, ".");
4229 match = !fstrcmp(prjTargetPath, path);
4234 match = !fstrcmp(prjTargetPath, path);
4238 projectsLibraryLoaded[prj.name] = true;
4240 ide.outputView.debugBox.Logf($"Loaded library %s doesn't match the %s target of the %s added project.\n", path, prjTargetPath, prj.topNode.name);
4247 void FGOBreakpointModified(Array<char *> outTokens)
4249 _dpl2(_dpct, dplchan::debuggerCall, 0, "Debugger::FGOBreakpointModified() -- TODO only if needed: support breakpoint modified");
4251 DebugListItem item { };
4252 if(outTokens.count > 1 && TokenizeListItem(outTokens[1], item))
4254 if(!strcmp(item.name, "bkpt"))
4256 GdbDataBreakpoint modBp = ParseBreakpoint(item.value, outTokens);
4264 ExpressionType ::DebugEvalExpTypeError(char * result)
4266 _dpl2(_dpct, dplchan::debuggerWatches, 0, "Debugger::DebugEvalExpTypeError()");
4271 case symbolNotFound:
4272 return symbolErrorExp;
4273 case memoryCantBeRead:
4274 return memoryErrorExp;
4276 return unknownErrorExp;
4279 char * ::EvaluateExpression(char * expression, ExpressionType * error)
4282 _dpl2(_dpct, dplchan::debuggerWatches, 0, "Debugger::EvaluateExpression(", expression, ")");
4283 if(ide.projectView && ide.debugger.state == stopped)
4285 result = GdbEvaluateExpression(expression);
4286 *error = DebugEvalExpTypeError(result);
4291 *error = noDebuggerErrorExp;
4296 char * ::ReadMemory(uint64 address, int size, char format, ExpressionType * error)
4299 char * result = GdbReadMemoryString(address, size, format, 1, 1);
4300 _dpl2(_dpct, dplchan::debuggerCall, 0, "Debugger::ReadMemory(", address, ")");
4301 if(!result || !strcmp(result, "N/A"))
4302 *error = memoryErrorExp;
4304 *error = DebugEvalExpTypeError(result);
4309 class ValgrindLogThread : Thread
4315 static char output[4096];
4316 bool lastLineEmpty = true;
4317 Array<char> dynamicBuffer { minAllocSize = 4096 };
4318 File oldValgrindHandle = vgLogFile;
4319 incref oldValgrindHandle;
4322 while(debugger.state != terminated && vgLogFile && vgLogFile.input)
4327 result = vgLogFile.Read(output, 1, sizeof(output));
4329 if(debugger.state == terminated || !vgLogFile) // || vgLogFile.Eof()
4336 for(c = 0; c<result; c++)
4338 if(output[c] == '\n')
4340 int pos = dynamicBuffer.size;
4341 dynamicBuffer.size += c - start;
4342 memcpy(&dynamicBuffer[pos], output + start, c - start);
4343 if(dynamicBuffer.count && dynamicBuffer[dynamicBuffer.count - 1] != '\r')
4344 dynamicBuffer.size++;
4345 dynamicBuffer[dynamicBuffer.count - 1] = '\0';
4347 // printf("%s\n", dynamicBuffer.array);
4349 if(strstr(&dynamicBuffer[0], "vgdb me ..."))
4350 debugger.serialSemaphore.Release();
4352 char * s = strstr(&dynamicBuffer[0], "==");
4354 s = strstr(s+2, "== ");
4358 if(s[0] == '\0' && !lastLineEmpty)
4361 lastLineEmpty = true;
4362 dynamicBuffer[0] = '\0';
4371 if(strstr(s, "vgdb me ..."))
4373 if(strstr(s, "(action on error) vgdb me ..."))
4374 ide.outputView.debugBox.Logf($"...breaked on Valgrind error (F5 to resume)\n");
4381 if(strstr(s, "TO DEBUG THIS PROCESS USING GDB: start GDB like this"))
4387 if(strstr(s, "and then give GDB the following command"))
4393 if(strstr(s, "/path/to/gdb") || strstr(s, "target remote | /usr/lib/valgrind/../../bin/vgdb --pid="))
4399 if(strstr(s, "--pid is optional if only one valgrind process is running"))
4405 if((s = strstr(s, "; rerun with -h for copyright info")))
4417 if(lastLineEmpty && t[0] != '\0')
4418 lastLineEmpty = false;
4421 ide.outputView.debugBox.Logf("%s\n", &dynamicBuffer[0]);
4423 dynamicBuffer.size = 0;
4429 int pos = dynamicBuffer.size;
4430 dynamicBuffer.size += c - start;
4431 memcpy(&dynamicBuffer[pos], output + start, c - start);
4434 else if(debugger.state == stopped)
4437 printf("Got end of file from GDB!\n");
4444 delete dynamicBuffer;
4445 _dpl2(_dpct, dplchan::debuggerCall, 0, "ValgrindLogThreadExit");
4446 //if(oldValgrindHandle == vgLogFile)
4447 debugger.GdbThreadExit/*ValgrindLogThreadExit*/();
4448 delete oldValgrindHandle;
4454 class ValgrindTargetThread : Thread
4460 static char output[4096];
4461 Array<char> dynamicBuffer { minAllocSize = 4096 };
4462 DualPipe oldValgrindHandle = vgTargetHandle;
4463 incref oldValgrindHandle;
4466 while(debugger.state != terminated && vgTargetHandle && !vgTargetHandle.Eof())
4470 result = vgTargetHandle.Read(output, 1, sizeof(output));
4472 if(debugger.state == terminated || !vgTargetHandle || vgTargetHandle.Eof())
4479 for(c = 0; c<result; c++)
4481 if(output[c] == '\n')
4483 int pos = dynamicBuffer.size;
4484 dynamicBuffer.size += c - start;
4485 memcpy(&dynamicBuffer[pos], output + start, c - start);
4486 if(dynamicBuffer.count && dynamicBuffer[dynamicBuffer.count - 1] != '\r')
4487 // COMMENTED OUT DUE TO ISSUE #135, FIXED
4488 //if(dynamicBuffer.array[dynamicBuffer.count - 1] != '\r')
4489 dynamicBuffer.size++;
4490 dynamicBuffer[dynamicBuffer.count - 1] = '\0';
4492 // printf("%s\n", dynamicBuffer.array);
4494 ide.outputView.debugBox.Logf("%s\n", &dynamicBuffer[0]);
4496 dynamicBuffer.size = 0;
4502 int pos = dynamicBuffer.size;
4503 dynamicBuffer.size += c - start;
4504 memcpy(&dynamicBuffer[pos], output + start, c - start);
4510 printf("Got end of file from GDB!\n");
4514 delete dynamicBuffer;
4515 //if(oldValgrindHandle == vgTargetHandle)
4516 debugger.ValgrindTargetThreadExit();
4517 delete oldValgrindHandle;
4523 class GdbThread : Thread
4529 static char output[4096];
4530 Array<char> dynamicBuffer { minAllocSize = 4096 };
4531 DualPipe oldGdbHandle = gdbHandle;
4532 incref oldGdbHandle;
4535 while(debugger.state != terminated && gdbHandle && !gdbHandle.Eof())
4539 result = gdbHandle.Read(output, 1, sizeof(output));
4541 if(debugger.state == terminated || !gdbHandle || gdbHandle.Eof())
4548 for(c = 0; c<result; c++)
4550 if(output[c] == '\n')
4552 int pos = dynamicBuffer.size;
4553 dynamicBuffer.size += c - start;
4554 memcpy(&dynamicBuffer[pos], output + start, c - start);
4555 if(dynamicBuffer.count && dynamicBuffer[dynamicBuffer.count - 1] != '\r')
4556 // COMMENTED OUT DUE TO ISSUE #135, FIXED
4557 //if(dynamicBuffer.array[dynamicBuffer.count - 1] != '\r')
4558 dynamicBuffer.size++;
4559 dynamicBuffer[dynamicBuffer.count - 1] = '\0';
4561 // _dpl(0, dynamicBuffer.array);
4563 debugger.GdbThreadMain(&dynamicBuffer[0]);
4564 dynamicBuffer.size = 0;
4570 int pos = dynamicBuffer.size;
4571 dynamicBuffer.size += c - start;
4572 memcpy(&dynamicBuffer[pos], output + start, c - start);
4578 _dpl(0, "Got end of file from GDB!");
4582 delete dynamicBuffer;
4583 //if(oldGdbHandle == gdbHandle)
4584 debugger.GdbThreadExit();
4585 delete oldGdbHandle;
4591 static define createFIFOMsg = $"err: Unable to create FIFO %s\n";
4592 static define openFIFOMsg = $"err: Unable to open FIFO %s for read\n";
4594 #if defined(__unix__)
4599 #include <sys/types.h>
4604 class ProgramThread : Thread
4609 //bool result = true;
4610 //bool fileCreated = false;
4611 //mode_t mask = 0600;
4612 static char output[1000];
4615 /*if(!mkfifo(progFifoPath, mask))
4622 ide.outputView.debugBox.Logf($"err: Unable to create FIFO %s\n", progFifoPath);
4626 if(FileExists(progFifoPath)) //fileCreated)
4628 fifoFile = FileOpen(progFifoPath, read);
4632 ide.outputView.debugBox.Logf(openFIFOMsg, progFifoPath);
4637 fd = fileno((FILE *)fifoFile.input);
4638 //fcntl(fd, F_SETFL, fcntl(fd, F_GETFL) | O_NONBLOCK);
4642 while(!terminate && fifoFile && !fifoFile.Eof())
4645 struct timeval time;
4653 /*selectResult = */select(fd + 1, &rs, null, null, &time);
4654 if(FD_ISSET(fd, &rs))
4656 int result = (int)read(fd, output, sizeof(output)-1);
4657 if(!result || (result < 0 && errno != EAGAIN))
4661 output[result] = '\0';
4662 if(strcmp(output,"&\"warning: GDB: Failed to set controlling terminal: Invalid argument\\n\"\n"))
4665 ide.outputView.debugBox.Log(output);
4674 //fifoFile.CloseInput();
4677 ide.outputView.debugBox.Log("\n");
4681 if(FileExists(progFifoPath)) //fileCreated)
4683 DeleteFile(progFifoPath);
4684 progFifoPath[0] = '\0';
4692 class Argument : struct
4694 Argument prev, next;
4696 property char * name { set { delete name; if(value) name = CopyString(value); } }
4698 property char * val { set { delete val; if(value) val = CopyString(value); } }
4712 class Frame : struct
4717 property char * addr { set { delete addr; if(value) addr = CopyString(value); } }
4719 property char * func { set { delete func; if(value) func = CopyString(value); } }
4723 property char * from { set { delete from; if(value) from = CopyUnescapedUnixPath(value); } }
4725 property char * file { set { delete file; if(value) file = CopyUnescapedUnixPath(value); } }
4726 char * absoluteFile;
4727 property char * absoluteFile { set { delete absoluteFile; if(value) absoluteFile = CopyUnescapedUnixPath(value); } }
4736 delete absoluteFile;
4737 args.Free(Argument::Free);
4746 class GdbDataStop : struct
4748 DebuggerReason reason;
4763 char * gdbResultVar;
4773 if(reason == signalReceived)
4778 else if(reason == functionFinished)
4780 delete gdbResultVar;
4784 if(frame) frame.Free();
4793 class GdbDataBreakpoint : struct
4797 property char * number { set { delete number; if(value) number = CopyString(value); } }
4799 property char * type { set { delete type; if(value) type = CopyString(value); } }
4801 property char * disp { set { delete disp; if(value) disp = CopyString(value); } }
4804 property char * addr { set { delete addr; if(value) addr = CopyString(value); } }
4806 property char * func { set { delete func; if(value) func = CopyString(value); } }
4808 property char * file { set { delete file; if(value) file = CopyUnescapedUnixPath(value); } }
4810 property char * fullname { set { delete fullname; if(value) fullname = CopyUnescapedUnixPath(value); } }
4813 property char * at { set { delete at; if(value) at = CopyString(value); } }
4816 Array<GdbDataBreakpoint> multipleBPs;
4821 PrintLn("{", "#", number, " T", type, " D", disp, " E", enabled, " H", times, " (", func, ") (", file, ":", line, ") (", fullname, ") (", addr, ") (", at, ")", "}");
4832 if(multipleBPs) multipleBPs.Free();
4838 ~GdbDataBreakpoint()
4844 class Breakpoint : struct
4849 property const char * function { set { delete function; if(value) function = CopyString(value); } }
4850 char * relativeFilePath;
4851 property const char * relativeFilePath { set { delete relativeFilePath; if(value) relativeFilePath = CopyString(value); } }
4852 char * absoluteFilePath;
4853 property const char * absoluteFilePath { set { delete absoluteFilePath; if(value) absoluteFilePath = CopyString(value); } }
4855 property const char * location { set { delete location; if(value) location = CopyString(value); } }
4864 BreakpointType type;
4866 GdbDataBreakpoint bp;
4869 property const char * address { set { delete address; if(value) address = CopyString(value); } }
4871 void ParseLocation()
4873 char * prjName = null;
4874 char * filePath = null;
4877 char fullPath[MAX_LOCATION];
4878 if(location[0] == '(' && location[1] && (file = strchr(location+2, ')')) && file[1])
4880 prjName = new char[file-location];
4881 strncpy(prjName, location+1, file-location-1);
4882 prjName[file-location-1] = '\0';
4887 if((line = strchr(file+1, ':')))
4889 filePath = new char[strlen(file)+1];
4890 strncpy(filePath, file, line-file);
4891 filePath[line-file] = '\0';
4895 filePath = CopyString(file);
4896 property::relativeFilePath = filePath;
4899 for(prj : ide.workspace.projects)
4901 if(!strcmp(prjName, prj.name))
4903 if(ProjectGetAbsoluteFromRelativePath(prj, filePath, fullPath))
4905 property::absoluteFilePath = fullPath;
4912 this.line = atoi(line);
4916 Project prj = ide.project;
4917 if(ProjectGetAbsoluteFromRelativePath(prj, filePath, fullPath))
4919 property::absoluteFilePath = fullPath;
4923 if(!absoluteFilePath)
4924 property::absoluteFilePath = "";
4929 char * CopyLocationString(bool removePath)
4932 char * file = relativeFilePath ? relativeFilePath : absoluteFilePath;
4933 bool removingPath = removePath && file;
4936 char * fileName = new char[MAX_FILENAME];
4937 GetLastDirectory(file, fileName);
4943 location = PrintString(file, ":", function);
4945 location = CopyString(function);
4948 location = PrintString(file, ":", line);
4954 char * CopyUserLocationString()
4957 char * loc = CopyLocationString(false);
4959 if(absoluteFilePath)
4961 for(p : ide.workspace.projects; p != ide.workspace.projects.firstIterator.data)
4963 if(p.topNode.FindByFullPath(absoluteFilePath, false))
4972 location = PrintString("(", prj.name, ")", loc);
4982 if(relativeFilePath && relativeFilePath[0])
4984 char * location = CopyUserLocationString();
4985 f.Printf(" * %d,%d,%d,%d,%s\n", enabled ? 1 : 0, ignore, level, line, location);
4988 f.Printf(" ~ %s\n", condition.expression);
4996 delete relativeFilePath;
4997 delete absoluteFilePath;
5017 class Watch : struct
5028 f.Printf(" ~ %s\n", expression);
5052 class DebugListItem : struct
5058 struct DebugEvaluationData
5063 uint64 nextBlockAddress;
5065 DebuggerEvaluationError error;
5068 class CodeLocation : struct
5071 char * absoluteFile;
5074 CodeLocation ::ParseCodeLocation(char * location)
5078 char * colon = null;
5080 char loc[MAX_LOCATION];
5081 strcpy(loc, location);
5082 for(temp = loc; (temp = strstr(temp, ":")); temp++)
5090 int line = atoi(colon);
5093 CodeLocation codloc { line = line };
5094 codloc.file = CopyString(loc);
5095 codloc.absoluteFile = ide.workspace.GetAbsolutePathFromRelative(loc);
5107 delete absoluteFile;
5116 void GDBFallBack(Expression exp, String expString)
5119 ExpressionType evalError = dummyExp;
5120 result = Debugger::EvaluateExpression(expString, &evalError);
5123 FreeExpContents(exp);
5124 exp.constant = result;
5125 exp.type = constantExp;
5129 static Project WorkspaceGetFileOwner(const char * absolutePath)
5131 Project owner = null;
5132 for(prj : ide.workspace.projects)
5134 if(prj.topNode.FindByFullPath(absolutePath, false))
5141 WorkspaceGetObjectFileNode(absolutePath, &owner);
5145 static ProjectNode WorkspaceGetObjectFileNode(const char * filePath, Project * project)
5147 ProjectNode node = null;
5148 char ext[MAX_EXTENSION];
5149 GetExtension(filePath, ext);
5152 IntermediateFileType type = IntermediateFileType::FromExtension(ext);
5155 char fileName[MAX_FILENAME];
5156 GetLastDirectory(filePath, fileName);
5159 DotMain dotMain = DotMain::FromFileName(fileName);
5160 for(prj : ide.workspace.projects)
5162 if((node = prj.FindNodeByObjectFileName(fileName, type, dotMain, null)))
5175 static ProjectNode ProjectGetObjectFileNode(Project project, const char * filePath)
5177 ProjectNode node = null;
5178 char ext[MAX_EXTENSION];
5179 GetExtension(filePath, ext);
5182 IntermediateFileType type = IntermediateFileType::FromExtension(ext);
5185 char fileName[MAX_FILENAME];
5186 GetLastDirectory(filePath, fileName);
5189 DotMain dotMain = DotMain::FromFileName(fileName);
5190 node = project.FindNodeByObjectFileName(fileName, type, dotMain, null);
5197 static void WorkspaceGetRelativePath(const char * absolutePath, char * relativePath, Project * owner)
5199 Project prj = WorkspaceGetFileOwner(absolutePath);
5203 prj = ide.workspace.projects.firstIterator.data;
5206 MakePathRelative(absolutePath, prj.topNode.path, relativePath);
5207 MakeSlashPath(relativePath);
5210 relativePath[0] = '\0';
5213 static bool ProjectGetAbsoluteFromRelativePath(Project project, const char * relativePath, char * absolutePath)
5215 ProjectNode node = project.topNode.FindWithPath(relativePath, false);
5217 node = ProjectGetObjectFileNode(project, relativePath);
5220 strcpy(absolutePath, node.project.topNode.path);
5221 PathCat(absolutePath, relativePath);
5222 MakeSlashPath(absolutePath);
5224 return node != null;