KDebugger does not deal with the debugger's default command line;
[kdbg.git] / kdbg / gdbdriver.cpp
blob2d0fd2ae6e189f904e2969cb28a991fecf8ce4c6
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_promptMinLen = 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 if (m_defaultCmd.isEmpty()) {
215 return defaultGdb();
216 } else {
217 return m_defaultCmd;
221 bool GdbDriver::startup(QString cmdStr)
223 if (!DebuggerDriver::startup(cmdStr))
224 return false;
226 static const char gdbInitialize[] =
228 * Work around buggy gdbs that do command line editing even if they
229 * are not on a tty. The readline library echos every command back
230 * in this case, which is confusing for us.
232 "set editing off\n"
233 "set confirm off\n"
234 "set print static-members off\n"
235 "set print asm-demangle on\n"
237 * Write a short macro that prints all locals: local variables and
238 * function arguments.
240 "define kdbg__alllocals\n"
241 "info locals\n" /* local vars supersede args with same name */
242 "info args\n" /* therefore, arguments must come last */
243 "end\n"
244 // change prompt string and synchronize with gdb
245 "set prompt " PROMPT "\n"
248 executeCmdString(DCinitialize, gdbInitialize, false);
250 // assume that QString::null is ok
251 cmds[DCprintQStringStruct].fmt = printQStringStructFmt;
253 return true;
256 void GdbDriver::commandFinished(CmdQueueItem* cmd)
258 // command string must be committed
259 if (!cmd->m_committed) {
260 // not commited!
261 TRACE("calling " + (__PRETTY_FUNCTION__ + (" with uncommited command:\n\t" +
262 cmd->m_cmdString)));
263 return;
266 switch (cmd->m_cmd) {
267 case DCinitialize:
268 // get version number from preamble
270 int len;
271 QRegExp GDBVersion("\\nGDB [0-9]+\\.[0-9]+");
272 int offset = GDBVersion.match(m_output, 0, &len);
273 if (offset >= 0) {
274 char* start = m_output + offset + 5; // skip "\nGDB "
275 char* end;
276 m_gdbMajor = strtol(start, &end, 10);
277 m_gdbMinor = strtol(end + 1, 0, 10); // skip "."
278 if (start == end) {
279 // nothing was parsed
280 m_gdbMajor = 4;
281 m_gdbMinor = 16;
283 } else {
284 // assume some default version (what would make sense?)
285 m_gdbMajor = 4;
286 m_gdbMinor = 16;
288 // use a feasible core-file command
289 if (m_gdbMajor > 4 || (m_gdbMajor == 4 && m_gdbMinor >= 16)) {
290 cmds[DCcorefile].fmt = "target core %s\n";
291 } else {
292 cmds[DCcorefile].fmt = "core-file %s\n";
295 break;
296 default:;
299 /* ok, the command is ready */
300 emit commandReceived(cmd, m_output);
302 switch (cmd->m_cmd) {
303 case DCcorefile:
304 case DCinfolinemain:
305 case DCframe:
306 case DCattach:
307 case DCrun:
308 case DCcont:
309 case DCstep:
310 case DCstepi:
311 case DCnext:
312 case DCnexti:
313 case DCfinish:
314 case DCuntil:
315 parseMarker();
316 default:;
321 * The --fullname option makes gdb send a special normalized sequence print
322 * each time the program stops and at some other points. The sequence has
323 * the form "\032\032filename:lineno:charoffset:(beg|middle):address".
325 void GdbDriver::parseMarker()
327 char* startMarker = strstr(m_output, "\032\032");
328 if (startMarker == 0)
329 return;
331 // extract the marker
332 startMarker += 2;
333 TRACE(QString("found marker: ") + startMarker);
334 char* endMarker = strchr(startMarker, '\n');
335 if (endMarker == 0)
336 return;
338 *endMarker = '\0';
340 // extract filename and line number
341 static QRegExp MarkerRE(":[0-9]+:[0-9]+:[begmidl]+:0x");
343 int len;
344 int lineNoStart = MarkerRE.match(startMarker, 0, &len);
345 if (lineNoStart >= 0) {
346 int lineNo = atoi(startMarker + lineNoStart+1);
348 // get address
349 const char* addrStart = startMarker + lineNoStart + len - 2;
350 DbgAddr address = QString(addrStart).stripWhiteSpace();
352 // now show the window
353 startMarker[lineNoStart] = '\0'; /* split off file name */
354 emit activateFileLine(startMarker, lineNo-1, address);
360 * Escapes characters that might lead to problems when they appear on gdb's
361 * command line.
363 static void normalizeStringArg(QString& arg)
366 * Remove trailing backslashes. This approach is a little simplistic,
367 * but we know that there is at the moment no case where a trailing
368 * backslash would make sense.
370 while (!arg.isEmpty() && arg[arg.length()-1] == '\\') {
371 arg = arg.left(arg.length()-1);
376 #if QT_VERSION < 200
377 #define LATIN1(str) ((str).isNull() ? "" : (str).data())
378 #else
379 #define LATIN1(str) (str).latin1()
380 #endif
382 QString GdbDriver::makeCmdString(DbgCommand cmd, QString strArg)
384 assert(cmd >= 0 && cmd < NUM_CMDS);
385 assert(cmds[cmd].argsNeeded == GdbCmdInfo::argString);
387 normalizeStringArg(strArg);
389 if (cmd == DCcd) {
390 // need the working directory when parsing the output
391 m_programWD = strArg;
392 } else if (cmd == DCsetargs) {
393 // attach saved redirection
394 #if QT_VERSION < 200
395 strArg.detach();
396 #endif
397 strArg += m_redirect;
400 SIZED_QString(cmdString, MAX_FMTLEN+strArg.length());
401 cmdString.sprintf(cmds[cmd].fmt, LATIN1(strArg));
402 return cmdString;
405 QString GdbDriver::makeCmdString(DbgCommand cmd, int intArg)
407 assert(cmd >= 0 && cmd < NUM_CMDS);
408 assert(cmds[cmd].argsNeeded == GdbCmdInfo::argNum);
410 SIZED_QString(cmdString, MAX_FMTLEN+30);
412 cmdString.sprintf(cmds[cmd].fmt, intArg);
413 return cmdString;
416 QString GdbDriver::makeCmdString(DbgCommand cmd, QString strArg, int intArg)
418 assert(cmd >= 0 && cmd < NUM_CMDS);
419 assert(cmds[cmd].argsNeeded == GdbCmdInfo::argStringNum ||
420 cmds[cmd].argsNeeded == GdbCmdInfo::argNumString ||
421 cmd == DCexamine ||
422 cmd == DCtty);
424 normalizeStringArg(strArg);
426 SIZED_QString(cmdString, MAX_FMTLEN+30+strArg.length());
428 if (cmd == DCtty)
431 * intArg specifies which channels should be redirected to
432 * /dev/null. It is a value or'ed together from RDNstdin,
433 * RDNstdout, RDNstderr. We store the value for a later DCsetargs
434 * command.
436 * Note: We rely on that after the DCtty a DCsetargs will follow,
437 * which will ultimately apply the redirection.
439 static const char* const runRedir[8] = {
441 " </dev/null",
442 " >/dev/null",
443 " </dev/null >/dev/null",
444 " 2>/dev/null",
445 " </dev/null 2>/dev/null",
446 " >/dev/null 2>&1",
447 " </dev/null >/dev/null 2>&1"
449 if (strArg.isEmpty())
450 intArg = 7; /* failsafe if no tty */
451 m_redirect = runRedir[intArg & 7];
453 return makeCmdString(DCtty, strArg); /* note: no problem if strArg empty */
456 if (cmd == DCexamine) {
457 // make a format specifier from the intArg
458 static const char size[16] = {
459 '\0', 'b', 'h', 'w', 'g'
461 static const char format[16] = {
462 '\0', 'x', 'd', 'u', 'o', 't',
463 'a', 'c', 'f', 's', 'i'
465 assert(MDTsizemask == 0xf); /* lowest 4 bits */
466 assert(MDTformatmask == 0xf0); /* next 4 bits */
467 int count = 16; /* number of entities to print */
468 char sizeSpec = size[intArg & MDTsizemask];
469 char formatSpec = format[(intArg & MDTformatmask) >> 4];
470 assert(sizeSpec != '\0');
471 assert(formatSpec != '\0');
472 // adjust count such that 16 lines are printed
473 switch (intArg & MDTformatmask) {
474 case MDTstring: case MDTinsn:
475 break; /* no modification needed */
476 default:
477 // all cases drop through:
478 switch (intArg & MDTsizemask) {
479 case MDTbyte:
480 case MDThalfword:
481 count *= 2;
482 case MDTword:
483 count *= 2;
484 case MDTgiantword:
485 count *= 2;
487 break;
489 QString spec;
490 spec.sprintf("/%d%c%c", count, sizeSpec, formatSpec);
492 return makeCmdString(DCexamine, spec, strArg);
495 if (cmds[cmd].argsNeeded == GdbCmdInfo::argStringNum)
497 // line numbers are zero-based
498 if (cmd == DCuntil || cmd == DCbreakline ||
499 cmd == DCtbreakline || cmd == DCinfoline)
501 intArg++;
503 if (cmd == DCinfoline)
505 // must split off file name part
506 int slash = strArg.findRev('/');
507 if (slash >= 0)
508 strArg = strArg.right(strArg.length()-slash-1);
510 cmdString.sprintf(cmds[cmd].fmt, LATIN1(strArg), intArg);
512 else
514 cmdString.sprintf(cmds[cmd].fmt, intArg, LATIN1(strArg));
516 return cmdString;
519 QString GdbDriver::makeCmdString(DbgCommand cmd, QString strArg1, QString strArg2)
521 assert(cmd >= 0 && cmd < NUM_CMDS);
522 assert(cmds[cmd].argsNeeded == GdbCmdInfo::argString2);
524 normalizeStringArg(strArg1);
525 normalizeStringArg(strArg2);
527 SIZED_QString(cmdString, MAX_FMTLEN+strArg1.length()+strArg2.length());
528 cmdString.sprintf(cmds[cmd].fmt, LATIN1(strArg1), LATIN1(strArg2));
529 return cmdString;
532 QString GdbDriver::makeCmdString(DbgCommand cmd, int intArg1, int intArg2)
534 assert(cmd >= 0 && cmd < NUM_CMDS);
535 assert(cmds[cmd].argsNeeded == GdbCmdInfo::argNum2);
537 SIZED_QString(cmdString, MAX_FMTLEN+60);
538 cmdString.sprintf(cmds[cmd].fmt, intArg1, intArg2);
539 return cmdString;
542 CmdQueueItem* GdbDriver::executeCmd(DbgCommand cmd, bool clearLow)
544 assert(cmd >= 0 && cmd < NUM_CMDS);
545 assert(cmds[cmd].argsNeeded == GdbCmdInfo::argNone);
547 if (cmd == DCrun) {
548 m_haveCoreFile = false;
551 return executeCmdString(cmd, cmds[cmd].fmt, clearLow);
554 CmdQueueItem* GdbDriver::executeCmd(DbgCommand cmd, QString strArg,
555 bool clearLow)
557 return executeCmdString(cmd, makeCmdString(cmd, strArg), clearLow);
560 CmdQueueItem* GdbDriver::executeCmd(DbgCommand cmd, int intArg,
561 bool clearLow)
564 return executeCmdString(cmd, makeCmdString(cmd, intArg), clearLow);
567 CmdQueueItem* GdbDriver::executeCmd(DbgCommand cmd, QString strArg, int intArg,
568 bool clearLow)
570 return executeCmdString(cmd, makeCmdString(cmd, strArg, intArg), clearLow);
573 CmdQueueItem* GdbDriver::executeCmd(DbgCommand cmd, QString strArg1, QString strArg2,
574 bool clearLow)
576 return executeCmdString(cmd, makeCmdString(cmd, strArg1, strArg2), clearLow);
579 CmdQueueItem* GdbDriver::executeCmd(DbgCommand cmd, int intArg1, int intArg2,
580 bool clearLow)
582 return executeCmdString(cmd, makeCmdString(cmd, intArg1, intArg2), clearLow);
585 CmdQueueItem* GdbDriver::queueCmd(DbgCommand cmd, QueueMode mode)
587 return queueCmdString(cmd, cmds[cmd].fmt, mode);
590 CmdQueueItem* GdbDriver::queueCmd(DbgCommand cmd, QString strArg,
591 QueueMode mode)
593 return queueCmdString(cmd, makeCmdString(cmd, strArg), mode);
596 CmdQueueItem* GdbDriver::queueCmd(DbgCommand cmd, int intArg,
597 QueueMode mode)
599 return queueCmdString(cmd, makeCmdString(cmd, intArg), mode);
602 CmdQueueItem* GdbDriver::queueCmd(DbgCommand cmd, QString strArg, int intArg,
603 QueueMode mode)
605 return queueCmdString(cmd, makeCmdString(cmd, strArg, intArg), mode);
608 CmdQueueItem* GdbDriver::queueCmd(DbgCommand cmd, QString strArg1, QString strArg2,
609 QueueMode mode)
611 return queueCmdString(cmd, makeCmdString(cmd, strArg1, strArg2), mode);
614 void GdbDriver::terminate()
616 kill(SIGTERM);
617 m_state = DSidle;
620 void GdbDriver::detachAndTerminate()
622 kill(SIGINT);
623 flushCommands();
624 executeCmdString(DCinitialize, "detach\nquit\n", true);
627 void GdbDriver::interruptInferior()
629 kill(SIGINT);
630 // remove accidentally queued commands
631 flushHiPriQueue();
634 static bool isErrorExpr(const char* output)
636 return
637 strncmp(output, "Cannot access memory at", 23) == 0 ||
638 strncmp(output, "Attempt to dereference a generic pointer", 40) == 0 ||
639 strncmp(output, "Attempt to take contents of ", 28) == 0 ||
640 strncmp(output, "Attempt to use a type name as an expression", 43) == 0 ||
641 strncmp(output, "There is no member or method named", 34) == 0 ||
642 strncmp(output, "No symbol \"", 11) == 0 ||
643 strncmp(output, "Internal error: ", 16) == 0;
647 * Returns true if the output is an error message. If wantErrorValue is
648 * true, a new VarTree object is created and filled with the error message.
650 static bool parseErrorMessage(const char* output,
651 VarTree*& variable, bool wantErrorValue)
653 if (isErrorExpr(output))
655 if (wantErrorValue) {
656 // put the error message as value in the variable
657 variable = new VarTree(QString(), VarTree::NKplain);
658 const char* endMsg = strchr(output, '\n');
659 if (endMsg == 0)
660 endMsg = output + strlen(output);
661 variable->m_value = FROM_LATIN1(output, endMsg-output);
662 } else {
663 variable = 0;
665 return true;
667 return false;
670 #if QT_VERSION < 200
671 struct QChar {
672 // this is the XChar2b on X11
673 uchar row;
674 uchar cell;
675 static QString toQString(QChar* unicode, int len);
676 QChar() : row(0), cell(0) { }
677 QChar(char c) : row(0), cell(c) { }
678 operator char() const { return row ? 0 : cell; }
681 QString QChar::toQString(QChar* unicode, int len)
683 QString result(len+1);
684 char* data = result.data();
685 data[len] = '\0';
686 while (len >= 0) {
687 data[len] = unicode[len].cell;
688 --len;
690 return result;
692 #endif
693 #if QT_VERSION >= 300
694 union Qt2QChar {
695 short s;
696 struct {
697 uchar row;
698 uchar cell;
699 } qch;
701 #endif
703 VarTree* GdbDriver::parseQCharArray(const char* output, bool wantErrorValue, bool qt3like)
705 VarTree* variable = 0;
708 * Parse off white space. gdb sometimes prints white space first if the
709 * printed array leaded to an error.
711 const char* p = output;
712 while (isspace(*p))
713 p++;
715 // check if this is an error indicating that gdb does not know about QString::null
716 if (cmds[DCprintQStringStruct].fmt == printQStringStructFmt &&
717 strncmp(p, "Internal error: could not find static variable null", 51) == 0)
719 /* QString::null doesn't work, use an alternate expression */
720 cmds[DCprintQStringStruct].fmt = printQStringStructNoNullFmt;
721 // continue and let parseOffErrorExpr catch the error
724 // special case: empty string (0 repetitions)
725 if (strncmp(p, "Invalid number 0 of repetitions", 31) == 0)
727 variable = new VarTree(QString(), VarTree::NKplain);
728 variable->m_value = "\"\"";
729 return variable;
732 // check for error conditions
733 if (parseErrorMessage(p, variable, wantErrorValue))
734 return variable;
736 // parse the array
738 // find '='
739 p = strchr(p, '=');
740 if (p == 0) {
741 goto error;
743 // skip white space
744 do {
745 p++;
746 } while (isspace(*p));
748 if (*p == '{')
750 // this is the real data
751 p++; /* skip '{' */
753 // parse the array
754 QString result;
755 QString repeatCount;
756 enum { wasNothing, wasChar, wasRepeat } lastThing = wasNothing;
758 * A matrix for separators between the individual "things"
759 * that are added to the string. The first index is a bool,
760 * the second index is from the enum above.
762 static const char* separator[2][3] = {
763 { "\"", 0, ", \"" }, /* normal char is added */
764 { "'", "\", '", ", '" } /* repeated char is added */
767 while (isdigit(*p)) {
768 // parse a number
769 char* end;
770 unsigned short value = (unsigned short) strtoul(p, &end, 0);
771 if (end == p)
772 goto error; /* huh? no valid digits */
773 // skip separator and search for a repeat count
774 p = end;
775 while (isspace(*p) || *p == ',')
776 p++;
777 bool repeats = strncmp(p, "<repeats ", 9) == 0;
778 if (repeats) {
779 const char* start = p;
780 p = strchr(p+9, '>'); /* search end and advance */
781 if (p == 0)
782 goto error;
783 p++; /* skip '>' */
784 repeatCount = FROM_LATIN1(start, p-start);
785 while (isspace(*p) || *p == ',')
786 p++;
788 // p is now at the next char (or the end)
790 // interpret the value as a QChar
791 // TODO: make cross-architecture compatible
792 QChar ch;
793 if (qt3like) {
794 ch = QChar(value);
795 } else {
796 #if QT_VERSION < 300
797 (unsigned short&)ch = value;
798 #else
799 Qt2QChar c;
800 c.s = value;
801 ch.setRow(c.qch.row);
802 ch.setCell(c.qch.cell);
803 #endif
806 // escape a few frequently used characters
807 char escapeCode = '\0';
808 switch (char(ch)) {
809 case '\n': escapeCode = 'n'; break;
810 case '\r': escapeCode = 'r'; break;
811 case '\t': escapeCode = 't'; break;
812 case '\b': escapeCode = 'b'; break;
813 case '\"': escapeCode = '\"'; break;
814 case '\\': escapeCode = '\\'; break;
815 #if QT_VERSION < 200
816 // since we only deal with ascii values must always escape '\0'
817 case '\0': escapeCode = '0'; break;
818 #else
819 case '\0': if (value == 0) { escapeCode = '0'; } break;
820 #endif
823 // add separator
824 result += separator[repeats][lastThing];
825 // add char
826 if (escapeCode != '\0') {
827 result += '\\';
828 ch = escapeCode;
830 result += ch;
832 // fixup repeat count and lastThing
833 if (repeats) {
834 result += "' ";
835 result += repeatCount;
836 lastThing = wasRepeat;
837 } else {
838 lastThing = wasChar;
841 if (*p != '}')
842 goto error;
844 // closing quote
845 if (lastThing == wasChar)
846 result += "\"";
848 // assign the value
849 variable = new VarTree(QString(), VarTree::NKplain);
850 variable->m_value = result;
852 else if (strncmp(p, "true", 4) == 0)
854 variable = new VarTree(QString(), VarTree::NKplain);
855 variable->m_value = "QString::null";
857 else if (strncmp(p, "false", 5) == 0)
859 variable = new VarTree(QString(), VarTree::NKplain);
860 variable->m_value = "(null)";
862 else
863 goto error;
864 return variable;
866 error:
867 if (wantErrorValue) {
868 variable = new VarTree(QString(), VarTree::NKplain);
869 variable->m_value = "internal parse error";
871 return variable;
874 static VarTree* parseVar(const char*& s)
876 const char* p = s;
878 // skip whitespace
879 while (isspace(*p))
880 p++;
882 QString name;
883 VarTree::NameKind kind;
884 if (!parseName(p, name, kind)) {
885 return 0;
888 // go for '='
889 while (isspace(*p))
890 p++;
891 if (*p != '=') {
892 TRACE(QString().sprintf("parse error: = not found after %s", (const char*)name));
893 return 0;
895 // skip the '=' and more whitespace
896 p++;
897 while (isspace(*p))
898 p++;
900 VarTree* variable = new VarTree(name, kind);
901 variable->setDeleteChildren(true);
903 if (!parseValue(p, variable)) {
904 delete variable;
905 return 0;
907 s = p;
908 return variable;
911 static void skipNested(const char*& s, char opening, char closing)
913 const char* p = s;
915 // parse a nested type
916 int nest = 1;
917 p++;
919 * Search for next matching `closing' char, skipping nested pairs of
920 * `opening' and `closing'.
922 while (*p && nest > 0) {
923 if (*p == opening) {
924 nest++;
925 } else if (*p == closing) {
926 nest--;
928 p++;
930 if (nest > 0) {
931 TRACE(QString().sprintf("parse error: mismatching %c%c at %-20.20s", opening, closing, s));
933 s = p;
936 void skipString(const char*& p)
938 moreStrings:
939 // opening quote
940 char quote = *p++;
941 while (*p != quote) {
942 if (*p == '\\') {
943 // skip escaped character
944 // no special treatment for octal values necessary
945 p++;
947 // simply return if no more characters
948 if (*p == '\0')
949 return;
950 p++;
952 // closing quote
953 p++;
955 * Strings can consist of several parts, some of which contain repeated
956 * characters.
958 if (quote == '\'') {
959 // look ahaead for <repeats 123 times>
960 const char* q = p+1;
961 while (isspace(*q))
962 q++;
963 if (strncmp(q, "<repeats ", 9) == 0) {
964 p = q+9;
965 while (*p != '\0' && *p != '>')
966 p++;
967 if (*p != '\0') {
968 p++; /* skip the '>' */
972 // is the string continued?
973 if (*p == ',') {
974 // look ahead for another quote
975 const char* q = p+1;
976 while (isspace(*q))
977 q++;
978 if (*q == '"' || *q == '\'') {
979 // yes!
980 p = q;
981 goto moreStrings;
984 /* very long strings are followed by `...' */
985 if (*p == '.' && p[1] == '.' && p[2] == '.') {
986 p += 3;
990 static void skipNestedWithString(const char*& s, char opening, char closing)
992 const char* p = s;
994 // parse a nested expression
995 int nest = 1;
996 p++;
998 * Search for next matching `closing' char, skipping nested pairs of
999 * `opening' and `closing' as well as strings.
1001 while (*p && nest > 0) {
1002 if (*p == opening) {
1003 nest++;
1004 } else if (*p == closing) {
1005 nest--;
1006 } else if (*p == '\'' || *p == '\"') {
1007 skipString(p);
1008 continue;
1010 p++;
1012 if (nest > 0) {
1013 TRACE(QString().sprintf("parse error: mismatching %c%c at %-20.20s", opening, closing, s));
1015 s = p;
1018 inline void skipName(const char*& p)
1020 // allow : (for enumeration values) and $ and . (for _vtbl.)
1021 while (isalnum(*p) || *p == '_' || *p == ':' || *p == '$' || *p == '.')
1022 p++;
1025 static bool parseName(const char*& s, QString& name, VarTree::NameKind& kind)
1027 kind = VarTree::NKplain;
1029 const char* p = s;
1030 // examples of names:
1031 // name
1032 // <Object>
1033 // <string<a,b<c>,7> >
1035 if (*p == '<') {
1036 skipNested(p, '<', '>');
1037 name = FROM_LATIN1(s, p - s);
1038 kind = VarTree::NKtype;
1040 else
1042 // name, which might be "static"; allow dot for "_vtbl."
1043 skipName(p);
1044 if (p == s) {
1045 TRACE(QString().sprintf("parse error: not a name %-20.20s", s));
1046 return false;
1048 int len = p - s;
1049 if (len == 6 && strncmp(s, "static", 6) == 0) {
1050 kind = VarTree::NKstatic;
1052 // its a static variable, name comes now
1053 while (isspace(*p))
1054 p++;
1055 s = p;
1056 skipName(p);
1057 if (p == s) {
1058 TRACE(QString().sprintf("parse error: not a name after static %-20.20s", s));
1059 return false;
1061 len = p - s;
1063 name = FROM_LATIN1(s, len);
1065 // return the new position
1066 s = p;
1067 return true;
1070 static bool parseValue(const char*& s, VarTree* variable)
1072 variable->m_value = "";
1074 repeat:
1075 if (*s == '{') {
1076 s++;
1077 if (!parseNested(s, variable)) {
1078 return false;
1080 // must be the closing brace
1081 if (*s != '}') {
1082 TRACE("parse error: missing } of " + variable->getText());
1083 return false;
1085 s++;
1086 // final white space
1087 while (isspace(*s))
1088 s++;
1089 } else {
1090 // examples of leaf values (cannot be the empty string):
1091 // 123
1092 // -123
1093 // 23.575e+37
1094 // 0x32a45
1095 // @0x012ab4
1096 // (DwContentType&) @0x8123456: {...}
1097 // 0x32a45 "text"
1098 // 10 '\n'
1099 // <optimized out>
1100 // 0x823abc <Array<int> virtual table>
1101 // (void (*)()) 0x8048480 <f(E *, char)>
1102 // (E *) 0xbffff450
1103 // red
1104 // &parseP (HTMLClueV *, char *)
1106 const char*p = s;
1108 // check for type
1109 QString type;
1110 if (*p == '(') {
1111 skipNested(p, '(', ')');
1113 while (isspace(*p))
1114 p++;
1115 variable->m_value = FROM_LATIN1(s, p - s);
1118 bool reference = false;
1119 if (*p == '@') {
1120 // skip reference marker
1121 p++;
1122 reference = true;
1124 const char* start = p;
1125 if (*p == '-')
1126 p++;
1128 // some values consist of more than one token
1129 bool checkMultiPart = false;
1131 if (p[0] == '0' && p[1] == 'x') {
1132 // parse hex number
1133 p += 2;
1134 while (isxdigit(*p))
1135 p++;
1138 * Assume this is a pointer, but only if it's not a reference, since
1139 * references can't be expanded.
1141 if (!reference) {
1142 variable->m_varKind = VarTree::VKpointer;
1143 } else {
1145 * References are followed by a colon, in which case we'll
1146 * find the value following the reference address.
1148 if (*p == ':') {
1149 p++;
1150 } else {
1151 // Paranoia. (Can this happen, i.e. reference not followed by ':'?)
1152 reference = false;
1155 checkMultiPart = true;
1156 } else if (isdigit(*p)) {
1157 // parse decimal number, possibly a float
1158 while (isdigit(*p))
1159 p++;
1160 if (*p == '.') { /* TODO: obey i18n? */
1161 // fractional part
1162 p++;
1163 while (isdigit(*p))
1164 p++;
1166 if (*p == 'e' || *p == 'E') {
1167 p++;
1168 // exponent
1169 if (*p == '-' || *p == '+')
1170 p++;
1171 while (isdigit(*p))
1172 p++;
1175 // for char variables there is the char, eg. 10 '\n'
1176 checkMultiPart = true;
1177 } else if (*p == '<') {
1178 // e.g. <optimized out>
1179 skipNested(p, '<', '>');
1180 } else if (*p == '"' || *p == '\'') {
1181 // character may have multipart: '\000' <repeats 11 times>
1182 checkMultiPart = *p == '\'';
1183 // found a string
1184 skipString(p);
1185 } else if (*p == '&') {
1186 // function pointer
1187 p++;
1188 skipName(p);
1189 while (isspace(*p)) {
1190 p++;
1192 if (*p == '(') {
1193 skipNested(p, '(', ')');
1195 } else {
1196 // must be an enumeration value
1197 skipName(p);
1199 variable->m_value += FROM_LATIN1(start, p - start);
1201 if (checkMultiPart) {
1202 // white space
1203 while (isspace(*p))
1204 p++;
1205 // may be followed by a string or <...>
1206 start = p;
1208 if (*p == '"' || *p == '\'') {
1209 skipString(p);
1210 } else if (*p == '<') {
1211 // if this value is part of an array, it might be followed
1212 // by <repeats 15 times>, which we don't skip here
1213 if (strncmp(p, "<repeats ", 9) != 0)
1214 skipNested(p, '<', '>');
1216 if (p != start) {
1217 // there is always a blank before the string,
1218 // which we will include in the final string value
1219 variable->m_value += FROM_LATIN1(start-1, (p - start)+1);
1220 // if this was a pointer, reset that flag since we
1221 // now got the value
1222 variable->m_varKind = VarTree::VKsimple;
1226 if (variable->m_value.length() == 0) {
1227 TRACE("parse error: no value for " + variable->getText());
1228 return false;
1231 // final white space
1232 while (isspace(*p))
1233 p++;
1234 s = p;
1237 * If this was a reference, the value follows. It might even be a
1238 * composite variable!
1240 if (reference) {
1241 goto repeat;
1244 if (variable->m_varKind == VarTree::VKpointer) {
1245 variable->setDelayedExpanding(true);
1249 return true;
1252 static bool parseNested(const char*& s, VarTree* variable)
1254 // could be a structure or an array
1255 while (isspace(*s))
1256 s++;
1258 const char* p = s;
1259 bool isStruct = false;
1261 * If there is a name followed by an = or an < -- which starts a type
1262 * name -- or "static", it is a structure
1264 if (*p == '<' || *p == '}') {
1265 isStruct = true;
1266 } else if (strncmp(p, "static ", 7) == 0) {
1267 isStruct = true;
1268 } else if (isalpha(*p) || *p == '_' || *p == '$') {
1269 // look ahead for a comma after the name
1270 skipName(p);
1271 while (isspace(*p))
1272 p++;
1273 if (*p == '=') {
1274 isStruct = true;
1276 p = s; /* rescan the name */
1278 if (isStruct) {
1279 if (!parseVarSeq(p, variable)) {
1280 return false;
1282 variable->m_varKind = VarTree::VKstruct;
1283 } else {
1284 if (!parseValueSeq(p, variable)) {
1285 return false;
1287 variable->m_varKind = VarTree::VKarray;
1289 s = p;
1290 return true;
1293 static bool parseVarSeq(const char*& s, VarTree* variable)
1295 // parse a comma-separated sequence of variables
1296 VarTree* var = variable; /* var != 0 to indicate success if empty seq */
1297 for (;;) {
1298 if (*s == '}')
1299 break;
1300 if (strncmp(s, "<No data fields>}", 17) == 0)
1302 // no member variables, so break out immediately
1303 s += 16; /* go to the closing brace */
1304 break;
1306 var = parseVar(s);
1307 if (var == 0)
1308 break; /* syntax error */
1309 variable->appendChild(var);
1310 if (*s != ',')
1311 break;
1312 // skip the comma and whitespace
1313 s++;
1314 while (isspace(*s))
1315 s++;
1317 return var != 0;
1320 static bool parseValueSeq(const char*& s, VarTree* variable)
1322 // parse a comma-separated sequence of variables
1323 int index = 0;
1324 bool good;
1325 for (;;) {
1326 QString name;
1327 name.sprintf("[%d]", index);
1328 VarTree* var = new VarTree(name, VarTree::NKplain);
1329 var->setDeleteChildren(true);
1330 good = parseValue(s, var);
1331 if (!good) {
1332 delete var;
1333 return false;
1335 // a value may be followed by "<repeats 45 times>"
1336 if (strncmp(s, "<repeats ", 9) == 0) {
1337 s += 9;
1338 char* end;
1339 int l = strtol(s, &end, 10);
1340 if (end == s || strncmp(end, " times>", 7) != 0) {
1341 // should not happen
1342 delete var;
1343 return false;
1345 TRACE(QString().sprintf("found <repeats %d times> in array", l));
1346 // replace name and advance index
1347 name.sprintf("[%d .. %d]", index, index+l-1);
1348 var->setText(name);
1349 index += l;
1350 // skip " times>" and space
1351 s = end+7;
1352 // possible final space
1353 while (isspace(*s))
1354 s++;
1355 } else {
1356 index++;
1358 variable->appendChild(var);
1359 if (*s != ',') {
1360 break;
1362 // skip the comma and whitespace
1363 s++;
1364 while (isspace(*s))
1365 s++;
1366 // sometimes there is a closing brace after a comma
1367 // if (*s == '}')
1368 // break;
1370 return true;
1373 #if QT_VERSION < 200
1374 #define ISSPACE(c) isspace((c))
1375 #else
1376 // c is a QChar
1377 #define ISSPACE(c) (c).isSpace()
1378 #endif
1381 * Parses a stack frame.
1383 static void parseFrameInfo(const char*& s, QString& func,
1384 QString& file, int& lineNo, DbgAddr& address)
1386 const char* p = s;
1388 // next may be a hexadecimal address
1389 if (*p == '0') {
1390 const char* start = p;
1391 p++;
1392 if (*p == 'x')
1393 p++;
1394 while (isxdigit(*p))
1395 p++;
1396 address = FROM_LATIN1(start, p-start);
1397 if (strncmp(p, " in ", 4) == 0)
1398 p += 4;
1399 } else {
1400 address = DbgAddr();
1402 const char* start = p;
1403 // check for special signal handler frame
1404 if (strncmp(p, "<signal handler called>", 23) == 0) {
1405 func = FROM_LATIN1(start, 23);
1406 file = QString();
1407 lineNo = -1;
1408 s = p+23;
1409 if (*s == '\n')
1410 s++;
1411 return;
1413 // search opening parenthesis
1414 while (*p != '\0' && *p != '(')
1415 p++;
1416 if (*p == '\0') {
1417 func = start;
1418 file = QString();
1419 lineNo = -1;
1420 s = p;
1421 return;
1424 * Skip parameters. But notice that for complicated conversion
1425 * functions (eg. "operator int(**)()()", ie. convert to pointer to
1426 * pointer to function) as well as operator()(...) we have to skip
1427 * additional pairs of parentheses.
1429 do {
1430 skipNestedWithString(p, '(', ')');
1431 while (isspace(*p))
1432 p++;
1433 } while (*p == '(');
1435 // check for file position
1436 if (strncmp(p, "at ", 3) == 0) {
1437 p += 3;
1438 const char* fileStart = p;
1439 // go for the end of the line
1440 while (*p != '\0' && *p != '\n')
1441 p++;
1442 // search back for colon
1443 const char* colon = p;
1444 do {
1445 --colon;
1446 } while (*colon != ':');
1447 file = FROM_LATIN1(fileStart, colon-fileStart);
1448 lineNo = atoi(colon+1)-1;
1449 // skip new-line
1450 if (*p != '\0')
1451 p++;
1452 } else {
1453 // check for "from shared lib"
1454 if (strncmp(p, "from ", 5) == 0) {
1455 p += 5;
1456 // go for the end of the line
1457 while (*p != '\0' && *p != '\n')
1458 p++;
1459 // skip new-line
1460 if (*p != '\0')
1461 p++;
1463 file = "";
1464 lineNo = -1;
1466 // construct the function name (including file info)
1467 if (*p == '\0') {
1468 func = start;
1469 } else {
1470 func = FROM_LATIN1(start, p-start-1); /* don't include \n */
1472 s = p;
1475 * Replace \n (and whitespace around it) in func by a blank. We cannot
1476 * use QString::simplifyWhiteSpace() for this because this would also
1477 * simplify space that belongs to a string arguments that gdb sometimes
1478 * prints in the argument lists of the function.
1480 ASSERT(!ISSPACE(func[0])); /* there must be non-white before first \n */
1481 int nl = 0;
1482 while ((nl = func.find('\n', nl)) >= 0) {
1483 // search back to the beginning of the whitespace
1484 int startWhite = nl;
1485 do {
1486 --startWhite;
1487 } while (ISSPACE(func[startWhite]));
1488 startWhite++;
1489 // search forward to the end of the whitespace
1490 do {
1491 nl++;
1492 } while (ISSPACE(func[nl]));
1493 // replace
1494 func.replace(startWhite, nl-startWhite, " ");
1495 /* continue searching for more \n's at this place: */
1496 nl = startWhite+1;
1500 #undef ISSPACE
1503 * Parses a stack frame including its frame number
1505 static bool parseFrame(const char*& s, int& frameNo, QString& func,
1506 QString& file, int& lineNo, DbgAddr& address)
1508 // Example:
1509 // #1 0x8048881 in Dl::Dl (this=0xbffff418, r=3214) at testfile.cpp:72
1511 // must start with a hash mark followed by number
1512 if (s[0] != '#' || !isdigit(s[1]))
1513 return false;
1515 s++; /* skip the hash mark */
1516 // frame number
1517 frameNo = atoi(s);
1518 while (isdigit(*s))
1519 s++;
1520 // space
1521 while (isspace(*s))
1522 s++;
1523 parseFrameInfo(s, func, file, lineNo, address);
1524 return true;
1527 void GdbDriver::parseBackTrace(const char* output, QList<StackFrame>& stack)
1529 QString func, file;
1530 int lineNo, frameNo;
1531 DbgAddr address;
1533 while (::parseFrame(output, frameNo, func, file, lineNo, address)) {
1534 StackFrame* frm = new StackFrame;
1535 frm->frameNo = frameNo;
1536 frm->fileName = file;
1537 frm->lineNo = lineNo;
1538 frm->address = address;
1539 frm->var = new VarTree(func, VarTree::NKplain);
1540 stack.append(frm);
1544 bool GdbDriver::parseFrameChange(const char* output, int& frameNo,
1545 QString& file, int& lineNo, DbgAddr& address)
1547 QString func;
1548 return ::parseFrame(output, frameNo, func, file, lineNo, address);
1552 bool GdbDriver::parseBreakList(const char* output, QList<Breakpoint>& brks)
1554 // skip first line, which is the headline
1555 const char* p = strchr(output, '\n');
1556 if (p == 0)
1557 return false;
1558 p++;
1559 if (*p == '\0')
1560 return false;
1562 // split up a line
1563 QString location;
1564 QString address;
1565 int hits = 0;
1566 uint ignoreCount = 0;
1567 QString condition;
1568 const char* end;
1569 char* dummy;
1570 while (*p != '\0') {
1571 // get Num
1572 long bpNum = strtol(p, &dummy, 10); /* don't care about overflows */
1573 p = dummy;
1574 // get Type
1575 while (isspace(*p))
1576 p++;
1577 Breakpoint::Type bpType;
1578 if (strncmp(p, "breakpoint", 10) == 0) {
1579 bpType = Breakpoint::breakpoint;
1580 p += 10;
1581 } else if (strncmp(p, "hw watchpoint", 13) == 0) {
1582 bpType = Breakpoint::watchpoint;
1583 p += 13;
1584 } else if (strncmp(p, "watchpoint", 10) == 0) {
1585 bpType = Breakpoint::watchpoint;
1586 p += 10;
1588 while (isspace(*p))
1589 p++;
1590 if (*p == '\0')
1591 break;
1592 // get Disp
1593 char disp = *p++;
1594 while (*p != '\0' && !isspace(*p)) /* "keep" or "del" */
1595 p++;
1596 while (isspace(*p))
1597 p++;
1598 if (*p == '\0')
1599 break;
1600 // get Enb
1601 char enable = *p++;
1602 while (*p != '\0' && !isspace(*p)) /* "y" or "n" */
1603 p++;
1604 while (isspace(*p))
1605 p++;
1606 if (*p == '\0')
1607 break;
1608 // the address, if present
1609 if (bpType == Breakpoint::breakpoint &&
1610 strncmp(p, "0x", 2) == 0)
1612 const char* start = p;
1613 while (*p != '\0' && !isspace(*p))
1614 p++;
1615 address = FROM_LATIN1(start, p-start);
1616 while (isspace(*p) && *p != '\n')
1617 p++;
1618 if (*p == '\0')
1619 break;
1620 } else {
1621 address = QString();
1623 // remainder is location, hit and ignore count, condition
1624 hits = 0;
1625 ignoreCount = 0;
1626 condition = QString();
1627 end = strchr(p, '\n');
1628 if (end == 0) {
1629 location = p;
1630 p += location.length();
1631 } else {
1632 location = FROM_LATIN1(p, end-p).stripWhiteSpace();
1633 p = end+1; /* skip over \n */
1636 // may be continued in next line
1637 while (isspace(*p)) { /* p points to beginning of line */
1638 // skip white space at beginning of line
1639 while (isspace(*p))
1640 p++;
1642 // seek end of line
1643 end = strchr(p, '\n');
1644 if (end == 0)
1645 end = p+strlen(p);
1647 if (strncmp(p, "breakpoint already hit", 22) == 0) {
1648 // extract the hit count
1649 p += 22;
1650 hits = strtol(p, &dummy, 10);
1651 TRACE(QString().sprintf("hit count %d", hits));
1652 } else if (strncmp(p, "stop only if ", 13) == 0) {
1653 // extract condition
1654 p += 13;
1655 condition = FROM_LATIN1(p, end-p).stripWhiteSpace();
1656 TRACE("condition: "+condition);
1657 } else if (strncmp(p, "ignore next ", 12) == 0) {
1658 // extract ignore count
1659 p += 12;
1660 ignoreCount = strtol(p, &dummy, 10);
1661 TRACE(QString().sprintf("ignore count %d", ignoreCount));
1662 } else {
1663 // indeed a continuation
1664 location += " " + FROM_LATIN1(p, end-p).stripWhiteSpace();
1666 p = end;
1667 if (*p != '\0')
1668 p++; /* skip '\n' */
1670 Breakpoint* bp = new Breakpoint;
1671 bp->id = bpNum;
1672 bp->type = bpType;
1673 bp->temporary = disp == 'd';
1674 bp->enabled = enable == 'y';
1675 bp->location = location;
1676 bp->address = address;
1677 bp->hitCount = hits;
1678 bp->ignoreCount = ignoreCount;
1679 bp->condition = condition;
1680 brks.append(bp);
1682 return true;
1685 bool GdbDriver::parseThreadList(const char* output, QList<ThreadInfo>& threads)
1687 if (strcmp(output, "\n") == 0 || strncmp(output, "No stack.", 9) == 0) {
1688 // no threads
1689 return true;
1692 int id;
1693 QString systag;
1694 QString func, file;
1695 int lineNo;
1696 DbgAddr address;
1698 const char* p = output;
1699 while (*p != '\0') {
1700 // seach look for thread id, watching out for the focus indicator
1701 bool hasFocus = false;
1702 while (isspace(*p)) /* may be \n from prev line: see "No stack" below */
1703 p++;
1704 if (*p == '*') {
1705 hasFocus = true;
1706 p++;
1707 // there follows only whitespace
1709 char* end;
1710 id = strtol(p, &end, 10);
1711 if (p == end) {
1712 // syntax error: no number found; bail out
1713 return true;
1715 p = end;
1717 // skip space
1718 while (isspace(*p))
1719 p++;
1722 * Now follows the thread's SYSTAG. It is terminated by two blanks.
1724 end = strstr(p, " ");
1725 if (end == 0) {
1726 // syntax error; bail out
1727 return true;
1729 systag = FROM_LATIN1(p, end-p);
1730 p = end+2;
1733 * Now follows a standard stack frame. Sometimes, however, gdb
1734 * catches a thread at an instant where it doesn't have a stack.
1736 if (strncmp(p, "[No stack.]", 11) != 0) {
1737 ::parseFrameInfo(p, func, file, lineNo, address);
1738 } else {
1739 func = "[No stack]";
1740 file = QString();
1741 lineNo = -1;
1742 address = QString();
1743 p += 11; /* \n is skipped above */
1746 ThreadInfo* thr = new ThreadInfo;
1747 thr->id = id;
1748 thr->threadName = systag;
1749 thr->hasFocus = hasFocus;
1750 thr->function = func;
1751 thr->fileName = file;
1752 thr->lineNo = lineNo;
1753 thr->address = address;
1754 threads.append(thr);
1756 return true;
1759 bool GdbDriver::parseBreakpoint(const char* output, int& id,
1760 QString& file, int& lineNo)
1762 const char* o = output;
1763 // skip lines of that begin with "(Cannot find"
1764 while (strncmp(o, "(Cannot find", 12) == 0) {
1765 o = strchr(o, '\n');
1766 if (o == 0)
1767 return false;
1768 o++; /* skip newline */
1771 if (strncmp(o, "Breakpoint ", 11) != 0)
1772 return false;
1774 // breakpoint id
1775 output += 11; /* skip "Breakpoint " */
1776 char* p;
1777 int num = strtoul(output, &p, 10);
1778 if (p == o)
1779 return false;
1781 // file name
1782 char* fileStart = strstr(p, "file ");
1783 if (fileStart == 0)
1784 return false;
1785 fileStart += 5;
1787 // line number
1788 char* numStart = strstr(fileStart, ", line ");
1789 QString fileName = FROM_LATIN1(fileStart, numStart-fileStart);
1790 numStart += 7;
1791 int line = strtoul(numStart, &p, 10);
1792 if (numStart == p)
1793 return false;
1795 id = num;
1796 file = fileName;
1797 lineNo = line-1; /* zero-based! */
1798 return true;
1801 void GdbDriver::parseLocals(const char* output, QList<VarTree>& newVars)
1803 // check for possible error conditions
1804 if (strncmp(output, "No symbol table", 15) == 0)
1806 return;
1809 while (*output != '\0') {
1810 while (isspace(*output))
1811 output++;
1812 if (*output == '\0')
1813 break;
1814 // skip occurrences of "No locals" and "No args"
1815 if (strncmp(output, "No locals", 9) == 0 ||
1816 strncmp(output, "No arguments", 12) == 0)
1818 output = strchr(output, '\n');
1819 if (output == 0) {
1820 break;
1822 continue;
1825 VarTree* variable = parseVar(output);
1826 if (variable == 0) {
1827 break;
1829 // do not add duplicates
1830 for (VarTree* o = newVars.first(); o != 0; o = newVars.next()) {
1831 if (o->getText() == variable->getText()) {
1832 delete variable;
1833 goto skipDuplicate;
1836 newVars.append(variable);
1837 skipDuplicate:;
1841 bool GdbDriver::parsePrintExpr(const char* output, bool wantErrorValue, VarTree*& var)
1843 // check for error conditions
1844 if (parseErrorMessage(output, var, wantErrorValue))
1846 return false;
1847 } else {
1848 // parse the variable
1849 var = parseVar(output);
1850 return true;
1854 bool GdbDriver::parseChangeWD(const char* output, QString& message)
1856 bool isGood = false;
1857 message = QString(output).simplifyWhiteSpace();
1858 if (message.isEmpty()) {
1859 message = i18n("New working directory: ") + m_programWD;
1860 isGood = true;
1862 return isGood;
1865 bool GdbDriver::parseChangeExecutable(const char* output, QString& message)
1867 message = output;
1869 m_haveCoreFile = false;
1872 * The command is successful if there is no output or the single
1873 * message (no debugging symbols found)...
1875 return
1876 output[0] == '\0' ||
1877 strcmp(output, "(no debugging symbols found)...") == 0;
1880 bool GdbDriver::parseCoreFile(const char* output)
1882 // if command succeeded, gdb emits a line starting with "#0 "
1883 m_haveCoreFile = strstr(output, "\n#0 ") != 0;
1884 return m_haveCoreFile;
1887 uint GdbDriver::parseProgramStopped(const char* output, QString& message)
1889 // optionally: "program changed, rereading symbols",
1890 // followed by:
1891 // "Program exited normally"
1892 // "Program terminated with wignal SIGSEGV"
1893 // "Program received signal SIGINT" or other signal
1894 // "Breakpoint..."
1896 // go through the output, line by line, checking what we have
1897 const char* start = output - 1;
1898 uint flags = SFprogramActive;
1899 message = QString();
1900 do {
1901 start++; /* skip '\n' */
1903 if (strncmp(start, "Program ", 8) == 0 ||
1904 strncmp(start, "ptrace: ", 8) == 0) {
1906 * When we receive a signal, the program remains active.
1908 * Special: If we "stopped" in a corefile, the string "Program
1909 * terminated with signal"... is displayed. (Normally, we see
1910 * "Program received signal"... when a signal happens.)
1912 if (strncmp(start, "Program exited", 14) == 0 ||
1913 (strncmp(start, "Program terminated", 18) == 0 && !m_haveCoreFile) ||
1914 strncmp(start, "ptrace: ", 8) == 0)
1916 flags &= ~SFprogramActive;
1919 // set message
1920 const char* endOfMessage = strchr(start, '\n');
1921 if (endOfMessage == 0)
1922 endOfMessage = start + strlen(start);
1923 message = FROM_LATIN1(start, endOfMessage-start);
1924 } else if (strncmp(start, "Breakpoint ", 11) == 0) {
1926 * We stopped at a (permanent) breakpoint (gdb doesn't tell us
1927 * that it stopped at a temporary breakpoint).
1929 flags |= SFrefreshBreak;
1930 } else if (strstr(start, "re-reading symbols.") != 0) {
1931 flags |= SFrefreshSource;
1934 // next line, please
1935 start = strchr(start, '\n');
1936 } while (start != 0);
1939 * Gdb only notices when new threads have appeared, but not when a
1940 * thread finishes. So we always have to assume that the list of
1941 * threads has changed.
1943 flags |= SFrefreshThreads;
1945 return flags;
1948 void GdbDriver::parseSharedLibs(const char* output, QStrList& shlibs)
1950 if (strncmp(output, "No shared libraries loaded", 26) == 0)
1951 return;
1953 // parse the table of shared libraries
1955 // strip off head line
1956 output = strchr(output, '\n');
1957 if (output == 0)
1958 return;
1959 output++; /* skip '\n' */
1960 QString shlibName;
1961 while (*output != '\0') {
1962 // format of a line is
1963 // 0x404c5000 0x40580d90 Yes /lib/libc.so.5
1964 // 3 blocks of non-space followed by space
1965 for (int i = 0; *output != '\0' && i < 3; i++) {
1966 while (*output != '\0' && !isspace(*output)) { /* non-space */
1967 output++;
1969 while (isspace(*output)) { /* space */
1970 output++;
1973 if (*output == '\0')
1974 return;
1975 const char* start = output;
1976 output = strchr(output, '\n');
1977 if (output == 0)
1978 output = start + strlen(start);
1979 shlibName = FROM_LATIN1(start, output-start);
1980 if (*output != '\0')
1981 output++;
1982 shlibs.append(shlibName);
1983 TRACE("found shared lib " + shlibName);
1987 bool GdbDriver::parseFindType(const char* output, QString& type)
1989 if (strncmp(output, "type = ", 7) != 0)
1990 return false;
1993 * Everything else is the type. We strip off all white-space from the
1994 * type.
1996 output += 7;
1997 type = output;
1998 type.replace(QRegExp("\\s+"), "");
1999 return true;
2002 void GdbDriver::parseRegisters(const char* output, QList<RegisterInfo>& regs)
2004 if (strncmp(output, "The program has no registers now", 32) == 0) {
2005 return;
2008 QString regName;
2009 QString value;
2011 // parse register values
2012 while (*output != '\0')
2014 // skip space at the start of the line
2015 while (isspace(*output))
2016 output++;
2018 // register name
2019 const char* start = output;
2020 while (*output != '\0' && !isspace(*output))
2021 output++;
2022 if (*output == '\0')
2023 break;
2024 regName = FROM_LATIN1(start, output-start);
2026 // skip space
2027 while (isspace(*output))
2028 output++;
2029 // the rest of the line is the register value
2030 start = output;
2031 output = strchr(output,'\n');
2032 if (output == 0)
2033 output = start + strlen(start);
2034 value = FROM_LATIN1(start, output-start).simplifyWhiteSpace();
2036 if (*output != '\0')
2037 output++; /* skip '\n' */
2039 RegisterInfo* reg = new RegisterInfo;
2040 reg->regName = regName;
2043 * We split the raw from the cooked values. For this purpose, we
2044 * split off the first token (separated by whitespace). It is the
2045 * raw value. The remainder of the line is the cooked value.
2047 int pos = value.find(' ');
2048 if (pos < 0) {
2049 reg->rawValue = value;
2050 reg->cookedValue = QString();
2051 } else {
2052 reg->rawValue = value.left(pos);
2053 reg->cookedValue = value.mid(pos+1,value.length());
2055 * Some modern gdbs explicitly say: "0.1234 (raw 0x3e4567...)".
2056 * Here the raw value is actually in the second part.
2058 if (reg->cookedValue.left(5) == "(raw ") {
2059 QString raw = reg->cookedValue.right(reg->cookedValue.length()-5);
2060 if (raw[raw.length()-1] == ')') /* remove closing bracket */
2061 raw = raw.left(raw.length()-1);
2062 reg->cookedValue = reg->rawValue;
2063 reg->rawValue = raw;
2067 regs.append(reg);
2071 bool GdbDriver::parseInfoLine(const char* output, QString& addrFrom, QString& addrTo)
2073 const char* start = strstr(output, "starts at address ");
2074 if (start == 0)
2075 return false;
2077 start += 18;
2078 const char* p = start;
2079 while (*p != '\0' && !isspace(*p))
2080 p++;
2081 addrFrom = FROM_LATIN1(start, p-start);
2083 start = strstr(p, "and ends at ");
2084 if (start == 0)
2085 return false;
2087 start += 12;
2088 p = start;
2089 while (*p != '\0' && !isspace(*p))
2090 p++;
2091 addrTo = FROM_LATIN1(start, p-start);
2093 return true;
2096 void GdbDriver::parseDisassemble(const char* output, QList<DisassembledCode>& code)
2098 code.clear();
2100 if (strncmp(output, "Dump of assembler", 17) != 0) {
2101 // error message?
2102 DisassembledCode c;
2103 c.code = output;
2104 code.append(new DisassembledCode(c));
2105 return;
2108 // remove first line
2109 const char* p = strchr(output, '\n');
2110 if (p == 0)
2111 return; /* not a regular output */
2113 p++;
2115 // remove last line
2116 const char* end = strstr(output, "\nEnd of assembler");
2117 if (end == 0)
2118 end = p + strlen(p);
2120 DbgAddr address;
2122 // remove function offsets from the lines
2123 while (p != end)
2125 const char* start = p;
2126 // address
2127 while (p != end && !isspace(*p))
2128 p++;
2129 address = FROM_LATIN1(start, p-start);
2131 // function name (enclosed in '<>', followed by ':')
2132 while (p != end && *p != '<')
2133 p++;
2134 if (*p == '<')
2135 skipNested(p, '<', '>');
2136 if (*p == ':')
2137 p++;
2139 // space until code
2140 while (p != end && isspace(*p))
2141 p++;
2143 // code until end of line
2144 start = p;
2145 while (p != end && *p != '\n')
2146 p++;
2147 if (p != end) /* include '\n' */
2148 p++;
2150 DisassembledCode* c = new DisassembledCode;
2151 c->address = address;
2152 c->code = FROM_LATIN1(start, p-start);
2153 code.append(c);
2157 QString GdbDriver::parseMemoryDump(const char* output, QList<MemoryDump>& memdump)
2159 if (isErrorExpr(output)) {
2160 // error; strip space
2161 QString msg = output;
2162 return msg.stripWhiteSpace();
2165 const char* p = output; /* save typing */
2166 DbgAddr addr;
2167 QString dump;
2169 // the address
2170 while (*p != 0) {
2171 const char* start = p;
2172 while (*p != '\0' && *p != ':' && !isspace(*p))
2173 p++;
2174 addr = FROM_LATIN1(start, p-start);
2175 if (*p != ':') {
2176 // parse function offset
2177 while (isspace(*p))
2178 p++;
2179 start = p;
2180 while (*p != '\0' && !(*p == ':' && isspace(p[1])))
2181 p++;
2182 addr.fnoffs = FROM_LATIN1(start, p-start);
2184 if (*p == ':')
2185 p++;
2186 // skip space; this may skip a new-line char!
2187 while (isspace(*p))
2188 p++;
2189 // everything to the end of the line is the memory dump
2190 const char* end = strchr(p, '\n');
2191 if (end != 0) {
2192 dump = FROM_LATIN1(p, end-p);
2193 p = end+1;
2194 } else {
2195 dump = FROM_LATIN1(p, strlen(p));
2196 p += strlen(p);
2198 MemoryDump* md = new MemoryDump;
2199 md->address = addr;
2200 md->dump = dump;
2201 memdump.append(md);
2204 return QString();
2208 #include "gdbdriver.moc"