Fixed stack display for functions in an anonymous namespace.
[kdbg.git] / kdbg / gdbdriver.cpp
blob92cdf5b200e2ca574f8854442bbfbcb0cd5753df
1 // $Id$
3 // Copyright by Johannes Sixt
4 // This file is under GPL, the GNU General Public Licence
6 #include "gdbdriver.h"
7 #include "exprwnd.h"
8 #include <qregexp.h>
9 #include <qstringlist.h>
10 #include <klocale.h> /* i18n */
11 #include <ctype.h>
12 #include <stdlib.h> /* strtol, atoi */
13 #include <string.h> /* strcpy */
15 #include "assert.h"
16 #ifdef HAVE_CONFIG_H
17 #include "config.h"
18 #endif
19 #include "mydebug.h"
21 static void skipString(const char*& p);
22 static void skipNested(const char*& s, char opening, char closing);
23 static VarTree* parseVar(const char*& s);
24 static bool parseName(const char*& s, QString& name, VarTree::NameKind& kind);
25 static bool parseValue(const char*& s, VarTree* variable);
26 static bool parseNested(const char*& s, VarTree* variable);
27 static bool parseVarSeq(const char*& s, VarTree* variable);
28 static bool parseValueSeq(const char*& s, VarTree* variable);
30 #define PROMPT "(kdbg)"
31 #define PROMPT_LEN 6
32 #define PROMPT_LAST_CHAR ')' /* needed when searching for prompt string */
35 // TODO: make this cmd info stuff non-static to allow multiple
36 // simultaneous gdbs to run!
38 struct GdbCmdInfo {
39 DbgCommand cmd;
40 const char* fmt; /* format string */
41 enum Args {
42 argNone, argString, argNum,
43 argStringNum, argNumString,
44 argString2, argNum2
45 } argsNeeded;
48 #if 0
49 // This is how the QString data print statement generally looks like.
50 // It is set by KDebugger via setPrintQStringDataCmd().
52 static const char printQStringStructFmt[] =
53 // if the string data is junk, fail early
54 "print ($qstrunicode=($qstrdata=(%s))->unicode)?"
55 // print an array of shorts
56 "(*(unsigned short*)$qstrunicode)@"
57 // limit the length
58 "(($qstrlen=(unsigned int)($qstrdata->len))>100?100:$qstrlen)"
59 // if unicode data is 0, report a special value
60 ":1==0\n";
61 #endif
62 static const char printQStringStructFmt[] = "print (0?\"%s\":$kdbgundef)\n";
65 * The following array of commands must be sorted by the DC* values,
66 * because they are used as indices.
68 static GdbCmdInfo cmds[] = {
69 { DCinitialize, "", GdbCmdInfo::argNone },
70 { DCtty, "tty %s\n", GdbCmdInfo::argString },
71 { DCexecutable, "file \"%s\"\n", GdbCmdInfo::argString },
72 { DCtargetremote, "target remote %s\n", GdbCmdInfo::argString },
73 { DCcorefile, "core-file %s\n", GdbCmdInfo::argString },
74 { DCattach, "attach %s\n", GdbCmdInfo::argString },
75 { DCinfolinemain, "kdbg_infolinemain\n", GdbCmdInfo::argNone },
76 { DCinfolocals, "kdbg__alllocals\n", GdbCmdInfo::argNone },
77 { DCinforegisters, "info all-registers\n", GdbCmdInfo::argNone},
78 { DCexamine, "x %s %s\n", GdbCmdInfo::argString2 },
79 { DCinfoline, "info line %s:%d\n", GdbCmdInfo::argStringNum },
80 { DCdisassemble, "disassemble %s %s\n", GdbCmdInfo::argString2 },
81 { DCsetargs, "set args %s\n", GdbCmdInfo::argString },
82 { DCsetenv, "set env %s %s\n", GdbCmdInfo::argString2 },
83 { DCunsetenv, "unset env %s\n", GdbCmdInfo::argString },
84 { DCsetoption, "setoption %s %d\n", GdbCmdInfo::argStringNum},
85 { DCcd, "cd %s\n", GdbCmdInfo::argString },
86 { DCbt, "bt\n", GdbCmdInfo::argNone },
87 { DCrun, "run\n", GdbCmdInfo::argNone },
88 { DCcont, "cont\n", GdbCmdInfo::argNone },
89 { DCstep, "step\n", GdbCmdInfo::argNone },
90 { DCstepi, "stepi\n", GdbCmdInfo::argNone },
91 { DCnext, "next\n", GdbCmdInfo::argNone },
92 { DCnexti, "nexti\n", GdbCmdInfo::argNone },
93 { DCfinish, "finish\n", GdbCmdInfo::argNone },
94 { DCuntil, "until %s:%d\n", GdbCmdInfo::argStringNum },
95 { DCkill, "kill\n", GdbCmdInfo::argNone },
96 { DCbreaktext, "break %s\n", GdbCmdInfo::argString },
97 { DCbreakline, "break %s:%d\n", GdbCmdInfo::argStringNum },
98 { DCtbreakline, "tbreak %s:%d\n", GdbCmdInfo::argStringNum },
99 { DCbreakaddr, "break *%s\n", GdbCmdInfo::argString },
100 { DCtbreakaddr, "tbreak *%s\n", GdbCmdInfo::argString },
101 { DCwatchpoint, "watch %s\n", GdbCmdInfo::argString },
102 { DCdelete, "delete %d\n", GdbCmdInfo::argNum },
103 { DCenable, "enable %d\n", GdbCmdInfo::argNum },
104 { DCdisable, "disable %d\n", GdbCmdInfo::argNum },
105 { DCprint, "print %s\n", GdbCmdInfo::argString },
106 { DCprintDeref, "print *(%s)\n", GdbCmdInfo::argString },
107 { DCprintStruct, "print %s\n", GdbCmdInfo::argString },
108 { DCprintQStringStruct, printQStringStructFmt, GdbCmdInfo::argString},
109 { DCframe, "frame %d\n", GdbCmdInfo::argNum },
110 { DCfindType, "whatis %s\n", GdbCmdInfo::argString },
111 { DCinfosharedlib, "info sharedlibrary\n", GdbCmdInfo::argNone },
112 { DCthread, "thread %d\n", GdbCmdInfo::argNum },
113 { DCinfothreads, "info threads\n", GdbCmdInfo::argNone },
114 { DCinfobreak, "info breakpoints\n", GdbCmdInfo::argNone },
115 { DCcondition, "condition %d %s\n", GdbCmdInfo::argNumString},
116 { DCsetpc, "set variable $pc=%s\n", GdbCmdInfo::argString },
117 { DCignore, "ignore %d %d\n", GdbCmdInfo::argNum2},
118 { DCsetvariable, "set variable %s=%s\n", GdbCmdInfo::argString2 },
121 #define NUM_CMDS (int(sizeof(cmds)/sizeof(cmds[0])))
122 #define MAX_FMTLEN 200
124 GdbDriver::GdbDriver() :
125 DebuggerDriver(),
126 m_gdbMajor(4), m_gdbMinor(16)
128 strcpy(m_prompt, PROMPT);
129 m_promptMinLen = PROMPT_LEN;
130 m_promptLastChar = PROMPT_LAST_CHAR;
132 #ifndef NDEBUG
133 // check command info array
134 char* perc;
135 for (int i = 0; i < NUM_CMDS; i++) {
136 // must be indexable by DbgCommand values, i.e. sorted by DbgCommand values
137 assert(i == cmds[i].cmd);
138 // a format string must be associated
139 assert(cmds[i].fmt != 0);
140 assert(strlen(cmds[i].fmt) <= MAX_FMTLEN);
141 // format string must match arg specification
142 switch (cmds[i].argsNeeded) {
143 case GdbCmdInfo::argNone:
144 assert(strchr(cmds[i].fmt, '%') == 0);
145 break;
146 case GdbCmdInfo::argString:
147 perc = strchr(cmds[i].fmt, '%');
148 assert(perc != 0 && perc[1] == 's');
149 assert(strchr(perc+2, '%') == 0);
150 break;
151 case GdbCmdInfo::argNum:
152 perc = strchr(cmds[i].fmt, '%');
153 assert(perc != 0 && perc[1] == 'd');
154 assert(strchr(perc+2, '%') == 0);
155 break;
156 case GdbCmdInfo::argStringNum:
157 perc = strchr(cmds[i].fmt, '%');
158 assert(perc != 0 && perc[1] == 's');
159 perc = strchr(perc+2, '%');
160 assert(perc != 0 && perc[1] == 'd');
161 assert(strchr(perc+2, '%') == 0);
162 break;
163 case GdbCmdInfo::argNumString:
164 perc = strchr(cmds[i].fmt, '%');
165 assert(perc != 0 && perc[1] == 'd');
166 perc = strchr(perc+2, '%');
167 assert(perc != 0 && perc[1] == 's');
168 assert(strchr(perc+2, '%') == 0);
169 break;
170 case GdbCmdInfo::argString2:
171 perc = strchr(cmds[i].fmt, '%');
172 assert(perc != 0 && perc[1] == 's');
173 perc = strchr(perc+2, '%');
174 assert(perc != 0 && perc[1] == 's');
175 assert(strchr(perc+2, '%') == 0);
176 break;
177 case GdbCmdInfo::argNum2:
178 perc = strchr(cmds[i].fmt, '%');
179 assert(perc != 0 && perc[1] == 'd');
180 perc = strchr(perc+2, '%');
181 assert(perc != 0 && perc[1] == 'd');
182 assert(strchr(perc+2, '%') == 0);
183 break;
186 assert(strlen(printQStringStructFmt) <= MAX_FMTLEN);
187 #endif
190 GdbDriver::~GdbDriver()
195 QString GdbDriver::driverName() const
197 return "GDB";
200 QString GdbDriver::defaultGdb()
202 return
203 "gdb"
204 " --fullname" /* to get standard file names each time the prog stops */
205 " --nx"; /* do not execute initialization files */
208 QString GdbDriver::defaultInvocation() const
210 if (m_defaultCmd.isEmpty()) {
211 return defaultGdb();
212 } else {
213 return m_defaultCmd;
217 QStringList GdbDriver::boolOptionList() const
219 // no options
220 return QStringList();
223 bool GdbDriver::startup(QString cmdStr)
225 if (!DebuggerDriver::startup(cmdStr))
226 return false;
228 static const char gdbInitialize[] =
230 * Work around buggy gdbs that do command line editing even if they
231 * are not on a tty. The readline library echos every command back
232 * in this case, which is confusing for us.
234 "set editing off\n"
235 "set confirm off\n"
236 "set print static-members off\n"
237 "set print asm-demangle on\n"
239 * Write a short macro that prints all locals: local variables and
240 * function arguments.
242 "define kdbg__alllocals\n"
243 "info locals\n" /* local vars supersede args with same name */
244 "info args\n" /* therefore, arguments must come last */
245 "end\n"
247 * Work around a bug in gdb-6.3: "info line main" crashes gdb.
249 "define kdbg_infolinemain\n"
250 "list\n"
251 "info line\n"
252 "end\n"
253 // change prompt string and synchronize with gdb
254 "set prompt " PROMPT "\n"
257 executeCmdString(DCinitialize, gdbInitialize, false);
259 // assume that QString::null is ok
260 cmds[DCprintQStringStruct].fmt = printQStringStructFmt;
262 return true;
265 void GdbDriver::commandFinished(CmdQueueItem* cmd)
267 // command string must be committed
268 if (!cmd->m_committed) {
269 // not commited!
270 TRACE("calling " + (__PRETTY_FUNCTION__ + (" with uncommited command:\n\t" +
271 cmd->m_cmdString)));
272 return;
275 switch (cmd->m_cmd) {
276 case DCinitialize:
277 // get version number from preamble
279 int len;
280 QRegExp GDBVersion("\\nGDB [0-9]+\\.[0-9]+");
281 int offset = GDBVersion.match(m_output, 0, &len);
282 if (offset >= 0) {
283 char* start = m_output + offset + 5; // skip "\nGDB "
284 char* end;
285 m_gdbMajor = strtol(start, &end, 10);
286 m_gdbMinor = strtol(end + 1, 0, 10); // skip "."
287 if (start == end) {
288 // nothing was parsed
289 m_gdbMajor = 4;
290 m_gdbMinor = 16;
292 } else {
293 // assume some default version (what would make sense?)
294 m_gdbMajor = 4;
295 m_gdbMinor = 16;
297 // use a feasible core-file command
298 if (m_gdbMajor > 4 || (m_gdbMajor == 4 && m_gdbMinor >= 16)) {
299 cmds[DCcorefile].fmt = "target core %s\n";
300 } else {
301 cmds[DCcorefile].fmt = "core-file %s\n";
304 break;
305 default:;
308 /* ok, the command is ready */
309 emit commandReceived(cmd, m_output);
311 switch (cmd->m_cmd) {
312 case DCcorefile:
313 case DCinfolinemain:
314 case DCframe:
315 case DCattach:
316 case DCrun:
317 case DCcont:
318 case DCstep:
319 case DCstepi:
320 case DCnext:
321 case DCnexti:
322 case DCfinish:
323 case DCuntil:
324 parseMarker();
325 default:;
330 * The --fullname option makes gdb send a special normalized sequence print
331 * each time the program stops and at some other points. The sequence has
332 * the form "\032\032filename:lineno:charoffset:(beg|middle):address".
334 void GdbDriver::parseMarker()
336 char* startMarker = strstr(m_output, "\032\032");
337 if (startMarker == 0)
338 return;
340 // extract the marker
341 startMarker += 2;
342 TRACE(QString("found marker: ") + startMarker);
343 char* endMarker = strchr(startMarker, '\n');
344 if (endMarker == 0)
345 return;
347 *endMarker = '\0';
349 // extract filename and line number
350 static QRegExp MarkerRE(":[0-9]+:[0-9]+:[begmidl]+:0x");
352 int len;
353 int lineNoStart = MarkerRE.match(startMarker, 0, &len);
354 if (lineNoStart >= 0) {
355 int lineNo = atoi(startMarker + lineNoStart+1);
357 // get address
358 const char* addrStart = startMarker + lineNoStart + len - 2;
359 DbgAddr address = QString(addrStart).stripWhiteSpace();
361 // now show the window
362 startMarker[lineNoStart] = '\0'; /* split off file name */
363 emit activateFileLine(startMarker, lineNo-1, address);
369 * Escapes characters that might lead to problems when they appear on gdb's
370 * command line.
372 static void normalizeStringArg(QString& arg)
375 * Remove trailing backslashes. This approach is a little simplistic,
376 * but we know that there is at the moment no case where a trailing
377 * backslash would make sense.
379 while (!arg.isEmpty() && arg[arg.length()-1] == '\\') {
380 arg = arg.left(arg.length()-1);
385 QString GdbDriver::makeCmdString(DbgCommand cmd, QString strArg)
387 assert(cmd >= 0 && cmd < NUM_CMDS);
388 assert(cmds[cmd].argsNeeded == GdbCmdInfo::argString);
390 normalizeStringArg(strArg);
392 if (cmd == DCcd) {
393 // need the working directory when parsing the output
394 m_programWD = strArg;
395 } else if (cmd == DCsetargs) {
396 // attach saved redirection
397 strArg += m_redirect;
400 SIZED_QString(cmdString, MAX_FMTLEN+strArg.length());
401 cmdString.sprintf(cmds[cmd].fmt, strArg.latin1());
402 return cmdString;
405 QString GdbDriver::makeCmdString(DbgCommand cmd, int intArg)
407 assert(cmd >= 0 && cmd < NUM_CMDS);
408 assert(cmds[cmd].argsNeeded == GdbCmdInfo::argNum);
410 SIZED_QString(cmdString, MAX_FMTLEN+30);
412 cmdString.sprintf(cmds[cmd].fmt, intArg);
413 return cmdString;
416 QString GdbDriver::makeCmdString(DbgCommand cmd, QString strArg, int intArg)
418 assert(cmd >= 0 && cmd < NUM_CMDS);
419 assert(cmds[cmd].argsNeeded == GdbCmdInfo::argStringNum ||
420 cmds[cmd].argsNeeded == GdbCmdInfo::argNumString ||
421 cmd == DCexamine ||
422 cmd == DCtty);
424 normalizeStringArg(strArg);
426 SIZED_QString(cmdString, MAX_FMTLEN+30+strArg.length());
428 if (cmd == DCtty)
431 * intArg specifies which channels should be redirected to
432 * /dev/null. It is a value or'ed together from RDNstdin,
433 * RDNstdout, RDNstderr. We store the value for a later DCsetargs
434 * command.
436 * Note: We rely on that after the DCtty a DCsetargs will follow,
437 * which will ultimately apply the redirection.
439 static const char* const runRedir[8] = {
441 " </dev/null",
442 " >/dev/null",
443 " </dev/null >/dev/null",
444 " 2>/dev/null",
445 " </dev/null 2>/dev/null",
446 " >/dev/null 2>&1",
447 " </dev/null >/dev/null 2>&1"
449 if (strArg.isEmpty())
450 intArg = 7; /* failsafe if no tty */
451 m_redirect = runRedir[intArg & 7];
453 return makeCmdString(DCtty, strArg); /* note: no problem if strArg empty */
456 if (cmd == DCexamine) {
457 // make a format specifier from the intArg
458 static const char size[16] = {
459 '\0', 'b', 'h', 'w', 'g'
461 static const char format[16] = {
462 '\0', 'x', 'd', 'u', 'o', 't',
463 'a', 'c', 'f', 's', 'i'
465 assert(MDTsizemask == 0xf); /* lowest 4 bits */
466 assert(MDTformatmask == 0xf0); /* next 4 bits */
467 int count = 16; /* number of entities to print */
468 char sizeSpec = size[intArg & MDTsizemask];
469 char formatSpec = format[(intArg & MDTformatmask) >> 4];
470 assert(sizeSpec != '\0');
471 assert(formatSpec != '\0');
472 // adjust count such that 16 lines are printed
473 switch (intArg & MDTformatmask) {
474 case MDTstring: case MDTinsn:
475 break; /* no modification needed */
476 default:
477 // all cases drop through:
478 switch (intArg & MDTsizemask) {
479 case MDTbyte:
480 case MDThalfword:
481 count *= 2;
482 case MDTword:
483 count *= 2;
484 case MDTgiantword:
485 count *= 2;
487 break;
489 QString spec;
490 spec.sprintf("/%d%c%c", count, sizeSpec, formatSpec);
492 return makeCmdString(DCexamine, spec, strArg);
495 if (cmds[cmd].argsNeeded == GdbCmdInfo::argStringNum)
497 // line numbers are zero-based
498 if (cmd == DCuntil || cmd == DCbreakline ||
499 cmd == DCtbreakline || cmd == DCinfoline)
501 intArg++;
503 if (cmd == DCinfoline)
505 // must split off file name part
506 int slash = strArg.findRev('/');
507 if (slash >= 0)
508 strArg = strArg.right(strArg.length()-slash-1);
510 cmdString.sprintf(cmds[cmd].fmt, strArg.latin1(), intArg);
512 else
514 cmdString.sprintf(cmds[cmd].fmt, intArg, strArg.latin1());
516 return cmdString;
519 QString GdbDriver::makeCmdString(DbgCommand cmd, QString strArg1, QString strArg2)
521 assert(cmd >= 0 && cmd < NUM_CMDS);
522 assert(cmds[cmd].argsNeeded == GdbCmdInfo::argString2);
524 normalizeStringArg(strArg1);
525 normalizeStringArg(strArg2);
527 SIZED_QString(cmdString, MAX_FMTLEN+strArg1.length()+strArg2.length());
528 cmdString.sprintf(cmds[cmd].fmt, strArg1.latin1(), strArg2.latin1());
529 return cmdString;
532 QString GdbDriver::makeCmdString(DbgCommand cmd, int intArg1, int intArg2)
534 assert(cmd >= 0 && cmd < NUM_CMDS);
535 assert(cmds[cmd].argsNeeded == GdbCmdInfo::argNum2);
537 SIZED_QString(cmdString, MAX_FMTLEN+60);
538 cmdString.sprintf(cmds[cmd].fmt, intArg1, intArg2);
539 return cmdString;
542 CmdQueueItem* GdbDriver::executeCmd(DbgCommand cmd, bool clearLow)
544 assert(cmd >= 0 && cmd < NUM_CMDS);
545 assert(cmds[cmd].argsNeeded == GdbCmdInfo::argNone);
547 if (cmd == DCrun) {
548 m_haveCoreFile = false;
551 return executeCmdString(cmd, cmds[cmd].fmt, clearLow);
554 CmdQueueItem* GdbDriver::executeCmd(DbgCommand cmd, QString strArg,
555 bool clearLow)
557 return executeCmdString(cmd, makeCmdString(cmd, strArg), clearLow);
560 CmdQueueItem* GdbDriver::executeCmd(DbgCommand cmd, int intArg,
561 bool clearLow)
564 return executeCmdString(cmd, makeCmdString(cmd, intArg), clearLow);
567 CmdQueueItem* GdbDriver::executeCmd(DbgCommand cmd, QString strArg, int intArg,
568 bool clearLow)
570 return executeCmdString(cmd, makeCmdString(cmd, strArg, intArg), clearLow);
573 CmdQueueItem* GdbDriver::executeCmd(DbgCommand cmd, QString strArg1, QString strArg2,
574 bool clearLow)
576 return executeCmdString(cmd, makeCmdString(cmd, strArg1, strArg2), clearLow);
579 CmdQueueItem* GdbDriver::executeCmd(DbgCommand cmd, int intArg1, int intArg2,
580 bool clearLow)
582 return executeCmdString(cmd, makeCmdString(cmd, intArg1, intArg2), clearLow);
585 CmdQueueItem* GdbDriver::queueCmd(DbgCommand cmd, QueueMode mode)
587 return queueCmdString(cmd, cmds[cmd].fmt, mode);
590 CmdQueueItem* GdbDriver::queueCmd(DbgCommand cmd, QString strArg,
591 QueueMode mode)
593 return queueCmdString(cmd, makeCmdString(cmd, strArg), mode);
596 CmdQueueItem* GdbDriver::queueCmd(DbgCommand cmd, int intArg,
597 QueueMode mode)
599 return queueCmdString(cmd, makeCmdString(cmd, intArg), mode);
602 CmdQueueItem* GdbDriver::queueCmd(DbgCommand cmd, QString strArg, int intArg,
603 QueueMode mode)
605 return queueCmdString(cmd, makeCmdString(cmd, strArg, intArg), mode);
608 CmdQueueItem* GdbDriver::queueCmd(DbgCommand cmd, QString strArg1, QString strArg2,
609 QueueMode mode)
611 return queueCmdString(cmd, makeCmdString(cmd, strArg1, strArg2), mode);
614 void GdbDriver::terminate()
616 kill(SIGTERM);
617 m_state = DSidle;
620 void GdbDriver::detachAndTerminate()
622 kill(SIGINT);
623 flushCommands();
624 executeCmdString(DCinitialize, "detach\nquit\n", true);
627 void GdbDriver::interruptInferior()
629 kill(SIGINT);
630 // remove accidentally queued commands
631 flushHiPriQueue();
634 static bool isErrorExpr(const char* output)
636 return
637 strncmp(output, "Cannot access memory at", 23) == 0 ||
638 strncmp(output, "Attempt to dereference a generic pointer", 40) == 0 ||
639 strncmp(output, "Attempt to take contents of ", 28) == 0 ||
640 strncmp(output, "Attempt to use a type name as an expression", 43) == 0 ||
641 strncmp(output, "There is no member or method named", 34) == 0 ||
642 strncmp(output, "A parse error in expression", 27) == 0 ||
643 strncmp(output, "No symbol \"", 11) == 0 ||
644 strncmp(output, "Internal error: ", 16) == 0;
648 * Returns true if the output is an error message. If wantErrorValue is
649 * true, a new VarTree object is created and filled with the error message.
651 static bool parseErrorMessage(const char* output,
652 VarTree*& variable, bool wantErrorValue)
654 if (isErrorExpr(output))
656 if (wantErrorValue) {
657 // put the error message as value in the variable
658 variable = new VarTree(QString(), VarTree::NKplain);
659 const char* endMsg = strchr(output, '\n');
660 if (endMsg == 0)
661 endMsg = output + strlen(output);
662 variable->m_value = FROM_LATIN1(output, endMsg-output);
663 } else {
664 variable = 0;
666 return true;
668 return false;
671 #if QT_VERSION >= 300
672 union Qt2QChar {
673 short s;
674 struct {
675 uchar row;
676 uchar cell;
677 } qch;
679 #endif
681 void GdbDriver::setPrintQStringDataCmd(const char* cmd)
683 // don't accept the command if it is empty
684 if (cmd == 0 || *cmd == '\0')
685 return;
686 assert(strlen(cmd) <= MAX_FMTLEN);
687 cmds[DCprintQStringStruct].fmt = cmd;
690 VarTree* GdbDriver::parseQCharArray(const char* output, bool wantErrorValue, bool qt3like)
692 VarTree* variable = 0;
695 * Parse off white space. gdb sometimes prints white space first if the
696 * printed array leaded to an error.
698 const char* p = output;
699 while (isspace(*p))
700 p++;
702 // special case: empty string (0 repetitions)
703 if (strncmp(p, "Invalid number 0 of repetitions", 31) == 0)
705 variable = new VarTree(QString(), VarTree::NKplain);
706 variable->m_value = "\"\"";
707 return variable;
710 // check for error conditions
711 if (parseErrorMessage(p, variable, wantErrorValue))
712 return variable;
714 // parse the array
716 // find '='
717 p = strchr(p, '=');
718 if (p == 0) {
719 goto error;
721 // skip white space
722 do {
723 p++;
724 } while (isspace(*p));
726 if (*p == '{')
728 // this is the real data
729 p++; /* skip '{' */
731 // parse the array
732 QString result;
733 QString repeatCount;
734 enum { wasNothing, wasChar, wasRepeat } lastThing = wasNothing;
736 * A matrix for separators between the individual "things"
737 * that are added to the string. The first index is a bool,
738 * the second index is from the enum above.
740 static const char* separator[2][3] = {
741 { "\"", 0, ", \"" }, /* normal char is added */
742 { "'", "\", '", ", '" } /* repeated char is added */
745 while (isdigit(*p)) {
746 // parse a number
747 char* end;
748 unsigned short value = (unsigned short) strtoul(p, &end, 0);
749 if (end == p)
750 goto error; /* huh? no valid digits */
751 // skip separator and search for a repeat count
752 p = end;
753 while (isspace(*p) || *p == ',')
754 p++;
755 bool repeats = strncmp(p, "<repeats ", 9) == 0;
756 if (repeats) {
757 const char* start = p;
758 p = strchr(p+9, '>'); /* search end and advance */
759 if (p == 0)
760 goto error;
761 p++; /* skip '>' */
762 repeatCount = FROM_LATIN1(start, p-start);
763 while (isspace(*p) || *p == ',')
764 p++;
766 // p is now at the next char (or the end)
768 // interpret the value as a QChar
769 // TODO: make cross-architecture compatible
770 QChar ch;
771 if (qt3like) {
772 ch = QChar(value);
773 } else {
774 #if QT_VERSION < 300
775 (unsigned short&)ch = value;
776 #else
777 Qt2QChar c;
778 c.s = value;
779 ch.setRow(c.qch.row);
780 ch.setCell(c.qch.cell);
781 #endif
784 // escape a few frequently used characters
785 char escapeCode = '\0';
786 switch (ch.latin1()) {
787 case '\n': escapeCode = 'n'; break;
788 case '\r': escapeCode = 'r'; break;
789 case '\t': escapeCode = 't'; break;
790 case '\b': escapeCode = 'b'; break;
791 case '\"': escapeCode = '\"'; break;
792 case '\\': escapeCode = '\\'; break;
793 case '\0': if (value == 0) { escapeCode = '0'; } break;
796 // add separator
797 result += separator[repeats][lastThing];
798 // add char
799 if (escapeCode != '\0') {
800 result += '\\';
801 ch = escapeCode;
803 result += ch;
805 // fixup repeat count and lastThing
806 if (repeats) {
807 result += "' ";
808 result += repeatCount;
809 lastThing = wasRepeat;
810 } else {
811 lastThing = wasChar;
814 if (*p != '}')
815 goto error;
817 // closing quote
818 if (lastThing == wasChar)
819 result += "\"";
821 // assign the value
822 variable = new VarTree(QString(), VarTree::NKplain);
823 variable->m_value = result;
825 else if (strncmp(p, "true", 4) == 0)
827 variable = new VarTree(QString(), VarTree::NKplain);
828 variable->m_value = "QString::null";
830 else if (strncmp(p, "false", 5) == 0)
832 variable = new VarTree(QString(), VarTree::NKplain);
833 variable->m_value = "(null)";
835 else
836 goto error;
837 return variable;
839 error:
840 if (wantErrorValue) {
841 variable = new VarTree(QString(), VarTree::NKplain);
842 variable->m_value = "internal parse error";
844 return variable;
847 static VarTree* parseVar(const char*& s)
849 const char* p = s;
851 // skip whitespace
852 while (isspace(*p))
853 p++;
855 QString name;
856 VarTree::NameKind kind;
857 if (!parseName(p, name, kind)) {
858 return 0;
861 // go for '='
862 while (isspace(*p))
863 p++;
864 if (*p != '=') {
865 TRACE(QString().sprintf("parse error: = not found after %s", (const char*)name));
866 return 0;
868 // skip the '=' and more whitespace
869 p++;
870 while (isspace(*p))
871 p++;
873 VarTree* variable = new VarTree(name, kind);
874 variable->setDeleteChildren(true);
876 if (!parseValue(p, variable)) {
877 delete variable;
878 return 0;
880 s = p;
881 return variable;
884 static void skipNested(const char*& s, char opening, char closing)
886 const char* p = s;
888 // parse a nested type
889 int nest = 1;
890 p++;
892 * Search for next matching `closing' char, skipping nested pairs of
893 * `opening' and `closing'.
895 while (*p && nest > 0) {
896 if (*p == opening) {
897 nest++;
898 } else if (*p == closing) {
899 nest--;
901 p++;
903 if (nest != 0) {
904 TRACE(QString().sprintf("parse error: mismatching %c%c at %-20.20s", opening, closing, s));
906 s = p;
910 * Find the end of line that is not inside braces
912 static void findEnd(const char*& s)
914 const char* p = s;
915 while (*p && *p!='\n') {
916 while (*p && *p!='\n' && *p!='{')
917 p++;
918 if (*p=='{') {
919 p++;
920 skipNested(p, '{', '}'); p--;
923 s = p;
926 static bool isNumberish(const char ch)
928 return (ch>='0' && ch<='9') || ch=='.' || ch=='x';
931 void skipString(const char*& p)
933 moreStrings:
934 // opening quote
935 char quote = *p++;
936 while (*p != quote) {
937 if (*p == '\\') {
938 // skip escaped character
939 // no special treatment for octal values necessary
940 p++;
942 // simply return if no more characters
943 if (*p == '\0')
944 return;
945 p++;
947 // closing quote
948 p++;
950 * Strings can consist of several parts, some of which contain repeated
951 * characters.
953 if (quote == '\'') {
954 // look ahaead for <repeats 123 times>
955 const char* q = p+1;
956 while (isspace(*q))
957 q++;
958 if (strncmp(q, "<repeats ", 9) == 0) {
959 p = q+9;
960 while (*p != '\0' && *p != '>')
961 p++;
962 if (*p != '\0') {
963 p++; /* skip the '>' */
967 // is the string continued?
968 if (*p == ',') {
969 // look ahead for another quote
970 const char* q = p+1;
971 while (isspace(*q))
972 q++;
973 if (*q == '"' || *q == '\'') {
974 // yes!
975 p = q;
976 goto moreStrings;
979 /* very long strings are followed by `...' */
980 if (*p == '.' && p[1] == '.' && p[2] == '.') {
981 p += 3;
985 static void skipNestedWithString(const char*& s, char opening, char closing)
987 const char* p = s;
989 // parse a nested expression
990 int nest = 1;
991 p++;
993 * Search for next matching `closing' char, skipping nested pairs of
994 * `opening' and `closing' as well as strings.
996 while (*p && nest > 0) {
997 if (*p == opening) {
998 nest++;
999 } else if (*p == closing) {
1000 nest--;
1001 } else if (*p == '\'' || *p == '\"') {
1002 skipString(p);
1003 continue;
1005 p++;
1007 if (nest > 0) {
1008 TRACE(QString().sprintf("parse error: mismatching %c%c at %-20.20s", opening, closing, s));
1010 s = p;
1013 inline void skipName(const char*& p)
1015 // allow : (for enumeration values) and $ and . (for _vtbl.)
1016 while (isalnum(*p) || *p == '_' || *p == ':' || *p == '$' || *p == '.')
1017 p++;
1020 static bool parseName(const char*& s, QString& name, VarTree::NameKind& kind)
1022 kind = VarTree::NKplain;
1024 const char* p = s;
1025 // examples of names:
1026 // name
1027 // <Object>
1028 // <string<a,b<c>,7> >
1030 if (*p == '<') {
1031 skipNested(p, '<', '>');
1032 name = FROM_LATIN1(s, p - s);
1033 kind = VarTree::NKtype;
1035 else
1037 // name, which might be "static"; allow dot for "_vtbl."
1038 skipName(p);
1039 if (p == s) {
1040 TRACE(QString().sprintf("parse error: not a name %-20.20s", s));
1041 return false;
1043 int len = p - s;
1044 if (len == 6 && strncmp(s, "static", 6) == 0) {
1045 kind = VarTree::NKstatic;
1047 // its a static variable, name comes now
1048 while (isspace(*p))
1049 p++;
1050 s = p;
1051 skipName(p);
1052 if (p == s) {
1053 TRACE(QString().sprintf("parse error: not a name after static %-20.20s", s));
1054 return false;
1056 len = p - s;
1058 name = FROM_LATIN1(s, len);
1060 // return the new position
1061 s = p;
1062 return true;
1065 static bool parseValue(const char*& s, VarTree* variable)
1067 variable->m_value = "";
1069 repeat:
1070 if (*s == '{') {
1071 s++;
1072 if (!parseNested(s, variable)) {
1073 return false;
1075 // must be the closing brace
1076 if (*s != '}') {
1077 TRACE("parse error: missing } of " + variable->getText());
1078 return false;
1080 s++;
1081 // final white space
1082 while (isspace(*s))
1083 s++;
1084 } else {
1085 // examples of leaf values (cannot be the empty string):
1086 // 123
1087 // -123
1088 // 23.575e+37
1089 // 0x32a45
1090 // @0x012ab4
1091 // (DwContentType&) @0x8123456: {...}
1092 // 0x32a45 "text"
1093 // 10 '\n'
1094 // <optimized out>
1095 // 0x823abc <Array<int> virtual table>
1096 // (void (*)()) 0x8048480 <f(E *, char)>
1097 // (E *) 0xbffff450
1098 // red
1099 // &parseP (HTMLClueV *, char *)
1100 // Variable "x" is not available.
1102 const char*p = s;
1104 // check for type
1105 QString type;
1106 if (*p == '(') {
1107 skipNested(p, '(', ')');
1109 while (isspace(*p))
1110 p++;
1111 variable->m_value = FROM_LATIN1(s, p - s);
1114 bool reference = false;
1115 if (*p == '@') {
1116 // skip reference marker
1117 p++;
1118 reference = true;
1120 const char* start = p;
1121 if (*p == '-')
1122 p++;
1124 // some values consist of more than one token
1125 bool checkMultiPart = false;
1127 if (p[0] == '0' && p[1] == 'x') {
1128 // parse hex number
1129 p += 2;
1130 while (isxdigit(*p))
1131 p++;
1134 * Assume this is a pointer, but only if it's not a reference, since
1135 * references can't be expanded.
1137 if (!reference) {
1138 variable->m_varKind = VarTree::VKpointer;
1139 } else {
1141 * References are followed by a colon, in which case we'll
1142 * find the value following the reference address.
1144 if (*p == ':') {
1145 p++;
1146 } else {
1147 // Paranoia. (Can this happen, i.e. reference not followed by ':'?)
1148 reference = false;
1151 checkMultiPart = true;
1152 } else if (isdigit(*p)) {
1153 // parse decimal number, possibly a float
1154 while (isdigit(*p))
1155 p++;
1156 if (*p == '.') { /* TODO: obey i18n? */
1157 // In long arrays an integer may be followed by '...'.
1158 // We test for this situation and don't gobble the '...'.
1159 if (p[1] != '.' || p[0] != '.') {
1160 // fractional part
1161 p++;
1162 while (isdigit(*p))
1163 p++;
1166 if (*p == 'e' || *p == 'E') {
1167 p++;
1168 // exponent
1169 if (*p == '-' || *p == '+')
1170 p++;
1171 while (isdigit(*p))
1172 p++;
1175 // for char variables there is the char, eg. 10 '\n'
1176 checkMultiPart = true;
1177 } else if (*p == '<') {
1178 // e.g. <optimized out>
1179 skipNested(p, '<', '>');
1180 } else if (*p == '"' || *p == '\'') {
1181 // character may have multipart: '\000' <repeats 11 times>
1182 checkMultiPart = *p == '\'';
1183 // found a string
1184 skipString(p);
1185 } else if (*p == '&') {
1186 // function pointer
1187 p++;
1188 skipName(p);
1189 while (isspace(*p)) {
1190 p++;
1192 if (*p == '(') {
1193 skipNested(p, '(', ')');
1195 } else if (strncmp(p, "Variable \"", 10) == 0) {
1196 // Variable "x" is not available.
1197 p += 10; // skip to "
1198 skipName(p);
1199 if (strncmp(p, "\" is not available.", 19) == 0) {
1200 p += 19;
1202 } else {
1203 // must be an enumeration value
1204 skipName(p);
1206 variable->m_value += FROM_LATIN1(start, p - start);
1208 if (checkMultiPart) {
1209 // white space
1210 while (isspace(*p))
1211 p++;
1212 // may be followed by a string or <...>
1213 start = p;
1215 if (*p == '"' || *p == '\'') {
1216 skipString(p);
1217 } else if (*p == '<') {
1218 // if this value is part of an array, it might be followed
1219 // by <repeats 15 times>, which we don't skip here
1220 if (strncmp(p, "<repeats ", 9) != 0)
1221 skipNested(p, '<', '>');
1223 if (p != start) {
1224 // there is always a blank before the string,
1225 // which we will include in the final string value
1226 variable->m_value += FROM_LATIN1(start-1, (p - start)+1);
1227 // if this was a pointer, reset that flag since we
1228 // now got the value
1229 variable->m_varKind = VarTree::VKsimple;
1233 if (variable->m_value.length() == 0) {
1234 TRACE("parse error: no value for " + variable->getText());
1235 return false;
1238 // final white space
1239 while (isspace(*p))
1240 p++;
1241 s = p;
1244 * If this was a reference, the value follows. It might even be a
1245 * composite variable!
1247 if (reference) {
1248 goto repeat;
1251 if (variable->m_varKind == VarTree::VKpointer) {
1252 variable->setDelayedExpanding(true);
1256 return true;
1259 static bool parseNested(const char*& s, VarTree* variable)
1261 // could be a structure or an array
1262 while (isspace(*s))
1263 s++;
1265 const char* p = s;
1266 bool isStruct = false;
1268 * If there is a name followed by an = or an < -- which starts a type
1269 * name -- or "static", it is a structure
1271 if (*p == '<' || *p == '}') {
1272 isStruct = true;
1273 } else if (strncmp(p, "static ", 7) == 0) {
1274 isStruct = true;
1275 } else if (isalpha(*p) || *p == '_' || *p == '$') {
1276 // look ahead for a comma after the name
1277 skipName(p);
1278 while (isspace(*p))
1279 p++;
1280 if (*p == '=') {
1281 isStruct = true;
1283 p = s; /* rescan the name */
1285 if (isStruct) {
1286 if (!parseVarSeq(p, variable)) {
1287 return false;
1289 variable->m_varKind = VarTree::VKstruct;
1290 } else {
1291 if (!parseValueSeq(p, variable)) {
1292 return false;
1294 variable->m_varKind = VarTree::VKarray;
1296 s = p;
1297 return true;
1300 static bool parseVarSeq(const char*& s, VarTree* variable)
1302 // parse a comma-separated sequence of variables
1303 VarTree* var = variable; /* var != 0 to indicate success if empty seq */
1304 for (;;) {
1305 if (*s == '}')
1306 break;
1307 if (strncmp(s, "<No data fields>}", 17) == 0)
1309 // no member variables, so break out immediately
1310 s += 16; /* go to the closing brace */
1311 break;
1313 var = parseVar(s);
1314 if (var == 0)
1315 break; /* syntax error */
1316 variable->appendChild(var);
1317 if (*s != ',')
1318 break;
1319 // skip the comma and whitespace
1320 s++;
1321 while (isspace(*s))
1322 s++;
1324 return var != 0;
1327 static bool parseValueSeq(const char*& s, VarTree* variable)
1329 // parse a comma-separated sequence of variables
1330 int index = 0;
1331 bool good;
1332 for (;;) {
1333 QString name;
1334 name.sprintf("[%d]", index);
1335 VarTree* var = new VarTree(name, VarTree::NKplain);
1336 var->setDeleteChildren(true);
1337 good = parseValue(s, var);
1338 if (!good) {
1339 delete var;
1340 return false;
1342 // a value may be followed by "<repeats 45 times>"
1343 if (strncmp(s, "<repeats ", 9) == 0) {
1344 s += 9;
1345 char* end;
1346 int l = strtol(s, &end, 10);
1347 if (end == s || strncmp(end, " times>", 7) != 0) {
1348 // should not happen
1349 delete var;
1350 return false;
1352 TRACE(QString().sprintf("found <repeats %d times> in array", l));
1353 // replace name and advance index
1354 name.sprintf("[%d .. %d]", index, index+l-1);
1355 var->setText(name);
1356 index += l;
1357 // skip " times>" and space
1358 s = end+7;
1359 // possible final space
1360 while (isspace(*s))
1361 s++;
1362 } else {
1363 index++;
1365 variable->appendChild(var);
1366 // long arrays may be terminated by '...'
1367 if (strncmp(s, "...", 3) == 0) {
1368 s += 3;
1369 VarTree* var = new VarTree("...", VarTree::NKplain);
1370 var->setDeleteChildren(true);
1371 var->m_value = i18n("<additional entries of the array suppressed>");
1372 variable->appendChild(var);
1373 break;
1375 if (*s != ',') {
1376 break;
1378 // skip the comma and whitespace
1379 s++;
1380 while (isspace(*s))
1381 s++;
1382 // sometimes there is a closing brace after a comma
1383 // if (*s == '}')
1384 // break;
1386 return true;
1390 * Parses a stack frame.
1392 static void parseFrameInfo(const char*& s, QString& func,
1393 QString& file, int& lineNo, DbgAddr& address)
1395 const char* p = s;
1397 // next may be a hexadecimal address
1398 if (*p == '0') {
1399 const char* start = p;
1400 p++;
1401 if (*p == 'x')
1402 p++;
1403 while (isxdigit(*p))
1404 p++;
1405 address = FROM_LATIN1(start, p-start);
1406 if (strncmp(p, " in ", 4) == 0)
1407 p += 4;
1408 } else {
1409 address = DbgAddr();
1411 const char* start = p;
1412 // check for special signal handler frame
1413 if (strncmp(p, "<signal handler called>", 23) == 0) {
1414 func = FROM_LATIN1(start, 23);
1415 file = QString();
1416 lineNo = -1;
1417 s = p+23;
1418 if (*s == '\n')
1419 s++;
1420 return;
1422 // search opening parenthesis
1423 while (*p != '\0' && *p != '(')
1424 p++;
1426 // skip (anonymous namespace)
1427 if (strncmp(p, "(anonymous namespace)", 21) == 0) {
1428 p+=21;
1429 while (*p != '\0' && *p != '(')
1430 p++;
1433 if (*p == '\0') {
1434 func = start;
1435 file = QString();
1436 lineNo = -1;
1437 s = p;
1438 return;
1441 * Skip parameters. But notice that for complicated conversion
1442 * functions (eg. "operator int(**)()()", ie. convert to pointer to
1443 * pointer to function) as well as operator()(...) we have to skip
1444 * additional pairs of parentheses. Furthermore, recent gdbs write the
1445 * demangled name followed by the arguments in a pair of parentheses,
1446 * where the demangled name can end in "const".
1448 do {
1449 skipNestedWithString(p, '(', ')');
1450 while (isspace(*p))
1451 p++;
1452 // skip "const"
1453 if (strncmp(p, "const", 5) == 0) {
1454 p += 5;
1455 while (isspace(*p))
1456 p++;
1458 } while (*p == '(');
1460 // check for file position
1461 if (strncmp(p, "at ", 3) == 0) {
1462 p += 3;
1463 const char* fileStart = p;
1464 // go for the end of the line
1465 while (*p != '\0' && *p != '\n')
1466 p++;
1467 // search back for colon
1468 const char* colon = p;
1469 do {
1470 --colon;
1471 } while (*colon != ':');
1472 file = FROM_LATIN1(fileStart, colon-fileStart);
1473 lineNo = atoi(colon+1)-1;
1474 // skip new-line
1475 if (*p != '\0')
1476 p++;
1477 } else {
1478 // check for "from shared lib"
1479 if (strncmp(p, "from ", 5) == 0) {
1480 p += 5;
1481 // go for the end of the line
1482 while (*p != '\0' && *p != '\n')
1483 p++;
1484 // skip new-line
1485 if (*p != '\0')
1486 p++;
1488 file = "";
1489 lineNo = -1;
1491 // construct the function name (including file info)
1492 if (*p == '\0') {
1493 func = start;
1494 } else {
1495 func = FROM_LATIN1(start, p-start-1); /* don't include \n */
1497 s = p;
1500 * Replace \n (and whitespace around it) in func by a blank. We cannot
1501 * use QString::simplifyWhiteSpace() for this because this would also
1502 * simplify space that belongs to a string arguments that gdb sometimes
1503 * prints in the argument lists of the function.
1505 ASSERT(!isspace(func[0].latin1())); /* there must be non-white before first \n */
1506 int nl = 0;
1507 while ((nl = func.find('\n', nl)) >= 0) {
1508 // search back to the beginning of the whitespace
1509 int startWhite = nl;
1510 do {
1511 --startWhite;
1512 } while (isspace(func[startWhite].latin1()));
1513 startWhite++;
1514 // search forward to the end of the whitespace
1515 do {
1516 nl++;
1517 } while (isspace(func[nl].latin1()));
1518 // replace
1519 func.replace(startWhite, nl-startWhite, " ");
1520 /* continue searching for more \n's at this place: */
1521 nl = startWhite+1;
1527 * Parses a stack frame including its frame number
1529 static bool parseFrame(const char*& s, int& frameNo, QString& func,
1530 QString& file, int& lineNo, DbgAddr& address)
1532 // Example:
1533 // #1 0x8048881 in Dl::Dl (this=0xbffff418, r=3214) at testfile.cpp:72
1534 // Breakpoint 3, Cl::f(int) const (this=0xbffff3c0, x=17) at testfile.cpp:155
1536 // must start with a hash mark followed by number
1537 // or with "Breakpoint " followed by number and comma
1538 if (s[0] == '#') {
1539 if (!isdigit(s[1]))
1540 return false;
1541 s++; /* skip the hash mark */
1542 } else if (strncmp(s, "Breakpoint ", 11) == 0) {
1543 if (!isdigit(s[11]))
1544 return false;
1545 s += 11; /* skip "Breakpoint" */
1546 } else
1547 return false;
1549 // frame number
1550 frameNo = atoi(s);
1551 while (isdigit(*s))
1552 s++;
1553 // space and comma
1554 while (isspace(*s) || *s == ',')
1555 s++;
1556 parseFrameInfo(s, func, file, lineNo, address);
1557 return true;
1560 void GdbDriver::parseBackTrace(const char* output, QList<StackFrame>& stack)
1562 QString func, file;
1563 int lineNo, frameNo;
1564 DbgAddr address;
1566 while (::parseFrame(output, frameNo, func, file, lineNo, address)) {
1567 StackFrame* frm = new StackFrame;
1568 frm->frameNo = frameNo;
1569 frm->fileName = file;
1570 frm->lineNo = lineNo;
1571 frm->address = address;
1572 frm->var = new VarTree(func, VarTree::NKplain);
1573 stack.append(frm);
1577 bool GdbDriver::parseFrameChange(const char* output, int& frameNo,
1578 QString& file, int& lineNo, DbgAddr& address)
1580 QString func;
1581 return ::parseFrame(output, frameNo, func, file, lineNo, address);
1585 bool GdbDriver::parseBreakList(const char* output, QList<Breakpoint>& brks)
1587 // skip first line, which is the headline
1588 const char* p = strchr(output, '\n');
1589 if (p == 0)
1590 return false;
1591 p++;
1592 if (*p == '\0')
1593 return false;
1595 // split up a line
1596 QString location;
1597 QString address;
1598 int hits = 0;
1599 uint ignoreCount = 0;
1600 QString condition;
1601 const char* end;
1602 char* dummy;
1603 while (*p != '\0') {
1604 // get Num
1605 long bpNum = strtol(p, &dummy, 10); /* don't care about overflows */
1606 p = dummy;
1607 // get Type
1608 while (isspace(*p))
1609 p++;
1610 Breakpoint::Type bpType = Breakpoint::breakpoint;
1611 if (strncmp(p, "breakpoint", 10) == 0) {
1612 p += 10;
1613 } else if (strncmp(p, "hw watchpoint", 13) == 0) {
1614 bpType = Breakpoint::watchpoint;
1615 p += 13;
1616 } else if (strncmp(p, "watchpoint", 10) == 0) {
1617 bpType = Breakpoint::watchpoint;
1618 p += 10;
1620 while (isspace(*p))
1621 p++;
1622 if (*p == '\0')
1623 break;
1624 // get Disp
1625 char disp = *p++;
1626 while (*p != '\0' && !isspace(*p)) /* "keep" or "del" */
1627 p++;
1628 while (isspace(*p))
1629 p++;
1630 if (*p == '\0')
1631 break;
1632 // get Enb
1633 char enable = *p++;
1634 while (*p != '\0' && !isspace(*p)) /* "y" or "n" */
1635 p++;
1636 while (isspace(*p))
1637 p++;
1638 if (*p == '\0')
1639 break;
1640 // the address, if present
1641 if (bpType == Breakpoint::breakpoint &&
1642 strncmp(p, "0x", 2) == 0)
1644 const char* start = p;
1645 while (*p != '\0' && !isspace(*p))
1646 p++;
1647 address = FROM_LATIN1(start, p-start);
1648 while (isspace(*p) && *p != '\n')
1649 p++;
1650 if (*p == '\0')
1651 break;
1652 } else {
1653 address = QString();
1655 // remainder is location, hit and ignore count, condition
1656 hits = 0;
1657 ignoreCount = 0;
1658 condition = QString();
1659 end = strchr(p, '\n');
1660 if (end == 0) {
1661 location = p;
1662 p += location.length();
1663 } else {
1664 location = FROM_LATIN1(p, end-p).stripWhiteSpace();
1665 p = end+1; /* skip over \n */
1668 // may be continued in next line
1669 while (isspace(*p)) { /* p points to beginning of line */
1670 // skip white space at beginning of line
1671 while (isspace(*p))
1672 p++;
1674 // seek end of line
1675 end = strchr(p, '\n');
1676 if (end == 0)
1677 end = p+strlen(p);
1679 if (strncmp(p, "breakpoint already hit", 22) == 0) {
1680 // extract the hit count
1681 p += 22;
1682 hits = strtol(p, &dummy, 10);
1683 TRACE(QString().sprintf("hit count %d", hits));
1684 } else if (strncmp(p, "stop only if ", 13) == 0) {
1685 // extract condition
1686 p += 13;
1687 condition = FROM_LATIN1(p, end-p).stripWhiteSpace();
1688 TRACE("condition: "+condition);
1689 } else if (strncmp(p, "ignore next ", 12) == 0) {
1690 // extract ignore count
1691 p += 12;
1692 ignoreCount = strtol(p, &dummy, 10);
1693 TRACE(QString().sprintf("ignore count %d", ignoreCount));
1694 } else {
1695 // indeed a continuation
1696 location += " " + FROM_LATIN1(p, end-p).stripWhiteSpace();
1698 p = end;
1699 if (*p != '\0')
1700 p++; /* skip '\n' */
1702 Breakpoint* bp = new Breakpoint;
1703 bp->id = bpNum;
1704 bp->type = bpType;
1705 bp->temporary = disp == 'd';
1706 bp->enabled = enable == 'y';
1707 bp->location = location;
1708 bp->address = address;
1709 bp->hitCount = hits;
1710 bp->ignoreCount = ignoreCount;
1711 bp->condition = condition;
1712 brks.append(bp);
1714 return true;
1717 bool GdbDriver::parseThreadList(const char* output, QList<ThreadInfo>& threads)
1719 if (strcmp(output, "\n") == 0 || strncmp(output, "No stack.", 9) == 0) {
1720 // no threads
1721 return true;
1724 int id;
1725 QString systag;
1726 QString func, file;
1727 int lineNo;
1728 DbgAddr address;
1730 const char* p = output;
1731 while (*p != '\0') {
1732 // seach look for thread id, watching out for the focus indicator
1733 bool hasFocus = false;
1734 while (isspace(*p)) /* may be \n from prev line: see "No stack" below */
1735 p++;
1736 if (*p == '*') {
1737 hasFocus = true;
1738 p++;
1739 // there follows only whitespace
1741 char* end;
1742 id = strtol(p, &end, 10);
1743 if (p == end) {
1744 // syntax error: no number found; bail out
1745 return true;
1747 p = end;
1749 // skip space
1750 while (isspace(*p))
1751 p++;
1754 * Now follows the thread's SYSTAG. It is terminated by two blanks.
1756 end = strstr(p, " ");
1757 if (end == 0) {
1758 // syntax error; bail out
1759 return true;
1761 systag = FROM_LATIN1(p, end-p);
1762 p = end+2;
1765 * Now follows a standard stack frame. Sometimes, however, gdb
1766 * catches a thread at an instant where it doesn't have a stack.
1768 if (strncmp(p, "[No stack.]", 11) != 0) {
1769 ::parseFrameInfo(p, func, file, lineNo, address);
1770 } else {
1771 func = "[No stack]";
1772 file = QString();
1773 lineNo = -1;
1774 address = QString();
1775 p += 11; /* \n is skipped above */
1778 ThreadInfo* thr = new ThreadInfo;
1779 thr->id = id;
1780 thr->threadName = systag;
1781 thr->hasFocus = hasFocus;
1782 thr->function = func;
1783 thr->fileName = file;
1784 thr->lineNo = lineNo;
1785 thr->address = address;
1786 threads.append(thr);
1788 return true;
1791 static bool parseNewBreakpoint(const char* o, int& id,
1792 QString& file, int& lineNo, QString& address);
1793 static bool parseNewWatchpoint(const char* o, int& id,
1794 QString& expr);
1796 bool GdbDriver::parseBreakpoint(const char* output, int& id,
1797 QString& file, int& lineNo, QString& address)
1799 const char* o = output;
1800 // skip lines of that begin with "(Cannot find"
1801 while (strncmp(o, "(Cannot find", 12) == 0) {
1802 o = strchr(o, '\n');
1803 if (o == 0)
1804 return false;
1805 o++; /* skip newline */
1808 if (strncmp(o, "Breakpoint ", 11) == 0) {
1809 output += 11; /* skip "Breakpoint " */
1810 return ::parseNewBreakpoint(output, id, file, lineNo, address);
1811 } else if (strncmp(o, "Hardware watchpoint ", 20) == 0) {
1812 output += 20;
1813 return ::parseNewWatchpoint(output, id, address);
1814 } else if (strncmp(o, "Watchpoint ", 11) == 0) {
1815 output += 11;
1816 return ::parseNewWatchpoint(output, id, address);
1818 return false;
1821 static bool parseNewBreakpoint(const char* o, int& id,
1822 QString& file, int& lineNo, QString& address)
1824 // breakpoint id
1825 char* p;
1826 id = strtoul(o, &p, 10);
1827 if (p == o)
1828 return false;
1830 // check for the address
1831 if (strncmp(p, " at 0x", 6) == 0) {
1832 char* start = p+4; /* skip " at ", but not 0x */
1833 p += 6;
1834 while (isxdigit(*p))
1835 ++p;
1836 address = FROM_LATIN1(start, p-start);
1839 // file name
1840 char* fileStart = strstr(p, "file ");
1841 if (fileStart == 0)
1842 return !address.isEmpty(); /* parse error only if there's no address */
1843 fileStart += 5;
1845 // line number
1846 char* numStart = strstr(fileStart, ", line ");
1847 QString fileName = FROM_LATIN1(fileStart, numStart-fileStart);
1848 numStart += 7;
1849 int line = strtoul(numStart, &p, 10);
1850 if (numStart == p)
1851 return false;
1853 file = fileName;
1854 lineNo = line-1; /* zero-based! */
1855 return true;
1858 static bool parseNewWatchpoint(const char* o, int& id,
1859 QString& expr)
1861 // watchpoint id
1862 char* p;
1863 id = strtoul(o, &p, 10);
1864 if (p == o)
1865 return false;
1867 if (strncmp(p, ": ", 2) != 0)
1868 return false;
1869 p += 2;
1871 // all the rest on the line is the expression
1872 expr = FROM_LATIN1(p, strlen(p)).stripWhiteSpace();
1873 return true;
1876 void GdbDriver::parseLocals(const char* output, QList<VarTree>& newVars)
1878 // check for possible error conditions
1879 if (strncmp(output, "No symbol table", 15) == 0)
1881 return;
1884 while (*output != '\0') {
1885 while (isspace(*output))
1886 output++;
1887 if (*output == '\0')
1888 break;
1889 // skip occurrences of "No locals" and "No args"
1890 if (strncmp(output, "No locals", 9) == 0 ||
1891 strncmp(output, "No arguments", 12) == 0)
1893 output = strchr(output, '\n');
1894 if (output == 0) {
1895 break;
1897 continue;
1900 VarTree* variable = parseVar(output);
1901 if (variable == 0) {
1902 break;
1904 // do not add duplicates
1905 for (VarTree* o = newVars.first(); o != 0; o = newVars.next()) {
1906 if (o->getText() == variable->getText()) {
1907 delete variable;
1908 goto skipDuplicate;
1911 newVars.append(variable);
1912 skipDuplicate:;
1916 bool GdbDriver::parsePrintExpr(const char* output, bool wantErrorValue, VarTree*& var)
1918 // check for error conditions
1919 if (parseErrorMessage(output, var, wantErrorValue))
1921 return false;
1922 } else {
1923 // parse the variable
1924 var = parseVar(output);
1925 return true;
1929 bool GdbDriver::parseChangeWD(const char* output, QString& message)
1931 bool isGood = false;
1932 message = QString(output).simplifyWhiteSpace();
1933 if (message.isEmpty()) {
1934 message = i18n("New working directory: ") + m_programWD;
1935 isGood = true;
1937 return isGood;
1940 bool GdbDriver::parseChangeExecutable(const char* output, QString& message)
1942 message = output;
1944 m_haveCoreFile = false;
1947 * Lines starting with the following do not indicate errors:
1948 * Using host libthread_db
1949 * (no debugging symbols found)
1951 while (strncmp(output, "Using host libthread_db", 23) == 0 ||
1952 strncmp(output, "(no debugging symbols found)", 28) == 0)
1954 // this line is good, go to the next one
1955 const char* end = strchr(output, '\n');
1956 if (end == 0)
1957 output += strlen(output);
1958 else
1959 output = end+1;
1963 * If we've parsed all lines, there was no error.
1965 return output[0] == '\0';
1968 bool GdbDriver::parseCoreFile(const char* output)
1970 // if command succeeded, gdb emits a line starting with "#0 "
1971 m_haveCoreFile = strstr(output, "\n#0 ") != 0;
1972 return m_haveCoreFile;
1975 uint GdbDriver::parseProgramStopped(const char* output, QString& message)
1977 // optionally: "program changed, rereading symbols",
1978 // followed by:
1979 // "Program exited normally"
1980 // "Program terminated with wignal SIGSEGV"
1981 // "Program received signal SIGINT" or other signal
1982 // "Breakpoint..."
1984 // go through the output, line by line, checking what we have
1985 const char* start = output - 1;
1986 uint flags = SFprogramActive;
1987 message = QString();
1988 do {
1989 start++; /* skip '\n' */
1991 if (strncmp(start, "Program ", 8) == 0 ||
1992 strncmp(start, "ptrace: ", 8) == 0) {
1994 * When we receive a signal, the program remains active.
1996 * Special: If we "stopped" in a corefile, the string "Program
1997 * terminated with signal"... is displayed. (Normally, we see
1998 * "Program received signal"... when a signal happens.)
2000 if (strncmp(start, "Program exited", 14) == 0 ||
2001 (strncmp(start, "Program terminated", 18) == 0 && !m_haveCoreFile) ||
2002 strncmp(start, "ptrace: ", 8) == 0)
2004 flags &= ~SFprogramActive;
2007 // set message
2008 const char* endOfMessage = strchr(start, '\n');
2009 if (endOfMessage == 0)
2010 endOfMessage = start + strlen(start);
2011 message = FROM_LATIN1(start, endOfMessage-start);
2012 } else if (strncmp(start, "Breakpoint ", 11) == 0) {
2014 * We stopped at a (permanent) breakpoint (gdb doesn't tell us
2015 * that it stopped at a temporary breakpoint).
2017 flags |= SFrefreshBreak;
2018 } else if (strstr(start, "re-reading symbols.") != 0) {
2019 flags |= SFrefreshSource;
2022 // next line, please
2023 start = strchr(start, '\n');
2024 } while (start != 0);
2027 * Gdb only notices when new threads have appeared, but not when a
2028 * thread finishes. So we always have to assume that the list of
2029 * threads has changed.
2031 flags |= SFrefreshThreads;
2033 return flags;
2036 void GdbDriver::parseSharedLibs(const char* output, QStrList& shlibs)
2038 if (strncmp(output, "No shared libraries loaded", 26) == 0)
2039 return;
2041 // parse the table of shared libraries
2043 // strip off head line
2044 output = strchr(output, '\n');
2045 if (output == 0)
2046 return;
2047 output++; /* skip '\n' */
2048 QString shlibName;
2049 while (*output != '\0') {
2050 // format of a line is
2051 // 0x404c5000 0x40580d90 Yes /lib/libc.so.5
2052 // 3 blocks of non-space followed by space
2053 for (int i = 0; *output != '\0' && i < 3; i++) {
2054 while (*output != '\0' && !isspace(*output)) { /* non-space */
2055 output++;
2057 while (isspace(*output)) { /* space */
2058 output++;
2061 if (*output == '\0')
2062 return;
2063 const char* start = output;
2064 output = strchr(output, '\n');
2065 if (output == 0)
2066 output = start + strlen(start);
2067 shlibName = FROM_LATIN1(start, output-start);
2068 if (*output != '\0')
2069 output++;
2070 shlibs.append(shlibName);
2071 TRACE("found shared lib " + shlibName);
2075 bool GdbDriver::parseFindType(const char* output, QString& type)
2077 if (strncmp(output, "type = ", 7) != 0)
2078 return false;
2081 * Everything else is the type. We strip off any leading "const" and any
2082 * trailing "&" on the grounds that neither affects the decoding of the
2083 * object. We also strip off all white-space from the type.
2085 output += 7;
2086 if (strncmp(output, "const ", 6) == 0)
2087 output += 6;
2088 type = output;
2089 type.replace(QRegExp("\\s+"), "");
2090 if (type.endsWith("&"))
2091 type.truncate(type.length() - 1);
2092 return true;
2095 void GdbDriver::parseRegisters(const char* output, QList<RegisterInfo>& regs)
2097 if (strncmp(output, "The program has no registers now", 32) == 0) {
2098 return;
2101 QString regName;
2102 QString value;
2104 // parse register values
2105 while (*output != '\0')
2107 // skip space at the start of the line
2108 while (isspace(*output))
2109 output++;
2111 // register name
2112 const char* start = output;
2113 while (*output != '\0' && !isspace(*output))
2114 output++;
2115 if (*output == '\0')
2116 break;
2117 regName = FROM_LATIN1(start, output-start);
2119 // skip space
2120 while (isspace(*output))
2121 output++;
2123 RegisterInfo* reg = new RegisterInfo;
2124 reg->regName = regName;
2127 * If we find a brace now, this is a vector register. We look for
2128 * the closing brace and treat the result as cooked value.
2130 if (*output == '{')
2132 start = output;
2133 skipNested(output, '{', '}');
2134 value = FROM_LATIN1(start, output-start).simplifyWhiteSpace();
2135 // skip space, but not the end of line
2136 while (isspace(*output) && *output != '\n')
2137 output++;
2138 // get rid of the braces at the begining and the end
2139 value.remove(0, 1);
2140 if (value[value.length()-1] == '}') {
2141 value = value.left(value.length()-1);
2143 // gdb 5.3 doesn't print a separate set of raw values
2144 if (*output == '{') {
2145 // another set of vector follows
2146 // what we have so far is the raw value
2147 reg->rawValue = value;
2149 start = output;
2150 skipNested(output, '{', '}');
2151 value = FROM_LATIN1(start, output-start).simplifyWhiteSpace();
2152 } else {
2153 // for gdb 5.3
2154 // find first type that does not have an array, this is the RAW value
2155 const char* end=start;
2156 findEnd(end);
2157 const char* cur=start;
2158 while (cur<end) {
2159 while (*cur != '=' && cur<end)
2160 cur++;
2161 cur++;
2162 while (isspace(*cur) && cur<end)
2163 cur++;
2164 if (isNumberish(*cur)) {
2165 end=cur;
2166 while (*end && (*end!='}') && (*end!=',') && (*end!='\n'))
2167 end++;
2168 QString rawValue = FROM_LATIN1(cur, end-cur).simplifyWhiteSpace();
2169 reg->rawValue = rawValue;
2171 if (rawValue.left(2)=="0x") {
2172 // ok we have a raw value, now get it's type
2173 end=cur-1;
2174 while (isspace(*end) || *end=='=') end--;
2175 end++;
2176 cur=end-1;
2177 while (*cur!='{' && *cur!=' ')
2178 cur--;
2179 cur++;
2180 reg->type=FROM_LATIN1(cur, end-cur);
2183 // end while loop
2184 cur=end;
2187 // skip to the end of line
2188 while (*output != '\0' && *output != '\n')
2189 output++;
2190 // get rid of the braces at the begining and the end
2191 value.remove(0, 1);
2192 if (value[value.length()-1] == '}') {
2193 value = value.left(value.length()-1);
2196 reg->cookedValue = value;
2198 else
2200 // the rest of the line is the register value
2201 start = output;
2202 output = strchr(output,'\n');
2203 if (output == 0)
2204 output = start + strlen(start);
2205 value = FROM_LATIN1(start, output-start).simplifyWhiteSpace();
2208 * We split the raw from the cooked values.
2209 * Some modern gdbs explicitly say: "0.1234 (raw 0x3e4567...)".
2210 * Here, the cooked value comes first, and the raw value is in
2211 * the second part.
2213 int pos = value.find(" (raw ");
2214 if (pos >= 0)
2216 reg->cookedValue = value.left(pos);
2217 reg->rawValue = value.mid(pos+6);
2218 if (reg->rawValue.right(1) == ")") // remove closing bracket
2219 reg->rawValue.truncate(reg->rawValue.length()-1);
2221 else
2224 * In other cases we split off the first token (separated by
2225 * whitespace). It is the raw value. The remainder of the line
2226 * is the cooked value.
2228 int pos = value.find(' ');
2229 if (pos < 0) {
2230 reg->rawValue = value;
2231 reg->cookedValue = QString();
2232 } else {
2233 reg->rawValue = value.left(pos);
2234 reg->cookedValue = value.mid(pos+1);
2238 if (*output != '\0')
2239 output++; /* skip '\n' */
2241 regs.append(reg);
2245 bool GdbDriver::parseInfoLine(const char* output, QString& addrFrom, QString& addrTo)
2247 // "is at address" or "starts at address"
2248 const char* start = strstr(output, "s at address ");
2249 if (start == 0)
2250 return false;
2252 start += 13;
2253 const char* p = start;
2254 while (*p != '\0' && !isspace(*p))
2255 p++;
2256 addrFrom = FROM_LATIN1(start, p-start);
2258 start = strstr(p, "and ends at ");
2259 if (start == 0) {
2260 addrTo = addrFrom;
2261 return true;
2264 start += 12;
2265 p = start;
2266 while (*p != '\0' && !isspace(*p))
2267 p++;
2268 addrTo = FROM_LATIN1(start, p-start);
2270 return true;
2273 void GdbDriver::parseDisassemble(const char* output, QList<DisassembledCode>& code)
2275 code.clear();
2277 if (strncmp(output, "Dump of assembler", 17) != 0) {
2278 // error message?
2279 DisassembledCode c;
2280 c.code = output;
2281 code.append(new DisassembledCode(c));
2282 return;
2285 // remove first line
2286 const char* p = strchr(output, '\n');
2287 if (p == 0)
2288 return; /* not a regular output */
2290 p++;
2292 // remove last line
2293 const char* end = strstr(output, "End of assembler");
2294 if (end == 0)
2295 end = p + strlen(p);
2297 DbgAddr address;
2299 // remove function offsets from the lines
2300 while (p != end)
2302 const char* start = p;
2303 // address
2304 while (p != end && !isspace(*p))
2305 p++;
2306 address = FROM_LATIN1(start, p-start);
2308 // function name (enclosed in '<>', followed by ':')
2309 while (p != end && *p != '<')
2310 p++;
2311 if (*p == '<')
2312 skipNested(p, '<', '>');
2313 if (*p == ':')
2314 p++;
2316 // space until code
2317 while (p != end && isspace(*p))
2318 p++;
2320 // code until end of line
2321 start = p;
2322 while (p != end && *p != '\n')
2323 p++;
2324 if (p != end) /* include '\n' */
2325 p++;
2327 DisassembledCode* c = new DisassembledCode;
2328 c->address = address;
2329 c->code = FROM_LATIN1(start, p-start);
2330 code.append(c);
2334 QString GdbDriver::parseMemoryDump(const char* output, QList<MemoryDump>& memdump)
2336 if (isErrorExpr(output)) {
2337 // error; strip space
2338 QString msg = output;
2339 return msg.stripWhiteSpace();
2342 const char* p = output; /* save typing */
2343 DbgAddr addr;
2344 QString dump;
2346 // the address
2347 while (*p != 0) {
2348 const char* start = p;
2349 while (*p != '\0' && *p != ':' && !isspace(*p))
2350 p++;
2351 addr = FROM_LATIN1(start, p-start);
2352 if (*p != ':') {
2353 // parse function offset
2354 while (isspace(*p))
2355 p++;
2356 start = p;
2357 while (*p != '\0' && !(*p == ':' && isspace(p[1])))
2358 p++;
2359 addr.fnoffs = FROM_LATIN1(start, p-start);
2361 if (*p == ':')
2362 p++;
2363 // skip space; this may skip a new-line char!
2364 while (isspace(*p))
2365 p++;
2366 // everything to the end of the line is the memory dump
2367 const char* end = strchr(p, '\n');
2368 if (end != 0) {
2369 dump = FROM_LATIN1(p, end-p);
2370 p = end+1;
2371 } else {
2372 dump = FROM_LATIN1(p, strlen(p));
2373 p += strlen(p);
2375 MemoryDump* md = new MemoryDump;
2376 md->address = addr;
2377 md->dump = dump;
2378 memdump.append(md);
2381 return QString();
2384 QString GdbDriver::editableValue(VarTree* value)
2386 const char* s = value->m_value.latin1();
2388 // if the variable is a pointer value that contains a cast,
2389 // remove the cast
2390 if (*s == '(') {
2391 skipNested(s, '(', ')');
2392 // skip space
2393 while (isspace(*s))
2394 ++s;
2397 repeat:
2398 const char* start = s;
2400 if (strncmp(s, "0x", 2) == 0)
2402 s += 2;
2403 while (isxdigit(*s))
2404 ++s;
2407 * What we saw so far might have been a reference. If so, edit the
2408 * referenced value. Otherwise, edit the pointer.
2410 if (*s == ':') {
2411 // a reference
2412 ++s;
2413 goto repeat;
2415 // a pointer
2416 // if it's a pointer to a string, remove the string
2417 const char* end = s;
2418 while (isspace(*s))
2419 ++s;
2420 if (*s == '"') {
2421 // a string
2422 return FROM_LATIN1(start, end-start);
2423 } else {
2424 // other pointer
2425 return FROM_LATIN1(start, strlen(start));
2429 // else leave it unchanged (or stripped of the reference preamble)
2430 return s;
2433 QString GdbDriver::parseSetVariable(const char* output)
2435 // if there is any output, it is an error message
2436 QString msg = output;
2437 return msg.stripWhiteSpace();
2441 #include "gdbdriver.moc"