Swapped the splitting of raw and cooked register values for floating point
[kdbg.git] / kdbg / gdbdriver.cpp
blob02a7a63245d1c7066a6629c66b8936c096191e73
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 { DCprintDeref, "print *(%s)\n", GdbCmdInfo::argString },
111 { DCprintStruct, "print %s\n", GdbCmdInfo::argString },
112 { DCprintQStringStruct, printQStringStructFmt, GdbCmdInfo::argString},
113 { DCframe, "frame %d\n", GdbCmdInfo::argNum },
114 { DCfindType, "whatis %s\n", GdbCmdInfo::argString },
115 { DCinfosharedlib, "info sharedlibrary\n", GdbCmdInfo::argNone },
116 { DCthread, "thread %d\n", GdbCmdInfo::argNum },
117 { DCinfothreads, "info threads\n", GdbCmdInfo::argNone },
118 { DCinfobreak, "info breakpoints\n", GdbCmdInfo::argNone },
119 { DCcondition, "condition %d %s\n", GdbCmdInfo::argNumString},
120 { DCsetpc, "set variable $pc=%s\n", GdbCmdInfo::argString },
121 { DCignore, "ignore %d %d\n", GdbCmdInfo::argNum2},
122 { DCsetvariable, "set variable %s=%s\n", GdbCmdInfo::argString2 },
125 #define NUM_CMDS (int(sizeof(cmds)/sizeof(cmds[0])))
126 #define MAX_FMTLEN 200
128 GdbDriver::GdbDriver() :
129 DebuggerDriver(),
130 m_gdbMajor(4), m_gdbMinor(16)
132 strcpy(m_prompt, PROMPT);
133 m_promptMinLen = PROMPT_LEN;
134 m_promptLastChar = PROMPT_LAST_CHAR;
136 #ifndef NDEBUG
137 // check command info array
138 char* perc;
139 for (int i = 0; i < NUM_CMDS; i++) {
140 // must be indexable by DbgCommand values, i.e. sorted by DbgCommand values
141 assert(i == cmds[i].cmd);
142 // a format string must be associated
143 assert(cmds[i].fmt != 0);
144 assert(strlen(cmds[i].fmt) <= MAX_FMTLEN);
145 // format string must match arg specification
146 switch (cmds[i].argsNeeded) {
147 case GdbCmdInfo::argNone:
148 assert(strchr(cmds[i].fmt, '%') == 0);
149 break;
150 case GdbCmdInfo::argString:
151 perc = strchr(cmds[i].fmt, '%');
152 assert(perc != 0 && perc[1] == 's');
153 assert(strchr(perc+2, '%') == 0);
154 break;
155 case GdbCmdInfo::argNum:
156 perc = strchr(cmds[i].fmt, '%');
157 assert(perc != 0 && perc[1] == 'd');
158 assert(strchr(perc+2, '%') == 0);
159 break;
160 case GdbCmdInfo::argStringNum:
161 perc = strchr(cmds[i].fmt, '%');
162 assert(perc != 0 && perc[1] == 's');
163 perc = strchr(perc+2, '%');
164 assert(perc != 0 && perc[1] == 'd');
165 assert(strchr(perc+2, '%') == 0);
166 break;
167 case GdbCmdInfo::argNumString:
168 perc = strchr(cmds[i].fmt, '%');
169 assert(perc != 0 && perc[1] == 'd');
170 perc = strchr(perc+2, '%');
171 assert(perc != 0 && perc[1] == 's');
172 assert(strchr(perc+2, '%') == 0);
173 break;
174 case GdbCmdInfo::argString2:
175 perc = strchr(cmds[i].fmt, '%');
176 assert(perc != 0 && perc[1] == 's');
177 perc = strchr(perc+2, '%');
178 assert(perc != 0 && perc[1] == 's');
179 assert(strchr(perc+2, '%') == 0);
180 break;
181 case GdbCmdInfo::argNum2:
182 perc = strchr(cmds[i].fmt, '%');
183 assert(perc != 0 && perc[1] == 'd');
184 perc = strchr(perc+2, '%');
185 assert(perc != 0 && perc[1] == 'd');
186 assert(strchr(perc+2, '%') == 0);
187 break;
190 assert(strlen(printQStringStructFmt) <= MAX_FMTLEN);
191 assert(strlen(printQStringStructNoNullFmt) <= MAX_FMTLEN);
192 #endif
195 GdbDriver::~GdbDriver()
200 QString GdbDriver::driverName() const
202 return "GDB";
205 QString GdbDriver::defaultGdb()
207 return
208 "gdb"
209 " --fullname" /* to get standard file names each time the prog stops */
210 " --nx"; /* do not execute initialization files */
213 QString GdbDriver::defaultInvocation() const
215 if (m_defaultCmd.isEmpty()) {
216 return defaultGdb();
217 } else {
218 return m_defaultCmd;
222 QStringList GdbDriver::boolOptionList() const
224 // no options
225 return QStringList();
228 bool GdbDriver::startup(QString cmdStr)
230 if (!DebuggerDriver::startup(cmdStr))
231 return false;
233 static const char gdbInitialize[] =
235 * Work around buggy gdbs that do command line editing even if they
236 * are not on a tty. The readline library echos every command back
237 * in this case, which is confusing for us.
239 "set editing off\n"
240 "set confirm off\n"
241 "set print static-members off\n"
242 "set print asm-demangle on\n"
244 * Write a short macro that prints all locals: local variables and
245 * function arguments.
247 "define kdbg__alllocals\n"
248 "info locals\n" /* local vars supersede args with same name */
249 "info args\n" /* therefore, arguments must come last */
250 "end\n"
251 // change prompt string and synchronize with gdb
252 "set prompt " PROMPT "\n"
255 executeCmdString(DCinitialize, gdbInitialize, false);
257 // assume that QString::null is ok
258 cmds[DCprintQStringStruct].fmt = printQStringStructFmt;
260 return true;
263 void GdbDriver::commandFinished(CmdQueueItem* cmd)
265 // command string must be committed
266 if (!cmd->m_committed) {
267 // not commited!
268 TRACE("calling " + (__PRETTY_FUNCTION__ + (" with uncommited command:\n\t" +
269 cmd->m_cmdString)));
270 return;
273 switch (cmd->m_cmd) {
274 case DCinitialize:
275 // get version number from preamble
277 int len;
278 QRegExp GDBVersion("\\nGDB [0-9]+\\.[0-9]+");
279 int offset = GDBVersion.match(m_output, 0, &len);
280 if (offset >= 0) {
281 char* start = m_output + offset + 5; // skip "\nGDB "
282 char* end;
283 m_gdbMajor = strtol(start, &end, 10);
284 m_gdbMinor = strtol(end + 1, 0, 10); // skip "."
285 if (start == end) {
286 // nothing was parsed
287 m_gdbMajor = 4;
288 m_gdbMinor = 16;
290 } else {
291 // assume some default version (what would make sense?)
292 m_gdbMajor = 4;
293 m_gdbMinor = 16;
295 // use a feasible core-file command
296 if (m_gdbMajor > 4 || (m_gdbMajor == 4 && m_gdbMinor >= 16)) {
297 cmds[DCcorefile].fmt = "target core %s\n";
298 } else {
299 cmds[DCcorefile].fmt = "core-file %s\n";
302 break;
303 default:;
306 /* ok, the command is ready */
307 emit commandReceived(cmd, m_output);
309 switch (cmd->m_cmd) {
310 case DCcorefile:
311 case DCinfolinemain:
312 case DCframe:
313 case DCattach:
314 case DCrun:
315 case DCcont:
316 case DCstep:
317 case DCstepi:
318 case DCnext:
319 case DCnexti:
320 case DCfinish:
321 case DCuntil:
322 parseMarker();
323 default:;
328 * The --fullname option makes gdb send a special normalized sequence print
329 * each time the program stops and at some other points. The sequence has
330 * the form "\032\032filename:lineno:charoffset:(beg|middle):address".
332 void GdbDriver::parseMarker()
334 char* startMarker = strstr(m_output, "\032\032");
335 if (startMarker == 0)
336 return;
338 // extract the marker
339 startMarker += 2;
340 TRACE(QString("found marker: ") + startMarker);
341 char* endMarker = strchr(startMarker, '\n');
342 if (endMarker == 0)
343 return;
345 *endMarker = '\0';
347 // extract filename and line number
348 static QRegExp MarkerRE(":[0-9]+:[0-9]+:[begmidl]+:0x");
350 int len;
351 int lineNoStart = MarkerRE.match(startMarker, 0, &len);
352 if (lineNoStart >= 0) {
353 int lineNo = atoi(startMarker + lineNoStart+1);
355 // get address
356 const char* addrStart = startMarker + lineNoStart + len - 2;
357 DbgAddr address = QString(addrStart).stripWhiteSpace();
359 // now show the window
360 startMarker[lineNoStart] = '\0'; /* split off file name */
361 emit activateFileLine(startMarker, lineNo-1, address);
367 * Escapes characters that might lead to problems when they appear on gdb's
368 * command line.
370 static void normalizeStringArg(QString& arg)
373 * Remove trailing backslashes. This approach is a little simplistic,
374 * but we know that there is at the moment no case where a trailing
375 * backslash would make sense.
377 while (!arg.isEmpty() && arg[arg.length()-1] == '\\') {
378 arg = arg.left(arg.length()-1);
383 QString GdbDriver::makeCmdString(DbgCommand cmd, QString strArg)
385 assert(cmd >= 0 && cmd < NUM_CMDS);
386 assert(cmds[cmd].argsNeeded == GdbCmdInfo::argString);
388 normalizeStringArg(strArg);
390 if (cmd == DCcd) {
391 // need the working directory when parsing the output
392 m_programWD = strArg;
393 } else if (cmd == DCsetargs) {
394 // attach saved redirection
395 strArg += m_redirect;
398 SIZED_QString(cmdString, MAX_FMTLEN+strArg.length());
399 cmdString.sprintf(cmds[cmd].fmt, strArg.latin1());
400 return cmdString;
403 QString GdbDriver::makeCmdString(DbgCommand cmd, int intArg)
405 assert(cmd >= 0 && cmd < NUM_CMDS);
406 assert(cmds[cmd].argsNeeded == GdbCmdInfo::argNum);
408 SIZED_QString(cmdString, MAX_FMTLEN+30);
410 cmdString.sprintf(cmds[cmd].fmt, intArg);
411 return cmdString;
414 QString GdbDriver::makeCmdString(DbgCommand cmd, QString strArg, int intArg)
416 assert(cmd >= 0 && cmd < NUM_CMDS);
417 assert(cmds[cmd].argsNeeded == GdbCmdInfo::argStringNum ||
418 cmds[cmd].argsNeeded == GdbCmdInfo::argNumString ||
419 cmd == DCexamine ||
420 cmd == DCtty);
422 normalizeStringArg(strArg);
424 SIZED_QString(cmdString, MAX_FMTLEN+30+strArg.length());
426 if (cmd == DCtty)
429 * intArg specifies which channels should be redirected to
430 * /dev/null. It is a value or'ed together from RDNstdin,
431 * RDNstdout, RDNstderr. We store the value for a later DCsetargs
432 * command.
434 * Note: We rely on that after the DCtty a DCsetargs will follow,
435 * which will ultimately apply the redirection.
437 static const char* const runRedir[8] = {
439 " </dev/null",
440 " >/dev/null",
441 " </dev/null >/dev/null",
442 " 2>/dev/null",
443 " </dev/null 2>/dev/null",
444 " >/dev/null 2>&1",
445 " </dev/null >/dev/null 2>&1"
447 if (strArg.isEmpty())
448 intArg = 7; /* failsafe if no tty */
449 m_redirect = runRedir[intArg & 7];
451 return makeCmdString(DCtty, strArg); /* note: no problem if strArg empty */
454 if (cmd == DCexamine) {
455 // make a format specifier from the intArg
456 static const char size[16] = {
457 '\0', 'b', 'h', 'w', 'g'
459 static const char format[16] = {
460 '\0', 'x', 'd', 'u', 'o', 't',
461 'a', 'c', 'f', 's', 'i'
463 assert(MDTsizemask == 0xf); /* lowest 4 bits */
464 assert(MDTformatmask == 0xf0); /* next 4 bits */
465 int count = 16; /* number of entities to print */
466 char sizeSpec = size[intArg & MDTsizemask];
467 char formatSpec = format[(intArg & MDTformatmask) >> 4];
468 assert(sizeSpec != '\0');
469 assert(formatSpec != '\0');
470 // adjust count such that 16 lines are printed
471 switch (intArg & MDTformatmask) {
472 case MDTstring: case MDTinsn:
473 break; /* no modification needed */
474 default:
475 // all cases drop through:
476 switch (intArg & MDTsizemask) {
477 case MDTbyte:
478 case MDThalfword:
479 count *= 2;
480 case MDTword:
481 count *= 2;
482 case MDTgiantword:
483 count *= 2;
485 break;
487 QString spec;
488 spec.sprintf("/%d%c%c", count, sizeSpec, formatSpec);
490 return makeCmdString(DCexamine, spec, strArg);
493 if (cmds[cmd].argsNeeded == GdbCmdInfo::argStringNum)
495 // line numbers are zero-based
496 if (cmd == DCuntil || cmd == DCbreakline ||
497 cmd == DCtbreakline || cmd == DCinfoline)
499 intArg++;
501 if (cmd == DCinfoline)
503 // must split off file name part
504 int slash = strArg.findRev('/');
505 if (slash >= 0)
506 strArg = strArg.right(strArg.length()-slash-1);
508 cmdString.sprintf(cmds[cmd].fmt, strArg.latin1(), intArg);
510 else
512 cmdString.sprintf(cmds[cmd].fmt, intArg, strArg.latin1());
514 return cmdString;
517 QString GdbDriver::makeCmdString(DbgCommand cmd, QString strArg1, QString strArg2)
519 assert(cmd >= 0 && cmd < NUM_CMDS);
520 assert(cmds[cmd].argsNeeded == GdbCmdInfo::argString2);
522 normalizeStringArg(strArg1);
523 normalizeStringArg(strArg2);
525 SIZED_QString(cmdString, MAX_FMTLEN+strArg1.length()+strArg2.length());
526 cmdString.sprintf(cmds[cmd].fmt, strArg1.latin1(), strArg2.latin1());
527 return cmdString;
530 QString GdbDriver::makeCmdString(DbgCommand cmd, int intArg1, int intArg2)
532 assert(cmd >= 0 && cmd < NUM_CMDS);
533 assert(cmds[cmd].argsNeeded == GdbCmdInfo::argNum2);
535 SIZED_QString(cmdString, MAX_FMTLEN+60);
536 cmdString.sprintf(cmds[cmd].fmt, intArg1, intArg2);
537 return cmdString;
540 CmdQueueItem* GdbDriver::executeCmd(DbgCommand cmd, bool clearLow)
542 assert(cmd >= 0 && cmd < NUM_CMDS);
543 assert(cmds[cmd].argsNeeded == GdbCmdInfo::argNone);
545 if (cmd == DCrun) {
546 m_haveCoreFile = false;
549 return executeCmdString(cmd, cmds[cmd].fmt, clearLow);
552 CmdQueueItem* GdbDriver::executeCmd(DbgCommand cmd, QString strArg,
553 bool clearLow)
555 return executeCmdString(cmd, makeCmdString(cmd, strArg), clearLow);
558 CmdQueueItem* GdbDriver::executeCmd(DbgCommand cmd, int intArg,
559 bool clearLow)
562 return executeCmdString(cmd, makeCmdString(cmd, intArg), clearLow);
565 CmdQueueItem* GdbDriver::executeCmd(DbgCommand cmd, QString strArg, int intArg,
566 bool clearLow)
568 return executeCmdString(cmd, makeCmdString(cmd, strArg, intArg), clearLow);
571 CmdQueueItem* GdbDriver::executeCmd(DbgCommand cmd, QString strArg1, QString strArg2,
572 bool clearLow)
574 return executeCmdString(cmd, makeCmdString(cmd, strArg1, strArg2), clearLow);
577 CmdQueueItem* GdbDriver::executeCmd(DbgCommand cmd, int intArg1, int intArg2,
578 bool clearLow)
580 return executeCmdString(cmd, makeCmdString(cmd, intArg1, intArg2), clearLow);
583 CmdQueueItem* GdbDriver::queueCmd(DbgCommand cmd, QueueMode mode)
585 return queueCmdString(cmd, cmds[cmd].fmt, mode);
588 CmdQueueItem* GdbDriver::queueCmd(DbgCommand cmd, QString strArg,
589 QueueMode mode)
591 return queueCmdString(cmd, makeCmdString(cmd, strArg), mode);
594 CmdQueueItem* GdbDriver::queueCmd(DbgCommand cmd, int intArg,
595 QueueMode mode)
597 return queueCmdString(cmd, makeCmdString(cmd, intArg), mode);
600 CmdQueueItem* GdbDriver::queueCmd(DbgCommand cmd, QString strArg, int intArg,
601 QueueMode mode)
603 return queueCmdString(cmd, makeCmdString(cmd, strArg, intArg), mode);
606 CmdQueueItem* GdbDriver::queueCmd(DbgCommand cmd, QString strArg1, QString strArg2,
607 QueueMode mode)
609 return queueCmdString(cmd, makeCmdString(cmd, strArg1, strArg2), mode);
612 void GdbDriver::terminate()
614 kill(SIGTERM);
615 m_state = DSidle;
618 void GdbDriver::detachAndTerminate()
620 kill(SIGINT);
621 flushCommands();
622 executeCmdString(DCinitialize, "detach\nquit\n", true);
625 void GdbDriver::interruptInferior()
627 kill(SIGINT);
628 // remove accidentally queued commands
629 flushHiPriQueue();
632 static bool isErrorExpr(const char* output)
634 return
635 strncmp(output, "Cannot access memory at", 23) == 0 ||
636 strncmp(output, "Attempt to dereference a generic pointer", 40) == 0 ||
637 strncmp(output, "Attempt to take contents of ", 28) == 0 ||
638 strncmp(output, "Attempt to use a type name as an expression", 43) == 0 ||
639 strncmp(output, "There is no member or method named", 34) == 0 ||
640 strncmp(output, "A parse error in expression", 27) == 0 ||
641 strncmp(output, "No symbol \"", 11) == 0 ||
642 strncmp(output, "Internal error: ", 16) == 0;
646 * Returns true if the output is an error message. If wantErrorValue is
647 * true, a new VarTree object is created and filled with the error message.
649 static bool parseErrorMessage(const char* output,
650 VarTree*& variable, bool wantErrorValue)
652 if (isErrorExpr(output))
654 if (wantErrorValue) {
655 // put the error message as value in the variable
656 variable = new VarTree(QString(), VarTree::NKplain);
657 const char* endMsg = strchr(output, '\n');
658 if (endMsg == 0)
659 endMsg = output + strlen(output);
660 variable->m_value = FROM_LATIN1(output, endMsg-output);
661 } else {
662 variable = 0;
664 return true;
666 return false;
669 #if QT_VERSION >= 300
670 union Qt2QChar {
671 short s;
672 struct {
673 uchar row;
674 uchar cell;
675 } qch;
677 #endif
679 VarTree* GdbDriver::parseQCharArray(const char* output, bool wantErrorValue, bool qt3like)
681 VarTree* variable = 0;
684 * Parse off white space. gdb sometimes prints white space first if the
685 * printed array leaded to an error.
687 const char* p = output;
688 while (isspace(*p))
689 p++;
691 // check if this is an error indicating that gdb does not know about QString::null
692 if (cmds[DCprintQStringStruct].fmt == printQStringStructFmt &&
693 (strncmp(p, "Internal error: could not find static variable null", 51) == 0 ||
695 * At least gdb 5.2.1 reports the following error when it accesses
696 * QString::null. Checking for it can result in false positives
697 * (where the error is actually triggered by a real NULL pointer
698 * in a badly initialized QString variable) but the consequences
699 * are mild.
701 strncmp(p, "Cannot access memory at address 0x0", 35) == 0))
703 /* QString::null doesn't work, use an alternate expression */
704 cmds[DCprintQStringStruct].fmt = printQStringStructNoNullFmt;
705 // continue and let parseOffErrorExpr catch the error
708 // special case: empty string (0 repetitions)
709 if (strncmp(p, "Invalid number 0 of repetitions", 31) == 0)
711 variable = new VarTree(QString(), VarTree::NKplain);
712 variable->m_value = "\"\"";
713 return variable;
716 // check for error conditions
717 if (parseErrorMessage(p, variable, wantErrorValue))
718 return variable;
720 // parse the array
722 // find '='
723 p = strchr(p, '=');
724 if (p == 0) {
725 goto error;
727 // skip white space
728 do {
729 p++;
730 } while (isspace(*p));
732 if (*p == '{')
734 // this is the real data
735 p++; /* skip '{' */
737 // parse the array
738 QString result;
739 QString repeatCount;
740 enum { wasNothing, wasChar, wasRepeat } lastThing = wasNothing;
742 * A matrix for separators between the individual "things"
743 * that are added to the string. The first index is a bool,
744 * the second index is from the enum above.
746 static const char* separator[2][3] = {
747 { "\"", 0, ", \"" }, /* normal char is added */
748 { "'", "\", '", ", '" } /* repeated char is added */
751 while (isdigit(*p)) {
752 // parse a number
753 char* end;
754 unsigned short value = (unsigned short) strtoul(p, &end, 0);
755 if (end == p)
756 goto error; /* huh? no valid digits */
757 // skip separator and search for a repeat count
758 p = end;
759 while (isspace(*p) || *p == ',')
760 p++;
761 bool repeats = strncmp(p, "<repeats ", 9) == 0;
762 if (repeats) {
763 const char* start = p;
764 p = strchr(p+9, '>'); /* search end and advance */
765 if (p == 0)
766 goto error;
767 p++; /* skip '>' */
768 repeatCount = FROM_LATIN1(start, p-start);
769 while (isspace(*p) || *p == ',')
770 p++;
772 // p is now at the next char (or the end)
774 // interpret the value as a QChar
775 // TODO: make cross-architecture compatible
776 QChar ch;
777 if (qt3like) {
778 ch = QChar(value);
779 } else {
780 #if QT_VERSION < 300
781 (unsigned short&)ch = value;
782 #else
783 Qt2QChar c;
784 c.s = value;
785 ch.setRow(c.qch.row);
786 ch.setCell(c.qch.cell);
787 #endif
790 // escape a few frequently used characters
791 char escapeCode = '\0';
792 switch (ch.latin1()) {
793 case '\n': escapeCode = 'n'; break;
794 case '\r': escapeCode = 'r'; break;
795 case '\t': escapeCode = 't'; break;
796 case '\b': escapeCode = 'b'; break;
797 case '\"': escapeCode = '\"'; break;
798 case '\\': escapeCode = '\\'; break;
799 case '\0': if (value == 0) { escapeCode = '0'; } break;
802 // add separator
803 result += separator[repeats][lastThing];
804 // add char
805 if (escapeCode != '\0') {
806 result += '\\';
807 ch = escapeCode;
809 result += ch;
811 // fixup repeat count and lastThing
812 if (repeats) {
813 result += "' ";
814 result += repeatCount;
815 lastThing = wasRepeat;
816 } else {
817 lastThing = wasChar;
820 if (*p != '}')
821 goto error;
823 // closing quote
824 if (lastThing == wasChar)
825 result += "\"";
827 // assign the value
828 variable = new VarTree(QString(), VarTree::NKplain);
829 variable->m_value = result;
831 else if (strncmp(p, "true", 4) == 0)
833 variable = new VarTree(QString(), VarTree::NKplain);
834 variable->m_value = "QString::null";
836 else if (strncmp(p, "false", 5) == 0)
838 variable = new VarTree(QString(), VarTree::NKplain);
839 variable->m_value = "(null)";
841 else
842 goto error;
843 return variable;
845 error:
846 if (wantErrorValue) {
847 variable = new VarTree(QString(), VarTree::NKplain);
848 variable->m_value = "internal parse error";
850 return variable;
853 static VarTree* parseVar(const char*& s)
855 const char* p = s;
857 // skip whitespace
858 while (isspace(*p))
859 p++;
861 QString name;
862 VarTree::NameKind kind;
863 if (!parseName(p, name, kind)) {
864 return 0;
867 // go for '='
868 while (isspace(*p))
869 p++;
870 if (*p != '=') {
871 TRACE(QString().sprintf("parse error: = not found after %s", (const char*)name));
872 return 0;
874 // skip the '=' and more whitespace
875 p++;
876 while (isspace(*p))
877 p++;
879 VarTree* variable = new VarTree(name, kind);
880 variable->setDeleteChildren(true);
882 if (!parseValue(p, variable)) {
883 delete variable;
884 return 0;
886 s = p;
887 return variable;
890 static void skipNested(const char*& s, char opening, char closing)
892 const char* p = s;
894 // parse a nested type
895 int nest = 1;
896 p++;
898 * Search for next matching `closing' char, skipping nested pairs of
899 * `opening' and `closing'.
901 while (*p && nest > 0) {
902 if (*p == opening) {
903 nest++;
904 } else if (*p == closing) {
905 nest--;
907 p++;
909 if (nest != 0) {
910 TRACE(QString().sprintf("parse error: mismatching %c%c at %-20.20s", opening, closing, s));
912 s = p;
916 * Find the end of line that is not inside braces
918 static void findEnd(const char*& s)
920 const char* p = s;
921 while (*p && *p!='\n') {
922 while (*p && *p!='\n' && *p!='{')
923 p++;
924 if (*p=='{') {
925 p++;
926 skipNested(p, '{', '}'); p--;
929 s = p;
932 static bool isNumberish(const char ch)
934 return (ch>='0' && ch<='9') || ch=='.' || ch=='x';
937 void skipString(const char*& p)
939 moreStrings:
940 // opening quote
941 char quote = *p++;
942 while (*p != quote) {
943 if (*p == '\\') {
944 // skip escaped character
945 // no special treatment for octal values necessary
946 p++;
948 // simply return if no more characters
949 if (*p == '\0')
950 return;
951 p++;
953 // closing quote
954 p++;
956 * Strings can consist of several parts, some of which contain repeated
957 * characters.
959 if (quote == '\'') {
960 // look ahaead for <repeats 123 times>
961 const char* q = p+1;
962 while (isspace(*q))
963 q++;
964 if (strncmp(q, "<repeats ", 9) == 0) {
965 p = q+9;
966 while (*p != '\0' && *p != '>')
967 p++;
968 if (*p != '\0') {
969 p++; /* skip the '>' */
973 // is the string continued?
974 if (*p == ',') {
975 // look ahead for another quote
976 const char* q = p+1;
977 while (isspace(*q))
978 q++;
979 if (*q == '"' || *q == '\'') {
980 // yes!
981 p = q;
982 goto moreStrings;
985 /* very long strings are followed by `...' */
986 if (*p == '.' && p[1] == '.' && p[2] == '.') {
987 p += 3;
991 static void skipNestedWithString(const char*& s, char opening, char closing)
993 const char* p = s;
995 // parse a nested expression
996 int nest = 1;
997 p++;
999 * Search for next matching `closing' char, skipping nested pairs of
1000 * `opening' and `closing' as well as strings.
1002 while (*p && nest > 0) {
1003 if (*p == opening) {
1004 nest++;
1005 } else if (*p == closing) {
1006 nest--;
1007 } else if (*p == '\'' || *p == '\"') {
1008 skipString(p);
1009 continue;
1011 p++;
1013 if (nest > 0) {
1014 TRACE(QString().sprintf("parse error: mismatching %c%c at %-20.20s", opening, closing, s));
1016 s = p;
1019 inline void skipName(const char*& p)
1021 // allow : (for enumeration values) and $ and . (for _vtbl.)
1022 while (isalnum(*p) || *p == '_' || *p == ':' || *p == '$' || *p == '.')
1023 p++;
1026 static bool parseName(const char*& s, QString& name, VarTree::NameKind& kind)
1028 kind = VarTree::NKplain;
1030 const char* p = s;
1031 // examples of names:
1032 // name
1033 // <Object>
1034 // <string<a,b<c>,7> >
1036 if (*p == '<') {
1037 skipNested(p, '<', '>');
1038 name = FROM_LATIN1(s, p - s);
1039 kind = VarTree::NKtype;
1041 else
1043 // name, which might be "static"; allow dot for "_vtbl."
1044 skipName(p);
1045 if (p == s) {
1046 TRACE(QString().sprintf("parse error: not a name %-20.20s", s));
1047 return false;
1049 int len = p - s;
1050 if (len == 6 && strncmp(s, "static", 6) == 0) {
1051 kind = VarTree::NKstatic;
1053 // its a static variable, name comes now
1054 while (isspace(*p))
1055 p++;
1056 s = p;
1057 skipName(p);
1058 if (p == s) {
1059 TRACE(QString().sprintf("parse error: not a name after static %-20.20s", s));
1060 return false;
1062 len = p - s;
1064 name = FROM_LATIN1(s, len);
1066 // return the new position
1067 s = p;
1068 return true;
1071 static bool parseValue(const char*& s, VarTree* variable)
1073 variable->m_value = "";
1075 repeat:
1076 if (*s == '{') {
1077 s++;
1078 if (!parseNested(s, variable)) {
1079 return false;
1081 // must be the closing brace
1082 if (*s != '}') {
1083 TRACE("parse error: missing } of " + variable->getText());
1084 return false;
1086 s++;
1087 // final white space
1088 while (isspace(*s))
1089 s++;
1090 } else {
1091 // examples of leaf values (cannot be the empty string):
1092 // 123
1093 // -123
1094 // 23.575e+37
1095 // 0x32a45
1096 // @0x012ab4
1097 // (DwContentType&) @0x8123456: {...}
1098 // 0x32a45 "text"
1099 // 10 '\n'
1100 // <optimized out>
1101 // 0x823abc <Array<int> virtual table>
1102 // (void (*)()) 0x8048480 <f(E *, char)>
1103 // (E *) 0xbffff450
1104 // red
1105 // &parseP (HTMLClueV *, char *)
1106 // Variable "x" is not available.
1108 const char*p = s;
1110 // check for type
1111 QString type;
1112 if (*p == '(') {
1113 skipNested(p, '(', ')');
1115 while (isspace(*p))
1116 p++;
1117 variable->m_value = FROM_LATIN1(s, p - s);
1120 bool reference = false;
1121 if (*p == '@') {
1122 // skip reference marker
1123 p++;
1124 reference = true;
1126 const char* start = p;
1127 if (*p == '-')
1128 p++;
1130 // some values consist of more than one token
1131 bool checkMultiPart = false;
1133 if (p[0] == '0' && p[1] == 'x') {
1134 // parse hex number
1135 p += 2;
1136 while (isxdigit(*p))
1137 p++;
1140 * Assume this is a pointer, but only if it's not a reference, since
1141 * references can't be expanded.
1143 if (!reference) {
1144 variable->m_varKind = VarTree::VKpointer;
1145 } else {
1147 * References are followed by a colon, in which case we'll
1148 * find the value following the reference address.
1150 if (*p == ':') {
1151 p++;
1152 } else {
1153 // Paranoia. (Can this happen, i.e. reference not followed by ':'?)
1154 reference = false;
1157 checkMultiPart = true;
1158 } else if (isdigit(*p)) {
1159 // parse decimal number, possibly a float
1160 while (isdigit(*p))
1161 p++;
1162 if (*p == '.') { /* TODO: obey i18n? */
1163 // fractional part
1164 p++;
1165 while (isdigit(*p))
1166 p++;
1168 if (*p == 'e' || *p == 'E') {
1169 p++;
1170 // exponent
1171 if (*p == '-' || *p == '+')
1172 p++;
1173 while (isdigit(*p))
1174 p++;
1177 // for char variables there is the char, eg. 10 '\n'
1178 checkMultiPart = true;
1179 } else if (*p == '<') {
1180 // e.g. <optimized out>
1181 skipNested(p, '<', '>');
1182 } else if (*p == '"' || *p == '\'') {
1183 // character may have multipart: '\000' <repeats 11 times>
1184 checkMultiPart = *p == '\'';
1185 // found a string
1186 skipString(p);
1187 } else if (*p == '&') {
1188 // function pointer
1189 p++;
1190 skipName(p);
1191 while (isspace(*p)) {
1192 p++;
1194 if (*p == '(') {
1195 skipNested(p, '(', ')');
1197 } else if (strncmp(p, "Variable \"", 10) == 0) {
1198 // Variable "x" is not available.
1199 p += 10; // skip to "
1200 skipName(p);
1201 if (strncmp(p, "\" is not available.", 19) == 0) {
1202 p += 19;
1204 } else {
1205 // must be an enumeration value
1206 skipName(p);
1208 variable->m_value += FROM_LATIN1(start, p - start);
1210 if (checkMultiPart) {
1211 // white space
1212 while (isspace(*p))
1213 p++;
1214 // may be followed by a string or <...>
1215 start = p;
1217 if (*p == '"' || *p == '\'') {
1218 skipString(p);
1219 } else if (*p == '<') {
1220 // if this value is part of an array, it might be followed
1221 // by <repeats 15 times>, which we don't skip here
1222 if (strncmp(p, "<repeats ", 9) != 0)
1223 skipNested(p, '<', '>');
1225 if (p != start) {
1226 // there is always a blank before the string,
1227 // which we will include in the final string value
1228 variable->m_value += FROM_LATIN1(start-1, (p - start)+1);
1229 // if this was a pointer, reset that flag since we
1230 // now got the value
1231 variable->m_varKind = VarTree::VKsimple;
1235 if (variable->m_value.length() == 0) {
1236 TRACE("parse error: no value for " + variable->getText());
1237 return false;
1240 // final white space
1241 while (isspace(*p))
1242 p++;
1243 s = p;
1246 * If this was a reference, the value follows. It might even be a
1247 * composite variable!
1249 if (reference) {
1250 goto repeat;
1253 if (variable->m_varKind == VarTree::VKpointer) {
1254 variable->setDelayedExpanding(true);
1258 return true;
1261 static bool parseNested(const char*& s, VarTree* variable)
1263 // could be a structure or an array
1264 while (isspace(*s))
1265 s++;
1267 const char* p = s;
1268 bool isStruct = false;
1270 * If there is a name followed by an = or an < -- which starts a type
1271 * name -- or "static", it is a structure
1273 if (*p == '<' || *p == '}') {
1274 isStruct = true;
1275 } else if (strncmp(p, "static ", 7) == 0) {
1276 isStruct = true;
1277 } else if (isalpha(*p) || *p == '_' || *p == '$') {
1278 // look ahead for a comma after the name
1279 skipName(p);
1280 while (isspace(*p))
1281 p++;
1282 if (*p == '=') {
1283 isStruct = true;
1285 p = s; /* rescan the name */
1287 if (isStruct) {
1288 if (!parseVarSeq(p, variable)) {
1289 return false;
1291 variable->m_varKind = VarTree::VKstruct;
1292 } else {
1293 if (!parseValueSeq(p, variable)) {
1294 return false;
1296 variable->m_varKind = VarTree::VKarray;
1298 s = p;
1299 return true;
1302 static bool parseVarSeq(const char*& s, VarTree* variable)
1304 // parse a comma-separated sequence of variables
1305 VarTree* var = variable; /* var != 0 to indicate success if empty seq */
1306 for (;;) {
1307 if (*s == '}')
1308 break;
1309 if (strncmp(s, "<No data fields>}", 17) == 0)
1311 // no member variables, so break out immediately
1312 s += 16; /* go to the closing brace */
1313 break;
1315 var = parseVar(s);
1316 if (var == 0)
1317 break; /* syntax error */
1318 variable->appendChild(var);
1319 if (*s != ',')
1320 break;
1321 // skip the comma and whitespace
1322 s++;
1323 while (isspace(*s))
1324 s++;
1326 return var != 0;
1329 static bool parseValueSeq(const char*& s, VarTree* variable)
1331 // parse a comma-separated sequence of variables
1332 int index = 0;
1333 bool good;
1334 for (;;) {
1335 QString name;
1336 name.sprintf("[%d]", index);
1337 VarTree* var = new VarTree(name, VarTree::NKplain);
1338 var->setDeleteChildren(true);
1339 good = parseValue(s, var);
1340 if (!good) {
1341 delete var;
1342 return false;
1344 // a value may be followed by "<repeats 45 times>"
1345 if (strncmp(s, "<repeats ", 9) == 0) {
1346 s += 9;
1347 char* end;
1348 int l = strtol(s, &end, 10);
1349 if (end == s || strncmp(end, " times>", 7) != 0) {
1350 // should not happen
1351 delete var;
1352 return false;
1354 TRACE(QString().sprintf("found <repeats %d times> in array", l));
1355 // replace name and advance index
1356 name.sprintf("[%d .. %d]", index, index+l-1);
1357 var->setText(name);
1358 index += l;
1359 // skip " times>" and space
1360 s = end+7;
1361 // possible final space
1362 while (isspace(*s))
1363 s++;
1364 } else {
1365 index++;
1367 variable->appendChild(var);
1368 if (*s != ',') {
1369 break;
1371 // skip the comma and whitespace
1372 s++;
1373 while (isspace(*s))
1374 s++;
1375 // sometimes there is a closing brace after a comma
1376 // if (*s == '}')
1377 // break;
1379 return true;
1383 * Parses a stack frame.
1385 static void parseFrameInfo(const char*& s, QString& func,
1386 QString& file, int& lineNo, DbgAddr& address)
1388 const char* p = s;
1390 // next may be a hexadecimal address
1391 if (*p == '0') {
1392 const char* start = p;
1393 p++;
1394 if (*p == 'x')
1395 p++;
1396 while (isxdigit(*p))
1397 p++;
1398 address = FROM_LATIN1(start, p-start);
1399 if (strncmp(p, " in ", 4) == 0)
1400 p += 4;
1401 } else {
1402 address = DbgAddr();
1404 const char* start = p;
1405 // check for special signal handler frame
1406 if (strncmp(p, "<signal handler called>", 23) == 0) {
1407 func = FROM_LATIN1(start, 23);
1408 file = QString();
1409 lineNo = -1;
1410 s = p+23;
1411 if (*s == '\n')
1412 s++;
1413 return;
1415 // search opening parenthesis
1416 while (*p != '\0' && *p != '(')
1417 p++;
1418 if (*p == '\0') {
1419 func = start;
1420 file = QString();
1421 lineNo = -1;
1422 s = p;
1423 return;
1426 * Skip parameters. But notice that for complicated conversion
1427 * functions (eg. "operator int(**)()()", ie. convert to pointer to
1428 * pointer to function) as well as operator()(...) we have to skip
1429 * additional pairs of parentheses. Furthermore, recent gdbs write the
1430 * demangled name followed by the arguments in a pair of parentheses,
1431 * where the demangled name can end in "const".
1433 do {
1434 skipNestedWithString(p, '(', ')');
1435 while (isspace(*p))
1436 p++;
1437 // skip "const"
1438 if (strncmp(p, "const", 5) == 0) {
1439 p += 5;
1440 while (isspace(*p))
1441 p++;
1443 } while (*p == '(');
1445 // check for file position
1446 if (strncmp(p, "at ", 3) == 0) {
1447 p += 3;
1448 const char* fileStart = p;
1449 // go for the end of the line
1450 while (*p != '\0' && *p != '\n')
1451 p++;
1452 // search back for colon
1453 const char* colon = p;
1454 do {
1455 --colon;
1456 } while (*colon != ':');
1457 file = FROM_LATIN1(fileStart, colon-fileStart);
1458 lineNo = atoi(colon+1)-1;
1459 // skip new-line
1460 if (*p != '\0')
1461 p++;
1462 } else {
1463 // check for "from shared lib"
1464 if (strncmp(p, "from ", 5) == 0) {
1465 p += 5;
1466 // go for the end of the line
1467 while (*p != '\0' && *p != '\n')
1468 p++;
1469 // skip new-line
1470 if (*p != '\0')
1471 p++;
1473 file = "";
1474 lineNo = -1;
1476 // construct the function name (including file info)
1477 if (*p == '\0') {
1478 func = start;
1479 } else {
1480 func = FROM_LATIN1(start, p-start-1); /* don't include \n */
1482 s = p;
1485 * Replace \n (and whitespace around it) in func by a blank. We cannot
1486 * use QString::simplifyWhiteSpace() for this because this would also
1487 * simplify space that belongs to a string arguments that gdb sometimes
1488 * prints in the argument lists of the function.
1490 ASSERT(!isspace(func[0].latin1())); /* there must be non-white before first \n */
1491 int nl = 0;
1492 while ((nl = func.find('\n', nl)) >= 0) {
1493 // search back to the beginning of the whitespace
1494 int startWhite = nl;
1495 do {
1496 --startWhite;
1497 } while (isspace(func[startWhite].latin1()));
1498 startWhite++;
1499 // search forward to the end of the whitespace
1500 do {
1501 nl++;
1502 } while (isspace(func[nl].latin1()));
1503 // replace
1504 func.replace(startWhite, nl-startWhite, " ");
1505 /* continue searching for more \n's at this place: */
1506 nl = startWhite+1;
1512 * Parses a stack frame including its frame number
1514 static bool parseFrame(const char*& s, int& frameNo, QString& func,
1515 QString& file, int& lineNo, DbgAddr& address)
1517 // Example:
1518 // #1 0x8048881 in Dl::Dl (this=0xbffff418, r=3214) at testfile.cpp:72
1519 // Breakpoint 3, Cl::f(int) const (this=0xbffff3c0, x=17) at testfile.cpp:155
1521 // must start with a hash mark followed by number
1522 // or with "Breakpoint " followed by number and comma
1523 if (s[0] == '#') {
1524 if (!isdigit(s[1]))
1525 return false;
1526 s++; /* skip the hash mark */
1527 } else if (strncmp(s, "Breakpoint ", 11) == 0) {
1528 if (!isdigit(s[11]))
1529 return false;
1530 s += 11; /* skip "Breakpoint" */
1531 } else
1532 return false;
1534 // frame number
1535 frameNo = atoi(s);
1536 while (isdigit(*s))
1537 s++;
1538 // space and comma
1539 while (isspace(*s) || *s == ',')
1540 s++;
1541 parseFrameInfo(s, func, file, lineNo, address);
1542 return true;
1545 void GdbDriver::parseBackTrace(const char* output, QList<StackFrame>& stack)
1547 QString func, file;
1548 int lineNo, frameNo;
1549 DbgAddr address;
1551 while (::parseFrame(output, frameNo, func, file, lineNo, address)) {
1552 StackFrame* frm = new StackFrame;
1553 frm->frameNo = frameNo;
1554 frm->fileName = file;
1555 frm->lineNo = lineNo;
1556 frm->address = address;
1557 frm->var = new VarTree(func, VarTree::NKplain);
1558 stack.append(frm);
1562 bool GdbDriver::parseFrameChange(const char* output, int& frameNo,
1563 QString& file, int& lineNo, DbgAddr& address)
1565 QString func;
1566 return ::parseFrame(output, frameNo, func, file, lineNo, address);
1570 bool GdbDriver::parseBreakList(const char* output, QList<Breakpoint>& brks)
1572 // skip first line, which is the headline
1573 const char* p = strchr(output, '\n');
1574 if (p == 0)
1575 return false;
1576 p++;
1577 if (*p == '\0')
1578 return false;
1580 // split up a line
1581 QString location;
1582 QString address;
1583 int hits = 0;
1584 uint ignoreCount = 0;
1585 QString condition;
1586 const char* end;
1587 char* dummy;
1588 while (*p != '\0') {
1589 // get Num
1590 long bpNum = strtol(p, &dummy, 10); /* don't care about overflows */
1591 p = dummy;
1592 // get Type
1593 while (isspace(*p))
1594 p++;
1595 Breakpoint::Type bpType = Breakpoint::breakpoint;
1596 if (strncmp(p, "breakpoint", 10) == 0) {
1597 p += 10;
1598 } else if (strncmp(p, "hw watchpoint", 13) == 0) {
1599 bpType = Breakpoint::watchpoint;
1600 p += 13;
1601 } else if (strncmp(p, "watchpoint", 10) == 0) {
1602 bpType = Breakpoint::watchpoint;
1603 p += 10;
1605 while (isspace(*p))
1606 p++;
1607 if (*p == '\0')
1608 break;
1609 // get Disp
1610 char disp = *p++;
1611 while (*p != '\0' && !isspace(*p)) /* "keep" or "del" */
1612 p++;
1613 while (isspace(*p))
1614 p++;
1615 if (*p == '\0')
1616 break;
1617 // get Enb
1618 char enable = *p++;
1619 while (*p != '\0' && !isspace(*p)) /* "y" or "n" */
1620 p++;
1621 while (isspace(*p))
1622 p++;
1623 if (*p == '\0')
1624 break;
1625 // the address, if present
1626 if (bpType == Breakpoint::breakpoint &&
1627 strncmp(p, "0x", 2) == 0)
1629 const char* start = p;
1630 while (*p != '\0' && !isspace(*p))
1631 p++;
1632 address = FROM_LATIN1(start, p-start);
1633 while (isspace(*p) && *p != '\n')
1634 p++;
1635 if (*p == '\0')
1636 break;
1637 } else {
1638 address = QString();
1640 // remainder is location, hit and ignore count, condition
1641 hits = 0;
1642 ignoreCount = 0;
1643 condition = QString();
1644 end = strchr(p, '\n');
1645 if (end == 0) {
1646 location = p;
1647 p += location.length();
1648 } else {
1649 location = FROM_LATIN1(p, end-p).stripWhiteSpace();
1650 p = end+1; /* skip over \n */
1653 // may be continued in next line
1654 while (isspace(*p)) { /* p points to beginning of line */
1655 // skip white space at beginning of line
1656 while (isspace(*p))
1657 p++;
1659 // seek end of line
1660 end = strchr(p, '\n');
1661 if (end == 0)
1662 end = p+strlen(p);
1664 if (strncmp(p, "breakpoint already hit", 22) == 0) {
1665 // extract the hit count
1666 p += 22;
1667 hits = strtol(p, &dummy, 10);
1668 TRACE(QString().sprintf("hit count %d", hits));
1669 } else if (strncmp(p, "stop only if ", 13) == 0) {
1670 // extract condition
1671 p += 13;
1672 condition = FROM_LATIN1(p, end-p).stripWhiteSpace();
1673 TRACE("condition: "+condition);
1674 } else if (strncmp(p, "ignore next ", 12) == 0) {
1675 // extract ignore count
1676 p += 12;
1677 ignoreCount = strtol(p, &dummy, 10);
1678 TRACE(QString().sprintf("ignore count %d", ignoreCount));
1679 } else {
1680 // indeed a continuation
1681 location += " " + FROM_LATIN1(p, end-p).stripWhiteSpace();
1683 p = end;
1684 if (*p != '\0')
1685 p++; /* skip '\n' */
1687 Breakpoint* bp = new Breakpoint;
1688 bp->id = bpNum;
1689 bp->type = bpType;
1690 bp->temporary = disp == 'd';
1691 bp->enabled = enable == 'y';
1692 bp->location = location;
1693 bp->address = address;
1694 bp->hitCount = hits;
1695 bp->ignoreCount = ignoreCount;
1696 bp->condition = condition;
1697 brks.append(bp);
1699 return true;
1702 bool GdbDriver::parseThreadList(const char* output, QList<ThreadInfo>& threads)
1704 if (strcmp(output, "\n") == 0 || strncmp(output, "No stack.", 9) == 0) {
1705 // no threads
1706 return true;
1709 int id;
1710 QString systag;
1711 QString func, file;
1712 int lineNo;
1713 DbgAddr address;
1715 const char* p = output;
1716 while (*p != '\0') {
1717 // seach look for thread id, watching out for the focus indicator
1718 bool hasFocus = false;
1719 while (isspace(*p)) /* may be \n from prev line: see "No stack" below */
1720 p++;
1721 if (*p == '*') {
1722 hasFocus = true;
1723 p++;
1724 // there follows only whitespace
1726 char* end;
1727 id = strtol(p, &end, 10);
1728 if (p == end) {
1729 // syntax error: no number found; bail out
1730 return true;
1732 p = end;
1734 // skip space
1735 while (isspace(*p))
1736 p++;
1739 * Now follows the thread's SYSTAG. It is terminated by two blanks.
1741 end = strstr(p, " ");
1742 if (end == 0) {
1743 // syntax error; bail out
1744 return true;
1746 systag = FROM_LATIN1(p, end-p);
1747 p = end+2;
1750 * Now follows a standard stack frame. Sometimes, however, gdb
1751 * catches a thread at an instant where it doesn't have a stack.
1753 if (strncmp(p, "[No stack.]", 11) != 0) {
1754 ::parseFrameInfo(p, func, file, lineNo, address);
1755 } else {
1756 func = "[No stack]";
1757 file = QString();
1758 lineNo = -1;
1759 address = QString();
1760 p += 11; /* \n is skipped above */
1763 ThreadInfo* thr = new ThreadInfo;
1764 thr->id = id;
1765 thr->threadName = systag;
1766 thr->hasFocus = hasFocus;
1767 thr->function = func;
1768 thr->fileName = file;
1769 thr->lineNo = lineNo;
1770 thr->address = address;
1771 threads.append(thr);
1773 return true;
1776 static bool parseNewBreakpoint(const char* o, int& id,
1777 QString& file, int& lineNo, QString& address);
1778 static bool parseNewWatchpoint(const char* o, int& id,
1779 QString& expr);
1781 bool GdbDriver::parseBreakpoint(const char* output, int& id,
1782 QString& file, int& lineNo, QString& address)
1784 const char* o = output;
1785 // skip lines of that begin with "(Cannot find"
1786 while (strncmp(o, "(Cannot find", 12) == 0) {
1787 o = strchr(o, '\n');
1788 if (o == 0)
1789 return false;
1790 o++; /* skip newline */
1793 if (strncmp(o, "Breakpoint ", 11) == 0) {
1794 output += 11; /* skip "Breakpoint " */
1795 return ::parseNewBreakpoint(output, id, file, lineNo, address);
1796 } else if (strncmp(o, "Hardware watchpoint ", 20) == 0) {
1797 output += 20;
1798 return ::parseNewWatchpoint(output, id, address);
1799 } else if (strncmp(o, "Watchpoint ", 11) == 0) {
1800 output += 11;
1801 return ::parseNewWatchpoint(output, id, address);
1803 return false;
1806 static bool parseNewBreakpoint(const char* o, int& id,
1807 QString& file, int& lineNo, QString& address)
1809 // breakpoint id
1810 char* p;
1811 id = strtoul(o, &p, 10);
1812 if (p == o)
1813 return false;
1815 // check for the address
1816 if (strncmp(p, " at 0x", 6) == 0) {
1817 char* start = p+4; /* skip " at ", but not 0x */
1818 p += 6;
1819 while (isxdigit(*p))
1820 ++p;
1821 address = FROM_LATIN1(start, p-start);
1824 // file name
1825 char* fileStart = strstr(p, "file ");
1826 if (fileStart == 0)
1827 return !address.isEmpty(); /* parse error only if there's no address */
1828 fileStart += 5;
1830 // line number
1831 char* numStart = strstr(fileStart, ", line ");
1832 QString fileName = FROM_LATIN1(fileStart, numStart-fileStart);
1833 numStart += 7;
1834 int line = strtoul(numStart, &p, 10);
1835 if (numStart == p)
1836 return false;
1838 file = fileName;
1839 lineNo = line-1; /* zero-based! */
1840 return true;
1843 static bool parseNewWatchpoint(const char* o, int& id,
1844 QString& expr)
1846 // watchpoint id
1847 char* p;
1848 id = strtoul(o, &p, 10);
1849 if (p == o)
1850 return false;
1852 if (strncmp(p, ": ", 2) != 0)
1853 return false;
1854 p += 2;
1856 // all the rest on the line is the expression
1857 expr = FROM_LATIN1(p, strlen(p)).stripWhiteSpace();
1858 return true;
1861 void GdbDriver::parseLocals(const char* output, QList<VarTree>& newVars)
1863 // check for possible error conditions
1864 if (strncmp(output, "No symbol table", 15) == 0)
1866 return;
1869 while (*output != '\0') {
1870 while (isspace(*output))
1871 output++;
1872 if (*output == '\0')
1873 break;
1874 // skip occurrences of "No locals" and "No args"
1875 if (strncmp(output, "No locals", 9) == 0 ||
1876 strncmp(output, "No arguments", 12) == 0)
1878 output = strchr(output, '\n');
1879 if (output == 0) {
1880 break;
1882 continue;
1885 VarTree* variable = parseVar(output);
1886 if (variable == 0) {
1887 break;
1889 // do not add duplicates
1890 for (VarTree* o = newVars.first(); o != 0; o = newVars.next()) {
1891 if (o->getText() == variable->getText()) {
1892 delete variable;
1893 goto skipDuplicate;
1896 newVars.append(variable);
1897 skipDuplicate:;
1901 bool GdbDriver::parsePrintExpr(const char* output, bool wantErrorValue, VarTree*& var)
1903 // check for error conditions
1904 if (parseErrorMessage(output, var, wantErrorValue))
1906 return false;
1907 } else {
1908 // parse the variable
1909 var = parseVar(output);
1910 return true;
1914 bool GdbDriver::parseChangeWD(const char* output, QString& message)
1916 bool isGood = false;
1917 message = QString(output).simplifyWhiteSpace();
1918 if (message.isEmpty()) {
1919 message = i18n("New working directory: ") + m_programWD;
1920 isGood = true;
1922 return isGood;
1925 bool GdbDriver::parseChangeExecutable(const char* output, QString& message)
1927 message = output;
1929 m_haveCoreFile = false;
1932 * Lines starting with the following do not indicate errors:
1933 * Using host libthread_db
1934 * (no debugging symbols found)
1936 while (strncmp(output, "Using host libthread_db", 23) == 0 ||
1937 strncmp(output, "(no debugging symbols found)", 28) == 0)
1939 // this line is good, go to the next one
1940 const char* end = strchr(output, '\n');
1941 if (end == 0)
1942 output += strlen(output);
1943 else
1944 output = end+1;
1948 * If we've parsed all lines, there was no error.
1950 return output[0] == '\0';
1953 bool GdbDriver::parseCoreFile(const char* output)
1955 // if command succeeded, gdb emits a line starting with "#0 "
1956 m_haveCoreFile = strstr(output, "\n#0 ") != 0;
1957 return m_haveCoreFile;
1960 uint GdbDriver::parseProgramStopped(const char* output, QString& message)
1962 // optionally: "program changed, rereading symbols",
1963 // followed by:
1964 // "Program exited normally"
1965 // "Program terminated with wignal SIGSEGV"
1966 // "Program received signal SIGINT" or other signal
1967 // "Breakpoint..."
1969 // go through the output, line by line, checking what we have
1970 const char* start = output - 1;
1971 uint flags = SFprogramActive;
1972 message = QString();
1973 do {
1974 start++; /* skip '\n' */
1976 if (strncmp(start, "Program ", 8) == 0 ||
1977 strncmp(start, "ptrace: ", 8) == 0) {
1979 * When we receive a signal, the program remains active.
1981 * Special: If we "stopped" in a corefile, the string "Program
1982 * terminated with signal"... is displayed. (Normally, we see
1983 * "Program received signal"... when a signal happens.)
1985 if (strncmp(start, "Program exited", 14) == 0 ||
1986 (strncmp(start, "Program terminated", 18) == 0 && !m_haveCoreFile) ||
1987 strncmp(start, "ptrace: ", 8) == 0)
1989 flags &= ~SFprogramActive;
1992 // set message
1993 const char* endOfMessage = strchr(start, '\n');
1994 if (endOfMessage == 0)
1995 endOfMessage = start + strlen(start);
1996 message = FROM_LATIN1(start, endOfMessage-start);
1997 } else if (strncmp(start, "Breakpoint ", 11) == 0) {
1999 * We stopped at a (permanent) breakpoint (gdb doesn't tell us
2000 * that it stopped at a temporary breakpoint).
2002 flags |= SFrefreshBreak;
2003 } else if (strstr(start, "re-reading symbols.") != 0) {
2004 flags |= SFrefreshSource;
2007 // next line, please
2008 start = strchr(start, '\n');
2009 } while (start != 0);
2012 * Gdb only notices when new threads have appeared, but not when a
2013 * thread finishes. So we always have to assume that the list of
2014 * threads has changed.
2016 flags |= SFrefreshThreads;
2018 return flags;
2021 void GdbDriver::parseSharedLibs(const char* output, QStrList& shlibs)
2023 if (strncmp(output, "No shared libraries loaded", 26) == 0)
2024 return;
2026 // parse the table of shared libraries
2028 // strip off head line
2029 output = strchr(output, '\n');
2030 if (output == 0)
2031 return;
2032 output++; /* skip '\n' */
2033 QString shlibName;
2034 while (*output != '\0') {
2035 // format of a line is
2036 // 0x404c5000 0x40580d90 Yes /lib/libc.so.5
2037 // 3 blocks of non-space followed by space
2038 for (int i = 0; *output != '\0' && i < 3; i++) {
2039 while (*output != '\0' && !isspace(*output)) { /* non-space */
2040 output++;
2042 while (isspace(*output)) { /* space */
2043 output++;
2046 if (*output == '\0')
2047 return;
2048 const char* start = output;
2049 output = strchr(output, '\n');
2050 if (output == 0)
2051 output = start + strlen(start);
2052 shlibName = FROM_LATIN1(start, output-start);
2053 if (*output != '\0')
2054 output++;
2055 shlibs.append(shlibName);
2056 TRACE("found shared lib " + shlibName);
2060 bool GdbDriver::parseFindType(const char* output, QString& type)
2062 if (strncmp(output, "type = ", 7) != 0)
2063 return false;
2066 * Everything else is the type. We strip off all white-space from the
2067 * type.
2069 output += 7;
2070 type = output;
2071 type.replace(QRegExp("\\s+"), "");
2072 return true;
2075 void GdbDriver::parseRegisters(const char* output, QList<RegisterInfo>& regs)
2077 if (strncmp(output, "The program has no registers now", 32) == 0) {
2078 return;
2081 QString regName;
2082 QString value;
2084 // parse register values
2085 while (*output != '\0')
2087 // skip space at the start of the line
2088 while (isspace(*output))
2089 output++;
2091 // register name
2092 const char* start = output;
2093 while (*output != '\0' && !isspace(*output))
2094 output++;
2095 if (*output == '\0')
2096 break;
2097 regName = FROM_LATIN1(start, output-start);
2099 // skip space
2100 while (isspace(*output))
2101 output++;
2103 RegisterInfo* reg = new RegisterInfo;
2104 reg->regName = regName;
2107 * If we find a brace now, this is a vector register. We look for
2108 * the closing brace and treat the result as cooked value.
2110 if (*output == '{')
2112 start = output;
2113 skipNested(output, '{', '}');
2114 value = FROM_LATIN1(start, output-start).simplifyWhiteSpace();
2115 // skip space, but not the end of line
2116 while (isspace(*output) && *output != '\n')
2117 output++;
2118 // get rid of the braces at the begining and the end
2119 value.remove(0, 1);
2120 if (value[value.length()-1] == '}') {
2121 value = value.left(value.length()-1);
2123 // gdb 5.3 doesn't print a separate set of raw values
2124 if (*output == '{') {
2125 // another set of vector follows
2126 // what we have so far is the raw value
2127 reg->rawValue = value;
2129 start = output;
2130 skipNested(output, '{', '}');
2131 value = FROM_LATIN1(start, output-start).simplifyWhiteSpace();
2132 } else {
2133 // for gdb 5.3
2134 // find first type that does not have an array, this is the RAW value
2135 const char* end=start;
2136 findEnd(end);
2137 const char* cur=start;
2138 while (cur<end) {
2139 while (*cur != '=' && cur<end)
2140 cur++;
2141 cur++;
2142 while (isspace(*cur) && cur<end)
2143 cur++;
2144 if (isNumberish(*cur)) {
2145 end=cur;
2146 while (*end && (*end!='}') && (*end!=',') && (*end!='\n'))
2147 end++;
2148 QString rawValue = FROM_LATIN1(cur, end-cur).simplifyWhiteSpace();
2149 reg->rawValue = rawValue;
2151 if (rawValue.left(2)=="0x") {
2152 // ok we have a raw value, now get it's type
2153 end=cur-1;
2154 while (isspace(*end) || *end=='=') end--;
2155 end++;
2156 cur=end-1;
2157 while (*cur!='{' && *cur!=' ')
2158 cur--;
2159 cur++;
2160 reg->type=FROM_LATIN1(cur, end-cur);
2163 // end while loop
2164 cur=end;
2167 // skip to the end of line
2168 while (*output != '\0' && *output != '\n')
2169 output++;
2170 // get rid of the braces at the begining and the end
2171 value.remove(0, 1);
2172 if (value[value.length()-1] == '}') {
2173 value = value.left(value.length()-1);
2176 reg->cookedValue = value;
2178 else
2180 // the rest of the line is the register value
2181 start = output;
2182 output = strchr(output,'\n');
2183 if (output == 0)
2184 output = start + strlen(start);
2185 value = FROM_LATIN1(start, output-start).simplifyWhiteSpace();
2188 * We split the raw from the cooked values.
2189 * Some modern gdbs explicitly say: "0.1234 (raw 0x3e4567...)".
2190 * Here, the cooked value comes first, and the raw value is in
2191 * the second part.
2193 int pos = value.find(" (raw ");
2194 if (pos >= 0)
2196 reg->cookedValue = value.left(pos);
2197 reg->rawValue = value.mid(pos+6);
2198 if (reg->rawValue.right(1) == ")") // remove closing bracket
2199 reg->rawValue.truncate(reg->rawValue.length()-1);
2201 else
2204 * In other cases we split off the first token (separated by
2205 * whitespace). It is the raw value. The remainder of the line
2206 * is the cooked value.
2208 int pos = value.find(' ');
2209 if (pos < 0) {
2210 reg->rawValue = value;
2211 reg->cookedValue = QString();
2212 } else {
2213 reg->rawValue = value.left(pos);
2214 reg->cookedValue = value.mid(pos+1);
2218 if (*output != '\0')
2219 output++; /* skip '\n' */
2221 regs.append(reg);
2225 bool GdbDriver::parseInfoLine(const char* output, QString& addrFrom, QString& addrTo)
2227 // "is at address" or "starts at address"
2228 const char* start = strstr(output, "s at address ");
2229 if (start == 0)
2230 return false;
2232 start += 13;
2233 const char* p = start;
2234 while (*p != '\0' && !isspace(*p))
2235 p++;
2236 addrFrom = FROM_LATIN1(start, p-start);
2238 start = strstr(p, "and ends at ");
2239 if (start == 0) {
2240 addrTo = addrFrom;
2241 return true;
2244 start += 12;
2245 p = start;
2246 while (*p != '\0' && !isspace(*p))
2247 p++;
2248 addrTo = FROM_LATIN1(start, p-start);
2250 return true;
2253 void GdbDriver::parseDisassemble(const char* output, QList<DisassembledCode>& code)
2255 code.clear();
2257 if (strncmp(output, "Dump of assembler", 17) != 0) {
2258 // error message?
2259 DisassembledCode c;
2260 c.code = output;
2261 code.append(new DisassembledCode(c));
2262 return;
2265 // remove first line
2266 const char* p = strchr(output, '\n');
2267 if (p == 0)
2268 return; /* not a regular output */
2270 p++;
2272 // remove last line
2273 const char* end = strstr(output, "End of assembler");
2274 if (end == 0)
2275 end = p + strlen(p);
2277 DbgAddr address;
2279 // remove function offsets from the lines
2280 while (p != end)
2282 const char* start = p;
2283 // address
2284 while (p != end && !isspace(*p))
2285 p++;
2286 address = FROM_LATIN1(start, p-start);
2288 // function name (enclosed in '<>', followed by ':')
2289 while (p != end && *p != '<')
2290 p++;
2291 if (*p == '<')
2292 skipNested(p, '<', '>');
2293 if (*p == ':')
2294 p++;
2296 // space until code
2297 while (p != end && isspace(*p))
2298 p++;
2300 // code until end of line
2301 start = p;
2302 while (p != end && *p != '\n')
2303 p++;
2304 if (p != end) /* include '\n' */
2305 p++;
2307 DisassembledCode* c = new DisassembledCode;
2308 c->address = address;
2309 c->code = FROM_LATIN1(start, p-start);
2310 code.append(c);
2314 QString GdbDriver::parseMemoryDump(const char* output, QList<MemoryDump>& memdump)
2316 if (isErrorExpr(output)) {
2317 // error; strip space
2318 QString msg = output;
2319 return msg.stripWhiteSpace();
2322 const char* p = output; /* save typing */
2323 DbgAddr addr;
2324 QString dump;
2326 // the address
2327 while (*p != 0) {
2328 const char* start = p;
2329 while (*p != '\0' && *p != ':' && !isspace(*p))
2330 p++;
2331 addr = FROM_LATIN1(start, p-start);
2332 if (*p != ':') {
2333 // parse function offset
2334 while (isspace(*p))
2335 p++;
2336 start = p;
2337 while (*p != '\0' && !(*p == ':' && isspace(p[1])))
2338 p++;
2339 addr.fnoffs = FROM_LATIN1(start, p-start);
2341 if (*p == ':')
2342 p++;
2343 // skip space; this may skip a new-line char!
2344 while (isspace(*p))
2345 p++;
2346 // everything to the end of the line is the memory dump
2347 const char* end = strchr(p, '\n');
2348 if (end != 0) {
2349 dump = FROM_LATIN1(p, end-p);
2350 p = end+1;
2351 } else {
2352 dump = FROM_LATIN1(p, strlen(p));
2353 p += strlen(p);
2355 MemoryDump* md = new MemoryDump;
2356 md->address = addr;
2357 md->dump = dump;
2358 memdump.append(md);
2361 return QString();
2364 QString GdbDriver::editableValue(VarTree* value)
2366 const char* s = value->m_value.latin1();
2368 // if the variable is a pointer value that contains a cast,
2369 // remove the cast
2370 if (*s == '(') {
2371 skipNested(s, '(', ')');
2372 // skip space
2373 while (isspace(*s))
2374 ++s;
2377 repeat:
2378 const char* start = s;
2380 if (strncmp(s, "0x", 2) == 0)
2382 s += 2;
2383 while (isxdigit(*s))
2384 ++s;
2387 * What we saw so far might have been a reference. If so, edit the
2388 * referenced value. Otherwise, edit the pointer.
2390 if (*s == ':') {
2391 // a reference
2392 ++s;
2393 goto repeat;
2395 // a pointer
2396 // if it's a pointer to a string, remove the string
2397 const char* end = s;
2398 while (isspace(*s))
2399 ++s;
2400 if (*s == '"') {
2401 // a string
2402 return FROM_LATIN1(start, end-start);
2403 } else {
2404 // other pointer
2405 return FROM_LATIN1(start, strlen(start));
2409 // else leave it unchanged (or stripped of the reference preamble)
2410 return s;
2413 QString GdbDriver::parseSetVariable(const char* output)
2415 // if there is any output, it is an error message
2416 QString msg = output;
2417 return msg.stripWhiteSpace();
2421 #include "gdbdriver.moc"