Upgraded the build system for KDE2.
[kdbg.git] / kdbg / gdbdriver.cpp
blob443558ae16ce202a00d8bfbcee341e439798b570
1 // $Id$
3 // Copyright by Johannes Sixt
4 // This file is under GPL, the GNU General Public Licence
6 #include "gdbdriver.h"
7 #include "exprwnd.h"
8 #include <qregexp.h>
9 #if QT_VERSION >= 200
10 #include <klocale.h> /* i18n */
11 #else
12 #include <kapp.h>
13 #endif
14 #include <ctype.h>
15 #include <stdlib.h> /* strtol, atoi */
16 #include <string.h> /* strcpy */
18 #include "assert.h"
19 #ifdef HAVE_CONFIG_H
20 #include "config.h"
21 #endif
22 #include "mydebug.h"
24 static void skipString(const char*& p);
25 static void skipNested(const char*& s, char opening, char closing);
26 static VarTree* parseVar(const char*& s);
27 static bool parseName(const char*& s, QString& name, VarTree::NameKind& kind);
28 static bool parseValue(const char*& s, VarTree* variable);
29 static bool parseNested(const char*& s, VarTree* variable);
30 static bool parseVarSeq(const char*& s, VarTree* variable);
31 static bool parseValueSeq(const char*& s, VarTree* variable);
33 #define PROMPT "(kdbg)"
34 #define PROMPT_LEN 6
35 #define PROMPT_LAST_CHAR ')' /* needed when searching for prompt string */
38 // TODO: make this cmd info stuff non-static to allow multiple
39 // simultaneous gdbs to run!
41 struct GdbCmdInfo {
42 DbgCommand cmd;
43 const char* fmt; /* format string */
44 enum Args {
45 argNone, argString, argNum,
46 argStringNum, argNumString,
47 argString2, argNum2
48 } argsNeeded;
51 static const char printQStringStructFmt[] =
52 // if the string data is junk, fail early
53 "print ($qstrunicode=($qstrdata=(%s))->unicode)?"
54 // print an array of shorts
55 "(*(unsigned short*)$qstrunicode)@"
56 // limit the length
57 "(($qstrlen=(unsigned int)($qstrdata->len))>100?100:$qstrlen)"
58 // if unicode data is 0, check if it is QString::null
59 ":($qstrdata==QString::null.d)\n";
61 // However, gdb can't always find QString::null (I don't know why)
62 // which results in an error; we autodetect this situation in
63 // parseQt2QStrings and revert to a safe expression.
64 // Same as above except for last line:
65 static const char printQStringStructNoNullFmt[] =
66 "print ($qstrunicode=($qstrdata=(%s))->unicode)?"
67 "(*(unsigned short*)$qstrunicode)@"
68 "(($qstrlen=(unsigned int)($qstrdata->len))>100?100:$qstrlen)"
69 ":1==0\n";
72 * The following array of commands must be sorted by the DC* values,
73 * because they are used as indices.
75 static GdbCmdInfo cmds[] = {
76 { DCinitialize, "", GdbCmdInfo::argNone },
77 { DCtty, "tty %s\n", GdbCmdInfo::argString },
78 { DCexecutable, "file \"%s\"\n", GdbCmdInfo::argString },
79 { DCtargetremote, "target remote %s\n", GdbCmdInfo::argString },
80 { DCcorefile, "core-file %s\n", GdbCmdInfo::argString },
81 { DCattach, "attach %s\n", GdbCmdInfo::argString },
82 { DCinfolinemain, "info line main\n", GdbCmdInfo::argNone },
83 { DCinfolocals, "kdbg__alllocals\n", GdbCmdInfo::argNone },
84 { DCinforegisters, "info all-registers\n", GdbCmdInfo::argNone},
85 { DCexamine, "x %s %s\n", GdbCmdInfo::argString2 },
86 { DCinfoline, "info line %s:%d\n", GdbCmdInfo::argStringNum },
87 { DCdisassemble, "disassemble %s %s\n", GdbCmdInfo::argString2 },
88 { DCsetargs, "set args %s\n", GdbCmdInfo::argString },
89 { DCsetenv, "set env %s %s\n", GdbCmdInfo::argString2 },
90 { DCunsetenv, "unset env %s\n", GdbCmdInfo::argString },
91 { DCcd, "cd %s\n", GdbCmdInfo::argString },
92 { DCbt, "bt\n", GdbCmdInfo::argNone },
93 { DCrun, "run\n", GdbCmdInfo::argNone },
94 { DCcont, "cont\n", GdbCmdInfo::argNone },
95 { DCstep, "step\n", GdbCmdInfo::argNone },
96 { DCstepi, "stepi\n", GdbCmdInfo::argNone },
97 { DCnext, "next\n", GdbCmdInfo::argNone },
98 { DCnexti, "nexti\n", GdbCmdInfo::argNone },
99 { DCfinish, "finish\n", GdbCmdInfo::argNone },
100 { DCuntil, "until %s:%d\n", GdbCmdInfo::argStringNum },
101 { DCkill, "kill\n", GdbCmdInfo::argNone },
102 { DCbreaktext, "break %s\n", GdbCmdInfo::argString },
103 { DCbreakline, "break %s:%d\n", GdbCmdInfo::argStringNum },
104 { DCtbreakline, "tbreak %s:%d\n", GdbCmdInfo::argStringNum },
105 { DCbreakaddr, "break *%s\n", GdbCmdInfo::argString },
106 { DCtbreakaddr, "tbreak *%s\n", GdbCmdInfo::argString },
107 { DCwatchpoint, "watch %s\n", GdbCmdInfo::argString },
108 { DCdelete, "delete %d\n", GdbCmdInfo::argNum },
109 { DCenable, "enable %d\n", GdbCmdInfo::argNum },
110 { DCdisable, "disable %d\n", GdbCmdInfo::argNum },
111 { DCprint, "print %s\n", GdbCmdInfo::argString },
112 { DCprintStruct, "print %s\n", GdbCmdInfo::argString },
113 { DCprintQStringStruct, printQStringStructFmt, GdbCmdInfo::argString},
114 { DCframe, "frame %d\n", GdbCmdInfo::argNum },
115 { DCfindType, "whatis %s\n", GdbCmdInfo::argString },
116 { DCinfosharedlib, "info sharedlibrary\n", GdbCmdInfo::argNone },
117 { DCthread, "thread %d\n", GdbCmdInfo::argNum },
118 { DCinfothreads, "info threads\n", GdbCmdInfo::argNone },
119 { DCinfobreak, "info breakpoints\n", GdbCmdInfo::argNone },
120 { DCcondition, "condition %d %s\n", GdbCmdInfo::argNumString},
121 { DCignore, "ignore %d %d\n", GdbCmdInfo::argNum2},
124 #define NUM_CMDS (int(sizeof(cmds)/sizeof(cmds[0])))
125 #define MAX_FMTLEN 200
127 GdbDriver::GdbDriver() :
128 DebuggerDriver(),
129 m_gdbMajor(4), m_gdbMinor(16)
131 strcpy(m_prompt, PROMPT);
132 m_promptLen = PROMPT_LEN;
133 m_promptLastChar = PROMPT_LAST_CHAR;
135 #ifndef NDEBUG
136 // check command info array
137 char* perc;
138 for (int i = 0; i < NUM_CMDS; i++) {
139 // must be indexable by DbgCommand values, i.e. sorted by DbgCommand values
140 assert(i == cmds[i].cmd);
141 // a format string must be associated
142 assert(cmds[i].fmt != 0);
143 assert(strlen(cmds[i].fmt) <= MAX_FMTLEN);
144 // format string must match arg specification
145 switch (cmds[i].argsNeeded) {
146 case GdbCmdInfo::argNone:
147 assert(strchr(cmds[i].fmt, '%') == 0);
148 break;
149 case GdbCmdInfo::argString:
150 perc = strchr(cmds[i].fmt, '%');
151 assert(perc != 0 && perc[1] == 's');
152 assert(strchr(perc+2, '%') == 0);
153 break;
154 case GdbCmdInfo::argNum:
155 perc = strchr(cmds[i].fmt, '%');
156 assert(perc != 0 && perc[1] == 'd');
157 assert(strchr(perc+2, '%') == 0);
158 break;
159 case GdbCmdInfo::argStringNum:
160 perc = strchr(cmds[i].fmt, '%');
161 assert(perc != 0 && perc[1] == 's');
162 perc = strchr(perc+2, '%');
163 assert(perc != 0 && perc[1] == 'd');
164 assert(strchr(perc+2, '%') == 0);
165 break;
166 case GdbCmdInfo::argNumString:
167 perc = strchr(cmds[i].fmt, '%');
168 assert(perc != 0 && perc[1] == 'd');
169 perc = strchr(perc+2, '%');
170 assert(perc != 0 && perc[1] == 's');
171 assert(strchr(perc+2, '%') == 0);
172 break;
173 case GdbCmdInfo::argString2:
174 perc = strchr(cmds[i].fmt, '%');
175 assert(perc != 0 && perc[1] == 's');
176 perc = strchr(perc+2, '%');
177 assert(perc != 0 && perc[1] == 's');
178 assert(strchr(perc+2, '%') == 0);
179 break;
180 case GdbCmdInfo::argNum2:
181 perc = strchr(cmds[i].fmt, '%');
182 assert(perc != 0 && perc[1] == 'd');
183 perc = strchr(perc+2, '%');
184 assert(perc != 0 && perc[1] == 'd');
185 assert(strchr(perc+2, '%') == 0);
186 break;
189 assert(strlen(printQStringStructFmt) <= MAX_FMTLEN);
190 assert(strlen(printQStringStructNoNullFmt) <= MAX_FMTLEN);
191 #endif
194 GdbDriver::~GdbDriver()
199 QString GdbDriver::driverName() const
201 return "GDB";
204 QString GdbDriver::defaultGdb()
206 return
207 "gdb"
208 " --fullname" /* to get standard file names each time the prog stops */
209 " --nx"; /* do not execute initialization files */
212 QString GdbDriver::defaultInvocation() const
214 return defaultGdb();
217 bool GdbDriver::startup(QString cmdStr)
219 if (!DebuggerDriver::startup(cmdStr))
220 return false;
222 static const char gdbInitialize[] =
224 * Work around buggy gdbs that do command line editing even if they
225 * are not on a tty. The readline library echos every command back
226 * in this case, which is confusing for us.
228 "set editing off\n"
229 "set confirm off\n"
230 "set print static-members off\n"
231 "set print asm-demangle on\n"
233 * Write a short macro that prints all locals: local variables and
234 * function arguments.
236 "define kdbg__alllocals\n"
237 "info locals\n" /* local vars supersede args with same name */
238 "info args\n" /* therefore, arguments must come last */
239 "end\n"
240 // change prompt string and synchronize with gdb
241 "set prompt " PROMPT "\n"
244 executeCmdString(DCinitialize, gdbInitialize, false);
246 // assume that QString::null is ok
247 cmds[DCprintQStringStruct].fmt = printQStringStructFmt;
249 return true;
252 void GdbDriver::commandFinished(CmdQueueItem* cmd)
254 // command string must be committed
255 if (!cmd->m_committed) {
256 // not commited!
257 TRACE("calling " + (__PRETTY_FUNCTION__ + (" with uncommited command:\n\t" +
258 cmd->m_cmdString)));
259 return;
262 switch (cmd->m_cmd) {
263 case DCinitialize:
264 // get version number from preamble
266 int len;
267 QRegExp GDBVersion("\\nGDB [0-9]+\\.[0-9]+");
268 int offset = GDBVersion.match(m_output, 0, &len);
269 if (offset >= 0) {
270 char* start = m_output + offset + 5; // skip "\nGDB "
271 char* end;
272 m_gdbMajor = strtol(start, &end, 10);
273 m_gdbMinor = strtol(end + 1, 0, 10); // skip "."
274 if (start == end) {
275 // nothing was parsed
276 m_gdbMajor = 4;
277 m_gdbMinor = 16;
279 } else {
280 // assume some default version (what would make sense?)
281 m_gdbMajor = 4;
282 m_gdbMinor = 16;
284 // use a feasible core-file command
285 if (m_gdbMajor > 4 || (m_gdbMajor == 4 && m_gdbMinor >= 16)) {
286 cmds[DCcorefile].fmt = "target core %s\n";
287 } else {
288 cmds[DCcorefile].fmt = "core-file %s\n";
291 break;
292 default:;
295 /* ok, the command is ready */
296 emit commandReceived(cmd, m_output);
298 switch (cmd->m_cmd) {
299 case DCcorefile:
300 case DCinfolinemain:
301 case DCframe:
302 case DCattach:
303 case DCrun:
304 case DCcont:
305 case DCstep:
306 case DCstepi:
307 case DCnext:
308 case DCnexti:
309 case DCfinish:
310 case DCuntil:
311 parseMarker();
312 default:;
317 * The --fullname option makes gdb send a special normalized sequence print
318 * each time the program stops and at some other points. The sequence has
319 * the form "\032\032filename:lineno:charoffset:(beg|middle):address".
321 void GdbDriver::parseMarker()
323 char* startMarker = strstr(m_output, "\032\032");
324 if (startMarker == 0)
325 return;
327 // extract the marker
328 startMarker += 2;
329 TRACE(QString("found marker: ") + startMarker);
330 char* endMarker = strchr(startMarker, '\n');
331 if (endMarker == 0)
332 return;
334 *endMarker = '\0';
336 // extract filename and line number
337 static QRegExp MarkerRE(":[0-9]+:[0-9]+:[begmidl]+:0x");
339 int len;
340 int lineNoStart = MarkerRE.match(startMarker, 0, &len);
341 if (lineNoStart >= 0) {
342 int lineNo = atoi(startMarker + lineNoStart+1);
344 // get address
345 const char* addrStart = startMarker + lineNoStart + len - 2;
346 DbgAddr address = QString(addrStart).stripWhiteSpace();
348 // now show the window
349 startMarker[lineNoStart] = '\0'; /* split off file name */
350 emit activateFileLine(startMarker, lineNo-1, address);
356 * Escapes characters that might lead to problems when they appear on gdb's
357 * command line.
359 static void normalizeStringArg(QString& arg)
362 * Remove trailing backslashes. This approach is a little simplistic,
363 * but we know that there is at the moment no case where a trailing
364 * backslash would make sense.
366 while (!arg.isEmpty() && arg[arg.length()-1] == '\\') {
367 arg = arg.left(arg.length()-1);
372 #if QT_VERSION < 200
373 #define LATIN1(str) ((str).isNull() ? "" : (str).data())
374 #else
375 #define LATIN1(str) (str).latin1()
376 #endif
378 QString GdbDriver::makeCmdString(DbgCommand cmd, QString strArg)
380 assert(cmd >= 0 && cmd < NUM_CMDS);
381 assert(cmds[cmd].argsNeeded == GdbCmdInfo::argString);
383 normalizeStringArg(strArg);
385 if (cmd == DCcd) {
386 // need the working directory when parsing the output
387 m_programWD = strArg;
388 } else if (cmd == DCsetargs) {
389 // attach saved redirection
390 #if QT_VERSION < 200
391 strArg.detach();
392 #endif
393 strArg += m_redirect;
396 SIZED_QString(cmdString, MAX_FMTLEN+strArg.length());
397 cmdString.sprintf(cmds[cmd].fmt, LATIN1(strArg));
398 return cmdString;
401 QString GdbDriver::makeCmdString(DbgCommand cmd, int intArg)
403 assert(cmd >= 0 && cmd < NUM_CMDS);
404 assert(cmds[cmd].argsNeeded == GdbCmdInfo::argNum);
406 SIZED_QString(cmdString, MAX_FMTLEN+30);
408 cmdString.sprintf(cmds[cmd].fmt, intArg);
409 return cmdString;
412 QString GdbDriver::makeCmdString(DbgCommand cmd, QString strArg, int intArg)
414 assert(cmd >= 0 && cmd < NUM_CMDS);
415 assert(cmds[cmd].argsNeeded == GdbCmdInfo::argStringNum ||
416 cmds[cmd].argsNeeded == GdbCmdInfo::argNumString ||
417 cmd == DCexamine ||
418 cmd == DCtty);
420 normalizeStringArg(strArg);
422 SIZED_QString(cmdString, MAX_FMTLEN+30+strArg.length());
424 if (cmd == DCtty)
427 * intArg specifies which channels should be redirected to
428 * /dev/null. It is a value or'ed together from RDNstdin,
429 * RDNstdout, RDNstderr. We store the value for a later DCsetargs
430 * command.
432 * Note: We rely on that after the DCtty a DCsetargs will follow,
433 * which will ultimately apply the redirection.
435 static const char* const runRedir[8] = {
437 " </dev/null",
438 " >/dev/null",
439 " </dev/null >/dev/null",
440 " 2>/dev/null",
441 " </dev/null 2>/dev/null",
442 " >/dev/null 2>&1",
443 " </dev/null >/dev/null 2>&1"
445 if (strArg.isEmpty())
446 intArg = 7; /* failsafe if no tty */
447 m_redirect = runRedir[intArg & 7];
449 return makeCmdString(DCtty, strArg); /* note: no problem if strArg empty */
452 if (cmd == DCexamine) {
453 // make a format specifier from the intArg
454 static const char size[16] = {
455 '\0', 'b', 'h', 'w', 'g'
457 static const char format[16] = {
458 '\0', 'x', 'd', 'u', 'o', 't',
459 'a', 'c', 'f', 's', 'i'
461 assert(MDTsizemask == 0xf); /* lowest 4 bits */
462 assert(MDTformatmask == 0xf0); /* next 4 bits */
463 int count = 16; /* number of entities to print */
464 char sizeSpec = size[intArg & MDTsizemask];
465 char formatSpec = format[(intArg & MDTformatmask) >> 4];
466 assert(sizeSpec != '\0');
467 assert(formatSpec != '\0');
468 // adjust count such that 16 lines are printed
469 switch (intArg & MDTformatmask) {
470 case MDTstring: case MDTinsn:
471 break; /* no modification needed */
472 default:
473 // all cases drop through:
474 switch (intArg & MDTsizemask) {
475 case MDTbyte:
476 case MDThalfword:
477 count *= 2;
478 case MDTword:
479 count *= 2;
480 case MDTgiantword:
481 count *= 2;
483 break;
485 QString spec;
486 spec.sprintf("/%d%c%c", count, sizeSpec, formatSpec);
488 return makeCmdString(DCexamine, spec, strArg);
491 if (cmds[cmd].argsNeeded == GdbCmdInfo::argStringNum)
493 // line numbers are zero-based
494 if (cmd == DCuntil || cmd == DCbreakline ||
495 cmd == DCtbreakline || cmd == DCinfoline)
497 intArg++;
499 if (cmd == DCinfoline)
501 // must split off file name part
502 int slash = strArg.findRev('/');
503 if (slash >= 0)
504 strArg = strArg.right(strArg.length()-slash-1);
506 cmdString.sprintf(cmds[cmd].fmt, LATIN1(strArg), intArg);
508 else
510 cmdString.sprintf(cmds[cmd].fmt, intArg, LATIN1(strArg));
512 return cmdString;
515 QString GdbDriver::makeCmdString(DbgCommand cmd, QString strArg1, QString strArg2)
517 assert(cmd >= 0 && cmd < NUM_CMDS);
518 assert(cmds[cmd].argsNeeded == GdbCmdInfo::argString2);
520 normalizeStringArg(strArg1);
521 normalizeStringArg(strArg2);
523 SIZED_QString(cmdString, MAX_FMTLEN+strArg1.length()+strArg2.length());
524 cmdString.sprintf(cmds[cmd].fmt, LATIN1(strArg1), LATIN1(strArg2));
525 return cmdString;
528 QString GdbDriver::makeCmdString(DbgCommand cmd, int intArg1, int intArg2)
530 assert(cmd >= 0 && cmd < NUM_CMDS);
531 assert(cmds[cmd].argsNeeded == GdbCmdInfo::argNum2);
533 SIZED_QString(cmdString, MAX_FMTLEN+60);
534 cmdString.sprintf(cmds[cmd].fmt, intArg1, intArg2);
535 return cmdString;
538 CmdQueueItem* GdbDriver::executeCmd(DbgCommand cmd, bool clearLow)
540 assert(cmd >= 0 && cmd < NUM_CMDS);
541 assert(cmds[cmd].argsNeeded == GdbCmdInfo::argNone);
543 if (cmd == DCrun) {
544 m_haveCoreFile = false;
547 return executeCmdString(cmd, cmds[cmd].fmt, clearLow);
550 CmdQueueItem* GdbDriver::executeCmd(DbgCommand cmd, QString strArg,
551 bool clearLow)
553 return executeCmdString(cmd, makeCmdString(cmd, strArg), clearLow);
556 CmdQueueItem* GdbDriver::executeCmd(DbgCommand cmd, int intArg,
557 bool clearLow)
560 return executeCmdString(cmd, makeCmdString(cmd, intArg), clearLow);
563 CmdQueueItem* GdbDriver::executeCmd(DbgCommand cmd, QString strArg, int intArg,
564 bool clearLow)
566 return executeCmdString(cmd, makeCmdString(cmd, strArg, intArg), clearLow);
569 CmdQueueItem* GdbDriver::executeCmd(DbgCommand cmd, QString strArg1, QString strArg2,
570 bool clearLow)
572 return executeCmdString(cmd, makeCmdString(cmd, strArg1, strArg2), clearLow);
575 CmdQueueItem* GdbDriver::executeCmd(DbgCommand cmd, int intArg1, int intArg2,
576 bool clearLow)
578 return executeCmdString(cmd, makeCmdString(cmd, intArg1, intArg2), clearLow);
581 CmdQueueItem* GdbDriver::queueCmd(DbgCommand cmd, QueueMode mode)
583 return queueCmdString(cmd, cmds[cmd].fmt, mode);
586 CmdQueueItem* GdbDriver::queueCmd(DbgCommand cmd, QString strArg,
587 QueueMode mode)
589 return queueCmdString(cmd, makeCmdString(cmd, strArg), mode);
592 CmdQueueItem* GdbDriver::queueCmd(DbgCommand cmd, int intArg,
593 QueueMode mode)
595 return queueCmdString(cmd, makeCmdString(cmd, intArg), mode);
598 CmdQueueItem* GdbDriver::queueCmd(DbgCommand cmd, QString strArg, int intArg,
599 QueueMode mode)
601 return queueCmdString(cmd, makeCmdString(cmd, strArg, intArg), mode);
604 CmdQueueItem* GdbDriver::queueCmd(DbgCommand cmd, QString strArg1, QString strArg2,
605 QueueMode mode)
607 return queueCmdString(cmd, makeCmdString(cmd, strArg1, strArg2), mode);
610 void GdbDriver::terminate()
612 kill(SIGTERM);
613 m_state = DSidle;
616 void GdbDriver::detachAndTerminate()
618 kill(SIGINT);
619 flushCommands();
620 executeCmdString(DCinitialize, "detach\nquit\n", true);
623 void GdbDriver::interruptInferior()
625 kill(SIGINT);
626 // remove accidentally queued commands
627 flushHiPriQueue();
630 static bool isErrorExpr(const char* output)
632 return
633 strncmp(output, "Cannot access memory at", 23) == 0 ||
634 strncmp(output, "Attempt to dereference a generic pointer", 40) == 0 ||
635 strncmp(output, "Attempt to take contents of ", 28) == 0 ||
636 strncmp(output, "Attempt to use a type name as an expression", 43) == 0 ||
637 strncmp(output, "There is no member or method named", 34) == 0 ||
638 strncmp(output, "No symbol \"", 11) == 0 ||
639 strncmp(output, "Internal error: ", 16) == 0;
643 * Returns true if the output is an error message. If wantErrorValue is
644 * true, a new VarTree object is created and filled with the error message.
646 static bool parseErrorMessage(const char* output,
647 VarTree*& variable, bool wantErrorValue)
649 if (isErrorExpr(output))
651 if (wantErrorValue) {
652 // put the error message as value in the variable
653 variable = new VarTree(QString(), VarTree::NKplain);
654 const char* endMsg = strchr(output, '\n');
655 if (endMsg == 0)
656 endMsg = output + strlen(output);
657 variable->m_value = FROM_LATIN1(output, endMsg-output);
658 } else {
659 variable = 0;
661 return true;
663 return false;
666 #if QT_VERSION < 200
667 struct QChar {
668 // this is the XChar2b on X11
669 uchar row;
670 uchar cell;
671 static QString toQString(QChar* unicode, int len);
672 QChar() : row(0), cell(0) { }
673 QChar(char c) : row(0), cell(c) { }
674 operator char() const { return row ? 0 : cell; }
677 QString QChar::toQString(QChar* unicode, int len)
679 QString result(len+1);
680 char* data = result.data();
681 data[len] = '\0';
682 while (len >= 0) {
683 data[len] = unicode[len].cell;
684 --len;
686 return result;
688 #endif
690 VarTree* GdbDriver::parseQCharArray(const char* output, bool wantErrorValue)
692 VarTree* variable = 0;
695 * Parse off white space. gdb sometimes prints white space first if the
696 * printed array leaded to an error.
698 const char* p = output;
699 while (isspace(*p))
700 p++;
702 // check if this is an error indicating that gdb does not know about QString::null
703 if (cmds[DCprintQStringStruct].fmt == printQStringStructFmt &&
704 strncmp(p, "Internal error: could not find static variable null", 51) == 0)
706 /* QString::null doesn't work, use an alternate expression */
707 cmds[DCprintQStringStruct].fmt = printQStringStructNoNullFmt;
708 // continue and let parseOffErrorExpr catch the error
711 // special case: empty string (0 repetitions)
712 if (strncmp(p, "Invalid number 0 of repetitions", 31) == 0)
714 variable = new VarTree(QString(), VarTree::NKplain);
715 variable->m_value = "\"\"";
716 return variable;
719 // check for error conditions
720 if (parseErrorMessage(p, variable, wantErrorValue))
721 return variable;
723 // parse the array
725 // find '='
726 p = strchr(p, '=');
727 if (p == 0) {
728 goto error;
730 // skip white space
731 do {
732 p++;
733 } while (isspace(*p));
735 if (*p == '{')
737 // this is the real data
738 p++; /* skip '{' */
740 // parse the array
741 QString result;
742 QString repeatCount;
743 enum { wasNothing, wasChar, wasRepeat } lastThing = wasNothing;
745 * A matrix for separators between the individual "things"
746 * that are added to the string. The first index is a bool,
747 * the second index is from the enum above.
749 static const char* separator[2][3] = {
750 { "\"", 0, ", \"" }, /* normal char is added */
751 { "'", "\", '", ", '" } /* repeated char is added */
754 while (isdigit(*p)) {
755 // parse a number
756 char* end;
757 unsigned short value = (unsigned short) strtoul(p, &end, 0);
758 if (end == p)
759 goto error; /* huh? no valid digits */
760 // skip separator and search for a repeat count
761 p = end;
762 while (isspace(*p) || *p == ',')
763 p++;
764 bool repeats = strncmp(p, "<repeats ", 9) == 0;
765 if (repeats) {
766 const char* start = p;
767 p = strchr(p+9, '>'); /* search end and advance */
768 if (p == 0)
769 goto error;
770 p++; /* skip '>' */
771 repeatCount = FROM_LATIN1(start, p-start);
772 while (isspace(*p) || *p == ',')
773 p++;
775 // p is now at the next char (or the end)
777 // interpret the value as a QChar
778 // TODO: make cross-architecture compatible
779 QChar ch;
780 (unsigned short&)ch = value;
782 // escape a few frequently used characters
783 char escapeCode = '\0';
784 switch (char(ch)) {
785 case '\n': escapeCode = 'n'; break;
786 case '\r': escapeCode = 'r'; break;
787 case '\t': escapeCode = 't'; break;
788 case '\b': escapeCode = 'b'; break;
789 case '\"': escapeCode = '\"'; break;
790 case '\\': escapeCode = '\\'; break;
791 #if QT_VERSION < 200
792 // since we only deal with ascii values must always escape '\0'
793 case '\0': escapeCode = '0'; break;
794 #else
795 case '\0': if (value == 0) { escapeCode = '0'; } break;
796 #endif
799 // add separator
800 result += separator[repeats][lastThing];
801 // add char
802 if (escapeCode != '\0') {
803 result += '\\';
804 ch = escapeCode;
806 result += ch;
808 // fixup repeat count and lastThing
809 if (repeats) {
810 result += "' ";
811 result += repeatCount;
812 lastThing = wasRepeat;
813 } else {
814 lastThing = wasChar;
817 if (*p != '}')
818 goto error;
820 // closing quote
821 if (lastThing == wasChar)
822 result += "\"";
824 // assign the value
825 variable = new VarTree(QString(), VarTree::NKplain);
826 variable->m_value = result;
828 else if (strncmp(p, "true", 4) == 0)
830 variable = new VarTree(QString(), VarTree::NKplain);
831 variable->m_value = "QString::null";
833 else if (strncmp(p, "false", 5) == 0)
835 variable = new VarTree(QString(), VarTree::NKplain);
836 variable->m_value = "(null)";
838 else
839 goto error;
840 return variable;
842 error:
843 if (wantErrorValue) {
844 variable = new VarTree(QString(), VarTree::NKplain);
845 variable->m_value = "internal parse error";
847 return variable;
850 static VarTree* parseVar(const char*& s)
852 const char* p = s;
854 // skip whitespace
855 while (isspace(*p))
856 p++;
858 QString name;
859 VarTree::NameKind kind;
860 if (!parseName(p, name, kind)) {
861 return 0;
864 // go for '='
865 while (isspace(*p))
866 p++;
867 if (*p != '=') {
868 TRACE(QString().sprintf("parse error: = not found after %s", (const char*)name));
869 return 0;
871 // skip the '=' and more whitespace
872 p++;
873 while (isspace(*p))
874 p++;
876 VarTree* variable = new VarTree(name, kind);
877 variable->setDeleteChildren(true);
879 if (!parseValue(p, variable)) {
880 delete variable;
881 return 0;
883 s = p;
884 return variable;
887 static void skipNested(const char*& s, char opening, char closing)
889 const char* p = s;
891 // parse a nested type
892 int nest = 1;
893 p++;
895 * Search for next matching `closing' char, skipping nested pairs of
896 * `opening' and `closing'.
898 while (*p && nest > 0) {
899 if (*p == opening) {
900 nest++;
901 } else if (*p == closing) {
902 nest--;
904 p++;
906 if (nest > 0) {
907 TRACE(QString().sprintf("parse error: mismatching %c%c at %-20.20s", opening, closing, s));
909 s = p;
912 void skipString(const char*& p)
914 moreStrings:
915 // opening quote
916 char quote = *p++;
917 while (*p != quote) {
918 if (*p == '\\') {
919 // skip escaped character
920 // no special treatment for octal values necessary
921 p++;
923 // simply return if no more characters
924 if (*p == '\0')
925 return;
926 p++;
928 // closing quote
929 p++;
931 * Strings can consist of several parts, some of which contain repeated
932 * characters.
934 if (quote == '\'') {
935 // look ahaead for <repeats 123 times>
936 const char* q = p+1;
937 while (isspace(*q))
938 q++;
939 if (strncmp(q, "<repeats ", 9) == 0) {
940 p = q+9;
941 while (*p != '\0' && *p != '>')
942 p++;
943 if (*p != '\0') {
944 p++; /* skip the '>' */
948 // is the string continued?
949 if (*p == ',') {
950 // look ahead for another quote
951 const char* q = p+1;
952 while (isspace(*q))
953 q++;
954 if (*q == '"' || *q == '\'') {
955 // yes!
956 p = q;
957 goto moreStrings;
960 /* very long strings are followed by `...' */
961 if (*p == '.' && p[1] == '.' && p[2] == '.') {
962 p += 3;
966 static void skipNestedWithString(const char*& s, char opening, char closing)
968 const char* p = s;
970 // parse a nested expression
971 int nest = 1;
972 p++;
974 * Search for next matching `closing' char, skipping nested pairs of
975 * `opening' and `closing' as well as strings.
977 while (*p && nest > 0) {
978 if (*p == opening) {
979 nest++;
980 } else if (*p == closing) {
981 nest--;
982 } else if (*p == '\'' || *p == '\"') {
983 skipString(p);
984 continue;
986 p++;
988 if (nest > 0) {
989 TRACE(QString().sprintf("parse error: mismatching %c%c at %-20.20s", opening, closing, s));
991 s = p;
994 inline void skipName(const char*& p)
996 // allow : (for enumeration values) and $ and . (for _vtbl.)
997 while (isalnum(*p) || *p == '_' || *p == ':' || *p == '$' || *p == '.')
998 p++;
1001 static bool parseName(const char*& s, QString& name, VarTree::NameKind& kind)
1003 kind = VarTree::NKplain;
1005 const char* p = s;
1006 // examples of names:
1007 // name
1008 // <Object>
1009 // <string<a,b<c>,7> >
1011 if (*p == '<') {
1012 skipNested(p, '<', '>');
1013 name = FROM_LATIN1(s, p - s);
1014 kind = VarTree::NKtype;
1016 else
1018 // name, which might be "static"; allow dot for "_vtbl."
1019 skipName(p);
1020 if (p == s) {
1021 TRACE(QString().sprintf("parse error: not a name %-20.20s", s));
1022 return false;
1024 int len = p - s;
1025 if (len == 6 && strncmp(s, "static", 6) == 0) {
1026 kind = VarTree::NKstatic;
1028 // its a static variable, name comes now
1029 while (isspace(*p))
1030 p++;
1031 s = p;
1032 skipName(p);
1033 if (p == s) {
1034 TRACE(QString().sprintf("parse error: not a name after static %-20.20s", s));
1035 return false;
1037 len = p - s;
1039 name = FROM_LATIN1(s, len);
1041 // return the new position
1042 s = p;
1043 return true;
1046 static bool parseValue(const char*& s, VarTree* variable)
1048 variable->m_value = "";
1050 repeat:
1051 if (*s == '{') {
1052 s++;
1053 if (!parseNested(s, variable)) {
1054 return false;
1056 // must be the closing brace
1057 if (*s != '}') {
1058 TRACE("parse error: missing } of " + variable->getText());
1059 return false;
1061 s++;
1062 // final white space
1063 while (isspace(*s))
1064 s++;
1065 } else {
1066 // examples of leaf values (cannot be the empty string):
1067 // 123
1068 // -123
1069 // 23.575e+37
1070 // 0x32a45
1071 // @0x012ab4
1072 // (DwContentType&) @0x8123456: {...}
1073 // 0x32a45 "text"
1074 // 10 '\n'
1075 // <optimized out>
1076 // 0x823abc <Array<int> virtual table>
1077 // (void (*)()) 0x8048480 <f(E *, char)>
1078 // (E *) 0xbffff450
1079 // red
1080 // &parseP (HTMLClueV *, char *)
1082 const char*p = s;
1084 // check for type
1085 QString type;
1086 if (*p == '(') {
1087 skipNested(p, '(', ')');
1089 while (isspace(*p))
1090 p++;
1091 variable->m_value = FROM_LATIN1(s, p - s);
1094 bool reference = false;
1095 if (*p == '@') {
1096 // skip reference marker
1097 p++;
1098 reference = true;
1100 const char* start = p;
1101 if (*p == '-')
1102 p++;
1104 // some values consist of more than one token
1105 bool checkMultiPart = false;
1107 if (p[0] == '0' && p[1] == 'x') {
1108 // parse hex number
1109 p += 2;
1110 while (isxdigit(*p))
1111 p++;
1114 * Assume this is a pointer, but only if it's not a reference, since
1115 * references can't be expanded.
1117 if (!reference) {
1118 variable->m_varKind = VarTree::VKpointer;
1119 } else {
1121 * References are followed by a colon, in which case we'll
1122 * find the value following the reference address.
1124 if (*p == ':') {
1125 p++;
1126 } else {
1127 // Paranoia. (Can this happen, i.e. reference not followed by ':'?)
1128 reference = false;
1131 checkMultiPart = true;
1132 } else if (isdigit(*p)) {
1133 // parse decimal number, possibly a float
1134 while (isdigit(*p))
1135 p++;
1136 if (*p == '.') { /* TODO: obey i18n? */
1137 // fractional part
1138 p++;
1139 while (isdigit(*p))
1140 p++;
1142 if (*p == 'e' || *p == 'E') {
1143 p++;
1144 // exponent
1145 if (*p == '-' || *p == '+')
1146 p++;
1147 while (isdigit(*p))
1148 p++;
1151 // for char variables there is the char, eg. 10 '\n'
1152 checkMultiPart = true;
1153 } else if (*p == '<') {
1154 // e.g. <optimized out>
1155 skipNested(p, '<', '>');
1156 } else if (*p == '"' || *p == '\'') {
1157 // character may have multipart: '\000' <repeats 11 times>
1158 checkMultiPart = *p == '\'';
1159 // found a string
1160 skipString(p);
1161 } else if (*p == '&') {
1162 // function pointer
1163 p++;
1164 skipName(p);
1165 while (isspace(*p)) {
1166 p++;
1168 if (*p == '(') {
1169 skipNested(p, '(', ')');
1171 } else {
1172 // must be an enumeration value
1173 skipName(p);
1175 variable->m_value += FROM_LATIN1(start, p - start);
1177 if (checkMultiPart) {
1178 // white space
1179 while (isspace(*p))
1180 p++;
1181 // may be followed by a string or <...>
1182 start = p;
1184 if (*p == '"' || *p == '\'') {
1185 skipString(p);
1186 } else if (*p == '<') {
1187 skipNested(p, '<', '>');
1189 if (p != start) {
1190 // there is always a blank before the string,
1191 // which we will include in the final string value
1192 variable->m_value += FROM_LATIN1(start-1, (p - start)+1);
1193 // if this was a pointer, reset that flag since we
1194 // now got the value
1195 variable->m_varKind = VarTree::VKsimple;
1199 if (variable->m_value.length() == 0) {
1200 TRACE("parse error: no value for " + variable->getText());
1201 return false;
1204 // final white space
1205 while (isspace(*p))
1206 p++;
1207 s = p;
1210 * If this was a reference, the value follows. It might even be a
1211 * composite variable!
1213 if (reference) {
1214 goto repeat;
1217 if (variable->m_varKind == VarTree::VKpointer) {
1218 variable->setDelayedExpanding(true);
1222 return true;
1225 static bool parseNested(const char*& s, VarTree* variable)
1227 // could be a structure or an array
1228 while (isspace(*s))
1229 s++;
1231 const char* p = s;
1232 bool isStruct = false;
1234 * If there is a name followed by an = or an < -- which starts a type
1235 * name -- or "static", it is a structure
1237 if (*p == '<' || *p == '}') {
1238 isStruct = true;
1239 } else if (strncmp(p, "static ", 7) == 0) {
1240 isStruct = true;
1241 } else if (isalpha(*p) || *p == '_' || *p == '$') {
1242 // look ahead for a comma after the name
1243 skipName(p);
1244 while (isspace(*p))
1245 p++;
1246 if (*p == '=') {
1247 isStruct = true;
1249 p = s; /* rescan the name */
1251 if (isStruct) {
1252 if (!parseVarSeq(p, variable)) {
1253 return false;
1255 variable->m_varKind = VarTree::VKstruct;
1256 } else {
1257 if (!parseValueSeq(p, variable)) {
1258 return false;
1260 variable->m_varKind = VarTree::VKarray;
1262 s = p;
1263 return true;
1266 static bool parseVarSeq(const char*& s, VarTree* variable)
1268 // parse a comma-separated sequence of variables
1269 VarTree* var = variable; /* var != 0 to indicate success if empty seq */
1270 for (;;) {
1271 if (*s == '}')
1272 break;
1273 if (strncmp(s, "<No data fields>}", 17) == 0)
1275 // no member variables, so break out immediately
1276 s += 16; /* go to the closing brace */
1277 break;
1279 var = parseVar(s);
1280 if (var == 0)
1281 break; /* syntax error */
1282 variable->appendChild(var);
1283 if (*s != ',')
1284 break;
1285 // skip the comma and whitespace
1286 s++;
1287 while (isspace(*s))
1288 s++;
1290 return var != 0;
1293 static bool parseValueSeq(const char*& s, VarTree* variable)
1295 // parse a comma-separated sequence of variables
1296 int index = 0;
1297 bool good;
1298 for (;;) {
1299 QString name;
1300 name.sprintf("[%d]", index);
1301 index++;
1302 VarTree* var = new VarTree(name, VarTree::NKplain);
1303 var->setDeleteChildren(true);
1304 good = parseValue(s, var);
1305 if (!good) {
1306 delete var;
1307 return false;
1309 variable->appendChild(var);
1310 if (*s != ',') {
1311 break;
1313 // skip the command and whitespace
1314 s++;
1315 while (isspace(*s))
1316 s++;
1317 // sometimes there is a closing brace after a comma
1318 // if (*s == '}')
1319 // break;
1321 return true;
1324 #if QT_VERSION < 200
1325 #define ISSPACE(c) isspace((c))
1326 #else
1327 // c is a QChar
1328 #define ISSPACE(c) (c).isSpace()
1329 #endif
1332 * Parses a stack frame.
1334 static void parseFrameInfo(const char*& s, QString& func,
1335 QString& file, int& lineNo, DbgAddr& address)
1337 const char* p = s;
1339 // next may be a hexadecimal address
1340 if (*p == '0') {
1341 const char* start = p;
1342 p++;
1343 if (*p == 'x')
1344 p++;
1345 while (isxdigit(*p))
1346 p++;
1347 address = FROM_LATIN1(start, p-start);
1348 if (strncmp(p, " in ", 4) == 0)
1349 p += 4;
1351 const char* start = p;
1352 // search opening parenthesis
1353 while (*p != '\0' && *p != '(')
1354 p++;
1355 if (*p == '\0') {
1356 func = start;
1357 file = "";
1358 lineNo = -1;
1359 s = p;
1360 return;
1363 * Skip parameters. But notice that for complicated conversion
1364 * functions (eg. "operator int(**)()()", ie. convert to pointer to
1365 * pointer to function) as well as operator()(...) we have to skip
1366 * additional pairs of parentheses.
1368 do {
1369 skipNestedWithString(p, '(', ')');
1370 while (isspace(*p))
1371 p++;
1372 } while (*p == '(');
1374 // check for file position
1375 if (strncmp(p, "at ", 3) == 0) {
1376 p += 3;
1377 const char* fileStart = p;
1378 // go for the end of the line
1379 while (*p != '\0' && *p != '\n')
1380 p++;
1381 // search back for colon
1382 const char* colon = p;
1383 do {
1384 --colon;
1385 } while (*colon != ':');
1386 file = FROM_LATIN1(fileStart, colon-fileStart);
1387 lineNo = atoi(colon+1)-1;
1388 // skip new-line
1389 if (*p != '\0')
1390 p++;
1391 } else {
1392 // check for "from shared lib"
1393 if (strncmp(p, "from ", 5) == 0) {
1394 p += 5;
1395 // go for the end of the line
1396 while (*p != '\0' && *p != '\n')
1397 p++;
1398 // skip new-line
1399 if (*p != '\0')
1400 p++;
1402 file = "";
1403 lineNo = -1;
1405 // construct the function name (including file info)
1406 if (*p == '\0') {
1407 func = start;
1408 } else {
1409 func = FROM_LATIN1(start, p-start-1); /* don't include \n */
1411 s = p;
1414 * Replace \n (and whitespace around it) in func by a blank. We cannot
1415 * use QString::simplifyWhiteSpace() for this because this would also
1416 * simplify space that belongs to a string arguments that gdb sometimes
1417 * prints in the argument lists of the function.
1419 ASSERT(!ISSPACE(func[0])); /* there must be non-white before first \n */
1420 int nl = 0;
1421 while ((nl = func.find('\n', nl)) >= 0) {
1422 // search back to the beginning of the whitespace
1423 int startWhite = nl;
1424 do {
1425 --startWhite;
1426 } while (ISSPACE(func[startWhite]));
1427 startWhite++;
1428 // search forward to the end of the whitespace
1429 do {
1430 nl++;
1431 } while (ISSPACE(func[nl]));
1432 // replace
1433 func.replace(startWhite, nl-startWhite, " ");
1434 /* continue searching for more \n's at this place: */
1435 nl = startWhite+1;
1437 return;
1440 #undef ISSPACE
1443 * Parses a stack frame including its frame number
1445 static bool parseFrame(const char*& s, int& frameNo, QString& func,
1446 QString& file, int& lineNo, DbgAddr& address)
1448 // Example:
1449 // #1 0x8048881 in Dl::Dl (this=0xbffff418, r=3214) at testfile.cpp:72
1451 // must start with a hash mark followed by number
1452 if (s[0] != '#' || !isdigit(s[1]))
1453 return false;
1455 s++; /* skip the hash mark */
1456 // frame number
1457 frameNo = atoi(s);
1458 while (isdigit(*s))
1459 s++;
1460 // space
1461 while (isspace(*s))
1462 s++;
1463 parseFrameInfo(s, func, file, lineNo, address);
1464 return true;
1467 void GdbDriver::parseBackTrace(const char* output, QList<StackFrame>& stack)
1469 QString func, file;
1470 int lineNo, frameNo;
1471 DbgAddr address;
1473 while (::parseFrame(output, frameNo, func, file, lineNo, address)) {
1474 StackFrame* frm = new StackFrame;
1475 frm->frameNo = frameNo;
1476 frm->fileName = file;
1477 frm->lineNo = lineNo;
1478 frm->address = address;
1479 frm->var = new VarTree(func, VarTree::NKplain);
1480 stack.append(frm);
1484 bool GdbDriver::parseFrameChange(const char* output, int& frameNo,
1485 QString& file, int& lineNo, DbgAddr& address)
1487 QString func;
1488 return ::parseFrame(output, frameNo, func, file, lineNo, address);
1492 bool GdbDriver::parseBreakList(const char* output, QList<Breakpoint>& brks)
1494 // skip first line, which is the headline
1495 const char* p = strchr(output, '\n');
1496 if (p == 0)
1497 return false;
1498 p++;
1499 if (*p == '\0')
1500 return false;
1502 // split up a line
1503 QString location;
1504 QString address;
1505 int hits = 0;
1506 uint ignoreCount = 0;
1507 QString condition;
1508 const char* end;
1509 char* dummy;
1510 while (*p != '\0') {
1511 // get Num
1512 long bpNum = strtol(p, &dummy, 10); /* don't care about overflows */
1513 p = dummy;
1514 // get Type
1515 while (isspace(*p))
1516 p++;
1517 Breakpoint::Type bpType;
1518 if (strncmp(p, "breakpoint", 10) == 0) {
1519 bpType = Breakpoint::breakpoint;
1520 p += 10;
1521 } else if (strncmp(p, "hw watchpoint", 13) == 0) {
1522 bpType = Breakpoint::watchpoint;
1523 p += 13;
1524 } else if (strncmp(p, "watchpoint", 10) == 0) {
1525 bpType = Breakpoint::watchpoint;
1526 p += 10;
1528 while (isspace(*p))
1529 p++;
1530 if (*p == '\0')
1531 break;
1532 // get Disp
1533 char disp = *p++;
1534 while (*p != '\0' && !isspace(*p)) /* "keep" or "del" */
1535 p++;
1536 while (isspace(*p))
1537 p++;
1538 if (*p == '\0')
1539 break;
1540 // get Enb
1541 char enable = *p++;
1542 while (*p != '\0' && !isspace(*p)) /* "y" or "n" */
1543 p++;
1544 while (isspace(*p))
1545 p++;
1546 if (*p == '\0')
1547 break;
1548 // the address, if present
1549 if (bpType == Breakpoint::breakpoint &&
1550 strncmp(p, "0x", 2) == 0)
1552 const char* start = p;
1553 while (*p != '\0' && !isspace(*p))
1554 p++;
1555 address = FROM_LATIN1(start, p-start);
1556 while (isspace(*p) && *p != '\n')
1557 p++;
1558 if (*p == '\0')
1559 break;
1560 } else {
1561 address = QString();
1563 // remainder is location, hit and ignore count, condition
1564 hits = 0;
1565 ignoreCount = 0;
1566 condition = QString();
1567 end = strchr(p, '\n');
1568 if (end == 0) {
1569 location = p;
1570 p += location.length();
1571 } else {
1572 location = FROM_LATIN1(p, end-p).stripWhiteSpace();
1573 p = end+1; /* skip over \n */
1576 // may be continued in next line
1577 while (isspace(*p)) { /* p points to beginning of line */
1578 // skip white space at beginning of line
1579 while (isspace(*p))
1580 p++;
1582 // seek end of line
1583 end = strchr(p, '\n');
1584 if (end == 0)
1585 end = p+strlen(p);
1587 if (strncmp(p, "breakpoint already hit", 22) == 0) {
1588 // extract the hit count
1589 p += 22;
1590 hits = strtol(p, &dummy, 10);
1591 TRACE(QString().sprintf("hit count %d", hits));
1592 } else if (strncmp(p, "stop only if ", 13) == 0) {
1593 // extract condition
1594 p += 13;
1595 condition = FROM_LATIN1(p, end-p).stripWhiteSpace();
1596 TRACE("condition: "+condition);
1597 } else if (strncmp(p, "ignore next ", 12) == 0) {
1598 // extract ignore count
1599 p += 12;
1600 ignoreCount = strtol(p, &dummy, 10);
1601 TRACE(QString().sprintf("ignore count %d", ignoreCount));
1602 } else {
1603 // indeed a continuation
1604 location += " " + FROM_LATIN1(p, end-p).stripWhiteSpace();
1606 p = end;
1607 if (*p != '\0')
1608 p++; /* skip '\n' */
1610 Breakpoint* bp = new Breakpoint;
1611 bp->id = bpNum;
1612 bp->type = bpType;
1613 bp->temporary = disp == 'd';
1614 bp->enabled = enable == 'y';
1615 bp->location = location;
1616 bp->address = address;
1617 bp->hitCount = hits;
1618 bp->ignoreCount = ignoreCount;
1619 bp->condition = condition;
1620 brks.append(bp);
1622 return true;
1625 bool GdbDriver::parseThreadList(const char* output, QList<ThreadInfo>& threads)
1627 if (strcmp(output, "\n") == 0 || strncmp(output, "No stack.", 9) == 0) {
1628 // no threads
1629 return true;
1632 int id;
1633 QString systag;
1634 QString func, file;
1635 int lineNo;
1636 DbgAddr address;
1638 const char* p = output;
1639 while (*p != '\0') {
1640 // seach look for thread id, watching out for the focus indicator
1641 bool hasFocus = false;
1642 while (isspace(*p)) /* may be \n from prev line: see "No stack" below */
1643 p++;
1644 if (*p == '*') {
1645 hasFocus = true;
1646 p++;
1647 // there follows only whitespace
1649 char* end;
1650 id = strtol(p, &end, 10);
1651 if (p == end) {
1652 // syntax error: no number found; bail out
1653 return true;
1655 p = end;
1657 // skip space
1658 while (isspace(*p))
1659 p++;
1662 * Now follows the thread's SYSTAG. It is terminated by two blanks.
1664 end = strstr(p, " ");
1665 if (end == 0) {
1666 // syntax error; bail out
1667 return true;
1669 systag = FROM_LATIN1(p, end-p);
1670 p = end+2;
1673 * Now follows a standard stack frame. Sometimes, however, gdb
1674 * catches a thread at an instant where it doesn't have a stack.
1676 if (strncmp(p, "[No stack.]", 11) != 0) {
1677 ::parseFrameInfo(p, func, file, lineNo, address);
1678 } else {
1679 func = "[No stack]";
1680 file = QString();
1681 lineNo = -1;
1682 address = QString();
1683 p += 11; /* \n is skipped above */
1686 ThreadInfo* thr = new ThreadInfo;
1687 thr->id = id;
1688 thr->threadName = systag;
1689 thr->hasFocus = hasFocus;
1690 thr->function = func;
1691 thr->fileName = file;
1692 thr->lineNo = lineNo;
1693 thr->address = address;
1694 threads.append(thr);
1696 return true;
1699 bool GdbDriver::parseBreakpoint(const char* output, int& id,
1700 QString& file, int& lineNo)
1702 const char* o = output;
1703 // skip lines of that begin with "(Cannot find"
1704 while (strncmp(o, "(Cannot find", 12) == 0) {
1705 o = strchr(o, '\n');
1706 if (o == 0)
1707 return false;
1708 o++; /* skip newline */
1711 if (strncmp(o, "Breakpoint ", 11) != 0)
1712 return false;
1714 // breakpoint id
1715 output += 11; /* skip "Breakpoint " */
1716 char* p;
1717 int num = strtoul(output, &p, 10);
1718 if (p == o)
1719 return false;
1721 // file name
1722 char* fileStart = strstr(p, "file ");
1723 if (fileStart == 0)
1724 return false;
1725 fileStart += 5;
1727 // line number
1728 char* numStart = strstr(fileStart, ", line ");
1729 QString fileName = FROM_LATIN1(fileStart, numStart-fileStart);
1730 numStart += 7;
1731 int line = strtoul(numStart, &p, 10);
1732 if (numStart == p)
1733 return false;
1735 id = num;
1736 file = fileName;
1737 lineNo = line-1; /* zero-based! */
1738 return true;
1741 void GdbDriver::parseLocals(const char* output, QList<VarTree>& newVars)
1743 // check for possible error conditions
1744 if (strncmp(output, "No symbol table", 15) == 0)
1746 return;
1749 while (*output != '\0') {
1750 while (isspace(*output))
1751 output++;
1752 if (*output == '\0')
1753 break;
1754 // skip occurrences of "No locals" and "No args"
1755 if (strncmp(output, "No locals", 9) == 0 ||
1756 strncmp(output, "No arguments", 12) == 0)
1758 output = strchr(output, '\n');
1759 if (output == 0) {
1760 break;
1762 continue;
1765 VarTree* variable = parseVar(output);
1766 if (variable == 0) {
1767 break;
1769 // do not add duplicates
1770 for (VarTree* o = newVars.first(); o != 0; o = newVars.next()) {
1771 if (o->getText() == variable->getText()) {
1772 delete variable;
1773 goto skipDuplicate;
1776 newVars.append(variable);
1777 skipDuplicate:;
1781 bool GdbDriver::parsePrintExpr(const char* output, bool wantErrorValue, VarTree*& var)
1783 // check for error conditions
1784 if (parseErrorMessage(output, var, wantErrorValue))
1786 return false;
1787 } else {
1788 // parse the variable
1789 var = parseVar(output);
1790 return true;
1794 bool GdbDriver::parseChangeWD(const char* output, QString& message)
1796 bool isGood = false;
1797 message = QString(output).simplifyWhiteSpace();
1798 if (message.isEmpty()) {
1799 message = i18n("New working directory: ") + m_programWD;
1800 isGood = true;
1802 return isGood;
1805 bool GdbDriver::parseChangeExecutable(const char* output, QString& message)
1807 message = output;
1809 m_haveCoreFile = false;
1812 * The command is successful if there is no output or the single
1813 * message (no debugging symbols found)...
1815 return
1816 output[0] == '\0' ||
1817 strcmp(output, "(no debugging symbols found)...") == 0;
1820 bool GdbDriver::parseCoreFile(const char* output)
1822 // if command succeeded, gdb emits a line starting with "#0 "
1823 m_haveCoreFile = strstr(output, "\n#0 ") != 0;
1824 return m_haveCoreFile;
1827 uint GdbDriver::parseProgramStopped(const char* output, QString& message)
1829 // optionally: "program changed, rereading symbols",
1830 // followed by:
1831 // "Program exited normally"
1832 // "Program terminated with wignal SIGSEGV"
1833 // "Program received signal SIGINT" or other signal
1834 // "Breakpoint..."
1836 // go through the output, line by line, checking what we have
1837 const char* start = output - 1;
1838 uint flags = SFprogramActive;
1839 message = QString();
1840 do {
1841 start++; /* skip '\n' */
1843 if (strncmp(start, "Program ", 8) == 0 ||
1844 strncmp(start, "ptrace: ", 8) == 0) {
1846 * When we receive a signal, the program remains active.
1848 * Special: If we "stopped" in a corefile, the string "Program
1849 * terminated with signal"... is displayed. (Normally, we see
1850 * "Program received signal"... when a signal happens.)
1852 if (strncmp(start, "Program exited", 14) == 0 ||
1853 (strncmp(start, "Program terminated", 18) == 0 && !m_haveCoreFile) ||
1854 strncmp(start, "ptrace: ", 8) == 0)
1856 flags &= ~SFprogramActive;
1859 // set message
1860 const char* endOfMessage = strchr(start, '\n');
1861 if (endOfMessage == 0)
1862 endOfMessage = start + strlen(start);
1863 message = FROM_LATIN1(start, endOfMessage-start);
1864 } else if (strncmp(start, "Breakpoint ", 11) == 0) {
1866 * We stopped at a (permanent) breakpoint (gdb doesn't tell us
1867 * that it stopped at a temporary breakpoint).
1869 flags |= SFrefreshBreak;
1870 } else if (strstr(start, "re-reading symbols.") != 0) {
1871 flags |= SFrefreshSource;
1874 // next line, please
1875 start = strchr(start, '\n');
1876 } while (start != 0);
1879 * Gdb only notices when new threads have appeared, but not when a
1880 * thread finishes. So we always have to assume that the list of
1881 * threads has changed.
1883 flags |= SFrefreshThreads;
1885 return flags;
1888 void GdbDriver::parseSharedLibs(const char* output, QStrList& shlibs)
1890 if (strncmp(output, "No shared libraries loaded", 26) == 0)
1891 return;
1893 // parse the table of shared libraries
1895 // strip off head line
1896 output = strchr(output, '\n');
1897 if (output == 0)
1898 return;
1899 output++; /* skip '\n' */
1900 QString shlibName;
1901 while (*output != '\0') {
1902 // format of a line is
1903 // 0x404c5000 0x40580d90 Yes /lib/libc.so.5
1904 // 3 blocks of non-space followed by space
1905 for (int i = 0; *output != '\0' && i < 3; i++) {
1906 while (*output != '\0' && !isspace(*output)) { /* non-space */
1907 output++;
1909 while (isspace(*output)) { /* space */
1910 output++;
1913 if (*output == '\0')
1914 return;
1915 const char* start = output;
1916 output = strchr(output, '\n');
1917 if (output == 0)
1918 output = start + strlen(start);
1919 shlibName = FROM_LATIN1(start, output-start);
1920 if (*output != '\0')
1921 output++;
1922 shlibs.append(shlibName);
1923 TRACE("found shared lib " + shlibName);
1927 bool GdbDriver::parseFindType(const char* output, QString& type)
1929 if (strncmp(output, "type = ", 7) != 0)
1930 return false;
1933 * Everything else is the type. We strip off all white-space from the
1934 * type.
1936 output += 7;
1937 type = output;
1938 type.replace(QRegExp("\\s+"), "");
1939 return true;
1942 void GdbDriver::parseRegisters(const char* output, QList<RegisterInfo>& regs)
1944 if (strncmp(output, "The program has no registers now", 32) == 0) {
1945 return;
1948 QString regName;
1949 QString value;
1951 // parse register values
1952 while (*output != '\0')
1954 // skip space at the start of the line
1955 while (isspace(*output))
1956 output++;
1958 // register name
1959 const char* start = output;
1960 while (*output != '\0' && !isspace(*output))
1961 output++;
1962 if (*output == '\0')
1963 break;
1964 regName = FROM_LATIN1(start, output-start);
1966 // skip space
1967 while (isspace(*output))
1968 output++;
1969 // the rest of the line is the register value
1970 start = output;
1971 output = strchr(output,'\n');
1972 if (output == 0)
1973 output = start + strlen(start);
1974 value = FROM_LATIN1(start, output-start).simplifyWhiteSpace();
1976 if (*output != '\0')
1977 output++; /* skip '\n' */
1979 RegisterInfo* reg = new RegisterInfo;
1980 reg->regName = regName;
1983 * We split the raw from the cooked values. For this purpose, we
1984 * split off the first token (separated by whitespace). It is the
1985 * raw value. The remainder of the line is the cooked value.
1987 int pos = value.find(' ');
1988 if (pos < 0) {
1989 reg->rawValue = value;
1990 reg->cookedValue = QString();
1991 } else {
1992 reg->rawValue = value.left(pos);
1993 reg->cookedValue = value.mid(pos+1,value.length());
1995 * Some modern gdbs explicitly say: "0.1234 (raw 0x3e4567...)".
1996 * Here the raw value is actually in the second part.
1998 if (reg->cookedValue.left(5) == "(raw ") {
1999 QString raw = reg->cookedValue.right(reg->cookedValue.length()-5);
2000 if (raw[raw.length()-1] == ')') /* remove closing bracket */
2001 raw = raw.left(raw.length()-1);
2002 reg->cookedValue = reg->rawValue;
2003 reg->rawValue = raw;
2007 regs.append(reg);
2011 bool GdbDriver::parseInfoLine(const char* output, QString& addrFrom, QString& addrTo)
2013 const char* start = strstr(output, "starts at address ");
2014 if (start == 0)
2015 return false;
2017 start += 18;
2018 const char* p = start;
2019 while (*p != '\0' && !isspace(*p))
2020 p++;
2021 addrFrom = FROM_LATIN1(start, p-start);
2023 start = strstr(p, "and ends at ");
2024 if (start == 0)
2025 return false;
2027 start += 12;
2028 p = start;
2029 while (*p != '\0' && !isspace(*p))
2030 p++;
2031 addrTo = FROM_LATIN1(start, p-start);
2033 return true;
2036 void GdbDriver::parseDisassemble(const char* output, QList<DisassembledCode>& code)
2038 code.clear();
2040 if (strncmp(output, "Dump of assembler", 17) != 0) {
2041 // error message?
2042 DisassembledCode c;
2043 c.code = output;
2044 code.append(new DisassembledCode(c));
2045 return;
2048 // remove first line
2049 const char* p = strchr(output, '\n');
2050 if (p == 0)
2051 return; /* not a regular output */
2053 p++;
2055 // remove last line
2056 const char* end = strstr(output, "\nEnd of assembler");
2057 if (end == 0)
2058 end = p + strlen(p);
2060 DbgAddr address;
2062 // remove function offsets from the lines
2063 while (p != end)
2065 const char* start = p;
2066 // address
2067 while (p != end && !isspace(*p))
2068 p++;
2069 address = FROM_LATIN1(start, p-start);
2071 // function name (enclosed in '<>', followed by ':')
2072 while (p != end && *p != '<')
2073 p++;
2074 if (*p == '<')
2075 skipNested(p, '<', '>');
2076 if (*p == ':')
2077 p++;
2079 // space until code
2080 while (p != end && isspace(*p))
2081 p++;
2083 // code until end of line
2084 start = p;
2085 while (p != end && *p != '\n')
2086 p++;
2087 if (p != end) /* include '\n' */
2088 p++;
2090 DisassembledCode* c = new DisassembledCode;
2091 c->address = address;
2092 c->code = FROM_LATIN1(start, p-start);
2093 code.append(c);
2097 QString GdbDriver::parseMemoryDump(const char* output, QList<MemoryDump>& memdump)
2099 if (isErrorExpr(output)) {
2100 // error; strip space
2101 QString msg = output;
2102 return msg.stripWhiteSpace();
2105 const char* p = output; /* save typing */
2106 DbgAddr addr;
2107 QString dump;
2109 // the address
2110 while (*p != 0) {
2111 const char* start = p;
2112 while (*p != '\0' && *p != ':' && !isspace(*p))
2113 p++;
2114 addr = FROM_LATIN1(start, p-start);
2115 if (*p != ':') {
2116 // parse function offset
2117 while (isspace(*p))
2118 p++;
2119 start = p;
2120 while (*p != '\0' && !(*p == ':' && isspace(p[1])))
2121 p++;
2122 addr.fnoffs = FROM_LATIN1(start, p-start);
2124 if (*p == ':')
2125 p++;
2126 // skip space; this may skip a new-line char!
2127 while (isspace(*p))
2128 p++;
2129 // everything to the end of the line is the memory dump
2130 const char* end = strchr(p, '\n');
2131 if (end != 0) {
2132 dump = FROM_LATIN1(p, end-p);
2133 p = end+1;
2134 } else {
2135 dump = FROM_LATIN1(p, strlen(p));
2136 p += strlen(p);
2138 MemoryDump* md = new MemoryDump;
2139 md->address = addr;
2140 md->dump = dump;
2141 memdump.append(md);
2144 return QString();
2148 #include "gdbdriver.moc"