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