Merge branch 'maint'
[kdbg.git] / kdbg / gdbdriver.cpp
blob73b87f8cd65d3264890c5291d8d5f6039704cfcc
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.toLatin1().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.toLatin1().constData(), intArg);
546 else
548 cmdString.sprintf(cmds[cmd].fmt, intArg, strArg.toLatin1().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.toLatin1().constData(),
564 strArg2.toLatin1().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 // (void (*)()) 0x8048480 <f(E *, char)>
1271 // (E *) 0xbffff450
1272 // red
1273 // &parseP (HTMLClueV *, char *)
1274 // Variable "x" is not available.
1275 // The value of variable 'x' is distributed...
1276 // -nan(0xfffff081defa0)
1278 const char*p = s;
1280 // check for type
1281 QString type;
1282 if (*p == '(') {
1283 skipNested(p, '(', ')');
1285 while (isspace(*p))
1286 p++;
1287 variable->m_value = QString::fromLatin1(s, p - s);
1290 bool reference = false;
1291 if (*p == '@') {
1292 // skip reference marker
1293 p++;
1294 reference = true;
1296 const char* start = p;
1297 if (*p == '-')
1298 p++;
1300 // some values consist of more than one token
1301 bool checkMultiPart = false;
1303 if (p[0] == '0' && p[1] == 'x') {
1304 // parse hex number
1305 p += 2;
1306 while (isxdigit(*p))
1307 p++;
1310 * Assume this is a pointer, but only if it's not a reference, since
1311 * references can't be expanded.
1313 if (!reference) {
1314 variable->m_varKind = VarTree::VKpointer;
1315 } else {
1317 * References are followed by a colon, in which case we'll
1318 * find the value following the reference address.
1320 if (*p == ':') {
1321 p++;
1322 } else {
1323 // Paranoia. (Can this happen, i.e. reference not followed by ':'?)
1324 reference = false;
1327 checkMultiPart = true;
1328 } else if (isdigit(*p)) {
1329 // parse decimal number, possibly a float
1330 while (isdigit(*p))
1331 p++;
1332 if (*p == '.') { /* TODO: obey i18n? */
1333 // In long arrays an integer may be followed by '...'.
1334 // We test for this situation and don't gobble the '...'.
1335 if (p[1] != '.' || p[0] != '.') {
1336 // fractional part
1337 p++;
1338 while (isdigit(*p))
1339 p++;
1342 if (*p == 'e' || *p == 'E') {
1343 p++;
1344 // exponent
1345 if (*p == '-' || *p == '+')
1346 p++;
1347 while (isdigit(*p))
1348 p++;
1351 // for char variables there is the char, eg. 10 '\n'
1352 checkMultiPart = true;
1353 } else if (*p == '<') {
1354 // e.g. <optimized out>
1355 skipNestedAngles(p);
1356 } else if (*p == '"' || *p == '\'') {
1357 // character may have multipart: '\000' <repeats 11 times>
1358 checkMultiPart = *p == '\'';
1359 // found a string
1360 skipString(p);
1361 } else if (*p == 'L' && (p[1] == '"' || p[1] == '\'')) {
1362 // ditto for wchar_t strings
1363 checkMultiPart = p[1] == '\'';
1364 skipString(p);
1365 } else if (*p == '&') {
1366 // function pointer
1367 p++;
1368 skipName(p);
1369 while (isspace(*p)) {
1370 p++;
1372 if (*p == '(') {
1373 skipNested(p, '(', ')');
1375 } else if (strncmp(p, "Variable \"", 10) == 0) {
1376 // Variable "x" is not available.
1377 p += 10; // skip to "
1378 skipName(p);
1379 if (strncmp(p, "\" is not available.", 19) == 0) {
1380 p += 19;
1382 } else if (strncmp(p, "The value of variable '", 23) == 0) {
1383 p += 23;
1384 skipName(p);
1385 const char* e = strchr(p, '.');
1386 if (e == 0) {
1387 p += strlen(p);
1388 } else {
1389 p = e+1;
1391 } else {
1392 moreEnum:
1393 // must be an enumeration value
1394 skipName(p);
1395 // nan (floating point Not a Number) is followed by a number in ()
1396 // enum values can look like A::(anonymous namespace)::blue
1397 if (*p == '(') {
1398 bool isAnonNS = strncmp(p+1, "anonymous namespace)", 20) == 0;
1399 skipNested(p, '(', ')');
1400 if (isAnonNS)
1401 goto moreEnum;
1404 variable->m_value += QString::fromLatin1(start, p - start);
1406 // remove line breaks from the value; this is ok since
1407 // string values never contain a literal line break
1408 variable->m_value.replace('\n', ' ');
1410 if (checkMultiPart) {
1411 // white space
1412 while (isspace(*p))
1413 p++;
1414 // may be followed by a string or <...>
1415 start = p;
1417 if (*p == '"' || *p == '\'') {
1418 skipString(p);
1419 } else if (*p == 'L' && (p[1] == '"' || p[1] == '\'')) {
1420 skipString(p); // wchar_t string
1421 } else if (*p == '<') {
1422 // if this value is part of an array, it might be followed
1423 // by <repeats 15 times>, which we don't skip here
1424 if (strncmp(p, "<repeats ", 9) != 0)
1425 skipNestedAngles(p);
1427 if (p != start) {
1428 // there is always a blank before the string,
1429 // which we will include in the final string value
1430 variable->m_value += QString::fromLatin1(start-1, (p - start)+1);
1431 // if this was a pointer, reset that flag since we
1432 // now got the value
1433 variable->m_varKind = VarTree::VKsimple;
1437 if (variable->m_value.length() == 0) {
1438 TRACE("parse error: no value for " + variable->m_name);
1439 return false;
1442 // final white space
1443 while (isspace(*p))
1444 p++;
1445 s = p;
1448 * If this was a reference, the value follows. It might even be a
1449 * composite variable!
1451 if (reference) {
1452 goto repeat;
1456 return true;
1459 static bool parseNested(const char*& s, ExprValue* variable)
1461 // could be a structure or an array
1462 while (isspace(*s))
1463 s++;
1465 const char* p = s;
1466 bool isStruct = false;
1468 * If there is a name followed by an = or an < -- which starts a type
1469 * name -- or "static", it is a structure
1471 if (*p == '<' || *p == '}') {
1472 isStruct = true;
1473 } else if (strncmp(p, "static ", 7) == 0) {
1474 isStruct = true;
1475 } else if (isalpha(*p) || *p == '_' || *p == '$') {
1476 // look ahead for a comma after the name
1477 skipName(p);
1478 while (isspace(*p))
1479 p++;
1480 if (*p == '=') {
1481 isStruct = true;
1483 p = s; /* rescan the name */
1485 if (isStruct) {
1486 if (!parseVarSeq(p, variable)) {
1487 return false;
1489 variable->m_varKind = VarTree::VKstruct;
1490 } else {
1491 if (!parseValueSeq(p, variable)) {
1492 return false;
1494 variable->m_varKind = VarTree::VKarray;
1496 s = p;
1497 return true;
1500 static bool parseVarSeq(const char*& s, ExprValue* variable)
1502 // parse a comma-separated sequence of variables
1503 ExprValue* var = variable; /* var != 0 to indicate success if empty seq */
1504 for (;;) {
1505 if (*s == '}')
1506 break;
1507 if (strncmp(s, "<No data fields>}", 17) == 0)
1509 // no member variables, so break out immediately
1510 s += 16; /* go to the closing brace */
1511 break;
1513 var = parseVar(s);
1514 if (var == 0)
1515 break; /* syntax error */
1516 variable->appendChild(var);
1517 if (*s != ',')
1518 break;
1519 // skip the comma and whitespace
1520 s++;
1521 while (isspace(*s))
1522 s++;
1524 return var != 0;
1527 static bool parseValueSeq(const char*& s, ExprValue* variable)
1529 // parse a comma-separated sequence of variables
1530 int index = 0;
1531 bool good;
1532 for (;;) {
1533 QString name;
1534 name.sprintf("[%d]", index);
1535 ExprValue* var = new ExprValue(name, VarTree::NKplain);
1536 good = parseValue(s, var);
1537 if (!good) {
1538 delete var;
1539 return false;
1541 // a value may be followed by "<repeats 45 times>"
1542 if (strncmp(s, "<repeats ", 9) == 0) {
1543 s += 9;
1544 char* end;
1545 int l = strtol(s, &end, 10);
1546 if (end == s || strncmp(end, " times>", 7) != 0) {
1547 // should not happen
1548 delete var;
1549 return false;
1551 TRACE(QString().sprintf("found <repeats %d times> in array", l));
1552 // replace name and advance index
1553 name.sprintf("[%d .. %d]", index, index+l-1);
1554 var->m_name = name;
1555 index += l;
1556 // skip " times>" and space
1557 s = end+7;
1558 // possible final space
1559 while (isspace(*s))
1560 s++;
1561 } else {
1562 index++;
1564 variable->appendChild(var);
1565 // long arrays may be terminated by '...'
1566 if (strncmp(s, "...", 3) == 0) {
1567 s += 3;
1568 ExprValue* var = new ExprValue("...", VarTree::NKplain);
1569 var->m_value = i18n("<additional entries of the array suppressed>");
1570 variable->appendChild(var);
1571 break;
1573 if (*s != ',') {
1574 break;
1576 // skip the comma and whitespace
1577 s++;
1578 while (isspace(*s))
1579 s++;
1580 // sometimes there is a closing brace after a comma
1581 // if (*s == '}')
1582 // break;
1584 return true;
1588 * Parses a stack frame.
1590 static void parseFrameInfo(const char*& s, QString& func,
1591 QString& file, int& lineNo, DbgAddr& address)
1593 const char* p = s;
1595 // next may be a hexadecimal address
1596 if (*p == '0') {
1597 const char* start = p;
1598 p++;
1599 if (*p == 'x')
1600 p++;
1601 while (isxdigit(*p))
1602 p++;
1603 address = QString::fromLatin1(start, p-start);
1604 if (strncmp(p, " in ", 4) == 0)
1605 p += 4;
1606 } else {
1607 address = DbgAddr();
1609 const char* start = p;
1610 // check for special signal handler frame
1611 if (strncmp(p, "<signal handler called>", 23) == 0) {
1612 func = QString::fromLatin1(start, 23);
1613 file = QString();
1614 lineNo = -1;
1615 s = p+23;
1616 if (*s == '\n')
1617 s++;
1618 return;
1622 * Skip the function name. It is terminated by a left parenthesis
1623 * which does not delimit "(anonymous namespace)" and which is
1624 * outside the angle brackets <> of template parameter lists
1625 * and is preceded by a space.
1627 while (*p != '\0')
1629 if (*p == '<') {
1630 // check for operator<< and operator<
1631 if (p-start >= 8 && strncmp(p-8, "operator", 8) == 0)
1633 p++;
1634 if (*p == '<')
1635 p++;
1637 else
1639 // skip template parameter list
1640 skipNestedAngles(p);
1642 } else if (*p == '(') {
1643 // this skips "(anonymous namespace)" as well as the formal
1644 // parameter list of the containing function if this is a member
1645 // of a nested class
1646 skipNestedWithString(p, '(', ')');
1647 } else if (*p == ' ') {
1648 ++p;
1649 if (*p == '(')
1650 break; // parameter list found
1651 } else {
1652 p++;
1656 if (*p == '\0') {
1657 func = start;
1658 file = QString();
1659 lineNo = -1;
1660 s = p;
1661 return;
1664 * Skip parameters. But notice that for complicated conversion
1665 * functions (eg. "operator int(**)()()", ie. convert to pointer to
1666 * pointer to function) as well as operator()(...) we have to skip
1667 * additional pairs of parentheses. Furthermore, recent gdbs write the
1668 * demangled name followed by the arguments in a pair of parentheses,
1669 * where the demangled name can end in "const".
1671 do {
1672 skipNestedWithString(p, '(', ')');
1673 while (isspace(*p))
1674 p++;
1675 // skip "const"
1676 if (strncmp(p, "const", 5) == 0) {
1677 p += 5;
1678 while (isspace(*p))
1679 p++;
1681 } while (*p == '(');
1683 // check for file position
1684 if (strncmp(p, "at ", 3) == 0) {
1685 p += 3;
1686 const char* fileStart = p;
1687 // go for the end of the line
1688 while (*p != '\0' && *p != '\n')
1689 p++;
1690 // search back for colon
1691 const char* colon = p;
1692 do {
1693 --colon;
1694 } while (*colon != ':');
1695 file = QString::fromLatin1(fileStart, colon-fileStart);
1696 lineNo = atoi(colon+1)-1;
1697 // skip new-line
1698 if (*p != '\0')
1699 p++;
1700 } else {
1701 // check for "from shared lib"
1702 if (strncmp(p, "from ", 5) == 0) {
1703 p += 5;
1704 // go for the end of the line
1705 while (*p != '\0' && *p != '\n')
1706 p++;
1707 // skip new-line
1708 if (*p != '\0')
1709 p++;
1711 file = "";
1712 lineNo = -1;
1714 // construct the function name (including file info)
1715 if (*p == '\0') {
1716 func = start;
1717 } else {
1718 func = QString::fromLatin1(start, p-start-1); /* don't include \n */
1720 s = p;
1723 * Replace \n (and whitespace around it) in func by a blank. We cannot
1724 * use QString::simplified() for this because this would also
1725 * simplify space that belongs to a string arguments that gdb sometimes
1726 * prints in the argument lists of the function.
1728 ASSERT(!isspace(func[0].toLatin1())); // there must be non-white before first \n
1729 int nl = 0;
1730 while ((nl = func.indexOf('\n', nl)) >= 0) {
1731 // search back to the beginning of the whitespace
1732 int startWhite = nl;
1733 do {
1734 --startWhite;
1735 } while (isspace(func[startWhite].toLatin1()));
1736 startWhite++;
1737 // search forward to the end of the whitespace
1738 do {
1739 nl++;
1740 } while (isspace(func[nl].toLatin1()));
1741 // replace
1742 func.replace(startWhite, nl-startWhite, " ");
1743 /* continue searching for more \n's at this place: */
1744 nl = startWhite+1;
1750 * Parses a stack frame including its frame number
1752 static bool parseFrame(const char*& s, int& frameNo, QString& func,
1753 QString& file, int& lineNo, DbgAddr& address)
1755 // Example:
1756 // #1 0x8048881 in Dl::Dl (this=0xbffff418, r=3214) at testfile.cpp:72
1757 // Breakpoint 3, Cl::f(int) const (this=0xbffff3c0, x=17) at testfile.cpp:155
1759 // must start with a hash mark followed by number
1760 // or with "Breakpoint " followed by number and comma
1761 if (s[0] == '#') {
1762 if (!isdigit(s[1]))
1763 return false;
1764 s++; /* skip the hash mark */
1765 } else if (strncmp(s, "Breakpoint ", 11) == 0) {
1766 if (!isdigit(s[11]))
1767 return false;
1768 s += 11; /* skip "Breakpoint" */
1769 } else
1770 return false;
1772 // frame number
1773 frameNo = atoi(s);
1774 while (isdigit(*s))
1775 s++;
1776 // space and comma
1777 while (isspace(*s) || *s == ',')
1778 s++;
1779 parseFrameInfo(s, func, file, lineNo, address);
1780 return true;
1783 void GdbDriver::parseBackTrace(const char* output, std::list<StackFrame>& stack)
1785 QString func, file;
1786 int lineNo, frameNo;
1787 DbgAddr address;
1789 while (::parseFrame(output, frameNo, func, file, lineNo, address)) {
1790 stack.push_back(StackFrame());
1791 StackFrame* frm = &stack.back();
1792 frm->frameNo = frameNo;
1793 frm->fileName = file;
1794 frm->lineNo = lineNo;
1795 frm->address = address;
1796 frm->var = new ExprValue(func, VarTree::NKplain);
1800 bool GdbDriver::parseFrameChange(const char* output, int& frameNo,
1801 QString& file, int& lineNo, DbgAddr& address)
1803 QString func;
1804 return ::parseFrame(output, frameNo, func, file, lineNo, address);
1808 bool GdbDriver::parseBreakList(const char* output, std::list<Breakpoint>& brks)
1810 // skip first line, which is the headline
1811 const char* p = strchr(output, '\n');
1812 if (p == 0)
1813 return false;
1814 p++;
1815 if (*p == '\0')
1816 return false;
1818 // split up a line
1819 const char* end;
1820 char* dummy;
1821 while (*p != '\0') {
1822 Breakpoint bp;
1823 // get Num
1824 bp.id = strtol(p, &dummy, 10); /* don't care about overflows */
1825 p = dummy;
1826 // get Type
1827 while (isspace(*p))
1828 p++;
1829 if (strncmp(p, "breakpoint", 10) == 0) {
1830 p += 10;
1831 } else if (strncmp(p, "hw watchpoint", 13) == 0) {
1832 bp.type = Breakpoint::watchpoint;
1833 p += 13;
1834 } else if (strncmp(p, "watchpoint", 10) == 0) {
1835 bp.type = Breakpoint::watchpoint;
1836 p += 10;
1838 while (isspace(*p))
1839 p++;
1840 if (*p == '\0')
1841 break;
1842 // get Disp
1843 bp.temporary = *p++ == 'd';
1844 while (*p != '\0' && !isspace(*p)) /* "keep" or "del" */
1845 p++;
1846 while (isspace(*p))
1847 p++;
1848 if (*p == '\0')
1849 break;
1850 // get Enb
1851 bp.enabled = *p++ == 'y';
1852 while (*p != '\0' && !isspace(*p)) /* "y" or "n" */
1853 p++;
1854 while (isspace(*p))
1855 p++;
1856 if (*p == '\0')
1857 break;
1858 // the address, if present
1859 if (bp.type == Breakpoint::breakpoint &&
1860 strncmp(p, "0x", 2) == 0)
1862 const char* start = p;
1863 while (*p != '\0' && !isspace(*p))
1864 p++;
1865 bp.address = QString::fromLatin1(start, p-start);
1866 while (isspace(*p) && *p != '\n')
1867 p++;
1868 if (*p == '\0')
1869 break;
1871 // remainder is location, hit and ignore count, condition
1872 end = strchr(p, '\n');
1873 if (end == 0) {
1874 bp.location = p;
1875 p += bp.location.length();
1876 } else {
1877 bp.location = QString::fromLatin1(p, end-p).trimmed();
1878 p = end+1; /* skip over \n */
1881 // may be continued in next line
1882 while (isspace(*p)) { /* p points to beginning of line */
1883 // skip white space at beginning of line
1884 while (isspace(*p))
1885 p++;
1887 // seek end of line
1888 end = strchr(p, '\n');
1889 if (end == 0)
1890 end = p+strlen(p);
1892 if (strncmp(p, "breakpoint already hit", 22) == 0) {
1893 // extract the hit count
1894 p += 22;
1895 bp.hitCount = strtol(p, &dummy, 10);
1896 TRACE(QString("hit count %1").arg(bp.hitCount));
1897 } else if (strncmp(p, "stop only if ", 13) == 0) {
1898 // extract condition
1899 p += 13;
1900 bp.condition = QString::fromLatin1(p, end-p).trimmed();
1901 TRACE("condition: "+bp.condition);
1902 } else if (strncmp(p, "ignore next ", 12) == 0) {
1903 // extract ignore count
1904 p += 12;
1905 bp.ignoreCount = strtol(p, &dummy, 10);
1906 TRACE(QString("ignore count %1").arg(bp.ignoreCount));
1907 } else {
1908 // indeed a continuation
1909 bp.location += " " + QString::fromLatin1(p, end-p).trimmed();
1911 p = end;
1912 if (*p != '\0')
1913 p++; /* skip '\n' */
1915 brks.push_back(bp);
1917 return true;
1920 std::list<ThreadInfo> GdbDriver::parseThreadList(const char* output)
1922 std::list<ThreadInfo> threads;
1923 if (strcmp(output, "\n") == 0 ||
1924 strncmp(output, "No stack.", 9) == 0 ||
1925 strncmp(output, "No threads.", 11) == 0) {
1926 // no threads
1927 return threads;
1930 bool newFormat = false;
1931 const char* p = output;
1932 while (*p != '\0') {
1933 ThreadInfo thr;
1934 // seach look for thread id, watching out for the focus indicator
1935 thr.hasFocus = false;
1936 while (isspace(*p)) /* may be \n from prev line: see "No stack" below */
1937 p++;
1939 // recent GDBs write a header line; skip it
1940 if (threads.empty() && strncmp(p, "Id Target", 11) == 0) {
1941 p = strchr(p, '\n');
1942 if (p == NULL)
1943 break;
1944 newFormat = true;
1945 continue; // next line please, '\n' is skipped above
1948 if (*p == '*') {
1949 thr.hasFocus = true;
1950 p++;
1951 // there follows only whitespace
1953 const char* end;
1954 char *temp_end = NULL; /* we need a non-const 'end' for strtol to use...*/
1955 thr.id = strtol(p, &temp_end, 10);
1956 end = temp_end;
1957 if (p == end) {
1958 // syntax error: no number found; bail out
1959 return threads;
1961 p = end;
1963 // skip space
1964 while (isspace(*p))
1965 p++;
1968 * Now follows the thread's SYSTAG.
1970 if (!newFormat) {
1971 // In the old format, it is terminated by two blanks.
1972 end = strstr(p, " ");
1973 if (end == 0) {
1974 // syntax error; bail out
1975 return threads;
1977 end += 2;
1978 } else {
1979 // In the new format lies crazyness: there is no definitive
1980 // end marker. At best we can guess when the SYSTAG ends.
1981 // A typical thread list on Linux looks like this:
1983 // Id Target Id Frame
1984 // 2 Thread 0x7ffff7854700 (LWP 10827) "thrserver" 0x00007ffff7928631 in clone () from /lib64/libc.so.6
1985 // * 1 Thread 0x7ffff7fcc700 (LWP 10808) "thrserver" main () at thrserver.c:84
1987 // Looking at GDB's code, the Target Id ends in tokens that
1988 // are bracketed by parentheses or quotes. Therefore,
1989 // we skip (at most) two tokens ('Thread' and the address),
1990 // and then all parts that are in parentheses or quotes.
1991 int n = 0;
1992 end = p;
1993 while (*end) {
1994 if (*end == '"') {
1995 skipString(end);
1996 n = 2;
1997 } else if (*end == '(') {
1998 skipNested(end, '(', ')');
1999 n = 2;
2000 } else if (n < 2) {
2001 while (*end && !isspace(*end))
2002 ++end;
2003 ++n;
2004 } else {
2005 break;
2007 while (isspace(*end))
2008 ++end;
2011 thr.threadName = QString::fromLatin1(p, end-p).trimmed();
2012 p = end;
2015 * Now follows a standard stack frame. Sometimes, however, gdb
2016 * catches a thread at an instant where it doesn't have a stack.
2018 if (strncmp(p, "[No stack.]", 11) != 0) {
2019 ::parseFrameInfo(p, thr.function, thr.fileName, thr.lineNo, thr.address);
2020 } else {
2021 thr.function = "[No stack]";
2022 thr.lineNo = -1;
2023 p += 11; /* \n is skipped above */
2026 threads.push_back(thr);
2028 return threads;
2031 static bool parseNewBreakpoint(const char* o, int& id,
2032 QString& file, int& lineNo, QString& address);
2033 static bool parseNewWatchpoint(const char* o, int& id,
2034 QString& expr);
2036 bool GdbDriver::parseBreakpoint(const char* output, int& id,
2037 QString& file, int& lineNo, QString& address)
2039 const char* o = output;
2040 // skip lines of that begin with "(Cannot find"
2041 while (strncmp(o, "(Cannot find", 12) == 0) {
2042 o = strchr(o, '\n');
2043 if (o == 0)
2044 return false;
2045 o++; /* skip newline */
2048 if (strncmp(o, "Breakpoint ", 11) == 0) {
2049 output += 11; /* skip "Breakpoint " */
2050 return ::parseNewBreakpoint(output, id, file, lineNo, address);
2051 } else if (strncmp(o, "Temporary breakpoint ", 21) == 0) {
2052 output += 21;
2053 return ::parseNewBreakpoint(output, id, file, lineNo, address);
2054 } else if (strncmp(o, "Hardware watchpoint ", 20) == 0) {
2055 output += 20;
2056 return ::parseNewWatchpoint(output, id, address);
2057 } else if (strncmp(o, "Watchpoint ", 11) == 0) {
2058 output += 11;
2059 return ::parseNewWatchpoint(output, id, address);
2061 return false;
2064 static bool parseNewBreakpoint(const char* o, int& id,
2065 QString& file, int& lineNo, QString& address)
2067 // breakpoint id
2068 char* p;
2069 id = strtoul(o, &p, 10);
2070 if (p == o)
2071 return false;
2073 // check for the address
2074 if (strncmp(p, " at 0x", 6) == 0) {
2075 char* start = p+4; /* skip " at ", but not 0x */
2076 p += 6;
2077 while (isxdigit(*p))
2078 ++p;
2079 address = QString::fromLatin1(start, p-start);
2082 // file name
2083 char* fileStart = strstr(p, "file ");
2084 if (fileStart == 0)
2085 return !address.isEmpty(); /* parse error only if there's no address */
2086 fileStart += 5;
2088 // line number
2089 char* numStart = strstr(fileStart, ", line ");
2090 QString fileName = QString::fromLatin1(fileStart, numStart-fileStart);
2091 numStart += 7;
2092 int line = strtoul(numStart, &p, 10);
2093 if (numStart == p)
2094 return false;
2096 file = fileName;
2097 lineNo = line-1; /* zero-based! */
2098 return true;
2101 static bool parseNewWatchpoint(const char* o, int& id,
2102 QString& expr)
2104 // watchpoint id
2105 char* p;
2106 id = strtoul(o, &p, 10);
2107 if (p == o)
2108 return false;
2110 if (strncmp(p, ": ", 2) != 0)
2111 return false;
2112 p += 2;
2114 // all the rest on the line is the expression
2115 expr = QString::fromLatin1(p, strlen(p)).trimmed();
2116 return true;
2119 void GdbDriver::parseLocals(const char* output, std::list<ExprValue*>& newVars)
2121 // check for possible error conditions
2122 if (strncmp(output, "No symbol table", 15) == 0)
2124 return;
2127 while (*output != '\0') {
2128 while (isspace(*output))
2129 output++;
2130 if (*output == '\0')
2131 break;
2132 // skip occurrences of "No locals" and "No args"
2133 if (strncmp(output, "No locals", 9) == 0 ||
2134 strncmp(output, "No arguments", 12) == 0)
2136 output = strchr(output, '\n');
2137 if (output == 0) {
2138 break;
2140 continue;
2143 ExprValue* variable = parseVar(output);
2144 if (variable == 0) {
2145 break;
2147 // do not add duplicates
2148 for (std::list<ExprValue*>::iterator o = newVars.begin(); o != newVars.end(); ++o) {
2149 if ((*o)->m_name == variable->m_name) {
2150 delete variable;
2151 goto skipDuplicate;
2154 newVars.push_back(variable);
2155 skipDuplicate:;
2159 ExprValue* GdbDriver::parsePrintExpr(const char* output, bool wantErrorValue)
2161 ExprValue* var = 0;
2162 // check for error conditions
2163 if (!parseErrorMessage(output, var, wantErrorValue))
2165 // parse the variable
2166 var = parseVar(output);
2168 return var;
2171 bool GdbDriver::parseChangeWD(const char* output, QString& message)
2173 bool isGood = false;
2174 message = QString(output).simplified();
2175 if (message.isEmpty()) {
2176 message = i18n("New working directory: ") + m_programWD;
2177 isGood = true;
2179 return isGood;
2182 bool GdbDriver::parseChangeExecutable(const char* output, QString& message)
2184 message = output;
2186 m_haveCoreFile = false;
2189 * Lines starting with the following do not indicate errors:
2190 * Using host libthread_db
2191 * (no debugging symbols found)
2192 * Reading symbols from
2194 while (strncmp(output, "Reading symbols from", 20) == 0 ||
2195 strncmp(output, "Using host libthread_db", 23) == 0 ||
2196 strncmp(output, "(no debugging symbols found)", 28) == 0)
2198 // this line is good, go to the next one
2199 const char* end = strchr(output, '\n');
2200 if (end == 0)
2201 output += strlen(output);
2202 else
2203 output = end+1;
2207 * If we've parsed all lines, there was no error.
2209 return output[0] == '\0';
2212 bool GdbDriver::parseCoreFile(const char* output)
2214 // if command succeeded, gdb emits a line starting with "#0 "
2215 m_haveCoreFile = strstr(output, "\n#0 ") != 0;
2216 return m_haveCoreFile;
2219 uint GdbDriver::parseProgramStopped(const char* output, QString& message)
2221 // optionally: "program changed, rereading symbols",
2222 // followed by:
2223 // "Program exited normally"
2224 // "Program terminated with wignal SIGSEGV"
2225 // "Program received signal SIGINT" or other signal
2226 // "Breakpoint..."
2227 // GDB since 7.3 prints
2228 // "[Inferior 1 (process 13400) exited normally]"
2229 // "[Inferior 1 (process 14698) exited with code 01]"
2231 // go through the output, line by line, checking what we have
2232 const char* start = output - 1;
2233 uint flags = SFprogramActive;
2234 message = QString();
2235 do {
2236 start++; /* skip '\n' */
2238 if (strncmp(start, "Program ", 8) == 0 ||
2239 strncmp(start, "ptrace: ", 8) == 0) {
2241 * When we receive a signal, the program remains active.
2243 * Special: If we "stopped" in a corefile, the string "Program
2244 * terminated with signal"... is displayed. (Normally, we see
2245 * "Program received signal"... when a signal happens.)
2247 if (strncmp(start, "Program exited", 14) == 0 ||
2248 (strncmp(start, "Program terminated", 18) == 0 && !m_haveCoreFile) ||
2249 strncmp(start, "ptrace: ", 8) == 0)
2251 flags &= ~SFprogramActive;
2254 // set message
2255 const char* endOfMessage = strchr(start, '\n');
2256 if (endOfMessage == 0)
2257 endOfMessage = start + strlen(start);
2258 message = QString::fromLatin1(start, endOfMessage-start);
2259 } else if (strncmp(start, "[Inferior ", 10) == 0) {
2260 const char* p = start + 10;
2261 // skip number and space
2262 while (*p && !isspace(*p))
2263 ++p;
2264 while (isspace(*p))
2265 ++p;
2266 if (*p == '(') {
2267 skipNested(p, '(', ')');
2268 if (strncmp(p, " exited ", 8) == 0) {
2269 flags &= ~SFprogramActive;
2271 // set message
2272 const char* end = strchr(p, '\n');
2273 if (end == 0)
2274 end = p + strlen(p);
2275 // strip [] from the message
2276 message = QString::fromLatin1(start+1, end-start-2);
2279 } else if (strncmp(start, "Breakpoint ", 11) == 0) {
2281 * We stopped at a (permanent) breakpoint (gdb doesn't tell us
2282 * that it stopped at a temporary breakpoint).
2284 flags |= SFrefreshBreak;
2285 } else if (strstr(start, "re-reading symbols.") != 0) {
2286 flags |= SFrefreshSource;
2289 // next line, please
2290 start = strchr(start, '\n');
2291 } while (start != 0);
2294 * Gdb only notices when new threads have appeared, but not when a
2295 * thread finishes. So we always have to assume that the list of
2296 * threads has changed.
2298 flags |= SFrefreshThreads;
2300 return flags;
2303 QStringList GdbDriver::parseSharedLibs(const char* output)
2305 QStringList shlibs;
2306 if (strncmp(output, "No shared libraries loaded", 26) == 0)
2307 return shlibs;
2309 // parse the table of shared libraries
2311 // strip off head line
2312 output = strchr(output, '\n');
2313 if (output == 0)
2314 return shlibs;
2315 output++; /* skip '\n' */
2316 QString shlibName;
2317 while (*output != '\0') {
2318 // format of a line is
2319 // 0x404c5000 0x40580d90 Yes /lib/libc.so.5
2320 // 3 blocks of non-space followed by space
2321 for (int i = 0; *output != '\0' && i < 3; i++) {
2322 while (*output != '\0' && !isspace(*output)) { /* non-space */
2323 output++;
2325 while (isspace(*output)) { /* space */
2326 output++;
2329 if (*output == '\0')
2330 return shlibs;
2331 const char* start = output;
2332 output = strchr(output, '\n');
2333 if (output == 0)
2334 output = start + strlen(start);
2335 shlibName = QString::fromLatin1(start, output-start);
2336 if (*output != '\0')
2337 output++;
2338 shlibs.append(shlibName);
2339 TRACE("found shared lib " + shlibName);
2341 return shlibs;
2344 bool GdbDriver::parseFindType(const char* output, QString& type)
2346 if (strncmp(output, "type = ", 7) != 0)
2347 return false;
2350 * Everything else is the type. We strip off any leading "const" and any
2351 * trailing "&" on the grounds that neither affects the decoding of the
2352 * object. We also strip off all white-space from the type.
2354 output += 7;
2355 if (strncmp(output, "const ", 6) == 0)
2356 output += 6;
2357 type = output;
2358 type.replace(QRegExp("\\s+"), "");
2359 if (type.endsWith("&"))
2360 type.truncate(type.length() - 1);
2361 return true;
2364 std::list<RegisterInfo> GdbDriver::parseRegisters(const char* output)
2366 std::list<RegisterInfo> regs;
2367 if (strncmp(output, "The program has no registers now", 32) == 0) {
2368 return regs;
2371 // parse register values
2372 while (*output != '\0')
2374 RegisterInfo reg;
2375 // skip space at the start of the line
2376 while (isspace(*output))
2377 output++;
2379 // register name
2380 const char* start = output;
2381 while (*output != '\0' && !isspace(*output))
2382 output++;
2383 if (*output == '\0')
2384 break;
2385 reg.regName = QString::fromLatin1(start, output-start);
2387 // skip space
2388 while (isspace(*output))
2389 output++;
2391 QString value;
2394 * If we find a brace now, this is a vector register. We look for
2395 * the closing brace and treat the result as cooked value.
2397 if (*output == '{')
2399 start = output;
2400 skipNested(output, '{', '}');
2401 value = QString::fromLatin1(start, output-start).simplified();
2402 // skip space, but not the end of line
2403 while (isspace(*output) && *output != '\n')
2404 output++;
2405 // get rid of the braces at the begining and the end
2406 value.remove(0, 1);
2407 if (value[value.length()-1] == '}') {
2408 value = value.left(value.length()-1);
2410 // gdb 5.3 doesn't print a separate set of raw values
2411 if (*output == '{') {
2412 // another set of vector follows
2413 // what we have so far is the raw value
2414 reg.rawValue = value;
2416 start = output;
2417 skipNested(output, '{', '}');
2418 value = QString::fromLatin1(start, output-start).simplified();
2419 } else {
2420 // for gdb 5.3
2421 // find first type that does not have an array, this is the RAW value
2422 const char* end=start;
2423 findEnd(end);
2424 const char* cur=start;
2425 while (cur<end) {
2426 while (*cur != '=' && cur<end)
2427 cur++;
2428 cur++;
2429 while (isspace(*cur) && cur<end)
2430 cur++;
2431 if (isNumberish(*cur)) {
2432 end=cur;
2433 while (*end && (*end!='}') && (*end!=',') && (*end!='\n'))
2434 end++;
2435 QString rawValue = QString::fromLatin1(cur, end-cur).simplified();
2436 reg.rawValue = rawValue;
2438 if (rawValue.left(2)=="0x") {
2439 // ok we have a raw value, now get it's type
2440 end=cur-1;
2441 while (isspace(*end) || *end=='=') end--;
2442 end++;
2443 cur=end-1;
2444 while (*cur!='{' && *cur!=' ')
2445 cur--;
2446 cur++;
2447 reg.type = QString::fromLatin1(cur, end-cur);
2450 // end while loop
2451 cur=end;
2454 // skip to the end of line
2455 while (*output != '\0' && *output != '\n')
2456 output++;
2457 // get rid of the braces at the begining and the end
2458 value.remove(0, 1);
2459 if (value[value.length()-1] == '}') {
2460 value.truncate(value.length()-1);
2463 reg.cookedValue = value;
2465 else
2467 continuation:
2468 // the rest of the line is the register value
2469 start = output;
2470 output = strchr(output,'\n');
2471 if (output == 0)
2472 output = start + strlen(start);
2473 value += QString::fromLatin1(start, output-start).simplified();
2476 * Look ahead: if the subsequent line is indented, it continues
2477 * the current register value.
2479 if (output != 0 && isspace(output[1]))
2481 ++output;
2482 value += ' ';
2483 goto continuation;
2487 * We split the raw from the cooked values.
2488 * Some modern gdbs explicitly say: "0.1234 (raw 0x3e4567...)".
2489 * Here, the cooked value comes first, and the raw value is in
2490 * the second part.
2492 int pos = value.indexOf(" (raw ");
2493 if (pos >= 0)
2495 reg.cookedValue = value.left(pos);
2496 reg.rawValue = value.mid(pos+6);
2497 if (reg.rawValue.right(1) == ")") // remove closing bracket
2498 reg.rawValue.truncate(reg.rawValue.length()-1);
2500 else
2503 * In other cases we split off the first token (separated by
2504 * whitespace). It is the raw value. The remainder of the line
2505 * is the cooked value.
2507 int pos = value.indexOf(' ');
2508 if (pos < 0) {
2509 reg.rawValue = value;
2510 reg.cookedValue = QString();
2511 } else {
2512 reg.rawValue = value.left(pos);
2513 reg.cookedValue = value.mid(pos+1);
2517 if (*output != '\0')
2518 output++; /* skip '\n' */
2520 regs.push_back(reg);
2522 return regs;
2525 bool GdbDriver::parseInfoLine(const char* output, QString& addrFrom, QString& addrTo)
2527 // "is at address" or "starts at address"
2528 const char* start = strstr(output, "s at address ");
2529 if (start == 0)
2530 return false;
2532 start += 13;
2533 const char* p = start;
2534 while (*p != '\0' && !isspace(*p))
2535 p++;
2536 addrFrom = QString::fromLatin1(start, p-start);
2538 start = strstr(p, "and ends at ");
2539 if (start == 0) {
2540 addrTo = addrFrom;
2541 return true;
2544 start += 12;
2545 p = start;
2546 while (*p != '\0' && !isspace(*p))
2547 p++;
2548 addrTo = QString::fromLatin1(start, p-start);
2550 return true;
2553 std::list<DisassembledCode> GdbDriver::parseDisassemble(const char* output)
2555 std::list<DisassembledCode> code;
2557 if (strncmp(output, "Dump of assembler", 17) != 0) {
2558 // error message?
2559 DisassembledCode c;
2560 c.code = output;
2561 code.push_back(c);
2562 return code;
2565 // remove first line
2566 const char* p = strchr(output, '\n');
2567 if (p == 0)
2568 return code; /* not a regular output */
2570 p++;
2572 // remove last line
2573 const char* end = strstr(output, "End of assembler");
2574 if (end == 0)
2575 end = p + strlen(p);
2577 // remove function offsets from the lines
2578 while (p != end)
2580 DisassembledCode c;
2581 // skip initial space or PC pointer ("=>", since gdb 7.1)
2582 while (p != end) {
2583 if (isspace(*p))
2584 ++p;
2585 else if (p[0] == '=' && p[1] == '>')
2586 p += 2;
2587 else
2588 break;
2590 const char* start = p;
2591 // address
2592 while (p != end && !isspace(*p))
2593 p++;
2594 c.address = QString::fromLatin1(start, p-start);
2596 // function name (enclosed in '<>', followed by ':')
2597 while (p != end && *p != '<')
2598 p++;
2599 if (*p == '<')
2600 skipNestedAngles(p);
2601 if (*p == ':')
2602 p++;
2604 // space until code
2605 while (p != end && isspace(*p))
2606 p++;
2608 // code until end of line
2609 start = p;
2610 while (p != end && *p != '\n')
2611 p++;
2612 if (p != end) /* include '\n' */
2613 p++;
2615 c.code = QString::fromLatin1(start, p-start);
2616 code.push_back(c);
2618 return code;
2621 QString GdbDriver::parseMemoryDump(const char* output, std::list<MemoryDump>& memdump)
2623 if (isErrorExpr(output)) {
2624 // error; strip space
2625 QString msg = output;
2626 return msg.trimmed();
2629 const char* p = output; /* save typing */
2631 // the address
2632 while (*p != 0) {
2633 MemoryDump md;
2635 const char* start = p;
2636 while (*p != '\0' && *p != ':' && !isspace(*p))
2637 p++;
2638 md.address = QString::fromLatin1(start, p-start);
2639 if (*p != ':') {
2640 // parse function offset
2641 while (isspace(*p))
2642 p++;
2643 start = p;
2644 while (*p != '\0' && !(*p == ':' && isspace(p[1])))
2645 p++;
2646 md.address.fnoffs = QString::fromLatin1(start, p-start);
2648 if (*p == ':')
2649 p++;
2650 // skip space; this may skip a new-line char!
2651 while (isspace(*p))
2652 p++;
2653 // everything to the end of the line is the memory dump
2654 const char* end = strchr(p, '\n');
2655 if (end != 0) {
2656 md.dump = QString::fromLatin1(p, end-p);
2657 p = end+1;
2658 } else {
2659 md.dump = QString::fromLatin1(p, strlen(p));
2660 p += strlen(p);
2662 memdump.push_back(md);
2665 return QString();
2668 QString GdbDriver::editableValue(VarTree* value)
2670 QByteArray ba = value->value().toLatin1();
2671 const char* s = ba.constData();
2673 // if the variable is a pointer value that contains a cast,
2674 // remove the cast
2675 if (*s == '(') {
2676 skipNested(s, '(', ')');
2677 // skip space
2678 while (isspace(*s))
2679 ++s;
2682 repeat:
2683 const char* start = s;
2685 if (strncmp(s, "0x", 2) == 0)
2687 s += 2;
2688 while (isxdigit(*s))
2689 ++s;
2692 * What we saw so far might have been a reference. If so, edit the
2693 * referenced value. Otherwise, edit the pointer.
2695 if (*s == ':') {
2696 // a reference
2697 ++s;
2698 goto repeat;
2700 // a pointer
2701 // if it's a pointer to a string, remove the string
2702 const char* end = s;
2703 while (isspace(*s))
2704 ++s;
2705 if (*s == '"') {
2706 // a string
2707 return QString::fromLatin1(start, end-start);
2708 } else {
2709 // other pointer
2710 return QString::fromLatin1(start, strlen(start));
2714 // else leave it unchanged (or stripped of the reference preamble)
2715 return s;
2718 QString GdbDriver::parseSetVariable(const char* output)
2720 // if there is any output, it is an error message
2721 QString msg = output;
2722 return msg.trimmed();
2726 #include "gdbdriver.moc"