KDbg 2.5.5.
[kdbg.git] / kdbg / gdbdriver.cpp
blob26d4e1d5fa9f0e1f2ebbab61bf1b41dda83aac39
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 { DCbreaktext, "break %s\n", GdbCmdInfo::argString },
99 { DCbreakline, "break %s:%d\n", GdbCmdInfo::argStringNum },
100 { DCtbreakline, "tbreak %s:%d\n", GdbCmdInfo::argStringNum },
101 { DCbreakaddr, "break *%s\n", GdbCmdInfo::argString },
102 { DCtbreakaddr, "tbreak *%s\n", GdbCmdInfo::argString },
103 { DCwatchpoint, "watch %s\n", GdbCmdInfo::argString },
104 { DCdelete, "delete %d\n", GdbCmdInfo::argNum },
105 { DCenable, "enable %d\n", GdbCmdInfo::argNum },
106 { DCdisable, "disable %d\n", GdbCmdInfo::argNum },
107 { DCprint, "print %s\n", GdbCmdInfo::argString },
108 { DCprintDeref, "print *(%s)\n", GdbCmdInfo::argString },
109 { DCprintStruct, "print %s\n", GdbCmdInfo::argString },
110 { DCprintQStringStruct, printQStringStructFmt, GdbCmdInfo::argString},
111 { DCframe, "frame %d\n", GdbCmdInfo::argNum },
112 { DCfindType, "whatis %s\n", GdbCmdInfo::argString },
113 { DCinfosharedlib, "info sharedlibrary\n", GdbCmdInfo::argNone },
114 { DCthread, "thread %d\n", GdbCmdInfo::argNum },
115 { DCinfothreads, "info threads\n", GdbCmdInfo::argNone },
116 { DCinfobreak, "info breakpoints\n", GdbCmdInfo::argNone },
117 { DCcondition, "condition %d %s\n", GdbCmdInfo::argNumString},
118 { DCsetpc, "set variable $pc=%s\n", GdbCmdInfo::argString },
119 { DCignore, "ignore %d %d\n", GdbCmdInfo::argNum2},
120 { DCprintWChar, "print ($s=%s)?*$s@wcslen($s):0x0\n", GdbCmdInfo::argString },
121 { DCsetvariable, "set variable %s=%s\n", GdbCmdInfo::argString2 },
124 #define NUM_CMDS (int(sizeof(cmds)/sizeof(cmds[0])))
125 #define MAX_FMTLEN 200
127 GdbDriver::GdbDriver() :
128 DebuggerDriver()
130 #ifndef NDEBUG
131 // check command info array
132 const char* perc;
133 for (int i = 0; i < NUM_CMDS; i++) {
134 // must be indexable by DbgCommand values, i.e. sorted by DbgCommand values
135 assert(i == cmds[i].cmd);
136 // a format string must be associated
137 assert(cmds[i].fmt != 0);
138 assert(strlen(cmds[i].fmt) <= MAX_FMTLEN);
139 // format string must match arg specification
140 switch (cmds[i].argsNeeded) {
141 case GdbCmdInfo::argNone:
142 assert(strchr(cmds[i].fmt, '%') == 0);
143 break;
144 case GdbCmdInfo::argString:
145 perc = strchr(cmds[i].fmt, '%');
146 assert(perc != 0 && perc[1] == 's');
147 assert(strchr(perc+2, '%') == 0);
148 break;
149 case GdbCmdInfo::argNum:
150 perc = strchr(cmds[i].fmt, '%');
151 assert(perc != 0 && perc[1] == 'd');
152 assert(strchr(perc+2, '%') == 0);
153 break;
154 case GdbCmdInfo::argStringNum:
155 perc = strchr(cmds[i].fmt, '%');
156 assert(perc != 0 && perc[1] == 's');
157 perc = strchr(perc+2, '%');
158 assert(perc != 0 && perc[1] == 'd');
159 assert(strchr(perc+2, '%') == 0);
160 break;
161 case GdbCmdInfo::argNumString:
162 perc = strchr(cmds[i].fmt, '%');
163 assert(perc != 0 && perc[1] == 'd');
164 perc = strchr(perc+2, '%');
165 assert(perc != 0 && perc[1] == 's');
166 assert(strchr(perc+2, '%') == 0);
167 break;
168 case GdbCmdInfo::argString2:
169 perc = strchr(cmds[i].fmt, '%');
170 assert(perc != 0 && perc[1] == 's');
171 perc = strchr(perc+2, '%');
172 assert(perc != 0 && perc[1] == 's');
173 assert(strchr(perc+2, '%') == 0);
174 break;
175 case GdbCmdInfo::argNum2:
176 perc = strchr(cmds[i].fmt, '%');
177 assert(perc != 0 && perc[1] == 'd');
178 perc = strchr(perc+2, '%');
179 assert(perc != 0 && perc[1] == 'd');
180 assert(strchr(perc+2, '%') == 0);
181 break;
184 assert(strlen(printQStringStructFmt) <= MAX_FMTLEN);
185 #endif
188 GdbDriver::~GdbDriver()
193 QString GdbDriver::driverName() const
195 return "GDB";
198 QString GdbDriver::defaultGdb()
200 return
201 "gdb"
202 " --fullname" /* to get standard file names each time the prog stops */
203 " --nx"; /* do not execute initialization files */
206 QString GdbDriver::defaultInvocation() const
208 if (m_defaultCmd.isEmpty()) {
209 return defaultGdb();
210 } else {
211 return m_defaultCmd;
215 QStringList GdbDriver::boolOptionList() const
217 // no options
218 return QStringList();
221 bool GdbDriver::startup(QString cmdStr)
223 if (!DebuggerDriver::startup(cmdStr))
224 return false;
226 static const char gdbInitialize[] =
228 * Work around buggy gdbs that do command line editing even if they
229 * are not on a tty. The readline library echos every command back
230 * in this case, which is confusing for us.
232 "set editing off\n"
233 "set confirm off\n"
234 "set print static-members off\n"
235 "set print asm-demangle on\n"
237 * Sometimes, gdb prints [New Thread ...] during 'info threads';
238 * we will not look at thread events anyway, so turn them off.
240 "set print thread-events off\n"
242 * We do not want Python pretty printer support, because their
243 * output is unpredictable, and we cannot parse it.
245 "set auto-load python off\n"
247 * Nevertheless, some Python messages get through, for example,
248 * when a backtrace is printed without the Python gdb module loaded.
250 "set python print-stack none\n"
252 * Don't assume that program functions invoked from a watch expression
253 * always succeed.
255 "set unwindonsignal on\n"
257 * Write a short macro that prints all locals: local variables and
258 * function arguments.
260 "define kdbg__alllocals\n"
261 "info locals\n" /* local vars supersede args with same name */
262 "info args\n" /* therefore, arguments must come last */
263 "end\n"
265 * Work around a bug in gdb-6.3: "info line main" crashes gdb.
267 "define kdbg_infolinemain\n"
268 "list\n"
269 "info line\n"
270 "end\n"
271 // change prompt string and synchronize with gdb
272 "set prompt " PROMPT "\n"
275 executeCmdString(DCinitialize, gdbInitialize, false);
277 // assume that QString::null is ok
278 cmds[DCprintQStringStruct].fmt = printQStringStructFmt;
280 return true;
283 void GdbDriver::commandFinished(CmdQueueItem* cmd)
285 // command string must be committed
286 if (!cmd->m_committed) {
287 // not commited!
288 TRACE("calling " + (__PRETTY_FUNCTION__ + (" with uncommited command:\n\t" +
289 cmd->m_cmdString)));
290 return;
293 switch (cmd->m_cmd) {
294 case DCinitialize:
297 * Check for GDB 7.1 or later; the syntax for the disassemble
298 * command has changed.
299 * This RE picks the last version number in the first line,
300 * because at least OpenSUSE writes its own version number
301 * in the first line (but before GDB's version number).
303 QRegExp re(
304 " " // must be preceded by space
305 "[(]?" // SLES 10 embeds in parentheses
306 "(\\d+)\\.(\\d+)" // major, minor
307 "[^ ]*\\n" // no space until end of line
309 int pos = re.indexIn(m_output);
310 const char* disass = "disassemble %s %s\n";
311 if (pos >= 0) {
312 int major = re.cap(1).toInt();
313 int minor = re.cap(2).toInt();
314 if (major > 7 || (major == 7 && minor >= 1))
316 disass = "disassemble %s, %s\n";
319 cmds[DCdisassemble].fmt = disass;
321 break;
322 default:;
325 /* ok, the command is ready */
326 emit commandReceived(cmd, m_output.constData());
328 switch (cmd->m_cmd) {
329 case DCcorefile:
330 case DCinfolinemain:
331 case DCinfoline:
332 case DCframe:
333 case DCattach:
334 case DCrun:
335 case DCcont:
336 case DCstep:
337 case DCstepi:
338 case DCnext:
339 case DCnexti:
340 case DCfinish:
341 case DCuntil:
342 parseMarker(cmd);
343 default:;
347 int GdbDriver::findPrompt(const QByteArray& output) const
350 * If there's a prompt string in the collected output, it must be at
351 * the very end.
353 * Note: It could nevertheless happen that a character sequence that is
354 * equal to the prompt string appears at the end of the output,
355 * although it is very, very unlikely (namely as part of a string that
356 * lingered in gdb's output buffer due to some timing/heavy load
357 * conditions for a very long time such that that buffer overflowed
358 * exactly at the end of the prompt string look-a-like).
360 int len = output.length();
361 if (len >= PROMPT_LEN &&
362 strncmp(output.data()+len-PROMPT_LEN, PROMPT, PROMPT_LEN) == 0)
364 return len-PROMPT_LEN;
366 return -1;
370 * The --fullname option makes gdb send a special normalized sequence print
371 * each time the program stops and at some other points. The sequence has
372 * the form "\032\032filename:lineno:charoffset:(beg|middle):address".
374 void GdbDriver::parseMarker(CmdQueueItem* cmd)
376 char* startMarker = strstr(m_output.data(), "\032\032");
377 if (startMarker == 0)
378 return;
380 // extract the marker
381 startMarker += 2;
382 TRACE(QString("found marker: ") + startMarker);
383 char* endMarker = strchr(startMarker, '\n');
384 if (endMarker == 0)
385 return;
387 *endMarker = '\0';
389 // extract filename and line number
390 static QRegExp MarkerRE(":(\\d+):\\d+:[begmidl]+:0x");
392 int lineNoStart = MarkerRE.indexIn(startMarker);
393 if (lineNoStart >= 0) {
394 int lineNo = MarkerRE.cap(1).toInt();
396 // get address unless there is one in cmd
397 DbgAddr address = cmd->m_addr;
398 if (address.isEmpty()) {
399 const char* addrStart = startMarker + lineNoStart +
400 MarkerRE.matchedLength() - 2;
401 address = QString(addrStart).trimmed();
404 // now show the window
405 startMarker[lineNoStart] = '\0'; /* split off file name */
406 emit activateFileLine(startMarker, lineNo-1, address);
412 * Escapes characters that might lead to problems when they appear on gdb's
413 * command line.
415 static void normalizeStringArg(QString& arg)
418 * Remove trailing backslashes. This approach is a little simplistic,
419 * but we know that there is at the moment no case where a trailing
420 * backslash would make sense.
422 while (!arg.isEmpty() && arg[arg.length()-1] == '\\') {
423 arg = arg.left(arg.length()-1);
428 QString GdbDriver::makeCmdString(DbgCommand cmd, QString strArg)
430 assert(cmd >= 0 && cmd < NUM_CMDS);
431 assert(cmds[cmd].argsNeeded == GdbCmdInfo::argString);
433 normalizeStringArg(strArg);
435 if (cmd == DCcd) {
436 // need the working directory when parsing the output
437 m_programWD = strArg;
438 } else if (cmd == DCsetargs && !m_redirect.isEmpty()) {
440 * Use saved redirection. We prepend it in front of the user's
441 * arguments so that the user can override the redirections.
443 strArg = m_redirect + " " + strArg;
446 QString cmdString;
447 cmdString.sprintf(cmds[cmd].fmt, strArg.toUtf8().constData());
448 return cmdString;
451 QString GdbDriver::makeCmdString(DbgCommand cmd, int intArg)
453 assert(cmd >= 0 && cmd < NUM_CMDS);
454 assert(cmds[cmd].argsNeeded == GdbCmdInfo::argNum);
456 QString cmdString;
457 cmdString.sprintf(cmds[cmd].fmt, intArg);
458 return cmdString;
461 QString GdbDriver::makeCmdString(DbgCommand cmd, QString strArg, int intArg)
463 assert(cmd >= 0 && cmd < NUM_CMDS);
464 assert(cmds[cmd].argsNeeded == GdbCmdInfo::argStringNum ||
465 cmds[cmd].argsNeeded == GdbCmdInfo::argNumString ||
466 cmd == DCexamine ||
467 cmd == DCtty);
469 normalizeStringArg(strArg);
471 QString cmdString;
473 if (cmd == DCtty)
476 * intArg specifies which channels should be redirected to
477 * /dev/null. It is a value or'ed together from RDNstdin,
478 * RDNstdout, RDNstderr. We store the value for a later DCsetargs
479 * command.
481 * Note: We rely on that after the DCtty a DCsetargs will follow,
482 * which will ultimately apply the redirection.
484 static const char* const runRedir[8] = {
486 "</dev/null",
487 ">/dev/null",
488 "</dev/null >/dev/null",
489 "2>/dev/null",
490 "</dev/null 2>/dev/null",
491 ">/dev/null 2>&1",
492 "</dev/null >/dev/null 2>&1"
494 if (strArg.isEmpty())
495 intArg = 7; /* failsafe if no tty */
496 m_redirect = runRedir[intArg & 7];
498 return makeCmdString(DCtty, strArg); /* note: no problem if strArg empty */
501 if (cmd == DCexamine) {
502 // make a format specifier from the intArg
503 static const char size[16] = {
504 '\0', 'b', 'h', 'w', 'g'
506 static const char format[16] = {
507 '\0', 'x', 'd', 'u', 'o', 't',
508 'a', 'c', 'f', 's', 'i'
510 assert(MDTsizemask == 0xf); /* lowest 4 bits */
511 assert(MDTformatmask == 0xf0); /* next 4 bits */
512 int count = 16; /* number of entities to print */
513 char sizeSpec = size[intArg & MDTsizemask];
514 char formatSpec = format[(intArg & MDTformatmask) >> 4];
515 assert(sizeSpec != '\0');
516 assert(formatSpec != '\0');
517 // adjust count such that 16 lines are printed
518 switch (intArg & MDTformatmask) {
519 case MDTstring: case MDTinsn:
520 break; /* no modification needed */
521 default:
522 // all cases drop through:
523 switch (intArg & MDTsizemask) {
524 case MDTbyte:
525 case MDThalfword:
526 count *= 2;
527 case MDTword:
528 count *= 2;
529 case MDTgiantword:
530 count *= 2;
532 break;
534 QString spec;
535 spec.sprintf("/%d%c%c", count, sizeSpec, formatSpec);
537 return makeCmdString(DCexamine, spec, strArg);
540 if (cmds[cmd].argsNeeded == GdbCmdInfo::argStringNum)
542 // line numbers are zero-based
543 if (cmd == DCuntil || cmd == DCbreakline ||
544 cmd == DCtbreakline || cmd == DCinfoline)
546 intArg++;
548 if (cmd == DCinfoline)
550 // must split off file name part
551 strArg = QFileInfo(strArg).fileName();
553 cmdString.sprintf(cmds[cmd].fmt, strArg.toUtf8().constData(), intArg);
555 else
557 cmdString.sprintf(cmds[cmd].fmt, intArg, strArg.toUtf8().constData());
559 return cmdString;
562 QString GdbDriver::makeCmdString(DbgCommand cmd, QString strArg1, QString strArg2)
564 assert(cmd >= 0 && cmd < NUM_CMDS);
565 assert(cmds[cmd].argsNeeded == GdbCmdInfo::argString2);
567 normalizeStringArg(strArg1);
568 normalizeStringArg(strArg2);
570 QString cmdString;
571 cmdString.sprintf(cmds[cmd].fmt,
572 strArg1.toUtf8().constData(),
573 strArg2.toUtf8().constData());
574 return cmdString;
577 QString GdbDriver::makeCmdString(DbgCommand cmd, int intArg1, int intArg2)
579 assert(cmd >= 0 && cmd < NUM_CMDS);
580 assert(cmds[cmd].argsNeeded == GdbCmdInfo::argNum2);
582 QString cmdString;
583 cmdString.sprintf(cmds[cmd].fmt, intArg1, intArg2);
584 return cmdString;
587 CmdQueueItem* GdbDriver::executeCmd(DbgCommand cmd, bool clearLow)
589 assert(cmd >= 0 && cmd < NUM_CMDS);
590 assert(cmds[cmd].argsNeeded == GdbCmdInfo::argNone);
592 if (cmd == DCrun) {
593 m_haveCoreFile = false;
596 return executeCmdString(cmd, cmds[cmd].fmt, clearLow);
599 CmdQueueItem* GdbDriver::executeCmd(DbgCommand cmd, QString strArg,
600 bool clearLow)
602 return executeCmdString(cmd, makeCmdString(cmd, strArg), clearLow);
605 CmdQueueItem* GdbDriver::executeCmd(DbgCommand cmd, int intArg,
606 bool clearLow)
609 return executeCmdString(cmd, makeCmdString(cmd, intArg), clearLow);
612 CmdQueueItem* GdbDriver::executeCmd(DbgCommand cmd, QString strArg, int intArg,
613 bool clearLow)
615 return executeCmdString(cmd, makeCmdString(cmd, strArg, intArg), clearLow);
618 CmdQueueItem* GdbDriver::executeCmd(DbgCommand cmd, QString strArg1, QString strArg2,
619 bool clearLow)
621 return executeCmdString(cmd, makeCmdString(cmd, strArg1, strArg2), clearLow);
624 CmdQueueItem* GdbDriver::executeCmd(DbgCommand cmd, int intArg1, int intArg2,
625 bool clearLow)
627 return executeCmdString(cmd, makeCmdString(cmd, intArg1, intArg2), clearLow);
630 CmdQueueItem* GdbDriver::queueCmd(DbgCommand cmd, QueueMode mode)
632 return queueCmdString(cmd, cmds[cmd].fmt, mode);
635 CmdQueueItem* GdbDriver::queueCmd(DbgCommand cmd, QString strArg,
636 QueueMode mode)
638 return queueCmdString(cmd, makeCmdString(cmd, strArg), mode);
641 CmdQueueItem* GdbDriver::queueCmd(DbgCommand cmd, int intArg,
642 QueueMode mode)
644 return queueCmdString(cmd, makeCmdString(cmd, intArg), mode);
647 CmdQueueItem* GdbDriver::queueCmd(DbgCommand cmd, QString strArg, int intArg,
648 QueueMode mode)
650 return queueCmdString(cmd, makeCmdString(cmd, strArg, intArg), mode);
653 CmdQueueItem* GdbDriver::queueCmd(DbgCommand cmd, QString strArg1, QString strArg2,
654 QueueMode mode)
656 return queueCmdString(cmd, makeCmdString(cmd, strArg1, strArg2), mode);
659 void GdbDriver::terminate()
661 if (m_state != DSidle)
663 ::kill(pid(), SIGINT);
664 m_state = DSinterrupted;
666 flushCommands();
667 closeWriteChannel();
670 void GdbDriver::detachAndTerminate()
672 ::kill(pid(), SIGINT);
673 flushCommands();
674 executeCmdString(DCinitialize, "detach\nquit\n", true);
677 void GdbDriver::interruptInferior()
679 ::kill(pid(), SIGINT);
680 // remove accidentally queued commands
681 flushHiPriQueue();
684 static bool isErrorExpr(const char* output)
686 return
687 strncmp(output, "Cannot access memory at", 23) == 0 ||
688 strncmp(output, "Attempt to dereference a generic pointer", 40) == 0 ||
689 strncmp(output, "Attempt to take contents of ", 28) == 0 ||
690 strncmp(output, "Attempt to use a type name as an expression", 43) == 0 ||
691 strncmp(output, "There is no member or method named", 34) == 0 ||
692 strncmp(output, "A parse error in expression", 27) == 0 ||
693 strncmp(output, "No symbol \"", 11) == 0 ||
694 strncmp(output, "Internal error: ", 16) == 0;
698 * Returns true if the output is an error message. If wantErrorValue is
699 * true, a new ExprValue object is created and filled with the error message.
700 * If there are warnings, they are skipped and output points past the warnings
701 * on return (even if there \e are errors).
703 static bool parseErrorMessage(const char*& output,
704 ExprValue*& variable, bool wantErrorValue)
706 while (isspace(*output))
707 output++;
709 // skip warnings
710 while (strncmp(output, "warning:", 8) == 0)
712 const char* end = strchr(output+8, '\n');
713 if (end == 0)
714 output += strlen(output);
715 else
716 output = end+1;
717 while (isspace(*output))
718 output++;
721 if (isErrorExpr(output))
723 if (wantErrorValue) {
724 // put the error message as value in the variable
725 variable = new ExprValue(QString(), VarTree::NKplain);
726 const char* endMsg = strchr(output, '\n');
727 if (endMsg == 0)
728 endMsg = output + strlen(output);
729 variable->m_value = QString::fromLatin1(output, endMsg-output);
730 } else {
731 variable = 0;
733 return true;
735 return false;
738 #if QT_VERSION >= 300
739 union Qt2QChar {
740 short s;
741 struct {
742 uchar row;
743 uchar cell;
744 } qch;
746 #endif
748 void GdbDriver::setPrintQStringDataCmd(const char* cmd)
750 // don't accept the command if it is empty
751 if (cmd == 0 || *cmd == '\0')
752 return;
753 assert(strlen(cmd) <= MAX_FMTLEN);
754 cmds[DCprintQStringStruct].fmt = cmd;
757 ExprValue* GdbDriver::parseQCharArray(const char* output, bool wantErrorValue, bool qt3like)
759 ExprValue* variable = 0;
762 * Parse off white space. gdb sometimes prints white space first if the
763 * printed array leaded to an error.
765 while (isspace(*output))
766 output++;
768 // special case: empty string (0 repetitions)
769 if (strncmp(output, "Invalid number 0 of repetitions", 31) == 0)
771 variable = new ExprValue(QString(), VarTree::NKplain);
772 variable->m_value = "\"\"";
773 return variable;
776 // check for error conditions
777 if (parseErrorMessage(output, variable, wantErrorValue))
778 return variable;
780 // parse the array
782 // find '='
783 const char* p = output;
784 p = strchr(p, '=');
785 if (p == 0) {
786 goto error;
788 // skip white space
789 do {
790 p++;
791 } while (isspace(*p));
793 if (*p == '{')
795 // this is the real data
796 p++; /* skip '{' */
798 // parse the array
799 QString result;
800 QString repeatCount;
801 enum { wasNothing, wasChar, wasRepeat } lastThing = wasNothing;
803 * A matrix for separators between the individual "things"
804 * that are added to the string. The first index is a bool,
805 * the second index is from the enum above.
807 static const char* separator[2][3] = {
808 { "\"", 0, ", \"" }, /* normal char is added */
809 { "'", "\", '", ", '" } /* repeated char is added */
812 while (isdigit(*p)) {
813 // parse a number
814 char* end;
815 unsigned short value = (unsigned short) strtoul(p, &end, 0);
816 if (end == p)
817 goto error; /* huh? no valid digits */
818 // skip separator and search for a repeat count
819 p = end;
820 while (isspace(*p) || *p == ',')
821 p++;
822 bool repeats = strncmp(p, "<repeats ", 9) == 0;
823 if (repeats) {
824 const char* start = p;
825 p = strchr(p+9, '>'); /* search end and advance */
826 if (p == 0)
827 goto error;
828 p++; /* skip '>' */
829 repeatCount = QString::fromLatin1(start, p-start);
830 while (isspace(*p) || *p == ',')
831 p++;
833 // p is now at the next char (or the end)
835 // interpret the value as a QChar
836 // TODO: make cross-architecture compatible
837 QChar ch;
838 if (qt3like) {
839 ch = QChar(value);
840 } else {
841 #if QT_VERSION < 300
842 (unsigned short&)ch = value;
843 #else
844 Qt2QChar c;
845 c.s = value;
846 ch.setRow(c.qch.row);
847 ch.setCell(c.qch.cell);
848 #endif
851 // escape a few frequently used characters
852 char escapeCode = '\0';
853 switch (ch.toLatin1()) {
854 case '\n': escapeCode = 'n'; break;
855 case '\r': escapeCode = 'r'; break;
856 case '\t': escapeCode = 't'; break;
857 case '\b': escapeCode = 'b'; break;
858 case '\"': escapeCode = '\"'; break;
859 case '\\': escapeCode = '\\'; break;
860 case '\0': if (value == 0) { escapeCode = '0'; } break;
863 // add separator
864 result += separator[repeats][lastThing];
865 // add char
866 if (escapeCode != '\0') {
867 result += '\\';
868 ch = escapeCode;
870 result += ch;
872 // fixup repeat count and lastThing
873 if (repeats) {
874 result += "' ";
875 result += repeatCount;
876 lastThing = wasRepeat;
877 } else {
878 lastThing = wasChar;
881 if (*p != '}')
882 goto error;
884 // closing quote
885 if (lastThing == wasChar)
886 result += "\"";
888 // assign the value
889 variable = new ExprValue(QString(), VarTree::NKplain);
890 variable->m_value = result;
892 else if (strncmp(p, "true", 4) == 0)
894 variable = new ExprValue(QString(), VarTree::NKplain);
895 variable->m_value = "QString::null";
897 else if (strncmp(p, "false", 5) == 0)
899 variable = new ExprValue(QString(), VarTree::NKplain);
900 variable->m_value = "(null)";
902 else
903 goto error;
904 return variable;
906 error:
907 if (wantErrorValue) {
908 variable = new ExprValue(QString(), VarTree::NKplain);
909 variable->m_value = "internal parse error";
911 return variable;
914 static ExprValue* parseVar(const char*& s)
916 const char* p = s;
918 // skip whitespace
919 while (isspace(*p))
920 p++;
922 QString name;
923 VarTree::NameKind kind;
925 * Detect anonymouse struct values: The 'name =' part is missing:
926 * s = { a = 1, { b = 2 }}
927 * Note that this detection works only inside structs when the anonymous
928 * struct is not the first member:
929 * s = {{ a = 1 }, b = 2}
930 * This is misparsed (by parseNested()) because it is mistakenly
931 * interprets the second opening brace as the first element of an array
932 * of structs.
934 if (*p == '{')
936 name = i18n("<anonymous struct or union>");
937 kind = VarTree::NKanonymous;
939 else
941 if (!parseName(p, name, kind)) {
942 return 0;
945 // go for '='
946 while (isspace(*p))
947 p++;
948 if (*p != '=') {
949 TRACE("parse error: = not found after " + name);
950 return 0;
952 // skip the '=' and more whitespace
953 p++;
954 while (isspace(*p))
955 p++;
958 ExprValue* variable = new ExprValue(name, kind);
960 if (!parseValue(p, variable)) {
961 delete variable;
962 return 0;
964 s = p;
965 return variable;
968 static void skipNested(const char*& s, char opening, char closing)
970 const char* p = s;
972 // parse a nested type
973 int nest = 1;
974 p++;
976 * Search for next matching `closing' char, skipping nested pairs of
977 * `opening' and `closing'.
979 while (*p && nest > 0) {
980 if (*p == opening) {
981 nest++;
982 } else if (*p == closing) {
983 nest--;
985 p++;
987 if (nest != 0) {
988 TRACE(QString().sprintf("parse error: mismatching %c%c at %-20.20s", opening, closing, s));
990 s = p;
994 * This function skips text that is delimited by nested angle bracktes, '<>'.
995 * A complication arises because the delimited text can contain the names of
996 * operator<<, operator>>, operator<, and operator>, which have to be treated
997 * specially so that they do not count towards the nesting of '<>'.
998 * This function assumes that the delimited text does not contain strings.
1000 static void skipNestedAngles(const char*& s)
1002 const char* p = s;
1004 int nest = 1;
1005 p++; // skip the initial '<'
1006 while (*p && nest > 0)
1008 // Below we can check for p-s >= 9 instead of 8 because
1009 // *s is '<' and cannot be part of "operator".
1010 if (*p == '<')
1012 if (p-s >= 9 && strncmp(p-8, "operator", 8) == 0) {
1013 if (p[1] == '<')
1014 p++;
1015 } else {
1016 nest++;
1019 else if (*p == '>')
1021 if (p-s >= 9 && strncmp(p-8, "operator", 8) == 0) {
1022 if (p[1] == '>')
1023 p++;
1024 } else {
1025 nest--;
1028 p++;
1030 if (nest != 0) {
1031 TRACE(QString().sprintf("parse error: mismatching <> at %-20.20s", s));
1033 s = p;
1037 * Find the end of line that is not inside braces
1039 static void findEnd(const char*& s)
1041 const char* p = s;
1042 while (*p && *p!='\n') {
1043 while (*p && *p!='\n' && *p!='{')
1044 p++;
1045 if (*p=='{') {
1046 p++;
1047 skipNested(p, '{', '}'); p--;
1050 s = p;
1053 static bool isNumberish(const char ch)
1055 return (ch>='0' && ch<='9') || ch=='.' || ch=='x';
1058 void skipString(const char*& p)
1060 // wchar_t strings begin with L
1061 if (*p == 'L')
1062 ++p;
1064 moreStrings:
1065 // opening quote
1066 char quote = *p++;
1067 while (*p != quote) {
1068 if (*p == '\\') {
1069 // skip escaped character
1070 // no special treatment for octal values necessary
1071 p++;
1073 // simply return if no more characters
1074 if (*p == '\0')
1075 return;
1076 p++;
1078 // closing quote
1079 p++;
1081 * Strings can consist of several parts, some of which contain repeated
1082 * characters.
1084 if (quote == '\'') {
1085 // look ahaead for <repeats 123 times>
1086 const char* q = p+1;
1087 while (isspace(*q))
1088 q++;
1089 if (strncmp(q, "<repeats ", 9) == 0) {
1090 p = q+9;
1091 while (*p != '\0' && *p != '>')
1092 p++;
1093 if (*p != '\0') {
1094 p++; /* skip the '>' */
1098 // Is the string continued? If so, there is no L in wchar_t strings
1099 if (*p == ',')
1101 // look ahead for another quote
1102 const char* q = p+1;
1103 while (isspace(*q))
1104 q++;
1105 if (*q == '"' || *q == '\'') {
1106 // yes!
1107 p = q;
1108 goto moreStrings;
1111 // some strings can end in <incomplete sequence ...>
1112 if (strncmp(q, "<incomplete sequence", 20) == 0)
1114 p = q+20;
1115 while (*p != '\0' && *p != '>')
1116 p++;
1117 if (*p != '\0') {
1118 p++; /* skip the '>' */
1123 * There's a bug in gdb where it prints the beginning of the string
1124 * continuation and the comma-blank in the wrong order if the new string
1125 * begins with an incomplete multi-byte character. For now, let's check
1126 * for this in a very narrow condition, particularly, where the next
1127 * character is given in octal notation. Example:
1128 * 'a' <repeats 20 times>"\240, b"
1130 if (*p == '"' && p[1] == '\\' && isdigit(p[2])) {
1131 int i = 3;
1132 while (isdigit(p[i]))
1133 ++i;
1134 if (p[i] == ',' && p[i+1] == ' ') {
1135 // just treat everything beginning at the dquote as string
1136 goto moreStrings;
1139 /* very long strings are followed by `...' */
1140 if (*p == '.' && p[1] == '.' && p[2] == '.') {
1141 p += 3;
1145 static void skipNestedWithString(const char*& s, char opening, char closing)
1147 const char* p = s;
1149 // parse a nested expression
1150 int nest = 1;
1151 p++;
1153 * Search for next matching `closing' char, skipping nested pairs of
1154 * `opening' and `closing' as well as strings.
1156 while (*p && nest > 0) {
1157 if (*p == opening) {
1158 nest++;
1159 } else if (*p == closing) {
1160 nest--;
1161 } else if (*p == '\'' || *p == '\"') {
1162 skipString(p);
1163 continue;
1165 p++;
1167 if (nest > 0) {
1168 TRACE(QString().sprintf("parse error: mismatching %c%c at %-20.20s", opening, closing, s));
1170 s = p;
1173 inline void skipName(const char*& p)
1175 // allow : (for enumeration values) and $ and . (for _vtbl.)
1176 while (isalnum(*p) || *p == '_' || *p == ':' || *p == '$' || *p == '.')
1177 p++;
1180 static bool parseName(const char*& s, QString& name, VarTree::NameKind& kind)
1182 kind = VarTree::NKplain;
1184 const char* p = s;
1185 // examples of names:
1186 // name
1187 // <Object>
1188 // <string<a,b<c>,7> >
1190 if (*p == '<') {
1191 skipNestedAngles(p);
1192 name = QString::fromLatin1(s, p - s);
1193 kind = VarTree::NKtype;
1195 else
1197 // name, which might be "static"; allow dot for "_vtbl."
1198 skipName(p);
1199 if (p == s) {
1200 TRACE(QString().sprintf("parse error: not a name %-20.20s", s));
1201 return false;
1203 int len = p - s;
1204 if (len == 6 && strncmp(s, "static", 6) == 0) {
1205 kind = VarTree::NKstatic;
1207 // its a static variable, name comes now
1208 while (isspace(*p))
1209 p++;
1210 s = p;
1211 skipName(p);
1212 if (p == s) {
1213 TRACE(QString().sprintf("parse error: not a name after static %-20.20s", s));
1214 return false;
1216 len = p - s;
1218 name = QString::fromLatin1(s, len);
1220 // return the new position
1221 s = p;
1222 return true;
1225 static bool parseValue(const char*& s, ExprValue* variable)
1227 variable->m_value = "";
1229 repeat:
1230 if (*s == '{') {
1231 // Sometimes we find the following output:
1232 // {<text variable, no debug info>} 0x40012000 <access>
1233 // {<data variable, no debug info>}
1234 // {<variable (not text or data), no debug info>}
1235 if (strncmp(s, "{<text variable, ", 17) == 0 ||
1236 strncmp(s, "{<data variable, ", 17) == 0 ||
1237 strncmp(s, "{<variable (not text or data), ", 31) == 0)
1239 const char* start = s;
1240 skipNested(s, '{', '}');
1241 variable->m_value = QString::fromLatin1(start, s-start);
1242 variable->m_value += ' '; // add only a single space
1243 while (isspace(*s))
1244 s++;
1245 goto repeat;
1247 else
1249 s++;
1250 if (!parseNested(s, variable)) {
1251 return false;
1253 // must be the closing brace
1254 if (*s != '}') {
1255 TRACE("parse error: missing } of " + variable->m_name);
1256 return false;
1258 s++;
1259 // final white space
1260 while (isspace(*s))
1261 s++;
1264 // Sometimes we find a warning; it ends at the next LF
1265 else if (strncmp(s, "warning: ", 9) == 0) {
1266 const char* end = strchr(s, '\n');
1267 s = end ? end : s+strlen(s);
1268 // skip space at start of next line
1269 while (isspace(*s))
1270 s++;
1271 goto repeat;
1272 } else {
1273 // examples of leaf values (cannot be the empty string):
1274 // 123
1275 // -123
1276 // 23.575e+37
1277 // 0x32a45
1278 // @0x012ab4
1279 // (DwContentType&) @0x8123456: {...}
1280 // 0x32a45 "text"
1281 // 10 '\n'
1282 // <optimized out>
1283 // 0x823abc <Array<int> virtual table>
1284 // 0x40240f <globarstr> "test"
1285 // (void (*)()) 0x8048480 <f(E *, char)>
1286 // (E *) 0xbffff450
1287 // red
1288 // &parseP (HTMLClueV *, char *)
1289 // Variable "x" is not available.
1290 // The value of variable 'x' is distributed...
1291 // -nan(0xfffff081defa0)
1293 const char*p = s;
1295 // check for type
1296 QString type;
1297 if (*p == '(') {
1298 skipNested(p, '(', ')');
1300 while (isspace(*p))
1301 p++;
1302 variable->m_value = QString::fromLatin1(s, p - s);
1305 bool reference = false;
1306 if (*p == '@') {
1307 // skip reference marker
1308 p++;
1309 reference = true;
1311 const char* start = p;
1312 if (*p == '-')
1313 p++;
1315 // some values consist of more than one token
1316 bool checkMultiPart = false;
1318 if (p[0] == '0' && p[1] == 'x') {
1319 // parse hex number
1320 p += 2;
1321 while (isxdigit(*p))
1322 p++;
1325 * Assume this is a pointer, but only if it's not a reference, since
1326 * references can't be expanded.
1328 if (!reference) {
1329 variable->m_varKind = VarTree::VKpointer;
1330 } else {
1332 * References are followed by a colon, in which case we'll
1333 * find the value following the reference address.
1335 if (*p == ':') {
1336 p++;
1337 } else {
1338 // Paranoia. (Can this happen, i.e. reference not followed by ':'?)
1339 reference = false;
1342 checkMultiPart = true;
1343 } else if (isdigit(*p)) {
1344 // parse decimal number, possibly a float
1345 while (isdigit(*p))
1346 p++;
1347 if (*p == '.') { /* TODO: obey i18n? */
1348 // In long arrays an integer may be followed by '...'.
1349 // We test for this situation and don't gobble the '...'.
1350 if (p[1] != '.' || p[0] != '.') {
1351 // fractional part
1352 p++;
1353 while (isdigit(*p))
1354 p++;
1357 if (*p == 'e' || *p == 'E') {
1358 p++;
1359 // exponent
1360 if (*p == '-' || *p == '+')
1361 p++;
1362 while (isdigit(*p))
1363 p++;
1366 // for char variables there is the char, eg. 10 '\n'
1367 checkMultiPart = true;
1368 } else if (*p == '<') {
1369 // e.g. <optimized out>
1370 skipNestedAngles(p);
1371 } else if (*p == '"' || *p == '\'') {
1372 // character may have multipart: '\000' <repeats 11 times>
1373 checkMultiPart = *p == '\'';
1374 // found a string
1375 skipString(p);
1376 } else if (*p == 'L' && (p[1] == '"' || p[1] == '\'')) {
1377 // ditto for wchar_t strings
1378 checkMultiPart = p[1] == '\'';
1379 skipString(p);
1380 } else if (*p == '&') {
1381 // function pointer
1382 p++;
1383 skipName(p);
1384 while (isspace(*p)) {
1385 p++;
1387 if (*p == '(') {
1388 skipNested(p, '(', ')');
1390 } else if (strncmp(p, "Variable \"", 10) == 0) {
1391 // Variable "x" is not available.
1392 p += 10; // skip to "
1393 skipName(p);
1394 if (strncmp(p, "\" is not available.", 19) == 0) {
1395 p += 19;
1397 } else if (strncmp(p, "The value of variable '", 23) == 0) {
1398 p += 23;
1399 skipName(p);
1400 const char* e = strchr(p, '.');
1401 if (e == 0) {
1402 p += strlen(p);
1403 } else {
1404 p = e+1;
1406 } else {
1407 moreEnum:
1408 // must be an enumeration value
1409 skipName(p);
1410 // nan (floating point Not a Number) is followed by a number in ()
1411 // enum values can look like A::(anonymous namespace)::blue
1412 if (*p == '(') {
1413 bool isAnonNS = strncmp(p+1, "anonymous namespace)", 20) == 0;
1414 skipNested(p, '(', ')');
1415 if (isAnonNS)
1416 goto moreEnum;
1419 variable->m_value += QString::fromLatin1(start, p - start);
1421 // remove line breaks from the value; this is ok since
1422 // string values never contain a literal line break
1423 variable->m_value.replace('\n', ' ');
1425 while (checkMultiPart) {
1426 // white space
1427 while (isspace(*p))
1428 p++;
1429 // may be followed by a string or <...>
1430 // if this was a pointer with a string,
1431 // reset that pointer flag since we have now a value
1432 start = p;
1433 checkMultiPart = false;
1435 if (*p == '"' || *p == '\'') {
1436 skipString(p);
1437 variable->m_varKind = VarTree::VKsimple;
1438 } else if (*p == 'L' && (p[1] == '"' || p[1] == '\'')) {
1439 skipString(p); // wchar_t string
1440 variable->m_varKind = VarTree::VKsimple;
1441 } else if (*p == '<') {
1442 // if this value is part of an array, it might be followed
1443 // by <repeats 15 times>, which we don't skip here
1444 if (strncmp(p, "<repeats ", 9) != 0) {
1445 skipNestedAngles(p);
1446 checkMultiPart = true;
1449 if (p != start) {
1450 // there is always a blank before the string,
1451 // which we will include in the final string value
1452 variable->m_value += QString::fromLatin1(start-1, (p - start)+1);
1456 if (variable->m_value.length() == 0) {
1457 TRACE("parse error: no value for " + variable->m_name);
1458 return false;
1461 // final white space
1462 while (isspace(*p))
1463 p++;
1464 s = p;
1467 * If this was a reference, the value follows. It might even be a
1468 * composite variable!
1470 if (reference) {
1471 goto repeat;
1475 return true;
1478 static bool parseNested(const char*& s, ExprValue* variable)
1480 // could be a structure or an array
1481 while (isspace(*s))
1482 s++;
1484 const char* p = s;
1485 bool isStruct = false;
1487 * If there is a name followed by an = or an < -- which starts a type
1488 * name -- or "static", it is a structure
1490 if (*p == '<' || *p == '}') {
1491 isStruct = true;
1492 } else if (strncmp(p, "static ", 7) == 0) {
1493 isStruct = true;
1494 } else if (isalpha(*p) || *p == '_' || *p == '$') {
1495 // look ahead for a comma after the name
1496 skipName(p);
1497 while (isspace(*p))
1498 p++;
1499 if (*p == '=') {
1500 isStruct = true;
1502 p = s; /* rescan the name */
1504 if (isStruct) {
1505 if (!parseVarSeq(p, variable)) {
1506 return false;
1508 variable->m_varKind = VarTree::VKstruct;
1509 } else {
1510 if (!parseValueSeq(p, variable)) {
1511 return false;
1513 variable->m_varKind = VarTree::VKarray;
1515 s = p;
1516 return true;
1519 static bool parseVarSeq(const char*& s, ExprValue* variable)
1521 // parse a comma-separated sequence of variables
1522 ExprValue* var = variable; /* var != 0 to indicate success if empty seq */
1523 for (;;) {
1524 if (*s == '}')
1525 break;
1526 if (strncmp(s, "<No data fields>}", 17) == 0)
1528 // no member variables, so break out immediately
1529 s += 16; /* go to the closing brace */
1530 break;
1532 var = parseVar(s);
1533 if (var == 0)
1534 break; /* syntax error */
1535 variable->appendChild(var);
1536 if (*s != ',')
1537 break;
1538 // skip the comma and whitespace
1539 s++;
1540 while (isspace(*s))
1541 s++;
1543 return var != 0;
1546 static bool parseValueSeq(const char*& s, ExprValue* variable)
1548 // parse a comma-separated sequence of variables
1549 int index = 0;
1550 bool good;
1551 for (;;) {
1552 QString name;
1553 name.sprintf("[%d]", index);
1554 ExprValue* var = new ExprValue(name, VarTree::NKplain);
1555 good = parseValue(s, var);
1556 if (!good) {
1557 delete var;
1558 return false;
1560 // a value may be followed by "<repeats 45 times>"
1561 if (strncmp(s, "<repeats ", 9) == 0) {
1562 s += 9;
1563 char* end;
1564 int l = strtol(s, &end, 10);
1565 if (end == s || strncmp(end, " times>", 7) != 0) {
1566 // should not happen
1567 delete var;
1568 return false;
1570 TRACE(QString().sprintf("found <repeats %d times> in array", l));
1571 // replace name and advance index
1572 name.sprintf("[%d .. %d]", index, index+l-1);
1573 var->m_name = name;
1574 index += l;
1575 // skip " times>" and space
1576 s = end+7;
1577 // possible final space
1578 while (isspace(*s))
1579 s++;
1580 } else {
1581 index++;
1583 variable->appendChild(var);
1584 // long arrays may be terminated by '...'
1585 if (strncmp(s, "...", 3) == 0) {
1586 s += 3;
1587 ExprValue* var = new ExprValue("...", VarTree::NKplain);
1588 var->m_value = i18n("<additional entries of the array suppressed>");
1589 variable->appendChild(var);
1590 break;
1592 if (*s != ',') {
1593 break;
1595 // skip the comma and whitespace
1596 s++;
1597 while (isspace(*s))
1598 s++;
1599 // sometimes there is a closing brace after a comma
1600 // if (*s == '}')
1601 // break;
1603 return true;
1607 * Parses a stack frame.
1609 static void parseFrameInfo(const char*& s, QString& func,
1610 QString& file, int& lineNo, DbgAddr& address)
1612 const char* p = s;
1614 // next may be a hexadecimal address
1615 if (*p == '0') {
1616 const char* start = p;
1617 p++;
1618 if (*p == 'x')
1619 p++;
1620 while (isxdigit(*p))
1621 p++;
1622 address = QString::fromLatin1(start, p-start);
1623 if (strncmp(p, " in ", 4) == 0)
1624 p += 4;
1625 } else {
1626 address = DbgAddr();
1628 const char* start = p;
1629 // check for special signal handler frame
1630 if (strncmp(p, "<signal handler called>", 23) == 0) {
1631 func = QString::fromLatin1(start, 23);
1632 file = QString();
1633 lineNo = -1;
1634 s = p+23;
1635 if (*s == '\n')
1636 s++;
1637 return;
1641 * Skip the function name. It is terminated by a left parenthesis
1642 * which does not delimit "(anonymous namespace)" and which is
1643 * outside the angle brackets <> of template parameter lists
1644 * and is preceded by a space.
1646 while (*p != '\0')
1648 if (*p == '<') {
1649 // check for operator<< and operator<
1650 if (p-start >= 8 && strncmp(p-8, "operator", 8) == 0)
1652 p++;
1653 if (*p == '<')
1654 p++;
1656 else
1658 // skip template parameter list
1659 skipNestedAngles(p);
1661 } else if (*p == '(') {
1662 // this skips "(anonymous namespace)" as well as the formal
1663 // parameter list of the containing function if this is a member
1664 // of a nested class
1665 skipNestedWithString(p, '(', ')');
1666 } else if (*p == ' ') {
1667 ++p;
1668 if (*p == '(')
1669 break; // parameter list found
1670 } else {
1671 p++;
1675 if (*p == '\0') {
1676 func = start;
1677 file = QString();
1678 lineNo = -1;
1679 s = p;
1680 return;
1683 * Skip parameters. But notice that for complicated conversion
1684 * functions (eg. "operator int(**)()()", ie. convert to pointer to
1685 * pointer to function) as well as operator()(...) we have to skip
1686 * additional pairs of parentheses. Furthermore, recent gdbs write the
1687 * demangled name followed by the arguments in a pair of parentheses,
1688 * where the demangled name can end in "const".
1690 do {
1691 skipNestedWithString(p, '(', ')');
1692 while (isspace(*p))
1693 p++;
1694 // skip "const"
1695 if (strncmp(p, "const", 5) == 0) {
1696 p += 5;
1697 while (isspace(*p))
1698 p++;
1700 } while (*p == '(');
1702 // check for file position
1703 if (strncmp(p, "at ", 3) == 0) {
1704 p += 3;
1705 const char* fileStart = p;
1706 // go for the end of the line
1707 while (*p != '\0' && *p != '\n')
1708 p++;
1709 // search back for colon
1710 const char* colon = p;
1711 do {
1712 --colon;
1713 } while (*colon != ':');
1714 file = QString::fromLatin1(fileStart, colon-fileStart);
1715 lineNo = atoi(colon+1)-1;
1716 // skip new-line
1717 if (*p != '\0')
1718 p++;
1719 } else {
1720 // check for "from shared lib"
1721 if (strncmp(p, "from ", 5) == 0) {
1722 p += 5;
1723 // go for the end of the line
1724 while (*p != '\0' && *p != '\n')
1725 p++;
1726 // skip new-line
1727 if (*p != '\0')
1728 p++;
1730 file = "";
1731 lineNo = -1;
1733 // construct the function name (including file info)
1734 if (*p == '\0') {
1735 func = start;
1736 } else {
1737 func = QString::fromLatin1(start, p-start-1); /* don't include \n */
1739 s = p;
1742 * Replace \n (and whitespace around it) in func by a blank. We cannot
1743 * use QString::simplified() for this because this would also
1744 * simplify space that belongs to a string arguments that gdb sometimes
1745 * prints in the argument lists of the function.
1747 ASSERT(!isspace(func[0].toLatin1())); // there must be non-white before first \n
1748 int nl = 0;
1749 while ((nl = func.indexOf('\n', nl)) >= 0) {
1750 // search back to the beginning of the whitespace
1751 int startWhite = nl;
1752 do {
1753 --startWhite;
1754 } while (isspace(func[startWhite].toLatin1()));
1755 startWhite++;
1756 // search forward to the end of the whitespace
1757 do {
1758 nl++;
1759 } while (isspace(func[nl].toLatin1()));
1760 // replace
1761 func.replace(startWhite, nl-startWhite, " ");
1762 /* continue searching for more \n's at this place: */
1763 nl = startWhite+1;
1769 * Parses a stack frame including its frame number
1771 static bool parseFrame(const char*& s, int& frameNo, QString& func,
1772 QString& file, int& lineNo, DbgAddr& address)
1774 // Example:
1775 // #1 0x8048881 in Dl::Dl (this=0xbffff418, r=3214) at testfile.cpp:72
1776 // Breakpoint 3, Cl::f(int) const (this=0xbffff3c0, x=17) at testfile.cpp:155
1778 // must start with a hash mark followed by number
1779 // or with "Breakpoint " followed by number and comma
1780 if (s[0] == '#') {
1781 if (!isdigit(s[1]))
1782 return false;
1783 s++; /* skip the hash mark */
1784 } else if (strncmp(s, "Breakpoint ", 11) == 0) {
1785 if (!isdigit(s[11]))
1786 return false;
1787 s += 11; /* skip "Breakpoint" */
1788 } else
1789 return false;
1791 // frame number
1792 frameNo = atoi(s);
1793 while (isdigit(*s))
1794 s++;
1795 // space and comma
1796 while (isspace(*s) || *s == ',')
1797 s++;
1798 parseFrameInfo(s, func, file, lineNo, address);
1799 return true;
1802 void GdbDriver::parseBackTrace(const char* output, std::list<StackFrame>& stack)
1804 QString func, file;
1805 int lineNo, frameNo;
1806 DbgAddr address;
1808 while (::parseFrame(output, frameNo, func, file, lineNo, address)) {
1809 stack.push_back(StackFrame());
1810 StackFrame* frm = &stack.back();
1811 frm->frameNo = frameNo;
1812 frm->fileName = file;
1813 frm->lineNo = lineNo;
1814 frm->address = address;
1815 frm->var = new ExprValue(func, VarTree::NKplain);
1819 bool GdbDriver::parseFrameChange(const char* output, int& frameNo,
1820 QString& file, int& lineNo, DbgAddr& address)
1822 QString func;
1823 return ::parseFrame(output, frameNo, func, file, lineNo, address);
1827 bool GdbDriver::parseBreakList(const char* output, std::list<Breakpoint>& brks)
1829 // skip first line, which is the headline
1830 const char* p = strchr(output, '\n');
1831 if (p == 0)
1832 return false;
1833 p++;
1834 if (*p == '\0')
1835 return false;
1837 // split up a line
1838 const char* end;
1839 char* dummy;
1840 while (*p != '\0') {
1841 Breakpoint bp;
1842 // get Num
1843 bp.id = strtol(p, &dummy, 10); /* don't care about overflows */
1844 p = dummy;
1845 // check for continued <MULTIPLE> breakpoint
1846 if (*p == '.' && isdigit(p[1]))
1848 // continuation: skip type and disposition
1850 else
1852 // get Type
1853 while (isspace(*p))
1854 p++;
1855 if (strncmp(p, "breakpoint", 10) == 0) {
1856 p += 10;
1857 } else if (strncmp(p, "hw watchpoint", 13) == 0) {
1858 bp.type = Breakpoint::watchpoint;
1859 p += 13;
1860 } else if (strncmp(p, "watchpoint", 10) == 0) {
1861 bp.type = Breakpoint::watchpoint;
1862 p += 10;
1864 while (isspace(*p))
1865 p++;
1866 if (*p == '\0')
1867 break;
1868 // get Disp
1869 bp.temporary = *p++ == 'd';
1871 while (*p != '\0' && !isspace(*p)) /* "keep" or "del" */
1872 p++;
1873 while (isspace(*p))
1874 p++;
1875 if (*p == '\0')
1876 break;
1877 // get Enb
1878 bp.enabled = *p++ == 'y';
1879 while (*p != '\0' && !isspace(*p)) /* "y" or "n" */
1880 p++;
1881 while (isspace(*p))
1882 p++;
1883 if (*p == '\0')
1884 break;
1885 // the address, if present
1886 if (bp.type == Breakpoint::breakpoint &&
1887 strncmp(p, "0x", 2) == 0)
1889 const char* start = p;
1890 while (*p != '\0' && !isspace(*p))
1891 p++;
1892 bp.address = QString::fromLatin1(start, p-start);
1893 while (isspace(*p) && *p != '\n')
1894 p++;
1895 if (*p == '\0')
1896 break;
1898 // remainder is location, hit and ignore count, condition
1899 end = strchr(p, '\n');
1900 if (end == 0) {
1901 bp.location = p;
1902 p += bp.location.length();
1903 } else {
1904 // location of a <MULTIPLE> filled in from subsequent breakpoints
1905 if (strncmp(p, "<MULTIPLE>", 10) != 0)
1906 bp.location = QString::fromLatin1(p, end-p).trimmed();
1907 p = end+1; /* skip over \n */
1910 // may be continued in next line
1911 while (isspace(*p)) { /* p points to beginning of line */
1912 // skip white space at beginning of line
1913 while (isspace(*p))
1914 p++;
1916 // seek end of line
1917 end = strchr(p, '\n');
1918 if (end == 0)
1919 end = p+strlen(p);
1921 if (strncmp(p, "breakpoint already hit", 22) == 0) {
1922 // extract the hit count
1923 p += 22;
1924 bp.hitCount = strtol(p, &dummy, 10);
1925 TRACE(QString("hit count %1").arg(bp.hitCount));
1926 } else if (strncmp(p, "stop only if ", 13) == 0) {
1927 // extract condition
1928 p += 13;
1929 bp.condition = QString::fromLatin1(p, end-p).trimmed();
1930 TRACE("condition: "+bp.condition);
1931 } else if (strncmp(p, "ignore next ", 12) == 0) {
1932 // extract ignore count
1933 p += 12;
1934 bp.ignoreCount = strtol(p, &dummy, 10);
1935 TRACE(QString("ignore count %1").arg(bp.ignoreCount));
1936 } else {
1937 // indeed a continuation
1938 bp.location += " " + QString::fromLatin1(p, end-p).trimmed();
1940 p = end;
1941 if (*p != '\0')
1942 p++; /* skip '\n' */
1945 if (brks.empty() || brks.back().id != bp.id) {
1946 brks.push_back(bp);
1947 } else {
1948 // this is a continuation; fill in location if not yet set
1949 // otherwise, drop this breakpoint
1950 Breakpoint& mbp = brks.back();
1951 if (mbp.location.isEmpty() && !bp.location.isEmpty()) {
1952 mbp.location = bp.location;
1953 mbp.address = bp.address;
1954 } else if (mbp.address.isEmpty() && !bp.address.isEmpty()) {
1955 mbp.address = bp.address;
1959 return true;
1962 std::list<ThreadInfo> GdbDriver::parseThreadList(const char* output)
1964 std::list<ThreadInfo> threads;
1965 if (strcmp(output, "\n") == 0 ||
1966 strncmp(output, "No stack.", 9) == 0 ||
1967 strncmp(output, "No threads.", 11) == 0) {
1968 // no threads
1969 return threads;
1972 bool newFormat = false;
1973 const char* p = output;
1974 while (*p != '\0') {
1975 ThreadInfo thr;
1976 // seach look for thread id, watching out for the focus indicator
1977 thr.hasFocus = false;
1978 while (isspace(*p)) /* may be \n from prev line: see "No stack" below */
1979 p++;
1981 // recent GDBs write a header line; skip it
1982 if (threads.empty() && strncmp(p, "Id Target", 11) == 0) {
1983 p = strchr(p, '\n');
1984 if (p == NULL)
1985 break;
1986 newFormat = true;
1987 continue; // next line please, '\n' is skipped above
1990 if (*p == '*') {
1991 thr.hasFocus = true;
1992 p++;
1993 // there follows only whitespace
1995 const char* end;
1996 char *temp_end = NULL; /* we need a non-const 'end' for strtol to use...*/
1997 thr.id = strtol(p, &temp_end, 10);
1998 end = temp_end;
1999 if (p == end) {
2000 // syntax error: no number found; bail out
2001 return threads;
2003 p = end;
2005 // skip space
2006 while (isspace(*p))
2007 p++;
2010 * Now follows the thread's SYSTAG.
2012 if (!newFormat) {
2013 // In the old format, it is terminated by two blanks.
2014 end = strstr(p, " ");
2015 if (end == 0) {
2016 // syntax error; bail out
2017 return threads;
2019 end += 2;
2020 } else {
2021 // In the new format lies crazyness: there is no definitive
2022 // end marker. At best we can guess when the SYSTAG ends.
2023 // A typical thread list on Linux looks like this:
2025 // Id Target Id Frame
2026 // 2 Thread 0x7ffff7854700 (LWP 10827) "thrserver" 0x00007ffff7928631 in clone () from /lib64/libc.so.6
2027 // * 1 Thread 0x7ffff7fcc700 (LWP 10808) "thrserver" main () at thrserver.c:84
2029 // Looking at GDB's code, the Target Id ends in tokens that
2030 // are bracketed by parentheses or quotes. Therefore,
2031 // we skip (at most) two tokens ('Thread' and the address),
2032 // and then all parts that are in parentheses or quotes.
2033 int n = 0;
2034 end = p;
2035 while (*end) {
2036 if (*end == '"') {
2037 skipString(end);
2038 n = 2;
2039 } else if (*end == '(') {
2040 skipNested(end, '(', ')');
2041 n = 2;
2042 } else if (n < 2) {
2043 while (*end && !isspace(*end))
2044 ++end;
2045 ++n;
2046 } else {
2047 break;
2049 while (isspace(*end))
2050 ++end;
2053 thr.threadName = QString::fromLatin1(p, end-p).trimmed();
2054 p = end;
2057 * Now follows a standard stack frame. Sometimes, however, gdb
2058 * catches a thread at an instant where it doesn't have a stack.
2060 if (strncmp(p, "[No stack.]", 11) != 0) {
2061 ::parseFrameInfo(p, thr.function, thr.fileName, thr.lineNo, thr.address);
2062 } else {
2063 thr.function = "[No stack]";
2064 thr.lineNo = -1;
2065 p += 11; /* \n is skipped above */
2068 threads.push_back(thr);
2070 return threads;
2073 static bool parseNewBreakpoint(const char* o, int& id,
2074 QString& file, int& lineNo, QString& address);
2075 static bool parseNewWatchpoint(const char* o, int& id,
2076 QString& expr);
2078 bool GdbDriver::parseBreakpoint(const char* output, int& id,
2079 QString& file, int& lineNo, QString& address)
2081 // skip lines of that begin with "(Cannot find"
2082 while (strncmp(output, "(Cannot find", 12) == 0 ||
2083 strncmp(output, "Note: breakpoint", 16) == 0)
2085 output = strchr(output, '\n');
2086 if (output == 0)
2087 return false;
2088 output++; /* skip newline */
2091 if (strncmp(output, "Breakpoint ", 11) == 0) {
2092 output += 11; /* skip "Breakpoint " */
2093 return ::parseNewBreakpoint(output, id, file, lineNo, address);
2094 } else if (strncmp(output, "Temporary breakpoint ", 21) == 0) {
2095 output += 21;
2096 return ::parseNewBreakpoint(output, id, file, lineNo, address);
2097 } else if (strncmp(output, "Hardware watchpoint ", 20) == 0) {
2098 output += 20;
2099 return ::parseNewWatchpoint(output, id, address);
2100 } else if (strncmp(output, "Watchpoint ", 11) == 0) {
2101 output += 11;
2102 return ::parseNewWatchpoint(output, id, address);
2104 return false;
2107 static bool parseNewBreakpoint(const char* o, int& id,
2108 QString& file, int& lineNo, QString& address)
2110 // breakpoint id
2111 char* p;
2112 id = strtoul(o, &p, 10);
2113 if (p == o)
2114 return false;
2116 // check for the address
2117 if (strncmp(p, " at 0x", 6) == 0) {
2118 char* start = p+4; /* skip " at ", but not 0x */
2119 p += 6;
2120 while (isxdigit(*p))
2121 ++p;
2122 address = QString::fromLatin1(start, p-start);
2126 * Mostly, GDB responds with this syntax:
2128 * Breakpoint 1 at 0x400b94: file multibrkpt.cpp, line 9. (2 locations)
2130 * but sometimes it uses this syntax:
2132 * Breakpoint 4 at 0x804f158: lotto739.cpp:95. (3 locations)
2134 char* fileEnd, *numStart = 0;
2135 char* fileStart = strstr(p, "file ");
2136 if (fileStart != 0)
2138 fileStart += 5;
2139 fileEnd = strstr(fileStart, ", line ");
2140 if (fileEnd != 0)
2141 numStart = fileEnd + 7;
2143 if (numStart == 0 && p[0] == ':' && p[1] == ' ')
2145 fileStart = p+2;
2146 while (isspace(*fileStart))
2147 ++fileStart;
2148 fileEnd = strchr(fileStart, ':');
2149 if (fileEnd != 0)
2150 numStart = fileEnd + 1;
2152 if (numStart == 0)
2153 return !address.isEmpty(); /* parse error only if there's no address */
2155 QString fileName = QString::fromLatin1(fileStart, fileEnd-fileStart);
2156 int line = strtoul(numStart, &p, 10);
2157 if (numStart == p)
2158 return false;
2160 file = fileName;
2161 lineNo = line-1; /* zero-based! */
2162 return true;
2165 static bool parseNewWatchpoint(const char* o, int& id,
2166 QString& expr)
2168 // watchpoint id
2169 char* p;
2170 id = strtoul(o, &p, 10);
2171 if (p == o)
2172 return false;
2174 if (strncmp(p, ": ", 2) != 0)
2175 return false;
2176 p += 2;
2178 // all the rest on the line is the expression
2179 expr = QString::fromLatin1(p, strlen(p)).trimmed();
2180 return true;
2183 void GdbDriver::parseLocals(const char* output, std::list<ExprValue*>& newVars)
2185 // check for possible error conditions
2186 if (strncmp(output, "No symbol table", 15) == 0)
2188 return;
2191 while (*output != '\0') {
2192 while (isspace(*output))
2193 output++;
2194 if (*output == '\0')
2195 break;
2196 // skip occurrences of "No locals" and "No args"
2197 if (strncmp(output, "No locals", 9) == 0 ||
2198 strncmp(output, "No arguments", 12) == 0)
2200 output = strchr(output, '\n');
2201 if (output == 0) {
2202 break;
2204 continue;
2207 ExprValue* variable = parseVar(output);
2208 if (variable == 0) {
2209 break;
2211 // do not add duplicates
2212 for (std::list<ExprValue*>::iterator o = newVars.begin(); o != newVars.end(); ++o) {
2213 if ((*o)->m_name == variable->m_name) {
2214 delete variable;
2215 goto skipDuplicate;
2218 newVars.push_back(variable);
2219 skipDuplicate:;
2223 ExprValue* GdbDriver::parsePrintExpr(const char* output, bool wantErrorValue)
2225 ExprValue* var = 0;
2226 // check for error conditions
2227 if (!parseErrorMessage(output, var, wantErrorValue))
2229 // parse the variable
2230 var = parseVar(output);
2232 return var;
2235 bool GdbDriver::parseChangeWD(const char* output, QString& message)
2237 bool isGood = false;
2238 message = QString(output).simplified();
2239 if (message.isEmpty()) {
2240 message = i18n("New working directory: ") + m_programWD;
2241 isGood = true;
2243 return isGood;
2246 bool GdbDriver::parseChangeExecutable(const char* output, QString& message)
2248 message = output;
2250 m_haveCoreFile = false;
2253 * Lines starting with the following do not indicate errors:
2254 * Using host libthread_db
2255 * (no debugging symbols found)
2256 * Reading symbols from
2258 while (strncmp(output, "Reading symbols from", 20) == 0 ||
2259 strncmp(output, "done.", 5) == 0 ||
2260 strncmp(output, "Missing separate debuginfo", 26) == 0 ||
2261 strncmp(output, "Try: ", 5) == 0 ||
2262 strncmp(output, "Using host libthread_db", 23) == 0 ||
2263 strncmp(output, "(no debugging symbols found)", 28) == 0)
2265 // this line is good, go to the next one
2266 const char* end = strchr(output, '\n');
2267 if (end == 0)
2268 output += strlen(output);
2269 else
2270 output = end+1;
2274 * If we've parsed all lines, there was no error.
2276 return output[0] == '\0';
2279 bool GdbDriver::parseCoreFile(const char* output)
2281 // if command succeeded, gdb emits a line starting with "#0 "
2282 m_haveCoreFile = strstr(output, "\n#0 ") != 0;
2283 return m_haveCoreFile;
2286 uint GdbDriver::parseProgramStopped(const char* output, QString& message)
2288 // optionally: "program changed, rereading symbols",
2289 // followed by:
2290 // "Program exited normally"
2291 // "Program terminated with wignal SIGSEGV"
2292 // "Program received signal SIGINT" or other signal
2293 // "Breakpoint..."
2294 // GDB since 7.3 prints
2295 // "[Inferior 1 (process 13400) exited normally]"
2296 // "[Inferior 1 (process 14698) exited with code 01]"
2298 // go through the output, line by line, checking what we have
2299 const char* start = output - 1;
2300 uint flags = SFprogramActive;
2301 message = QString();
2302 do {
2303 start++; /* skip '\n' */
2305 if (strncmp(start, "Program ", 8) == 0 ||
2306 strncmp(start, "ptrace: ", 8) == 0) {
2308 * When we receive a signal, the program remains active.
2310 * Special: If we "stopped" in a corefile, the string "Program
2311 * terminated with signal"... is displayed. (Normally, we see
2312 * "Program received signal"... when a signal happens.)
2314 if (strncmp(start, "Program exited", 14) == 0 ||
2315 (strncmp(start, "Program terminated", 18) == 0 && !m_haveCoreFile) ||
2316 strncmp(start, "ptrace: ", 8) == 0)
2318 flags &= ~SFprogramActive;
2321 // set message
2322 const char* endOfMessage = strchr(start, '\n');
2323 if (endOfMessage == 0)
2324 endOfMessage = start + strlen(start);
2325 message = QString::fromLatin1(start, endOfMessage-start);
2326 } else if (strncmp(start, "[Inferior ", 10) == 0) {
2327 const char* p = start + 10;
2328 // skip number and space
2329 while (*p && !isspace(*p))
2330 ++p;
2331 while (isspace(*p))
2332 ++p;
2333 if (*p == '(') {
2334 skipNested(p, '(', ')');
2335 if (strncmp(p, " exited ", 8) == 0) {
2336 flags &= ~SFprogramActive;
2338 // set message
2339 const char* end = strchr(p, '\n');
2340 if (end == 0)
2341 end = p + strlen(p);
2342 // strip [] from the message
2343 message = QString::fromLatin1(start+1, end-start-2);
2346 } else if (strncmp(start, "Breakpoint ", 11) == 0) {
2348 * We stopped at a (permanent) breakpoint (gdb doesn't tell us
2349 * that it stopped at a temporary breakpoint).
2351 flags |= SFrefreshBreak;
2352 } else if (strstr(start, "re-reading symbols.") != 0) {
2353 flags |= SFrefreshSource;
2356 // next line, please
2357 start = strchr(start, '\n');
2358 } while (start != 0);
2361 * Gdb only notices when new threads have appeared, but not when a
2362 * thread finishes. So we always have to assume that the list of
2363 * threads has changed.
2365 flags |= SFrefreshThreads;
2367 return flags;
2370 QStringList GdbDriver::parseSharedLibs(const char* output)
2372 QStringList shlibs;
2373 if (strncmp(output, "No shared libraries loaded", 26) == 0)
2374 return shlibs;
2376 // parse the table of shared libraries
2378 // strip off head line
2379 output = strchr(output, '\n');
2380 if (output == 0)
2381 return shlibs;
2382 output++; /* skip '\n' */
2383 QString shlibName;
2384 while (*output != '\0') {
2385 // format of a line is
2386 // 0x404c5000 0x40580d90 Yes /lib/libc.so.5
2387 // 3 blocks of non-space followed by space
2388 for (int i = 0; *output != '\0' && i < 3; i++) {
2389 while (*output != '\0' && !isspace(*output)) { /* non-space */
2390 output++;
2392 while (isspace(*output)) { /* space */
2393 output++;
2396 if (*output == '\0')
2397 return shlibs;
2398 const char* start = output;
2399 output = strchr(output, '\n');
2400 if (output == 0)
2401 output = start + strlen(start);
2402 shlibName = QString::fromLatin1(start, output-start);
2403 if (*output != '\0')
2404 output++;
2405 shlibs.append(shlibName);
2406 TRACE("found shared lib " + shlibName);
2408 return shlibs;
2411 bool GdbDriver::parseFindType(const char* output, QString& type)
2413 if (strncmp(output, "type = ", 7) != 0)
2414 return false;
2417 * Everything else is the type. We strip off any leading "const" and any
2418 * trailing "&" on the grounds that neither affects the decoding of the
2419 * object. We also strip off all white-space from the type.
2421 output += 7;
2422 if (strncmp(output, "const ", 6) == 0)
2423 output += 6;
2424 type = output;
2425 type.replace(QRegExp("\\s+"), "");
2426 if (type.endsWith("&"))
2427 type.truncate(type.length() - 1);
2428 return true;
2431 std::list<RegisterInfo> GdbDriver::parseRegisters(const char* output)
2433 std::list<RegisterInfo> regs;
2434 if (strncmp(output, "The program has no registers now", 32) == 0) {
2435 return regs;
2438 // parse register values
2439 while (*output != '\0')
2441 RegisterInfo reg;
2442 // skip space at the start of the line
2443 while (isspace(*output))
2444 output++;
2446 // register name
2447 const char* start = output;
2448 while (*output != '\0' && !isspace(*output))
2449 output++;
2450 if (*output == '\0')
2451 break;
2452 reg.regName = QString::fromLatin1(start, output-start);
2454 // skip space
2455 while (isspace(*output))
2456 output++;
2458 QString value;
2461 * If we find a brace now, this is a vector register. We look for
2462 * the closing brace and treat the result as cooked value.
2464 if (*output == '{')
2466 start = output;
2467 skipNested(output, '{', '}');
2468 value = QString::fromLatin1(start, output-start).simplified();
2469 // skip space, but not the end of line
2470 while (isspace(*output) && *output != '\n')
2471 output++;
2472 // get rid of the braces at the begining and the end
2473 value.remove(0, 1);
2474 if (value[value.length()-1] == '}') {
2475 value = value.left(value.length()-1);
2477 // gdb 5.3 doesn't print a separate set of raw values
2478 if (*output == '{') {
2479 // another set of vector follows
2480 // what we have so far is the raw value
2481 reg.rawValue = value;
2483 start = output;
2484 skipNested(output, '{', '}');
2485 value = QString::fromLatin1(start, output-start).simplified();
2486 } else {
2487 // for gdb 5.3
2488 // find first type that does not have an array, this is the RAW value
2489 const char* end=start;
2490 findEnd(end);
2491 const char* cur=start;
2492 while (cur<end) {
2493 while (*cur != '=' && cur<end)
2494 cur++;
2495 cur++;
2496 while (isspace(*cur) && cur<end)
2497 cur++;
2498 if (isNumberish(*cur)) {
2499 end=cur;
2500 while (*end && (*end!='}') && (*end!=',') && (*end!='\n'))
2501 end++;
2502 QString rawValue = QString::fromLatin1(cur, end-cur).simplified();
2503 reg.rawValue = rawValue;
2505 if (rawValue.left(2)=="0x") {
2506 // ok we have a raw value, now get it's type
2507 end=cur-1;
2508 while (isspace(*end) || *end=='=') end--;
2509 end++;
2510 cur=end-1;
2511 while (*cur!='{' && *cur!=' ')
2512 cur--;
2513 cur++;
2514 reg.type = QString::fromLatin1(cur, end-cur);
2517 // end while loop
2518 cur=end;
2521 // skip to the end of line
2522 while (*output != '\0' && *output != '\n')
2523 output++;
2524 // get rid of the braces at the begining and the end
2525 value.remove(0, 1);
2526 if (value[value.length()-1] == '}') {
2527 value.truncate(value.length()-1);
2530 reg.cookedValue = value;
2532 else
2534 continuation:
2535 // the rest of the line is the register value
2536 start = output;
2537 output = strchr(output,'\n');
2538 if (output == 0)
2539 output = start + strlen(start);
2540 value += QString::fromLatin1(start, output-start).simplified();
2543 * Look ahead: if the subsequent line is indented, it continues
2544 * the current register value.
2546 if (output != 0 && isspace(output[1]))
2548 ++output;
2549 value += ' ';
2550 goto continuation;
2554 * We split the raw from the cooked values.
2555 * Some modern gdbs explicitly say: "0.1234 (raw 0x3e4567...)".
2556 * Here, the cooked value comes first, and the raw value is in
2557 * the second part.
2559 int pos = value.indexOf(" (raw ");
2560 if (pos >= 0)
2562 reg.cookedValue = value.left(pos);
2563 reg.rawValue = value.mid(pos+6);
2564 if (reg.rawValue.right(1) == ")") // remove closing bracket
2565 reg.rawValue.truncate(reg.rawValue.length()-1);
2567 else
2570 * In other cases we split off the first token (separated by
2571 * whitespace). It is the raw value. The remainder of the line
2572 * is the cooked value.
2574 int pos = value.indexOf(' ');
2575 if (pos < 0) {
2576 reg.rawValue = value;
2577 reg.cookedValue = QString();
2578 } else {
2579 reg.rawValue = value.left(pos);
2580 reg.cookedValue = value.mid(pos+1);
2584 if (*output != '\0')
2585 output++; /* skip '\n' */
2587 regs.push_back(reg);
2589 return regs;
2592 bool GdbDriver::parseInfoLine(const char* output, QString& addrFrom, QString& addrTo)
2594 // "is at address" or "starts at address"
2595 const char* start = strstr(output, "s at address ");
2596 if (start == 0)
2597 return false;
2599 start += 13;
2600 const char* p = start;
2601 while (*p != '\0' && !isspace(*p))
2602 p++;
2603 addrFrom = QString::fromLatin1(start, p-start);
2605 start = strstr(p, "and ends at ");
2606 if (start == 0) {
2607 addrTo = addrFrom;
2608 return true;
2611 start += 12;
2612 p = start;
2613 while (*p != '\0' && !isspace(*p))
2614 p++;
2615 addrTo = QString::fromLatin1(start, p-start);
2617 return true;
2620 std::list<DisassembledCode> GdbDriver::parseDisassemble(const char* output)
2622 std::list<DisassembledCode> code;
2624 if (strncmp(output, "Dump of assembler", 17) != 0) {
2625 // error message?
2626 DisassembledCode c;
2627 c.code = output;
2628 code.push_back(c);
2629 return code;
2632 // remove first line
2633 const char* p = strchr(output, '\n');
2634 if (p == 0)
2635 return code; /* not a regular output */
2637 p++;
2639 // remove last line
2640 const char* end = strstr(output, "End of assembler");
2641 if (end == 0)
2642 end = p + strlen(p);
2644 // remove function offsets from the lines
2645 while (p != end)
2647 DisassembledCode c;
2648 // skip initial space or PC pointer ("=>", since gdb 7.1)
2649 while (p != end) {
2650 if (isspace(*p))
2651 ++p;
2652 else if (p[0] == '=' && p[1] == '>')
2653 p += 2;
2654 else
2655 break;
2657 const char* start = p;
2658 // address
2659 while (p != end && !isspace(*p))
2660 p++;
2661 c.address = QString::fromLatin1(start, p-start);
2663 // function name (enclosed in '<>', followed by ':')
2664 while (p != end && *p != '<')
2665 p++;
2666 if (*p == '<')
2667 skipNestedAngles(p);
2668 if (*p == ':')
2669 p++;
2671 // space until code
2672 while (p != end && isspace(*p))
2673 p++;
2675 // code until end of line
2676 start = p;
2677 while (p != end && *p != '\n')
2678 p++;
2679 if (p != end) /* include '\n' */
2680 p++;
2682 c.code = QString::fromLatin1(start, p-start);
2683 code.push_back(c);
2685 return code;
2688 QString GdbDriver::parseMemoryDump(const char* output, std::list<MemoryDump>& memdump)
2690 if (isErrorExpr(output)) {
2691 // error; strip space
2692 QString msg = output;
2693 return msg.trimmed();
2696 const char* p = output; /* save typing */
2698 // the address
2699 while (*p != 0) {
2700 MemoryDump md;
2702 const char* start = p;
2703 while (*p != '\0' && *p != ':' && !isspace(*p))
2704 p++;
2705 md.address = QString::fromLatin1(start, p-start);
2706 if (*p != ':') {
2707 // parse function offset
2708 while (isspace(*p))
2709 p++;
2710 start = p;
2711 while (*p != '\0' && !(*p == ':' && isspace(p[1])))
2712 p++;
2713 md.address.fnoffs = QString::fromLatin1(start, p-start);
2715 if (*p == ':')
2716 p++;
2717 // skip space; this may skip a new-line char!
2718 while (isspace(*p))
2719 p++;
2720 // everything to the end of the line is the memory dump
2721 const char* end = strchr(p, '\n');
2722 if (end != 0) {
2723 md.dump = QString::fromLatin1(p, end-p);
2724 p = end+1;
2725 } else {
2726 md.dump = QString::fromLatin1(p, strlen(p));
2727 p += strlen(p);
2729 memdump.push_back(md);
2732 return QString();
2735 QString GdbDriver::editableValue(VarTree* value)
2737 QByteArray ba = value->value().toLatin1();
2738 const char* s = ba.constData();
2740 // if the variable is a pointer value that contains a cast,
2741 // remove the cast
2742 if (*s == '(') {
2743 skipNested(s, '(', ')');
2744 // skip space
2745 while (isspace(*s))
2746 ++s;
2749 repeat:
2750 const char* start = s;
2752 if (strncmp(s, "0x", 2) == 0)
2754 s += 2;
2755 while (isxdigit(*s))
2756 ++s;
2759 * What we saw so far might have been a reference. If so, edit the
2760 * referenced value. Otherwise, edit the pointer.
2762 if (*s == ':') {
2763 // a reference
2764 ++s;
2765 goto repeat;
2767 // a pointer
2768 // if it's a pointer to a string, remove the string
2769 const char* end = s;
2770 while (isspace(*s))
2771 ++s;
2772 if (*s == '"') {
2773 // a string
2774 return QString::fromLatin1(start, end-start);
2775 } else {
2776 // other pointer
2777 return QString::fromLatin1(start, strlen(start));
2781 // else leave it unchanged (or stripped of the reference preamble)
2782 return s;
2785 QString GdbDriver::parseSetVariable(const char* output)
2787 // if there is any output, it is an error message
2788 QString msg = output;
2789 return msg.trimmed();
2793 #include "gdbdriver.moc"