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