2 * Copyright Johannes Sixt
3 * This file is licensed under the GNU General Public License Version 2.
4 * See the file COPYING in the toplevel directory of the source directory.
11 #include <QStringList>
12 #include <klocale.h> /* i18n */
15 #include <stdlib.h> /* strtol, atoi */
16 #include <string.h> /* strcpy */
21 static void skipString(const char*& p
);
22 static void skipNested(const char*& s
, char opening
, char closing
);
23 static ExprValue
* parseVar(const char*& s
);
24 static bool parseName(const char*& s
, QString
& name
, VarTree::NameKind
& kind
);
25 static bool parseValue(const char*& s
, ExprValue
* variable
);
26 static bool parseNested(const char*& s
, ExprValue
* variable
);
27 static bool parseVarSeq(const char*& s
, ExprValue
* variable
);
28 static bool parseValueSeq(const char*& s
, ExprValue
* variable
);
30 #define PROMPT "(kdbg)"
33 // TODO: make this cmd info stuff non-static to allow multiple
34 // simultaneous gdbs to run!
38 const char* fmt
; /* format string */
40 argNone
, argString
, argNum
,
41 argStringNum
, argNumString
,
47 // This is how the QString data print statement generally looks like.
48 // It is set by KDebugger via setPrintQStringDataCmd().
50 static const char printQStringStructFmt
[] =
51 // if the string data is junk, fail early
52 "print ($qstrunicode=($qstrdata=(%s))->unicode)?"
53 // print an array of shorts
54 "(*(unsigned short*)$qstrunicode)@"
56 "(($qstrlen=(unsigned int)($qstrdata->len))>100?100:$qstrlen)"
57 // if unicode data is 0, report a special value
60 static const char printQStringStructFmt
[] = "print (0?\"%s\":$kdbgundef)\n";
63 * The following array of commands must be sorted by the DC* values,
64 * because they are used as indices.
66 static GdbCmdInfo cmds
[] = {
67 { DCinitialize
, "", GdbCmdInfo::argNone
},
68 { DCtty
, "tty %s\n", GdbCmdInfo::argString
},
69 { DCexecutable
, "file \"%s\"\n", GdbCmdInfo::argString
},
70 { DCtargetremote
, "target remote %s\n", GdbCmdInfo::argString
},
72 { DCcorefile
, "target FreeBSD-core %s\n", GdbCmdInfo::argString
},
74 { DCcorefile
, "target core %s\n", GdbCmdInfo::argString
},
76 { DCattach
, "attach %s\n", GdbCmdInfo::argString
},
77 { DCinfolinemain
, "kdbg_infolinemain\n", GdbCmdInfo::argNone
},
78 { DCinfolocals
, "kdbg__alllocals\n", GdbCmdInfo::argNone
},
79 { DCinforegisters
, "info all-registers\n", GdbCmdInfo::argNone
},
80 { DCexamine
, "x %s %s\n", GdbCmdInfo::argString2
},
81 { DCinfoline
, "info line %s:%d\n", GdbCmdInfo::argStringNum
},
82 { DCdisassemble
, "disassemble %s %s\n", GdbCmdInfo::argString2
},
83 { DCsetargs
, "set args %s\n", GdbCmdInfo::argString
},
84 { DCsetenv
, "set env %s %s\n", GdbCmdInfo::argString2
},
85 { DCunsetenv
, "unset env %s\n", GdbCmdInfo::argString
},
86 { DCsetoption
, "setoption %s %d\n", GdbCmdInfo::argStringNum
},
87 { DCcd
, "cd %s\n", GdbCmdInfo::argString
},
88 { DCbt
, "bt\n", GdbCmdInfo::argNone
},
89 { DCrun
, "run\n", GdbCmdInfo::argNone
},
90 { DCcont
, "cont\n", GdbCmdInfo::argNone
},
91 { DCstep
, "step\n", GdbCmdInfo::argNone
},
92 { DCstepi
, "stepi\n", GdbCmdInfo::argNone
},
93 { DCnext
, "next\n", GdbCmdInfo::argNone
},
94 { DCnexti
, "nexti\n", GdbCmdInfo::argNone
},
95 { DCfinish
, "finish\n", GdbCmdInfo::argNone
},
96 { DCuntil
, "until %s:%d\n", GdbCmdInfo::argStringNum
},
97 { DCkill
, "kill\n", GdbCmdInfo::argNone
},
98 { DCbreaktext
, "break %s\n", GdbCmdInfo::argString
},
99 { DCbreakline
, "break %s:%d\n", GdbCmdInfo::argStringNum
},
100 { DCtbreakline
, "tbreak %s:%d\n", GdbCmdInfo::argStringNum
},
101 { DCbreakaddr
, "break *%s\n", GdbCmdInfo::argString
},
102 { DCtbreakaddr
, "tbreak *%s\n", GdbCmdInfo::argString
},
103 { DCwatchpoint
, "watch %s\n", GdbCmdInfo::argString
},
104 { DCdelete
, "delete %d\n", GdbCmdInfo::argNum
},
105 { DCenable
, "enable %d\n", GdbCmdInfo::argNum
},
106 { DCdisable
, "disable %d\n", GdbCmdInfo::argNum
},
107 { DCprint
, "print %s\n", GdbCmdInfo::argString
},
108 { DCprintDeref
, "print *(%s)\n", GdbCmdInfo::argString
},
109 { DCprintStruct
, "print %s\n", GdbCmdInfo::argString
},
110 { DCprintQStringStruct
, printQStringStructFmt
, GdbCmdInfo::argString
},
111 { DCframe
, "frame %d\n", GdbCmdInfo::argNum
},
112 { DCfindType
, "whatis %s\n", GdbCmdInfo::argString
},
113 { DCinfosharedlib
, "info sharedlibrary\n", GdbCmdInfo::argNone
},
114 { DCthread
, "thread %d\n", GdbCmdInfo::argNum
},
115 { DCinfothreads
, "info threads\n", GdbCmdInfo::argNone
},
116 { DCinfobreak
, "info breakpoints\n", GdbCmdInfo::argNone
},
117 { DCcondition
, "condition %d %s\n", GdbCmdInfo::argNumString
},
118 { DCsetpc
, "set variable $pc=%s\n", GdbCmdInfo::argString
},
119 { DCignore
, "ignore %d %d\n", GdbCmdInfo::argNum2
},
120 { DCprintWChar
, "print ($s=%s)?*$s@wcslen($s):0x0\n", GdbCmdInfo::argString
},
121 { DCsetvariable
, "set variable %s=%s\n", GdbCmdInfo::argString2
},
124 #define NUM_CMDS (int(sizeof(cmds)/sizeof(cmds[0])))
125 #define MAX_FMTLEN 200
127 GdbDriver::GdbDriver() :
131 // check command info array
133 for (int i
= 0; i
< NUM_CMDS
; i
++) {
134 // must be indexable by DbgCommand values, i.e. sorted by DbgCommand values
135 assert(i
== cmds
[i
].cmd
);
136 // a format string must be associated
137 assert(cmds
[i
].fmt
!= 0);
138 assert(strlen(cmds
[i
].fmt
) <= MAX_FMTLEN
);
139 // format string must match arg specification
140 switch (cmds
[i
].argsNeeded
) {
141 case GdbCmdInfo::argNone
:
142 assert(strchr(cmds
[i
].fmt
, '%') == 0);
144 case GdbCmdInfo::argString
:
145 perc
= strchr(cmds
[i
].fmt
, '%');
146 assert(perc
!= 0 && perc
[1] == 's');
147 assert(strchr(perc
+2, '%') == 0);
149 case GdbCmdInfo::argNum
:
150 perc
= strchr(cmds
[i
].fmt
, '%');
151 assert(perc
!= 0 && perc
[1] == 'd');
152 assert(strchr(perc
+2, '%') == 0);
154 case GdbCmdInfo::argStringNum
:
155 perc
= strchr(cmds
[i
].fmt
, '%');
156 assert(perc
!= 0 && perc
[1] == 's');
157 perc
= strchr(perc
+2, '%');
158 assert(perc
!= 0 && perc
[1] == 'd');
159 assert(strchr(perc
+2, '%') == 0);
161 case GdbCmdInfo::argNumString
:
162 perc
= strchr(cmds
[i
].fmt
, '%');
163 assert(perc
!= 0 && perc
[1] == 'd');
164 perc
= strchr(perc
+2, '%');
165 assert(perc
!= 0 && perc
[1] == 's');
166 assert(strchr(perc
+2, '%') == 0);
168 case GdbCmdInfo::argString2
:
169 perc
= strchr(cmds
[i
].fmt
, '%');
170 assert(perc
!= 0 && perc
[1] == 's');
171 perc
= strchr(perc
+2, '%');
172 assert(perc
!= 0 && perc
[1] == 's');
173 assert(strchr(perc
+2, '%') == 0);
175 case GdbCmdInfo::argNum2
:
176 perc
= strchr(cmds
[i
].fmt
, '%');
177 assert(perc
!= 0 && perc
[1] == 'd');
178 perc
= strchr(perc
+2, '%');
179 assert(perc
!= 0 && perc
[1] == 'd');
180 assert(strchr(perc
+2, '%') == 0);
184 assert(strlen(printQStringStructFmt
) <= MAX_FMTLEN
);
188 GdbDriver::~GdbDriver()
193 QString
GdbDriver::driverName() const
198 QString
GdbDriver::defaultGdb()
202 " --fullname" /* to get standard file names each time the prog stops */
203 " --nx"; /* do not execute initialization files */
206 QString
GdbDriver::defaultInvocation() const
208 if (m_defaultCmd
.isEmpty()) {
215 QStringList
GdbDriver::boolOptionList() const
218 return QStringList();
221 bool GdbDriver::startup(QString cmdStr
)
223 if (!DebuggerDriver::startup(cmdStr
))
226 static const char gdbInitialize
[] =
228 * Work around buggy gdbs that do command line editing even if they
229 * are not on a tty. The readline library echos every command back
230 * in this case, which is confusing for us.
234 "set print static-members off\n"
235 "set print asm-demangle on\n"
237 * Sometimes, gdb prints [New Thread ...] during 'info threads';
238 * we will not look at thread events anyway, so turn them off.
240 "set print thread-events off\n"
242 * We do not want Python pretty printer support, because their
243 * output is unpredictable, and we cannot parse it.
245 "set auto-load python off\n"
247 * Nevertheless, some Python messages get through, for example,
248 * when a backtrace is printed without the Python gdb module loaded.
250 "set python print-stack none\n"
252 * Don't assume that program functions invoked from a watch expression
255 "set unwindonsignal on\n"
257 * Write a short macro that prints all locals: local variables and
258 * function arguments.
260 "define kdbg__alllocals\n"
261 "info locals\n" /* local vars supersede args with same name */
262 "info args\n" /* therefore, arguments must come last */
265 * Work around a bug in gdb-6.3: "info line main" crashes gdb.
267 "define kdbg_infolinemain\n"
271 // change prompt string and synchronize with gdb
272 "set prompt " PROMPT
"\n"
275 executeCmdString(DCinitialize
, gdbInitialize
, false);
277 // assume that QString::null is ok
278 cmds
[DCprintQStringStruct
].fmt
= printQStringStructFmt
;
283 void GdbDriver::commandFinished(CmdQueueItem
* cmd
)
285 // command string must be committed
286 if (!cmd
->m_committed
) {
288 TRACE("calling " + (__PRETTY_FUNCTION__
+ (" with uncommited command:\n\t" +
293 switch (cmd
->m_cmd
) {
297 * Check for GDB 7.1 or later; the syntax for the disassemble
298 * command has changed.
299 * This RE picks the last version number in the first line,
300 * because at least OpenSUSE writes its own version number
301 * in the first line (but before GDB's version number).
304 " " // must be preceded by space
305 "[(]?" // SLES 10 embeds in parentheses
306 "(\\d+)\\.(\\d+)" // major, minor
307 "[^ ]*\\n" // no space until end of line
309 int pos
= re
.indexIn(m_output
);
310 const char* disass
= "disassemble %s %s\n";
312 int major
= re
.cap(1).toInt();
313 int minor
= re
.cap(2).toInt();
314 if (major
> 7 || (major
== 7 && minor
>= 1))
316 disass
= "disassemble %s, %s\n";
319 cmds
[DCdisassemble
].fmt
= disass
;
325 /* ok, the command is ready */
326 emit
commandReceived(cmd
, m_output
.constData());
328 switch (cmd
->m_cmd
) {
347 int GdbDriver::findPrompt(const QByteArray
& output
) const
350 * If there's a prompt string in the collected output, it must be at
353 * Note: It could nevertheless happen that a character sequence that is
354 * equal to the prompt string appears at the end of the output,
355 * although it is very, very unlikely (namely as part of a string that
356 * lingered in gdb's output buffer due to some timing/heavy load
357 * conditions for a very long time such that that buffer overflowed
358 * exactly at the end of the prompt string look-a-like).
360 int len
= output
.length();
361 if (len
>= PROMPT_LEN
&&
362 strncmp(output
.data()+len
-PROMPT_LEN
, PROMPT
, PROMPT_LEN
) == 0)
364 return len
-PROMPT_LEN
;
370 * The --fullname option makes gdb send a special normalized sequence print
371 * each time the program stops and at some other points. The sequence has
372 * the form "\032\032filename:lineno:charoffset:(beg|middle):address".
374 void GdbDriver::parseMarker(CmdQueueItem
* cmd
)
376 char* startMarker
= strstr(m_output
.data(), "\032\032");
377 if (startMarker
== 0)
380 // extract the marker
382 TRACE(QString("found marker: ") + startMarker
);
383 char* endMarker
= strchr(startMarker
, '\n');
389 // extract filename and line number
390 static QRegExp
MarkerRE(":(\\d+):\\d+:[begmidl]+:0x");
392 int lineNoStart
= MarkerRE
.indexIn(startMarker
);
393 if (lineNoStart
>= 0) {
394 int lineNo
= MarkerRE
.cap(1).toInt();
396 // get address unless there is one in cmd
397 DbgAddr address
= cmd
->m_addr
;
398 if (address
.isEmpty()) {
399 const char* addrStart
= startMarker
+ lineNoStart
+
400 MarkerRE
.matchedLength() - 2;
401 address
= QString(addrStart
).trimmed();
404 // now show the window
405 startMarker
[lineNoStart
] = '\0'; /* split off file name */
406 emit
activateFileLine(startMarker
, lineNo
-1, address
);
412 * Escapes characters that might lead to problems when they appear on gdb's
415 static void normalizeStringArg(QString
& arg
)
418 * Remove trailing backslashes. This approach is a little simplistic,
419 * but we know that there is at the moment no case where a trailing
420 * backslash would make sense.
422 while (!arg
.isEmpty() && arg
[arg
.length()-1] == '\\') {
423 arg
= arg
.left(arg
.length()-1);
428 QString
GdbDriver::makeCmdString(DbgCommand cmd
, QString strArg
)
430 assert(cmd
>= 0 && cmd
< NUM_CMDS
);
431 assert(cmds
[cmd
].argsNeeded
== GdbCmdInfo::argString
);
433 normalizeStringArg(strArg
);
436 // need the working directory when parsing the output
437 m_programWD
= strArg
;
438 } else if (cmd
== DCsetargs
&& !m_redirect
.isEmpty()) {
440 * Use saved redirection. We prepend it in front of the user's
441 * arguments so that the user can override the redirections.
443 strArg
= m_redirect
+ " " + strArg
;
447 cmdString
.sprintf(cmds
[cmd
].fmt
, strArg
.toUtf8().constData());
451 QString
GdbDriver::makeCmdString(DbgCommand cmd
, int intArg
)
453 assert(cmd
>= 0 && cmd
< NUM_CMDS
);
454 assert(cmds
[cmd
].argsNeeded
== GdbCmdInfo::argNum
);
457 cmdString
.sprintf(cmds
[cmd
].fmt
, intArg
);
461 QString
GdbDriver::makeCmdString(DbgCommand cmd
, QString strArg
, int intArg
)
463 assert(cmd
>= 0 && cmd
< NUM_CMDS
);
464 assert(cmds
[cmd
].argsNeeded
== GdbCmdInfo::argStringNum
||
465 cmds
[cmd
].argsNeeded
== GdbCmdInfo::argNumString
||
469 normalizeStringArg(strArg
);
476 * intArg specifies which channels should be redirected to
477 * /dev/null. It is a value or'ed together from RDNstdin,
478 * RDNstdout, RDNstderr. We store the value for a later DCsetargs
481 * Note: We rely on that after the DCtty a DCsetargs will follow,
482 * which will ultimately apply the redirection.
484 static const char* const runRedir
[8] = {
488 "</dev/null >/dev/null",
490 "</dev/null 2>/dev/null",
492 "</dev/null >/dev/null 2>&1"
494 if (strArg
.isEmpty())
495 intArg
= 7; /* failsafe if no tty */
496 m_redirect
= runRedir
[intArg
& 7];
498 return makeCmdString(DCtty
, strArg
); /* note: no problem if strArg empty */
501 if (cmd
== DCexamine
) {
502 // make a format specifier from the intArg
503 static const char size
[16] = {
504 '\0', 'b', 'h', 'w', 'g'
506 static const char format
[16] = {
507 '\0', 'x', 'd', 'u', 'o', 't',
508 'a', 'c', 'f', 's', 'i'
510 assert(MDTsizemask
== 0xf); /* lowest 4 bits */
511 assert(MDTformatmask
== 0xf0); /* next 4 bits */
512 int count
= 16; /* number of entities to print */
513 char sizeSpec
= size
[intArg
& MDTsizemask
];
514 char formatSpec
= format
[(intArg
& MDTformatmask
) >> 4];
515 assert(sizeSpec
!= '\0');
516 assert(formatSpec
!= '\0');
517 // adjust count such that 16 lines are printed
518 switch (intArg
& MDTformatmask
) {
519 case MDTstring
: case MDTinsn
:
520 break; /* no modification needed */
522 // all cases drop through:
523 switch (intArg
& MDTsizemask
) {
535 spec
.sprintf("/%d%c%c", count
, sizeSpec
, formatSpec
);
537 return makeCmdString(DCexamine
, spec
, strArg
);
540 if (cmds
[cmd
].argsNeeded
== GdbCmdInfo::argStringNum
)
542 // line numbers are zero-based
543 if (cmd
== DCuntil
|| cmd
== DCbreakline
||
544 cmd
== DCtbreakline
|| cmd
== DCinfoline
)
548 if (cmd
== DCinfoline
)
550 // must split off file name part
551 strArg
= QFileInfo(strArg
).fileName();
553 cmdString
.sprintf(cmds
[cmd
].fmt
, strArg
.toUtf8().constData(), intArg
);
557 cmdString
.sprintf(cmds
[cmd
].fmt
, intArg
, strArg
.toUtf8().constData());
562 QString
GdbDriver::makeCmdString(DbgCommand cmd
, QString strArg1
, QString strArg2
)
564 assert(cmd
>= 0 && cmd
< NUM_CMDS
);
565 assert(cmds
[cmd
].argsNeeded
== GdbCmdInfo::argString2
);
567 normalizeStringArg(strArg1
);
568 normalizeStringArg(strArg2
);
571 cmdString
.sprintf(cmds
[cmd
].fmt
,
572 strArg1
.toUtf8().constData(),
573 strArg2
.toUtf8().constData());
577 QString
GdbDriver::makeCmdString(DbgCommand cmd
, int intArg1
, int intArg2
)
579 assert(cmd
>= 0 && cmd
< NUM_CMDS
);
580 assert(cmds
[cmd
].argsNeeded
== GdbCmdInfo::argNum2
);
583 cmdString
.sprintf(cmds
[cmd
].fmt
, intArg1
, intArg2
);
587 CmdQueueItem
* GdbDriver::executeCmd(DbgCommand cmd
, bool clearLow
)
589 assert(cmd
>= 0 && cmd
< NUM_CMDS
);
590 assert(cmds
[cmd
].argsNeeded
== GdbCmdInfo::argNone
);
593 m_haveCoreFile
= false;
596 return executeCmdString(cmd
, cmds
[cmd
].fmt
, clearLow
);
599 CmdQueueItem
* GdbDriver::executeCmd(DbgCommand cmd
, QString strArg
,
602 return executeCmdString(cmd
, makeCmdString(cmd
, strArg
), clearLow
);
605 CmdQueueItem
* GdbDriver::executeCmd(DbgCommand cmd
, int intArg
,
609 return executeCmdString(cmd
, makeCmdString(cmd
, intArg
), clearLow
);
612 CmdQueueItem
* GdbDriver::executeCmd(DbgCommand cmd
, QString strArg
, int intArg
,
615 return executeCmdString(cmd
, makeCmdString(cmd
, strArg
, intArg
), clearLow
);
618 CmdQueueItem
* GdbDriver::executeCmd(DbgCommand cmd
, QString strArg1
, QString strArg2
,
621 return executeCmdString(cmd
, makeCmdString(cmd
, strArg1
, strArg2
), clearLow
);
624 CmdQueueItem
* GdbDriver::executeCmd(DbgCommand cmd
, int intArg1
, int intArg2
,
627 return executeCmdString(cmd
, makeCmdString(cmd
, intArg1
, intArg2
), clearLow
);
630 CmdQueueItem
* GdbDriver::queueCmd(DbgCommand cmd
, QueueMode mode
)
632 return queueCmdString(cmd
, cmds
[cmd
].fmt
, mode
);
635 CmdQueueItem
* GdbDriver::queueCmd(DbgCommand cmd
, QString strArg
,
638 return queueCmdString(cmd
, makeCmdString(cmd
, strArg
), mode
);
641 CmdQueueItem
* GdbDriver::queueCmd(DbgCommand cmd
, int intArg
,
644 return queueCmdString(cmd
, makeCmdString(cmd
, intArg
), mode
);
647 CmdQueueItem
* GdbDriver::queueCmd(DbgCommand cmd
, QString strArg
, int intArg
,
650 return queueCmdString(cmd
, makeCmdString(cmd
, strArg
, intArg
), mode
);
653 CmdQueueItem
* GdbDriver::queueCmd(DbgCommand cmd
, QString strArg1
, QString strArg2
,
656 return queueCmdString(cmd
, makeCmdString(cmd
, strArg1
, strArg2
), mode
);
659 void GdbDriver::terminate()
661 if (m_state
!= DSidle
)
663 ::kill(pid(), SIGINT
);
664 m_state
= DSinterrupted
;
670 void GdbDriver::detachAndTerminate()
672 ::kill(pid(), SIGINT
);
674 executeCmdString(DCinitialize
, "detach\nquit\n", true);
677 void GdbDriver::interruptInferior()
679 ::kill(pid(), SIGINT
);
680 // remove accidentally queued commands
684 static bool isErrorExpr(const char* output
)
687 strncmp(output
, "Cannot access memory at", 23) == 0 ||
688 strncmp(output
, "Attempt to dereference a generic pointer", 40) == 0 ||
689 strncmp(output
, "Attempt to take contents of ", 28) == 0 ||
690 strncmp(output
, "Attempt to use a type name as an expression", 43) == 0 ||
691 strncmp(output
, "There is no member or method named", 34) == 0 ||
692 strncmp(output
, "A parse error in expression", 27) == 0 ||
693 strncmp(output
, "No symbol \"", 11) == 0 ||
694 strncmp(output
, "Internal error: ", 16) == 0;
698 * Returns true if the output is an error message. If wantErrorValue is
699 * true, a new ExprValue object is created and filled with the error message.
700 * If there are warnings, they are skipped and output points past the warnings
701 * on return (even if there \e are errors).
703 static bool parseErrorMessage(const char*& output
,
704 ExprValue
*& variable
, bool wantErrorValue
)
706 while (isspace(*output
))
710 while (strncmp(output
, "warning:", 8) == 0)
712 const char* end
= strchr(output
+8, '\n');
714 output
+= strlen(output
);
717 while (isspace(*output
))
721 if (isErrorExpr(output
))
723 if (wantErrorValue
) {
724 // put the error message as value in the variable
725 variable
= new ExprValue(QString(), VarTree::NKplain
);
726 const char* endMsg
= strchr(output
, '\n');
728 endMsg
= output
+ strlen(output
);
729 variable
->m_value
= QString::fromLatin1(output
, endMsg
-output
);
738 #if QT_VERSION >= 300
748 void GdbDriver::setPrintQStringDataCmd(const char* cmd
)
750 // don't accept the command if it is empty
751 if (cmd
== 0 || *cmd
== '\0')
753 assert(strlen(cmd
) <= MAX_FMTLEN
);
754 cmds
[DCprintQStringStruct
].fmt
= cmd
;
757 ExprValue
* GdbDriver::parseQCharArray(const char* output
, bool wantErrorValue
, bool qt3like
)
759 ExprValue
* variable
= 0;
762 * Parse off white space. gdb sometimes prints white space first if the
763 * printed array leaded to an error.
765 while (isspace(*output
))
768 // special case: empty string (0 repetitions)
769 if (strncmp(output
, "Invalid number 0 of repetitions", 31) == 0)
771 variable
= new ExprValue(QString(), VarTree::NKplain
);
772 variable
->m_value
= "\"\"";
776 // check for error conditions
777 if (parseErrorMessage(output
, variable
, wantErrorValue
))
783 const char* p
= output
;
791 } while (isspace(*p
));
795 // this is the real data
801 enum { wasNothing
, wasChar
, wasRepeat
} lastThing
= wasNothing
;
803 * A matrix for separators between the individual "things"
804 * that are added to the string. The first index is a bool,
805 * the second index is from the enum above.
807 static const char* separator
[2][3] = {
808 { "\"", 0, ", \"" }, /* normal char is added */
809 { "'", "\", '", ", '" } /* repeated char is added */
812 while (isdigit(*p
)) {
815 unsigned short value
= (unsigned short) strtoul(p
, &end
, 0);
817 goto error
; /* huh? no valid digits */
818 // skip separator and search for a repeat count
820 while (isspace(*p
) || *p
== ',')
822 bool repeats
= strncmp(p
, "<repeats ", 9) == 0;
824 const char* start
= p
;
825 p
= strchr(p
+9, '>'); /* search end and advance */
829 repeatCount
= QString::fromLatin1(start
, p
-start
);
830 while (isspace(*p
) || *p
== ',')
833 // p is now at the next char (or the end)
835 // interpret the value as a QChar
836 // TODO: make cross-architecture compatible
842 (unsigned short&)ch
= value
;
846 ch
.setRow(c
.qch
.row
);
847 ch
.setCell(c
.qch
.cell
);
851 // escape a few frequently used characters
852 char escapeCode
= '\0';
853 switch (ch
.toLatin1()) {
854 case '\n': escapeCode
= 'n'; break;
855 case '\r': escapeCode
= 'r'; break;
856 case '\t': escapeCode
= 't'; break;
857 case '\b': escapeCode
= 'b'; break;
858 case '\"': escapeCode
= '\"'; break;
859 case '\\': escapeCode
= '\\'; break;
860 case '\0': if (value
== 0) { escapeCode
= '0'; } break;
864 result
+= separator
[repeats
][lastThing
];
866 if (escapeCode
!= '\0') {
872 // fixup repeat count and lastThing
875 result
+= repeatCount
;
876 lastThing
= wasRepeat
;
885 if (lastThing
== wasChar
)
889 variable
= new ExprValue(QString(), VarTree::NKplain
);
890 variable
->m_value
= result
;
892 else if (strncmp(p
, "true", 4) == 0)
894 variable
= new ExprValue(QString(), VarTree::NKplain
);
895 variable
->m_value
= "QString::null";
897 else if (strncmp(p
, "false", 5) == 0)
899 variable
= new ExprValue(QString(), VarTree::NKplain
);
900 variable
->m_value
= "(null)";
907 if (wantErrorValue
) {
908 variable
= new ExprValue(QString(), VarTree::NKplain
);
909 variable
->m_value
= "internal parse error";
914 static ExprValue
* parseVar(const char*& s
)
923 VarTree::NameKind kind
;
925 * Detect anonymouse struct values: The 'name =' part is missing:
926 * s = { a = 1, { b = 2 }}
927 * Note that this detection works only inside structs when the anonymous
928 * struct is not the first member:
929 * s = {{ a = 1 }, b = 2}
930 * This is misparsed (by parseNested()) because it is mistakenly
931 * interprets the second opening brace as the first element of an array
936 name
= i18n("<anonymous struct or union>");
937 kind
= VarTree::NKanonymous
;
941 if (!parseName(p
, name
, kind
)) {
949 TRACE("parse error: = not found after " + name
);
952 // skip the '=' and more whitespace
958 ExprValue
* variable
= new ExprValue(name
, kind
);
960 if (!parseValue(p
, variable
)) {
968 static void skipNested(const char*& s
, char opening
, char closing
)
972 // parse a nested type
976 * Search for next matching `closing' char, skipping nested pairs of
977 * `opening' and `closing'.
979 while (*p
&& nest
> 0) {
982 } else if (*p
== closing
) {
988 TRACE(QString().sprintf("parse error: mismatching %c%c at %-20.20s", opening
, closing
, s
));
994 * This function skips text that is delimited by nested angle bracktes, '<>'.
995 * A complication arises because the delimited text can contain the names of
996 * operator<<, operator>>, operator<, and operator>, which have to be treated
997 * specially so that they do not count towards the nesting of '<>'.
998 * This function assumes that the delimited text does not contain strings.
1000 static void skipNestedAngles(const char*& s
)
1005 p
++; // skip the initial '<'
1006 while (*p
&& nest
> 0)
1008 // Below we can check for p-s >= 9 instead of 8 because
1009 // *s is '<' and cannot be part of "operator".
1012 if (p
-s
>= 9 && strncmp(p
-8, "operator", 8) == 0) {
1021 if (p
-s
>= 9 && strncmp(p
-8, "operator", 8) == 0) {
1031 TRACE(QString().sprintf("parse error: mismatching <> at %-20.20s", s
));
1037 * Find the end of line that is not inside braces
1039 static void findEnd(const char*& s
)
1042 while (*p
&& *p
!='\n') {
1043 while (*p
&& *p
!='\n' && *p
!='{')
1047 skipNested(p
, '{', '}'); p
--;
1053 static bool isNumberish(const char ch
)
1055 return (ch
>='0' && ch
<='9') || ch
=='.' || ch
=='x';
1058 void skipString(const char*& p
)
1060 // wchar_t strings begin with L
1067 while (*p
!= quote
) {
1069 // skip escaped character
1070 // no special treatment for octal values necessary
1073 // simply return if no more characters
1081 * Strings can consist of several parts, some of which contain repeated
1084 if (quote
== '\'') {
1085 // look ahaead for <repeats 123 times>
1086 const char* q
= p
+1;
1089 if (strncmp(q
, "<repeats ", 9) == 0) {
1091 while (*p
!= '\0' && *p
!= '>')
1094 p
++; /* skip the '>' */
1098 // Is the string continued? If so, there is no L in wchar_t strings
1101 // look ahead for another quote
1102 const char* q
= p
+1;
1105 if (*q
== '"' || *q
== '\'') {
1111 // some strings can end in <incomplete sequence ...>
1112 if (strncmp(q
, "<incomplete sequence", 20) == 0)
1115 while (*p
!= '\0' && *p
!= '>')
1118 p
++; /* skip the '>' */
1123 * There's a bug in gdb where it prints the beginning of the string
1124 * continuation and the comma-blank in the wrong order if the new string
1125 * begins with an incomplete multi-byte character. For now, let's check
1126 * for this in a very narrow condition, particularly, where the next
1127 * character is given in octal notation. Example:
1128 * 'a' <repeats 20 times>"\240, b"
1130 if (*p
== '"' && p
[1] == '\\' && isdigit(p
[2])) {
1132 while (isdigit(p
[i
]))
1134 if (p
[i
] == ',' && p
[i
+1] == ' ') {
1135 // just treat everything beginning at the dquote as string
1139 /* very long strings are followed by `...' */
1140 if (*p
== '.' && p
[1] == '.' && p
[2] == '.') {
1145 static void skipNestedWithString(const char*& s
, char opening
, char closing
)
1149 // parse a nested expression
1153 * Search for next matching `closing' char, skipping nested pairs of
1154 * `opening' and `closing' as well as strings.
1156 while (*p
&& nest
> 0) {
1157 if (*p
== opening
) {
1159 } else if (*p
== closing
) {
1161 } else if (*p
== '\'' || *p
== '\"') {
1168 TRACE(QString().sprintf("parse error: mismatching %c%c at %-20.20s", opening
, closing
, s
));
1173 inline void skipName(const char*& p
)
1175 // allow : (for enumeration values) and $ and . (for _vtbl.)
1176 while (isalnum(*p
) || *p
== '_' || *p
== ':' || *p
== '$' || *p
== '.')
1180 static bool parseName(const char*& s
, QString
& name
, VarTree::NameKind
& kind
)
1182 kind
= VarTree::NKplain
;
1185 // examples of names:
1188 // <string<a,b<c>,7> >
1191 skipNestedAngles(p
);
1192 name
= QString::fromLatin1(s
, p
- s
);
1193 kind
= VarTree::NKtype
;
1197 // name, which might be "static"; allow dot for "_vtbl."
1200 TRACE(QString().sprintf("parse error: not a name %-20.20s", s
));
1204 if (len
== 6 && strncmp(s
, "static", 6) == 0) {
1205 kind
= VarTree::NKstatic
;
1207 // its a static variable, name comes now
1213 TRACE(QString().sprintf("parse error: not a name after static %-20.20s", s
));
1218 name
= QString::fromLatin1(s
, len
);
1220 // return the new position
1225 static bool parseValue(const char*& s
, ExprValue
* variable
)
1227 variable
->m_value
= "";
1231 // Sometimes we find the following output:
1232 // {<text variable, no debug info>} 0x40012000 <access>
1233 // {<data variable, no debug info>}
1234 // {<variable (not text or data), no debug info>}
1235 if (strncmp(s
, "{<text variable, ", 17) == 0 ||
1236 strncmp(s
, "{<data variable, ", 17) == 0 ||
1237 strncmp(s
, "{<variable (not text or data), ", 31) == 0)
1239 const char* start
= s
;
1240 skipNested(s
, '{', '}');
1241 variable
->m_value
= QString::fromLatin1(start
, s
-start
);
1242 variable
->m_value
+= ' '; // add only a single space
1250 if (!parseNested(s
, variable
)) {
1253 // must be the closing brace
1255 TRACE("parse error: missing } of " + variable
->m_name
);
1259 // final white space
1264 // Sometimes we find a warning; it ends at the next LF
1265 else if (strncmp(s
, "warning: ", 9) == 0) {
1266 const char* end
= strchr(s
, '\n');
1267 s
= end
? end
: s
+strlen(s
);
1268 // skip space at start of next line
1273 // examples of leaf values (cannot be the empty string):
1279 // (DwContentType&) @0x8123456: {...}
1283 // 0x823abc <Array<int> virtual table>
1284 // 0x40240f <globarstr> "test"
1285 // (void (*)()) 0x8048480 <f(E *, char)>
1288 // &parseP (HTMLClueV *, char *)
1289 // Variable "x" is not available.
1290 // The value of variable 'x' is distributed...
1291 // -nan(0xfffff081defa0)
1298 skipNested(p
, '(', ')');
1302 variable
->m_value
= QString::fromLatin1(s
, p
- s
);
1305 bool reference
= false;
1307 // skip reference marker
1311 const char* start
= p
;
1315 // some values consist of more than one token
1316 bool checkMultiPart
= false;
1318 if (p
[0] == '0' && p
[1] == 'x') {
1321 while (isxdigit(*p
))
1325 * Assume this is a pointer, but only if it's not a reference, since
1326 * references can't be expanded.
1329 variable
->m_varKind
= VarTree::VKpointer
;
1332 * References are followed by a colon, in which case we'll
1333 * find the value following the reference address.
1338 // Paranoia. (Can this happen, i.e. reference not followed by ':'?)
1342 checkMultiPart
= true;
1343 } else if (isdigit(*p
)) {
1344 // parse decimal number, possibly a float
1347 if (*p
== '.') { /* TODO: obey i18n? */
1348 // In long arrays an integer may be followed by '...'.
1349 // We test for this situation and don't gobble the '...'.
1350 if (p
[1] != '.' || p
[0] != '.') {
1357 if (*p
== 'e' || *p
== 'E') {
1360 if (*p
== '-' || *p
== '+')
1366 // for char variables there is the char, eg. 10 '\n'
1367 checkMultiPart
= true;
1368 } else if (*p
== '<') {
1369 // e.g. <optimized out>
1370 skipNestedAngles(p
);
1371 } else if (*p
== '"' || *p
== '\'') {
1372 // character may have multipart: '\000' <repeats 11 times>
1373 checkMultiPart
= *p
== '\'';
1376 } else if (*p
== 'L' && (p
[1] == '"' || p
[1] == '\'')) {
1377 // ditto for wchar_t strings
1378 checkMultiPart
= p
[1] == '\'';
1380 } else if (*p
== '&') {
1384 while (isspace(*p
)) {
1388 skipNested(p
, '(', ')');
1390 } else if (strncmp(p
, "Variable \"", 10) == 0) {
1391 // Variable "x" is not available.
1392 p
+= 10; // skip to "
1394 if (strncmp(p
, "\" is not available.", 19) == 0) {
1397 } else if (strncmp(p
, "The value of variable '", 23) == 0) {
1400 const char* e
= strchr(p
, '.');
1408 // must be an enumeration value
1410 // nan (floating point Not a Number) is followed by a number in ()
1411 // enum values can look like A::(anonymous namespace)::blue
1413 bool isAnonNS
= strncmp(p
+1, "anonymous namespace)", 20) == 0;
1414 skipNested(p
, '(', ')');
1419 variable
->m_value
+= QString::fromLatin1(start
, p
- start
);
1421 // remove line breaks from the value; this is ok since
1422 // string values never contain a literal line break
1423 variable
->m_value
.replace('\n', ' ');
1425 while (checkMultiPart
) {
1429 // may be followed by a string or <...>
1430 // if this was a pointer with a string,
1431 // reset that pointer flag since we have now a value
1433 checkMultiPart
= false;
1435 if (*p
== '"' || *p
== '\'') {
1437 variable
->m_varKind
= VarTree::VKsimple
;
1438 } else if (*p
== 'L' && (p
[1] == '"' || p
[1] == '\'')) {
1439 skipString(p
); // wchar_t string
1440 variable
->m_varKind
= VarTree::VKsimple
;
1441 } else if (*p
== '<') {
1442 // if this value is part of an array, it might be followed
1443 // by <repeats 15 times>, which we don't skip here
1444 if (strncmp(p
, "<repeats ", 9) != 0) {
1445 skipNestedAngles(p
);
1446 checkMultiPart
= true;
1450 // there is always a blank before the string,
1451 // which we will include in the final string value
1452 variable
->m_value
+= QString::fromLatin1(start
-1, (p
- start
)+1);
1456 if (variable
->m_value
.length() == 0) {
1457 TRACE("parse error: no value for " + variable
->m_name
);
1461 // final white space
1467 * If this was a reference, the value follows. It might even be a
1468 * composite variable!
1478 static bool parseNested(const char*& s
, ExprValue
* variable
)
1480 // could be a structure or an array
1485 bool isStruct
= false;
1487 * If there is a name followed by an = or an < -- which starts a type
1488 * name -- or "static", it is a structure
1490 if (*p
== '<' || *p
== '}') {
1492 } else if (strncmp(p
, "static ", 7) == 0) {
1494 } else if (isalpha(*p
) || *p
== '_' || *p
== '$') {
1495 // look ahead for a comma after the name
1502 p
= s
; /* rescan the name */
1505 if (!parseVarSeq(p
, variable
)) {
1508 variable
->m_varKind
= VarTree::VKstruct
;
1510 if (!parseValueSeq(p
, variable
)) {
1513 variable
->m_varKind
= VarTree::VKarray
;
1519 static bool parseVarSeq(const char*& s
, ExprValue
* variable
)
1521 // parse a comma-separated sequence of variables
1522 ExprValue
* var
= variable
; /* var != 0 to indicate success if empty seq */
1526 if (strncmp(s
, "<No data fields>}", 17) == 0)
1528 // no member variables, so break out immediately
1529 s
+= 16; /* go to the closing brace */
1534 break; /* syntax error */
1535 variable
->appendChild(var
);
1538 // skip the comma and whitespace
1546 static bool parseValueSeq(const char*& s
, ExprValue
* variable
)
1548 // parse a comma-separated sequence of variables
1553 name
.sprintf("[%d]", index
);
1554 ExprValue
* var
= new ExprValue(name
, VarTree::NKplain
);
1555 good
= parseValue(s
, var
);
1560 // a value may be followed by "<repeats 45 times>"
1561 if (strncmp(s
, "<repeats ", 9) == 0) {
1564 int l
= strtol(s
, &end
, 10);
1565 if (end
== s
|| strncmp(end
, " times>", 7) != 0) {
1566 // should not happen
1570 TRACE(QString().sprintf("found <repeats %d times> in array", l
));
1571 // replace name and advance index
1572 name
.sprintf("[%d .. %d]", index
, index
+l
-1);
1575 // skip " times>" and space
1577 // possible final space
1583 variable
->appendChild(var
);
1584 // long arrays may be terminated by '...'
1585 if (strncmp(s
, "...", 3) == 0) {
1587 ExprValue
* var
= new ExprValue("...", VarTree::NKplain
);
1588 var
->m_value
= i18n("<additional entries of the array suppressed>");
1589 variable
->appendChild(var
);
1595 // skip the comma and whitespace
1599 // sometimes there is a closing brace after a comma
1607 * Parses a stack frame.
1609 static void parseFrameInfo(const char*& s
, QString
& func
,
1610 QString
& file
, int& lineNo
, DbgAddr
& address
)
1614 // next may be a hexadecimal address
1616 const char* start
= p
;
1620 while (isxdigit(*p
))
1622 address
= QString::fromLatin1(start
, p
-start
);
1623 if (strncmp(p
, " in ", 4) == 0)
1626 address
= DbgAddr();
1628 const char* start
= p
;
1629 // check for special signal handler frame
1630 if (strncmp(p
, "<signal handler called>", 23) == 0) {
1631 func
= QString::fromLatin1(start
, 23);
1641 * Skip the function name. It is terminated by a left parenthesis
1642 * which does not delimit "(anonymous namespace)" and which is
1643 * outside the angle brackets <> of template parameter lists
1644 * and is preceded by a space.
1649 // check for operator<< and operator<
1650 if (p
-start
>= 8 && strncmp(p
-8, "operator", 8) == 0)
1658 // skip template parameter list
1659 skipNestedAngles(p
);
1661 } else if (*p
== '(') {
1662 // this skips "(anonymous namespace)" as well as the formal
1663 // parameter list of the containing function if this is a member
1664 // of a nested class
1665 skipNestedWithString(p
, '(', ')');
1666 } else if (*p
== ' ') {
1669 break; // parameter list found
1683 * Skip parameters. But notice that for complicated conversion
1684 * functions (eg. "operator int(**)()()", ie. convert to pointer to
1685 * pointer to function) as well as operator()(...) we have to skip
1686 * additional pairs of parentheses. Furthermore, recent gdbs write the
1687 * demangled name followed by the arguments in a pair of parentheses,
1688 * where the demangled name can end in "const".
1691 skipNestedWithString(p
, '(', ')');
1695 if (strncmp(p
, "const", 5) == 0) {
1700 } while (*p
== '(');
1702 // check for file position
1703 if (strncmp(p
, "at ", 3) == 0) {
1705 const char* fileStart
= p
;
1706 // go for the end of the line
1707 while (*p
!= '\0' && *p
!= '\n')
1709 // search back for colon
1710 const char* colon
= p
;
1713 } while (*colon
!= ':');
1714 file
= QString::fromLatin1(fileStart
, colon
-fileStart
);
1715 lineNo
= atoi(colon
+1)-1;
1720 // check for "from shared lib"
1721 if (strncmp(p
, "from ", 5) == 0) {
1723 // go for the end of the line
1724 while (*p
!= '\0' && *p
!= '\n')
1733 // construct the function name (including file info)
1737 func
= QString::fromLatin1(start
, p
-start
-1); /* don't include \n */
1742 * Replace \n (and whitespace around it) in func by a blank. We cannot
1743 * use QString::simplified() for this because this would also
1744 * simplify space that belongs to a string arguments that gdb sometimes
1745 * prints in the argument lists of the function.
1747 ASSERT(!isspace(func
[0].toLatin1())); // there must be non-white before first \n
1749 while ((nl
= func
.indexOf('\n', nl
)) >= 0) {
1750 // search back to the beginning of the whitespace
1751 int startWhite
= nl
;
1754 } while (isspace(func
[startWhite
].toLatin1()));
1756 // search forward to the end of the whitespace
1759 } while (isspace(func
[nl
].toLatin1()));
1761 func
.replace(startWhite
, nl
-startWhite
, " ");
1762 /* continue searching for more \n's at this place: */
1769 * Parses a stack frame including its frame number
1771 static bool parseFrame(const char*& s
, int& frameNo
, QString
& func
,
1772 QString
& file
, int& lineNo
, DbgAddr
& address
)
1775 // #1 0x8048881 in Dl::Dl (this=0xbffff418, r=3214) at testfile.cpp:72
1776 // Breakpoint 3, Cl::f(int) const (this=0xbffff3c0, x=17) at testfile.cpp:155
1778 // must start with a hash mark followed by number
1779 // or with "Breakpoint " followed by number and comma
1783 s
++; /* skip the hash mark */
1784 } else if (strncmp(s
, "Breakpoint ", 11) == 0) {
1785 if (!isdigit(s
[11]))
1787 s
+= 11; /* skip "Breakpoint" */
1796 while (isspace(*s
) || *s
== ',')
1798 parseFrameInfo(s
, func
, file
, lineNo
, address
);
1802 void GdbDriver::parseBackTrace(const char* output
, std::list
<StackFrame
>& stack
)
1805 int lineNo
, frameNo
;
1808 while (::parseFrame(output
, frameNo
, func
, file
, lineNo
, address
)) {
1809 stack
.push_back(StackFrame());
1810 StackFrame
* frm
= &stack
.back();
1811 frm
->frameNo
= frameNo
;
1812 frm
->fileName
= file
;
1813 frm
->lineNo
= lineNo
;
1814 frm
->address
= address
;
1815 frm
->var
= new ExprValue(func
, VarTree::NKplain
);
1819 bool GdbDriver::parseFrameChange(const char* output
, int& frameNo
,
1820 QString
& file
, int& lineNo
, DbgAddr
& address
)
1823 return ::parseFrame(output
, frameNo
, func
, file
, lineNo
, address
);
1827 bool GdbDriver::parseBreakList(const char* output
, std::list
<Breakpoint
>& brks
)
1829 // skip first line, which is the headline
1830 const char* p
= strchr(output
, '\n');
1840 while (*p
!= '\0') {
1843 bp
.id
= strtol(p
, &dummy
, 10); /* don't care about overflows */
1845 // check for continued <MULTIPLE> breakpoint
1846 if (*p
== '.' && isdigit(p
[1]))
1848 // continuation: skip type and disposition
1855 if (strncmp(p
, "breakpoint", 10) == 0) {
1857 } else if (strncmp(p
, "hw watchpoint", 13) == 0) {
1858 bp
.type
= Breakpoint::watchpoint
;
1860 } else if (strncmp(p
, "watchpoint", 10) == 0) {
1861 bp
.type
= Breakpoint::watchpoint
;
1869 bp
.temporary
= *p
++ == 'd';
1871 while (*p
!= '\0' && !isspace(*p
)) /* "keep" or "del" */
1878 bp
.enabled
= *p
++ == 'y';
1879 while (*p
!= '\0' && !isspace(*p
)) /* "y" or "n" */
1885 // the address, if present
1886 if (bp
.type
== Breakpoint::breakpoint
&&
1887 strncmp(p
, "0x", 2) == 0)
1889 const char* start
= p
;
1890 while (*p
!= '\0' && !isspace(*p
))
1892 bp
.address
= QString::fromLatin1(start
, p
-start
);
1893 while (isspace(*p
) && *p
!= '\n')
1898 // remainder is location, hit and ignore count, condition
1899 end
= strchr(p
, '\n');
1902 p
+= bp
.location
.length();
1904 // location of a <MULTIPLE> filled in from subsequent breakpoints
1905 if (strncmp(p
, "<MULTIPLE>", 10) != 0)
1906 bp
.location
= QString::fromLatin1(p
, end
-p
).trimmed();
1907 p
= end
+1; /* skip over \n */
1910 // may be continued in next line
1911 while (isspace(*p
)) { /* p points to beginning of line */
1912 // skip white space at beginning of line
1917 end
= strchr(p
, '\n');
1921 if (strncmp(p
, "breakpoint already hit", 22) == 0) {
1922 // extract the hit count
1924 bp
.hitCount
= strtol(p
, &dummy
, 10);
1925 TRACE(QString("hit count %1").arg(bp
.hitCount
));
1926 } else if (strncmp(p
, "stop only if ", 13) == 0) {
1927 // extract condition
1929 bp
.condition
= QString::fromLatin1(p
, end
-p
).trimmed();
1930 TRACE("condition: "+bp
.condition
);
1931 } else if (strncmp(p
, "ignore next ", 12) == 0) {
1932 // extract ignore count
1934 bp
.ignoreCount
= strtol(p
, &dummy
, 10);
1935 TRACE(QString("ignore count %1").arg(bp
.ignoreCount
));
1937 // indeed a continuation
1938 bp
.location
+= " " + QString::fromLatin1(p
, end
-p
).trimmed();
1942 p
++; /* skip '\n' */
1945 if (brks
.empty() || brks
.back().id
!= bp
.id
) {
1948 // this is a continuation; fill in location if not yet set
1949 // otherwise, drop this breakpoint
1950 Breakpoint
& mbp
= brks
.back();
1951 if (mbp
.location
.isEmpty() && !bp
.location
.isEmpty()) {
1952 mbp
.location
= bp
.location
;
1953 mbp
.address
= bp
.address
;
1954 } else if (mbp
.address
.isEmpty() && !bp
.address
.isEmpty()) {
1955 mbp
.address
= bp
.address
;
1962 std::list
<ThreadInfo
> GdbDriver::parseThreadList(const char* output
)
1964 std::list
<ThreadInfo
> threads
;
1965 if (strcmp(output
, "\n") == 0 ||
1966 strncmp(output
, "No stack.", 9) == 0 ||
1967 strncmp(output
, "No threads.", 11) == 0) {
1972 bool newFormat
= false;
1973 const char* p
= output
;
1974 while (*p
!= '\0') {
1976 // seach look for thread id, watching out for the focus indicator
1977 thr
.hasFocus
= false;
1978 while (isspace(*p
)) /* may be \n from prev line: see "No stack" below */
1981 // recent GDBs write a header line; skip it
1982 if (threads
.empty() && strncmp(p
, "Id Target", 11) == 0) {
1983 p
= strchr(p
, '\n');
1987 continue; // next line please, '\n' is skipped above
1991 thr
.hasFocus
= true;
1993 // there follows only whitespace
1996 char *temp_end
= NULL
; /* we need a non-const 'end' for strtol to use...*/
1997 thr
.id
= strtol(p
, &temp_end
, 10);
2000 // syntax error: no number found; bail out
2010 * Now follows the thread's SYSTAG.
2013 // In the old format, it is terminated by two blanks.
2014 end
= strstr(p
, " ");
2016 // syntax error; bail out
2021 // In the new format lies crazyness: there is no definitive
2022 // end marker. At best we can guess when the SYSTAG ends.
2023 // A typical thread list on Linux looks like this:
2025 // Id Target Id Frame
2026 // 2 Thread 0x7ffff7854700 (LWP 10827) "thrserver" 0x00007ffff7928631 in clone () from /lib64/libc.so.6
2027 // * 1 Thread 0x7ffff7fcc700 (LWP 10808) "thrserver" main () at thrserver.c:84
2029 // Looking at GDB's code, the Target Id ends in tokens that
2030 // are bracketed by parentheses or quotes. Therefore,
2031 // we skip (at most) two tokens ('Thread' and the address),
2032 // and then all parts that are in parentheses or quotes.
2039 } else if (*end
== '(') {
2040 skipNested(end
, '(', ')');
2043 while (*end
&& !isspace(*end
))
2049 while (isspace(*end
))
2053 thr
.threadName
= QString::fromLatin1(p
, end
-p
).trimmed();
2057 * Now follows a standard stack frame. Sometimes, however, gdb
2058 * catches a thread at an instant where it doesn't have a stack.
2060 if (strncmp(p
, "[No stack.]", 11) != 0) {
2061 ::parseFrameInfo(p
, thr
.function
, thr
.fileName
, thr
.lineNo
, thr
.address
);
2063 thr
.function
= "[No stack]";
2065 p
+= 11; /* \n is skipped above */
2068 threads
.push_back(thr
);
2073 static bool parseNewBreakpoint(const char* o
, int& id
,
2074 QString
& file
, int& lineNo
, QString
& address
);
2075 static bool parseNewWatchpoint(const char* o
, int& id
,
2078 bool GdbDriver::parseBreakpoint(const char* output
, int& id
,
2079 QString
& file
, int& lineNo
, QString
& address
)
2081 // skip lines of that begin with "(Cannot find"
2082 while (strncmp(output
, "(Cannot find", 12) == 0 ||
2083 strncmp(output
, "Note: breakpoint", 16) == 0)
2085 output
= strchr(output
, '\n');
2088 output
++; /* skip newline */
2091 if (strncmp(output
, "Breakpoint ", 11) == 0) {
2092 output
+= 11; /* skip "Breakpoint " */
2093 return ::parseNewBreakpoint(output
, id
, file
, lineNo
, address
);
2094 } else if (strncmp(output
, "Temporary breakpoint ", 21) == 0) {
2096 return ::parseNewBreakpoint(output
, id
, file
, lineNo
, address
);
2097 } else if (strncmp(output
, "Hardware watchpoint ", 20) == 0) {
2099 return ::parseNewWatchpoint(output
, id
, address
);
2100 } else if (strncmp(output
, "Watchpoint ", 11) == 0) {
2102 return ::parseNewWatchpoint(output
, id
, address
);
2107 static bool parseNewBreakpoint(const char* o
, int& id
,
2108 QString
& file
, int& lineNo
, QString
& address
)
2112 id
= strtoul(o
, &p
, 10);
2116 // check for the address
2117 if (strncmp(p
, " at 0x", 6) == 0) {
2118 char* start
= p
+4; /* skip " at ", but not 0x */
2120 while (isxdigit(*p
))
2122 address
= QString::fromLatin1(start
, p
-start
);
2126 * Mostly, GDB responds with this syntax:
2128 * Breakpoint 1 at 0x400b94: file multibrkpt.cpp, line 9. (2 locations)
2130 * but sometimes it uses this syntax:
2132 * Breakpoint 4 at 0x804f158: lotto739.cpp:95. (3 locations)
2134 char* fileEnd
, *numStart
= 0;
2135 char* fileStart
= strstr(p
, "file ");
2139 fileEnd
= strstr(fileStart
, ", line ");
2141 numStart
= fileEnd
+ 7;
2143 if (numStart
== 0 && p
[0] == ':' && p
[1] == ' ')
2146 while (isspace(*fileStart
))
2148 fileEnd
= strchr(fileStart
, ':');
2150 numStart
= fileEnd
+ 1;
2153 return !address
.isEmpty(); /* parse error only if there's no address */
2155 QString fileName
= QString::fromLatin1(fileStart
, fileEnd
-fileStart
);
2156 int line
= strtoul(numStart
, &p
, 10);
2161 lineNo
= line
-1; /* zero-based! */
2165 static bool parseNewWatchpoint(const char* o
, int& id
,
2170 id
= strtoul(o
, &p
, 10);
2174 if (strncmp(p
, ": ", 2) != 0)
2178 // all the rest on the line is the expression
2179 expr
= QString::fromLatin1(p
, strlen(p
)).trimmed();
2183 void GdbDriver::parseLocals(const char* output
, std::list
<ExprValue
*>& newVars
)
2185 // check for possible error conditions
2186 if (strncmp(output
, "No symbol table", 15) == 0)
2191 while (*output
!= '\0') {
2192 while (isspace(*output
))
2194 if (*output
== '\0')
2196 // skip occurrences of "No locals" and "No args"
2197 if (strncmp(output
, "No locals", 9) == 0 ||
2198 strncmp(output
, "No arguments", 12) == 0)
2200 output
= strchr(output
, '\n');
2207 ExprValue
* variable
= parseVar(output
);
2208 if (variable
== 0) {
2211 // do not add duplicates
2212 for (std::list
<ExprValue
*>::iterator o
= newVars
.begin(); o
!= newVars
.end(); ++o
) {
2213 if ((*o
)->m_name
== variable
->m_name
) {
2218 newVars
.push_back(variable
);
2223 ExprValue
* GdbDriver::parsePrintExpr(const char* output
, bool wantErrorValue
)
2226 // check for error conditions
2227 if (!parseErrorMessage(output
, var
, wantErrorValue
))
2229 // parse the variable
2230 var
= parseVar(output
);
2235 bool GdbDriver::parseChangeWD(const char* output
, QString
& message
)
2237 bool isGood
= false;
2238 message
= QString(output
).simplified();
2239 if (message
.isEmpty()) {
2240 message
= i18n("New working directory: ") + m_programWD
;
2246 bool GdbDriver::parseChangeExecutable(const char* output
, QString
& message
)
2250 m_haveCoreFile
= false;
2253 * Lines starting with the following do not indicate errors:
2254 * Using host libthread_db
2255 * (no debugging symbols found)
2256 * Reading symbols from
2258 while (strncmp(output
, "Reading symbols from", 20) == 0 ||
2259 strncmp(output
, "done.", 5) == 0 ||
2260 strncmp(output
, "Missing separate debuginfo", 26) == 0 ||
2261 strncmp(output
, "Try: ", 5) == 0 ||
2262 strncmp(output
, "Using host libthread_db", 23) == 0 ||
2263 strncmp(output
, "(no debugging symbols found)", 28) == 0)
2265 // this line is good, go to the next one
2266 const char* end
= strchr(output
, '\n');
2268 output
+= strlen(output
);
2274 * If we've parsed all lines, there was no error.
2276 return output
[0] == '\0';
2279 bool GdbDriver::parseCoreFile(const char* output
)
2281 // if command succeeded, gdb emits a line starting with "#0 "
2282 m_haveCoreFile
= strstr(output
, "\n#0 ") != 0;
2283 return m_haveCoreFile
;
2286 uint
GdbDriver::parseProgramStopped(const char* output
, QString
& message
)
2288 // optionally: "program changed, rereading symbols",
2290 // "Program exited normally"
2291 // "Program terminated with wignal SIGSEGV"
2292 // "Program received signal SIGINT" or other signal
2294 // GDB since 7.3 prints
2295 // "[Inferior 1 (process 13400) exited normally]"
2296 // "[Inferior 1 (process 14698) exited with code 01]"
2298 // go through the output, line by line, checking what we have
2299 const char* start
= output
- 1;
2300 uint flags
= SFprogramActive
;
2301 message
= QString();
2303 start
++; /* skip '\n' */
2305 if (strncmp(start
, "Program ", 8) == 0 ||
2306 strncmp(start
, "ptrace: ", 8) == 0) {
2308 * When we receive a signal, the program remains active.
2310 * Special: If we "stopped" in a corefile, the string "Program
2311 * terminated with signal"... is displayed. (Normally, we see
2312 * "Program received signal"... when a signal happens.)
2314 if (strncmp(start
, "Program exited", 14) == 0 ||
2315 (strncmp(start
, "Program terminated", 18) == 0 && !m_haveCoreFile
) ||
2316 strncmp(start
, "ptrace: ", 8) == 0)
2318 flags
&= ~SFprogramActive
;
2322 const char* endOfMessage
= strchr(start
, '\n');
2323 if (endOfMessage
== 0)
2324 endOfMessage
= start
+ strlen(start
);
2325 message
= QString::fromLatin1(start
, endOfMessage
-start
);
2326 } else if (strncmp(start
, "[Inferior ", 10) == 0) {
2327 const char* p
= start
+ 10;
2328 // skip number and space
2329 while (*p
&& !isspace(*p
))
2334 skipNested(p
, '(', ')');
2335 if (strncmp(p
, " exited ", 8) == 0) {
2336 flags
&= ~SFprogramActive
;
2339 const char* end
= strchr(p
, '\n');
2341 end
= p
+ strlen(p
);
2342 // strip [] from the message
2343 message
= QString::fromLatin1(start
+1, end
-start
-2);
2346 } else if (strncmp(start
, "Breakpoint ", 11) == 0) {
2348 * We stopped at a (permanent) breakpoint (gdb doesn't tell us
2349 * that it stopped at a temporary breakpoint).
2351 flags
|= SFrefreshBreak
;
2352 } else if (strstr(start
, "re-reading symbols.") != 0) {
2353 flags
|= SFrefreshSource
;
2356 // next line, please
2357 start
= strchr(start
, '\n');
2358 } while (start
!= 0);
2361 * Gdb only notices when new threads have appeared, but not when a
2362 * thread finishes. So we always have to assume that the list of
2363 * threads has changed.
2365 flags
|= SFrefreshThreads
;
2370 QStringList
GdbDriver::parseSharedLibs(const char* output
)
2373 if (strncmp(output
, "No shared libraries loaded", 26) == 0)
2376 // parse the table of shared libraries
2378 // strip off head line
2379 output
= strchr(output
, '\n');
2382 output
++; /* skip '\n' */
2384 while (*output
!= '\0') {
2385 // format of a line is
2386 // 0x404c5000 0x40580d90 Yes /lib/libc.so.5
2387 // 3 blocks of non-space followed by space
2388 for (int i
= 0; *output
!= '\0' && i
< 3; i
++) {
2389 while (*output
!= '\0' && !isspace(*output
)) { /* non-space */
2392 while (isspace(*output
)) { /* space */
2396 if (*output
== '\0')
2398 const char* start
= output
;
2399 output
= strchr(output
, '\n');
2401 output
= start
+ strlen(start
);
2402 shlibName
= QString::fromLatin1(start
, output
-start
);
2403 if (*output
!= '\0')
2405 shlibs
.append(shlibName
);
2406 TRACE("found shared lib " + shlibName
);
2411 bool GdbDriver::parseFindType(const char* output
, QString
& type
)
2413 if (strncmp(output
, "type = ", 7) != 0)
2417 * Everything else is the type. We strip off any leading "const" and any
2418 * trailing "&" on the grounds that neither affects the decoding of the
2419 * object. We also strip off all white-space from the type.
2422 if (strncmp(output
, "const ", 6) == 0)
2425 type
.replace(QRegExp("\\s+"), "");
2426 if (type
.endsWith("&"))
2427 type
.truncate(type
.length() - 1);
2431 std::list
<RegisterInfo
> GdbDriver::parseRegisters(const char* output
)
2433 std::list
<RegisterInfo
> regs
;
2434 if (strncmp(output
, "The program has no registers now", 32) == 0) {
2438 // parse register values
2439 while (*output
!= '\0')
2442 // skip space at the start of the line
2443 while (isspace(*output
))
2447 const char* start
= output
;
2448 while (*output
!= '\0' && !isspace(*output
))
2450 if (*output
== '\0')
2452 reg
.regName
= QString::fromLatin1(start
, output
-start
);
2455 while (isspace(*output
))
2461 * If we find a brace now, this is a vector register. We look for
2462 * the closing brace and treat the result as cooked value.
2467 skipNested(output
, '{', '}');
2468 value
= QString::fromLatin1(start
, output
-start
).simplified();
2469 // skip space, but not the end of line
2470 while (isspace(*output
) && *output
!= '\n')
2472 // get rid of the braces at the begining and the end
2474 if (value
[value
.length()-1] == '}') {
2475 value
= value
.left(value
.length()-1);
2477 // gdb 5.3 doesn't print a separate set of raw values
2478 if (*output
== '{') {
2479 // another set of vector follows
2480 // what we have so far is the raw value
2481 reg
.rawValue
= value
;
2484 skipNested(output
, '{', '}');
2485 value
= QString::fromLatin1(start
, output
-start
).simplified();
2488 // find first type that does not have an array, this is the RAW value
2489 const char* end
=start
;
2491 const char* cur
=start
;
2493 while (*cur
!= '=' && cur
<end
)
2496 while (isspace(*cur
) && cur
<end
)
2498 if (isNumberish(*cur
)) {
2500 while (*end
&& (*end
!='}') && (*end
!=',') && (*end
!='\n'))
2502 QString rawValue
= QString::fromLatin1(cur
, end
-cur
).simplified();
2503 reg
.rawValue
= rawValue
;
2505 if (rawValue
.left(2)=="0x") {
2506 // ok we have a raw value, now get it's type
2508 while (isspace(*end
) || *end
=='=') end
--;
2511 while (*cur
!='{' && *cur
!=' ')
2514 reg
.type
= QString::fromLatin1(cur
, end
-cur
);
2521 // skip to the end of line
2522 while (*output
!= '\0' && *output
!= '\n')
2524 // get rid of the braces at the begining and the end
2526 if (value
[value
.length()-1] == '}') {
2527 value
.truncate(value
.length()-1);
2530 reg
.cookedValue
= value
;
2535 // the rest of the line is the register value
2537 output
= strchr(output
,'\n');
2539 output
= start
+ strlen(start
);
2540 value
+= QString::fromLatin1(start
, output
-start
).simplified();
2543 * Look ahead: if the subsequent line is indented, it continues
2544 * the current register value.
2546 if (output
!= 0 && isspace(output
[1]))
2554 * We split the raw from the cooked values.
2555 * Some modern gdbs explicitly say: "0.1234 (raw 0x3e4567...)".
2556 * Here, the cooked value comes first, and the raw value is in
2559 int pos
= value
.indexOf(" (raw ");
2562 reg
.cookedValue
= value
.left(pos
);
2563 reg
.rawValue
= value
.mid(pos
+6);
2564 if (reg
.rawValue
.right(1) == ")") // remove closing bracket
2565 reg
.rawValue
.truncate(reg
.rawValue
.length()-1);
2570 * In other cases we split off the first token (separated by
2571 * whitespace). It is the raw value. The remainder of the line
2572 * is the cooked value.
2574 int pos
= value
.indexOf(' ');
2576 reg
.rawValue
= value
;
2577 reg
.cookedValue
= QString();
2579 reg
.rawValue
= value
.left(pos
);
2580 reg
.cookedValue
= value
.mid(pos
+1);
2584 if (*output
!= '\0')
2585 output
++; /* skip '\n' */
2587 regs
.push_back(reg
);
2592 bool GdbDriver::parseInfoLine(const char* output
, QString
& addrFrom
, QString
& addrTo
)
2594 // "is at address" or "starts at address"
2595 const char* start
= strstr(output
, "s at address ");
2600 const char* p
= start
;
2601 while (*p
!= '\0' && !isspace(*p
))
2603 addrFrom
= QString::fromLatin1(start
, p
-start
);
2605 start
= strstr(p
, "and ends at ");
2613 while (*p
!= '\0' && !isspace(*p
))
2615 addrTo
= QString::fromLatin1(start
, p
-start
);
2620 std::list
<DisassembledCode
> GdbDriver::parseDisassemble(const char* output
)
2622 std::list
<DisassembledCode
> code
;
2624 if (strncmp(output
, "Dump of assembler", 17) != 0) {
2632 // remove first line
2633 const char* p
= strchr(output
, '\n');
2635 return code
; /* not a regular output */
2640 const char* end
= strstr(output
, "End of assembler");
2642 end
= p
+ strlen(p
);
2644 // remove function offsets from the lines
2648 // skip initial space or PC pointer ("=>", since gdb 7.1)
2652 else if (p
[0] == '=' && p
[1] == '>')
2657 const char* start
= p
;
2659 while (p
!= end
&& !isspace(*p
))
2661 c
.address
= QString::fromLatin1(start
, p
-start
);
2663 // function name (enclosed in '<>', followed by ':')
2664 while (p
!= end
&& *p
!= '<')
2667 skipNestedAngles(p
);
2672 while (p
!= end
&& isspace(*p
))
2675 // code until end of line
2677 while (p
!= end
&& *p
!= '\n')
2679 if (p
!= end
) /* include '\n' */
2682 c
.code
= QString::fromLatin1(start
, p
-start
);
2688 QString
GdbDriver::parseMemoryDump(const char* output
, std::list
<MemoryDump
>& memdump
)
2690 if (isErrorExpr(output
)) {
2691 // error; strip space
2692 QString msg
= output
;
2693 return msg
.trimmed();
2696 const char* p
= output
; /* save typing */
2702 const char* start
= p
;
2703 while (*p
!= '\0' && *p
!= ':' && !isspace(*p
))
2705 md
.address
= QString::fromLatin1(start
, p
-start
);
2707 // parse function offset
2711 while (*p
!= '\0' && !(*p
== ':' && isspace(p
[1])))
2713 md
.address
.fnoffs
= QString::fromLatin1(start
, p
-start
);
2717 // skip space; this may skip a new-line char!
2720 // everything to the end of the line is the memory dump
2721 const char* end
= strchr(p
, '\n');
2723 md
.dump
= QString::fromLatin1(p
, end
-p
);
2726 md
.dump
= QString::fromLatin1(p
, strlen(p
));
2729 memdump
.push_back(md
);
2735 QString
GdbDriver::editableValue(VarTree
* value
)
2737 QByteArray ba
= value
->value().toLatin1();
2738 const char* s
= ba
.constData();
2740 // if the variable is a pointer value that contains a cast,
2743 skipNested(s
, '(', ')');
2750 const char* start
= s
;
2752 if (strncmp(s
, "0x", 2) == 0)
2755 while (isxdigit(*s
))
2759 * What we saw so far might have been a reference. If so, edit the
2760 * referenced value. Otherwise, edit the pointer.
2768 // if it's a pointer to a string, remove the string
2769 const char* end
= s
;
2774 return QString::fromLatin1(start
, end
-start
);
2777 return QString::fromLatin1(start
, strlen(start
));
2781 // else leave it unchanged (or stripped of the reference preamble)
2785 QString
GdbDriver::parseSetVariable(const char* output
)
2787 // if there is any output, it is an error message
2788 QString msg
= output
;
2789 return msg
.trimmed();
2793 #include "gdbdriver.moc"