Update version number and build instructions in the spec file.
[kdbg.git] / kdbg / gdbdriver.cpp
blobb764a06c201a6241eb665448f8ea0be5ba8dd3c4
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 * Don't assume that program functions invoked from a watch expression
243 * always succeed.
245 "set unwindonsignal on\n"
247 * Write a short macro that prints all locals: local variables and
248 * function arguments.
250 "define kdbg__alllocals\n"
251 "info locals\n" /* local vars supersede args with same name */
252 "info args\n" /* therefore, arguments must come last */
253 "end\n"
255 * Work around a bug in gdb-6.3: "info line main" crashes gdb.
257 "define kdbg_infolinemain\n"
258 "list\n"
259 "info line\n"
260 "end\n"
261 // change prompt string and synchronize with gdb
262 "set prompt " PROMPT "\n"
265 executeCmdString(DCinitialize, gdbInitialize, false);
267 // assume that QString::null is ok
268 cmds[DCprintQStringStruct].fmt = printQStringStructFmt;
270 return true;
273 void GdbDriver::commandFinished(CmdQueueItem* cmd)
275 // command string must be committed
276 if (!cmd->m_committed) {
277 // not commited!
278 TRACE("calling " + (__PRETTY_FUNCTION__ + (" with uncommited command:\n\t" +
279 cmd->m_cmdString)));
280 return;
283 switch (cmd->m_cmd) {
284 case DCinitialize:
287 * Check for GDB 7.1 or later; the syntax for the disassemble
288 * command has changed.
289 * This RE picks the last version number in the first line,
290 * because at least OpenSUSE writes its own version number
291 * in the first line (but before GDB's version number).
293 QRegExp re(
294 " " // must be preceded by space
295 "[(]?" // SLES 10 embeds in parentheses
296 "(\\d+)\\.(\\d+)" // major, minor
297 "[^ ]*\\n" // no space until end of line
299 int pos = re.indexIn(m_output);
300 const char* disass = "disassemble %s %s\n";
301 if (pos >= 0) {
302 int major = re.cap(1).toInt();
303 int minor = re.cap(2).toInt();
304 if (major > 7 || (major == 7 && minor >= 1))
306 disass = "disassemble %s, %s\n";
309 cmds[DCdisassemble].fmt = disass;
311 break;
312 default:;
315 /* ok, the command is ready */
316 emit commandReceived(cmd, m_output.constData());
318 switch (cmd->m_cmd) {
319 case DCcorefile:
320 case DCinfolinemain:
321 case DCinfoline:
322 case DCframe:
323 case DCattach:
324 case DCrun:
325 case DCcont:
326 case DCstep:
327 case DCstepi:
328 case DCnext:
329 case DCnexti:
330 case DCfinish:
331 case DCuntil:
332 parseMarker(cmd);
333 default:;
337 int GdbDriver::findPrompt(const QByteArray& output) const
340 * If there's a prompt string in the collected output, it must be at
341 * the very end.
343 * Note: It could nevertheless happen that a character sequence that is
344 * equal to the prompt string appears at the end of the output,
345 * although it is very, very unlikely (namely as part of a string that
346 * lingered in gdb's output buffer due to some timing/heavy load
347 * conditions for a very long time such that that buffer overflowed
348 * exactly at the end of the prompt string look-a-like).
350 int len = output.length();
351 if (len >= PROMPT_LEN &&
352 strncmp(output.data()+len-PROMPT_LEN, PROMPT, PROMPT_LEN) == 0)
354 return len-PROMPT_LEN;
356 return -1;
360 * The --fullname option makes gdb send a special normalized sequence print
361 * each time the program stops and at some other points. The sequence has
362 * the form "\032\032filename:lineno:charoffset:(beg|middle):address".
364 void GdbDriver::parseMarker(CmdQueueItem* cmd)
366 char* startMarker = strstr(m_output.data(), "\032\032");
367 if (startMarker == 0)
368 return;
370 // extract the marker
371 startMarker += 2;
372 TRACE(QString("found marker: ") + startMarker);
373 char* endMarker = strchr(startMarker, '\n');
374 if (endMarker == 0)
375 return;
377 *endMarker = '\0';
379 // extract filename and line number
380 static QRegExp MarkerRE(":(\\d+):\\d+:[begmidl]+:0x");
382 int lineNoStart = MarkerRE.indexIn(startMarker);
383 if (lineNoStart >= 0) {
384 int lineNo = MarkerRE.cap(1).toInt();
386 // get address unless there is one in cmd
387 DbgAddr address = cmd->m_addr;
388 if (address.isEmpty()) {
389 const char* addrStart = startMarker + lineNoStart +
390 MarkerRE.matchedLength() - 2;
391 address = QString(addrStart).trimmed();
394 // now show the window
395 startMarker[lineNoStart] = '\0'; /* split off file name */
396 emit activateFileLine(startMarker, lineNo-1, address);
402 * Escapes characters that might lead to problems when they appear on gdb's
403 * command line.
405 static void normalizeStringArg(QString& arg)
408 * Remove trailing backslashes. This approach is a little simplistic,
409 * but we know that there is at the moment no case where a trailing
410 * backslash would make sense.
412 while (!arg.isEmpty() && arg[arg.length()-1] == '\\') {
413 arg = arg.left(arg.length()-1);
418 QString GdbDriver::makeCmdString(DbgCommand cmd, QString strArg)
420 assert(cmd >= 0 && cmd < NUM_CMDS);
421 assert(cmds[cmd].argsNeeded == GdbCmdInfo::argString);
423 normalizeStringArg(strArg);
425 if (cmd == DCcd) {
426 // need the working directory when parsing the output
427 m_programWD = strArg;
428 } else if (cmd == DCsetargs && !m_redirect.isEmpty()) {
430 * Use saved redirection. We prepend it in front of the user's
431 * arguments so that the user can override the redirections.
433 strArg = m_redirect + " " + strArg;
436 QString cmdString;
437 cmdString.sprintf(cmds[cmd].fmt, strArg.toUtf8().constData());
438 return cmdString;
441 QString GdbDriver::makeCmdString(DbgCommand cmd, int intArg)
443 assert(cmd >= 0 && cmd < NUM_CMDS);
444 assert(cmds[cmd].argsNeeded == GdbCmdInfo::argNum);
446 QString cmdString;
447 cmdString.sprintf(cmds[cmd].fmt, intArg);
448 return cmdString;
451 QString GdbDriver::makeCmdString(DbgCommand cmd, QString strArg, int intArg)
453 assert(cmd >= 0 && cmd < NUM_CMDS);
454 assert(cmds[cmd].argsNeeded == GdbCmdInfo::argStringNum ||
455 cmds[cmd].argsNeeded == GdbCmdInfo::argNumString ||
456 cmd == DCexamine ||
457 cmd == DCtty);
459 normalizeStringArg(strArg);
461 QString cmdString;
463 if (cmd == DCtty)
466 * intArg specifies which channels should be redirected to
467 * /dev/null. It is a value or'ed together from RDNstdin,
468 * RDNstdout, RDNstderr. We store the value for a later DCsetargs
469 * command.
471 * Note: We rely on that after the DCtty a DCsetargs will follow,
472 * which will ultimately apply the redirection.
474 static const char* const runRedir[8] = {
476 "</dev/null",
477 ">/dev/null",
478 "</dev/null >/dev/null",
479 "2>/dev/null",
480 "</dev/null 2>/dev/null",
481 ">/dev/null 2>&1",
482 "</dev/null >/dev/null 2>&1"
484 if (strArg.isEmpty())
485 intArg = 7; /* failsafe if no tty */
486 m_redirect = runRedir[intArg & 7];
488 return makeCmdString(DCtty, strArg); /* note: no problem if strArg empty */
491 if (cmd == DCexamine) {
492 // make a format specifier from the intArg
493 static const char size[16] = {
494 '\0', 'b', 'h', 'w', 'g'
496 static const char format[16] = {
497 '\0', 'x', 'd', 'u', 'o', 't',
498 'a', 'c', 'f', 's', 'i'
500 assert(MDTsizemask == 0xf); /* lowest 4 bits */
501 assert(MDTformatmask == 0xf0); /* next 4 bits */
502 int count = 16; /* number of entities to print */
503 char sizeSpec = size[intArg & MDTsizemask];
504 char formatSpec = format[(intArg & MDTformatmask) >> 4];
505 assert(sizeSpec != '\0');
506 assert(formatSpec != '\0');
507 // adjust count such that 16 lines are printed
508 switch (intArg & MDTformatmask) {
509 case MDTstring: case MDTinsn:
510 break; /* no modification needed */
511 default:
512 // all cases drop through:
513 switch (intArg & MDTsizemask) {
514 case MDTbyte:
515 case MDThalfword:
516 count *= 2;
517 case MDTword:
518 count *= 2;
519 case MDTgiantword:
520 count *= 2;
522 break;
524 QString spec;
525 spec.sprintf("/%d%c%c", count, sizeSpec, formatSpec);
527 return makeCmdString(DCexamine, spec, strArg);
530 if (cmds[cmd].argsNeeded == GdbCmdInfo::argStringNum)
532 // line numbers are zero-based
533 if (cmd == DCuntil || cmd == DCbreakline ||
534 cmd == DCtbreakline || cmd == DCinfoline)
536 intArg++;
538 if (cmd == DCinfoline)
540 // must split off file name part
541 strArg = QFileInfo(strArg).fileName();
543 cmdString.sprintf(cmds[cmd].fmt, strArg.toUtf8().constData(), intArg);
545 else
547 cmdString.sprintf(cmds[cmd].fmt, intArg, strArg.toUtf8().constData());
549 return cmdString;
552 QString GdbDriver::makeCmdString(DbgCommand cmd, QString strArg1, QString strArg2)
554 assert(cmd >= 0 && cmd < NUM_CMDS);
555 assert(cmds[cmd].argsNeeded == GdbCmdInfo::argString2);
557 normalizeStringArg(strArg1);
558 normalizeStringArg(strArg2);
560 QString cmdString;
561 cmdString.sprintf(cmds[cmd].fmt,
562 strArg1.toUtf8().constData(),
563 strArg2.toUtf8().constData());
564 return cmdString;
567 QString GdbDriver::makeCmdString(DbgCommand cmd, int intArg1, int intArg2)
569 assert(cmd >= 0 && cmd < NUM_CMDS);
570 assert(cmds[cmd].argsNeeded == GdbCmdInfo::argNum2);
572 QString cmdString;
573 cmdString.sprintf(cmds[cmd].fmt, intArg1, intArg2);
574 return cmdString;
577 CmdQueueItem* GdbDriver::executeCmd(DbgCommand cmd, bool clearLow)
579 assert(cmd >= 0 && cmd < NUM_CMDS);
580 assert(cmds[cmd].argsNeeded == GdbCmdInfo::argNone);
582 if (cmd == DCrun) {
583 m_haveCoreFile = false;
586 return executeCmdString(cmd, cmds[cmd].fmt, clearLow);
589 CmdQueueItem* GdbDriver::executeCmd(DbgCommand cmd, QString strArg,
590 bool clearLow)
592 return executeCmdString(cmd, makeCmdString(cmd, strArg), clearLow);
595 CmdQueueItem* GdbDriver::executeCmd(DbgCommand cmd, int intArg,
596 bool clearLow)
599 return executeCmdString(cmd, makeCmdString(cmd, intArg), clearLow);
602 CmdQueueItem* GdbDriver::executeCmd(DbgCommand cmd, QString strArg, int intArg,
603 bool clearLow)
605 return executeCmdString(cmd, makeCmdString(cmd, strArg, intArg), clearLow);
608 CmdQueueItem* GdbDriver::executeCmd(DbgCommand cmd, QString strArg1, QString strArg2,
609 bool clearLow)
611 return executeCmdString(cmd, makeCmdString(cmd, strArg1, strArg2), clearLow);
614 CmdQueueItem* GdbDriver::executeCmd(DbgCommand cmd, int intArg1, int intArg2,
615 bool clearLow)
617 return executeCmdString(cmd, makeCmdString(cmd, intArg1, intArg2), clearLow);
620 CmdQueueItem* GdbDriver::queueCmd(DbgCommand cmd, QueueMode mode)
622 return queueCmdString(cmd, cmds[cmd].fmt, mode);
625 CmdQueueItem* GdbDriver::queueCmd(DbgCommand cmd, QString strArg,
626 QueueMode mode)
628 return queueCmdString(cmd, makeCmdString(cmd, strArg), mode);
631 CmdQueueItem* GdbDriver::queueCmd(DbgCommand cmd, int intArg,
632 QueueMode mode)
634 return queueCmdString(cmd, makeCmdString(cmd, intArg), mode);
637 CmdQueueItem* GdbDriver::queueCmd(DbgCommand cmd, QString strArg, int intArg,
638 QueueMode mode)
640 return queueCmdString(cmd, makeCmdString(cmd, strArg, intArg), mode);
643 CmdQueueItem* GdbDriver::queueCmd(DbgCommand cmd, QString strArg1, QString strArg2,
644 QueueMode mode)
646 return queueCmdString(cmd, makeCmdString(cmd, strArg1, strArg2), mode);
649 void GdbDriver::terminate()
651 ::kill(pid(), SIGTERM);
652 m_state = DSidle;
655 void GdbDriver::detachAndTerminate()
657 ::kill(pid(), SIGINT);
658 flushCommands();
659 executeCmdString(DCinitialize, "detach\nquit\n", true);
662 void GdbDriver::interruptInferior()
664 ::kill(pid(), SIGINT);
665 // remove accidentally queued commands
666 flushHiPriQueue();
669 static bool isErrorExpr(const char* output)
671 return
672 strncmp(output, "Cannot access memory at", 23) == 0 ||
673 strncmp(output, "Attempt to dereference a generic pointer", 40) == 0 ||
674 strncmp(output, "Attempt to take contents of ", 28) == 0 ||
675 strncmp(output, "Attempt to use a type name as an expression", 43) == 0 ||
676 strncmp(output, "There is no member or method named", 34) == 0 ||
677 strncmp(output, "A parse error in expression", 27) == 0 ||
678 strncmp(output, "No symbol \"", 11) == 0 ||
679 strncmp(output, "Internal error: ", 16) == 0;
683 * Returns true if the output is an error message. If wantErrorValue is
684 * true, a new ExprValue object is created and filled with the error message.
685 * If there are warnings, they are skipped and output points past the warnings
686 * on return (even if there \e are errors).
688 static bool parseErrorMessage(const char*& output,
689 ExprValue*& variable, bool wantErrorValue)
691 while (isspace(*output))
692 output++;
694 // skip warnings
695 while (strncmp(output, "warning:", 8) == 0)
697 const char* end = strchr(output+8, '\n');
698 if (end == 0)
699 output += strlen(output);
700 else
701 output = end+1;
702 while (isspace(*output))
703 output++;
706 if (isErrorExpr(output))
708 if (wantErrorValue) {
709 // put the error message as value in the variable
710 variable = new ExprValue(QString(), VarTree::NKplain);
711 const char* endMsg = strchr(output, '\n');
712 if (endMsg == 0)
713 endMsg = output + strlen(output);
714 variable->m_value = QString::fromLatin1(output, endMsg-output);
715 } else {
716 variable = 0;
718 return true;
720 return false;
723 #if QT_VERSION >= 300
724 union Qt2QChar {
725 short s;
726 struct {
727 uchar row;
728 uchar cell;
729 } qch;
731 #endif
733 void GdbDriver::setPrintQStringDataCmd(const char* cmd)
735 // don't accept the command if it is empty
736 if (cmd == 0 || *cmd == '\0')
737 return;
738 assert(strlen(cmd) <= MAX_FMTLEN);
739 cmds[DCprintQStringStruct].fmt = cmd;
742 ExprValue* GdbDriver::parseQCharArray(const char* output, bool wantErrorValue, bool qt3like)
744 ExprValue* variable = 0;
747 * Parse off white space. gdb sometimes prints white space first if the
748 * printed array leaded to an error.
750 while (isspace(*output))
751 output++;
753 // special case: empty string (0 repetitions)
754 if (strncmp(output, "Invalid number 0 of repetitions", 31) == 0)
756 variable = new ExprValue(QString(), VarTree::NKplain);
757 variable->m_value = "\"\"";
758 return variable;
761 // check for error conditions
762 if (parseErrorMessage(output, variable, wantErrorValue))
763 return variable;
765 // parse the array
767 // find '='
768 const char* p = output;
769 p = strchr(p, '=');
770 if (p == 0) {
771 goto error;
773 // skip white space
774 do {
775 p++;
776 } while (isspace(*p));
778 if (*p == '{')
780 // this is the real data
781 p++; /* skip '{' */
783 // parse the array
784 QString result;
785 QString repeatCount;
786 enum { wasNothing, wasChar, wasRepeat } lastThing = wasNothing;
788 * A matrix for separators between the individual "things"
789 * that are added to the string. The first index is a bool,
790 * the second index is from the enum above.
792 static const char* separator[2][3] = {
793 { "\"", 0, ", \"" }, /* normal char is added */
794 { "'", "\", '", ", '" } /* repeated char is added */
797 while (isdigit(*p)) {
798 // parse a number
799 char* end;
800 unsigned short value = (unsigned short) strtoul(p, &end, 0);
801 if (end == p)
802 goto error; /* huh? no valid digits */
803 // skip separator and search for a repeat count
804 p = end;
805 while (isspace(*p) || *p == ',')
806 p++;
807 bool repeats = strncmp(p, "<repeats ", 9) == 0;
808 if (repeats) {
809 const char* start = p;
810 p = strchr(p+9, '>'); /* search end and advance */
811 if (p == 0)
812 goto error;
813 p++; /* skip '>' */
814 repeatCount = QString::fromLatin1(start, p-start);
815 while (isspace(*p) || *p == ',')
816 p++;
818 // p is now at the next char (or the end)
820 // interpret the value as a QChar
821 // TODO: make cross-architecture compatible
822 QChar ch;
823 if (qt3like) {
824 ch = QChar(value);
825 } else {
826 #if QT_VERSION < 300
827 (unsigned short&)ch = value;
828 #else
829 Qt2QChar c;
830 c.s = value;
831 ch.setRow(c.qch.row);
832 ch.setCell(c.qch.cell);
833 #endif
836 // escape a few frequently used characters
837 char escapeCode = '\0';
838 switch (ch.toLatin1()) {
839 case '\n': escapeCode = 'n'; break;
840 case '\r': escapeCode = 'r'; break;
841 case '\t': escapeCode = 't'; break;
842 case '\b': escapeCode = 'b'; break;
843 case '\"': escapeCode = '\"'; break;
844 case '\\': escapeCode = '\\'; break;
845 case '\0': if (value == 0) { escapeCode = '0'; } break;
848 // add separator
849 result += separator[repeats][lastThing];
850 // add char
851 if (escapeCode != '\0') {
852 result += '\\';
853 ch = escapeCode;
855 result += ch;
857 // fixup repeat count and lastThing
858 if (repeats) {
859 result += "' ";
860 result += repeatCount;
861 lastThing = wasRepeat;
862 } else {
863 lastThing = wasChar;
866 if (*p != '}')
867 goto error;
869 // closing quote
870 if (lastThing == wasChar)
871 result += "\"";
873 // assign the value
874 variable = new ExprValue(QString(), VarTree::NKplain);
875 variable->m_value = result;
877 else if (strncmp(p, "true", 4) == 0)
879 variable = new ExprValue(QString(), VarTree::NKplain);
880 variable->m_value = "QString::null";
882 else if (strncmp(p, "false", 5) == 0)
884 variable = new ExprValue(QString(), VarTree::NKplain);
885 variable->m_value = "(null)";
887 else
888 goto error;
889 return variable;
891 error:
892 if (wantErrorValue) {
893 variable = new ExprValue(QString(), VarTree::NKplain);
894 variable->m_value = "internal parse error";
896 return variable;
899 static ExprValue* parseVar(const char*& s)
901 const char* p = s;
903 // skip whitespace
904 while (isspace(*p))
905 p++;
907 QString name;
908 VarTree::NameKind kind;
910 * Detect anonymouse struct values: The 'name =' part is missing:
911 * s = { a = 1, { b = 2 }}
912 * Note that this detection works only inside structs when the anonymous
913 * struct is not the first member:
914 * s = {{ a = 1 }, b = 2}
915 * This is misparsed (by parseNested()) because it is mistakenly
916 * interprets the second opening brace as the first element of an array
917 * of structs.
919 if (*p == '{')
921 name = i18n("<anonymous struct or union>");
922 kind = VarTree::NKanonymous;
924 else
926 if (!parseName(p, name, kind)) {
927 return 0;
930 // go for '='
931 while (isspace(*p))
932 p++;
933 if (*p != '=') {
934 TRACE("parse error: = not found after " + name);
935 return 0;
937 // skip the '=' and more whitespace
938 p++;
939 while (isspace(*p))
940 p++;
943 ExprValue* variable = new ExprValue(name, kind);
945 if (!parseValue(p, variable)) {
946 delete variable;
947 return 0;
949 s = p;
950 return variable;
953 static void skipNested(const char*& s, char opening, char closing)
955 const char* p = s;
957 // parse a nested type
958 int nest = 1;
959 p++;
961 * Search for next matching `closing' char, skipping nested pairs of
962 * `opening' and `closing'.
964 while (*p && nest > 0) {
965 if (*p == opening) {
966 nest++;
967 } else if (*p == closing) {
968 nest--;
970 p++;
972 if (nest != 0) {
973 TRACE(QString().sprintf("parse error: mismatching %c%c at %-20.20s", opening, closing, s));
975 s = p;
979 * This function skips text that is delimited by nested angle bracktes, '<>'.
980 * A complication arises because the delimited text can contain the names of
981 * operator<<, operator>>, operator<, and operator>, which have to be treated
982 * specially so that they do not count towards the nesting of '<>'.
983 * This function assumes that the delimited text does not contain strings.
985 static void skipNestedAngles(const char*& s)
987 const char* p = s;
989 int nest = 1;
990 p++; // skip the initial '<'
991 while (*p && nest > 0)
993 // Below we can check for p-s >= 9 instead of 8 because
994 // *s is '<' and cannot be part of "operator".
995 if (*p == '<')
997 if (p-s >= 9 && strncmp(p-8, "operator", 8) == 0) {
998 if (p[1] == '<')
999 p++;
1000 } else {
1001 nest++;
1004 else if (*p == '>')
1006 if (p-s >= 9 && strncmp(p-8, "operator", 8) == 0) {
1007 if (p[1] == '>')
1008 p++;
1009 } else {
1010 nest--;
1013 p++;
1015 if (nest != 0) {
1016 TRACE(QString().sprintf("parse error: mismatching <> at %-20.20s", s));
1018 s = p;
1022 * Find the end of line that is not inside braces
1024 static void findEnd(const char*& s)
1026 const char* p = s;
1027 while (*p && *p!='\n') {
1028 while (*p && *p!='\n' && *p!='{')
1029 p++;
1030 if (*p=='{') {
1031 p++;
1032 skipNested(p, '{', '}'); p--;
1035 s = p;
1038 static bool isNumberish(const char ch)
1040 return (ch>='0' && ch<='9') || ch=='.' || ch=='x';
1043 void skipString(const char*& p)
1045 // wchar_t strings begin with L
1046 if (*p == 'L')
1047 ++p;
1049 moreStrings:
1050 // opening quote
1051 char quote = *p++;
1052 while (*p != quote) {
1053 if (*p == '\\') {
1054 // skip escaped character
1055 // no special treatment for octal values necessary
1056 p++;
1058 // simply return if no more characters
1059 if (*p == '\0')
1060 return;
1061 p++;
1063 // closing quote
1064 p++;
1066 * Strings can consist of several parts, some of which contain repeated
1067 * characters.
1069 if (quote == '\'') {
1070 // look ahaead for <repeats 123 times>
1071 const char* q = p+1;
1072 while (isspace(*q))
1073 q++;
1074 if (strncmp(q, "<repeats ", 9) == 0) {
1075 p = q+9;
1076 while (*p != '\0' && *p != '>')
1077 p++;
1078 if (*p != '\0') {
1079 p++; /* skip the '>' */
1083 // Is the string continued? If so, there is no L in wchar_t strings
1084 if (*p == ',')
1086 // look ahead for another quote
1087 const char* q = p+1;
1088 while (isspace(*q))
1089 q++;
1090 if (*q == '"' || *q == '\'') {
1091 // yes!
1092 p = q;
1093 goto moreStrings;
1096 // some strings can end in <incomplete sequence ...>
1097 if (strncmp(q, "<incomplete sequence", 20) == 0)
1099 p = q+20;
1100 while (*p != '\0' && *p != '>')
1101 p++;
1102 if (*p != '\0') {
1103 p++; /* skip the '>' */
1108 * There's a bug in gdb where it prints the beginning of the string
1109 * continuation and the comma-blank in the wrong order if the new string
1110 * begins with an incomplete multi-byte character. For now, let's check
1111 * for this in a very narrow condition, particularly, where the next
1112 * character is given in octal notation. Example:
1113 * 'a' <repeats 20 times>"\240, b"
1115 if (*p == '"' && p[1] == '\\' && isdigit(p[2])) {
1116 int i = 3;
1117 while (isdigit(p[i]))
1118 ++i;
1119 if (p[i] == ',' && p[i+1] == ' ') {
1120 // just treat everything beginning at the dquote as string
1121 goto moreStrings;
1124 /* very long strings are followed by `...' */
1125 if (*p == '.' && p[1] == '.' && p[2] == '.') {
1126 p += 3;
1130 static void skipNestedWithString(const char*& s, char opening, char closing)
1132 const char* p = s;
1134 // parse a nested expression
1135 int nest = 1;
1136 p++;
1138 * Search for next matching `closing' char, skipping nested pairs of
1139 * `opening' and `closing' as well as strings.
1141 while (*p && nest > 0) {
1142 if (*p == opening) {
1143 nest++;
1144 } else if (*p == closing) {
1145 nest--;
1146 } else if (*p == '\'' || *p == '\"') {
1147 skipString(p);
1148 continue;
1150 p++;
1152 if (nest > 0) {
1153 TRACE(QString().sprintf("parse error: mismatching %c%c at %-20.20s", opening, closing, s));
1155 s = p;
1158 inline void skipName(const char*& p)
1160 // allow : (for enumeration values) and $ and . (for _vtbl.)
1161 while (isalnum(*p) || *p == '_' || *p == ':' || *p == '$' || *p == '.')
1162 p++;
1165 static bool parseName(const char*& s, QString& name, VarTree::NameKind& kind)
1167 kind = VarTree::NKplain;
1169 const char* p = s;
1170 // examples of names:
1171 // name
1172 // <Object>
1173 // <string<a,b<c>,7> >
1175 if (*p == '<') {
1176 skipNestedAngles(p);
1177 name = QString::fromLatin1(s, p - s);
1178 kind = VarTree::NKtype;
1180 else
1182 // name, which might be "static"; allow dot for "_vtbl."
1183 skipName(p);
1184 if (p == s) {
1185 TRACE(QString().sprintf("parse error: not a name %-20.20s", s));
1186 return false;
1188 int len = p - s;
1189 if (len == 6 && strncmp(s, "static", 6) == 0) {
1190 kind = VarTree::NKstatic;
1192 // its a static variable, name comes now
1193 while (isspace(*p))
1194 p++;
1195 s = p;
1196 skipName(p);
1197 if (p == s) {
1198 TRACE(QString().sprintf("parse error: not a name after static %-20.20s", s));
1199 return false;
1201 len = p - s;
1203 name = QString::fromLatin1(s, len);
1205 // return the new position
1206 s = p;
1207 return true;
1210 static bool parseValue(const char*& s, ExprValue* variable)
1212 variable->m_value = "";
1214 repeat:
1215 if (*s == '{') {
1216 // Sometimes we find the following output:
1217 // {<text variable, no debug info>} 0x40012000 <access>
1218 // {<data variable, no debug info>}
1219 // {<variable (not text or data), no debug info>}
1220 if (strncmp(s, "{<text variable, ", 17) == 0 ||
1221 strncmp(s, "{<data variable, ", 17) == 0 ||
1222 strncmp(s, "{<variable (not text or data), ", 31) == 0)
1224 const char* start = s;
1225 skipNested(s, '{', '}');
1226 variable->m_value = QString::fromLatin1(start, s-start);
1227 variable->m_value += ' '; // add only a single space
1228 while (isspace(*s))
1229 s++;
1230 goto repeat;
1232 else
1234 s++;
1235 if (!parseNested(s, variable)) {
1236 return false;
1238 // must be the closing brace
1239 if (*s != '}') {
1240 TRACE("parse error: missing } of " + variable->m_name);
1241 return false;
1243 s++;
1244 // final white space
1245 while (isspace(*s))
1246 s++;
1249 // Sometimes we find a warning; it ends at the next LF
1250 else if (strncmp(s, "warning: ", 9) == 0) {
1251 const char* end = strchr(s, '\n');
1252 s = end ? end : s+strlen(s);
1253 // skip space at start of next line
1254 while (isspace(*s))
1255 s++;
1256 goto repeat;
1257 } else {
1258 // examples of leaf values (cannot be the empty string):
1259 // 123
1260 // -123
1261 // 23.575e+37
1262 // 0x32a45
1263 // @0x012ab4
1264 // (DwContentType&) @0x8123456: {...}
1265 // 0x32a45 "text"
1266 // 10 '\n'
1267 // <optimized out>
1268 // 0x823abc <Array<int> virtual table>
1269 // 0x40240f <globarstr> "test"
1270 // (void (*)()) 0x8048480 <f(E *, char)>
1271 // (E *) 0xbffff450
1272 // red
1273 // &parseP (HTMLClueV *, char *)
1274 // Variable "x" is not available.
1275 // The value of variable 'x' is distributed...
1276 // -nan(0xfffff081defa0)
1278 const char*p = s;
1280 // check for type
1281 QString type;
1282 if (*p == '(') {
1283 skipNested(p, '(', ')');
1285 while (isspace(*p))
1286 p++;
1287 variable->m_value = QString::fromLatin1(s, p - s);
1290 bool reference = false;
1291 if (*p == '@') {
1292 // skip reference marker
1293 p++;
1294 reference = true;
1296 const char* start = p;
1297 if (*p == '-')
1298 p++;
1300 // some values consist of more than one token
1301 bool checkMultiPart = false;
1303 if (p[0] == '0' && p[1] == 'x') {
1304 // parse hex number
1305 p += 2;
1306 while (isxdigit(*p))
1307 p++;
1310 * Assume this is a pointer, but only if it's not a reference, since
1311 * references can't be expanded.
1313 if (!reference) {
1314 variable->m_varKind = VarTree::VKpointer;
1315 } else {
1317 * References are followed by a colon, in which case we'll
1318 * find the value following the reference address.
1320 if (*p == ':') {
1321 p++;
1322 } else {
1323 // Paranoia. (Can this happen, i.e. reference not followed by ':'?)
1324 reference = false;
1327 checkMultiPart = true;
1328 } else if (isdigit(*p)) {
1329 // parse decimal number, possibly a float
1330 while (isdigit(*p))
1331 p++;
1332 if (*p == '.') { /* TODO: obey i18n? */
1333 // In long arrays an integer may be followed by '...'.
1334 // We test for this situation and don't gobble the '...'.
1335 if (p[1] != '.' || p[0] != '.') {
1336 // fractional part
1337 p++;
1338 while (isdigit(*p))
1339 p++;
1342 if (*p == 'e' || *p == 'E') {
1343 p++;
1344 // exponent
1345 if (*p == '-' || *p == '+')
1346 p++;
1347 while (isdigit(*p))
1348 p++;
1351 // for char variables there is the char, eg. 10 '\n'
1352 checkMultiPart = true;
1353 } else if (*p == '<') {
1354 // e.g. <optimized out>
1355 skipNestedAngles(p);
1356 } else if (*p == '"' || *p == '\'') {
1357 // character may have multipart: '\000' <repeats 11 times>
1358 checkMultiPart = *p == '\'';
1359 // found a string
1360 skipString(p);
1361 } else if (*p == 'L' && (p[1] == '"' || p[1] == '\'')) {
1362 // ditto for wchar_t strings
1363 checkMultiPart = p[1] == '\'';
1364 skipString(p);
1365 } else if (*p == '&') {
1366 // function pointer
1367 p++;
1368 skipName(p);
1369 while (isspace(*p)) {
1370 p++;
1372 if (*p == '(') {
1373 skipNested(p, '(', ')');
1375 } else if (strncmp(p, "Variable \"", 10) == 0) {
1376 // Variable "x" is not available.
1377 p += 10; // skip to "
1378 skipName(p);
1379 if (strncmp(p, "\" is not available.", 19) == 0) {
1380 p += 19;
1382 } else if (strncmp(p, "The value of variable '", 23) == 0) {
1383 p += 23;
1384 skipName(p);
1385 const char* e = strchr(p, '.');
1386 if (e == 0) {
1387 p += strlen(p);
1388 } else {
1389 p = e+1;
1391 } else {
1392 moreEnum:
1393 // must be an enumeration value
1394 skipName(p);
1395 // nan (floating point Not a Number) is followed by a number in ()
1396 // enum values can look like A::(anonymous namespace)::blue
1397 if (*p == '(') {
1398 bool isAnonNS = strncmp(p+1, "anonymous namespace)", 20) == 0;
1399 skipNested(p, '(', ')');
1400 if (isAnonNS)
1401 goto moreEnum;
1404 variable->m_value += QString::fromLatin1(start, p - start);
1406 // remove line breaks from the value; this is ok since
1407 // string values never contain a literal line break
1408 variable->m_value.replace('\n', ' ');
1410 while (checkMultiPart) {
1411 // white space
1412 while (isspace(*p))
1413 p++;
1414 // may be followed by a string or <...>
1415 // if this was a pointer with a string,
1416 // reset that pointer flag since we have now a value
1417 start = p;
1418 checkMultiPart = false;
1420 if (*p == '"' || *p == '\'') {
1421 skipString(p);
1422 variable->m_varKind = VarTree::VKsimple;
1423 } else if (*p == 'L' && (p[1] == '"' || p[1] == '\'')) {
1424 skipString(p); // wchar_t string
1425 variable->m_varKind = VarTree::VKsimple;
1426 } else if (*p == '<') {
1427 // if this value is part of an array, it might be followed
1428 // by <repeats 15 times>, which we don't skip here
1429 if (strncmp(p, "<repeats ", 9) != 0) {
1430 skipNestedAngles(p);
1431 checkMultiPart = true;
1434 if (p != start) {
1435 // there is always a blank before the string,
1436 // which we will include in the final string value
1437 variable->m_value += QString::fromLatin1(start-1, (p - start)+1);
1441 if (variable->m_value.length() == 0) {
1442 TRACE("parse error: no value for " + variable->m_name);
1443 return false;
1446 // final white space
1447 while (isspace(*p))
1448 p++;
1449 s = p;
1452 * If this was a reference, the value follows. It might even be a
1453 * composite variable!
1455 if (reference) {
1456 goto repeat;
1460 return true;
1463 static bool parseNested(const char*& s, ExprValue* variable)
1465 // could be a structure or an array
1466 while (isspace(*s))
1467 s++;
1469 const char* p = s;
1470 bool isStruct = false;
1472 * If there is a name followed by an = or an < -- which starts a type
1473 * name -- or "static", it is a structure
1475 if (*p == '<' || *p == '}') {
1476 isStruct = true;
1477 } else if (strncmp(p, "static ", 7) == 0) {
1478 isStruct = true;
1479 } else if (isalpha(*p) || *p == '_' || *p == '$') {
1480 // look ahead for a comma after the name
1481 skipName(p);
1482 while (isspace(*p))
1483 p++;
1484 if (*p == '=') {
1485 isStruct = true;
1487 p = s; /* rescan the name */
1489 if (isStruct) {
1490 if (!parseVarSeq(p, variable)) {
1491 return false;
1493 variable->m_varKind = VarTree::VKstruct;
1494 } else {
1495 if (!parseValueSeq(p, variable)) {
1496 return false;
1498 variable->m_varKind = VarTree::VKarray;
1500 s = p;
1501 return true;
1504 static bool parseVarSeq(const char*& s, ExprValue* variable)
1506 // parse a comma-separated sequence of variables
1507 ExprValue* var = variable; /* var != 0 to indicate success if empty seq */
1508 for (;;) {
1509 if (*s == '}')
1510 break;
1511 if (strncmp(s, "<No data fields>}", 17) == 0)
1513 // no member variables, so break out immediately
1514 s += 16; /* go to the closing brace */
1515 break;
1517 var = parseVar(s);
1518 if (var == 0)
1519 break; /* syntax error */
1520 variable->appendChild(var);
1521 if (*s != ',')
1522 break;
1523 // skip the comma and whitespace
1524 s++;
1525 while (isspace(*s))
1526 s++;
1528 return var != 0;
1531 static bool parseValueSeq(const char*& s, ExprValue* variable)
1533 // parse a comma-separated sequence of variables
1534 int index = 0;
1535 bool good;
1536 for (;;) {
1537 QString name;
1538 name.sprintf("[%d]", index);
1539 ExprValue* var = new ExprValue(name, VarTree::NKplain);
1540 good = parseValue(s, var);
1541 if (!good) {
1542 delete var;
1543 return false;
1545 // a value may be followed by "<repeats 45 times>"
1546 if (strncmp(s, "<repeats ", 9) == 0) {
1547 s += 9;
1548 char* end;
1549 int l = strtol(s, &end, 10);
1550 if (end == s || strncmp(end, " times>", 7) != 0) {
1551 // should not happen
1552 delete var;
1553 return false;
1555 TRACE(QString().sprintf("found <repeats %d times> in array", l));
1556 // replace name and advance index
1557 name.sprintf("[%d .. %d]", index, index+l-1);
1558 var->m_name = name;
1559 index += l;
1560 // skip " times>" and space
1561 s = end+7;
1562 // possible final space
1563 while (isspace(*s))
1564 s++;
1565 } else {
1566 index++;
1568 variable->appendChild(var);
1569 // long arrays may be terminated by '...'
1570 if (strncmp(s, "...", 3) == 0) {
1571 s += 3;
1572 ExprValue* var = new ExprValue("...", VarTree::NKplain);
1573 var->m_value = i18n("<additional entries of the array suppressed>");
1574 variable->appendChild(var);
1575 break;
1577 if (*s != ',') {
1578 break;
1580 // skip the comma and whitespace
1581 s++;
1582 while (isspace(*s))
1583 s++;
1584 // sometimes there is a closing brace after a comma
1585 // if (*s == '}')
1586 // break;
1588 return true;
1592 * Parses a stack frame.
1594 static void parseFrameInfo(const char*& s, QString& func,
1595 QString& file, int& lineNo, DbgAddr& address)
1597 const char* p = s;
1599 // next may be a hexadecimal address
1600 if (*p == '0') {
1601 const char* start = p;
1602 p++;
1603 if (*p == 'x')
1604 p++;
1605 while (isxdigit(*p))
1606 p++;
1607 address = QString::fromLatin1(start, p-start);
1608 if (strncmp(p, " in ", 4) == 0)
1609 p += 4;
1610 } else {
1611 address = DbgAddr();
1613 const char* start = p;
1614 // check for special signal handler frame
1615 if (strncmp(p, "<signal handler called>", 23) == 0) {
1616 func = QString::fromLatin1(start, 23);
1617 file = QString();
1618 lineNo = -1;
1619 s = p+23;
1620 if (*s == '\n')
1621 s++;
1622 return;
1626 * Skip the function name. It is terminated by a left parenthesis
1627 * which does not delimit "(anonymous namespace)" and which is
1628 * outside the angle brackets <> of template parameter lists
1629 * and is preceded by a space.
1631 while (*p != '\0')
1633 if (*p == '<') {
1634 // check for operator<< and operator<
1635 if (p-start >= 8 && strncmp(p-8, "operator", 8) == 0)
1637 p++;
1638 if (*p == '<')
1639 p++;
1641 else
1643 // skip template parameter list
1644 skipNestedAngles(p);
1646 } else if (*p == '(') {
1647 // this skips "(anonymous namespace)" as well as the formal
1648 // parameter list of the containing function if this is a member
1649 // of a nested class
1650 skipNestedWithString(p, '(', ')');
1651 } else if (*p == ' ') {
1652 ++p;
1653 if (*p == '(')
1654 break; // parameter list found
1655 } else {
1656 p++;
1660 if (*p == '\0') {
1661 func = start;
1662 file = QString();
1663 lineNo = -1;
1664 s = p;
1665 return;
1668 * Skip parameters. But notice that for complicated conversion
1669 * functions (eg. "operator int(**)()()", ie. convert to pointer to
1670 * pointer to function) as well as operator()(...) we have to skip
1671 * additional pairs of parentheses. Furthermore, recent gdbs write the
1672 * demangled name followed by the arguments in a pair of parentheses,
1673 * where the demangled name can end in "const".
1675 do {
1676 skipNestedWithString(p, '(', ')');
1677 while (isspace(*p))
1678 p++;
1679 // skip "const"
1680 if (strncmp(p, "const", 5) == 0) {
1681 p += 5;
1682 while (isspace(*p))
1683 p++;
1685 } while (*p == '(');
1687 // check for file position
1688 if (strncmp(p, "at ", 3) == 0) {
1689 p += 3;
1690 const char* fileStart = p;
1691 // go for the end of the line
1692 while (*p != '\0' && *p != '\n')
1693 p++;
1694 // search back for colon
1695 const char* colon = p;
1696 do {
1697 --colon;
1698 } while (*colon != ':');
1699 file = QString::fromLatin1(fileStart, colon-fileStart);
1700 lineNo = atoi(colon+1)-1;
1701 // skip new-line
1702 if (*p != '\0')
1703 p++;
1704 } else {
1705 // check for "from shared lib"
1706 if (strncmp(p, "from ", 5) == 0) {
1707 p += 5;
1708 // go for the end of the line
1709 while (*p != '\0' && *p != '\n')
1710 p++;
1711 // skip new-line
1712 if (*p != '\0')
1713 p++;
1715 file = "";
1716 lineNo = -1;
1718 // construct the function name (including file info)
1719 if (*p == '\0') {
1720 func = start;
1721 } else {
1722 func = QString::fromLatin1(start, p-start-1); /* don't include \n */
1724 s = p;
1727 * Replace \n (and whitespace around it) in func by a blank. We cannot
1728 * use QString::simplified() for this because this would also
1729 * simplify space that belongs to a string arguments that gdb sometimes
1730 * prints in the argument lists of the function.
1732 ASSERT(!isspace(func[0].toLatin1())); // there must be non-white before first \n
1733 int nl = 0;
1734 while ((nl = func.indexOf('\n', nl)) >= 0) {
1735 // search back to the beginning of the whitespace
1736 int startWhite = nl;
1737 do {
1738 --startWhite;
1739 } while (isspace(func[startWhite].toLatin1()));
1740 startWhite++;
1741 // search forward to the end of the whitespace
1742 do {
1743 nl++;
1744 } while (isspace(func[nl].toLatin1()));
1745 // replace
1746 func.replace(startWhite, nl-startWhite, " ");
1747 /* continue searching for more \n's at this place: */
1748 nl = startWhite+1;
1754 * Parses a stack frame including its frame number
1756 static bool parseFrame(const char*& s, int& frameNo, QString& func,
1757 QString& file, int& lineNo, DbgAddr& address)
1759 // Example:
1760 // #1 0x8048881 in Dl::Dl (this=0xbffff418, r=3214) at testfile.cpp:72
1761 // Breakpoint 3, Cl::f(int) const (this=0xbffff3c0, x=17) at testfile.cpp:155
1763 // must start with a hash mark followed by number
1764 // or with "Breakpoint " followed by number and comma
1765 if (s[0] == '#') {
1766 if (!isdigit(s[1]))
1767 return false;
1768 s++; /* skip the hash mark */
1769 } else if (strncmp(s, "Breakpoint ", 11) == 0) {
1770 if (!isdigit(s[11]))
1771 return false;
1772 s += 11; /* skip "Breakpoint" */
1773 } else
1774 return false;
1776 // frame number
1777 frameNo = atoi(s);
1778 while (isdigit(*s))
1779 s++;
1780 // space and comma
1781 while (isspace(*s) || *s == ',')
1782 s++;
1783 parseFrameInfo(s, func, file, lineNo, address);
1784 return true;
1787 void GdbDriver::parseBackTrace(const char* output, std::list<StackFrame>& stack)
1789 QString func, file;
1790 int lineNo, frameNo;
1791 DbgAddr address;
1793 while (::parseFrame(output, frameNo, func, file, lineNo, address)) {
1794 stack.push_back(StackFrame());
1795 StackFrame* frm = &stack.back();
1796 frm->frameNo = frameNo;
1797 frm->fileName = file;
1798 frm->lineNo = lineNo;
1799 frm->address = address;
1800 frm->var = new ExprValue(func, VarTree::NKplain);
1804 bool GdbDriver::parseFrameChange(const char* output, int& frameNo,
1805 QString& file, int& lineNo, DbgAddr& address)
1807 QString func;
1808 return ::parseFrame(output, frameNo, func, file, lineNo, address);
1812 bool GdbDriver::parseBreakList(const char* output, std::list<Breakpoint>& brks)
1814 // skip first line, which is the headline
1815 const char* p = strchr(output, '\n');
1816 if (p == 0)
1817 return false;
1818 p++;
1819 if (*p == '\0')
1820 return false;
1822 // split up a line
1823 const char* end;
1824 char* dummy;
1825 while (*p != '\0') {
1826 Breakpoint bp;
1827 // get Num
1828 bp.id = strtol(p, &dummy, 10); /* don't care about overflows */
1829 p = dummy;
1830 // check for continued <MULTIPLE> breakpoint
1831 if (*p == '.' && isdigit(p[1]))
1833 // continuation: skip type and disposition
1835 else
1837 // get Type
1838 while (isspace(*p))
1839 p++;
1840 if (strncmp(p, "breakpoint", 10) == 0) {
1841 p += 10;
1842 } else if (strncmp(p, "hw watchpoint", 13) == 0) {
1843 bp.type = Breakpoint::watchpoint;
1844 p += 13;
1845 } else if (strncmp(p, "watchpoint", 10) == 0) {
1846 bp.type = Breakpoint::watchpoint;
1847 p += 10;
1849 while (isspace(*p))
1850 p++;
1851 if (*p == '\0')
1852 break;
1853 // get Disp
1854 bp.temporary = *p++ == 'd';
1856 while (*p != '\0' && !isspace(*p)) /* "keep" or "del" */
1857 p++;
1858 while (isspace(*p))
1859 p++;
1860 if (*p == '\0')
1861 break;
1862 // get Enb
1863 bp.enabled = *p++ == 'y';
1864 while (*p != '\0' && !isspace(*p)) /* "y" or "n" */
1865 p++;
1866 while (isspace(*p))
1867 p++;
1868 if (*p == '\0')
1869 break;
1870 // the address, if present
1871 if (bp.type == Breakpoint::breakpoint &&
1872 strncmp(p, "0x", 2) == 0)
1874 const char* start = p;
1875 while (*p != '\0' && !isspace(*p))
1876 p++;
1877 bp.address = QString::fromLatin1(start, p-start);
1878 while (isspace(*p) && *p != '\n')
1879 p++;
1880 if (*p == '\0')
1881 break;
1883 // remainder is location, hit and ignore count, condition
1884 end = strchr(p, '\n');
1885 if (end == 0) {
1886 bp.location = p;
1887 p += bp.location.length();
1888 } else {
1889 // location of a <MULTIPLE> filled in from subsequent breakpoints
1890 if (strncmp(p, "<MULTIPLE>", 10) != 0)
1891 bp.location = QString::fromLatin1(p, end-p).trimmed();
1892 p = end+1; /* skip over \n */
1895 // may be continued in next line
1896 while (isspace(*p)) { /* p points to beginning of line */
1897 // skip white space at beginning of line
1898 while (isspace(*p))
1899 p++;
1901 // seek end of line
1902 end = strchr(p, '\n');
1903 if (end == 0)
1904 end = p+strlen(p);
1906 if (strncmp(p, "breakpoint already hit", 22) == 0) {
1907 // extract the hit count
1908 p += 22;
1909 bp.hitCount = strtol(p, &dummy, 10);
1910 TRACE(QString("hit count %1").arg(bp.hitCount));
1911 } else if (strncmp(p, "stop only if ", 13) == 0) {
1912 // extract condition
1913 p += 13;
1914 bp.condition = QString::fromLatin1(p, end-p).trimmed();
1915 TRACE("condition: "+bp.condition);
1916 } else if (strncmp(p, "ignore next ", 12) == 0) {
1917 // extract ignore count
1918 p += 12;
1919 bp.ignoreCount = strtol(p, &dummy, 10);
1920 TRACE(QString("ignore count %1").arg(bp.ignoreCount));
1921 } else {
1922 // indeed a continuation
1923 bp.location += " " + QString::fromLatin1(p, end-p).trimmed();
1925 p = end;
1926 if (*p != '\0')
1927 p++; /* skip '\n' */
1930 if (brks.empty() || brks.back().id != bp.id) {
1931 brks.push_back(bp);
1932 } else {
1933 // this is a continuation; fill in location if not yet set
1934 // otherwise, drop this breakpoint
1935 Breakpoint& mbp = brks.back();
1936 if (mbp.location.isEmpty() && !bp.location.isEmpty()) {
1937 mbp.location = bp.location;
1938 mbp.address = bp.address;
1939 } else if (mbp.address.isEmpty() && !bp.address.isEmpty()) {
1940 mbp.address = bp.address;
1944 return true;
1947 std::list<ThreadInfo> GdbDriver::parseThreadList(const char* output)
1949 std::list<ThreadInfo> threads;
1950 if (strcmp(output, "\n") == 0 ||
1951 strncmp(output, "No stack.", 9) == 0 ||
1952 strncmp(output, "No threads.", 11) == 0) {
1953 // no threads
1954 return threads;
1957 bool newFormat = false;
1958 const char* p = output;
1959 while (*p != '\0') {
1960 ThreadInfo thr;
1961 // seach look for thread id, watching out for the focus indicator
1962 thr.hasFocus = false;
1963 while (isspace(*p)) /* may be \n from prev line: see "No stack" below */
1964 p++;
1966 // recent GDBs write a header line; skip it
1967 if (threads.empty() && strncmp(p, "Id Target", 11) == 0) {
1968 p = strchr(p, '\n');
1969 if (p == NULL)
1970 break;
1971 newFormat = true;
1972 continue; // next line please, '\n' is skipped above
1975 if (*p == '*') {
1976 thr.hasFocus = true;
1977 p++;
1978 // there follows only whitespace
1980 const char* end;
1981 char *temp_end = NULL; /* we need a non-const 'end' for strtol to use...*/
1982 thr.id = strtol(p, &temp_end, 10);
1983 end = temp_end;
1984 if (p == end) {
1985 // syntax error: no number found; bail out
1986 return threads;
1988 p = end;
1990 // skip space
1991 while (isspace(*p))
1992 p++;
1995 * Now follows the thread's SYSTAG.
1997 if (!newFormat) {
1998 // In the old format, it is terminated by two blanks.
1999 end = strstr(p, " ");
2000 if (end == 0) {
2001 // syntax error; bail out
2002 return threads;
2004 end += 2;
2005 } else {
2006 // In the new format lies crazyness: there is no definitive
2007 // end marker. At best we can guess when the SYSTAG ends.
2008 // A typical thread list on Linux looks like this:
2010 // Id Target Id Frame
2011 // 2 Thread 0x7ffff7854700 (LWP 10827) "thrserver" 0x00007ffff7928631 in clone () from /lib64/libc.so.6
2012 // * 1 Thread 0x7ffff7fcc700 (LWP 10808) "thrserver" main () at thrserver.c:84
2014 // Looking at GDB's code, the Target Id ends in tokens that
2015 // are bracketed by parentheses or quotes. Therefore,
2016 // we skip (at most) two tokens ('Thread' and the address),
2017 // and then all parts that are in parentheses or quotes.
2018 int n = 0;
2019 end = p;
2020 while (*end) {
2021 if (*end == '"') {
2022 skipString(end);
2023 n = 2;
2024 } else if (*end == '(') {
2025 skipNested(end, '(', ')');
2026 n = 2;
2027 } else if (n < 2) {
2028 while (*end && !isspace(*end))
2029 ++end;
2030 ++n;
2031 } else {
2032 break;
2034 while (isspace(*end))
2035 ++end;
2038 thr.threadName = QString::fromLatin1(p, end-p).trimmed();
2039 p = end;
2042 * Now follows a standard stack frame. Sometimes, however, gdb
2043 * catches a thread at an instant where it doesn't have a stack.
2045 if (strncmp(p, "[No stack.]", 11) != 0) {
2046 ::parseFrameInfo(p, thr.function, thr.fileName, thr.lineNo, thr.address);
2047 } else {
2048 thr.function = "[No stack]";
2049 thr.lineNo = -1;
2050 p += 11; /* \n is skipped above */
2053 threads.push_back(thr);
2055 return threads;
2058 static bool parseNewBreakpoint(const char* o, int& id,
2059 QString& file, int& lineNo, QString& address);
2060 static bool parseNewWatchpoint(const char* o, int& id,
2061 QString& expr);
2063 bool GdbDriver::parseBreakpoint(const char* output, int& id,
2064 QString& file, int& lineNo, QString& address)
2066 // skip lines of that begin with "(Cannot find"
2067 while (strncmp(output, "(Cannot find", 12) == 0 ||
2068 strncmp(output, "Note: breakpoint", 16) == 0)
2070 output = strchr(output, '\n');
2071 if (output == 0)
2072 return false;
2073 output++; /* skip newline */
2076 if (strncmp(output, "Breakpoint ", 11) == 0) {
2077 output += 11; /* skip "Breakpoint " */
2078 return ::parseNewBreakpoint(output, id, file, lineNo, address);
2079 } else if (strncmp(output, "Temporary breakpoint ", 21) == 0) {
2080 output += 21;
2081 return ::parseNewBreakpoint(output, id, file, lineNo, address);
2082 } else if (strncmp(output, "Hardware watchpoint ", 20) == 0) {
2083 output += 20;
2084 return ::parseNewWatchpoint(output, id, address);
2085 } else if (strncmp(output, "Watchpoint ", 11) == 0) {
2086 output += 11;
2087 return ::parseNewWatchpoint(output, id, address);
2089 return false;
2092 static bool parseNewBreakpoint(const char* o, int& id,
2093 QString& file, int& lineNo, QString& address)
2095 // breakpoint id
2096 char* p;
2097 id = strtoul(o, &p, 10);
2098 if (p == o)
2099 return false;
2101 // check for the address
2102 if (strncmp(p, " at 0x", 6) == 0) {
2103 char* start = p+4; /* skip " at ", but not 0x */
2104 p += 6;
2105 while (isxdigit(*p))
2106 ++p;
2107 address = QString::fromLatin1(start, p-start);
2111 * Mostly, GDB responds with this syntax:
2113 * Breakpoint 1 at 0x400b94: file multibrkpt.cpp, line 9. (2 locations)
2115 * but sometimes it uses this syntax:
2117 * Breakpoint 4 at 0x804f158: lotto739.cpp:95. (3 locations)
2119 char* fileEnd, *numStart = 0;
2120 char* fileStart = strstr(p, "file ");
2121 if (fileStart != 0)
2123 fileStart += 5;
2124 fileEnd = strstr(fileStart, ", line ");
2125 if (fileEnd != 0)
2126 numStart = fileEnd + 7;
2128 if (numStart == 0 && p[0] == ':' && p[1] == ' ')
2130 fileStart = p+2;
2131 while (isspace(*fileStart))
2132 ++fileStart;
2133 fileEnd = strchr(fileStart, ':');
2134 if (fileEnd != 0)
2135 numStart = fileEnd + 1;
2137 if (numStart == 0)
2138 return !address.isEmpty(); /* parse error only if there's no address */
2140 QString fileName = QString::fromLatin1(fileStart, fileEnd-fileStart);
2141 int line = strtoul(numStart, &p, 10);
2142 if (numStart == p)
2143 return false;
2145 file = fileName;
2146 lineNo = line-1; /* zero-based! */
2147 return true;
2150 static bool parseNewWatchpoint(const char* o, int& id,
2151 QString& expr)
2153 // watchpoint id
2154 char* p;
2155 id = strtoul(o, &p, 10);
2156 if (p == o)
2157 return false;
2159 if (strncmp(p, ": ", 2) != 0)
2160 return false;
2161 p += 2;
2163 // all the rest on the line is the expression
2164 expr = QString::fromLatin1(p, strlen(p)).trimmed();
2165 return true;
2168 void GdbDriver::parseLocals(const char* output, std::list<ExprValue*>& newVars)
2170 // check for possible error conditions
2171 if (strncmp(output, "No symbol table", 15) == 0)
2173 return;
2176 while (*output != '\0') {
2177 while (isspace(*output))
2178 output++;
2179 if (*output == '\0')
2180 break;
2181 // skip occurrences of "No locals" and "No args"
2182 if (strncmp(output, "No locals", 9) == 0 ||
2183 strncmp(output, "No arguments", 12) == 0)
2185 output = strchr(output, '\n');
2186 if (output == 0) {
2187 break;
2189 continue;
2192 ExprValue* variable = parseVar(output);
2193 if (variable == 0) {
2194 break;
2196 // do not add duplicates
2197 for (std::list<ExprValue*>::iterator o = newVars.begin(); o != newVars.end(); ++o) {
2198 if ((*o)->m_name == variable->m_name) {
2199 delete variable;
2200 goto skipDuplicate;
2203 newVars.push_back(variable);
2204 skipDuplicate:;
2208 ExprValue* GdbDriver::parsePrintExpr(const char* output, bool wantErrorValue)
2210 ExprValue* var = 0;
2211 // check for error conditions
2212 if (!parseErrorMessage(output, var, wantErrorValue))
2214 // parse the variable
2215 var = parseVar(output);
2217 return var;
2220 bool GdbDriver::parseChangeWD(const char* output, QString& message)
2222 bool isGood = false;
2223 message = QString(output).simplified();
2224 if (message.isEmpty()) {
2225 message = i18n("New working directory: ") + m_programWD;
2226 isGood = true;
2228 return isGood;
2231 bool GdbDriver::parseChangeExecutable(const char* output, QString& message)
2233 message = output;
2235 m_haveCoreFile = false;
2238 * Lines starting with the following do not indicate errors:
2239 * Using host libthread_db
2240 * (no debugging symbols found)
2241 * Reading symbols from
2243 while (strncmp(output, "Reading symbols from", 20) == 0 ||
2244 strncmp(output, "done.", 5) == 0 ||
2245 strncmp(output, "Missing separate debuginfo", 26) == 0 ||
2246 strncmp(output, "Try: ", 5) == 0 ||
2247 strncmp(output, "Using host libthread_db", 23) == 0 ||
2248 strncmp(output, "(no debugging symbols found)", 28) == 0)
2250 // this line is good, go to the next one
2251 const char* end = strchr(output, '\n');
2252 if (end == 0)
2253 output += strlen(output);
2254 else
2255 output = end+1;
2259 * If we've parsed all lines, there was no error.
2261 return output[0] == '\0';
2264 bool GdbDriver::parseCoreFile(const char* output)
2266 // if command succeeded, gdb emits a line starting with "#0 "
2267 m_haveCoreFile = strstr(output, "\n#0 ") != 0;
2268 return m_haveCoreFile;
2271 uint GdbDriver::parseProgramStopped(const char* output, QString& message)
2273 // optionally: "program changed, rereading symbols",
2274 // followed by:
2275 // "Program exited normally"
2276 // "Program terminated with wignal SIGSEGV"
2277 // "Program received signal SIGINT" or other signal
2278 // "Breakpoint..."
2279 // GDB since 7.3 prints
2280 // "[Inferior 1 (process 13400) exited normally]"
2281 // "[Inferior 1 (process 14698) exited with code 01]"
2283 // go through the output, line by line, checking what we have
2284 const char* start = output - 1;
2285 uint flags = SFprogramActive;
2286 message = QString();
2287 do {
2288 start++; /* skip '\n' */
2290 if (strncmp(start, "Program ", 8) == 0 ||
2291 strncmp(start, "ptrace: ", 8) == 0) {
2293 * When we receive a signal, the program remains active.
2295 * Special: If we "stopped" in a corefile, the string "Program
2296 * terminated with signal"... is displayed. (Normally, we see
2297 * "Program received signal"... when a signal happens.)
2299 if (strncmp(start, "Program exited", 14) == 0 ||
2300 (strncmp(start, "Program terminated", 18) == 0 && !m_haveCoreFile) ||
2301 strncmp(start, "ptrace: ", 8) == 0)
2303 flags &= ~SFprogramActive;
2306 // set message
2307 const char* endOfMessage = strchr(start, '\n');
2308 if (endOfMessage == 0)
2309 endOfMessage = start + strlen(start);
2310 message = QString::fromLatin1(start, endOfMessage-start);
2311 } else if (strncmp(start, "[Inferior ", 10) == 0) {
2312 const char* p = start + 10;
2313 // skip number and space
2314 while (*p && !isspace(*p))
2315 ++p;
2316 while (isspace(*p))
2317 ++p;
2318 if (*p == '(') {
2319 skipNested(p, '(', ')');
2320 if (strncmp(p, " exited ", 8) == 0) {
2321 flags &= ~SFprogramActive;
2323 // set message
2324 const char* end = strchr(p, '\n');
2325 if (end == 0)
2326 end = p + strlen(p);
2327 // strip [] from the message
2328 message = QString::fromLatin1(start+1, end-start-2);
2331 } else if (strncmp(start, "Breakpoint ", 11) == 0) {
2333 * We stopped at a (permanent) breakpoint (gdb doesn't tell us
2334 * that it stopped at a temporary breakpoint).
2336 flags |= SFrefreshBreak;
2337 } else if (strstr(start, "re-reading symbols.") != 0) {
2338 flags |= SFrefreshSource;
2341 // next line, please
2342 start = strchr(start, '\n');
2343 } while (start != 0);
2346 * Gdb only notices when new threads have appeared, but not when a
2347 * thread finishes. So we always have to assume that the list of
2348 * threads has changed.
2350 flags |= SFrefreshThreads;
2352 return flags;
2355 QStringList GdbDriver::parseSharedLibs(const char* output)
2357 QStringList shlibs;
2358 if (strncmp(output, "No shared libraries loaded", 26) == 0)
2359 return shlibs;
2361 // parse the table of shared libraries
2363 // strip off head line
2364 output = strchr(output, '\n');
2365 if (output == 0)
2366 return shlibs;
2367 output++; /* skip '\n' */
2368 QString shlibName;
2369 while (*output != '\0') {
2370 // format of a line is
2371 // 0x404c5000 0x40580d90 Yes /lib/libc.so.5
2372 // 3 blocks of non-space followed by space
2373 for (int i = 0; *output != '\0' && i < 3; i++) {
2374 while (*output != '\0' && !isspace(*output)) { /* non-space */
2375 output++;
2377 while (isspace(*output)) { /* space */
2378 output++;
2381 if (*output == '\0')
2382 return shlibs;
2383 const char* start = output;
2384 output = strchr(output, '\n');
2385 if (output == 0)
2386 output = start + strlen(start);
2387 shlibName = QString::fromLatin1(start, output-start);
2388 if (*output != '\0')
2389 output++;
2390 shlibs.append(shlibName);
2391 TRACE("found shared lib " + shlibName);
2393 return shlibs;
2396 bool GdbDriver::parseFindType(const char* output, QString& type)
2398 if (strncmp(output, "type = ", 7) != 0)
2399 return false;
2402 * Everything else is the type. We strip off any leading "const" and any
2403 * trailing "&" on the grounds that neither affects the decoding of the
2404 * object. We also strip off all white-space from the type.
2406 output += 7;
2407 if (strncmp(output, "const ", 6) == 0)
2408 output += 6;
2409 type = output;
2410 type.replace(QRegExp("\\s+"), "");
2411 if (type.endsWith("&"))
2412 type.truncate(type.length() - 1);
2413 return true;
2416 std::list<RegisterInfo> GdbDriver::parseRegisters(const char* output)
2418 std::list<RegisterInfo> regs;
2419 if (strncmp(output, "The program has no registers now", 32) == 0) {
2420 return regs;
2423 // parse register values
2424 while (*output != '\0')
2426 RegisterInfo reg;
2427 // skip space at the start of the line
2428 while (isspace(*output))
2429 output++;
2431 // register name
2432 const char* start = output;
2433 while (*output != '\0' && !isspace(*output))
2434 output++;
2435 if (*output == '\0')
2436 break;
2437 reg.regName = QString::fromLatin1(start, output-start);
2439 // skip space
2440 while (isspace(*output))
2441 output++;
2443 QString value;
2446 * If we find a brace now, this is a vector register. We look for
2447 * the closing brace and treat the result as cooked value.
2449 if (*output == '{')
2451 start = output;
2452 skipNested(output, '{', '}');
2453 value = QString::fromLatin1(start, output-start).simplified();
2454 // skip space, but not the end of line
2455 while (isspace(*output) && *output != '\n')
2456 output++;
2457 // get rid of the braces at the begining and the end
2458 value.remove(0, 1);
2459 if (value[value.length()-1] == '}') {
2460 value = value.left(value.length()-1);
2462 // gdb 5.3 doesn't print a separate set of raw values
2463 if (*output == '{') {
2464 // another set of vector follows
2465 // what we have so far is the raw value
2466 reg.rawValue = value;
2468 start = output;
2469 skipNested(output, '{', '}');
2470 value = QString::fromLatin1(start, output-start).simplified();
2471 } else {
2472 // for gdb 5.3
2473 // find first type that does not have an array, this is the RAW value
2474 const char* end=start;
2475 findEnd(end);
2476 const char* cur=start;
2477 while (cur<end) {
2478 while (*cur != '=' && cur<end)
2479 cur++;
2480 cur++;
2481 while (isspace(*cur) && cur<end)
2482 cur++;
2483 if (isNumberish(*cur)) {
2484 end=cur;
2485 while (*end && (*end!='}') && (*end!=',') && (*end!='\n'))
2486 end++;
2487 QString rawValue = QString::fromLatin1(cur, end-cur).simplified();
2488 reg.rawValue = rawValue;
2490 if (rawValue.left(2)=="0x") {
2491 // ok we have a raw value, now get it's type
2492 end=cur-1;
2493 while (isspace(*end) || *end=='=') end--;
2494 end++;
2495 cur=end-1;
2496 while (*cur!='{' && *cur!=' ')
2497 cur--;
2498 cur++;
2499 reg.type = QString::fromLatin1(cur, end-cur);
2502 // end while loop
2503 cur=end;
2506 // skip to the end of line
2507 while (*output != '\0' && *output != '\n')
2508 output++;
2509 // get rid of the braces at the begining and the end
2510 value.remove(0, 1);
2511 if (value[value.length()-1] == '}') {
2512 value.truncate(value.length()-1);
2515 reg.cookedValue = value;
2517 else
2519 continuation:
2520 // the rest of the line is the register value
2521 start = output;
2522 output = strchr(output,'\n');
2523 if (output == 0)
2524 output = start + strlen(start);
2525 value += QString::fromLatin1(start, output-start).simplified();
2528 * Look ahead: if the subsequent line is indented, it continues
2529 * the current register value.
2531 if (output != 0 && isspace(output[1]))
2533 ++output;
2534 value += ' ';
2535 goto continuation;
2539 * We split the raw from the cooked values.
2540 * Some modern gdbs explicitly say: "0.1234 (raw 0x3e4567...)".
2541 * Here, the cooked value comes first, and the raw value is in
2542 * the second part.
2544 int pos = value.indexOf(" (raw ");
2545 if (pos >= 0)
2547 reg.cookedValue = value.left(pos);
2548 reg.rawValue = value.mid(pos+6);
2549 if (reg.rawValue.right(1) == ")") // remove closing bracket
2550 reg.rawValue.truncate(reg.rawValue.length()-1);
2552 else
2555 * In other cases we split off the first token (separated by
2556 * whitespace). It is the raw value. The remainder of the line
2557 * is the cooked value.
2559 int pos = value.indexOf(' ');
2560 if (pos < 0) {
2561 reg.rawValue = value;
2562 reg.cookedValue = QString();
2563 } else {
2564 reg.rawValue = value.left(pos);
2565 reg.cookedValue = value.mid(pos+1);
2569 if (*output != '\0')
2570 output++; /* skip '\n' */
2572 regs.push_back(reg);
2574 return regs;
2577 bool GdbDriver::parseInfoLine(const char* output, QString& addrFrom, QString& addrTo)
2579 // "is at address" or "starts at address"
2580 const char* start = strstr(output, "s at address ");
2581 if (start == 0)
2582 return false;
2584 start += 13;
2585 const char* p = start;
2586 while (*p != '\0' && !isspace(*p))
2587 p++;
2588 addrFrom = QString::fromLatin1(start, p-start);
2590 start = strstr(p, "and ends at ");
2591 if (start == 0) {
2592 addrTo = addrFrom;
2593 return true;
2596 start += 12;
2597 p = start;
2598 while (*p != '\0' && !isspace(*p))
2599 p++;
2600 addrTo = QString::fromLatin1(start, p-start);
2602 return true;
2605 std::list<DisassembledCode> GdbDriver::parseDisassemble(const char* output)
2607 std::list<DisassembledCode> code;
2609 if (strncmp(output, "Dump of assembler", 17) != 0) {
2610 // error message?
2611 DisassembledCode c;
2612 c.code = output;
2613 code.push_back(c);
2614 return code;
2617 // remove first line
2618 const char* p = strchr(output, '\n');
2619 if (p == 0)
2620 return code; /* not a regular output */
2622 p++;
2624 // remove last line
2625 const char* end = strstr(output, "End of assembler");
2626 if (end == 0)
2627 end = p + strlen(p);
2629 // remove function offsets from the lines
2630 while (p != end)
2632 DisassembledCode c;
2633 // skip initial space or PC pointer ("=>", since gdb 7.1)
2634 while (p != end) {
2635 if (isspace(*p))
2636 ++p;
2637 else if (p[0] == '=' && p[1] == '>')
2638 p += 2;
2639 else
2640 break;
2642 const char* start = p;
2643 // address
2644 while (p != end && !isspace(*p))
2645 p++;
2646 c.address = QString::fromLatin1(start, p-start);
2648 // function name (enclosed in '<>', followed by ':')
2649 while (p != end && *p != '<')
2650 p++;
2651 if (*p == '<')
2652 skipNestedAngles(p);
2653 if (*p == ':')
2654 p++;
2656 // space until code
2657 while (p != end && isspace(*p))
2658 p++;
2660 // code until end of line
2661 start = p;
2662 while (p != end && *p != '\n')
2663 p++;
2664 if (p != end) /* include '\n' */
2665 p++;
2667 c.code = QString::fromLatin1(start, p-start);
2668 code.push_back(c);
2670 return code;
2673 QString GdbDriver::parseMemoryDump(const char* output, std::list<MemoryDump>& memdump)
2675 if (isErrorExpr(output)) {
2676 // error; strip space
2677 QString msg = output;
2678 return msg.trimmed();
2681 const char* p = output; /* save typing */
2683 // the address
2684 while (*p != 0) {
2685 MemoryDump md;
2687 const char* start = p;
2688 while (*p != '\0' && *p != ':' && !isspace(*p))
2689 p++;
2690 md.address = QString::fromLatin1(start, p-start);
2691 if (*p != ':') {
2692 // parse function offset
2693 while (isspace(*p))
2694 p++;
2695 start = p;
2696 while (*p != '\0' && !(*p == ':' && isspace(p[1])))
2697 p++;
2698 md.address.fnoffs = QString::fromLatin1(start, p-start);
2700 if (*p == ':')
2701 p++;
2702 // skip space; this may skip a new-line char!
2703 while (isspace(*p))
2704 p++;
2705 // everything to the end of the line is the memory dump
2706 const char* end = strchr(p, '\n');
2707 if (end != 0) {
2708 md.dump = QString::fromLatin1(p, end-p);
2709 p = end+1;
2710 } else {
2711 md.dump = QString::fromLatin1(p, strlen(p));
2712 p += strlen(p);
2714 memdump.push_back(md);
2717 return QString();
2720 QString GdbDriver::editableValue(VarTree* value)
2722 QByteArray ba = value->value().toLatin1();
2723 const char* s = ba.constData();
2725 // if the variable is a pointer value that contains a cast,
2726 // remove the cast
2727 if (*s == '(') {
2728 skipNested(s, '(', ')');
2729 // skip space
2730 while (isspace(*s))
2731 ++s;
2734 repeat:
2735 const char* start = s;
2737 if (strncmp(s, "0x", 2) == 0)
2739 s += 2;
2740 while (isxdigit(*s))
2741 ++s;
2744 * What we saw so far might have been a reference. If so, edit the
2745 * referenced value. Otherwise, edit the pointer.
2747 if (*s == ':') {
2748 // a reference
2749 ++s;
2750 goto repeat;
2752 // a pointer
2753 // if it's a pointer to a string, remove the string
2754 const char* end = s;
2755 while (isspace(*s))
2756 ++s;
2757 if (*s == '"') {
2758 // a string
2759 return QString::fromLatin1(start, end-start);
2760 } else {
2761 // other pointer
2762 return QString::fromLatin1(start, strlen(start));
2766 // else leave it unchanged (or stripped of the reference preamble)
2767 return s;
2770 QString GdbDriver::parseSetVariable(const char* output)
2772 // if there is any output, it is an error message
2773 QString msg = output;
2774 return msg.trimmed();
2778 #include "gdbdriver.moc"