Fixed parsing of stack frames for recent gdbs.
[kdbg.git] / kdbg / gdbdriver.cpp
blob4410d9fac869517811af91356646e78e9647ec9f
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 #include <qstringlist.h>
10 #include <klocale.h> /* i18n */
11 #include <ctype.h>
12 #include <stdlib.h> /* strtol, atoi */
13 #include <string.h> /* strcpy */
15 #include "assert.h"
16 #ifdef HAVE_CONFIG_H
17 #include "config.h"
18 #endif
19 #include "mydebug.h"
21 static void skipString(const char*& p);
22 static void skipNested(const char*& s, char opening, char closing);
23 static VarTree* parseVar(const char*& s);
24 static bool parseName(const char*& s, QString& name, VarTree::NameKind& kind);
25 static bool parseValue(const char*& s, VarTree* variable);
26 static bool parseNested(const char*& s, VarTree* variable);
27 static bool parseVarSeq(const char*& s, VarTree* variable);
28 static bool parseValueSeq(const char*& s, VarTree* variable);
30 #define PROMPT "(kdbg)"
31 #define PROMPT_LEN 6
32 #define PROMPT_LAST_CHAR ')' /* needed when searching for prompt string */
35 // TODO: make this cmd info stuff non-static to allow multiple
36 // simultaneous gdbs to run!
38 struct GdbCmdInfo {
39 DbgCommand cmd;
40 const char* fmt; /* format string */
41 enum Args {
42 argNone, argString, argNum,
43 argStringNum, argNumString,
44 argString2, argNum2
45 } argsNeeded;
48 static const char printQStringStructFmt[] =
49 // if the string data is junk, fail early
50 "print ($qstrunicode=($qstrdata=(%s))->unicode)?"
51 // print an array of shorts
52 "(*(unsigned short*)$qstrunicode)@"
53 // limit the length
54 "(($qstrlen=(unsigned int)($qstrdata->len))>100?100:$qstrlen)"
55 // if unicode data is 0, check if it is QString::null
56 ":($qstrdata==QString::null.d)\n";
58 // However, gdb can't always find QString::null (I don't know why)
59 // which results in an error; we autodetect this situation in
60 // parseQt2QStrings and revert to a safe expression.
61 // Same as above except for last line:
62 static const char printQStringStructNoNullFmt[] =
63 "print ($qstrunicode=($qstrdata=(%s))->unicode)?"
64 "(*(unsigned short*)$qstrunicode)@"
65 "(($qstrlen=(unsigned int)($qstrdata->len))>100?100:$qstrlen)"
66 ":1==0\n";
69 * The following array of commands must be sorted by the DC* values,
70 * because they are used as indices.
72 static GdbCmdInfo cmds[] = {
73 { DCinitialize, "", GdbCmdInfo::argNone },
74 { DCtty, "tty %s\n", GdbCmdInfo::argString },
75 { DCexecutable, "file \"%s\"\n", GdbCmdInfo::argString },
76 { DCtargetremote, "target remote %s\n", GdbCmdInfo::argString },
77 { DCcorefile, "core-file %s\n", GdbCmdInfo::argString },
78 { DCattach, "attach %s\n", GdbCmdInfo::argString },
79 { DCinfolinemain, "info line main\n", GdbCmdInfo::argNone },
80 { DCinfolocals, "kdbg__alllocals\n", GdbCmdInfo::argNone },
81 { DCinforegisters, "info all-registers\n", GdbCmdInfo::argNone},
82 { DCexamine, "x %s %s\n", GdbCmdInfo::argString2 },
83 { DCinfoline, "info line %s:%d\n", GdbCmdInfo::argStringNum },
84 { DCdisassemble, "disassemble %s %s\n", GdbCmdInfo::argString2 },
85 { DCsetargs, "set args %s\n", GdbCmdInfo::argString },
86 { DCsetenv, "set env %s %s\n", GdbCmdInfo::argString2 },
87 { DCunsetenv, "unset env %s\n", GdbCmdInfo::argString },
88 { DCsetoption, "setoption %s %d\n", GdbCmdInfo::argStringNum},
89 { DCcd, "cd %s\n", GdbCmdInfo::argString },
90 { DCbt, "bt\n", GdbCmdInfo::argNone },
91 { DCrun, "run\n", GdbCmdInfo::argNone },
92 { DCcont, "cont\n", GdbCmdInfo::argNone },
93 { DCstep, "step\n", GdbCmdInfo::argNone },
94 { DCstepi, "stepi\n", GdbCmdInfo::argNone },
95 { DCnext, "next\n", GdbCmdInfo::argNone },
96 { DCnexti, "nexti\n", GdbCmdInfo::argNone },
97 { DCfinish, "finish\n", GdbCmdInfo::argNone },
98 { DCuntil, "until %s:%d\n", GdbCmdInfo::argStringNum },
99 { DCkill, "kill\n", GdbCmdInfo::argNone },
100 { DCbreaktext, "break %s\n", GdbCmdInfo::argString },
101 { DCbreakline, "break %s:%d\n", GdbCmdInfo::argStringNum },
102 { DCtbreakline, "tbreak %s:%d\n", GdbCmdInfo::argStringNum },
103 { DCbreakaddr, "break *%s\n", GdbCmdInfo::argString },
104 { DCtbreakaddr, "tbreak *%s\n", GdbCmdInfo::argString },
105 { DCwatchpoint, "watch %s\n", GdbCmdInfo::argString },
106 { DCdelete, "delete %d\n", GdbCmdInfo::argNum },
107 { DCenable, "enable %d\n", GdbCmdInfo::argNum },
108 { DCdisable, "disable %d\n", GdbCmdInfo::argNum },
109 { DCprint, "print %s\n", GdbCmdInfo::argString },
110 { DCprintStruct, "print %s\n", GdbCmdInfo::argString },
111 { DCprintQStringStruct, printQStringStructFmt, 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 { DCignore, "ignore %d %d\n", GdbCmdInfo::argNum2},
122 #define NUM_CMDS (int(sizeof(cmds)/sizeof(cmds[0])))
123 #define MAX_FMTLEN 200
125 GdbDriver::GdbDriver() :
126 DebuggerDriver(),
127 m_gdbMajor(4), m_gdbMinor(16)
129 strcpy(m_prompt, PROMPT);
130 m_promptMinLen = PROMPT_LEN;
131 m_promptLastChar = PROMPT_LAST_CHAR;
133 #ifndef NDEBUG
134 // check command info array
135 char* perc;
136 for (int i = 0; i < NUM_CMDS; i++) {
137 // must be indexable by DbgCommand values, i.e. sorted by DbgCommand values
138 assert(i == cmds[i].cmd);
139 // a format string must be associated
140 assert(cmds[i].fmt != 0);
141 assert(strlen(cmds[i].fmt) <= MAX_FMTLEN);
142 // format string must match arg specification
143 switch (cmds[i].argsNeeded) {
144 case GdbCmdInfo::argNone:
145 assert(strchr(cmds[i].fmt, '%') == 0);
146 break;
147 case GdbCmdInfo::argString:
148 perc = strchr(cmds[i].fmt, '%');
149 assert(perc != 0 && perc[1] == 's');
150 assert(strchr(perc+2, '%') == 0);
151 break;
152 case GdbCmdInfo::argNum:
153 perc = strchr(cmds[i].fmt, '%');
154 assert(perc != 0 && perc[1] == 'd');
155 assert(strchr(perc+2, '%') == 0);
156 break;
157 case GdbCmdInfo::argStringNum:
158 perc = strchr(cmds[i].fmt, '%');
159 assert(perc != 0 && perc[1] == 's');
160 perc = strchr(perc+2, '%');
161 assert(perc != 0 && perc[1] == 'd');
162 assert(strchr(perc+2, '%') == 0);
163 break;
164 case GdbCmdInfo::argNumString:
165 perc = strchr(cmds[i].fmt, '%');
166 assert(perc != 0 && perc[1] == 'd');
167 perc = strchr(perc+2, '%');
168 assert(perc != 0 && perc[1] == 's');
169 assert(strchr(perc+2, '%') == 0);
170 break;
171 case GdbCmdInfo::argString2:
172 perc = strchr(cmds[i].fmt, '%');
173 assert(perc != 0 && perc[1] == 's');
174 perc = strchr(perc+2, '%');
175 assert(perc != 0 && perc[1] == 's');
176 assert(strchr(perc+2, '%') == 0);
177 break;
178 case GdbCmdInfo::argNum2:
179 perc = strchr(cmds[i].fmt, '%');
180 assert(perc != 0 && perc[1] == 'd');
181 perc = strchr(perc+2, '%');
182 assert(perc != 0 && perc[1] == 'd');
183 assert(strchr(perc+2, '%') == 0);
184 break;
187 assert(strlen(printQStringStructFmt) <= MAX_FMTLEN);
188 assert(strlen(printQStringStructNoNullFmt) <= MAX_FMTLEN);
189 #endif
192 GdbDriver::~GdbDriver()
197 QString GdbDriver::driverName() const
199 return "GDB";
202 QString GdbDriver::defaultGdb()
204 return
205 "gdb"
206 " --fullname" /* to get standard file names each time the prog stops */
207 " --nx"; /* do not execute initialization files */
210 QString GdbDriver::defaultInvocation() const
212 if (m_defaultCmd.isEmpty()) {
213 return defaultGdb();
214 } else {
215 return m_defaultCmd;
219 QStringList GdbDriver::boolOptionList() const
221 // no options
222 return QStringList();
225 bool GdbDriver::startup(QString cmdStr)
227 if (!DebuggerDriver::startup(cmdStr))
228 return false;
230 static const char gdbInitialize[] =
232 * Work around buggy gdbs that do command line editing even if they
233 * are not on a tty. The readline library echos every command back
234 * in this case, which is confusing for us.
236 "set editing off\n"
237 "set confirm off\n"
238 "set print static-members off\n"
239 "set print asm-demangle on\n"
241 * Write a short macro that prints all locals: local variables and
242 * function arguments.
244 "define kdbg__alllocals\n"
245 "info locals\n" /* local vars supersede args with same name */
246 "info args\n" /* therefore, arguments must come last */
247 "end\n"
248 // change prompt string and synchronize with gdb
249 "set prompt " PROMPT "\n"
252 executeCmdString(DCinitialize, gdbInitialize, false);
254 // assume that QString::null is ok
255 cmds[DCprintQStringStruct].fmt = printQStringStructFmt;
257 return true;
260 void GdbDriver::commandFinished(CmdQueueItem* cmd)
262 // command string must be committed
263 if (!cmd->m_committed) {
264 // not commited!
265 TRACE("calling " + (__PRETTY_FUNCTION__ + (" with uncommited command:\n\t" +
266 cmd->m_cmdString)));
267 return;
270 switch (cmd->m_cmd) {
271 case DCinitialize:
272 // get version number from preamble
274 int len;
275 QRegExp GDBVersion("\\nGDB [0-9]+\\.[0-9]+");
276 int offset = GDBVersion.match(m_output, 0, &len);
277 if (offset >= 0) {
278 char* start = m_output + offset + 5; // skip "\nGDB "
279 char* end;
280 m_gdbMajor = strtol(start, &end, 10);
281 m_gdbMinor = strtol(end + 1, 0, 10); // skip "."
282 if (start == end) {
283 // nothing was parsed
284 m_gdbMajor = 4;
285 m_gdbMinor = 16;
287 } else {
288 // assume some default version (what would make sense?)
289 m_gdbMajor = 4;
290 m_gdbMinor = 16;
292 // use a feasible core-file command
293 if (m_gdbMajor > 4 || (m_gdbMajor == 4 && m_gdbMinor >= 16)) {
294 cmds[DCcorefile].fmt = "target core %s\n";
295 } else {
296 cmds[DCcorefile].fmt = "core-file %s\n";
299 break;
300 default:;
303 /* ok, the command is ready */
304 emit commandReceived(cmd, m_output);
306 switch (cmd->m_cmd) {
307 case DCcorefile:
308 case DCinfolinemain:
309 case DCframe:
310 case DCattach:
311 case DCrun:
312 case DCcont:
313 case DCstep:
314 case DCstepi:
315 case DCnext:
316 case DCnexti:
317 case DCfinish:
318 case DCuntil:
319 parseMarker();
320 default:;
325 * The --fullname option makes gdb send a special normalized sequence print
326 * each time the program stops and at some other points. The sequence has
327 * the form "\032\032filename:lineno:charoffset:(beg|middle):address".
329 void GdbDriver::parseMarker()
331 char* startMarker = strstr(m_output, "\032\032");
332 if (startMarker == 0)
333 return;
335 // extract the marker
336 startMarker += 2;
337 TRACE(QString("found marker: ") + startMarker);
338 char* endMarker = strchr(startMarker, '\n');
339 if (endMarker == 0)
340 return;
342 *endMarker = '\0';
344 // extract filename and line number
345 static QRegExp MarkerRE(":[0-9]+:[0-9]+:[begmidl]+:0x");
347 int len;
348 int lineNoStart = MarkerRE.match(startMarker, 0, &len);
349 if (lineNoStart >= 0) {
350 int lineNo = atoi(startMarker + lineNoStart+1);
352 // get address
353 const char* addrStart = startMarker + lineNoStart + len - 2;
354 DbgAddr address = QString(addrStart).stripWhiteSpace();
356 // now show the window
357 startMarker[lineNoStart] = '\0'; /* split off file name */
358 emit activateFileLine(startMarker, lineNo-1, address);
364 * Escapes characters that might lead to problems when they appear on gdb's
365 * command line.
367 static void normalizeStringArg(QString& arg)
370 * Remove trailing backslashes. This approach is a little simplistic,
371 * but we know that there is at the moment no case where a trailing
372 * backslash would make sense.
374 while (!arg.isEmpty() && arg[arg.length()-1] == '\\') {
375 arg = arg.left(arg.length()-1);
380 QString GdbDriver::makeCmdString(DbgCommand cmd, QString strArg)
382 assert(cmd >= 0 && cmd < NUM_CMDS);
383 assert(cmds[cmd].argsNeeded == GdbCmdInfo::argString);
385 normalizeStringArg(strArg);
387 if (cmd == DCcd) {
388 // need the working directory when parsing the output
389 m_programWD = strArg;
390 } else if (cmd == DCsetargs) {
391 // attach saved redirection
392 strArg += m_redirect;
395 SIZED_QString(cmdString, MAX_FMTLEN+strArg.length());
396 cmdString.sprintf(cmds[cmd].fmt, strArg.latin1());
397 return cmdString;
400 QString GdbDriver::makeCmdString(DbgCommand cmd, int intArg)
402 assert(cmd >= 0 && cmd < NUM_CMDS);
403 assert(cmds[cmd].argsNeeded == GdbCmdInfo::argNum);
405 SIZED_QString(cmdString, MAX_FMTLEN+30);
407 cmdString.sprintf(cmds[cmd].fmt, intArg);
408 return cmdString;
411 QString GdbDriver::makeCmdString(DbgCommand cmd, QString strArg, int intArg)
413 assert(cmd >= 0 && cmd < NUM_CMDS);
414 assert(cmds[cmd].argsNeeded == GdbCmdInfo::argStringNum ||
415 cmds[cmd].argsNeeded == GdbCmdInfo::argNumString ||
416 cmd == DCexamine ||
417 cmd == DCtty);
419 normalizeStringArg(strArg);
421 SIZED_QString(cmdString, MAX_FMTLEN+30+strArg.length());
423 if (cmd == DCtty)
426 * intArg specifies which channels should be redirected to
427 * /dev/null. It is a value or'ed together from RDNstdin,
428 * RDNstdout, RDNstderr. We store the value for a later DCsetargs
429 * command.
431 * Note: We rely on that after the DCtty a DCsetargs will follow,
432 * which will ultimately apply the redirection.
434 static const char* const runRedir[8] = {
436 " </dev/null",
437 " >/dev/null",
438 " </dev/null >/dev/null",
439 " 2>/dev/null",
440 " </dev/null 2>/dev/null",
441 " >/dev/null 2>&1",
442 " </dev/null >/dev/null 2>&1"
444 if (strArg.isEmpty())
445 intArg = 7; /* failsafe if no tty */
446 m_redirect = runRedir[intArg & 7];
448 return makeCmdString(DCtty, strArg); /* note: no problem if strArg empty */
451 if (cmd == DCexamine) {
452 // make a format specifier from the intArg
453 static const char size[16] = {
454 '\0', 'b', 'h', 'w', 'g'
456 static const char format[16] = {
457 '\0', 'x', 'd', 'u', 'o', 't',
458 'a', 'c', 'f', 's', 'i'
460 assert(MDTsizemask == 0xf); /* lowest 4 bits */
461 assert(MDTformatmask == 0xf0); /* next 4 bits */
462 int count = 16; /* number of entities to print */
463 char sizeSpec = size[intArg & MDTsizemask];
464 char formatSpec = format[(intArg & MDTformatmask) >> 4];
465 assert(sizeSpec != '\0');
466 assert(formatSpec != '\0');
467 // adjust count such that 16 lines are printed
468 switch (intArg & MDTformatmask) {
469 case MDTstring: case MDTinsn:
470 break; /* no modification needed */
471 default:
472 // all cases drop through:
473 switch (intArg & MDTsizemask) {
474 case MDTbyte:
475 case MDThalfword:
476 count *= 2;
477 case MDTword:
478 count *= 2;
479 case MDTgiantword:
480 count *= 2;
482 break;
484 QString spec;
485 spec.sprintf("/%d%c%c", count, sizeSpec, formatSpec);
487 return makeCmdString(DCexamine, spec, strArg);
490 if (cmds[cmd].argsNeeded == GdbCmdInfo::argStringNum)
492 // line numbers are zero-based
493 if (cmd == DCuntil || cmd == DCbreakline ||
494 cmd == DCtbreakline || cmd == DCinfoline)
496 intArg++;
498 if (cmd == DCinfoline)
500 // must split off file name part
501 int slash = strArg.findRev('/');
502 if (slash >= 0)
503 strArg = strArg.right(strArg.length()-slash-1);
505 cmdString.sprintf(cmds[cmd].fmt, strArg.latin1(), intArg);
507 else
509 cmdString.sprintf(cmds[cmd].fmt, intArg, strArg.latin1());
511 return cmdString;
514 QString GdbDriver::makeCmdString(DbgCommand cmd, QString strArg1, QString strArg2)
516 assert(cmd >= 0 && cmd < NUM_CMDS);
517 assert(cmds[cmd].argsNeeded == GdbCmdInfo::argString2);
519 normalizeStringArg(strArg1);
520 normalizeStringArg(strArg2);
522 SIZED_QString(cmdString, MAX_FMTLEN+strArg1.length()+strArg2.length());
523 cmdString.sprintf(cmds[cmd].fmt, strArg1.latin1(), strArg2.latin1());
524 return cmdString;
527 QString GdbDriver::makeCmdString(DbgCommand cmd, int intArg1, int intArg2)
529 assert(cmd >= 0 && cmd < NUM_CMDS);
530 assert(cmds[cmd].argsNeeded == GdbCmdInfo::argNum2);
532 SIZED_QString(cmdString, MAX_FMTLEN+60);
533 cmdString.sprintf(cmds[cmd].fmt, intArg1, intArg2);
534 return cmdString;
537 CmdQueueItem* GdbDriver::executeCmd(DbgCommand cmd, bool clearLow)
539 assert(cmd >= 0 && cmd < NUM_CMDS);
540 assert(cmds[cmd].argsNeeded == GdbCmdInfo::argNone);
542 if (cmd == DCrun) {
543 m_haveCoreFile = false;
546 return executeCmdString(cmd, cmds[cmd].fmt, clearLow);
549 CmdQueueItem* GdbDriver::executeCmd(DbgCommand cmd, QString strArg,
550 bool clearLow)
552 return executeCmdString(cmd, makeCmdString(cmd, strArg), clearLow);
555 CmdQueueItem* GdbDriver::executeCmd(DbgCommand cmd, int intArg,
556 bool clearLow)
559 return executeCmdString(cmd, makeCmdString(cmd, intArg), clearLow);
562 CmdQueueItem* GdbDriver::executeCmd(DbgCommand cmd, QString strArg, int intArg,
563 bool clearLow)
565 return executeCmdString(cmd, makeCmdString(cmd, strArg, intArg), clearLow);
568 CmdQueueItem* GdbDriver::executeCmd(DbgCommand cmd, QString strArg1, QString strArg2,
569 bool clearLow)
571 return executeCmdString(cmd, makeCmdString(cmd, strArg1, strArg2), clearLow);
574 CmdQueueItem* GdbDriver::executeCmd(DbgCommand cmd, int intArg1, int intArg2,
575 bool clearLow)
577 return executeCmdString(cmd, makeCmdString(cmd, intArg1, intArg2), clearLow);
580 CmdQueueItem* GdbDriver::queueCmd(DbgCommand cmd, QueueMode mode)
582 return queueCmdString(cmd, cmds[cmd].fmt, mode);
585 CmdQueueItem* GdbDriver::queueCmd(DbgCommand cmd, QString strArg,
586 QueueMode mode)
588 return queueCmdString(cmd, makeCmdString(cmd, strArg), mode);
591 CmdQueueItem* GdbDriver::queueCmd(DbgCommand cmd, int intArg,
592 QueueMode mode)
594 return queueCmdString(cmd, makeCmdString(cmd, intArg), mode);
597 CmdQueueItem* GdbDriver::queueCmd(DbgCommand cmd, QString strArg, int intArg,
598 QueueMode mode)
600 return queueCmdString(cmd, makeCmdString(cmd, strArg, intArg), mode);
603 CmdQueueItem* GdbDriver::queueCmd(DbgCommand cmd, QString strArg1, QString strArg2,
604 QueueMode mode)
606 return queueCmdString(cmd, makeCmdString(cmd, strArg1, strArg2), mode);
609 void GdbDriver::terminate()
611 kill(SIGTERM);
612 m_state = DSidle;
615 void GdbDriver::detachAndTerminate()
617 kill(SIGINT);
618 flushCommands();
619 executeCmdString(DCinitialize, "detach\nquit\n", true);
622 void GdbDriver::interruptInferior()
624 kill(SIGINT);
625 // remove accidentally queued commands
626 flushHiPriQueue();
629 static bool isErrorExpr(const char* output)
631 return
632 strncmp(output, "Cannot access memory at", 23) == 0 ||
633 strncmp(output, "Attempt to dereference a generic pointer", 40) == 0 ||
634 strncmp(output, "Attempt to take contents of ", 28) == 0 ||
635 strncmp(output, "Attempt to use a type name as an expression", 43) == 0 ||
636 strncmp(output, "There is no member or method named", 34) == 0 ||
637 strncmp(output, "A parse error in expression", 27) == 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 >= 300
667 union Qt2QChar {
668 short s;
669 struct {
670 uchar row;
671 uchar cell;
672 } qch;
674 #endif
676 VarTree* GdbDriver::parseQCharArray(const char* output, bool wantErrorValue, bool qt3like)
678 VarTree* variable = 0;
681 * Parse off white space. gdb sometimes prints white space first if the
682 * printed array leaded to an error.
684 const char* p = output;
685 while (isspace(*p))
686 p++;
688 // check if this is an error indicating that gdb does not know about QString::null
689 if (cmds[DCprintQStringStruct].fmt == printQStringStructFmt &&
690 strncmp(p, "Internal error: could not find static variable null", 51) == 0)
692 /* QString::null doesn't work, use an alternate expression */
693 cmds[DCprintQStringStruct].fmt = printQStringStructNoNullFmt;
694 // continue and let parseOffErrorExpr catch the error
697 // special case: empty string (0 repetitions)
698 if (strncmp(p, "Invalid number 0 of repetitions", 31) == 0)
700 variable = new VarTree(QString(), VarTree::NKplain);
701 variable->m_value = "\"\"";
702 return variable;
705 // check for error conditions
706 if (parseErrorMessage(p, variable, wantErrorValue))
707 return variable;
709 // parse the array
711 // find '='
712 p = strchr(p, '=');
713 if (p == 0) {
714 goto error;
716 // skip white space
717 do {
718 p++;
719 } while (isspace(*p));
721 if (*p == '{')
723 // this is the real data
724 p++; /* skip '{' */
726 // parse the array
727 QString result;
728 QString repeatCount;
729 enum { wasNothing, wasChar, wasRepeat } lastThing = wasNothing;
731 * A matrix for separators between the individual "things"
732 * that are added to the string. The first index is a bool,
733 * the second index is from the enum above.
735 static const char* separator[2][3] = {
736 { "\"", 0, ", \"" }, /* normal char is added */
737 { "'", "\", '", ", '" } /* repeated char is added */
740 while (isdigit(*p)) {
741 // parse a number
742 char* end;
743 unsigned short value = (unsigned short) strtoul(p, &end, 0);
744 if (end == p)
745 goto error; /* huh? no valid digits */
746 // skip separator and search for a repeat count
747 p = end;
748 while (isspace(*p) || *p == ',')
749 p++;
750 bool repeats = strncmp(p, "<repeats ", 9) == 0;
751 if (repeats) {
752 const char* start = p;
753 p = strchr(p+9, '>'); /* search end and advance */
754 if (p == 0)
755 goto error;
756 p++; /* skip '>' */
757 repeatCount = FROM_LATIN1(start, p-start);
758 while (isspace(*p) || *p == ',')
759 p++;
761 // p is now at the next char (or the end)
763 // interpret the value as a QChar
764 // TODO: make cross-architecture compatible
765 QChar ch;
766 if (qt3like) {
767 ch = QChar(value);
768 } else {
769 #if QT_VERSION < 300
770 (unsigned short&)ch = value;
771 #else
772 Qt2QChar c;
773 c.s = value;
774 ch.setRow(c.qch.row);
775 ch.setCell(c.qch.cell);
776 #endif
779 // escape a few frequently used characters
780 char escapeCode = '\0';
781 switch (ch.latin1()) {
782 case '\n': escapeCode = 'n'; break;
783 case '\r': escapeCode = 'r'; break;
784 case '\t': escapeCode = 't'; break;
785 case '\b': escapeCode = 'b'; break;
786 case '\"': escapeCode = '\"'; break;
787 case '\\': escapeCode = '\\'; break;
788 case '\0': if (value == 0) { escapeCode = '0'; } break;
791 // add separator
792 result += separator[repeats][lastThing];
793 // add char
794 if (escapeCode != '\0') {
795 result += '\\';
796 ch = escapeCode;
798 result += ch;
800 // fixup repeat count and lastThing
801 if (repeats) {
802 result += "' ";
803 result += repeatCount;
804 lastThing = wasRepeat;
805 } else {
806 lastThing = wasChar;
809 if (*p != '}')
810 goto error;
812 // closing quote
813 if (lastThing == wasChar)
814 result += "\"";
816 // assign the value
817 variable = new VarTree(QString(), VarTree::NKplain);
818 variable->m_value = result;
820 else if (strncmp(p, "true", 4) == 0)
822 variable = new VarTree(QString(), VarTree::NKplain);
823 variable->m_value = "QString::null";
825 else if (strncmp(p, "false", 5) == 0)
827 variable = new VarTree(QString(), VarTree::NKplain);
828 variable->m_value = "(null)";
830 else
831 goto error;
832 return variable;
834 error:
835 if (wantErrorValue) {
836 variable = new VarTree(QString(), VarTree::NKplain);
837 variable->m_value = "internal parse error";
839 return variable;
842 static VarTree* parseVar(const char*& s)
844 const char* p = s;
846 // skip whitespace
847 while (isspace(*p))
848 p++;
850 QString name;
851 VarTree::NameKind kind;
852 if (!parseName(p, name, kind)) {
853 return 0;
856 // go for '='
857 while (isspace(*p))
858 p++;
859 if (*p != '=') {
860 TRACE(QString().sprintf("parse error: = not found after %s", (const char*)name));
861 return 0;
863 // skip the '=' and more whitespace
864 p++;
865 while (isspace(*p))
866 p++;
868 VarTree* variable = new VarTree(name, kind);
869 variable->setDeleteChildren(true);
871 if (!parseValue(p, variable)) {
872 delete variable;
873 return 0;
875 s = p;
876 return variable;
879 static void skipNested(const char*& s, char opening, char closing)
881 const char* p = s;
883 // parse a nested type
884 int nest = 1;
885 p++;
887 * Search for next matching `closing' char, skipping nested pairs of
888 * `opening' and `closing'.
890 while (*p && nest > 0) {
891 if (*p == opening) {
892 nest++;
893 } else if (*p == closing) {
894 nest--;
896 p++;
898 if (nest > 0) {
899 TRACE(QString().sprintf("parse error: mismatching %c%c at %-20.20s", opening, closing, s));
901 s = p;
904 void skipString(const char*& p)
906 moreStrings:
907 // opening quote
908 char quote = *p++;
909 while (*p != quote) {
910 if (*p == '\\') {
911 // skip escaped character
912 // no special treatment for octal values necessary
913 p++;
915 // simply return if no more characters
916 if (*p == '\0')
917 return;
918 p++;
920 // closing quote
921 p++;
923 * Strings can consist of several parts, some of which contain repeated
924 * characters.
926 if (quote == '\'') {
927 // look ahaead for <repeats 123 times>
928 const char* q = p+1;
929 while (isspace(*q))
930 q++;
931 if (strncmp(q, "<repeats ", 9) == 0) {
932 p = q+9;
933 while (*p != '\0' && *p != '>')
934 p++;
935 if (*p != '\0') {
936 p++; /* skip the '>' */
940 // is the string continued?
941 if (*p == ',') {
942 // look ahead for another quote
943 const char* q = p+1;
944 while (isspace(*q))
945 q++;
946 if (*q == '"' || *q == '\'') {
947 // yes!
948 p = q;
949 goto moreStrings;
952 /* very long strings are followed by `...' */
953 if (*p == '.' && p[1] == '.' && p[2] == '.') {
954 p += 3;
958 static void skipNestedWithString(const char*& s, char opening, char closing)
960 const char* p = s;
962 // parse a nested expression
963 int nest = 1;
964 p++;
966 * Search for next matching `closing' char, skipping nested pairs of
967 * `opening' and `closing' as well as strings.
969 while (*p && nest > 0) {
970 if (*p == opening) {
971 nest++;
972 } else if (*p == closing) {
973 nest--;
974 } else if (*p == '\'' || *p == '\"') {
975 skipString(p);
976 continue;
978 p++;
980 if (nest > 0) {
981 TRACE(QString().sprintf("parse error: mismatching %c%c at %-20.20s", opening, closing, s));
983 s = p;
986 inline void skipName(const char*& p)
988 // allow : (for enumeration values) and $ and . (for _vtbl.)
989 while (isalnum(*p) || *p == '_' || *p == ':' || *p == '$' || *p == '.')
990 p++;
993 static bool parseName(const char*& s, QString& name, VarTree::NameKind& kind)
995 kind = VarTree::NKplain;
997 const char* p = s;
998 // examples of names:
999 // name
1000 // <Object>
1001 // <string<a,b<c>,7> >
1003 if (*p == '<') {
1004 skipNested(p, '<', '>');
1005 name = FROM_LATIN1(s, p - s);
1006 kind = VarTree::NKtype;
1008 else
1010 // name, which might be "static"; allow dot for "_vtbl."
1011 skipName(p);
1012 if (p == s) {
1013 TRACE(QString().sprintf("parse error: not a name %-20.20s", s));
1014 return false;
1016 int len = p - s;
1017 if (len == 6 && strncmp(s, "static", 6) == 0) {
1018 kind = VarTree::NKstatic;
1020 // its a static variable, name comes now
1021 while (isspace(*p))
1022 p++;
1023 s = p;
1024 skipName(p);
1025 if (p == s) {
1026 TRACE(QString().sprintf("parse error: not a name after static %-20.20s", s));
1027 return false;
1029 len = p - s;
1031 name = FROM_LATIN1(s, len);
1033 // return the new position
1034 s = p;
1035 return true;
1038 static bool parseValue(const char*& s, VarTree* variable)
1040 variable->m_value = "";
1042 repeat:
1043 if (*s == '{') {
1044 s++;
1045 if (!parseNested(s, variable)) {
1046 return false;
1048 // must be the closing brace
1049 if (*s != '}') {
1050 TRACE("parse error: missing } of " + variable->getText());
1051 return false;
1053 s++;
1054 // final white space
1055 while (isspace(*s))
1056 s++;
1057 } else {
1058 // examples of leaf values (cannot be the empty string):
1059 // 123
1060 // -123
1061 // 23.575e+37
1062 // 0x32a45
1063 // @0x012ab4
1064 // (DwContentType&) @0x8123456: {...}
1065 // 0x32a45 "text"
1066 // 10 '\n'
1067 // <optimized out>
1068 // 0x823abc <Array<int> virtual table>
1069 // (void (*)()) 0x8048480 <f(E *, char)>
1070 // (E *) 0xbffff450
1071 // red
1072 // &parseP (HTMLClueV *, char *)
1074 const char*p = s;
1076 // check for type
1077 QString type;
1078 if (*p == '(') {
1079 skipNested(p, '(', ')');
1081 while (isspace(*p))
1082 p++;
1083 variable->m_value = FROM_LATIN1(s, p - s);
1086 bool reference = false;
1087 if (*p == '@') {
1088 // skip reference marker
1089 p++;
1090 reference = true;
1092 const char* start = p;
1093 if (*p == '-')
1094 p++;
1096 // some values consist of more than one token
1097 bool checkMultiPart = false;
1099 if (p[0] == '0' && p[1] == 'x') {
1100 // parse hex number
1101 p += 2;
1102 while (isxdigit(*p))
1103 p++;
1106 * Assume this is a pointer, but only if it's not a reference, since
1107 * references can't be expanded.
1109 if (!reference) {
1110 variable->m_varKind = VarTree::VKpointer;
1111 } else {
1113 * References are followed by a colon, in which case we'll
1114 * find the value following the reference address.
1116 if (*p == ':') {
1117 p++;
1118 } else {
1119 // Paranoia. (Can this happen, i.e. reference not followed by ':'?)
1120 reference = false;
1123 checkMultiPart = true;
1124 } else if (isdigit(*p)) {
1125 // parse decimal number, possibly a float
1126 while (isdigit(*p))
1127 p++;
1128 if (*p == '.') { /* TODO: obey i18n? */
1129 // fractional part
1130 p++;
1131 while (isdigit(*p))
1132 p++;
1134 if (*p == 'e' || *p == 'E') {
1135 p++;
1136 // exponent
1137 if (*p == '-' || *p == '+')
1138 p++;
1139 while (isdigit(*p))
1140 p++;
1143 // for char variables there is the char, eg. 10 '\n'
1144 checkMultiPart = true;
1145 } else if (*p == '<') {
1146 // e.g. <optimized out>
1147 skipNested(p, '<', '>');
1148 } else if (*p == '"' || *p == '\'') {
1149 // character may have multipart: '\000' <repeats 11 times>
1150 checkMultiPart = *p == '\'';
1151 // found a string
1152 skipString(p);
1153 } else if (*p == '&') {
1154 // function pointer
1155 p++;
1156 skipName(p);
1157 while (isspace(*p)) {
1158 p++;
1160 if (*p == '(') {
1161 skipNested(p, '(', ')');
1163 } else {
1164 // must be an enumeration value
1165 skipName(p);
1167 variable->m_value += FROM_LATIN1(start, p - start);
1169 if (checkMultiPart) {
1170 // white space
1171 while (isspace(*p))
1172 p++;
1173 // may be followed by a string or <...>
1174 start = p;
1176 if (*p == '"' || *p == '\'') {
1177 skipString(p);
1178 } else if (*p == '<') {
1179 // if this value is part of an array, it might be followed
1180 // by <repeats 15 times>, which we don't skip here
1181 if (strncmp(p, "<repeats ", 9) != 0)
1182 skipNested(p, '<', '>');
1184 if (p != start) {
1185 // there is always a blank before the string,
1186 // which we will include in the final string value
1187 variable->m_value += FROM_LATIN1(start-1, (p - start)+1);
1188 // if this was a pointer, reset that flag since we
1189 // now got the value
1190 variable->m_varKind = VarTree::VKsimple;
1194 if (variable->m_value.length() == 0) {
1195 TRACE("parse error: no value for " + variable->getText());
1196 return false;
1199 // final white space
1200 while (isspace(*p))
1201 p++;
1202 s = p;
1205 * If this was a reference, the value follows. It might even be a
1206 * composite variable!
1208 if (reference) {
1209 goto repeat;
1212 if (variable->m_varKind == VarTree::VKpointer) {
1213 variable->setDelayedExpanding(true);
1217 return true;
1220 static bool parseNested(const char*& s, VarTree* variable)
1222 // could be a structure or an array
1223 while (isspace(*s))
1224 s++;
1226 const char* p = s;
1227 bool isStruct = false;
1229 * If there is a name followed by an = or an < -- which starts a type
1230 * name -- or "static", it is a structure
1232 if (*p == '<' || *p == '}') {
1233 isStruct = true;
1234 } else if (strncmp(p, "static ", 7) == 0) {
1235 isStruct = true;
1236 } else if (isalpha(*p) || *p == '_' || *p == '$') {
1237 // look ahead for a comma after the name
1238 skipName(p);
1239 while (isspace(*p))
1240 p++;
1241 if (*p == '=') {
1242 isStruct = true;
1244 p = s; /* rescan the name */
1246 if (isStruct) {
1247 if (!parseVarSeq(p, variable)) {
1248 return false;
1250 variable->m_varKind = VarTree::VKstruct;
1251 } else {
1252 if (!parseValueSeq(p, variable)) {
1253 return false;
1255 variable->m_varKind = VarTree::VKarray;
1257 s = p;
1258 return true;
1261 static bool parseVarSeq(const char*& s, VarTree* variable)
1263 // parse a comma-separated sequence of variables
1264 VarTree* var = variable; /* var != 0 to indicate success if empty seq */
1265 for (;;) {
1266 if (*s == '}')
1267 break;
1268 if (strncmp(s, "<No data fields>}", 17) == 0)
1270 // no member variables, so break out immediately
1271 s += 16; /* go to the closing brace */
1272 break;
1274 var = parseVar(s);
1275 if (var == 0)
1276 break; /* syntax error */
1277 variable->appendChild(var);
1278 if (*s != ',')
1279 break;
1280 // skip the comma and whitespace
1281 s++;
1282 while (isspace(*s))
1283 s++;
1285 return var != 0;
1288 static bool parseValueSeq(const char*& s, VarTree* variable)
1290 // parse a comma-separated sequence of variables
1291 int index = 0;
1292 bool good;
1293 for (;;) {
1294 QString name;
1295 name.sprintf("[%d]", index);
1296 VarTree* var = new VarTree(name, VarTree::NKplain);
1297 var->setDeleteChildren(true);
1298 good = parseValue(s, var);
1299 if (!good) {
1300 delete var;
1301 return false;
1303 // a value may be followed by "<repeats 45 times>"
1304 if (strncmp(s, "<repeats ", 9) == 0) {
1305 s += 9;
1306 char* end;
1307 int l = strtol(s, &end, 10);
1308 if (end == s || strncmp(end, " times>", 7) != 0) {
1309 // should not happen
1310 delete var;
1311 return false;
1313 TRACE(QString().sprintf("found <repeats %d times> in array", l));
1314 // replace name and advance index
1315 name.sprintf("[%d .. %d]", index, index+l-1);
1316 var->setText(name);
1317 index += l;
1318 // skip " times>" and space
1319 s = end+7;
1320 // possible final space
1321 while (isspace(*s))
1322 s++;
1323 } else {
1324 index++;
1326 variable->appendChild(var);
1327 if (*s != ',') {
1328 break;
1330 // skip the comma and whitespace
1331 s++;
1332 while (isspace(*s))
1333 s++;
1334 // sometimes there is a closing brace after a comma
1335 // if (*s == '}')
1336 // break;
1338 return true;
1342 * Parses a stack frame.
1344 static void parseFrameInfo(const char*& s, QString& func,
1345 QString& file, int& lineNo, DbgAddr& address)
1347 const char* p = s;
1349 // next may be a hexadecimal address
1350 if (*p == '0') {
1351 const char* start = p;
1352 p++;
1353 if (*p == 'x')
1354 p++;
1355 while (isxdigit(*p))
1356 p++;
1357 address = FROM_LATIN1(start, p-start);
1358 if (strncmp(p, " in ", 4) == 0)
1359 p += 4;
1360 } else {
1361 address = DbgAddr();
1363 const char* start = p;
1364 // check for special signal handler frame
1365 if (strncmp(p, "<signal handler called>", 23) == 0) {
1366 func = FROM_LATIN1(start, 23);
1367 file = QString();
1368 lineNo = -1;
1369 s = p+23;
1370 if (*s == '\n')
1371 s++;
1372 return;
1374 // search opening parenthesis
1375 while (*p != '\0' && *p != '(')
1376 p++;
1377 if (*p == '\0') {
1378 func = start;
1379 file = QString();
1380 lineNo = -1;
1381 s = p;
1382 return;
1385 * Skip parameters. But notice that for complicated conversion
1386 * functions (eg. "operator int(**)()()", ie. convert to pointer to
1387 * pointer to function) as well as operator()(...) we have to skip
1388 * additional pairs of parentheses. Furthermore, recent gdbs write the
1389 * demangled name followed by the arguments in a pair of parentheses,
1390 * where the demangled name can end in "const".
1392 do {
1393 skipNestedWithString(p, '(', ')');
1394 while (isspace(*p))
1395 p++;
1396 // skip "const"
1397 if (strncmp(p, "const", 5) == 0) {
1398 p += 5;
1399 while (isspace(*p))
1400 p++;
1402 } while (*p == '(');
1404 // check for file position
1405 if (strncmp(p, "at ", 3) == 0) {
1406 p += 3;
1407 const char* fileStart = p;
1408 // go for the end of the line
1409 while (*p != '\0' && *p != '\n')
1410 p++;
1411 // search back for colon
1412 const char* colon = p;
1413 do {
1414 --colon;
1415 } while (*colon != ':');
1416 file = FROM_LATIN1(fileStart, colon-fileStart);
1417 lineNo = atoi(colon+1)-1;
1418 // skip new-line
1419 if (*p != '\0')
1420 p++;
1421 } else {
1422 // check for "from shared lib"
1423 if (strncmp(p, "from ", 5) == 0) {
1424 p += 5;
1425 // go for the end of the line
1426 while (*p != '\0' && *p != '\n')
1427 p++;
1428 // skip new-line
1429 if (*p != '\0')
1430 p++;
1432 file = "";
1433 lineNo = -1;
1435 // construct the function name (including file info)
1436 if (*p == '\0') {
1437 func = start;
1438 } else {
1439 func = FROM_LATIN1(start, p-start-1); /* don't include \n */
1441 s = p;
1444 * Replace \n (and whitespace around it) in func by a blank. We cannot
1445 * use QString::simplifyWhiteSpace() for this because this would also
1446 * simplify space that belongs to a string arguments that gdb sometimes
1447 * prints in the argument lists of the function.
1449 ASSERT(!isspace(func[0].latin1())); /* there must be non-white before first \n */
1450 int nl = 0;
1451 while ((nl = func.find('\n', nl)) >= 0) {
1452 // search back to the beginning of the whitespace
1453 int startWhite = nl;
1454 do {
1455 --startWhite;
1456 } while (isspace(func[startWhite].latin1()));
1457 startWhite++;
1458 // search forward to the end of the whitespace
1459 do {
1460 nl++;
1461 } while (isspace(func[nl].latin1()));
1462 // replace
1463 func.replace(startWhite, nl-startWhite, " ");
1464 /* continue searching for more \n's at this place: */
1465 nl = startWhite+1;
1471 * Parses a stack frame including its frame number
1473 static bool parseFrame(const char*& s, int& frameNo, QString& func,
1474 QString& file, int& lineNo, DbgAddr& address)
1476 // Example:
1477 // #1 0x8048881 in Dl::Dl (this=0xbffff418, r=3214) at testfile.cpp:72
1478 // Breakpoint 3, Cl::f(int) const (this=0xbffff3c0, x=17) at testfile.cpp:155
1480 // must start with a hash mark followed by number
1481 // or with "Breakpoint " followed by number and comma
1482 if (s[0] == '#') {
1483 if (!isdigit(s[1]))
1484 return false;
1485 s++; /* skip the hash mark */
1486 } else if (strncmp(s, "Breakpoint ", 11) == 0) {
1487 if (!isdigit(s[11]))
1488 return false;
1489 s += 11; /* skip "Breakpoint" */
1490 } else
1491 return false;
1493 // frame number
1494 frameNo = atoi(s);
1495 while (isdigit(*s))
1496 s++;
1497 // space and comma
1498 while (isspace(*s) || *s == ',')
1499 s++;
1500 parseFrameInfo(s, func, file, lineNo, address);
1501 return true;
1504 void GdbDriver::parseBackTrace(const char* output, QList<StackFrame>& stack)
1506 QString func, file;
1507 int lineNo, frameNo;
1508 DbgAddr address;
1510 while (::parseFrame(output, frameNo, func, file, lineNo, address)) {
1511 StackFrame* frm = new StackFrame;
1512 frm->frameNo = frameNo;
1513 frm->fileName = file;
1514 frm->lineNo = lineNo;
1515 frm->address = address;
1516 frm->var = new VarTree(func, VarTree::NKplain);
1517 stack.append(frm);
1521 bool GdbDriver::parseFrameChange(const char* output, int& frameNo,
1522 QString& file, int& lineNo, DbgAddr& address)
1524 QString func;
1525 return ::parseFrame(output, frameNo, func, file, lineNo, address);
1529 bool GdbDriver::parseBreakList(const char* output, QList<Breakpoint>& brks)
1531 // skip first line, which is the headline
1532 const char* p = strchr(output, '\n');
1533 if (p == 0)
1534 return false;
1535 p++;
1536 if (*p == '\0')
1537 return false;
1539 // split up a line
1540 QString location;
1541 QString address;
1542 int hits = 0;
1543 uint ignoreCount = 0;
1544 QString condition;
1545 const char* end;
1546 char* dummy;
1547 while (*p != '\0') {
1548 // get Num
1549 long bpNum = strtol(p, &dummy, 10); /* don't care about overflows */
1550 p = dummy;
1551 // get Type
1552 while (isspace(*p))
1553 p++;
1554 Breakpoint::Type bpType;
1555 if (strncmp(p, "breakpoint", 10) == 0) {
1556 bpType = Breakpoint::breakpoint;
1557 p += 10;
1558 } else if (strncmp(p, "hw watchpoint", 13) == 0) {
1559 bpType = Breakpoint::watchpoint;
1560 p += 13;
1561 } else if (strncmp(p, "watchpoint", 10) == 0) {
1562 bpType = Breakpoint::watchpoint;
1563 p += 10;
1565 while (isspace(*p))
1566 p++;
1567 if (*p == '\0')
1568 break;
1569 // get Disp
1570 char disp = *p++;
1571 while (*p != '\0' && !isspace(*p)) /* "keep" or "del" */
1572 p++;
1573 while (isspace(*p))
1574 p++;
1575 if (*p == '\0')
1576 break;
1577 // get Enb
1578 char enable = *p++;
1579 while (*p != '\0' && !isspace(*p)) /* "y" or "n" */
1580 p++;
1581 while (isspace(*p))
1582 p++;
1583 if (*p == '\0')
1584 break;
1585 // the address, if present
1586 if (bpType == Breakpoint::breakpoint &&
1587 strncmp(p, "0x", 2) == 0)
1589 const char* start = p;
1590 while (*p != '\0' && !isspace(*p))
1591 p++;
1592 address = FROM_LATIN1(start, p-start);
1593 while (isspace(*p) && *p != '\n')
1594 p++;
1595 if (*p == '\0')
1596 break;
1597 } else {
1598 address = QString();
1600 // remainder is location, hit and ignore count, condition
1601 hits = 0;
1602 ignoreCount = 0;
1603 condition = QString();
1604 end = strchr(p, '\n');
1605 if (end == 0) {
1606 location = p;
1607 p += location.length();
1608 } else {
1609 location = FROM_LATIN1(p, end-p).stripWhiteSpace();
1610 p = end+1; /* skip over \n */
1613 // may be continued in next line
1614 while (isspace(*p)) { /* p points to beginning of line */
1615 // skip white space at beginning of line
1616 while (isspace(*p))
1617 p++;
1619 // seek end of line
1620 end = strchr(p, '\n');
1621 if (end == 0)
1622 end = p+strlen(p);
1624 if (strncmp(p, "breakpoint already hit", 22) == 0) {
1625 // extract the hit count
1626 p += 22;
1627 hits = strtol(p, &dummy, 10);
1628 TRACE(QString().sprintf("hit count %d", hits));
1629 } else if (strncmp(p, "stop only if ", 13) == 0) {
1630 // extract condition
1631 p += 13;
1632 condition = FROM_LATIN1(p, end-p).stripWhiteSpace();
1633 TRACE("condition: "+condition);
1634 } else if (strncmp(p, "ignore next ", 12) == 0) {
1635 // extract ignore count
1636 p += 12;
1637 ignoreCount = strtol(p, &dummy, 10);
1638 TRACE(QString().sprintf("ignore count %d", ignoreCount));
1639 } else {
1640 // indeed a continuation
1641 location += " " + FROM_LATIN1(p, end-p).stripWhiteSpace();
1643 p = end;
1644 if (*p != '\0')
1645 p++; /* skip '\n' */
1647 Breakpoint* bp = new Breakpoint;
1648 bp->id = bpNum;
1649 bp->type = bpType;
1650 bp->temporary = disp == 'd';
1651 bp->enabled = enable == 'y';
1652 bp->location = location;
1653 bp->address = address;
1654 bp->hitCount = hits;
1655 bp->ignoreCount = ignoreCount;
1656 bp->condition = condition;
1657 brks.append(bp);
1659 return true;
1662 bool GdbDriver::parseThreadList(const char* output, QList<ThreadInfo>& threads)
1664 if (strcmp(output, "\n") == 0 || strncmp(output, "No stack.", 9) == 0) {
1665 // no threads
1666 return true;
1669 int id;
1670 QString systag;
1671 QString func, file;
1672 int lineNo;
1673 DbgAddr address;
1675 const char* p = output;
1676 while (*p != '\0') {
1677 // seach look for thread id, watching out for the focus indicator
1678 bool hasFocus = false;
1679 while (isspace(*p)) /* may be \n from prev line: see "No stack" below */
1680 p++;
1681 if (*p == '*') {
1682 hasFocus = true;
1683 p++;
1684 // there follows only whitespace
1686 char* end;
1687 id = strtol(p, &end, 10);
1688 if (p == end) {
1689 // syntax error: no number found; bail out
1690 return true;
1692 p = end;
1694 // skip space
1695 while (isspace(*p))
1696 p++;
1699 * Now follows the thread's SYSTAG. It is terminated by two blanks.
1701 end = strstr(p, " ");
1702 if (end == 0) {
1703 // syntax error; bail out
1704 return true;
1706 systag = FROM_LATIN1(p, end-p);
1707 p = end+2;
1710 * Now follows a standard stack frame. Sometimes, however, gdb
1711 * catches a thread at an instant where it doesn't have a stack.
1713 if (strncmp(p, "[No stack.]", 11) != 0) {
1714 ::parseFrameInfo(p, func, file, lineNo, address);
1715 } else {
1716 func = "[No stack]";
1717 file = QString();
1718 lineNo = -1;
1719 address = QString();
1720 p += 11; /* \n is skipped above */
1723 ThreadInfo* thr = new ThreadInfo;
1724 thr->id = id;
1725 thr->threadName = systag;
1726 thr->hasFocus = hasFocus;
1727 thr->function = func;
1728 thr->fileName = file;
1729 thr->lineNo = lineNo;
1730 thr->address = address;
1731 threads.append(thr);
1733 return true;
1736 bool GdbDriver::parseBreakpoint(const char* output, int& id,
1737 QString& file, int& lineNo)
1739 const char* o = output;
1740 // skip lines of that begin with "(Cannot find"
1741 while (strncmp(o, "(Cannot find", 12) == 0) {
1742 o = strchr(o, '\n');
1743 if (o == 0)
1744 return false;
1745 o++; /* skip newline */
1748 if (strncmp(o, "Breakpoint ", 11) != 0)
1749 return false;
1751 // breakpoint id
1752 output += 11; /* skip "Breakpoint " */
1753 char* p;
1754 int num = strtoul(output, &p, 10);
1755 if (p == o)
1756 return false;
1758 // file name
1759 char* fileStart = strstr(p, "file ");
1760 if (fileStart == 0)
1761 return false;
1762 fileStart += 5;
1764 // line number
1765 char* numStart = strstr(fileStart, ", line ");
1766 QString fileName = FROM_LATIN1(fileStart, numStart-fileStart);
1767 numStart += 7;
1768 int line = strtoul(numStart, &p, 10);
1769 if (numStart == p)
1770 return false;
1772 id = num;
1773 file = fileName;
1774 lineNo = line-1; /* zero-based! */
1775 return true;
1778 void GdbDriver::parseLocals(const char* output, QList<VarTree>& newVars)
1780 // check for possible error conditions
1781 if (strncmp(output, "No symbol table", 15) == 0)
1783 return;
1786 while (*output != '\0') {
1787 while (isspace(*output))
1788 output++;
1789 if (*output == '\0')
1790 break;
1791 // skip occurrences of "No locals" and "No args"
1792 if (strncmp(output, "No locals", 9) == 0 ||
1793 strncmp(output, "No arguments", 12) == 0)
1795 output = strchr(output, '\n');
1796 if (output == 0) {
1797 break;
1799 continue;
1802 VarTree* variable = parseVar(output);
1803 if (variable == 0) {
1804 break;
1806 // do not add duplicates
1807 for (VarTree* o = newVars.first(); o != 0; o = newVars.next()) {
1808 if (o->getText() == variable->getText()) {
1809 delete variable;
1810 goto skipDuplicate;
1813 newVars.append(variable);
1814 skipDuplicate:;
1818 bool GdbDriver::parsePrintExpr(const char* output, bool wantErrorValue, VarTree*& var)
1820 // check for error conditions
1821 if (parseErrorMessage(output, var, wantErrorValue))
1823 return false;
1824 } else {
1825 // parse the variable
1826 var = parseVar(output);
1827 return true;
1831 bool GdbDriver::parseChangeWD(const char* output, QString& message)
1833 bool isGood = false;
1834 message = QString(output).simplifyWhiteSpace();
1835 if (message.isEmpty()) {
1836 message = i18n("New working directory: ") + m_programWD;
1837 isGood = true;
1839 return isGood;
1842 bool GdbDriver::parseChangeExecutable(const char* output, QString& message)
1844 message = output;
1846 m_haveCoreFile = false;
1849 * The command is successful if there is no output or the single
1850 * message (no debugging symbols found)...
1852 return
1853 output[0] == '\0' ||
1854 strcmp(output, "(no debugging symbols found)...") == 0;
1857 bool GdbDriver::parseCoreFile(const char* output)
1859 // if command succeeded, gdb emits a line starting with "#0 "
1860 m_haveCoreFile = strstr(output, "\n#0 ") != 0;
1861 return m_haveCoreFile;
1864 uint GdbDriver::parseProgramStopped(const char* output, QString& message)
1866 // optionally: "program changed, rereading symbols",
1867 // followed by:
1868 // "Program exited normally"
1869 // "Program terminated with wignal SIGSEGV"
1870 // "Program received signal SIGINT" or other signal
1871 // "Breakpoint..."
1873 // go through the output, line by line, checking what we have
1874 const char* start = output - 1;
1875 uint flags = SFprogramActive;
1876 message = QString();
1877 do {
1878 start++; /* skip '\n' */
1880 if (strncmp(start, "Program ", 8) == 0 ||
1881 strncmp(start, "ptrace: ", 8) == 0) {
1883 * When we receive a signal, the program remains active.
1885 * Special: If we "stopped" in a corefile, the string "Program
1886 * terminated with signal"... is displayed. (Normally, we see
1887 * "Program received signal"... when a signal happens.)
1889 if (strncmp(start, "Program exited", 14) == 0 ||
1890 (strncmp(start, "Program terminated", 18) == 0 && !m_haveCoreFile) ||
1891 strncmp(start, "ptrace: ", 8) == 0)
1893 flags &= ~SFprogramActive;
1896 // set message
1897 const char* endOfMessage = strchr(start, '\n');
1898 if (endOfMessage == 0)
1899 endOfMessage = start + strlen(start);
1900 message = FROM_LATIN1(start, endOfMessage-start);
1901 } else if (strncmp(start, "Breakpoint ", 11) == 0) {
1903 * We stopped at a (permanent) breakpoint (gdb doesn't tell us
1904 * that it stopped at a temporary breakpoint).
1906 flags |= SFrefreshBreak;
1907 } else if (strstr(start, "re-reading symbols.") != 0) {
1908 flags |= SFrefreshSource;
1911 // next line, please
1912 start = strchr(start, '\n');
1913 } while (start != 0);
1916 * Gdb only notices when new threads have appeared, but not when a
1917 * thread finishes. So we always have to assume that the list of
1918 * threads has changed.
1920 flags |= SFrefreshThreads;
1922 return flags;
1925 void GdbDriver::parseSharedLibs(const char* output, QStrList& shlibs)
1927 if (strncmp(output, "No shared libraries loaded", 26) == 0)
1928 return;
1930 // parse the table of shared libraries
1932 // strip off head line
1933 output = strchr(output, '\n');
1934 if (output == 0)
1935 return;
1936 output++; /* skip '\n' */
1937 QString shlibName;
1938 while (*output != '\0') {
1939 // format of a line is
1940 // 0x404c5000 0x40580d90 Yes /lib/libc.so.5
1941 // 3 blocks of non-space followed by space
1942 for (int i = 0; *output != '\0' && i < 3; i++) {
1943 while (*output != '\0' && !isspace(*output)) { /* non-space */
1944 output++;
1946 while (isspace(*output)) { /* space */
1947 output++;
1950 if (*output == '\0')
1951 return;
1952 const char* start = output;
1953 output = strchr(output, '\n');
1954 if (output == 0)
1955 output = start + strlen(start);
1956 shlibName = FROM_LATIN1(start, output-start);
1957 if (*output != '\0')
1958 output++;
1959 shlibs.append(shlibName);
1960 TRACE("found shared lib " + shlibName);
1964 bool GdbDriver::parseFindType(const char* output, QString& type)
1966 if (strncmp(output, "type = ", 7) != 0)
1967 return false;
1970 * Everything else is the type. We strip off all white-space from the
1971 * type.
1973 output += 7;
1974 type = output;
1975 type.replace(QRegExp("\\s+"), "");
1976 return true;
1979 void GdbDriver::parseRegisters(const char* output, QList<RegisterInfo>& regs)
1981 if (strncmp(output, "The program has no registers now", 32) == 0) {
1982 return;
1985 QString regName;
1986 QString value;
1988 // parse register values
1989 while (*output != '\0')
1991 // skip space at the start of the line
1992 while (isspace(*output))
1993 output++;
1995 // register name
1996 const char* start = output;
1997 while (*output != '\0' && !isspace(*output))
1998 output++;
1999 if (*output == '\0')
2000 break;
2001 regName = FROM_LATIN1(start, output-start);
2003 // skip space
2004 while (isspace(*output))
2005 output++;
2006 // the rest of the line is the register value
2007 start = output;
2008 output = strchr(output,'\n');
2009 if (output == 0)
2010 output = start + strlen(start);
2011 value = FROM_LATIN1(start, output-start).simplifyWhiteSpace();
2013 if (*output != '\0')
2014 output++; /* skip '\n' */
2016 RegisterInfo* reg = new RegisterInfo;
2017 reg->regName = regName;
2020 * We split the raw from the cooked values. For this purpose, we
2021 * split off the first token (separated by whitespace). It is the
2022 * raw value. The remainder of the line is the cooked value.
2024 int pos = value.find(' ');
2025 if (pos < 0) {
2026 reg->rawValue = value;
2027 reg->cookedValue = QString();
2028 } else {
2029 reg->rawValue = value.left(pos);
2030 reg->cookedValue = value.mid(pos+1,value.length());
2032 * Some modern gdbs explicitly say: "0.1234 (raw 0x3e4567...)".
2033 * Here the raw value is actually in the second part.
2035 if (reg->cookedValue.left(5) == "(raw ") {
2036 QString raw = reg->cookedValue.right(reg->cookedValue.length()-5);
2037 if (raw[raw.length()-1] == ')') /* remove closing bracket */
2038 raw = raw.left(raw.length()-1);
2039 reg->cookedValue = reg->rawValue;
2040 reg->rawValue = raw;
2044 regs.append(reg);
2048 bool GdbDriver::parseInfoLine(const char* output, QString& addrFrom, QString& addrTo)
2050 const char* start = strstr(output, "starts at address ");
2051 if (start == 0)
2052 return false;
2054 start += 18;
2055 const char* p = start;
2056 while (*p != '\0' && !isspace(*p))
2057 p++;
2058 addrFrom = FROM_LATIN1(start, p-start);
2060 start = strstr(p, "and ends at ");
2061 if (start == 0)
2062 return false;
2064 start += 12;
2065 p = start;
2066 while (*p != '\0' && !isspace(*p))
2067 p++;
2068 addrTo = FROM_LATIN1(start, p-start);
2070 return true;
2073 void GdbDriver::parseDisassemble(const char* output, QList<DisassembledCode>& code)
2075 code.clear();
2077 if (strncmp(output, "Dump of assembler", 17) != 0) {
2078 // error message?
2079 DisassembledCode c;
2080 c.code = output;
2081 code.append(new DisassembledCode(c));
2082 return;
2085 // remove first line
2086 const char* p = strchr(output, '\n');
2087 if (p == 0)
2088 return; /* not a regular output */
2090 p++;
2092 // remove last line
2093 const char* end = strstr(output, "\nEnd of assembler");
2094 if (end == 0)
2095 end = p + strlen(p);
2097 DbgAddr address;
2099 // remove function offsets from the lines
2100 while (p != end)
2102 const char* start = p;
2103 // address
2104 while (p != end && !isspace(*p))
2105 p++;
2106 address = FROM_LATIN1(start, p-start);
2108 // function name (enclosed in '<>', followed by ':')
2109 while (p != end && *p != '<')
2110 p++;
2111 if (*p == '<')
2112 skipNested(p, '<', '>');
2113 if (*p == ':')
2114 p++;
2116 // space until code
2117 while (p != end && isspace(*p))
2118 p++;
2120 // code until end of line
2121 start = p;
2122 while (p != end && *p != '\n')
2123 p++;
2124 if (p != end) /* include '\n' */
2125 p++;
2127 DisassembledCode* c = new DisassembledCode;
2128 c->address = address;
2129 c->code = FROM_LATIN1(start, p-start);
2130 code.append(c);
2134 QString GdbDriver::parseMemoryDump(const char* output, QList<MemoryDump>& memdump)
2136 if (isErrorExpr(output)) {
2137 // error; strip space
2138 QString msg = output;
2139 return msg.stripWhiteSpace();
2142 const char* p = output; /* save typing */
2143 DbgAddr addr;
2144 QString dump;
2146 // the address
2147 while (*p != 0) {
2148 const char* start = p;
2149 while (*p != '\0' && *p != ':' && !isspace(*p))
2150 p++;
2151 addr = FROM_LATIN1(start, p-start);
2152 if (*p != ':') {
2153 // parse function offset
2154 while (isspace(*p))
2155 p++;
2156 start = p;
2157 while (*p != '\0' && !(*p == ':' && isspace(p[1])))
2158 p++;
2159 addr.fnoffs = FROM_LATIN1(start, p-start);
2161 if (*p == ':')
2162 p++;
2163 // skip space; this may skip a new-line char!
2164 while (isspace(*p))
2165 p++;
2166 // everything to the end of the line is the memory dump
2167 const char* end = strchr(p, '\n');
2168 if (end != 0) {
2169 dump = FROM_LATIN1(p, end-p);
2170 p = end+1;
2171 } else {
2172 dump = FROM_LATIN1(p, strlen(p));
2173 p += strlen(p);
2175 MemoryDump* md = new MemoryDump;
2176 md->address = addr;
2177 md->dump = dump;
2178 memdump.append(md);
2181 return QString();
2185 #include "gdbdriver.moc"