Add a possibility to detach from the debugged process.
[kdbg.git] / kdbg / gdbdriver.cpp
blobf15671307aa9d4583a16e688026fb91cb7c7f1fd
1 /*
2 * Copyright Johannes Sixt
3 * This file is licensed under the GNU General Public License Version 2.
4 * See the file COPYING in the toplevel directory of the source directory.
5 */
7 #include "gdbdriver.h"
8 #include "exprwnd.h"
9 #include <QFileInfo>
10 #include <QRegExp>
11 #include <QStringList>
12 #include <klocale.h> /* i18n */
13 #include <ctype.h>
14 #include <signal.h>
15 #include <stdlib.h> /* strtol, atoi */
16 #include <string.h> /* strcpy */
18 #include "assert.h"
19 #include "mydebug.h"
21 static void skipString(const char*& p);
22 static void skipNested(const char*& s, char opening, char closing);
23 static ExprValue* parseVar(const char*& s);
24 static bool parseName(const char*& s, QString& name, VarTree::NameKind& kind);
25 static bool parseValue(const char*& s, ExprValue* variable);
26 static bool parseNested(const char*& s, ExprValue* variable);
27 static bool parseVarSeq(const char*& s, ExprValue* variable);
28 static bool parseValueSeq(const char*& s, ExprValue* variable);
30 #define PROMPT "(kdbg)"
31 #define PROMPT_LEN 6
33 // TODO: make this cmd info stuff non-static to allow multiple
34 // simultaneous gdbs to run!
36 struct GdbCmdInfo {
37 DbgCommand cmd;
38 const char* fmt; /* format string */
39 enum Args {
40 argNone, argString, argNum,
41 argStringNum, argNumString,
42 argString2, argNum2
43 } argsNeeded;
46 #if 0
47 // This is how the QString data print statement generally looks like.
48 // It is set by KDebugger via setPrintQStringDataCmd().
50 static const char printQStringStructFmt[] =
51 // if the string data is junk, fail early
52 "print ($qstrunicode=($qstrdata=(%s))->unicode)?"
53 // print an array of shorts
54 "(*(unsigned short*)$qstrunicode)@"
55 // limit the length
56 "(($qstrlen=(unsigned int)($qstrdata->len))>100?100:$qstrlen)"
57 // if unicode data is 0, report a special value
58 ":1==0\n";
59 #endif
60 static const char printQStringStructFmt[] = "print (0?\"%s\":$kdbgundef)\n";
63 * The following array of commands must be sorted by the DC* values,
64 * because they are used as indices.
66 static GdbCmdInfo cmds[] = {
67 { DCinitialize, "", GdbCmdInfo::argNone },
68 { DCtty, "tty %s\n", GdbCmdInfo::argString },
69 { DCexecutable, "file \"%s\"\n", GdbCmdInfo::argString },
70 { DCtargetremote, "target remote %s\n", GdbCmdInfo::argString },
71 #ifdef __FreeBSD__
72 { DCcorefile, "target FreeBSD-core %s\n", GdbCmdInfo::argString },
73 #else
74 { DCcorefile, "target core %s\n", GdbCmdInfo::argString },
75 #endif
76 { DCattach, "attach %s\n", GdbCmdInfo::argString },
77 { DCinfolinemain, "kdbg_infolinemain\n", GdbCmdInfo::argNone },
78 { DCinfolocals, "kdbg__alllocals\n", GdbCmdInfo::argNone },
79 { DCinforegisters, "info all-registers\n", GdbCmdInfo::argNone},
80 { DCexamine, "x %s %s\n", GdbCmdInfo::argString2 },
81 { DCinfoline, "info line %s:%d\n", GdbCmdInfo::argStringNum },
82 { DCdisassemble, "disassemble %s %s\n", GdbCmdInfo::argString2 },
83 { DCsetargs, "set args %s\n", GdbCmdInfo::argString },
84 { DCsetenv, "set env %s %s\n", GdbCmdInfo::argString2 },
85 { DCunsetenv, "unset env %s\n", GdbCmdInfo::argString },
86 { DCsetoption, "setoption %s %d\n", GdbCmdInfo::argStringNum},
87 { DCcd, "cd %s\n", GdbCmdInfo::argString },
88 { DCbt, "bt\n", GdbCmdInfo::argNone },
89 { DCrun, "run\n", GdbCmdInfo::argNone },
90 { DCcont, "cont\n", GdbCmdInfo::argNone },
91 { DCstep, "step\n", GdbCmdInfo::argNone },
92 { DCstepi, "stepi\n", GdbCmdInfo::argNone },
93 { DCnext, "next\n", GdbCmdInfo::argNone },
94 { DCnexti, "nexti\n", GdbCmdInfo::argNone },
95 { DCfinish, "finish\n", GdbCmdInfo::argNone },
96 { DCuntil, "until %s:%d\n", GdbCmdInfo::argStringNum },
97 { DCkill, "kill\n", GdbCmdInfo::argNone },
98 { DCdetach, "detach\n", GdbCmdInfo::argNone },
99 { DCbreaktext, "break %s\n", GdbCmdInfo::argString },
100 { DCbreakline, "break %s:%d\n", GdbCmdInfo::argStringNum },
101 { DCtbreakline, "tbreak %s:%d\n", GdbCmdInfo::argStringNum },
102 { DCbreakaddr, "break *%s\n", GdbCmdInfo::argString },
103 { DCtbreakaddr, "tbreak *%s\n", GdbCmdInfo::argString },
104 { DCwatchpoint, "watch %s\n", GdbCmdInfo::argString },
105 { DCdelete, "delete %d\n", GdbCmdInfo::argNum },
106 { DCenable, "enable %d\n", GdbCmdInfo::argNum },
107 { DCdisable, "disable %d\n", GdbCmdInfo::argNum },
108 { DCprint, "print %s\n", GdbCmdInfo::argString },
109 { DCprintDeref, "print *(%s)\n", GdbCmdInfo::argString },
110 { DCprintStruct, "print %s\n", GdbCmdInfo::argString },
111 { DCprintQStringStruct, printQStringStructFmt, GdbCmdInfo::argString},
112 { DCprintPopup, "print %s\n", GdbCmdInfo::argString },
113 { DCframe, "frame %d\n", GdbCmdInfo::argNum },
114 { DCfindType, "whatis %s\n", GdbCmdInfo::argString },
115 { DCinfosharedlib, "info sharedlibrary\n", GdbCmdInfo::argNone },
116 { DCthread, "thread %d\n", GdbCmdInfo::argNum },
117 { DCinfothreads, "info threads\n", GdbCmdInfo::argNone },
118 { DCinfobreak, "info breakpoints\n", GdbCmdInfo::argNone },
119 { DCcondition, "condition %d %s\n", GdbCmdInfo::argNumString},
120 { DCsetpc, "set variable $pc=%s\n", GdbCmdInfo::argString },
121 { DCignore, "ignore %d %d\n", GdbCmdInfo::argNum2},
122 { DCprintWChar, "print ($s=%s)?*$s@wcslen($s):0x0\n", GdbCmdInfo::argString },
123 { DCsetvariable, "set variable %s=%s\n", GdbCmdInfo::argString2 },
126 #define NUM_CMDS (int(sizeof(cmds)/sizeof(cmds[0])))
127 #define MAX_FMTLEN 200
129 GdbDriver::GdbDriver() :
130 DebuggerDriver()
132 #ifndef NDEBUG
133 // check command info array
134 const char* perc;
135 for (int i = 0; i < NUM_CMDS; i++) {
136 // must be indexable by DbgCommand values, i.e. sorted by DbgCommand values
137 assert(i == cmds[i].cmd);
138 // a format string must be associated
139 assert(cmds[i].fmt != 0);
140 assert(strlen(cmds[i].fmt) <= MAX_FMTLEN);
141 // format string must match arg specification
142 switch (cmds[i].argsNeeded) {
143 case GdbCmdInfo::argNone:
144 assert(strchr(cmds[i].fmt, '%') == 0);
145 break;
146 case GdbCmdInfo::argString:
147 perc = strchr(cmds[i].fmt, '%');
148 assert(perc != 0 && perc[1] == 's');
149 assert(strchr(perc+2, '%') == 0);
150 break;
151 case GdbCmdInfo::argNum:
152 perc = strchr(cmds[i].fmt, '%');
153 assert(perc != 0 && perc[1] == 'd');
154 assert(strchr(perc+2, '%') == 0);
155 break;
156 case GdbCmdInfo::argStringNum:
157 perc = strchr(cmds[i].fmt, '%');
158 assert(perc != 0 && perc[1] == 's');
159 perc = strchr(perc+2, '%');
160 assert(perc != 0 && perc[1] == 'd');
161 assert(strchr(perc+2, '%') == 0);
162 break;
163 case GdbCmdInfo::argNumString:
164 perc = strchr(cmds[i].fmt, '%');
165 assert(perc != 0 && perc[1] == 'd');
166 perc = strchr(perc+2, '%');
167 assert(perc != 0 && perc[1] == 's');
168 assert(strchr(perc+2, '%') == 0);
169 break;
170 case GdbCmdInfo::argString2:
171 perc = strchr(cmds[i].fmt, '%');
172 assert(perc != 0 && perc[1] == 's');
173 perc = strchr(perc+2, '%');
174 assert(perc != 0 && perc[1] == 's');
175 assert(strchr(perc+2, '%') == 0);
176 break;
177 case GdbCmdInfo::argNum2:
178 perc = strchr(cmds[i].fmt, '%');
179 assert(perc != 0 && perc[1] == 'd');
180 perc = strchr(perc+2, '%');
181 assert(perc != 0 && perc[1] == 'd');
182 assert(strchr(perc+2, '%') == 0);
183 break;
186 assert(strlen(printQStringStructFmt) <= MAX_FMTLEN);
187 #endif
190 GdbDriver::~GdbDriver()
195 QString GdbDriver::driverName() const
197 return "GDB";
200 QString GdbDriver::defaultGdb()
202 return
203 "gdb"
204 " --fullname" /* to get standard file names each time the prog stops */
205 " --nx"; /* do not execute initialization files */
208 QString GdbDriver::defaultInvocation() const
210 if (m_defaultCmd.isEmpty()) {
211 return defaultGdb();
212 } else {
213 return m_defaultCmd;
217 QStringList GdbDriver::boolOptionList() const
219 // no options
220 return QStringList();
223 bool GdbDriver::startup(QString cmdStr)
225 if (!DebuggerDriver::startup(cmdStr))
226 return false;
228 static const char gdbInitialize[] =
230 * Work around buggy gdbs that do command line editing even if they
231 * are not on a tty. The readline library echos every command back
232 * in this case, which is confusing for us.
234 "set editing off\n"
235 "set confirm off\n"
236 "set print static-members off\n"
237 "set print asm-demangle on\n"
239 * Sometimes, gdb prints [New Thread ...] during 'info threads';
240 * we will not look at thread events anyway, so turn them off.
242 "set print thread-events off\n"
244 * We do not want Python pretty printer support, because their
245 * output is unpredictable, and we cannot parse it.
247 "set auto-load python off\n"
249 * Nevertheless, some Python messages get through, for example,
250 * when a backtrace is printed without the Python gdb module loaded.
252 "set python print-stack none\n"
254 * Don't assume that program functions invoked from a watch expression
255 * always succeed.
257 "set unwindonsignal on\n"
259 * Write a short macro that prints all locals: local variables and
260 * function arguments.
262 "define kdbg__alllocals\n"
263 "info locals\n" /* local vars supersede args with same name */
264 "info args\n" /* therefore, arguments must come last */
265 "end\n"
267 * Work around a bug in gdb-6.3: "info line main" crashes gdb.
269 "define kdbg_infolinemain\n"
270 "list\n"
271 "info line\n"
272 "end\n"
273 // change prompt string and synchronize with gdb
274 "set prompt " PROMPT "\n"
277 executeCmdString(DCinitialize, gdbInitialize, false);
279 // assume that QString::null is ok
280 cmds[DCprintQStringStruct].fmt = printQStringStructFmt;
282 return true;
285 void GdbDriver::commandFinished(CmdQueueItem* cmd)
287 // command string must be committed
288 if (!cmd->m_committed) {
289 // not commited!
290 TRACE("calling " + (__PRETTY_FUNCTION__ + (" with uncommited command:\n\t" +
291 cmd->m_cmdString)));
292 return;
295 switch (cmd->m_cmd) {
296 case DCinitialize:
299 * Check for GDB 7.1 or later; the syntax for the disassemble
300 * command has changed.
301 * This RE picks the last version number in the first line,
302 * because at least OpenSUSE writes its own version number
303 * in the first line (but before GDB's version number).
305 QRegExp re(
306 " " // must be preceded by space
307 "[(]?" // SLES 10 embeds in parentheses
308 "(\\d+)\\.(\\d+)" // major, minor
309 "[^ ]*\\n" // no space until end of line
311 int pos = re.indexIn(m_output);
312 const char* disass = "disassemble %s %s\n";
313 if (pos >= 0) {
314 int major = re.cap(1).toInt();
315 int minor = re.cap(2).toInt();
316 if (major > 7 || (major == 7 && minor >= 1))
318 disass = "disassemble %s, %s\n";
321 cmds[DCdisassemble].fmt = disass;
323 break;
324 default:;
327 /* ok, the command is ready */
328 emit commandReceived(cmd, m_output.constData());
330 switch (cmd->m_cmd) {
331 case DCcorefile:
332 case DCinfolinemain:
333 case DCinfoline:
334 case DCframe:
335 case DCattach:
336 case DCrun:
337 case DCcont:
338 case DCstep:
339 case DCstepi:
340 case DCnext:
341 case DCnexti:
342 case DCfinish:
343 case DCuntil:
344 parseMarker(cmd);
345 default:;
349 int GdbDriver::findPrompt(const QByteArray& output) const
352 * If there's a prompt string in the collected output, it must be at
353 * the very end.
355 * Note: It could nevertheless happen that a character sequence that is
356 * equal to the prompt string appears at the end of the output,
357 * although it is very, very unlikely (namely as part of a string that
358 * lingered in gdb's output buffer due to some timing/heavy load
359 * conditions for a very long time such that that buffer overflowed
360 * exactly at the end of the prompt string look-a-like).
362 int len = output.length();
363 if (len >= PROMPT_LEN &&
364 strncmp(output.data()+len-PROMPT_LEN, PROMPT, PROMPT_LEN) == 0)
366 return len-PROMPT_LEN;
368 return -1;
372 * The --fullname option makes gdb send a special normalized sequence print
373 * each time the program stops and at some other points. The sequence has
374 * the form "\032\032filename:lineno:charoffset:(beg|middle):address".
376 void GdbDriver::parseMarker(CmdQueueItem* cmd)
378 char* startMarker = strstr(m_output.data(), "\032\032");
379 if (startMarker == 0)
380 return;
382 // extract the marker
383 startMarker += 2;
384 TRACE(QString("found marker: ") + startMarker);
385 char* endMarker = strchr(startMarker, '\n');
386 if (endMarker == 0)
387 return;
389 *endMarker = '\0';
391 // extract filename and line number
392 static QRegExp MarkerRE(":(\\d+):\\d+:[begmidl]+:0x");
394 int lineNoStart = MarkerRE.indexIn(startMarker);
395 if (lineNoStart >= 0) {
396 int lineNo = MarkerRE.cap(1).toInt();
398 // get address unless there is one in cmd
399 DbgAddr address = cmd->m_addr;
400 if (address.isEmpty()) {
401 const char* addrStart = startMarker + lineNoStart +
402 MarkerRE.matchedLength() - 2;
403 address = QString(addrStart).trimmed();
406 // now show the window
407 startMarker[lineNoStart] = '\0'; /* split off file name */
408 emit activateFileLine(startMarker, lineNo-1, address);
414 * Escapes characters that might lead to problems when they appear on gdb's
415 * command line.
417 static void normalizeStringArg(QString& arg)
420 * Remove trailing backslashes. This approach is a little simplistic,
421 * but we know that there is at the moment no case where a trailing
422 * backslash would make sense.
424 while (!arg.isEmpty() && arg[arg.length()-1] == '\\') {
425 arg = arg.left(arg.length()-1);
430 QString GdbDriver::makeCmdString(DbgCommand cmd, QString strArg)
432 assert(cmd >= 0 && cmd < NUM_CMDS);
433 assert(cmds[cmd].argsNeeded == GdbCmdInfo::argString);
435 normalizeStringArg(strArg);
437 if (cmd == DCcd) {
438 // need the working directory when parsing the output
439 m_programWD = strArg;
440 } else if (cmd == DCsetargs && !m_redirect.isEmpty()) {
442 * Use saved redirection. We prepend it in front of the user's
443 * arguments so that the user can override the redirections.
445 strArg = m_redirect + " " + strArg;
448 QString cmdString;
449 cmdString.sprintf(cmds[cmd].fmt, strArg.toUtf8().constData());
450 return cmdString;
453 QString GdbDriver::makeCmdString(DbgCommand cmd, int intArg)
455 assert(cmd >= 0 && cmd < NUM_CMDS);
456 assert(cmds[cmd].argsNeeded == GdbCmdInfo::argNum);
458 QString cmdString;
459 cmdString.sprintf(cmds[cmd].fmt, intArg);
460 return cmdString;
463 QString GdbDriver::makeCmdString(DbgCommand cmd, QString strArg, int intArg)
465 assert(cmd >= 0 && cmd < NUM_CMDS);
466 assert(cmds[cmd].argsNeeded == GdbCmdInfo::argStringNum ||
467 cmds[cmd].argsNeeded == GdbCmdInfo::argNumString ||
468 cmd == DCexamine ||
469 cmd == DCtty);
471 normalizeStringArg(strArg);
473 QString cmdString;
475 if (cmd == DCtty)
478 * intArg specifies which channels should be redirected to
479 * /dev/null. It is a value or'ed together from RDNstdin,
480 * RDNstdout, RDNstderr. We store the value for a later DCsetargs
481 * command.
483 * Note: We rely on that after the DCtty a DCsetargs will follow,
484 * which will ultimately apply the redirection.
486 static const char* const runRedir[8] = {
488 "</dev/null",
489 ">/dev/null",
490 "</dev/null >/dev/null",
491 "2>/dev/null",
492 "</dev/null 2>/dev/null",
493 ">/dev/null 2>&1",
494 "</dev/null >/dev/null 2>&1"
496 if (strArg.isEmpty())
497 intArg = 7; /* failsafe if no tty */
498 m_redirect = runRedir[intArg & 7];
500 return makeCmdString(DCtty, strArg); /* note: no problem if strArg empty */
503 if (cmd == DCexamine) {
504 // make a format specifier from the intArg
505 static const char size[16] = {
506 '\0', 'b', 'h', 'w', 'g'
508 static const char format[16] = {
509 '\0', 'x', 'd', 'u', 'o', 't',
510 'a', 'c', 'f', 's', 'i'
512 assert(MDTsizemask == 0xf); /* lowest 4 bits */
513 assert(MDTformatmask == 0xf0); /* next 4 bits */
514 int count = 16; /* number of entities to print */
515 char sizeSpec = size[intArg & MDTsizemask];
516 char formatSpec = format[(intArg & MDTformatmask) >> 4];
517 assert(sizeSpec != '\0');
518 assert(formatSpec != '\0');
519 // adjust count such that 16 lines are printed
520 switch (intArg & MDTformatmask) {
521 case MDTstring: case MDTinsn:
522 break; /* no modification needed */
523 default:
524 // all cases drop through:
525 switch (intArg & MDTsizemask) {
526 case MDTbyte:
527 case MDThalfword:
528 count *= 2;
529 case MDTword:
530 count *= 2;
531 case MDTgiantword:
532 count *= 2;
534 break;
536 QString spec;
537 spec.sprintf("/%d%c%c", count, sizeSpec, formatSpec);
539 return makeCmdString(DCexamine, spec, strArg);
542 if (cmds[cmd].argsNeeded == GdbCmdInfo::argStringNum)
544 // line numbers are zero-based
545 if (cmd == DCuntil || cmd == DCbreakline ||
546 cmd == DCtbreakline || cmd == DCinfoline)
548 intArg++;
550 if (cmd == DCinfoline)
552 // must split off file name part
553 strArg = QFileInfo(strArg).fileName();
555 cmdString.sprintf(cmds[cmd].fmt, strArg.toUtf8().constData(), intArg);
557 else
559 cmdString.sprintf(cmds[cmd].fmt, intArg, strArg.toUtf8().constData());
561 return cmdString;
564 QString GdbDriver::makeCmdString(DbgCommand cmd, QString strArg1, QString strArg2)
566 assert(cmd >= 0 && cmd < NUM_CMDS);
567 assert(cmds[cmd].argsNeeded == GdbCmdInfo::argString2);
569 normalizeStringArg(strArg1);
570 normalizeStringArg(strArg2);
572 QString cmdString;
573 cmdString.sprintf(cmds[cmd].fmt,
574 strArg1.toUtf8().constData(),
575 strArg2.toUtf8().constData());
576 return cmdString;
579 QString GdbDriver::makeCmdString(DbgCommand cmd, int intArg1, int intArg2)
581 assert(cmd >= 0 && cmd < NUM_CMDS);
582 assert(cmds[cmd].argsNeeded == GdbCmdInfo::argNum2);
584 QString cmdString;
585 cmdString.sprintf(cmds[cmd].fmt, intArg1, intArg2);
586 return cmdString;
589 CmdQueueItem* GdbDriver::executeCmd(DbgCommand cmd, bool clearLow)
591 assert(cmd >= 0 && cmd < NUM_CMDS);
592 assert(cmds[cmd].argsNeeded == GdbCmdInfo::argNone);
594 if (cmd == DCrun) {
595 m_haveCoreFile = false;
598 return executeCmdString(cmd, cmds[cmd].fmt, clearLow);
601 CmdQueueItem* GdbDriver::executeCmd(DbgCommand cmd, QString strArg,
602 bool clearLow)
604 return executeCmdString(cmd, makeCmdString(cmd, strArg), clearLow);
607 CmdQueueItem* GdbDriver::executeCmd(DbgCommand cmd, int intArg,
608 bool clearLow)
611 return executeCmdString(cmd, makeCmdString(cmd, intArg), clearLow);
614 CmdQueueItem* GdbDriver::executeCmd(DbgCommand cmd, QString strArg, int intArg,
615 bool clearLow)
617 return executeCmdString(cmd, makeCmdString(cmd, strArg, intArg), clearLow);
620 CmdQueueItem* GdbDriver::executeCmd(DbgCommand cmd, QString strArg1, QString strArg2,
621 bool clearLow)
623 return executeCmdString(cmd, makeCmdString(cmd, strArg1, strArg2), clearLow);
626 CmdQueueItem* GdbDriver::executeCmd(DbgCommand cmd, int intArg1, int intArg2,
627 bool clearLow)
629 return executeCmdString(cmd, makeCmdString(cmd, intArg1, intArg2), clearLow);
632 CmdQueueItem* GdbDriver::queueCmd(DbgCommand cmd, QueueMode mode)
634 return queueCmdString(cmd, cmds[cmd].fmt, mode);
637 CmdQueueItem* GdbDriver::queueCmd(DbgCommand cmd, QString strArg,
638 QueueMode mode)
640 return queueCmdString(cmd, makeCmdString(cmd, strArg), mode);
643 CmdQueueItem* GdbDriver::queueCmd(DbgCommand cmd, int intArg,
644 QueueMode mode)
646 return queueCmdString(cmd, makeCmdString(cmd, intArg), mode);
649 CmdQueueItem* GdbDriver::queueCmd(DbgCommand cmd, QString strArg, int intArg,
650 QueueMode mode)
652 return queueCmdString(cmd, makeCmdString(cmd, strArg, intArg), mode);
655 CmdQueueItem* GdbDriver::queueCmd(DbgCommand cmd, QString strArg1, QString strArg2,
656 QueueMode mode)
658 return queueCmdString(cmd, makeCmdString(cmd, strArg1, strArg2), mode);
661 void GdbDriver::terminate()
663 if (m_state != DSidle)
665 ::kill(pid(), SIGINT);
666 m_state = DSinterrupted;
668 flushCommands();
669 closeWriteChannel();
672 void GdbDriver::detachAndTerminate()
674 ::kill(pid(), SIGINT);
675 flushCommands();
676 executeCmdString(DCinitialize, "detach\nquit\n", true);
679 void GdbDriver::interruptInferior()
681 ::kill(pid(), SIGINT);
682 // remove accidentally queued commands
683 flushHiPriQueue();
686 static bool isErrorExpr(const char* output)
688 return
689 strncmp(output, "Cannot access memory at", 23) == 0 ||
690 strncmp(output, "Attempt to dereference a generic pointer", 40) == 0 ||
691 strncmp(output, "Attempt to take contents of ", 28) == 0 ||
692 strncmp(output, "Attempt to use a type name as an expression", 43) == 0 ||
693 strncmp(output, "There is no member or method named", 34) == 0 ||
694 strncmp(output, "A parse error in expression", 27) == 0 ||
695 strncmp(output, "No symbol \"", 11) == 0 ||
696 strncmp(output, "Internal error: ", 16) == 0;
700 * Returns true if the output is an error message. If wantErrorValue is
701 * true, a new ExprValue object is created and filled with the error message.
702 * If there are warnings, they are skipped and output points past the warnings
703 * on return (even if there \e are errors).
705 static bool parseErrorMessage(const char*& output,
706 ExprValue*& variable, bool wantErrorValue)
708 while (isspace(*output))
709 output++;
711 // skip warnings
712 while (strncmp(output, "warning:", 8) == 0)
714 const char* end = strchr(output+8, '\n');
715 if (end == 0)
716 output += strlen(output);
717 else
718 output = end+1;
719 while (isspace(*output))
720 output++;
723 if (isErrorExpr(output))
725 if (wantErrorValue) {
726 // put the error message as value in the variable
727 variable = new ExprValue(QString(), VarTree::NKplain);
728 const char* endMsg = strchr(output, '\n');
729 if (endMsg == 0)
730 endMsg = output + strlen(output);
731 variable->m_value = QString::fromLatin1(output, endMsg-output);
732 } else {
733 variable = 0;
735 return true;
737 return false;
740 #if QT_VERSION >= 300
741 union Qt2QChar {
742 short s;
743 struct {
744 uchar row;
745 uchar cell;
746 } qch;
748 #endif
750 void GdbDriver::setPrintQStringDataCmd(const char* cmd)
752 // don't accept the command if it is empty
753 if (cmd == 0 || *cmd == '\0')
754 return;
755 assert(strlen(cmd) <= MAX_FMTLEN);
756 cmds[DCprintQStringStruct].fmt = cmd;
759 ExprValue* GdbDriver::parseQCharArray(const char* output, bool wantErrorValue, bool qt3like)
761 ExprValue* variable = 0;
764 * Parse off white space. gdb sometimes prints white space first if the
765 * printed array leaded to an error.
767 while (isspace(*output))
768 output++;
770 // special case: empty string (0 repetitions)
771 if (strncmp(output, "Invalid number 0 of repetitions", 31) == 0)
773 variable = new ExprValue(QString(), VarTree::NKplain);
774 variable->m_value = "\"\"";
775 return variable;
778 // check for error conditions
779 if (parseErrorMessage(output, variable, wantErrorValue))
780 return variable;
782 // parse the array
784 // find '='
785 const char* p = output;
786 p = strchr(p, '=');
787 if (p == 0) {
788 goto error;
790 // skip white space
791 do {
792 p++;
793 } while (isspace(*p));
795 if (*p == '{')
797 // this is the real data
798 p++; /* skip '{' */
800 // parse the array
801 QString result;
802 QString repeatCount;
803 enum { wasNothing, wasChar, wasRepeat } lastThing = wasNothing;
805 * A matrix for separators between the individual "things"
806 * that are added to the string. The first index is a bool,
807 * the second index is from the enum above.
809 static const char* separator[2][3] = {
810 { "\"", 0, ", \"" }, /* normal char is added */
811 { "'", "\", '", ", '" } /* repeated char is added */
814 while (isdigit(*p)) {
815 // parse a number
816 char* end;
817 unsigned short value = (unsigned short) strtoul(p, &end, 0);
818 if (end == p)
819 goto error; /* huh? no valid digits */
820 // skip separator and search for a repeat count
821 p = end;
822 while (isspace(*p) || *p == ',')
823 p++;
824 bool repeats = strncmp(p, "<repeats ", 9) == 0;
825 if (repeats) {
826 const char* start = p;
827 p = strchr(p+9, '>'); /* search end and advance */
828 if (p == 0)
829 goto error;
830 p++; /* skip '>' */
831 repeatCount = QString::fromLatin1(start, p-start);
832 while (isspace(*p) || *p == ',')
833 p++;
835 // p is now at the next char (or the end)
837 // interpret the value as a QChar
838 // TODO: make cross-architecture compatible
839 QChar ch;
840 if (qt3like) {
841 ch = QChar(value);
842 } else {
843 #if QT_VERSION < 300
844 (unsigned short&)ch = value;
845 #else
846 Qt2QChar c;
847 c.s = value;
848 ch.setRow(c.qch.row);
849 ch.setCell(c.qch.cell);
850 #endif
853 // escape a few frequently used characters
854 char escapeCode = '\0';
855 switch (ch.toLatin1()) {
856 case '\n': escapeCode = 'n'; break;
857 case '\r': escapeCode = 'r'; break;
858 case '\t': escapeCode = 't'; break;
859 case '\b': escapeCode = 'b'; break;
860 case '\"': escapeCode = '\"'; break;
861 case '\\': escapeCode = '\\'; break;
862 case '\0': if (value == 0) { escapeCode = '0'; } break;
865 // add separator
866 result += separator[repeats][lastThing];
867 // add char
868 if (escapeCode != '\0') {
869 result += '\\';
870 ch = escapeCode;
872 result += ch;
874 // fixup repeat count and lastThing
875 if (repeats) {
876 result += "' ";
877 result += repeatCount;
878 lastThing = wasRepeat;
879 } else {
880 lastThing = wasChar;
883 if (*p != '}')
884 goto error;
886 // closing quote
887 if (lastThing == wasChar)
888 result += "\"";
890 // assign the value
891 variable = new ExprValue(QString(), VarTree::NKplain);
892 variable->m_value = result;
894 else if (strncmp(p, "true", 4) == 0)
896 variable = new ExprValue(QString(), VarTree::NKplain);
897 variable->m_value = "QString::null";
899 else if (strncmp(p, "false", 5) == 0)
901 variable = new ExprValue(QString(), VarTree::NKplain);
902 variable->m_value = "(null)";
904 else
905 goto error;
906 return variable;
908 error:
909 if (wantErrorValue) {
910 variable = new ExprValue(QString(), VarTree::NKplain);
911 variable->m_value = "internal parse error";
913 return variable;
916 static ExprValue* parseVar(const char*& s)
918 const char* p = s;
920 // skip whitespace
921 while (isspace(*p))
922 p++;
924 QString name;
925 VarTree::NameKind kind;
927 * Detect anonymouse struct values: The 'name =' part is missing:
928 * s = { a = 1, { b = 2 }}
929 * Note that this detection works only inside structs when the anonymous
930 * struct is not the first member:
931 * s = {{ a = 1 }, b = 2}
932 * This is misparsed (by parseNested()) because it is mistakenly
933 * interprets the second opening brace as the first element of an array
934 * of structs.
936 if (*p == '{')
938 name = i18n("<anonymous struct or union>");
939 kind = VarTree::NKanonymous;
941 else
943 if (!parseName(p, name, kind)) {
944 return 0;
947 // go for '='
948 while (isspace(*p))
949 p++;
950 if (*p != '=') {
951 TRACE("parse error: = not found after " + name);
952 return 0;
954 // skip the '=' and more whitespace
955 p++;
956 while (isspace(*p))
957 p++;
960 ExprValue* variable = new ExprValue(name, kind);
962 if (!parseValue(p, variable)) {
963 delete variable;
964 return 0;
966 s = p;
967 return variable;
970 static void skipNested(const char*& s, char opening, char closing)
972 const char* p = s;
974 // parse a nested type
975 int nest = 1;
976 p++;
978 * Search for next matching `closing' char, skipping nested pairs of
979 * `opening' and `closing'.
981 while (*p && nest > 0) {
982 if (*p == opening) {
983 nest++;
984 } else if (*p == closing) {
985 nest--;
987 p++;
989 if (nest != 0) {
990 TRACE(QString().sprintf("parse error: mismatching %c%c at %-20.20s", opening, closing, s));
992 s = p;
996 * This function skips text that is delimited by nested angle bracktes, '<>'.
997 * A complication arises because the delimited text can contain the names of
998 * operator<<, operator>>, operator<, and operator>, which have to be treated
999 * specially so that they do not count towards the nesting of '<>'.
1000 * This function assumes that the delimited text does not contain strings.
1002 static void skipNestedAngles(const char*& s)
1004 const char* p = s;
1006 int nest = 1;
1007 p++; // skip the initial '<'
1008 while (*p && nest > 0)
1010 // Below we can check for p-s >= 9 instead of 8 because
1011 // *s is '<' and cannot be part of "operator".
1012 if (*p == '<')
1014 if (p-s >= 9 && strncmp(p-8, "operator", 8) == 0) {
1015 if (p[1] == '<')
1016 p++;
1017 } else {
1018 nest++;
1021 else if (*p == '>')
1023 if (p-s >= 9 && strncmp(p-8, "operator", 8) == 0) {
1024 if (p[1] == '>')
1025 p++;
1026 } else {
1027 nest--;
1030 p++;
1032 if (nest != 0) {
1033 TRACE(QString().sprintf("parse error: mismatching <> at %-20.20s", s));
1035 s = p;
1039 * Find the end of line that is not inside braces
1041 static void findEnd(const char*& s)
1043 const char* p = s;
1044 while (*p && *p!='\n') {
1045 while (*p && *p!='\n' && *p!='{')
1046 p++;
1047 if (*p=='{') {
1048 p++;
1049 skipNested(p, '{', '}'); p--;
1052 s = p;
1055 static bool isNumberish(const char ch)
1057 return (ch>='0' && ch<='9') || ch=='.' || ch=='x';
1060 void skipString(const char*& p)
1062 // wchar_t strings begin with L
1063 if (*p == 'L')
1064 ++p;
1066 moreStrings:
1067 // opening quote
1068 char quote = *p++;
1069 while (*p != quote) {
1070 if (*p == '\\') {
1071 // skip escaped character
1072 // no special treatment for octal values necessary
1073 p++;
1075 // simply return if no more characters
1076 if (*p == '\0')
1077 return;
1078 p++;
1080 // closing quote
1081 p++;
1083 * Strings can consist of several parts, some of which contain repeated
1084 * characters.
1086 if (quote == '\'') {
1087 // look ahaead for <repeats 123 times>
1088 const char* q = p+1;
1089 while (isspace(*q))
1090 q++;
1091 if (strncmp(q, "<repeats ", 9) == 0) {
1092 p = q+9;
1093 while (*p != '\0' && *p != '>')
1094 p++;
1095 if (*p != '\0') {
1096 p++; /* skip the '>' */
1100 // Is the string continued? If so, there is no L in wchar_t strings
1101 if (*p == ',')
1103 // look ahead for another quote
1104 const char* q = p+1;
1105 while (isspace(*q))
1106 q++;
1107 if (*q == '"' || *q == '\'') {
1108 // yes!
1109 p = q;
1110 goto moreStrings;
1113 // some strings can end in <incomplete sequence ...>
1114 if (strncmp(q, "<incomplete sequence", 20) == 0)
1116 p = q+20;
1117 while (*p != '\0' && *p != '>')
1118 p++;
1119 if (*p != '\0') {
1120 p++; /* skip the '>' */
1125 * There's a bug in gdb where it prints the beginning of the string
1126 * continuation and the comma-blank in the wrong order if the new string
1127 * begins with an incomplete multi-byte character. For now, let's check
1128 * for this in a very narrow condition, particularly, where the next
1129 * character is given in octal notation. Example:
1130 * 'a' <repeats 20 times>"\240, b"
1132 if (*p == '"' && p[1] == '\\' && isdigit(p[2])) {
1133 int i = 3;
1134 while (isdigit(p[i]))
1135 ++i;
1136 if (p[i] == ',' && p[i+1] == ' ') {
1137 // just treat everything beginning at the dquote as string
1138 goto moreStrings;
1141 /* very long strings are followed by `...' */
1142 if (*p == '.' && p[1] == '.' && p[2] == '.') {
1143 p += 3;
1147 static void skipNestedWithString(const char*& s, char opening, char closing)
1149 const char* p = s;
1151 // parse a nested expression
1152 int nest = 1;
1153 p++;
1155 * Search for next matching `closing' char, skipping nested pairs of
1156 * `opening' and `closing' as well as strings.
1158 while (*p && nest > 0) {
1159 if (*p == opening) {
1160 nest++;
1161 } else if (*p == closing) {
1162 nest--;
1163 } else if (*p == '\'' || *p == '\"') {
1164 skipString(p);
1165 continue;
1167 p++;
1169 if (nest > 0) {
1170 TRACE(QString().sprintf("parse error: mismatching %c%c at %-20.20s", opening, closing, s));
1172 s = p;
1175 inline void skipName(const char*& p)
1177 // allow : (for enumeration values) and $ and . (for _vtbl.)
1178 while (isalnum(*p) || *p == '_' || *p == ':' || *p == '$' || *p == '.')
1179 p++;
1182 static bool parseName(const char*& s, QString& name, VarTree::NameKind& kind)
1184 kind = VarTree::NKplain;
1186 const char* p = s;
1187 // examples of names:
1188 // name
1189 // <Object>
1190 // <string<a,b<c>,7> >
1192 if (*p == '<') {
1193 skipNestedAngles(p);
1194 name = QString::fromLatin1(s, p - s);
1195 kind = VarTree::NKtype;
1197 else
1199 // name, which might be "static"; allow dot for "_vtbl."
1200 skipName(p);
1201 if (p == s) {
1202 TRACE(QString().sprintf("parse error: not a name %-20.20s", s));
1203 return false;
1205 int len = p - s;
1206 if (len == 6 && strncmp(s, "static", 6) == 0) {
1207 kind = VarTree::NKstatic;
1209 // its a static variable, name comes now
1210 while (isspace(*p))
1211 p++;
1212 s = p;
1213 skipName(p);
1214 if (p == s) {
1215 TRACE(QString().sprintf("parse error: not a name after static %-20.20s", s));
1216 return false;
1218 len = p - s;
1220 name = QString::fromLatin1(s, len);
1222 // return the new position
1223 s = p;
1224 return true;
1227 static bool parseValue(const char*& s, ExprValue* variable)
1229 variable->m_value = "";
1231 repeat:
1232 if (*s == '{') {
1233 // Sometimes we find the following output:
1234 // {<text variable, no debug info>} 0x40012000 <access>
1235 // {<data variable, no debug info>}
1236 // {<variable (not text or data), no debug info>}
1237 if (strncmp(s, "{<text variable, ", 17) == 0 ||
1238 strncmp(s, "{<data variable, ", 17) == 0 ||
1239 strncmp(s, "{<variable (not text or data), ", 31) == 0)
1241 const char* start = s;
1242 skipNested(s, '{', '}');
1243 variable->m_value = QString::fromLatin1(start, s-start);
1244 variable->m_value += ' '; // add only a single space
1245 while (isspace(*s))
1246 s++;
1247 goto repeat;
1249 else
1251 s++;
1252 if (!parseNested(s, variable)) {
1253 return false;
1255 // must be the closing brace
1256 if (*s != '}') {
1257 TRACE("parse error: missing } of " + variable->m_name);
1258 return false;
1260 s++;
1261 // final white space
1262 while (isspace(*s))
1263 s++;
1266 // Sometimes we find a warning; it ends at the next LF
1267 else if (strncmp(s, "warning: ", 9) == 0) {
1268 const char* end = strchr(s, '\n');
1269 s = end ? end : s+strlen(s);
1270 // skip space at start of next line
1271 while (isspace(*s))
1272 s++;
1273 goto repeat;
1274 } else {
1275 // examples of leaf values (cannot be the empty string):
1276 // 123
1277 // -123
1278 // 23.575e+37
1279 // 0x32a45
1280 // @0x012ab4
1281 // (DwContentType&) @0x8123456: {...}
1282 // 0x32a45 "text"
1283 // 10 '\n'
1284 // <optimized out>
1285 // 0x823abc <Array<int> virtual table>
1286 // 0x40240f <globarstr> "test"
1287 // (void (*)()) 0x8048480 <f(E *, char)>
1288 // (E *) 0xbffff450
1289 // red
1290 // &parseP (HTMLClueV *, char *)
1291 // Variable "x" is not available.
1292 // The value of variable 'x' is distributed...
1293 // -nan(0xfffff081defa0)
1295 const char*p = s;
1297 // check for type
1298 QString type;
1299 if (*p == '(') {
1300 skipNested(p, '(', ')');
1302 while (isspace(*p))
1303 p++;
1304 variable->m_value = QString::fromLatin1(s, p - s);
1307 bool reference = false;
1308 if (*p == '@') {
1309 // skip reference marker
1310 p++;
1311 reference = true;
1313 const char* start = p;
1314 if (*p == '-')
1315 p++;
1317 // some values consist of more than one token
1318 bool checkMultiPart = false;
1320 if (p[0] == '0' && p[1] == 'x') {
1321 // parse hex number
1322 p += 2;
1323 while (isxdigit(*p))
1324 p++;
1327 * Assume this is a pointer, but only if it's not a reference, since
1328 * references can't be expanded.
1330 if (!reference) {
1331 variable->m_varKind = VarTree::VKpointer;
1332 } else {
1334 * References are followed by a colon, in which case we'll
1335 * find the value following the reference address.
1337 if (*p == ':') {
1338 p++;
1339 } else {
1340 // Paranoia. (Can this happen, i.e. reference not followed by ':'?)
1341 reference = false;
1344 checkMultiPart = true;
1345 } else if (isdigit(*p)) {
1346 // parse decimal number, possibly a float
1347 while (isdigit(*p))
1348 p++;
1349 if (*p == '.') { /* TODO: obey i18n? */
1350 // In long arrays an integer may be followed by '...'.
1351 // We test for this situation and don't gobble the '...'.
1352 if (p[1] != '.' || p[0] != '.') {
1353 // fractional part
1354 p++;
1355 while (isdigit(*p))
1356 p++;
1359 if (*p == 'e' || *p == 'E') {
1360 p++;
1361 // exponent
1362 if (*p == '-' || *p == '+')
1363 p++;
1364 while (isdigit(*p))
1365 p++;
1368 // for char variables there is the char, eg. 10 '\n'
1369 checkMultiPart = true;
1370 } else if (*p == '<') {
1371 // e.g. <optimized out>
1372 skipNestedAngles(p);
1373 } else if (*p == '"' || *p == '\'') {
1374 // character may have multipart: '\000' <repeats 11 times>
1375 checkMultiPart = *p == '\'';
1376 // found a string
1377 skipString(p);
1378 } else if (*p == 'L' && (p[1] == '"' || p[1] == '\'')) {
1379 // ditto for wchar_t strings
1380 checkMultiPart = p[1] == '\'';
1381 skipString(p);
1382 } else if (*p == '&') {
1383 // function pointer
1384 p++;
1385 skipName(p);
1386 while (isspace(*p)) {
1387 p++;
1389 if (*p == '(') {
1390 skipNested(p, '(', ')');
1392 } else if (strncmp(p, "Variable \"", 10) == 0) {
1393 // Variable "x" is not available.
1394 p += 10; // skip to "
1395 skipName(p);
1396 if (strncmp(p, "\" is not available.", 19) == 0) {
1397 p += 19;
1399 } else if (strncmp(p, "The value of variable '", 23) == 0) {
1400 p += 23;
1401 skipName(p);
1402 const char* e = strchr(p, '.');
1403 if (e == 0) {
1404 p += strlen(p);
1405 } else {
1406 p = e+1;
1408 } else {
1409 moreEnum:
1410 // must be an enumeration value
1411 skipName(p);
1412 // nan (floating point Not a Number) is followed by a number in ()
1413 // enum values can look like A::(anonymous namespace)::blue
1414 if (*p == '(') {
1415 bool isAnonNS = strncmp(p+1, "anonymous namespace)", 20) == 0;
1416 skipNested(p, '(', ')');
1417 if (isAnonNS)
1418 goto moreEnum;
1421 variable->m_value += QString::fromLatin1(start, p - start);
1423 // remove line breaks from the value; this is ok since
1424 // string values never contain a literal line break
1425 variable->m_value.replace('\n', ' ');
1427 while (checkMultiPart) {
1428 // white space
1429 while (isspace(*p))
1430 p++;
1431 // may be followed by a string or <...>
1432 // if this was a pointer with a string,
1433 // reset that pointer flag since we have now a value
1434 start = p;
1435 checkMultiPart = false;
1437 if (*p == '"' || *p == '\'') {
1438 skipString(p);
1439 variable->m_varKind = VarTree::VKsimple;
1440 } else if (*p == 'L' && (p[1] == '"' || p[1] == '\'')) {
1441 skipString(p); // wchar_t string
1442 variable->m_varKind = VarTree::VKsimple;
1443 } else if (*p == '<') {
1444 // if this value is part of an array, it might be followed
1445 // by <repeats 15 times>, which we don't skip here
1446 if (strncmp(p, "<repeats ", 9) != 0) {
1447 skipNestedAngles(p);
1448 checkMultiPart = true;
1451 if (p != start) {
1452 // there is always a blank before the string,
1453 // which we will include in the final string value
1454 variable->m_value += QString::fromLatin1(start-1, (p - start)+1);
1458 if (variable->m_value.length() == 0) {
1459 TRACE("parse error: no value for " + variable->m_name);
1460 return false;
1463 // final white space
1464 while (isspace(*p))
1465 p++;
1466 s = p;
1469 * If this was a reference, the value follows. It might even be a
1470 * composite variable!
1472 if (reference) {
1473 goto repeat;
1477 return true;
1480 static bool parseNested(const char*& s, ExprValue* variable)
1482 // could be a structure or an array
1483 while (isspace(*s))
1484 s++;
1486 const char* p = s;
1487 bool isStruct = false;
1489 * If there is a name followed by an = or an < -- which starts a type
1490 * name -- or "static", it is a structure
1492 if (*p == '<' || *p == '}') {
1493 isStruct = true;
1494 } else if (strncmp(p, "static ", 7) == 0) {
1495 isStruct = true;
1496 } else if (isalpha(*p) || *p == '_' || *p == '$') {
1497 // look ahead for a comma after the name
1498 skipName(p);
1499 while (isspace(*p))
1500 p++;
1501 if (*p == '=') {
1502 isStruct = true;
1504 p = s; /* rescan the name */
1506 if (isStruct) {
1507 if (!parseVarSeq(p, variable)) {
1508 return false;
1510 variable->m_varKind = VarTree::VKstruct;
1511 } else {
1512 if (!parseValueSeq(p, variable)) {
1513 return false;
1515 variable->m_varKind = VarTree::VKarray;
1517 s = p;
1518 return true;
1521 static bool parseVarSeq(const char*& s, ExprValue* variable)
1523 // parse a comma-separated sequence of variables
1524 ExprValue* var = variable; /* var != 0 to indicate success if empty seq */
1525 for (;;) {
1526 if (*s == '}')
1527 break;
1528 if (strncmp(s, "<No data fields>}", 17) == 0)
1530 // no member variables, so break out immediately
1531 s += 16; /* go to the closing brace */
1532 break;
1534 var = parseVar(s);
1535 if (var == 0)
1536 break; /* syntax error */
1537 variable->appendChild(var);
1538 if (*s != ',')
1539 break;
1540 // skip the comma and whitespace
1541 s++;
1542 while (isspace(*s))
1543 s++;
1545 return var != 0;
1548 static bool parseValueSeq(const char*& s, ExprValue* variable)
1550 // parse a comma-separated sequence of variables
1551 int index = 0;
1552 bool good;
1553 for (;;) {
1554 QString name;
1555 name.sprintf("[%d]", index);
1556 ExprValue* var = new ExprValue(name, VarTree::NKplain);
1557 good = parseValue(s, var);
1558 if (!good) {
1559 delete var;
1560 return false;
1562 // a value may be followed by "<repeats 45 times>"
1563 if (strncmp(s, "<repeats ", 9) == 0) {
1564 s += 9;
1565 char* end;
1566 int l = strtol(s, &end, 10);
1567 if (end == s || strncmp(end, " times>", 7) != 0) {
1568 // should not happen
1569 delete var;
1570 return false;
1572 TRACE(QString().sprintf("found <repeats %d times> in array", l));
1573 // replace name and advance index
1574 name.sprintf("[%d .. %d]", index, index+l-1);
1575 var->m_name = name;
1576 index += l;
1577 // skip " times>" and space
1578 s = end+7;
1579 // possible final space
1580 while (isspace(*s))
1581 s++;
1582 } else {
1583 index++;
1585 variable->appendChild(var);
1586 // long arrays may be terminated by '...'
1587 if (strncmp(s, "...", 3) == 0) {
1588 s += 3;
1589 ExprValue* var = new ExprValue("...", VarTree::NKplain);
1590 var->m_value = i18n("<additional entries of the array suppressed>");
1591 variable->appendChild(var);
1592 break;
1594 if (*s != ',') {
1595 break;
1597 // skip the comma and whitespace
1598 s++;
1599 while (isspace(*s))
1600 s++;
1601 // sometimes there is a closing brace after a comma
1602 // if (*s == '}')
1603 // break;
1605 return true;
1609 * Parses a stack frame.
1611 static void parseFrameInfo(const char*& s, QString& func,
1612 QString& file, int& lineNo, DbgAddr& address)
1614 const char* p = s;
1616 // next may be a hexadecimal address
1617 if (*p == '0') {
1618 const char* start = p;
1619 p++;
1620 if (*p == 'x')
1621 p++;
1622 while (isxdigit(*p))
1623 p++;
1624 address = QString::fromLatin1(start, p-start);
1625 if (strncmp(p, " in ", 4) == 0)
1626 p += 4;
1627 } else {
1628 address = DbgAddr();
1630 const char* start = p;
1631 // check for special signal handler frame
1632 if (strncmp(p, "<signal handler called>", 23) == 0) {
1633 func = QString::fromLatin1(start, 23);
1634 file = QString();
1635 lineNo = -1;
1636 s = p+23;
1637 if (*s == '\n')
1638 s++;
1639 return;
1643 * Skip the function name. It is terminated by a left parenthesis
1644 * which does not delimit "(anonymous namespace)" and which is
1645 * outside the angle brackets <> of template parameter lists
1646 * and is preceded by a space.
1648 while (*p != '\0')
1650 if (*p == '<') {
1651 // check for operator<< and operator<
1652 if (p-start >= 8 && strncmp(p-8, "operator", 8) == 0)
1654 p++;
1655 if (*p == '<')
1656 p++;
1658 else
1660 // skip template parameter list
1661 skipNestedAngles(p);
1663 } else if (*p == '(') {
1664 // this skips "(anonymous namespace)" as well as the formal
1665 // parameter list of the containing function if this is a member
1666 // of a nested class
1667 skipNestedWithString(p, '(', ')');
1668 } else if (*p == ' ') {
1669 ++p;
1670 if (*p == '(')
1671 break; // parameter list found
1672 } else {
1673 p++;
1677 if (*p == '\0') {
1678 func = start;
1679 file = QString();
1680 lineNo = -1;
1681 s = p;
1682 return;
1685 * Skip parameters. But notice that for complicated conversion
1686 * functions (eg. "operator int(**)()()", ie. convert to pointer to
1687 * pointer to function) as well as operator()(...) we have to skip
1688 * additional pairs of parentheses. Furthermore, recent gdbs write the
1689 * demangled name followed by the arguments in a pair of parentheses,
1690 * where the demangled name can end in "const".
1692 do {
1693 skipNestedWithString(p, '(', ')');
1694 while (isspace(*p))
1695 p++;
1696 // skip "const"
1697 if (strncmp(p, "const", 5) == 0) {
1698 p += 5;
1699 while (isspace(*p))
1700 p++;
1702 } while (*p == '(');
1704 // check for file position
1705 if (strncmp(p, "at ", 3) == 0) {
1706 p += 3;
1707 const char* fileStart = p;
1708 // go for the end of the line
1709 while (*p != '\0' && *p != '\n')
1710 p++;
1711 // search back for colon
1712 const char* colon = p;
1713 do {
1714 --colon;
1715 } while (*colon != ':');
1716 file = QString::fromLatin1(fileStart, colon-fileStart);
1717 lineNo = atoi(colon+1)-1;
1718 // skip new-line
1719 if (*p != '\0')
1720 p++;
1721 } else {
1722 // check for "from shared lib"
1723 if (strncmp(p, "from ", 5) == 0) {
1724 p += 5;
1725 // go for the end of the line
1726 while (*p != '\0' && *p != '\n')
1727 p++;
1728 // skip new-line
1729 if (*p != '\0')
1730 p++;
1732 file = "";
1733 lineNo = -1;
1735 // construct the function name (including file info)
1736 if (*p == '\0') {
1737 func = start;
1738 } else {
1739 func = QString::fromLatin1(start, p-start-1); /* don't include \n */
1741 s = p;
1744 * Replace \n (and whitespace around it) in func by a blank. We cannot
1745 * use QString::simplified() for this because this would also
1746 * simplify space that belongs to a string arguments that gdb sometimes
1747 * prints in the argument lists of the function.
1749 ASSERT(!isspace(func[0].toLatin1())); // there must be non-white before first \n
1750 int nl = 0;
1751 while ((nl = func.indexOf('\n', nl)) >= 0) {
1752 // search back to the beginning of the whitespace
1753 int startWhite = nl;
1754 do {
1755 --startWhite;
1756 } while (isspace(func[startWhite].toLatin1()));
1757 startWhite++;
1758 // search forward to the end of the whitespace
1759 do {
1760 nl++;
1761 } while (isspace(func[nl].toLatin1()));
1762 // replace
1763 func.replace(startWhite, nl-startWhite, " ");
1764 /* continue searching for more \n's at this place: */
1765 nl = startWhite+1;
1771 * Parses a stack frame including its frame number
1773 static bool parseFrame(const char*& s, int& frameNo, QString& func,
1774 QString& file, int& lineNo, DbgAddr& address)
1776 // Example:
1777 // #1 0x8048881 in Dl::Dl (this=0xbffff418, r=3214) at testfile.cpp:72
1778 // Breakpoint 3, Cl::f(int) const (this=0xbffff3c0, x=17) at testfile.cpp:155
1780 // must start with a hash mark followed by number
1781 // or with "Breakpoint " followed by number and comma
1782 if (s[0] == '#') {
1783 if (!isdigit(s[1]))
1784 return false;
1785 s++; /* skip the hash mark */
1786 } else if (strncmp(s, "Breakpoint ", 11) == 0) {
1787 if (!isdigit(s[11]))
1788 return false;
1789 s += 11; /* skip "Breakpoint" */
1790 } else
1791 return false;
1793 // frame number
1794 frameNo = atoi(s);
1795 while (isdigit(*s))
1796 s++;
1797 // space and comma
1798 while (isspace(*s) || *s == ',')
1799 s++;
1800 parseFrameInfo(s, func, file, lineNo, address);
1801 return true;
1804 void GdbDriver::parseBackTrace(const char* output, std::list<StackFrame>& stack)
1806 QString func, file;
1807 int lineNo, frameNo;
1808 DbgAddr address;
1810 while (::parseFrame(output, frameNo, func, file, lineNo, address)) {
1811 stack.push_back(StackFrame());
1812 StackFrame* frm = &stack.back();
1813 frm->frameNo = frameNo;
1814 frm->fileName = file;
1815 frm->lineNo = lineNo;
1816 frm->address = address;
1817 frm->var = new ExprValue(func, VarTree::NKplain);
1821 bool GdbDriver::parseFrameChange(const char* output, int& frameNo,
1822 QString& file, int& lineNo, DbgAddr& address)
1824 QString func;
1825 return ::parseFrame(output, frameNo, func, file, lineNo, address);
1829 bool GdbDriver::parseBreakList(const char* output, std::list<Breakpoint>& brks)
1831 // skip first line, which is the headline
1832 const char* p = strchr(output, '\n');
1833 if (p == 0)
1834 return false;
1835 p++;
1836 if (*p == '\0')
1837 return false;
1839 // split up a line
1840 const char* end;
1841 char* dummy;
1842 while (*p != '\0') {
1843 Breakpoint bp;
1844 // get Num
1845 bp.id = strtol(p, &dummy, 10); /* don't care about overflows */
1846 p = dummy;
1847 // check for continued <MULTIPLE> breakpoint
1848 if (*p == '.' && isdigit(p[1]))
1850 // continuation: skip type and disposition
1852 else
1854 // get Type
1855 while (isspace(*p))
1856 p++;
1857 if (strncmp(p, "breakpoint", 10) == 0) {
1858 p += 10;
1859 } else if (strncmp(p, "hw watchpoint", 13) == 0) {
1860 bp.type = Breakpoint::watchpoint;
1861 p += 13;
1862 } else if (strncmp(p, "watchpoint", 10) == 0) {
1863 bp.type = Breakpoint::watchpoint;
1864 p += 10;
1866 while (isspace(*p))
1867 p++;
1868 if (*p == '\0')
1869 break;
1870 // get Disp
1871 bp.temporary = *p++ == 'd';
1873 while (*p != '\0' && !isspace(*p)) /* "keep" or "del" */
1874 p++;
1875 while (isspace(*p))
1876 p++;
1877 if (*p == '\0')
1878 break;
1879 // get Enb
1880 bp.enabled = *p++ == 'y';
1881 while (*p != '\0' && !isspace(*p)) /* "y" or "n" */
1882 p++;
1883 while (isspace(*p))
1884 p++;
1885 if (*p == '\0')
1886 break;
1887 // the address, if present
1888 if (bp.type == Breakpoint::breakpoint &&
1889 strncmp(p, "0x", 2) == 0)
1891 const char* start = p;
1892 while (*p != '\0' && !isspace(*p))
1893 p++;
1894 bp.address = QString::fromLatin1(start, p-start);
1895 while (isspace(*p) && *p != '\n')
1896 p++;
1897 if (*p == '\0')
1898 break;
1900 // remainder is location, hit and ignore count, condition
1901 end = strchr(p, '\n');
1902 if (end == 0) {
1903 bp.location = p;
1904 p += bp.location.length();
1905 } else {
1906 // location of a <MULTIPLE> filled in from subsequent breakpoints
1907 if (strncmp(p, "<MULTIPLE>", 10) != 0)
1908 bp.location = QString::fromLatin1(p, end-p).trimmed();
1909 p = end+1; /* skip over \n */
1912 // may be continued in next line
1913 while (isspace(*p)) { /* p points to beginning of line */
1914 // skip white space at beginning of line
1915 while (isspace(*p))
1916 p++;
1918 // seek end of line
1919 end = strchr(p, '\n');
1920 if (end == 0)
1921 end = p+strlen(p);
1923 if (strncmp(p, "breakpoint already hit", 22) == 0) {
1924 // extract the hit count
1925 p += 22;
1926 bp.hitCount = strtol(p, &dummy, 10);
1927 TRACE(QString("hit count %1").arg(bp.hitCount));
1928 } else if (strncmp(p, "stop only if ", 13) == 0) {
1929 // extract condition
1930 p += 13;
1931 bp.condition = QString::fromLatin1(p, end-p).trimmed();
1932 TRACE("condition: "+bp.condition);
1933 } else if (strncmp(p, "ignore next ", 12) == 0) {
1934 // extract ignore count
1935 p += 12;
1936 bp.ignoreCount = strtol(p, &dummy, 10);
1937 TRACE(QString("ignore count %1").arg(bp.ignoreCount));
1938 } else {
1939 // indeed a continuation
1940 bp.location += " " + QString::fromLatin1(p, end-p).trimmed();
1942 p = end;
1943 if (*p != '\0')
1944 p++; /* skip '\n' */
1947 if (brks.empty() || brks.back().id != bp.id) {
1948 brks.push_back(bp);
1949 } else {
1950 // this is a continuation; fill in location if not yet set
1951 // otherwise, drop this breakpoint
1952 Breakpoint& mbp = brks.back();
1953 if (mbp.location.isEmpty() && !bp.location.isEmpty()) {
1954 mbp.location = bp.location;
1955 mbp.address = bp.address;
1956 } else if (mbp.address.isEmpty() && !bp.address.isEmpty()) {
1957 mbp.address = bp.address;
1961 return true;
1964 std::list<ThreadInfo> GdbDriver::parseThreadList(const char* output)
1966 std::list<ThreadInfo> threads;
1967 if (strcmp(output, "\n") == 0 ||
1968 strncmp(output, "No stack.", 9) == 0 ||
1969 strncmp(output, "No threads.", 11) == 0) {
1970 // no threads
1971 return threads;
1974 bool newFormat = false;
1975 const char* p = output;
1976 while (*p != '\0') {
1977 ThreadInfo thr;
1978 // seach look for thread id, watching out for the focus indicator
1979 thr.hasFocus = false;
1980 while (isspace(*p)) /* may be \n from prev line: see "No stack" below */
1981 p++;
1983 // recent GDBs write a header line; skip it
1984 if (threads.empty() && strncmp(p, "Id Target", 11) == 0) {
1985 p = strchr(p, '\n');
1986 if (p == NULL)
1987 break;
1988 newFormat = true;
1989 continue; // next line please, '\n' is skipped above
1992 if (*p == '*') {
1993 thr.hasFocus = true;
1994 p++;
1995 // there follows only whitespace
1997 const char* end;
1998 char *temp_end = NULL; /* we need a non-const 'end' for strtol to use...*/
1999 thr.id = strtol(p, &temp_end, 10);
2000 end = temp_end;
2001 if (p == end) {
2002 // syntax error: no number found; bail out
2003 return threads;
2005 p = end;
2007 // skip space
2008 while (isspace(*p))
2009 p++;
2012 * Now follows the thread's SYSTAG.
2014 if (!newFormat) {
2015 // In the old format, it is terminated by two blanks.
2016 end = strstr(p, " ");
2017 if (end == 0) {
2018 // syntax error; bail out
2019 return threads;
2021 end += 2;
2022 } else {
2023 // In the new format lies crazyness: there is no definitive
2024 // end marker. At best we can guess when the SYSTAG ends.
2025 // A typical thread list on Linux looks like this:
2027 // Id Target Id Frame
2028 // 2 Thread 0x7ffff7854700 (LWP 10827) "thrserver" 0x00007ffff7928631 in clone () from /lib64/libc.so.6
2029 // * 1 Thread 0x7ffff7fcc700 (LWP 10808) "thrserver" main () at thrserver.c:84
2031 // Looking at GDB's code, the Target Id ends in tokens that
2032 // are bracketed by parentheses or quotes. Therefore,
2033 // we skip (at most) two tokens ('Thread' and the address),
2034 // and then all parts that are in parentheses or quotes.
2035 int n = 0;
2036 end = p;
2037 while (*end) {
2038 if (*end == '"') {
2039 skipString(end);
2040 n = 2;
2041 } else if (*end == '(') {
2042 skipNested(end, '(', ')');
2043 n = 2;
2044 } else if (n < 2) {
2045 while (*end && !isspace(*end))
2046 ++end;
2047 ++n;
2048 } else {
2049 break;
2051 while (isspace(*end))
2052 ++end;
2055 thr.threadName = QString::fromLatin1(p, end-p).trimmed();
2056 p = end;
2059 * Now follows a standard stack frame. Sometimes, however, gdb
2060 * catches a thread at an instant where it doesn't have a stack.
2062 if (strncmp(p, "[No stack.]", 11) != 0) {
2063 ::parseFrameInfo(p, thr.function, thr.fileName, thr.lineNo, thr.address);
2064 } else {
2065 thr.function = "[No stack]";
2066 thr.lineNo = -1;
2067 p += 11; /* \n is skipped above */
2070 threads.push_back(thr);
2072 return threads;
2075 static bool parseNewBreakpoint(const char* o, int& id,
2076 QString& file, int& lineNo, QString& address);
2077 static bool parseNewWatchpoint(const char* o, int& id,
2078 QString& expr);
2080 bool GdbDriver::parseBreakpoint(const char* output, int& id,
2081 QString& file, int& lineNo, QString& address)
2083 // skip lines of that begin with "(Cannot find"
2084 while (strncmp(output, "(Cannot find", 12) == 0 ||
2085 strncmp(output, "Note: breakpoint", 16) == 0)
2087 output = strchr(output, '\n');
2088 if (output == 0)
2089 return false;
2090 output++; /* skip newline */
2093 if (strncmp(output, "Breakpoint ", 11) == 0) {
2094 output += 11; /* skip "Breakpoint " */
2095 return ::parseNewBreakpoint(output, id, file, lineNo, address);
2096 } else if (strncmp(output, "Temporary breakpoint ", 21) == 0) {
2097 output += 21;
2098 return ::parseNewBreakpoint(output, id, file, lineNo, address);
2099 } else if (strncmp(output, "Hardware watchpoint ", 20) == 0) {
2100 output += 20;
2101 return ::parseNewWatchpoint(output, id, address);
2102 } else if (strncmp(output, "Watchpoint ", 11) == 0) {
2103 output += 11;
2104 return ::parseNewWatchpoint(output, id, address);
2106 return false;
2109 static bool parseNewBreakpoint(const char* o, int& id,
2110 QString& file, int& lineNo, QString& address)
2112 // breakpoint id
2113 char* p;
2114 id = strtoul(o, &p, 10);
2115 if (p == o)
2116 return false;
2118 // check for the address
2119 if (strncmp(p, " at 0x", 6) == 0) {
2120 char* start = p+4; /* skip " at ", but not 0x */
2121 p += 6;
2122 while (isxdigit(*p))
2123 ++p;
2124 address = QString::fromLatin1(start, p-start);
2128 * Mostly, GDB responds with this syntax:
2130 * Breakpoint 1 at 0x400b94: file multibrkpt.cpp, line 9. (2 locations)
2132 * but sometimes it uses this syntax:
2134 * Breakpoint 4 at 0x804f158: lotto739.cpp:95. (3 locations)
2136 char* fileEnd, *numStart = 0;
2137 char* fileStart = strstr(p, "file ");
2138 if (fileStart != 0)
2140 fileStart += 5;
2141 fileEnd = strstr(fileStart, ", line ");
2142 if (fileEnd != 0)
2143 numStart = fileEnd + 7;
2145 if (numStart == 0 && p[0] == ':' && p[1] == ' ')
2147 fileStart = p+2;
2148 while (isspace(*fileStart))
2149 ++fileStart;
2150 fileEnd = strchr(fileStart, ':');
2151 if (fileEnd != 0)
2152 numStart = fileEnd + 1;
2154 if (numStart == 0)
2155 return !address.isEmpty(); /* parse error only if there's no address */
2157 QString fileName = QString::fromLatin1(fileStart, fileEnd-fileStart);
2158 int line = strtoul(numStart, &p, 10);
2159 if (numStart == p)
2160 return false;
2162 file = fileName;
2163 lineNo = line-1; /* zero-based! */
2164 return true;
2167 static bool parseNewWatchpoint(const char* o, int& id,
2168 QString& expr)
2170 // watchpoint id
2171 char* p;
2172 id = strtoul(o, &p, 10);
2173 if (p == o)
2174 return false;
2176 if (strncmp(p, ": ", 2) != 0)
2177 return false;
2178 p += 2;
2180 // all the rest on the line is the expression
2181 expr = QString::fromLatin1(p, strlen(p)).trimmed();
2182 return true;
2185 void GdbDriver::parseLocals(const char* output, std::list<ExprValue*>& newVars)
2187 // check for possible error conditions
2188 if (strncmp(output, "No symbol table", 15) == 0)
2190 return;
2193 while (*output != '\0') {
2194 while (isspace(*output))
2195 output++;
2196 if (*output == '\0')
2197 break;
2198 // skip occurrences of "No locals" and "No args"
2199 if (strncmp(output, "No locals", 9) == 0 ||
2200 strncmp(output, "No arguments", 12) == 0)
2202 output = strchr(output, '\n');
2203 if (output == 0) {
2204 break;
2206 continue;
2209 ExprValue* variable = parseVar(output);
2210 if (variable == 0) {
2211 break;
2213 // do not add duplicates
2214 for (std::list<ExprValue*>::iterator o = newVars.begin(); o != newVars.end(); ++o) {
2215 if ((*o)->m_name == variable->m_name) {
2216 delete variable;
2217 goto skipDuplicate;
2220 newVars.push_back(variable);
2221 skipDuplicate:;
2225 ExprValue* GdbDriver::parsePrintExpr(const char* output, bool wantErrorValue)
2227 ExprValue* var = 0;
2228 // check for error conditions
2229 if (!parseErrorMessage(output, var, wantErrorValue))
2231 // parse the variable
2232 var = parseVar(output);
2234 return var;
2237 bool GdbDriver::parseChangeWD(const char* output, QString& message)
2239 bool isGood = false;
2240 message = QString(output).simplified();
2241 if (message.isEmpty()) {
2242 message = i18n("New working directory: ") + m_programWD;
2243 isGood = true;
2245 return isGood;
2248 bool GdbDriver::parseChangeExecutable(const char* output, QString& message)
2250 message = output;
2252 m_haveCoreFile = false;
2255 * Lines starting with the following do not indicate errors:
2256 * Using host libthread_db
2257 * (no debugging symbols found)
2258 * Reading symbols from
2260 while (strncmp(output, "Reading symbols from", 20) == 0 ||
2261 strncmp(output, "done.", 5) == 0 ||
2262 strncmp(output, "Missing separate debuginfo", 26) == 0 ||
2263 strncmp(output, "Try: ", 5) == 0 ||
2264 strncmp(output, "Using host libthread_db", 23) == 0 ||
2265 strncmp(output, "(no debugging symbols found)", 28) == 0)
2267 // this line is good, go to the next one
2268 const char* end = strchr(output, '\n');
2269 if (end == 0)
2270 output += strlen(output);
2271 else
2272 output = end+1;
2276 * If we've parsed all lines, there was no error.
2278 return output[0] == '\0';
2281 bool GdbDriver::parseCoreFile(const char* output)
2283 // if command succeeded, gdb emits a line starting with "#0 "
2284 m_haveCoreFile = strstr(output, "\n#0 ") != 0;
2285 return m_haveCoreFile;
2288 uint GdbDriver::parseProgramStopped(const char* output, QString& message)
2290 // optionally: "program changed, rereading symbols",
2291 // followed by:
2292 // "Program exited normally"
2293 // "Program terminated with wignal SIGSEGV"
2294 // "Program received signal SIGINT" or other signal
2295 // "Breakpoint..."
2296 // GDB since 7.3 prints
2297 // "[Inferior 1 (process 13400) exited normally]"
2298 // "[Inferior 1 (process 14698) exited with code 01]"
2300 // go through the output, line by line, checking what we have
2301 const char* start = output - 1;
2302 uint flags = SFprogramActive;
2303 message = QString();
2304 do {
2305 start++; /* skip '\n' */
2307 if (strncmp(start, "Program ", 8) == 0 ||
2308 strncmp(start, "ptrace: ", 8) == 0) {
2310 * When we receive a signal, the program remains active.
2312 * Special: If we "stopped" in a corefile, the string "Program
2313 * terminated with signal"... is displayed. (Normally, we see
2314 * "Program received signal"... when a signal happens.)
2316 if (strncmp(start, "Program exited", 14) == 0 ||
2317 (strncmp(start, "Program terminated", 18) == 0 && !m_haveCoreFile) ||
2318 strncmp(start, "ptrace: ", 8) == 0)
2320 flags &= ~SFprogramActive;
2323 // set message
2324 const char* endOfMessage = strchr(start, '\n');
2325 if (endOfMessage == 0)
2326 endOfMessage = start + strlen(start);
2327 message = QString::fromLatin1(start, endOfMessage-start);
2328 } else if (strncmp(start, "[Inferior ", 10) == 0) {
2329 const char* p = start + 10;
2330 // skip number and space
2331 while (*p && !isspace(*p))
2332 ++p;
2333 while (isspace(*p))
2334 ++p;
2335 if (*p == '(') {
2336 skipNested(p, '(', ')');
2337 if (strncmp(p, " exited ", 8) == 0) {
2338 flags &= ~SFprogramActive;
2340 // set message
2341 const char* end = strchr(p, '\n');
2342 if (end == 0)
2343 end = p + strlen(p);
2344 // strip [] from the message
2345 message = QString::fromLatin1(start+1, end-start-2);
2348 } else if (strncmp(start, "Breakpoint ", 11) == 0) {
2350 * We stopped at a (permanent) breakpoint (gdb doesn't tell us
2351 * that it stopped at a temporary breakpoint).
2353 flags |= SFrefreshBreak;
2354 } else if (strstr(start, "re-reading symbols.") != 0) {
2355 flags |= SFrefreshSource;
2358 // next line, please
2359 start = strchr(start, '\n');
2360 } while (start != 0);
2363 * Gdb only notices when new threads have appeared, but not when a
2364 * thread finishes. So we always have to assume that the list of
2365 * threads has changed.
2367 flags |= SFrefreshThreads;
2369 return flags;
2372 QStringList GdbDriver::parseSharedLibs(const char* output)
2374 QStringList shlibs;
2375 if (strncmp(output, "No shared libraries loaded", 26) == 0)
2376 return shlibs;
2378 // parse the table of shared libraries
2380 // strip off head line
2381 output = strchr(output, '\n');
2382 if (output == 0)
2383 return shlibs;
2384 output++; /* skip '\n' */
2385 QString shlibName;
2386 while (*output != '\0') {
2387 // format of a line is
2388 // 0x404c5000 0x40580d90 Yes /lib/libc.so.5
2389 // 3 blocks of non-space followed by space
2390 for (int i = 0; *output != '\0' && i < 3; i++) {
2391 while (*output != '\0' && !isspace(*output)) { /* non-space */
2392 output++;
2394 while (isspace(*output)) { /* space */
2395 output++;
2398 if (*output == '\0')
2399 return shlibs;
2400 const char* start = output;
2401 output = strchr(output, '\n');
2402 if (output == 0)
2403 output = start + strlen(start);
2404 shlibName = QString::fromLatin1(start, output-start);
2405 if (*output != '\0')
2406 output++;
2407 shlibs.append(shlibName);
2408 TRACE("found shared lib " + shlibName);
2410 return shlibs;
2413 bool GdbDriver::parseFindType(const char* output, QString& type)
2415 if (strncmp(output, "type = ", 7) != 0)
2416 return false;
2419 * Everything else is the type. We strip off any leading "const" and any
2420 * trailing "&" on the grounds that neither affects the decoding of the
2421 * object. We also strip off all white-space from the type.
2423 output += 7;
2424 if (strncmp(output, "const ", 6) == 0)
2425 output += 6;
2426 type = output;
2427 type.replace(QRegExp("\\s+"), "");
2428 if (type.endsWith("&"))
2429 type.truncate(type.length() - 1);
2430 return true;
2433 std::list<RegisterInfo> GdbDriver::parseRegisters(const char* output)
2435 std::list<RegisterInfo> regs;
2436 if (strncmp(output, "The program has no registers now", 32) == 0) {
2437 return regs;
2440 // parse register values
2441 while (*output != '\0')
2443 RegisterInfo reg;
2444 // skip space at the start of the line
2445 while (isspace(*output))
2446 output++;
2448 // register name
2449 const char* start = output;
2450 while (*output != '\0' && !isspace(*output))
2451 output++;
2452 if (*output == '\0')
2453 break;
2454 reg.regName = QString::fromLatin1(start, output-start);
2456 // skip space
2457 while (isspace(*output))
2458 output++;
2460 QString value;
2463 * If we find a brace now, this is a vector register. We look for
2464 * the closing brace and treat the result as cooked value.
2466 if (*output == '{')
2468 start = output;
2469 skipNested(output, '{', '}');
2470 value = QString::fromLatin1(start, output-start).simplified();
2471 // skip space, but not the end of line
2472 while (isspace(*output) && *output != '\n')
2473 output++;
2474 // get rid of the braces at the begining and the end
2475 value.remove(0, 1);
2476 if (value[value.length()-1] == '}') {
2477 value = value.left(value.length()-1);
2479 // gdb 5.3 doesn't print a separate set of raw values
2480 if (*output == '{') {
2481 // another set of vector follows
2482 // what we have so far is the raw value
2483 reg.rawValue = value;
2485 start = output;
2486 skipNested(output, '{', '}');
2487 value = QString::fromLatin1(start, output-start).simplified();
2488 } else {
2489 // for gdb 5.3
2490 // find first type that does not have an array, this is the RAW value
2491 const char* end=start;
2492 findEnd(end);
2493 const char* cur=start;
2494 while (cur<end) {
2495 while (*cur != '=' && cur<end)
2496 cur++;
2497 cur++;
2498 while (isspace(*cur) && cur<end)
2499 cur++;
2500 if (isNumberish(*cur)) {
2501 end=cur;
2502 while (*end && (*end!='}') && (*end!=',') && (*end!='\n'))
2503 end++;
2504 QString rawValue = QString::fromLatin1(cur, end-cur).simplified();
2505 reg.rawValue = rawValue;
2507 if (rawValue.left(2)=="0x") {
2508 // ok we have a raw value, now get it's type
2509 end=cur-1;
2510 while (isspace(*end) || *end=='=') end--;
2511 end++;
2512 cur=end-1;
2513 while (*cur!='{' && *cur!=' ')
2514 cur--;
2515 cur++;
2516 reg.type = QString::fromLatin1(cur, end-cur);
2519 // end while loop
2520 cur=end;
2523 // skip to the end of line
2524 while (*output != '\0' && *output != '\n')
2525 output++;
2526 // get rid of the braces at the begining and the end
2527 value.remove(0, 1);
2528 if (value[value.length()-1] == '}') {
2529 value.truncate(value.length()-1);
2532 reg.cookedValue = value;
2534 else
2536 continuation:
2537 // the rest of the line is the register value
2538 start = output;
2539 output = strchr(output,'\n');
2540 if (output == 0)
2541 output = start + strlen(start);
2542 value += QString::fromLatin1(start, output-start).simplified();
2545 * Look ahead: if the subsequent line is indented, it continues
2546 * the current register value.
2548 if (output != 0 && isspace(output[1]))
2550 ++output;
2551 value += ' ';
2552 goto continuation;
2556 * We split the raw from the cooked values.
2557 * Some modern gdbs explicitly say: "0.1234 (raw 0x3e4567...)".
2558 * Here, the cooked value comes first, and the raw value is in
2559 * the second part.
2561 int pos = value.indexOf(" (raw ");
2562 if (pos >= 0)
2564 reg.cookedValue = value.left(pos);
2565 reg.rawValue = value.mid(pos+6);
2566 if (reg.rawValue.right(1) == ")") // remove closing bracket
2567 reg.rawValue.truncate(reg.rawValue.length()-1);
2569 else
2572 * In other cases we split off the first token (separated by
2573 * whitespace). It is the raw value. The remainder of the line
2574 * is the cooked value.
2576 int pos = value.indexOf(' ');
2577 if (pos < 0) {
2578 reg.rawValue = value;
2579 reg.cookedValue = QString();
2580 } else {
2581 reg.rawValue = value.left(pos);
2582 reg.cookedValue = value.mid(pos+1);
2586 if (*output != '\0')
2587 output++; /* skip '\n' */
2589 regs.push_back(reg);
2591 return regs;
2594 bool GdbDriver::parseInfoLine(const char* output, QString& addrFrom, QString& addrTo)
2596 // "is at address" or "starts at address"
2597 const char* start = strstr(output, "s at address ");
2598 if (start == 0)
2599 return false;
2601 start += 13;
2602 const char* p = start;
2603 while (*p != '\0' && !isspace(*p))
2604 p++;
2605 addrFrom = QString::fromLatin1(start, p-start);
2607 start = strstr(p, "and ends at ");
2608 if (start == 0) {
2609 addrTo = addrFrom;
2610 return true;
2613 start += 12;
2614 p = start;
2615 while (*p != '\0' && !isspace(*p))
2616 p++;
2617 addrTo = QString::fromLatin1(start, p-start);
2619 return true;
2622 std::list<DisassembledCode> GdbDriver::parseDisassemble(const char* output)
2624 std::list<DisassembledCode> code;
2626 if (strncmp(output, "Dump of assembler", 17) != 0) {
2627 // error message?
2628 DisassembledCode c;
2629 c.code = output;
2630 code.push_back(c);
2631 return code;
2634 // remove first line
2635 const char* p = strchr(output, '\n');
2636 if (p == 0)
2637 return code; /* not a regular output */
2639 p++;
2641 // remove last line
2642 const char* end = strstr(output, "End of assembler");
2643 if (end == 0)
2644 end = p + strlen(p);
2646 // remove function offsets from the lines
2647 while (p != end)
2649 DisassembledCode c;
2650 // skip initial space or PC pointer ("=>", since gdb 7.1)
2651 while (p != end) {
2652 if (isspace(*p))
2653 ++p;
2654 else if (p[0] == '=' && p[1] == '>')
2655 p += 2;
2656 else
2657 break;
2659 const char* start = p;
2660 // address
2661 while (p != end && !isspace(*p))
2662 p++;
2663 c.address = QString::fromLatin1(start, p-start);
2665 // function name (enclosed in '<>', followed by ':')
2666 while (p != end && *p != '<')
2667 p++;
2668 if (*p == '<')
2669 skipNestedAngles(p);
2670 if (*p == ':')
2671 p++;
2673 // space until code
2674 while (p != end && isspace(*p))
2675 p++;
2677 // code until end of line
2678 start = p;
2679 while (p != end && *p != '\n')
2680 p++;
2681 if (p != end) /* include '\n' */
2682 p++;
2684 c.code = QString::fromLatin1(start, p-start);
2685 code.push_back(c);
2687 return code;
2690 QString GdbDriver::parseMemoryDump(const char* output, std::list<MemoryDump>& memdump)
2692 if (isErrorExpr(output)) {
2693 // error; strip space
2694 QString msg = output;
2695 return msg.trimmed();
2698 const char* p = output; /* save typing */
2700 // the address
2701 while (*p != 0) {
2702 MemoryDump md;
2704 const char* start = p;
2705 while (*p != '\0' && *p != ':' && !isspace(*p))
2706 p++;
2707 md.address = QString::fromLatin1(start, p-start);
2708 if (*p != ':') {
2709 // parse function offset
2710 while (isspace(*p))
2711 p++;
2712 start = p;
2713 while (*p != '\0' && !(*p == ':' && isspace(p[1])))
2714 p++;
2715 md.address.fnoffs = QString::fromLatin1(start, p-start);
2717 if (*p == ':')
2718 p++;
2719 // skip space; this may skip a new-line char!
2720 while (isspace(*p))
2721 p++;
2722 // everything to the end of the line is the memory dump
2723 const char* end = strchr(p, '\n');
2724 if (end != 0) {
2725 md.dump = QString::fromLatin1(p, end-p);
2726 p = end+1;
2727 } else {
2728 md.dump = QString::fromLatin1(p, strlen(p));
2729 p += strlen(p);
2731 memdump.push_back(md);
2734 return QString();
2737 QString GdbDriver::editableValue(VarTree* value)
2739 QByteArray ba = value->value().toLatin1();
2740 const char* s = ba.constData();
2742 // if the variable is a pointer value that contains a cast,
2743 // remove the cast
2744 if (*s == '(') {
2745 skipNested(s, '(', ')');
2746 // skip space
2747 while (isspace(*s))
2748 ++s;
2751 repeat:
2752 const char* start = s;
2754 if (strncmp(s, "0x", 2) == 0)
2756 s += 2;
2757 while (isxdigit(*s))
2758 ++s;
2761 * What we saw so far might have been a reference. If so, edit the
2762 * referenced value. Otherwise, edit the pointer.
2764 if (*s == ':') {
2765 // a reference
2766 ++s;
2767 goto repeat;
2769 // a pointer
2770 // if it's a pointer to a string, remove the string
2771 const char* end = s;
2772 while (isspace(*s))
2773 ++s;
2774 if (*s == '"') {
2775 // a string
2776 return QString::fromLatin1(start, end-start);
2777 } else {
2778 // other pointer
2779 return QString::fromLatin1(start, strlen(start));
2783 // else leave it unchanged (or stripped of the reference preamble)
2784 return s;
2787 QString GdbDriver::parseSetVariable(const char* output)
2789 // if there is any output, it is an error message
2790 QString msg = output;
2791 return msg.trimmed();
2795 #include "gdbdriver.moc"