Remove unused clearLow parameter from the debugger driver interface.
[kdbg.git] / kdbg / gdbdriver.cpp
blobd4ec0f345ede4b00a892fd649fa98d551957d860
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)
591 assert(cmd >= 0 && cmd < NUM_CMDS);
592 assert(cmds[cmd].argsNeeded == GdbCmdInfo::argNone);
594 return executeCmdString(cmd, cmds[cmd].fmt, false);
597 CmdQueueItem* GdbDriver::executeCmd(DbgCommand cmd, QString strArg)
599 return executeCmdString(cmd, makeCmdString(cmd, strArg), false);
602 CmdQueueItem* GdbDriver::executeCmd(DbgCommand cmd, int intArg)
605 return executeCmdString(cmd, makeCmdString(cmd, intArg), false);
608 CmdQueueItem* GdbDriver::executeCmd(DbgCommand cmd, QString strArg, int intArg)
610 return executeCmdString(cmd, makeCmdString(cmd, strArg, intArg), false);
613 CmdQueueItem* GdbDriver::executeCmd(DbgCommand cmd, QString strArg1, QString strArg2)
615 return executeCmdString(cmd, makeCmdString(cmd, strArg1, strArg2), false);
618 CmdQueueItem* GdbDriver::executeCmd(DbgCommand cmd, int intArg1, int intArg2)
620 return executeCmdString(cmd, makeCmdString(cmd, intArg1, intArg2), false);
623 CmdQueueItem* GdbDriver::executeCmdOnce(DbgCommand cmd)
625 assert(cmd >= 0 && cmd < NUM_CMDS);
626 assert(cmds[cmd].argsNeeded == GdbCmdInfo::argNone);
628 return executeCmdString(cmd, cmds[cmd].fmt, true);
631 CmdQueueItem* GdbDriver::executeCmdOnce(DbgCommand cmd, QString strArg, int intArg)
633 return executeCmdString(cmd, makeCmdString(cmd, strArg, intArg), true);
636 CmdQueueItem* GdbDriver::queueCmd(DbgCommand cmd, QueueMode mode)
638 return queueCmdString(cmd, cmds[cmd].fmt, mode);
641 CmdQueueItem* GdbDriver::queueCmd(DbgCommand cmd, QString strArg,
642 QueueMode mode)
644 return queueCmdString(cmd, makeCmdString(cmd, strArg), mode);
647 CmdQueueItem* GdbDriver::queueCmd(DbgCommand cmd, int intArg,
648 QueueMode mode)
650 return queueCmdString(cmd, makeCmdString(cmd, intArg), mode);
653 CmdQueueItem* GdbDriver::queueCmd(DbgCommand cmd, QString strArg, int intArg,
654 QueueMode mode)
656 return queueCmdString(cmd, makeCmdString(cmd, strArg, intArg), mode);
659 CmdQueueItem* GdbDriver::queueCmd(DbgCommand cmd, QString strArg1, QString strArg2,
660 QueueMode mode)
662 return queueCmdString(cmd, makeCmdString(cmd, strArg1, strArg2), mode);
665 void GdbDriver::terminate()
667 if (m_state != DSidle)
669 ::kill(pid(), SIGINT);
670 m_state = DSinterrupted;
672 flushCommands();
673 closeWriteChannel();
676 void GdbDriver::detachAndTerminate()
678 ::kill(pid(), SIGINT);
679 flushCommands();
680 executeCmdString(DCinitialize, "detach\nquit\n", true);
683 void GdbDriver::interruptInferior()
685 ::kill(pid(), SIGINT);
686 // remove accidentally queued commands
687 flushHiPriQueue();
690 static bool isErrorExpr(const char* output)
692 return
693 strncmp(output, "Cannot access memory at", 23) == 0 ||
694 strncmp(output, "Attempt to dereference a generic pointer", 40) == 0 ||
695 strncmp(output, "Attempt to take contents of ", 28) == 0 ||
696 strncmp(output, "Attempt to use a type name as an expression", 43) == 0 ||
697 strncmp(output, "There is no member or method named", 34) == 0 ||
698 strncmp(output, "A parse error in expression", 27) == 0 ||
699 strncmp(output, "No symbol \"", 11) == 0 ||
700 strncmp(output, "Internal error: ", 16) == 0;
703 static void skipSpace(const char*& p)
705 while (isspace(*p))
706 p++;
709 static void skipDecimal(const char*& p)
711 while (isdigit(*p))
712 p++;
716 * Returns true if the output is an error message. If wantErrorValue is
717 * true, a new ExprValue object is created and filled with the error message.
718 * If there are warnings, they are skipped and output points past the warnings
719 * on return (even if there \e are errors).
721 static bool parseErrorMessage(const char*& output,
722 ExprValue*& variable, bool wantErrorValue)
724 skipSpace(output);
726 // skip warnings
727 while (strncmp(output, "warning:", 8) == 0)
729 const char* end = strchr(output+8, '\n');
730 if (end == 0)
731 output += strlen(output);
732 else
733 output = end+1;
734 skipSpace(output);
737 if (isErrorExpr(output))
739 if (wantErrorValue) {
740 // put the error message as value in the variable
741 variable = new ExprValue(QString(), VarTree::NKplain);
742 const char* endMsg = strchr(output, '\n');
743 if (endMsg == 0)
744 endMsg = output + strlen(output);
745 variable->m_value = QString::fromLatin1(output, endMsg-output);
746 } else {
747 variable = 0;
749 return true;
751 return false;
754 #if QT_VERSION >= 300
755 union Qt2QChar {
756 short s;
757 struct {
758 uchar row;
759 uchar cell;
760 } qch;
762 #endif
764 void GdbDriver::setPrintQStringDataCmd(const char* cmd)
766 // don't accept the command if it is empty
767 if (cmd == 0 || *cmd == '\0')
768 return;
769 assert(strlen(cmd) <= MAX_FMTLEN);
770 cmds[DCprintQStringStruct].fmt = cmd;
773 ExprValue* GdbDriver::parseQCharArray(const char* output, bool wantErrorValue, bool qt3like)
775 ExprValue* variable = 0;
778 * Parse off white space. gdb sometimes prints white space first if the
779 * printed array leaded to an error.
781 skipSpace(output);
783 // special case: empty string (0 repetitions)
784 if (strncmp(output, "Invalid number 0 of repetitions", 31) == 0)
786 variable = new ExprValue(QString(), VarTree::NKplain);
787 variable->m_value = "\"\"";
788 return variable;
791 // check for error conditions
792 if (parseErrorMessage(output, variable, wantErrorValue))
793 return variable;
795 // parse the array
797 // find '='
798 const char* p = output;
799 p = strchr(p, '=');
800 if (p == 0) {
801 goto error;
803 p++;
804 skipSpace(p);
806 if (*p == '{')
808 // this is the real data
809 p++; /* skip '{' */
811 // parse the array
812 QString result;
813 QString repeatCount;
814 enum { wasNothing, wasChar, wasRepeat } lastThing = wasNothing;
816 * A matrix for separators between the individual "things"
817 * that are added to the string. The first index is a bool,
818 * the second index is from the enum above.
820 static const char* separator[2][3] = {
821 { "\"", 0, ", \"" }, /* normal char is added */
822 { "'", "\", '", ", '" } /* repeated char is added */
825 while (isdigit(*p)) {
826 // parse a number
827 char* end;
828 unsigned short value = (unsigned short) strtoul(p, &end, 0);
829 if (end == p)
830 goto error; /* huh? no valid digits */
831 // skip separator and search for a repeat count
832 p = end;
833 while (isspace(*p) || *p == ',')
834 p++;
835 bool repeats = strncmp(p, "<repeats ", 9) == 0;
836 if (repeats) {
837 const char* start = p;
838 p = strchr(p+9, '>'); /* search end and advance */
839 if (p == 0)
840 goto error;
841 p++; /* skip '>' */
842 repeatCount = QString::fromLatin1(start, p-start);
843 while (isspace(*p) || *p == ',')
844 p++;
846 // p is now at the next char (or the end)
848 // interpret the value as a QChar
849 // TODO: make cross-architecture compatible
850 QChar ch;
851 if (qt3like) {
852 ch = QChar(value);
853 } else {
854 #if QT_VERSION < 300
855 (unsigned short&)ch = value;
856 #else
857 Qt2QChar c;
858 c.s = value;
859 ch.setRow(c.qch.row);
860 ch.setCell(c.qch.cell);
861 #endif
864 // escape a few frequently used characters
865 char escapeCode = '\0';
866 switch (ch.toLatin1()) {
867 case '\n': escapeCode = 'n'; break;
868 case '\r': escapeCode = 'r'; break;
869 case '\t': escapeCode = 't'; break;
870 case '\b': escapeCode = 'b'; break;
871 case '\"': escapeCode = '\"'; break;
872 case '\\': escapeCode = '\\'; break;
873 case '\0': if (value == 0) { escapeCode = '0'; } break;
876 // add separator
877 result += separator[repeats][lastThing];
878 // add char
879 if (escapeCode != '\0') {
880 result += '\\';
881 ch = escapeCode;
883 result += ch;
885 // fixup repeat count and lastThing
886 if (repeats) {
887 result += "' ";
888 result += repeatCount;
889 lastThing = wasRepeat;
890 } else {
891 lastThing = wasChar;
894 if (*p != '}')
895 goto error;
897 // closing quote
898 if (lastThing == wasChar)
899 result += "\"";
901 // assign the value
902 variable = new ExprValue(QString(), VarTree::NKplain);
903 variable->m_value = result;
905 else if (strncmp(p, "true", 4) == 0)
907 variable = new ExprValue(QString(), VarTree::NKplain);
908 variable->m_value = "QString::null";
910 else if (strncmp(p, "false", 5) == 0)
912 variable = new ExprValue(QString(), VarTree::NKplain);
913 variable->m_value = "(null)";
915 else
916 goto error;
917 return variable;
919 error:
920 if (wantErrorValue) {
921 variable = new ExprValue(QString(), VarTree::NKplain);
922 variable->m_value = "internal parse error";
924 return variable;
927 static ExprValue* parseVar(const char*& s)
929 const char* p = s;
931 skipSpace(p);
933 QString name;
934 VarTree::NameKind kind;
936 * Detect anonymouse struct values: The 'name =' part is missing:
937 * s = { a = 1, { b = 2 }}
938 * Note that this detection works only inside structs when the anonymous
939 * struct is not the first member:
940 * s = {{ a = 1 }, b = 2}
941 * This is misparsed (by parseNested()) because it is mistakenly
942 * interprets the second opening brace as the first element of an array
943 * of structs.
945 if (*p == '{')
947 name = i18n("<anonymous struct or union>");
948 kind = VarTree::NKanonymous;
950 else
952 if (!parseName(p, name, kind)) {
953 return 0;
956 // go for '='
957 skipSpace(p);
958 if (*p != '=') {
959 TRACE("parse error: = not found after " + name);
960 return 0;
962 // skip the '=' and more whitespace
963 p++;
964 skipSpace(p);
967 ExprValue* variable = new ExprValue(name, kind);
969 if (!parseValue(p, variable)) {
970 delete variable;
971 return 0;
973 s = p;
974 return variable;
977 static void skipNested(const char*& s, char opening, char closing)
979 const char* p = s;
981 // parse a nested type
982 int nest = 1;
983 p++;
985 * Search for next matching `closing' char, skipping nested pairs of
986 * `opening' and `closing'.
988 while (*p && nest > 0) {
989 if (*p == opening) {
990 nest++;
991 } else if (*p == closing) {
992 nest--;
994 p++;
996 if (nest != 0) {
997 TRACE(QString().sprintf("parse error: mismatching %c%c at %-20.20s", opening, closing, s));
999 s = p;
1003 * This function skips text that is delimited by nested angle bracktes, '<>'.
1004 * A complication arises because the delimited text can contain the names of
1005 * operator<<, operator>>, operator<, and operator>, which have to be treated
1006 * specially so that they do not count towards the nesting of '<>'.
1007 * This function assumes that the delimited text does not contain strings.
1009 static void skipNestedAngles(const char*& s)
1011 const char* p = s;
1013 int nest = 1;
1014 p++; // skip the initial '<'
1015 while (*p && nest > 0)
1017 // Below we can check for p-s >= 9 instead of 8 because
1018 // *s is '<' and cannot be part of "operator".
1019 if (*p == '<')
1021 if (p-s >= 9 && strncmp(p-8, "operator", 8) == 0) {
1022 if (p[1] == '<')
1023 p++;
1024 } else {
1025 nest++;
1028 else if (*p == '>')
1030 if (p-s >= 9 && strncmp(p-8, "operator", 8) == 0) {
1031 if (p[1] == '>')
1032 p++;
1033 } else {
1034 nest--;
1037 p++;
1039 if (nest != 0) {
1040 TRACE(QString().sprintf("parse error: mismatching <> at %-20.20s", s));
1042 s = p;
1046 * Find the end of line that is not inside braces
1048 static void findEnd(const char*& s)
1050 const char* p = s;
1051 while (*p && *p!='\n') {
1052 while (*p && *p!='\n' && *p!='{')
1053 p++;
1054 if (*p=='{') {
1055 p++;
1056 skipNested(p, '{', '}'); p--;
1059 s = p;
1062 static bool isNumberish(const char ch)
1064 return (ch>='0' && ch<='9') || ch=='.' || ch=='x';
1067 void skipString(const char*& p)
1069 // wchar_t strings begin with L
1070 if (*p == 'L')
1071 ++p;
1073 moreStrings:
1074 // opening quote
1075 char quote = *p++;
1076 while (*p != quote) {
1077 if (*p == '\\') {
1078 // skip escaped character
1079 // no special treatment for octal values necessary
1080 p++;
1082 // simply return if no more characters
1083 if (*p == '\0')
1084 return;
1085 p++;
1087 // closing quote
1088 p++;
1090 * Strings can consist of several parts, some of which contain repeated
1091 * characters.
1093 if (quote == '\'') {
1094 // look ahaead for <repeats 123 times>
1095 const char* q = p+1;
1096 skipSpace(q);
1097 if (strncmp(q, "<repeats ", 9) == 0) {
1098 p = q+9;
1099 while (*p != '\0' && *p != '>')
1100 p++;
1101 if (*p != '\0') {
1102 p++; /* skip the '>' */
1106 // Is the string continued? If so, there is no L in wchar_t strings
1107 if (*p == ',')
1109 // look ahead for another quote
1110 const char* q = p+1;
1111 skipSpace(q);
1112 if (*q == '"' || *q == '\'') {
1113 // yes!
1114 p = q;
1115 goto moreStrings;
1118 // some strings can end in <incomplete sequence ...>
1119 if (strncmp(q, "<incomplete sequence", 20) == 0)
1121 p = q+20;
1122 while (*p != '\0' && *p != '>')
1123 p++;
1124 if (*p != '\0') {
1125 p++; /* skip the '>' */
1130 * There's a bug in gdb where it prints the beginning of the string
1131 * continuation and the comma-blank in the wrong order if the new string
1132 * begins with an incomplete multi-byte character. For now, let's check
1133 * for this in a very narrow condition, particularly, where the next
1134 * character is given in octal notation. Example:
1135 * 'a' <repeats 20 times>"\240, b"
1137 if (*p == '"' && p[1] == '\\' && isdigit(p[2])) {
1138 int i = 3;
1139 while (isdigit(p[i]))
1140 ++i;
1141 if (p[i] == ',' && p[i+1] == ' ') {
1142 // just treat everything beginning at the dquote as string
1143 goto moreStrings;
1146 /* very long strings are followed by `...' */
1147 if (*p == '.' && p[1] == '.' && p[2] == '.') {
1148 p += 3;
1152 static void skipNestedWithString(const char*& s, char opening, char closing)
1154 const char* p = s;
1156 // parse a nested expression
1157 int nest = 1;
1158 p++;
1160 * Search for next matching `closing' char, skipping nested pairs of
1161 * `opening' and `closing' as well as strings.
1163 while (*p && nest > 0) {
1164 if (*p == opening) {
1165 nest++;
1166 } else if (*p == closing) {
1167 nest--;
1168 } else if (*p == '\'' || *p == '\"') {
1169 skipString(p);
1170 continue;
1172 p++;
1174 if (nest > 0) {
1175 TRACE(QString().sprintf("parse error: mismatching %c%c at %-20.20s", opening, closing, s));
1177 s = p;
1180 static void skipName(const char*& p)
1182 // allow : (for enumeration values) and $ and . (for _vtbl.)
1183 while (isalnum(*p) || *p == '_' || *p == ':' || *p == '$' || *p == '.')
1184 p++;
1187 static void skipFunctionName(const char*& p)
1189 while (*p)
1191 if (*p == '<') {
1192 // skip template parameter list
1193 skipNestedAngles(p);
1194 } else if (*p == '(') {
1195 // this skips "(anonymous namespace)" as well as the formal
1196 // parameter list of the containing function if this is a member
1197 // of a nested class
1198 skipNestedWithString(p, '(', ')');
1199 } else if (isalnum(*p) || *p == '_' || *p == ':') {
1200 const char* start = p;
1201 skipName(p);
1202 // check for operator
1203 if (p-start >= 8 &&
1204 strncmp(p-8, "operator", 8) == 0 &&
1205 // do not mistake this as the tail of some identifier
1206 (p-start == 8 || !(isalnum(p[-9]) || p[-9] == '_')))
1208 // skip forward until we find the opening parenthesis
1209 // this catches both operator()(...) as well as
1210 // type conversion operators, e.g.
1211 // operator char const*() const
1212 // operator void(*)()
1213 while (*p && *p != '(')
1214 p++;
1216 } else if (strncmp(p, " const", 6) == 0 &&
1217 // must not mistake "const" as the beginning of
1218 // a subequent identifier
1219 !isalnum(p[6]) && p[6] != '_') {
1220 p += 6;
1221 } else {
1222 break;
1227 static bool parseName(const char*& s, QString& name, VarTree::NameKind& kind)
1229 kind = VarTree::NKplain;
1231 const char* p = s;
1232 // examples of names:
1233 // name
1234 // <Object>
1235 // <string<a,b<c>,7> >
1237 if (*p == '<') {
1238 skipNestedAngles(p);
1239 name = QString::fromLatin1(s, p - s);
1240 kind = VarTree::NKtype;
1242 else
1244 // name, which might be "static"; allow dot for "_vtbl."
1245 skipName(p);
1246 if (p == s) {
1247 TRACE(QString().sprintf("parse error: not a name %-20.20s", s));
1248 return false;
1250 int len = p - s;
1251 if (len == 6 && strncmp(s, "static", 6) == 0) {
1252 kind = VarTree::NKstatic;
1254 // its a static variable, name comes now
1255 skipSpace(p);
1256 s = p;
1257 skipName(p);
1258 if (p == s) {
1259 TRACE(QString().sprintf("parse error: not a name after static %-20.20s", s));
1260 return false;
1262 len = p - s;
1264 name = QString::fromLatin1(s, len);
1266 // return the new position
1267 s = p;
1268 return true;
1271 static bool parseValue(const char*& s, ExprValue* variable)
1273 variable->m_value = "";
1275 repeat:
1276 if (*s == '{') {
1277 // Sometimes we find the following output:
1278 // {<text variable, no debug info>} 0x40012000 <access>
1279 // {<data variable, no debug info>}
1280 // {<variable (not text or data), no debug info>}
1281 if (strncmp(s, "{<text variable, ", 17) == 0 ||
1282 strncmp(s, "{<data variable, ", 17) == 0 ||
1283 strncmp(s, "{<variable (not text or data), ", 31) == 0)
1285 const char* start = s;
1286 skipNested(s, '{', '}');
1287 variable->m_value = QString::fromLatin1(start, s-start);
1288 variable->m_value += ' '; // add only a single space
1289 skipSpace(s);
1290 goto repeat;
1292 else
1294 s++;
1295 if (!parseNested(s, variable)) {
1296 return false;
1298 // must be the closing brace
1299 if (*s != '}') {
1300 TRACE("parse error: missing } of " + variable->m_name);
1301 return false;
1303 s++;
1304 // final white space
1305 skipSpace(s);
1308 // Sometimes we find a warning; it ends at the next LF
1309 else if (strncmp(s, "warning: ", 9) == 0) {
1310 const char* end = strchr(s, '\n');
1311 s = end ? end : s+strlen(s);
1312 // skip space at start of next line
1313 skipSpace(s);
1314 goto repeat;
1315 } else {
1316 // examples of leaf values (cannot be the empty string):
1317 // 123
1318 // -123
1319 // 23.575e+37
1320 // 0x32a45
1321 // @0x012ab4
1322 // (DwContentType&) @0x8123456: {...}
1323 // 0x32a45 "text"
1324 // 10 '\n'
1325 // <optimized out>
1326 // 0x823abc <Array<int> virtual table>
1327 // 0x40240f <globarstr> "test"
1328 // (void (*)()) 0x8048480 <f(E *, char)>
1329 // (E *) 0xbffff450
1330 // red
1331 // &parseP (HTMLClueV *, char *)
1332 // &virtual table offset 0, this adjustment 140737488346016
1333 // &virtual Dl::operator char const*() const
1334 // Variable "x" is not available.
1335 // The value of variable 'x' is distributed...
1336 // -nan(0xfffff081defa0)
1337 // @0x100400f08: <error reading variable>
1338 // (void (Templated<double>::*)(Templated<double> * const)) 0x400d74 <MostDerived::PrintV()>, this adjustment -16
1340 const char*p = s;
1342 // check for type
1343 QString type;
1344 if (*p == '(') {
1345 skipNested(p, '(', ')');
1347 skipSpace(p);
1348 variable->m_value = QString::fromLatin1(s, p - s);
1351 bool reference = false;
1352 if (*p == '@') {
1353 // skip reference marker
1354 p++;
1355 reference = true;
1357 const char* start = p;
1358 if (*p == '-')
1359 p++;
1361 // some values consist of more than one token
1362 bool checkMultiPart = false;
1364 if (p[0] == '0' && p[1] == 'x') {
1365 // parse hex number
1366 p += 2;
1367 while (isxdigit(*p))
1368 p++;
1371 * Assume this is a pointer, but only if it's not a reference, since
1372 * references can't be expanded.
1374 if (!reference) {
1375 variable->m_varKind = VarTree::VKpointer;
1376 } else {
1378 * References are followed by a colon, in which case we'll
1379 * find the value following the reference address.
1381 if (*p == ':') {
1382 p++;
1383 } else {
1384 // Paranoia. (Can this happen, i.e. reference not followed by ':'?)
1385 reference = false;
1388 checkMultiPart = true;
1389 } else if (isdigit(*p)) {
1390 // parse decimal number, possibly a float
1391 skipDecimal(p);
1392 if (*p == '.') { /* TODO: obey i18n? */
1393 // In long arrays an integer may be followed by '...'.
1394 // We test for this situation and don't gobble the '...'.
1395 if (p[1] != '.' || p[0] != '.') {
1396 // fractional part
1397 p++;
1398 skipDecimal(p);
1401 if (*p == 'e' || *p == 'E') {
1402 p++;
1403 // exponent
1404 if (*p == '-' || *p == '+')
1405 p++;
1406 skipDecimal(p);
1409 // for char variables there is the char, eg. 10 '\n'
1410 checkMultiPart = true;
1411 } else if (*p == '<') {
1412 // e.g. <optimized out>
1413 skipNestedAngles(p);
1414 } else if (*p == '"' || *p == '\'') {
1415 // character may have multipart: '\000' <repeats 11 times>
1416 checkMultiPart = *p == '\'';
1417 // found a string
1418 skipString(p);
1419 } else if (*p == 'L' && (p[1] == '"' || p[1] == '\'')) {
1420 // ditto for wchar_t strings
1421 checkMultiPart = p[1] == '\'';
1422 skipString(p);
1423 } else if (*p == '&') {
1424 p++;
1425 if (strncmp(p, "virtual ", 8) == 0) {
1426 p += 8;
1427 if (strncmp(p, "table offset ", 13) == 0) {
1428 p += 13;
1429 skipDecimal(p);
1430 checkMultiPart = true;
1431 } else {
1432 skipFunctionName(p);
1434 } else {
1435 // function pointer
1436 skipName(p);
1437 skipSpace(p);
1438 if (*p == '(') {
1439 skipNested(p, '(', ')');
1442 } else if (strncmp(p, "Variable \"", 10) == 0) {
1443 // Variable "x" is not available.
1444 p += 10; // skip to "
1445 skipName(p);
1446 if (strncmp(p, "\" is not available.", 19) == 0) {
1447 p += 19;
1449 } else if (strncmp(p, "The value of variable '", 23) == 0) {
1450 p += 23;
1451 skipName(p);
1452 const char* e = strchr(p, '.');
1453 if (e == 0) {
1454 p += strlen(p);
1455 } else {
1456 p = e+1;
1458 } else {
1459 moreEnum:
1460 // must be an enumeration value
1461 skipName(p);
1462 // nan (floating point Not a Number) is followed by a number in ()
1463 // enum values can look like A::(anonymous namespace)::blue
1464 if (*p == '(') {
1465 bool isAnonNS = strncmp(p+1, "anonymous namespace)", 20) == 0;
1466 skipNested(p, '(', ')');
1467 if (isAnonNS)
1468 goto moreEnum;
1471 variable->m_value += QString::fromLatin1(start, p - start);
1473 // remove line breaks from the value; this is ok since
1474 // string values never contain a literal line break
1475 variable->m_value.replace('\n', ' ');
1477 while (checkMultiPart) {
1478 // white space
1479 skipSpace(p);
1480 // may be followed by a string or <...>
1481 // if this was a pointer with a string,
1482 // reset that pointer flag since we have now a value
1483 start = p;
1484 checkMultiPart = false;
1486 if (*p == '"' || *p == '\'') {
1487 skipString(p);
1488 variable->m_varKind = VarTree::VKsimple;
1489 } else if (*p == 'L' && (p[1] == '"' || p[1] == '\'')) {
1490 skipString(p); // wchar_t string
1491 variable->m_varKind = VarTree::VKsimple;
1492 } else if (*p == '<') {
1493 // if this value is part of an array, it might be followed
1494 // by <repeats 15 times>, which we don't skip here
1495 if (strncmp(p, "<repeats ", 9) == 0)
1497 // sometimes, a reference is followed by an error message:
1498 // @0x100400f08: <error reading variable>
1499 // in this case, we do not skip the text here, but leave it
1500 // for the subsequent parsing pass induced by the reference
1501 else if (reference && strncmp(p, "<error reading", 14) == 0)
1503 else {
1504 skipNestedAngles(p);
1505 checkMultiPart = true;
1507 } else if (strncmp(p, ", this adjustment ", 18) == 0) {
1508 // pointers-to-member are sometimes followed by
1509 // a "this adjustment" hint
1510 p += 18;
1511 if (*p == '-')
1512 p++;
1513 skipDecimal(p);
1514 // we know that this is not a dereferencable pointer
1515 variable->m_varKind = VarTree::VKsimple;
1516 ++start; // skip ',', will be picked up below
1518 if (p != start) {
1519 // there is always a blank before the string,
1520 // which we will include in the final string value
1521 variable->m_value += QString::fromLatin1(start-1, (p - start)+1);
1525 if (variable->m_value.length() == 0) {
1526 TRACE("parse error: no value for " + variable->m_name);
1527 return false;
1530 // final white space
1531 skipSpace(p);
1532 s = p;
1535 * If this was a reference, the value follows. It might even be a
1536 * composite variable!
1538 if (reference) {
1539 goto repeat;
1543 return true;
1546 static bool parseNested(const char*& s, ExprValue* variable)
1548 // could be a structure or an array
1549 skipSpace(s);
1551 const char* p = s;
1552 bool isStruct = false;
1554 * If there is a name followed by an = or an < -- which starts a type
1555 * name -- or "static", it is a structure
1557 if (*p == '<' || *p == '}') {
1558 isStruct = true;
1559 } else if (strncmp(p, "static ", 7) == 0) {
1560 isStruct = true;
1561 } else if (isalpha(*p) || *p == '_' || *p == '$') {
1562 // look ahead for a comma after the name
1563 skipName(p);
1564 skipSpace(p);
1565 if (*p == '=') {
1566 isStruct = true;
1568 p = s; /* rescan the name */
1570 if (isStruct) {
1571 if (!parseVarSeq(p, variable)) {
1572 return false;
1574 variable->m_varKind = VarTree::VKstruct;
1575 } else {
1576 if (!parseValueSeq(p, variable)) {
1577 return false;
1579 variable->m_varKind = VarTree::VKarray;
1581 s = p;
1582 return true;
1585 static bool parseVarSeq(const char*& s, ExprValue* variable)
1587 // parse a comma-separated sequence of variables
1588 ExprValue* var = variable; /* var != 0 to indicate success if empty seq */
1589 for (;;) {
1590 if (*s == '}')
1591 break;
1592 if (strncmp(s, "<No data fields>}", 17) == 0)
1594 // no member variables, so break out immediately
1595 s += 16; /* go to the closing brace */
1596 break;
1598 var = parseVar(s);
1599 if (var == 0)
1600 break; /* syntax error */
1601 variable->appendChild(var);
1602 if (*s != ',')
1603 break;
1604 // skip the comma and whitespace
1605 s++;
1606 skipSpace(s);
1608 return var != 0;
1611 static bool parseValueSeq(const char*& s, ExprValue* variable)
1613 // parse a comma-separated sequence of variables
1614 int index = 0;
1615 bool good;
1616 for (;;) {
1617 QString name;
1618 name.sprintf("[%d]", index);
1619 ExprValue* var = new ExprValue(name, VarTree::NKplain);
1620 good = parseValue(s, var);
1621 if (!good) {
1622 delete var;
1623 return false;
1625 // a value may be followed by "<repeats 45 times>"
1626 if (strncmp(s, "<repeats ", 9) == 0) {
1627 s += 9;
1628 char* end;
1629 int l = strtol(s, &end, 10);
1630 if (end == s || strncmp(end, " times>", 7) != 0) {
1631 // should not happen
1632 delete var;
1633 return false;
1635 TRACE(QString().sprintf("found <repeats %d times> in array", l));
1636 // replace name and advance index
1637 name.sprintf("[%d .. %d]", index, index+l-1);
1638 var->m_name = name;
1639 index += l;
1640 // skip " times>" and space
1641 s = end+7;
1642 // possible final space
1643 skipSpace(s);
1644 } else {
1645 index++;
1647 variable->appendChild(var);
1648 // long arrays may be terminated by '...'
1649 if (strncmp(s, "...", 3) == 0) {
1650 s += 3;
1651 ExprValue* var = new ExprValue("...", VarTree::NKplain);
1652 var->m_value = i18n("<additional entries of the array suppressed>");
1653 variable->appendChild(var);
1654 break;
1656 if (*s != ',') {
1657 break;
1659 // skip the comma and whitespace
1660 s++;
1661 skipSpace(s);
1662 // sometimes there is a closing brace after a comma
1663 // if (*s == '}')
1664 // break;
1666 return true;
1670 * Parses a stack frame.
1672 static void parseFrameInfo(const char*& s, QString& func,
1673 QString& file, int& lineNo, DbgAddr& address)
1675 const char* p = s;
1677 // next may be a hexadecimal address
1678 if (*p == '0') {
1679 const char* start = p;
1680 p++;
1681 if (*p == 'x')
1682 p++;
1683 while (isxdigit(*p))
1684 p++;
1685 address = QString::fromLatin1(start, p-start);
1686 if (strncmp(p, " in ", 4) == 0)
1687 p += 4;
1688 } else {
1689 address = DbgAddr();
1691 const char* start = p;
1692 // check for special signal handler frame
1693 if (strncmp(p, "<signal handler called>", 23) == 0) {
1694 func = QString::fromLatin1(start, 23);
1695 file = QString();
1696 lineNo = -1;
1697 s = p+23;
1698 if (*s == '\n')
1699 s++;
1700 return;
1704 * Skip the function name. It is terminated by a left parenthesis
1705 * which does not delimit "(anonymous namespace)" and which is
1706 * outside the angle brackets <> of template parameter lists
1707 * and is preceded by a space.
1709 while (*p != '\0')
1711 if (*p == '<') {
1712 // check for operator<< and operator<
1713 if (p-start >= 8 && strncmp(p-8, "operator", 8) == 0)
1715 p++;
1716 if (*p == '<')
1717 p++;
1719 else
1721 // skip template parameter list
1722 skipNestedAngles(p);
1724 } else if (*p == '(') {
1725 // this skips "(anonymous namespace)" as well as the formal
1726 // parameter list of the containing function if this is a member
1727 // of a nested class
1728 skipNestedWithString(p, '(', ')');
1729 } else if (*p == ' ') {
1730 ++p;
1731 if (*p == '(')
1732 break; // parameter list found
1733 } else {
1734 p++;
1738 if (*p == '\0') {
1739 func = start;
1740 file = QString();
1741 lineNo = -1;
1742 s = p;
1743 return;
1746 * Skip parameters. But notice that for complicated conversion
1747 * functions (eg. "operator int(**)()()", ie. convert to pointer to
1748 * pointer to function) as well as operator()(...) we have to skip
1749 * additional pairs of parentheses. Furthermore, recent gdbs write the
1750 * demangled name followed by the arguments in a pair of parentheses,
1751 * where the demangled name can end in "const".
1753 do {
1754 skipNestedWithString(p, '(', ')');
1755 skipSpace(p);
1756 // skip "const"
1757 if (strncmp(p, "const", 5) == 0) {
1758 p += 5;
1759 skipSpace(p);
1761 } while (*p == '(');
1763 // check for file position
1764 if (strncmp(p, "at ", 3) == 0) {
1765 p += 3;
1766 const char* fileStart = p;
1767 // go for the end of the line
1768 while (*p != '\0' && *p != '\n')
1769 p++;
1770 // search back for colon
1771 const char* colon = p;
1772 do {
1773 --colon;
1774 } while (*colon != ':');
1775 file = QString::fromLatin1(fileStart, colon-fileStart);
1776 lineNo = atoi(colon+1)-1;
1777 // skip new-line
1778 if (*p != '\0')
1779 p++;
1780 } else {
1781 // check for "from shared lib"
1782 if (strncmp(p, "from ", 5) == 0) {
1783 p += 5;
1784 // go for the end of the line
1785 while (*p != '\0' && *p != '\n')
1786 p++;
1787 // skip new-line
1788 if (*p != '\0')
1789 p++;
1791 file = "";
1792 lineNo = -1;
1794 // construct the function name (including file info)
1795 if (*p == '\0') {
1796 func = start;
1797 } else {
1798 func = QString::fromLatin1(start, p-start-1); /* don't include \n */
1800 s = p;
1803 * Replace \n (and whitespace around it) in func by a blank. We cannot
1804 * use QString::simplified() for this because this would also
1805 * simplify space that belongs to a string arguments that gdb sometimes
1806 * prints in the argument lists of the function.
1808 ASSERT(!isspace(func[0].toLatin1())); // there must be non-white before first \n
1809 int nl = 0;
1810 while ((nl = func.indexOf('\n', nl)) >= 0) {
1811 // search back to the beginning of the whitespace
1812 int startWhite = nl;
1813 do {
1814 --startWhite;
1815 } while (isspace(func[startWhite].toLatin1()));
1816 startWhite++;
1817 // search forward to the end of the whitespace
1818 do {
1819 nl++;
1820 } while (isspace(func[nl].toLatin1()));
1821 // replace
1822 func.replace(startWhite, nl-startWhite, " ");
1823 /* continue searching for more \n's at this place: */
1824 nl = startWhite+1;
1830 * Parses a stack frame including its frame number
1832 static bool parseFrame(const char*& s, int& frameNo, QString& func,
1833 QString& file, int& lineNo, DbgAddr& address)
1835 // Example:
1836 // #1 0x8048881 in Dl::Dl (this=0xbffff418, r=3214) at testfile.cpp:72
1837 // Breakpoint 3, Cl::f(int) const (this=0xbffff3c0, x=17) at testfile.cpp:155
1839 // must start with a hash mark followed by number
1840 // or with "Breakpoint " followed by number and comma
1841 if (s[0] == '#') {
1842 if (!isdigit(s[1]))
1843 return false;
1844 s++; /* skip the hash mark */
1845 } else if (strncmp(s, "Breakpoint ", 11) == 0) {
1846 if (!isdigit(s[11]))
1847 return false;
1848 s += 11; /* skip "Breakpoint" */
1849 } else
1850 return false;
1852 // frame number
1853 frameNo = atoi(s);
1854 skipDecimal(s);
1855 // space and comma
1856 while (isspace(*s) || *s == ',')
1857 s++;
1858 parseFrameInfo(s, func, file, lineNo, address);
1859 return true;
1862 void GdbDriver::parseBackTrace(const char* output, std::list<StackFrame>& stack)
1864 QString func, file;
1865 int lineNo, frameNo;
1866 DbgAddr address;
1868 while (::parseFrame(output, frameNo, func, file, lineNo, address)) {
1869 stack.push_back(StackFrame());
1870 StackFrame* frm = &stack.back();
1871 frm->frameNo = frameNo;
1872 frm->fileName = file;
1873 frm->lineNo = lineNo;
1874 frm->address = address;
1875 frm->var = new ExprValue(func, VarTree::NKplain);
1879 bool GdbDriver::parseFrameChange(const char* output, int& frameNo,
1880 QString& file, int& lineNo, DbgAddr& address)
1882 QString func;
1883 return ::parseFrame(output, frameNo, func, file, lineNo, address);
1887 bool GdbDriver::parseBreakList(const char* output, std::list<Breakpoint>& brks)
1889 // skip first line, which is the headline
1890 const char* p = strchr(output, '\n');
1891 if (p == 0)
1892 return false;
1893 p++;
1894 if (*p == '\0')
1895 return false;
1897 // split up a line
1898 const char* end;
1899 char* dummy;
1900 while (*p != '\0') {
1901 Breakpoint bp;
1902 // get Num
1903 bp.id = strtol(p, &dummy, 10); /* don't care about overflows */
1904 p = dummy;
1905 // check for continued <MULTIPLE> breakpoint
1906 if (*p == '.' && isdigit(p[1]))
1908 // continuation: skip type and disposition
1910 else
1912 // get Type
1913 skipSpace(p);
1914 if (strncmp(p, "breakpoint", 10) == 0) {
1915 p += 10;
1916 } else if (strncmp(p, "hw watchpoint", 13) == 0) {
1917 bp.type = Breakpoint::watchpoint;
1918 p += 13;
1919 } else if (strncmp(p, "watchpoint", 10) == 0) {
1920 bp.type = Breakpoint::watchpoint;
1921 p += 10;
1923 skipSpace(p);
1924 if (*p == '\0')
1925 break;
1926 // get Disp
1927 bp.temporary = *p++ == 'd';
1929 while (*p != '\0' && !isspace(*p)) /* "keep" or "del" */
1930 p++;
1931 skipSpace(p);
1932 if (*p == '\0')
1933 break;
1934 // get Enb
1935 bp.enabled = *p++ == 'y';
1936 while (*p != '\0' && !isspace(*p)) /* "y" or "n" */
1937 p++;
1938 skipSpace(p);
1939 if (*p == '\0')
1940 break;
1941 // the address, if present
1942 if (bp.type == Breakpoint::breakpoint &&
1943 strncmp(p, "0x", 2) == 0)
1945 const char* start = p;
1946 while (*p != '\0' && !isspace(*p))
1947 p++;
1948 bp.address = QString::fromLatin1(start, p-start);
1949 while (isspace(*p) && *p != '\n')
1950 p++;
1951 if (*p == '\0')
1952 break;
1954 // remainder is location, hit and ignore count, condition
1955 end = strchr(p, '\n');
1956 if (end == 0) {
1957 bp.location = p;
1958 p += bp.location.length();
1959 } else {
1960 // location of a <MULTIPLE> filled in from subsequent breakpoints
1961 if (strncmp(p, "<MULTIPLE>", 10) != 0)
1962 bp.location = QString::fromLatin1(p, end-p).trimmed();
1963 p = end+1; /* skip over \n */
1966 // may be continued in next line
1967 while (isspace(*p)) { /* p points to beginning of line */
1968 // skip white space at beginning of line
1969 skipSpace(p);
1971 // seek end of line
1972 end = strchr(p, '\n');
1973 if (end == 0)
1974 end = p+strlen(p);
1976 if (strncmp(p, "breakpoint already hit", 22) == 0) {
1977 // extract the hit count
1978 p += 22;
1979 bp.hitCount = strtol(p, &dummy, 10);
1980 TRACE(QString("hit count %1").arg(bp.hitCount));
1981 } else if (strncmp(p, "stop only if ", 13) == 0) {
1982 // extract condition
1983 p += 13;
1984 bp.condition = QString::fromLatin1(p, end-p).trimmed();
1985 TRACE("condition: "+bp.condition);
1986 } else if (strncmp(p, "ignore next ", 12) == 0) {
1987 // extract ignore count
1988 p += 12;
1989 bp.ignoreCount = strtol(p, &dummy, 10);
1990 TRACE(QString("ignore count %1").arg(bp.ignoreCount));
1991 } else {
1992 // indeed a continuation
1993 bp.location += " " + QString::fromLatin1(p, end-p).trimmed();
1995 p = end;
1996 if (*p != '\0')
1997 p++; /* skip '\n' */
2000 if (brks.empty() || brks.back().id != bp.id) {
2001 brks.push_back(bp);
2002 } else {
2003 // this is a continuation; fill in location if not yet set
2004 // otherwise, drop this breakpoint
2005 Breakpoint& mbp = brks.back();
2006 if (mbp.location.isEmpty() && !bp.location.isEmpty()) {
2007 mbp.location = bp.location;
2008 mbp.address = bp.address;
2009 } else if (mbp.address.isEmpty() && !bp.address.isEmpty()) {
2010 mbp.address = bp.address;
2014 return true;
2017 std::list<ThreadInfo> GdbDriver::parseThreadList(const char* output)
2019 std::list<ThreadInfo> threads;
2020 if (strcmp(output, "\n") == 0 ||
2021 strncmp(output, "No stack.", 9) == 0 ||
2022 strncmp(output, "No threads.", 11) == 0) {
2023 // no threads
2024 return threads;
2027 bool newFormat = false;
2028 const char* p = output;
2029 while (*p != '\0') {
2030 ThreadInfo thr;
2031 // seach look for thread id, watching out for the focus indicator
2032 thr.hasFocus = false;
2033 skipSpace(p); /* may be \n from prev line: see "No stack" below */
2035 // recent GDBs write a header line; skip it
2036 if (threads.empty() && strncmp(p, "Id Target", 11) == 0) {
2037 p = strchr(p, '\n');
2038 if (p == NULL)
2039 break;
2040 newFormat = true;
2041 continue; // next line please, '\n' is skipped above
2044 if (*p == '*') {
2045 thr.hasFocus = true;
2046 p++;
2047 // there follows only whitespace
2049 const char* end;
2050 char *temp_end = NULL; /* we need a non-const 'end' for strtol to use...*/
2051 thr.id = strtol(p, &temp_end, 10);
2052 end = temp_end;
2053 if (p == end) {
2054 // syntax error: no number found; bail out
2055 return threads;
2057 p = end;
2059 skipSpace(p);
2062 * Now follows the thread's SYSTAG.
2064 if (!newFormat) {
2065 // In the old format, it is terminated by two blanks.
2066 end = strstr(p, " ");
2067 if (end == 0) {
2068 // syntax error; bail out
2069 return threads;
2071 end += 2;
2072 } else {
2073 // In the new format lies crazyness: there is no definitive
2074 // end marker. At best we can guess when the SYSTAG ends.
2075 // A typical thread list on Linux looks like this:
2077 // Id Target Id Frame
2078 // 2 Thread 0x7ffff7854700 (LWP 10827) "thrserver" 0x00007ffff7928631 in clone () from /lib64/libc.so.6
2079 // * 1 Thread 0x7ffff7fcc700 (LWP 10808) "thrserver" main () at thrserver.c:84
2081 // Looking at GDB's code, the Target Id ends in tokens that
2082 // are bracketed by parentheses or quotes. Therefore,
2083 // we skip (at most) two tokens ('Thread' and the address),
2084 // and then all parts that are in parentheses or quotes.
2085 int n = 0;
2086 end = p;
2087 while (*end) {
2088 if (*end == '"') {
2089 skipString(end);
2090 n = 2;
2091 } else if (*end == '(') {
2092 skipNested(end, '(', ')');
2093 n = 2;
2094 } else if (n < 2) {
2095 while (*end && !isspace(*end))
2096 ++end;
2097 ++n;
2098 } else {
2099 break;
2101 skipSpace(end);
2104 thr.threadName = QString::fromLatin1(p, end-p).trimmed();
2105 p = end;
2108 * Now follows a standard stack frame. Sometimes, however, gdb
2109 * catches a thread at an instant where it doesn't have a stack.
2111 if (strncmp(p, "[No stack.]", 11) != 0) {
2112 ::parseFrameInfo(p, thr.function, thr.fileName, thr.lineNo, thr.address);
2113 } else {
2114 thr.function = "[No stack]";
2115 thr.lineNo = -1;
2116 p += 11; /* \n is skipped above */
2119 threads.push_back(thr);
2121 return threads;
2124 static bool parseNewBreakpoint(const char* o, int& id,
2125 QString& file, int& lineNo, QString& address);
2126 static bool parseNewWatchpoint(const char* o, int& id,
2127 QString& expr);
2129 bool GdbDriver::parseBreakpoint(const char* output, int& id,
2130 QString& file, int& lineNo, QString& address)
2132 // skip lines of that begin with "(Cannot find"
2133 while (strncmp(output, "(Cannot find", 12) == 0 ||
2134 strncmp(output, "Note: breakpoint", 16) == 0)
2136 output = strchr(output, '\n');
2137 if (output == 0)
2138 return false;
2139 output++; /* skip newline */
2142 if (strncmp(output, "Breakpoint ", 11) == 0) {
2143 output += 11; /* skip "Breakpoint " */
2144 return ::parseNewBreakpoint(output, id, file, lineNo, address);
2145 } else if (strncmp(output, "Temporary breakpoint ", 21) == 0) {
2146 output += 21;
2147 return ::parseNewBreakpoint(output, id, file, lineNo, address);
2148 } else if (strncmp(output, "Hardware watchpoint ", 20) == 0) {
2149 output += 20;
2150 return ::parseNewWatchpoint(output, id, address);
2151 } else if (strncmp(output, "Watchpoint ", 11) == 0) {
2152 output += 11;
2153 return ::parseNewWatchpoint(output, id, address);
2155 return false;
2158 static bool parseNewBreakpoint(const char* o, int& id,
2159 QString& file, int& lineNo, QString& address)
2161 // breakpoint id
2162 char* p;
2163 id = strtoul(o, &p, 10);
2164 if (p == o)
2165 return false;
2167 // check for the address
2168 if (strncmp(p, " at 0x", 6) == 0) {
2169 char* start = p+4; /* skip " at ", but not 0x */
2170 p += 6;
2171 while (isxdigit(*p))
2172 ++p;
2173 address = QString::fromLatin1(start, p-start);
2177 * Mostly, GDB responds with this syntax:
2179 * Breakpoint 1 at 0x400b94: file multibrkpt.cpp, line 9. (2 locations)
2181 * but sometimes it uses this syntax:
2183 * Breakpoint 4 at 0x804f158: lotto739.cpp:95. (3 locations)
2185 const char* fileEnd, *numStart = 0;
2186 const char* fileStart = strstr(p, "file ");
2187 if (fileStart != 0)
2189 fileStart += 5;
2190 fileEnd = strstr(fileStart, ", line ");
2191 if (fileEnd != 0)
2192 numStart = fileEnd + 7;
2194 if (numStart == 0 && p[0] == ':' && p[1] == ' ')
2196 fileStart = p+2;
2197 skipSpace(fileStart);
2198 fileEnd = strchr(fileStart, ':');
2199 if (fileEnd != 0)
2200 numStart = fileEnd + 1;
2202 if (numStart == 0)
2203 return !address.isEmpty(); /* parse error only if there's no address */
2205 QString fileName = QString::fromLatin1(fileStart, fileEnd-fileStart);
2206 int line = strtoul(numStart, &p, 10);
2207 if (numStart == p)
2208 return false;
2210 file = fileName;
2211 lineNo = line-1; /* zero-based! */
2212 return true;
2215 static bool parseNewWatchpoint(const char* o, int& id,
2216 QString& expr)
2218 // watchpoint id
2219 char* p;
2220 id = strtoul(o, &p, 10);
2221 if (p == o)
2222 return false;
2224 if (strncmp(p, ": ", 2) != 0)
2225 return false;
2226 p += 2;
2228 // all the rest on the line is the expression
2229 expr = QString::fromLatin1(p, strlen(p)).trimmed();
2230 return true;
2233 void GdbDriver::parseLocals(const char* output, std::list<ExprValue*>& newVars)
2235 // check for possible error conditions
2236 if (strncmp(output, "No symbol table", 15) == 0)
2238 return;
2241 while (*output != '\0') {
2242 skipSpace(output);
2243 if (*output == '\0')
2244 break;
2245 // skip occurrences of "No locals" and "No args"
2246 if (strncmp(output, "No locals", 9) == 0 ||
2247 strncmp(output, "No arguments", 12) == 0)
2249 output = strchr(output, '\n');
2250 if (output == 0) {
2251 break;
2253 continue;
2256 ExprValue* variable = parseVar(output);
2257 if (variable == 0) {
2258 break;
2260 // do not add duplicates
2261 for (std::list<ExprValue*>::iterator o = newVars.begin(); o != newVars.end(); ++o) {
2262 if ((*o)->m_name == variable->m_name) {
2263 delete variable;
2264 goto skipDuplicate;
2267 newVars.push_back(variable);
2268 skipDuplicate:;
2272 ExprValue* GdbDriver::parsePrintExpr(const char* output, bool wantErrorValue)
2274 ExprValue* var = 0;
2275 // check for error conditions
2276 if (!parseErrorMessage(output, var, wantErrorValue))
2278 // parse the variable
2279 var = parseVar(output);
2281 return var;
2284 bool GdbDriver::parseChangeWD(const char* output, QString& message)
2286 bool isGood = false;
2287 message = QString(output).simplified();
2288 if (message.isEmpty()) {
2289 message = i18n("New working directory: ") + m_programWD;
2290 isGood = true;
2292 return isGood;
2295 bool GdbDriver::parseChangeExecutable(const char* output, QString& message)
2297 message = output;
2300 * Lines starting with the following do not indicate errors:
2301 * Using host libthread_db
2302 * (no debugging symbols found)
2303 * Reading symbols from
2305 while (strncmp(output, "Reading symbols from", 20) == 0 ||
2306 strncmp(output, "done.", 5) == 0 ||
2307 strncmp(output, "Missing separate debuginfo", 26) == 0 ||
2308 strncmp(output, "Try: ", 5) == 0 ||
2309 strncmp(output, "Using host libthread_db", 23) == 0 ||
2310 strncmp(output, "(no debugging symbols found)", 28) == 0)
2312 // this line is good, go to the next one
2313 const char* end = strchr(output, '\n');
2314 if (end == 0)
2315 output += strlen(output);
2316 else
2317 output = end+1;
2321 * If we've parsed all lines, there was no error.
2323 return output[0] == '\0';
2326 bool GdbDriver::parseCoreFile(const char* output)
2328 // if command succeeded, gdb emits a line starting with "#0 "
2329 return strstr(output, "\n#0 ") != 0;
2332 uint GdbDriver::parseProgramStopped(const char* output, bool haveCoreFile,
2333 QString& message)
2335 // optionally: "program changed, rereading symbols",
2336 // followed by:
2337 // "Program exited normally"
2338 // "Program terminated with wignal SIGSEGV"
2339 // "Program received signal SIGINT" or other signal
2340 // "Breakpoint..."
2341 // GDB since 7.3 prints
2342 // "[Inferior 1 (process 13400) exited normally]"
2343 // "[Inferior 1 (process 14698) exited with code 01]"
2345 // go through the output, line by line, checking what we have
2346 const char* start = output - 1;
2347 uint flags = SFprogramActive;
2348 message = QString();
2349 do {
2350 start++; /* skip '\n' */
2352 if (strncmp(start, "Program ", 8) == 0 ||
2353 strncmp(start, "ptrace: ", 8) == 0) {
2355 * When we receive a signal, the program remains active.
2357 * Special: If we "stopped" in a corefile, the string "Program
2358 * terminated with signal"... is displayed. (Normally, we see
2359 * "Program received signal"... when a signal happens.)
2361 if (strncmp(start, "Program exited", 14) == 0 ||
2362 (strncmp(start, "Program terminated", 18) == 0 && !haveCoreFile) ||
2363 strncmp(start, "ptrace: ", 8) == 0)
2365 flags &= ~SFprogramActive;
2368 // set message
2369 const char* endOfMessage = strchr(start, '\n');
2370 if (endOfMessage == 0)
2371 endOfMessage = start + strlen(start);
2372 message = QString::fromLatin1(start, endOfMessage-start);
2373 } else if (strncmp(start, "[Inferior ", 10) == 0) {
2374 const char* p = start + 10;
2375 // skip number and space
2376 while (*p && !isspace(*p))
2377 ++p;
2378 skipSpace(p);
2379 if (*p == '(') {
2380 skipNested(p, '(', ')');
2381 if (strncmp(p, " exited ", 8) == 0) {
2382 flags &= ~SFprogramActive;
2384 // set message
2385 const char* end = strchr(p, '\n');
2386 if (end == 0)
2387 end = p + strlen(p);
2388 // strip [] from the message
2389 message = QString::fromLatin1(start+1, end-start-2);
2392 } else if (strncmp(start, "Breakpoint ", 11) == 0) {
2394 * We stopped at a (permanent) breakpoint (gdb doesn't tell us
2395 * that it stopped at a temporary breakpoint).
2397 flags |= SFrefreshBreak;
2398 } else if (strstr(start, "re-reading symbols.") != 0) {
2399 flags |= SFrefreshSource;
2402 // next line, please
2403 start = strchr(start, '\n');
2404 } while (start != 0);
2407 * Gdb only notices when new threads have appeared, but not when a
2408 * thread finishes. So we always have to assume that the list of
2409 * threads has changed.
2411 flags |= SFrefreshThreads;
2413 return flags;
2416 QStringList GdbDriver::parseSharedLibs(const char* output)
2418 QStringList shlibs;
2419 if (strncmp(output, "No shared libraries loaded", 26) == 0)
2420 return shlibs;
2422 // parse the table of shared libraries
2424 // strip off head line
2425 output = strchr(output, '\n');
2426 if (output == 0)
2427 return shlibs;
2428 output++; /* skip '\n' */
2429 QString shlibName;
2430 while (*output != '\0') {
2431 // format of a line is
2432 // 0x404c5000 0x40580d90 Yes /lib/libc.so.5
2433 // 3 blocks of non-space followed by space
2434 for (int i = 0; *output != '\0' && i < 3; i++) {
2435 while (*output != '\0' && !isspace(*output)) { /* non-space */
2436 output++;
2438 skipSpace(output); /* space */
2440 if (*output == '\0')
2441 return shlibs;
2442 const char* start = output;
2443 output = strchr(output, '\n');
2444 if (output == 0)
2445 output = start + strlen(start);
2446 shlibName = QString::fromLatin1(start, output-start);
2447 if (*output != '\0')
2448 output++;
2449 shlibs.append(shlibName);
2450 TRACE("found shared lib " + shlibName);
2452 return shlibs;
2455 bool GdbDriver::parseFindType(const char* output, QString& type)
2457 if (strncmp(output, "type = ", 7) != 0)
2458 return false;
2461 * Everything else is the type. We strip off any leading "const" and any
2462 * trailing "&" on the grounds that neither affects the decoding of the
2463 * object. We also strip off all white-space from the type.
2465 output += 7;
2466 if (strncmp(output, "const ", 6) == 0)
2467 output += 6;
2468 type = output;
2469 type.replace(QRegExp("\\s+"), "");
2470 if (type.endsWith("&"))
2471 type.truncate(type.length() - 1);
2472 return true;
2475 std::list<RegisterInfo> GdbDriver::parseRegisters(const char* output)
2477 std::list<RegisterInfo> regs;
2478 if (strncmp(output, "The program has no registers now", 32) == 0) {
2479 return regs;
2482 // parse register values
2483 while (*output != '\0')
2485 RegisterInfo reg;
2486 // skip space at the start of the line
2487 skipSpace(output);
2489 // register name
2490 const char* start = output;
2491 while (*output != '\0' && !isspace(*output))
2492 output++;
2493 if (*output == '\0')
2494 break;
2495 reg.regName = QString::fromLatin1(start, output-start);
2497 skipSpace(output);
2499 QString value;
2502 * If we find a brace now, this is a vector register. We look for
2503 * the closing brace and treat the result as cooked value.
2505 if (*output == '{')
2507 start = output;
2508 skipNested(output, '{', '}');
2509 value = QString::fromLatin1(start, output-start).simplified();
2510 // skip space, but not the end of line
2511 while (isspace(*output) && *output != '\n')
2512 output++;
2513 // get rid of the braces at the begining and the end
2514 value.remove(0, 1);
2515 if (value[value.length()-1] == '}') {
2516 value = value.left(value.length()-1);
2518 // gdb 5.3 doesn't print a separate set of raw values
2519 if (*output == '{') {
2520 // another set of vector follows
2521 // what we have so far is the raw value
2522 reg.rawValue = value;
2524 start = output;
2525 skipNested(output, '{', '}');
2526 value = QString::fromLatin1(start, output-start).simplified();
2527 } else {
2528 // for gdb 5.3
2529 // find first type that does not have an array, this is the RAW value
2530 const char* end=start;
2531 findEnd(end);
2532 const char* cur=start;
2533 while (cur<end) {
2534 while (*cur != '=' && cur<end)
2535 cur++;
2536 cur++;
2537 while (isspace(*cur) && cur<end)
2538 cur++;
2539 if (isNumberish(*cur)) {
2540 end=cur;
2541 while (*end && (*end!='}') && (*end!=',') && (*end!='\n'))
2542 end++;
2543 QString rawValue = QString::fromLatin1(cur, end-cur).simplified();
2544 reg.rawValue = rawValue;
2546 if (rawValue.left(2)=="0x") {
2547 // ok we have a raw value, now get it's type
2548 end=cur-1;
2549 while (isspace(*end) || *end=='=') end--;
2550 end++;
2551 cur=end-1;
2552 while (*cur!='{' && *cur!=' ')
2553 cur--;
2554 cur++;
2555 reg.type = QString::fromLatin1(cur, end-cur);
2558 // end while loop
2559 cur=end;
2562 // skip to the end of line
2563 while (*output != '\0' && *output != '\n')
2564 output++;
2565 // get rid of the braces at the begining and the end
2566 value.remove(0, 1);
2567 if (value[value.length()-1] == '}') {
2568 value.truncate(value.length()-1);
2571 reg.cookedValue = value;
2573 else
2575 continuation:
2576 // the rest of the line is the register value
2577 start = output;
2578 output = strchr(output,'\n');
2579 if (output == 0)
2580 output = start + strlen(start);
2581 value += QString::fromLatin1(start, output-start).simplified();
2584 * Look ahead: if the subsequent line is indented, it continues
2585 * the current register value.
2587 if (output != 0 && isspace(output[1]))
2589 ++output;
2590 value += ' ';
2591 goto continuation;
2595 * We split the raw from the cooked values.
2596 * Some modern gdbs explicitly say: "0.1234 (raw 0x3e4567...)".
2597 * Here, the cooked value comes first, and the raw value is in
2598 * the second part.
2600 int pos = value.indexOf(" (raw ");
2601 if (pos >= 0)
2603 reg.cookedValue = value.left(pos);
2604 reg.rawValue = value.mid(pos+6);
2605 if (reg.rawValue.right(1) == ")") // remove closing bracket
2606 reg.rawValue.truncate(reg.rawValue.length()-1);
2608 else
2611 * In other cases we split off the first token (separated by
2612 * whitespace). It is the raw value. The remainder of the line
2613 * is the cooked value.
2615 int pos = value.indexOf(' ');
2616 if (pos < 0) {
2617 reg.rawValue = value;
2618 reg.cookedValue = QString();
2619 } else {
2620 reg.rawValue = value.left(pos);
2621 reg.cookedValue = value.mid(pos+1);
2625 if (*output != '\0')
2626 output++; /* skip '\n' */
2628 regs.push_back(reg);
2630 return regs;
2633 bool GdbDriver::parseInfoLine(const char* output, QString& addrFrom, QString& addrTo)
2635 // "is at address" or "starts at address"
2636 const char* start = strstr(output, "s at address ");
2637 if (start == 0)
2638 return false;
2640 start += 13;
2641 const char* p = start;
2642 while (*p != '\0' && !isspace(*p))
2643 p++;
2644 addrFrom = QString::fromLatin1(start, p-start);
2646 start = strstr(p, "and ends at ");
2647 if (start == 0) {
2648 addrTo = addrFrom;
2649 return true;
2652 start += 12;
2653 p = start;
2654 while (*p != '\0' && !isspace(*p))
2655 p++;
2656 addrTo = QString::fromLatin1(start, p-start);
2658 return true;
2661 std::list<DisassembledCode> GdbDriver::parseDisassemble(const char* output)
2663 std::list<DisassembledCode> code;
2665 if (strncmp(output, "Dump of assembler", 17) != 0) {
2666 // error message?
2667 DisassembledCode c;
2668 c.code = output;
2669 code.push_back(c);
2670 return code;
2673 // remove first line
2674 const char* p = strchr(output, '\n');
2675 if (p == 0)
2676 return code; /* not a regular output */
2678 p++;
2680 // remove last line
2681 const char* end = strstr(output, "End of assembler");
2682 if (end == 0)
2683 end = p + strlen(p);
2685 // remove function offsets from the lines
2686 while (p != end)
2688 DisassembledCode c;
2689 // skip initial space or PC pointer ("=>", since gdb 7.1)
2690 while (p != end) {
2691 if (isspace(*p))
2692 ++p;
2693 else if (p[0] == '=' && p[1] == '>')
2694 p += 2;
2695 else
2696 break;
2698 const char* start = p;
2699 // address
2700 while (p != end && !isspace(*p))
2701 p++;
2702 c.address = QString::fromLatin1(start, p-start);
2704 // function name (enclosed in '<>', followed by ':')
2705 while (p != end && *p != '<')
2706 p++;
2707 if (*p == '<')
2708 skipNestedAngles(p);
2709 if (*p == ':')
2710 p++;
2712 // space until code
2713 while (p != end && isspace(*p))
2714 p++;
2716 // code until end of line
2717 start = p;
2718 while (p != end && *p != '\n')
2719 p++;
2720 if (p != end) /* include '\n' */
2721 p++;
2723 c.code = QString::fromLatin1(start, p-start);
2724 code.push_back(c);
2726 return code;
2729 QString GdbDriver::parseMemoryDump(const char* output, std::list<MemoryDump>& memdump)
2731 if (isErrorExpr(output)) {
2732 // error; strip space
2733 QString msg = output;
2734 return msg.trimmed();
2737 const char* p = output; /* save typing */
2739 // the address
2740 while (*p != 0) {
2741 MemoryDump md;
2743 const char* start = p;
2744 while (*p != '\0' && *p != ':' && !isspace(*p))
2745 p++;
2746 md.address = QString::fromLatin1(start, p-start);
2747 if (*p != ':') {
2748 // parse function offset
2749 skipSpace(p);
2750 start = p;
2751 while (*p != '\0' && !(*p == ':' && isspace(p[1])))
2752 p++;
2753 md.address.fnoffs = QString::fromLatin1(start, p-start);
2755 if (*p == ':')
2756 p++;
2757 // skip space; this may skip a new-line char!
2758 skipSpace(p);
2759 // everything to the end of the line is the memory dump
2760 const char* end = strchr(p, '\n');
2761 if (end != 0) {
2762 md.dump = QString::fromLatin1(p, end-p);
2763 p = end+1;
2764 } else {
2765 md.dump = QString::fromLatin1(p, strlen(p));
2766 p += strlen(p);
2768 memdump.push_back(md);
2771 return QString();
2774 QString GdbDriver::editableValue(VarTree* value)
2776 QByteArray ba = value->value().toLatin1();
2777 const char* s = ba.constData();
2779 // if the variable is a pointer value that contains a cast,
2780 // remove the cast
2781 if (*s == '(') {
2782 skipNested(s, '(', ')');
2783 // skip space
2784 skipSpace(s);
2787 repeat:
2788 const char* start = s;
2790 if (strncmp(s, "0x", 2) == 0)
2792 s += 2;
2793 while (isxdigit(*s))
2794 ++s;
2797 * What we saw so far might have been a reference. If so, edit the
2798 * referenced value. Otherwise, edit the pointer.
2800 if (*s == ':') {
2801 // a reference
2802 ++s;
2803 goto repeat;
2805 // a pointer
2806 // if it's a pointer to a string, remove the string
2807 const char* end = s;
2808 skipSpace(s);
2809 if (*s == '"') {
2810 // a string
2811 return QString::fromLatin1(start, end-start);
2812 } else {
2813 // other pointer
2814 return QString::fromLatin1(start, strlen(start));
2818 // else leave it unchanged (or stripped of the reference preamble)
2819 return s;
2822 QString GdbDriver::parseSetVariable(const char* output)
2824 // if there is any output, it is an error message
2825 QString msg = output;
2826 return msg.trimmed();
2830 #include "gdbdriver.moc"