2 public import static "ecere"
3 public import static "ec"
16 #define GDB_DEBUG_CONSOLE
20 extern char * strrchr(const char * s, int c);
23 #define strlen _strlen
26 #include <string.h> // For memchr
34 #include <sys/time.h> // Required on Apple...
41 // use =0 to disable printing of specific channels
42 static enum dplchan { none, gdbProtoIgnored=0/*1*/, gdbProtoUnknown=2, gdbOutput=3/*3*/, gdbCommand=4/*4*/, debuggerCall=0/*5*/, debuggerProblem=6,
43 debuggerUserAction=7,debuggerState=8, debuggerBreakpoints=9, debuggerWatches=0/*10*/, debuggerTemp=0 };
44 static const char * _dpct[] = {
46 "GDB Protocol Ignored",
47 "GDB Protocol ***Unknown***",
51 "Debugger ***Problem***",
52 "Debugger::ChangeUserAction",
53 "Debugger::ChangeState",
56 "-----> Temporary Message",
61 public char * StripQuotes2(char * string, char * output)
65 bool quoted = false, escaped = false;
67 for(c = 0; (ch = string[c]); c++)
71 if(escaped || ch != '\"')
74 escaped = !escaped && ch == '\\';
89 static void strescpy(char * d, char * s)
97 case '\n': d[k] = '\\'; d[++k] = 'n'; break;
98 case '\t': d[k] = '\\'; d[++k] = 't'; break;
99 case '\a': d[k] = '\\'; d[++k] = 'a'; break;
100 case '\b': d[k] = '\\'; d[++k] = 'b'; break;
101 case '\f': d[k] = '\\'; d[++k] = 'f'; break;
102 case '\r': d[k] = '\\'; d[++k] = 'r'; break;
103 case '\v': d[k] = '\\'; d[++k] = 'v'; break;
104 case '\\': d[k] = '\\'; d[++k] = '\\'; break;
105 case '\"': d[k] = '\\'; d[++k] = '\"'; break;
106 default: d[k] = s[j];
113 /*static char * CopyUnescapedSystemPath(char * p)
116 char * d = new char[len + 1];
117 UnescapeString(d, p, len);
118 #if defined(__WIN32__)
119 ChangeCh(d, '/', '\\');
124 static char * CopyUnescapedUnixPath(char * p)
127 char * d = new char[len + 1];
128 UnescapeString(d, p, len);
129 #if defined(__WIN32__)
130 ChangeCh(d, '\\', '/');
135 static char * CopyUnescapedString(char * s)
138 char * d = new char[len + 1];
139 UnescapeString(d, s, len);
143 static char * StripBrackets(char * string)
145 int length = strlen(string);
146 if(length > 1 && *string == '[' && string[length - 1] == ']')
149 string[length - 1] = '\0';
156 static char * StripCurlies(char * string)
158 int length = strlen(string);
159 if(length > 1 && *string == '{' && string[length - 1] == '}')
162 string[length - 1] = '\0';
169 /*static int StringGetInt(char * string, int start)
172 int i, len = strlen(string);
174 for(i = start; i < len && i < start + 8; i++)
176 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')
177 strncat(number, &string[i], 1);
184 static int TokenizeList(char * string, const char seperator, Array<char *> tokens)
188 bool quoted = false, escaped = false;
189 char * start = string, ch;
191 for(; (ch = *string); string++)
198 if(escaped || ch != '\"')
199 escaped = !escaped && ch == '\\';
205 else if(ch == '{' || ch == '[' || ch == '(' || ch == '<')
207 else if(ch == '}' || ch == ']' || ch == ')' || ch == '>')
209 else if(ch == seperator && !level)
218 //tokens[count] = start;
219 //tokens[count++] = start;
226 static bool TokenizeListItem(char * string, DebugListItem item)
228 char * equal = strstr(string, "=");
240 static bool CheckCommandAvailable(const char * command)
242 bool available = false;
244 char * name = new char[MAX_FILENAME];
245 char * pathVar = new char[maxPathLen];
247 GetEnvironment("PATH", pathVar, maxPathLen);
248 count = TokenizeWith(pathVar, sizeof(paths) / sizeof(char *), paths, pathListSep, false);
249 strcpy(name, command);
253 const char * extensions[] = { "exe", "com", "bat", null };
254 for(e=0; extensions[e]; e++)
256 ChangeExtension(name, extensions[e], name);
258 for(c=0; c<count; c++)
260 FileListing fl { paths[c] };
263 if(fl.stats.attribs.isFile && !fstrcmp(fl.name, name))
282 // define GdbGetLineSize = 1638400;
283 define GdbGetLineSize = 5638400;
284 #if defined(__unix__)
285 char progFifoPath[MAX_LOCATION];
286 char progFifoDir[MAX_LOCATION];
289 enum DebuggerState { none, prompt, loaded, running, stopped, terminated, error };
292 none, hit, breakEvent, signal, stepEnd, functionEnd, exit, valgrindStartPause, locationReached;
294 property bool canBeMonitored { get { return (this == hit || this == breakEvent || this == signal || this == stepEnd || this == functionEnd || this == locationReached); } };
296 enum DebuggerAction { none, internal, restart, stop, selectFrame, advance }; //, bpValidation
299 unknown, endSteppingRange, functionFinished, signalReceived, breakpointHit, locationReached
300 //watchpointTrigger, readWatchpointTrigger, accessWatchpointTrigger, watchpointScope,
301 //exited, exitedNormally, exitedSignalled;
305 none, internalMain, internalWinMain, internalModulesLoaded, user, runToCursor, internalModuleLoad, internalEntry;
307 property bool isInternal { get { return (this == internalMain || this == internalWinMain || this == internalModulesLoaded || this == internalModuleLoad || this == internalEntry); } };
308 property bool isUser { get { return (this == user || this == runToCursor); } };
310 enum DebuggerEvaluationError { none, symbolNotFound, memoryCantBeRead, unknown };
311 enum DebuggerUserAction
313 none, start, resume, _break, stop, restart, selectThread, selectFrame, stepInto, stepOver, stepUntil, stepOut, runToCursor;
314 property bool breaksOnInternalBreakpoint { get { return (this == stepInto || this == stepOver || this == stepUntil); } };
318 none, run, _continue, next, until, advance, step, finish;
319 property bool suspendInternalBreakpoints { get { return (this == until || this == advance || this == step || this == finish); } };
322 FileDialog debuggerFileDialog { type = selectDir };
324 static DualPipe vgTargetHandle;
325 static File vgLogFile;
326 static char vgLogPath[MAX_LOCATION];
327 static DualPipe gdbHandle;
328 static DebugEvaluationData eval { };
330 static int targetProcessId;
332 static bool gdbReady;
333 static bool breakpointError;
337 Semaphore serialSemaphore { };
343 bool sentBreakInsert;
344 bool ignoreBreakpoints;
352 int activeFrameLevel;
361 GdbExecution gdbExecution;
362 DebuggerUserAction userAction;
365 DebuggerAction breakType;
367 //DebuggerCommand lastCommand; // THE COMPILER COMPILES STUFF THAT DOES NOT EXIST???
369 GdbDataStop stopItem;
370 GdbDataBreakpoint bpItem;
373 List<Breakpoint> sysBPs { };
374 Breakpoint bpRunToCursor;
375 Breakpoint intBpEntry;
376 Breakpoint intBpMain;
377 Breakpoint intBpWinMain;
381 CompilerConfig currentCompiler;
382 ProjectConfig prjConfig;
385 CodeEditor codeEditor;
387 ValgrindLogThread vgLogThread { debugger = this };
388 ValgrindTargetThread vgTargetThread { debugger = this };
389 GdbThread gdbThread { debugger = this };
392 Map<String, bool> projectsLibraryLoaded { };
396 delay = 0.0, userData = this;
400 bool monitor = false;
401 DebuggerEvent curEvent = event;
402 GdbDataStop stopItem = this.stopItem;
403 Breakpoint bpUser = null;
404 Breakpoint bpInternal = null;
412 this.stopItem = null;
416 DynamicString bpReport { };
418 for(bp : sysBPs; bp.inserted)
420 bpReport.concatx(",", bp.type, "(", s=bp.CopyLocationString(false), ")");
423 if(bpRunToCursor && bpRunToCursor.inserted)
425 Breakpoint bp = bpRunToCursor;
426 bpReport.concatx(",", bp.type, "(", s=bp.CopyLocationString(false), ")");
429 for(bp : ide.workspace.breakpoints; bp.inserted)
431 bpReport.concatx(",", bp.type, "(", s=bp.CopyLocationString(false), ")");
435 _dpcl(_dpct, dplchan::debuggerBreakpoints, 0, "gdbTimer::DelayExpired: ", s+1);
440 Breakpoint bp = GetBreakpointById(stopItem.bkptno, &isInternal);
443 _dpcl(_dpct, dplchan::debuggerBreakpoints, 0, "gdb stopped by a breakpoint: ", bp.type, "(", s=bp.CopyLocationString(false), ")");
454 if(curEvent && curEvent != exit)
456 _dplf(0, "No stop item");
464 Restart(currentCompiler, prjConfig, bitDepth, usingValgrind);
473 GdbCommand(0, false, "-stack-select-frame %d", activeFrameLevel);
474 for(activeFrame = stackFrames.first; activeFrame; activeFrame = activeFrame.next)
475 if(activeFrame.level == activeFrameLevel)
481 // GdbCommand(0, false, "-break-info %s", bpItem.number);
493 Breakpoint bp = stopItem ? GetBreakpointById(stopItem.bkptno, &isInternal) : null;
494 if(bp && bp.inserted && bp.bp.addr)
496 if(bp.type.isInternal)
500 if(stopItem && stopItem.frame)
502 if(bpInternal && bpRunToCursor && bpRunToCursor.inserted && !strcmp(bpRunToCursor.bp.addr, bp.bp.addr))
503 bpUser = bpRunToCursor;
506 for(item : (bpInternal ? ide.workspace.breakpoints : sysBPs); item.inserted)
508 if(item.bp && item.bp.addr && !strcmp(item.bp.addr, bp.bp.addr))
520 _dpcl(_dpct, dplchan::debuggerProblem, 0, "Invalid stopItem!");
521 if(bpUser && stopItem.frame.addr && strcmp(stopItem.frame.addr, bpUser.bp.addr))
522 _dpcl(_dpct, dplchan::debuggerProblem, 0, "Breakpoint bkptno(", stopItem.bkptno, ") address missmatch!");
525 _dpcl(_dpct, dplchan::debuggerProblem, 0, "Breakpoint bkptno(", stopItem.bkptno, ") invalid or not found!");
526 if((bpUser && !ignoreBreakpoints) || (bpInternal && userAction.breaksOnInternalBreakpoint))
528 hitThread = stopItem.threadid;
532 signalThread = stopItem.threadid;
536 case locationReached:
538 ignoreBreakpoints = false;
540 case valgrindStartPause:
541 GdbExecContinue(true);
549 if(curEvent == signal)
553 ide.outputView.debugBox.Logf($"Signal received: %s - %s\n", stopItem.name, stopItem.meaning);
554 ide.outputView.debugBox.Logf(" %s:%d\n", (s = CopySystemPath(stopItem.frame.file)), stopItem.frame.line);
555 ide.outputView.Show();
556 ide.callStackView.Show();
559 else if(curEvent == breakEvent)
561 ide.threadsView.Show();
562 ide.callStackView.Show();
563 ide.callStackView.Activate();
565 else if(curEvent == hit)
567 if(BreakpointHit(stopItem, bpInternal, bpUser))
569 ide.AdjustDebugMenus();
570 if(bpUser && bpUser.type == runToCursor)
572 ignoreBreakpoints = false;
573 UnsetBreakpoint(bpUser);
574 delete bpRunToCursor;
579 if(breakType == advance && bpInternal && (bpInternal.type == internalMain || bpInternal.type == internalEntry))
582 GdbExecAdvance(breakString, 0);
587 GdbExecContinue(false);
593 if(monitor && curEvent.canBeMonitored)
596 activeThread = stopItem.threadid;
597 GdbCommand(0, false, "-thread-list-ids");
598 InternalSelectFrame(activeFrameLevel);
599 GoToStackFrameLine(activeFrameLevel, true, false);
601 ide.ShowCodeEditor();
602 ide.AdjustDebugMenus();
603 ideMainFrame.Activate(); // TOFIX: ide.Activate() is not reliable (app inactive)
616 #ifdef GDB_DEBUG_CONSOLE
617 char lastGdbOutput[GdbGetLineSize];
619 #if defined(__unix__)
620 ProgramThread progThread { };
624 #define _ChangeUserAction(value) ChangeUserAction(__FILE__, __LINE__, value)
625 void ChangeUserAction(const char * file, int line, DebuggerUserAction value)
628 bool same = value == userAction;
629 __dpl(file, line, _dpct, dplchan::debuggerUserAction, 0, userAction, /*same ? " *** == *** " : */" -> ", value);
634 #define _ChangeUserAction(value) userAction = value
638 #define _ChangeState(value) ChangeState(__FILE__, __LINE__, value)
639 void ChangeState(const char * file, int line, DebuggerState value)
641 #define _ChangeState(value) ChangeState(value)
642 void ChangeState(DebuggerState value)
645 bool same = value == state;
647 __dpl(file, line, _dpct, dplchan::debuggerState, 0, state, same ? " *** == *** " : " -> ", value);
650 if(!same) ide.AdjustDebugMenus();
655 _dpcl(_dpct, dplchan::debuggerCall, 0, "Debugger::CleanUp");
657 stackFrames.Free(Frame::Free);
667 waitingForPID = false;
672 sentBreakInsert = false;
673 ignoreBreakpoints = false;
676 activeFrameLevel = 0;
693 bpRunToCursor = null;
695 delete currentCompiler;
698 WatchesReleaseCodeEditor();
701 projectsLibraryLoaded.Free();
703 /*GdbThread gdbThread
709 _dpcl(_dpct, dplchan::debuggerCall, 0, "Debugger::constructor");
710 ideProcessId = Process_GetCurrentProcessId();
712 sysBPs.Add((intBpEntry = Breakpoint { type = internalEntry, enabled = false, level = -1 }));
713 sysBPs.Add((intBpMain = Breakpoint { type = internalMain, function = "main", enabled = true, level = -1 }));
714 #if defined(__WIN32__)
715 sysBPs.Add((intBpWinMain = Breakpoint { type = internalWinMain, function = "WinMain", enabled = true, level = -1 }));
717 sysBPs.Add(Breakpoint { type = internalModulesLoaded, enabled = true, level = -1 });
718 sysBPs.Add(Breakpoint { type = internalModuleLoad, function = "InternalModuleLoadBreakpoint", enabled = true, level = -1 });
723 _dpcl(_dpct, dplchan::debuggerCall, 0, "Debugger::destructor");
731 property bool isActive { get { return state == running || state == stopped; } }
732 property bool isPrepared { get { return state == loaded || state == running || state == stopped; } }
736 _dpcl(_dpct, dplchan::debuggerCall, 0, "Debugger::Resume");
737 _ChangeUserAction(resume);
738 GdbExecContinue(true);
743 _dpcl(_dpct, dplchan::debuggerCall, 0, "Debugger::Break");
744 _ChangeUserAction(_break);
748 GdbDebugBreak(false);
754 _dpcl(_dpct, dplchan::debuggerCall, 0, "Debugger::Stop");
755 _ChangeUserAction(stop);
762 GdbDebugBreak(false);
776 void Restart(CompilerConfig compiler, ProjectConfig config, int bitDepth, bool useValgrind)
778 _dpcl(_dpct, dplchan::debuggerCall, 0, "Debugger::Restart");
779 _ChangeUserAction(restart);
780 if(StartSession(compiler, config, bitDepth, useValgrind, true, false) == loaded)
784 bool GoToCodeLine(char * location)
787 _dpcl(_dpct, dplchan::debuggerCall, 0, "Debugger::GoToCodeLine(", location, ")");
788 codloc = CodeLocation::ParseCodeLocation(location);
791 CodeEditor editor = (CodeEditor)ide.OpenFile(codloc.absoluteFile, false, true, null, no, normal, false);
794 EditBox editBox = editor.editBox;
795 if(editBox.GoToLineNum(codloc.line - 1))
796 editBox.GoToPosition(editBox.line, codloc.line - 1, 0);
803 bool GoToStackFrameLine(int stackLevel, bool askForLocation, bool fromCallStack)
805 _dpcl(_dpct, dplchan::debuggerCall, 0, "Debugger::GoToStackFrameLine(", stackLevel, ", ", askForLocation, ")");
808 char sourceDir[MAX_LOCATION];
810 CodeEditor editor = null;
811 if(stackLevel == -1) // this (the two lines) is part of that fix that I would not put in for some time
813 for(frame = stackFrames.first; frame; frame = frame.next)
814 if(frame.level == stackLevel)
819 ide.callStackView.Show();
821 if(frame.absoluteFile)
822 editor = (CodeEditor)ide.OpenFile(frame.absoluteFile, false, true, null, no, normal, false);
823 if(!editor && frame.file)
824 frame.absoluteFile = ide.workspace.CopyAbsolutePathFromRelative(frame.file);
825 if(!frame.absoluteFile && askForLocation && frame.file)
828 char title[MAX_LOCATION];
829 snprintf(title, sizeof(title), $"Provide source file location for %s", (s = CopySystemPath(frame.file)));
830 title[sizeof(title)-1] = 0;
832 if(SourceDirDialog(title, ide.workspace.projectDir, frame.file, sourceDir))
834 AddSourceDir(sourceDir);
835 frame.absoluteFile = ide.workspace.CopyAbsolutePathFromRelative(frame.file);
838 if(!editor && frame.absoluteFile)
839 editor = (CodeEditor)ide.OpenFile(frame.absoluteFile, false, true, null, no, normal, false);
841 ide.RepositionWindows(false);
843 if(editor && frame.line)
845 EditBox editBox = editor.editBox;
846 editBox.GoToLineNum(frame.line - 1);
847 editBox.GoToPosition(editBox.line, frame.line - 1, 0);
855 void SelectThread(int thread)
857 _dpcl(_dpct, dplchan::debuggerCall, 0, "Debugger::SelectThread(", thread, ")");
858 _ChangeUserAction(selectThread);
861 if(thread != activeThread)
863 activeFrameLevel = -1;
864 ide.callStackView.Clear();
865 GdbCommand(0, false, "-thread-select %d", thread);
867 InternalSelectFrame(activeFrameLevel);
868 GoToStackFrameLine(activeFrameLevel, true, false);
872 ide.callStackView.Show();
876 void SelectFrame(int frame)
878 //_dpcl(_dpct, dplchan::debuggerCall, 0, "Debugger::SelectFrame(", frame, ")");
879 _ChangeUserAction(selectFrame);
882 if(frame != activeFrameLevel)
884 InternalSelectFrame(frame);
891 void InternalSelectFrame(int frame)
893 //_dpcl(_dpct, dplchan::debuggerCall, 0, "Debugger::InternalSelectFrame(", frame, ")");
894 activeFrameLevel = frame; // there is no active frame number in the gdb reply
895 GdbCommand(0, false, "-stack-select-frame %d", activeFrameLevel);
896 for(activeFrame = stackFrames.first; activeFrame; activeFrame = activeFrame.next)
897 if(activeFrame.level == activeFrameLevel)
901 void HandleExit(char * reason, char * code)
903 char verboseExitCode[128];
905 _dpcl(_dpct, dplchan::debuggerCall, 0, "Debugger::HandleExit(", reason, ", ", code, ")");
906 _ChangeState(loaded); // this state change seems to be superfluous, might be in case of gdb crash
911 snprintf(verboseExitCode, sizeof(verboseExitCode), $" with exit code %s", code);
912 verboseExitCode[sizeof(verboseExitCode)-1] = 0;
915 verboseExitCode[0] = '\0';
919 // ClearBreakDisplay();
923 for(wh : ide.workspace.watches)
925 if(wh.type) FreeType(wh.type);
928 ide.watchesView.UpdateWatch(wh);
932 #if defined(__unix__)
935 progThread.terminate = true;
938 fifoFile.CloseInput();
948 char program[MAX_LOCATION];
949 GetSystemPathBuffer(program, targetFile);
951 ide.outputView.debugBox.Logf($"The program %s has exited%s.\n", program, verboseExitCode);
952 else if(!strcmp(reason, "exited-normally"))
953 ide.outputView.debugBox.Logf($"The program %s has exited normally%s.\n", program, verboseExitCode);
954 else if(!strcmp(reason, "exited"))
955 ide.outputView.debugBox.Logf($"The program %s has exited%s.\n", program, verboseExitCode);
956 else if(!strcmp(reason, "exited-signalled"))
957 ide.outputView.debugBox.Logf($"The program %s has exited with a signal%s.\n", program, verboseExitCode);
959 ide.outputView.debugBox.Logf($"The program %s has exited (gdb provided an unknown reason)%s.\n", program, verboseExitCode);
964 DebuggerState StartSession(CompilerConfig compiler, ProjectConfig config, int bitDepth, bool useValgrind, bool restart, bool ignoreBreakpoints)
966 DebuggerState result = none;
967 _dpcl(_dpct, dplchan::debuggerCall, 0, "Debugger::StartSession(restart(", restart, "), ignoreBreakpoints(", ignoreBreakpoints, ")");
968 if(restart && state == running && targetProcessId)
970 breakType = DebuggerAction::restart;
971 GdbDebugBreak(false);
975 if(restart && state == stopped)
977 if(needReset && state == loaded)
978 GdbExit(); // this reset is to get a clean state with all the breakpoints until a better state can be maintained on program exit
980 if(result == none || result == terminated)
982 ide.outputView.ShowClearSelectTab(debug);
983 ide.outputView.debugBox.Logf($"Starting debug mode\n");
990 for(bp : ide.workspace.breakpoints)
996 if(GdbInit(compiler, config, bitDepth, useValgrind))
1001 this.ignoreBreakpoints = ignoreBreakpoints;
1006 void Start(CompilerConfig compiler, ProjectConfig config, int bitDepth, bool useValgrind)
1008 _dpcl(_dpct, dplchan::debuggerCall, 0, "Debugger::Start()");
1009 _ChangeUserAction(start);
1010 if(StartSession(compiler, config, bitDepth, useValgrind, true, false) == loaded)
1014 void StepInto(CompilerConfig compiler, ProjectConfig config, int bitDepth, bool useValgrind)
1016 _dpcl(_dpct, dplchan::debuggerCall, 0, "Debugger::StepInto()");
1017 _ChangeUserAction(stepInto);
1018 switch(StartSession(compiler, config, bitDepth, useValgrind, false, false))
1020 case loaded: GdbExecRun(); break;
1021 case stopped: GdbExecStep(); break;
1025 void StepOver(CompilerConfig compiler, ProjectConfig config, int bitDepth, bool useValgrind, bool ignoreBreakpoints)
1027 _dpcl(_dpct, dplchan::debuggerCall, 0, "Debugger::StepOver()");
1028 _ChangeUserAction(stepOver);
1029 switch(StartSession(compiler, config, bitDepth, useValgrind, false, ignoreBreakpoints))
1031 case loaded: GdbExecRun(); break;
1032 case stopped: GdbExecNext(); break;
1036 void StepUntil(CompilerConfig compiler, ProjectConfig config, int bitDepth, bool useValgrind, bool ignoreBreakpoints)
1038 _dpcl(_dpct, dplchan::debuggerCall, 0, "Debugger::StepUntil()");
1039 _ChangeUserAction(stepUntil);
1040 switch(StartSession(compiler, config, bitDepth, useValgrind, false, ignoreBreakpoints))
1042 case loaded: GdbExecRun(); break;
1043 case stopped: GdbExecUntil(null, 0); break;
1047 void StepOut(bool ignoreBreakpoints)
1049 _dpcl(_dpct, dplchan::debuggerCall, 0, "Debugger::StepOut()");
1050 _ChangeUserAction(stepOut);
1051 if(state == stopped)
1053 this.ignoreBreakpoints = ignoreBreakpoints;
1057 GdbExecContinue(true);
1061 void RunToCursor(CompilerConfig compiler, ProjectConfig config, int bitDepth, bool useValgrind, const char * absoluteFilePath, int lineNumber, bool ignoreBreakpoints, bool atSameLevel, bool oldImplementation)
1063 char relativeFilePath[MAX_LOCATION];
1064 const char * objectFileExt = compiler ? compiler.objectFileExt : objectDefaultFileExt;
1065 _dpcl(_dpct, dplchan::debuggerCall, 0, "Debugger::RunToCursor()");
1066 _ChangeUserAction(runToCursor);
1067 ide.workspace.GetRelativePath(absoluteFilePath, relativeFilePath, null, objectFileExt);
1069 if(bpRunToCursor && bpRunToCursor.inserted && symbols)
1071 UnsetBreakpoint(bpRunToCursor);
1072 delete bpRunToCursor;
1075 StartSession(compiler, config, bitDepth, useValgrind, false, ignoreBreakpoints);
1078 if(oldImplementation)
1080 bpRunToCursor = Breakpoint { };
1081 bpRunToCursor.absoluteFilePath = absoluteFilePath;
1082 bpRunToCursor.relativeFilePath = relativeFilePath;
1083 bpRunToCursor.line = lineNumber;
1084 bpRunToCursor.type = runToCursor;
1085 bpRunToCursor.enabled = true;
1086 bpRunToCursor.level = atSameLevel ? frameCount - activeFrameLevel -1 : -1;
1091 breakType = advance;
1092 breakString = PrintString(relativeFilePath, ":", lineNumber);
1095 else if(state == stopped)
1097 if(oldImplementation)
1098 GdbExecContinue(true);
1102 GdbExecUntil(absoluteFilePath, lineNumber);
1104 GdbExecAdvance(absoluteFilePath, lineNumber);
1109 void GetCallStackCursorLine(bool * error, int * lineCursor, int * lineTopFrame)
1111 //_dpcl(_dpct, dplchan::debuggerCall, 0, "Debugger::GetCallStackCursorLine()");
1112 if(activeFrameLevel == -1)
1120 *error = signalOn && activeThread == signalThread;
1121 *lineCursor = activeFrameLevel - ((frameCount > 192 && activeFrameLevel > 191) ? frameCount - 192 - 1 : 0) + 1;
1122 *lineTopFrame = activeFrameLevel ? 1 : 0;
1126 int GetMarginIconsLineNumbers(const char * fileName, int lines[], bool enabled[], int max, bool * error, int * lineCursor, int * lineTopFrame)
1128 char winFilePath[MAX_LOCATION];
1129 char * absoluteFilePath = GetSlashPathBuffer(winFilePath, fileName);
1131 Iterator<Breakpoint> it { ide.workspace.breakpoints };
1132 //_dpcl(_dpct, dplchan::debuggerCall, 0, "Debugger::GetMarginIconsLineNumbers()");
1133 while(it.Next() && count < max)
1135 Breakpoint bp = it.data;
1138 if(bp.absoluteFilePath && bp.absoluteFilePath[0] && !fstrcmp(bp.absoluteFilePath, absoluteFilePath))
1140 lines[count] = bp.line;
1141 enabled[count] = bp.enabled;
1146 if(activeFrameLevel == -1)
1154 *error = signalOn && activeThread == signalThread;
1155 if(activeFrame && activeFrame.absoluteFile && !fstrcmp(absoluteFilePath, activeFrame.absoluteFile))
1156 *lineCursor = activeFrame.line;
1159 if(activeFrame && stopItem && stopItem.frame && activeFrame.level == stopItem.frame.level)
1161 else if(stopItem && stopItem.frame && stopItem.frame.absoluteFile && !fstrcmp(absoluteFilePath, stopItem.frame.absoluteFile))
1162 *lineTopFrame = stopItem.frame.line;
1166 if(*lineTopFrame == *lineCursor && *lineTopFrame)
1172 void ChangeWatch(DataRow row, char * expression)
1174 Watch wh = (Watch)(intptr)row.tag;
1175 //_dpcl(_dpct, dplchan::debuggerCall, 0, "Debugger::ChangeWatch(", expression, ")");
1178 delete wh.expression;
1180 wh.expression = CopyString(expression);
1183 Iterator<Watch> it { ide.workspace.watches };
1185 ide.workspace.watches.Delete(it.pointer);
1191 row.tag = (int64)(intptr)wh;
1192 ide.workspace.watches.Add(wh);
1194 wh.expression = CopyString(expression);
1196 ide.workspace.Save();
1197 //if(expression && state == stopped)
1202 void MoveIcons(const char * fileName, int lineNumber, int move, bool start)
1204 char winFilePath[MAX_LOCATION];
1205 const char * absoluteFilePath = GetSlashPathBuffer(winFilePath, fileName);
1208 //_dpcl(_dpct, dplchan::debuggerCall, 0, "Debugger::MoveIcons()");
1209 for(bpLink = ide.workspace.breakpoints.first; bpLink; bpLink = next)
1211 Breakpoint bp = (Breakpoint)(intptr)bpLink.data;
1214 if(bp.type == user && bp.absoluteFilePath && !fstrcmp(bp.absoluteFilePath, absoluteFilePath))
1216 if(bp.line > lineNumber || (bp.line == lineNumber && start))
1218 if(move < 0 && (bp.line < lineNumber - move))
1219 ide.workspace.RemoveBreakpoint(bp);
1223 ide.breakpointsView.UpdateBreakpoint(bp.row);
1224 ide.workspace.Save();
1230 // moving code cursors is futile, on next step, stop, hit, cursors will be offset anyways
1233 bool SourceDirDialog(const char * title, const char * startDir, const char * test, char * sourceDir)
1236 String srcDir = null;
1238 _dpcl(_dpct, dplchan::debuggerCall, 0, "Debugger::SourceDirDialog()");
1239 debuggerFileDialog.text = title;
1240 debuggerFileDialog.currentDirectory = startDir;
1241 debuggerFileDialog.master = ide;
1243 while(debuggerFileDialog.Modal())
1245 strcpy(sourceDir, debuggerFileDialog.filePath);
1246 if(!fstrcmp(ide.workspace.projectDir, sourceDir) &&
1247 MessageBox { type = yesNo, master = ide,
1248 contents = $"This is the project directory.\nWould you like to try again?",
1249 text = $"Invalid Source Directory" }.Modal() == no)
1253 for(dir : ide.workspace.sourceDirs)
1255 if(!fstrcmp(dir, sourceDir))
1263 MessageBox { type = yesNo, master = ide,
1264 contents = $"This source directory is already specified.\nWould you like to try again?",
1265 text = $"Invalid Source Directory" }.Modal() == no)
1271 char file[MAX_LOCATION];
1272 strcpy(file, sourceDir);
1273 PathCat(file, test);
1274 result = FileExists(file);
1276 MessageBox { type = yesNo, master = ide,
1277 contents = $"Unable to locate source file.\nWould you like to try again?",
1278 text = $"Invalid Source Directory" }.Modal() == no)
1292 void AddSourceDir(const char * sourceDir)
1294 _dpcl(_dpct, dplchan::debuggerCall, 0, "Debugger::AddSourceDir(", sourceDir, ")");
1295 ide.workspace.sourceDirs.Add(CopyString(sourceDir));
1296 ide.workspace.Save();
1300 DebuggerState oldState = state;
1305 GdbDebugBreak(true);
1308 GdbCommand(0, false, "-environment-directory \"%s\"", sourceDir);
1311 if(oldState == running)
1312 GdbExecContinue(false);
1316 void ToggleBreakpoint(const char * fileName, int lineNumber)
1318 char absolutePath[MAX_LOCATION];
1319 Breakpoint bp = null;
1321 _dpcl(_dpct, dplchan::debuggerBreakpoints, 0, "Debugger::ToggleBreakpoint(", fileName, ":", lineNumber, ")");
1323 GetSlashPathBuffer(absolutePath, fileName);
1324 for(i : ide.workspace.breakpoints; i.type == user && i.absoluteFilePath && !fstrcmp(i.absoluteFilePath, absolutePath) && i.line == lineNumber)
1333 ide.workspace.RemoveBreakpoint(bp);
1342 char relativePath[MAX_LOCATION];
1343 const char * objectFileExt = currentCompiler ? currentCompiler.objectFileExt : objectDefaultFileExt;
1345 ide.workspace.GetRelativePath(absolutePath, relativePath, &owner, objectFileExt);
1347 if(!owner && !FileExists(absolutePath))
1349 char title[MAX_LOCATION];
1350 char directory[MAX_LOCATION];
1351 char sourceDir[MAX_LOCATION];
1352 StripLastDirectory(absolutePath, directory);
1353 snprintf(title, sizeof(title), $"Provide source files location directory for %s", relativePath);
1354 title[sizeof(title)-1] = 0;
1357 String srcDir = null;
1358 for(dir : ide.workspace.sourceDirs)
1360 if(IsPathInsideOf(absolutePath, dir))
1362 MakePathRelative(absolutePath, dir, relativePath);
1370 if(SourceDirDialog(title, directory, null, sourceDir))
1372 if(IsPathInsideOf(absolutePath, sourceDir))
1374 AddSourceDir(sourceDir);
1375 MakePathRelative(absolutePath, sourceDir, relativePath);
1378 else if(MessageBox { type = yesNo, master = ide,
1379 contents = $"You must provide a valid source directory in order to place a breakpoint in this file.\nWould you like to try again?",
1380 text = $"Invalid Source Directory" }.Modal() == no)
1387 ide.workspace.bpCount++;
1388 bp = { line = lineNumber, type = user, enabled = true, level = -1, project = owner };
1389 ide.workspace.breakpoints.Add(bp);
1390 bp.absoluteFilePath = absolutePath;
1391 bp.relativeFilePath = relativePath;
1392 ide.breakpointsView.AddBreakpoint(bp);
1397 DebuggerState oldState = state;
1402 GdbDebugBreak(true);
1405 if(!SetBreakpoint(bp, false))
1406 SetBreakpoint(bp, true);
1409 if(oldState == running)
1410 GdbExecContinue(false);
1413 ide.workspace.Save();
1416 void UpdateRemovedBreakpoint(Breakpoint bp)
1418 _dpcl(_dpct, dplchan::debuggerCall, 0, "Debugger::UpdateRemovedBreakpoint()");
1419 if(targeted && bp.inserted)
1421 DebuggerState oldState = state;
1426 GdbDebugBreak(true);
1429 UnsetBreakpoint(bp);
1432 if(oldState == running)
1433 GdbExecContinue(false);
1439 void ParseFrame(Frame frame, char * string)
1442 Array<char *> frameTokens { minAllocSize = 50 };
1443 Array<char *> argsTokens { minAllocSize = 50 };
1444 Array<char *> argumentTokens { minAllocSize = 50 };
1445 DebugListItem item { };
1448 //_dpcl(_dpct, dplchan::debuggerCall, 0, "Debugger::ParseFrame()");
1449 TokenizeList(string, ',', frameTokens);
1450 for(i = 0; i < frameTokens.count; i++)
1452 if(TokenizeListItem(frameTokens[i], item))
1454 StripQuotes(item.value, item.value);
1455 if(!strcmp(item.name, "level"))
1456 frame.level = atoi(item.value);
1457 else if(!strcmp(item.name, "addr"))
1458 frame.addr = item.value;
1459 else if(!strcmp(item.name, "func"))
1460 frame.func = item.value;
1461 else if(!strcmp(item.name, "args"))
1463 if(!strcmp(item.value, "[]"))
1464 frame.argsCount = 0;
1467 item.value = StripBrackets(item.value);
1468 TokenizeList(item.value, ',', argsTokens);
1469 for(j = 0; j < argsTokens.count; j++)
1471 argsTokens[j] = StripCurlies(argsTokens[j]);
1472 TokenizeList(argsTokens[j], ',', argumentTokens);
1473 for(k = 0; k < argumentTokens.count; k++)
1476 frame.args.Add(arg);
1477 if(TokenizeListItem(argumentTokens[k], item))
1479 if(!strcmp(item.name, "name"))
1481 StripQuotes(item.value, item.value);
1482 arg.name = item.value;
1484 else if(!strcmp(item.name, "value"))
1486 StripQuotes(item.value, item.value);
1487 arg.val = item.value;
1490 _dpcl(_dpct, dplchan::gdbProtoUnknown, 0, "frame args item (", item.name, "=", item.value, ") is unheard of");
1493 _dplf(0, "Bad frame args item");
1495 argumentTokens.RemoveAll();
1497 frame.argsCount = argsTokens.count;
1498 argsTokens.RemoveAll();
1501 else if(!strcmp(item.name, "from"))
1502 frame.from = item.value;
1503 else if(!strcmp(item.name, "file"))
1504 frame.file = item.value;
1505 else if(!strcmp(item.name, "line"))
1506 frame.line = atoi(item.value);
1507 else if(!strcmp(item.name, "fullname"))
1509 // GDB 6.3 on OS X is giving "fullname" and "dir", all in absolute, but file name only in 'file'
1510 Workspace ws = ide.workspace;
1513 String path = ide.workspace.CopyUnixPathWorkspaceRelativeOrAbsolute(item.value);
1514 if(strcmp(frame.file, path))
1518 frame.absoluteFile = item.value;
1521 _dpcl(_dpct, dplchan::gdbProtoUnknown, 0, "frame member (", item.name, "=", item.value, ") is unheard of");
1524 _dplf(0, "Bad frame");
1529 delete argumentTokens;
1533 Breakpoint GetBreakpointById(int id, bool * isInternal)
1535 Breakpoint bp = null;
1536 //_dpcl(_dpct, dplchan::debuggerBreakpoints, 0, "Debugger::GetBreakpointById(", id, ")");
1538 *isInternal = false;
1541 for(i : sysBPs; i.bp && i.bp.id == id)
1548 if(!bp && bpRunToCursor && bpRunToCursor.bp && bpRunToCursor.bp.id == id)
1552 for(i : ide.workspace.breakpoints; i.bp && i.bp.id == id)
1562 GdbDataBreakpoint ParseBreakpoint(char * string, Array<char *> outTokens)
1565 GdbDataBreakpoint bp { };
1566 DebugListItem item { };
1567 Array<char *> bpTokens { minAllocSize = 16 };
1568 _dpcl(_dpct, dplchan::debuggerCall, 0, "Debugger::ParseBreakpoint()");
1569 string = StripCurlies(string);
1570 TokenizeList(string, ',', bpTokens);
1571 for(i = 0; i < bpTokens.count; i++)
1573 if(TokenizeListItem(bpTokens[i], item))
1575 StripQuotes(item.value, item.value);
1576 if(!strcmp(item.name, "number"))
1578 if(!strchr(item.value, '.'))
1579 bp.id = atoi(item.value);
1580 bp.number = item.value;
1582 else if(!strcmp(item.name, "type"))
1583 bp.type = item.value;
1584 else if(!strcmp(item.name, "disp"))
1585 bp.disp = item.value;
1586 else if(!strcmp(item.name, "enabled"))
1587 bp.enabled = (!strcmpi(item.value, "y"));
1588 else if(!strcmp(item.name, "addr"))
1590 if(outTokens && !strcmp(item.value, "<MULTIPLE>"))
1593 Array<GdbDataBreakpoint> bpArray = bp.multipleBPs = { };
1594 while(outTokens.count > ++c)
1596 GdbDataBreakpoint multBp = ParseBreakpoint(outTokens[c], null);
1597 bpArray.Add(multBp);
1601 bp.addr = item.value;
1603 else if(!strcmp(item.name, "func"))
1604 bp.func = item.value;
1605 else if(!strcmp(item.name, "file"))
1606 bp.file = item.value;
1607 else if(!strcmp(item.name, "fullname"))
1608 bp.fullname = item.value;
1609 else if(!strcmp(item.name, "line"))
1610 bp.line = atoi(item.value);
1611 else if(!strcmp(item.name, "at"))
1613 else if(!strcmp(item.name, "times"))
1614 bp.times = atoi(item.value);
1615 else if(!strcmp(item.name, "original-location") || !strcmp(item.name, "thread-groups"))
1616 _dpcl(_dpct, dplchan::gdbProtoIgnored, 0, "breakpoint member (", item.name, "=", item.value, ") is ignored");
1618 _dpcl(_dpct, dplchan::gdbProtoUnknown, 0, "breakpoint member (", item.name, "=", item.value, ") is unheard of");
1626 void ShowDebuggerViews()
1628 //_dpcl(_dpct, dplchan::debuggerCall, 0, "Debugger::ShowDebuggerViews()");
1629 ide.outputView.Show();
1630 ide.outputView.SelectTab(debug);
1631 ide.threadsView.Show();
1632 ide.callStackView.Show();
1633 ide.watchesView.Show();
1637 void HideDebuggerViews()
1639 //_dpcl(_dpct, dplchan::debuggerCall, 0, "Debugger::HideDebuggerViews()");
1640 ide.RepositionWindows(true);
1643 bool ::GdbCommand(Time timeOut, bool focus, const char * format, ...)
1645 bool result = false;
1649 // TODO: Improve this limit
1650 static char string[MAX_F_STRING*4];
1652 va_start(args, format);
1653 vsnprintf(string, sizeof(string), format, args);
1654 string[sizeof(string)-1] = 0;
1658 ide.debugger.serialSemaphore.TryWait();
1660 #ifdef GDB_DEBUG_CONSOLE
1661 _dpcl(_dpct, dplchan::gdbCommand, 0, string);
1663 #ifdef GDB_DEBUG_OUTPUT
1664 ide.outputView.gdbBox.Logf("cmd: %s\n", string);
1666 #ifdef GDB_DEBUG_GUI
1668 ide.gdbDialog.AddCommand(string);
1671 strcat(string,"\n");
1672 gdbHandle.Puts(string);
1675 Process_ShowWindows(targetProcessId);
1681 startTime = GetTime();
1684 if(ide.debugger.serialSemaphore.TryWait())
1691 if(GetTime() - startTime > timeOut)
1699 ide.debugger.serialSemaphore.Wait();
1708 bool ValidateBreakpoint(Breakpoint bp)
1710 _dpcl(_dpct, dplchan::debuggerCall, 0, "Debugger::ValidateBreakpoint()");
1711 if(modules && bp.line && bp.bp)
1713 if(bp.bp.line != bp.line)
1719 ide.outputView.debugBox.Logf("WOULD HAVE -- Invalid breakpoint disabled: %s:%d\n", bp.relativeFilePath, bp.line);
1721 //UnsetBreakpoint(bp);
1722 //bp.enabled = false;
1728 ide.outputView.debugBox.Logf("Debugger Error: ValidateBreakpoint error\n");
1729 bp.line = bp.bp.line;
1736 void BreakpointsMaintenance()
1738 //_dpcl(_dpct, dplchan::debuggerBreakpoints, 0, "Debugger::BreakpointsMaintenance()");
1741 if(gdbExecution.suspendInternalBreakpoints)
1743 for(bp : sysBPs; bp.inserted)
1744 UnsetBreakpoint(bp);
1748 DirExpression objDir = ide.project.GetObjDir(currentCompiler, prjConfig, bitDepth);
1749 for(bp : sysBPs; !bp.inserted)
1751 bool insert = false;
1752 if(bp.type == internalModulesLoaded)
1754 char path[MAX_LOCATION];
1755 char name[MAX_LOCATION];
1756 char fixedModuleName[MAX_FILENAME];
1759 bool moduleLoadBlock = false;
1761 ReplaceSpaces(fixedModuleName, ide.project.moduleName);
1762 snprintf(name, sizeof(name),"%s.main.ec", fixedModuleName);
1763 name[sizeof(name)-1] = 0;
1764 strcpy(path, ide.workspace.projectDir);
1765 PathCatSlash(path, objDir.dir);
1766 PathCatSlash(path, name);
1767 f = FileOpen(path, read);
1770 for(lineNumber = 1; !f.Eof(); lineNumber++)
1772 if(f.GetLine(line, sizeof(line) - 1))
1774 bool moduleLoadLine;
1775 TrimLSpaces(line, line);
1776 moduleLoadLine = !strncmp(line, "eModule_Load", strlen("eModule_Load"));
1777 if(!moduleLoadBlock && moduleLoadLine)
1778 moduleLoadBlock = true;
1779 else if(moduleLoadBlock && !moduleLoadLine && strlen(line) > 0)
1785 char relative[MAX_LOCATION];
1786 bp.absoluteFilePath = path;
1787 MakePathRelative(path, ide.workspace.projectDir, relative);
1788 bp.relativeFilePath = relative;
1789 bp.line = lineNumber;
1795 else if(bp.type == internalModuleLoad)
1799 for(prj : ide.workspace.projects)
1801 if(!strcmp(prj.moduleName, "ecere"))
1803 ProjectNode node = prj.topNode.Find("instance.c", false);
1806 char path[MAX_LOCATION];
1807 char relative[MAX_LOCATION];
1808 node.GetFullFilePath(path);
1809 bp.absoluteFilePath = path;
1810 MakePathRelative(path, prj.topNode.path, relative);
1811 bp.relativeFilePath = relative;
1823 if(!SetBreakpoint(bp, false))
1824 SetBreakpoint(bp, true);
1830 if(userAction != runToCursor && bpRunToCursor && bpRunToCursor.inserted)
1831 UnsetBreakpoint(bpRunToCursor);
1832 if(bpRunToCursor && !bpRunToCursor.inserted)
1834 if(!SetBreakpoint(bpRunToCursor, false))
1835 SetBreakpoint(bpRunToCursor, true);
1838 if(ignoreBreakpoints)
1840 for(bp : ide.workspace.breakpoints; bp.inserted)
1841 UnsetBreakpoint(bp);
1845 for(bp : ide.workspace.breakpoints; !bp.inserted && bp.type == user)
1849 if(!SetBreakpoint(bp, false))
1850 SetBreakpoint(bp, true);
1856 _dplf(0, "problem");
1859 bp.bp = GdbDataBreakpoint { };
1866 void UnsetBreakpoint(Breakpoint bp)
1868 char * s = null; _dpcl(_dpct, dplchan::debuggerBreakpoints, 0, "Debugger::UnsetBreakpoint(", s=bp.CopyLocationString(false), ") -- ", bp.type); delete s;
1869 if(symbols && bp.inserted)
1871 GdbCommand(0, false, "-break-delete %s", bp.bp.number);
1872 bp.inserted = false;
1878 bool SetBreakpoint(Breakpoint bp, bool removePath)
1880 char * s = null; _dpcl(_dpct, dplchan::debuggerBreakpoints, 0, "Debugger::SetBreakpoint(", s=bp.CopyLocationString(false), ", ", removePath ? "**** removePath(true) ****" : "", ") -- ", bp.type); delete s;
1881 breakpointError = false;
1882 if(symbols && bp.enabled && (!bp.project || bp.project.GetTargetType(bp.project.config) == staticLibrary || bp.project == ide.project || projectsLibraryLoaded[bp.project.name]))
1884 sentBreakInsert = true;
1886 GdbCommand(0, false, "-break-insert *%s", bp.address);
1889 char * location = bp.CopyLocationString(removePath);
1890 GdbCommand(0, false, "-break-insert %s", location);
1893 if(!breakpointError)
1895 char * address = null;
1896 if(bpItem && bpItem.multipleBPs && bpItem.multipleBPs.count)
1899 GdbDataBreakpoint first = null;
1900 for(n : bpItem.multipleBPs)
1902 if(!fstrcmp(n.fullname, bp.absoluteFilePath) && !first)
1912 GdbCommand(0, false, "-break-disable %s", n.number);
1916 _dpcl(_dpct, dplchan::debuggerProblem, 0, "Debugger::SetBreakpoint -- error breakpoint already disabled.");
1921 address = CopyString(first.addr);
1922 bpItem.addr = first.addr;
1923 bpItem.func = first.func;
1924 bpItem.file = first.file;
1925 bpItem.fullname = first.fullname;
1926 bpItem.line = first.line;
1927 //bpItem.thread-groups = first.thread-groups;*/
1930 _dpcl(_dpct, dplchan::debuggerProblem, 0, "Debugger::SetBreakpoint -- error multiple breakpoints all disabled.");
1932 _dpcl(_dpct, dplchan::debuggerProblem, 0, "Debugger::SetBreakpoint -- error multiple breakpoints in exact same file not supported.");
1933 bpItem.multipleBPs.Free();
1934 delete bpItem.multipleBPs;
1939 bp.inserted = (bp.bp && bp.bp.number && strcmp(bp.bp.number, "0"));
1941 ValidateBreakpoint(bp);
1945 UnsetBreakpoint(bp);
1946 bp.address = address;
1948 SetBreakpoint(bp, removePath);
1951 return !breakpointError;
1958 _dpcl(_dpct, dplchan::debuggerCall, 0, "Debugger::GdbGetStack()");
1960 stackFrames.Free(Frame::Free);
1961 GdbCommand(0, false, "-stack-info-depth");
1963 GdbCommand(0, false, "-stack-info-depth 192");
1964 if(frameCount && frameCount <= 192)
1965 GdbCommand(0, false, "-stack-list-frames 0 %d", Min(frameCount-1, 191));
1968 GdbCommand(0, false, "-stack-list-frames 0 %d", Min(frameCount-1, 95));
1969 GdbCommand(0, false, "-stack-list-frames %d %d", Max(frameCount - 96, 96), frameCount - 1);
1971 GdbCommand(0, false, "");
1976 _dpcl(_dpct, dplchan::debuggerCall, 0, "Debugger::GdbTargetSet()");
1979 char escaped[MAX_LOCATION];
1980 strescpy(escaped, targetFile);
1981 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
1988 const char *vgdbCommand = "/usr/bin/vgdb"; // TODO: vgdb command config option
1989 //GdbCommand(0, false, "-target-select remote | %s --pid=%d", "vgdb", targetProcessId);
1990 printf("target remote | %s --pid=%d\n", vgdbCommand, targetProcessId);
1991 GdbCommand(0, false, "target remote | %s --pid=%d", vgdbCommand, targetProcessId); // TODO: vgdb command config option
1994 GdbCommand(0, false, "info target"); //GDB/MI Missing Implementation -file-list-symbol-files and -file-list-exec-sections
1996 /*for(prj : ide.workspace.projects; prj != ide.workspace.projects.firstIterator.data)
1997 GdbCommand(0, false, "-environment-directory \"%s\"", prj.topNode.path);*/
1999 for(dir : ide.workspace.sourceDirs; dir && dir[0])
2001 bool interference = false;
2002 for(prj : ide.workspace.projects)
2004 if(!fstrcmp(prj.topNode.path, dir))
2006 interference = true;
2010 if(!interference && dir[0])
2011 GdbCommand(0, false, "-environment-directory \"%s\"", dir);
2019 /*void GdbTargetRelease()
2023 BreakpointsDeleteAll();
2024 GdbCommand(0, false, "file"); //GDB/MI Missing Implementation -target-detach
2030 void GdbDebugBreak(bool internal)
2032 _dpcl(_dpct, dplchan::debuggerCall, 0, "Debugger::GdbDebugBreak()");
2036 breakType = DebuggerAction::internal;
2038 if(ide) ide.Update(null);
2040 if(Process_Break(targetProcessId)) //GdbCommand(0, false, "-exec-interrupt");
2041 serialSemaphore.Wait();
2044 _ChangeState(loaded);
2045 targetProcessId = 0;
2050 ide.outputView.debugBox.Logf("Debugger Error: GdbDebugBreak with not target id should never happen\n");
2055 _dpcl(_dpct, dplchan::debuggerCall, 0, "Debugger::GdbExecRun()");
2060 ShowDebuggerViews();
2062 GdbExecContinue(true);
2063 else if(!GdbCommand(3, true, "-exec-run"))
2064 gdbExecution = none;
2067 void GdbExecContinue(bool focus)
2069 _dpcl(_dpct, dplchan::debuggerCall, 0, "Debugger::GdbExecContinue()");
2072 GdbCommand(0, focus, "-exec-continue");
2077 _dpcl(_dpct, dplchan::debuggerCall, 0, "Debugger::GdbExecNext()");
2078 gdbExecution = next;
2080 GdbCommand(0, true, "-exec-next");
2083 void ForceUpdateCurrentFrame()
2086 GdbCommand(0, false, "-thread-list-ids");
2087 InternalSelectFrame(activeFrameLevel);
2088 GoToStackFrameLine(activeFrameLevel, true, false);
2090 ide.ShowCodeEditor();
2091 ide.AdjustDebugMenus();
2092 ideMainFrame.Activate(); // TOFIX: ide.Activate() is not reliable (app inactive)
2096 void GdbExecUntil(const char * absoluteFilePath, int lineNumber)
2098 bool forceUpdate = false;
2099 char relativeFilePath[MAX_LOCATION];
2100 _dpcl(_dpct, dplchan::debuggerCall, 0, "Debugger::GdbExecUntil()");
2101 gdbExecution = until;
2103 if(absoluteFilePath)
2105 const char * objectFileExt = currentCompiler ? currentCompiler.objectFileExt : objectDefaultFileExt;
2106 ide.workspace.GetRelativePath(absoluteFilePath, relativeFilePath, null, objectFileExt);
2107 if(!GdbCommand(0.1, true, "-exec-until %s:%d", relativeFilePath, lineNumber))
2109 GetLastDirectory(relativeFilePath, relativeFilePath);
2110 if(GdbCommand(1, true, "-exec-until %s:%d", relativeFilePath, lineNumber))
2115 GdbCommand(0, true, "-exec-until");
2117 // This is to handle GDB 6.3 on OS X not giving us *running then *stopped:
2118 // (It may not be ideal, we may need to wait?)
2120 ForceUpdateCurrentFrame();
2123 void GdbExecAdvance(const char * absoluteFilePathOrLocation, int lineNumber)
2125 bool forceUpdate = false;
2126 char relativeFilePath[MAX_LOCATION];
2127 _dpcl(_dpct, dplchan::debuggerCall, 0, "Debugger::GdbExecAdvance()");
2128 gdbExecution = advance;
2132 const char * objectFileExt = currentCompiler ? currentCompiler.objectFileExt : objectDefaultFileExt;
2133 ide.workspace.GetRelativePath(absoluteFilePathOrLocation, relativeFilePath, null, objectFileExt);
2134 if(!GdbCommand(0.1, true, "advance %s:%d", relativeFilePath, lineNumber)) // should use -exec-advance -- GDB/MI implementation missing
2136 GetLastDirectory(relativeFilePath, relativeFilePath);
2137 if(GdbCommand(1, true, "advance %s:%d", relativeFilePath, lineNumber))
2143 if(!GdbCommand(0.1, true, "advance %s", absoluteFilePathOrLocation)) // should use -exec-advance -- GDB/MI implementation missing
2145 GetLastDirectory(absoluteFilePathOrLocation, relativeFilePath);
2146 if(GdbCommand(1, true, "advance %s", relativeFilePath))
2151 // This is to handle GDB 6.3 on OS X not giving us *running then *stopped:
2152 // (It may not be ideal, we may need to wait?)
2154 ForceUpdateCurrentFrame();
2159 _dpcl(_dpct, dplchan::debuggerCall, 0, "Debugger::GdbExecStep()");
2160 gdbExecution = step;
2162 GdbCommand(0, true, "-exec-step");
2165 void GdbExecFinish()
2167 _dpcl(_dpct, dplchan::debuggerCall, 0, "Debugger::GdbExecFinish()");
2168 gdbExecution = finish;
2170 GdbCommand(0, true, "-exec-finish");
2173 void GdbExecCommon()
2175 //_dpcl(_dpct, dplchan::debuggerCall, 0, "Debugger::GdbExecCommon()");
2176 BreakpointsMaintenance();
2179 #ifdef GDB_DEBUG_GUI
2180 void SendGDBCommand(const char * command)
2182 //_dpcl(_dpct, dplchan::debuggerCall, 0, "Debugger::SendGDBCommand()");
2183 DebuggerState oldState = state;
2188 GdbDebugBreak(true);
2191 GdbCommand(0, false, command);
2194 if(oldState == running)
2195 GdbExecContinue(false);
2199 void ClearBreakDisplay()
2201 //_dpcl(_dpct, dplchan::debuggerCall, 0, "Debugger::ClearBreakDisplay()");
2203 activeFrameLevel = -1;
2213 stackFrames.Free(Frame::Free);
2214 ide.callStackView.Clear();
2215 ide.threadsView.Clear();
2221 _dpcl(_dpct, dplchan::debuggerCall, 0, "Debugger::GdbAbortExec()");
2223 GdbCommand(0, false, "-interpreter-exec console \"kill\""); // should use -exec-abort -- GDB/MI implementation incomplete
2227 bool GdbInit(CompilerConfig compiler, ProjectConfig config, int bitDepth, bool useValgrind)
2230 char oldDirectory[MAX_LOCATION];
2231 char tempPath[MAX_LOCATION];
2232 char command[MAX_F_STRING*4];
2233 Project project = ide.project;
2234 DirExpression targetDirExp = project.GetTargetDir(compiler, config, bitDepth);
2235 PathBackup pathBackup { };
2236 Map<String, String> envBackup { };
2238 _dpcl(_dpct, dplchan::debuggerCall, 0, "Debugger::GdbInit()");
2239 if(currentCompiler != compiler)
2241 delete currentCompiler;
2242 currentCompiler = compiler;
2243 incref currentCompiler;
2246 this.bitDepth = bitDepth;
2247 usingValgrind = useValgrind;
2249 _ChangeState(loaded);
2251 sentBreakInsert = false;
2252 breakpointError = false;
2253 ignoreBreakpoints = false;
2259 projectsLibraryLoaded.Free();
2261 ide.outputView.ShowClearSelectTab(debug);
2262 ide.outputView.debugBox.Logf($"Starting debug mode\n");
2264 #ifdef GDB_DEBUG_OUTPUT
2265 ide.outputView.gdbBox.Logf("run: Starting GDB\n");
2268 strcpy(tempPath, ide.workspace.projectDir);
2269 PathCatSlash(tempPath, targetDirExp.dir);
2271 targetDir = CopyString(tempPath);
2272 project.CatTargetFileName(tempPath, compiler, config);
2274 targetFile = CopyString(tempPath);
2276 GetWorkingDir(oldDirectory, MAX_LOCATION);
2277 if(ide.workspace.debugDir && ide.workspace.debugDir[0])
2279 char temp[MAX_LOCATION];
2280 strcpy(temp, ide.workspace.projectDir);
2281 PathCatSlash(temp, ide.workspace.debugDir);
2282 ChangeWorkingDir(temp);
2285 ChangeWorkingDir(ide.workspace.projectDir);
2287 ide.SetPath(true, compiler, config, bitDepth);
2289 // TODO: This pollutes the environment, but at least it works
2290 // It shouldn't really affect the IDE as the PATH gets restored and other variables set for testing will unlikely cause problems
2291 // What is the proper solution for this? DualPipeOpenEnv?
2292 // gdb set environment commands don't seem to take effect
2293 for(e : ide.workspace.environmentVars)
2295 // Backing up the environment variables until we use DualPipeOpenEnv()
2296 envBackup[e.name] = CopyString(getenv(e.name));
2297 SetEnvironment(e.name, e.string);
2302 char * clArgs = ide.workspace.commandLineArgs;
2303 const char *valgrindCommand = "valgrind"; // TODO: valgrind command config option //TODO: valgrind options
2304 ValgrindLeakCheck vgLeakCheck = ide.workspace.vgLeakCheck;
2305 int vgRedzoneSize = ide.workspace.vgRedzoneSize;
2306 bool vgTrackOrigins = ide.workspace.vgTrackOrigins;
2307 vgLogFile = CreateTemporaryFile(vgLogPath, "ecereidevglog");
2311 vgLogThread.Create();
2315 ide.outputView.debugBox.Logf($"Debugger Fatal Error: Couldn't open temporary log file for Valgrind output\n");
2318 if(result && !CheckCommandAvailable(valgrindCommand))
2320 ide.outputView.debugBox.Logf($"Debugger Fatal Error: Command %s for Valgrind is not available.\n", valgrindCommand);
2325 char * vgRedzoneSizeFlag = PrintString(" --redzone-size=", vgRedzoneSize);
2326 sprintf(command, "%s --vgdb=yes --vgdb-error=0 --log-file=%s --leak-check=%s%s --track-origins=%s %s%s%s",
2327 valgrindCommand, vgLogPath, (char*)vgLeakCheck, vgRedzoneSize > -1 ? vgRedzoneSizeFlag : "", vgTrackOrigins ? "yes" : "no", targetFile, clArgs ? " " : "", clArgs ? clArgs : "");
2328 delete vgRedzoneSizeFlag;
2329 vgTargetHandle = DualPipeOpen(PipeOpenMode { output = true, /*error = true, */input = true }, command);
2332 ide.outputView.debugBox.Logf($"Debugger Fatal Error: Couldn't start Valgrind\n");
2338 incref vgTargetHandle;
2339 vgTargetThread.Create();
2341 targetProcessId = vgTargetHandle.GetProcessID();
2342 waitingForPID = false;
2343 if(!targetProcessId)
2345 ide.outputView.debugBox.Logf($"Debugger Fatal Error: Couldn't get Valgrind process ID\n");
2352 serialSemaphore.Wait();
2359 if(compiler.targetPlatform == win32)
2362 #if !((defined(__WORDSIZE) && __WORDSIZE == 8) || defined(__x86_64__))
2365 bitDepth == 32 ? "i686-w64-mingw32-gdb" : "gdb"); // x86_64-w64-mingw32-gdb
2368 // We really should have a box to select GDB in the compiler/toolchain options
2369 strcpy(command, "gdb");
2370 if(!CheckCommandAvailable(command))
2372 ide.outputView.debugBox.Logf($"Debugger Fatal Error: Command %s for GDB is not available.\n", command);
2377 strcat(command, " -n -silent --interpreter=mi2"); //-async //\"%s\"
2379 gdbHandle = DualPipeOpen(PipeOpenMode { output = true, /*error = true, */input = true }, command);
2382 ide.outputView.debugBox.Logf($"Debugger Fatal Error: Couldn't start GDB\n");
2392 gdbProcessId = gdbHandle.GetProcessID();
2395 ide.outputView.debugBox.Logf($"Debugger Fatal Error: Couldn't get GDB process ID\n");
2402 serialSemaphore.Wait();
2405 GdbCommand(0, false, "-gdb-set verbose off");
2406 //GdbCommand(0, false, "-gdb-set exec-done-display on");
2407 GdbCommand(0, false, "-gdb-set step-mode off");
2408 GdbCommand(0, false, "-gdb-set unwindonsignal on");
2409 //GdbCommand(0, false, "-gdb-set shell on");
2410 GdbCommand(0, false, "set print elements 992");
2411 GdbCommand(0, false, "-gdb-set backtrace limit 100000");
2415 //_ChangeState(terminated);
2421 #if defined(__unix__)
2423 CreateTemporaryDir(progFifoDir, "ecereide");
2424 strcpy(progFifoPath, progFifoDir);
2425 PathCat(progFifoPath, "ideprogfifo");
2426 if(!mkfifo(progFifoPath, 0600))
2428 //fileCreated = true;
2433 ide.outputView.debugBox.Logf(createFIFOMsg, progFifoPath);
2440 progThread.terminate = false;
2441 progThread.Create();
2445 #if defined(__WIN32__)
2446 GdbCommand(0, false, "-gdb-set new-console on");
2449 #if defined(__unix__)
2451 GdbCommand(0, false, "-inferior-tty-set %s", progFifoPath);
2455 GdbCommand(0, false, "-gdb-set args %s", ide.workspace.commandLineArgs ? ide.workspace.commandLineArgs : "");
2457 for(e : ide.workspace.environmentVars)
2459 GdbCommand(0, false, "set environment %s=%s", e.name, e.string);
2464 ChangeWorkingDir(oldDirectory);
2468 SetEnvironment(&e, e);
2477 delete targetDirExp;
2483 _dpcl(_dpct, dplchan::debuggerCall, 0, "Debugger::GdbExit()");
2484 if(gdbHandle && gdbProcessId)
2487 GdbCommand(0, false, "-gdb-exit");
2496 vgLogFile.CloseInput();
2497 if(vgLogThread.created)
2507 vgTargetThread.Wait();
2517 _ChangeState(terminated); // this state change seems to be superfluous, is it safety for something?
2522 for(bp : ide.workspace.breakpoints)
2528 bpRunToCursor.Reset();
2530 ide.outputView.debugBox.Logf($"Debugging stopped\n");
2532 #if defined(__unix__)
2533 if(!usingValgrind && FileExists(progFifoPath)) //fileCreated)
2535 progThread.terminate = true;
2538 fifoFile.CloseInput();
2544 DeleteFile(progFifoPath);
2545 progFifoPath[0] = '\0';
2554 bool WatchesLinkCodeEditor()
2556 bool goodFrame = activeFrame && activeFrame.absoluteFile;
2557 //_dpcl(_dpct, dplchan::debuggerCall, 0, "Debugger::WatchesLinkCodeEditor()");
2558 if(codeEditor && (!goodFrame || fstrcmp(codeEditor.fileName, activeFrame.absoluteFile)))
2559 WatchesReleaseCodeEditor();
2561 if(!codeEditor && goodFrame)
2563 codeEditor = (CodeEditor)ide.OpenFile(activeFrame.absoluteFile, false, false, null, no, normal, false);
2566 codeEditor.inUseDebug = true;
2570 return codeEditor != null;
2573 void WatchesReleaseCodeEditor()
2575 //_dpcl(_dpct, dplchan::debuggerCall, 0, "Debugger::WatchesReleaseCodeEditor()");
2578 codeEditor.inUseDebug = false;
2579 if(!codeEditor.visible)
2580 codeEditor.Destroy(0);
2585 bool ResolveWatch(Watch wh)
2587 bool result = false;
2589 _dpcl(_dpct, dplchan::debuggerWatches, 0, "Debugger::ResolveWatch()");
2601 char watchmsg[MAX_F_STRING];
2603 if(state == stopped && !codeEditor)
2604 wh.value = CopyString($"No source file found for selected frame");
2605 //if(codeEditor && state == stopped || state != stopped)
2608 Module backupPrivateModule;
2609 Context backupContext;
2610 Class backupThisClass;
2613 backupPrivateModule = GetPrivateModule();
2614 backupContext = GetCurrentContext();
2615 backupThisClass = GetThisClass();
2618 SetPrivateModule(codeEditor.privateModule);
2619 SetCurrentContext(codeEditor.globalContext);
2620 SetTopContext(codeEditor.globalContext);
2621 SetGlobalContext(codeEditor.globalContext);
2622 SetGlobalData(&codeEditor.globalData);
2625 exp = ParseExpressionString(wh.expression);
2627 if(exp && !GetParseError())
2629 char expString[4096];
2631 PrintExpression(exp, expString);
2633 SetInDebugger(true);
2636 // NOTE: DebugFindCtxTree() should be called only once for evaluating all watches in the watch window
2637 if(codeEditor && activeFrame)
2638 DebugFindCtxTree(codeEditor.ast, activeFrame.line, 0);
2639 ProcessExpressionType(exp);
2641 wh.type = exp.expType;
2644 DebugComputeExpression(exp);
2645 // e.g. Meters * Degrees has no type set yet for some reason
2646 if(!wh.type && exp.expType)
2648 wh.type = exp.expType;
2649 exp.expType.refCount++;
2652 // This makes Degrees { 45 } work
2653 if(exp.type == constantExp && exp.isConstant && exp.expType && exp.expType.kind == classType &&
2654 exp.expType._class && exp.expType._class.registered && exp.expType._class.registered.type == unitClass && exp.expType._class.registered.base.type == unitClass)
2656 ApplyUnitConverters(exp);
2658 else if(exp.type == instanceExp && exp.instance.data)
2660 Symbol s = exp.instance._class ? exp.instance._class.symbol : null;
2661 Class c = s ? s.registered : null;
2665 bool needClass = false;
2666 char * s = ((char * (*)(void *, void *, void *, void *, void *))(void *)c._vTbl[__ecereVMethodID_class_OnGetString])(c, exp.instance.data, tmp, null, &needClass);
2669 FreeExpContents(exp);
2670 exp.type = constantExp;
2671 exp.isConstant = true;
2672 exp.constant = CopyString(s);
2676 else if(exp.expType && exp.expType.kind == classType && exp.expType._class && exp.expType._class.registered && exp.expType._class.registered.type == bitClass)
2678 Class c = exp.expType._class.registered;
2680 bool needClass = false;
2681 Operand op = GetOperand(exp);
2683 char * (* onGetString)(void *, void *, void *, void *, void *) = (void *)c._vTbl[__ecereVMethodID_class_OnGetString];
2686 if(op.type) op.type.refCount++;
2689 case charType: s = onGetString(c, &op.c, tmp, null, &needClass); break;
2690 case shortType: s = onGetString(c, &op.s, tmp, null, &needClass); break;
2691 case intType: s = onGetString(c, &op.i, tmp, null, &needClass); break;
2692 case int64Type: s = onGetString(c, &op.i64, tmp, null, &needClass); break;
2697 FreeExpContents(exp);
2698 exp.type = constantExp;
2699 exp.isConstant = true;
2700 exp.constant = CopyString(s);
2704 else if(exp.expType && exp.expType.kind == classType && exp.expType._class && exp.expType._class.registered && exp.expType._class.registered.type == structClass && exp.hasAddress)
2706 Class c = exp.expType._class.registered;
2707 char structString[1024];
2708 strcpy(structString, "*(struct ");
2709 FullClassNameCat(structString, c.fullName, false);
2710 strcat(structString, " *)");
2711 strcatf(structString, "0x%p", exp.address);
2712 GDBFallBack(exp, structString);
2714 byte * data = GdbReadMemory(exp.address, c.structSize);
2718 bool needClass = false;
2719 char * s = ((char * (*)(void *, void *, void *, void *, void *))(void *)c._vTbl[__ecereVMethodID_class_OnGetString])(c, data, tmp, null, &needClass);
2722 FreeExpContents(exp);
2723 exp.type = constantExp;
2724 exp.isConstant = true;
2725 exp.constant = CopyString(s);
2732 if(ExpressionIsError(exp) && exp.type != functionCallErrorExp)
2734 GDBFallBack(exp, expString);
2737 /*if(exp.hasAddress)
2739 char temp[MAX_F_STRING];
2740 sprintf(temp, "0x%x", exp.address);
2741 wh.address = CopyString(temp);
2742 // wh.address = CopyStringf("0x%x", exp.address);
2747 Type dataType = exp.expType;
2750 char temp[MAX_F_STRING];
2751 switch(dataType.kind)
2754 sprintf(temp, "%i", exp.val.c);
2757 sprintf(temp, "%i", exp.val.s);
2762 sprintf(temp, "%i", exp.val.i);
2765 sprintf(temp, "%i", exp.val.i64);
2768 sprintf(temp, "%i", exp.val.p);
2773 long v = (long)exp.val.f;
2774 sprintf(temp, "%i", v);
2779 long v = (long)exp.val.d;
2780 sprintf(temp, "%i", v);
2785 wh.intVal = CopyString(temp);
2786 switch(dataType.kind)
2789 sprintf(temp, "0x%x", exp.val.c);
2792 sprintf(temp, "0x%x", exp.val.s);
2796 sprintf(temp, "0x%x", exp.val.i);
2799 sprintf(temp, "0x%x", exp.val.i64);
2802 sprintf(temp, "0x%x", exp.val.i64);
2805 sprintf(temp, "0x%x", exp.val.p);
2810 long v = (long)exp.val.f;
2811 sprintf(temp, "0x%x", v);
2816 long v = (long)exp.val.d;
2817 sprintf(temp, "0x%x", v);
2822 wh.hexVal = CopyString(temp);
2823 switch(dataType.kind)
2826 sprintf(temp, "0o%o", exp.val.c);
2829 sprintf(temp, "0o%o", exp.val.s);
2833 sprintf(temp, "0o%o", exp.val.i);
2836 sprintf(temp, "0o%o", exp.val.i64);
2839 sprintf(temp, "0o%o", exp.val.i64);
2842 sprintf(temp, "0o%o", exp.val.p);
2847 long v = (long)exp.val.f;
2848 sprintf(temp, "0o%o", v);
2853 long v = (long)exp.val.d;
2854 sprintf(temp, "0o%o", v);
2859 wh.octVal = CopyString(temp);
2862 // WHATS THIS HERE ?
2863 if(exp.type == constantExp && exp.constant)
2864 wh.constant = CopyString(exp.constant);
2870 case symbolErrorExp:
2871 snprintf(watchmsg, sizeof(watchmsg), $"Symbol \"%s\" not found", exp.identifier.string);
2873 case memberSymbolErrorExp:
2875 Expression memberExp = exp.member.exp;
2876 Identifier memberID = exp.member.member;
2877 Type type = memberExp.expType;
2880 if(type.kind == structType || type.kind == unionType)
2882 char string[1024] = "";
2884 PrintTypeNoConst(type, string, false, true);
2885 snprintf(watchmsg, sizeof(watchmsg), $"Member \"%s\" not found in %s \"%s\"",
2886 memberID ? memberID.string : "", type.kind == unionType ? "union" : "struct", type.name ? type.name : string);
2890 Class _class = (memberID && memberID.classSym) ? memberID.classSym.registered : ((type.kind == classType && type._class) ? type._class.registered : null);
2891 char string[1024] = "";
2895 PrintTypeNoConst(type, string, false, true);
2896 classSym = FindClass(string);
2897 _class = classSym ? classSym.registered : null;
2900 snprintf(watchmsg, sizeof(watchmsg), $"Member \"%s\" not found in class \"%s\"", memberID ? memberID.string : "", _class.name);
2902 // NOTE: This should probably never happen, only classes and struct can be dereferenced, a dereferenceErrorExp should be displayed instead
2903 snprintf(watchmsg, sizeof(watchmsg), $"Member \"%s\" not found in type \"%s\"", memberID ? memberID.string : "", string);
2907 // NOTE: This should probably never happen, the error causing the unresolved expression should be displayed instead
2908 snprintf(watchmsg, sizeof(watchmsg), $"Accessing member \"%s\" from unresolved expression", memberID ? memberID.string : "");
2911 case memberPropertyErrorExp:
2913 Expression memberExp = exp.member.exp;
2914 Identifier memberID = exp.member.member;
2915 Type type = memberExp.expType;
2916 Class _class = (type && memberID) ? (memberID && memberID.classSym) ? memberID.classSym.registered : ((type.kind == classType && type._class) ? type._class.registered : null) : null;
2917 if(_class && memberID && memberID.string)
2918 snprintf(watchmsg, sizeof(watchmsg), $"Missing property evaluation for \"%s\" in class \"%s\"", memberID.string, _class.name);
2920 snprintf(watchmsg, sizeof(watchmsg), $"Missing property evaluation for \"%s\"", wh.expression);
2923 case functionCallErrorExp:
2924 if(exp.call.exp && exp.call.exp.type == identifierExp && exp.call.exp.identifier.string)
2925 snprintf(watchmsg, sizeof(watchmsg), $"Missing function evaluation for call to \"%s\"", exp.call.exp.identifier.string);
2927 snprintf(watchmsg, sizeof(watchmsg), $"Missing function evaluation for \"%s\"", wh.expression);
2929 case memoryErrorExp:
2930 // Need to ensure when set to memoryErrorExp, constant is set
2931 snprintf(watchmsg, sizeof(watchmsg), $"Memory can't be read at %s", /*(exp.type == constantExp) ? */exp.constant /*: null*/);
2933 case dereferenceErrorExp:
2934 snprintf(watchmsg, sizeof(watchmsg), $"Dereferencing error evaluating \"%s\"", wh.expression);
2936 case divideBy0ErrorExp:
2937 snprintf(watchmsg, sizeof(watchmsg), "%s", $"Integer division by 0");
2939 case noDebuggerErrorExp:
2940 snprintf(watchmsg, sizeof(watchmsg), $"Debugger required for symbol evaluation in \"%s\"", wh.expression);
2942 case unknownErrorExp:
2943 // NOTE: This should never happen
2944 snprintf(watchmsg, sizeof(watchmsg), $"Error evaluating \"%s\"", wh.expression);
2947 // NOTE: This should never happen
2948 snprintf(watchmsg, sizeof(watchmsg), $"Null type for \"%s\"", wh.expression);
2951 wh.value = CopyString(exp.string);
2954 // Temporary Code for displaying Strings
2955 if((exp.expType && ((exp.expType.kind == pointerType ||
2956 exp.expType.kind == arrayType) && exp.expType.type.kind == charType)) ||
2957 (wh.type && wh.type.kind == classType && wh.type._class &&
2958 wh.type._class.registered && wh.type._class.registered.type == normalClass &&
2959 !strcmp(wh.type._class.registered.name, "String")))
2962 if(exp.expType && (exp.expType.kind != arrayType || exp.hasAddress))
2966 //char temp[MAX_F_STRING * 32];
2968 //ExpressionType evalError = dummyExp;
2969 /*if(exp.expType.kind == arrayType)
2970 sprintf(temp, "(char*)0x%x", exp.address);
2972 sprintf(temp, "(char*)%s", exp.constant);*/
2974 //evaluation = Debugger::EvaluateExpression(temp, &evalError);
2975 // address = strtoul(exp.constant, null, 0);
2976 address = _strtoui64(exp.constant, null, 0);
2977 //_dplf(0, "0x", address);
2978 // snprintf(value, sizeof(value), "0x%08x ", address);
2980 if(address > 0xFFFFFFFFLL)
2981 snprintf(value, sizeof(value), (__runtimePlatform == win32) ? "0x%016I64x " : "0x%016llx ", address);
2983 snprintf(value, sizeof(value), (__runtimePlatform == win32) ? "0x%08I64x " : "0x%08llx ", address);
2984 value[sizeof(value)-1] = 0;
2987 strcat(value, $"Null string");
2990 String string = new char[4097];
2992 bool success = false;
2996 for(start = 0; !done && start + size <= 4096; start += size)
3001 // Try to read 256 bytes at a time, then half if that fails
3002 s = GdbReadMemory(address + start, size);
3006 memcpy(string + start, s, size);
3007 string[start + size] = 0;
3008 if(size == 1 || memchr(s, 0, size))
3022 int len = strlen(value);
3024 if(UTF8Validate(string))
3029 for(c = 0; (ch = string[c]); c++)
3032 value[len++] = '\0';
3037 ISO8859_1toUTF8(string, value + len, strlen(value) - len - 30);
3038 strcat(value, ") (ISO8859-1)");
3042 strcat(value, $"Empty string");
3045 strcat(value, $"Couldn't read memory");
3048 wh.value = CopyString(value);
3051 else if(wh.type && wh.type.kind == classType && wh.type._class &&
3052 wh.type._class.registered && wh.type._class.registered.type == enumClass)
3054 Class enumClass = eSystem_FindClass(GetPrivateModule(), wh.type._class.registered.name);
3055 EnumClassData enumeration = (EnumClassData)enumClass.data;
3059 if(!strcmp(enumClass.dataTypeString, "uint64"))
3061 uint64 v = strtoull(exp.constant, null, 0);
3062 value = *(int64*)&v;
3065 value = strtoll(exp.constant, null, 0);
3067 for(item = enumeration.values.first; item; item = item.next)
3068 if(item.data == value)
3071 wh.value = CopyString(item.name);
3073 wh.value = PrintString($"Invalid Enum Value (", value, ")");
3076 else if(wh.type && (wh.type.kind == charType || (wh.type.kind == classType && wh.type._class &&
3077 wh.type._class.registered && !strcmp(wh.type._class.registered.fullName, "unichar"))) )
3084 if(exp.constant[0] == '\'')
3086 if((int)((byte *)exp.constant)[1] > 127)
3089 value = UTF8GetChar(exp.constant + 1, &nb);
3090 if(nb < 2) value = exp.constant[1];
3091 signedValue = value;
3095 signedValue = exp.constant[1];
3097 // Precomp Syntax error with boot strap here:
3098 byte b = (byte)(char)signedValue;
3099 value = (unichar) b;
3105 if(wh.type.kind == charType && wh.type.isSigned)
3107 signedValue = (int)(char)strtol(exp.constant, null, 0);
3109 // Precomp Syntax error with boot strap here:
3110 byte b = (byte)(char)signedValue;
3111 value = (unichar) b;
3116 value = (uint)strtoul(exp.constant, null, 0);
3117 signedValue = (int)value;
3121 UTF32toUTF8Len(&value, 1, charString, 5);
3123 snprintf(string, sizeof(string), "\'\\0' (0)");
3124 else if(value == '\t')
3125 snprintf(string, sizeof(string), "\'\\t' (%d)", value);
3126 else if(value == '\n')
3127 snprintf(string, sizeof(string), "\'\\n' (%d)", value);
3128 else if(value == '\r')
3129 snprintf(string, sizeof(string), "\'\\r' (%d)", value);
3130 else if(wh.type.kind == charType && wh.type.isSigned)
3131 snprintf(string, sizeof(string), "\'%s\' (%d)", charString, signedValue);
3132 else if(value > 256 || wh.type.kind != charType)
3134 if(value > 0x10FFFF || !GetCharCategory(value))
3135 snprintf(string, sizeof(string), $"Invalid Unicode Codepoint (0x%08X)", value);
3137 snprintf(string, sizeof(string), "\'%s\' (U+%04X)", charString, value);
3140 snprintf(string, sizeof(string), "\'%s\' (%d)", charString, value);
3141 string[sizeof(string)-1] = 0;
3143 wh.value = CopyString(string);
3148 wh.value = CopyString(exp.constant);
3154 bool genericError = true;
3155 if(exp.expType && exp.hasAddress)
3157 bool showAddress = false;
3158 switch(exp.expType.kind)
3170 Symbol s = exp.expType._class;
3173 Class c = s.registered;
3174 if(c.type == noHeadClass || c.type == normalClass)
3182 wh.value = PrintHexUInt64(exp.address);
3184 genericError = false;
3188 // NOTE: This should ideally be handled with a specific error message
3189 snprintf(watchmsg, sizeof(watchmsg), $"Error evaluating \"%s\"", wh.expression);
3194 SetInDebugger(false);
3197 snprintf(watchmsg, sizeof(watchmsg), $"Invalid expression: \"%s\"", wh.expression);
3198 if(exp) FreeExpression(exp);
3201 SetPrivateModule(backupPrivateModule);
3202 SetCurrentContext(backupContext);
3203 SetTopContext(backupContext);
3204 SetGlobalContext(backupContext);
3205 SetThisClass(backupThisClass);
3208 // wh.value = CopyString("No source file found for selected frame");
3210 watchmsg[sizeof(watchmsg)-1] = 0;
3212 wh.value = CopyString(watchmsg);
3214 ide.watchesView.UpdateWatch(wh);
3218 void EvaluateWatches()
3220 _dpcl(_dpct, dplchan::debuggerWatches, 0, "Debugger::EvaluateWatches()");
3221 WatchesLinkCodeEditor();
3222 if(state == stopped)
3224 for(wh : ide.workspace.watches)
3229 char * ::GdbEvaluateExpression(char * expression)
3231 _dpcl(_dpct, dplchan::debuggerWatches, 0, "Debugger::GdbEvaluateExpression(", expression, ")");
3234 GdbCommand(0, false, "-data-evaluate-expression \"%s\"", expression);
3236 ide.outputView.debugBox.Logf("Debugger Error: GdbEvaluateExpression\n");
3240 // to be removed... use GdbReadMemory that returns a byte array instead
3241 char * ::GdbReadMemoryString(uint64 address, int size, char format, int rows, int cols)
3243 _dpcl(_dpct, dplchan::debuggerCall, 0, "Debugger::GdbReadMemoryString(", address, ")");
3248 _dplf(0, "GdbReadMemoryString called with size = 0!");
3250 GdbCommand(0, false,
3251 (__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);
3253 ide.outputView.debugBox.Logf("Debugger Error: GdbReadMemoryString\n");
3257 byte * ::GdbReadMemory(uint64 address, int bytes)
3259 _dpcl(_dpct, dplchan::debuggerCall, 0, "Debugger::GdbReadMemory(", address, ")");
3262 GdbCommand(0, false,
3263 (__runtimePlatform == win32) ? "-data-read-memory 0x%016I64x %c, 1, 1, %d" : "-data-read-memory 0x%016llx %c, 1, 1, %d",
3264 address, 'u', bytes);
3267 _dplf(0, "GdbReadMemory called with bytes = 0!");
3270 ide.outputView.debugBox.Logf("Debugger Error: GdbReadMemory\n");
3271 else if(eval.result && strcmp(eval.result, "N/A"))
3273 byte * result = new byte[bytes];
3274 char * string = eval.result;
3278 result[c++] = (byte)strtol(string, &string, 10);
3295 bool BreakpointHit(GdbDataStop stopItem, Breakpoint bpInternal, Breakpoint bpUser)
3298 char * s1 = null; char * s2 = null;
3299 _dpcl(_dpct, dplchan::debuggerCall, 0, "Debugger::BreakpointHit(",
3300 "bpInternal(", bpInternal ? s1=bpInternal.CopyLocationString(false) : null, "), ",
3301 "bpUser(", bpUser ? s2=bpUser.CopyLocationString(false) : null, ")) -- ",
3302 "ignoreBreakpoints(", ignoreBreakpoints, "), ",
3303 "hitCursorBreakpoint(", bpUser && bpUser.type == runToCursor, ")");
3304 delete s1; delete s2;
3308 bool conditionMet = true;
3309 if(bpUser.condition)
3311 if(WatchesLinkCodeEditor())
3312 conditionMet = ResolveWatch(bpUser.condition);
3314 conditionMet = false;
3329 if(stopItem.frame.line && bpUser.line != stopItem.frame.line)
3331 // updating user breakpoint on hit location difference
3332 // todo, print something?
3333 bpUser.line = stopItem.frame.line;
3334 ide.breakpointsView.UpdateBreakpoint(bpUser.row);
3335 ide.workspace.Save();
3338 ide.breakpointsView.UpdateBreakpoint(bpUser.row);
3343 if(bpInternal.type == internalModulesLoaded)
3345 if(userAction == stepOver)
3347 if((bpInternal.type == internalEntry && ((intBpMain && intBpMain.inserted) || (intBpWinMain && intBpWinMain.inserted))) ||
3348 (bpInternal.type == internalMain && intBpWinMain && intBpWinMain.inserted))
3351 if(!bpUser && !userAction.breaksOnInternalBreakpoint)
3353 if(userAction == stepOut)
3354 StepOut(ignoreBreakpoints);
3360 if(!bpUser && !bpInternal)
3366 void ValgrindTargetThreadExit()
3368 _dpcl(_dpct, dplchan::debuggerCall, 0, "Debugger::ValgrindTargetThreadExit()");
3371 vgTargetHandle.Wait();
3372 delete vgTargetHandle;
3374 HandleExit(null, null);
3377 void GdbThreadExit()
3379 _dpcl(_dpct, dplchan::debuggerCall, 0, "Debugger::GdbThreadExit()");
3380 if(state != terminated)
3382 _ChangeState(terminated);
3383 targetProcessId = 0;
3384 ClearBreakDisplay();
3389 serialSemaphore.Release();
3394 ide.outputView.debugBox.Logf($"Debugger Fatal Error: GDB lost\n");
3395 ide.outputView.debugBox.Logf($"Debugging stopped\n");
3397 HideDebuggerViews();
3399 //_ChangeState(terminated);
3403 void GdbThreadMain(char * output)
3407 Array<char *> outTokens { minAllocSize = 50 };
3408 Array<char *> subTokens { minAllocSize = 50 };
3409 DebugListItem item { };
3410 DebugListItem item2 { };
3411 bool setWaitingForPID = false;
3413 #if defined(GDB_DEBUG_CONSOLE) || defined(GDB_DEBUG_GUI)
3414 #ifdef GDB_DEBUG_CONSOLE
3415 // _dpcl(_dpct, dplchan::gdbOutput, 0, output);
3418 #ifdef GDB_DEBUG_OUTPUT
3420 int len = strlen(output);
3428 for(c = 0; c < len / 1024; c++)
3430 strncpy(tmp, start, 1024);
3431 ide.outputView.gdbBox.Logf("out: %s\n", tmp);
3434 ide.outputView.gdbBox.Logf("out: %s\n", start);
3438 ide.outputView.gdbBox.Logf("out: %s\n", output);
3442 #ifdef GDB_DEBUG_CONSOLE
3443 strcpy(lastGdbOutput, output);
3445 #ifdef GDB_DEBUG_GUI
3446 if(ide.gdbDialog) ide.gdbDialog.AddOutput(output);
3453 if(strstr(output, "No debugging symbols found") || strstr(output, "(no debugging symbols found)"))
3456 ide.outputView.debugBox.Logf($"Target doesn't contain debug information!\n");
3459 if(!entryPoint && (t = strstr(output, "Entry point:")))
3461 char * addr = t + strlen("Entry point:");
3463 if(*t++ == ' ' && *t++ == '0' && *t == 'x')
3466 while(isxdigit(*++t));
3468 for(bp : sysBPs; bp.type == internalEntry)
3471 bp.enabled = entryPoint = true;
3479 if(TokenizeList(output, ',', outTokens) && !strcmp(outTokens[0], "^done"))
3481 //if(outTokens.count == 1)
3486 _ChangeState(loaded);
3487 targetProcessId = 0;
3488 if(outTokens.count > 1 && TokenizeListItem(outTokens[1], item))
3490 if(!strcmp(item.name, "reason"))
3492 char * reason = item.value;
3493 StripQuotes(reason, reason);
3494 if(!strcmp(reason, "exited-normally") || !strcmp(reason, "exited") || !strcmp(reason, "exited-signalled"))
3497 if(outTokens.count > 2 && TokenizeListItem(outTokens[2], item2))
3499 StripQuotes(item2.value, item2.value);
3500 if(!strcmp(item2.name, "exit-code"))
3501 exitCode = item2.value;
3507 HandleExit(reason, exitCode);
3511 _dpcl(_dpct, dplchan::gdbProtoUnknown, 0, "kill reply (", item.name, "=", item.value, ") is unheard of");
3514 HandleExit(null, null);
3517 if(outTokens.count > 1 && TokenizeListItem(outTokens[1], item))
3519 if(!strcmp(item.name, "bkpt"))
3521 sentBreakInsert = false;
3524 _dplf(0, "problem");
3527 bpItem = ParseBreakpoint(item.value, outTokens);
3528 //breakType = bpValidation;
3530 else if(!strcmp(item.name, "depth"))
3532 StripQuotes(item.value, item.value);
3533 frameCount = atoi(item.value);
3535 stackFrames.Free(Frame::Free);
3537 else if(!strcmp(item.name, "stack"))
3540 if(stackFrames.count)
3541 ide.callStackView.Logf("...\n");
3544 item.value = StripBrackets(item.value);
3545 TokenizeList(item.value, ',', subTokens);
3546 for(i = 0; i < subTokens.count; i++)
3548 if(TokenizeListItem(subTokens[i], item))
3550 if(!strcmp(item.name, "frame"))
3553 stackFrames.Add(frame);
3554 item.value = StripCurlies(item.value);
3555 ParseFrame(frame, item.value);
3556 if(frame.file && frame.from)
3557 _dpcl(_dpct, dplchan::gdbProtoUnknown, 0, "unexpected frame file and from members present");
3561 if(activeFrameLevel == -1)
3563 if(ide.projectView.IsModuleInProject(frame.file));
3565 if(frame.level != 0)
3567 //stopItem.frame = frame;
3568 breakType = selectFrame;
3571 activeFrame = frame;
3572 activeFrameLevel = frame.level;
3575 ide.callStackView.Logf("%3d ", frame.level);
3576 if(!strncmp(frame.func, "__ecereMethod_", strlen("__ecereMethod_")))
3577 ide.callStackView.Logf($"%s Method, %s:%d\n", &frame.func[strlen("__ecereMethod_")], (s = CopySystemPath(frame.file)), frame.line);
3578 else if(!strncmp(frame.func, "__ecereProp_", strlen("__ecereProp_")))
3579 ide.callStackView.Logf($"%s Property, %s:%d\n", &frame.func[strlen("__ecereProp_")], (s = CopySystemPath(frame.file)), frame.line);
3580 else if(!strncmp(frame.func, "__ecereConstructor_", strlen("__ecereConstructor_")))
3581 ide.callStackView.Logf($"%s Constructor, %s:%d\n", &frame.func[strlen("__ecereConstructor_")], (s = CopySystemPath(frame.file)), frame.line);
3582 else if(!strncmp(frame.func, "__ecereDestructor_", strlen("__ecereDestructor_")))
3583 ide.callStackView.Logf($"%s Destructor, %s:%d\n", &frame.func[strlen("__ecereDestructor_")], (s = CopySystemPath(frame.file)), frame.line);
3585 ide.callStackView.Logf($"%s Function, %s:%d\n", frame.func, (s = CopySystemPath(frame.file)), frame.line);
3590 ide.callStackView.Logf("%3d ", frame.level);
3595 ide.callStackView.Logf($"inside %s, %s\n", frame.func, (s = CopySystemPath(frame.from)));
3599 ide.callStackView.Logf("%s\n", frame.func);
3601 ide.callStackView.Logf($"unknown source\n");
3605 _dpcl(_dpct, dplchan::gdbProtoUnknown, 0, "stack content (", item.name, "=", item.value, ") is unheard of");
3608 if(activeFrameLevel == -1)
3610 activeFrameLevel = 0;
3611 activeFrame = stackFrames.first;
3613 ide.callStackView.Home();
3615 subTokens.RemoveAll();
3617 /*else if(!strcmp(item.name, "frame"))
3620 item.value = StripCurlies(item.value);
3621 ParseFrame(&frame, item.value);
3623 else if(!strcmp(item.name, "thread-ids"))
3625 ide.threadsView.Clear();
3626 item.value = StripCurlies(item.value);
3627 TokenizeList(item.value, ',', subTokens);
3628 for(i = subTokens.count - 1; ; i--)
3630 if(TokenizeListItem(subTokens[i], item))
3632 if(!strcmp(item.name, "thread-id"))
3635 StripQuotes(item.value, item.value);
3636 value = atoi(item.value);
3637 ide.threadsView.Logf("%3d \n", value);
3640 _dpcl(_dpct, dplchan::gdbProtoUnknown, 0, "threads content (", item.name, "=", item.value, ") is unheard of");
3645 ide.threadsView.Home();
3647 subTokens.RemoveAll();
3648 //if(!strcmp(outTokens[2], "number-of-threads"))
3650 else if(!strcmp(item.name, "new-thread-id"))
3652 StripQuotes(item.value, item.value);
3653 activeThread = atoi(item.value);
3655 else if(!strcmp(item.name, "value"))
3657 StripQuotes(item.value, item.value);
3658 eval.result = CopyString(item.value);
3659 eval.active = false;
3661 else if(!strcmp(item.name, "addr"))
3663 for(i = 2; i < outTokens.count; i++)
3665 if(TokenizeListItem(outTokens[i], item))
3667 if(!strcmp(item.name, "total-bytes"))
3669 StripQuotes(item.value, item.value);
3670 eval.bytes = atoi(item.value);
3672 else if(!strcmp(item.name, "next-row"))
3674 StripQuotes(item.value, item.value);
3675 eval.nextBlockAddress = _strtoui64(item.value, null, 0);
3677 else if(!strcmp(item.name, "memory"))
3681 //StripQuotes(item.value, item.value);
3682 item.value = StripBrackets(item.value);
3683 // this should be treated as a list...
3684 item.value = StripCurlies(item.value);
3685 TokenizeList(item.value, ',', subTokens);
3686 for(j = 0; j < subTokens.count; j++)
3688 if(TokenizeListItem(subTokens[j], item))
3690 if(!strcmp(item.name, "data"))
3692 item.value = StripBrackets(item.value);
3693 StripQuotes2(item.value, item.value);
3694 eval.result = CopyString(item.value);
3695 eval.active = false;
3699 subTokens.RemoveAll();
3704 else if(!strcmp(item.name, "source-path") || !strcmp(item.name, "BreakpointTable"))
3705 _dpcl(_dpct, dplchan::gdbProtoIgnored, 0, "command reply (", item.name, "=", item.value, ") is ignored");
3707 _dpcl(_dpct, dplchan::gdbProtoUnknown, 0, "command reply (", item.name, "=", item.value, ") is unheard of");
3710 else if(!strcmp(outTokens[0], "^running"))
3712 waitingForPID = true;
3713 setWaitingForPID = true;
3714 ClearBreakDisplay();
3716 else if(!strcmp(outTokens[0], "^exit"))
3718 _ChangeState(terminated);
3719 // ide.outputView.debugBox.Logf("Exit\n");
3720 // ide.Update(null);
3722 serialSemaphore.Release();
3724 else if(!strcmp(outTokens[0], "^error"))
3728 sentBreakInsert = false;
3729 breakpointError = true;
3732 if(outTokens.count > 1 && TokenizeListItem(outTokens[1], item))
3734 if(!strcmp(item.name, "msg"))
3736 StripQuotes(item.value, item.value);
3739 eval.active = false;
3741 if(strstr(item.value, "No symbol") && strstr(item.value, "in current context"))
3742 eval.error = symbolNotFound;
3743 else if(strstr(item.value, "Cannot access memory at address"))
3744 eval.error = memoryCantBeRead;
3746 eval.error = unknown;
3748 else if(!strcmp(item.value, "Previous frame inner to this frame (corrupt stack?)"))
3751 else if(!strncmp(item.value, "Cannot access memory at address", 31))
3754 else if(!strcmp(item.value, "Cannot find bounds of current function"))
3756 _ChangeState(stopped);
3757 gdbHandle.Printf("-exec-continue\n");
3759 else if(!strcmp(item.value, "ptrace: No such process."))
3761 _ChangeState(loaded);
3762 targetProcessId = 0;
3764 else if(!strcmp(item.value, "Function \\\"WinMain\\\" not defined."))
3767 else if(!strcmp(item.value, "You can't do that without a process to debug."))
3769 _ChangeState(loaded);
3770 targetProcessId = 0;
3772 else if(strstr(item.value, "No such file or directory."))
3774 _ChangeState(loaded);
3775 targetProcessId = 0;
3777 else if(strstr(item.value, "During startup program exited with code "))
3779 _ChangeState(loaded);
3780 targetProcessId = 0;
3785 if(strlen(item.value) < MAX_F_STRING)
3788 ide.outputView.debugBox.Logf("GDB: %s\n", (s = CopyUnescapedString(item.value)));
3792 ide.outputView.debugBox.Logf("GDB: %s\n", item.value);
3798 _dpcl(_dpct, dplchan::gdbProtoUnknown, 0, "error content (", item.name, "=", item.value, ") is unheard of");
3801 _dpcl(_dpct, dplchan::gdbProtoUnknown, 0, "result-record: ", outTokens[0]);
3802 outTokens.RemoveAll();
3805 _dpcl(_dpct, dplchan::gdbProtoUnknown, 0, "status-async-output: ", outTokens[0]);
3808 if(TokenizeList(output, ',', outTokens))
3810 if(!strcmp(outTokens[0], "=library-loaded"))
3811 FGODetectLoadedLibraryForAddedProjectIssues(outTokens, false);
3812 else if(!strcmp(outTokens[0], "=shlibs-added"))
3813 FGODetectLoadedLibraryForAddedProjectIssues(outTokens, true);
3814 else if(!strcmp(outTokens[0], "=thread-group-created") || !strcmp(outTokens[0], "=thread-group-added") ||
3815 !strcmp(outTokens[0], "=thread-group-started") || !strcmp(outTokens[0], "=thread-group-exited") ||
3816 !strcmp(outTokens[0], "=thread-created") || !strcmp(outTokens[0], "=thread-exited") ||
3817 !strcmp(outTokens[0], "=cmd-param-changed") || !strcmp(outTokens[0], "=library-unloaded") ||
3818 !strcmp(outTokens[0], "=breakpoint-modified"))
3819 _dpcl(_dpct, dplchan::gdbProtoIgnored, 0, outTokens[0], outTokens.count>1 ? outTokens[1] : "",
3820 outTokens.count>2 ? outTokens[2] : "", outTokens.count>3 ? outTokens[3] : "",
3821 outTokens.count>4 ? outTokens[4] : "", outTokens.count>5 ? outTokens[5] : "",
3822 outTokens.count>6 ? outTokens[6] : "", outTokens.count>7 ? outTokens[7] : "",
3823 outTokens.count>8 ? outTokens[8] : "", outTokens.count>9 ? outTokens[9] : "");
3825 _dpcl(_dpct, dplchan::gdbProtoUnknown, 0, "notify-async-output: ", outTokens[0]);
3827 outTokens.RemoveAll();
3831 if(TokenizeList(output, ',', outTokens))
3833 if(!strcmp(outTokens[0],"*running"))
3835 waitingForPID = true;
3836 setWaitingForPID = true;
3838 else if(!strcmp(outTokens[0], "*stopped"))
3841 _ChangeState(stopped);
3843 for(tk = 1; tk < outTokens.count; tk++)
3845 if(TokenizeListItem(outTokens[tk], item))
3847 if(!strcmp(item.name, "reason"))
3849 char * reason = item.value;
3850 StripQuotes(reason, reason);
3851 if(!strcmp(reason, "exited-normally") || !strcmp(reason, "exited") || !strcmp(reason, "exited-signalled"))
3854 if(outTokens.count > tk+1 && TokenizeListItem(outTokens[tk+1], item2))
3857 StripQuotes(item2.value, item2.value);
3858 if(!strcmp(item2.name, "exit-code"))
3859 exitCode = item2.value;
3865 HandleExit(reason, exitCode);
3868 else if(!strcmp(reason, "breakpoint-hit") ||
3869 !strcmp(reason, "function-finished") ||
3870 !strcmp(reason, "end-stepping-range") ||
3871 !strcmp(reason, "location-reached") ||
3872 !strcmp(reason, "signal-received"))
3876 if(stopItem) _dplf(0, "problem");
3878 stopItem = GdbDataStop { };
3879 stopItem.reason = r == 'b' ? breakpointHit : r == 'f' ? functionFinished : r == 'e' ? endSteppingRange : r == 'l' ? locationReached : signalReceived;
3881 for(i = tk+1; i < outTokens.count; i++)
3883 TokenizeListItem(outTokens[i], item);
3884 StripQuotes(item.value, item.value);
3885 if(!strcmp(item.name, "thread-id"))
3886 stopItem.threadid = atoi(item.value);
3887 else if(!strcmp(item.name, "frame"))
3889 item.value = StripCurlies(item.value);
3890 ParseFrame(stopItem.frame, item.value);
3892 else if(stopItem.reason == breakpointHit && !strcmp(item.name, "bkptno"))
3893 stopItem.bkptno = atoi(item.value);
3894 else if(stopItem.reason == functionFinished && !strcmp(item.name, "gdb-result-var"))
3895 stopItem.gdbResultVar = CopyString(item.value);
3896 else if(stopItem.reason == functionFinished && !strcmp(item.name, "return-value"))
3897 stopItem.returnValue = CopyString(item.value);
3898 else if(stopItem.reason == signalReceived && !strcmp(item.name, "signal-name"))
3899 stopItem.name = CopyString(item.value);
3900 else if(stopItem.reason == signalReceived && !strcmp(item.name, "signal-meaning"))
3901 stopItem.meaning = CopyString(item.value);
3902 else if(!strcmp(item.name, "stopped-threads"))
3903 _dpcl(_dpct, dplchan::gdbProtoIgnored, 0, reason, ": Advanced thread debugging not handled");
3904 else if(!strcmp(item.name, "core"))
3905 _dpcl(_dpct, dplchan::gdbProtoIgnored, 0, reason, ": Information (core) not used");
3906 else if(!strcmp(item.name, "disp"))
3907 _dpcl(_dpct, dplchan::gdbProtoIgnored, 0, reason, ": (", item.name, "=", item.value, ")");
3909 _dpcl(_dpct, dplchan::gdbProtoUnknown, 0, "Unknown ", reason, " item name (", item.name, "=", item.value, ")");
3912 if(stopItem.reason == signalReceived && !strcmp(stopItem.name, "SIGTRAP"))
3928 event = r == 'b' ? hit : r == 'f' ? functionEnd : r == 'e' ? stepEnd : r == 'l' ? locationReached : signal;
3932 else if(!strcmp(reason, "watchpoint-trigger"))
3933 _dpcl(_dpct, dplchan::gdbProtoIgnored, 0, "Reason watchpoint trigger not handled");
3934 else if(!strcmp(reason, "read-watchpoint-trigger"))
3935 _dpcl(_dpct, dplchan::gdbProtoIgnored, 0, "Reason read watchpoint trigger not handled");
3936 else if(!strcmp(reason, "access-watchpoint-trigger"))
3937 _dpcl(_dpct, dplchan::gdbProtoIgnored, 0, "Reason access watchpoint trigger not handled");
3938 else if(!strcmp(reason, "watchpoint-scope"))
3939 _dpcl(_dpct, dplchan::gdbProtoIgnored, 0, "Reason watchpoint scope not handled");
3941 _dpcl(_dpct, dplchan::gdbProtoUnknown, 0, "Unknown reason: ", reason);
3949 if(usingValgrind && event == none && !stopItem)
3950 event = valgrindStartPause;
3955 _dpcl(_dpct, dplchan::gdbProtoUnknown, 0, "Unknown exec-async-output: ", outTokens[0]);
3956 outTokens.RemoveAll();
3959 if(!strcmpi(output, "(gdb) "))
3963 Time startTime = GetTime();
3964 char exeFile[MAX_LOCATION];
3965 int oldProcessID = targetProcessId;
3966 GetLastDirectory(targetFile, exeFile);
3968 while(!targetProcessId/*true*/)
3970 targetProcessId = Process_GetChildExeProcessId(gdbProcessId, exeFile);
3971 if(targetProcessId) break;
3972 // Can't break on Peek(), GDB is giving us =library and other info before the process is listed in /proc
3973 // if(gdbHandle.Peek()) break;
3975 if(gdbHandle.Peek() && GetTime() - startTime > 2.5) // Give the process 2.5 seconds to show up in /proc
3980 _ChangeState(running);
3981 else if(!oldProcessID)
3983 ide.outputView.debugBox.Logf($"Debugger Error: No target process ID\n");
3984 // TO VERIFY: The rest of this block has not been thoroughly tested in this particular location
3985 gdbHandle.Printf("-gdb-exit\n");
3987 _ChangeState(terminated); //loaded;
3992 for(bp : ide.workspace.breakpoints)
3993 bp.inserted = false;
3996 bp.inserted = false;
3998 bpRunToCursor.inserted = false;
4000 ide.outputView.debugBox.Logf($"Debugging stopped\n");
4001 ClearBreakDisplay();
4003 #if defined(__unix__)
4004 if(!usingValgrind && FileExists(progFifoPath)) //fileCreated)
4006 progThread.terminate = true;
4009 fifoFile.CloseInput();
4016 DeleteFile(progFifoPath);
4017 progFifoPath[0] = '\0';
4024 serialSemaphore.Release();
4027 _dpcl(_dpct, dplchan::gdbProtoUnknown, 0, $"Unknown prompt", output);
4031 if(!strncmp(output, "&\"warning:", 10))
4034 content = strstr(output, "\"");
4035 StripQuotes(content, content);
4036 content = strstr(content, ":");
4042 ide.outputView.debugBox.LogRaw((s = CopyUnescapedString(content)));
4049 _dpcl(_dpct, dplchan::gdbProtoUnknown, 0, $"Unknown output: ", output);
4051 if(!setWaitingForPID)
4052 waitingForPID = false;
4053 setWaitingForPID = false;
4061 // From GDB Output functions
4062 void FGODetectLoadedLibraryForAddedProjectIssues(Array<char *> outTokens, bool shlibs)
4064 char path[MAX_LOCATION] = "";
4065 char file[MAX_FILENAME] = "";
4066 //bool symbolsLoaded = false;
4067 DebugListItem item { };
4068 //_dpcl(_dpct, dplchan::debuggerCall, 0, "Debugger::FGODetectLoadedLibraryForAddedProjectIssues()");
4069 for(token : outTokens)
4071 if(TokenizeListItem(token, item))
4073 if(!strcmp(item.name, "target-name"))
4075 StripQuotes(item.value, path);
4076 MakeSystemPath(path);
4077 GetLastDirectory(path, file);
4079 else if(!strcmp(item.name, "symbols-loaded"))
4081 //symbolsLoaded = (atoi(item.value) == 1);
4083 else if(!strcmp(item.name, "shlib-info"))
4085 DebugListItem subItem { };
4086 Array<char *> tokens { minAllocSize = 50 };
4087 item.value = StripBrackets(item.value);
4088 TokenizeList(item.value, ',', tokens);
4091 if(TokenizeListItem(t, subItem))
4093 if(!strcmp(subItem.name, "path"))
4095 StripQuotes(subItem.value, path);
4096 MakeSystemPath(path);
4097 GetLastDirectory(path, file);
4098 //symbolsLoaded = true;
4109 if(path[0] && file[0])
4111 for(prj : ide.workspace.projects; prj != ide.workspace.projects.firstIterator.data)
4115 char prjTargetPath[MAX_LOCATION];
4116 char prjTargetFile[MAX_FILENAME];
4117 DirExpression targetDirExp = prj.GetTargetDir(currentCompiler, prj.config, bitDepth);
4118 strcpy(prjTargetPath, prj.topNode.path);
4119 PathCat(prjTargetPath, targetDirExp.dir);
4120 delete targetDirExp;
4121 prjTargetFile[0] = '\0';
4122 prj.CatTargetFileName(prjTargetFile, currentCompiler, prj.config);
4123 PathCat(prjTargetPath, prjTargetFile);
4124 MakeSystemPath(prjTargetPath);
4126 match = !fstrcmp(prjTargetFile, file);
4127 if(!match && (dot = strstr(prjTargetFile, ".so.")))
4129 char * dot3 = strstr(dot+4, ".");
4133 match = !fstrcmp(prjTargetFile, file);
4138 match = !fstrcmp(prjTargetFile, file);
4143 // TODO: nice visual feedback to better warn user. use some ide notification system or other means.
4144 /* -- 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)
4146 ide.outputView.debugBox.Logf($"Attention! No symbols for loaded library %s matched to the %s added project.\n", path, prj.topNode.name);
4148 match = !fstrcmp(prjTargetPath, path);
4149 if(!match && (dot = strstr(prjTargetPath, ".so.")))
4151 char * dot3 = strstr(dot+4, ".");
4155 match = !fstrcmp(prjTargetPath, path);
4160 match = !fstrcmp(prjTargetPath, path);
4164 projectsLibraryLoaded[prj.name] = true;
4166 ide.outputView.debugBox.Logf($"Loaded library %s doesn't match the %s target of the %s added project.\n", path, prjTargetPath, prj.topNode.name);
4173 void FGOBreakpointModified(Array<char *> outTokens)
4175 _dpcl(_dpct, dplchan::debuggerCall, 0, "Debugger::FGOBreakpointModified() -- TODO only if needed: support breakpoint modified");
4177 DebugListItem item { };
4178 if(outTokens.count > 1 && TokenizeListItem(outTokens[1], item))
4180 if(!strcmp(item.name, "bkpt"))
4182 GdbDataBreakpoint modBp = ParseBreakpoint(item.value, outTokens);
4190 ExpressionType ::DebugEvalExpTypeError(char * result)
4192 _dpcl(_dpct, dplchan::debuggerWatches, 0, "Debugger::DebugEvalExpTypeError()");
4197 case symbolNotFound:
4198 return symbolErrorExp;
4199 case memoryCantBeRead:
4200 return memoryErrorExp;
4202 return unknownErrorExp;
4205 char * ::EvaluateExpression(char * expression, ExpressionType * error)
4208 _dpcl(_dpct, dplchan::debuggerWatches, 0, "Debugger::EvaluateExpression(", expression, ")");
4209 if(ide.projectView && ide.debugger.state == stopped)
4211 result = GdbEvaluateExpression(expression);
4212 *error = DebugEvalExpTypeError(result);
4217 *error = noDebuggerErrorExp;
4222 char * ::ReadMemory(uint64 address, int size, char format, ExpressionType * error)
4225 char * result = GdbReadMemoryString(address, size, format, 1, 1);
4226 _dpcl(_dpct, dplchan::debuggerCall, 0, "Debugger::ReadMemory(", address, ")");
4227 if(!result || !strcmp(result, "N/A"))
4228 *error = memoryErrorExp;
4230 *error = DebugEvalExpTypeError(result);
4235 class ValgrindLogThread : Thread
4241 static char output[4096];
4242 bool lastLineEmpty = true;
4243 Array<char> dynamicBuffer { minAllocSize = 4096 };
4244 File oldValgrindHandle = vgLogFile;
4245 incref oldValgrindHandle;
4248 while(debugger.state != terminated && vgLogFile && vgLogFile.input)
4253 result = vgLogFile.Read(output, 1, sizeof(output));
4255 if(debugger.state == terminated || !vgLogFile) // || vgLogFile.Eof()
4262 for(c = 0; c<result; c++)
4264 if(output[c] == '\n')
4266 int pos = dynamicBuffer.size;
4267 dynamicBuffer.size += c - start;
4268 memcpy(&dynamicBuffer[pos], output + start, c - start);
4269 if(dynamicBuffer.count && dynamicBuffer[dynamicBuffer.count - 1] != '\r')
4270 dynamicBuffer.size++;
4271 dynamicBuffer[dynamicBuffer.count - 1] = '\0';
4273 // printf("%s\n", dynamicBuffer.array);
4275 if(strstr(&dynamicBuffer[0], "vgdb me ..."))
4276 debugger.serialSemaphore.Release();
4278 char * s = strstr(&dynamicBuffer[0], "==");
4280 s = strstr(s+2, "== ");
4284 if(s[0] == '\0' && !lastLineEmpty)
4287 lastLineEmpty = true;
4288 dynamicBuffer[0] = '\0';
4297 if(strstr(s, "vgdb me ..."))
4299 if(strstr(s, "(action on error) vgdb me ..."))
4300 ide.outputView.debugBox.Logf($"...breaked on Valgrind error (F5 to resume)\n");
4307 if(strstr(s, "TO DEBUG THIS PROCESS USING GDB: start GDB like this"))
4313 if(strstr(s, "and then give GDB the following command"))
4319 if(strstr(s, "/path/to/gdb") || strstr(s, "target remote | /usr/lib/valgrind/../../bin/vgdb --pid="))
4325 if(strstr(s, "--pid is optional if only one valgrind process is running"))
4331 if((s = strstr(s, "; rerun with -h for copyright info")))
4343 if(lastLineEmpty && t[0] != '\0')
4344 lastLineEmpty = false;
4347 ide.outputView.debugBox.Logf("%s\n", &dynamicBuffer[0]);
4349 dynamicBuffer.size = 0;
4355 int pos = dynamicBuffer.size;
4356 dynamicBuffer.size += c - start;
4357 memcpy(&dynamicBuffer[pos], output + start, c - start);
4360 else if(debugger.state == stopped)
4363 printf("Got end of file from GDB!\n");
4370 delete dynamicBuffer;
4371 _dpcl(_dpct, dplchan::debuggerCall, 0, "ValgrindLogThreadExit");
4372 //if(oldValgrindHandle == vgLogFile)
4373 debugger.GdbThreadExit/*ValgrindLogThreadExit*/();
4374 delete oldValgrindHandle;
4380 class ValgrindTargetThread : Thread
4386 static char output[4096];
4387 Array<char> dynamicBuffer { minAllocSize = 4096 };
4388 DualPipe oldValgrindHandle = vgTargetHandle;
4389 incref oldValgrindHandle;
4392 while(debugger.state != terminated && vgTargetHandle && !vgTargetHandle.Eof())
4396 result = vgTargetHandle.Read(output, 1, sizeof(output));
4398 if(debugger.state == terminated || !vgTargetHandle || vgTargetHandle.Eof())
4405 for(c = 0; c<result; c++)
4407 if(output[c] == '\n')
4409 int pos = dynamicBuffer.size;
4410 dynamicBuffer.size += c - start;
4411 memcpy(&dynamicBuffer[pos], output + start, c - start);
4412 if(dynamicBuffer.count && dynamicBuffer[dynamicBuffer.count - 1] != '\r')
4413 // COMMENTED OUT DUE TO ISSUE #135, FIXED
4414 //if(dynamicBuffer.array[dynamicBuffer.count - 1] != '\r')
4415 dynamicBuffer.size++;
4416 dynamicBuffer[dynamicBuffer.count - 1] = '\0';
4418 // printf("%s\n", dynamicBuffer.array);
4420 ide.outputView.debugBox.Logf("%s\n", &dynamicBuffer[0]);
4422 dynamicBuffer.size = 0;
4428 int pos = dynamicBuffer.size;
4429 dynamicBuffer.size += c - start;
4430 memcpy(&dynamicBuffer[pos], output + start, c - start);
4436 printf("Got end of file from GDB!\n");
4440 delete dynamicBuffer;
4441 //if(oldValgrindHandle == vgTargetHandle)
4442 debugger.ValgrindTargetThreadExit();
4443 delete oldValgrindHandle;
4449 class GdbThread : Thread
4455 static char output[4096];
4456 Array<char> dynamicBuffer { minAllocSize = 4096 };
4457 DualPipe oldGdbHandle = gdbHandle;
4458 incref oldGdbHandle;
4461 while(debugger.state != terminated && gdbHandle && !gdbHandle.Eof())
4465 result = gdbHandle.Read(output, 1, sizeof(output));
4467 if(debugger.state == terminated || !gdbHandle || gdbHandle.Eof())
4474 for(c = 0; c<result; c++)
4476 if(output[c] == '\n')
4478 int pos = dynamicBuffer.size;
4479 dynamicBuffer.size += c - start;
4480 memcpy(&dynamicBuffer[pos], output + start, c - start);
4481 if(dynamicBuffer.count && dynamicBuffer[dynamicBuffer.count - 1] != '\r')
4482 // COMMENTED OUT DUE TO ISSUE #135, FIXED
4483 //if(dynamicBuffer.array[dynamicBuffer.count - 1] != '\r')
4484 dynamicBuffer.size++;
4485 dynamicBuffer[dynamicBuffer.count - 1] = '\0';
4487 // _dplf(0, dynamicBuffer.array);
4489 debugger.GdbThreadMain(&dynamicBuffer[0]);
4490 dynamicBuffer.size = 0;
4496 int pos = dynamicBuffer.size;
4497 dynamicBuffer.size += c - start;
4498 memcpy(&dynamicBuffer[pos], output + start, c - start);
4504 _dplf(0, "Got end of file from GDB!");
4508 delete dynamicBuffer;
4509 //if(oldGdbHandle == gdbHandle)
4510 debugger.GdbThreadExit();
4511 delete oldGdbHandle;
4517 static define createFIFOMsg = $"err: Unable to create FIFO %s\n";
4518 static define openFIFOMsg = $"err: Unable to open FIFO %s for read\n";
4520 #if defined(__unix__)
4525 #include <sys/types.h>
4530 class ProgramThread : Thread
4535 //bool result = true;
4536 //bool fileCreated = false;
4537 //mode_t mask = 0600;
4538 static char output[1000];
4541 /*if(!mkfifo(progFifoPath, mask))
4548 ide.outputView.debugBox.Logf($"err: Unable to create FIFO %s\n", progFifoPath);
4552 if(FileExists(progFifoPath)) //fileCreated)
4554 fifoFile = FileOpen(progFifoPath, read);
4558 ide.outputView.debugBox.Logf(openFIFOMsg, progFifoPath);
4563 fd = fileno((FILE *)fifoFile.input);
4564 //fcntl(fd, F_SETFL, fcntl(fd, F_GETFL) | O_NONBLOCK);
4568 while(!terminate && fifoFile && !fifoFile.Eof())
4571 struct timeval time;
4579 /*selectResult = */select(fd + 1, &rs, null, null, &time);
4580 if(FD_ISSET(fd, &rs))
4582 int result = (int)read(fd, output, sizeof(output)-1);
4583 if(!result || (result < 0 && errno != EAGAIN))
4587 output[result] = '\0';
4588 if(strcmp(output,"&\"warning: GDB: Failed to set controlling terminal: Invalid argument\\n\"\n"))
4591 ide.outputView.debugBox.Log(output);
4600 //fifoFile.CloseInput();
4603 ide.outputView.debugBox.Log("\n");
4607 if(FileExists(progFifoPath)) //fileCreated)
4609 DeleteFile(progFifoPath);
4610 progFifoPath[0] = '\0';
4618 class Argument : struct
4620 Argument prev, next;
4622 property char * name { set { delete name; if(value) name = CopyString(value); } }
4624 property char * val { set { delete val; if(value) val = CopyString(value); } }
4638 class Frame : struct
4643 property char * addr { set { delete addr; if(value) addr = CopyString(value); } }
4645 property char * func { set { delete func; if(value) func = CopyString(value); } }
4649 property char * from { set { delete from; if(value) from = CopyUnescapedUnixPath(value); } }
4651 property char * file { set { delete file; if(value) file = CopyUnescapedUnixPath(value); } }
4652 char * absoluteFile;
4653 property char * absoluteFile { set { delete absoluteFile; if(value) absoluteFile = CopyUnescapedUnixPath(value); } }
4662 delete absoluteFile;
4663 args.Free(Argument::Free);
4672 class GdbDataStop : struct
4674 DebuggerReason reason;
4689 char * gdbResultVar;
4699 if(reason == signalReceived)
4704 else if(reason == functionFinished)
4706 delete gdbResultVar;
4710 if(frame) frame.Free();
4719 class GdbDataBreakpoint : struct
4723 property char * number { set { delete number; if(value) number = CopyString(value); } }
4725 property char * type { set { delete type; if(value) type = CopyString(value); } }
4727 property char * disp { set { delete disp; if(value) disp = CopyString(value); } }
4730 property char * addr { set { delete addr; if(value) addr = CopyString(value); } }
4732 property char * func { set { delete func; if(value) func = CopyString(value); } }
4734 property char * file { set { delete file; if(value) file = CopyUnescapedUnixPath(value); } }
4736 property char * fullname { set { delete fullname; if(value) fullname = CopyUnescapedUnixPath(value); } }
4739 property char * at { set { delete at; if(value) at = CopyString(value); } }
4742 Array<GdbDataBreakpoint> multipleBPs;
4747 PrintLn("{", "#", number, " T", type, " D", disp, " E", enabled, " H", times, " (", func, ") (", file, ":", line, ") (", fullname, ") (", addr, ") (", at, ")", "}");
4758 if(multipleBPs) multipleBPs.Free();
4764 ~GdbDataBreakpoint()
4770 class Breakpoint : struct
4775 property const char * function { set { delete function; if(value) function = CopyString(value); } }
4776 char * relativeFilePath;
4777 property const char * relativeFilePath { set { delete relativeFilePath; if(value) relativeFilePath = CopyString(value); } }
4778 char * absoluteFilePath;
4779 property const char * absoluteFilePath { set { delete absoluteFilePath; if(value) absoluteFilePath = CopyString(value); } }
4781 property const char * location { set { delete location; if(value) location = CopyString(value); } }
4790 BreakpointType type;
4792 GdbDataBreakpoint bp;
4795 property const char * address { set { delete address; if(value) address = CopyString(value); } }
4797 void ParseLocation()
4799 char * prjName = null;
4800 char * filePath = null;
4803 char fullPath[MAX_LOCATION];
4804 if(location[0] == '(' && location[1] && (file = strchr(location+2, ')')) && file[1])
4806 prjName = new char[file-location];
4807 strncpy(prjName, location+1, file-location-1);
4808 prjName[file-location-1] = '\0';
4813 if((line = strchr(file+1, ':')))
4815 filePath = new char[strlen(file)+1];
4816 strncpy(filePath, file, line-file);
4817 filePath[line-file] = '\0';
4821 filePath = CopyString(file);
4822 property::relativeFilePath = filePath;
4825 for(prj : ide.workspace.projects)
4827 if(!strcmp(prjName, prj.name))
4829 if(prj.GetAbsoluteFromRelativePath(filePath, fullPath, null))
4831 property::absoluteFilePath = fullPath;
4838 this.line = atoi(line);
4842 Project prj = ide.project;
4843 if(prj.GetAbsoluteFromRelativePath(filePath, fullPath, null))
4845 property::absoluteFilePath = fullPath;
4849 if(!absoluteFilePath)
4850 property::absoluteFilePath = "";
4855 char * CopyLocationString(bool removePath)
4858 char * file = relativeFilePath ? relativeFilePath : absoluteFilePath;
4859 bool removingPath = removePath && file;
4862 char * fileName = new char[MAX_FILENAME];
4863 GetLastDirectory(file, fileName);
4869 location = PrintString(file, ":", function);
4871 location = CopyString(function);
4874 location = PrintString(file, ":", line);
4880 char * CopyUserLocationString()
4883 char * loc = CopyLocationString(false);
4885 if(absoluteFilePath)
4887 for(p : ide.workspace.projects; p != ide.workspace.projects.firstIterator.data)
4889 if(p.topNode.FindByFullPath(absoluteFilePath, false))
4898 location = PrintString("(", prj.name, ")", loc);
4908 if(relativeFilePath && relativeFilePath[0])
4910 char * location = CopyUserLocationString();
4911 f.Printf(" * %d,%d,%d,%d,%s\n", enabled ? 1 : 0, ignore, level, line, location);
4914 f.Printf(" ~ %s\n", condition.expression);
4922 delete relativeFilePath;
4923 delete absoluteFilePath;
4943 class Watch : struct
4954 f.Printf(" ~ %s\n", expression);
4978 class DebugListItem : struct
4984 struct DebugEvaluationData
4989 uint64 nextBlockAddress;
4991 DebuggerEvaluationError error;
4994 class CodeLocation : struct
4997 char * absoluteFile;
5000 CodeLocation ::ParseCodeLocation(char * location)
5004 char * colon = null;
5006 char loc[MAX_LOCATION];
5007 strcpy(loc, location);
5008 for(temp = loc; (temp = strstr(temp, ":")); temp++)
5016 int line = atoi(colon);
5019 CodeLocation codloc { line = line };
5020 codloc.file = CopyString(loc);
5021 codloc.absoluteFile = ide.workspace.CopyAbsolutePathFromRelative(loc);
5033 delete absoluteFile;
5042 void GDBFallBack(Expression exp, String expString)
5045 ExpressionType evalError = dummyExp;
5046 result = Debugger::EvaluateExpression(expString, &evalError);
5049 FreeExpContents(exp);
5050 exp.constant = result;
5051 exp.type = constantExp;