Support debugger drivers that use a regular expression to search for the prompt.
[kdbg.git] / kdbg / gdbdriver.cpp
blob85fea2a669aa9a32b0abb91e7561c3f0c1e198a8
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 return defaultGdb();
217 bool GdbDriver::startup(QString cmdStr)
219 if (!DebuggerDriver::startup(cmdStr))
220 return false;
222 static const char gdbInitialize[] =
224 * Work around buggy gdbs that do command line editing even if they
225 * are not on a tty. The readline library echos every command back
226 * in this case, which is confusing for us.
228 "set editing off\n"
229 "set confirm off\n"
230 "set print static-members off\n"
231 "set print asm-demangle on\n"
233 * Write a short macro that prints all locals: local variables and
234 * function arguments.
236 "define kdbg__alllocals\n"
237 "info locals\n" /* local vars supersede args with same name */
238 "info args\n" /* therefore, arguments must come last */
239 "end\n"
240 // change prompt string and synchronize with gdb
241 "set prompt " PROMPT "\n"
244 executeCmdString(DCinitialize, gdbInitialize, false);
246 // assume that QString::null is ok
247 cmds[DCprintQStringStruct].fmt = printQStringStructFmt;
249 return true;
252 void GdbDriver::commandFinished(CmdQueueItem* cmd)
254 // command string must be committed
255 if (!cmd->m_committed) {
256 // not commited!
257 TRACE("calling " + (__PRETTY_FUNCTION__ + (" with uncommited command:\n\t" +
258 cmd->m_cmdString)));
259 return;
262 switch (cmd->m_cmd) {
263 case DCinitialize:
264 // get version number from preamble
266 int len;
267 QRegExp GDBVersion("\\nGDB [0-9]+\\.[0-9]+");
268 int offset = GDBVersion.match(m_output, 0, &len);
269 if (offset >= 0) {
270 char* start = m_output + offset + 5; // skip "\nGDB "
271 char* end;
272 m_gdbMajor = strtol(start, &end, 10);
273 m_gdbMinor = strtol(end + 1, 0, 10); // skip "."
274 if (start == end) {
275 // nothing was parsed
276 m_gdbMajor = 4;
277 m_gdbMinor = 16;
279 } else {
280 // assume some default version (what would make sense?)
281 m_gdbMajor = 4;
282 m_gdbMinor = 16;
284 // use a feasible core-file command
285 if (m_gdbMajor > 4 || (m_gdbMajor == 4 && m_gdbMinor >= 16)) {
286 cmds[DCcorefile].fmt = "target core %s\n";
287 } else {
288 cmds[DCcorefile].fmt = "core-file %s\n";
291 break;
292 default:;
295 /* ok, the command is ready */
296 emit commandReceived(cmd, m_output);
298 switch (cmd->m_cmd) {
299 case DCcorefile:
300 case DCinfolinemain:
301 case DCframe:
302 case DCattach:
303 case DCrun:
304 case DCcont:
305 case DCstep:
306 case DCstepi:
307 case DCnext:
308 case DCnexti:
309 case DCfinish:
310 case DCuntil:
311 parseMarker();
312 default:;
317 * The --fullname option makes gdb send a special normalized sequence print
318 * each time the program stops and at some other points. The sequence has
319 * the form "\032\032filename:lineno:charoffset:(beg|middle):address".
321 void GdbDriver::parseMarker()
323 char* startMarker = strstr(m_output, "\032\032");
324 if (startMarker == 0)
325 return;
327 // extract the marker
328 startMarker += 2;
329 TRACE(QString("found marker: ") + startMarker);
330 char* endMarker = strchr(startMarker, '\n');
331 if (endMarker == 0)
332 return;
334 *endMarker = '\0';
336 // extract filename and line number
337 static QRegExp MarkerRE(":[0-9]+:[0-9]+:[begmidl]+:0x");
339 int len;
340 int lineNoStart = MarkerRE.match(startMarker, 0, &len);
341 if (lineNoStart >= 0) {
342 int lineNo = atoi(startMarker + lineNoStart+1);
344 // get address
345 const char* addrStart = startMarker + lineNoStart + len - 2;
346 DbgAddr address = QString(addrStart).stripWhiteSpace();
348 // now show the window
349 startMarker[lineNoStart] = '\0'; /* split off file name */
350 emit activateFileLine(startMarker, lineNo-1, address);
356 * Escapes characters that might lead to problems when they appear on gdb's
357 * command line.
359 static void normalizeStringArg(QString& arg)
362 * Remove trailing backslashes. This approach is a little simplistic,
363 * but we know that there is at the moment no case where a trailing
364 * backslash would make sense.
366 while (!arg.isEmpty() && arg[arg.length()-1] == '\\') {
367 arg = arg.left(arg.length()-1);
372 #if QT_VERSION < 200
373 #define LATIN1(str) ((str).isNull() ? "" : (str).data())
374 #else
375 #define LATIN1(str) (str).latin1()
376 #endif
378 QString GdbDriver::makeCmdString(DbgCommand cmd, QString strArg)
380 assert(cmd >= 0 && cmd < NUM_CMDS);
381 assert(cmds[cmd].argsNeeded == GdbCmdInfo::argString);
383 normalizeStringArg(strArg);
385 if (cmd == DCcd) {
386 // need the working directory when parsing the output
387 m_programWD = strArg;
388 } else if (cmd == DCsetargs) {
389 // attach saved redirection
390 #if QT_VERSION < 200
391 strArg.detach();
392 #endif
393 strArg += m_redirect;
396 SIZED_QString(cmdString, MAX_FMTLEN+strArg.length());
397 cmdString.sprintf(cmds[cmd].fmt, LATIN1(strArg));
398 return cmdString;
401 QString GdbDriver::makeCmdString(DbgCommand cmd, int intArg)
403 assert(cmd >= 0 && cmd < NUM_CMDS);
404 assert(cmds[cmd].argsNeeded == GdbCmdInfo::argNum);
406 SIZED_QString(cmdString, MAX_FMTLEN+30);
408 cmdString.sprintf(cmds[cmd].fmt, intArg);
409 return cmdString;
412 QString GdbDriver::makeCmdString(DbgCommand cmd, QString strArg, int intArg)
414 assert(cmd >= 0 && cmd < NUM_CMDS);
415 assert(cmds[cmd].argsNeeded == GdbCmdInfo::argStringNum ||
416 cmds[cmd].argsNeeded == GdbCmdInfo::argNumString ||
417 cmd == DCexamine ||
418 cmd == DCtty);
420 normalizeStringArg(strArg);
422 SIZED_QString(cmdString, MAX_FMTLEN+30+strArg.length());
424 if (cmd == DCtty)
427 * intArg specifies which channels should be redirected to
428 * /dev/null. It is a value or'ed together from RDNstdin,
429 * RDNstdout, RDNstderr. We store the value for a later DCsetargs
430 * command.
432 * Note: We rely on that after the DCtty a DCsetargs will follow,
433 * which will ultimately apply the redirection.
435 static const char* const runRedir[8] = {
437 " </dev/null",
438 " >/dev/null",
439 " </dev/null >/dev/null",
440 " 2>/dev/null",
441 " </dev/null 2>/dev/null",
442 " >/dev/null 2>&1",
443 " </dev/null >/dev/null 2>&1"
445 if (strArg.isEmpty())
446 intArg = 7; /* failsafe if no tty */
447 m_redirect = runRedir[intArg & 7];
449 return makeCmdString(DCtty, strArg); /* note: no problem if strArg empty */
452 if (cmd == DCexamine) {
453 // make a format specifier from the intArg
454 static const char size[16] = {
455 '\0', 'b', 'h', 'w', 'g'
457 static const char format[16] = {
458 '\0', 'x', 'd', 'u', 'o', 't',
459 'a', 'c', 'f', 's', 'i'
461 assert(MDTsizemask == 0xf); /* lowest 4 bits */
462 assert(MDTformatmask == 0xf0); /* next 4 bits */
463 int count = 16; /* number of entities to print */
464 char sizeSpec = size[intArg & MDTsizemask];
465 char formatSpec = format[(intArg & MDTformatmask) >> 4];
466 assert(sizeSpec != '\0');
467 assert(formatSpec != '\0');
468 // adjust count such that 16 lines are printed
469 switch (intArg & MDTformatmask) {
470 case MDTstring: case MDTinsn:
471 break; /* no modification needed */
472 default:
473 // all cases drop through:
474 switch (intArg & MDTsizemask) {
475 case MDTbyte:
476 case MDThalfword:
477 count *= 2;
478 case MDTword:
479 count *= 2;
480 case MDTgiantword:
481 count *= 2;
483 break;
485 QString spec;
486 spec.sprintf("/%d%c%c", count, sizeSpec, formatSpec);
488 return makeCmdString(DCexamine, spec, strArg);
491 if (cmds[cmd].argsNeeded == GdbCmdInfo::argStringNum)
493 // line numbers are zero-based
494 if (cmd == DCuntil || cmd == DCbreakline ||
495 cmd == DCtbreakline || cmd == DCinfoline)
497 intArg++;
499 if (cmd == DCinfoline)
501 // must split off file name part
502 int slash = strArg.findRev('/');
503 if (slash >= 0)
504 strArg = strArg.right(strArg.length()-slash-1);
506 cmdString.sprintf(cmds[cmd].fmt, LATIN1(strArg), intArg);
508 else
510 cmdString.sprintf(cmds[cmd].fmt, intArg, LATIN1(strArg));
512 return cmdString;
515 QString GdbDriver::makeCmdString(DbgCommand cmd, QString strArg1, QString strArg2)
517 assert(cmd >= 0 && cmd < NUM_CMDS);
518 assert(cmds[cmd].argsNeeded == GdbCmdInfo::argString2);
520 normalizeStringArg(strArg1);
521 normalizeStringArg(strArg2);
523 SIZED_QString(cmdString, MAX_FMTLEN+strArg1.length()+strArg2.length());
524 cmdString.sprintf(cmds[cmd].fmt, LATIN1(strArg1), LATIN1(strArg2));
525 return cmdString;
528 QString GdbDriver::makeCmdString(DbgCommand cmd, int intArg1, int intArg2)
530 assert(cmd >= 0 && cmd < NUM_CMDS);
531 assert(cmds[cmd].argsNeeded == GdbCmdInfo::argNum2);
533 SIZED_QString(cmdString, MAX_FMTLEN+60);
534 cmdString.sprintf(cmds[cmd].fmt, intArg1, intArg2);
535 return cmdString;
538 CmdQueueItem* GdbDriver::executeCmd(DbgCommand cmd, bool clearLow)
540 assert(cmd >= 0 && cmd < NUM_CMDS);
541 assert(cmds[cmd].argsNeeded == GdbCmdInfo::argNone);
543 if (cmd == DCrun) {
544 m_haveCoreFile = false;
547 return executeCmdString(cmd, cmds[cmd].fmt, clearLow);
550 CmdQueueItem* GdbDriver::executeCmd(DbgCommand cmd, QString strArg,
551 bool clearLow)
553 return executeCmdString(cmd, makeCmdString(cmd, strArg), clearLow);
556 CmdQueueItem* GdbDriver::executeCmd(DbgCommand cmd, int intArg,
557 bool clearLow)
560 return executeCmdString(cmd, makeCmdString(cmd, intArg), clearLow);
563 CmdQueueItem* GdbDriver::executeCmd(DbgCommand cmd, QString strArg, int intArg,
564 bool clearLow)
566 return executeCmdString(cmd, makeCmdString(cmd, strArg, intArg), clearLow);
569 CmdQueueItem* GdbDriver::executeCmd(DbgCommand cmd, QString strArg1, QString strArg2,
570 bool clearLow)
572 return executeCmdString(cmd, makeCmdString(cmd, strArg1, strArg2), clearLow);
575 CmdQueueItem* GdbDriver::executeCmd(DbgCommand cmd, int intArg1, int intArg2,
576 bool clearLow)
578 return executeCmdString(cmd, makeCmdString(cmd, intArg1, intArg2), clearLow);
581 CmdQueueItem* GdbDriver::queueCmd(DbgCommand cmd, QueueMode mode)
583 return queueCmdString(cmd, cmds[cmd].fmt, mode);
586 CmdQueueItem* GdbDriver::queueCmd(DbgCommand cmd, QString strArg,
587 QueueMode mode)
589 return queueCmdString(cmd, makeCmdString(cmd, strArg), mode);
592 CmdQueueItem* GdbDriver::queueCmd(DbgCommand cmd, int intArg,
593 QueueMode mode)
595 return queueCmdString(cmd, makeCmdString(cmd, intArg), mode);
598 CmdQueueItem* GdbDriver::queueCmd(DbgCommand cmd, QString strArg, int intArg,
599 QueueMode mode)
601 return queueCmdString(cmd, makeCmdString(cmd, strArg, intArg), mode);
604 CmdQueueItem* GdbDriver::queueCmd(DbgCommand cmd, QString strArg1, QString strArg2,
605 QueueMode mode)
607 return queueCmdString(cmd, makeCmdString(cmd, strArg1, strArg2), mode);
610 void GdbDriver::terminate()
612 kill(SIGTERM);
613 m_state = DSidle;
616 void GdbDriver::detachAndTerminate()
618 kill(SIGINT);
619 flushCommands();
620 executeCmdString(DCinitialize, "detach\nquit\n", true);
623 void GdbDriver::interruptInferior()
625 kill(SIGINT);
626 // remove accidentally queued commands
627 flushHiPriQueue();
630 static bool isErrorExpr(const char* output)
632 return
633 strncmp(output, "Cannot access memory at", 23) == 0 ||
634 strncmp(output, "Attempt to dereference a generic pointer", 40) == 0 ||
635 strncmp(output, "Attempt to take contents of ", 28) == 0 ||
636 strncmp(output, "Attempt to use a type name as an expression", 43) == 0 ||
637 strncmp(output, "There is no member or method named", 34) == 0 ||
638 strncmp(output, "No symbol \"", 11) == 0 ||
639 strncmp(output, "Internal error: ", 16) == 0;
643 * Returns true if the output is an error message. If wantErrorValue is
644 * true, a new VarTree object is created and filled with the error message.
646 static bool parseErrorMessage(const char* output,
647 VarTree*& variable, bool wantErrorValue)
649 if (isErrorExpr(output))
651 if (wantErrorValue) {
652 // put the error message as value in the variable
653 variable = new VarTree(QString(), VarTree::NKplain);
654 const char* endMsg = strchr(output, '\n');
655 if (endMsg == 0)
656 endMsg = output + strlen(output);
657 variable->m_value = FROM_LATIN1(output, endMsg-output);
658 } else {
659 variable = 0;
661 return true;
663 return false;
666 #if QT_VERSION < 200
667 struct QChar {
668 // this is the XChar2b on X11
669 uchar row;
670 uchar cell;
671 static QString toQString(QChar* unicode, int len);
672 QChar() : row(0), cell(0) { }
673 QChar(char c) : row(0), cell(c) { }
674 operator char() const { return row ? 0 : cell; }
677 QString QChar::toQString(QChar* unicode, int len)
679 QString result(len+1);
680 char* data = result.data();
681 data[len] = '\0';
682 while (len >= 0) {
683 data[len] = unicode[len].cell;
684 --len;
686 return result;
688 #endif
689 #if QT_VERSION >= 300
690 union Qt2QChar {
691 short s;
692 struct {
693 uchar row;
694 uchar cell;
695 } qch;
697 #endif
699 VarTree* GdbDriver::parseQCharArray(const char* output, bool wantErrorValue, bool qt3like)
701 VarTree* variable = 0;
704 * Parse off white space. gdb sometimes prints white space first if the
705 * printed array leaded to an error.
707 const char* p = output;
708 while (isspace(*p))
709 p++;
711 // check if this is an error indicating that gdb does not know about QString::null
712 if (cmds[DCprintQStringStruct].fmt == printQStringStructFmt &&
713 strncmp(p, "Internal error: could not find static variable null", 51) == 0)
715 /* QString::null doesn't work, use an alternate expression */
716 cmds[DCprintQStringStruct].fmt = printQStringStructNoNullFmt;
717 // continue and let parseOffErrorExpr catch the error
720 // special case: empty string (0 repetitions)
721 if (strncmp(p, "Invalid number 0 of repetitions", 31) == 0)
723 variable = new VarTree(QString(), VarTree::NKplain);
724 variable->m_value = "\"\"";
725 return variable;
728 // check for error conditions
729 if (parseErrorMessage(p, variable, wantErrorValue))
730 return variable;
732 // parse the array
734 // find '='
735 p = strchr(p, '=');
736 if (p == 0) {
737 goto error;
739 // skip white space
740 do {
741 p++;
742 } while (isspace(*p));
744 if (*p == '{')
746 // this is the real data
747 p++; /* skip '{' */
749 // parse the array
750 QString result;
751 QString repeatCount;
752 enum { wasNothing, wasChar, wasRepeat } lastThing = wasNothing;
754 * A matrix for separators between the individual "things"
755 * that are added to the string. The first index is a bool,
756 * the second index is from the enum above.
758 static const char* separator[2][3] = {
759 { "\"", 0, ", \"" }, /* normal char is added */
760 { "'", "\", '", ", '" } /* repeated char is added */
763 while (isdigit(*p)) {
764 // parse a number
765 char* end;
766 unsigned short value = (unsigned short) strtoul(p, &end, 0);
767 if (end == p)
768 goto error; /* huh? no valid digits */
769 // skip separator and search for a repeat count
770 p = end;
771 while (isspace(*p) || *p == ',')
772 p++;
773 bool repeats = strncmp(p, "<repeats ", 9) == 0;
774 if (repeats) {
775 const char* start = p;
776 p = strchr(p+9, '>'); /* search end and advance */
777 if (p == 0)
778 goto error;
779 p++; /* skip '>' */
780 repeatCount = FROM_LATIN1(start, p-start);
781 while (isspace(*p) || *p == ',')
782 p++;
784 // p is now at the next char (or the end)
786 // interpret the value as a QChar
787 // TODO: make cross-architecture compatible
788 QChar ch;
789 if (qt3like) {
790 ch = QChar(value);
791 } else {
792 #if QT_VERSION < 300
793 (unsigned short&)ch = value;
794 #else
795 Qt2QChar c;
796 c.s = value;
797 ch.setRow(c.qch.row);
798 ch.setCell(c.qch.cell);
799 #endif
802 // escape a few frequently used characters
803 char escapeCode = '\0';
804 switch (char(ch)) {
805 case '\n': escapeCode = 'n'; break;
806 case '\r': escapeCode = 'r'; break;
807 case '\t': escapeCode = 't'; break;
808 case '\b': escapeCode = 'b'; break;
809 case '\"': escapeCode = '\"'; break;
810 case '\\': escapeCode = '\\'; break;
811 #if QT_VERSION < 200
812 // since we only deal with ascii values must always escape '\0'
813 case '\0': escapeCode = '0'; break;
814 #else
815 case '\0': if (value == 0) { escapeCode = '0'; } break;
816 #endif
819 // add separator
820 result += separator[repeats][lastThing];
821 // add char
822 if (escapeCode != '\0') {
823 result += '\\';
824 ch = escapeCode;
826 result += ch;
828 // fixup repeat count and lastThing
829 if (repeats) {
830 result += "' ";
831 result += repeatCount;
832 lastThing = wasRepeat;
833 } else {
834 lastThing = wasChar;
837 if (*p != '}')
838 goto error;
840 // closing quote
841 if (lastThing == wasChar)
842 result += "\"";
844 // assign the value
845 variable = new VarTree(QString(), VarTree::NKplain);
846 variable->m_value = result;
848 else if (strncmp(p, "true", 4) == 0)
850 variable = new VarTree(QString(), VarTree::NKplain);
851 variable->m_value = "QString::null";
853 else if (strncmp(p, "false", 5) == 0)
855 variable = new VarTree(QString(), VarTree::NKplain);
856 variable->m_value = "(null)";
858 else
859 goto error;
860 return variable;
862 error:
863 if (wantErrorValue) {
864 variable = new VarTree(QString(), VarTree::NKplain);
865 variable->m_value = "internal parse error";
867 return variable;
870 static VarTree* parseVar(const char*& s)
872 const char* p = s;
874 // skip whitespace
875 while (isspace(*p))
876 p++;
878 QString name;
879 VarTree::NameKind kind;
880 if (!parseName(p, name, kind)) {
881 return 0;
884 // go for '='
885 while (isspace(*p))
886 p++;
887 if (*p != '=') {
888 TRACE(QString().sprintf("parse error: = not found after %s", (const char*)name));
889 return 0;
891 // skip the '=' and more whitespace
892 p++;
893 while (isspace(*p))
894 p++;
896 VarTree* variable = new VarTree(name, kind);
897 variable->setDeleteChildren(true);
899 if (!parseValue(p, variable)) {
900 delete variable;
901 return 0;
903 s = p;
904 return variable;
907 static void skipNested(const char*& s, char opening, char closing)
909 const char* p = s;
911 // parse a nested type
912 int nest = 1;
913 p++;
915 * Search for next matching `closing' char, skipping nested pairs of
916 * `opening' and `closing'.
918 while (*p && nest > 0) {
919 if (*p == opening) {
920 nest++;
921 } else if (*p == closing) {
922 nest--;
924 p++;
926 if (nest > 0) {
927 TRACE(QString().sprintf("parse error: mismatching %c%c at %-20.20s", opening, closing, s));
929 s = p;
932 void skipString(const char*& p)
934 moreStrings:
935 // opening quote
936 char quote = *p++;
937 while (*p != quote) {
938 if (*p == '\\') {
939 // skip escaped character
940 // no special treatment for octal values necessary
941 p++;
943 // simply return if no more characters
944 if (*p == '\0')
945 return;
946 p++;
948 // closing quote
949 p++;
951 * Strings can consist of several parts, some of which contain repeated
952 * characters.
954 if (quote == '\'') {
955 // look ahaead for <repeats 123 times>
956 const char* q = p+1;
957 while (isspace(*q))
958 q++;
959 if (strncmp(q, "<repeats ", 9) == 0) {
960 p = q+9;
961 while (*p != '\0' && *p != '>')
962 p++;
963 if (*p != '\0') {
964 p++; /* skip the '>' */
968 // is the string continued?
969 if (*p == ',') {
970 // look ahead for another quote
971 const char* q = p+1;
972 while (isspace(*q))
973 q++;
974 if (*q == '"' || *q == '\'') {
975 // yes!
976 p = q;
977 goto moreStrings;
980 /* very long strings are followed by `...' */
981 if (*p == '.' && p[1] == '.' && p[2] == '.') {
982 p += 3;
986 static void skipNestedWithString(const char*& s, char opening, char closing)
988 const char* p = s;
990 // parse a nested expression
991 int nest = 1;
992 p++;
994 * Search for next matching `closing' char, skipping nested pairs of
995 * `opening' and `closing' as well as strings.
997 while (*p && nest > 0) {
998 if (*p == opening) {
999 nest++;
1000 } else if (*p == closing) {
1001 nest--;
1002 } else if (*p == '\'' || *p == '\"') {
1003 skipString(p);
1004 continue;
1006 p++;
1008 if (nest > 0) {
1009 TRACE(QString().sprintf("parse error: mismatching %c%c at %-20.20s", opening, closing, s));
1011 s = p;
1014 inline void skipName(const char*& p)
1016 // allow : (for enumeration values) and $ and . (for _vtbl.)
1017 while (isalnum(*p) || *p == '_' || *p == ':' || *p == '$' || *p == '.')
1018 p++;
1021 static bool parseName(const char*& s, QString& name, VarTree::NameKind& kind)
1023 kind = VarTree::NKplain;
1025 const char* p = s;
1026 // examples of names:
1027 // name
1028 // <Object>
1029 // <string<a,b<c>,7> >
1031 if (*p == '<') {
1032 skipNested(p, '<', '>');
1033 name = FROM_LATIN1(s, p - s);
1034 kind = VarTree::NKtype;
1036 else
1038 // name, which might be "static"; allow dot for "_vtbl."
1039 skipName(p);
1040 if (p == s) {
1041 TRACE(QString().sprintf("parse error: not a name %-20.20s", s));
1042 return false;
1044 int len = p - s;
1045 if (len == 6 && strncmp(s, "static", 6) == 0) {
1046 kind = VarTree::NKstatic;
1048 // its a static variable, name comes now
1049 while (isspace(*p))
1050 p++;
1051 s = p;
1052 skipName(p);
1053 if (p == s) {
1054 TRACE(QString().sprintf("parse error: not a name after static %-20.20s", s));
1055 return false;
1057 len = p - s;
1059 name = FROM_LATIN1(s, len);
1061 // return the new position
1062 s = p;
1063 return true;
1066 static bool parseValue(const char*& s, VarTree* variable)
1068 variable->m_value = "";
1070 repeat:
1071 if (*s == '{') {
1072 s++;
1073 if (!parseNested(s, variable)) {
1074 return false;
1076 // must be the closing brace
1077 if (*s != '}') {
1078 TRACE("parse error: missing } of " + variable->getText());
1079 return false;
1081 s++;
1082 // final white space
1083 while (isspace(*s))
1084 s++;
1085 } else {
1086 // examples of leaf values (cannot be the empty string):
1087 // 123
1088 // -123
1089 // 23.575e+37
1090 // 0x32a45
1091 // @0x012ab4
1092 // (DwContentType&) @0x8123456: {...}
1093 // 0x32a45 "text"
1094 // 10 '\n'
1095 // <optimized out>
1096 // 0x823abc <Array<int> virtual table>
1097 // (void (*)()) 0x8048480 <f(E *, char)>
1098 // (E *) 0xbffff450
1099 // red
1100 // &parseP (HTMLClueV *, char *)
1102 const char*p = s;
1104 // check for type
1105 QString type;
1106 if (*p == '(') {
1107 skipNested(p, '(', ')');
1109 while (isspace(*p))
1110 p++;
1111 variable->m_value = FROM_LATIN1(s, p - s);
1114 bool reference = false;
1115 if (*p == '@') {
1116 // skip reference marker
1117 p++;
1118 reference = true;
1120 const char* start = p;
1121 if (*p == '-')
1122 p++;
1124 // some values consist of more than one token
1125 bool checkMultiPart = false;
1127 if (p[0] == '0' && p[1] == 'x') {
1128 // parse hex number
1129 p += 2;
1130 while (isxdigit(*p))
1131 p++;
1134 * Assume this is a pointer, but only if it's not a reference, since
1135 * references can't be expanded.
1137 if (!reference) {
1138 variable->m_varKind = VarTree::VKpointer;
1139 } else {
1141 * References are followed by a colon, in which case we'll
1142 * find the value following the reference address.
1144 if (*p == ':') {
1145 p++;
1146 } else {
1147 // Paranoia. (Can this happen, i.e. reference not followed by ':'?)
1148 reference = false;
1151 checkMultiPart = true;
1152 } else if (isdigit(*p)) {
1153 // parse decimal number, possibly a float
1154 while (isdigit(*p))
1155 p++;
1156 if (*p == '.') { /* TODO: obey i18n? */
1157 // fractional part
1158 p++;
1159 while (isdigit(*p))
1160 p++;
1162 if (*p == 'e' || *p == 'E') {
1163 p++;
1164 // exponent
1165 if (*p == '-' || *p == '+')
1166 p++;
1167 while (isdigit(*p))
1168 p++;
1171 // for char variables there is the char, eg. 10 '\n'
1172 checkMultiPart = true;
1173 } else if (*p == '<') {
1174 // e.g. <optimized out>
1175 skipNested(p, '<', '>');
1176 } else if (*p == '"' || *p == '\'') {
1177 // character may have multipart: '\000' <repeats 11 times>
1178 checkMultiPart = *p == '\'';
1179 // found a string
1180 skipString(p);
1181 } else if (*p == '&') {
1182 // function pointer
1183 p++;
1184 skipName(p);
1185 while (isspace(*p)) {
1186 p++;
1188 if (*p == '(') {
1189 skipNested(p, '(', ')');
1191 } else {
1192 // must be an enumeration value
1193 skipName(p);
1195 variable->m_value += FROM_LATIN1(start, p - start);
1197 if (checkMultiPart) {
1198 // white space
1199 while (isspace(*p))
1200 p++;
1201 // may be followed by a string or <...>
1202 start = p;
1204 if (*p == '"' || *p == '\'') {
1205 skipString(p);
1206 } else if (*p == '<') {
1207 // if this value is part of an array, it might be followed
1208 // by <repeats 15 times>, which we don't skip here
1209 if (strncmp(p, "<repeats ", 9) != 0)
1210 skipNested(p, '<', '>');
1212 if (p != start) {
1213 // there is always a blank before the string,
1214 // which we will include in the final string value
1215 variable->m_value += FROM_LATIN1(start-1, (p - start)+1);
1216 // if this was a pointer, reset that flag since we
1217 // now got the value
1218 variable->m_varKind = VarTree::VKsimple;
1222 if (variable->m_value.length() == 0) {
1223 TRACE("parse error: no value for " + variable->getText());
1224 return false;
1227 // final white space
1228 while (isspace(*p))
1229 p++;
1230 s = p;
1233 * If this was a reference, the value follows. It might even be a
1234 * composite variable!
1236 if (reference) {
1237 goto repeat;
1240 if (variable->m_varKind == VarTree::VKpointer) {
1241 variable->setDelayedExpanding(true);
1245 return true;
1248 static bool parseNested(const char*& s, VarTree* variable)
1250 // could be a structure or an array
1251 while (isspace(*s))
1252 s++;
1254 const char* p = s;
1255 bool isStruct = false;
1257 * If there is a name followed by an = or an < -- which starts a type
1258 * name -- or "static", it is a structure
1260 if (*p == '<' || *p == '}') {
1261 isStruct = true;
1262 } else if (strncmp(p, "static ", 7) == 0) {
1263 isStruct = true;
1264 } else if (isalpha(*p) || *p == '_' || *p == '$') {
1265 // look ahead for a comma after the name
1266 skipName(p);
1267 while (isspace(*p))
1268 p++;
1269 if (*p == '=') {
1270 isStruct = true;
1272 p = s; /* rescan the name */
1274 if (isStruct) {
1275 if (!parseVarSeq(p, variable)) {
1276 return false;
1278 variable->m_varKind = VarTree::VKstruct;
1279 } else {
1280 if (!parseValueSeq(p, variable)) {
1281 return false;
1283 variable->m_varKind = VarTree::VKarray;
1285 s = p;
1286 return true;
1289 static bool parseVarSeq(const char*& s, VarTree* variable)
1291 // parse a comma-separated sequence of variables
1292 VarTree* var = variable; /* var != 0 to indicate success if empty seq */
1293 for (;;) {
1294 if (*s == '}')
1295 break;
1296 if (strncmp(s, "<No data fields>}", 17) == 0)
1298 // no member variables, so break out immediately
1299 s += 16; /* go to the closing brace */
1300 break;
1302 var = parseVar(s);
1303 if (var == 0)
1304 break; /* syntax error */
1305 variable->appendChild(var);
1306 if (*s != ',')
1307 break;
1308 // skip the comma and whitespace
1309 s++;
1310 while (isspace(*s))
1311 s++;
1313 return var != 0;
1316 static bool parseValueSeq(const char*& s, VarTree* variable)
1318 // parse a comma-separated sequence of variables
1319 int index = 0;
1320 bool good;
1321 for (;;) {
1322 QString name;
1323 name.sprintf("[%d]", index);
1324 VarTree* var = new VarTree(name, VarTree::NKplain);
1325 var->setDeleteChildren(true);
1326 good = parseValue(s, var);
1327 if (!good) {
1328 delete var;
1329 return false;
1331 // a value may be followed by "<repeats 45 times>"
1332 if (strncmp(s, "<repeats ", 9) == 0) {
1333 s += 9;
1334 char* end;
1335 int l = strtol(s, &end, 10);
1336 if (end == s || strncmp(end, " times>", 7) != 0) {
1337 // should not happen
1338 delete var;
1339 return false;
1341 TRACE(QString().sprintf("found <repeats %d times> in array", l));
1342 // replace name and advance index
1343 name.sprintf("[%d .. %d]", index, index+l-1);
1344 var->setText(name);
1345 index += l;
1346 // skip " times>" and space
1347 s = end+7;
1348 // possible final space
1349 while (isspace(*s))
1350 s++;
1351 } else {
1352 index++;
1354 variable->appendChild(var);
1355 if (*s != ',') {
1356 break;
1358 // skip the comma and whitespace
1359 s++;
1360 while (isspace(*s))
1361 s++;
1362 // sometimes there is a closing brace after a comma
1363 // if (*s == '}')
1364 // break;
1366 return true;
1369 #if QT_VERSION < 200
1370 #define ISSPACE(c) isspace((c))
1371 #else
1372 // c is a QChar
1373 #define ISSPACE(c) (c).isSpace()
1374 #endif
1377 * Parses a stack frame.
1379 static void parseFrameInfo(const char*& s, QString& func,
1380 QString& file, int& lineNo, DbgAddr& address)
1382 const char* p = s;
1384 // next may be a hexadecimal address
1385 if (*p == '0') {
1386 const char* start = p;
1387 p++;
1388 if (*p == 'x')
1389 p++;
1390 while (isxdigit(*p))
1391 p++;
1392 address = FROM_LATIN1(start, p-start);
1393 if (strncmp(p, " in ", 4) == 0)
1394 p += 4;
1395 } else {
1396 address = DbgAddr();
1398 const char* start = p;
1399 // check for special signal handler frame
1400 if (strncmp(p, "<signal handler called>", 23) == 0) {
1401 func = FROM_LATIN1(start, 23);
1402 file = QString();
1403 lineNo = -1;
1404 s = p+23;
1405 if (*s == '\n')
1406 s++;
1407 return;
1409 // search opening parenthesis
1410 while (*p != '\0' && *p != '(')
1411 p++;
1412 if (*p == '\0') {
1413 func = start;
1414 file = QString();
1415 lineNo = -1;
1416 s = p;
1417 return;
1420 * Skip parameters. But notice that for complicated conversion
1421 * functions (eg. "operator int(**)()()", ie. convert to pointer to
1422 * pointer to function) as well as operator()(...) we have to skip
1423 * additional pairs of parentheses.
1425 do {
1426 skipNestedWithString(p, '(', ')');
1427 while (isspace(*p))
1428 p++;
1429 } while (*p == '(');
1431 // check for file position
1432 if (strncmp(p, "at ", 3) == 0) {
1433 p += 3;
1434 const char* fileStart = p;
1435 // go for the end of the line
1436 while (*p != '\0' && *p != '\n')
1437 p++;
1438 // search back for colon
1439 const char* colon = p;
1440 do {
1441 --colon;
1442 } while (*colon != ':');
1443 file = FROM_LATIN1(fileStart, colon-fileStart);
1444 lineNo = atoi(colon+1)-1;
1445 // skip new-line
1446 if (*p != '\0')
1447 p++;
1448 } else {
1449 // check for "from shared lib"
1450 if (strncmp(p, "from ", 5) == 0) {
1451 p += 5;
1452 // go for the end of the line
1453 while (*p != '\0' && *p != '\n')
1454 p++;
1455 // skip new-line
1456 if (*p != '\0')
1457 p++;
1459 file = "";
1460 lineNo = -1;
1462 // construct the function name (including file info)
1463 if (*p == '\0') {
1464 func = start;
1465 } else {
1466 func = FROM_LATIN1(start, p-start-1); /* don't include \n */
1468 s = p;
1471 * Replace \n (and whitespace around it) in func by a blank. We cannot
1472 * use QString::simplifyWhiteSpace() for this because this would also
1473 * simplify space that belongs to a string arguments that gdb sometimes
1474 * prints in the argument lists of the function.
1476 ASSERT(!ISSPACE(func[0])); /* there must be non-white before first \n */
1477 int nl = 0;
1478 while ((nl = func.find('\n', nl)) >= 0) {
1479 // search back to the beginning of the whitespace
1480 int startWhite = nl;
1481 do {
1482 --startWhite;
1483 } while (ISSPACE(func[startWhite]));
1484 startWhite++;
1485 // search forward to the end of the whitespace
1486 do {
1487 nl++;
1488 } while (ISSPACE(func[nl]));
1489 // replace
1490 func.replace(startWhite, nl-startWhite, " ");
1491 /* continue searching for more \n's at this place: */
1492 nl = startWhite+1;
1496 #undef ISSPACE
1499 * Parses a stack frame including its frame number
1501 static bool parseFrame(const char*& s, int& frameNo, QString& func,
1502 QString& file, int& lineNo, DbgAddr& address)
1504 // Example:
1505 // #1 0x8048881 in Dl::Dl (this=0xbffff418, r=3214) at testfile.cpp:72
1507 // must start with a hash mark followed by number
1508 if (s[0] != '#' || !isdigit(s[1]))
1509 return false;
1511 s++; /* skip the hash mark */
1512 // frame number
1513 frameNo = atoi(s);
1514 while (isdigit(*s))
1515 s++;
1516 // space
1517 while (isspace(*s))
1518 s++;
1519 parseFrameInfo(s, func, file, lineNo, address);
1520 return true;
1523 void GdbDriver::parseBackTrace(const char* output, QList<StackFrame>& stack)
1525 QString func, file;
1526 int lineNo, frameNo;
1527 DbgAddr address;
1529 while (::parseFrame(output, frameNo, func, file, lineNo, address)) {
1530 StackFrame* frm = new StackFrame;
1531 frm->frameNo = frameNo;
1532 frm->fileName = file;
1533 frm->lineNo = lineNo;
1534 frm->address = address;
1535 frm->var = new VarTree(func, VarTree::NKplain);
1536 stack.append(frm);
1540 bool GdbDriver::parseFrameChange(const char* output, int& frameNo,
1541 QString& file, int& lineNo, DbgAddr& address)
1543 QString func;
1544 return ::parseFrame(output, frameNo, func, file, lineNo, address);
1548 bool GdbDriver::parseBreakList(const char* output, QList<Breakpoint>& brks)
1550 // skip first line, which is the headline
1551 const char* p = strchr(output, '\n');
1552 if (p == 0)
1553 return false;
1554 p++;
1555 if (*p == '\0')
1556 return false;
1558 // split up a line
1559 QString location;
1560 QString address;
1561 int hits = 0;
1562 uint ignoreCount = 0;
1563 QString condition;
1564 const char* end;
1565 char* dummy;
1566 while (*p != '\0') {
1567 // get Num
1568 long bpNum = strtol(p, &dummy, 10); /* don't care about overflows */
1569 p = dummy;
1570 // get Type
1571 while (isspace(*p))
1572 p++;
1573 Breakpoint::Type bpType;
1574 if (strncmp(p, "breakpoint", 10) == 0) {
1575 bpType = Breakpoint::breakpoint;
1576 p += 10;
1577 } else if (strncmp(p, "hw watchpoint", 13) == 0) {
1578 bpType = Breakpoint::watchpoint;
1579 p += 13;
1580 } else if (strncmp(p, "watchpoint", 10) == 0) {
1581 bpType = Breakpoint::watchpoint;
1582 p += 10;
1584 while (isspace(*p))
1585 p++;
1586 if (*p == '\0')
1587 break;
1588 // get Disp
1589 char disp = *p++;
1590 while (*p != '\0' && !isspace(*p)) /* "keep" or "del" */
1591 p++;
1592 while (isspace(*p))
1593 p++;
1594 if (*p == '\0')
1595 break;
1596 // get Enb
1597 char enable = *p++;
1598 while (*p != '\0' && !isspace(*p)) /* "y" or "n" */
1599 p++;
1600 while (isspace(*p))
1601 p++;
1602 if (*p == '\0')
1603 break;
1604 // the address, if present
1605 if (bpType == Breakpoint::breakpoint &&
1606 strncmp(p, "0x", 2) == 0)
1608 const char* start = p;
1609 while (*p != '\0' && !isspace(*p))
1610 p++;
1611 address = FROM_LATIN1(start, p-start);
1612 while (isspace(*p) && *p != '\n')
1613 p++;
1614 if (*p == '\0')
1615 break;
1616 } else {
1617 address = QString();
1619 // remainder is location, hit and ignore count, condition
1620 hits = 0;
1621 ignoreCount = 0;
1622 condition = QString();
1623 end = strchr(p, '\n');
1624 if (end == 0) {
1625 location = p;
1626 p += location.length();
1627 } else {
1628 location = FROM_LATIN1(p, end-p).stripWhiteSpace();
1629 p = end+1; /* skip over \n */
1632 // may be continued in next line
1633 while (isspace(*p)) { /* p points to beginning of line */
1634 // skip white space at beginning of line
1635 while (isspace(*p))
1636 p++;
1638 // seek end of line
1639 end = strchr(p, '\n');
1640 if (end == 0)
1641 end = p+strlen(p);
1643 if (strncmp(p, "breakpoint already hit", 22) == 0) {
1644 // extract the hit count
1645 p += 22;
1646 hits = strtol(p, &dummy, 10);
1647 TRACE(QString().sprintf("hit count %d", hits));
1648 } else if (strncmp(p, "stop only if ", 13) == 0) {
1649 // extract condition
1650 p += 13;
1651 condition = FROM_LATIN1(p, end-p).stripWhiteSpace();
1652 TRACE("condition: "+condition);
1653 } else if (strncmp(p, "ignore next ", 12) == 0) {
1654 // extract ignore count
1655 p += 12;
1656 ignoreCount = strtol(p, &dummy, 10);
1657 TRACE(QString().sprintf("ignore count %d", ignoreCount));
1658 } else {
1659 // indeed a continuation
1660 location += " " + FROM_LATIN1(p, end-p).stripWhiteSpace();
1662 p = end;
1663 if (*p != '\0')
1664 p++; /* skip '\n' */
1666 Breakpoint* bp = new Breakpoint;
1667 bp->id = bpNum;
1668 bp->type = bpType;
1669 bp->temporary = disp == 'd';
1670 bp->enabled = enable == 'y';
1671 bp->location = location;
1672 bp->address = address;
1673 bp->hitCount = hits;
1674 bp->ignoreCount = ignoreCount;
1675 bp->condition = condition;
1676 brks.append(bp);
1678 return true;
1681 bool GdbDriver::parseThreadList(const char* output, QList<ThreadInfo>& threads)
1683 if (strcmp(output, "\n") == 0 || strncmp(output, "No stack.", 9) == 0) {
1684 // no threads
1685 return true;
1688 int id;
1689 QString systag;
1690 QString func, file;
1691 int lineNo;
1692 DbgAddr address;
1694 const char* p = output;
1695 while (*p != '\0') {
1696 // seach look for thread id, watching out for the focus indicator
1697 bool hasFocus = false;
1698 while (isspace(*p)) /* may be \n from prev line: see "No stack" below */
1699 p++;
1700 if (*p == '*') {
1701 hasFocus = true;
1702 p++;
1703 // there follows only whitespace
1705 char* end;
1706 id = strtol(p, &end, 10);
1707 if (p == end) {
1708 // syntax error: no number found; bail out
1709 return true;
1711 p = end;
1713 // skip space
1714 while (isspace(*p))
1715 p++;
1718 * Now follows the thread's SYSTAG. It is terminated by two blanks.
1720 end = strstr(p, " ");
1721 if (end == 0) {
1722 // syntax error; bail out
1723 return true;
1725 systag = FROM_LATIN1(p, end-p);
1726 p = end+2;
1729 * Now follows a standard stack frame. Sometimes, however, gdb
1730 * catches a thread at an instant where it doesn't have a stack.
1732 if (strncmp(p, "[No stack.]", 11) != 0) {
1733 ::parseFrameInfo(p, func, file, lineNo, address);
1734 } else {
1735 func = "[No stack]";
1736 file = QString();
1737 lineNo = -1;
1738 address = QString();
1739 p += 11; /* \n is skipped above */
1742 ThreadInfo* thr = new ThreadInfo;
1743 thr->id = id;
1744 thr->threadName = systag;
1745 thr->hasFocus = hasFocus;
1746 thr->function = func;
1747 thr->fileName = file;
1748 thr->lineNo = lineNo;
1749 thr->address = address;
1750 threads.append(thr);
1752 return true;
1755 bool GdbDriver::parseBreakpoint(const char* output, int& id,
1756 QString& file, int& lineNo)
1758 const char* o = output;
1759 // skip lines of that begin with "(Cannot find"
1760 while (strncmp(o, "(Cannot find", 12) == 0) {
1761 o = strchr(o, '\n');
1762 if (o == 0)
1763 return false;
1764 o++; /* skip newline */
1767 if (strncmp(o, "Breakpoint ", 11) != 0)
1768 return false;
1770 // breakpoint id
1771 output += 11; /* skip "Breakpoint " */
1772 char* p;
1773 int num = strtoul(output, &p, 10);
1774 if (p == o)
1775 return false;
1777 // file name
1778 char* fileStart = strstr(p, "file ");
1779 if (fileStart == 0)
1780 return false;
1781 fileStart += 5;
1783 // line number
1784 char* numStart = strstr(fileStart, ", line ");
1785 QString fileName = FROM_LATIN1(fileStart, numStart-fileStart);
1786 numStart += 7;
1787 int line = strtoul(numStart, &p, 10);
1788 if (numStart == p)
1789 return false;
1791 id = num;
1792 file = fileName;
1793 lineNo = line-1; /* zero-based! */
1794 return true;
1797 void GdbDriver::parseLocals(const char* output, QList<VarTree>& newVars)
1799 // check for possible error conditions
1800 if (strncmp(output, "No symbol table", 15) == 0)
1802 return;
1805 while (*output != '\0') {
1806 while (isspace(*output))
1807 output++;
1808 if (*output == '\0')
1809 break;
1810 // skip occurrences of "No locals" and "No args"
1811 if (strncmp(output, "No locals", 9) == 0 ||
1812 strncmp(output, "No arguments", 12) == 0)
1814 output = strchr(output, '\n');
1815 if (output == 0) {
1816 break;
1818 continue;
1821 VarTree* variable = parseVar(output);
1822 if (variable == 0) {
1823 break;
1825 // do not add duplicates
1826 for (VarTree* o = newVars.first(); o != 0; o = newVars.next()) {
1827 if (o->getText() == variable->getText()) {
1828 delete variable;
1829 goto skipDuplicate;
1832 newVars.append(variable);
1833 skipDuplicate:;
1837 bool GdbDriver::parsePrintExpr(const char* output, bool wantErrorValue, VarTree*& var)
1839 // check for error conditions
1840 if (parseErrorMessage(output, var, wantErrorValue))
1842 return false;
1843 } else {
1844 // parse the variable
1845 var = parseVar(output);
1846 return true;
1850 bool GdbDriver::parseChangeWD(const char* output, QString& message)
1852 bool isGood = false;
1853 message = QString(output).simplifyWhiteSpace();
1854 if (message.isEmpty()) {
1855 message = i18n("New working directory: ") + m_programWD;
1856 isGood = true;
1858 return isGood;
1861 bool GdbDriver::parseChangeExecutable(const char* output, QString& message)
1863 message = output;
1865 m_haveCoreFile = false;
1868 * The command is successful if there is no output or the single
1869 * message (no debugging symbols found)...
1871 return
1872 output[0] == '\0' ||
1873 strcmp(output, "(no debugging symbols found)...") == 0;
1876 bool GdbDriver::parseCoreFile(const char* output)
1878 // if command succeeded, gdb emits a line starting with "#0 "
1879 m_haveCoreFile = strstr(output, "\n#0 ") != 0;
1880 return m_haveCoreFile;
1883 uint GdbDriver::parseProgramStopped(const char* output, QString& message)
1885 // optionally: "program changed, rereading symbols",
1886 // followed by:
1887 // "Program exited normally"
1888 // "Program terminated with wignal SIGSEGV"
1889 // "Program received signal SIGINT" or other signal
1890 // "Breakpoint..."
1892 // go through the output, line by line, checking what we have
1893 const char* start = output - 1;
1894 uint flags = SFprogramActive;
1895 message = QString();
1896 do {
1897 start++; /* skip '\n' */
1899 if (strncmp(start, "Program ", 8) == 0 ||
1900 strncmp(start, "ptrace: ", 8) == 0) {
1902 * When we receive a signal, the program remains active.
1904 * Special: If we "stopped" in a corefile, the string "Program
1905 * terminated with signal"... is displayed. (Normally, we see
1906 * "Program received signal"... when a signal happens.)
1908 if (strncmp(start, "Program exited", 14) == 0 ||
1909 (strncmp(start, "Program terminated", 18) == 0 && !m_haveCoreFile) ||
1910 strncmp(start, "ptrace: ", 8) == 0)
1912 flags &= ~SFprogramActive;
1915 // set message
1916 const char* endOfMessage = strchr(start, '\n');
1917 if (endOfMessage == 0)
1918 endOfMessage = start + strlen(start);
1919 message = FROM_LATIN1(start, endOfMessage-start);
1920 } else if (strncmp(start, "Breakpoint ", 11) == 0) {
1922 * We stopped at a (permanent) breakpoint (gdb doesn't tell us
1923 * that it stopped at a temporary breakpoint).
1925 flags |= SFrefreshBreak;
1926 } else if (strstr(start, "re-reading symbols.") != 0) {
1927 flags |= SFrefreshSource;
1930 // next line, please
1931 start = strchr(start, '\n');
1932 } while (start != 0);
1935 * Gdb only notices when new threads have appeared, but not when a
1936 * thread finishes. So we always have to assume that the list of
1937 * threads has changed.
1939 flags |= SFrefreshThreads;
1941 return flags;
1944 void GdbDriver::parseSharedLibs(const char* output, QStrList& shlibs)
1946 if (strncmp(output, "No shared libraries loaded", 26) == 0)
1947 return;
1949 // parse the table of shared libraries
1951 // strip off head line
1952 output = strchr(output, '\n');
1953 if (output == 0)
1954 return;
1955 output++; /* skip '\n' */
1956 QString shlibName;
1957 while (*output != '\0') {
1958 // format of a line is
1959 // 0x404c5000 0x40580d90 Yes /lib/libc.so.5
1960 // 3 blocks of non-space followed by space
1961 for (int i = 0; *output != '\0' && i < 3; i++) {
1962 while (*output != '\0' && !isspace(*output)) { /* non-space */
1963 output++;
1965 while (isspace(*output)) { /* space */
1966 output++;
1969 if (*output == '\0')
1970 return;
1971 const char* start = output;
1972 output = strchr(output, '\n');
1973 if (output == 0)
1974 output = start + strlen(start);
1975 shlibName = FROM_LATIN1(start, output-start);
1976 if (*output != '\0')
1977 output++;
1978 shlibs.append(shlibName);
1979 TRACE("found shared lib " + shlibName);
1983 bool GdbDriver::parseFindType(const char* output, QString& type)
1985 if (strncmp(output, "type = ", 7) != 0)
1986 return false;
1989 * Everything else is the type. We strip off all white-space from the
1990 * type.
1992 output += 7;
1993 type = output;
1994 type.replace(QRegExp("\\s+"), "");
1995 return true;
1998 void GdbDriver::parseRegisters(const char* output, QList<RegisterInfo>& regs)
2000 if (strncmp(output, "The program has no registers now", 32) == 0) {
2001 return;
2004 QString regName;
2005 QString value;
2007 // parse register values
2008 while (*output != '\0')
2010 // skip space at the start of the line
2011 while (isspace(*output))
2012 output++;
2014 // register name
2015 const char* start = output;
2016 while (*output != '\0' && !isspace(*output))
2017 output++;
2018 if (*output == '\0')
2019 break;
2020 regName = FROM_LATIN1(start, output-start);
2022 // skip space
2023 while (isspace(*output))
2024 output++;
2025 // the rest of the line is the register value
2026 start = output;
2027 output = strchr(output,'\n');
2028 if (output == 0)
2029 output = start + strlen(start);
2030 value = FROM_LATIN1(start, output-start).simplifyWhiteSpace();
2032 if (*output != '\0')
2033 output++; /* skip '\n' */
2035 RegisterInfo* reg = new RegisterInfo;
2036 reg->regName = regName;
2039 * We split the raw from the cooked values. For this purpose, we
2040 * split off the first token (separated by whitespace). It is the
2041 * raw value. The remainder of the line is the cooked value.
2043 int pos = value.find(' ');
2044 if (pos < 0) {
2045 reg->rawValue = value;
2046 reg->cookedValue = QString();
2047 } else {
2048 reg->rawValue = value.left(pos);
2049 reg->cookedValue = value.mid(pos+1,value.length());
2051 * Some modern gdbs explicitly say: "0.1234 (raw 0x3e4567...)".
2052 * Here the raw value is actually in the second part.
2054 if (reg->cookedValue.left(5) == "(raw ") {
2055 QString raw = reg->cookedValue.right(reg->cookedValue.length()-5);
2056 if (raw[raw.length()-1] == ')') /* remove closing bracket */
2057 raw = raw.left(raw.length()-1);
2058 reg->cookedValue = reg->rawValue;
2059 reg->rawValue = raw;
2063 regs.append(reg);
2067 bool GdbDriver::parseInfoLine(const char* output, QString& addrFrom, QString& addrTo)
2069 const char* start = strstr(output, "starts at address ");
2070 if (start == 0)
2071 return false;
2073 start += 18;
2074 const char* p = start;
2075 while (*p != '\0' && !isspace(*p))
2076 p++;
2077 addrFrom = FROM_LATIN1(start, p-start);
2079 start = strstr(p, "and ends at ");
2080 if (start == 0)
2081 return false;
2083 start += 12;
2084 p = start;
2085 while (*p != '\0' && !isspace(*p))
2086 p++;
2087 addrTo = FROM_LATIN1(start, p-start);
2089 return true;
2092 void GdbDriver::parseDisassemble(const char* output, QList<DisassembledCode>& code)
2094 code.clear();
2096 if (strncmp(output, "Dump of assembler", 17) != 0) {
2097 // error message?
2098 DisassembledCode c;
2099 c.code = output;
2100 code.append(new DisassembledCode(c));
2101 return;
2104 // remove first line
2105 const char* p = strchr(output, '\n');
2106 if (p == 0)
2107 return; /* not a regular output */
2109 p++;
2111 // remove last line
2112 const char* end = strstr(output, "\nEnd of assembler");
2113 if (end == 0)
2114 end = p + strlen(p);
2116 DbgAddr address;
2118 // remove function offsets from the lines
2119 while (p != end)
2121 const char* start = p;
2122 // address
2123 while (p != end && !isspace(*p))
2124 p++;
2125 address = FROM_LATIN1(start, p-start);
2127 // function name (enclosed in '<>', followed by ':')
2128 while (p != end && *p != '<')
2129 p++;
2130 if (*p == '<')
2131 skipNested(p, '<', '>');
2132 if (*p == ':')
2133 p++;
2135 // space until code
2136 while (p != end && isspace(*p))
2137 p++;
2139 // code until end of line
2140 start = p;
2141 while (p != end && *p != '\n')
2142 p++;
2143 if (p != end) /* include '\n' */
2144 p++;
2146 DisassembledCode* c = new DisassembledCode;
2147 c->address = address;
2148 c->code = FROM_LATIN1(start, p-start);
2149 code.append(c);
2153 QString GdbDriver::parseMemoryDump(const char* output, QList<MemoryDump>& memdump)
2155 if (isErrorExpr(output)) {
2156 // error; strip space
2157 QString msg = output;
2158 return msg.stripWhiteSpace();
2161 const char* p = output; /* save typing */
2162 DbgAddr addr;
2163 QString dump;
2165 // the address
2166 while (*p != 0) {
2167 const char* start = p;
2168 while (*p != '\0' && *p != ':' && !isspace(*p))
2169 p++;
2170 addr = FROM_LATIN1(start, p-start);
2171 if (*p != ':') {
2172 // parse function offset
2173 while (isspace(*p))
2174 p++;
2175 start = p;
2176 while (*p != '\0' && !(*p == ':' && isspace(p[1])))
2177 p++;
2178 addr.fnoffs = FROM_LATIN1(start, p-start);
2180 if (*p == ':')
2181 p++;
2182 // skip space; this may skip a new-line char!
2183 while (isspace(*p))
2184 p++;
2185 // everything to the end of the line is the memory dump
2186 const char* end = strchr(p, '\n');
2187 if (end != 0) {
2188 dump = FROM_LATIN1(p, end-p);
2189 p = end+1;
2190 } else {
2191 dump = FROM_LATIN1(p, strlen(p));
2192 p += strlen(p);
2194 MemoryDump* md = new MemoryDump;
2195 md->address = addr;
2196 md->dump = dump;
2197 memdump.append(md);
2200 return QString();
2204 #include "gdbdriver.moc"