Implemented individual register format settings. Kudos to Daniel Kristjansson.
[kdbg.git] / kdbg / gdbdriver.cpp
blobf9ee182836b382f4d5a708b8b1ce94a15cc1d7ea
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;
914 * Find the end of line that is not inside braces
916 static void findEnd(const char*& s)
918 const char* p = s;
919 while (*p && *p!='\n') {
920 while (*p && *p!='\n' && *p!='{')
921 p++;
922 if (*p=='{') {
923 p++;
924 skipNested(p, '{', '}'); p--;
927 s = p;
930 static bool isNumberish(const char ch)
932 return (ch>='0' && ch<='9') || ch=='.' || ch=='x';
935 void skipString(const char*& p)
937 moreStrings:
938 // opening quote
939 char quote = *p++;
940 while (*p != quote) {
941 if (*p == '\\') {
942 // skip escaped character
943 // no special treatment for octal values necessary
944 p++;
946 // simply return if no more characters
947 if (*p == '\0')
948 return;
949 p++;
951 // closing quote
952 p++;
954 * Strings can consist of several parts, some of which contain repeated
955 * characters.
957 if (quote == '\'') {
958 // look ahaead for <repeats 123 times>
959 const char* q = p+1;
960 while (isspace(*q))
961 q++;
962 if (strncmp(q, "<repeats ", 9) == 0) {
963 p = q+9;
964 while (*p != '\0' && *p != '>')
965 p++;
966 if (*p != '\0') {
967 p++; /* skip the '>' */
971 // is the string continued?
972 if (*p == ',') {
973 // look ahead for another quote
974 const char* q = p+1;
975 while (isspace(*q))
976 q++;
977 if (*q == '"' || *q == '\'') {
978 // yes!
979 p = q;
980 goto moreStrings;
983 /* very long strings are followed by `...' */
984 if (*p == '.' && p[1] == '.' && p[2] == '.') {
985 p += 3;
989 static void skipNestedWithString(const char*& s, char opening, char closing)
991 const char* p = s;
993 // parse a nested expression
994 int nest = 1;
995 p++;
997 * Search for next matching `closing' char, skipping nested pairs of
998 * `opening' and `closing' as well as strings.
1000 while (*p && nest > 0) {
1001 if (*p == opening) {
1002 nest++;
1003 } else if (*p == closing) {
1004 nest--;
1005 } else if (*p == '\'' || *p == '\"') {
1006 skipString(p);
1007 continue;
1009 p++;
1011 if (nest > 0) {
1012 TRACE(QString().sprintf("parse error: mismatching %c%c at %-20.20s", opening, closing, s));
1014 s = p;
1017 inline void skipName(const char*& p)
1019 // allow : (for enumeration values) and $ and . (for _vtbl.)
1020 while (isalnum(*p) || *p == '_' || *p == ':' || *p == '$' || *p == '.')
1021 p++;
1024 static bool parseName(const char*& s, QString& name, VarTree::NameKind& kind)
1026 kind = VarTree::NKplain;
1028 const char* p = s;
1029 // examples of names:
1030 // name
1031 // <Object>
1032 // <string<a,b<c>,7> >
1034 if (*p == '<') {
1035 skipNested(p, '<', '>');
1036 name = FROM_LATIN1(s, p - s);
1037 kind = VarTree::NKtype;
1039 else
1041 // name, which might be "static"; allow dot for "_vtbl."
1042 skipName(p);
1043 if (p == s) {
1044 TRACE(QString().sprintf("parse error: not a name %-20.20s", s));
1045 return false;
1047 int len = p - s;
1048 if (len == 6 && strncmp(s, "static", 6) == 0) {
1049 kind = VarTree::NKstatic;
1051 // its a static variable, name comes now
1052 while (isspace(*p))
1053 p++;
1054 s = p;
1055 skipName(p);
1056 if (p == s) {
1057 TRACE(QString().sprintf("parse error: not a name after static %-20.20s", s));
1058 return false;
1060 len = p - s;
1062 name = FROM_LATIN1(s, len);
1064 // return the new position
1065 s = p;
1066 return true;
1069 static bool parseValue(const char*& s, VarTree* variable)
1071 variable->m_value = "";
1073 repeat:
1074 if (*s == '{') {
1075 s++;
1076 if (!parseNested(s, variable)) {
1077 return false;
1079 // must be the closing brace
1080 if (*s != '}') {
1081 TRACE("parse error: missing } of " + variable->getText());
1082 return false;
1084 s++;
1085 // final white space
1086 while (isspace(*s))
1087 s++;
1088 } else {
1089 // examples of leaf values (cannot be the empty string):
1090 // 123
1091 // -123
1092 // 23.575e+37
1093 // 0x32a45
1094 // @0x012ab4
1095 // (DwContentType&) @0x8123456: {...}
1096 // 0x32a45 "text"
1097 // 10 '\n'
1098 // <optimized out>
1099 // 0x823abc <Array<int> virtual table>
1100 // (void (*)()) 0x8048480 <f(E *, char)>
1101 // (E *) 0xbffff450
1102 // red
1103 // &parseP (HTMLClueV *, char *)
1105 const char*p = s;
1107 // check for type
1108 QString type;
1109 if (*p == '(') {
1110 skipNested(p, '(', ')');
1112 while (isspace(*p))
1113 p++;
1114 variable->m_value = FROM_LATIN1(s, p - s);
1117 bool reference = false;
1118 if (*p == '@') {
1119 // skip reference marker
1120 p++;
1121 reference = true;
1123 const char* start = p;
1124 if (*p == '-')
1125 p++;
1127 // some values consist of more than one token
1128 bool checkMultiPart = false;
1130 if (p[0] == '0' && p[1] == 'x') {
1131 // parse hex number
1132 p += 2;
1133 while (isxdigit(*p))
1134 p++;
1137 * Assume this is a pointer, but only if it's not a reference, since
1138 * references can't be expanded.
1140 if (!reference) {
1141 variable->m_varKind = VarTree::VKpointer;
1142 } else {
1144 * References are followed by a colon, in which case we'll
1145 * find the value following the reference address.
1147 if (*p == ':') {
1148 p++;
1149 } else {
1150 // Paranoia. (Can this happen, i.e. reference not followed by ':'?)
1151 reference = false;
1154 checkMultiPart = true;
1155 } else if (isdigit(*p)) {
1156 // parse decimal number, possibly a float
1157 while (isdigit(*p))
1158 p++;
1159 if (*p == '.') { /* TODO: obey i18n? */
1160 // fractional part
1161 p++;
1162 while (isdigit(*p))
1163 p++;
1165 if (*p == 'e' || *p == 'E') {
1166 p++;
1167 // exponent
1168 if (*p == '-' || *p == '+')
1169 p++;
1170 while (isdigit(*p))
1171 p++;
1174 // for char variables there is the char, eg. 10 '\n'
1175 checkMultiPart = true;
1176 } else if (*p == '<') {
1177 // e.g. <optimized out>
1178 skipNested(p, '<', '>');
1179 } else if (*p == '"' || *p == '\'') {
1180 // character may have multipart: '\000' <repeats 11 times>
1181 checkMultiPart = *p == '\'';
1182 // found a string
1183 skipString(p);
1184 } else if (*p == '&') {
1185 // function pointer
1186 p++;
1187 skipName(p);
1188 while (isspace(*p)) {
1189 p++;
1191 if (*p == '(') {
1192 skipNested(p, '(', ')');
1194 } else {
1195 // must be an enumeration value
1196 skipName(p);
1198 variable->m_value += FROM_LATIN1(start, p - start);
1200 if (checkMultiPart) {
1201 // white space
1202 while (isspace(*p))
1203 p++;
1204 // may be followed by a string or <...>
1205 start = p;
1207 if (*p == '"' || *p == '\'') {
1208 skipString(p);
1209 } else if (*p == '<') {
1210 // if this value is part of an array, it might be followed
1211 // by <repeats 15 times>, which we don't skip here
1212 if (strncmp(p, "<repeats ", 9) != 0)
1213 skipNested(p, '<', '>');
1215 if (p != start) {
1216 // there is always a blank before the string,
1217 // which we will include in the final string value
1218 variable->m_value += FROM_LATIN1(start-1, (p - start)+1);
1219 // if this was a pointer, reset that flag since we
1220 // now got the value
1221 variable->m_varKind = VarTree::VKsimple;
1225 if (variable->m_value.length() == 0) {
1226 TRACE("parse error: no value for " + variable->getText());
1227 return false;
1230 // final white space
1231 while (isspace(*p))
1232 p++;
1233 s = p;
1236 * If this was a reference, the value follows. It might even be a
1237 * composite variable!
1239 if (reference) {
1240 goto repeat;
1243 if (variable->m_varKind == VarTree::VKpointer) {
1244 variable->setDelayedExpanding(true);
1248 return true;
1251 static bool parseNested(const char*& s, VarTree* variable)
1253 // could be a structure or an array
1254 while (isspace(*s))
1255 s++;
1257 const char* p = s;
1258 bool isStruct = false;
1260 * If there is a name followed by an = or an < -- which starts a type
1261 * name -- or "static", it is a structure
1263 if (*p == '<' || *p == '}') {
1264 isStruct = true;
1265 } else if (strncmp(p, "static ", 7) == 0) {
1266 isStruct = true;
1267 } else if (isalpha(*p) || *p == '_' || *p == '$') {
1268 // look ahead for a comma after the name
1269 skipName(p);
1270 while (isspace(*p))
1271 p++;
1272 if (*p == '=') {
1273 isStruct = true;
1275 p = s; /* rescan the name */
1277 if (isStruct) {
1278 if (!parseVarSeq(p, variable)) {
1279 return false;
1281 variable->m_varKind = VarTree::VKstruct;
1282 } else {
1283 if (!parseValueSeq(p, variable)) {
1284 return false;
1286 variable->m_varKind = VarTree::VKarray;
1288 s = p;
1289 return true;
1292 static bool parseVarSeq(const char*& s, VarTree* variable)
1294 // parse a comma-separated sequence of variables
1295 VarTree* var = variable; /* var != 0 to indicate success if empty seq */
1296 for (;;) {
1297 if (*s == '}')
1298 break;
1299 if (strncmp(s, "<No data fields>}", 17) == 0)
1301 // no member variables, so break out immediately
1302 s += 16; /* go to the closing brace */
1303 break;
1305 var = parseVar(s);
1306 if (var == 0)
1307 break; /* syntax error */
1308 variable->appendChild(var);
1309 if (*s != ',')
1310 break;
1311 // skip the comma and whitespace
1312 s++;
1313 while (isspace(*s))
1314 s++;
1316 return var != 0;
1319 static bool parseValueSeq(const char*& s, VarTree* variable)
1321 // parse a comma-separated sequence of variables
1322 int index = 0;
1323 bool good;
1324 for (;;) {
1325 QString name;
1326 name.sprintf("[%d]", index);
1327 VarTree* var = new VarTree(name, VarTree::NKplain);
1328 var->setDeleteChildren(true);
1329 good = parseValue(s, var);
1330 if (!good) {
1331 delete var;
1332 return false;
1334 // a value may be followed by "<repeats 45 times>"
1335 if (strncmp(s, "<repeats ", 9) == 0) {
1336 s += 9;
1337 char* end;
1338 int l = strtol(s, &end, 10);
1339 if (end == s || strncmp(end, " times>", 7) != 0) {
1340 // should not happen
1341 delete var;
1342 return false;
1344 TRACE(QString().sprintf("found <repeats %d times> in array", l));
1345 // replace name and advance index
1346 name.sprintf("[%d .. %d]", index, index+l-1);
1347 var->setText(name);
1348 index += l;
1349 // skip " times>" and space
1350 s = end+7;
1351 // possible final space
1352 while (isspace(*s))
1353 s++;
1354 } else {
1355 index++;
1357 variable->appendChild(var);
1358 if (*s != ',') {
1359 break;
1361 // skip the comma and whitespace
1362 s++;
1363 while (isspace(*s))
1364 s++;
1365 // sometimes there is a closing brace after a comma
1366 // if (*s == '}')
1367 // break;
1369 return true;
1373 * Parses a stack frame.
1375 static void parseFrameInfo(const char*& s, QString& func,
1376 QString& file, int& lineNo, DbgAddr& address)
1378 const char* p = s;
1380 // next may be a hexadecimal address
1381 if (*p == '0') {
1382 const char* start = p;
1383 p++;
1384 if (*p == 'x')
1385 p++;
1386 while (isxdigit(*p))
1387 p++;
1388 address = FROM_LATIN1(start, p-start);
1389 if (strncmp(p, " in ", 4) == 0)
1390 p += 4;
1391 } else {
1392 address = DbgAddr();
1394 const char* start = p;
1395 // check for special signal handler frame
1396 if (strncmp(p, "<signal handler called>", 23) == 0) {
1397 func = FROM_LATIN1(start, 23);
1398 file = QString();
1399 lineNo = -1;
1400 s = p+23;
1401 if (*s == '\n')
1402 s++;
1403 return;
1405 // search opening parenthesis
1406 while (*p != '\0' && *p != '(')
1407 p++;
1408 if (*p == '\0') {
1409 func = start;
1410 file = QString();
1411 lineNo = -1;
1412 s = p;
1413 return;
1416 * Skip parameters. But notice that for complicated conversion
1417 * functions (eg. "operator int(**)()()", ie. convert to pointer to
1418 * pointer to function) as well as operator()(...) we have to skip
1419 * additional pairs of parentheses. Furthermore, recent gdbs write the
1420 * demangled name followed by the arguments in a pair of parentheses,
1421 * where the demangled name can end in "const".
1423 do {
1424 skipNestedWithString(p, '(', ')');
1425 while (isspace(*p))
1426 p++;
1427 // skip "const"
1428 if (strncmp(p, "const", 5) == 0) {
1429 p += 5;
1430 while (isspace(*p))
1431 p++;
1433 } while (*p == '(');
1435 // check for file position
1436 if (strncmp(p, "at ", 3) == 0) {
1437 p += 3;
1438 const char* fileStart = p;
1439 // go for the end of the line
1440 while (*p != '\0' && *p != '\n')
1441 p++;
1442 // search back for colon
1443 const char* colon = p;
1444 do {
1445 --colon;
1446 } while (*colon != ':');
1447 file = FROM_LATIN1(fileStart, colon-fileStart);
1448 lineNo = atoi(colon+1)-1;
1449 // skip new-line
1450 if (*p != '\0')
1451 p++;
1452 } else {
1453 // check for "from shared lib"
1454 if (strncmp(p, "from ", 5) == 0) {
1455 p += 5;
1456 // go for the end of the line
1457 while (*p != '\0' && *p != '\n')
1458 p++;
1459 // skip new-line
1460 if (*p != '\0')
1461 p++;
1463 file = "";
1464 lineNo = -1;
1466 // construct the function name (including file info)
1467 if (*p == '\0') {
1468 func = start;
1469 } else {
1470 func = FROM_LATIN1(start, p-start-1); /* don't include \n */
1472 s = p;
1475 * Replace \n (and whitespace around it) in func by a blank. We cannot
1476 * use QString::simplifyWhiteSpace() for this because this would also
1477 * simplify space that belongs to a string arguments that gdb sometimes
1478 * prints in the argument lists of the function.
1480 ASSERT(!isspace(func[0].latin1())); /* there must be non-white before first \n */
1481 int nl = 0;
1482 while ((nl = func.find('\n', nl)) >= 0) {
1483 // search back to the beginning of the whitespace
1484 int startWhite = nl;
1485 do {
1486 --startWhite;
1487 } while (isspace(func[startWhite].latin1()));
1488 startWhite++;
1489 // search forward to the end of the whitespace
1490 do {
1491 nl++;
1492 } while (isspace(func[nl].latin1()));
1493 // replace
1494 func.replace(startWhite, nl-startWhite, " ");
1495 /* continue searching for more \n's at this place: */
1496 nl = startWhite+1;
1502 * Parses a stack frame including its frame number
1504 static bool parseFrame(const char*& s, int& frameNo, QString& func,
1505 QString& file, int& lineNo, DbgAddr& address)
1507 // Example:
1508 // #1 0x8048881 in Dl::Dl (this=0xbffff418, r=3214) at testfile.cpp:72
1509 // Breakpoint 3, Cl::f(int) const (this=0xbffff3c0, x=17) at testfile.cpp:155
1511 // must start with a hash mark followed by number
1512 // or with "Breakpoint " followed by number and comma
1513 if (s[0] == '#') {
1514 if (!isdigit(s[1]))
1515 return false;
1516 s++; /* skip the hash mark */
1517 } else if (strncmp(s, "Breakpoint ", 11) == 0) {
1518 if (!isdigit(s[11]))
1519 return false;
1520 s += 11; /* skip "Breakpoint" */
1521 } else
1522 return false;
1524 // frame number
1525 frameNo = atoi(s);
1526 while (isdigit(*s))
1527 s++;
1528 // space and comma
1529 while (isspace(*s) || *s == ',')
1530 s++;
1531 parseFrameInfo(s, func, file, lineNo, address);
1532 return true;
1535 void GdbDriver::parseBackTrace(const char* output, QList<StackFrame>& stack)
1537 QString func, file;
1538 int lineNo, frameNo;
1539 DbgAddr address;
1541 while (::parseFrame(output, frameNo, func, file, lineNo, address)) {
1542 StackFrame* frm = new StackFrame;
1543 frm->frameNo = frameNo;
1544 frm->fileName = file;
1545 frm->lineNo = lineNo;
1546 frm->address = address;
1547 frm->var = new VarTree(func, VarTree::NKplain);
1548 stack.append(frm);
1552 bool GdbDriver::parseFrameChange(const char* output, int& frameNo,
1553 QString& file, int& lineNo, DbgAddr& address)
1555 QString func;
1556 return ::parseFrame(output, frameNo, func, file, lineNo, address);
1560 bool GdbDriver::parseBreakList(const char* output, QList<Breakpoint>& brks)
1562 // skip first line, which is the headline
1563 const char* p = strchr(output, '\n');
1564 if (p == 0)
1565 return false;
1566 p++;
1567 if (*p == '\0')
1568 return false;
1570 // split up a line
1571 QString location;
1572 QString address;
1573 int hits = 0;
1574 uint ignoreCount = 0;
1575 QString condition;
1576 const char* end;
1577 char* dummy;
1578 while (*p != '\0') {
1579 // get Num
1580 long bpNum = strtol(p, &dummy, 10); /* don't care about overflows */
1581 p = dummy;
1582 // get Type
1583 while (isspace(*p))
1584 p++;
1585 Breakpoint::Type bpType = Breakpoint::breakpoint;
1586 if (strncmp(p, "breakpoint", 10) == 0) {
1587 p += 10;
1588 } else if (strncmp(p, "hw watchpoint", 13) == 0) {
1589 bpType = Breakpoint::watchpoint;
1590 p += 13;
1591 } else if (strncmp(p, "watchpoint", 10) == 0) {
1592 bpType = Breakpoint::watchpoint;
1593 p += 10;
1595 while (isspace(*p))
1596 p++;
1597 if (*p == '\0')
1598 break;
1599 // get Disp
1600 char disp = *p++;
1601 while (*p != '\0' && !isspace(*p)) /* "keep" or "del" */
1602 p++;
1603 while (isspace(*p))
1604 p++;
1605 if (*p == '\0')
1606 break;
1607 // get Enb
1608 char enable = *p++;
1609 while (*p != '\0' && !isspace(*p)) /* "y" or "n" */
1610 p++;
1611 while (isspace(*p))
1612 p++;
1613 if (*p == '\0')
1614 break;
1615 // the address, if present
1616 if (bpType == Breakpoint::breakpoint &&
1617 strncmp(p, "0x", 2) == 0)
1619 const char* start = p;
1620 while (*p != '\0' && !isspace(*p))
1621 p++;
1622 address = FROM_LATIN1(start, p-start);
1623 while (isspace(*p) && *p != '\n')
1624 p++;
1625 if (*p == '\0')
1626 break;
1627 } else {
1628 address = QString();
1630 // remainder is location, hit and ignore count, condition
1631 hits = 0;
1632 ignoreCount = 0;
1633 condition = QString();
1634 end = strchr(p, '\n');
1635 if (end == 0) {
1636 location = p;
1637 p += location.length();
1638 } else {
1639 location = FROM_LATIN1(p, end-p).stripWhiteSpace();
1640 p = end+1; /* skip over \n */
1643 // may be continued in next line
1644 while (isspace(*p)) { /* p points to beginning of line */
1645 // skip white space at beginning of line
1646 while (isspace(*p))
1647 p++;
1649 // seek end of line
1650 end = strchr(p, '\n');
1651 if (end == 0)
1652 end = p+strlen(p);
1654 if (strncmp(p, "breakpoint already hit", 22) == 0) {
1655 // extract the hit count
1656 p += 22;
1657 hits = strtol(p, &dummy, 10);
1658 TRACE(QString().sprintf("hit count %d", hits));
1659 } else if (strncmp(p, "stop only if ", 13) == 0) {
1660 // extract condition
1661 p += 13;
1662 condition = FROM_LATIN1(p, end-p).stripWhiteSpace();
1663 TRACE("condition: "+condition);
1664 } else if (strncmp(p, "ignore next ", 12) == 0) {
1665 // extract ignore count
1666 p += 12;
1667 ignoreCount = strtol(p, &dummy, 10);
1668 TRACE(QString().sprintf("ignore count %d", ignoreCount));
1669 } else {
1670 // indeed a continuation
1671 location += " " + FROM_LATIN1(p, end-p).stripWhiteSpace();
1673 p = end;
1674 if (*p != '\0')
1675 p++; /* skip '\n' */
1677 Breakpoint* bp = new Breakpoint;
1678 bp->id = bpNum;
1679 bp->type = bpType;
1680 bp->temporary = disp == 'd';
1681 bp->enabled = enable == 'y';
1682 bp->location = location;
1683 bp->address = address;
1684 bp->hitCount = hits;
1685 bp->ignoreCount = ignoreCount;
1686 bp->condition = condition;
1687 brks.append(bp);
1689 return true;
1692 bool GdbDriver::parseThreadList(const char* output, QList<ThreadInfo>& threads)
1694 if (strcmp(output, "\n") == 0 || strncmp(output, "No stack.", 9) == 0) {
1695 // no threads
1696 return true;
1699 int id;
1700 QString systag;
1701 QString func, file;
1702 int lineNo;
1703 DbgAddr address;
1705 const char* p = output;
1706 while (*p != '\0') {
1707 // seach look for thread id, watching out for the focus indicator
1708 bool hasFocus = false;
1709 while (isspace(*p)) /* may be \n from prev line: see "No stack" below */
1710 p++;
1711 if (*p == '*') {
1712 hasFocus = true;
1713 p++;
1714 // there follows only whitespace
1716 char* end;
1717 id = strtol(p, &end, 10);
1718 if (p == end) {
1719 // syntax error: no number found; bail out
1720 return true;
1722 p = end;
1724 // skip space
1725 while (isspace(*p))
1726 p++;
1729 * Now follows the thread's SYSTAG. It is terminated by two blanks.
1731 end = strstr(p, " ");
1732 if (end == 0) {
1733 // syntax error; bail out
1734 return true;
1736 systag = FROM_LATIN1(p, end-p);
1737 p = end+2;
1740 * Now follows a standard stack frame. Sometimes, however, gdb
1741 * catches a thread at an instant where it doesn't have a stack.
1743 if (strncmp(p, "[No stack.]", 11) != 0) {
1744 ::parseFrameInfo(p, func, file, lineNo, address);
1745 } else {
1746 func = "[No stack]";
1747 file = QString();
1748 lineNo = -1;
1749 address = QString();
1750 p += 11; /* \n is skipped above */
1753 ThreadInfo* thr = new ThreadInfo;
1754 thr->id = id;
1755 thr->threadName = systag;
1756 thr->hasFocus = hasFocus;
1757 thr->function = func;
1758 thr->fileName = file;
1759 thr->lineNo = lineNo;
1760 thr->address = address;
1761 threads.append(thr);
1763 return true;
1766 bool GdbDriver::parseBreakpoint(const char* output, int& id,
1767 QString& file, int& lineNo)
1769 const char* o = output;
1770 // skip lines of that begin with "(Cannot find"
1771 while (strncmp(o, "(Cannot find", 12) == 0) {
1772 o = strchr(o, '\n');
1773 if (o == 0)
1774 return false;
1775 o++; /* skip newline */
1778 if (strncmp(o, "Breakpoint ", 11) != 0)
1779 return false;
1781 // breakpoint id
1782 output += 11; /* skip "Breakpoint " */
1783 char* p;
1784 int num = strtoul(output, &p, 10);
1785 if (p == o)
1786 return false;
1788 // file name
1789 char* fileStart = strstr(p, "file ");
1790 if (fileStart == 0)
1791 return false;
1792 fileStart += 5;
1794 // line number
1795 char* numStart = strstr(fileStart, ", line ");
1796 QString fileName = FROM_LATIN1(fileStart, numStart-fileStart);
1797 numStart += 7;
1798 int line = strtoul(numStart, &p, 10);
1799 if (numStart == p)
1800 return false;
1802 id = num;
1803 file = fileName;
1804 lineNo = line-1; /* zero-based! */
1805 return true;
1808 void GdbDriver::parseLocals(const char* output, QList<VarTree>& newVars)
1810 // check for possible error conditions
1811 if (strncmp(output, "No symbol table", 15) == 0)
1813 return;
1816 while (*output != '\0') {
1817 while (isspace(*output))
1818 output++;
1819 if (*output == '\0')
1820 break;
1821 // skip occurrences of "No locals" and "No args"
1822 if (strncmp(output, "No locals", 9) == 0 ||
1823 strncmp(output, "No arguments", 12) == 0)
1825 output = strchr(output, '\n');
1826 if (output == 0) {
1827 break;
1829 continue;
1832 VarTree* variable = parseVar(output);
1833 if (variable == 0) {
1834 break;
1836 // do not add duplicates
1837 for (VarTree* o = newVars.first(); o != 0; o = newVars.next()) {
1838 if (o->getText() == variable->getText()) {
1839 delete variable;
1840 goto skipDuplicate;
1843 newVars.append(variable);
1844 skipDuplicate:;
1848 bool GdbDriver::parsePrintExpr(const char* output, bool wantErrorValue, VarTree*& var)
1850 // check for error conditions
1851 if (parseErrorMessage(output, var, wantErrorValue))
1853 return false;
1854 } else {
1855 // parse the variable
1856 var = parseVar(output);
1857 return true;
1861 bool GdbDriver::parseChangeWD(const char* output, QString& message)
1863 bool isGood = false;
1864 message = QString(output).simplifyWhiteSpace();
1865 if (message.isEmpty()) {
1866 message = i18n("New working directory: ") + m_programWD;
1867 isGood = true;
1869 return isGood;
1872 bool GdbDriver::parseChangeExecutable(const char* output, QString& message)
1874 message = output;
1876 m_haveCoreFile = false;
1879 * The command is successful if there is no output or the single
1880 * message (no debugging symbols found)...
1882 return
1883 output[0] == '\0' ||
1884 strcmp(output, "(no debugging symbols found)...") == 0;
1887 bool GdbDriver::parseCoreFile(const char* output)
1889 // if command succeeded, gdb emits a line starting with "#0 "
1890 m_haveCoreFile = strstr(output, "\n#0 ") != 0;
1891 return m_haveCoreFile;
1894 uint GdbDriver::parseProgramStopped(const char* output, QString& message)
1896 // optionally: "program changed, rereading symbols",
1897 // followed by:
1898 // "Program exited normally"
1899 // "Program terminated with wignal SIGSEGV"
1900 // "Program received signal SIGINT" or other signal
1901 // "Breakpoint..."
1903 // go through the output, line by line, checking what we have
1904 const char* start = output - 1;
1905 uint flags = SFprogramActive;
1906 message = QString();
1907 do {
1908 start++; /* skip '\n' */
1910 if (strncmp(start, "Program ", 8) == 0 ||
1911 strncmp(start, "ptrace: ", 8) == 0) {
1913 * When we receive a signal, the program remains active.
1915 * Special: If we "stopped" in a corefile, the string "Program
1916 * terminated with signal"... is displayed. (Normally, we see
1917 * "Program received signal"... when a signal happens.)
1919 if (strncmp(start, "Program exited", 14) == 0 ||
1920 (strncmp(start, "Program terminated", 18) == 0 && !m_haveCoreFile) ||
1921 strncmp(start, "ptrace: ", 8) == 0)
1923 flags &= ~SFprogramActive;
1926 // set message
1927 const char* endOfMessage = strchr(start, '\n');
1928 if (endOfMessage == 0)
1929 endOfMessage = start + strlen(start);
1930 message = FROM_LATIN1(start, endOfMessage-start);
1931 } else if (strncmp(start, "Breakpoint ", 11) == 0) {
1933 * We stopped at a (permanent) breakpoint (gdb doesn't tell us
1934 * that it stopped at a temporary breakpoint).
1936 flags |= SFrefreshBreak;
1937 } else if (strstr(start, "re-reading symbols.") != 0) {
1938 flags |= SFrefreshSource;
1941 // next line, please
1942 start = strchr(start, '\n');
1943 } while (start != 0);
1946 * Gdb only notices when new threads have appeared, but not when a
1947 * thread finishes. So we always have to assume that the list of
1948 * threads has changed.
1950 flags |= SFrefreshThreads;
1952 return flags;
1955 void GdbDriver::parseSharedLibs(const char* output, QStrList& shlibs)
1957 if (strncmp(output, "No shared libraries loaded", 26) == 0)
1958 return;
1960 // parse the table of shared libraries
1962 // strip off head line
1963 output = strchr(output, '\n');
1964 if (output == 0)
1965 return;
1966 output++; /* skip '\n' */
1967 QString shlibName;
1968 while (*output != '\0') {
1969 // format of a line is
1970 // 0x404c5000 0x40580d90 Yes /lib/libc.so.5
1971 // 3 blocks of non-space followed by space
1972 for (int i = 0; *output != '\0' && i < 3; i++) {
1973 while (*output != '\0' && !isspace(*output)) { /* non-space */
1974 output++;
1976 while (isspace(*output)) { /* space */
1977 output++;
1980 if (*output == '\0')
1981 return;
1982 const char* start = output;
1983 output = strchr(output, '\n');
1984 if (output == 0)
1985 output = start + strlen(start);
1986 shlibName = FROM_LATIN1(start, output-start);
1987 if (*output != '\0')
1988 output++;
1989 shlibs.append(shlibName);
1990 TRACE("found shared lib " + shlibName);
1994 bool GdbDriver::parseFindType(const char* output, QString& type)
1996 if (strncmp(output, "type = ", 7) != 0)
1997 return false;
2000 * Everything else is the type. We strip off all white-space from the
2001 * type.
2003 output += 7;
2004 type = output;
2005 type.replace(QRegExp("\\s+"), "");
2006 return true;
2009 void GdbDriver::parseRegisters(const char* output, QList<RegisterInfo>& regs)
2011 if (strncmp(output, "The program has no registers now", 32) == 0) {
2012 return;
2015 QString regName;
2016 QString value;
2018 // parse register values
2019 while (*output != '\0')
2021 // skip space at the start of the line
2022 while (isspace(*output))
2023 output++;
2025 // register name
2026 const char* start = output;
2027 while (*output != '\0' && !isspace(*output))
2028 output++;
2029 if (*output == '\0')
2030 break;
2031 regName = FROM_LATIN1(start, output-start);
2033 // skip space
2034 while (isspace(*output))
2035 output++;
2037 RegisterInfo* reg = new RegisterInfo;
2038 reg->regName = regName;
2041 * If we find a brace now, this is a vector register. We look for
2042 * the closing brace and treat the result as cooked value.
2044 if (*output == '{')
2046 start = output;
2047 skipNested(output, '{', '}');
2048 value = FROM_LATIN1(start, output-start).simplifyWhiteSpace();
2049 // skip space, but not the end of line
2050 while (isspace(*output) && *output != '\n')
2051 output++;
2052 // get rid of the braces at the begining and the end
2053 value.remove(0, 1);
2054 if (value[value.length()-1] == '}') {
2055 value = value.left(value.length()-1);
2057 // gdb 5.3 doesn't print a separate set of raw values
2058 if (*output == '{') {
2059 // another set of vector follows
2060 // what we have so far is the raw value
2061 reg->rawValue = value;
2063 start = output;
2064 skipNested(output, '{', '}');
2065 value = FROM_LATIN1(start, output-start).simplifyWhiteSpace();
2066 } else {
2067 // for gdb 5.3
2068 // find first type that does not have an array, this is the RAW value
2069 const char* end=start;
2070 findEnd(end);
2071 const char* cur=start;
2072 while (cur<end) {
2073 while (*cur != '=' && cur<end)
2074 cur++;
2075 cur++;
2076 while (isspace(*cur) && cur<end)
2077 cur++;
2078 if (isNumberish(*cur)) {
2079 end=cur;
2080 while (*end && (*end!='}') && (*end!=',') && (*end!='\n'))
2081 end++;
2082 QString rawValue = FROM_LATIN1(cur, end-cur).simplifyWhiteSpace();
2083 reg->rawValue = rawValue;
2085 if (rawValue.left(2)=="0x") {
2086 // ok we have a raw value, now get it's type
2087 end=cur-1;
2088 while (isspace(*end) || *end=='=') end--;
2089 end++;
2090 cur=end-1;
2091 while (*cur!='{' && *cur!=' ')
2092 cur--;
2093 cur++;
2094 reg->type=FROM_LATIN1(cur, end-cur);
2097 // end while loop
2098 cur=end;
2101 // skip to the end of line
2102 while (*output != '\0' && *output != '\n')
2103 output++;
2104 // get rid of the braces at the begining and the end
2105 value.remove(0, 1);
2106 if (value[value.length()-1] == '}') {
2107 value = value.left(value.length()-1);
2110 reg->cookedValue = value;
2112 else
2114 // the rest of the line is the register value
2115 start = output;
2116 output = strchr(output,'\n');
2117 if (output == 0)
2118 output = start + strlen(start);
2119 value = FROM_LATIN1(start, output-start).simplifyWhiteSpace();
2122 * We split the raw from the cooked values. For this purpose,
2123 * we split off the first token (separated by whitespace). It
2124 * is the raw value. The remainder of the line is the cooked
2125 * value.
2127 int pos = value.find(' ');
2128 if (pos < 0) {
2129 reg->rawValue = value;
2130 reg->cookedValue = QString();
2131 } else {
2132 reg->rawValue = value.left(pos);
2133 reg->cookedValue = value.mid(pos+1);
2135 * Some modern gdbs explicitly say: "0.1234 (raw 0x3e4567...)".
2136 * Here the raw value is actually in the second part.
2138 if (reg->cookedValue.left(5) == "(raw ") {
2139 QString raw = reg->cookedValue.right(reg->cookedValue.length()-5);
2140 if (raw[raw.length()-1] == ')') /* remove closing bracket */
2141 raw = raw.left(raw.length()-1);
2142 reg->cookedValue = reg->rawValue;
2143 reg->rawValue = raw;
2147 if (*output != '\0')
2148 output++; /* skip '\n' */
2150 regs.append(reg);
2154 bool GdbDriver::parseInfoLine(const char* output, QString& addrFrom, QString& addrTo)
2156 // "is at address" or "starts at address"
2157 const char* start = strstr(output, "s at address ");
2158 if (start == 0)
2159 return false;
2161 start += 13;
2162 const char* p = start;
2163 while (*p != '\0' && !isspace(*p))
2164 p++;
2165 addrFrom = FROM_LATIN1(start, p-start);
2167 start = strstr(p, "and ends at ");
2168 if (start == 0) {
2169 addrTo = addrFrom;
2170 return true;
2173 start += 12;
2174 p = start;
2175 while (*p != '\0' && !isspace(*p))
2176 p++;
2177 addrTo = FROM_LATIN1(start, p-start);
2179 return true;
2182 void GdbDriver::parseDisassemble(const char* output, QList<DisassembledCode>& code)
2184 code.clear();
2186 if (strncmp(output, "Dump of assembler", 17) != 0) {
2187 // error message?
2188 DisassembledCode c;
2189 c.code = output;
2190 code.append(new DisassembledCode(c));
2191 return;
2194 // remove first line
2195 const char* p = strchr(output, '\n');
2196 if (p == 0)
2197 return; /* not a regular output */
2199 p++;
2201 // remove last line
2202 const char* end = strstr(output, "End of assembler");
2203 if (end == 0)
2204 end = p + strlen(p);
2206 DbgAddr address;
2208 // remove function offsets from the lines
2209 while (p != end)
2211 const char* start = p;
2212 // address
2213 while (p != end && !isspace(*p))
2214 p++;
2215 address = FROM_LATIN1(start, p-start);
2217 // function name (enclosed in '<>', followed by ':')
2218 while (p != end && *p != '<')
2219 p++;
2220 if (*p == '<')
2221 skipNested(p, '<', '>');
2222 if (*p == ':')
2223 p++;
2225 // space until code
2226 while (p != end && isspace(*p))
2227 p++;
2229 // code until end of line
2230 start = p;
2231 while (p != end && *p != '\n')
2232 p++;
2233 if (p != end) /* include '\n' */
2234 p++;
2236 DisassembledCode* c = new DisassembledCode;
2237 c->address = address;
2238 c->code = FROM_LATIN1(start, p-start);
2239 code.append(c);
2243 QString GdbDriver::parseMemoryDump(const char* output, QList<MemoryDump>& memdump)
2245 if (isErrorExpr(output)) {
2246 // error; strip space
2247 QString msg = output;
2248 return msg.stripWhiteSpace();
2251 const char* p = output; /* save typing */
2252 DbgAddr addr;
2253 QString dump;
2255 // the address
2256 while (*p != 0) {
2257 const char* start = p;
2258 while (*p != '\0' && *p != ':' && !isspace(*p))
2259 p++;
2260 addr = FROM_LATIN1(start, p-start);
2261 if (*p != ':') {
2262 // parse function offset
2263 while (isspace(*p))
2264 p++;
2265 start = p;
2266 while (*p != '\0' && !(*p == ':' && isspace(p[1])))
2267 p++;
2268 addr.fnoffs = FROM_LATIN1(start, p-start);
2270 if (*p == ':')
2271 p++;
2272 // skip space; this may skip a new-line char!
2273 while (isspace(*p))
2274 p++;
2275 // everything to the end of the line is the memory dump
2276 const char* end = strchr(p, '\n');
2277 if (end != 0) {
2278 dump = FROM_LATIN1(p, end-p);
2279 p = end+1;
2280 } else {
2281 dump = FROM_LATIN1(p, strlen(p));
2282 p += strlen(p);
2284 MemoryDump* md = new MemoryDump;
2285 md->address = addr;
2286 md->dump = dump;
2287 memdump.append(md);
2290 return QString();
2294 #include "gdbdriver.moc"