Address status bar text boxes by pointer instead of "command IDs".
[kdbg.git] / kdbg / gdbdriver.cpp
blob418d1813f504b2a98b7765a25f827460ee00f141
1 /*
2 * Copyright Johannes Sixt
3 * This file is licensed under the GNU General Public License Version 2.
4 * See the file COPYING in the toplevel directory of the source directory.
5 */
7 #include "gdbdriver.h"
8 #include "exprwnd.h"
9 #include <QFileInfo>
10 #include <QRegExp>
11 #include <QStringList>
12 #include <klocale.h> /* i18n */
13 #include <ctype.h>
14 #include <signal.h>
15 #include <stdlib.h> /* strtol, atoi */
16 #include <string.h> /* strcpy */
18 #include "assert.h"
19 #include "mydebug.h"
21 static void skipString(const char*& p);
22 static void skipNested(const char*& s, char opening, char closing);
23 static ExprValue* parseVar(const char*& s);
24 static bool parseName(const char*& s, QString& name, VarTree::NameKind& kind);
25 static bool parseValue(const char*& s, ExprValue* variable);
26 static bool parseNested(const char*& s, ExprValue* variable);
27 static bool parseVarSeq(const char*& s, ExprValue* variable);
28 static bool parseValueSeq(const char*& s, ExprValue* variable);
30 #define PROMPT "(kdbg)"
31 #define PROMPT_LEN 6
33 // TODO: make this cmd info stuff non-static to allow multiple
34 // simultaneous gdbs to run!
36 struct GdbCmdInfo {
37 DbgCommand cmd;
38 const char* fmt; /* format string */
39 enum Args {
40 argNone, argString, argNum,
41 argStringNum, argNumString,
42 argString2, argNum2
43 } argsNeeded;
46 #if 0
47 // This is how the QString data print statement generally looks like.
48 // It is set by KDebugger via setPrintQStringDataCmd().
50 static const char printQStringStructFmt[] =
51 // if the string data is junk, fail early
52 "print ($qstrunicode=($qstrdata=(%s))->unicode)?"
53 // print an array of shorts
54 "(*(unsigned short*)$qstrunicode)@"
55 // limit the length
56 "(($qstrlen=(unsigned int)($qstrdata->len))>100?100:$qstrlen)"
57 // if unicode data is 0, report a special value
58 ":1==0\n";
59 #endif
60 static const char printQStringStructFmt[] = "print (0?\"%s\":$kdbgundef)\n";
63 * The following array of commands must be sorted by the DC* values,
64 * because they are used as indices.
66 static GdbCmdInfo cmds[] = {
67 { DCinitialize, "", GdbCmdInfo::argNone },
68 { DCtty, "tty %s\n", GdbCmdInfo::argString },
69 { DCexecutable, "file \"%s\"\n", GdbCmdInfo::argString },
70 { DCtargetremote, "target remote %s\n", GdbCmdInfo::argString },
71 #ifdef __FreeBSD__
72 { DCcorefile, "target FreeBSD-core %s\n", GdbCmdInfo::argString },
73 #else
74 { DCcorefile, "target core %s\n", GdbCmdInfo::argString },
75 #endif
76 { DCattach, "attach %s\n", GdbCmdInfo::argString },
77 { DCinfolinemain, "kdbg_infolinemain\n", GdbCmdInfo::argNone },
78 { DCinfolocals, "kdbg__alllocals\n", GdbCmdInfo::argNone },
79 { DCinforegisters, "info all-registers\n", GdbCmdInfo::argNone},
80 { DCexamine, "x %s %s\n", GdbCmdInfo::argString2 },
81 { DCinfoline, "info line %s:%d\n", GdbCmdInfo::argStringNum },
82 { DCdisassemble, "disassemble %s %s\n", GdbCmdInfo::argString2 },
83 { DCsetargs, "set args %s\n", GdbCmdInfo::argString },
84 { DCsetenv, "set env %s %s\n", GdbCmdInfo::argString2 },
85 { DCunsetenv, "unset env %s\n", GdbCmdInfo::argString },
86 { DCsetoption, "setoption %s %d\n", GdbCmdInfo::argStringNum},
87 { DCcd, "cd %s\n", GdbCmdInfo::argString },
88 { DCbt, "bt\n", GdbCmdInfo::argNone },
89 { DCrun, "run\n", GdbCmdInfo::argNone },
90 { DCcont, "cont\n", GdbCmdInfo::argNone },
91 { DCstep, "step\n", GdbCmdInfo::argNone },
92 { DCstepi, "stepi\n", GdbCmdInfo::argNone },
93 { DCnext, "next\n", GdbCmdInfo::argNone },
94 { DCnexti, "nexti\n", GdbCmdInfo::argNone },
95 { DCfinish, "finish\n", GdbCmdInfo::argNone },
96 { DCuntil, "until %s:%d\n", GdbCmdInfo::argStringNum },
97 { DCkill, "kill\n", GdbCmdInfo::argNone },
98 { DCdetach, "detach\n", GdbCmdInfo::argNone },
99 { DCbreaktext, "break %s\n", GdbCmdInfo::argString },
100 { DCbreakline, "break %s:%d\n", GdbCmdInfo::argStringNum },
101 { DCtbreakline, "tbreak %s:%d\n", GdbCmdInfo::argStringNum },
102 { DCbreakaddr, "break *%s\n", GdbCmdInfo::argString },
103 { DCtbreakaddr, "tbreak *%s\n", GdbCmdInfo::argString },
104 { DCwatchpoint, "watch %s\n", GdbCmdInfo::argString },
105 { DCdelete, "delete %d\n", GdbCmdInfo::argNum },
106 { DCenable, "enable %d\n", GdbCmdInfo::argNum },
107 { DCdisable, "disable %d\n", GdbCmdInfo::argNum },
108 { DCprint, "print %s\n", GdbCmdInfo::argString },
109 { DCprintDeref, "print *(%s)\n", GdbCmdInfo::argString },
110 { DCprintStruct, "print %s\n", GdbCmdInfo::argString },
111 { DCprintQStringStruct, printQStringStructFmt, GdbCmdInfo::argString},
112 { DCprintPopup, "print %s\n", GdbCmdInfo::argString },
113 { DCframe, "frame %d\n", GdbCmdInfo::argNum },
114 { DCfindType, "whatis %s\n", GdbCmdInfo::argString },
115 { DCinfosharedlib, "info sharedlibrary\n", GdbCmdInfo::argNone },
116 { DCthread, "thread %d\n", GdbCmdInfo::argNum },
117 { DCinfothreads, "info threads\n", GdbCmdInfo::argNone },
118 { DCinfobreak, "info breakpoints\n", GdbCmdInfo::argNone },
119 { DCcondition, "condition %d %s\n", GdbCmdInfo::argNumString},
120 { DCsetpc, "set variable $pc=%s\n", GdbCmdInfo::argString },
121 { DCignore, "ignore %d %d\n", GdbCmdInfo::argNum2},
122 { DCprintWChar, "print ($s=%s)?*$s@wcslen($s):0x0\n", GdbCmdInfo::argString },
123 { DCsetvariable, "set variable %s=%s\n", GdbCmdInfo::argString2 },
126 #define NUM_CMDS (int(sizeof(cmds)/sizeof(cmds[0])))
127 #define MAX_FMTLEN 200
129 GdbDriver::GdbDriver() :
130 DebuggerDriver()
132 #ifndef NDEBUG
133 // check command info array
134 const 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 * Sometimes, gdb prints [New Thread ...] during 'info threads';
240 * we will not look at thread events anyway, so turn them off.
242 "set print thread-events off\n"
244 * We do not want Python pretty printer support, because their
245 * output is unpredictable, and we cannot parse it.
247 "set auto-load python off\n"
249 * Nevertheless, some Python messages get through, for example,
250 * when a backtrace is printed without the Python gdb module loaded.
252 "set python print-stack none\n"
254 * Don't assume that program functions invoked from a watch expression
255 * always succeed.
257 "set unwindonsignal on\n"
259 * Write a short macro that prints all locals: local variables and
260 * function arguments.
262 "define kdbg__alllocals\n"
263 "info locals\n" /* local vars supersede args with same name */
264 "info args\n" /* therefore, arguments must come last */
265 "end\n"
267 * Work around a bug in gdb-6.3: "info line main" crashes gdb.
269 "define kdbg_infolinemain\n"
270 "list\n"
271 "info line\n"
272 "end\n"
273 // change prompt string and synchronize with gdb
274 "set prompt " PROMPT "\n"
277 executeCmdString(DCinitialize, gdbInitialize, false);
279 // assume that QString::null is ok
280 cmds[DCprintQStringStruct].fmt = printQStringStructFmt;
282 return true;
285 void GdbDriver::commandFinished(CmdQueueItem* cmd)
287 // command string must be committed
288 if (!cmd->m_committed) {
289 // not commited!
290 TRACE("calling " + (__PRETTY_FUNCTION__ + (" with uncommited command:\n\t" +
291 cmd->m_cmdString)));
292 return;
295 switch (cmd->m_cmd) {
296 case DCinitialize:
299 * Check for GDB 7.1 or later; the syntax for the disassemble
300 * command has changed.
301 * This RE picks the last version number in the first line,
302 * because at least OpenSUSE writes its own version number
303 * in the first line (but before GDB's version number).
305 QRegExp re(
306 " " // must be preceded by space
307 "[(]?" // SLES 10 embeds in parentheses
308 "(\\d+)\\.(\\d+)" // major, minor
309 "[^ ]*\\n" // no space until end of line
311 int pos = re.indexIn(m_output);
312 const char* disass = "disassemble %s %s\n";
313 if (pos >= 0) {
314 int major = re.cap(1).toInt();
315 int minor = re.cap(2).toInt();
316 if (major > 7 || (major == 7 && minor >= 1))
318 disass = "disassemble %s, %s\n";
321 cmds[DCdisassemble].fmt = disass;
323 break;
324 default:;
327 /* ok, the command is ready */
328 emit commandReceived(cmd, m_output.constData());
330 switch (cmd->m_cmd) {
331 case DCcorefile:
332 case DCinfolinemain:
333 case DCinfoline:
334 case DCframe:
335 case DCattach:
336 case DCrun:
337 case DCcont:
338 case DCstep:
339 case DCstepi:
340 case DCnext:
341 case DCnexti:
342 case DCfinish:
343 case DCuntil:
344 parseMarker(cmd);
345 default:;
349 int GdbDriver::findPrompt(const QByteArray& output) const
352 * If there's a prompt string in the collected output, it must be at
353 * the very end.
355 * Note: It could nevertheless happen that a character sequence that is
356 * equal to the prompt string appears at the end of the output,
357 * although it is very, very unlikely (namely as part of a string that
358 * lingered in gdb's output buffer due to some timing/heavy load
359 * conditions for a very long time such that that buffer overflowed
360 * exactly at the end of the prompt string look-a-like).
362 int len = output.length();
363 if (len >= PROMPT_LEN &&
364 strncmp(output.data()+len-PROMPT_LEN, PROMPT, PROMPT_LEN) == 0)
366 return len-PROMPT_LEN;
368 return -1;
372 * The --fullname option makes gdb send a special normalized sequence print
373 * each time the program stops and at some other points. The sequence has
374 * the form "\032\032filename:lineno:charoffset:(beg|middle):address".
376 void GdbDriver::parseMarker(CmdQueueItem* cmd)
378 char* startMarker = strstr(m_output.data(), "\032\032");
379 if (startMarker == 0)
380 return;
382 // extract the marker
383 startMarker += 2;
384 TRACE(QString("found marker: ") + startMarker);
385 char* endMarker = strchr(startMarker, '\n');
386 if (endMarker == 0)
387 return;
389 *endMarker = '\0';
391 // extract filename and line number
392 static QRegExp MarkerRE(":(\\d+):\\d+:[begmidl]+:0x");
394 int lineNoStart = MarkerRE.indexIn(startMarker);
395 if (lineNoStart >= 0) {
396 int lineNo = MarkerRE.cap(1).toInt();
398 // get address unless there is one in cmd
399 DbgAddr address = cmd->m_addr;
400 if (address.isEmpty()) {
401 const char* addrStart = startMarker + lineNoStart +
402 MarkerRE.matchedLength() - 2;
403 address = QString(addrStart).trimmed();
406 // now show the window
407 startMarker[lineNoStart] = '\0'; /* split off file name */
408 emit activateFileLine(startMarker, lineNo-1, address);
414 * Escapes characters that might lead to problems when they appear on gdb's
415 * command line.
417 static void normalizeStringArg(QString& arg)
420 * Remove trailing backslashes. This approach is a little simplistic,
421 * but we know that there is at the moment no case where a trailing
422 * backslash would make sense.
424 while (!arg.isEmpty() && arg[arg.length()-1] == '\\') {
425 arg = arg.left(arg.length()-1);
430 QString GdbDriver::makeCmdString(DbgCommand cmd, QString strArg)
432 assert(cmd >= 0 && cmd < NUM_CMDS);
433 assert(cmds[cmd].argsNeeded == GdbCmdInfo::argString);
435 normalizeStringArg(strArg);
437 if (cmd == DCcd) {
438 // need the working directory when parsing the output
439 m_programWD = strArg;
440 } else if (cmd == DCsetargs && !m_redirect.isEmpty()) {
442 * Use saved redirection. We prepend it in front of the user's
443 * arguments so that the user can override the redirections.
445 strArg = m_redirect + " " + strArg;
448 QString cmdString;
449 cmdString.sprintf(cmds[cmd].fmt, strArg.toUtf8().constData());
450 return cmdString;
453 QString GdbDriver::makeCmdString(DbgCommand cmd, int intArg)
455 assert(cmd >= 0 && cmd < NUM_CMDS);
456 assert(cmds[cmd].argsNeeded == GdbCmdInfo::argNum);
458 QString cmdString;
459 cmdString.sprintf(cmds[cmd].fmt, intArg);
460 return cmdString;
463 QString GdbDriver::makeCmdString(DbgCommand cmd, QString strArg, int intArg)
465 assert(cmd >= 0 && cmd < NUM_CMDS);
466 assert(cmds[cmd].argsNeeded == GdbCmdInfo::argStringNum ||
467 cmds[cmd].argsNeeded == GdbCmdInfo::argNumString ||
468 cmd == DCexamine ||
469 cmd == DCtty);
471 normalizeStringArg(strArg);
473 QString cmdString;
475 if (cmd == DCtty)
478 * intArg specifies which channels should be redirected to
479 * /dev/null. It is a value or'ed together from RDNstdin,
480 * RDNstdout, RDNstderr. We store the value for a later DCsetargs
481 * command.
483 * Note: We rely on that after the DCtty a DCsetargs will follow,
484 * which will ultimately apply the redirection.
486 static const char* const runRedir[8] = {
488 "</dev/null",
489 ">/dev/null",
490 "</dev/null >/dev/null",
491 "2>/dev/null",
492 "</dev/null 2>/dev/null",
493 ">/dev/null 2>&1",
494 "</dev/null >/dev/null 2>&1"
496 if (strArg.isEmpty())
497 intArg = 7; /* failsafe if no tty */
498 m_redirect = runRedir[intArg & 7];
500 return makeCmdString(DCtty, strArg); /* note: no problem if strArg empty */
503 if (cmd == DCexamine) {
504 // make a format specifier from the intArg
505 static const char size[16] = {
506 '\0', 'b', 'h', 'w', 'g'
508 static const char format[16] = {
509 '\0', 'x', 'd', 'u', 'o', 't',
510 'a', 'c', 'f', 's', 'i'
512 assert(MDTsizemask == 0xf); /* lowest 4 bits */
513 assert(MDTformatmask == 0xf0); /* next 4 bits */
514 int count = 16; /* number of entities to print */
515 char sizeSpec = size[intArg & MDTsizemask];
516 char formatSpec = format[(intArg & MDTformatmask) >> 4];
517 assert(sizeSpec != '\0');
518 assert(formatSpec != '\0');
519 // adjust count such that 16 lines are printed
520 switch (intArg & MDTformatmask) {
521 case MDTstring: case MDTinsn:
522 break; /* no modification needed */
523 default:
524 // all cases drop through:
525 switch (intArg & MDTsizemask) {
526 case MDTbyte:
527 case MDThalfword:
528 count *= 2;
529 case MDTword:
530 count *= 2;
531 case MDTgiantword:
532 count *= 2;
534 break;
536 QString spec;
537 spec.sprintf("/%d%c%c", count, sizeSpec, formatSpec);
539 return makeCmdString(DCexamine, spec, strArg);
542 if (cmds[cmd].argsNeeded == GdbCmdInfo::argStringNum)
544 // line numbers are zero-based
545 if (cmd == DCuntil || cmd == DCbreakline ||
546 cmd == DCtbreakline || cmd == DCinfoline)
548 intArg++;
550 if (cmd == DCinfoline)
552 // must split off file name part
553 strArg = QFileInfo(strArg).fileName();
555 cmdString.sprintf(cmds[cmd].fmt, strArg.toUtf8().constData(), intArg);
557 else
559 cmdString.sprintf(cmds[cmd].fmt, intArg, strArg.toUtf8().constData());
561 return cmdString;
564 QString GdbDriver::makeCmdString(DbgCommand cmd, QString strArg1, QString strArg2)
566 assert(cmd >= 0 && cmd < NUM_CMDS);
567 assert(cmds[cmd].argsNeeded == GdbCmdInfo::argString2);
569 normalizeStringArg(strArg1);
570 normalizeStringArg(strArg2);
572 QString cmdString;
573 cmdString.sprintf(cmds[cmd].fmt,
574 strArg1.toUtf8().constData(),
575 strArg2.toUtf8().constData());
576 return cmdString;
579 QString GdbDriver::makeCmdString(DbgCommand cmd, int intArg1, int intArg2)
581 assert(cmd >= 0 && cmd < NUM_CMDS);
582 assert(cmds[cmd].argsNeeded == GdbCmdInfo::argNum2);
584 QString cmdString;
585 cmdString.sprintf(cmds[cmd].fmt, intArg1, intArg2);
586 return cmdString;
589 CmdQueueItem* GdbDriver::executeCmd(DbgCommand cmd, bool clearLow)
591 assert(cmd >= 0 && cmd < NUM_CMDS);
592 assert(cmds[cmd].argsNeeded == GdbCmdInfo::argNone);
594 if (cmd == DCrun) {
595 m_haveCoreFile = false;
598 return executeCmdString(cmd, cmds[cmd].fmt, clearLow);
601 CmdQueueItem* GdbDriver::executeCmd(DbgCommand cmd, QString strArg,
602 bool clearLow)
604 return executeCmdString(cmd, makeCmdString(cmd, strArg), clearLow);
607 CmdQueueItem* GdbDriver::executeCmd(DbgCommand cmd, int intArg,
608 bool clearLow)
611 return executeCmdString(cmd, makeCmdString(cmd, intArg), clearLow);
614 CmdQueueItem* GdbDriver::executeCmd(DbgCommand cmd, QString strArg, int intArg,
615 bool clearLow)
617 return executeCmdString(cmd, makeCmdString(cmd, strArg, intArg), clearLow);
620 CmdQueueItem* GdbDriver::executeCmd(DbgCommand cmd, QString strArg1, QString strArg2,
621 bool clearLow)
623 return executeCmdString(cmd, makeCmdString(cmd, strArg1, strArg2), clearLow);
626 CmdQueueItem* GdbDriver::executeCmd(DbgCommand cmd, int intArg1, int intArg2,
627 bool clearLow)
629 return executeCmdString(cmd, makeCmdString(cmd, intArg1, intArg2), clearLow);
632 CmdQueueItem* GdbDriver::queueCmd(DbgCommand cmd, QueueMode mode)
634 return queueCmdString(cmd, cmds[cmd].fmt, mode);
637 CmdQueueItem* GdbDriver::queueCmd(DbgCommand cmd, QString strArg,
638 QueueMode mode)
640 return queueCmdString(cmd, makeCmdString(cmd, strArg), mode);
643 CmdQueueItem* GdbDriver::queueCmd(DbgCommand cmd, int intArg,
644 QueueMode mode)
646 return queueCmdString(cmd, makeCmdString(cmd, intArg), mode);
649 CmdQueueItem* GdbDriver::queueCmd(DbgCommand cmd, QString strArg, int intArg,
650 QueueMode mode)
652 return queueCmdString(cmd, makeCmdString(cmd, strArg, intArg), mode);
655 CmdQueueItem* GdbDriver::queueCmd(DbgCommand cmd, QString strArg1, QString strArg2,
656 QueueMode mode)
658 return queueCmdString(cmd, makeCmdString(cmd, strArg1, strArg2), mode);
661 void GdbDriver::terminate()
663 if (m_state != DSidle)
665 ::kill(pid(), SIGINT);
666 m_state = DSinterrupted;
668 flushCommands();
669 closeWriteChannel();
672 void GdbDriver::detachAndTerminate()
674 ::kill(pid(), SIGINT);
675 flushCommands();
676 executeCmdString(DCinitialize, "detach\nquit\n", true);
679 void GdbDriver::interruptInferior()
681 ::kill(pid(), SIGINT);
682 // remove accidentally queued commands
683 flushHiPriQueue();
686 static bool isErrorExpr(const char* output)
688 return
689 strncmp(output, "Cannot access memory at", 23) == 0 ||
690 strncmp(output, "Attempt to dereference a generic pointer", 40) == 0 ||
691 strncmp(output, "Attempt to take contents of ", 28) == 0 ||
692 strncmp(output, "Attempt to use a type name as an expression", 43) == 0 ||
693 strncmp(output, "There is no member or method named", 34) == 0 ||
694 strncmp(output, "A parse error in expression", 27) == 0 ||
695 strncmp(output, "No symbol \"", 11) == 0 ||
696 strncmp(output, "Internal error: ", 16) == 0;
699 static void skipSpace(const char*& p)
701 while (isspace(*p))
702 p++;
705 static void skipDecimal(const char*& p)
707 while (isdigit(*p))
708 p++;
712 * Returns true if the output is an error message. If wantErrorValue is
713 * true, a new ExprValue object is created and filled with the error message.
714 * If there are warnings, they are skipped and output points past the warnings
715 * on return (even if there \e are errors).
717 static bool parseErrorMessage(const char*& output,
718 ExprValue*& variable, bool wantErrorValue)
720 skipSpace(output);
722 // skip warnings
723 while (strncmp(output, "warning:", 8) == 0)
725 const char* end = strchr(output+8, '\n');
726 if (end == 0)
727 output += strlen(output);
728 else
729 output = end+1;
730 skipSpace(output);
733 if (isErrorExpr(output))
735 if (wantErrorValue) {
736 // put the error message as value in the variable
737 variable = new ExprValue(QString(), VarTree::NKplain);
738 const char* endMsg = strchr(output, '\n');
739 if (endMsg == 0)
740 endMsg = output + strlen(output);
741 variable->m_value = QString::fromLatin1(output, endMsg-output);
742 } else {
743 variable = 0;
745 return true;
747 return false;
750 #if QT_VERSION >= 300
751 union Qt2QChar {
752 short s;
753 struct {
754 uchar row;
755 uchar cell;
756 } qch;
758 #endif
760 void GdbDriver::setPrintQStringDataCmd(const char* cmd)
762 // don't accept the command if it is empty
763 if (cmd == 0 || *cmd == '\0')
764 return;
765 assert(strlen(cmd) <= MAX_FMTLEN);
766 cmds[DCprintQStringStruct].fmt = cmd;
769 ExprValue* GdbDriver::parseQCharArray(const char* output, bool wantErrorValue, bool qt3like)
771 ExprValue* variable = 0;
774 * Parse off white space. gdb sometimes prints white space first if the
775 * printed array leaded to an error.
777 skipSpace(output);
779 // special case: empty string (0 repetitions)
780 if (strncmp(output, "Invalid number 0 of repetitions", 31) == 0)
782 variable = new ExprValue(QString(), VarTree::NKplain);
783 variable->m_value = "\"\"";
784 return variable;
787 // check for error conditions
788 if (parseErrorMessage(output, variable, wantErrorValue))
789 return variable;
791 // parse the array
793 // find '='
794 const char* p = output;
795 p = strchr(p, '=');
796 if (p == 0) {
797 goto error;
799 p++;
800 skipSpace(p);
802 if (*p == '{')
804 // this is the real data
805 p++; /* skip '{' */
807 // parse the array
808 QString result;
809 QString repeatCount;
810 enum { wasNothing, wasChar, wasRepeat } lastThing = wasNothing;
812 * A matrix for separators between the individual "things"
813 * that are added to the string. The first index is a bool,
814 * the second index is from the enum above.
816 static const char* separator[2][3] = {
817 { "\"", 0, ", \"" }, /* normal char is added */
818 { "'", "\", '", ", '" } /* repeated char is added */
821 while (isdigit(*p)) {
822 // parse a number
823 char* end;
824 unsigned short value = (unsigned short) strtoul(p, &end, 0);
825 if (end == p)
826 goto error; /* huh? no valid digits */
827 // skip separator and search for a repeat count
828 p = end;
829 while (isspace(*p) || *p == ',')
830 p++;
831 bool repeats = strncmp(p, "<repeats ", 9) == 0;
832 if (repeats) {
833 const char* start = p;
834 p = strchr(p+9, '>'); /* search end and advance */
835 if (p == 0)
836 goto error;
837 p++; /* skip '>' */
838 repeatCount = QString::fromLatin1(start, p-start);
839 while (isspace(*p) || *p == ',')
840 p++;
842 // p is now at the next char (or the end)
844 // interpret the value as a QChar
845 // TODO: make cross-architecture compatible
846 QChar ch;
847 if (qt3like) {
848 ch = QChar(value);
849 } else {
850 #if QT_VERSION < 300
851 (unsigned short&)ch = value;
852 #else
853 Qt2QChar c;
854 c.s = value;
855 ch.setRow(c.qch.row);
856 ch.setCell(c.qch.cell);
857 #endif
860 // escape a few frequently used characters
861 char escapeCode = '\0';
862 switch (ch.toLatin1()) {
863 case '\n': escapeCode = 'n'; break;
864 case '\r': escapeCode = 'r'; break;
865 case '\t': escapeCode = 't'; break;
866 case '\b': escapeCode = 'b'; break;
867 case '\"': escapeCode = '\"'; break;
868 case '\\': escapeCode = '\\'; break;
869 case '\0': if (value == 0) { escapeCode = '0'; } break;
872 // add separator
873 result += separator[repeats][lastThing];
874 // add char
875 if (escapeCode != '\0') {
876 result += '\\';
877 ch = escapeCode;
879 result += ch;
881 // fixup repeat count and lastThing
882 if (repeats) {
883 result += "' ";
884 result += repeatCount;
885 lastThing = wasRepeat;
886 } else {
887 lastThing = wasChar;
890 if (*p != '}')
891 goto error;
893 // closing quote
894 if (lastThing == wasChar)
895 result += "\"";
897 // assign the value
898 variable = new ExprValue(QString(), VarTree::NKplain);
899 variable->m_value = result;
901 else if (strncmp(p, "true", 4) == 0)
903 variable = new ExprValue(QString(), VarTree::NKplain);
904 variable->m_value = "QString::null";
906 else if (strncmp(p, "false", 5) == 0)
908 variable = new ExprValue(QString(), VarTree::NKplain);
909 variable->m_value = "(null)";
911 else
912 goto error;
913 return variable;
915 error:
916 if (wantErrorValue) {
917 variable = new ExprValue(QString(), VarTree::NKplain);
918 variable->m_value = "internal parse error";
920 return variable;
923 static ExprValue* parseVar(const char*& s)
925 const char* p = s;
927 skipSpace(p);
929 QString name;
930 VarTree::NameKind kind;
932 * Detect anonymouse struct values: The 'name =' part is missing:
933 * s = { a = 1, { b = 2 }}
934 * Note that this detection works only inside structs when the anonymous
935 * struct is not the first member:
936 * s = {{ a = 1 }, b = 2}
937 * This is misparsed (by parseNested()) because it is mistakenly
938 * interprets the second opening brace as the first element of an array
939 * of structs.
941 if (*p == '{')
943 name = i18n("<anonymous struct or union>");
944 kind = VarTree::NKanonymous;
946 else
948 if (!parseName(p, name, kind)) {
949 return 0;
952 // go for '='
953 skipSpace(p);
954 if (*p != '=') {
955 TRACE("parse error: = not found after " + name);
956 return 0;
958 // skip the '=' and more whitespace
959 p++;
960 skipSpace(p);
963 ExprValue* variable = new ExprValue(name, kind);
965 if (!parseValue(p, variable)) {
966 delete variable;
967 return 0;
969 s = p;
970 return variable;
973 static void skipNested(const char*& s, char opening, char closing)
975 const char* p = s;
977 // parse a nested type
978 int nest = 1;
979 p++;
981 * Search for next matching `closing' char, skipping nested pairs of
982 * `opening' and `closing'.
984 while (*p && nest > 0) {
985 if (*p == opening) {
986 nest++;
987 } else if (*p == closing) {
988 nest--;
990 p++;
992 if (nest != 0) {
993 TRACE(QString().sprintf("parse error: mismatching %c%c at %-20.20s", opening, closing, s));
995 s = p;
999 * This function skips text that is delimited by nested angle bracktes, '<>'.
1000 * A complication arises because the delimited text can contain the names of
1001 * operator<<, operator>>, operator<, and operator>, which have to be treated
1002 * specially so that they do not count towards the nesting of '<>'.
1003 * This function assumes that the delimited text does not contain strings.
1005 static void skipNestedAngles(const char*& s)
1007 const char* p = s;
1009 int nest = 1;
1010 p++; // skip the initial '<'
1011 while (*p && nest > 0)
1013 // Below we can check for p-s >= 9 instead of 8 because
1014 // *s is '<' and cannot be part of "operator".
1015 if (*p == '<')
1017 if (p-s >= 9 && strncmp(p-8, "operator", 8) == 0) {
1018 if (p[1] == '<')
1019 p++;
1020 } else {
1021 nest++;
1024 else if (*p == '>')
1026 if (p-s >= 9 && strncmp(p-8, "operator", 8) == 0) {
1027 if (p[1] == '>')
1028 p++;
1029 } else {
1030 nest--;
1033 p++;
1035 if (nest != 0) {
1036 TRACE(QString().sprintf("parse error: mismatching <> at %-20.20s", s));
1038 s = p;
1042 * Find the end of line that is not inside braces
1044 static void findEnd(const char*& s)
1046 const char* p = s;
1047 while (*p && *p!='\n') {
1048 while (*p && *p!='\n' && *p!='{')
1049 p++;
1050 if (*p=='{') {
1051 p++;
1052 skipNested(p, '{', '}'); p--;
1055 s = p;
1058 static bool isNumberish(const char ch)
1060 return (ch>='0' && ch<='9') || ch=='.' || ch=='x';
1063 void skipString(const char*& p)
1065 // wchar_t strings begin with L
1066 if (*p == 'L')
1067 ++p;
1069 moreStrings:
1070 // opening quote
1071 char quote = *p++;
1072 while (*p != quote) {
1073 if (*p == '\\') {
1074 // skip escaped character
1075 // no special treatment for octal values necessary
1076 p++;
1078 // simply return if no more characters
1079 if (*p == '\0')
1080 return;
1081 p++;
1083 // closing quote
1084 p++;
1086 * Strings can consist of several parts, some of which contain repeated
1087 * characters.
1089 if (quote == '\'') {
1090 // look ahaead for <repeats 123 times>
1091 const char* q = p+1;
1092 skipSpace(q);
1093 if (strncmp(q, "<repeats ", 9) == 0) {
1094 p = q+9;
1095 while (*p != '\0' && *p != '>')
1096 p++;
1097 if (*p != '\0') {
1098 p++; /* skip the '>' */
1102 // Is the string continued? If so, there is no L in wchar_t strings
1103 if (*p == ',')
1105 // look ahead for another quote
1106 const char* q = p+1;
1107 skipSpace(q);
1108 if (*q == '"' || *q == '\'') {
1109 // yes!
1110 p = q;
1111 goto moreStrings;
1114 // some strings can end in <incomplete sequence ...>
1115 if (strncmp(q, "<incomplete sequence", 20) == 0)
1117 p = q+20;
1118 while (*p != '\0' && *p != '>')
1119 p++;
1120 if (*p != '\0') {
1121 p++; /* skip the '>' */
1126 * There's a bug in gdb where it prints the beginning of the string
1127 * continuation and the comma-blank in the wrong order if the new string
1128 * begins with an incomplete multi-byte character. For now, let's check
1129 * for this in a very narrow condition, particularly, where the next
1130 * character is given in octal notation. Example:
1131 * 'a' <repeats 20 times>"\240, b"
1133 if (*p == '"' && p[1] == '\\' && isdigit(p[2])) {
1134 int i = 3;
1135 while (isdigit(p[i]))
1136 ++i;
1137 if (p[i] == ',' && p[i+1] == ' ') {
1138 // just treat everything beginning at the dquote as string
1139 goto moreStrings;
1142 /* very long strings are followed by `...' */
1143 if (*p == '.' && p[1] == '.' && p[2] == '.') {
1144 p += 3;
1148 static void skipNestedWithString(const char*& s, char opening, char closing)
1150 const char* p = s;
1152 // parse a nested expression
1153 int nest = 1;
1154 p++;
1156 * Search for next matching `closing' char, skipping nested pairs of
1157 * `opening' and `closing' as well as strings.
1159 while (*p && nest > 0) {
1160 if (*p == opening) {
1161 nest++;
1162 } else if (*p == closing) {
1163 nest--;
1164 } else if (*p == '\'' || *p == '\"') {
1165 skipString(p);
1166 continue;
1168 p++;
1170 if (nest > 0) {
1171 TRACE(QString().sprintf("parse error: mismatching %c%c at %-20.20s", opening, closing, s));
1173 s = p;
1176 static void skipName(const char*& p)
1178 // allow : (for enumeration values) and $ and . (for _vtbl.)
1179 while (isalnum(*p) || *p == '_' || *p == ':' || *p == '$' || *p == '.')
1180 p++;
1183 static void skipFunctionName(const char*& p)
1185 while (*p)
1187 if (*p == '<') {
1188 // skip template parameter list
1189 skipNestedAngles(p);
1190 } else if (*p == '(') {
1191 // this skips "(anonymous namespace)" as well as the formal
1192 // parameter list of the containing function if this is a member
1193 // of a nested class
1194 skipNestedWithString(p, '(', ')');
1195 } else if (isalnum(*p) || *p == '_' || *p == ':') {
1196 const char* start = p;
1197 skipName(p);
1198 // check for operator
1199 if (p-start >= 8 &&
1200 strncmp(p-8, "operator", 8) == 0 &&
1201 // do not mistake this as the tail of some identifier
1202 (p-start == 8 || !(isalnum(p[-9]) || p[-9] == '_')))
1204 // skip forward until we find the opening parenthesis
1205 // this catches both operator()(...) as well as
1206 // type conversion operators, e.g.
1207 // operator char const*() const
1208 // operator void(*)()
1209 while (*p && *p != '(')
1210 p++;
1212 } else if (strncmp(p, " const", 6) == 0 &&
1213 // must not mistake "const" as the beginning of
1214 // a subequent identifier
1215 !isalnum(p[6]) && p[6] != '_') {
1216 p += 6;
1217 } else {
1218 break;
1223 static bool parseName(const char*& s, QString& name, VarTree::NameKind& kind)
1225 kind = VarTree::NKplain;
1227 const char* p = s;
1228 // examples of names:
1229 // name
1230 // <Object>
1231 // <string<a,b<c>,7> >
1233 if (*p == '<') {
1234 skipNestedAngles(p);
1235 name = QString::fromLatin1(s, p - s);
1236 kind = VarTree::NKtype;
1238 else
1240 // name, which might be "static"; allow dot for "_vtbl."
1241 skipName(p);
1242 if (p == s) {
1243 TRACE(QString().sprintf("parse error: not a name %-20.20s", s));
1244 return false;
1246 int len = p - s;
1247 if (len == 6 && strncmp(s, "static", 6) == 0) {
1248 kind = VarTree::NKstatic;
1250 // its a static variable, name comes now
1251 skipSpace(p);
1252 s = p;
1253 skipName(p);
1254 if (p == s) {
1255 TRACE(QString().sprintf("parse error: not a name after static %-20.20s", s));
1256 return false;
1258 len = p - s;
1260 name = QString::fromLatin1(s, len);
1262 // return the new position
1263 s = p;
1264 return true;
1267 static bool parseValue(const char*& s, ExprValue* variable)
1269 variable->m_value = "";
1271 repeat:
1272 if (*s == '{') {
1273 // Sometimes we find the following output:
1274 // {<text variable, no debug info>} 0x40012000 <access>
1275 // {<data variable, no debug info>}
1276 // {<variable (not text or data), no debug info>}
1277 if (strncmp(s, "{<text variable, ", 17) == 0 ||
1278 strncmp(s, "{<data variable, ", 17) == 0 ||
1279 strncmp(s, "{<variable (not text or data), ", 31) == 0)
1281 const char* start = s;
1282 skipNested(s, '{', '}');
1283 variable->m_value = QString::fromLatin1(start, s-start);
1284 variable->m_value += ' '; // add only a single space
1285 skipSpace(s);
1286 goto repeat;
1288 else
1290 s++;
1291 if (!parseNested(s, variable)) {
1292 return false;
1294 // must be the closing brace
1295 if (*s != '}') {
1296 TRACE("parse error: missing } of " + variable->m_name);
1297 return false;
1299 s++;
1300 // final white space
1301 skipSpace(s);
1304 // Sometimes we find a warning; it ends at the next LF
1305 else if (strncmp(s, "warning: ", 9) == 0) {
1306 const char* end = strchr(s, '\n');
1307 s = end ? end : s+strlen(s);
1308 // skip space at start of next line
1309 skipSpace(s);
1310 goto repeat;
1311 } else {
1312 // examples of leaf values (cannot be the empty string):
1313 // 123
1314 // -123
1315 // 23.575e+37
1316 // 0x32a45
1317 // @0x012ab4
1318 // (DwContentType&) @0x8123456: {...}
1319 // 0x32a45 "text"
1320 // 10 '\n'
1321 // <optimized out>
1322 // 0x823abc <Array<int> virtual table>
1323 // 0x40240f <globarstr> "test"
1324 // (void (*)()) 0x8048480 <f(E *, char)>
1325 // (E *) 0xbffff450
1326 // red
1327 // &parseP (HTMLClueV *, char *)
1328 // &virtual table offset 0, this adjustment 140737488346016
1329 // &virtual Dl::operator char const*() const
1330 // Variable "x" is not available.
1331 // The value of variable 'x' is distributed...
1332 // -nan(0xfffff081defa0)
1333 // @0x100400f08: <error reading variable>
1334 // (void (Templated<double>::*)(Templated<double> * const)) 0x400d74 <MostDerived::PrintV()>, this adjustment -16
1336 const char*p = s;
1338 // check for type
1339 QString type;
1340 if (*p == '(') {
1341 skipNested(p, '(', ')');
1343 skipSpace(p);
1344 variable->m_value = QString::fromLatin1(s, p - s);
1347 bool reference = false;
1348 if (*p == '@') {
1349 // skip reference marker
1350 p++;
1351 reference = true;
1353 const char* start = p;
1354 if (*p == '-')
1355 p++;
1357 // some values consist of more than one token
1358 bool checkMultiPart = false;
1360 if (p[0] == '0' && p[1] == 'x') {
1361 // parse hex number
1362 p += 2;
1363 while (isxdigit(*p))
1364 p++;
1367 * Assume this is a pointer, but only if it's not a reference, since
1368 * references can't be expanded.
1370 if (!reference) {
1371 variable->m_varKind = VarTree::VKpointer;
1372 } else {
1374 * References are followed by a colon, in which case we'll
1375 * find the value following the reference address.
1377 if (*p == ':') {
1378 p++;
1379 } else {
1380 // Paranoia. (Can this happen, i.e. reference not followed by ':'?)
1381 reference = false;
1384 checkMultiPart = true;
1385 } else if (isdigit(*p)) {
1386 // parse decimal number, possibly a float
1387 skipDecimal(p);
1388 if (*p == '.') { /* TODO: obey i18n? */
1389 // In long arrays an integer may be followed by '...'.
1390 // We test for this situation and don't gobble the '...'.
1391 if (p[1] != '.' || p[0] != '.') {
1392 // fractional part
1393 p++;
1394 skipDecimal(p);
1397 if (*p == 'e' || *p == 'E') {
1398 p++;
1399 // exponent
1400 if (*p == '-' || *p == '+')
1401 p++;
1402 skipDecimal(p);
1405 // for char variables there is the char, eg. 10 '\n'
1406 checkMultiPart = true;
1407 } else if (*p == '<') {
1408 // e.g. <optimized out>
1409 skipNestedAngles(p);
1410 } else if (*p == '"' || *p == '\'') {
1411 // character may have multipart: '\000' <repeats 11 times>
1412 checkMultiPart = *p == '\'';
1413 // found a string
1414 skipString(p);
1415 } else if (*p == 'L' && (p[1] == '"' || p[1] == '\'')) {
1416 // ditto for wchar_t strings
1417 checkMultiPart = p[1] == '\'';
1418 skipString(p);
1419 } else if (*p == '&') {
1420 p++;
1421 if (strncmp(p, "virtual ", 8) == 0) {
1422 p += 8;
1423 if (strncmp(p, "table offset ", 13) == 0) {
1424 p += 13;
1425 skipDecimal(p);
1426 checkMultiPart = true;
1427 } else {
1428 skipFunctionName(p);
1430 } else {
1431 // function pointer
1432 skipName(p);
1433 skipSpace(p);
1434 if (*p == '(') {
1435 skipNested(p, '(', ')');
1438 } else if (strncmp(p, "Variable \"", 10) == 0) {
1439 // Variable "x" is not available.
1440 p += 10; // skip to "
1441 skipName(p);
1442 if (strncmp(p, "\" is not available.", 19) == 0) {
1443 p += 19;
1445 } else if (strncmp(p, "The value of variable '", 23) == 0) {
1446 p += 23;
1447 skipName(p);
1448 const char* e = strchr(p, '.');
1449 if (e == 0) {
1450 p += strlen(p);
1451 } else {
1452 p = e+1;
1454 } else {
1455 moreEnum:
1456 // must be an enumeration value
1457 skipName(p);
1458 // nan (floating point Not a Number) is followed by a number in ()
1459 // enum values can look like A::(anonymous namespace)::blue
1460 if (*p == '(') {
1461 bool isAnonNS = strncmp(p+1, "anonymous namespace)", 20) == 0;
1462 skipNested(p, '(', ')');
1463 if (isAnonNS)
1464 goto moreEnum;
1467 variable->m_value += QString::fromLatin1(start, p - start);
1469 // remove line breaks from the value; this is ok since
1470 // string values never contain a literal line break
1471 variable->m_value.replace('\n', ' ');
1473 while (checkMultiPart) {
1474 // white space
1475 skipSpace(p);
1476 // may be followed by a string or <...>
1477 // if this was a pointer with a string,
1478 // reset that pointer flag since we have now a value
1479 start = p;
1480 checkMultiPart = false;
1482 if (*p == '"' || *p == '\'') {
1483 skipString(p);
1484 variable->m_varKind = VarTree::VKsimple;
1485 } else if (*p == 'L' && (p[1] == '"' || p[1] == '\'')) {
1486 skipString(p); // wchar_t string
1487 variable->m_varKind = VarTree::VKsimple;
1488 } else if (*p == '<') {
1489 // if this value is part of an array, it might be followed
1490 // by <repeats 15 times>, which we don't skip here
1491 if (strncmp(p, "<repeats ", 9) == 0)
1493 // sometimes, a reference is followed by an error message:
1494 // @0x100400f08: <error reading variable>
1495 // in this case, we do not skip the text here, but leave it
1496 // for the subsequent parsing pass induced by the reference
1497 else if (reference && strncmp(p, "<error reading", 14) == 0)
1499 else {
1500 skipNestedAngles(p);
1501 checkMultiPart = true;
1503 } else if (strncmp(p, ", this adjustment ", 18) == 0) {
1504 // pointers-to-member are sometimes followed by
1505 // a "this adjustment" hint
1506 p += 18;
1507 if (*p == '-')
1508 p++;
1509 skipDecimal(p);
1510 // we know that this is not a dereferencable pointer
1511 variable->m_varKind = VarTree::VKsimple;
1512 ++start; // skip ',', will be picked up below
1514 if (p != start) {
1515 // there is always a blank before the string,
1516 // which we will include in the final string value
1517 variable->m_value += QString::fromLatin1(start-1, (p - start)+1);
1521 if (variable->m_value.length() == 0) {
1522 TRACE("parse error: no value for " + variable->m_name);
1523 return false;
1526 // final white space
1527 skipSpace(p);
1528 s = p;
1531 * If this was a reference, the value follows. It might even be a
1532 * composite variable!
1534 if (reference) {
1535 goto repeat;
1539 return true;
1542 static bool parseNested(const char*& s, ExprValue* variable)
1544 // could be a structure or an array
1545 skipSpace(s);
1547 const char* p = s;
1548 bool isStruct = false;
1550 * If there is a name followed by an = or an < -- which starts a type
1551 * name -- or "static", it is a structure
1553 if (*p == '<' || *p == '}') {
1554 isStruct = true;
1555 } else if (strncmp(p, "static ", 7) == 0) {
1556 isStruct = true;
1557 } else if (isalpha(*p) || *p == '_' || *p == '$') {
1558 // look ahead for a comma after the name
1559 skipName(p);
1560 skipSpace(p);
1561 if (*p == '=') {
1562 isStruct = true;
1564 p = s; /* rescan the name */
1566 if (isStruct) {
1567 if (!parseVarSeq(p, variable)) {
1568 return false;
1570 variable->m_varKind = VarTree::VKstruct;
1571 } else {
1572 if (!parseValueSeq(p, variable)) {
1573 return false;
1575 variable->m_varKind = VarTree::VKarray;
1577 s = p;
1578 return true;
1581 static bool parseVarSeq(const char*& s, ExprValue* variable)
1583 // parse a comma-separated sequence of variables
1584 ExprValue* var = variable; /* var != 0 to indicate success if empty seq */
1585 for (;;) {
1586 if (*s == '}')
1587 break;
1588 if (strncmp(s, "<No data fields>}", 17) == 0)
1590 // no member variables, so break out immediately
1591 s += 16; /* go to the closing brace */
1592 break;
1594 var = parseVar(s);
1595 if (var == 0)
1596 break; /* syntax error */
1597 variable->appendChild(var);
1598 if (*s != ',')
1599 break;
1600 // skip the comma and whitespace
1601 s++;
1602 skipSpace(s);
1604 return var != 0;
1607 static bool parseValueSeq(const char*& s, ExprValue* variable)
1609 // parse a comma-separated sequence of variables
1610 int index = 0;
1611 bool good;
1612 for (;;) {
1613 QString name;
1614 name.sprintf("[%d]", index);
1615 ExprValue* var = new ExprValue(name, VarTree::NKplain);
1616 good = parseValue(s, var);
1617 if (!good) {
1618 delete var;
1619 return false;
1621 // a value may be followed by "<repeats 45 times>"
1622 if (strncmp(s, "<repeats ", 9) == 0) {
1623 s += 9;
1624 char* end;
1625 int l = strtol(s, &end, 10);
1626 if (end == s || strncmp(end, " times>", 7) != 0) {
1627 // should not happen
1628 delete var;
1629 return false;
1631 TRACE(QString().sprintf("found <repeats %d times> in array", l));
1632 // replace name and advance index
1633 name.sprintf("[%d .. %d]", index, index+l-1);
1634 var->m_name = name;
1635 index += l;
1636 // skip " times>" and space
1637 s = end+7;
1638 // possible final space
1639 skipSpace(s);
1640 } else {
1641 index++;
1643 variable->appendChild(var);
1644 // long arrays may be terminated by '...'
1645 if (strncmp(s, "...", 3) == 0) {
1646 s += 3;
1647 ExprValue* var = new ExprValue("...", VarTree::NKplain);
1648 var->m_value = i18n("<additional entries of the array suppressed>");
1649 variable->appendChild(var);
1650 break;
1652 if (*s != ',') {
1653 break;
1655 // skip the comma and whitespace
1656 s++;
1657 skipSpace(s);
1658 // sometimes there is a closing brace after a comma
1659 // if (*s == '}')
1660 // break;
1662 return true;
1666 * Parses a stack frame.
1668 static void parseFrameInfo(const char*& s, QString& func,
1669 QString& file, int& lineNo, DbgAddr& address)
1671 const char* p = s;
1673 // next may be a hexadecimal address
1674 if (*p == '0') {
1675 const char* start = p;
1676 p++;
1677 if (*p == 'x')
1678 p++;
1679 while (isxdigit(*p))
1680 p++;
1681 address = QString::fromLatin1(start, p-start);
1682 if (strncmp(p, " in ", 4) == 0)
1683 p += 4;
1684 } else {
1685 address = DbgAddr();
1687 const char* start = p;
1688 // check for special signal handler frame
1689 if (strncmp(p, "<signal handler called>", 23) == 0) {
1690 func = QString::fromLatin1(start, 23);
1691 file = QString();
1692 lineNo = -1;
1693 s = p+23;
1694 if (*s == '\n')
1695 s++;
1696 return;
1700 * Skip the function name. It is terminated by a left parenthesis
1701 * which does not delimit "(anonymous namespace)" and which is
1702 * outside the angle brackets <> of template parameter lists
1703 * and is preceded by a space.
1705 while (*p != '\0')
1707 if (*p == '<') {
1708 // check for operator<< and operator<
1709 if (p-start >= 8 && strncmp(p-8, "operator", 8) == 0)
1711 p++;
1712 if (*p == '<')
1713 p++;
1715 else
1717 // skip template parameter list
1718 skipNestedAngles(p);
1720 } else if (*p == '(') {
1721 // this skips "(anonymous namespace)" as well as the formal
1722 // parameter list of the containing function if this is a member
1723 // of a nested class
1724 skipNestedWithString(p, '(', ')');
1725 } else if (*p == ' ') {
1726 ++p;
1727 if (*p == '(')
1728 break; // parameter list found
1729 } else {
1730 p++;
1734 if (*p == '\0') {
1735 func = start;
1736 file = QString();
1737 lineNo = -1;
1738 s = p;
1739 return;
1742 * Skip parameters. But notice that for complicated conversion
1743 * functions (eg. "operator int(**)()()", ie. convert to pointer to
1744 * pointer to function) as well as operator()(...) we have to skip
1745 * additional pairs of parentheses. Furthermore, recent gdbs write the
1746 * demangled name followed by the arguments in a pair of parentheses,
1747 * where the demangled name can end in "const".
1749 do {
1750 skipNestedWithString(p, '(', ')');
1751 skipSpace(p);
1752 // skip "const"
1753 if (strncmp(p, "const", 5) == 0) {
1754 p += 5;
1755 skipSpace(p);
1757 } while (*p == '(');
1759 // check for file position
1760 if (strncmp(p, "at ", 3) == 0) {
1761 p += 3;
1762 const char* fileStart = p;
1763 // go for the end of the line
1764 while (*p != '\0' && *p != '\n')
1765 p++;
1766 // search back for colon
1767 const char* colon = p;
1768 do {
1769 --colon;
1770 } while (*colon != ':');
1771 file = QString::fromLatin1(fileStart, colon-fileStart);
1772 lineNo = atoi(colon+1)-1;
1773 // skip new-line
1774 if (*p != '\0')
1775 p++;
1776 } else {
1777 // check for "from shared lib"
1778 if (strncmp(p, "from ", 5) == 0) {
1779 p += 5;
1780 // go for the end of the line
1781 while (*p != '\0' && *p != '\n')
1782 p++;
1783 // skip new-line
1784 if (*p != '\0')
1785 p++;
1787 file = "";
1788 lineNo = -1;
1790 // construct the function name (including file info)
1791 if (*p == '\0') {
1792 func = start;
1793 } else {
1794 func = QString::fromLatin1(start, p-start-1); /* don't include \n */
1796 s = p;
1799 * Replace \n (and whitespace around it) in func by a blank. We cannot
1800 * use QString::simplified() for this because this would also
1801 * simplify space that belongs to a string arguments that gdb sometimes
1802 * prints in the argument lists of the function.
1804 ASSERT(!isspace(func[0].toLatin1())); // there must be non-white before first \n
1805 int nl = 0;
1806 while ((nl = func.indexOf('\n', nl)) >= 0) {
1807 // search back to the beginning of the whitespace
1808 int startWhite = nl;
1809 do {
1810 --startWhite;
1811 } while (isspace(func[startWhite].toLatin1()));
1812 startWhite++;
1813 // search forward to the end of the whitespace
1814 do {
1815 nl++;
1816 } while (isspace(func[nl].toLatin1()));
1817 // replace
1818 func.replace(startWhite, nl-startWhite, " ");
1819 /* continue searching for more \n's at this place: */
1820 nl = startWhite+1;
1826 * Parses a stack frame including its frame number
1828 static bool parseFrame(const char*& s, int& frameNo, QString& func,
1829 QString& file, int& lineNo, DbgAddr& address)
1831 // Example:
1832 // #1 0x8048881 in Dl::Dl (this=0xbffff418, r=3214) at testfile.cpp:72
1833 // Breakpoint 3, Cl::f(int) const (this=0xbffff3c0, x=17) at testfile.cpp:155
1835 // must start with a hash mark followed by number
1836 // or with "Breakpoint " followed by number and comma
1837 if (s[0] == '#') {
1838 if (!isdigit(s[1]))
1839 return false;
1840 s++; /* skip the hash mark */
1841 } else if (strncmp(s, "Breakpoint ", 11) == 0) {
1842 if (!isdigit(s[11]))
1843 return false;
1844 s += 11; /* skip "Breakpoint" */
1845 } else
1846 return false;
1848 // frame number
1849 frameNo = atoi(s);
1850 skipDecimal(s);
1851 // space and comma
1852 while (isspace(*s) || *s == ',')
1853 s++;
1854 parseFrameInfo(s, func, file, lineNo, address);
1855 return true;
1858 void GdbDriver::parseBackTrace(const char* output, std::list<StackFrame>& stack)
1860 QString func, file;
1861 int lineNo, frameNo;
1862 DbgAddr address;
1864 while (::parseFrame(output, frameNo, func, file, lineNo, address)) {
1865 stack.push_back(StackFrame());
1866 StackFrame* frm = &stack.back();
1867 frm->frameNo = frameNo;
1868 frm->fileName = file;
1869 frm->lineNo = lineNo;
1870 frm->address = address;
1871 frm->var = new ExprValue(func, VarTree::NKplain);
1875 bool GdbDriver::parseFrameChange(const char* output, int& frameNo,
1876 QString& file, int& lineNo, DbgAddr& address)
1878 QString func;
1879 return ::parseFrame(output, frameNo, func, file, lineNo, address);
1883 bool GdbDriver::parseBreakList(const char* output, std::list<Breakpoint>& brks)
1885 // skip first line, which is the headline
1886 const char* p = strchr(output, '\n');
1887 if (p == 0)
1888 return false;
1889 p++;
1890 if (*p == '\0')
1891 return false;
1893 // split up a line
1894 const char* end;
1895 char* dummy;
1896 while (*p != '\0') {
1897 Breakpoint bp;
1898 // get Num
1899 bp.id = strtol(p, &dummy, 10); /* don't care about overflows */
1900 p = dummy;
1901 // check for continued <MULTIPLE> breakpoint
1902 if (*p == '.' && isdigit(p[1]))
1904 // continuation: skip type and disposition
1906 else
1908 // get Type
1909 skipSpace(p);
1910 if (strncmp(p, "breakpoint", 10) == 0) {
1911 p += 10;
1912 } else if (strncmp(p, "hw watchpoint", 13) == 0) {
1913 bp.type = Breakpoint::watchpoint;
1914 p += 13;
1915 } else if (strncmp(p, "watchpoint", 10) == 0) {
1916 bp.type = Breakpoint::watchpoint;
1917 p += 10;
1919 skipSpace(p);
1920 if (*p == '\0')
1921 break;
1922 // get Disp
1923 bp.temporary = *p++ == 'd';
1925 while (*p != '\0' && !isspace(*p)) /* "keep" or "del" */
1926 p++;
1927 skipSpace(p);
1928 if (*p == '\0')
1929 break;
1930 // get Enb
1931 bp.enabled = *p++ == 'y';
1932 while (*p != '\0' && !isspace(*p)) /* "y" or "n" */
1933 p++;
1934 skipSpace(p);
1935 if (*p == '\0')
1936 break;
1937 // the address, if present
1938 if (bp.type == Breakpoint::breakpoint &&
1939 strncmp(p, "0x", 2) == 0)
1941 const char* start = p;
1942 while (*p != '\0' && !isspace(*p))
1943 p++;
1944 bp.address = QString::fromLatin1(start, p-start);
1945 while (isspace(*p) && *p != '\n')
1946 p++;
1947 if (*p == '\0')
1948 break;
1950 // remainder is location, hit and ignore count, condition
1951 end = strchr(p, '\n');
1952 if (end == 0) {
1953 bp.location = p;
1954 p += bp.location.length();
1955 } else {
1956 // location of a <MULTIPLE> filled in from subsequent breakpoints
1957 if (strncmp(p, "<MULTIPLE>", 10) != 0)
1958 bp.location = QString::fromLatin1(p, end-p).trimmed();
1959 p = end+1; /* skip over \n */
1962 // may be continued in next line
1963 while (isspace(*p)) { /* p points to beginning of line */
1964 // skip white space at beginning of line
1965 skipSpace(p);
1967 // seek end of line
1968 end = strchr(p, '\n');
1969 if (end == 0)
1970 end = p+strlen(p);
1972 if (strncmp(p, "breakpoint already hit", 22) == 0) {
1973 // extract the hit count
1974 p += 22;
1975 bp.hitCount = strtol(p, &dummy, 10);
1976 TRACE(QString("hit count %1").arg(bp.hitCount));
1977 } else if (strncmp(p, "stop only if ", 13) == 0) {
1978 // extract condition
1979 p += 13;
1980 bp.condition = QString::fromLatin1(p, end-p).trimmed();
1981 TRACE("condition: "+bp.condition);
1982 } else if (strncmp(p, "ignore next ", 12) == 0) {
1983 // extract ignore count
1984 p += 12;
1985 bp.ignoreCount = strtol(p, &dummy, 10);
1986 TRACE(QString("ignore count %1").arg(bp.ignoreCount));
1987 } else {
1988 // indeed a continuation
1989 bp.location += " " + QString::fromLatin1(p, end-p).trimmed();
1991 p = end;
1992 if (*p != '\0')
1993 p++; /* skip '\n' */
1996 if (brks.empty() || brks.back().id != bp.id) {
1997 brks.push_back(bp);
1998 } else {
1999 // this is a continuation; fill in location if not yet set
2000 // otherwise, drop this breakpoint
2001 Breakpoint& mbp = brks.back();
2002 if (mbp.location.isEmpty() && !bp.location.isEmpty()) {
2003 mbp.location = bp.location;
2004 mbp.address = bp.address;
2005 } else if (mbp.address.isEmpty() && !bp.address.isEmpty()) {
2006 mbp.address = bp.address;
2010 return true;
2013 std::list<ThreadInfo> GdbDriver::parseThreadList(const char* output)
2015 std::list<ThreadInfo> threads;
2016 if (strcmp(output, "\n") == 0 ||
2017 strncmp(output, "No stack.", 9) == 0 ||
2018 strncmp(output, "No threads.", 11) == 0) {
2019 // no threads
2020 return threads;
2023 bool newFormat = false;
2024 const char* p = output;
2025 while (*p != '\0') {
2026 ThreadInfo thr;
2027 // seach look for thread id, watching out for the focus indicator
2028 thr.hasFocus = false;
2029 skipSpace(p); /* may be \n from prev line: see "No stack" below */
2031 // recent GDBs write a header line; skip it
2032 if (threads.empty() && strncmp(p, "Id Target", 11) == 0) {
2033 p = strchr(p, '\n');
2034 if (p == NULL)
2035 break;
2036 newFormat = true;
2037 continue; // next line please, '\n' is skipped above
2040 if (*p == '*') {
2041 thr.hasFocus = true;
2042 p++;
2043 // there follows only whitespace
2045 const char* end;
2046 char *temp_end = NULL; /* we need a non-const 'end' for strtol to use...*/
2047 thr.id = strtol(p, &temp_end, 10);
2048 end = temp_end;
2049 if (p == end) {
2050 // syntax error: no number found; bail out
2051 return threads;
2053 p = end;
2055 skipSpace(p);
2058 * Now follows the thread's SYSTAG.
2060 if (!newFormat) {
2061 // In the old format, it is terminated by two blanks.
2062 end = strstr(p, " ");
2063 if (end == 0) {
2064 // syntax error; bail out
2065 return threads;
2067 end += 2;
2068 } else {
2069 // In the new format lies crazyness: there is no definitive
2070 // end marker. At best we can guess when the SYSTAG ends.
2071 // A typical thread list on Linux looks like this:
2073 // Id Target Id Frame
2074 // 2 Thread 0x7ffff7854700 (LWP 10827) "thrserver" 0x00007ffff7928631 in clone () from /lib64/libc.so.6
2075 // * 1 Thread 0x7ffff7fcc700 (LWP 10808) "thrserver" main () at thrserver.c:84
2077 // Looking at GDB's code, the Target Id ends in tokens that
2078 // are bracketed by parentheses or quotes. Therefore,
2079 // we skip (at most) two tokens ('Thread' and the address),
2080 // and then all parts that are in parentheses or quotes.
2081 int n = 0;
2082 end = p;
2083 while (*end) {
2084 if (*end == '"') {
2085 skipString(end);
2086 n = 2;
2087 } else if (*end == '(') {
2088 skipNested(end, '(', ')');
2089 n = 2;
2090 } else if (n < 2) {
2091 while (*end && !isspace(*end))
2092 ++end;
2093 ++n;
2094 } else {
2095 break;
2097 skipSpace(end);
2100 thr.threadName = QString::fromLatin1(p, end-p).trimmed();
2101 p = end;
2104 * Now follows a standard stack frame. Sometimes, however, gdb
2105 * catches a thread at an instant where it doesn't have a stack.
2107 if (strncmp(p, "[No stack.]", 11) != 0) {
2108 ::parseFrameInfo(p, thr.function, thr.fileName, thr.lineNo, thr.address);
2109 } else {
2110 thr.function = "[No stack]";
2111 thr.lineNo = -1;
2112 p += 11; /* \n is skipped above */
2115 threads.push_back(thr);
2117 return threads;
2120 static bool parseNewBreakpoint(const char* o, int& id,
2121 QString& file, int& lineNo, QString& address);
2122 static bool parseNewWatchpoint(const char* o, int& id,
2123 QString& expr);
2125 bool GdbDriver::parseBreakpoint(const char* output, int& id,
2126 QString& file, int& lineNo, QString& address)
2128 // skip lines of that begin with "(Cannot find"
2129 while (strncmp(output, "(Cannot find", 12) == 0 ||
2130 strncmp(output, "Note: breakpoint", 16) == 0)
2132 output = strchr(output, '\n');
2133 if (output == 0)
2134 return false;
2135 output++; /* skip newline */
2138 if (strncmp(output, "Breakpoint ", 11) == 0) {
2139 output += 11; /* skip "Breakpoint " */
2140 return ::parseNewBreakpoint(output, id, file, lineNo, address);
2141 } else if (strncmp(output, "Temporary breakpoint ", 21) == 0) {
2142 output += 21;
2143 return ::parseNewBreakpoint(output, id, file, lineNo, address);
2144 } else if (strncmp(output, "Hardware watchpoint ", 20) == 0) {
2145 output += 20;
2146 return ::parseNewWatchpoint(output, id, address);
2147 } else if (strncmp(output, "Watchpoint ", 11) == 0) {
2148 output += 11;
2149 return ::parseNewWatchpoint(output, id, address);
2151 return false;
2154 static bool parseNewBreakpoint(const char* o, int& id,
2155 QString& file, int& lineNo, QString& address)
2157 // breakpoint id
2158 char* p;
2159 id = strtoul(o, &p, 10);
2160 if (p == o)
2161 return false;
2163 // check for the address
2164 if (strncmp(p, " at 0x", 6) == 0) {
2165 char* start = p+4; /* skip " at ", but not 0x */
2166 p += 6;
2167 while (isxdigit(*p))
2168 ++p;
2169 address = QString::fromLatin1(start, p-start);
2173 * Mostly, GDB responds with this syntax:
2175 * Breakpoint 1 at 0x400b94: file multibrkpt.cpp, line 9. (2 locations)
2177 * but sometimes it uses this syntax:
2179 * Breakpoint 4 at 0x804f158: lotto739.cpp:95. (3 locations)
2181 const char* fileEnd, *numStart = 0;
2182 const char* fileStart = strstr(p, "file ");
2183 if (fileStart != 0)
2185 fileStart += 5;
2186 fileEnd = strstr(fileStart, ", line ");
2187 if (fileEnd != 0)
2188 numStart = fileEnd + 7;
2190 if (numStart == 0 && p[0] == ':' && p[1] == ' ')
2192 fileStart = p+2;
2193 skipSpace(fileStart);
2194 fileEnd = strchr(fileStart, ':');
2195 if (fileEnd != 0)
2196 numStart = fileEnd + 1;
2198 if (numStart == 0)
2199 return !address.isEmpty(); /* parse error only if there's no address */
2201 QString fileName = QString::fromLatin1(fileStart, fileEnd-fileStart);
2202 int line = strtoul(numStart, &p, 10);
2203 if (numStart == p)
2204 return false;
2206 file = fileName;
2207 lineNo = line-1; /* zero-based! */
2208 return true;
2211 static bool parseNewWatchpoint(const char* o, int& id,
2212 QString& expr)
2214 // watchpoint id
2215 char* p;
2216 id = strtoul(o, &p, 10);
2217 if (p == o)
2218 return false;
2220 if (strncmp(p, ": ", 2) != 0)
2221 return false;
2222 p += 2;
2224 // all the rest on the line is the expression
2225 expr = QString::fromLatin1(p, strlen(p)).trimmed();
2226 return true;
2229 void GdbDriver::parseLocals(const char* output, std::list<ExprValue*>& newVars)
2231 // check for possible error conditions
2232 if (strncmp(output, "No symbol table", 15) == 0)
2234 return;
2237 while (*output != '\0') {
2238 skipSpace(output);
2239 if (*output == '\0')
2240 break;
2241 // skip occurrences of "No locals" and "No args"
2242 if (strncmp(output, "No locals", 9) == 0 ||
2243 strncmp(output, "No arguments", 12) == 0)
2245 output = strchr(output, '\n');
2246 if (output == 0) {
2247 break;
2249 continue;
2252 ExprValue* variable = parseVar(output);
2253 if (variable == 0) {
2254 break;
2256 // do not add duplicates
2257 for (std::list<ExprValue*>::iterator o = newVars.begin(); o != newVars.end(); ++o) {
2258 if ((*o)->m_name == variable->m_name) {
2259 delete variable;
2260 goto skipDuplicate;
2263 newVars.push_back(variable);
2264 skipDuplicate:;
2268 ExprValue* GdbDriver::parsePrintExpr(const char* output, bool wantErrorValue)
2270 ExprValue* var = 0;
2271 // check for error conditions
2272 if (!parseErrorMessage(output, var, wantErrorValue))
2274 // parse the variable
2275 var = parseVar(output);
2277 return var;
2280 bool GdbDriver::parseChangeWD(const char* output, QString& message)
2282 bool isGood = false;
2283 message = QString(output).simplified();
2284 if (message.isEmpty()) {
2285 message = i18n("New working directory: ") + m_programWD;
2286 isGood = true;
2288 return isGood;
2291 bool GdbDriver::parseChangeExecutable(const char* output, QString& message)
2293 message = output;
2295 m_haveCoreFile = false;
2298 * Lines starting with the following do not indicate errors:
2299 * Using host libthread_db
2300 * (no debugging symbols found)
2301 * Reading symbols from
2303 while (strncmp(output, "Reading symbols from", 20) == 0 ||
2304 strncmp(output, "done.", 5) == 0 ||
2305 strncmp(output, "Missing separate debuginfo", 26) == 0 ||
2306 strncmp(output, "Try: ", 5) == 0 ||
2307 strncmp(output, "Using host libthread_db", 23) == 0 ||
2308 strncmp(output, "(no debugging symbols found)", 28) == 0)
2310 // this line is good, go to the next one
2311 const char* end = strchr(output, '\n');
2312 if (end == 0)
2313 output += strlen(output);
2314 else
2315 output = end+1;
2319 * If we've parsed all lines, there was no error.
2321 return output[0] == '\0';
2324 bool GdbDriver::parseCoreFile(const char* output)
2326 // if command succeeded, gdb emits a line starting with "#0 "
2327 m_haveCoreFile = strstr(output, "\n#0 ") != 0;
2328 return m_haveCoreFile;
2331 uint GdbDriver::parseProgramStopped(const char* output, QString& message)
2333 // optionally: "program changed, rereading symbols",
2334 // followed by:
2335 // "Program exited normally"
2336 // "Program terminated with wignal SIGSEGV"
2337 // "Program received signal SIGINT" or other signal
2338 // "Breakpoint..."
2339 // GDB since 7.3 prints
2340 // "[Inferior 1 (process 13400) exited normally]"
2341 // "[Inferior 1 (process 14698) exited with code 01]"
2343 // go through the output, line by line, checking what we have
2344 const char* start = output - 1;
2345 uint flags = SFprogramActive;
2346 message = QString();
2347 do {
2348 start++; /* skip '\n' */
2350 if (strncmp(start, "Program ", 8) == 0 ||
2351 strncmp(start, "ptrace: ", 8) == 0) {
2353 * When we receive a signal, the program remains active.
2355 * Special: If we "stopped" in a corefile, the string "Program
2356 * terminated with signal"... is displayed. (Normally, we see
2357 * "Program received signal"... when a signal happens.)
2359 if (strncmp(start, "Program exited", 14) == 0 ||
2360 (strncmp(start, "Program terminated", 18) == 0 && !m_haveCoreFile) ||
2361 strncmp(start, "ptrace: ", 8) == 0)
2363 flags &= ~SFprogramActive;
2366 // set message
2367 const char* endOfMessage = strchr(start, '\n');
2368 if (endOfMessage == 0)
2369 endOfMessage = start + strlen(start);
2370 message = QString::fromLatin1(start, endOfMessage-start);
2371 } else if (strncmp(start, "[Inferior ", 10) == 0) {
2372 const char* p = start + 10;
2373 // skip number and space
2374 while (*p && !isspace(*p))
2375 ++p;
2376 skipSpace(p);
2377 if (*p == '(') {
2378 skipNested(p, '(', ')');
2379 if (strncmp(p, " exited ", 8) == 0) {
2380 flags &= ~SFprogramActive;
2382 // set message
2383 const char* end = strchr(p, '\n');
2384 if (end == 0)
2385 end = p + strlen(p);
2386 // strip [] from the message
2387 message = QString::fromLatin1(start+1, end-start-2);
2390 } else if (strncmp(start, "Breakpoint ", 11) == 0) {
2392 * We stopped at a (permanent) breakpoint (gdb doesn't tell us
2393 * that it stopped at a temporary breakpoint).
2395 flags |= SFrefreshBreak;
2396 } else if (strstr(start, "re-reading symbols.") != 0) {
2397 flags |= SFrefreshSource;
2400 // next line, please
2401 start = strchr(start, '\n');
2402 } while (start != 0);
2405 * Gdb only notices when new threads have appeared, but not when a
2406 * thread finishes. So we always have to assume that the list of
2407 * threads has changed.
2409 flags |= SFrefreshThreads;
2411 return flags;
2414 QStringList GdbDriver::parseSharedLibs(const char* output)
2416 QStringList shlibs;
2417 if (strncmp(output, "No shared libraries loaded", 26) == 0)
2418 return shlibs;
2420 // parse the table of shared libraries
2422 // strip off head line
2423 output = strchr(output, '\n');
2424 if (output == 0)
2425 return shlibs;
2426 output++; /* skip '\n' */
2427 QString shlibName;
2428 while (*output != '\0') {
2429 // format of a line is
2430 // 0x404c5000 0x40580d90 Yes /lib/libc.so.5
2431 // 3 blocks of non-space followed by space
2432 for (int i = 0; *output != '\0' && i < 3; i++) {
2433 while (*output != '\0' && !isspace(*output)) { /* non-space */
2434 output++;
2436 skipSpace(output); /* space */
2438 if (*output == '\0')
2439 return shlibs;
2440 const char* start = output;
2441 output = strchr(output, '\n');
2442 if (output == 0)
2443 output = start + strlen(start);
2444 shlibName = QString::fromLatin1(start, output-start);
2445 if (*output != '\0')
2446 output++;
2447 shlibs.append(shlibName);
2448 TRACE("found shared lib " + shlibName);
2450 return shlibs;
2453 bool GdbDriver::parseFindType(const char* output, QString& type)
2455 if (strncmp(output, "type = ", 7) != 0)
2456 return false;
2459 * Everything else is the type. We strip off any leading "const" and any
2460 * trailing "&" on the grounds that neither affects the decoding of the
2461 * object. We also strip off all white-space from the type.
2463 output += 7;
2464 if (strncmp(output, "const ", 6) == 0)
2465 output += 6;
2466 type = output;
2467 type.replace(QRegExp("\\s+"), "");
2468 if (type.endsWith("&"))
2469 type.truncate(type.length() - 1);
2470 return true;
2473 std::list<RegisterInfo> GdbDriver::parseRegisters(const char* output)
2475 std::list<RegisterInfo> regs;
2476 if (strncmp(output, "The program has no registers now", 32) == 0) {
2477 return regs;
2480 // parse register values
2481 while (*output != '\0')
2483 RegisterInfo reg;
2484 // skip space at the start of the line
2485 skipSpace(output);
2487 // register name
2488 const char* start = output;
2489 while (*output != '\0' && !isspace(*output))
2490 output++;
2491 if (*output == '\0')
2492 break;
2493 reg.regName = QString::fromLatin1(start, output-start);
2495 skipSpace(output);
2497 QString value;
2500 * If we find a brace now, this is a vector register. We look for
2501 * the closing brace and treat the result as cooked value.
2503 if (*output == '{')
2505 start = output;
2506 skipNested(output, '{', '}');
2507 value = QString::fromLatin1(start, output-start).simplified();
2508 // skip space, but not the end of line
2509 while (isspace(*output) && *output != '\n')
2510 output++;
2511 // get rid of the braces at the begining and the end
2512 value.remove(0, 1);
2513 if (value[value.length()-1] == '}') {
2514 value = value.left(value.length()-1);
2516 // gdb 5.3 doesn't print a separate set of raw values
2517 if (*output == '{') {
2518 // another set of vector follows
2519 // what we have so far is the raw value
2520 reg.rawValue = value;
2522 start = output;
2523 skipNested(output, '{', '}');
2524 value = QString::fromLatin1(start, output-start).simplified();
2525 } else {
2526 // for gdb 5.3
2527 // find first type that does not have an array, this is the RAW value
2528 const char* end=start;
2529 findEnd(end);
2530 const char* cur=start;
2531 while (cur<end) {
2532 while (*cur != '=' && cur<end)
2533 cur++;
2534 cur++;
2535 while (isspace(*cur) && cur<end)
2536 cur++;
2537 if (isNumberish(*cur)) {
2538 end=cur;
2539 while (*end && (*end!='}') && (*end!=',') && (*end!='\n'))
2540 end++;
2541 QString rawValue = QString::fromLatin1(cur, end-cur).simplified();
2542 reg.rawValue = rawValue;
2544 if (rawValue.left(2)=="0x") {
2545 // ok we have a raw value, now get it's type
2546 end=cur-1;
2547 while (isspace(*end) || *end=='=') end--;
2548 end++;
2549 cur=end-1;
2550 while (*cur!='{' && *cur!=' ')
2551 cur--;
2552 cur++;
2553 reg.type = QString::fromLatin1(cur, end-cur);
2556 // end while loop
2557 cur=end;
2560 // skip to the end of line
2561 while (*output != '\0' && *output != '\n')
2562 output++;
2563 // get rid of the braces at the begining and the end
2564 value.remove(0, 1);
2565 if (value[value.length()-1] == '}') {
2566 value.truncate(value.length()-1);
2569 reg.cookedValue = value;
2571 else
2573 continuation:
2574 // the rest of the line is the register value
2575 start = output;
2576 output = strchr(output,'\n');
2577 if (output == 0)
2578 output = start + strlen(start);
2579 value += QString::fromLatin1(start, output-start).simplified();
2582 * Look ahead: if the subsequent line is indented, it continues
2583 * the current register value.
2585 if (output != 0 && isspace(output[1]))
2587 ++output;
2588 value += ' ';
2589 goto continuation;
2593 * We split the raw from the cooked values.
2594 * Some modern gdbs explicitly say: "0.1234 (raw 0x3e4567...)".
2595 * Here, the cooked value comes first, and the raw value is in
2596 * the second part.
2598 int pos = value.indexOf(" (raw ");
2599 if (pos >= 0)
2601 reg.cookedValue = value.left(pos);
2602 reg.rawValue = value.mid(pos+6);
2603 if (reg.rawValue.right(1) == ")") // remove closing bracket
2604 reg.rawValue.truncate(reg.rawValue.length()-1);
2606 else
2609 * In other cases we split off the first token (separated by
2610 * whitespace). It is the raw value. The remainder of the line
2611 * is the cooked value.
2613 int pos = value.indexOf(' ');
2614 if (pos < 0) {
2615 reg.rawValue = value;
2616 reg.cookedValue = QString();
2617 } else {
2618 reg.rawValue = value.left(pos);
2619 reg.cookedValue = value.mid(pos+1);
2623 if (*output != '\0')
2624 output++; /* skip '\n' */
2626 regs.push_back(reg);
2628 return regs;
2631 bool GdbDriver::parseInfoLine(const char* output, QString& addrFrom, QString& addrTo)
2633 // "is at address" or "starts at address"
2634 const char* start = strstr(output, "s at address ");
2635 if (start == 0)
2636 return false;
2638 start += 13;
2639 const char* p = start;
2640 while (*p != '\0' && !isspace(*p))
2641 p++;
2642 addrFrom = QString::fromLatin1(start, p-start);
2644 start = strstr(p, "and ends at ");
2645 if (start == 0) {
2646 addrTo = addrFrom;
2647 return true;
2650 start += 12;
2651 p = start;
2652 while (*p != '\0' && !isspace(*p))
2653 p++;
2654 addrTo = QString::fromLatin1(start, p-start);
2656 return true;
2659 std::list<DisassembledCode> GdbDriver::parseDisassemble(const char* output)
2661 std::list<DisassembledCode> code;
2663 if (strncmp(output, "Dump of assembler", 17) != 0) {
2664 // error message?
2665 DisassembledCode c;
2666 c.code = output;
2667 code.push_back(c);
2668 return code;
2671 // remove first line
2672 const char* p = strchr(output, '\n');
2673 if (p == 0)
2674 return code; /* not a regular output */
2676 p++;
2678 // remove last line
2679 const char* end = strstr(output, "End of assembler");
2680 if (end == 0)
2681 end = p + strlen(p);
2683 // remove function offsets from the lines
2684 while (p != end)
2686 DisassembledCode c;
2687 // skip initial space or PC pointer ("=>", since gdb 7.1)
2688 while (p != end) {
2689 if (isspace(*p))
2690 ++p;
2691 else if (p[0] == '=' && p[1] == '>')
2692 p += 2;
2693 else
2694 break;
2696 const char* start = p;
2697 // address
2698 while (p != end && !isspace(*p))
2699 p++;
2700 c.address = QString::fromLatin1(start, p-start);
2702 // function name (enclosed in '<>', followed by ':')
2703 while (p != end && *p != '<')
2704 p++;
2705 if (*p == '<')
2706 skipNestedAngles(p);
2707 if (*p == ':')
2708 p++;
2710 // space until code
2711 while (p != end && isspace(*p))
2712 p++;
2714 // code until end of line
2715 start = p;
2716 while (p != end && *p != '\n')
2717 p++;
2718 if (p != end) /* include '\n' */
2719 p++;
2721 c.code = QString::fromLatin1(start, p-start);
2722 code.push_back(c);
2724 return code;
2727 QString GdbDriver::parseMemoryDump(const char* output, std::list<MemoryDump>& memdump)
2729 if (isErrorExpr(output)) {
2730 // error; strip space
2731 QString msg = output;
2732 return msg.trimmed();
2735 const char* p = output; /* save typing */
2737 // the address
2738 while (*p != 0) {
2739 MemoryDump md;
2741 const char* start = p;
2742 while (*p != '\0' && *p != ':' && !isspace(*p))
2743 p++;
2744 md.address = QString::fromLatin1(start, p-start);
2745 if (*p != ':') {
2746 // parse function offset
2747 skipSpace(p);
2748 start = p;
2749 while (*p != '\0' && !(*p == ':' && isspace(p[1])))
2750 p++;
2751 md.address.fnoffs = QString::fromLatin1(start, p-start);
2753 if (*p == ':')
2754 p++;
2755 // skip space; this may skip a new-line char!
2756 skipSpace(p);
2757 // everything to the end of the line is the memory dump
2758 const char* end = strchr(p, '\n');
2759 if (end != 0) {
2760 md.dump = QString::fromLatin1(p, end-p);
2761 p = end+1;
2762 } else {
2763 md.dump = QString::fromLatin1(p, strlen(p));
2764 p += strlen(p);
2766 memdump.push_back(md);
2769 return QString();
2772 QString GdbDriver::editableValue(VarTree* value)
2774 QByteArray ba = value->value().toLatin1();
2775 const char* s = ba.constData();
2777 // if the variable is a pointer value that contains a cast,
2778 // remove the cast
2779 if (*s == '(') {
2780 skipNested(s, '(', ')');
2781 // skip space
2782 skipSpace(s);
2785 repeat:
2786 const char* start = s;
2788 if (strncmp(s, "0x", 2) == 0)
2790 s += 2;
2791 while (isxdigit(*s))
2792 ++s;
2795 * What we saw so far might have been a reference. If so, edit the
2796 * referenced value. Otherwise, edit the pointer.
2798 if (*s == ':') {
2799 // a reference
2800 ++s;
2801 goto repeat;
2803 // a pointer
2804 // if it's a pointer to a string, remove the string
2805 const char* end = s;
2806 skipSpace(s);
2807 if (*s == '"') {
2808 // a string
2809 return QString::fromLatin1(start, end-start);
2810 } else {
2811 // other pointer
2812 return QString::fromLatin1(start, strlen(start));
2816 // else leave it unchanged (or stripped of the reference preamble)
2817 return s;
2820 QString GdbDriver::parseSetVariable(const char* output)
2822 // if there is any output, it is an error message
2823 QString msg = output;
2824 return msg.trimmed();
2828 #include "gdbdriver.moc"