Workaround for Fedora Core + gdb 5.3 error, where no executable can be loaded.
[kdbg.git] / kdbg / gdbdriver.cpp
blob9d9ed7c962aa7a38b394c8037059c27e37c32ca9
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 *)
1107 const char*p = s;
1109 // check for type
1110 QString type;
1111 if (*p == '(') {
1112 skipNested(p, '(', ')');
1114 while (isspace(*p))
1115 p++;
1116 variable->m_value = FROM_LATIN1(s, p - s);
1119 bool reference = false;
1120 if (*p == '@') {
1121 // skip reference marker
1122 p++;
1123 reference = true;
1125 const char* start = p;
1126 if (*p == '-')
1127 p++;
1129 // some values consist of more than one token
1130 bool checkMultiPart = false;
1132 if (p[0] == '0' && p[1] == 'x') {
1133 // parse hex number
1134 p += 2;
1135 while (isxdigit(*p))
1136 p++;
1139 * Assume this is a pointer, but only if it's not a reference, since
1140 * references can't be expanded.
1142 if (!reference) {
1143 variable->m_varKind = VarTree::VKpointer;
1144 } else {
1146 * References are followed by a colon, in which case we'll
1147 * find the value following the reference address.
1149 if (*p == ':') {
1150 p++;
1151 } else {
1152 // Paranoia. (Can this happen, i.e. reference not followed by ':'?)
1153 reference = false;
1156 checkMultiPart = true;
1157 } else if (isdigit(*p)) {
1158 // parse decimal number, possibly a float
1159 while (isdigit(*p))
1160 p++;
1161 if (*p == '.') { /* TODO: obey i18n? */
1162 // fractional part
1163 p++;
1164 while (isdigit(*p))
1165 p++;
1167 if (*p == 'e' || *p == 'E') {
1168 p++;
1169 // exponent
1170 if (*p == '-' || *p == '+')
1171 p++;
1172 while (isdigit(*p))
1173 p++;
1176 // for char variables there is the char, eg. 10 '\n'
1177 checkMultiPart = true;
1178 } else if (*p == '<') {
1179 // e.g. <optimized out>
1180 skipNested(p, '<', '>');
1181 } else if (*p == '"' || *p == '\'') {
1182 // character may have multipart: '\000' <repeats 11 times>
1183 checkMultiPart = *p == '\'';
1184 // found a string
1185 skipString(p);
1186 } else if (*p == '&') {
1187 // function pointer
1188 p++;
1189 skipName(p);
1190 while (isspace(*p)) {
1191 p++;
1193 if (*p == '(') {
1194 skipNested(p, '(', ')');
1196 } else {
1197 // must be an enumeration value
1198 skipName(p);
1200 variable->m_value += FROM_LATIN1(start, p - start);
1202 if (checkMultiPart) {
1203 // white space
1204 while (isspace(*p))
1205 p++;
1206 // may be followed by a string or <...>
1207 start = p;
1209 if (*p == '"' || *p == '\'') {
1210 skipString(p);
1211 } else if (*p == '<') {
1212 // if this value is part of an array, it might be followed
1213 // by <repeats 15 times>, which we don't skip here
1214 if (strncmp(p, "<repeats ", 9) != 0)
1215 skipNested(p, '<', '>');
1217 if (p != start) {
1218 // there is always a blank before the string,
1219 // which we will include in the final string value
1220 variable->m_value += FROM_LATIN1(start-1, (p - start)+1);
1221 // if this was a pointer, reset that flag since we
1222 // now got the value
1223 variable->m_varKind = VarTree::VKsimple;
1227 if (variable->m_value.length() == 0) {
1228 TRACE("parse error: no value for " + variable->getText());
1229 return false;
1232 // final white space
1233 while (isspace(*p))
1234 p++;
1235 s = p;
1238 * If this was a reference, the value follows. It might even be a
1239 * composite variable!
1241 if (reference) {
1242 goto repeat;
1245 if (variable->m_varKind == VarTree::VKpointer) {
1246 variable->setDelayedExpanding(true);
1250 return true;
1253 static bool parseNested(const char*& s, VarTree* variable)
1255 // could be a structure or an array
1256 while (isspace(*s))
1257 s++;
1259 const char* p = s;
1260 bool isStruct = false;
1262 * If there is a name followed by an = or an < -- which starts a type
1263 * name -- or "static", it is a structure
1265 if (*p == '<' || *p == '}') {
1266 isStruct = true;
1267 } else if (strncmp(p, "static ", 7) == 0) {
1268 isStruct = true;
1269 } else if (isalpha(*p) || *p == '_' || *p == '$') {
1270 // look ahead for a comma after the name
1271 skipName(p);
1272 while (isspace(*p))
1273 p++;
1274 if (*p == '=') {
1275 isStruct = true;
1277 p = s; /* rescan the name */
1279 if (isStruct) {
1280 if (!parseVarSeq(p, variable)) {
1281 return false;
1283 variable->m_varKind = VarTree::VKstruct;
1284 } else {
1285 if (!parseValueSeq(p, variable)) {
1286 return false;
1288 variable->m_varKind = VarTree::VKarray;
1290 s = p;
1291 return true;
1294 static bool parseVarSeq(const char*& s, VarTree* variable)
1296 // parse a comma-separated sequence of variables
1297 VarTree* var = variable; /* var != 0 to indicate success if empty seq */
1298 for (;;) {
1299 if (*s == '}')
1300 break;
1301 if (strncmp(s, "<No data fields>}", 17) == 0)
1303 // no member variables, so break out immediately
1304 s += 16; /* go to the closing brace */
1305 break;
1307 var = parseVar(s);
1308 if (var == 0)
1309 break; /* syntax error */
1310 variable->appendChild(var);
1311 if (*s != ',')
1312 break;
1313 // skip the comma and whitespace
1314 s++;
1315 while (isspace(*s))
1316 s++;
1318 return var != 0;
1321 static bool parseValueSeq(const char*& s, VarTree* variable)
1323 // parse a comma-separated sequence of variables
1324 int index = 0;
1325 bool good;
1326 for (;;) {
1327 QString name;
1328 name.sprintf("[%d]", index);
1329 VarTree* var = new VarTree(name, VarTree::NKplain);
1330 var->setDeleteChildren(true);
1331 good = parseValue(s, var);
1332 if (!good) {
1333 delete var;
1334 return false;
1336 // a value may be followed by "<repeats 45 times>"
1337 if (strncmp(s, "<repeats ", 9) == 0) {
1338 s += 9;
1339 char* end;
1340 int l = strtol(s, &end, 10);
1341 if (end == s || strncmp(end, " times>", 7) != 0) {
1342 // should not happen
1343 delete var;
1344 return false;
1346 TRACE(QString().sprintf("found <repeats %d times> in array", l));
1347 // replace name and advance index
1348 name.sprintf("[%d .. %d]", index, index+l-1);
1349 var->setText(name);
1350 index += l;
1351 // skip " times>" and space
1352 s = end+7;
1353 // possible final space
1354 while (isspace(*s))
1355 s++;
1356 } else {
1357 index++;
1359 variable->appendChild(var);
1360 if (*s != ',') {
1361 break;
1363 // skip the comma and whitespace
1364 s++;
1365 while (isspace(*s))
1366 s++;
1367 // sometimes there is a closing brace after a comma
1368 // if (*s == '}')
1369 // break;
1371 return true;
1375 * Parses a stack frame.
1377 static void parseFrameInfo(const char*& s, QString& func,
1378 QString& file, int& lineNo, DbgAddr& address)
1380 const char* p = s;
1382 // next may be a hexadecimal address
1383 if (*p == '0') {
1384 const char* start = p;
1385 p++;
1386 if (*p == 'x')
1387 p++;
1388 while (isxdigit(*p))
1389 p++;
1390 address = FROM_LATIN1(start, p-start);
1391 if (strncmp(p, " in ", 4) == 0)
1392 p += 4;
1393 } else {
1394 address = DbgAddr();
1396 const char* start = p;
1397 // check for special signal handler frame
1398 if (strncmp(p, "<signal handler called>", 23) == 0) {
1399 func = FROM_LATIN1(start, 23);
1400 file = QString();
1401 lineNo = -1;
1402 s = p+23;
1403 if (*s == '\n')
1404 s++;
1405 return;
1407 // search opening parenthesis
1408 while (*p != '\0' && *p != '(')
1409 p++;
1410 if (*p == '\0') {
1411 func = start;
1412 file = QString();
1413 lineNo = -1;
1414 s = p;
1415 return;
1418 * Skip parameters. But notice that for complicated conversion
1419 * functions (eg. "operator int(**)()()", ie. convert to pointer to
1420 * pointer to function) as well as operator()(...) we have to skip
1421 * additional pairs of parentheses. Furthermore, recent gdbs write the
1422 * demangled name followed by the arguments in a pair of parentheses,
1423 * where the demangled name can end in "const".
1425 do {
1426 skipNestedWithString(p, '(', ')');
1427 while (isspace(*p))
1428 p++;
1429 // skip "const"
1430 if (strncmp(p, "const", 5) == 0) {
1431 p += 5;
1432 while (isspace(*p))
1433 p++;
1435 } while (*p == '(');
1437 // check for file position
1438 if (strncmp(p, "at ", 3) == 0) {
1439 p += 3;
1440 const char* fileStart = p;
1441 // go for the end of the line
1442 while (*p != '\0' && *p != '\n')
1443 p++;
1444 // search back for colon
1445 const char* colon = p;
1446 do {
1447 --colon;
1448 } while (*colon != ':');
1449 file = FROM_LATIN1(fileStart, colon-fileStart);
1450 lineNo = atoi(colon+1)-1;
1451 // skip new-line
1452 if (*p != '\0')
1453 p++;
1454 } else {
1455 // check for "from shared lib"
1456 if (strncmp(p, "from ", 5) == 0) {
1457 p += 5;
1458 // go for the end of the line
1459 while (*p != '\0' && *p != '\n')
1460 p++;
1461 // skip new-line
1462 if (*p != '\0')
1463 p++;
1465 file = "";
1466 lineNo = -1;
1468 // construct the function name (including file info)
1469 if (*p == '\0') {
1470 func = start;
1471 } else {
1472 func = FROM_LATIN1(start, p-start-1); /* don't include \n */
1474 s = p;
1477 * Replace \n (and whitespace around it) in func by a blank. We cannot
1478 * use QString::simplifyWhiteSpace() for this because this would also
1479 * simplify space that belongs to a string arguments that gdb sometimes
1480 * prints in the argument lists of the function.
1482 ASSERT(!isspace(func[0].latin1())); /* there must be non-white before first \n */
1483 int nl = 0;
1484 while ((nl = func.find('\n', nl)) >= 0) {
1485 // search back to the beginning of the whitespace
1486 int startWhite = nl;
1487 do {
1488 --startWhite;
1489 } while (isspace(func[startWhite].latin1()));
1490 startWhite++;
1491 // search forward to the end of the whitespace
1492 do {
1493 nl++;
1494 } while (isspace(func[nl].latin1()));
1495 // replace
1496 func.replace(startWhite, nl-startWhite, " ");
1497 /* continue searching for more \n's at this place: */
1498 nl = startWhite+1;
1504 * Parses a stack frame including its frame number
1506 static bool parseFrame(const char*& s, int& frameNo, QString& func,
1507 QString& file, int& lineNo, DbgAddr& address)
1509 // Example:
1510 // #1 0x8048881 in Dl::Dl (this=0xbffff418, r=3214) at testfile.cpp:72
1511 // Breakpoint 3, Cl::f(int) const (this=0xbffff3c0, x=17) at testfile.cpp:155
1513 // must start with a hash mark followed by number
1514 // or with "Breakpoint " followed by number and comma
1515 if (s[0] == '#') {
1516 if (!isdigit(s[1]))
1517 return false;
1518 s++; /* skip the hash mark */
1519 } else if (strncmp(s, "Breakpoint ", 11) == 0) {
1520 if (!isdigit(s[11]))
1521 return false;
1522 s += 11; /* skip "Breakpoint" */
1523 } else
1524 return false;
1526 // frame number
1527 frameNo = atoi(s);
1528 while (isdigit(*s))
1529 s++;
1530 // space and comma
1531 while (isspace(*s) || *s == ',')
1532 s++;
1533 parseFrameInfo(s, func, file, lineNo, address);
1534 return true;
1537 void GdbDriver::parseBackTrace(const char* output, QList<StackFrame>& stack)
1539 QString func, file;
1540 int lineNo, frameNo;
1541 DbgAddr address;
1543 while (::parseFrame(output, frameNo, func, file, lineNo, address)) {
1544 StackFrame* frm = new StackFrame;
1545 frm->frameNo = frameNo;
1546 frm->fileName = file;
1547 frm->lineNo = lineNo;
1548 frm->address = address;
1549 frm->var = new VarTree(func, VarTree::NKplain);
1550 stack.append(frm);
1554 bool GdbDriver::parseFrameChange(const char* output, int& frameNo,
1555 QString& file, int& lineNo, DbgAddr& address)
1557 QString func;
1558 return ::parseFrame(output, frameNo, func, file, lineNo, address);
1562 bool GdbDriver::parseBreakList(const char* output, QList<Breakpoint>& brks)
1564 // skip first line, which is the headline
1565 const char* p = strchr(output, '\n');
1566 if (p == 0)
1567 return false;
1568 p++;
1569 if (*p == '\0')
1570 return false;
1572 // split up a line
1573 QString location;
1574 QString address;
1575 int hits = 0;
1576 uint ignoreCount = 0;
1577 QString condition;
1578 const char* end;
1579 char* dummy;
1580 while (*p != '\0') {
1581 // get Num
1582 long bpNum = strtol(p, &dummy, 10); /* don't care about overflows */
1583 p = dummy;
1584 // get Type
1585 while (isspace(*p))
1586 p++;
1587 Breakpoint::Type bpType = Breakpoint::breakpoint;
1588 if (strncmp(p, "breakpoint", 10) == 0) {
1589 p += 10;
1590 } else if (strncmp(p, "hw watchpoint", 13) == 0) {
1591 bpType = Breakpoint::watchpoint;
1592 p += 13;
1593 } else if (strncmp(p, "watchpoint", 10) == 0) {
1594 bpType = Breakpoint::watchpoint;
1595 p += 10;
1597 while (isspace(*p))
1598 p++;
1599 if (*p == '\0')
1600 break;
1601 // get Disp
1602 char disp = *p++;
1603 while (*p != '\0' && !isspace(*p)) /* "keep" or "del" */
1604 p++;
1605 while (isspace(*p))
1606 p++;
1607 if (*p == '\0')
1608 break;
1609 // get Enb
1610 char enable = *p++;
1611 while (*p != '\0' && !isspace(*p)) /* "y" or "n" */
1612 p++;
1613 while (isspace(*p))
1614 p++;
1615 if (*p == '\0')
1616 break;
1617 // the address, if present
1618 if (bpType == Breakpoint::breakpoint &&
1619 strncmp(p, "0x", 2) == 0)
1621 const char* start = p;
1622 while (*p != '\0' && !isspace(*p))
1623 p++;
1624 address = FROM_LATIN1(start, p-start);
1625 while (isspace(*p) && *p != '\n')
1626 p++;
1627 if (*p == '\0')
1628 break;
1629 } else {
1630 address = QString();
1632 // remainder is location, hit and ignore count, condition
1633 hits = 0;
1634 ignoreCount = 0;
1635 condition = QString();
1636 end = strchr(p, '\n');
1637 if (end == 0) {
1638 location = p;
1639 p += location.length();
1640 } else {
1641 location = FROM_LATIN1(p, end-p).stripWhiteSpace();
1642 p = end+1; /* skip over \n */
1645 // may be continued in next line
1646 while (isspace(*p)) { /* p points to beginning of line */
1647 // skip white space at beginning of line
1648 while (isspace(*p))
1649 p++;
1651 // seek end of line
1652 end = strchr(p, '\n');
1653 if (end == 0)
1654 end = p+strlen(p);
1656 if (strncmp(p, "breakpoint already hit", 22) == 0) {
1657 // extract the hit count
1658 p += 22;
1659 hits = strtol(p, &dummy, 10);
1660 TRACE(QString().sprintf("hit count %d", hits));
1661 } else if (strncmp(p, "stop only if ", 13) == 0) {
1662 // extract condition
1663 p += 13;
1664 condition = FROM_LATIN1(p, end-p).stripWhiteSpace();
1665 TRACE("condition: "+condition);
1666 } else if (strncmp(p, "ignore next ", 12) == 0) {
1667 // extract ignore count
1668 p += 12;
1669 ignoreCount = strtol(p, &dummy, 10);
1670 TRACE(QString().sprintf("ignore count %d", ignoreCount));
1671 } else {
1672 // indeed a continuation
1673 location += " " + FROM_LATIN1(p, end-p).stripWhiteSpace();
1675 p = end;
1676 if (*p != '\0')
1677 p++; /* skip '\n' */
1679 Breakpoint* bp = new Breakpoint;
1680 bp->id = bpNum;
1681 bp->type = bpType;
1682 bp->temporary = disp == 'd';
1683 bp->enabled = enable == 'y';
1684 bp->location = location;
1685 bp->address = address;
1686 bp->hitCount = hits;
1687 bp->ignoreCount = ignoreCount;
1688 bp->condition = condition;
1689 brks.append(bp);
1691 return true;
1694 bool GdbDriver::parseThreadList(const char* output, QList<ThreadInfo>& threads)
1696 if (strcmp(output, "\n") == 0 || strncmp(output, "No stack.", 9) == 0) {
1697 // no threads
1698 return true;
1701 int id;
1702 QString systag;
1703 QString func, file;
1704 int lineNo;
1705 DbgAddr address;
1707 const char* p = output;
1708 while (*p != '\0') {
1709 // seach look for thread id, watching out for the focus indicator
1710 bool hasFocus = false;
1711 while (isspace(*p)) /* may be \n from prev line: see "No stack" below */
1712 p++;
1713 if (*p == '*') {
1714 hasFocus = true;
1715 p++;
1716 // there follows only whitespace
1718 char* end;
1719 id = strtol(p, &end, 10);
1720 if (p == end) {
1721 // syntax error: no number found; bail out
1722 return true;
1724 p = end;
1726 // skip space
1727 while (isspace(*p))
1728 p++;
1731 * Now follows the thread's SYSTAG. It is terminated by two blanks.
1733 end = strstr(p, " ");
1734 if (end == 0) {
1735 // syntax error; bail out
1736 return true;
1738 systag = FROM_LATIN1(p, end-p);
1739 p = end+2;
1742 * Now follows a standard stack frame. Sometimes, however, gdb
1743 * catches a thread at an instant where it doesn't have a stack.
1745 if (strncmp(p, "[No stack.]", 11) != 0) {
1746 ::parseFrameInfo(p, func, file, lineNo, address);
1747 } else {
1748 func = "[No stack]";
1749 file = QString();
1750 lineNo = -1;
1751 address = QString();
1752 p += 11; /* \n is skipped above */
1755 ThreadInfo* thr = new ThreadInfo;
1756 thr->id = id;
1757 thr->threadName = systag;
1758 thr->hasFocus = hasFocus;
1759 thr->function = func;
1760 thr->fileName = file;
1761 thr->lineNo = lineNo;
1762 thr->address = address;
1763 threads.append(thr);
1765 return true;
1768 static bool parseNewBreakpoint(const char* o, int& id,
1769 QString& file, int& lineNo, QString& address);
1770 static bool parseNewWatchpoint(const char* o, int& id,
1771 QString& expr);
1773 bool GdbDriver::parseBreakpoint(const char* output, int& id,
1774 QString& file, int& lineNo, QString& address)
1776 const char* o = output;
1777 // skip lines of that begin with "(Cannot find"
1778 while (strncmp(o, "(Cannot find", 12) == 0) {
1779 o = strchr(o, '\n');
1780 if (o == 0)
1781 return false;
1782 o++; /* skip newline */
1785 if (strncmp(o, "Breakpoint ", 11) == 0) {
1786 output += 11; /* skip "Breakpoint " */
1787 return ::parseNewBreakpoint(output, id, file, lineNo, address);
1788 } else if (strncmp(o, "Hardware watchpoint ", 20) == 0) {
1789 output += 20;
1790 return ::parseNewWatchpoint(output, id, address);
1791 } else if (strncmp(o, "Watchpoint ", 11) == 0) {
1792 output += 11;
1793 return ::parseNewWatchpoint(output, id, address);
1795 return false;
1798 static bool parseNewBreakpoint(const char* o, int& id,
1799 QString& file, int& lineNo, QString& address)
1801 // breakpoint id
1802 char* p;
1803 id = strtoul(o, &p, 10);
1804 if (p == o)
1805 return false;
1807 // check for the address
1808 if (strncmp(p, " at 0x", 6) == 0) {
1809 char* start = p+4; /* skip " at ", but not 0x */
1810 p += 6;
1811 while (isxdigit(*p))
1812 ++p;
1813 address = FROM_LATIN1(start, p-start);
1816 // file name
1817 char* fileStart = strstr(p, "file ");
1818 if (fileStart == 0)
1819 return !address.isEmpty(); /* parse error only if there's no address */
1820 fileStart += 5;
1822 // line number
1823 char* numStart = strstr(fileStart, ", line ");
1824 QString fileName = FROM_LATIN1(fileStart, numStart-fileStart);
1825 numStart += 7;
1826 int line = strtoul(numStart, &p, 10);
1827 if (numStart == p)
1828 return false;
1830 file = fileName;
1831 lineNo = line-1; /* zero-based! */
1832 return true;
1835 static bool parseNewWatchpoint(const char* o, int& id,
1836 QString& expr)
1838 // watchpoint id
1839 char* p;
1840 id = strtoul(o, &p, 10);
1841 if (p == o)
1842 return false;
1844 if (strncmp(p, ": ", 2) != 0)
1845 return false;
1846 p += 2;
1848 // all the rest on the line is the expression
1849 expr = FROM_LATIN1(p, strlen(p)).stripWhiteSpace();
1850 return true;
1853 void GdbDriver::parseLocals(const char* output, QList<VarTree>& newVars)
1855 // check for possible error conditions
1856 if (strncmp(output, "No symbol table", 15) == 0)
1858 return;
1861 while (*output != '\0') {
1862 while (isspace(*output))
1863 output++;
1864 if (*output == '\0')
1865 break;
1866 // skip occurrences of "No locals" and "No args"
1867 if (strncmp(output, "No locals", 9) == 0 ||
1868 strncmp(output, "No arguments", 12) == 0)
1870 output = strchr(output, '\n');
1871 if (output == 0) {
1872 break;
1874 continue;
1877 VarTree* variable = parseVar(output);
1878 if (variable == 0) {
1879 break;
1881 // do not add duplicates
1882 for (VarTree* o = newVars.first(); o != 0; o = newVars.next()) {
1883 if (o->getText() == variable->getText()) {
1884 delete variable;
1885 goto skipDuplicate;
1888 newVars.append(variable);
1889 skipDuplicate:;
1893 bool GdbDriver::parsePrintExpr(const char* output, bool wantErrorValue, VarTree*& var)
1895 // check for error conditions
1896 if (parseErrorMessage(output, var, wantErrorValue))
1898 return false;
1899 } else {
1900 // parse the variable
1901 var = parseVar(output);
1902 return true;
1906 bool GdbDriver::parseChangeWD(const char* output, QString& message)
1908 bool isGood = false;
1909 message = QString(output).simplifyWhiteSpace();
1910 if (message.isEmpty()) {
1911 message = i18n("New working directory: ") + m_programWD;
1912 isGood = true;
1914 return isGood;
1917 bool GdbDriver::parseChangeExecutable(const char* output, QString& message)
1919 message = output;
1921 m_haveCoreFile = false;
1924 * The command is successful if there is no output or the single
1925 * message (no debugging symbols found) or
1926 * (Using host libthread_db library "/lib/tls/libthread_db.so.1".)
1928 return
1929 output[0] == '\0' ||
1930 strcmp(output, "(no debugging symbols found)...") == 0 ||
1931 strncmp(output, "Using host libthread_db library", 31) == 0;
1934 bool GdbDriver::parseCoreFile(const char* output)
1936 // if command succeeded, gdb emits a line starting with "#0 "
1937 m_haveCoreFile = strstr(output, "\n#0 ") != 0;
1938 return m_haveCoreFile;
1941 uint GdbDriver::parseProgramStopped(const char* output, QString& message)
1943 // optionally: "program changed, rereading symbols",
1944 // followed by:
1945 // "Program exited normally"
1946 // "Program terminated with wignal SIGSEGV"
1947 // "Program received signal SIGINT" or other signal
1948 // "Breakpoint..."
1950 // go through the output, line by line, checking what we have
1951 const char* start = output - 1;
1952 uint flags = SFprogramActive;
1953 message = QString();
1954 do {
1955 start++; /* skip '\n' */
1957 if (strncmp(start, "Program ", 8) == 0 ||
1958 strncmp(start, "ptrace: ", 8) == 0) {
1960 * When we receive a signal, the program remains active.
1962 * Special: If we "stopped" in a corefile, the string "Program
1963 * terminated with signal"... is displayed. (Normally, we see
1964 * "Program received signal"... when a signal happens.)
1966 if (strncmp(start, "Program exited", 14) == 0 ||
1967 (strncmp(start, "Program terminated", 18) == 0 && !m_haveCoreFile) ||
1968 strncmp(start, "ptrace: ", 8) == 0)
1970 flags &= ~SFprogramActive;
1973 // set message
1974 const char* endOfMessage = strchr(start, '\n');
1975 if (endOfMessage == 0)
1976 endOfMessage = start + strlen(start);
1977 message = FROM_LATIN1(start, endOfMessage-start);
1978 } else if (strncmp(start, "Breakpoint ", 11) == 0) {
1980 * We stopped at a (permanent) breakpoint (gdb doesn't tell us
1981 * that it stopped at a temporary breakpoint).
1983 flags |= SFrefreshBreak;
1984 } else if (strstr(start, "re-reading symbols.") != 0) {
1985 flags |= SFrefreshSource;
1988 // next line, please
1989 start = strchr(start, '\n');
1990 } while (start != 0);
1993 * Gdb only notices when new threads have appeared, but not when a
1994 * thread finishes. So we always have to assume that the list of
1995 * threads has changed.
1997 flags |= SFrefreshThreads;
1999 return flags;
2002 void GdbDriver::parseSharedLibs(const char* output, QStrList& shlibs)
2004 if (strncmp(output, "No shared libraries loaded", 26) == 0)
2005 return;
2007 // parse the table of shared libraries
2009 // strip off head line
2010 output = strchr(output, '\n');
2011 if (output == 0)
2012 return;
2013 output++; /* skip '\n' */
2014 QString shlibName;
2015 while (*output != '\0') {
2016 // format of a line is
2017 // 0x404c5000 0x40580d90 Yes /lib/libc.so.5
2018 // 3 blocks of non-space followed by space
2019 for (int i = 0; *output != '\0' && i < 3; i++) {
2020 while (*output != '\0' && !isspace(*output)) { /* non-space */
2021 output++;
2023 while (isspace(*output)) { /* space */
2024 output++;
2027 if (*output == '\0')
2028 return;
2029 const char* start = output;
2030 output = strchr(output, '\n');
2031 if (output == 0)
2032 output = start + strlen(start);
2033 shlibName = FROM_LATIN1(start, output-start);
2034 if (*output != '\0')
2035 output++;
2036 shlibs.append(shlibName);
2037 TRACE("found shared lib " + shlibName);
2041 bool GdbDriver::parseFindType(const char* output, QString& type)
2043 if (strncmp(output, "type = ", 7) != 0)
2044 return false;
2047 * Everything else is the type. We strip off all white-space from the
2048 * type.
2050 output += 7;
2051 type = output;
2052 type.replace(QRegExp("\\s+"), "");
2053 return true;
2056 void GdbDriver::parseRegisters(const char* output, QList<RegisterInfo>& regs)
2058 if (strncmp(output, "The program has no registers now", 32) == 0) {
2059 return;
2062 QString regName;
2063 QString value;
2065 // parse register values
2066 while (*output != '\0')
2068 // skip space at the start of the line
2069 while (isspace(*output))
2070 output++;
2072 // register name
2073 const char* start = output;
2074 while (*output != '\0' && !isspace(*output))
2075 output++;
2076 if (*output == '\0')
2077 break;
2078 regName = FROM_LATIN1(start, output-start);
2080 // skip space
2081 while (isspace(*output))
2082 output++;
2084 RegisterInfo* reg = new RegisterInfo;
2085 reg->regName = regName;
2088 * If we find a brace now, this is a vector register. We look for
2089 * the closing brace and treat the result as cooked value.
2091 if (*output == '{')
2093 start = output;
2094 skipNested(output, '{', '}');
2095 value = FROM_LATIN1(start, output-start).simplifyWhiteSpace();
2096 // skip space, but not the end of line
2097 while (isspace(*output) && *output != '\n')
2098 output++;
2099 // get rid of the braces at the begining and the end
2100 value.remove(0, 1);
2101 if (value[value.length()-1] == '}') {
2102 value = value.left(value.length()-1);
2104 // gdb 5.3 doesn't print a separate set of raw values
2105 if (*output == '{') {
2106 // another set of vector follows
2107 // what we have so far is the raw value
2108 reg->rawValue = value;
2110 start = output;
2111 skipNested(output, '{', '}');
2112 value = FROM_LATIN1(start, output-start).simplifyWhiteSpace();
2113 } else {
2114 // for gdb 5.3
2115 // find first type that does not have an array, this is the RAW value
2116 const char* end=start;
2117 findEnd(end);
2118 const char* cur=start;
2119 while (cur<end) {
2120 while (*cur != '=' && cur<end)
2121 cur++;
2122 cur++;
2123 while (isspace(*cur) && cur<end)
2124 cur++;
2125 if (isNumberish(*cur)) {
2126 end=cur;
2127 while (*end && (*end!='}') && (*end!=',') && (*end!='\n'))
2128 end++;
2129 QString rawValue = FROM_LATIN1(cur, end-cur).simplifyWhiteSpace();
2130 reg->rawValue = rawValue;
2132 if (rawValue.left(2)=="0x") {
2133 // ok we have a raw value, now get it's type
2134 end=cur-1;
2135 while (isspace(*end) || *end=='=') end--;
2136 end++;
2137 cur=end-1;
2138 while (*cur!='{' && *cur!=' ')
2139 cur--;
2140 cur++;
2141 reg->type=FROM_LATIN1(cur, end-cur);
2144 // end while loop
2145 cur=end;
2148 // skip to the end of line
2149 while (*output != '\0' && *output != '\n')
2150 output++;
2151 // get rid of the braces at the begining and the end
2152 value.remove(0, 1);
2153 if (value[value.length()-1] == '}') {
2154 value = value.left(value.length()-1);
2157 reg->cookedValue = value;
2159 else
2161 // the rest of the line is the register value
2162 start = output;
2163 output = strchr(output,'\n');
2164 if (output == 0)
2165 output = start + strlen(start);
2166 value = FROM_LATIN1(start, output-start).simplifyWhiteSpace();
2169 * We split the raw from the cooked values. For this purpose,
2170 * we split off the first token (separated by whitespace). It
2171 * is the raw value. The remainder of the line is the cooked
2172 * value.
2174 int pos = value.find(' ');
2175 if (pos < 0) {
2176 reg->rawValue = value;
2177 reg->cookedValue = QString();
2178 } else {
2179 reg->rawValue = value.left(pos);
2180 reg->cookedValue = value.mid(pos+1);
2182 * Some modern gdbs explicitly say: "0.1234 (raw 0x3e4567...)".
2183 * Here the raw value is actually in the second part.
2185 if (reg->cookedValue.left(5) == "(raw ") {
2186 QString raw = reg->cookedValue.right(reg->cookedValue.length()-5);
2187 if (raw[raw.length()-1] == ')') /* remove closing bracket */
2188 raw = raw.left(raw.length()-1);
2189 reg->cookedValue = reg->rawValue;
2190 reg->rawValue = raw;
2194 if (*output != '\0')
2195 output++; /* skip '\n' */
2197 regs.append(reg);
2201 bool GdbDriver::parseInfoLine(const char* output, QString& addrFrom, QString& addrTo)
2203 // "is at address" or "starts at address"
2204 const char* start = strstr(output, "s at address ");
2205 if (start == 0)
2206 return false;
2208 start += 13;
2209 const char* p = start;
2210 while (*p != '\0' && !isspace(*p))
2211 p++;
2212 addrFrom = FROM_LATIN1(start, p-start);
2214 start = strstr(p, "and ends at ");
2215 if (start == 0) {
2216 addrTo = addrFrom;
2217 return true;
2220 start += 12;
2221 p = start;
2222 while (*p != '\0' && !isspace(*p))
2223 p++;
2224 addrTo = FROM_LATIN1(start, p-start);
2226 return true;
2229 void GdbDriver::parseDisassemble(const char* output, QList<DisassembledCode>& code)
2231 code.clear();
2233 if (strncmp(output, "Dump of assembler", 17) != 0) {
2234 // error message?
2235 DisassembledCode c;
2236 c.code = output;
2237 code.append(new DisassembledCode(c));
2238 return;
2241 // remove first line
2242 const char* p = strchr(output, '\n');
2243 if (p == 0)
2244 return; /* not a regular output */
2246 p++;
2248 // remove last line
2249 const char* end = strstr(output, "End of assembler");
2250 if (end == 0)
2251 end = p + strlen(p);
2253 DbgAddr address;
2255 // remove function offsets from the lines
2256 while (p != end)
2258 const char* start = p;
2259 // address
2260 while (p != end && !isspace(*p))
2261 p++;
2262 address = FROM_LATIN1(start, p-start);
2264 // function name (enclosed in '<>', followed by ':')
2265 while (p != end && *p != '<')
2266 p++;
2267 if (*p == '<')
2268 skipNested(p, '<', '>');
2269 if (*p == ':')
2270 p++;
2272 // space until code
2273 while (p != end && isspace(*p))
2274 p++;
2276 // code until end of line
2277 start = p;
2278 while (p != end && *p != '\n')
2279 p++;
2280 if (p != end) /* include '\n' */
2281 p++;
2283 DisassembledCode* c = new DisassembledCode;
2284 c->address = address;
2285 c->code = FROM_LATIN1(start, p-start);
2286 code.append(c);
2290 QString GdbDriver::parseMemoryDump(const char* output, QList<MemoryDump>& memdump)
2292 if (isErrorExpr(output)) {
2293 // error; strip space
2294 QString msg = output;
2295 return msg.stripWhiteSpace();
2298 const char* p = output; /* save typing */
2299 DbgAddr addr;
2300 QString dump;
2302 // the address
2303 while (*p != 0) {
2304 const char* start = p;
2305 while (*p != '\0' && *p != ':' && !isspace(*p))
2306 p++;
2307 addr = FROM_LATIN1(start, p-start);
2308 if (*p != ':') {
2309 // parse function offset
2310 while (isspace(*p))
2311 p++;
2312 start = p;
2313 while (*p != '\0' && !(*p == ':' && isspace(p[1])))
2314 p++;
2315 addr.fnoffs = FROM_LATIN1(start, p-start);
2317 if (*p == ':')
2318 p++;
2319 // skip space; this may skip a new-line char!
2320 while (isspace(*p))
2321 p++;
2322 // everything to the end of the line is the memory dump
2323 const char* end = strchr(p, '\n');
2324 if (end != 0) {
2325 dump = FROM_LATIN1(p, end-p);
2326 p = end+1;
2327 } else {
2328 dump = FROM_LATIN1(p, strlen(p));
2329 p += strlen(p);
2331 MemoryDump* md = new MemoryDump;
2332 md->address = addr;
2333 md->dump = dump;
2334 memdump.append(md);
2337 return QString();
2340 QString GdbDriver::editableValue(VarTree* value)
2342 const char* s = value->m_value.latin1();
2344 // if the variable is a pointer value that contains a cast,
2345 // remove the cast
2346 if (*s == '(') {
2347 skipNested(s, '(', ')');
2348 // skip space
2349 while (isspace(*s))
2350 ++s;
2353 repeat:
2354 const char* start = s;
2356 if (strncmp(s, "0x", 2) == 0)
2358 s += 2;
2359 while (isxdigit(*s))
2360 ++s;
2363 * What we saw so far might have been a reference. If so, edit the
2364 * referenced value. Otherwise, edit the pointer.
2366 if (*s == ':') {
2367 // a reference
2368 ++s;
2369 goto repeat;
2371 // a pointer
2372 // if it's a pointer to a string, remove the string
2373 const char* end = s;
2374 while (isspace(*s))
2375 ++s;
2376 if (*s == '"') {
2377 // a string
2378 return FROM_LATIN1(start, end-start);
2379 } else {
2380 // other pointer
2381 return FROM_LATIN1(start, strlen(start));
2385 // else leave it unchanged (or stripped of the reference preamble)
2386 return s;
2389 QString GdbDriver::parseSetVariable(const char* output)
2391 // if there is any output, it is an error message
2392 QString msg = output;
2393 return msg.stripWhiteSpace();
2397 #include "gdbdriver.moc"