ide/Debugger: Not polluting the environment with variables set in workspace
[sdk] / ide / src / debugger / Debugger.ec
1 #ifdef ECERE_STATIC
2 public import static "ecere"
3 public import static "ec"
4 #else
5 public import "ecere"
6 public import "ec"
7 #endif
8
9 import "ide"
10 import "process"
11 import "debugFindCtx"
12 import "debugTools"
13
14 #ifdef _DEBUG
15 #define GDB_DEBUG_CONSOLE
16 #define _DEBUG_INST
17 #endif
18
19 extern char * strrchr(const char * s, int c);
20
21 #define uint _uint
22 #define strlen _strlen
23 #include <stdarg.h>
24 #include <unistd.h>
25 #include <ctype.h>
26
27 #ifdef __APPLE__
28 #define __unix__
29 #endif
30
31 #if defined(__unix__)
32 #include <sys/stat.h>
33 #include <sys/time.h> // Required on Apple...
34 #endif
35 #undef uint
36 #undef strlen
37
38 char * PrintNow()
39 {
40    int c;
41    char * s[6];
42    char * time;
43    DateTime now;
44    now.GetLocalTime();
45    for(c=0; c<6; c++)
46       s[c] = new char[8];
47    sprintf(s[0], "%04d", now.year);
48    sprintf(s[1], "%02d", now.month+1);
49    sprintf(s[2], "%02d", now.day);
50    sprintf(s[3], "%02d", now.hour);
51    sprintf(s[4], "%02d", now.minute);
52    sprintf(s[5], "%02d", now.second);
53    time = PrintString("*", s[0], s[1], s[2], "-", s[3], s[4], s[5], "*");
54    for(c=0; c<6; c++)
55       delete s[c];
56    return time;
57 }
58
59 // use =0 to disable printing of specific channels
60 #ifdef _DEBUG_INST
61 static enum dplchan { none, gdbProtoIgnored=0/*1*/, gdbProtoUnknown=2, gdbOutput=3/*3*/, gdbCommand=4/*4*/, debuggerCall=0/*5*/, debuggerProblem=6,
62                         debuggerUserAction=7,debuggerState=8, debuggerBreakpoints=9, debuggerWatches=0/*10*/, debuggerTemp=0 };
63 #else
64 static enum dplchan { none, gdbProtoIgnored=0, gdbProtoUnknown=0, gdbOutput=0, gdbCommand=0, debuggerCall=0, debuggerProblem=0,
65                         debuggerUserAction=0,debuggerState=0, debuggerBreakpoints=0, debuggerWatches=0, debuggerTemp=0 };
66 #endif
67 static char * _dpct[] = {
68    null,
69    "GDB Protocol Ignored",
70    "GDB Protocol ***Unknown***",
71    "GDB Output",
72    "GDB Command",
73    ""/*Debugger Call*/,
74    "Debugger ***Problem***",
75    "Debugger::ChangeUserAction",
76    "Debugger::ChangeState",
77    "Breakpoints",
78    "Watches",
79    "-----> Temporary Message",
80    null
81 };
82
83 // TODO if(strlen(item.value) < MAX_F_STRING)
84
85 // Debug Print Line
86 #ifdef _DEBUG_INST
87 #define _dpl2(...) __dpl2(__FILE__, __LINE__, ##__VA_ARGS__)
88 #else
89 #define _dpl2(...)
90 #endif
91 static void __dpl2(char * file, int line, char ** channels, int channel, int indent, typed_object object, ...)
92 {
93    bool chan = channel && channels && channels[channel];
94    if(chan || !channels)
95    {
96       char string[MAX_F_STRING];
97       int len;
98       char * time = PrintNow();
99       va_list args;
100       //ide.outputView.debugBox.Logf();
101       Logf("%s %s:% 5d: %s%s", time, file, line, chan ? channels[channel] : "", chan && channels[channel][0] ? ": " : "");
102       va_start(args, object);
103       len = PrintStdArgsToBuffer(string, sizeof(string), object, args);
104       Log(string);
105       va_end(args);
106       Log("\n");
107       delete time;
108    }
109 }
110
111 #define _dpl(...) __dpl(__FILE__, __LINE__, ##__VA_ARGS__)
112 static void __dpl(char * file, int line, int indent, char * format, ...)
113 {
114    va_list args;
115    char string[MAX_F_STRING];
116    int c;
117    char * time = PrintNow();
118    //static File f = null;
119    va_start(args, format);
120    vsnprintf(string, sizeof(string), format, args);
121    string[sizeof(string)-1] = 0;
122    /*if(!f)
123    {
124       char * time = PrintNow();
125       char * logName;
126       logName = PrintString(time, ".log");
127       delete time;
128       f = FileOpen(logName, write);
129       delete logName;
130    }*/
131    /*f.Printf("%s %s:% 5d: ", time, file, line);
132    for(c = 0; c<indent; c++)
133       f.Putc(' ');
134    f.Printf("%s\n", string);*/
135    Logf("%s %s:% 5d: ", time, file, line);
136    for(c = 0; c<indent; c++)
137       Log(" ");
138    Logf("%s\n", string);
139    va_end(args);
140    delete time;
141 }
142
143 public char * StripQuotes2(char * string, char * output)
144 {
145    int c;
146    int d = 0;
147    bool quoted = false, escaped = false;
148    char ch;
149    for(c = 0; ch = string[c]; c++)
150    {
151       if(quoted)
152       {
153          if(escaped || ch != '\"')
154          {
155             output[d++] = ch;
156             escaped = !escaped && ch == '\\';
157          }
158          else
159             quoted = false;
160       }
161       else if(ch == '\"')
162          quoted = true;
163       else
164          output[d++] = ch;
165    }
166    output[d] = '\0';
167    return output;
168 }
169
170 // String Escape Copy
171 static void strescpy(char * d, char * s)
172 {
173    int j = 0, k = 0;
174    char ch;
175    while((ch = s[j]))
176    {
177       switch(ch)
178       {
179          case '\n': d[k] = '\\'; d[++k] = 'n'; break;
180          case '\t': d[k] = '\\'; d[++k] = 't'; break;
181          case '\a': d[k] = '\\'; d[++k] = 'a'; break;
182          case '\b': d[k] = '\\'; d[++k] = 'b'; break;
183          case '\f': d[k] = '\\'; d[++k] = 'f'; break;
184          case '\r': d[k] = '\\'; d[++k] = 'r'; break;
185          case '\v': d[k] = '\\'; d[++k] = 'v'; break;
186          case '\\': d[k] = '\\'; d[++k] = '\\'; break;
187          case '\"': d[k] = '\\'; d[++k] = '\"'; break;
188          default: d[k] = s[j];
189       }
190       j++, k++;
191    }
192    d[k] = '\0';
193 }
194
195 static char * CopyUnescapedSystemPath(char * p)
196 {
197    char * d = new char[strlen(p) + 1];
198    struscpy(d, p);
199 #if defined(__WIN32__)
200    ChangeCh(d, '/', '\\');
201 #endif
202    return d;
203 }
204
205 static char * CopyUnescapedUnixPath(char * p)
206 {
207    char * d = new char[strlen(p) + 1];
208    struscpy(d, p);
209 #if defined(__WIN32__)
210    ChangeCh(d, '\\', '/');
211 #endif
212    return d;
213 }
214
215 static char * CopyUnescapedString(char * s)
216 {
217    char * d = new char[strlen(s) + 1];
218    struscpy(d, s);
219    return d;
220 }
221
222 // String Unescape Copy
223
224 // TOFIX: THIS DOESN'T HANDLE NUMERIC ESCAPE CODES (OCTAL/HEXADECIMAL...)?
225 // Seems very similar to ReadString in pass15.ec (which also misses numeric escape codes :) )
226
227 static void struscpy(char * d, char * s)
228 {
229    int j = 0, k = 0;
230    char ch;
231    while((ch = s[j]))
232    {
233       switch(ch)
234       {
235          case '\\':
236             switch(s[++j])
237             {
238                case 'n': d[k] = '\n'; break;
239                case 't': d[k] = '\t'; break;
240                case 'a': d[k] = '\a'; break;
241                case 'b': d[k] = '\b'; break;
242                case 'f': d[k] = '\f'; break;
243                case 'r': d[k] = '\r'; break;
244                case 'v': d[k] = '\v'; break;
245                case '\\': d[k] = '\\'; break;
246                case '\"': d[k] = '\"'; break;
247                default: d[k] = '\\'; d[++k] = s[j];
248             }
249             break;
250          default:
251             d[k] = s[j];
252       }
253       j++, k++;
254    }
255    d[k] = '\0';
256 }
257
258 static char * StripBrackets(char * string)
259 {
260    int length = strlen(string);
261    if(length > 1 && *string == '[' && string[length - 1] == ']')
262    {
263       *string = '\0';
264       string[length - 1] = '\0';
265       return ++string;
266    }
267    else
268       return string;
269 }
270
271 static char * StripCurlies(char * string)
272 {
273    int length = strlen(string);
274    if(length > 1 && *string == '{' && string[length - 1] == '}')
275    {
276       *string = '\0';
277       string[length - 1] = '\0';
278       return ++string;
279    }
280    else
281       return string;
282 }
283
284 static int StringGetInt(char * string, int start)
285 {
286    char number[8];
287    int i, len = strlen(string);
288    number[0] = '\0';
289    for(i = start; i < len && i < start + 8; i++)
290    {
291       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')
292          strncat(number, &string[i], 1);
293       else
294          break;
295    }
296    return atoi(number);
297 }
298
299 static int TokenizeList(char * string, const char seperator, Array<char *> tokens)
300 {
301    uint level = 0;
302
303    bool quoted = false, escaped = false;
304    char * start = string, ch;
305
306    for(; (ch = *string); string++)
307    {
308       if(!start)
309          start = string;
310
311       if(quoted)
312       {
313          if(escaped || ch != '\"')
314             escaped = !escaped && ch == '\\';
315          else
316             quoted = false;
317       }
318       else if(ch == '\"')
319          quoted = true;
320       else if(ch == '{' || ch == '[' || ch == '(' || ch == '<')
321          level++;
322       else if(ch == '}' || ch == ']' || ch == ')' || ch == '>')
323          level--;
324       else if(ch == seperator && !level)
325       {
326          tokens.Add(start);
327          *string = '\0';
328          start = null;
329       }
330    }
331    if(start)
332    {
333       //tokens[count] = start;
334       //tokens[count++] = start;
335       tokens.Add(start);
336       *string = '\0';
337    }
338    return tokens.count;
339 }
340
341 static bool TokenizeListItem(char * string, DebugListItem item)
342 {
343    char * equal = strstr(string, "=");
344    if(equal)
345    {
346       item.name = string;
347       *equal = '\0';
348       equal++;
349       item.value = equal;
350       return true;
351    }
352    return false;
353 }
354
355 static bool CheckCommandAvailable(const char * command)
356 {
357    bool available = false;
358    int c, count;
359    char * name = new char[MAX_FILENAME];
360    char * pathVar = new char[maxPathLen];
361    char * paths[128];
362    GetEnvironment("PATH", pathVar, maxPathLen);
363    count = TokenizeWith(pathVar, sizeof(paths) / sizeof(char *), paths, pathListSep, false);
364    strcpy(name, command);
365 #ifdef __WIN32__
366    {
367       int e;
368       const char * extensions[] = { "exe", "com", "bat", null };
369       for(e=0; extensions[e]; e++)
370       {
371          ChangeExtension(name, extensions[e], name);
372 #endif
373          for(c=0; c<count; c++)
374          {
375             FileListing fl { paths[c] };
376             while(fl.Find())
377             {
378                if(fl.stats.attribs.isFile && !fstrcmp(fl.name, name))
379                {
380                   available = true;
381                   fl.Stop();
382                   break;
383                }
384             }
385             if(available) break;
386          }
387 #ifdef __WIN32__
388          if(available) break;
389       }
390    }
391 #endif
392    delete name;
393    delete pathVar;
394    return available;
395 }
396
397 // define GdbGetLineSize = 1638400;
398 define GdbGetLineSize = 5638400;
399 #if defined(__unix__)
400 char progFifoPath[MAX_LOCATION];
401 char progFifoDir[MAX_LOCATION];
402 #endif
403
404 enum DebuggerState { none, prompt, loaded, running, stopped, terminated, error };
405 enum DebuggerEvent
406 {
407    none, hit, breakEvent, signal, stepEnd, functionEnd, exit, valgrindStartPause, locationReached;
408
409    property bool canBeMonitored { get { return (this == hit || this == breakEvent || this == signal || this == stepEnd || this == functionEnd || this == locationReached); } };
410 };
411 enum DebuggerAction { none, internal, restart, stop, selectFrame, advance }; //, bpValidation
412 enum DebuggerReason
413 {
414    unknown, endSteppingRange, functionFinished, signalReceived, breakpointHit, locationReached
415    //watchpointTrigger, readWatchpointTrigger, accessWatchpointTrigger, watchpointScope,
416    //exited, exitedNormally, exitedSignalled;
417 };
418 enum BreakpointType
419 {
420    none, internalMain, internalWinMain, internalModulesLoaded, user, runToCursor, internalModuleLoad, internalEntry;
421
422    property bool isInternal { get { return (this == internalMain || this == internalWinMain || this == internalModulesLoaded || this == internalModuleLoad || this == internalEntry); } };
423    property bool isUser { get { return (this == user || this == runToCursor); } };
424 };
425 enum DebuggerEvaluationError { none, symbolNotFound, memoryCantBeRead, unknown };
426 enum DebuggerUserAction
427 {
428    none, start, resume, _break, stop, restart, selectThread, selectFrame, stepInto, stepOver, stepUntil, stepOut, runToCursor;
429    property bool breaksOnInternalBreakpoint { get { return (this == stepInto || this == stepOver || this == stepUntil); } };
430 };
431 enum GdbExecution
432 {
433    none, run, _continue, next, until, advance, step, finish;
434    property bool suspendInternalBreakpoints { get { return (this == until || this == advance || this == step || this == finish); } };
435 };
436
437 FileDialog debuggerFileDialog { type = selectDir };
438
439 static DualPipe vgTargetHandle;
440 static File vgLogFile;
441 static char vgLogPath[MAX_LOCATION];
442 static DualPipe gdbHandle;
443 static DebugEvaluationData eval { };
444
445 static int targetProcessId;
446
447 static bool gdbReady;
448 static bool breakpointError;
449
450 class Debugger
451 {
452    Semaphore serialSemaphore { };
453    bool waitingForPID;
454    bool targeted;
455    bool symbols;
456    bool modules;
457    bool sentKill;
458    bool sentBreakInsert;
459    bool ignoreBreakpoints;
460    bool signalOn;
461    bool needReset;
462    bool usingValgrind;
463
464    int ideProcessId;
465    int gdbProcessId;
466
467    int activeFrameLevel;
468    int activeThread;
469    int hitThread;
470    int signalThread;
471    int frameCount;
472
473    char * targetDir;
474    char * targetFile;
475
476    GdbExecution gdbExecution;
477    DebuggerUserAction userAction;
478    DebuggerState state;
479    DebuggerEvent event;
480    DebuggerAction breakType;
481    char * breakString;
482    //DebuggerCommand lastCommand;    // THE COMPILER COMPILES STUFF THAT DOES NOT EXIST???
483
484    GdbDataStop stopItem;
485    GdbDataBreakpoint bpItem;
486    Frame activeFrame;
487
488    List<Breakpoint> sysBPs { };
489    Breakpoint bpRunToCursor;
490    Breakpoint intBpEntry;
491    Breakpoint intBpMain;
492    Breakpoint intBpWinMain;
493
494    OldList stackFrames;
495
496    CompilerConfig currentCompiler;
497    ProjectConfig prjConfig;
498    int bitDepth;
499
500    CodeEditor codeEditor;
501
502    ValgrindLogThread vgLogThread { debugger = this };
503    ValgrindTargetThread vgTargetThread { debugger = this };
504    GdbThread gdbThread { debugger = this };
505
506    bool entryPoint;
507    Map<String, bool> projectsLibraryLoaded { };
508
509    Timer gdbTimer
510    {
511       delay = 0.0, userData = this;
512
513       bool DelayExpired()
514       {
515          bool monitor = false;
516          DebuggerEvent curEvent = event;
517          GdbDataStop stopItem = this.stopItem;
518          Breakpoint bpUser = null;
519          Breakpoint bpInternal = null;
520
521          if(!gdbReady)
522             return false;
523
524          event = none;
525          if(this.stopItem)
526          {
527             this.stopItem = null;
528 #ifdef _DEBUG_INST
529             {
530                char * s = null;
531                DynamicString bpReport { };
532
533                for(bp : sysBPs; bp.inserted)
534                {
535                   bpReport.concatx(",", bp.type, "(", s=bp.CopyLocationString(false), ")");
536                   delete s;
537                }
538                if(bpRunToCursor && bpRunToCursor.inserted)
539                {
540                   Breakpoint bp = bpRunToCursor;
541                   bpReport.concatx(",", bp.type, "(", s=bp.CopyLocationString(false), ")");
542                   delete s;
543                }
544                for(bp : ide.workspace.breakpoints; bp.inserted)
545                {
546                   bpReport.concatx(",", bp.type, "(", s=bp.CopyLocationString(false), ")");
547                   delete s;
548                }
549                s = bpReport;
550                _dpl2(_dpct, dplchan::debuggerBreakpoints, 0, "gdbTimer::DelayExpired: ", s+1);
551
552                if(stopItem.bkptno)
553                {
554                   bool isInternal;
555                   Breakpoint bp = GetBreakpointById(stopItem.bkptno, &isInternal);
556                   if(bp)
557                   {
558                      _dpl2(_dpct, dplchan::debuggerBreakpoints, 0, "gdb stopped by a breakpoint: ", bp.type, "(", s=bp.CopyLocationString(false), ")");
559                      delete s;
560                   }
561                }
562                delete bpReport;
563             }
564 #endif
565          }
566 #ifdef _DEBUG_INST
567          else
568          {
569             if(curEvent && curEvent != exit)
570             {
571                _dpl(0, "No stop item");
572             }
573          }
574 #endif
575          switch(breakType)
576          {
577             case restart:
578                breakType = none;
579                Restart(currentCompiler, prjConfig, bitDepth, usingValgrind);
580                break;
581             case stop:
582                breakType = none;
583                Stop();
584                break;
585             case selectFrame:
586             {
587                breakType = none;
588                GdbCommand(0, false, "-stack-select-frame %d", activeFrameLevel);
589                for(activeFrame = stackFrames.first; activeFrame; activeFrame = activeFrame.next)
590                   if(activeFrame.level == activeFrameLevel)
591                      break;
592                break;
593             }
594             //case bpValidation:
595             //   breakType = none;
596             //   GdbCommand(0, false, "-break-info %s", bpItem.number);
597             //   break;
598          }
599
600          if(curEvent == none)
601             return false;
602
603          switch(curEvent)
604          {
605             case hit:
606                {
607                   bool isInternal;
608                   Breakpoint bp = stopItem ? GetBreakpointById(stopItem.bkptno, &isInternal) : null;
609                   if(bp && bp.inserted && bp.bp.addr)
610                   {
611                      if(bp.type.isInternal)
612                         bpInternal = bp;
613                      else
614                         bpUser = bp;
615                      if(stopItem && stopItem.frame)
616                      {
617                         if(bpInternal && bpRunToCursor && bpRunToCursor.inserted && !strcmp(bpRunToCursor.bp.addr, bp.bp.addr))
618                            bpUser = bpRunToCursor;
619                         else
620                         {
621                            for(item : (bpInternal ? ide.workspace.breakpoints : sysBPs); item.inserted)
622                            {
623                               if(item.bp && item.bp.addr && !strcmp(item.bp.addr, bp.bp.addr))
624                               {
625                                  if(bpInternal)
626                                     bpUser = item;
627                                  else
628                                     bpInternal = item;
629                                  break;
630                               }
631                            }
632                         }
633                      }
634                      else
635                         _dpl2(_dpct, dplchan::debuggerProblem, 0, "Invalid stopItem!");
636                      if(bpUser && strcmp(stopItem.frame.addr, bpUser.bp.addr))
637                         _dpl2(_dpct, dplchan::debuggerProblem, 0, "Breakpoint bkptno(", stopItem.bkptno, ") address missmatch!");
638                   }
639                   else
640                      _dpl2(_dpct, dplchan::debuggerProblem, 0, "Breakpoint bkptno(", stopItem.bkptno, ") invalid or not found!");
641                   if((bpUser && !ignoreBreakpoints) || (bpInternal && userAction.breaksOnInternalBreakpoint))
642                      monitor = true;
643                   hitThread = stopItem.threadid;
644                }
645                break;
646             case signal:
647                signalThread = stopItem.threadid;
648             case breakEvent:
649             case stepEnd:
650             case functionEnd:
651             case locationReached:
652                monitor = true;
653                ignoreBreakpoints = false;
654                break;
655             case valgrindStartPause:
656                GdbExecContinue(true);
657                monitor = false;
658                break;
659             case exit:
660                HideDebuggerViews();
661                break;
662          }
663
664          if(curEvent == signal)
665          {
666             char * s = null;
667             signalOn = true;
668             ide.outputView.debugBox.Logf($"Signal received: %s - %s\n", stopItem.name, stopItem.meaning);
669             ide.outputView.debugBox.Logf("    %s:%d\n", (s = CopySystemPath(stopItem.frame.file)), stopItem.frame.line);
670             ide.outputView.Show();
671             ide.callStackView.Show();
672             delete s;
673          }
674          else if(curEvent == breakEvent)
675          {
676             ide.threadsView.Show();
677             ide.callStackView.Show();
678             ide.callStackView.Activate();
679          }
680          else if(curEvent == hit)
681          {
682             if(BreakpointHit(stopItem, bpInternal, bpUser))
683             {
684                ide.AdjustDebugMenus();
685                if(bpUser && bpUser.type == runToCursor)
686                {
687                   ignoreBreakpoints = false;
688                   UnsetBreakpoint(bpUser);
689                   delete bpRunToCursor;
690                }
691             }
692             else
693             {
694                if(breakType == advance && bpInternal && (bpInternal.type == internalMain || bpInternal.type == internalEntry))
695                {
696                   breakType = none;
697                   GdbExecAdvance(breakString, 0);
698                   delete breakString;
699                }
700                else
701                {
702                   GdbExecContinue(false);
703                   monitor = false;
704                }
705             }
706          }
707
708          if(monitor && curEvent.canBeMonitored)
709          {
710             GdbGetStack();
711             activeThread = stopItem.threadid;
712             GdbCommand(0, false, "-thread-list-ids");
713             InternalSelectFrame(activeFrameLevel);
714             GoToStackFrameLine(activeFrameLevel, true, false);
715             EvaluateWatches();
716             ide.ShowCodeEditor();
717             ide.AdjustDebugMenus();
718             ideMainFrame.Activate();   // TOFIX: ide.Activate() is not reliable (app inactive)
719             ide.Update(null);
720          }
721
722          if(stopItem)
723          {
724             stopItem.Free();
725             delete stopItem;
726          }
727          return false;
728       }
729    };
730
731 #ifdef GDB_DEBUG_CONSOLE
732    char lastGdbOutput[GdbGetLineSize];
733 #endif
734 #if defined(__unix__)
735    ProgramThread progThread { };
736 #endif
737
738 #ifdef _DEBUG_INST
739 #define _ChangeUserAction(value) ChangeUserAction(__FILE__, __LINE__, value)
740    void ChangeUserAction(char * file, int line, DebuggerUserAction value)
741    {
742       bool same = value == userAction;
743       __dpl2(file, line, _dpct, dplchan::debuggerUserAction, 0, userAction, /*same ? " *** == *** " : */" -> ", value);
744       userAction = value;
745    }
746 #else
747 #define _ChangeUserAction(value) userAction = value
748 #endif
749
750 #ifdef _DEBUG_INST
751 #define _ChangeState(value) ChangeState(__FILE__, __LINE__, value)
752    void ChangeState(char * file, int line, DebuggerState value)
753 #else
754 #define _ChangeState(value) ChangeState(value)
755    void ChangeState(DebuggerState value)
756 #endif
757    {
758       bool same = value == state;
759 #ifdef _DEBUG_INST
760       __dpl2(file, line, _dpct, dplchan::debuggerState, 0, state, same ? " *** == *** " : " -> ", value);
761 #endif
762       state = value;
763       if(!same) ide.AdjustDebugMenus();
764    }
765
766    void CleanUp()
767    {
768       _dpl2(_dpct, dplchan::debuggerCall, 0, "Debugger::CleanUp");
769
770       stackFrames.Free(Frame::Free);
771
772       delete targetDir;
773       delete targetFile;
774
775       ClearBreakDisplay();
776
777       // Clear Stuff up
778       gdbProcessId = 0;
779
780       waitingForPID = false;
781       targeted = false;
782       symbols = false;
783       modules = false;
784       sentKill = false;
785       sentBreakInsert = false;
786       ignoreBreakpoints = false;
787       signalOn = false;
788
789       activeFrameLevel = 0;
790       activeThread = 0;
791       hitThread = 0;
792       signalThread = 0;
793       frameCount = 0;
794
795       targetDir = null;
796       targetFile = null;
797
798       _ChangeState(none);
799       event = none;
800       breakType = none;
801
802       delete stopItem;
803       delete bpItem;
804       activeFrame = 0;
805
806       bpRunToCursor = null;
807
808       delete currentCompiler;
809       prjConfig = null;
810
811       WatchesReleaseCodeEditor();
812
813       entryPoint = false;
814       projectsLibraryLoaded.Free();
815
816       /*GdbThread gdbThread
817       Timer gdbTimer*/
818    }
819
820    Debugger()
821    {
822       _dpl2(_dpct, dplchan::debuggerCall, 0, "Debugger::constructor");
823       ideProcessId = Process_GetCurrentProcessId();
824
825       sysBPs.Add((intBpEntry = Breakpoint { type = internalEntry, enabled = false, level = -1 }));
826       sysBPs.Add((intBpMain = Breakpoint { type = internalMain, function = "main", enabled = true, level = -1 }));
827 #if defined(__WIN32__)
828       sysBPs.Add((intBpWinMain = Breakpoint { type = internalWinMain, function = "WinMain", enabled = true, level = -1 }));
829 #endif
830       sysBPs.Add(Breakpoint { type = internalModulesLoaded, enabled = true, level = -1 });
831       sysBPs.Add(Breakpoint { type = internalModuleLoad, function = "InternalModuleLoadBreakpoint", enabled = true, level = -1 });
832    }
833
834    ~Debugger()
835    {
836       _dpl2(_dpct, dplchan::debuggerCall, 0, "Debugger::destructor");
837       sysBPs.Free();
838       Stop();
839       CleanUp();
840    }
841
842    // PUBLIC MEMBERS
843
844    property bool isActive { get { return state == running || state == stopped; } }
845    property bool isPrepared  { get { return state == loaded || state == running || state == stopped; } }
846
847    void Resume()
848    {
849       _dpl2(_dpct, dplchan::debuggerCall, 0, "Debugger::Resume");
850       _ChangeUserAction(resume);
851       GdbExecContinue(true);
852    }
853
854    void Break()
855    {
856       _dpl2(_dpct, dplchan::debuggerCall, 0, "Debugger::Break");
857       _ChangeUserAction(_break);
858       if(state == running)
859       {
860          if(targetProcessId)
861             GdbDebugBreak(false);
862       }
863    }
864
865    void Stop()
866    {
867       _dpl2(_dpct, dplchan::debuggerCall, 0, "Debugger::Stop");
868       _ChangeUserAction(stop);
869       switch(state)
870       {
871          case running:
872             if(targetProcessId)
873             {
874                breakType = stop;
875                GdbDebugBreak(false);
876             }
877             break;
878          case stopped:
879             GdbAbortExec();
880             HideDebuggerViews();
881             GdbExit();
882             break;
883          case loaded:
884             GdbExit();
885             break;
886       }
887    }
888
889    void Restart(CompilerConfig compiler, ProjectConfig config, int bitDepth, bool useValgrind)
890    {
891       _dpl2(_dpct, dplchan::debuggerCall, 0, "Debugger::Restart");
892       _ChangeUserAction(restart);
893       if(StartSession(compiler, config, bitDepth, useValgrind, true, false) == loaded)
894          GdbExecRun();
895    }
896
897    bool GoToCodeLine(char * location)
898    {
899       CodeLocation codloc;
900       _dpl2(_dpct, dplchan::debuggerCall, 0, "Debugger::GoToCodeLine(", location, ")");
901       codloc = CodeLocation::ParseCodeLocation(location);
902       if(codloc)
903       {
904          CodeEditor editor = (CodeEditor)ide.OpenFile(codloc.absoluteFile, normal, true, null, no, normal, false);
905          if(editor)
906          {
907             EditBox editBox = editor.editBox;
908             editBox.GoToLineNum(codloc.line - 1);
909             editBox.GoToPosition(editBox.line, codloc.line - 1, 0);
910             return true;
911          }
912       }
913       return false;
914    }
915
916    bool GoToStackFrameLine(int stackLevel, bool askForLocation, bool fromCallStack)
917    {
918       _dpl2(_dpct, dplchan::debuggerCall, 0, "Debugger::GoToStackFrameLine(", stackLevel, ", ", askForLocation, ")");
919       if(ide)
920       {
921          char filePath[MAX_LOCATION];
922          char sourceDir[MAX_LOCATION];
923          Frame frame;
924          CodeEditor editor = null;
925          if(stackLevel == -1)  // this (the two lines) is part of that fix that I would not put in for some time
926             return false;
927          for(frame = stackFrames.first; frame; frame = frame.next)
928             if(frame.level == stackLevel)
929                break;
930          if(frame)
931          {
932             if(!fromCallStack)
933                ide.callStackView.Show();
934
935             if(frame.absoluteFile)
936                editor = (CodeEditor)ide.OpenFile(frame.absoluteFile, normal, true, null, no, normal, false);
937             if(!editor && frame.file)
938                frame.absoluteFile = ide.workspace.GetAbsolutePathFromRelative(frame.file);
939             if(!frame.absoluteFile && askForLocation && frame.file)
940             {
941                char * s = null;
942                char title[MAX_LOCATION];
943                snprintf(title, sizeof(title), $"Provide source file location for %s", (s = CopySystemPath(frame.file)));
944                title[sizeof(title)-1] = 0;
945                delete s;
946                if(SourceDirDialog(title, ide.workspace.projectDir, frame.file, sourceDir))
947                {
948                   AddSourceDir(sourceDir);
949                   frame.absoluteFile = ide.workspace.GetAbsolutePathFromRelative(frame.file);
950                }
951             }
952             if(!editor && frame.absoluteFile)
953                editor = (CodeEditor)ide.OpenFile(frame.absoluteFile, normal, true, null, no, normal, false);
954             if(editor)
955                ide.RepositionWindows(false);
956             ide.Update(null);
957             if(editor && frame.line)
958             {
959                EditBox editBox = editor.editBox;
960                editBox.GoToLineNum(frame.line - 1);
961                editBox.GoToPosition(editBox.line, frame.line - 1, 0);
962                return true;
963             }
964          }
965       }
966       return false;
967    }
968
969    void SelectThread(int thread)
970    {
971       _dpl2(_dpct, dplchan::debuggerCall, 0, "Debugger::SelectThread(", thread, ")");
972       _ChangeUserAction(selectThread);
973       if(state == stopped)
974       {
975          if(thread != activeThread)
976          {
977             activeFrameLevel = -1;
978             ide.callStackView.Clear();
979             GdbCommand(0, false, "-thread-select %d", thread);
980             GdbGetStack();
981             InternalSelectFrame(activeFrameLevel);
982             GoToStackFrameLine(activeFrameLevel, true, false);
983             EvaluateWatches();
984             ide.Update(null);
985          }
986          ide.callStackView.Show();
987       }
988    }
989
990    void SelectFrame(int frame)
991    {
992       //_dpl2(_dpct, dplchan::debuggerCall, 0, "Debugger::SelectFrame(", frame, ")");
993       _ChangeUserAction(selectFrame);
994       if(state == stopped)
995       {
996          if(frame != activeFrameLevel)
997          {
998             InternalSelectFrame(frame);
999             EvaluateWatches();
1000             ide.Update(null);
1001          }
1002       }
1003    }
1004
1005    void InternalSelectFrame(int frame)
1006    {
1007       //_dpl2(_dpct, dplchan::debuggerCall, 0, "Debugger::InternalSelectFrame(", frame, ")");
1008       activeFrameLevel = frame;  // there is no active frame number in the gdb reply
1009       GdbCommand(0, false, "-stack-select-frame %d", activeFrameLevel);
1010       for(activeFrame = stackFrames.first; activeFrame; activeFrame = activeFrame.next)
1011          if(activeFrame.level == activeFrameLevel)
1012             break;
1013    }
1014
1015    void HandleExit(char * reason, char * code)
1016    {
1017       bool returnedExitCode = false;
1018       char verboseExitCode[128];
1019
1020       _dpl2(_dpct, dplchan::debuggerCall, 0, "Debugger::HandleExit(", reason, ", ", code, ")");
1021       _ChangeState(loaded); // this state change seems to be superfluous, might be in case of gdb crash
1022       targetProcessId = 0;
1023
1024       if(code)
1025       {
1026          snprintf(verboseExitCode, sizeof(verboseExitCode), $" with exit code %s", code);
1027          verboseExitCode[sizeof(verboseExitCode)-1] = 0;
1028       }
1029       else
1030          verboseExitCode[0] = '\0';
1031
1032       event = exit;
1033
1034       // ClearBreakDisplay();
1035
1036       if(ide.workspace)
1037       {
1038          for(wh : ide.workspace.watches)
1039          {
1040             if(wh.type) FreeType(wh.type);
1041             wh.type = null;
1042             delete wh.value;
1043             ide.watchesView.UpdateWatch(wh);
1044          }
1045       }
1046
1047 #if defined(__unix__)
1048       if(!usingValgrind)
1049       {
1050          progThread.terminate = true;
1051          if(fifoFile)
1052          {
1053             fifoFile.CloseInput();
1054             app.Unlock();
1055             progThread.Wait();
1056             app.Lock();
1057             delete fifoFile;
1058          }
1059       }
1060 #endif
1061
1062       {
1063          char program[MAX_LOCATION];
1064          GetSystemPathBuffer(program, targetFile);
1065          if(!reason)
1066             ide.outputView.debugBox.Logf($"The program %s has exited%s.\n", program, verboseExitCode);
1067          else if(!strcmp(reason, "exited-normally"))
1068             ide.outputView.debugBox.Logf($"The program %s has exited normally%s.\n", program, verboseExitCode);
1069          else if(!strcmp(reason, "exited"))
1070             ide.outputView.debugBox.Logf($"The program %s has exited%s.\n", program, verboseExitCode);
1071          else if(!strcmp(reason, "exited-signalled"))
1072             ide.outputView.debugBox.Logf($"The program %s has exited with a signal%s.\n", program, verboseExitCode);
1073          else
1074             ide.outputView.debugBox.Logf($"The program %s has exited (gdb provided an unknown reason)%s.\n", program, verboseExitCode);
1075       }
1076       ide.Update(null);
1077    }
1078
1079    DebuggerState StartSession(CompilerConfig compiler, ProjectConfig config, int bitDepth, bool useValgrind, bool restart, bool ignoreBreakpoints)
1080    {
1081       DebuggerState result = none;
1082       _dpl2(_dpct, dplchan::debuggerCall, 0, "Debugger::StartSession(restart(", restart, "), ignoreBreakpoints(", ignoreBreakpoints, ")");
1083       if(restart && state == running && targetProcessId)
1084       {
1085          breakType = DebuggerAction::restart;
1086          GdbDebugBreak(false);
1087       }
1088       else
1089       {
1090          if(restart && state == stopped)
1091             GdbAbortExec();
1092          if(needReset && state == loaded)
1093             GdbExit(); // this reset is to get a clean state with all the breakpoints until a better state can be maintained on program exit
1094          result = state;
1095          if(result == none || result == terminated)
1096          {
1097             ide.outputView.ShowClearSelectTab(debug);
1098             ide.outputView.debugBox.Logf($"Starting debug mode\n");
1099
1100             for(bp : sysBPs)
1101             {
1102                bp.hits = 0;
1103                bp.breaks = 0;
1104             }
1105             for(bp : ide.workspace.breakpoints)
1106             {
1107                bp.hits = 0;
1108                bp.breaks = 0;
1109             }
1110
1111             if(GdbInit(compiler, config, bitDepth, useValgrind))
1112                result = state;
1113             else
1114                result = error;
1115          }
1116          this.ignoreBreakpoints = ignoreBreakpoints;
1117       }
1118       return result;
1119    }
1120
1121    void Start(CompilerConfig compiler, ProjectConfig config, int bitDepth, bool useValgrind)
1122    {
1123       _dpl2(_dpct, dplchan::debuggerCall, 0, "Debugger::Start()");
1124       _ChangeUserAction(start);
1125       if(StartSession(compiler, config, bitDepth, useValgrind, true, false) == loaded)
1126          GdbExecRun();
1127    }
1128
1129    void StepInto(CompilerConfig compiler, ProjectConfig config, int bitDepth, bool useValgrind)
1130    {
1131       _dpl2(_dpct, dplchan::debuggerCall, 0, "Debugger::StepInto()");
1132       _ChangeUserAction(stepInto);
1133       switch(StartSession(compiler, config, bitDepth, useValgrind, false, false))
1134       {
1135          case loaded:  GdbExecRun();  break;
1136          case stopped: GdbExecStep(); break;
1137       }
1138    }
1139
1140    void StepOver(CompilerConfig compiler, ProjectConfig config, int bitDepth, bool useValgrind, bool ignoreBreakpoints)
1141    {
1142       _dpl2(_dpct, dplchan::debuggerCall, 0, "Debugger::StepOver()");
1143       _ChangeUserAction(stepOver);
1144       switch(StartSession(compiler, config, bitDepth, useValgrind, false, ignoreBreakpoints))
1145       {
1146          case loaded:  GdbExecRun();  break;
1147          case stopped: GdbExecNext(); break;
1148       }
1149    }
1150
1151    void StepUntil(CompilerConfig compiler, ProjectConfig config, int bitDepth, bool useValgrind, bool ignoreBreakpoints)
1152    {
1153       _dpl2(_dpct, dplchan::debuggerCall, 0, "Debugger::StepUntil()");
1154       _ChangeUserAction(stepUntil);
1155       switch(StartSession(compiler, config, bitDepth, useValgrind, false, ignoreBreakpoints))
1156       {
1157          case loaded:  GdbExecRun();          break;
1158          case stopped: GdbExecUntil(null, 0); break;
1159       }
1160    }
1161
1162    void StepOut(bool ignoreBreakpoints)
1163    {
1164       _dpl2(_dpct, dplchan::debuggerCall, 0, "Debugger::StepOut()");
1165       _ChangeUserAction(stepOut);
1166       if(state == stopped)
1167       {
1168          this.ignoreBreakpoints = ignoreBreakpoints;
1169          if(frameCount > 1)
1170             GdbExecFinish();
1171          else
1172             GdbExecContinue(true);
1173       }
1174    }
1175
1176    void RunToCursor(CompilerConfig compiler, ProjectConfig config, int bitDepth, bool useValgrind, char * absoluteFilePath, int lineNumber, bool ignoreBreakpoints, bool atSameLevel, bool oldImplementation)
1177    {
1178       char relativeFilePath[MAX_LOCATION];
1179       _dpl2(_dpct, dplchan::debuggerCall, 0, "Debugger::RunToCursor()");
1180       _ChangeUserAction(runToCursor);
1181       WorkspaceGetRelativePath(absoluteFilePath, relativeFilePath, null);
1182
1183       if(bpRunToCursor && bpRunToCursor.inserted && symbols)
1184       {
1185          UnsetBreakpoint(bpRunToCursor);
1186          delete bpRunToCursor;
1187       }
1188
1189       StartSession(compiler, config, bitDepth, useValgrind, false, ignoreBreakpoints);
1190
1191 #if 0
1192       if(oldImplementation)
1193       {
1194          bpRunToCursor = Breakpoint { };
1195          bpRunToCursor.absoluteFilePath = absoluteFilePath;
1196          bpRunToCursor.relativeFilePath = relativeFilePath;
1197          bpRunToCursor.line = lineNumber;
1198          bpRunToCursor.type = runToCursor;
1199          bpRunToCursor.enabled = true;
1200          bpRunToCursor.level = atSameLevel ? frameCount - activeFrameLevel -1 : -1;
1201       }
1202 #endif
1203       if(state == loaded)
1204       {
1205          breakType = advance;
1206          breakString = PrintString(relativeFilePath, ":", lineNumber);
1207          GdbExecRun();
1208       }
1209       else if(state == stopped)
1210       {
1211          if(oldImplementation)
1212             GdbExecContinue(true);
1213          else
1214          {
1215             if(atSameLevel)
1216                GdbExecUntil(absoluteFilePath, lineNumber);
1217             else
1218                GdbExecAdvance(absoluteFilePath, lineNumber);
1219          }
1220       }
1221    }
1222
1223    void GetCallStackCursorLine(bool * error, int * lineCursor, int * lineTopFrame)
1224    {
1225       //_dpl2(_dpct, dplchan::debuggerCall, 0, "Debugger::GetCallStackCursorLine()");
1226       if(activeFrameLevel == -1)
1227       {
1228          *error = false;
1229          *lineCursor = 0;
1230          *lineTopFrame = 0;
1231       }
1232       else
1233       {
1234          *error = signalOn && activeThread == signalThread;
1235          *lineCursor = activeFrameLevel - ((frameCount > 192 && activeFrameLevel > 191) ? frameCount - 192 - 1 : 0) + 1;
1236          *lineTopFrame = activeFrameLevel ? 1 : 0;
1237       }
1238    }
1239
1240    int GetMarginIconsLineNumbers(char * fileName, int lines[], bool enabled[], int max, bool * error, int * lineCursor, int * lineTopFrame)
1241    {
1242       char winFilePath[MAX_LOCATION];
1243       char * absoluteFilePath = GetSlashPathBuffer(winFilePath, fileName);
1244       int count = 0;
1245       Iterator<Breakpoint> it { ide.workspace.breakpoints };
1246       //_dpl2(_dpct, dplchan::debuggerCall, 0, "Debugger::GetMarginIconsLineNumbers()");
1247       while(it.Next() && count < max)
1248       {
1249          Breakpoint bp = it.data;
1250          if(bp.type == user)
1251          {
1252             if(bp.absoluteFilePath && bp.absoluteFilePath[0] && !fstrcmp(bp.absoluteFilePath, absoluteFilePath))
1253             {
1254                lines[count] = bp.line;
1255                enabled[count] = bp.enabled;
1256                count++;
1257             }
1258          }
1259       }
1260       if(activeFrameLevel == -1)
1261       {
1262          *error = false;
1263          *lineCursor = 0;
1264          *lineTopFrame = 0;
1265       }
1266       else
1267       {
1268          *error = signalOn && activeThread == signalThread;
1269          if(activeFrame && activeFrame.absoluteFile && !fstrcmp(absoluteFilePath, activeFrame.absoluteFile))
1270             *lineCursor = activeFrame.line;
1271          else
1272             *lineCursor = 0;
1273          if(activeFrame && stopItem && stopItem.frame && activeFrame.level == stopItem.frame.level)
1274             *lineTopFrame = 0;
1275          else if(stopItem && stopItem.frame && stopItem.frame.absoluteFile && !fstrcmp(absoluteFilePath, stopItem.frame.absoluteFile))
1276             *lineTopFrame = stopItem.frame.line;
1277          else
1278             *lineTopFrame = 0;
1279
1280          if(*lineTopFrame == *lineCursor && *lineTopFrame)
1281             *lineTopFrame = 0;
1282       }
1283       return count;
1284    }
1285
1286    void ChangeWatch(DataRow row, char * expression)
1287    {
1288       Watch wh = (Watch)row.tag;
1289       //_dpl2(_dpct, dplchan::debuggerCall, 0, "Debugger::ChangeWatch(", expression, ")");
1290       if(wh)
1291       {
1292          delete wh.expression;
1293          if(expression)
1294             wh.expression = CopyString(expression);
1295          else
1296          {
1297             Iterator<Watch> it { ide.workspace.watches };
1298             if(it.Find(wh))
1299                ide.workspace.watches.Delete(it.pointer);
1300          }
1301       }
1302       else if(expression)
1303       {
1304          wh = Watch { };
1305          row.tag = (int64)wh;
1306          ide.workspace.watches.Add(wh);
1307          wh.row = row;
1308          wh.expression = CopyString(expression);
1309       }
1310       ide.workspace.Save();
1311       //if(expression && state == stopped)
1312       if(expression)
1313          ResolveWatch(wh);
1314    }
1315
1316    void MoveIcons(char * fileName, int lineNumber, int move, bool start)
1317    {
1318       char winFilePath[MAX_LOCATION];
1319       char * absoluteFilePath = GetSlashPathBuffer(winFilePath, fileName);
1320
1321       Link bpLink, next;
1322       //_dpl2(_dpct, dplchan::debuggerCall, 0, "Debugger::MoveIcons()");
1323       for(bpLink = ide.workspace.breakpoints.first; bpLink; bpLink = next)
1324       {
1325          Breakpoint bp = (Breakpoint)bpLink.data;
1326          next = bpLink.next;
1327
1328          if(bp.type == user && bp.absoluteFilePath && !fstrcmp(bp.absoluteFilePath, absoluteFilePath))
1329          {
1330             if(bp.line > lineNumber || (bp.line == lineNumber && start))
1331             {
1332                if(move < 0 && (bp.line < lineNumber - move))
1333                   ide.workspace.RemoveBreakpoint(bp);
1334                else
1335                {
1336                   bp.line += move;
1337                   ide.breakpointsView.UpdateBreakpoint(bp.row);
1338                   ide.workspace.Save();
1339                }
1340             }
1341          }
1342       }
1343
1344       // moving code cursors is futile, on next step, stop, hit, cursors will be offset anyways
1345    }
1346
1347    bool SourceDirDialog(char * title, char * startDir, char * test, char * sourceDir)
1348    {
1349       bool result;
1350       bool retry;
1351       String srcDir = null;
1352
1353       _dpl2(_dpct, dplchan::debuggerCall, 0, "Debugger::SourceDirDialog()");
1354       debuggerFileDialog.text = title;
1355       debuggerFileDialog.currentDirectory = startDir;
1356       debuggerFileDialog.master = ide;
1357
1358       while(debuggerFileDialog.Modal())
1359       {
1360          strcpy(sourceDir, debuggerFileDialog.filePath);
1361          if(!fstrcmp(ide.workspace.projectDir, sourceDir) &&
1362                   MessageBox { type = yesNo, master = ide,
1363                               contents = $"This is the project directory.\nWould you like to try again?",
1364                               text = $"Invalid Source Directory" }.Modal() == no)
1365             return false;
1366          else
1367          {
1368             for(dir : ide.workspace.sourceDirs)
1369             {
1370                if(!fstrcmp(dir, sourceDir))
1371                {
1372                   srcDir = dir;
1373                   break;
1374                }
1375             }
1376
1377             if(srcDir &&
1378                   MessageBox { type = yesNo, master = ide,
1379                               contents = $"This source directory is already specified.\nWould you like to try again?",
1380                               text = $"Invalid Source Directory" }.Modal() == no)
1381                return false;
1382             else
1383             {
1384                if(test)
1385                {
1386                   char file[MAX_LOCATION];
1387                   strcpy(file, sourceDir);
1388                   PathCat(file, test);
1389                   result = FileExists(file);
1390                   if(!result &&
1391                         MessageBox { type = yesNo, master = ide,
1392                                     contents = $"Unable to locate source file.\nWould you like to try again?",
1393                                     text = $"Invalid Source Directory" }.Modal() == no)
1394                         return false;
1395                }
1396                else
1397                   result = true;
1398
1399                if(result)
1400                   return true;
1401             }
1402          }
1403       }
1404       return false;
1405    }
1406
1407    void AddSourceDir(char * sourceDir)
1408    {
1409       _dpl2(_dpct, dplchan::debuggerCall, 0, "Debugger::AddSourceDir(", sourceDir, ")");
1410       ide.workspace.sourceDirs.Add(CopyString(sourceDir));
1411       ide.workspace.Save();
1412
1413       if(targeted)
1414       {
1415          DebuggerState oldState = state;
1416          switch(state)
1417          {
1418             case running:
1419                if(targetProcessId)
1420                   GdbDebugBreak(true);
1421             case stopped:
1422             case loaded:
1423                GdbCommand(0, false, "-environment-directory \"%s\"", sourceDir);
1424                break;
1425          }
1426          if(oldState == running)
1427             GdbExecContinue(false);
1428       }
1429    }
1430
1431    void ToggleBreakpoint(char * fileName, int lineNumber)
1432    {
1433       char absolutePath[MAX_LOCATION];
1434       Breakpoint bp = null;
1435
1436       _dpl2(_dpct, dplchan::debuggerBreakpoints, 0, "Debugger::ToggleBreakpoint(", fileName, ":", lineNumber, ")");
1437
1438       GetSlashPathBuffer(absolutePath, fileName);
1439       for(i : ide.workspace.breakpoints; i.type == user && i.absoluteFilePath && !fstrcmp(i.absoluteFilePath, absolutePath) && i.line == lineNumber)
1440       {
1441          bp = i;
1442          break;
1443       }
1444       if(bp)
1445       {
1446          if(bp.enabled)
1447          {
1448             ide.workspace.RemoveBreakpoint(bp);
1449             bp = null;
1450          }
1451          else
1452             bp.enabled = true;
1453       }
1454       else
1455       {
1456          Project owner;
1457          char relativePath[MAX_LOCATION];
1458
1459          WorkspaceGetRelativePath(absolutePath, relativePath, &owner);
1460
1461          if(!owner && !FileExists(absolutePath))
1462          {
1463             char title[MAX_LOCATION];
1464             char directory[MAX_LOCATION];
1465             char sourceDir[MAX_LOCATION];
1466             StripLastDirectory(absolutePath, directory);
1467             snprintf(title, sizeof(title), $"Provide source files location directory for %s", relativePath);
1468             title[sizeof(title)-1] = 0;
1469             while(true)
1470             {
1471                String srcDir = null;
1472                for(dir : ide.workspace.sourceDirs)
1473                {
1474                   if(IsPathInsideOf(absolutePath, dir))
1475                   {
1476                      MakePathRelative(absolutePath, dir, relativePath);
1477                      srcDir = dir;
1478                      break;
1479                   }
1480                }
1481                if(srcDir)
1482                   break;
1483
1484                if(SourceDirDialog(title, directory, null, sourceDir))
1485                {
1486                   if(IsPathInsideOf(absolutePath, sourceDir))
1487                   {
1488                      AddSourceDir(sourceDir);
1489                      MakePathRelative(absolutePath, sourceDir, relativePath);
1490                      break;
1491                   }
1492                   else if(MessageBox { type = yesNo, master = ide,
1493                                  contents = $"You must provide a valid source directory in order to place a breakpoint in this file.\nWould you like to try again?",
1494                                  text = $"Invalid Source Directory" }.Modal() == no)
1495                      return;
1496                }
1497                else
1498                   return;
1499             }
1500          }
1501          ide.workspace.bpCount++;
1502          bp = { line = lineNumber, type = user, enabled = true, level = -1, project = owner };
1503          ide.workspace.breakpoints.Add(bp);
1504          bp.absoluteFilePath = absolutePath;
1505          bp.relativeFilePath = relativePath;
1506          ide.breakpointsView.AddBreakpoint(bp);
1507       }
1508
1509       if(bp && targeted)
1510       {
1511          DebuggerState oldState = state;
1512          switch(state)
1513          {
1514             case running:
1515                if(targetProcessId)
1516                   GdbDebugBreak(true);
1517             case stopped:
1518             case loaded:
1519                SetBreakpoint(bp, false);
1520                break;
1521          }
1522          if(oldState == running)
1523             GdbExecContinue(false);
1524       }
1525
1526       ide.workspace.Save();
1527    }
1528
1529    void UpdateRemovedBreakpoint(Breakpoint bp)
1530    {
1531       _dpl2(_dpct, dplchan::debuggerCall, 0, "Debugger::UpdateRemovedBreakpoint()");
1532       if(targeted && bp.inserted)
1533       {
1534          DebuggerState oldState = state;
1535          switch(state)
1536          {
1537             case running:
1538                if(targetProcessId)
1539                   GdbDebugBreak(true);
1540             case stopped:
1541             case loaded:
1542                UnsetBreakpoint(bp);
1543                break;
1544          }
1545          if(oldState == running)
1546             GdbExecContinue(false);
1547       }
1548    }
1549
1550    // PRIVATE MEMBERS
1551
1552    void ParseFrame(Frame frame, char * string)
1553    {
1554       int i, j, k;
1555       Array<char *> frameTokens { minAllocSize = 50 };
1556       Array<char *> argsTokens { minAllocSize = 50 };
1557       Array<char *> argumentTokens { minAllocSize = 50 };
1558       DebugListItem item { };
1559       Argument arg;
1560
1561       //_dpl2(_dpct, dplchan::debuggerCall, 0, "Debugger::ParseFrame()");
1562       TokenizeList(string, ',', frameTokens);
1563       for(i = 0; i < frameTokens.count; i++)
1564       {
1565          if(TokenizeListItem(frameTokens[i], item))
1566          {
1567             StripQuotes(item.value, item.value);
1568             if(!strcmp(item.name, "level"))
1569                frame.level = atoi(item.value);
1570             else if(!strcmp(item.name, "addr"))
1571                frame.addr = item.value;
1572             else if(!strcmp(item.name, "func"))
1573                frame.func = item.value;
1574             else if(!strcmp(item.name, "args"))
1575             {
1576                if(!strcmp(item.value, "[]"))
1577                   frame.argsCount = 0;
1578                else
1579                {
1580                   item.value = StripBrackets(item.value);
1581                   TokenizeList(item.value, ',', argsTokens);
1582                   for(j = 0; j < argsTokens.count; j++)
1583                   {
1584                      argsTokens[j] = StripCurlies(argsTokens[j]);
1585                      TokenizeList(argsTokens[j], ',', argumentTokens);
1586                      for(k = 0; k < argumentTokens.count; k++)
1587                      {
1588                         arg = Argument { };
1589                         frame.args.Add(arg);
1590                         if(TokenizeListItem(argumentTokens[k], item))
1591                         {
1592                            if(!strcmp(item.name, "name"))
1593                            {
1594                               StripQuotes(item.value, item.value);
1595                               arg.name = item.value;
1596                            }
1597                            else if(!strcmp(item.name, "value"))
1598                            {
1599                               StripQuotes(item.value, item.value);
1600                               arg.val = item.value;
1601                            }
1602                            else
1603                               _dpl2(_dpct, dplchan::gdbProtoUnknown, 0, "frame args item (", item.name, "=", item.value, ") is unheard of");
1604                         }
1605                         else
1606                            _dpl(0, "Bad frame args item");
1607                      }
1608                      argumentTokens.RemoveAll();
1609                   }
1610                   frame.argsCount = argsTokens.count;
1611                   argsTokens.RemoveAll();
1612                }
1613             }
1614             else if(!strcmp(item.name, "from"))
1615                frame.from = item.value;
1616             else if(!strcmp(item.name, "file"))
1617                frame.file = item.value;
1618             else if(!strcmp(item.name, "line"))
1619                frame.line = atoi(item.value);
1620             else if(!strcmp(item.name, "fullname"))
1621                frame.absoluteFile = item.value;
1622             /*{
1623                // GDB 6.3 on OS X is giving "fullname" and "dir", all in absolute, but file name only in 'file'
1624                String path = ide.workspace.GetPathWorkspaceRelativeOrAbsolute(item.value);
1625                if(strcmp(frame.file, path))
1626                {
1627                   frame.file = path;
1628                   frame.absoluteFile = ide.workspace.GetAbsolutePathFromRelative(frame.file);
1629                }
1630                delete path;
1631             }*/
1632             else
1633                _dpl2(_dpct, dplchan::gdbProtoUnknown, 0, "frame member (", item.name, "=", item.value, ") is unheard of");
1634          }
1635          else
1636             _dpl(0, "Bad frame");
1637       }
1638
1639       delete frameTokens;
1640       delete argsTokens;
1641       delete argumentTokens;
1642       delete item;
1643    }
1644
1645    Breakpoint GetBreakpointById(int id, bool * isInternal)
1646    {
1647       Breakpoint bp = null;
1648       //_dpl2(_dpct, dplchan::debuggerBreakpoints, 0, "Debugger::GetBreakpointById(", id, ")");
1649       if(isInternal)
1650          *isInternal = false;
1651       if(id)
1652       {
1653          for(i : sysBPs; i.bp && i.bp.id == id)
1654          {
1655             if(isInternal)
1656                *isInternal = true;
1657             bp = i;
1658             break;
1659          }
1660          if(!bp && bpRunToCursor && bpRunToCursor.bp && bpRunToCursor.bp.id == id)
1661             bp = bpRunToCursor;
1662          if(!bp)
1663          {
1664             for(i : ide.workspace.breakpoints; i.bp && i.bp.id == id)
1665             {
1666                bp = i;
1667                break;
1668             }
1669          }
1670       }
1671       return bp;
1672    }
1673
1674    GdbDataBreakpoint ParseBreakpoint(char * string, Array<char *> outTokens)
1675    {
1676       int i;
1677       GdbDataBreakpoint bp { };
1678       DebugListItem item { };
1679       Array<char *> bpTokens { minAllocSize = 16 };
1680       _dpl2(_dpct, dplchan::debuggerCall, 0, "Debugger::ParseBreakpoint()");
1681       string = StripCurlies(string);
1682       TokenizeList(string, ',', bpTokens);
1683       for(i = 0; i < bpTokens.count; i++)
1684       {
1685          if(TokenizeListItem(bpTokens[i], item))
1686          {
1687             StripQuotes(item.value, item.value);
1688             if(!strcmp(item.name, "number"))
1689             {
1690                if(!strchr(item.value, '.'))
1691                   bp.id = atoi(item.value);
1692                bp.number = item.value;
1693             }
1694             else if(!strcmp(item.name, "type"))
1695                bp.type = item.value;
1696             else if(!strcmp(item.name, "disp"))
1697                bp.disp = item.value;
1698             else if(!strcmp(item.name, "enabled"))
1699                bp.enabled = (!strcmpi(item.value, "y"));
1700             else if(!strcmp(item.name, "addr"))
1701             {
1702                if(outTokens && !strcmp(item.value, "<MULTIPLE>"))
1703                {
1704                   int c = 1;
1705                   Array<GdbDataBreakpoint> bpArray = bp.multipleBPs = { };
1706                   while(outTokens.count > ++c)
1707                   {
1708                      GdbDataBreakpoint multBp = ParseBreakpoint(outTokens[c], null);
1709                      bpArray.Add(multBp);
1710                   }
1711                }
1712                else
1713                   bp.addr = item.value;
1714             }
1715             else if(!strcmp(item.name, "func"))
1716                bp.func = item.value;
1717             else if(!strcmp(item.name, "file"))
1718                bp.file = item.value;
1719             else if(!strcmp(item.name, "fullname"))
1720                bp.fullname = item.value;
1721             else if(!strcmp(item.name, "line"))
1722                bp.line = atoi(item.value);
1723             else if(!strcmp(item.name, "at"))
1724                bp.at = item.value;
1725             else if(!strcmp(item.name, "times"))
1726                bp.times = atoi(item.value);
1727             else if(!strcmp(item.name, "original-location") || !strcmp(item.name, "thread-groups"))
1728                _dpl2(_dpct, dplchan::gdbProtoIgnored, 0, "breakpoint member (", item.name, "=", item.value, ") is ignored");
1729             else
1730                _dpl2(_dpct, dplchan::gdbProtoUnknown, 0, "breakpoint member (", item.name, "=", item.value, ") is unheard of");
1731          }
1732       }
1733       delete bpTokens;
1734       delete item;
1735       return bp;
1736    }
1737
1738    void ShowDebuggerViews()
1739    {
1740       //_dpl2(_dpct, dplchan::debuggerCall, 0, "Debugger::ShowDebuggerViews()");
1741       ide.outputView.Show();
1742       ide.outputView.SelectTab(debug);
1743       ide.threadsView.Show();
1744       ide.callStackView.Show();
1745       ide.watchesView.Show();
1746       ide.Update(null);
1747    }
1748
1749    void HideDebuggerViews()
1750    {
1751       //_dpl2(_dpct, dplchan::debuggerCall, 0, "Debugger::HideDebuggerViews()");
1752       ide.RepositionWindows(true);
1753    }
1754
1755    bool ::GdbCommand(Time timeOut, bool focus, char * format, ...)
1756    {
1757       bool result = false;
1758       if(gdbHandle)
1759       {
1760          Time startTime;
1761          // TODO: Improve this limit
1762          static char string[MAX_F_STRING*4];
1763          va_list args;
1764          va_start(args, format);
1765          vsnprintf(string, sizeof(string), format, args);
1766          string[sizeof(string)-1] = 0;
1767          va_end(args);
1768
1769          gdbReady = false;
1770          ide.debugger.serialSemaphore.TryWait();
1771
1772 #ifdef GDB_DEBUG_CONSOLE
1773          _dpl2(_dpct, dplchan::gdbCommand, 0, string);
1774 #endif
1775 #ifdef GDB_DEBUG_OUTPUT
1776          ide.outputView.gdbBox.Logf("cmd: %s\n", string);
1777 #endif
1778 #ifdef GDB_DEBUG_GUI
1779          if(ide.gdbDialog)
1780             ide.gdbDialog.AddCommand(string);
1781 #endif
1782
1783          strcat(string,"\n");
1784          gdbHandle.Puts(string);
1785
1786          if(focus)
1787             Process_ShowWindows(targetProcessId);
1788
1789          app.Unlock();
1790
1791          if(timeOut)
1792          {
1793             startTime = GetTime();
1794             while(true)
1795             {
1796                if(ide.debugger.serialSemaphore.TryWait())
1797                {
1798                   result = true;
1799                   break;
1800                }
1801                else
1802                {
1803                   if(GetTime() - startTime > timeOut)
1804                      break;
1805                   Sleep(0.01);
1806                }
1807             }
1808          }
1809          else
1810          {
1811             ide.debugger.serialSemaphore.Wait();
1812             result = true;
1813          }
1814
1815          app.Lock();
1816       }
1817       return result;
1818    }
1819
1820    bool ValidateBreakpoint(Breakpoint bp)
1821    {
1822       _dpl2(_dpct, dplchan::debuggerCall, 0, "Debugger::ValidateBreakpoint()");
1823       if(modules && bp.line && bp.bp)
1824       {
1825          if(bp.bp.line != bp.line)
1826          {
1827             if(!bp.bp.line)
1828             {
1829 #ifdef _DEBUG
1830                //here
1831                ide.outputView.debugBox.Logf("WOULD HAVE -- Invalid breakpoint disabled: %s:%d\n", bp.relativeFilePath, bp.line);
1832 #endif
1833                //UnsetBreakpoint(bp);
1834                //bp.enabled = false;
1835                return false;
1836             }
1837             else
1838             {
1839                //here
1840                ide.outputView.debugBox.Logf("Debugger Error: ValidateBreakpoint error\n");
1841                bp.line = bp.bp.line;
1842             }
1843          }
1844       }
1845       return true;
1846    }
1847
1848    void BreakpointsMaintenance()
1849    {
1850       //_dpl2(_dpct, dplchan::debuggerBreakpoints, 0, "Debugger::BreakpointsMaintenance()");
1851       if(symbols)
1852       {
1853          if(gdbExecution.suspendInternalBreakpoints)
1854          {
1855             for(bp : sysBPs; bp.inserted)
1856                UnsetBreakpoint(bp);
1857          }
1858          else
1859          {
1860             DirExpression objDir = ide.project.GetObjDir(currentCompiler, prjConfig, bitDepth);
1861             for(bp : sysBPs; !bp.inserted)
1862             {
1863                bool insert = false;
1864                if(bp.type == internalModulesLoaded)
1865                {
1866                   char path[MAX_LOCATION];
1867                   char name[MAX_LOCATION];
1868                   char fixedModuleName[MAX_FILENAME];
1869                   char line[16384];
1870                   int lineNumber;
1871                   bool moduleLoadBlock = false;
1872                   File f;
1873                   ReplaceSpaces(fixedModuleName, ide.project.moduleName);
1874                   snprintf(name, sizeof(name),"%s.main.ec", fixedModuleName);
1875                   name[sizeof(name)-1] = 0;
1876                   strcpy(path, ide.workspace.projectDir);
1877                   PathCatSlash(path, objDir.dir);
1878                   PathCatSlash(path, name);
1879                   f = FileOpen(path, read);
1880                   if(f)
1881                   {
1882                      for(lineNumber = 1; !f.Eof(); lineNumber++)
1883                      {
1884                         if(f.GetLine(line, sizeof(line) - 1))
1885                         {
1886                            bool moduleLoadLine;
1887                            TrimLSpaces(line, line);
1888                            moduleLoadLine = !strncmp(line, "eModule_Load", strlen("eModule_Load"));
1889                            if(!moduleLoadBlock && moduleLoadLine)
1890                               moduleLoadBlock = true;
1891                            else if(moduleLoadBlock && !moduleLoadLine && strlen(line) > 0)
1892                               break;
1893                         }
1894                      }
1895                      if(!f.Eof())
1896                      {
1897                         char relative[MAX_LOCATION];
1898                         bp.absoluteFilePath = path;
1899                         MakePathRelative(path, ide.workspace.projectDir, relative);
1900                         bp.relativeFilePath = relative;
1901                         bp.line = lineNumber;
1902                         insert = true;
1903                      }
1904                      delete f;
1905                   }
1906                }
1907                else if(bp.type == internalModuleLoad)
1908                {
1909                   if(modules)
1910                   {
1911                      for(prj : ide.workspace.projects)
1912                      {
1913                         if(!strcmp(prj.moduleName, "ecere"))
1914                         {
1915                            ProjectNode node = prj.topNode.Find("instance.c", false);
1916                            if(node)
1917                            {
1918                               char path[MAX_LOCATION];
1919                               char relative[MAX_LOCATION];
1920                               node.GetFullFilePath(path);
1921                               bp.absoluteFilePath = path;
1922                               MakePathRelative(path, prj.topNode.path, relative);
1923                               bp.relativeFilePath = relative;
1924                               insert = true;
1925                               break;
1926                            }
1927                         }
1928                      }
1929                   }
1930                }
1931                else
1932                   insert = true;
1933                if(insert)
1934                   SetBreakpoint(bp, false);
1935             }
1936             delete objDir;
1937          }
1938
1939          if(userAction != runToCursor && bpRunToCursor && bpRunToCursor.inserted)
1940             UnsetBreakpoint(bpRunToCursor);
1941          if(bpRunToCursor && !bpRunToCursor.inserted)
1942             SetBreakpoint(bpRunToCursor, false);
1943
1944          if(ignoreBreakpoints)
1945          {
1946             for(bp : ide.workspace.breakpoints; bp.inserted)
1947                UnsetBreakpoint(bp);
1948          }
1949          else
1950          {
1951             for(bp : ide.workspace.breakpoints; !bp.inserted && bp.type == user)
1952             {
1953                if(bp.enabled)
1954                {
1955                   if(!SetBreakpoint(bp, false))
1956                      SetBreakpoint(bp, true);
1957                }
1958                else
1959                {
1960 #ifdef _DEBUG
1961                   if(bp.bp)
1962                      _dpl(0, "problem");
1963 #endif
1964                   delete bp.bp;
1965                   bp.bp = GdbDataBreakpoint { };
1966                }
1967             }
1968          }
1969       }
1970    }
1971
1972    void UnsetBreakpoint(Breakpoint bp)
1973    {
1974       char * s = null; _dpl2(_dpct, dplchan::debuggerBreakpoints, 0, "Debugger::UnsetBreakpoint(", s=bp.CopyLocationString(false), ") -- ", bp.type); delete s;
1975       if(symbols && bp.inserted)
1976       {
1977          GdbCommand(0, false, "-break-delete %s", bp.bp.number);
1978          bp.inserted = false;
1979          delete bp.bp;
1980          bp.bp = { };
1981       }
1982    }
1983
1984    bool SetBreakpoint(Breakpoint bp, bool removePath)
1985    {
1986       char * s = null; _dpl2(_dpct, dplchan::debuggerBreakpoints, 0, "Debugger::SetBreakpoint(", s=bp.CopyLocationString(false), ", ", removePath ? "**** removePath(true) ****" : "", ") -- ", bp.type); delete s;
1987       breakpointError = false;
1988       if(symbols && bp.enabled && (!bp.project || bp.project.GetTargetType(bp.project.config) == staticLibrary || bp.project == ide.project || projectsLibraryLoaded[bp.project.name]))
1989       {
1990          sentBreakInsert = true;
1991          if(bp.address)
1992             GdbCommand(0, false, "-break-insert *%s", bp.address);
1993          else
1994          {
1995             char * location = bp.CopyLocationString(removePath);
1996             GdbCommand(0, false, "-break-insert %s", location);
1997             delete location;
1998          }
1999          if(!breakpointError)
2000          {
2001             char * address = null;
2002             if(bpItem && bpItem.multipleBPs && bpItem.multipleBPs.count)
2003             {
2004                int count = 0;
2005                GdbDataBreakpoint first = null;
2006                for(n : bpItem.multipleBPs)
2007                {
2008                   if(!fstrcmp(n.fullname, bp.absoluteFilePath) && !first)
2009                   {
2010                      count++;
2011                      first = n;
2012                      break;
2013                   }
2014                   /*else
2015                   {
2016                      if(n.enabled)
2017                      {
2018                         GdbCommand(0, false, "-break-disable %s", n.number);
2019                         n.enabled = false;
2020                      }
2021                      else
2022                         _dpl2(_dpct, dplchan::debuggerProblem, 0, "Debugger::SetBreakpoint -- error breakpoint already disabled.");
2023                   }*/
2024                }
2025                if(first)
2026                {
2027                   address = CopyString(first.addr);
2028                   bpItem.addr = first.addr;
2029                   bpItem.func = first.func;
2030                   bpItem.file = first.file;
2031                   bpItem.fullname = first.fullname;
2032                   bpItem.line = first.line;
2033                   //bpItem.thread-groups = first.thread-groups;*/
2034                }
2035                else if(count == 0)
2036                   _dpl2(_dpct, dplchan::debuggerProblem, 0, "Debugger::SetBreakpoint -- error multiple breakpoints all disabled.");
2037                else
2038                   _dpl2(_dpct, dplchan::debuggerProblem, 0, "Debugger::SetBreakpoint -- error multiple breakpoints in exact same file not supported.");
2039                bpItem.multipleBPs.Free();
2040                delete bpItem.multipleBPs;
2041             }
2042             delete bp.bp;
2043             bp.bp = bpItem;
2044             bpItem = null;
2045             bp.inserted = (bp.bp && bp.bp.number && strcmp(bp.bp.number, "0"));
2046             if(bp.inserted)
2047                ValidateBreakpoint(bp);
2048
2049             if(address)
2050             {
2051                UnsetBreakpoint(bp);
2052                bp.address = address;
2053                delete address;
2054                SetBreakpoint(bp, removePath);
2055             }
2056          }
2057       }
2058       return !breakpointError;
2059    }
2060
2061    void GdbGetStack()
2062    {
2063       _dpl2(_dpct, dplchan::debuggerCall, 0, "Debugger::GdbGetStack()");
2064       activeFrame = null;
2065       stackFrames.Free(Frame::Free);
2066       GdbCommand(0, false, "-stack-info-depth");
2067       if(!frameCount)
2068          GdbCommand(0, false, "-stack-info-depth 192");
2069       if(frameCount && frameCount <= 192)
2070          GdbCommand(0, false, "-stack-list-frames 0 %d", Min(frameCount-1, 191));
2071       else
2072       {
2073          GdbCommand(0, false, "-stack-list-frames 0 %d", Min(frameCount-1, 95));
2074          GdbCommand(0, false, "-stack-list-frames %d %d", Max(frameCount - 96, 96), frameCount - 1);
2075       }
2076       GdbCommand(0, false, "");
2077    }
2078
2079    bool GdbTargetSet()
2080    {
2081       _dpl2(_dpct, dplchan::debuggerCall, 0, "Debugger::GdbTargetSet()");
2082       if(!targeted)
2083       {
2084          char escaped[MAX_LOCATION];
2085          strescpy(escaped, targetFile);
2086          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
2087
2088          if(!symbols)
2089             return true;
2090
2091          if(usingValgrind)
2092          {
2093             const char *vgdbCommand = "/usr/bin/vgdb"; // TODO: vgdb command config option
2094             //GdbCommand(0, false, "-target-select remote | %s --pid=%d", "vgdb", targetProcessId);
2095             printf("target remote | %s --pid=%d\n", vgdbCommand, targetProcessId);
2096             GdbCommand(0, false, "target remote | %s --pid=%d", vgdbCommand, targetProcessId); // TODO: vgdb command config option
2097          }
2098          else
2099             GdbCommand(0, false, "info target"); //GDB/MI Missing Implementation -file-list-symbol-files and -file-list-exec-sections
2100
2101          /*for(prj : ide.workspace.projects; prj != ide.workspace.projects.firstIterator.data)
2102             GdbCommand(0, false, "-environment-directory \"%s\"", prj.topNode.path);*/
2103
2104          for(dir : ide.workspace.sourceDirs; dir && dir[0])
2105          {
2106            bool interference = false;
2107            for(prj : ide.workspace.projects)
2108            {
2109               if(!fstrcmp(prj.topNode.path, dir))
2110               {
2111                  interference = true;
2112                  break;
2113               }
2114            }
2115            if(!interference && dir[0])
2116               GdbCommand(0, false, "-environment-directory \"%s\"", dir);
2117          }
2118
2119          targeted = true;
2120       }
2121       return true;
2122    }
2123
2124    /*void GdbTargetRelease()
2125    {
2126       if(targeted)
2127       {
2128          BreakpointsDeleteAll();
2129          GdbCommand(0, false, "file");  //GDB/MI Missing Implementation -target-detach
2130          targeted = false;
2131          symbols = true;
2132       }
2133    }*/
2134
2135    void GdbDebugBreak(bool internal)
2136    {
2137       _dpl2(_dpct, dplchan::debuggerCall, 0, "Debugger::GdbDebugBreak()");
2138       if(targetProcessId)
2139       {
2140          if(internal)
2141             breakType = DebuggerAction::internal;
2142
2143          if(ide) ide.Update(null);
2144          app.Unlock();
2145          if(Process_Break(targetProcessId))  //GdbCommand(0, false, "-exec-interrupt");
2146             serialSemaphore.Wait();
2147          else
2148          {
2149             _ChangeState(loaded);
2150             targetProcessId = 0;
2151          }
2152          app.Lock();
2153       }
2154       else
2155          ide.outputView.debugBox.Logf("Debugger Error: GdbDebugBreak with not target id should never happen\n");
2156    }
2157
2158    void GdbExecRun()
2159    {
2160       _dpl2(_dpct, dplchan::debuggerCall, 0, "Debugger::GdbExecRun()");
2161       GdbTargetSet();
2162       if(!usingValgrind)
2163          gdbExecution = run;
2164       GdbExecCommon();
2165       ShowDebuggerViews();
2166       if(usingValgrind)
2167          GdbExecContinue(true);
2168       else if(!GdbCommand(3, true, "-exec-run"))
2169          gdbExecution = none;
2170    }
2171
2172    void GdbExecContinue(bool focus)
2173    {
2174       _dpl2(_dpct, dplchan::debuggerCall, 0, "Debugger::GdbExecContinue()");
2175       gdbExecution = run;
2176       GdbExecCommon();
2177       GdbCommand(0, focus, "-exec-continue");
2178    }
2179
2180    void GdbExecNext()
2181    {
2182       _dpl2(_dpct, dplchan::debuggerCall, 0, "Debugger::GdbExecNext()");
2183       gdbExecution = next;
2184       GdbExecCommon();
2185       GdbCommand(0, true, "-exec-next");
2186    }
2187
2188    void GdbExecUntil(char * absoluteFilePath, int lineNumber)
2189    {
2190       char relativeFilePath[MAX_LOCATION];
2191       _dpl2(_dpct, dplchan::debuggerCall, 0, "Debugger::GdbExecUntil()");
2192       gdbExecution = until;
2193       GdbExecCommon();
2194       if(absoluteFilePath)
2195       {
2196          WorkspaceGetRelativePath(absoluteFilePath, relativeFilePath, null);
2197          GdbCommand(0, true, "-exec-until %s:%d", relativeFilePath, lineNumber);
2198       }
2199       else
2200          GdbCommand(0, true, "-exec-until");
2201    }
2202
2203    void GdbExecAdvance(char * absoluteFilePathOrLocation, int lineNumber)
2204    {
2205       char relativeFilePath[MAX_LOCATION];
2206       _dpl2(_dpct, dplchan::debuggerCall, 0, "Debugger::GdbExecAdvance()");
2207       gdbExecution = advance;
2208       GdbExecCommon();
2209       if(lineNumber)
2210       {
2211          WorkspaceGetRelativePath(absoluteFilePathOrLocation, relativeFilePath, null);
2212          GdbCommand(0, true, "advance %s:%d", relativeFilePath, lineNumber); // should use -exec-advance -- GDB/MI implementation missing
2213       }
2214       else
2215          GdbCommand(0, true, "advance %s", absoluteFilePathOrLocation); // should use -exec-advance -- GDB/MI implementation missing
2216    }
2217
2218    void GdbExecStep()
2219    {
2220       _dpl2(_dpct, dplchan::debuggerCall, 0, "Debugger::GdbExecStep()");
2221       gdbExecution = step;
2222       GdbExecCommon();
2223       GdbCommand(0, true, "-exec-step");
2224    }
2225
2226    void GdbExecFinish()
2227    {
2228       _dpl2(_dpct, dplchan::debuggerCall, 0, "Debugger::GdbExecFinish()");
2229       gdbExecution = finish;
2230       GdbExecCommon();
2231       GdbCommand(0, true, "-exec-finish");
2232    }
2233
2234    void GdbExecCommon()
2235    {
2236       //_dpl2(_dpct, dplchan::debuggerCall, 0, "Debugger::GdbExecCommon()");
2237       BreakpointsMaintenance();
2238    }
2239
2240 #ifdef GDB_DEBUG_GUI
2241    void SendGDBCommand(char * command)
2242    {
2243       //_dpl2(_dpct, dplchan::debuggerCall, 0, "Debugger::SendGDBCommand()");
2244       DebuggerState oldState = state;
2245       switch(state)
2246       {
2247          case running:
2248             if(targetProcessId)
2249                GdbDebugBreak(true);
2250          case stopped:
2251          case loaded:
2252             GdbCommand(0, false, command);
2253             break;
2254       }
2255       if(oldState == running)
2256          GdbExecContinue(false);
2257    }
2258 #endif
2259
2260    void ClearBreakDisplay()
2261    {
2262       //_dpl2(_dpct, dplchan::debuggerCall, 0, "Debugger::ClearBreakDisplay()");
2263       activeThread = 0;
2264       activeFrameLevel = -1;
2265       hitThread = 0;
2266       signalThread = 0;
2267       signalOn = false;
2268       frameCount = 0;
2269       if(stopItem)
2270          stopItem.Free();
2271       delete stopItem;
2272       event = none;
2273       activeFrame = null;
2274       stackFrames.Free(Frame::Free);
2275       ide.callStackView.Clear();
2276       ide.threadsView.Clear();
2277       ide.Update(null);
2278    }
2279
2280    bool GdbAbortExec()
2281    {
2282       _dpl2(_dpct, dplchan::debuggerCall, 0, "Debugger::GdbAbortExec()");
2283       sentKill = true;
2284       GdbCommand(0, false, "-interpreter-exec console \"kill\""); // should use -exec-abort -- GDB/MI implementation incomplete
2285       return true;
2286    }
2287
2288    bool GdbInit(CompilerConfig compiler, ProjectConfig config, int bitDepth, bool useValgrind)
2289    {
2290       bool result = true;
2291       char oldDirectory[MAX_LOCATION];
2292       char tempPath[MAX_LOCATION];
2293       char command[MAX_F_STRING*4];
2294       Project project = ide.project;
2295       DirExpression targetDirExp = project.GetTargetDir(compiler, config, bitDepth);
2296       PathBackup pathBackup { };
2297       Map<String, String> envBackup { };
2298
2299       _dpl2(_dpct, dplchan::debuggerCall, 0, "Debugger::GdbInit()");
2300       if(currentCompiler != compiler)
2301       {
2302          delete currentCompiler;
2303          currentCompiler = compiler;
2304          incref currentCompiler;
2305       }
2306       prjConfig = config;
2307       this.bitDepth = bitDepth;
2308       usingValgrind = useValgrind;
2309
2310       _ChangeState(loaded);
2311       sentKill = false;
2312       sentBreakInsert = false;
2313       breakpointError = false;
2314       ignoreBreakpoints = false;
2315       symbols = true;
2316       targeted = false;
2317       modules = false;
2318       needReset = false;
2319       projectsLibraryLoaded.Free();
2320
2321       ide.outputView.ShowClearSelectTab(debug);
2322       ide.outputView.debugBox.Logf($"Starting debug mode\n");
2323
2324 #ifdef GDB_DEBUG_OUTPUT
2325       ide.outputView.gdbBox.Logf("run: Starting GDB\n");
2326 #endif
2327
2328       strcpy(tempPath, ide.workspace.projectDir);
2329       PathCatSlash(tempPath, targetDirExp.dir);
2330       delete targetDir;
2331       targetDir = CopyString(tempPath);
2332       project.CatTargetFileName(tempPath, compiler, config);
2333       delete targetFile;
2334       targetFile = CopyString(tempPath);
2335
2336       GetWorkingDir(oldDirectory, MAX_LOCATION);
2337       if(ide.workspace.debugDir && ide.workspace.debugDir[0])
2338       {
2339          char temp[MAX_LOCATION];
2340          strcpy(temp, ide.workspace.projectDir);
2341          PathCatSlash(temp, ide.workspace.debugDir);
2342          ChangeWorkingDir(temp);
2343       }
2344       else
2345          ChangeWorkingDir(ide.workspace.projectDir);
2346
2347       ide.SetPath(true, compiler, config, bitDepth);
2348
2349       // TODO: This pollutes the environment, but at least it works
2350       // It shouldn't really affect the IDE as the PATH gets restored and other variables set for testing will unlikely cause problems
2351       // What is the proper solution for this? DualPipeOpenEnv?
2352       // gdb set environment commands don't seem to take effect
2353       for(e : ide.workspace.environmentVars)
2354       {
2355          // Backing up the environment variables until we use DualPipeOpenEnv()
2356          envBackup[e.name] = CopyString(getenv(e.name));
2357          SetEnvironment(e.name, e.string);
2358       }
2359
2360       if(usingValgrind)
2361       {
2362          char * clArgs = ide.workspace.commandLineArgs;
2363          const char *valgrindCommand = "valgrind"; // TODO: valgrind command config option //TODO: valgrind options
2364          ValgrindLeakCheck vgLeakCheck = ide.workspace.vgLeakCheck;
2365          int vgRedzoneSize = ide.workspace.vgRedzoneSize;
2366          bool vgTrackOrigins = ide.workspace.vgTrackOrigins;
2367          vgLogFile = CreateTemporaryFile(vgLogPath, "ecereidevglog");
2368          if(vgLogFile)
2369          {
2370             incref vgLogFile;
2371             vgLogThread.Create();
2372          }
2373          else
2374          {
2375             ide.outputView.debugBox.Logf($"Debugger Fatal Error: Couldn't open temporary log file for Valgrind output\n");
2376             result = false;
2377          }
2378          if(result && !CheckCommandAvailable(valgrindCommand))
2379          {
2380             ide.outputView.debugBox.Logf($"Debugger Fatal Error: Command %s for Valgrind is not available.\n", valgrindCommand);
2381             result = false;
2382          }
2383          if(result)
2384          {
2385             char * vgRedzoneSizeFlag = vgRedzoneSize == -1 ? "" : PrintString(" --redzone-size=", vgRedzoneSize);
2386             sprintf(command, "%s --vgdb=yes --vgdb-error=0 --log-file=%s --leak-check=%s%s --track-origins=%s %s%s%s",
2387                   valgrindCommand, vgLogPath, (char*)vgLeakCheck, vgRedzoneSizeFlag, vgTrackOrigins ? "yes" : "no", targetFile, clArgs ? " " : "", clArgs ? clArgs : "");
2388             if(vgRedzoneSize != -1)
2389                delete vgRedzoneSizeFlag;
2390             vgTargetHandle = DualPipeOpen(PipeOpenMode { output = true, /*error = true, */input = true }, command);
2391             if(!vgTargetHandle)
2392             {
2393                ide.outputView.debugBox.Logf($"Debugger Fatal Error: Couldn't start Valgrind\n");
2394                result = false;
2395             }
2396          }
2397          if(result)
2398          {
2399             incref vgTargetHandle;
2400             vgTargetThread.Create();
2401
2402             targetProcessId = vgTargetHandle.GetProcessID();
2403             waitingForPID = false;
2404             if(!targetProcessId)
2405             {
2406                ide.outputView.debugBox.Logf($"Debugger Fatal Error: Couldn't get Valgrind process ID\n");
2407                result = false;
2408             }
2409          }
2410          if(result)
2411          {
2412             app.Unlock();
2413             serialSemaphore.Wait();
2414             app.Lock();
2415          }
2416       }
2417
2418       if(result)
2419       {
2420          if(compiler.targetPlatform == win32)
2421          {
2422             strcpy(command,
2423 #if !((defined(__WORDSIZE) && __WORDSIZE == 8) || defined(__x86_64__))
2424                1 ||
2425 #endif
2426                bitDepth == 32 ? "i686-w64-mingw32-gdb" : "gdb");  // x86_64-w64-mingw32-gdb
2427          }
2428          else
2429             // We really should have a box to select GDB in the compiler/toolchain options
2430             strcpy(command, "gdb");
2431          if(!CheckCommandAvailable(command))
2432          {
2433             ide.outputView.debugBox.Logf($"Debugger Fatal Error: Command %s for GDB is not available.\n", command);
2434             result = false;
2435          }
2436          else
2437          {
2438             strcat(command, " -n -silent --interpreter=mi2"); //-async //\"%s\"
2439             gdbTimer.Start();
2440             gdbHandle = DualPipeOpen(PipeOpenMode { output = true, /*error = true, */input = true }, command);
2441             if(!gdbHandle)
2442             {
2443                ide.outputView.debugBox.Logf($"Debugger Fatal Error: Couldn't start GDB\n");
2444                result = false;
2445             }
2446          }
2447       }
2448       if(result)
2449       {
2450          incref gdbHandle;
2451          gdbThread.Create();
2452
2453          gdbProcessId = gdbHandle.GetProcessID();
2454          if(!gdbProcessId)
2455          {
2456             ide.outputView.debugBox.Logf($"Debugger Fatal Error: Couldn't get GDB process ID\n");
2457             result = false;
2458          }
2459       }
2460       if(result)
2461       {
2462          app.Unlock();
2463          serialSemaphore.Wait();
2464          app.Lock();
2465
2466          GdbCommand(0, false, "-gdb-set verbose off");
2467          //GdbCommand(0, false, "-gdb-set exec-done-display on");
2468          GdbCommand(0, false, "-gdb-set step-mode off");
2469          GdbCommand(0, false, "-gdb-set unwindonsignal on");
2470          //GdbCommand(0, false, "-gdb-set shell on");
2471          GdbCommand(0, false, "set print elements 992");
2472          GdbCommand(0, false, "-gdb-set backtrace limit 100000");
2473
2474          if(!GdbTargetSet())
2475          {
2476             //_ChangeState(terminated);
2477             result = false;
2478          }
2479       }
2480       if(result)
2481       {
2482 #if defined(__unix__)
2483          {
2484             CreateTemporaryDir(progFifoDir, "ecereide");
2485             strcpy(progFifoPath, progFifoDir);
2486             PathCat(progFifoPath, "ideprogfifo");
2487             if(!mkfifo(progFifoPath, 0600))
2488             {
2489                //fileCreated = true;
2490             }
2491             else
2492             {
2493                //app.Lock();
2494                ide.outputView.debugBox.Logf(createFIFOMsg, progFifoPath);
2495                //app.Unlock();
2496             }
2497          }
2498
2499          if(!usingValgrind)
2500          {
2501             progThread.terminate = false;
2502             progThread.Create();
2503          }
2504 #endif
2505
2506 #if defined(__WIN32__)
2507          GdbCommand(0, false, "-gdb-set new-console on");
2508 #endif
2509
2510 #if defined(__unix__)
2511          if(!usingValgrind)
2512             GdbCommand(0, false, "-inferior-tty-set %s", progFifoPath);
2513 #endif
2514
2515          if(!usingValgrind)
2516             GdbCommand(0, false, "-gdb-set args %s", ide.workspace.commandLineArgs ? ide.workspace.commandLineArgs : "");
2517          /*
2518          for(e : ide.workspace.environmentVars)
2519          {
2520             GdbCommand(0, false, "set environment %s=%s", e.name, e.string);
2521          }
2522          */
2523       }
2524
2525       ChangeWorkingDir(oldDirectory);
2526
2527       for(e : envBackup)
2528       {
2529          SetEnvironment(&e, e);
2530       }
2531       envBackup.Free();
2532       delete envBackup;
2533
2534       delete pathBackup;
2535
2536       if(!result)
2537          GdbExit();
2538       delete targetDirExp;
2539       return result;
2540    }
2541
2542    void GdbExit()
2543    {
2544       _dpl2(_dpct, dplchan::debuggerCall, 0, "Debugger::GdbExit()");
2545       if(gdbHandle && gdbProcessId)
2546       {
2547          gdbTimer.Stop();
2548          GdbCommand(0, false, "-gdb-exit");
2549
2550          if(gdbThread)
2551          {
2552             app.Unlock();
2553             gdbThread.Wait();
2554             app.Lock();
2555          }
2556          if(vgLogFile)
2557             vgLogFile.CloseInput();
2558          if(vgLogThread.created)
2559          {
2560             app.Unlock();
2561             vgLogThread.Wait();
2562             app.Lock();
2563          }
2564          delete vgLogFile;
2565          if(vgTargetThread)
2566          {
2567             app.Unlock();
2568             vgTargetThread.Wait();
2569             app.Lock();
2570          }
2571          if(gdbHandle)
2572          {
2573             gdbHandle.Wait();
2574             delete gdbHandle;
2575          }
2576       }
2577       gdbTimer.Stop();
2578       _ChangeState(terminated); // this state change seems to be superfluous, is it safety for something?
2579       prjConfig = null;
2580       needReset = false;
2581
2582       if(ide.workspace)
2583       {
2584          for(bp : ide.workspace.breakpoints)
2585             bp.Reset();
2586       }
2587       for(bp : sysBPs)
2588          bp.Reset();
2589       if(bpRunToCursor)
2590          bpRunToCursor.Reset();
2591
2592       ide.outputView.debugBox.Logf($"Debugging stopped\n");
2593       ClearBreakDisplay();
2594       ide.Update(null);
2595
2596 #if defined(__unix__)
2597       if(!usingValgrind && FileExists(progFifoPath)) //fileCreated)
2598       {
2599          progThread.terminate = true;
2600          if(fifoFile)
2601          {
2602             fifoFile.CloseInput();
2603             app.Unlock();
2604             progThread.Wait();
2605             app.Lock();
2606             delete fifoFile;
2607          }
2608          DeleteFile(progFifoPath);
2609          progFifoPath[0] = '\0';
2610          rmdir(progFifoDir);
2611       }
2612 #endif
2613    }
2614
2615    bool WatchesLinkCodeEditor()
2616    {
2617       bool goodFrame = activeFrame && activeFrame.absoluteFile;
2618       //_dpl2(_dpct, dplchan::debuggerCall, 0, "Debugger::WatchesLinkCodeEditor()");
2619       if(codeEditor && (!goodFrame || fstrcmp(codeEditor.fileName, activeFrame.absoluteFile)))
2620          WatchesReleaseCodeEditor();
2621
2622       if(!codeEditor && goodFrame)
2623       {
2624          codeEditor = (CodeEditor)ide.OpenFile(activeFrame.absoluteFile, normal, false, null, no, normal, false);
2625          if(codeEditor)
2626          {
2627             codeEditor.inUseDebug = true;
2628             incref codeEditor;
2629          }
2630       }
2631       return codeEditor != null;
2632    }
2633
2634    void WatchesReleaseCodeEditor()
2635    {
2636       //_dpl2(_dpct, dplchan::debuggerCall, 0, "Debugger::WatchesReleaseCodeEditor()");
2637       if(codeEditor)
2638       {
2639          codeEditor.inUseDebug = false;
2640          if(!codeEditor.visible)
2641             codeEditor.Destroy(0);
2642          delete codeEditor;
2643       }
2644    }
2645
2646    bool ResolveWatch(Watch wh)
2647    {
2648       bool result = false;
2649
2650       _dpl2(_dpct, dplchan::debuggerWatches, 0, "Debugger::ResolveWatch()");
2651       wh.Reset();
2652
2653       /*delete wh.value;
2654       if(wh.type)
2655       {
2656          FreeType(wh.type);
2657          wh.type = null;
2658       }*/
2659
2660       if(wh.expression)
2661       {
2662          char watchmsg[MAX_F_STRING];
2663          if(state == stopped && !codeEditor)
2664             wh.value = CopyString($"No source file found for selected frame");
2665          //if(codeEditor && state == stopped || state != stopped)
2666          else
2667          {
2668             Module backupPrivateModule;
2669             Context backupContext;
2670             Class backupThisClass;
2671             Expression exp;
2672             parseError = false;
2673
2674             backupPrivateModule = GetPrivateModule();
2675             backupContext = GetCurrentContext();
2676             backupThisClass = GetThisClass();
2677             if(codeEditor)
2678             {
2679                SetPrivateModule(codeEditor.privateModule);
2680                SetCurrentContext(codeEditor.globalContext);
2681                SetTopContext(codeEditor.globalContext);
2682                SetGlobalContext(codeEditor.globalContext);
2683                SetGlobalData(&codeEditor.globalData);
2684             }
2685
2686             exp = ParseExpressionString(wh.expression);
2687
2688             if(exp && !parseError)
2689             {
2690                char expString[4096];
2691                expString[0] = 0;
2692                PrintExpression(exp, expString);
2693
2694                if(GetPrivateModule())
2695                {
2696                   if(codeEditor)
2697                      DebugFindCtxTree(codeEditor.ast, activeFrame.line, 0);
2698                   ProcessExpressionType(exp);
2699                }
2700                wh.type = exp.expType;
2701                if(wh.type)
2702                   wh.type.refCount++;
2703                DebugComputeExpression(exp);
2704                if(ExpressionIsError(exp))
2705                {
2706                   GDBFallBack(exp, expString);
2707                }
2708
2709                /*if(exp.hasAddress)
2710                {
2711                   char temp[MAX_F_STRING];
2712                   sprintf(temp, "0x%x", exp.address);
2713                   wh.address = CopyString(temp);
2714                   // wh.address = CopyStringf("0x%x", exp.address);
2715                }*/
2716 /*
2717 //#ifdef _DEBUG
2718                {
2719                   Type dataType = exp.expType;
2720                   if(dataType)
2721                   {
2722                      char temp[MAX_F_STRING];
2723                      switch(dataType.kind)
2724                      {
2725                         case charType:
2726                            sprintf(temp, "%i", exp.val.c);
2727                            break;
2728                         case shortType:
2729                            sprintf(temp, "%i", exp.val.s);
2730                            break;
2731                         case intType:
2732                         case longType:
2733                         case enumType:
2734                            sprintf(temp, "%i", exp.val.i);
2735                            break;
2736                         case int64Type:
2737                            sprintf(temp, "%i", exp.val.i64);
2738                            break;
2739                         case pointerType:
2740                            sprintf(temp, "%i", exp.val.p);
2741                            break;
2742
2743                         case floatType:
2744                         {
2745                            long v = (long)exp.val.f;
2746                            sprintf(temp, "%i", v);
2747                            break;
2748                         }
2749                         case doubleType:
2750                         {
2751                            long v = (long)exp.val.d;
2752                            sprintf(temp, "%i", v);
2753                            break;
2754                         }
2755                      }
2756                      if(temp)
2757                         wh.intVal = CopyString(temp);
2758                      switch(dataType.kind)
2759                      {
2760                         case charType:
2761                            sprintf(temp, "0x%x", exp.val.c);
2762                            break;
2763                         case shortType:
2764                            sprintf(temp, "0x%x", exp.val.s);
2765                            break;
2766                         case enumType:
2767                         case intType:
2768                            sprintf(temp, "0x%x", exp.val.i);
2769                            break;
2770                         case int64Type:
2771                            sprintf(temp, "0x%x", exp.val.i64);
2772                            break;
2773                         case longType:
2774                            sprintf(temp, "0x%x", exp.val.i64);
2775                            break;
2776                         case pointerType:
2777                            sprintf(temp, "0x%x", exp.val.p);
2778                            break;
2779
2780                         case floatType:
2781                         {
2782                            long v = (long)exp.val.f;
2783                            sprintf(temp, "0x%x", v);
2784                            break;
2785                         }
2786                         case doubleType:
2787                         {
2788                            long v = (long)exp.val.d;
2789                            sprintf(temp, "0x%x", v);
2790                            break;
2791                         }
2792                      }
2793                      if(temp)
2794                         wh.hexVal = CopyString(temp);
2795                      switch(dataType.kind)
2796                      {
2797                         case charType:
2798                            sprintf(temp, "0o%o", exp.val.c);
2799                            break;
2800                         case shortType:
2801                            sprintf(temp, "0o%o", exp.val.s);
2802                            break;
2803                         case enumType:
2804                         case intType:
2805                            sprintf(temp, "0o%o", exp.val.i);
2806                            break;
2807                         case int64Type:
2808                            sprintf(temp, "0o%o", exp.val.i64);
2809                            break;
2810                         case longType:
2811                            sprintf(temp, "0o%o", exp.val.i64);
2812                            break;
2813                         case pointerType:
2814                            sprintf(temp, "0o%o", exp.val.p);
2815                            break;
2816
2817                         case floatType:
2818                         {
2819                            long v = (long)exp.val.f;
2820                            sprintf(temp, "0o%o", v);
2821                            break;
2822                         }
2823                         case doubleType:
2824                         {
2825                            long v = (long)exp.val.d;
2826                            sprintf(temp, "0o%o", v);
2827                            break;
2828                         }
2829                      }
2830                      if(temp)
2831                         wh.octVal = CopyString(temp);
2832                   }
2833                }
2834                // WHATS THIS HERE ?
2835                if(exp.type == constantExp && exp.constant)
2836                   wh.constant = CopyString(exp.constant);
2837 //#endif
2838 */
2839
2840                switch(exp.type)
2841                {
2842                   case symbolErrorExp:
2843                      snprintf(watchmsg, sizeof(watchmsg), $"Symbol \"%s\" not found", exp.identifier.string);
2844                      break;
2845                   case structMemberSymbolErrorExp:
2846                      // todo get info as in next case (ExpClassMemberSymbolError)
2847                      snprintf(watchmsg, sizeof(watchmsg), $"Error: Struct member not found for \"%s\"", wh.expression);
2848                      break;
2849                   case classMemberSymbolErrorExp:
2850                      {
2851                         Class _class;
2852                         Expression memberExp = exp.member.exp;
2853                         Identifier memberID = exp.member.member;
2854                         Type type = memberExp.expType;
2855                         if(type)
2856                         {
2857                            _class = (memberID && memberID.classSym) ? memberID.classSym.registered : ((type.kind == classType && type._class) ? type._class.registered : null);
2858                            if(!_class)
2859                            {
2860                               char string[256] = "";
2861                               Symbol classSym;
2862                               PrintTypeNoConst(type, string, false, true);
2863                               classSym = FindClass(string);
2864                               _class = classSym ? classSym.registered : null;
2865                            }
2866                            if(_class)
2867                               snprintf(watchmsg, sizeof(watchmsg), $"Member \"%s\" not found in class \"%s\"", memberID ? memberID.string : "", _class.name);
2868                            else
2869                               snprintf(watchmsg, sizeof(watchmsg), "Member \"%s\" not found in unregistered class? (Should never get this message)", memberID ? memberID.string : "");
2870                         }
2871                         else
2872                            snprintf(watchmsg, sizeof(watchmsg), "Member \"%s\" not found in no type? (Should never get this message)", memberID ? memberID.string : "");
2873                      }
2874                      break;
2875                   case memoryErrorExp:
2876                      // Need to ensure when set to memoryErrorExp, constant is set
2877                      snprintf(watchmsg, sizeof(watchmsg), $"Memory can't be read at %s", /*(exp.type == constantExp) ? */exp.constant /*: null*/);
2878                      break;
2879                   case dereferenceErrorExp:
2880                      snprintf(watchmsg, sizeof(watchmsg), $"Dereference failure for \"%s\"", wh.expression);
2881                      break;
2882                   case unknownErrorExp:
2883                      snprintf(watchmsg, sizeof(watchmsg), $"Unknown error for \"%s\"", wh.expression);
2884                      break;
2885                   case noDebuggerErrorExp:
2886                      snprintf(watchmsg, sizeof(watchmsg), $"Debugger required for symbol evaluation in \"%s\"", wh.expression);
2887                      break;
2888                   case debugStateErrorExp:
2889                      snprintf(watchmsg, sizeof(watchmsg), $"Incorrect debugger state for symbol evaluation in \"%s\"", wh.expression);
2890                      break;
2891                   case 0:
2892                      snprintf(watchmsg, sizeof(watchmsg), $"Null type for \"%s\"", wh.expression);
2893                      break;
2894                   case constantExp:
2895                   case stringExp:
2896                      // Temporary Code for displaying Strings
2897                      if((exp.expType && ((exp.expType.kind == pointerType ||
2898                               exp.expType.kind == arrayType) && exp.expType.type.kind == charType)) ||
2899                            (wh.type && wh.type.kind == classType && wh.type._class &&
2900                               wh.type._class.registered && wh.type._class.registered.type == normalClass &&
2901                               !strcmp(wh.type._class.registered.name, "String")))
2902                      {
2903
2904                         if(exp.expType.kind != arrayType || exp.hasAddress)
2905                         {
2906                            uint64 address;
2907                            char * string;
2908                            char value[4196];
2909                            int len;
2910                            //char temp[MAX_F_STRING * 32];
2911
2912                            ExpressionType evalError = dummyExp;
2913                            /*if(exp.expType.kind == arrayType)
2914                               sprintf(temp, "(char*)0x%x", exp.address);
2915                            else
2916                               sprintf(temp, "(char*)%s", exp.constant);*/
2917
2918                            //evaluation = Debugger::EvaluateExpression(temp, &evalError);
2919                            // address = strtoul(exp.constant, null, 0);
2920                            address = _strtoui64(exp.constant, null, 0);
2921                            //_dpl(0, "0x", address);
2922                            // snprintf(value, sizeof(value), "0x%08x ", address);
2923
2924                            if(address > 0xFFFFFFFFLL)
2925                               snprintf(value, sizeof(value), (GetRuntimePlatform() == win32) ? "0x%016I64x " : "0x%016llx ", address);
2926                            else
2927                               snprintf(value, sizeof(value), (GetRuntimePlatform() == win32) ? "0x%08I64x " : "0x%08llx ", address);
2928                            value[sizeof(value)-1] = 0;
2929
2930                            if(!address)
2931                               strcat(value, $"Null string");
2932                            else
2933                            {
2934                               int size = 4096;
2935                               len = strlen(value);
2936                               string = null;
2937                               while(!string && size > 2)
2938                               {
2939                                  string = GdbReadMemory(address, size);
2940                                  size /= 2;
2941                               }
2942                               if(string && string[0])
2943                               {
2944                                  value[len++] = '(';
2945                                  if(UTF8Validate(string))
2946                                  {
2947                                     int c;
2948                                     char ch;
2949
2950                                     for(c = 0; (ch = string[c]) && c<4096; c++)
2951                                        value[len++] = ch;
2952                                     value[len++] = ')';
2953                                     value[len++] = '\0';
2954
2955                                  }
2956                                  else
2957                                  {
2958                                     ISO8859_1toUTF8(string, value + len, 4096 - len - 30);
2959                                     strcat(value, ") (ISO8859-1)");
2960                                  }
2961
2962                                  delete string;
2963                               }
2964                               else if(string)
2965                               {
2966                                  strcat(value, $"Empty string");
2967                                  delete string;
2968                               }
2969                               else
2970                                  strcat(value, $"Couldn't read memory");
2971                            }
2972                            wh.value = CopyString(value);
2973                         }
2974                      }
2975                      else if(wh.type && wh.type.kind == classType && wh.type._class &&
2976                               wh.type._class.registered && wh.type._class.registered.type == enumClass)
2977                      {
2978                         uint64 value = strtoul(exp.constant, null, 0);
2979                         Class enumClass = eSystem_FindClass(GetPrivateModule(), wh.type._class.registered.name);
2980                         EnumClassData enumeration = (EnumClassData)enumClass.data;
2981                         NamedLink item;
2982                         for(item = enumeration.values.first; item; item = item.next)
2983                            if((int)item.data == value)
2984                               break;
2985                         if(item)
2986                            wh.value = CopyString(item.name);
2987                         else
2988                            wh.value = CopyString($"Invalid Enum Value");
2989                         result = true;
2990                      }
2991                      else if(wh.type && (wh.type.kind == charType || (wh.type.kind == classType && wh.type._class &&
2992                               wh.type._class.registered && !strcmp(wh.type._class.registered.fullName, "ecere::com::unichar"))) )
2993                      {
2994                         unichar value;
2995                         int signedValue;
2996                         char charString[5];
2997                         char string[256];
2998
2999                         if(exp.constant[0] == '\'')
3000                         {
3001                            if((int)((byte *)exp.constant)[1] > 127)
3002                            {
3003                               int nb;
3004                               value = UTF8GetChar(exp.constant + 1, &nb);
3005                               if(nb < 2) value = exp.constant[1];
3006                               signedValue = value;
3007                            }
3008                            else
3009                            {
3010                               signedValue = exp.constant[1];
3011                               {
3012                                  // Precomp Syntax error with boot strap here:
3013                                  byte b = (byte)(char)signedValue;
3014                                  value = (unichar) b;
3015                               }
3016                            }
3017                         }
3018                         else
3019                         {
3020                            if(wh.type.kind == charType && wh.type.isSigned)
3021                            {
3022                               signedValue = (int)(char)strtol(exp.constant, null, 0);
3023                               {
3024                                  // Precomp Syntax error with boot strap here:
3025                                  byte b = (byte)(char)signedValue;
3026                                  value = (unichar) b;
3027                               }
3028                            }
3029                            else
3030                            {
3031                               value = (uint)strtoul(exp.constant, null, 0);
3032                               signedValue = (int)value;
3033                            }
3034                         }
3035                         charString[0] = 0;
3036                         UTF32toUTF8Len(&value, 1, charString, 5);
3037                         if(value == '\0')
3038                            snprintf(string, sizeof(string), "\'\\0' (0)");
3039                         else if(value == '\t')
3040                            snprintf(string, sizeof(string), "\'\\t' (%d)", value);
3041                         else if(value == '\n')
3042                            snprintf(string, sizeof(string), "\'\\n' (%d)", value);
3043                         else if(value == '\r')
3044                            snprintf(string, sizeof(string), "\'\\r' (%d)", value);
3045                         else if(wh.type.kind == charType && wh.type.isSigned)
3046                            snprintf(string, sizeof(string), "\'%s\' (%d)", charString, signedValue);
3047                         else if(value > 256 || wh.type.kind != charType)
3048                         {
3049                            if(value > 0x10FFFF || !GetCharCategory(value))
3050                               snprintf(string, sizeof(string), $"Invalid Unicode Keypoint (0x%08X)", value);
3051                            else
3052                               snprintf(string, sizeof(string), "\'%s\' (U+%04X)", charString, value);
3053                         }
3054                         else
3055                            snprintf(string, sizeof(string), "\'%s\' (%d)", charString, value);
3056                         string[sizeof(string)-1] = 0;
3057
3058                         wh.value = CopyString(string);
3059                         result = true;
3060                      }
3061                      else
3062                      {
3063                         wh.value = CopyString(exp.constant);
3064                         result = true;
3065                      }
3066                      break;
3067                   default:
3068                      if(exp.hasAddress)
3069                      {
3070                         wh.value = PrintHexUInt64(exp.address);
3071                         result = true;
3072                      }
3073                      else
3074                      {
3075                         char tempString[256];
3076                         if(exp.member.memberType == propertyMember)
3077                            snprintf(watchmsg, sizeof(watchmsg), $"Missing property evaluation support for \"%s\"", wh.expression);
3078                         else
3079                            snprintf(watchmsg, sizeof(watchmsg), $"Evaluation failed for \"%s\" of type \"%s\"", wh.expression,
3080                                  exp.type.OnGetString(tempString, null, null));
3081                      }
3082                      break;
3083                }
3084             }
3085             else
3086                snprintf(watchmsg, sizeof(watchmsg), $"Invalid expression: \"%s\"", wh.expression);
3087             if(exp) FreeExpression(exp);
3088
3089
3090             SetPrivateModule(backupPrivateModule);
3091             SetCurrentContext(backupContext);
3092             SetTopContext(backupContext);
3093             SetGlobalContext(backupContext);
3094             SetThisClass(backupThisClass);
3095          }
3096          //else
3097          //   wh.value = CopyString("No source file found for selected frame");
3098
3099          watchmsg[sizeof(watchmsg)-1] = 0;
3100          if(!wh.value)
3101             wh.value = CopyString(watchmsg);
3102       }
3103       ide.watchesView.UpdateWatch(wh);
3104       return result;
3105    }
3106
3107    void EvaluateWatches()
3108    {
3109       _dpl2(_dpct, dplchan::debuggerWatches, 0, "Debugger::EvaluateWatches()");
3110       WatchesLinkCodeEditor();
3111       if(state == stopped)
3112       {
3113          for(wh : ide.workspace.watches)
3114             ResolveWatch(wh);
3115       }
3116    }
3117
3118    char * ::GdbEvaluateExpression(char * expression)
3119    {
3120       _dpl2(_dpct, dplchan::debuggerWatches, 0, "Debugger::GdbEvaluateExpression(", expression, ")");
3121       eval.active = true;
3122       eval.error = none;
3123       GdbCommand(0, false, "-data-evaluate-expression \"%s\"", expression);
3124       if(eval.active)
3125          ide.outputView.debugBox.Logf("Debugger Error: GdbEvaluateExpression\n");
3126       return eval.result;
3127    }
3128
3129    // to be removed... use GdbReadMemory that returns a byte array instead
3130    char * ::GdbReadMemoryString(uint64 address, int size, char format, int rows, int cols)
3131    {
3132       _dpl2(_dpct, dplchan::debuggerCall, 0, "Debugger::GdbReadMemoryString(", address, ")");
3133       eval.active = true;
3134       eval.error = none;
3135 #ifdef _DEBUG
3136       if(!size)
3137          _dpl(0, "GdbReadMemoryString called with size = 0!");
3138 #endif
3139       // GdbCommand(0, false, "-data-read-memory 0x%08x %c, %d, %d, %d", address, format, size, rows, cols);
3140       if(GetRuntimePlatform() == win32)
3141          GdbCommand(0, false, "-data-read-memory 0x%016I64x %c, %d, %d, %d", address, format, size, rows, cols);
3142       else
3143          GdbCommand(0, false, "-data-read-memory 0x%016llx %c, %d, %d, %d", address, format, size, rows, cols);
3144       if(eval.active)
3145          ide.outputView.debugBox.Logf("Debugger Error: GdbReadMemoryString\n");
3146       return eval.result;
3147    }
3148
3149    byte * ::GdbReadMemory(uint64 address, int bytes)
3150    {
3151       _dpl2(_dpct, dplchan::debuggerCall, 0, "Debugger::GdbReadMemory(", address, ")");
3152       eval.active = true;
3153       eval.error = none;
3154       //GdbCommand(0, false, "-data-read-memory 0x%08x %c, 1, 1, %d", address, 'u', bytes);
3155       if(GetRuntimePlatform() == win32)
3156          GdbCommand(0, false, "-data-read-memory 0x%016I64x %c, 1, 1, %d", address, 'u', bytes);
3157       else
3158          GdbCommand(0, false, "-data-read-memory 0x%016llx %c, 1, 1, %d", address, 'u', bytes);
3159 #ifdef _DEBUG
3160       if(!bytes)
3161          _dpl(0, "GdbReadMemory called with bytes = 0!");
3162 #endif
3163       if(eval.active)
3164          ide.outputView.debugBox.Logf("Debugger Error: GdbReadMemory\n");
3165       else if(eval.result && strcmp(eval.result, "N/A"))
3166       {
3167          byte * result = new byte[bytes];
3168          byte * string = eval.result;
3169          int c = 0;
3170          while(true)
3171          {
3172             result[c++] = (byte)strtol(string, &string, 10);
3173             if(string)
3174             {
3175                if(*string == ',')
3176                   string++;
3177                 else
3178                   break;
3179             }
3180             else
3181                break;
3182          }
3183          return result;
3184       }
3185       return null;
3186    }
3187
3188    bool BreakpointHit(GdbDataStop stopItem, Breakpoint bpInternal, Breakpoint bpUser)
3189    {
3190       bool result = true;
3191       char * s1 = null; char * s2 = null;
3192       _dpl2(_dpct, dplchan::debuggerCall, 0, "Debugger::BreakpointHit(",
3193             "bpInternal(", bpInternal ? s1=bpInternal.CopyLocationString(false) : null, "), ",
3194             "bpUser(", bpUser ? s2=bpUser.CopyLocationString(false) : null, ")) -- ",
3195             "ignoreBreakpoints(", ignoreBreakpoints, "), ",
3196             "hitCursorBreakpoint(", bpUser && bpUser.type == runToCursor,  ")");
3197       delete s1; delete s2;
3198
3199       if(bpUser)
3200       {
3201          bool conditionMet = true;
3202          if(bpUser.condition)
3203          {
3204             if(WatchesLinkCodeEditor())
3205                conditionMet = ResolveWatch(bpUser.condition);
3206             else
3207                conditionMet = false;
3208          }
3209          bpUser.hits++;
3210          if(conditionMet)
3211          {
3212             if(!bpUser.ignore)
3213                bpUser.breaks++;
3214             else
3215             {
3216                bpUser.ignore--;
3217                result = false;
3218             }
3219          }
3220          else
3221             result = false;
3222          if(stopItem.frame.line && bpUser.line != stopItem.frame.line)
3223          {
3224             // updating user breakpoint on hit location difference
3225             // todo, print something?
3226             bpUser.line = stopItem.frame.line;
3227             ide.breakpointsView.UpdateBreakpoint(bpUser.row);
3228             ide.workspace.Save();
3229          }
3230          else
3231             ide.breakpointsView.UpdateBreakpoint(bpUser.row);
3232       }
3233       if(bpInternal)
3234       {
3235          bpInternal.hits++;
3236          if(bpInternal.type == internalModulesLoaded)
3237             modules = true;
3238          if(userAction == stepOver)
3239          {
3240             if((bpInternal.type == internalEntry && ((intBpMain && intBpMain.inserted) || (intBpWinMain && intBpWinMain.inserted))) ||
3241                   (bpInternal.type == internalMain && intBpWinMain && intBpWinMain.inserted))
3242                result = false;
3243          }
3244          if(!bpUser && !userAction.breaksOnInternalBreakpoint)
3245          {
3246             if(userAction == stepOut)
3247                StepOut(ignoreBreakpoints);
3248             else
3249                result = false;
3250          }
3251       }
3252
3253       if(!bpUser && !bpInternal)
3254          result = false;
3255
3256       return result;
3257    }
3258
3259    void ValgrindTargetThreadExit()
3260    {
3261       _dpl2(_dpct, dplchan::debuggerCall, 0, "Debugger::ValgrindTargetThreadExit()");
3262       if(vgTargetHandle)
3263       {
3264          vgTargetHandle.Wait();
3265          delete vgTargetHandle;
3266       }
3267       HandleExit(null, null);
3268    }
3269
3270    void GdbThreadExit()
3271    {
3272       _dpl2(_dpct, dplchan::debuggerCall, 0, "Debugger::GdbThreadExit()");
3273       if(state != terminated)
3274       {
3275          _ChangeState(terminated);
3276          targetProcessId = 0;
3277          ClearBreakDisplay();
3278
3279          delete vgLogFile;
3280          if(gdbHandle)
3281          {
3282             serialSemaphore.Release();
3283             gdbTimer.Stop();
3284             gdbHandle.Wait();
3285             delete gdbHandle;
3286
3287             ide.outputView.debugBox.Logf($"Debugger Fatal Error: GDB lost\n");
3288             ide.outputView.debugBox.Logf($"Debugging stopped\n");
3289             ide.Update(null);
3290             HideDebuggerViews();
3291          }
3292          //_ChangeState(terminated);
3293       }
3294    }
3295
3296    void GdbThreadMain(char * output)
3297    {
3298       int i;
3299       char * t;
3300       Array<char *> outTokens { minAllocSize = 50 };
3301       Array<char *> subTokens { minAllocSize = 50 };
3302       DebugListItem item { };
3303       DebugListItem item2 { };
3304       bool setWaitingForPID = false;
3305
3306 #if defined(GDB_DEBUG_CONSOLE) || defined(GDB_DEBUG_GUI)
3307 #ifdef GDB_DEBUG_CONSOLE
3308       // _dpl2(_dpct, dplchan::gdbOutput, 0, output);
3309       puts(output);
3310 #endif
3311 #ifdef GDB_DEBUG_OUTPUT
3312       {
3313          int len = strlen(output);
3314          if(len > 1024)
3315          {
3316             int c;
3317             char * start;
3318             char tmp[1025];
3319             tmp[1024] = '\0';
3320             start = output;
3321             for(c = 0; c < len / 1024; c++)
3322             {
3323                strncpy(tmp, start, 1024);
3324                ide.outputView.gdbBox.Logf("out: %s\n", tmp);
3325                start += 1024;
3326             }
3327             ide.outputView.gdbBox.Logf("out: %s\n", start);
3328          }
3329          else
3330          {
3331             ide.outputView.gdbBox.Logf("out: %s\n", output);
3332          }
3333       }
3334 #endif
3335 #ifdef GDB_DEBUG_CONSOLE
3336          strcpy(lastGdbOutput, output);
3337 #endif
3338 #ifdef GDB_DEBUG_GUI
3339          if(ide.gdbDialog) ide.gdbDialog.AddOutput(output);
3340 #endif
3341 #endif
3342
3343       switch(output[0])
3344       {
3345          case '~':
3346             if(strstr(output, "No debugging symbols found") || strstr(output, "(no debugging symbols found)"))
3347             {
3348                symbols = false;
3349                ide.outputView.debugBox.Logf($"Target doesn't contain debug information!\n");
3350                ide.Update(null);
3351             }
3352             if(!entryPoint && (t = strstr(output, "Entry point:")))
3353             {
3354                char * addr = t + strlen("Entry point:");
3355                t = addr;
3356                if(*t++ == ' ' && *t++ == '0' && *t == 'x')
3357                {
3358                   *addr = '*';
3359                   while(isxdigit(*++t));
3360                   *t = '\0';
3361                   for(bp : sysBPs; bp.type == internalEntry)
3362                   {
3363                      bp.function = addr;
3364                      bp.enabled = entryPoint = true;
3365                      break;
3366                   }
3367                }
3368             }
3369             break;
3370          case '^':
3371             gdbReady = false;
3372             if(TokenizeList(output, ',', outTokens) && !strcmp(outTokens[0], "^done"))
3373             {
3374                //if(outTokens.count == 1)
3375                {
3376                   if(sentKill)
3377                   {
3378                      sentKill = false;
3379                      _ChangeState(loaded);
3380                      targetProcessId = 0;
3381                      if(outTokens.count > 1 && TokenizeListItem(outTokens[1], item))
3382                      {
3383                         if(!strcmp(item.name, "reason"))
3384                         {
3385                            char * reason = item.value;
3386                            StripQuotes(reason, reason);
3387                            if(!strcmp(reason, "exited-normally") || !strcmp(reason, "exited") || !strcmp(reason, "exited-signalled"))
3388                            {
3389                               char * exitCode;
3390                               if(outTokens.count > 2 && TokenizeListItem(outTokens[2], item2))
3391                               {
3392                                  StripQuotes(item2.value, item2.value);
3393                                  if(!strcmp(item2.name, "exit-code"))
3394                                     exitCode = item2.value;
3395                                  else
3396                                     exitCode = null;
3397                               }
3398                               else
3399                                  exitCode = null;
3400                               HandleExit(reason, exitCode);
3401                            }
3402                         }
3403                         else
3404                            _dpl2(_dpct, dplchan::gdbProtoUnknown, 0, "kill reply (", item.name, "=", item.value, ") is unheard of");
3405                      }
3406                      else
3407                         HandleExit(null, null);
3408                   }
3409                }
3410                if(outTokens.count > 1 && TokenizeListItem(outTokens[1], item))
3411                {
3412                   if(!strcmp(item.name, "bkpt"))
3413                   {
3414                      sentBreakInsert = false;
3415 #ifdef _DEBUG
3416                      if(bpItem)
3417                         _dpl(0, "problem");
3418 #endif
3419                      delete bpItem;
3420                      bpItem = ParseBreakpoint(item.value, outTokens);
3421                      //breakType = bpValidation;
3422                   }
3423                   else if(!strcmp(item.name, "depth"))
3424                   {
3425                      StripQuotes(item.value, item.value);
3426                      frameCount = atoi(item.value);
3427                      activeFrame = null;
3428                      stackFrames.Free(Frame::Free);
3429                   }
3430                   else if(!strcmp(item.name, "stack"))
3431                   {
3432                      Frame frame;
3433                      if(stackFrames.count)
3434                         ide.callStackView.Logf("...\n");
3435                      else
3436                         activeFrame = null;
3437                      item.value = StripBrackets(item.value);
3438                      TokenizeList(item.value, ',', subTokens);
3439                      for(i = 0; i < subTokens.count; i++)
3440                      {
3441                         if(TokenizeListItem(subTokens[i], item))
3442                         {
3443                            if(!strcmp(item.name, "frame"))
3444                            {
3445                               frame = Frame { };
3446                               stackFrames.Add(frame);
3447                               item.value = StripCurlies(item.value);
3448                               ParseFrame(frame, item.value);
3449                               if(frame.file && frame.from)
3450                                  _dpl2(_dpct, dplchan::gdbProtoUnknown, 0, "unexpected frame file and from members present");
3451                               if(frame.file)
3452                               {
3453                                  char * s = null;
3454                                  if(activeFrameLevel == -1)
3455                                  {
3456                                     if(ide.projectView.IsModuleInProject(frame.file));
3457                                     {
3458                                        if(frame.level != 0)
3459                                        {
3460                                           //stopItem.frame = frame;
3461                                           breakType = selectFrame;
3462                                        }
3463                                        else
3464                                           activeFrame = frame;
3465                                        activeFrameLevel = frame.level;
3466                                     }
3467                                  }
3468                                  ide.callStackView.Logf("%3d ", frame.level);
3469                                  if(!strncmp(frame.func, "__ecereMethod_", strlen("__ecereMethod_")))
3470                                     ide.callStackView.Logf($"%s Method, %s:%d\n", &frame.func[strlen("__ecereMethod_")], (s = CopySystemPath(frame.file)), frame.line);
3471                                  else if(!strncmp(frame.func, "__ecereProp_", strlen("__ecereProp_")))
3472                                     ide.callStackView.Logf($"%s Property, %s:%d\n", &frame.func[strlen("__ecereProp_")], (s = CopySystemPath(frame.file)), frame.line);
3473                                  else if(!strncmp(frame.func, "__ecereConstructor_", strlen("__ecereConstructor_")))
3474                                     ide.callStackView.Logf($"%s Constructor, %s:%d\n", &frame.func[strlen("__ecereConstructor_")], (s = CopySystemPath(frame.file)), frame.line);
3475                                  else if(!strncmp(frame.func, "__ecereDestructor_", strlen("__ecereDestructor_")))
3476                                     ide.callStackView.Logf($"%s Destructor, %s:%d\n", &frame.func[strlen("__ecereDestructor_")], (s = CopySystemPath(frame.file)), frame.line);
3477                                  else
3478                                     ide.callStackView.Logf($"%s Function, %s:%d\n", frame.func, (s = CopySystemPath(frame.file)), frame.line);
3479                                  delete s;
3480                               }
3481                               else
3482                               {
3483                                  ide.callStackView.Logf("%3d ", frame.level);
3484
3485                                  if(frame.from)
3486                                  {
3487                                     char * s = null;
3488                                     ide.callStackView.Logf($"inside %s, %s\n", frame.func, (s = CopySystemPath(frame.from)));
3489                                     delete s;
3490                                  }
3491                                  else if(frame.func)
3492                                     ide.callStackView.Logf("%s\n", frame.func);
3493                                  else
3494                                     ide.callStackView.Logf($"unknown source\n");
3495                               }
3496                            }
3497                            else
3498                               _dpl2(_dpct, dplchan::gdbProtoUnknown, 0, "stack content (", item.name, "=", item.value, ") is unheard of");
3499                         }
3500                      }
3501                      if(activeFrameLevel == -1)
3502                      {
3503                         activeFrameLevel = 0;
3504                         activeFrame = stackFrames.first;
3505                      }
3506                      ide.callStackView.Home();
3507                      ide.Update(null);
3508                      subTokens.RemoveAll();
3509                   }
3510                   /*else if(!strcmp(item.name, "frame"))
3511                   {
3512                      Frame frame { };
3513                      item.value = StripCurlies(item.value);
3514                      ParseFrame(&frame, item.value);
3515                   }*/
3516                   else if(!strcmp(item.name, "thread-ids"))
3517                   {
3518                      ide.threadsView.Clear();
3519                      item.value = StripCurlies(item.value);
3520                      TokenizeList(item.value, ',', subTokens);
3521                      for(i = subTokens.count - 1; ; i--)
3522                      {
3523                         if(TokenizeListItem(subTokens[i], item))
3524                         {
3525                            if(!strcmp(item.name, "thread-id"))
3526                            {
3527                               int value;
3528                               StripQuotes(item.value, item.value);
3529                               value = atoi(item.value);
3530                               ide.threadsView.Logf("%3d \n", value);
3531                            }
3532                            else
3533                               _dpl2(_dpct, dplchan::gdbProtoUnknown, 0, "threads content (", item.name, "=", item.value, ") is unheard of");
3534                         }
3535                         if(!i)
3536                            break;
3537                      }
3538                      ide.threadsView.Home();
3539                      ide.Update(null);
3540                      subTokens.RemoveAll();
3541                      //if(!strcmp(outTokens[2], "number-of-threads"))
3542                   }
3543                   else if(!strcmp(item.name, "new-thread-id"))
3544                   {
3545                      StripQuotes(item.value, item.value);
3546                      activeThread = atoi(item.value);
3547                   }
3548                   else if(!strcmp(item.name, "value"))
3549                   {
3550                      StripQuotes(item.value, item.value);
3551                      eval.result = CopyString(item.value);
3552                      eval.active = false;
3553                   }
3554                   else if(!strcmp(item.name, "addr"))
3555                   {
3556                      for(i = 2; i < outTokens.count; i++)
3557                      {
3558                         if(TokenizeListItem(outTokens[i], item))
3559                         {
3560                            if(!strcmp(item.name, "total-bytes"))
3561                            {
3562                               StripQuotes(item.value, item.value);
3563                               eval.bytes = atoi(item.value);
3564                            }
3565                            else if(!strcmp(item.name, "next-row"))
3566                            {
3567                               StripQuotes(item.value, item.value);
3568                               eval.nextBlockAddress = _strtoui64(item.value, null, 0);
3569                            }
3570                            else if(!strcmp(item.name, "memory"))
3571                            {
3572                               int j;
3573                               //int value;
3574                               //StripQuotes(item.value, item.value);
3575                               item.value = StripBrackets(item.value);
3576                               // this should be treated as a list...
3577                               item.value = StripCurlies(item.value);
3578                               TokenizeList(item.value, ',', subTokens);
3579                               for(j = 0; j < subTokens.count; j++)
3580                               {
3581                                  if(TokenizeListItem(subTokens[j], item))
3582                                  {
3583                                     if(!strcmp(item.name, "data"))
3584                                     {
3585                                        item.value = StripBrackets(item.value);
3586                                        StripQuotes2(item.value, item.value);
3587                                        eval.result = CopyString(item.value);
3588                                        eval.active = false;
3589                                     }
3590                                  }
3591                               }
3592                               subTokens.RemoveAll();
3593                            }
3594                         }
3595                      }
3596                   }
3597                   else if(!strcmp(item.name, "source-path") || !strcmp(item.name, "BreakpointTable"))
3598                      _dpl2(_dpct, dplchan::gdbProtoIgnored, 0, "command reply (", item.name, "=", item.value, ") is ignored");
3599                   else
3600                      _dpl2(_dpct, dplchan::gdbProtoUnknown, 0, "command reply (", item.name, "=", item.value, ") is unheard of");
3601                }
3602             }
3603             else if(!strcmp(outTokens[0], "^running"))
3604             {
3605                waitingForPID = true;
3606                setWaitingForPID = true;
3607                ClearBreakDisplay();
3608             }
3609             else if(!strcmp(outTokens[0], "^exit"))
3610             {
3611                _ChangeState(terminated);
3612                // ide.outputView.debugBox.Logf("Exit\n");
3613                // ide.Update(null);
3614                gdbReady = true;
3615                serialSemaphore.Release();
3616             }
3617             else if(!strcmp(outTokens[0], "^error"))
3618             {
3619                if(sentBreakInsert)
3620                {
3621                   sentBreakInsert = false;
3622                   breakpointError = true;
3623                }
3624
3625                if(outTokens.count > 1 && TokenizeListItem(outTokens[1], item))
3626                {
3627                   if(!strcmp(item.name, "msg"))
3628                   {
3629                      StripQuotes(item.value, item.value);
3630                      if(eval.active)
3631                      {
3632                         eval.active = false;
3633                         eval.result = null;
3634                         if(strstr(item.value, "No symbol") && strstr(item.value, "in current context"))
3635                            eval.error = symbolNotFound;
3636                         else if(strstr(item.value, "Cannot access memory at address"))
3637                            eval.error = memoryCantBeRead;
3638                         else
3639                            eval.error = unknown;
3640                      }
3641                      else if(!strcmp(item.value, "Previous frame inner to this frame (corrupt stack?)"))
3642                      {
3643                      }
3644                      else if(!strncmp(item.value, "Cannot access memory at address", 31))
3645                      {
3646                      }
3647                      else if(!strcmp(item.value, "Cannot find bounds of current function"))
3648                      {
3649                         _ChangeState(stopped);
3650                         gdbHandle.Printf("-exec-continue\n");
3651                      }
3652                      else if(!strcmp(item.value, "ptrace: No such process."))
3653                      {
3654                         _ChangeState(loaded);
3655                         targetProcessId = 0;
3656                      }
3657                      else if(!strcmp(item.value, "Function \\\"WinMain\\\" not defined."))
3658                      {
3659                      }
3660                      else if(!strcmp(item.value, "You can't do that without a process to debug."))
3661                      {
3662                         _ChangeState(loaded);
3663                         targetProcessId = 0;
3664                      }
3665                      else if(strstr(item.value, "No such file or directory."))
3666                      {
3667                         _ChangeState(loaded);
3668                         targetProcessId = 0;
3669                      }
3670                      else if(strstr(item.value, "During startup program exited with code "))
3671                      {
3672                         _ChangeState(loaded);
3673                         targetProcessId = 0;
3674                      }
3675                      else
3676                      {
3677 #ifdef _DEBUG
3678                         if(strlen(item.value) < MAX_F_STRING)
3679                         {
3680                            char * s = null;
3681                            ide.outputView.debugBox.Logf("GDB: %s\n", (s = CopyUnescapedString(item.value)));
3682                            delete s;
3683                         }
3684                         else
3685                            ide.outputView.debugBox.Logf("GDB: %s\n", item.value);
3686 #endif
3687                      }
3688                   }
3689                }
3690                else
3691                   _dpl2(_dpct, dplchan::gdbProtoUnknown, 0, "error content (", item.name, "=", item.value, ") is unheard of");
3692             }
3693             else
3694                _dpl2(_dpct, dplchan::gdbProtoUnknown, 0, "result-record: ", outTokens[0]);
3695             outTokens.RemoveAll();
3696             break;
3697          case '+':
3698             _dpl2(_dpct, dplchan::gdbProtoUnknown, 0, "status-async-output: ", outTokens[0]);
3699             break;
3700          case '=':
3701             if(TokenizeList(output, ',', outTokens))
3702             {
3703                if(!strcmp(outTokens[0], "=library-loaded"))
3704                   FGODetectLoadedLibraryForAddedProjectIssues(outTokens);
3705                else if(!strcmp(outTokens[0], "=thread-group-created") || !strcmp(outTokens[0], "=thread-group-added") ||
3706                         !strcmp(outTokens[0], "=thread-group-started") || !strcmp(outTokens[0], "=thread-group-exited") ||
3707                         !strcmp(outTokens[0], "=thread-created") || !strcmp(outTokens[0], "=thread-exited") ||
3708                         !strcmp(outTokens[0], "=cmd-param-changed") || !strcmp(outTokens[0], "=library-unloaded") ||
3709                         !strcmp(outTokens[0], "=breakpoint-modified"))
3710                   _dpl2(_dpct, dplchan::gdbProtoIgnored, 0, outTokens[0], outTokens.count>1 ? outTokens[1] : "",
3711                            outTokens.count>2 ? outTokens[2] : "", outTokens.count>3 ? outTokens[3] : "",
3712                            outTokens.count>4 ? outTokens[4] : "", outTokens.count>5 ? outTokens[5] : "",
3713                            outTokens.count>6 ? outTokens[6] : "", outTokens.count>7 ? outTokens[7] : "",
3714                            outTokens.count>8 ? outTokens[8] : "", outTokens.count>9 ? outTokens[9] : "");
3715                else
3716                   _dpl2(_dpct, dplchan::gdbProtoUnknown, 0, "notify-async-output: ", outTokens[0]);
3717             }
3718             outTokens.RemoveAll();
3719             break;
3720          case '*':
3721             gdbReady = false;
3722             if(TokenizeList(output, ',', outTokens))
3723             {
3724                if(!strcmp(outTokens[0],"*running"))
3725                {
3726                   waitingForPID = true;
3727                   setWaitingForPID = true;
3728                }
3729                else if(!strcmp(outTokens[0], "*stopped"))
3730                {
3731                   int tk;
3732                   _ChangeState(stopped);
3733
3734                   for(tk = 1; tk < outTokens.count; tk++)
3735                   {
3736                      if(TokenizeListItem(outTokens[tk], item))
3737                      {
3738                         if(!strcmp(item.name, "reason"))
3739                         {
3740                            char * reason = item.value;
3741                            StripQuotes(reason, reason);
3742                            if(!strcmp(reason, "exited-normally") || !strcmp(reason, "exited") || !strcmp(reason, "exited-signalled"))
3743                            {
3744                               char * exitCode;
3745                               if(outTokens.count > tk+1 && TokenizeListItem(outTokens[tk+1], item2))
3746                               {
3747                                  tk++;
3748                                  StripQuotes(item2.value, item2.value);
3749                                  if(!strcmp(item2.name, "exit-code"))
3750                                     exitCode = item2.value;
3751                                  else
3752                                     exitCode = null;
3753                               }
3754                               else
3755                                  exitCode = null;
3756                               HandleExit(reason, exitCode);
3757                               needReset = true;
3758                            }
3759                            else if(!strcmp(reason, "breakpoint-hit") ||
3760                                    !strcmp(reason, "function-finished") ||
3761                                    !strcmp(reason, "end-stepping-range") ||
3762                                    !strcmp(reason, "location-reached") ||
3763                                    !strcmp(reason, "signal-received"))
3764                            {
3765                               char r = reason[0];
3766 #ifdef _DEBUG
3767                               if(stopItem) _dpl(0, "problem");
3768 #endif
3769                               stopItem = GdbDataStop { };
3770                               stopItem.reason = r == 'b' ? breakpointHit : r == 'f' ? functionFinished : r == 'e' ? endSteppingRange : r == 'l' ? locationReached : signalReceived;
3771
3772                               for(i = tk+1; i < outTokens.count; i++)
3773                               {
3774                                  TokenizeListItem(outTokens[i], item);
3775                                  StripQuotes(item.value, item.value);
3776                                  if(!strcmp(item.name, "thread-id"))
3777                                     stopItem.threadid = atoi(item.value);
3778                                  else if(!strcmp(item.name, "frame"))
3779                                  {
3780                                     item.value = StripCurlies(item.value);
3781                                     ParseFrame(stopItem.frame, item.value);
3782                                  }
3783                                  else if(stopItem.reason == breakpointHit && !strcmp(item.name, "bkptno"))
3784                                     stopItem.bkptno = atoi(item.value);
3785                                  else if(stopItem.reason == functionFinished && !strcmp(item.name, "gdb-result-var"))
3786                                     stopItem.gdbResultVar = CopyString(item.value);
3787                                  else if(stopItem.reason == functionFinished && !strcmp(item.name, "return-value"))
3788                                     stopItem.returnValue = CopyString(item.value);
3789                                  else if(stopItem.reason == signalReceived && !strcmp(item.name, "signal-name"))
3790                                     stopItem.name = CopyString(item.value);
3791                                  else if(stopItem.reason == signalReceived && !strcmp(item.name, "signal-meaning"))
3792                                     stopItem.meaning = CopyString(item.value);
3793                                  else if(!strcmp(item.name, "stopped-threads"))
3794                                     _dpl2(_dpct, dplchan::gdbProtoIgnored, 0, reason, ": Advanced thread debugging not handled");
3795                                  else if(!strcmp(item.name, "core"))
3796                                     _dpl2(_dpct, dplchan::gdbProtoIgnored, 0, reason, ": Information (core) not used");
3797                                  else if(!strcmp(item.name, "disp"))
3798                                     _dpl2(_dpct, dplchan::gdbProtoIgnored, 0, reason, ": (", item.name, "=", item.value, ")");
3799                                  else
3800                                     _dpl2(_dpct, dplchan::gdbProtoUnknown, 0, "Unknown ", reason, " item name (", item.name, "=", item.value, ")");
3801                               }
3802
3803                               if(stopItem.reason == signalReceived && !strcmp(stopItem.name, "SIGTRAP"))
3804                               {
3805                                  switch(breakType)
3806                                  {
3807                                     case internal:
3808                                        breakType = none;
3809                                        break;
3810                                     case restart:
3811                                     case stop:
3812                                        break;
3813                                     default:
3814                                        event = breakEvent;
3815                                  }
3816                               }
3817                               else
3818                               {
3819                                  event = r == 'b' ? hit : r == 'f' ? functionEnd : r == 'e' ? stepEnd : r == 'l' ? locationReached : signal;
3820                                  ide.Update(null);
3821                               }
3822                            }
3823                            else if(!strcmp(reason, "watchpoint-trigger"))
3824                               _dpl2(_dpct, dplchan::gdbProtoIgnored, 0, "Reason watchpoint trigger not handled");
3825                            else if(!strcmp(reason, "read-watchpoint-trigger"))
3826                               _dpl2(_dpct, dplchan::gdbProtoIgnored, 0, "Reason read watchpoint trigger not handled");
3827                            else if(!strcmp(reason, "access-watchpoint-trigger"))
3828                               _dpl2(_dpct, dplchan::gdbProtoIgnored, 0, "Reason access watchpoint trigger not handled");
3829                            else if(!strcmp(reason, "watchpoint-scope"))
3830                               _dpl2(_dpct, dplchan::gdbProtoIgnored, 0, "Reason watchpoint scope not handled");
3831                            else
3832                               _dpl2(_dpct, dplchan::gdbProtoUnknown, 0, "Unknown reason: ", reason);
3833                         }
3834                         else
3835                         {
3836                            PrintLn(output);
3837                         }
3838                      }
3839                   }
3840                   if(usingValgrind && event == none && !stopItem)
3841                      event = valgrindStartPause;
3842                   app.SignalEvent();
3843                }
3844             }
3845             else
3846                _dpl2(_dpct, dplchan::gdbProtoUnknown, 0, "Unknown exec-async-output: ", outTokens[0]);
3847             outTokens.RemoveAll();
3848             break;
3849          case '(':
3850             if(!strcmpi(output, "(gdb) "))
3851             {
3852                if(waitingForPID)
3853                {
3854                   Time startTime = GetTime();
3855                   char exeFile[MAX_LOCATION];
3856                   int oldProcessID = targetProcessId;
3857                   GetLastDirectory(targetFile, exeFile);
3858
3859                   while(!targetProcessId/*true*/)
3860                   {
3861                      targetProcessId = Process_GetChildExeProcessId(gdbProcessId, exeFile);
3862                      if(targetProcessId) break;
3863                      // Can't break on Peek(), GDB is giving us =library and other info before the process is listed in /proc
3864                      // if(gdbHandle.Peek()) break;
3865                      Sleep(0.01);
3866                      if(gdbHandle.Peek() && GetTime() - startTime > 2.5)  // Give the process 2.5 seconds to show up in /proc
3867                         break;
3868                   }
3869
3870                   if(targetProcessId)
3871                      _ChangeState(running);
3872                   else if(!oldProcessID)
3873                   {
3874                      ide.outputView.debugBox.Logf($"Debugger Error: No target process ID\n");
3875                      // TO VERIFY: The rest of this block has not been thoroughly tested in this particular location
3876                      gdbHandle.Printf("-gdb-exit\n");
3877                      gdbTimer.Stop();
3878                      _ChangeState(terminated); //loaded;
3879                      prjConfig = null;
3880
3881                      if(ide.workspace)
3882                      {
3883                         for(bp : ide.workspace.breakpoints)
3884                            bp.inserted = false;
3885                      }
3886                      for(bp : sysBPs)
3887                         bp.inserted = false;
3888                      if(bpRunToCursor)
3889                         bpRunToCursor.inserted = false;
3890
3891                      ide.outputView.debugBox.Logf($"Debugging stopped\n");
3892                      ClearBreakDisplay();
3893
3894                #if defined(__unix__)
3895                      if(!usingValgrind && FileExists(progFifoPath)) //fileCreated)
3896                      {
3897                         progThread.terminate = true;
3898                         if(fifoFile)
3899                         {
3900                            fifoFile.CloseInput();
3901                            app.Unlock();
3902                            progThread.Wait();
3903                            app.Lock();
3904                            delete fifoFile;
3905                         }
3906
3907                         DeleteFile(progFifoPath);
3908                         progFifoPath[0] = '\0';
3909                         rmdir(progFifoDir);
3910                      }
3911                #endif
3912                   }
3913                }
3914                gdbReady = true;
3915                serialSemaphore.Release();
3916             }
3917             else
3918                _dpl2(_dpct, dplchan::gdbProtoUnknown, 0, $"Unknown prompt", output);
3919
3920             break;
3921          case '&':
3922             if(!strncmp(output, "&\"warning:", 10))
3923             {
3924                char * content;
3925                content = strstr(output, "\"");
3926                StripQuotes(content, content);
3927                content = strstr(content, ":");
3928                if(content)
3929                   content++;
3930                if(content)
3931                {
3932                   char * s = null;
3933                   ide.outputView.debugBox.LogRaw((s = CopyUnescapedString(content)));
3934                   delete s;
3935                   ide.Update(null);
3936                }
3937             }
3938             break;
3939          default:
3940             _dpl2(_dpct, dplchan::gdbProtoUnknown, 0, $"Unknown output: ", output);
3941       }
3942       if(!setWaitingForPID)
3943          waitingForPID = false;
3944       setWaitingForPID = false;
3945
3946       delete outTokens;
3947       delete subTokens;
3948       delete item;
3949       delete item2;
3950    }
3951
3952    // From GDB Output functions
3953    void FGODetectLoadedLibraryForAddedProjectIssues(Array<char *> outTokens)
3954    {
3955       char path[MAX_LOCATION] = "";
3956       char file[MAX_FILENAME] = "";
3957       bool symbolsLoaded;
3958       DebugListItem item { };
3959       //_dpl2(_dpct, dplchan::debuggerCall, 0, "Debugger::FGODetectLoadedLibraryForAddedProjectIssues()");
3960       for(token : outTokens)
3961       {
3962          if(TokenizeListItem(token, item))
3963          {
3964             if(!strcmp(item.name, "target-name"))
3965             {
3966                StripQuotes(item.value, path);
3967                MakeSystemPath(path);
3968                GetLastDirectory(path, file);
3969             }
3970             else if(!strcmp(item.name, "symbols-loaded"))
3971             {
3972                symbolsLoaded = (atoi(item.value) == 1);
3973             }
3974          }
3975       }
3976       delete item;
3977       if(path[0] && file[0])
3978       {
3979          for(prj : ide.workspace.projects; prj != ide.workspace.projects.firstIterator.data)
3980          {
3981             bool match;
3982             char * dot;
3983             char prjTargetPath[MAX_LOCATION];
3984             char prjTargetFile[MAX_FILENAME];
3985             DirExpression targetDirExp = prj.GetTargetDir(currentCompiler, prj.config, bitDepth);
3986             strcpy(prjTargetPath, prj.topNode.path);
3987             PathCat(prjTargetPath, targetDirExp.dir);
3988             delete targetDirExp;
3989             prjTargetFile[0] = '\0';
3990             prj.CatTargetFileName(prjTargetFile, currentCompiler, prj.config);
3991             PathCat(prjTargetPath, prjTargetFile);
3992             MakeSystemPath(prjTargetPath);
3993
3994             match = !fstrcmp(prjTargetFile, file);
3995             if(!match && (dot = strstr(prjTargetFile, ".so.")))
3996             {
3997                char * dot3 = strstr(dot+4, ".");
3998                if(dot3)
3999                {
4000                   dot3[0] = '\0';
4001                   match = !fstrcmp(prjTargetFile, file);
4002                }
4003                if(!match)
4004                {
4005                   dot[3] = '\0';
4006                   match = !fstrcmp(prjTargetFile, file);
4007                }
4008             }
4009             if(match)
4010             {
4011                // TODO: nice visual feedback to better warn user. use some ide notification system or other means.
4012                /* -- 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)
4013                if(!symbolsLoaded)
4014                   ide.outputView.debugBox.Logf($"Attention! No symbols for loaded library %s matched to the %s added project.\n", path, prj.topNode.name);
4015                */
4016                match = !fstrcmp(prjTargetPath, path);
4017                if(!match && (dot = strstr(prjTargetPath, ".so.")))
4018                {
4019                   char * dot3 = strstr(dot+4, ".");
4020                   if(dot3)
4021                   {
4022                      dot3[0] = '\0';
4023                      match = !fstrcmp(prjTargetPath, path);
4024                   }
4025                   if(!match)
4026                   {
4027                      dot[3] = '\0';
4028                      match = !fstrcmp(prjTargetPath, path);
4029                   }
4030                }
4031                if(match)
4032                   projectsLibraryLoaded[prj.name] = true;
4033                else
4034                   ide.outputView.debugBox.Logf($"Loaded library %s doesn't match the %s target of the %s added project.\n", path, prjTargetPath, prj.topNode.name);
4035                break;
4036             }
4037          }
4038       }
4039    }
4040
4041    void FGOBreakpointModified(Array<char *> outTokens)
4042    {
4043       _dpl2(_dpct, dplchan::debuggerCall, 0, "Debugger::FGOBreakpointModified() -- TODO only if needed: support breakpoint modified");
4044 #if 0
4045       DebugListItem item { };
4046       if(outTokens.count > 1 && TokenizeListItem(outTokens[1], item))
4047       {
4048          if(!strcmp(item.name, "bkpt"))
4049          {
4050             GdbDataBreakpoint modBp = ParseBreakpoint(item.value, outTokens);
4051             delete modBp;
4052          }
4053       }
4054 #endif
4055    }
4056
4057
4058    ExpressionType ::DebugEvalExpTypeError(char * result)
4059    {
4060       _dpl2(_dpct, dplchan::debuggerWatches, 0, "Debugger::DebugEvalExpTypeError()");
4061       if(result)
4062          return dummyExp;
4063       switch(eval.error)
4064       {
4065          case symbolNotFound:
4066             return symbolErrorExp;
4067          case memoryCantBeRead:
4068             return memoryErrorExp;
4069       }
4070       return unknownErrorExp;
4071    }
4072
4073    char * ::EvaluateExpression(char * expression, ExpressionType * error)
4074    {
4075       char * result;
4076       _dpl2(_dpct, dplchan::debuggerWatches, 0, "Debugger::EvaluateExpression(", expression, ")");
4077       if(ide.projectView && ide.debugger.state == stopped)
4078       {
4079          result = GdbEvaluateExpression(expression);
4080          *error = DebugEvalExpTypeError(result);
4081       }
4082       else
4083       {
4084          result = null;
4085          *error = noDebuggerErrorExp;
4086       }
4087       return result;
4088    }
4089
4090    char * ::ReadMemory(uint64 address, int size, char format, ExpressionType * error)
4091    {
4092       // check for state
4093       char * result = GdbReadMemoryString(address, size, format, 1, 1);
4094       _dpl2(_dpct, dplchan::debuggerCall, 0, "Debugger::ReadMemory(", address, ")");
4095       if(!result || !strcmp(result, "N/A"))
4096          *error = memoryErrorExp;
4097       else
4098          *error = DebugEvalExpTypeError(result);
4099       return result;
4100    }
4101 }
4102
4103 class ValgrindLogThread : Thread
4104 {
4105    Debugger debugger;
4106
4107    unsigned int Main()
4108    {
4109       static char output[4096];
4110       bool lastLineEmpty = true;
4111       Array<char> dynamicBuffer { minAllocSize = 4096 };
4112       File oldValgrindHandle = vgLogFile;
4113       incref oldValgrindHandle;
4114
4115       app.Lock();
4116       while(debugger.state != terminated && vgLogFile && vgLogFile.input)
4117       {
4118          int result = 0;
4119          app.Unlock();
4120          if(vgLogFile)
4121             result = vgLogFile.Read(output, 1, sizeof(output));
4122          app.Lock();
4123          if(debugger.state == terminated || !vgLogFile) // || vgLogFile.Eof()
4124             break;
4125          if(result)
4126          {
4127             int c;
4128             int start = 0;
4129
4130             for(c = 0; c<result; c++)
4131             {
4132                if(output[c] == '\n')
4133                {
4134                   int pos = dynamicBuffer.size;
4135                   dynamicBuffer.size += c - start;
4136                   memcpy(&dynamicBuffer[pos], output + start, c - start);
4137                   if(dynamicBuffer.count && dynamicBuffer[dynamicBuffer.count - 1] != '\r')
4138                      dynamicBuffer.size++;
4139                   dynamicBuffer[dynamicBuffer.count - 1] = '\0';
4140 #ifdef _DEBUG
4141                   // printf("%s\n", dynamicBuffer.array);
4142 #endif
4143                   if(strstr(&dynamicBuffer[0], "vgdb me ..."))
4144                      debugger.serialSemaphore.Release();
4145                   {
4146                      char * s = strstr(&dynamicBuffer[0], "==");
4147                      if(s)
4148                         s = strstr(s+2, "== ");
4149                      if(s)
4150                      {
4151                         s += 3;
4152                         if(s[0] == '\0' && !lastLineEmpty)
4153                         {
4154                            s = null;
4155                            lastLineEmpty = true;
4156                            dynamicBuffer[0] = '\0';
4157                         }
4158                      }
4159                      if(s)
4160                      {
4161                         char * t = s;
4162                         switch(s[0])
4163                         {
4164                            case '(':
4165                               if(strstr(s, "vgdb me ..."))
4166                               {
4167                                  if(strstr(s, "(action on error) vgdb me ..."))
4168                                     ide.outputView.debugBox.Logf($"...breaked on Valgrind error (F5 to resume)\n");
4169                                  s[0] = '\0';
4170                               }
4171                               else
4172                                  s = null;
4173                               break;
4174                            case 'T':
4175                               if(strstr(s, "TO DEBUG THIS PROCESS USING GDB: start GDB like this"))
4176                                  s[0] = '\0';
4177                               else
4178                                  s = null;
4179                               break;
4180                            case 'a':
4181                               if(strstr(s, "and then give GDB the following command"))
4182                                  s[0] = '\0';
4183                               else
4184                                  s = null;
4185                               break;
4186                            case ' ':
4187                               if(strstr(s, "/path/to/gdb") || strstr(s, "target remote | /usr/lib/valgrind/../../bin/vgdb --pid="))
4188                                  s[0] = '\0';
4189                               else
4190                                  s = null;
4191                               break;
4192                            case '-':
4193                               if(strstr(s, "--pid is optional if only one valgrind process is running"))
4194                                  s[0] = '\0';
4195                               else
4196                                  s = null;
4197                               break;
4198                            case 'U':
4199                               if((s = strstr(s, "; rerun with -h for copyright info")))
4200                               {
4201                                  s[0] = '\0';
4202                                  s = null;
4203                               }
4204                               break;
4205                            case '\0':
4206                               break;
4207                            default:
4208                               s = null;
4209                               break;
4210                         }
4211                         if(lastLineEmpty && t[0] != '\0')
4212                            lastLineEmpty = false;
4213                      }
4214                      if(!s)
4215                         ide.outputView.debugBox.Logf("%s\n", &dynamicBuffer[0]);
4216                   }
4217                   dynamicBuffer.size = 0;
4218                   start = c + 1;
4219                }
4220             }
4221             if(c == result)
4222             {
4223                int pos = dynamicBuffer.size;
4224                dynamicBuffer.size += c - start;
4225                memcpy(&dynamicBuffer[pos], output + start, c - start);
4226             }
4227          }
4228          else if(debugger.state == stopped)
4229          {
4230 /*#ifdef _DEBUG
4231             printf("Got end of file from GDB!\n");
4232 #endif*/
4233             app.Unlock();
4234             Sleep(0.2);
4235             app.Lock();
4236          }
4237       }
4238       delete dynamicBuffer;
4239       _dpl2(_dpct, dplchan::debuggerCall, 0, "ValgrindLogThreadExit");
4240       //if(oldValgrindHandle == vgLogFile)
4241          debugger.GdbThreadExit/*ValgrindLogThreadExit*/();
4242       delete oldValgrindHandle;
4243       app.Unlock();
4244       return 0;
4245    }
4246 }
4247
4248 class ValgrindTargetThread : Thread
4249 {
4250    Debugger debugger;
4251
4252    unsigned int Main()
4253    {
4254       static char output[4096];
4255       Array<char> dynamicBuffer { minAllocSize = 4096 };
4256       DualPipe oldValgrindHandle = vgTargetHandle;
4257       incref oldValgrindHandle;
4258
4259       app.Lock();
4260       while(debugger.state != terminated && vgTargetHandle && !vgTargetHandle.Eof())
4261       {
4262          int result;
4263          app.Unlock();
4264          result = vgTargetHandle.Read(output, 1, sizeof(output));
4265          app.Lock();
4266          if(debugger.state == terminated || !vgTargetHandle || vgTargetHandle.Eof())
4267             break;
4268          if(result)
4269          {
4270             int c;
4271             int start = 0;
4272
4273             for(c = 0; c<result; c++)
4274             {
4275                if(output[c] == '\n')
4276                {
4277                   int pos = dynamicBuffer.size;
4278                   dynamicBuffer.size += c - start;
4279                   memcpy(&dynamicBuffer[pos], output + start, c - start);
4280                   if(dynamicBuffer.count && dynamicBuffer[dynamicBuffer.count - 1] != '\r')
4281                   // COMMENTED OUT DUE TO ISSUE #135, FIXED
4282                   //if(dynamicBuffer.array[dynamicBuffer.count - 1] != '\r')
4283                      dynamicBuffer.size++;
4284                   dynamicBuffer[dynamicBuffer.count - 1] = '\0';
4285 #ifdef _DEBUG
4286                   // printf("%s\n", dynamicBuffer.array);
4287 #endif
4288                   ide.outputView.debugBox.Logf("%s\n", &dynamicBuffer[0]);
4289
4290                   dynamicBuffer.size = 0;
4291                   start = c + 1;
4292                }
4293             }
4294             if(c == result)
4295             {
4296                int pos = dynamicBuffer.size;
4297                dynamicBuffer.size += c - start;
4298                memcpy(&dynamicBuffer[pos], output + start, c - start);
4299             }
4300          }
4301          else
4302          {
4303 #ifdef _DEBUG
4304             printf("Got end of file from GDB!\n");
4305 #endif
4306          }
4307       }
4308       delete dynamicBuffer;
4309       //if(oldValgrindHandle == vgTargetHandle)
4310          debugger.ValgrindTargetThreadExit();
4311       delete oldValgrindHandle;
4312       app.Unlock();
4313       return 0;
4314    }
4315 }
4316
4317 class GdbThread : Thread
4318 {
4319    Debugger debugger;
4320
4321    unsigned int Main()
4322    {
4323       static char output[4096];
4324       Array<char> dynamicBuffer { minAllocSize = 4096 };
4325       DualPipe oldGdbHandle = gdbHandle;
4326       incref oldGdbHandle;
4327
4328       app.Lock();
4329       while(debugger.state != terminated && gdbHandle && !gdbHandle.Eof())
4330       {
4331          int result;
4332          app.Unlock();
4333          result = gdbHandle.Read(output, 1, sizeof(output));
4334          app.Lock();
4335          if(debugger.state == terminated || !gdbHandle || gdbHandle.Eof())
4336             break;
4337          if(result)
4338          {
4339             int c;
4340             int start = 0;
4341
4342             for(c = 0; c<result; c++)
4343             {
4344                if(output[c] == '\n')
4345                {
4346                   int pos = dynamicBuffer.size;
4347                   dynamicBuffer.size += c - start;
4348                   memcpy(&dynamicBuffer[pos], output + start, c - start);
4349                   if(dynamicBuffer.count && dynamicBuffer[dynamicBuffer.count - 1] != '\r')
4350                   // COMMENTED OUT DUE TO ISSUE #135, FIXED
4351                   //if(dynamicBuffer.array[dynamicBuffer.count - 1] != '\r')
4352                      dynamicBuffer.size++;
4353                   dynamicBuffer[dynamicBuffer.count - 1] = '\0';
4354 #ifdef _DEBUG
4355                   // _dpl(0, dynamicBuffer.array);
4356 #endif
4357                   debugger.GdbThreadMain(&dynamicBuffer[0]);
4358                   dynamicBuffer.size = 0;
4359                   start = c + 1;
4360                }
4361             }
4362             if(c == result)
4363             {
4364                int pos = dynamicBuffer.size;
4365                dynamicBuffer.size += c - start;
4366                memcpy(&dynamicBuffer[pos], output + start, c - start);
4367             }
4368          }
4369          else
4370          {
4371 #ifdef _DEBUG
4372             _dpl(0, "Got end of file from GDB!");
4373 #endif
4374          }
4375       }
4376       delete dynamicBuffer;
4377       //if(oldGdbHandle == gdbHandle)
4378          debugger.GdbThreadExit();
4379       delete oldGdbHandle;
4380       app.Unlock();
4381       return 0;
4382    }
4383 }
4384
4385 static define createFIFOMsg = $"err: Unable to create FIFO %s\n";
4386 static define openFIFOMsg = $"err: Unable to open FIFO %s for read\n";
4387
4388 #if defined(__unix__)
4389 #define uint _uint
4390 #include <errno.h>
4391 #include <stdio.h>
4392 #include <fcntl.h>
4393 #include <sys/types.h>
4394 #undef uint
4395
4396 File fifoFile;
4397
4398 class ProgramThread : Thread
4399 {
4400    bool terminate;
4401    unsigned int Main()
4402    {
4403       bool result = true;
4404       bool fileCreated = false;
4405       mode_t mask = 0600;
4406       static char output[1000];
4407       int fd;
4408
4409       /*if(!mkfifo(progFifoPath, mask))
4410       {
4411          fileCreated = true;
4412       }
4413       else
4414       {
4415          app.Lock();
4416          ide.outputView.debugBox.Logf($"err: Unable to create FIFO %s\n", progFifoPath);
4417          app.Unlock();
4418       }*/
4419
4420       if(FileExists(progFifoPath)) //fileCreated)
4421       {
4422          fifoFile = FileOpen(progFifoPath, read);
4423          if(!fifoFile)
4424          {
4425             app.Lock();
4426             ide.outputView.debugBox.Logf(openFIFOMsg, progFifoPath);
4427             app.Unlock();
4428          }
4429          else
4430          {
4431             fd = fileno((FILE *)fifoFile.input);
4432             //fcntl(fd, F_SETFL, fcntl(fd, F_GETFL) | O_NONBLOCK);
4433          }
4434       }
4435
4436       while(!terminate && fifoFile && !fifoFile.Eof())
4437       {
4438          fd_set rs, es;
4439          struct timeval time;
4440          int selectResult;
4441          time.tv_sec = 1;
4442          time.tv_usec = 0;
4443          FD_ZERO(&rs);
4444          FD_ZERO(&es);
4445          FD_SET(fd, &rs);
4446          FD_SET(fd, &es);
4447          selectResult = select(fd + 1, &rs, null, null, &time);
4448          if(FD_ISSET(fd, &rs))
4449          {
4450             int result = (int)read(fd, output, sizeof(output)-1);
4451             if(!result || (result < 0 && errno != EAGAIN))
4452                break;
4453             if(result > 0)
4454             {
4455                output[result] = '\0';
4456                if(strcmp(output,"&\"warning: GDB: Failed to set controlling terminal: Invalid argument\\n\"\n"))
4457                {
4458                   app.Lock();
4459                   ide.outputView.debugBox.Log(output);
4460                   app.Unlock();
4461                }
4462             }
4463          }
4464       }
4465
4466       //if(fifoFile)
4467       {
4468          //fifoFile.CloseInput();
4469          //delete fifoFile;
4470          app.Lock();
4471          ide.outputView.debugBox.Log("\n");
4472          app.Unlock();
4473       }
4474       /*
4475       if(FileExists(progFifoPath)) //fileCreated)
4476       {
4477          DeleteFile(progFifoPath);
4478          progFifoPath[0] = '\0';
4479       }
4480       */
4481       return 0;
4482    }
4483 }
4484 #endif
4485
4486 class Argument : struct
4487 {
4488    Argument prev, next;
4489    char * name;
4490    property char * name { set { delete name; if(value) name = CopyString(value); } }
4491    char * val;
4492    property char * val { set { delete val; if(value) val = CopyString(value); } }
4493
4494    void Free()
4495    {
4496       delete name;
4497       delete val;
4498    }
4499
4500    ~Argument()
4501    {
4502       Free();
4503    }
4504 }
4505
4506 class Frame : struct
4507 {
4508    Frame prev, next;
4509    int level;
4510    char * addr;
4511    property char * addr { set { delete addr; if(value) addr = CopyString(value); } }
4512    char * func;
4513    property char * func { set { delete func; if(value) func = CopyString(value); } }
4514    int argsCount;
4515    OldList args;
4516    char * from;
4517    property char * from { set { delete from; if(value) from = CopyUnescapedUnixPath(value); } }
4518    char * file;
4519    property char * file { set { delete file; if(value) file = CopyUnescapedUnixPath(value); } }
4520    char * absoluteFile;
4521    property char * absoluteFile { set { delete absoluteFile; if(value) absoluteFile = CopyUnescapedUnixPath(value); } }
4522    int line;
4523
4524    void Free()
4525    {
4526       delete addr;
4527       delete func;
4528       delete from;
4529       delete file;
4530       delete absoluteFile;
4531       args.Free(Argument::Free);
4532    }
4533
4534    ~Frame()
4535    {
4536       Free();
4537    }
4538 }
4539
4540 class GdbDataStop : struct
4541 {
4542    DebuggerReason reason;
4543    int threadid;
4544    union
4545    {
4546       struct
4547       {
4548          int bkptno;
4549       };
4550       struct
4551       {
4552          char * name;
4553          char * meaning;
4554       };
4555       struct
4556       {
4557          char * gdbResultVar;
4558          char * returnValue;
4559       };
4560    };
4561    Frame frame { };
4562
4563    void Free()
4564    {
4565       if(reason)
4566       {
4567          if(reason == signalReceived)
4568          {
4569             delete name;
4570             delete meaning;
4571          }
4572          else if(reason == functionFinished)
4573          {
4574             delete gdbResultVar;
4575             delete returnValue;
4576          }
4577       }
4578       if(frame) frame.Free();
4579    }
4580
4581    ~GdbDataStop()
4582    {
4583       Free();
4584    }
4585 }
4586
4587 class GdbDataBreakpoint : struct
4588 {
4589    int id;
4590    char * number;
4591    property char * number { set { delete number; if(value) number = CopyString(value); } }
4592    char * type;
4593    property char * type { set { delete type; if(value) type = CopyString(value); } }
4594    char * disp;
4595    property char * disp { set { delete disp; if(value) disp = CopyString(value); } }
4596    bool enabled;
4597    char * addr;
4598    property char * addr { set { delete addr; if(value) addr = CopyString(value); } }
4599    char * func;
4600    property char * func { set { delete func; if(value) func = CopyString(value); } }
4601    char * file;
4602    property char * file { set { delete file; if(value) file = CopyUnescapedUnixPath(value); } }
4603    char * fullname;
4604    property char * fullname { set { delete fullname; if(value) fullname = CopyUnescapedUnixPath(value); } }
4605    int line;
4606    char * at;
4607    property char * at { set { delete at; if(value) at = CopyString(value); } }
4608    int times;
4609
4610    Array<GdbDataBreakpoint> multipleBPs;
4611
4612    void Print()
4613    {
4614    _dpl(0, "");
4615       PrintLn("{", "#", number, " T", type, " D", disp, " E", enabled, " H", times, " (", func, ") (", file, ":", line, ") (", fullname, ") (", addr, ") (", at, ")", "}");
4616    }
4617
4618    void Free()
4619    {
4620       delete type;
4621       delete disp;
4622       delete addr;
4623       delete func;
4624       delete file;
4625       delete at;
4626       if(multipleBPs) multipleBPs.Free();
4627       delete multipleBPs;
4628       delete number;
4629       delete fullname;
4630    }
4631
4632    ~GdbDataBreakpoint()
4633    {
4634       Free();
4635    }
4636 }
4637
4638 class Breakpoint : struct
4639 {
4640    class_no_expansion;
4641
4642    char * function;
4643    property char * function { set { delete function; if(value) function = CopyString(value); } }
4644    char * relativeFilePath;
4645    property char * relativeFilePath { set { delete relativeFilePath; if(value) relativeFilePath = CopyString(value); } }
4646    char * absoluteFilePath;
4647    property char * absoluteFilePath { set { delete absoluteFilePath; if(value) absoluteFilePath = CopyString(value); } }
4648    char * location;
4649    property char * location { set { delete location; if(value) location = CopyString(value); } }
4650    int line;
4651    bool enabled;
4652    int hits;
4653    int breaks;
4654    int ignore;
4655    int level;
4656    Watch condition;
4657    bool inserted;
4658    BreakpointType type;
4659    DataRow row;
4660    GdbDataBreakpoint bp;
4661    Project project;
4662    char * address;
4663    property char * address { set { delete address; if(value) address = CopyString(value); } }
4664
4665    void ParseLocation()
4666    {
4667       char * prjName = null;
4668       char * filePath = null;
4669       char * file;
4670       char * line;
4671       char fullPath[MAX_LOCATION];
4672       if(location[0] == '(' && location[1] && (file = strchr(location+2, ')')) && file[1])
4673       {
4674          prjName = new char[file-location];
4675          strncpy(prjName, location+1, file-location-1);
4676          prjName[file-location-1] = '\0';
4677          file++;
4678       }
4679       else
4680          file = location;
4681       if((line = strchr(file+1, ':')))
4682       {
4683          filePath = new char[strlen(file)+1];
4684          strncpy(filePath, file, line-file);
4685          filePath[line-file] = '\0';
4686          line++;
4687       }
4688       else
4689          filePath = CopyString(file);
4690       property::relativeFilePath = filePath;
4691       if(prjName)
4692       {
4693          for(prj : ide.workspace.projects)
4694          {
4695             if(!strcmp(prjName, prj.name))
4696             {
4697                if(ProjectGetAbsoluteFromRelativePath(prj, filePath, fullPath))
4698                {
4699                   property::absoluteFilePath = fullPath;
4700                   project = prj;
4701                   break;
4702                }
4703             }
4704          }
4705          if(line[0])
4706             this.line = atoi(line);
4707       }
4708       else
4709       {
4710          Project prj = ide.project;
4711          if(ProjectGetAbsoluteFromRelativePath(prj, filePath, fullPath))
4712          {
4713             property::absoluteFilePath = fullPath;
4714             project = prj;
4715          }
4716       }
4717       if(!absoluteFilePath)
4718          property::absoluteFilePath = "";
4719       delete prjName;
4720       delete filePath;
4721    }
4722
4723    char * CopyLocationString(bool removePath)
4724    {
4725       char * location;
4726       char * file = relativeFilePath ? relativeFilePath : absoluteFilePath;
4727       bool removingPath = removePath && file;
4728       if(removingPath)
4729       {
4730          char * fileName = new char[MAX_FILENAME];
4731          GetLastDirectory(file, fileName);
4732          file = fileName;
4733       }
4734       if(function)
4735       {
4736          if(file)
4737             location = PrintString(file, ":", function);
4738          else
4739             location = CopyString(function);
4740       }
4741       else
4742          location = PrintString(file, ":", line);
4743       if(removingPath)
4744          delete file;
4745       return location;
4746    }
4747
4748    char * CopyUserLocationString()
4749    {
4750       char * location;
4751       char * loc = CopyLocationString(false);
4752       Project prj = null;
4753       if(absoluteFilePath)
4754       {
4755          for(p : ide.workspace.projects; p != ide.workspace.projects.firstIterator.data)
4756          {
4757             if(p.topNode.FindByFullPath(absoluteFilePath, false))
4758             {
4759                prj = p;
4760                break;
4761             }
4762          }
4763       }
4764       if(prj)
4765       {
4766          location = PrintString("(", prj.name, ")", loc);
4767          delete loc;
4768       }
4769       else
4770          location = loc;
4771       return location;
4772    }
4773
4774    void Save(File f)
4775    {
4776       if(relativeFilePath && relativeFilePath[0])
4777       {
4778          char * location = CopyUserLocationString();
4779          f.Printf("    * %d,%d,%d,%d,%s\n", enabled ? 1 : 0, ignore, level, line, location);
4780          delete location;
4781          if(condition)
4782             f.Printf("       ~ %s\n", condition.expression);
4783       }
4784    }
4785
4786    void Free()
4787    {
4788       Reset();
4789       delete function;
4790       delete relativeFilePath;
4791       delete absoluteFilePath;
4792       delete location;
4793    }
4794
4795    void Reset()
4796    {
4797       inserted = false;
4798       delete address;
4799       if(bp)
4800          bp.Free();
4801       delete bp;
4802    }
4803
4804    ~Breakpoint()
4805    {
4806       Free();
4807    }
4808
4809 }
4810
4811 class Watch : struct
4812 {
4813    class_no_expansion;
4814
4815    Type type;
4816    char * expression;
4817    char * value;
4818    DataRow row;
4819
4820    void Save(File f)
4821    {
4822       f.Printf("    ~ %s\n", expression);
4823    }
4824
4825    void Free()
4826    {
4827       delete expression;
4828       delete value;
4829       FreeType(type);
4830       type = null;
4831    }
4832
4833    void Reset()
4834    {
4835       delete value;
4836       FreeType(type);
4837       type = null;
4838    }
4839
4840    ~Watch()
4841    {
4842       Free();
4843    }
4844 }
4845
4846 class DebugListItem : struct
4847 {
4848    char * name;
4849    char * value;
4850 }
4851
4852 struct DebugEvaluationData
4853 {
4854    bool active;
4855    char * result;
4856    int bytes;
4857    uint64 nextBlockAddress;
4858
4859    DebuggerEvaluationError error;
4860 };
4861
4862 class CodeLocation : struct
4863 {
4864    char * file;
4865    char * absoluteFile;
4866    int line;
4867
4868    CodeLocation ::ParseCodeLocation(char * location)
4869    {
4870       if(location)
4871       {
4872          char * colon = null;
4873          char * temp;
4874          char loc[MAX_LOCATION];
4875          strcpy(loc, location);
4876          for(temp = loc; temp = strstr(temp, ":"); temp++)
4877             colon = temp;
4878          if(colon)
4879          {
4880             colon[0] = '\0';
4881             colon++;
4882             if(colon)
4883             {
4884                int line = atoi(colon);
4885                if(line)
4886                {
4887                   CodeLocation codloc { line = line };
4888                   codloc.file = CopyString(loc);
4889                   codloc.absoluteFile = ide.workspace.GetAbsolutePathFromRelative(loc);
4890                   return codloc;
4891                }
4892             }
4893          }
4894       }
4895       return null;
4896    }
4897
4898    void Free()
4899    {
4900       delete file;
4901       delete absoluteFile;
4902    }
4903
4904    ~CodeLocation()
4905    {
4906       Free();
4907    }
4908 }
4909
4910 void GDBFallBack(Expression exp, String expString)
4911 {
4912    char * result;
4913    ExpressionType evalError = dummyExp;
4914    result = Debugger::EvaluateExpression(expString, &evalError);
4915    if(result)
4916    {
4917       exp.constant = result;
4918       exp.type = constantExp;
4919    }
4920 }
4921
4922 static Project WorkspaceGetFileOwner(char * absolutePath)
4923 {
4924    Project owner = null;
4925    for(prj : ide.workspace.projects)
4926    {
4927       if(prj.topNode.FindByFullPath(absolutePath, false))
4928       {
4929          owner = prj;
4930          break;
4931       }
4932    }
4933    if(!owner)
4934       WorkspaceGetObjectFileNode(absolutePath, &owner);
4935    return owner;
4936 }
4937
4938 static ProjectNode WorkspaceGetObjectFileNode(char * filePath, Project * project)
4939 {
4940    ProjectNode node = null;
4941    char ext[MAX_EXTENSION];
4942    GetExtension(filePath, ext);
4943    if(ext[0])
4944    {
4945       IntermediateFileType type = IntermediateFileType::FromExtension(ext);
4946       if(type)
4947       {
4948          char fileName[MAX_FILENAME];
4949          GetLastDirectory(filePath, fileName);
4950          if(fileName[0])
4951          {
4952             DotMain dotMain = DotMain::FromFileName(fileName);
4953             for(prj : ide.workspace.projects)
4954             {
4955                if((node = prj.FindNodeByObjectFileName(fileName, type, dotMain, null)))
4956                {
4957                   if(project)
4958                      *project = prj;
4959                   break;
4960                }
4961             }
4962          }
4963       }
4964    }
4965    return node;
4966 }
4967
4968 static ProjectNode ProjectGetObjectFileNode(Project project, char * filePath)
4969 {
4970    ProjectNode node = null;
4971    char ext[MAX_EXTENSION];
4972    GetExtension(filePath, ext);
4973    if(ext[0])
4974    {
4975       IntermediateFileType type = IntermediateFileType::FromExtension(ext);
4976       if(type)
4977       {
4978          char fileName[MAX_FILENAME];
4979          GetLastDirectory(filePath, fileName);
4980          if(fileName[0])
4981          {
4982             DotMain dotMain = DotMain::FromFileName(fileName);
4983             node = project.FindNodeByObjectFileName(fileName, type, dotMain, null);
4984          }
4985       }
4986    }
4987    return node;
4988 }
4989
4990 static void WorkspaceGetRelativePath(char * absolutePath, char * relativePath, Project * owner)
4991 {
4992    Project prj = WorkspaceGetFileOwner(absolutePath);
4993    if(owner)
4994       *owner = prj;
4995    if(!prj)
4996       prj = ide.workspace.projects.firstIterator.data;
4997    if(prj)
4998    {
4999       MakePathRelative(absolutePath, prj.topNode.path, relativePath);
5000       MakeSlashPath(relativePath);
5001    }
5002    else
5003       relativePath[0] = '\0';
5004 }
5005
5006 static bool ProjectGetAbsoluteFromRelativePath(Project project, char * relativePath, char * absolutePath)
5007 {
5008    ProjectNode node = project.topNode.FindWithPath(relativePath, false);
5009    if(!node)
5010       node = ProjectGetObjectFileNode(project, relativePath);
5011    if(node)
5012    {
5013       strcpy(absolutePath, node.project.topNode.path);
5014       PathCat(absolutePath, relativePath);
5015       MakeSlashPath(absolutePath);
5016    }
5017    return node != null;
5018 }