The program counter can be changed via point and click.
[kdbg.git] / kdbg / gdbdriver.cpp
blob744931da88e0fe0bda365dec2521e9225363a7ae
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 { DCsetpc, "set variable $pc=%s\n", GdbCmdInfo::argString },
120 { DCignore, "ignore %d %d\n", GdbCmdInfo::argNum2},
123 #define NUM_CMDS (int(sizeof(cmds)/sizeof(cmds[0])))
124 #define MAX_FMTLEN 200
126 GdbDriver::GdbDriver() :
127 DebuggerDriver(),
128 m_gdbMajor(4), m_gdbMinor(16)
130 strcpy(m_prompt, PROMPT);
131 m_promptMinLen = PROMPT_LEN;
132 m_promptLastChar = PROMPT_LAST_CHAR;
134 #ifndef NDEBUG
135 // check command info array
136 char* perc;
137 for (int i = 0; i < NUM_CMDS; i++) {
138 // must be indexable by DbgCommand values, i.e. sorted by DbgCommand values
139 assert(i == cmds[i].cmd);
140 // a format string must be associated
141 assert(cmds[i].fmt != 0);
142 assert(strlen(cmds[i].fmt) <= MAX_FMTLEN);
143 // format string must match arg specification
144 switch (cmds[i].argsNeeded) {
145 case GdbCmdInfo::argNone:
146 assert(strchr(cmds[i].fmt, '%') == 0);
147 break;
148 case GdbCmdInfo::argString:
149 perc = strchr(cmds[i].fmt, '%');
150 assert(perc != 0 && perc[1] == 's');
151 assert(strchr(perc+2, '%') == 0);
152 break;
153 case GdbCmdInfo::argNum:
154 perc = strchr(cmds[i].fmt, '%');
155 assert(perc != 0 && perc[1] == 'd');
156 assert(strchr(perc+2, '%') == 0);
157 break;
158 case GdbCmdInfo::argStringNum:
159 perc = strchr(cmds[i].fmt, '%');
160 assert(perc != 0 && perc[1] == 's');
161 perc = strchr(perc+2, '%');
162 assert(perc != 0 && perc[1] == 'd');
163 assert(strchr(perc+2, '%') == 0);
164 break;
165 case GdbCmdInfo::argNumString:
166 perc = strchr(cmds[i].fmt, '%');
167 assert(perc != 0 && perc[1] == 'd');
168 perc = strchr(perc+2, '%');
169 assert(perc != 0 && perc[1] == 's');
170 assert(strchr(perc+2, '%') == 0);
171 break;
172 case GdbCmdInfo::argString2:
173 perc = strchr(cmds[i].fmt, '%');
174 assert(perc != 0 && perc[1] == 's');
175 perc = strchr(perc+2, '%');
176 assert(perc != 0 && perc[1] == 's');
177 assert(strchr(perc+2, '%') == 0);
178 break;
179 case GdbCmdInfo::argNum2:
180 perc = strchr(cmds[i].fmt, '%');
181 assert(perc != 0 && perc[1] == 'd');
182 perc = strchr(perc+2, '%');
183 assert(perc != 0 && perc[1] == 'd');
184 assert(strchr(perc+2, '%') == 0);
185 break;
188 assert(strlen(printQStringStructFmt) <= MAX_FMTLEN);
189 assert(strlen(printQStringStructNoNullFmt) <= MAX_FMTLEN);
190 #endif
193 GdbDriver::~GdbDriver()
198 QString GdbDriver::driverName() const
200 return "GDB";
203 QString GdbDriver::defaultGdb()
205 return
206 "gdb"
207 " --fullname" /* to get standard file names each time the prog stops */
208 " --nx"; /* do not execute initialization files */
211 QString GdbDriver::defaultInvocation() const
213 if (m_defaultCmd.isEmpty()) {
214 return defaultGdb();
215 } else {
216 return m_defaultCmd;
220 QStringList GdbDriver::boolOptionList() const
222 // no options
223 return QStringList();
226 bool GdbDriver::startup(QString cmdStr)
228 if (!DebuggerDriver::startup(cmdStr))
229 return false;
231 static const char gdbInitialize[] =
233 * Work around buggy gdbs that do command line editing even if they
234 * are not on a tty. The readline library echos every command back
235 * in this case, which is confusing for us.
237 "set editing off\n"
238 "set confirm off\n"
239 "set print static-members off\n"
240 "set print asm-demangle on\n"
242 * Write a short macro that prints all locals: local variables and
243 * function arguments.
245 "define kdbg__alllocals\n"
246 "info locals\n" /* local vars supersede args with same name */
247 "info args\n" /* therefore, arguments must come last */
248 "end\n"
249 // change prompt string and synchronize with gdb
250 "set prompt " PROMPT "\n"
253 executeCmdString(DCinitialize, gdbInitialize, false);
255 // assume that QString::null is ok
256 cmds[DCprintQStringStruct].fmt = printQStringStructFmt;
258 return true;
261 void GdbDriver::commandFinished(CmdQueueItem* cmd)
263 // command string must be committed
264 if (!cmd->m_committed) {
265 // not commited!
266 TRACE("calling " + (__PRETTY_FUNCTION__ + (" with uncommited command:\n\t" +
267 cmd->m_cmdString)));
268 return;
271 switch (cmd->m_cmd) {
272 case DCinitialize:
273 // get version number from preamble
275 int len;
276 QRegExp GDBVersion("\\nGDB [0-9]+\\.[0-9]+");
277 int offset = GDBVersion.match(m_output, 0, &len);
278 if (offset >= 0) {
279 char* start = m_output + offset + 5; // skip "\nGDB "
280 char* end;
281 m_gdbMajor = strtol(start, &end, 10);
282 m_gdbMinor = strtol(end + 1, 0, 10); // skip "."
283 if (start == end) {
284 // nothing was parsed
285 m_gdbMajor = 4;
286 m_gdbMinor = 16;
288 } else {
289 // assume some default version (what would make sense?)
290 m_gdbMajor = 4;
291 m_gdbMinor = 16;
293 // use a feasible core-file command
294 if (m_gdbMajor > 4 || (m_gdbMajor == 4 && m_gdbMinor >= 16)) {
295 cmds[DCcorefile].fmt = "target core %s\n";
296 } else {
297 cmds[DCcorefile].fmt = "core-file %s\n";
300 break;
301 default:;
304 /* ok, the command is ready */
305 emit commandReceived(cmd, m_output);
307 switch (cmd->m_cmd) {
308 case DCcorefile:
309 case DCinfolinemain:
310 case DCframe:
311 case DCattach:
312 case DCrun:
313 case DCcont:
314 case DCstep:
315 case DCstepi:
316 case DCnext:
317 case DCnexti:
318 case DCfinish:
319 case DCuntil:
320 parseMarker();
321 default:;
326 * The --fullname option makes gdb send a special normalized sequence print
327 * each time the program stops and at some other points. The sequence has
328 * the form "\032\032filename:lineno:charoffset:(beg|middle):address".
330 void GdbDriver::parseMarker()
332 char* startMarker = strstr(m_output, "\032\032");
333 if (startMarker == 0)
334 return;
336 // extract the marker
337 startMarker += 2;
338 TRACE(QString("found marker: ") + startMarker);
339 char* endMarker = strchr(startMarker, '\n');
340 if (endMarker == 0)
341 return;
343 *endMarker = '\0';
345 // extract filename and line number
346 static QRegExp MarkerRE(":[0-9]+:[0-9]+:[begmidl]+:0x");
348 int len;
349 int lineNoStart = MarkerRE.match(startMarker, 0, &len);
350 if (lineNoStart >= 0) {
351 int lineNo = atoi(startMarker + lineNoStart+1);
353 // get address
354 const char* addrStart = startMarker + lineNoStart + len - 2;
355 DbgAddr address = QString(addrStart).stripWhiteSpace();
357 // now show the window
358 startMarker[lineNoStart] = '\0'; /* split off file name */
359 emit activateFileLine(startMarker, lineNo-1, address);
365 * Escapes characters that might lead to problems when they appear on gdb's
366 * command line.
368 static void normalizeStringArg(QString& arg)
371 * Remove trailing backslashes. This approach is a little simplistic,
372 * but we know that there is at the moment no case where a trailing
373 * backslash would make sense.
375 while (!arg.isEmpty() && arg[arg.length()-1] == '\\') {
376 arg = arg.left(arg.length()-1);
381 QString GdbDriver::makeCmdString(DbgCommand cmd, QString strArg)
383 assert(cmd >= 0 && cmd < NUM_CMDS);
384 assert(cmds[cmd].argsNeeded == GdbCmdInfo::argString);
386 normalizeStringArg(strArg);
388 if (cmd == DCcd) {
389 // need the working directory when parsing the output
390 m_programWD = strArg;
391 } else if (cmd == DCsetargs) {
392 // attach saved redirection
393 strArg += m_redirect;
396 SIZED_QString(cmdString, MAX_FMTLEN+strArg.length());
397 cmdString.sprintf(cmds[cmd].fmt, strArg.latin1());
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, strArg.latin1(), intArg);
508 else
510 cmdString.sprintf(cmds[cmd].fmt, intArg, strArg.latin1());
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, strArg1.latin1(), strArg2.latin1());
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, "A parse error in expression", 27) == 0 ||
639 strncmp(output, "No symbol \"", 11) == 0 ||
640 strncmp(output, "Internal error: ", 16) == 0;
644 * Returns true if the output is an error message. If wantErrorValue is
645 * true, a new VarTree object is created and filled with the error message.
647 static bool parseErrorMessage(const char* output,
648 VarTree*& variable, bool wantErrorValue)
650 if (isErrorExpr(output))
652 if (wantErrorValue) {
653 // put the error message as value in the variable
654 variable = new VarTree(QString(), VarTree::NKplain);
655 const char* endMsg = strchr(output, '\n');
656 if (endMsg == 0)
657 endMsg = output + strlen(output);
658 variable->m_value = FROM_LATIN1(output, endMsg-output);
659 } else {
660 variable = 0;
662 return true;
664 return false;
667 #if QT_VERSION >= 300
668 union Qt2QChar {
669 short s;
670 struct {
671 uchar row;
672 uchar cell;
673 } qch;
675 #endif
677 VarTree* GdbDriver::parseQCharArray(const char* output, bool wantErrorValue, bool qt3like)
679 VarTree* variable = 0;
682 * Parse off white space. gdb sometimes prints white space first if the
683 * printed array leaded to an error.
685 const char* p = output;
686 while (isspace(*p))
687 p++;
689 // check if this is an error indicating that gdb does not know about QString::null
690 if (cmds[DCprintQStringStruct].fmt == printQStringStructFmt &&
691 (strncmp(p, "Internal error: could not find static variable null", 51) == 0 ||
693 * At least gdb 5.2.1 reports the following error when it accesses
694 * QString::null. Checking for it can result in false positives
695 * (where the error is actually triggered by a real NULL pointer
696 * in a badly initialized QString variable) but the consequences
697 * are mild.
699 strncmp(p, "Cannot access memory at address 0x0", 35) == 0))
701 /* QString::null doesn't work, use an alternate expression */
702 cmds[DCprintQStringStruct].fmt = printQStringStructNoNullFmt;
703 // continue and let parseOffErrorExpr catch the error
706 // special case: empty string (0 repetitions)
707 if (strncmp(p, "Invalid number 0 of repetitions", 31) == 0)
709 variable = new VarTree(QString(), VarTree::NKplain);
710 variable->m_value = "\"\"";
711 return variable;
714 // check for error conditions
715 if (parseErrorMessage(p, variable, wantErrorValue))
716 return variable;
718 // parse the array
720 // find '='
721 p = strchr(p, '=');
722 if (p == 0) {
723 goto error;
725 // skip white space
726 do {
727 p++;
728 } while (isspace(*p));
730 if (*p == '{')
732 // this is the real data
733 p++; /* skip '{' */
735 // parse the array
736 QString result;
737 QString repeatCount;
738 enum { wasNothing, wasChar, wasRepeat } lastThing = wasNothing;
740 * A matrix for separators between the individual "things"
741 * that are added to the string. The first index is a bool,
742 * the second index is from the enum above.
744 static const char* separator[2][3] = {
745 { "\"", 0, ", \"" }, /* normal char is added */
746 { "'", "\", '", ", '" } /* repeated char is added */
749 while (isdigit(*p)) {
750 // parse a number
751 char* end;
752 unsigned short value = (unsigned short) strtoul(p, &end, 0);
753 if (end == p)
754 goto error; /* huh? no valid digits */
755 // skip separator and search for a repeat count
756 p = end;
757 while (isspace(*p) || *p == ',')
758 p++;
759 bool repeats = strncmp(p, "<repeats ", 9) == 0;
760 if (repeats) {
761 const char* start = p;
762 p = strchr(p+9, '>'); /* search end and advance */
763 if (p == 0)
764 goto error;
765 p++; /* skip '>' */
766 repeatCount = FROM_LATIN1(start, p-start);
767 while (isspace(*p) || *p == ',')
768 p++;
770 // p is now at the next char (or the end)
772 // interpret the value as a QChar
773 // TODO: make cross-architecture compatible
774 QChar ch;
775 if (qt3like) {
776 ch = QChar(value);
777 } else {
778 #if QT_VERSION < 300
779 (unsigned short&)ch = value;
780 #else
781 Qt2QChar c;
782 c.s = value;
783 ch.setRow(c.qch.row);
784 ch.setCell(c.qch.cell);
785 #endif
788 // escape a few frequently used characters
789 char escapeCode = '\0';
790 switch (ch.latin1()) {
791 case '\n': escapeCode = 'n'; break;
792 case '\r': escapeCode = 'r'; break;
793 case '\t': escapeCode = 't'; break;
794 case '\b': escapeCode = 'b'; break;
795 case '\"': escapeCode = '\"'; break;
796 case '\\': escapeCode = '\\'; break;
797 case '\0': if (value == 0) { escapeCode = '0'; } break;
800 // add separator
801 result += separator[repeats][lastThing];
802 // add char
803 if (escapeCode != '\0') {
804 result += '\\';
805 ch = escapeCode;
807 result += ch;
809 // fixup repeat count and lastThing
810 if (repeats) {
811 result += "' ";
812 result += repeatCount;
813 lastThing = wasRepeat;
814 } else {
815 lastThing = wasChar;
818 if (*p != '}')
819 goto error;
821 // closing quote
822 if (lastThing == wasChar)
823 result += "\"";
825 // assign the value
826 variable = new VarTree(QString(), VarTree::NKplain);
827 variable->m_value = result;
829 else if (strncmp(p, "true", 4) == 0)
831 variable = new VarTree(QString(), VarTree::NKplain);
832 variable->m_value = "QString::null";
834 else if (strncmp(p, "false", 5) == 0)
836 variable = new VarTree(QString(), VarTree::NKplain);
837 variable->m_value = "(null)";
839 else
840 goto error;
841 return variable;
843 error:
844 if (wantErrorValue) {
845 variable = new VarTree(QString(), VarTree::NKplain);
846 variable->m_value = "internal parse error";
848 return variable;
851 static VarTree* parseVar(const char*& s)
853 const char* p = s;
855 // skip whitespace
856 while (isspace(*p))
857 p++;
859 QString name;
860 VarTree::NameKind kind;
861 if (!parseName(p, name, kind)) {
862 return 0;
865 // go for '='
866 while (isspace(*p))
867 p++;
868 if (*p != '=') {
869 TRACE(QString().sprintf("parse error: = not found after %s", (const char*)name));
870 return 0;
872 // skip the '=' and more whitespace
873 p++;
874 while (isspace(*p))
875 p++;
877 VarTree* variable = new VarTree(name, kind);
878 variable->setDeleteChildren(true);
880 if (!parseValue(p, variable)) {
881 delete variable;
882 return 0;
884 s = p;
885 return variable;
888 static void skipNested(const char*& s, char opening, char closing)
890 const char* p = s;
892 // parse a nested type
893 int nest = 1;
894 p++;
896 * Search for next matching `closing' char, skipping nested pairs of
897 * `opening' and `closing'.
899 while (*p && nest > 0) {
900 if (*p == opening) {
901 nest++;
902 } else if (*p == closing) {
903 nest--;
905 p++;
907 if (nest > 0) {
908 TRACE(QString().sprintf("parse error: mismatching %c%c at %-20.20s", opening, closing, s));
910 s = p;
913 void skipString(const char*& p)
915 moreStrings:
916 // opening quote
917 char quote = *p++;
918 while (*p != quote) {
919 if (*p == '\\') {
920 // skip escaped character
921 // no special treatment for octal values necessary
922 p++;
924 // simply return if no more characters
925 if (*p == '\0')
926 return;
927 p++;
929 // closing quote
930 p++;
932 * Strings can consist of several parts, some of which contain repeated
933 * characters.
935 if (quote == '\'') {
936 // look ahaead for <repeats 123 times>
937 const char* q = p+1;
938 while (isspace(*q))
939 q++;
940 if (strncmp(q, "<repeats ", 9) == 0) {
941 p = q+9;
942 while (*p != '\0' && *p != '>')
943 p++;
944 if (*p != '\0') {
945 p++; /* skip the '>' */
949 // is the string continued?
950 if (*p == ',') {
951 // look ahead for another quote
952 const char* q = p+1;
953 while (isspace(*q))
954 q++;
955 if (*q == '"' || *q == '\'') {
956 // yes!
957 p = q;
958 goto moreStrings;
961 /* very long strings are followed by `...' */
962 if (*p == '.' && p[1] == '.' && p[2] == '.') {
963 p += 3;
967 static void skipNestedWithString(const char*& s, char opening, char closing)
969 const char* p = s;
971 // parse a nested expression
972 int nest = 1;
973 p++;
975 * Search for next matching `closing' char, skipping nested pairs of
976 * `opening' and `closing' as well as strings.
978 while (*p && nest > 0) {
979 if (*p == opening) {
980 nest++;
981 } else if (*p == closing) {
982 nest--;
983 } else if (*p == '\'' || *p == '\"') {
984 skipString(p);
985 continue;
987 p++;
989 if (nest > 0) {
990 TRACE(QString().sprintf("parse error: mismatching %c%c at %-20.20s", opening, closing, s));
992 s = p;
995 inline void skipName(const char*& p)
997 // allow : (for enumeration values) and $ and . (for _vtbl.)
998 while (isalnum(*p) || *p == '_' || *p == ':' || *p == '$' || *p == '.')
999 p++;
1002 static bool parseName(const char*& s, QString& name, VarTree::NameKind& kind)
1004 kind = VarTree::NKplain;
1006 const char* p = s;
1007 // examples of names:
1008 // name
1009 // <Object>
1010 // <string<a,b<c>,7> >
1012 if (*p == '<') {
1013 skipNested(p, '<', '>');
1014 name = FROM_LATIN1(s, p - s);
1015 kind = VarTree::NKtype;
1017 else
1019 // name, which might be "static"; allow dot for "_vtbl."
1020 skipName(p);
1021 if (p == s) {
1022 TRACE(QString().sprintf("parse error: not a name %-20.20s", s));
1023 return false;
1025 int len = p - s;
1026 if (len == 6 && strncmp(s, "static", 6) == 0) {
1027 kind = VarTree::NKstatic;
1029 // its a static variable, name comes now
1030 while (isspace(*p))
1031 p++;
1032 s = p;
1033 skipName(p);
1034 if (p == s) {
1035 TRACE(QString().sprintf("parse error: not a name after static %-20.20s", s));
1036 return false;
1038 len = p - s;
1040 name = FROM_LATIN1(s, len);
1042 // return the new position
1043 s = p;
1044 return true;
1047 static bool parseValue(const char*& s, VarTree* variable)
1049 variable->m_value = "";
1051 repeat:
1052 if (*s == '{') {
1053 s++;
1054 if (!parseNested(s, variable)) {
1055 return false;
1057 // must be the closing brace
1058 if (*s != '}') {
1059 TRACE("parse error: missing } of " + variable->getText());
1060 return false;
1062 s++;
1063 // final white space
1064 while (isspace(*s))
1065 s++;
1066 } else {
1067 // examples of leaf values (cannot be the empty string):
1068 // 123
1069 // -123
1070 // 23.575e+37
1071 // 0x32a45
1072 // @0x012ab4
1073 // (DwContentType&) @0x8123456: {...}
1074 // 0x32a45 "text"
1075 // 10 '\n'
1076 // <optimized out>
1077 // 0x823abc <Array<int> virtual table>
1078 // (void (*)()) 0x8048480 <f(E *, char)>
1079 // (E *) 0xbffff450
1080 // red
1081 // &parseP (HTMLClueV *, char *)
1083 const char*p = s;
1085 // check for type
1086 QString type;
1087 if (*p == '(') {
1088 skipNested(p, '(', ')');
1090 while (isspace(*p))
1091 p++;
1092 variable->m_value = FROM_LATIN1(s, p - s);
1095 bool reference = false;
1096 if (*p == '@') {
1097 // skip reference marker
1098 p++;
1099 reference = true;
1101 const char* start = p;
1102 if (*p == '-')
1103 p++;
1105 // some values consist of more than one token
1106 bool checkMultiPart = false;
1108 if (p[0] == '0' && p[1] == 'x') {
1109 // parse hex number
1110 p += 2;
1111 while (isxdigit(*p))
1112 p++;
1115 * Assume this is a pointer, but only if it's not a reference, since
1116 * references can't be expanded.
1118 if (!reference) {
1119 variable->m_varKind = VarTree::VKpointer;
1120 } else {
1122 * References are followed by a colon, in which case we'll
1123 * find the value following the reference address.
1125 if (*p == ':') {
1126 p++;
1127 } else {
1128 // Paranoia. (Can this happen, i.e. reference not followed by ':'?)
1129 reference = false;
1132 checkMultiPart = true;
1133 } else if (isdigit(*p)) {
1134 // parse decimal number, possibly a float
1135 while (isdigit(*p))
1136 p++;
1137 if (*p == '.') { /* TODO: obey i18n? */
1138 // fractional part
1139 p++;
1140 while (isdigit(*p))
1141 p++;
1143 if (*p == 'e' || *p == 'E') {
1144 p++;
1145 // exponent
1146 if (*p == '-' || *p == '+')
1147 p++;
1148 while (isdigit(*p))
1149 p++;
1152 // for char variables there is the char, eg. 10 '\n'
1153 checkMultiPart = true;
1154 } else if (*p == '<') {
1155 // e.g. <optimized out>
1156 skipNested(p, '<', '>');
1157 } else if (*p == '"' || *p == '\'') {
1158 // character may have multipart: '\000' <repeats 11 times>
1159 checkMultiPart = *p == '\'';
1160 // found a string
1161 skipString(p);
1162 } else if (*p == '&') {
1163 // function pointer
1164 p++;
1165 skipName(p);
1166 while (isspace(*p)) {
1167 p++;
1169 if (*p == '(') {
1170 skipNested(p, '(', ')');
1172 } else {
1173 // must be an enumeration value
1174 skipName(p);
1176 variable->m_value += FROM_LATIN1(start, p - start);
1178 if (checkMultiPart) {
1179 // white space
1180 while (isspace(*p))
1181 p++;
1182 // may be followed by a string or <...>
1183 start = p;
1185 if (*p == '"' || *p == '\'') {
1186 skipString(p);
1187 } else if (*p == '<') {
1188 // if this value is part of an array, it might be followed
1189 // by <repeats 15 times>, which we don't skip here
1190 if (strncmp(p, "<repeats ", 9) != 0)
1191 skipNested(p, '<', '>');
1193 if (p != start) {
1194 // there is always a blank before the string,
1195 // which we will include in the final string value
1196 variable->m_value += FROM_LATIN1(start-1, (p - start)+1);
1197 // if this was a pointer, reset that flag since we
1198 // now got the value
1199 variable->m_varKind = VarTree::VKsimple;
1203 if (variable->m_value.length() == 0) {
1204 TRACE("parse error: no value for " + variable->getText());
1205 return false;
1208 // final white space
1209 while (isspace(*p))
1210 p++;
1211 s = p;
1214 * If this was a reference, the value follows. It might even be a
1215 * composite variable!
1217 if (reference) {
1218 goto repeat;
1221 if (variable->m_varKind == VarTree::VKpointer) {
1222 variable->setDelayedExpanding(true);
1226 return true;
1229 static bool parseNested(const char*& s, VarTree* variable)
1231 // could be a structure or an array
1232 while (isspace(*s))
1233 s++;
1235 const char* p = s;
1236 bool isStruct = false;
1238 * If there is a name followed by an = or an < -- which starts a type
1239 * name -- or "static", it is a structure
1241 if (*p == '<' || *p == '}') {
1242 isStruct = true;
1243 } else if (strncmp(p, "static ", 7) == 0) {
1244 isStruct = true;
1245 } else if (isalpha(*p) || *p == '_' || *p == '$') {
1246 // look ahead for a comma after the name
1247 skipName(p);
1248 while (isspace(*p))
1249 p++;
1250 if (*p == '=') {
1251 isStruct = true;
1253 p = s; /* rescan the name */
1255 if (isStruct) {
1256 if (!parseVarSeq(p, variable)) {
1257 return false;
1259 variable->m_varKind = VarTree::VKstruct;
1260 } else {
1261 if (!parseValueSeq(p, variable)) {
1262 return false;
1264 variable->m_varKind = VarTree::VKarray;
1266 s = p;
1267 return true;
1270 static bool parseVarSeq(const char*& s, VarTree* variable)
1272 // parse a comma-separated sequence of variables
1273 VarTree* var = variable; /* var != 0 to indicate success if empty seq */
1274 for (;;) {
1275 if (*s == '}')
1276 break;
1277 if (strncmp(s, "<No data fields>}", 17) == 0)
1279 // no member variables, so break out immediately
1280 s += 16; /* go to the closing brace */
1281 break;
1283 var = parseVar(s);
1284 if (var == 0)
1285 break; /* syntax error */
1286 variable->appendChild(var);
1287 if (*s != ',')
1288 break;
1289 // skip the comma and whitespace
1290 s++;
1291 while (isspace(*s))
1292 s++;
1294 return var != 0;
1297 static bool parseValueSeq(const char*& s, VarTree* variable)
1299 // parse a comma-separated sequence of variables
1300 int index = 0;
1301 bool good;
1302 for (;;) {
1303 QString name;
1304 name.sprintf("[%d]", index);
1305 VarTree* var = new VarTree(name, VarTree::NKplain);
1306 var->setDeleteChildren(true);
1307 good = parseValue(s, var);
1308 if (!good) {
1309 delete var;
1310 return false;
1312 // a value may be followed by "<repeats 45 times>"
1313 if (strncmp(s, "<repeats ", 9) == 0) {
1314 s += 9;
1315 char* end;
1316 int l = strtol(s, &end, 10);
1317 if (end == s || strncmp(end, " times>", 7) != 0) {
1318 // should not happen
1319 delete var;
1320 return false;
1322 TRACE(QString().sprintf("found <repeats %d times> in array", l));
1323 // replace name and advance index
1324 name.sprintf("[%d .. %d]", index, index+l-1);
1325 var->setText(name);
1326 index += l;
1327 // skip " times>" and space
1328 s = end+7;
1329 // possible final space
1330 while (isspace(*s))
1331 s++;
1332 } else {
1333 index++;
1335 variable->appendChild(var);
1336 if (*s != ',') {
1337 break;
1339 // skip the comma and whitespace
1340 s++;
1341 while (isspace(*s))
1342 s++;
1343 // sometimes there is a closing brace after a comma
1344 // if (*s == '}')
1345 // break;
1347 return true;
1351 * Parses a stack frame.
1353 static void parseFrameInfo(const char*& s, QString& func,
1354 QString& file, int& lineNo, DbgAddr& address)
1356 const char* p = s;
1358 // next may be a hexadecimal address
1359 if (*p == '0') {
1360 const char* start = p;
1361 p++;
1362 if (*p == 'x')
1363 p++;
1364 while (isxdigit(*p))
1365 p++;
1366 address = FROM_LATIN1(start, p-start);
1367 if (strncmp(p, " in ", 4) == 0)
1368 p += 4;
1369 } else {
1370 address = DbgAddr();
1372 const char* start = p;
1373 // check for special signal handler frame
1374 if (strncmp(p, "<signal handler called>", 23) == 0) {
1375 func = FROM_LATIN1(start, 23);
1376 file = QString();
1377 lineNo = -1;
1378 s = p+23;
1379 if (*s == '\n')
1380 s++;
1381 return;
1383 // search opening parenthesis
1384 while (*p != '\0' && *p != '(')
1385 p++;
1386 if (*p == '\0') {
1387 func = start;
1388 file = QString();
1389 lineNo = -1;
1390 s = p;
1391 return;
1394 * Skip parameters. But notice that for complicated conversion
1395 * functions (eg. "operator int(**)()()", ie. convert to pointer to
1396 * pointer to function) as well as operator()(...) we have to skip
1397 * additional pairs of parentheses. Furthermore, recent gdbs write the
1398 * demangled name followed by the arguments in a pair of parentheses,
1399 * where the demangled name can end in "const".
1401 do {
1402 skipNestedWithString(p, '(', ')');
1403 while (isspace(*p))
1404 p++;
1405 // skip "const"
1406 if (strncmp(p, "const", 5) == 0) {
1407 p += 5;
1408 while (isspace(*p))
1409 p++;
1411 } while (*p == '(');
1413 // check for file position
1414 if (strncmp(p, "at ", 3) == 0) {
1415 p += 3;
1416 const char* fileStart = p;
1417 // go for the end of the line
1418 while (*p != '\0' && *p != '\n')
1419 p++;
1420 // search back for colon
1421 const char* colon = p;
1422 do {
1423 --colon;
1424 } while (*colon != ':');
1425 file = FROM_LATIN1(fileStart, colon-fileStart);
1426 lineNo = atoi(colon+1)-1;
1427 // skip new-line
1428 if (*p != '\0')
1429 p++;
1430 } else {
1431 // check for "from shared lib"
1432 if (strncmp(p, "from ", 5) == 0) {
1433 p += 5;
1434 // go for the end of the line
1435 while (*p != '\0' && *p != '\n')
1436 p++;
1437 // skip new-line
1438 if (*p != '\0')
1439 p++;
1441 file = "";
1442 lineNo = -1;
1444 // construct the function name (including file info)
1445 if (*p == '\0') {
1446 func = start;
1447 } else {
1448 func = FROM_LATIN1(start, p-start-1); /* don't include \n */
1450 s = p;
1453 * Replace \n (and whitespace around it) in func by a blank. We cannot
1454 * use QString::simplifyWhiteSpace() for this because this would also
1455 * simplify space that belongs to a string arguments that gdb sometimes
1456 * prints in the argument lists of the function.
1458 ASSERT(!isspace(func[0].latin1())); /* there must be non-white before first \n */
1459 int nl = 0;
1460 while ((nl = func.find('\n', nl)) >= 0) {
1461 // search back to the beginning of the whitespace
1462 int startWhite = nl;
1463 do {
1464 --startWhite;
1465 } while (isspace(func[startWhite].latin1()));
1466 startWhite++;
1467 // search forward to the end of the whitespace
1468 do {
1469 nl++;
1470 } while (isspace(func[nl].latin1()));
1471 // replace
1472 func.replace(startWhite, nl-startWhite, " ");
1473 /* continue searching for more \n's at this place: */
1474 nl = startWhite+1;
1480 * Parses a stack frame including its frame number
1482 static bool parseFrame(const char*& s, int& frameNo, QString& func,
1483 QString& file, int& lineNo, DbgAddr& address)
1485 // Example:
1486 // #1 0x8048881 in Dl::Dl (this=0xbffff418, r=3214) at testfile.cpp:72
1487 // Breakpoint 3, Cl::f(int) const (this=0xbffff3c0, x=17) at testfile.cpp:155
1489 // must start with a hash mark followed by number
1490 // or with "Breakpoint " followed by number and comma
1491 if (s[0] == '#') {
1492 if (!isdigit(s[1]))
1493 return false;
1494 s++; /* skip the hash mark */
1495 } else if (strncmp(s, "Breakpoint ", 11) == 0) {
1496 if (!isdigit(s[11]))
1497 return false;
1498 s += 11; /* skip "Breakpoint" */
1499 } else
1500 return false;
1502 // frame number
1503 frameNo = atoi(s);
1504 while (isdigit(*s))
1505 s++;
1506 // space and comma
1507 while (isspace(*s) || *s == ',')
1508 s++;
1509 parseFrameInfo(s, func, file, lineNo, address);
1510 return true;
1513 void GdbDriver::parseBackTrace(const char* output, QList<StackFrame>& stack)
1515 QString func, file;
1516 int lineNo, frameNo;
1517 DbgAddr address;
1519 while (::parseFrame(output, frameNo, func, file, lineNo, address)) {
1520 StackFrame* frm = new StackFrame;
1521 frm->frameNo = frameNo;
1522 frm->fileName = file;
1523 frm->lineNo = lineNo;
1524 frm->address = address;
1525 frm->var = new VarTree(func, VarTree::NKplain);
1526 stack.append(frm);
1530 bool GdbDriver::parseFrameChange(const char* output, int& frameNo,
1531 QString& file, int& lineNo, DbgAddr& address)
1533 QString func;
1534 return ::parseFrame(output, frameNo, func, file, lineNo, address);
1538 bool GdbDriver::parseBreakList(const char* output, QList<Breakpoint>& brks)
1540 // skip first line, which is the headline
1541 const char* p = strchr(output, '\n');
1542 if (p == 0)
1543 return false;
1544 p++;
1545 if (*p == '\0')
1546 return false;
1548 // split up a line
1549 QString location;
1550 QString address;
1551 int hits = 0;
1552 uint ignoreCount = 0;
1553 QString condition;
1554 const char* end;
1555 char* dummy;
1556 while (*p != '\0') {
1557 // get Num
1558 long bpNum = strtol(p, &dummy, 10); /* don't care about overflows */
1559 p = dummy;
1560 // get Type
1561 while (isspace(*p))
1562 p++;
1563 Breakpoint::Type bpType = Breakpoint::breakpoint;
1564 if (strncmp(p, "breakpoint", 10) == 0) {
1565 p += 10;
1566 } else if (strncmp(p, "hw watchpoint", 13) == 0) {
1567 bpType = Breakpoint::watchpoint;
1568 p += 13;
1569 } else if (strncmp(p, "watchpoint", 10) == 0) {
1570 bpType = Breakpoint::watchpoint;
1571 p += 10;
1573 while (isspace(*p))
1574 p++;
1575 if (*p == '\0')
1576 break;
1577 // get Disp
1578 char disp = *p++;
1579 while (*p != '\0' && !isspace(*p)) /* "keep" or "del" */
1580 p++;
1581 while (isspace(*p))
1582 p++;
1583 if (*p == '\0')
1584 break;
1585 // get Enb
1586 char enable = *p++;
1587 while (*p != '\0' && !isspace(*p)) /* "y" or "n" */
1588 p++;
1589 while (isspace(*p))
1590 p++;
1591 if (*p == '\0')
1592 break;
1593 // the address, if present
1594 if (bpType == Breakpoint::breakpoint &&
1595 strncmp(p, "0x", 2) == 0)
1597 const char* start = p;
1598 while (*p != '\0' && !isspace(*p))
1599 p++;
1600 address = FROM_LATIN1(start, p-start);
1601 while (isspace(*p) && *p != '\n')
1602 p++;
1603 if (*p == '\0')
1604 break;
1605 } else {
1606 address = QString();
1608 // remainder is location, hit and ignore count, condition
1609 hits = 0;
1610 ignoreCount = 0;
1611 condition = QString();
1612 end = strchr(p, '\n');
1613 if (end == 0) {
1614 location = p;
1615 p += location.length();
1616 } else {
1617 location = FROM_LATIN1(p, end-p).stripWhiteSpace();
1618 p = end+1; /* skip over \n */
1621 // may be continued in next line
1622 while (isspace(*p)) { /* p points to beginning of line */
1623 // skip white space at beginning of line
1624 while (isspace(*p))
1625 p++;
1627 // seek end of line
1628 end = strchr(p, '\n');
1629 if (end == 0)
1630 end = p+strlen(p);
1632 if (strncmp(p, "breakpoint already hit", 22) == 0) {
1633 // extract the hit count
1634 p += 22;
1635 hits = strtol(p, &dummy, 10);
1636 TRACE(QString().sprintf("hit count %d", hits));
1637 } else if (strncmp(p, "stop only if ", 13) == 0) {
1638 // extract condition
1639 p += 13;
1640 condition = FROM_LATIN1(p, end-p).stripWhiteSpace();
1641 TRACE("condition: "+condition);
1642 } else if (strncmp(p, "ignore next ", 12) == 0) {
1643 // extract ignore count
1644 p += 12;
1645 ignoreCount = strtol(p, &dummy, 10);
1646 TRACE(QString().sprintf("ignore count %d", ignoreCount));
1647 } else {
1648 // indeed a continuation
1649 location += " " + FROM_LATIN1(p, end-p).stripWhiteSpace();
1651 p = end;
1652 if (*p != '\0')
1653 p++; /* skip '\n' */
1655 Breakpoint* bp = new Breakpoint;
1656 bp->id = bpNum;
1657 bp->type = bpType;
1658 bp->temporary = disp == 'd';
1659 bp->enabled = enable == 'y';
1660 bp->location = location;
1661 bp->address = address;
1662 bp->hitCount = hits;
1663 bp->ignoreCount = ignoreCount;
1664 bp->condition = condition;
1665 brks.append(bp);
1667 return true;
1670 bool GdbDriver::parseThreadList(const char* output, QList<ThreadInfo>& threads)
1672 if (strcmp(output, "\n") == 0 || strncmp(output, "No stack.", 9) == 0) {
1673 // no threads
1674 return true;
1677 int id;
1678 QString systag;
1679 QString func, file;
1680 int lineNo;
1681 DbgAddr address;
1683 const char* p = output;
1684 while (*p != '\0') {
1685 // seach look for thread id, watching out for the focus indicator
1686 bool hasFocus = false;
1687 while (isspace(*p)) /* may be \n from prev line: see "No stack" below */
1688 p++;
1689 if (*p == '*') {
1690 hasFocus = true;
1691 p++;
1692 // there follows only whitespace
1694 char* end;
1695 id = strtol(p, &end, 10);
1696 if (p == end) {
1697 // syntax error: no number found; bail out
1698 return true;
1700 p = end;
1702 // skip space
1703 while (isspace(*p))
1704 p++;
1707 * Now follows the thread's SYSTAG. It is terminated by two blanks.
1709 end = strstr(p, " ");
1710 if (end == 0) {
1711 // syntax error; bail out
1712 return true;
1714 systag = FROM_LATIN1(p, end-p);
1715 p = end+2;
1718 * Now follows a standard stack frame. Sometimes, however, gdb
1719 * catches a thread at an instant where it doesn't have a stack.
1721 if (strncmp(p, "[No stack.]", 11) != 0) {
1722 ::parseFrameInfo(p, func, file, lineNo, address);
1723 } else {
1724 func = "[No stack]";
1725 file = QString();
1726 lineNo = -1;
1727 address = QString();
1728 p += 11; /* \n is skipped above */
1731 ThreadInfo* thr = new ThreadInfo;
1732 thr->id = id;
1733 thr->threadName = systag;
1734 thr->hasFocus = hasFocus;
1735 thr->function = func;
1736 thr->fileName = file;
1737 thr->lineNo = lineNo;
1738 thr->address = address;
1739 threads.append(thr);
1741 return true;
1744 bool GdbDriver::parseBreakpoint(const char* output, int& id,
1745 QString& file, int& lineNo)
1747 const char* o = output;
1748 // skip lines of that begin with "(Cannot find"
1749 while (strncmp(o, "(Cannot find", 12) == 0) {
1750 o = strchr(o, '\n');
1751 if (o == 0)
1752 return false;
1753 o++; /* skip newline */
1756 if (strncmp(o, "Breakpoint ", 11) != 0)
1757 return false;
1759 // breakpoint id
1760 output += 11; /* skip "Breakpoint " */
1761 char* p;
1762 int num = strtoul(output, &p, 10);
1763 if (p == o)
1764 return false;
1766 // file name
1767 char* fileStart = strstr(p, "file ");
1768 if (fileStart == 0)
1769 return false;
1770 fileStart += 5;
1772 // line number
1773 char* numStart = strstr(fileStart, ", line ");
1774 QString fileName = FROM_LATIN1(fileStart, numStart-fileStart);
1775 numStart += 7;
1776 int line = strtoul(numStart, &p, 10);
1777 if (numStart == p)
1778 return false;
1780 id = num;
1781 file = fileName;
1782 lineNo = line-1; /* zero-based! */
1783 return true;
1786 void GdbDriver::parseLocals(const char* output, QList<VarTree>& newVars)
1788 // check for possible error conditions
1789 if (strncmp(output, "No symbol table", 15) == 0)
1791 return;
1794 while (*output != '\0') {
1795 while (isspace(*output))
1796 output++;
1797 if (*output == '\0')
1798 break;
1799 // skip occurrences of "No locals" and "No args"
1800 if (strncmp(output, "No locals", 9) == 0 ||
1801 strncmp(output, "No arguments", 12) == 0)
1803 output = strchr(output, '\n');
1804 if (output == 0) {
1805 break;
1807 continue;
1810 VarTree* variable = parseVar(output);
1811 if (variable == 0) {
1812 break;
1814 // do not add duplicates
1815 for (VarTree* o = newVars.first(); o != 0; o = newVars.next()) {
1816 if (o->getText() == variable->getText()) {
1817 delete variable;
1818 goto skipDuplicate;
1821 newVars.append(variable);
1822 skipDuplicate:;
1826 bool GdbDriver::parsePrintExpr(const char* output, bool wantErrorValue, VarTree*& var)
1828 // check for error conditions
1829 if (parseErrorMessage(output, var, wantErrorValue))
1831 return false;
1832 } else {
1833 // parse the variable
1834 var = parseVar(output);
1835 return true;
1839 bool GdbDriver::parseChangeWD(const char* output, QString& message)
1841 bool isGood = false;
1842 message = QString(output).simplifyWhiteSpace();
1843 if (message.isEmpty()) {
1844 message = i18n("New working directory: ") + m_programWD;
1845 isGood = true;
1847 return isGood;
1850 bool GdbDriver::parseChangeExecutable(const char* output, QString& message)
1852 message = output;
1854 m_haveCoreFile = false;
1857 * The command is successful if there is no output or the single
1858 * message (no debugging symbols found)...
1860 return
1861 output[0] == '\0' ||
1862 strcmp(output, "(no debugging symbols found)...") == 0;
1865 bool GdbDriver::parseCoreFile(const char* output)
1867 // if command succeeded, gdb emits a line starting with "#0 "
1868 m_haveCoreFile = strstr(output, "\n#0 ") != 0;
1869 return m_haveCoreFile;
1872 uint GdbDriver::parseProgramStopped(const char* output, QString& message)
1874 // optionally: "program changed, rereading symbols",
1875 // followed by:
1876 // "Program exited normally"
1877 // "Program terminated with wignal SIGSEGV"
1878 // "Program received signal SIGINT" or other signal
1879 // "Breakpoint..."
1881 // go through the output, line by line, checking what we have
1882 const char* start = output - 1;
1883 uint flags = SFprogramActive;
1884 message = QString();
1885 do {
1886 start++; /* skip '\n' */
1888 if (strncmp(start, "Program ", 8) == 0 ||
1889 strncmp(start, "ptrace: ", 8) == 0) {
1891 * When we receive a signal, the program remains active.
1893 * Special: If we "stopped" in a corefile, the string "Program
1894 * terminated with signal"... is displayed. (Normally, we see
1895 * "Program received signal"... when a signal happens.)
1897 if (strncmp(start, "Program exited", 14) == 0 ||
1898 (strncmp(start, "Program terminated", 18) == 0 && !m_haveCoreFile) ||
1899 strncmp(start, "ptrace: ", 8) == 0)
1901 flags &= ~SFprogramActive;
1904 // set message
1905 const char* endOfMessage = strchr(start, '\n');
1906 if (endOfMessage == 0)
1907 endOfMessage = start + strlen(start);
1908 message = FROM_LATIN1(start, endOfMessage-start);
1909 } else if (strncmp(start, "Breakpoint ", 11) == 0) {
1911 * We stopped at a (permanent) breakpoint (gdb doesn't tell us
1912 * that it stopped at a temporary breakpoint).
1914 flags |= SFrefreshBreak;
1915 } else if (strstr(start, "re-reading symbols.") != 0) {
1916 flags |= SFrefreshSource;
1919 // next line, please
1920 start = strchr(start, '\n');
1921 } while (start != 0);
1924 * Gdb only notices when new threads have appeared, but not when a
1925 * thread finishes. So we always have to assume that the list of
1926 * threads has changed.
1928 flags |= SFrefreshThreads;
1930 return flags;
1933 void GdbDriver::parseSharedLibs(const char* output, QStrList& shlibs)
1935 if (strncmp(output, "No shared libraries loaded", 26) == 0)
1936 return;
1938 // parse the table of shared libraries
1940 // strip off head line
1941 output = strchr(output, '\n');
1942 if (output == 0)
1943 return;
1944 output++; /* skip '\n' */
1945 QString shlibName;
1946 while (*output != '\0') {
1947 // format of a line is
1948 // 0x404c5000 0x40580d90 Yes /lib/libc.so.5
1949 // 3 blocks of non-space followed by space
1950 for (int i = 0; *output != '\0' && i < 3; i++) {
1951 while (*output != '\0' && !isspace(*output)) { /* non-space */
1952 output++;
1954 while (isspace(*output)) { /* space */
1955 output++;
1958 if (*output == '\0')
1959 return;
1960 const char* start = output;
1961 output = strchr(output, '\n');
1962 if (output == 0)
1963 output = start + strlen(start);
1964 shlibName = FROM_LATIN1(start, output-start);
1965 if (*output != '\0')
1966 output++;
1967 shlibs.append(shlibName);
1968 TRACE("found shared lib " + shlibName);
1972 bool GdbDriver::parseFindType(const char* output, QString& type)
1974 if (strncmp(output, "type = ", 7) != 0)
1975 return false;
1978 * Everything else is the type. We strip off all white-space from the
1979 * type.
1981 output += 7;
1982 type = output;
1983 type.replace(QRegExp("\\s+"), "");
1984 return true;
1987 void GdbDriver::parseRegisters(const char* output, QList<RegisterInfo>& regs)
1989 if (strncmp(output, "The program has no registers now", 32) == 0) {
1990 return;
1993 QString regName;
1994 QString value;
1996 // parse register values
1997 while (*output != '\0')
1999 // skip space at the start of the line
2000 while (isspace(*output))
2001 output++;
2003 // register name
2004 const char* start = output;
2005 while (*output != '\0' && !isspace(*output))
2006 output++;
2007 if (*output == '\0')
2008 break;
2009 regName = FROM_LATIN1(start, output-start);
2011 // skip space
2012 while (isspace(*output))
2013 output++;
2015 RegisterInfo* reg = new RegisterInfo;
2016 reg->regName = regName;
2019 * If we find a brace now, this is a vector register. We look for
2020 * the closing brace and treat the result as cooked value.
2022 if (*output == '{')
2024 start = output;
2025 skipNested(output, '{', '}');
2026 value = FROM_LATIN1(start, output-start).simplifyWhiteSpace();
2027 // skip space, but not the end of line
2028 while (isspace(*output) && *output != '\n')
2029 output++;
2030 // get rid of the braces at the begining and the end
2031 value.remove(0, 1);
2032 if (value[value.length()-1] == '}') {
2033 value = value.left(value.length()-1);
2035 // gdb 5.3 doesn't print a separate set of raw values
2036 if (*output == '{') {
2037 // another set of vector follows
2038 // what we have so far is the raw value
2039 reg->rawValue = value;
2041 start = output;
2042 skipNested(output, '{', '}');
2043 value = FROM_LATIN1(start, output-start).simplifyWhiteSpace();
2044 // skip to the end of line
2045 while (*output != '\0' && *output != '\n')
2046 output++;
2047 // get rid of the braces at the begining and the end
2048 value.remove(0, 1);
2049 if (value[value.length()-1] == '}') {
2050 value = value.left(value.length()-1);
2053 reg->cookedValue = value;
2055 else
2057 // the rest of the line is the register value
2058 start = output;
2059 output = strchr(output,'\n');
2060 if (output == 0)
2061 output = start + strlen(start);
2062 value = FROM_LATIN1(start, output-start).simplifyWhiteSpace();
2065 * We split the raw from the cooked values. For this purpose,
2066 * we split off the first token (separated by whitespace). It
2067 * is the raw value. The remainder of the line is the cooked
2068 * value.
2070 int pos = value.find(' ');
2071 if (pos < 0) {
2072 reg->rawValue = value;
2073 reg->cookedValue = QString();
2074 } else {
2075 reg->rawValue = value.left(pos);
2076 reg->cookedValue = value.mid(pos+1);
2078 * Some modern gdbs explicitly say: "0.1234 (raw 0x3e4567...)".
2079 * Here the raw value is actually in the second part.
2081 if (reg->cookedValue.left(5) == "(raw ") {
2082 QString raw = reg->cookedValue.right(reg->cookedValue.length()-5);
2083 if (raw[raw.length()-1] == ')') /* remove closing bracket */
2084 raw = raw.left(raw.length()-1);
2085 reg->cookedValue = reg->rawValue;
2086 reg->rawValue = raw;
2090 if (*output != '\0')
2091 output++; /* skip '\n' */
2093 regs.append(reg);
2097 bool GdbDriver::parseInfoLine(const char* output, QString& addrFrom, QString& addrTo)
2099 // "is at address" or "starts at address"
2100 const char* start = strstr(output, "s at address ");
2101 if (start == 0)
2102 return false;
2104 start += 13;
2105 const char* p = start;
2106 while (*p != '\0' && !isspace(*p))
2107 p++;
2108 addrFrom = FROM_LATIN1(start, p-start);
2110 start = strstr(p, "and ends at ");
2111 if (start == 0) {
2112 addrTo = addrFrom;
2113 return true;
2116 start += 12;
2117 p = start;
2118 while (*p != '\0' && !isspace(*p))
2119 p++;
2120 addrTo = FROM_LATIN1(start, p-start);
2122 return true;
2125 void GdbDriver::parseDisassemble(const char* output, QList<DisassembledCode>& code)
2127 code.clear();
2129 if (strncmp(output, "Dump of assembler", 17) != 0) {
2130 // error message?
2131 DisassembledCode c;
2132 c.code = output;
2133 code.append(new DisassembledCode(c));
2134 return;
2137 // remove first line
2138 const char* p = strchr(output, '\n');
2139 if (p == 0)
2140 return; /* not a regular output */
2142 p++;
2144 // remove last line
2145 const char* end = strstr(output, "End of assembler");
2146 if (end == 0)
2147 end = p + strlen(p);
2149 DbgAddr address;
2151 // remove function offsets from the lines
2152 while (p != end)
2154 const char* start = p;
2155 // address
2156 while (p != end && !isspace(*p))
2157 p++;
2158 address = FROM_LATIN1(start, p-start);
2160 // function name (enclosed in '<>', followed by ':')
2161 while (p != end && *p != '<')
2162 p++;
2163 if (*p == '<')
2164 skipNested(p, '<', '>');
2165 if (*p == ':')
2166 p++;
2168 // space until code
2169 while (p != end && isspace(*p))
2170 p++;
2172 // code until end of line
2173 start = p;
2174 while (p != end && *p != '\n')
2175 p++;
2176 if (p != end) /* include '\n' */
2177 p++;
2179 DisassembledCode* c = new DisassembledCode;
2180 c->address = address;
2181 c->code = FROM_LATIN1(start, p-start);
2182 code.append(c);
2186 QString GdbDriver::parseMemoryDump(const char* output, QList<MemoryDump>& memdump)
2188 if (isErrorExpr(output)) {
2189 // error; strip space
2190 QString msg = output;
2191 return msg.stripWhiteSpace();
2194 const char* p = output; /* save typing */
2195 DbgAddr addr;
2196 QString dump;
2198 // the address
2199 while (*p != 0) {
2200 const char* start = p;
2201 while (*p != '\0' && *p != ':' && !isspace(*p))
2202 p++;
2203 addr = FROM_LATIN1(start, p-start);
2204 if (*p != ':') {
2205 // parse function offset
2206 while (isspace(*p))
2207 p++;
2208 start = p;
2209 while (*p != '\0' && !(*p == ':' && isspace(p[1])))
2210 p++;
2211 addr.fnoffs = FROM_LATIN1(start, p-start);
2213 if (*p == ':')
2214 p++;
2215 // skip space; this may skip a new-line char!
2216 while (isspace(*p))
2217 p++;
2218 // everything to the end of the line is the memory dump
2219 const char* end = strchr(p, '\n');
2220 if (end != 0) {
2221 dump = FROM_LATIN1(p, end-p);
2222 p = end+1;
2223 } else {
2224 dump = FROM_LATIN1(p, strlen(p));
2225 p += strlen(p);
2227 MemoryDump* md = new MemoryDump;
2228 md->address = addr;
2229 md->dump = dump;
2230 memdump.append(md);
2233 return QString();
2237 #include "gdbdriver.moc"