Merge branch 'maint'
[kdbg.git] / kdbg / gdbdriver.cpp
blobbee945deb097c234326e1aa82f0803a99d85845d
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 { DCprintPopup, "print %s\n", GdbCmdInfo::argString },
112 { DCframe, "frame %d\n", GdbCmdInfo::argNum },
113 { DCfindType, "whatis %s\n", GdbCmdInfo::argString },
114 { DCinfosharedlib, "info sharedlibrary\n", GdbCmdInfo::argNone },
115 { DCthread, "thread %d\n", GdbCmdInfo::argNum },
116 { DCinfothreads, "info threads\n", GdbCmdInfo::argNone },
117 { DCinfobreak, "info breakpoints\n", GdbCmdInfo::argNone },
118 { DCcondition, "condition %d %s\n", GdbCmdInfo::argNumString},
119 { DCsetpc, "set variable $pc=%s\n", GdbCmdInfo::argString },
120 { DCignore, "ignore %d %d\n", GdbCmdInfo::argNum2},
121 { DCprintWChar, "print ($s=%s)?*$s@wcslen($s):0x0\n", GdbCmdInfo::argString },
122 { DCsetvariable, "set variable %s=%s\n", GdbCmdInfo::argString2 },
125 #define NUM_CMDS (int(sizeof(cmds)/sizeof(cmds[0])))
126 #define MAX_FMTLEN 200
128 GdbDriver::GdbDriver() :
129 DebuggerDriver()
131 #ifndef NDEBUG
132 // check command info array
133 const char* perc;
134 for (int i = 0; i < NUM_CMDS; i++) {
135 // must be indexable by DbgCommand values, i.e. sorted by DbgCommand values
136 assert(i == cmds[i].cmd);
137 // a format string must be associated
138 assert(cmds[i].fmt != 0);
139 assert(strlen(cmds[i].fmt) <= MAX_FMTLEN);
140 // format string must match arg specification
141 switch (cmds[i].argsNeeded) {
142 case GdbCmdInfo::argNone:
143 assert(strchr(cmds[i].fmt, '%') == 0);
144 break;
145 case GdbCmdInfo::argString:
146 perc = strchr(cmds[i].fmt, '%');
147 assert(perc != 0 && perc[1] == 's');
148 assert(strchr(perc+2, '%') == 0);
149 break;
150 case GdbCmdInfo::argNum:
151 perc = strchr(cmds[i].fmt, '%');
152 assert(perc != 0 && perc[1] == 'd');
153 assert(strchr(perc+2, '%') == 0);
154 break;
155 case GdbCmdInfo::argStringNum:
156 perc = strchr(cmds[i].fmt, '%');
157 assert(perc != 0 && perc[1] == 's');
158 perc = strchr(perc+2, '%');
159 assert(perc != 0 && perc[1] == 'd');
160 assert(strchr(perc+2, '%') == 0);
161 break;
162 case GdbCmdInfo::argNumString:
163 perc = strchr(cmds[i].fmt, '%');
164 assert(perc != 0 && perc[1] == 'd');
165 perc = strchr(perc+2, '%');
166 assert(perc != 0 && perc[1] == 's');
167 assert(strchr(perc+2, '%') == 0);
168 break;
169 case GdbCmdInfo::argString2:
170 perc = strchr(cmds[i].fmt, '%');
171 assert(perc != 0 && perc[1] == 's');
172 perc = strchr(perc+2, '%');
173 assert(perc != 0 && perc[1] == 's');
174 assert(strchr(perc+2, '%') == 0);
175 break;
176 case GdbCmdInfo::argNum2:
177 perc = strchr(cmds[i].fmt, '%');
178 assert(perc != 0 && perc[1] == 'd');
179 perc = strchr(perc+2, '%');
180 assert(perc != 0 && perc[1] == 'd');
181 assert(strchr(perc+2, '%') == 0);
182 break;
185 assert(strlen(printQStringStructFmt) <= MAX_FMTLEN);
186 #endif
189 GdbDriver::~GdbDriver()
194 QString GdbDriver::driverName() const
196 return "GDB";
199 QString GdbDriver::defaultGdb()
201 return
202 "gdb"
203 " --fullname" /* to get standard file names each time the prog stops */
204 " --nx"; /* do not execute initialization files */
207 QString GdbDriver::defaultInvocation() const
209 if (m_defaultCmd.isEmpty()) {
210 return defaultGdb();
211 } else {
212 return m_defaultCmd;
216 QStringList GdbDriver::boolOptionList() const
218 // no options
219 return QStringList();
222 bool GdbDriver::startup(QString cmdStr)
224 if (!DebuggerDriver::startup(cmdStr))
225 return false;
227 static const char gdbInitialize[] =
229 * Work around buggy gdbs that do command line editing even if they
230 * are not on a tty. The readline library echos every command back
231 * in this case, which is confusing for us.
233 "set editing off\n"
234 "set confirm off\n"
235 "set print static-members off\n"
236 "set print asm-demangle on\n"
238 * Sometimes, gdb prints [New Thread ...] during 'info threads';
239 * we will not look at thread events anyway, so turn them off.
241 "set print thread-events off\n"
243 * Don't assume that program functions invoked from a watch expression
244 * always succeed.
246 "set unwindonsignal on\n"
248 * Write a short macro that prints all locals: local variables and
249 * function arguments.
251 "define kdbg__alllocals\n"
252 "info locals\n" /* local vars supersede args with same name */
253 "info args\n" /* therefore, arguments must come last */
254 "end\n"
256 * Work around a bug in gdb-6.3: "info line main" crashes gdb.
258 "define kdbg_infolinemain\n"
259 "list\n"
260 "info line\n"
261 "end\n"
262 // change prompt string and synchronize with gdb
263 "set prompt " PROMPT "\n"
266 executeCmdString(DCinitialize, gdbInitialize, false);
268 // assume that QString::null is ok
269 cmds[DCprintQStringStruct].fmt = printQStringStructFmt;
271 return true;
274 void GdbDriver::commandFinished(CmdQueueItem* cmd)
276 // command string must be committed
277 if (!cmd->m_committed) {
278 // not commited!
279 TRACE("calling " + (__PRETTY_FUNCTION__ + (" with uncommited command:\n\t" +
280 cmd->m_cmdString)));
281 return;
284 switch (cmd->m_cmd) {
285 case DCinitialize:
288 * Check for GDB 7.1 or later; the syntax for the disassemble
289 * command has changed.
290 * This RE picks the last version number in the first line,
291 * because at least OpenSUSE writes its own version number
292 * in the first line (but before GDB's version number).
294 QRegExp re(
295 " " // must be preceded by space
296 "[(]?" // SLES 10 embeds in parentheses
297 "(\\d+)\\.(\\d+)" // major, minor
298 "[^ ]*\\n" // no space until end of line
300 int pos = re.indexIn(m_output);
301 const char* disass = "disassemble %s %s\n";
302 if (pos >= 0) {
303 int major = re.cap(1).toInt();
304 int minor = re.cap(2).toInt();
305 if (major > 7 || (major == 7 && minor >= 1))
307 disass = "disassemble %s, %s\n";
310 cmds[DCdisassemble].fmt = disass;
312 break;
313 default:;
316 /* ok, the command is ready */
317 emit commandReceived(cmd, m_output.constData());
319 switch (cmd->m_cmd) {
320 case DCcorefile:
321 case DCinfolinemain:
322 case DCinfoline:
323 case DCframe:
324 case DCattach:
325 case DCrun:
326 case DCcont:
327 case DCstep:
328 case DCstepi:
329 case DCnext:
330 case DCnexti:
331 case DCfinish:
332 case DCuntil:
333 parseMarker(cmd);
334 default:;
338 int GdbDriver::findPrompt(const QByteArray& output) const
341 * If there's a prompt string in the collected output, it must be at
342 * the very end.
344 * Note: It could nevertheless happen that a character sequence that is
345 * equal to the prompt string appears at the end of the output,
346 * although it is very, very unlikely (namely as part of a string that
347 * lingered in gdb's output buffer due to some timing/heavy load
348 * conditions for a very long time such that that buffer overflowed
349 * exactly at the end of the prompt string look-a-like).
351 int len = output.length();
352 if (len >= PROMPT_LEN &&
353 strncmp(output.data()+len-PROMPT_LEN, PROMPT, PROMPT_LEN) == 0)
355 return len-PROMPT_LEN;
357 return -1;
361 * The --fullname option makes gdb send a special normalized sequence print
362 * each time the program stops and at some other points. The sequence has
363 * the form "\032\032filename:lineno:charoffset:(beg|middle):address".
365 void GdbDriver::parseMarker(CmdQueueItem* cmd)
367 char* startMarker = strstr(m_output.data(), "\032\032");
368 if (startMarker == 0)
369 return;
371 // extract the marker
372 startMarker += 2;
373 TRACE(QString("found marker: ") + startMarker);
374 char* endMarker = strchr(startMarker, '\n');
375 if (endMarker == 0)
376 return;
378 *endMarker = '\0';
380 // extract filename and line number
381 static QRegExp MarkerRE(":(\\d+):\\d+:[begmidl]+:0x");
383 int lineNoStart = MarkerRE.indexIn(startMarker);
384 if (lineNoStart >= 0) {
385 int lineNo = MarkerRE.cap(1).toInt();
387 // get address unless there is one in cmd
388 DbgAddr address = cmd->m_addr;
389 if (address.isEmpty()) {
390 const char* addrStart = startMarker + lineNoStart +
391 MarkerRE.matchedLength() - 2;
392 address = QString(addrStart).trimmed();
395 // now show the window
396 startMarker[lineNoStart] = '\0'; /* split off file name */
397 emit activateFileLine(startMarker, lineNo-1, address);
403 * Escapes characters that might lead to problems when they appear on gdb's
404 * command line.
406 static void normalizeStringArg(QString& arg)
409 * Remove trailing backslashes. This approach is a little simplistic,
410 * but we know that there is at the moment no case where a trailing
411 * backslash would make sense.
413 while (!arg.isEmpty() && arg[arg.length()-1] == '\\') {
414 arg = arg.left(arg.length()-1);
419 QString GdbDriver::makeCmdString(DbgCommand cmd, QString strArg)
421 assert(cmd >= 0 && cmd < NUM_CMDS);
422 assert(cmds[cmd].argsNeeded == GdbCmdInfo::argString);
424 normalizeStringArg(strArg);
426 if (cmd == DCcd) {
427 // need the working directory when parsing the output
428 m_programWD = strArg;
429 } else if (cmd == DCsetargs && !m_redirect.isEmpty()) {
431 * Use saved redirection. We prepend it in front of the user's
432 * arguments so that the user can override the redirections.
434 strArg = m_redirect + " " + strArg;
437 QString cmdString;
438 cmdString.sprintf(cmds[cmd].fmt, strArg.toUtf8().constData());
439 return cmdString;
442 QString GdbDriver::makeCmdString(DbgCommand cmd, int intArg)
444 assert(cmd >= 0 && cmd < NUM_CMDS);
445 assert(cmds[cmd].argsNeeded == GdbCmdInfo::argNum);
447 QString cmdString;
448 cmdString.sprintf(cmds[cmd].fmt, intArg);
449 return cmdString;
452 QString GdbDriver::makeCmdString(DbgCommand cmd, QString strArg, int intArg)
454 assert(cmd >= 0 && cmd < NUM_CMDS);
455 assert(cmds[cmd].argsNeeded == GdbCmdInfo::argStringNum ||
456 cmds[cmd].argsNeeded == GdbCmdInfo::argNumString ||
457 cmd == DCexamine ||
458 cmd == DCtty);
460 normalizeStringArg(strArg);
462 QString cmdString;
464 if (cmd == DCtty)
467 * intArg specifies which channels should be redirected to
468 * /dev/null. It is a value or'ed together from RDNstdin,
469 * RDNstdout, RDNstderr. We store the value for a later DCsetargs
470 * command.
472 * Note: We rely on that after the DCtty a DCsetargs will follow,
473 * which will ultimately apply the redirection.
475 static const char* const runRedir[8] = {
477 "</dev/null",
478 ">/dev/null",
479 "</dev/null >/dev/null",
480 "2>/dev/null",
481 "</dev/null 2>/dev/null",
482 ">/dev/null 2>&1",
483 "</dev/null >/dev/null 2>&1"
485 if (strArg.isEmpty())
486 intArg = 7; /* failsafe if no tty */
487 m_redirect = runRedir[intArg & 7];
489 return makeCmdString(DCtty, strArg); /* note: no problem if strArg empty */
492 if (cmd == DCexamine) {
493 // make a format specifier from the intArg
494 static const char size[16] = {
495 '\0', 'b', 'h', 'w', 'g'
497 static const char format[16] = {
498 '\0', 'x', 'd', 'u', 'o', 't',
499 'a', 'c', 'f', 's', 'i'
501 assert(MDTsizemask == 0xf); /* lowest 4 bits */
502 assert(MDTformatmask == 0xf0); /* next 4 bits */
503 int count = 16; /* number of entities to print */
504 char sizeSpec = size[intArg & MDTsizemask];
505 char formatSpec = format[(intArg & MDTformatmask) >> 4];
506 assert(sizeSpec != '\0');
507 assert(formatSpec != '\0');
508 // adjust count such that 16 lines are printed
509 switch (intArg & MDTformatmask) {
510 case MDTstring: case MDTinsn:
511 break; /* no modification needed */
512 default:
513 // all cases drop through:
514 switch (intArg & MDTsizemask) {
515 case MDTbyte:
516 case MDThalfword:
517 count *= 2;
518 case MDTword:
519 count *= 2;
520 case MDTgiantword:
521 count *= 2;
523 break;
525 QString spec;
526 spec.sprintf("/%d%c%c", count, sizeSpec, formatSpec);
528 return makeCmdString(DCexamine, spec, strArg);
531 if (cmds[cmd].argsNeeded == GdbCmdInfo::argStringNum)
533 // line numbers are zero-based
534 if (cmd == DCuntil || cmd == DCbreakline ||
535 cmd == DCtbreakline || cmd == DCinfoline)
537 intArg++;
539 if (cmd == DCinfoline)
541 // must split off file name part
542 strArg = QFileInfo(strArg).fileName();
544 cmdString.sprintf(cmds[cmd].fmt, strArg.toUtf8().constData(), intArg);
546 else
548 cmdString.sprintf(cmds[cmd].fmt, intArg, strArg.toUtf8().constData());
550 return cmdString;
553 QString GdbDriver::makeCmdString(DbgCommand cmd, QString strArg1, QString strArg2)
555 assert(cmd >= 0 && cmd < NUM_CMDS);
556 assert(cmds[cmd].argsNeeded == GdbCmdInfo::argString2);
558 normalizeStringArg(strArg1);
559 normalizeStringArg(strArg2);
561 QString cmdString;
562 cmdString.sprintf(cmds[cmd].fmt,
563 strArg1.toUtf8().constData(),
564 strArg2.toUtf8().constData());
565 return cmdString;
568 QString GdbDriver::makeCmdString(DbgCommand cmd, int intArg1, int intArg2)
570 assert(cmd >= 0 && cmd < NUM_CMDS);
571 assert(cmds[cmd].argsNeeded == GdbCmdInfo::argNum2);
573 QString cmdString;
574 cmdString.sprintf(cmds[cmd].fmt, intArg1, intArg2);
575 return cmdString;
578 CmdQueueItem* GdbDriver::executeCmd(DbgCommand cmd, bool clearLow)
580 assert(cmd >= 0 && cmd < NUM_CMDS);
581 assert(cmds[cmd].argsNeeded == GdbCmdInfo::argNone);
583 if (cmd == DCrun) {
584 m_haveCoreFile = false;
587 return executeCmdString(cmd, cmds[cmd].fmt, clearLow);
590 CmdQueueItem* GdbDriver::executeCmd(DbgCommand cmd, QString strArg,
591 bool clearLow)
593 return executeCmdString(cmd, makeCmdString(cmd, strArg), clearLow);
596 CmdQueueItem* GdbDriver::executeCmd(DbgCommand cmd, int intArg,
597 bool clearLow)
600 return executeCmdString(cmd, makeCmdString(cmd, intArg), clearLow);
603 CmdQueueItem* GdbDriver::executeCmd(DbgCommand cmd, QString strArg, int intArg,
604 bool clearLow)
606 return executeCmdString(cmd, makeCmdString(cmd, strArg, intArg), clearLow);
609 CmdQueueItem* GdbDriver::executeCmd(DbgCommand cmd, QString strArg1, QString strArg2,
610 bool clearLow)
612 return executeCmdString(cmd, makeCmdString(cmd, strArg1, strArg2), clearLow);
615 CmdQueueItem* GdbDriver::executeCmd(DbgCommand cmd, int intArg1, int intArg2,
616 bool clearLow)
618 return executeCmdString(cmd, makeCmdString(cmd, intArg1, intArg2), clearLow);
621 CmdQueueItem* GdbDriver::queueCmd(DbgCommand cmd, QueueMode mode)
623 return queueCmdString(cmd, cmds[cmd].fmt, mode);
626 CmdQueueItem* GdbDriver::queueCmd(DbgCommand cmd, QString strArg,
627 QueueMode mode)
629 return queueCmdString(cmd, makeCmdString(cmd, strArg), mode);
632 CmdQueueItem* GdbDriver::queueCmd(DbgCommand cmd, int intArg,
633 QueueMode mode)
635 return queueCmdString(cmd, makeCmdString(cmd, intArg), mode);
638 CmdQueueItem* GdbDriver::queueCmd(DbgCommand cmd, QString strArg, int intArg,
639 QueueMode mode)
641 return queueCmdString(cmd, makeCmdString(cmd, strArg, intArg), mode);
644 CmdQueueItem* GdbDriver::queueCmd(DbgCommand cmd, QString strArg1, QString strArg2,
645 QueueMode mode)
647 return queueCmdString(cmd, makeCmdString(cmd, strArg1, strArg2), mode);
650 void GdbDriver::terminate()
652 ::kill(pid(), SIGTERM);
653 m_state = DSidle;
656 void GdbDriver::detachAndTerminate()
658 ::kill(pid(), SIGINT);
659 flushCommands();
660 executeCmdString(DCinitialize, "detach\nquit\n", true);
663 void GdbDriver::interruptInferior()
665 ::kill(pid(), SIGINT);
666 // remove accidentally queued commands
667 flushHiPriQueue();
670 static bool isErrorExpr(const char* output)
672 return
673 strncmp(output, "Cannot access memory at", 23) == 0 ||
674 strncmp(output, "Attempt to dereference a generic pointer", 40) == 0 ||
675 strncmp(output, "Attempt to take contents of ", 28) == 0 ||
676 strncmp(output, "Attempt to use a type name as an expression", 43) == 0 ||
677 strncmp(output, "There is no member or method named", 34) == 0 ||
678 strncmp(output, "A parse error in expression", 27) == 0 ||
679 strncmp(output, "No symbol \"", 11) == 0 ||
680 strncmp(output, "Internal error: ", 16) == 0;
684 * Returns true if the output is an error message. If wantErrorValue is
685 * true, a new ExprValue object is created and filled with the error message.
686 * If there are warnings, they are skipped and output points past the warnings
687 * on return (even if there \e are errors).
689 static bool parseErrorMessage(const char*& output,
690 ExprValue*& variable, bool wantErrorValue)
692 while (isspace(*output))
693 output++;
695 // skip warnings
696 while (strncmp(output, "warning:", 8) == 0)
698 const char* end = strchr(output+8, '\n');
699 if (end == 0)
700 output += strlen(output);
701 else
702 output = end+1;
703 while (isspace(*output))
704 output++;
707 if (isErrorExpr(output))
709 if (wantErrorValue) {
710 // put the error message as value in the variable
711 variable = new ExprValue(QString(), VarTree::NKplain);
712 const char* endMsg = strchr(output, '\n');
713 if (endMsg == 0)
714 endMsg = output + strlen(output);
715 variable->m_value = QString::fromLatin1(output, endMsg-output);
716 } else {
717 variable = 0;
719 return true;
721 return false;
724 #if QT_VERSION >= 300
725 union Qt2QChar {
726 short s;
727 struct {
728 uchar row;
729 uchar cell;
730 } qch;
732 #endif
734 void GdbDriver::setPrintQStringDataCmd(const char* cmd)
736 // don't accept the command if it is empty
737 if (cmd == 0 || *cmd == '\0')
738 return;
739 assert(strlen(cmd) <= MAX_FMTLEN);
740 cmds[DCprintQStringStruct].fmt = cmd;
743 ExprValue* GdbDriver::parseQCharArray(const char* output, bool wantErrorValue, bool qt3like)
745 ExprValue* variable = 0;
748 * Parse off white space. gdb sometimes prints white space first if the
749 * printed array leaded to an error.
751 while (isspace(*output))
752 output++;
754 // special case: empty string (0 repetitions)
755 if (strncmp(output, "Invalid number 0 of repetitions", 31) == 0)
757 variable = new ExprValue(QString(), VarTree::NKplain);
758 variable->m_value = "\"\"";
759 return variable;
762 // check for error conditions
763 if (parseErrorMessage(output, variable, wantErrorValue))
764 return variable;
766 // parse the array
768 // find '='
769 const char* p = output;
770 p = strchr(p, '=');
771 if (p == 0) {
772 goto error;
774 // skip white space
775 do {
776 p++;
777 } while (isspace(*p));
779 if (*p == '{')
781 // this is the real data
782 p++; /* skip '{' */
784 // parse the array
785 QString result;
786 QString repeatCount;
787 enum { wasNothing, wasChar, wasRepeat } lastThing = wasNothing;
789 * A matrix for separators between the individual "things"
790 * that are added to the string. The first index is a bool,
791 * the second index is from the enum above.
793 static const char* separator[2][3] = {
794 { "\"", 0, ", \"" }, /* normal char is added */
795 { "'", "\", '", ", '" } /* repeated char is added */
798 while (isdigit(*p)) {
799 // parse a number
800 char* end;
801 unsigned short value = (unsigned short) strtoul(p, &end, 0);
802 if (end == p)
803 goto error; /* huh? no valid digits */
804 // skip separator and search for a repeat count
805 p = end;
806 while (isspace(*p) || *p == ',')
807 p++;
808 bool repeats = strncmp(p, "<repeats ", 9) == 0;
809 if (repeats) {
810 const char* start = p;
811 p = strchr(p+9, '>'); /* search end and advance */
812 if (p == 0)
813 goto error;
814 p++; /* skip '>' */
815 repeatCount = QString::fromLatin1(start, p-start);
816 while (isspace(*p) || *p == ',')
817 p++;
819 // p is now at the next char (or the end)
821 // interpret the value as a QChar
822 // TODO: make cross-architecture compatible
823 QChar ch;
824 if (qt3like) {
825 ch = QChar(value);
826 } else {
827 #if QT_VERSION < 300
828 (unsigned short&)ch = value;
829 #else
830 Qt2QChar c;
831 c.s = value;
832 ch.setRow(c.qch.row);
833 ch.setCell(c.qch.cell);
834 #endif
837 // escape a few frequently used characters
838 char escapeCode = '\0';
839 switch (ch.toLatin1()) {
840 case '\n': escapeCode = 'n'; break;
841 case '\r': escapeCode = 'r'; break;
842 case '\t': escapeCode = 't'; break;
843 case '\b': escapeCode = 'b'; break;
844 case '\"': escapeCode = '\"'; break;
845 case '\\': escapeCode = '\\'; break;
846 case '\0': if (value == 0) { escapeCode = '0'; } break;
849 // add separator
850 result += separator[repeats][lastThing];
851 // add char
852 if (escapeCode != '\0') {
853 result += '\\';
854 ch = escapeCode;
856 result += ch;
858 // fixup repeat count and lastThing
859 if (repeats) {
860 result += "' ";
861 result += repeatCount;
862 lastThing = wasRepeat;
863 } else {
864 lastThing = wasChar;
867 if (*p != '}')
868 goto error;
870 // closing quote
871 if (lastThing == wasChar)
872 result += "\"";
874 // assign the value
875 variable = new ExprValue(QString(), VarTree::NKplain);
876 variable->m_value = result;
878 else if (strncmp(p, "true", 4) == 0)
880 variable = new ExprValue(QString(), VarTree::NKplain);
881 variable->m_value = "QString::null";
883 else if (strncmp(p, "false", 5) == 0)
885 variable = new ExprValue(QString(), VarTree::NKplain);
886 variable->m_value = "(null)";
888 else
889 goto error;
890 return variable;
892 error:
893 if (wantErrorValue) {
894 variable = new ExprValue(QString(), VarTree::NKplain);
895 variable->m_value = "internal parse error";
897 return variable;
900 static ExprValue* parseVar(const char*& s)
902 const char* p = s;
904 // skip whitespace
905 while (isspace(*p))
906 p++;
908 QString name;
909 VarTree::NameKind kind;
911 * Detect anonymouse struct values: The 'name =' part is missing:
912 * s = { a = 1, { b = 2 }}
913 * Note that this detection works only inside structs when the anonymous
914 * struct is not the first member:
915 * s = {{ a = 1 }, b = 2}
916 * This is misparsed (by parseNested()) because it is mistakenly
917 * interprets the second opening brace as the first element of an array
918 * of structs.
920 if (*p == '{')
922 name = i18n("<anonymous struct or union>");
923 kind = VarTree::NKanonymous;
925 else
927 if (!parseName(p, name, kind)) {
928 return 0;
931 // go for '='
932 while (isspace(*p))
933 p++;
934 if (*p != '=') {
935 TRACE("parse error: = not found after " + name);
936 return 0;
938 // skip the '=' and more whitespace
939 p++;
940 while (isspace(*p))
941 p++;
944 ExprValue* variable = new ExprValue(name, kind);
946 if (!parseValue(p, variable)) {
947 delete variable;
948 return 0;
950 s = p;
951 return variable;
954 static void skipNested(const char*& s, char opening, char closing)
956 const char* p = s;
958 // parse a nested type
959 int nest = 1;
960 p++;
962 * Search for next matching `closing' char, skipping nested pairs of
963 * `opening' and `closing'.
965 while (*p && nest > 0) {
966 if (*p == opening) {
967 nest++;
968 } else if (*p == closing) {
969 nest--;
971 p++;
973 if (nest != 0) {
974 TRACE(QString().sprintf("parse error: mismatching %c%c at %-20.20s", opening, closing, s));
976 s = p;
980 * This function skips text that is delimited by nested angle bracktes, '<>'.
981 * A complication arises because the delimited text can contain the names of
982 * operator<<, operator>>, operator<, and operator>, which have to be treated
983 * specially so that they do not count towards the nesting of '<>'.
984 * This function assumes that the delimited text does not contain strings.
986 static void skipNestedAngles(const char*& s)
988 const char* p = s;
990 int nest = 1;
991 p++; // skip the initial '<'
992 while (*p && nest > 0)
994 // Below we can check for p-s >= 9 instead of 8 because
995 // *s is '<' and cannot be part of "operator".
996 if (*p == '<')
998 if (p-s >= 9 && strncmp(p-8, "operator", 8) == 0) {
999 if (p[1] == '<')
1000 p++;
1001 } else {
1002 nest++;
1005 else if (*p == '>')
1007 if (p-s >= 9 && strncmp(p-8, "operator", 8) == 0) {
1008 if (p[1] == '>')
1009 p++;
1010 } else {
1011 nest--;
1014 p++;
1016 if (nest != 0) {
1017 TRACE(QString().sprintf("parse error: mismatching <> at %-20.20s", s));
1019 s = p;
1023 * Find the end of line that is not inside braces
1025 static void findEnd(const char*& s)
1027 const char* p = s;
1028 while (*p && *p!='\n') {
1029 while (*p && *p!='\n' && *p!='{')
1030 p++;
1031 if (*p=='{') {
1032 p++;
1033 skipNested(p, '{', '}'); p--;
1036 s = p;
1039 static bool isNumberish(const char ch)
1041 return (ch>='0' && ch<='9') || ch=='.' || ch=='x';
1044 void skipString(const char*& p)
1046 // wchar_t strings begin with L
1047 if (*p == 'L')
1048 ++p;
1050 moreStrings:
1051 // opening quote
1052 char quote = *p++;
1053 while (*p != quote) {
1054 if (*p == '\\') {
1055 // skip escaped character
1056 // no special treatment for octal values necessary
1057 p++;
1059 // simply return if no more characters
1060 if (*p == '\0')
1061 return;
1062 p++;
1064 // closing quote
1065 p++;
1067 * Strings can consist of several parts, some of which contain repeated
1068 * characters.
1070 if (quote == '\'') {
1071 // look ahaead for <repeats 123 times>
1072 const char* q = p+1;
1073 while (isspace(*q))
1074 q++;
1075 if (strncmp(q, "<repeats ", 9) == 0) {
1076 p = q+9;
1077 while (*p != '\0' && *p != '>')
1078 p++;
1079 if (*p != '\0') {
1080 p++; /* skip the '>' */
1084 // Is the string continued? If so, there is no L in wchar_t strings
1085 if (*p == ',')
1087 // look ahead for another quote
1088 const char* q = p+1;
1089 while (isspace(*q))
1090 q++;
1091 if (*q == '"' || *q == '\'') {
1092 // yes!
1093 p = q;
1094 goto moreStrings;
1097 // some strings can end in <incomplete sequence ...>
1098 if (strncmp(q, "<incomplete sequence", 20) == 0)
1100 p = q+20;
1101 while (*p != '\0' && *p != '>')
1102 p++;
1103 if (*p != '\0') {
1104 p++; /* skip the '>' */
1109 * There's a bug in gdb where it prints the beginning of the string
1110 * continuation and the comma-blank in the wrong order if the new string
1111 * begins with an incomplete multi-byte character. For now, let's check
1112 * for this in a very narrow condition, particularly, where the next
1113 * character is given in octal notation. Example:
1114 * 'a' <repeats 20 times>"\240, b"
1116 if (*p == '"' && p[1] == '\\' && isdigit(p[2])) {
1117 int i = 3;
1118 while (isdigit(p[i]))
1119 ++i;
1120 if (p[i] == ',' && p[i+1] == ' ') {
1121 // just treat everything beginning at the dquote as string
1122 goto moreStrings;
1125 /* very long strings are followed by `...' */
1126 if (*p == '.' && p[1] == '.' && p[2] == '.') {
1127 p += 3;
1131 static void skipNestedWithString(const char*& s, char opening, char closing)
1133 const char* p = s;
1135 // parse a nested expression
1136 int nest = 1;
1137 p++;
1139 * Search for next matching `closing' char, skipping nested pairs of
1140 * `opening' and `closing' as well as strings.
1142 while (*p && nest > 0) {
1143 if (*p == opening) {
1144 nest++;
1145 } else if (*p == closing) {
1146 nest--;
1147 } else if (*p == '\'' || *p == '\"') {
1148 skipString(p);
1149 continue;
1151 p++;
1153 if (nest > 0) {
1154 TRACE(QString().sprintf("parse error: mismatching %c%c at %-20.20s", opening, closing, s));
1156 s = p;
1159 inline void skipName(const char*& p)
1161 // allow : (for enumeration values) and $ and . (for _vtbl.)
1162 while (isalnum(*p) || *p == '_' || *p == ':' || *p == '$' || *p == '.')
1163 p++;
1166 static bool parseName(const char*& s, QString& name, VarTree::NameKind& kind)
1168 kind = VarTree::NKplain;
1170 const char* p = s;
1171 // examples of names:
1172 // name
1173 // <Object>
1174 // <string<a,b<c>,7> >
1176 if (*p == '<') {
1177 skipNestedAngles(p);
1178 name = QString::fromLatin1(s, p - s);
1179 kind = VarTree::NKtype;
1181 else
1183 // name, which might be "static"; allow dot for "_vtbl."
1184 skipName(p);
1185 if (p == s) {
1186 TRACE(QString().sprintf("parse error: not a name %-20.20s", s));
1187 return false;
1189 int len = p - s;
1190 if (len == 6 && strncmp(s, "static", 6) == 0) {
1191 kind = VarTree::NKstatic;
1193 // its a static variable, name comes now
1194 while (isspace(*p))
1195 p++;
1196 s = p;
1197 skipName(p);
1198 if (p == s) {
1199 TRACE(QString().sprintf("parse error: not a name after static %-20.20s", s));
1200 return false;
1202 len = p - s;
1204 name = QString::fromLatin1(s, len);
1206 // return the new position
1207 s = p;
1208 return true;
1211 static bool parseValue(const char*& s, ExprValue* variable)
1213 variable->m_value = "";
1215 repeat:
1216 if (*s == '{') {
1217 // Sometimes we find the following output:
1218 // {<text variable, no debug info>} 0x40012000 <access>
1219 // {<data variable, no debug info>}
1220 // {<variable (not text or data), no debug info>}
1221 if (strncmp(s, "{<text variable, ", 17) == 0 ||
1222 strncmp(s, "{<data variable, ", 17) == 0 ||
1223 strncmp(s, "{<variable (not text or data), ", 31) == 0)
1225 const char* start = s;
1226 skipNested(s, '{', '}');
1227 variable->m_value = QString::fromLatin1(start, s-start);
1228 variable->m_value += ' '; // add only a single space
1229 while (isspace(*s))
1230 s++;
1231 goto repeat;
1233 else
1235 s++;
1236 if (!parseNested(s, variable)) {
1237 return false;
1239 // must be the closing brace
1240 if (*s != '}') {
1241 TRACE("parse error: missing } of " + variable->m_name);
1242 return false;
1244 s++;
1245 // final white space
1246 while (isspace(*s))
1247 s++;
1250 // Sometimes we find a warning; it ends at the next LF
1251 else if (strncmp(s, "warning: ", 9) == 0) {
1252 const char* end = strchr(s, '\n');
1253 s = end ? end : s+strlen(s);
1254 // skip space at start of next line
1255 while (isspace(*s))
1256 s++;
1257 goto repeat;
1258 } else {
1259 // examples of leaf values (cannot be the empty string):
1260 // 123
1261 // -123
1262 // 23.575e+37
1263 // 0x32a45
1264 // @0x012ab4
1265 // (DwContentType&) @0x8123456: {...}
1266 // 0x32a45 "text"
1267 // 10 '\n'
1268 // <optimized out>
1269 // 0x823abc <Array<int> virtual table>
1270 // 0x40240f <globarstr> "test"
1271 // (void (*)()) 0x8048480 <f(E *, char)>
1272 // (E *) 0xbffff450
1273 // red
1274 // &parseP (HTMLClueV *, char *)
1275 // Variable "x" is not available.
1276 // The value of variable 'x' is distributed...
1277 // -nan(0xfffff081defa0)
1279 const char*p = s;
1281 // check for type
1282 QString type;
1283 if (*p == '(') {
1284 skipNested(p, '(', ')');
1286 while (isspace(*p))
1287 p++;
1288 variable->m_value = QString::fromLatin1(s, p - s);
1291 bool reference = false;
1292 if (*p == '@') {
1293 // skip reference marker
1294 p++;
1295 reference = true;
1297 const char* start = p;
1298 if (*p == '-')
1299 p++;
1301 // some values consist of more than one token
1302 bool checkMultiPart = false;
1304 if (p[0] == '0' && p[1] == 'x') {
1305 // parse hex number
1306 p += 2;
1307 while (isxdigit(*p))
1308 p++;
1311 * Assume this is a pointer, but only if it's not a reference, since
1312 * references can't be expanded.
1314 if (!reference) {
1315 variable->m_varKind = VarTree::VKpointer;
1316 } else {
1318 * References are followed by a colon, in which case we'll
1319 * find the value following the reference address.
1321 if (*p == ':') {
1322 p++;
1323 } else {
1324 // Paranoia. (Can this happen, i.e. reference not followed by ':'?)
1325 reference = false;
1328 checkMultiPart = true;
1329 } else if (isdigit(*p)) {
1330 // parse decimal number, possibly a float
1331 while (isdigit(*p))
1332 p++;
1333 if (*p == '.') { /* TODO: obey i18n? */
1334 // In long arrays an integer may be followed by '...'.
1335 // We test for this situation and don't gobble the '...'.
1336 if (p[1] != '.' || p[0] != '.') {
1337 // fractional part
1338 p++;
1339 while (isdigit(*p))
1340 p++;
1343 if (*p == 'e' || *p == 'E') {
1344 p++;
1345 // exponent
1346 if (*p == '-' || *p == '+')
1347 p++;
1348 while (isdigit(*p))
1349 p++;
1352 // for char variables there is the char, eg. 10 '\n'
1353 checkMultiPart = true;
1354 } else if (*p == '<') {
1355 // e.g. <optimized out>
1356 skipNestedAngles(p);
1357 } else if (*p == '"' || *p == '\'') {
1358 // character may have multipart: '\000' <repeats 11 times>
1359 checkMultiPart = *p == '\'';
1360 // found a string
1361 skipString(p);
1362 } else if (*p == 'L' && (p[1] == '"' || p[1] == '\'')) {
1363 // ditto for wchar_t strings
1364 checkMultiPart = p[1] == '\'';
1365 skipString(p);
1366 } else if (*p == '&') {
1367 // function pointer
1368 p++;
1369 skipName(p);
1370 while (isspace(*p)) {
1371 p++;
1373 if (*p == '(') {
1374 skipNested(p, '(', ')');
1376 } else if (strncmp(p, "Variable \"", 10) == 0) {
1377 // Variable "x" is not available.
1378 p += 10; // skip to "
1379 skipName(p);
1380 if (strncmp(p, "\" is not available.", 19) == 0) {
1381 p += 19;
1383 } else if (strncmp(p, "The value of variable '", 23) == 0) {
1384 p += 23;
1385 skipName(p);
1386 const char* e = strchr(p, '.');
1387 if (e == 0) {
1388 p += strlen(p);
1389 } else {
1390 p = e+1;
1392 } else {
1393 moreEnum:
1394 // must be an enumeration value
1395 skipName(p);
1396 // nan (floating point Not a Number) is followed by a number in ()
1397 // enum values can look like A::(anonymous namespace)::blue
1398 if (*p == '(') {
1399 bool isAnonNS = strncmp(p+1, "anonymous namespace)", 20) == 0;
1400 skipNested(p, '(', ')');
1401 if (isAnonNS)
1402 goto moreEnum;
1405 variable->m_value += QString::fromLatin1(start, p - start);
1407 // remove line breaks from the value; this is ok since
1408 // string values never contain a literal line break
1409 variable->m_value.replace('\n', ' ');
1411 while (checkMultiPart) {
1412 // white space
1413 while (isspace(*p))
1414 p++;
1415 // may be followed by a string or <...>
1416 // if this was a pointer with a string,
1417 // reset that pointer flag since we have now a value
1418 start = p;
1419 checkMultiPart = false;
1421 if (*p == '"' || *p == '\'') {
1422 skipString(p);
1423 variable->m_varKind = VarTree::VKsimple;
1424 } else if (*p == 'L' && (p[1] == '"' || p[1] == '\'')) {
1425 skipString(p); // wchar_t string
1426 variable->m_varKind = VarTree::VKsimple;
1427 } else if (*p == '<') {
1428 // if this value is part of an array, it might be followed
1429 // by <repeats 15 times>, which we don't skip here
1430 if (strncmp(p, "<repeats ", 9) != 0) {
1431 skipNestedAngles(p);
1432 checkMultiPart = true;
1435 if (p != start) {
1436 // there is always a blank before the string,
1437 // which we will include in the final string value
1438 variable->m_value += QString::fromLatin1(start-1, (p - start)+1);
1442 if (variable->m_value.length() == 0) {
1443 TRACE("parse error: no value for " + variable->m_name);
1444 return false;
1447 // final white space
1448 while (isspace(*p))
1449 p++;
1450 s = p;
1453 * If this was a reference, the value follows. It might even be a
1454 * composite variable!
1456 if (reference) {
1457 goto repeat;
1461 return true;
1464 static bool parseNested(const char*& s, ExprValue* variable)
1466 // could be a structure or an array
1467 while (isspace(*s))
1468 s++;
1470 const char* p = s;
1471 bool isStruct = false;
1473 * If there is a name followed by an = or an < -- which starts a type
1474 * name -- or "static", it is a structure
1476 if (*p == '<' || *p == '}') {
1477 isStruct = true;
1478 } else if (strncmp(p, "static ", 7) == 0) {
1479 isStruct = true;
1480 } else if (isalpha(*p) || *p == '_' || *p == '$') {
1481 // look ahead for a comma after the name
1482 skipName(p);
1483 while (isspace(*p))
1484 p++;
1485 if (*p == '=') {
1486 isStruct = true;
1488 p = s; /* rescan the name */
1490 if (isStruct) {
1491 if (!parseVarSeq(p, variable)) {
1492 return false;
1494 variable->m_varKind = VarTree::VKstruct;
1495 } else {
1496 if (!parseValueSeq(p, variable)) {
1497 return false;
1499 variable->m_varKind = VarTree::VKarray;
1501 s = p;
1502 return true;
1505 static bool parseVarSeq(const char*& s, ExprValue* variable)
1507 // parse a comma-separated sequence of variables
1508 ExprValue* var = variable; /* var != 0 to indicate success if empty seq */
1509 for (;;) {
1510 if (*s == '}')
1511 break;
1512 if (strncmp(s, "<No data fields>}", 17) == 0)
1514 // no member variables, so break out immediately
1515 s += 16; /* go to the closing brace */
1516 break;
1518 var = parseVar(s);
1519 if (var == 0)
1520 break; /* syntax error */
1521 variable->appendChild(var);
1522 if (*s != ',')
1523 break;
1524 // skip the comma and whitespace
1525 s++;
1526 while (isspace(*s))
1527 s++;
1529 return var != 0;
1532 static bool parseValueSeq(const char*& s, ExprValue* variable)
1534 // parse a comma-separated sequence of variables
1535 int index = 0;
1536 bool good;
1537 for (;;) {
1538 QString name;
1539 name.sprintf("[%d]", index);
1540 ExprValue* var = new ExprValue(name, VarTree::NKplain);
1541 good = parseValue(s, var);
1542 if (!good) {
1543 delete var;
1544 return false;
1546 // a value may be followed by "<repeats 45 times>"
1547 if (strncmp(s, "<repeats ", 9) == 0) {
1548 s += 9;
1549 char* end;
1550 int l = strtol(s, &end, 10);
1551 if (end == s || strncmp(end, " times>", 7) != 0) {
1552 // should not happen
1553 delete var;
1554 return false;
1556 TRACE(QString().sprintf("found <repeats %d times> in array", l));
1557 // replace name and advance index
1558 name.sprintf("[%d .. %d]", index, index+l-1);
1559 var->m_name = name;
1560 index += l;
1561 // skip " times>" and space
1562 s = end+7;
1563 // possible final space
1564 while (isspace(*s))
1565 s++;
1566 } else {
1567 index++;
1569 variable->appendChild(var);
1570 // long arrays may be terminated by '...'
1571 if (strncmp(s, "...", 3) == 0) {
1572 s += 3;
1573 ExprValue* var = new ExprValue("...", VarTree::NKplain);
1574 var->m_value = i18n("<additional entries of the array suppressed>");
1575 variable->appendChild(var);
1576 break;
1578 if (*s != ',') {
1579 break;
1581 // skip the comma and whitespace
1582 s++;
1583 while (isspace(*s))
1584 s++;
1585 // sometimes there is a closing brace after a comma
1586 // if (*s == '}')
1587 // break;
1589 return true;
1593 * Parses a stack frame.
1595 static void parseFrameInfo(const char*& s, QString& func,
1596 QString& file, int& lineNo, DbgAddr& address)
1598 const char* p = s;
1600 // next may be a hexadecimal address
1601 if (*p == '0') {
1602 const char* start = p;
1603 p++;
1604 if (*p == 'x')
1605 p++;
1606 while (isxdigit(*p))
1607 p++;
1608 address = QString::fromLatin1(start, p-start);
1609 if (strncmp(p, " in ", 4) == 0)
1610 p += 4;
1611 } else {
1612 address = DbgAddr();
1614 const char* start = p;
1615 // check for special signal handler frame
1616 if (strncmp(p, "<signal handler called>", 23) == 0) {
1617 func = QString::fromLatin1(start, 23);
1618 file = QString();
1619 lineNo = -1;
1620 s = p+23;
1621 if (*s == '\n')
1622 s++;
1623 return;
1627 * Skip the function name. It is terminated by a left parenthesis
1628 * which does not delimit "(anonymous namespace)" and which is
1629 * outside the angle brackets <> of template parameter lists
1630 * and is preceded by a space.
1632 while (*p != '\0')
1634 if (*p == '<') {
1635 // check for operator<< and operator<
1636 if (p-start >= 8 && strncmp(p-8, "operator", 8) == 0)
1638 p++;
1639 if (*p == '<')
1640 p++;
1642 else
1644 // skip template parameter list
1645 skipNestedAngles(p);
1647 } else if (*p == '(') {
1648 // this skips "(anonymous namespace)" as well as the formal
1649 // parameter list of the containing function if this is a member
1650 // of a nested class
1651 skipNestedWithString(p, '(', ')');
1652 } else if (*p == ' ') {
1653 ++p;
1654 if (*p == '(')
1655 break; // parameter list found
1656 } else {
1657 p++;
1661 if (*p == '\0') {
1662 func = start;
1663 file = QString();
1664 lineNo = -1;
1665 s = p;
1666 return;
1669 * Skip parameters. But notice that for complicated conversion
1670 * functions (eg. "operator int(**)()()", ie. convert to pointer to
1671 * pointer to function) as well as operator()(...) we have to skip
1672 * additional pairs of parentheses. Furthermore, recent gdbs write the
1673 * demangled name followed by the arguments in a pair of parentheses,
1674 * where the demangled name can end in "const".
1676 do {
1677 skipNestedWithString(p, '(', ')');
1678 while (isspace(*p))
1679 p++;
1680 // skip "const"
1681 if (strncmp(p, "const", 5) == 0) {
1682 p += 5;
1683 while (isspace(*p))
1684 p++;
1686 } while (*p == '(');
1688 // check for file position
1689 if (strncmp(p, "at ", 3) == 0) {
1690 p += 3;
1691 const char* fileStart = p;
1692 // go for the end of the line
1693 while (*p != '\0' && *p != '\n')
1694 p++;
1695 // search back for colon
1696 const char* colon = p;
1697 do {
1698 --colon;
1699 } while (*colon != ':');
1700 file = QString::fromLatin1(fileStart, colon-fileStart);
1701 lineNo = atoi(colon+1)-1;
1702 // skip new-line
1703 if (*p != '\0')
1704 p++;
1705 } else {
1706 // check for "from shared lib"
1707 if (strncmp(p, "from ", 5) == 0) {
1708 p += 5;
1709 // go for the end of the line
1710 while (*p != '\0' && *p != '\n')
1711 p++;
1712 // skip new-line
1713 if (*p != '\0')
1714 p++;
1716 file = "";
1717 lineNo = -1;
1719 // construct the function name (including file info)
1720 if (*p == '\0') {
1721 func = start;
1722 } else {
1723 func = QString::fromLatin1(start, p-start-1); /* don't include \n */
1725 s = p;
1728 * Replace \n (and whitespace around it) in func by a blank. We cannot
1729 * use QString::simplified() for this because this would also
1730 * simplify space that belongs to a string arguments that gdb sometimes
1731 * prints in the argument lists of the function.
1733 ASSERT(!isspace(func[0].toLatin1())); // there must be non-white before first \n
1734 int nl = 0;
1735 while ((nl = func.indexOf('\n', nl)) >= 0) {
1736 // search back to the beginning of the whitespace
1737 int startWhite = nl;
1738 do {
1739 --startWhite;
1740 } while (isspace(func[startWhite].toLatin1()));
1741 startWhite++;
1742 // search forward to the end of the whitespace
1743 do {
1744 nl++;
1745 } while (isspace(func[nl].toLatin1()));
1746 // replace
1747 func.replace(startWhite, nl-startWhite, " ");
1748 /* continue searching for more \n's at this place: */
1749 nl = startWhite+1;
1755 * Parses a stack frame including its frame number
1757 static bool parseFrame(const char*& s, int& frameNo, QString& func,
1758 QString& file, int& lineNo, DbgAddr& address)
1760 // Example:
1761 // #1 0x8048881 in Dl::Dl (this=0xbffff418, r=3214) at testfile.cpp:72
1762 // Breakpoint 3, Cl::f(int) const (this=0xbffff3c0, x=17) at testfile.cpp:155
1764 // must start with a hash mark followed by number
1765 // or with "Breakpoint " followed by number and comma
1766 if (s[0] == '#') {
1767 if (!isdigit(s[1]))
1768 return false;
1769 s++; /* skip the hash mark */
1770 } else if (strncmp(s, "Breakpoint ", 11) == 0) {
1771 if (!isdigit(s[11]))
1772 return false;
1773 s += 11; /* skip "Breakpoint" */
1774 } else
1775 return false;
1777 // frame number
1778 frameNo = atoi(s);
1779 while (isdigit(*s))
1780 s++;
1781 // space and comma
1782 while (isspace(*s) || *s == ',')
1783 s++;
1784 parseFrameInfo(s, func, file, lineNo, address);
1785 return true;
1788 void GdbDriver::parseBackTrace(const char* output, std::list<StackFrame>& stack)
1790 QString func, file;
1791 int lineNo, frameNo;
1792 DbgAddr address;
1794 while (::parseFrame(output, frameNo, func, file, lineNo, address)) {
1795 stack.push_back(StackFrame());
1796 StackFrame* frm = &stack.back();
1797 frm->frameNo = frameNo;
1798 frm->fileName = file;
1799 frm->lineNo = lineNo;
1800 frm->address = address;
1801 frm->var = new ExprValue(func, VarTree::NKplain);
1805 bool GdbDriver::parseFrameChange(const char* output, int& frameNo,
1806 QString& file, int& lineNo, DbgAddr& address)
1808 QString func;
1809 return ::parseFrame(output, frameNo, func, file, lineNo, address);
1813 bool GdbDriver::parseBreakList(const char* output, std::list<Breakpoint>& brks)
1815 // skip first line, which is the headline
1816 const char* p = strchr(output, '\n');
1817 if (p == 0)
1818 return false;
1819 p++;
1820 if (*p == '\0')
1821 return false;
1823 // split up a line
1824 const char* end;
1825 char* dummy;
1826 while (*p != '\0') {
1827 Breakpoint bp;
1828 // get Num
1829 bp.id = strtol(p, &dummy, 10); /* don't care about overflows */
1830 p = dummy;
1831 // check for continued <MULTIPLE> breakpoint
1832 if (*p == '.' && isdigit(p[1]))
1834 // continuation: skip type and disposition
1836 else
1838 // get Type
1839 while (isspace(*p))
1840 p++;
1841 if (strncmp(p, "breakpoint", 10) == 0) {
1842 p += 10;
1843 } else if (strncmp(p, "hw watchpoint", 13) == 0) {
1844 bp.type = Breakpoint::watchpoint;
1845 p += 13;
1846 } else if (strncmp(p, "watchpoint", 10) == 0) {
1847 bp.type = Breakpoint::watchpoint;
1848 p += 10;
1850 while (isspace(*p))
1851 p++;
1852 if (*p == '\0')
1853 break;
1854 // get Disp
1855 bp.temporary = *p++ == 'd';
1857 while (*p != '\0' && !isspace(*p)) /* "keep" or "del" */
1858 p++;
1859 while (isspace(*p))
1860 p++;
1861 if (*p == '\0')
1862 break;
1863 // get Enb
1864 bp.enabled = *p++ == 'y';
1865 while (*p != '\0' && !isspace(*p)) /* "y" or "n" */
1866 p++;
1867 while (isspace(*p))
1868 p++;
1869 if (*p == '\0')
1870 break;
1871 // the address, if present
1872 if (bp.type == Breakpoint::breakpoint &&
1873 strncmp(p, "0x", 2) == 0)
1875 const char* start = p;
1876 while (*p != '\0' && !isspace(*p))
1877 p++;
1878 bp.address = QString::fromLatin1(start, p-start);
1879 while (isspace(*p) && *p != '\n')
1880 p++;
1881 if (*p == '\0')
1882 break;
1884 // remainder is location, hit and ignore count, condition
1885 end = strchr(p, '\n');
1886 if (end == 0) {
1887 bp.location = p;
1888 p += bp.location.length();
1889 } else {
1890 // location of a <MULTIPLE> filled in from subsequent breakpoints
1891 if (strncmp(p, "<MULTIPLE>", 10) != 0)
1892 bp.location = QString::fromLatin1(p, end-p).trimmed();
1893 p = end+1; /* skip over \n */
1896 // may be continued in next line
1897 while (isspace(*p)) { /* p points to beginning of line */
1898 // skip white space at beginning of line
1899 while (isspace(*p))
1900 p++;
1902 // seek end of line
1903 end = strchr(p, '\n');
1904 if (end == 0)
1905 end = p+strlen(p);
1907 if (strncmp(p, "breakpoint already hit", 22) == 0) {
1908 // extract the hit count
1909 p += 22;
1910 bp.hitCount = strtol(p, &dummy, 10);
1911 TRACE(QString("hit count %1").arg(bp.hitCount));
1912 } else if (strncmp(p, "stop only if ", 13) == 0) {
1913 // extract condition
1914 p += 13;
1915 bp.condition = QString::fromLatin1(p, end-p).trimmed();
1916 TRACE("condition: "+bp.condition);
1917 } else if (strncmp(p, "ignore next ", 12) == 0) {
1918 // extract ignore count
1919 p += 12;
1920 bp.ignoreCount = strtol(p, &dummy, 10);
1921 TRACE(QString("ignore count %1").arg(bp.ignoreCount));
1922 } else {
1923 // indeed a continuation
1924 bp.location += " " + QString::fromLatin1(p, end-p).trimmed();
1926 p = end;
1927 if (*p != '\0')
1928 p++; /* skip '\n' */
1931 if (brks.empty() || brks.back().id != bp.id) {
1932 brks.push_back(bp);
1933 } else {
1934 // this is a continuation; fill in location if not yet set
1935 // otherwise, drop this breakpoint
1936 Breakpoint& mbp = brks.back();
1937 if (mbp.location.isEmpty() && !bp.location.isEmpty()) {
1938 mbp.location = bp.location;
1939 mbp.address = bp.address;
1940 } else if (mbp.address.isEmpty() && !bp.address.isEmpty()) {
1941 mbp.address = bp.address;
1945 return true;
1948 std::list<ThreadInfo> GdbDriver::parseThreadList(const char* output)
1950 std::list<ThreadInfo> threads;
1951 if (strcmp(output, "\n") == 0 ||
1952 strncmp(output, "No stack.", 9) == 0 ||
1953 strncmp(output, "No threads.", 11) == 0) {
1954 // no threads
1955 return threads;
1958 bool newFormat = false;
1959 const char* p = output;
1960 while (*p != '\0') {
1961 ThreadInfo thr;
1962 // seach look for thread id, watching out for the focus indicator
1963 thr.hasFocus = false;
1964 while (isspace(*p)) /* may be \n from prev line: see "No stack" below */
1965 p++;
1967 // recent GDBs write a header line; skip it
1968 if (threads.empty() && strncmp(p, "Id Target", 11) == 0) {
1969 p = strchr(p, '\n');
1970 if (p == NULL)
1971 break;
1972 newFormat = true;
1973 continue; // next line please, '\n' is skipped above
1976 if (*p == '*') {
1977 thr.hasFocus = true;
1978 p++;
1979 // there follows only whitespace
1981 const char* end;
1982 char *temp_end = NULL; /* we need a non-const 'end' for strtol to use...*/
1983 thr.id = strtol(p, &temp_end, 10);
1984 end = temp_end;
1985 if (p == end) {
1986 // syntax error: no number found; bail out
1987 return threads;
1989 p = end;
1991 // skip space
1992 while (isspace(*p))
1993 p++;
1996 * Now follows the thread's SYSTAG.
1998 if (!newFormat) {
1999 // In the old format, it is terminated by two blanks.
2000 end = strstr(p, " ");
2001 if (end == 0) {
2002 // syntax error; bail out
2003 return threads;
2005 end += 2;
2006 } else {
2007 // In the new format lies crazyness: there is no definitive
2008 // end marker. At best we can guess when the SYSTAG ends.
2009 // A typical thread list on Linux looks like this:
2011 // Id Target Id Frame
2012 // 2 Thread 0x7ffff7854700 (LWP 10827) "thrserver" 0x00007ffff7928631 in clone () from /lib64/libc.so.6
2013 // * 1 Thread 0x7ffff7fcc700 (LWP 10808) "thrserver" main () at thrserver.c:84
2015 // Looking at GDB's code, the Target Id ends in tokens that
2016 // are bracketed by parentheses or quotes. Therefore,
2017 // we skip (at most) two tokens ('Thread' and the address),
2018 // and then all parts that are in parentheses or quotes.
2019 int n = 0;
2020 end = p;
2021 while (*end) {
2022 if (*end == '"') {
2023 skipString(end);
2024 n = 2;
2025 } else if (*end == '(') {
2026 skipNested(end, '(', ')');
2027 n = 2;
2028 } else if (n < 2) {
2029 while (*end && !isspace(*end))
2030 ++end;
2031 ++n;
2032 } else {
2033 break;
2035 while (isspace(*end))
2036 ++end;
2039 thr.threadName = QString::fromLatin1(p, end-p).trimmed();
2040 p = end;
2043 * Now follows a standard stack frame. Sometimes, however, gdb
2044 * catches a thread at an instant where it doesn't have a stack.
2046 if (strncmp(p, "[No stack.]", 11) != 0) {
2047 ::parseFrameInfo(p, thr.function, thr.fileName, thr.lineNo, thr.address);
2048 } else {
2049 thr.function = "[No stack]";
2050 thr.lineNo = -1;
2051 p += 11; /* \n is skipped above */
2054 threads.push_back(thr);
2056 return threads;
2059 static bool parseNewBreakpoint(const char* o, int& id,
2060 QString& file, int& lineNo, QString& address);
2061 static bool parseNewWatchpoint(const char* o, int& id,
2062 QString& expr);
2064 bool GdbDriver::parseBreakpoint(const char* output, int& id,
2065 QString& file, int& lineNo, QString& address)
2067 // skip lines of that begin with "(Cannot find"
2068 while (strncmp(output, "(Cannot find", 12) == 0 ||
2069 strncmp(output, "Note: breakpoint", 16) == 0)
2071 output = strchr(output, '\n');
2072 if (output == 0)
2073 return false;
2074 output++; /* skip newline */
2077 if (strncmp(output, "Breakpoint ", 11) == 0) {
2078 output += 11; /* skip "Breakpoint " */
2079 return ::parseNewBreakpoint(output, id, file, lineNo, address);
2080 } else if (strncmp(output, "Temporary breakpoint ", 21) == 0) {
2081 output += 21;
2082 return ::parseNewBreakpoint(output, id, file, lineNo, address);
2083 } else if (strncmp(output, "Hardware watchpoint ", 20) == 0) {
2084 output += 20;
2085 return ::parseNewWatchpoint(output, id, address);
2086 } else if (strncmp(output, "Watchpoint ", 11) == 0) {
2087 output += 11;
2088 return ::parseNewWatchpoint(output, id, address);
2090 return false;
2093 static bool parseNewBreakpoint(const char* o, int& id,
2094 QString& file, int& lineNo, QString& address)
2096 // breakpoint id
2097 char* p;
2098 id = strtoul(o, &p, 10);
2099 if (p == o)
2100 return false;
2102 // check for the address
2103 if (strncmp(p, " at 0x", 6) == 0) {
2104 char* start = p+4; /* skip " at ", but not 0x */
2105 p += 6;
2106 while (isxdigit(*p))
2107 ++p;
2108 address = QString::fromLatin1(start, p-start);
2112 * Mostly, GDB responds with this syntax:
2114 * Breakpoint 1 at 0x400b94: file multibrkpt.cpp, line 9. (2 locations)
2116 * but sometimes it uses this syntax:
2118 * Breakpoint 4 at 0x804f158: lotto739.cpp:95. (3 locations)
2120 char* fileEnd, *numStart = 0;
2121 char* fileStart = strstr(p, "file ");
2122 if (fileStart != 0)
2124 fileStart += 5;
2125 fileEnd = strstr(fileStart, ", line ");
2126 if (fileEnd != 0)
2127 numStart = fileEnd + 7;
2129 if (numStart == 0 && p[0] == ':' && p[1] == ' ')
2131 fileStart = p+2;
2132 while (isspace(*fileStart))
2133 ++fileStart;
2134 fileEnd = strchr(fileStart, ':');
2135 if (fileEnd != 0)
2136 numStart = fileEnd + 1;
2138 if (numStart == 0)
2139 return !address.isEmpty(); /* parse error only if there's no address */
2141 QString fileName = QString::fromLatin1(fileStart, fileEnd-fileStart);
2142 int line = strtoul(numStart, &p, 10);
2143 if (numStart == p)
2144 return false;
2146 file = fileName;
2147 lineNo = line-1; /* zero-based! */
2148 return true;
2151 static bool parseNewWatchpoint(const char* o, int& id,
2152 QString& expr)
2154 // watchpoint id
2155 char* p;
2156 id = strtoul(o, &p, 10);
2157 if (p == o)
2158 return false;
2160 if (strncmp(p, ": ", 2) != 0)
2161 return false;
2162 p += 2;
2164 // all the rest on the line is the expression
2165 expr = QString::fromLatin1(p, strlen(p)).trimmed();
2166 return true;
2169 void GdbDriver::parseLocals(const char* output, std::list<ExprValue*>& newVars)
2171 // check for possible error conditions
2172 if (strncmp(output, "No symbol table", 15) == 0)
2174 return;
2177 while (*output != '\0') {
2178 while (isspace(*output))
2179 output++;
2180 if (*output == '\0')
2181 break;
2182 // skip occurrences of "No locals" and "No args"
2183 if (strncmp(output, "No locals", 9) == 0 ||
2184 strncmp(output, "No arguments", 12) == 0)
2186 output = strchr(output, '\n');
2187 if (output == 0) {
2188 break;
2190 continue;
2193 ExprValue* variable = parseVar(output);
2194 if (variable == 0) {
2195 break;
2197 // do not add duplicates
2198 for (std::list<ExprValue*>::iterator o = newVars.begin(); o != newVars.end(); ++o) {
2199 if ((*o)->m_name == variable->m_name) {
2200 delete variable;
2201 goto skipDuplicate;
2204 newVars.push_back(variable);
2205 skipDuplicate:;
2209 ExprValue* GdbDriver::parsePrintExpr(const char* output, bool wantErrorValue)
2211 ExprValue* var = 0;
2212 // check for error conditions
2213 if (!parseErrorMessage(output, var, wantErrorValue))
2215 // parse the variable
2216 var = parseVar(output);
2218 return var;
2221 bool GdbDriver::parseChangeWD(const char* output, QString& message)
2223 bool isGood = false;
2224 message = QString(output).simplified();
2225 if (message.isEmpty()) {
2226 message = i18n("New working directory: ") + m_programWD;
2227 isGood = true;
2229 return isGood;
2232 bool GdbDriver::parseChangeExecutable(const char* output, QString& message)
2234 message = output;
2236 m_haveCoreFile = false;
2239 * Lines starting with the following do not indicate errors:
2240 * Using host libthread_db
2241 * (no debugging symbols found)
2242 * Reading symbols from
2244 while (strncmp(output, "Reading symbols from", 20) == 0 ||
2245 strncmp(output, "done.", 5) == 0 ||
2246 strncmp(output, "Missing separate debuginfo", 26) == 0 ||
2247 strncmp(output, "Try: ", 5) == 0 ||
2248 strncmp(output, "Using host libthread_db", 23) == 0 ||
2249 strncmp(output, "(no debugging symbols found)", 28) == 0)
2251 // this line is good, go to the next one
2252 const char* end = strchr(output, '\n');
2253 if (end == 0)
2254 output += strlen(output);
2255 else
2256 output = end+1;
2260 * If we've parsed all lines, there was no error.
2262 return output[0] == '\0';
2265 bool GdbDriver::parseCoreFile(const char* output)
2267 // if command succeeded, gdb emits a line starting with "#0 "
2268 m_haveCoreFile = strstr(output, "\n#0 ") != 0;
2269 return m_haveCoreFile;
2272 uint GdbDriver::parseProgramStopped(const char* output, QString& message)
2274 // optionally: "program changed, rereading symbols",
2275 // followed by:
2276 // "Program exited normally"
2277 // "Program terminated with wignal SIGSEGV"
2278 // "Program received signal SIGINT" or other signal
2279 // "Breakpoint..."
2280 // GDB since 7.3 prints
2281 // "[Inferior 1 (process 13400) exited normally]"
2282 // "[Inferior 1 (process 14698) exited with code 01]"
2284 // go through the output, line by line, checking what we have
2285 const char* start = output - 1;
2286 uint flags = SFprogramActive;
2287 message = QString();
2288 do {
2289 start++; /* skip '\n' */
2291 if (strncmp(start, "Program ", 8) == 0 ||
2292 strncmp(start, "ptrace: ", 8) == 0) {
2294 * When we receive a signal, the program remains active.
2296 * Special: If we "stopped" in a corefile, the string "Program
2297 * terminated with signal"... is displayed. (Normally, we see
2298 * "Program received signal"... when a signal happens.)
2300 if (strncmp(start, "Program exited", 14) == 0 ||
2301 (strncmp(start, "Program terminated", 18) == 0 && !m_haveCoreFile) ||
2302 strncmp(start, "ptrace: ", 8) == 0)
2304 flags &= ~SFprogramActive;
2307 // set message
2308 const char* endOfMessage = strchr(start, '\n');
2309 if (endOfMessage == 0)
2310 endOfMessage = start + strlen(start);
2311 message = QString::fromLatin1(start, endOfMessage-start);
2312 } else if (strncmp(start, "[Inferior ", 10) == 0) {
2313 const char* p = start + 10;
2314 // skip number and space
2315 while (*p && !isspace(*p))
2316 ++p;
2317 while (isspace(*p))
2318 ++p;
2319 if (*p == '(') {
2320 skipNested(p, '(', ')');
2321 if (strncmp(p, " exited ", 8) == 0) {
2322 flags &= ~SFprogramActive;
2324 // set message
2325 const char* end = strchr(p, '\n');
2326 if (end == 0)
2327 end = p + strlen(p);
2328 // strip [] from the message
2329 message = QString::fromLatin1(start+1, end-start-2);
2332 } else if (strncmp(start, "Breakpoint ", 11) == 0) {
2334 * We stopped at a (permanent) breakpoint (gdb doesn't tell us
2335 * that it stopped at a temporary breakpoint).
2337 flags |= SFrefreshBreak;
2338 } else if (strstr(start, "re-reading symbols.") != 0) {
2339 flags |= SFrefreshSource;
2342 // next line, please
2343 start = strchr(start, '\n');
2344 } while (start != 0);
2347 * Gdb only notices when new threads have appeared, but not when a
2348 * thread finishes. So we always have to assume that the list of
2349 * threads has changed.
2351 flags |= SFrefreshThreads;
2353 return flags;
2356 QStringList GdbDriver::parseSharedLibs(const char* output)
2358 QStringList shlibs;
2359 if (strncmp(output, "No shared libraries loaded", 26) == 0)
2360 return shlibs;
2362 // parse the table of shared libraries
2364 // strip off head line
2365 output = strchr(output, '\n');
2366 if (output == 0)
2367 return shlibs;
2368 output++; /* skip '\n' */
2369 QString shlibName;
2370 while (*output != '\0') {
2371 // format of a line is
2372 // 0x404c5000 0x40580d90 Yes /lib/libc.so.5
2373 // 3 blocks of non-space followed by space
2374 for (int i = 0; *output != '\0' && i < 3; i++) {
2375 while (*output != '\0' && !isspace(*output)) { /* non-space */
2376 output++;
2378 while (isspace(*output)) { /* space */
2379 output++;
2382 if (*output == '\0')
2383 return shlibs;
2384 const char* start = output;
2385 output = strchr(output, '\n');
2386 if (output == 0)
2387 output = start + strlen(start);
2388 shlibName = QString::fromLatin1(start, output-start);
2389 if (*output != '\0')
2390 output++;
2391 shlibs.append(shlibName);
2392 TRACE("found shared lib " + shlibName);
2394 return shlibs;
2397 bool GdbDriver::parseFindType(const char* output, QString& type)
2399 if (strncmp(output, "type = ", 7) != 0)
2400 return false;
2403 * Everything else is the type. We strip off any leading "const" and any
2404 * trailing "&" on the grounds that neither affects the decoding of the
2405 * object. We also strip off all white-space from the type.
2407 output += 7;
2408 if (strncmp(output, "const ", 6) == 0)
2409 output += 6;
2410 type = output;
2411 type.replace(QRegExp("\\s+"), "");
2412 if (type.endsWith("&"))
2413 type.truncate(type.length() - 1);
2414 return true;
2417 std::list<RegisterInfo> GdbDriver::parseRegisters(const char* output)
2419 std::list<RegisterInfo> regs;
2420 if (strncmp(output, "The program has no registers now", 32) == 0) {
2421 return regs;
2424 // parse register values
2425 while (*output != '\0')
2427 RegisterInfo reg;
2428 // skip space at the start of the line
2429 while (isspace(*output))
2430 output++;
2432 // register name
2433 const char* start = output;
2434 while (*output != '\0' && !isspace(*output))
2435 output++;
2436 if (*output == '\0')
2437 break;
2438 reg.regName = QString::fromLatin1(start, output-start);
2440 // skip space
2441 while (isspace(*output))
2442 output++;
2444 QString value;
2447 * If we find a brace now, this is a vector register. We look for
2448 * the closing brace and treat the result as cooked value.
2450 if (*output == '{')
2452 start = output;
2453 skipNested(output, '{', '}');
2454 value = QString::fromLatin1(start, output-start).simplified();
2455 // skip space, but not the end of line
2456 while (isspace(*output) && *output != '\n')
2457 output++;
2458 // get rid of the braces at the begining and the end
2459 value.remove(0, 1);
2460 if (value[value.length()-1] == '}') {
2461 value = value.left(value.length()-1);
2463 // gdb 5.3 doesn't print a separate set of raw values
2464 if (*output == '{') {
2465 // another set of vector follows
2466 // what we have so far is the raw value
2467 reg.rawValue = value;
2469 start = output;
2470 skipNested(output, '{', '}');
2471 value = QString::fromLatin1(start, output-start).simplified();
2472 } else {
2473 // for gdb 5.3
2474 // find first type that does not have an array, this is the RAW value
2475 const char* end=start;
2476 findEnd(end);
2477 const char* cur=start;
2478 while (cur<end) {
2479 while (*cur != '=' && cur<end)
2480 cur++;
2481 cur++;
2482 while (isspace(*cur) && cur<end)
2483 cur++;
2484 if (isNumberish(*cur)) {
2485 end=cur;
2486 while (*end && (*end!='}') && (*end!=',') && (*end!='\n'))
2487 end++;
2488 QString rawValue = QString::fromLatin1(cur, end-cur).simplified();
2489 reg.rawValue = rawValue;
2491 if (rawValue.left(2)=="0x") {
2492 // ok we have a raw value, now get it's type
2493 end=cur-1;
2494 while (isspace(*end) || *end=='=') end--;
2495 end++;
2496 cur=end-1;
2497 while (*cur!='{' && *cur!=' ')
2498 cur--;
2499 cur++;
2500 reg.type = QString::fromLatin1(cur, end-cur);
2503 // end while loop
2504 cur=end;
2507 // skip to the end of line
2508 while (*output != '\0' && *output != '\n')
2509 output++;
2510 // get rid of the braces at the begining and the end
2511 value.remove(0, 1);
2512 if (value[value.length()-1] == '}') {
2513 value.truncate(value.length()-1);
2516 reg.cookedValue = value;
2518 else
2520 continuation:
2521 // the rest of the line is the register value
2522 start = output;
2523 output = strchr(output,'\n');
2524 if (output == 0)
2525 output = start + strlen(start);
2526 value += QString::fromLatin1(start, output-start).simplified();
2529 * Look ahead: if the subsequent line is indented, it continues
2530 * the current register value.
2532 if (output != 0 && isspace(output[1]))
2534 ++output;
2535 value += ' ';
2536 goto continuation;
2540 * We split the raw from the cooked values.
2541 * Some modern gdbs explicitly say: "0.1234 (raw 0x3e4567...)".
2542 * Here, the cooked value comes first, and the raw value is in
2543 * the second part.
2545 int pos = value.indexOf(" (raw ");
2546 if (pos >= 0)
2548 reg.cookedValue = value.left(pos);
2549 reg.rawValue = value.mid(pos+6);
2550 if (reg.rawValue.right(1) == ")") // remove closing bracket
2551 reg.rawValue.truncate(reg.rawValue.length()-1);
2553 else
2556 * In other cases we split off the first token (separated by
2557 * whitespace). It is the raw value. The remainder of the line
2558 * is the cooked value.
2560 int pos = value.indexOf(' ');
2561 if (pos < 0) {
2562 reg.rawValue = value;
2563 reg.cookedValue = QString();
2564 } else {
2565 reg.rawValue = value.left(pos);
2566 reg.cookedValue = value.mid(pos+1);
2570 if (*output != '\0')
2571 output++; /* skip '\n' */
2573 regs.push_back(reg);
2575 return regs;
2578 bool GdbDriver::parseInfoLine(const char* output, QString& addrFrom, QString& addrTo)
2580 // "is at address" or "starts at address"
2581 const char* start = strstr(output, "s at address ");
2582 if (start == 0)
2583 return false;
2585 start += 13;
2586 const char* p = start;
2587 while (*p != '\0' && !isspace(*p))
2588 p++;
2589 addrFrom = QString::fromLatin1(start, p-start);
2591 start = strstr(p, "and ends at ");
2592 if (start == 0) {
2593 addrTo = addrFrom;
2594 return true;
2597 start += 12;
2598 p = start;
2599 while (*p != '\0' && !isspace(*p))
2600 p++;
2601 addrTo = QString::fromLatin1(start, p-start);
2603 return true;
2606 std::list<DisassembledCode> GdbDriver::parseDisassemble(const char* output)
2608 std::list<DisassembledCode> code;
2610 if (strncmp(output, "Dump of assembler", 17) != 0) {
2611 // error message?
2612 DisassembledCode c;
2613 c.code = output;
2614 code.push_back(c);
2615 return code;
2618 // remove first line
2619 const char* p = strchr(output, '\n');
2620 if (p == 0)
2621 return code; /* not a regular output */
2623 p++;
2625 // remove last line
2626 const char* end = strstr(output, "End of assembler");
2627 if (end == 0)
2628 end = p + strlen(p);
2630 // remove function offsets from the lines
2631 while (p != end)
2633 DisassembledCode c;
2634 // skip initial space or PC pointer ("=>", since gdb 7.1)
2635 while (p != end) {
2636 if (isspace(*p))
2637 ++p;
2638 else if (p[0] == '=' && p[1] == '>')
2639 p += 2;
2640 else
2641 break;
2643 const char* start = p;
2644 // address
2645 while (p != end && !isspace(*p))
2646 p++;
2647 c.address = QString::fromLatin1(start, p-start);
2649 // function name (enclosed in '<>', followed by ':')
2650 while (p != end && *p != '<')
2651 p++;
2652 if (*p == '<')
2653 skipNestedAngles(p);
2654 if (*p == ':')
2655 p++;
2657 // space until code
2658 while (p != end && isspace(*p))
2659 p++;
2661 // code until end of line
2662 start = p;
2663 while (p != end && *p != '\n')
2664 p++;
2665 if (p != end) /* include '\n' */
2666 p++;
2668 c.code = QString::fromLatin1(start, p-start);
2669 code.push_back(c);
2671 return code;
2674 QString GdbDriver::parseMemoryDump(const char* output, std::list<MemoryDump>& memdump)
2676 if (isErrorExpr(output)) {
2677 // error; strip space
2678 QString msg = output;
2679 return msg.trimmed();
2682 const char* p = output; /* save typing */
2684 // the address
2685 while (*p != 0) {
2686 MemoryDump md;
2688 const char* start = p;
2689 while (*p != '\0' && *p != ':' && !isspace(*p))
2690 p++;
2691 md.address = QString::fromLatin1(start, p-start);
2692 if (*p != ':') {
2693 // parse function offset
2694 while (isspace(*p))
2695 p++;
2696 start = p;
2697 while (*p != '\0' && !(*p == ':' && isspace(p[1])))
2698 p++;
2699 md.address.fnoffs = QString::fromLatin1(start, p-start);
2701 if (*p == ':')
2702 p++;
2703 // skip space; this may skip a new-line char!
2704 while (isspace(*p))
2705 p++;
2706 // everything to the end of the line is the memory dump
2707 const char* end = strchr(p, '\n');
2708 if (end != 0) {
2709 md.dump = QString::fromLatin1(p, end-p);
2710 p = end+1;
2711 } else {
2712 md.dump = QString::fromLatin1(p, strlen(p));
2713 p += strlen(p);
2715 memdump.push_back(md);
2718 return QString();
2721 QString GdbDriver::editableValue(VarTree* value)
2723 QByteArray ba = value->value().toLatin1();
2724 const char* s = ba.constData();
2726 // if the variable is a pointer value that contains a cast,
2727 // remove the cast
2728 if (*s == '(') {
2729 skipNested(s, '(', ')');
2730 // skip space
2731 while (isspace(*s))
2732 ++s;
2735 repeat:
2736 const char* start = s;
2738 if (strncmp(s, "0x", 2) == 0)
2740 s += 2;
2741 while (isxdigit(*s))
2742 ++s;
2745 * What we saw so far might have been a reference. If so, edit the
2746 * referenced value. Otherwise, edit the pointer.
2748 if (*s == ':') {
2749 // a reference
2750 ++s;
2751 goto repeat;
2753 // a pointer
2754 // if it's a pointer to a string, remove the string
2755 const char* end = s;
2756 while (isspace(*s))
2757 ++s;
2758 if (*s == '"') {
2759 // a string
2760 return QString::fromLatin1(start, end-start);
2761 } else {
2762 // other pointer
2763 return QString::fromLatin1(start, strlen(start));
2767 // else leave it unchanged (or stripped of the reference preamble)
2768 return s;
2771 QString GdbDriver::parseSetVariable(const char* output)
2773 // if there is any output, it is an error message
2774 QString msg = output;
2775 return msg.trimmed();
2779 #include "gdbdriver.moc"