Latest updates from Keith for xsldbg 3.0.5.
[kdbg.git] / kdbg / gdbdriver.cpp
blob8cd6f1784c680f82fd38b9e87f56c2ba88ca076b
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.
1390 do {
1391 skipNestedWithString(p, '(', ')');
1392 while (isspace(*p))
1393 p++;
1394 } while (*p == '(');
1396 // check for file position
1397 if (strncmp(p, "at ", 3) == 0) {
1398 p += 3;
1399 const char* fileStart = p;
1400 // go for the end of the line
1401 while (*p != '\0' && *p != '\n')
1402 p++;
1403 // search back for colon
1404 const char* colon = p;
1405 do {
1406 --colon;
1407 } while (*colon != ':');
1408 file = FROM_LATIN1(fileStart, colon-fileStart);
1409 lineNo = atoi(colon+1)-1;
1410 // skip new-line
1411 if (*p != '\0')
1412 p++;
1413 } else {
1414 // check for "from shared lib"
1415 if (strncmp(p, "from ", 5) == 0) {
1416 p += 5;
1417 // go for the end of the line
1418 while (*p != '\0' && *p != '\n')
1419 p++;
1420 // skip new-line
1421 if (*p != '\0')
1422 p++;
1424 file = "";
1425 lineNo = -1;
1427 // construct the function name (including file info)
1428 if (*p == '\0') {
1429 func = start;
1430 } else {
1431 func = FROM_LATIN1(start, p-start-1); /* don't include \n */
1433 s = p;
1436 * Replace \n (and whitespace around it) in func by a blank. We cannot
1437 * use QString::simplifyWhiteSpace() for this because this would also
1438 * simplify space that belongs to a string arguments that gdb sometimes
1439 * prints in the argument lists of the function.
1441 ASSERT(!isspace(func[0].latin1())); /* there must be non-white before first \n */
1442 int nl = 0;
1443 while ((nl = func.find('\n', nl)) >= 0) {
1444 // search back to the beginning of the whitespace
1445 int startWhite = nl;
1446 do {
1447 --startWhite;
1448 } while (isspace(func[startWhite].latin1()));
1449 startWhite++;
1450 // search forward to the end of the whitespace
1451 do {
1452 nl++;
1453 } while (isspace(func[nl].latin1()));
1454 // replace
1455 func.replace(startWhite, nl-startWhite, " ");
1456 /* continue searching for more \n's at this place: */
1457 nl = startWhite+1;
1463 * Parses a stack frame including its frame number
1465 static bool parseFrame(const char*& s, int& frameNo, QString& func,
1466 QString& file, int& lineNo, DbgAddr& address)
1468 // Example:
1469 // #1 0x8048881 in Dl::Dl (this=0xbffff418, r=3214) at testfile.cpp:72
1471 // must start with a hash mark followed by number
1472 if (s[0] != '#' || !isdigit(s[1]))
1473 return false;
1475 s++; /* skip the hash mark */
1476 // frame number
1477 frameNo = atoi(s);
1478 while (isdigit(*s))
1479 s++;
1480 // space
1481 while (isspace(*s))
1482 s++;
1483 parseFrameInfo(s, func, file, lineNo, address);
1484 return true;
1487 void GdbDriver::parseBackTrace(const char* output, QList<StackFrame>& stack)
1489 QString func, file;
1490 int lineNo, frameNo;
1491 DbgAddr address;
1493 while (::parseFrame(output, frameNo, func, file, lineNo, address)) {
1494 StackFrame* frm = new StackFrame;
1495 frm->frameNo = frameNo;
1496 frm->fileName = file;
1497 frm->lineNo = lineNo;
1498 frm->address = address;
1499 frm->var = new VarTree(func, VarTree::NKplain);
1500 stack.append(frm);
1504 bool GdbDriver::parseFrameChange(const char* output, int& frameNo,
1505 QString& file, int& lineNo, DbgAddr& address)
1507 QString func;
1508 return ::parseFrame(output, frameNo, func, file, lineNo, address);
1512 bool GdbDriver::parseBreakList(const char* output, QList<Breakpoint>& brks)
1514 // skip first line, which is the headline
1515 const char* p = strchr(output, '\n');
1516 if (p == 0)
1517 return false;
1518 p++;
1519 if (*p == '\0')
1520 return false;
1522 // split up a line
1523 QString location;
1524 QString address;
1525 int hits = 0;
1526 uint ignoreCount = 0;
1527 QString condition;
1528 const char* end;
1529 char* dummy;
1530 while (*p != '\0') {
1531 // get Num
1532 long bpNum = strtol(p, &dummy, 10); /* don't care about overflows */
1533 p = dummy;
1534 // get Type
1535 while (isspace(*p))
1536 p++;
1537 Breakpoint::Type bpType;
1538 if (strncmp(p, "breakpoint", 10) == 0) {
1539 bpType = Breakpoint::breakpoint;
1540 p += 10;
1541 } else if (strncmp(p, "hw watchpoint", 13) == 0) {
1542 bpType = Breakpoint::watchpoint;
1543 p += 13;
1544 } else if (strncmp(p, "watchpoint", 10) == 0) {
1545 bpType = Breakpoint::watchpoint;
1546 p += 10;
1548 while (isspace(*p))
1549 p++;
1550 if (*p == '\0')
1551 break;
1552 // get Disp
1553 char disp = *p++;
1554 while (*p != '\0' && !isspace(*p)) /* "keep" or "del" */
1555 p++;
1556 while (isspace(*p))
1557 p++;
1558 if (*p == '\0')
1559 break;
1560 // get Enb
1561 char enable = *p++;
1562 while (*p != '\0' && !isspace(*p)) /* "y" or "n" */
1563 p++;
1564 while (isspace(*p))
1565 p++;
1566 if (*p == '\0')
1567 break;
1568 // the address, if present
1569 if (bpType == Breakpoint::breakpoint &&
1570 strncmp(p, "0x", 2) == 0)
1572 const char* start = p;
1573 while (*p != '\0' && !isspace(*p))
1574 p++;
1575 address = FROM_LATIN1(start, p-start);
1576 while (isspace(*p) && *p != '\n')
1577 p++;
1578 if (*p == '\0')
1579 break;
1580 } else {
1581 address = QString();
1583 // remainder is location, hit and ignore count, condition
1584 hits = 0;
1585 ignoreCount = 0;
1586 condition = QString();
1587 end = strchr(p, '\n');
1588 if (end == 0) {
1589 location = p;
1590 p += location.length();
1591 } else {
1592 location = FROM_LATIN1(p, end-p).stripWhiteSpace();
1593 p = end+1; /* skip over \n */
1596 // may be continued in next line
1597 while (isspace(*p)) { /* p points to beginning of line */
1598 // skip white space at beginning of line
1599 while (isspace(*p))
1600 p++;
1602 // seek end of line
1603 end = strchr(p, '\n');
1604 if (end == 0)
1605 end = p+strlen(p);
1607 if (strncmp(p, "breakpoint already hit", 22) == 0) {
1608 // extract the hit count
1609 p += 22;
1610 hits = strtol(p, &dummy, 10);
1611 TRACE(QString().sprintf("hit count %d", hits));
1612 } else if (strncmp(p, "stop only if ", 13) == 0) {
1613 // extract condition
1614 p += 13;
1615 condition = FROM_LATIN1(p, end-p).stripWhiteSpace();
1616 TRACE("condition: "+condition);
1617 } else if (strncmp(p, "ignore next ", 12) == 0) {
1618 // extract ignore count
1619 p += 12;
1620 ignoreCount = strtol(p, &dummy, 10);
1621 TRACE(QString().sprintf("ignore count %d", ignoreCount));
1622 } else {
1623 // indeed a continuation
1624 location += " " + FROM_LATIN1(p, end-p).stripWhiteSpace();
1626 p = end;
1627 if (*p != '\0')
1628 p++; /* skip '\n' */
1630 Breakpoint* bp = new Breakpoint;
1631 bp->id = bpNum;
1632 bp->type = bpType;
1633 bp->temporary = disp == 'd';
1634 bp->enabled = enable == 'y';
1635 bp->location = location;
1636 bp->address = address;
1637 bp->hitCount = hits;
1638 bp->ignoreCount = ignoreCount;
1639 bp->condition = condition;
1640 brks.append(bp);
1642 return true;
1645 bool GdbDriver::parseThreadList(const char* output, QList<ThreadInfo>& threads)
1647 if (strcmp(output, "\n") == 0 || strncmp(output, "No stack.", 9) == 0) {
1648 // no threads
1649 return true;
1652 int id;
1653 QString systag;
1654 QString func, file;
1655 int lineNo;
1656 DbgAddr address;
1658 const char* p = output;
1659 while (*p != '\0') {
1660 // seach look for thread id, watching out for the focus indicator
1661 bool hasFocus = false;
1662 while (isspace(*p)) /* may be \n from prev line: see "No stack" below */
1663 p++;
1664 if (*p == '*') {
1665 hasFocus = true;
1666 p++;
1667 // there follows only whitespace
1669 char* end;
1670 id = strtol(p, &end, 10);
1671 if (p == end) {
1672 // syntax error: no number found; bail out
1673 return true;
1675 p = end;
1677 // skip space
1678 while (isspace(*p))
1679 p++;
1682 * Now follows the thread's SYSTAG. It is terminated by two blanks.
1684 end = strstr(p, " ");
1685 if (end == 0) {
1686 // syntax error; bail out
1687 return true;
1689 systag = FROM_LATIN1(p, end-p);
1690 p = end+2;
1693 * Now follows a standard stack frame. Sometimes, however, gdb
1694 * catches a thread at an instant where it doesn't have a stack.
1696 if (strncmp(p, "[No stack.]", 11) != 0) {
1697 ::parseFrameInfo(p, func, file, lineNo, address);
1698 } else {
1699 func = "[No stack]";
1700 file = QString();
1701 lineNo = -1;
1702 address = QString();
1703 p += 11; /* \n is skipped above */
1706 ThreadInfo* thr = new ThreadInfo;
1707 thr->id = id;
1708 thr->threadName = systag;
1709 thr->hasFocus = hasFocus;
1710 thr->function = func;
1711 thr->fileName = file;
1712 thr->lineNo = lineNo;
1713 thr->address = address;
1714 threads.append(thr);
1716 return true;
1719 bool GdbDriver::parseBreakpoint(const char* output, int& id,
1720 QString& file, int& lineNo)
1722 const char* o = output;
1723 // skip lines of that begin with "(Cannot find"
1724 while (strncmp(o, "(Cannot find", 12) == 0) {
1725 o = strchr(o, '\n');
1726 if (o == 0)
1727 return false;
1728 o++; /* skip newline */
1731 if (strncmp(o, "Breakpoint ", 11) != 0)
1732 return false;
1734 // breakpoint id
1735 output += 11; /* skip "Breakpoint " */
1736 char* p;
1737 int num = strtoul(output, &p, 10);
1738 if (p == o)
1739 return false;
1741 // file name
1742 char* fileStart = strstr(p, "file ");
1743 if (fileStart == 0)
1744 return false;
1745 fileStart += 5;
1747 // line number
1748 char* numStart = strstr(fileStart, ", line ");
1749 QString fileName = FROM_LATIN1(fileStart, numStart-fileStart);
1750 numStart += 7;
1751 int line = strtoul(numStart, &p, 10);
1752 if (numStart == p)
1753 return false;
1755 id = num;
1756 file = fileName;
1757 lineNo = line-1; /* zero-based! */
1758 return true;
1761 void GdbDriver::parseLocals(const char* output, QList<VarTree>& newVars)
1763 // check for possible error conditions
1764 if (strncmp(output, "No symbol table", 15) == 0)
1766 return;
1769 while (*output != '\0') {
1770 while (isspace(*output))
1771 output++;
1772 if (*output == '\0')
1773 break;
1774 // skip occurrences of "No locals" and "No args"
1775 if (strncmp(output, "No locals", 9) == 0 ||
1776 strncmp(output, "No arguments", 12) == 0)
1778 output = strchr(output, '\n');
1779 if (output == 0) {
1780 break;
1782 continue;
1785 VarTree* variable = parseVar(output);
1786 if (variable == 0) {
1787 break;
1789 // do not add duplicates
1790 for (VarTree* o = newVars.first(); o != 0; o = newVars.next()) {
1791 if (o->getText() == variable->getText()) {
1792 delete variable;
1793 goto skipDuplicate;
1796 newVars.append(variable);
1797 skipDuplicate:;
1801 bool GdbDriver::parsePrintExpr(const char* output, bool wantErrorValue, VarTree*& var)
1803 // check for error conditions
1804 if (parseErrorMessage(output, var, wantErrorValue))
1806 return false;
1807 } else {
1808 // parse the variable
1809 var = parseVar(output);
1810 return true;
1814 bool GdbDriver::parseChangeWD(const char* output, QString& message)
1816 bool isGood = false;
1817 message = QString(output).simplifyWhiteSpace();
1818 if (message.isEmpty()) {
1819 message = i18n("New working directory: ") + m_programWD;
1820 isGood = true;
1822 return isGood;
1825 bool GdbDriver::parseChangeExecutable(const char* output, QString& message)
1827 message = output;
1829 m_haveCoreFile = false;
1832 * The command is successful if there is no output or the single
1833 * message (no debugging symbols found)...
1835 return
1836 output[0] == '\0' ||
1837 strcmp(output, "(no debugging symbols found)...") == 0;
1840 bool GdbDriver::parseCoreFile(const char* output)
1842 // if command succeeded, gdb emits a line starting with "#0 "
1843 m_haveCoreFile = strstr(output, "\n#0 ") != 0;
1844 return m_haveCoreFile;
1847 uint GdbDriver::parseProgramStopped(const char* output, QString& message)
1849 // optionally: "program changed, rereading symbols",
1850 // followed by:
1851 // "Program exited normally"
1852 // "Program terminated with wignal SIGSEGV"
1853 // "Program received signal SIGINT" or other signal
1854 // "Breakpoint..."
1856 // go through the output, line by line, checking what we have
1857 const char* start = output - 1;
1858 uint flags = SFprogramActive;
1859 message = QString();
1860 do {
1861 start++; /* skip '\n' */
1863 if (strncmp(start, "Program ", 8) == 0 ||
1864 strncmp(start, "ptrace: ", 8) == 0) {
1866 * When we receive a signal, the program remains active.
1868 * Special: If we "stopped" in a corefile, the string "Program
1869 * terminated with signal"... is displayed. (Normally, we see
1870 * "Program received signal"... when a signal happens.)
1872 if (strncmp(start, "Program exited", 14) == 0 ||
1873 (strncmp(start, "Program terminated", 18) == 0 && !m_haveCoreFile) ||
1874 strncmp(start, "ptrace: ", 8) == 0)
1876 flags &= ~SFprogramActive;
1879 // set message
1880 const char* endOfMessage = strchr(start, '\n');
1881 if (endOfMessage == 0)
1882 endOfMessage = start + strlen(start);
1883 message = FROM_LATIN1(start, endOfMessage-start);
1884 } else if (strncmp(start, "Breakpoint ", 11) == 0) {
1886 * We stopped at a (permanent) breakpoint (gdb doesn't tell us
1887 * that it stopped at a temporary breakpoint).
1889 flags |= SFrefreshBreak;
1890 } else if (strstr(start, "re-reading symbols.") != 0) {
1891 flags |= SFrefreshSource;
1894 // next line, please
1895 start = strchr(start, '\n');
1896 } while (start != 0);
1899 * Gdb only notices when new threads have appeared, but not when a
1900 * thread finishes. So we always have to assume that the list of
1901 * threads has changed.
1903 flags |= SFrefreshThreads;
1905 return flags;
1908 void GdbDriver::parseSharedLibs(const char* output, QStrList& shlibs)
1910 if (strncmp(output, "No shared libraries loaded", 26) == 0)
1911 return;
1913 // parse the table of shared libraries
1915 // strip off head line
1916 output = strchr(output, '\n');
1917 if (output == 0)
1918 return;
1919 output++; /* skip '\n' */
1920 QString shlibName;
1921 while (*output != '\0') {
1922 // format of a line is
1923 // 0x404c5000 0x40580d90 Yes /lib/libc.so.5
1924 // 3 blocks of non-space followed by space
1925 for (int i = 0; *output != '\0' && i < 3; i++) {
1926 while (*output != '\0' && !isspace(*output)) { /* non-space */
1927 output++;
1929 while (isspace(*output)) { /* space */
1930 output++;
1933 if (*output == '\0')
1934 return;
1935 const char* start = output;
1936 output = strchr(output, '\n');
1937 if (output == 0)
1938 output = start + strlen(start);
1939 shlibName = FROM_LATIN1(start, output-start);
1940 if (*output != '\0')
1941 output++;
1942 shlibs.append(shlibName);
1943 TRACE("found shared lib " + shlibName);
1947 bool GdbDriver::parseFindType(const char* output, QString& type)
1949 if (strncmp(output, "type = ", 7) != 0)
1950 return false;
1953 * Everything else is the type. We strip off all white-space from the
1954 * type.
1956 output += 7;
1957 type = output;
1958 type.replace(QRegExp("\\s+"), "");
1959 return true;
1962 void GdbDriver::parseRegisters(const char* output, QList<RegisterInfo>& regs)
1964 if (strncmp(output, "The program has no registers now", 32) == 0) {
1965 return;
1968 QString regName;
1969 QString value;
1971 // parse register values
1972 while (*output != '\0')
1974 // skip space at the start of the line
1975 while (isspace(*output))
1976 output++;
1978 // register name
1979 const char* start = output;
1980 while (*output != '\0' && !isspace(*output))
1981 output++;
1982 if (*output == '\0')
1983 break;
1984 regName = FROM_LATIN1(start, output-start);
1986 // skip space
1987 while (isspace(*output))
1988 output++;
1989 // the rest of the line is the register value
1990 start = output;
1991 output = strchr(output,'\n');
1992 if (output == 0)
1993 output = start + strlen(start);
1994 value = FROM_LATIN1(start, output-start).simplifyWhiteSpace();
1996 if (*output != '\0')
1997 output++; /* skip '\n' */
1999 RegisterInfo* reg = new RegisterInfo;
2000 reg->regName = regName;
2003 * We split the raw from the cooked values. For this purpose, we
2004 * split off the first token (separated by whitespace). It is the
2005 * raw value. The remainder of the line is the cooked value.
2007 int pos = value.find(' ');
2008 if (pos < 0) {
2009 reg->rawValue = value;
2010 reg->cookedValue = QString();
2011 } else {
2012 reg->rawValue = value.left(pos);
2013 reg->cookedValue = value.mid(pos+1,value.length());
2015 * Some modern gdbs explicitly say: "0.1234 (raw 0x3e4567...)".
2016 * Here the raw value is actually in the second part.
2018 if (reg->cookedValue.left(5) == "(raw ") {
2019 QString raw = reg->cookedValue.right(reg->cookedValue.length()-5);
2020 if (raw[raw.length()-1] == ')') /* remove closing bracket */
2021 raw = raw.left(raw.length()-1);
2022 reg->cookedValue = reg->rawValue;
2023 reg->rawValue = raw;
2027 regs.append(reg);
2031 bool GdbDriver::parseInfoLine(const char* output, QString& addrFrom, QString& addrTo)
2033 const char* start = strstr(output, "starts at address ");
2034 if (start == 0)
2035 return false;
2037 start += 18;
2038 const char* p = start;
2039 while (*p != '\0' && !isspace(*p))
2040 p++;
2041 addrFrom = FROM_LATIN1(start, p-start);
2043 start = strstr(p, "and ends at ");
2044 if (start == 0)
2045 return false;
2047 start += 12;
2048 p = start;
2049 while (*p != '\0' && !isspace(*p))
2050 p++;
2051 addrTo = FROM_LATIN1(start, p-start);
2053 return true;
2056 void GdbDriver::parseDisassemble(const char* output, QList<DisassembledCode>& code)
2058 code.clear();
2060 if (strncmp(output, "Dump of assembler", 17) != 0) {
2061 // error message?
2062 DisassembledCode c;
2063 c.code = output;
2064 code.append(new DisassembledCode(c));
2065 return;
2068 // remove first line
2069 const char* p = strchr(output, '\n');
2070 if (p == 0)
2071 return; /* not a regular output */
2073 p++;
2075 // remove last line
2076 const char* end = strstr(output, "\nEnd of assembler");
2077 if (end == 0)
2078 end = p + strlen(p);
2080 DbgAddr address;
2082 // remove function offsets from the lines
2083 while (p != end)
2085 const char* start = p;
2086 // address
2087 while (p != end && !isspace(*p))
2088 p++;
2089 address = FROM_LATIN1(start, p-start);
2091 // function name (enclosed in '<>', followed by ':')
2092 while (p != end && *p != '<')
2093 p++;
2094 if (*p == '<')
2095 skipNested(p, '<', '>');
2096 if (*p == ':')
2097 p++;
2099 // space until code
2100 while (p != end && isspace(*p))
2101 p++;
2103 // code until end of line
2104 start = p;
2105 while (p != end && *p != '\n')
2106 p++;
2107 if (p != end) /* include '\n' */
2108 p++;
2110 DisassembledCode* c = new DisassembledCode;
2111 c->address = address;
2112 c->code = FROM_LATIN1(start, p-start);
2113 code.append(c);
2117 QString GdbDriver::parseMemoryDump(const char* output, QList<MemoryDump>& memdump)
2119 if (isErrorExpr(output)) {
2120 // error; strip space
2121 QString msg = output;
2122 return msg.stripWhiteSpace();
2125 const char* p = output; /* save typing */
2126 DbgAddr addr;
2127 QString dump;
2129 // the address
2130 while (*p != 0) {
2131 const char* start = p;
2132 while (*p != '\0' && *p != ':' && !isspace(*p))
2133 p++;
2134 addr = FROM_LATIN1(start, p-start);
2135 if (*p != ':') {
2136 // parse function offset
2137 while (isspace(*p))
2138 p++;
2139 start = p;
2140 while (*p != '\0' && !(*p == ':' && isspace(p[1])))
2141 p++;
2142 addr.fnoffs = FROM_LATIN1(start, p-start);
2144 if (*p == ':')
2145 p++;
2146 // skip space; this may skip a new-line char!
2147 while (isspace(*p))
2148 p++;
2149 // everything to the end of the line is the memory dump
2150 const char* end = strchr(p, '\n');
2151 if (end != 0) {
2152 dump = FROM_LATIN1(p, end-p);
2153 p = end+1;
2154 } else {
2155 dump = FROM_LATIN1(p, strlen(p));
2156 p += strlen(p);
2158 MemoryDump* md = new MemoryDump;
2159 md->address = addr;
2160 md->dump = dump;
2161 memdump.append(md);
2164 return QString();
2168 #include "gdbdriver.moc"