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 { DCdetach
, "detach\n", GdbCmdInfo::argNone
},
99 { DCbreaktext
, "break %s\n", GdbCmdInfo::argString
},
100 { DCbreakline
, "break %s:%d\n", GdbCmdInfo::argStringNum
},
101 { DCtbreakline
, "tbreak %s:%d\n", GdbCmdInfo::argStringNum
},
102 { DCbreakaddr
, "break *%s\n", GdbCmdInfo::argString
},
103 { DCtbreakaddr
, "tbreak *%s\n", GdbCmdInfo::argString
},
104 { DCwatchpoint
, "watch %s\n", GdbCmdInfo::argString
},
105 { DCdelete
, "delete %d\n", GdbCmdInfo::argNum
},
106 { DCenable
, "enable %d\n", GdbCmdInfo::argNum
},
107 { DCdisable
, "disable %d\n", GdbCmdInfo::argNum
},
108 { DCprint
, "print %s\n", GdbCmdInfo::argString
},
109 { DCprintDeref
, "print *(%s)\n", GdbCmdInfo::argString
},
110 { DCprintStruct
, "print %s\n", GdbCmdInfo::argString
},
111 { DCprintQStringStruct
, printQStringStructFmt
, GdbCmdInfo::argString
},
112 { DCprintPopup
, "print %s\n", 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 { DCprintWChar
, "print ($s=%s)?*$s@wcslen($s):0x0\n", GdbCmdInfo::argString
},
123 { DCsetvariable
, "set variable %s=%s\n", GdbCmdInfo::argString2
},
126 #define NUM_CMDS (int(sizeof(cmds)/sizeof(cmds[0])))
127 #define MAX_FMTLEN 200
129 GdbDriver::GdbDriver() :
133 // check command info array
135 for (int i
= 0; i
< NUM_CMDS
; i
++) {
136 // must be indexable by DbgCommand values, i.e. sorted by DbgCommand values
137 assert(i
== cmds
[i
].cmd
);
138 // a format string must be associated
139 assert(cmds
[i
].fmt
!= 0);
140 assert(strlen(cmds
[i
].fmt
) <= MAX_FMTLEN
);
141 // format string must match arg specification
142 switch (cmds
[i
].argsNeeded
) {
143 case GdbCmdInfo::argNone
:
144 assert(strchr(cmds
[i
].fmt
, '%') == 0);
146 case GdbCmdInfo::argString
:
147 perc
= strchr(cmds
[i
].fmt
, '%');
148 assert(perc
!= 0 && perc
[1] == 's');
149 assert(strchr(perc
+2, '%') == 0);
151 case GdbCmdInfo::argNum
:
152 perc
= strchr(cmds
[i
].fmt
, '%');
153 assert(perc
!= 0 && perc
[1] == 'd');
154 assert(strchr(perc
+2, '%') == 0);
156 case GdbCmdInfo::argStringNum
:
157 perc
= strchr(cmds
[i
].fmt
, '%');
158 assert(perc
!= 0 && perc
[1] == 's');
159 perc
= strchr(perc
+2, '%');
160 assert(perc
!= 0 && perc
[1] == 'd');
161 assert(strchr(perc
+2, '%') == 0);
163 case GdbCmdInfo::argNumString
:
164 perc
= strchr(cmds
[i
].fmt
, '%');
165 assert(perc
!= 0 && perc
[1] == 'd');
166 perc
= strchr(perc
+2, '%');
167 assert(perc
!= 0 && perc
[1] == 's');
168 assert(strchr(perc
+2, '%') == 0);
170 case GdbCmdInfo::argString2
:
171 perc
= strchr(cmds
[i
].fmt
, '%');
172 assert(perc
!= 0 && perc
[1] == 's');
173 perc
= strchr(perc
+2, '%');
174 assert(perc
!= 0 && perc
[1] == 's');
175 assert(strchr(perc
+2, '%') == 0);
177 case GdbCmdInfo::argNum2
:
178 perc
= strchr(cmds
[i
].fmt
, '%');
179 assert(perc
!= 0 && perc
[1] == 'd');
180 perc
= strchr(perc
+2, '%');
181 assert(perc
!= 0 && perc
[1] == 'd');
182 assert(strchr(perc
+2, '%') == 0);
186 assert(strlen(printQStringStructFmt
) <= MAX_FMTLEN
);
190 GdbDriver::~GdbDriver()
195 QString
GdbDriver::driverName() const
200 QString
GdbDriver::defaultGdb()
204 " --fullname" /* to get standard file names each time the prog stops */
205 " --nx"; /* do not execute initialization files */
208 QString
GdbDriver::defaultInvocation() const
210 if (m_defaultCmd
.isEmpty()) {
217 QStringList
GdbDriver::boolOptionList() const
220 return QStringList();
223 bool GdbDriver::startup(QString cmdStr
)
225 if (!DebuggerDriver::startup(cmdStr
))
228 static const char gdbInitialize
[] =
230 * Work around buggy gdbs that do command line editing even if they
231 * are not on a tty. The readline library echos every command back
232 * in this case, which is confusing for us.
236 "set print static-members off\n"
237 "set print asm-demangle on\n"
239 * Sometimes, gdb prints [New Thread ...] during 'info threads';
240 * we will not look at thread events anyway, so turn them off.
242 "set print thread-events off\n"
244 * We do not want Python pretty printer support, because their
245 * output is unpredictable, and we cannot parse it.
247 "set auto-load python off\n"
249 * Nevertheless, some Python messages get through, for example,
250 * when a backtrace is printed without the Python gdb module loaded.
252 "set python print-stack none\n"
254 * Don't assume that program functions invoked from a watch expression
257 "set unwindonsignal on\n"
259 * Write a short macro that prints all locals: local variables and
260 * function arguments.
262 "define kdbg__alllocals\n"
263 "info locals\n" /* local vars supersede args with same name */
264 "info args\n" /* therefore, arguments must come last */
267 * Work around a bug in gdb-6.3: "info line main" crashes gdb.
269 "define kdbg_infolinemain\n"
273 // change prompt string and synchronize with gdb
274 "set prompt " PROMPT
"\n"
277 executeCmdString(DCinitialize
, gdbInitialize
, false);
279 // assume that QString::null is ok
280 cmds
[DCprintQStringStruct
].fmt
= printQStringStructFmt
;
285 void GdbDriver::commandFinished(CmdQueueItem
* cmd
)
287 // command string must be committed
288 if (!cmd
->m_committed
) {
290 TRACE("calling " + (__PRETTY_FUNCTION__
+ (" with uncommited command:\n\t" +
295 switch (cmd
->m_cmd
) {
299 * Check for GDB 7.1 or later; the syntax for the disassemble
300 * command has changed.
301 * This RE picks the last version number in the first line,
302 * because at least OpenSUSE writes its own version number
303 * in the first line (but before GDB's version number).
306 " " // must be preceded by space
307 "[(]?" // SLES 10 embeds in parentheses
308 "(\\d+)\\.(\\d+)" // major, minor
309 "[^ ]*\\n" // no space until end of line
311 int pos
= re
.indexIn(m_output
);
312 const char* disass
= "disassemble %s %s\n";
314 int major
= re
.cap(1).toInt();
315 int minor
= re
.cap(2).toInt();
316 if (major
> 7 || (major
== 7 && minor
>= 1))
318 disass
= "disassemble %s, %s\n";
321 cmds
[DCdisassemble
].fmt
= disass
;
327 /* ok, the command is ready */
328 emit
commandReceived(cmd
, m_output
.constData());
330 switch (cmd
->m_cmd
) {
349 int GdbDriver::findPrompt(const QByteArray
& output
) const
352 * If there's a prompt string in the collected output, it must be at
355 * Note: It could nevertheless happen that a character sequence that is
356 * equal to the prompt string appears at the end of the output,
357 * although it is very, very unlikely (namely as part of a string that
358 * lingered in gdb's output buffer due to some timing/heavy load
359 * conditions for a very long time such that that buffer overflowed
360 * exactly at the end of the prompt string look-a-like).
362 int len
= output
.length();
363 if (len
>= PROMPT_LEN
&&
364 strncmp(output
.data()+len
-PROMPT_LEN
, PROMPT
, PROMPT_LEN
) == 0)
366 return len
-PROMPT_LEN
;
372 * The --fullname option makes gdb send a special normalized sequence print
373 * each time the program stops and at some other points. The sequence has
374 * the form "\032\032filename:lineno:charoffset:(beg|middle):address".
376 void GdbDriver::parseMarker(CmdQueueItem
* cmd
)
378 char* startMarker
= strstr(m_output
.data(), "\032\032");
379 if (startMarker
== 0)
382 // extract the marker
384 TRACE(QString("found marker: ") + startMarker
);
385 char* endMarker
= strchr(startMarker
, '\n');
391 // extract filename and line number
392 static QRegExp
MarkerRE(":(\\d+):\\d+:[begmidl]+:0x");
394 int lineNoStart
= MarkerRE
.indexIn(startMarker
);
395 if (lineNoStart
>= 0) {
396 int lineNo
= MarkerRE
.cap(1).toInt();
398 // get address unless there is one in cmd
399 DbgAddr address
= cmd
->m_addr
;
400 if (address
.isEmpty()) {
401 const char* addrStart
= startMarker
+ lineNoStart
+
402 MarkerRE
.matchedLength() - 2;
403 address
= QString(addrStart
).trimmed();
406 // now show the window
407 startMarker
[lineNoStart
] = '\0'; /* split off file name */
408 emit
activateFileLine(startMarker
, lineNo
-1, address
);
414 * Escapes characters that might lead to problems when they appear on gdb's
417 static void normalizeStringArg(QString
& arg
)
420 * Remove trailing backslashes. This approach is a little simplistic,
421 * but we know that there is at the moment no case where a trailing
422 * backslash would make sense.
424 while (!arg
.isEmpty() && arg
[arg
.length()-1] == '\\') {
425 arg
= arg
.left(arg
.length()-1);
430 QString
GdbDriver::makeCmdString(DbgCommand cmd
, QString strArg
)
432 assert(cmd
>= 0 && cmd
< NUM_CMDS
);
433 assert(cmds
[cmd
].argsNeeded
== GdbCmdInfo::argString
);
435 normalizeStringArg(strArg
);
438 // need the working directory when parsing the output
439 m_programWD
= strArg
;
440 } else if (cmd
== DCsetargs
&& !m_redirect
.isEmpty()) {
442 * Use saved redirection. We prepend it in front of the user's
443 * arguments so that the user can override the redirections.
445 strArg
= m_redirect
+ " " + strArg
;
449 cmdString
.sprintf(cmds
[cmd
].fmt
, strArg
.toUtf8().constData());
453 QString
GdbDriver::makeCmdString(DbgCommand cmd
, int intArg
)
455 assert(cmd
>= 0 && cmd
< NUM_CMDS
);
456 assert(cmds
[cmd
].argsNeeded
== GdbCmdInfo::argNum
);
459 cmdString
.sprintf(cmds
[cmd
].fmt
, intArg
);
463 QString
GdbDriver::makeCmdString(DbgCommand cmd
, QString strArg
, int intArg
)
465 assert(cmd
>= 0 && cmd
< NUM_CMDS
);
466 assert(cmds
[cmd
].argsNeeded
== GdbCmdInfo::argStringNum
||
467 cmds
[cmd
].argsNeeded
== GdbCmdInfo::argNumString
||
471 normalizeStringArg(strArg
);
478 * intArg specifies which channels should be redirected to
479 * /dev/null. It is a value or'ed together from RDNstdin,
480 * RDNstdout, RDNstderr. We store the value for a later DCsetargs
483 * Note: We rely on that after the DCtty a DCsetargs will follow,
484 * which will ultimately apply the redirection.
486 static const char* const runRedir
[8] = {
490 "</dev/null >/dev/null",
492 "</dev/null 2>/dev/null",
494 "</dev/null >/dev/null 2>&1"
496 if (strArg
.isEmpty())
497 intArg
= 7; /* failsafe if no tty */
498 m_redirect
= runRedir
[intArg
& 7];
500 return makeCmdString(DCtty
, strArg
); /* note: no problem if strArg empty */
503 if (cmd
== DCexamine
) {
504 // make a format specifier from the intArg
505 static const char size
[16] = {
506 '\0', 'b', 'h', 'w', 'g'
508 static const char format
[16] = {
509 '\0', 'x', 'd', 'u', 'o', 't',
510 'a', 'c', 'f', 's', 'i'
512 assert(MDTsizemask
== 0xf); /* lowest 4 bits */
513 assert(MDTformatmask
== 0xf0); /* next 4 bits */
514 int count
= 16; /* number of entities to print */
515 char sizeSpec
= size
[intArg
& MDTsizemask
];
516 char formatSpec
= format
[(intArg
& MDTformatmask
) >> 4];
517 assert(sizeSpec
!= '\0');
518 assert(formatSpec
!= '\0');
519 // adjust count such that 16 lines are printed
520 switch (intArg
& MDTformatmask
) {
521 case MDTstring
: case MDTinsn
:
522 break; /* no modification needed */
524 // all cases drop through:
525 switch (intArg
& MDTsizemask
) {
537 spec
.sprintf("/%d%c%c", count
, sizeSpec
, formatSpec
);
539 return makeCmdString(DCexamine
, spec
, strArg
);
542 if (cmds
[cmd
].argsNeeded
== GdbCmdInfo::argStringNum
)
544 // line numbers are zero-based
545 if (cmd
== DCuntil
|| cmd
== DCbreakline
||
546 cmd
== DCtbreakline
|| cmd
== DCinfoline
)
550 if (cmd
== DCinfoline
)
552 // must split off file name part
553 strArg
= QFileInfo(strArg
).fileName();
555 cmdString
.sprintf(cmds
[cmd
].fmt
, strArg
.toUtf8().constData(), intArg
);
559 cmdString
.sprintf(cmds
[cmd
].fmt
, intArg
, strArg
.toUtf8().constData());
564 QString
GdbDriver::makeCmdString(DbgCommand cmd
, QString strArg1
, QString strArg2
)
566 assert(cmd
>= 0 && cmd
< NUM_CMDS
);
567 assert(cmds
[cmd
].argsNeeded
== GdbCmdInfo::argString2
);
569 normalizeStringArg(strArg1
);
570 normalizeStringArg(strArg2
);
573 cmdString
.sprintf(cmds
[cmd
].fmt
,
574 strArg1
.toUtf8().constData(),
575 strArg2
.toUtf8().constData());
579 QString
GdbDriver::makeCmdString(DbgCommand cmd
, int intArg1
, int intArg2
)
581 assert(cmd
>= 0 && cmd
< NUM_CMDS
);
582 assert(cmds
[cmd
].argsNeeded
== GdbCmdInfo::argNum2
);
585 cmdString
.sprintf(cmds
[cmd
].fmt
, intArg1
, intArg2
);
589 CmdQueueItem
* GdbDriver::executeCmd(DbgCommand cmd
)
591 assert(cmd
>= 0 && cmd
< NUM_CMDS
);
592 assert(cmds
[cmd
].argsNeeded
== GdbCmdInfo::argNone
);
594 return executeCmdString(cmd
, cmds
[cmd
].fmt
, false);
597 CmdQueueItem
* GdbDriver::executeCmd(DbgCommand cmd
, QString strArg
)
599 return executeCmdString(cmd
, makeCmdString(cmd
, strArg
), false);
602 CmdQueueItem
* GdbDriver::executeCmd(DbgCommand cmd
, int intArg
)
605 return executeCmdString(cmd
, makeCmdString(cmd
, intArg
), false);
608 CmdQueueItem
* GdbDriver::executeCmd(DbgCommand cmd
, QString strArg
, int intArg
)
610 return executeCmdString(cmd
, makeCmdString(cmd
, strArg
, intArg
), false);
613 CmdQueueItem
* GdbDriver::executeCmd(DbgCommand cmd
, QString strArg1
, QString strArg2
)
615 return executeCmdString(cmd
, makeCmdString(cmd
, strArg1
, strArg2
), false);
618 CmdQueueItem
* GdbDriver::executeCmd(DbgCommand cmd
, int intArg1
, int intArg2
)
620 return executeCmdString(cmd
, makeCmdString(cmd
, intArg1
, intArg2
), false);
623 CmdQueueItem
* GdbDriver::executeCmdOnce(DbgCommand cmd
)
625 assert(cmd
>= 0 && cmd
< NUM_CMDS
);
626 assert(cmds
[cmd
].argsNeeded
== GdbCmdInfo::argNone
);
628 return executeCmdString(cmd
, cmds
[cmd
].fmt
, true);
631 CmdQueueItem
* GdbDriver::executeCmdOnce(DbgCommand cmd
, QString strArg
, int intArg
)
633 return executeCmdString(cmd
, makeCmdString(cmd
, strArg
, intArg
), true);
636 CmdQueueItem
* GdbDriver::queueCmd(DbgCommand cmd
, QueueMode mode
)
638 return queueCmdString(cmd
, cmds
[cmd
].fmt
, mode
);
641 CmdQueueItem
* GdbDriver::queueCmd(DbgCommand cmd
, QString strArg
,
644 return queueCmdString(cmd
, makeCmdString(cmd
, strArg
), mode
);
647 CmdQueueItem
* GdbDriver::queueCmd(DbgCommand cmd
, int intArg
,
650 return queueCmdString(cmd
, makeCmdString(cmd
, intArg
), mode
);
653 CmdQueueItem
* GdbDriver::queueCmd(DbgCommand cmd
, QString strArg
, int intArg
,
656 return queueCmdString(cmd
, makeCmdString(cmd
, strArg
, intArg
), mode
);
659 CmdQueueItem
* GdbDriver::queueCmd(DbgCommand cmd
, QString strArg1
, QString strArg2
,
662 return queueCmdString(cmd
, makeCmdString(cmd
, strArg1
, strArg2
), mode
);
665 void GdbDriver::terminate()
667 if (m_state
!= DSidle
)
669 ::kill(pid(), SIGINT
);
670 m_state
= DSinterrupted
;
676 void GdbDriver::detachAndTerminate()
678 ::kill(pid(), SIGINT
);
680 executeCmdString(DCinitialize
, "detach\nquit\n", true);
683 void GdbDriver::interruptInferior()
685 ::kill(pid(), SIGINT
);
686 // remove accidentally queued commands
690 static bool isErrorExpr(const char* output
)
693 strncmp(output
, "Cannot access memory at", 23) == 0 ||
694 strncmp(output
, "Attempt to dereference a generic pointer", 40) == 0 ||
695 strncmp(output
, "Attempt to take contents of ", 28) == 0 ||
696 strncmp(output
, "Attempt to use a type name as an expression", 43) == 0 ||
697 strncmp(output
, "There is no member or method named", 34) == 0 ||
698 strncmp(output
, "A parse error in expression", 27) == 0 ||
699 strncmp(output
, "No symbol \"", 11) == 0 ||
700 strncmp(output
, "Internal error: ", 16) == 0;
703 static void skipSpace(const char*& p
)
709 static void skipDecimal(const char*& p
)
716 * Returns true if the output is an error message. If wantErrorValue is
717 * true, a new ExprValue object is created and filled with the error message.
718 * If there are warnings, they are skipped and output points past the warnings
719 * on return (even if there \e are errors).
721 static bool parseErrorMessage(const char*& output
,
722 ExprValue
*& variable
, bool wantErrorValue
)
727 while (strncmp(output
, "warning:", 8) == 0)
729 const char* end
= strchr(output
+8, '\n');
731 output
+= strlen(output
);
737 if (isErrorExpr(output
))
739 if (wantErrorValue
) {
740 // put the error message as value in the variable
741 variable
= new ExprValue(QString(), VarTree::NKplain
);
742 const char* endMsg
= strchr(output
, '\n');
744 endMsg
= output
+ strlen(output
);
745 variable
->m_value
= QString::fromLatin1(output
, endMsg
-output
);
754 #if QT_VERSION >= 300
764 void GdbDriver::setPrintQStringDataCmd(const char* cmd
)
766 // don't accept the command if it is empty
767 if (cmd
== 0 || *cmd
== '\0')
769 assert(strlen(cmd
) <= MAX_FMTLEN
);
770 cmds
[DCprintQStringStruct
].fmt
= cmd
;
773 ExprValue
* GdbDriver::parseQCharArray(const char* output
, bool wantErrorValue
, bool qt3like
)
775 ExprValue
* variable
= 0;
778 * Parse off white space. gdb sometimes prints white space first if the
779 * printed array leaded to an error.
783 // special case: empty string (0 repetitions)
784 if (strncmp(output
, "Invalid number 0 of repetitions", 31) == 0)
786 variable
= new ExprValue(QString(), VarTree::NKplain
);
787 variable
->m_value
= "\"\"";
791 // check for error conditions
792 if (parseErrorMessage(output
, variable
, wantErrorValue
))
798 const char* p
= output
;
808 // this is the real data
814 enum { wasNothing
, wasChar
, wasRepeat
} lastThing
= wasNothing
;
816 * A matrix for separators between the individual "things"
817 * that are added to the string. The first index is a bool,
818 * the second index is from the enum above.
820 static const char* separator
[2][3] = {
821 { "\"", 0, ", \"" }, /* normal char is added */
822 { "'", "\", '", ", '" } /* repeated char is added */
825 while (isdigit(*p
)) {
828 unsigned short value
= (unsigned short) strtoul(p
, &end
, 0);
830 goto error
; /* huh? no valid digits */
831 // skip separator and search for a repeat count
833 while (isspace(*p
) || *p
== ',')
835 bool repeats
= strncmp(p
, "<repeats ", 9) == 0;
837 const char* start
= p
;
838 p
= strchr(p
+9, '>'); /* search end and advance */
842 repeatCount
= QString::fromLatin1(start
, p
-start
);
843 while (isspace(*p
) || *p
== ',')
846 // p is now at the next char (or the end)
848 // interpret the value as a QChar
849 // TODO: make cross-architecture compatible
855 (unsigned short&)ch
= value
;
859 ch
.setRow(c
.qch
.row
);
860 ch
.setCell(c
.qch
.cell
);
864 // escape a few frequently used characters
865 char escapeCode
= '\0';
866 switch (ch
.toLatin1()) {
867 case '\n': escapeCode
= 'n'; break;
868 case '\r': escapeCode
= 'r'; break;
869 case '\t': escapeCode
= 't'; break;
870 case '\b': escapeCode
= 'b'; break;
871 case '\"': escapeCode
= '\"'; break;
872 case '\\': escapeCode
= '\\'; break;
873 case '\0': if (value
== 0) { escapeCode
= '0'; } break;
877 result
+= separator
[repeats
][lastThing
];
879 if (escapeCode
!= '\0') {
885 // fixup repeat count and lastThing
888 result
+= repeatCount
;
889 lastThing
= wasRepeat
;
898 if (lastThing
== wasChar
)
902 variable
= new ExprValue(QString(), VarTree::NKplain
);
903 variable
->m_value
= result
;
905 else if (strncmp(p
, "true", 4) == 0)
907 variable
= new ExprValue(QString(), VarTree::NKplain
);
908 variable
->m_value
= "QString::null";
910 else if (strncmp(p
, "false", 5) == 0)
912 variable
= new ExprValue(QString(), VarTree::NKplain
);
913 variable
->m_value
= "(null)";
920 if (wantErrorValue
) {
921 variable
= new ExprValue(QString(), VarTree::NKplain
);
922 variable
->m_value
= "internal parse error";
927 static ExprValue
* parseVar(const char*& s
)
934 VarTree::NameKind kind
;
936 * Detect anonymouse struct values: The 'name =' part is missing:
937 * s = { a = 1, { b = 2 }}
938 * Note that this detection works only inside structs when the anonymous
939 * struct is not the first member:
940 * s = {{ a = 1 }, b = 2}
941 * This is misparsed (by parseNested()) because it is mistakenly
942 * interprets the second opening brace as the first element of an array
947 name
= i18n("<anonymous struct or union>");
948 kind
= VarTree::NKanonymous
;
952 if (!parseName(p
, name
, kind
)) {
959 TRACE("parse error: = not found after " + name
);
962 // skip the '=' and more whitespace
967 ExprValue
* variable
= new ExprValue(name
, kind
);
969 if (!parseValue(p
, variable
)) {
977 static void skipNested(const char*& s
, char opening
, char closing
)
981 // parse a nested type
985 * Search for next matching `closing' char, skipping nested pairs of
986 * `opening' and `closing'.
988 while (*p
&& nest
> 0) {
991 } else if (*p
== closing
) {
997 TRACE(QString().sprintf("parse error: mismatching %c%c at %-20.20s", opening
, closing
, s
));
1003 * This function skips text that is delimited by nested angle bracktes, '<>'.
1004 * A complication arises because the delimited text can contain the names of
1005 * operator<<, operator>>, operator<, and operator>, which have to be treated
1006 * specially so that they do not count towards the nesting of '<>'.
1007 * This function assumes that the delimited text does not contain strings.
1009 static void skipNestedAngles(const char*& s
)
1014 p
++; // skip the initial '<'
1015 while (*p
&& nest
> 0)
1017 // Below we can check for p-s >= 9 instead of 8 because
1018 // *s is '<' and cannot be part of "operator".
1021 if (p
-s
>= 9 && strncmp(p
-8, "operator", 8) == 0) {
1030 if (p
-s
>= 9 && strncmp(p
-8, "operator", 8) == 0) {
1040 TRACE(QString().sprintf("parse error: mismatching <> at %-20.20s", s
));
1046 * Find the end of line that is not inside braces
1048 static void findEnd(const char*& s
)
1051 while (*p
&& *p
!='\n') {
1052 while (*p
&& *p
!='\n' && *p
!='{')
1056 skipNested(p
, '{', '}'); p
--;
1062 static bool isNumberish(const char ch
)
1064 return (ch
>='0' && ch
<='9') || ch
=='.' || ch
=='x';
1067 void skipString(const char*& p
)
1069 // wchar_t strings begin with L
1076 while (*p
!= quote
) {
1078 // skip escaped character
1079 // no special treatment for octal values necessary
1082 // simply return if no more characters
1090 * Strings can consist of several parts, some of which contain repeated
1093 if (quote
== '\'') {
1094 // look ahaead for <repeats 123 times>
1095 const char* q
= p
+1;
1097 if (strncmp(q
, "<repeats ", 9) == 0) {
1099 while (*p
!= '\0' && *p
!= '>')
1102 p
++; /* skip the '>' */
1106 // Is the string continued? If so, there is no L in wchar_t strings
1109 // look ahead for another quote
1110 const char* q
= p
+1;
1112 if (*q
== '"' || *q
== '\'') {
1118 // some strings can end in <incomplete sequence ...>
1119 if (strncmp(q
, "<incomplete sequence", 20) == 0)
1122 while (*p
!= '\0' && *p
!= '>')
1125 p
++; /* skip the '>' */
1130 * There's a bug in gdb where it prints the beginning of the string
1131 * continuation and the comma-blank in the wrong order if the new string
1132 * begins with an incomplete multi-byte character. For now, let's check
1133 * for this in a very narrow condition, particularly, where the next
1134 * character is given in octal notation. Example:
1135 * 'a' <repeats 20 times>"\240, b"
1137 if (*p
== '"' && p
[1] == '\\' && isdigit(p
[2])) {
1139 while (isdigit(p
[i
]))
1141 if (p
[i
] == ',' && p
[i
+1] == ' ') {
1142 // just treat everything beginning at the dquote as string
1146 /* very long strings are followed by `...' */
1147 if (*p
== '.' && p
[1] == '.' && p
[2] == '.') {
1152 static void skipNestedWithString(const char*& s
, char opening
, char closing
)
1156 // parse a nested expression
1160 * Search for next matching `closing' char, skipping nested pairs of
1161 * `opening' and `closing' as well as strings.
1163 while (*p
&& nest
> 0) {
1164 if (*p
== opening
) {
1166 } else if (*p
== closing
) {
1168 } else if (*p
== '\'' || *p
== '\"') {
1175 TRACE(QString().sprintf("parse error: mismatching %c%c at %-20.20s", opening
, closing
, s
));
1180 static void skipName(const char*& p
)
1182 // allow : (for enumeration values) and $ and . (for _vtbl.)
1183 while (isalnum(*p
) || *p
== '_' || *p
== ':' || *p
== '$' || *p
== '.')
1187 static void skipFunctionName(const char*& p
)
1192 // skip template parameter list
1193 skipNestedAngles(p
);
1194 } else if (*p
== '(') {
1195 // this skips "(anonymous namespace)" as well as the formal
1196 // parameter list of the containing function if this is a member
1197 // of a nested class
1198 skipNestedWithString(p
, '(', ')');
1199 } else if (isalnum(*p
) || *p
== '_' || *p
== ':') {
1200 const char* start
= p
;
1202 // check for operator
1204 strncmp(p
-8, "operator", 8) == 0 &&
1205 // do not mistake this as the tail of some identifier
1206 (p
-start
== 8 || !(isalnum(p
[-9]) || p
[-9] == '_')))
1208 // skip forward until we find the opening parenthesis
1209 // this catches both operator()(...) as well as
1210 // type conversion operators, e.g.
1211 // operator char const*() const
1212 // operator void(*)()
1213 while (*p
&& *p
!= '(')
1216 } else if (strncmp(p
, " const", 6) == 0 &&
1217 // must not mistake "const" as the beginning of
1218 // a subequent identifier
1219 !isalnum(p
[6]) && p
[6] != '_') {
1227 static bool parseName(const char*& s
, QString
& name
, VarTree::NameKind
& kind
)
1229 kind
= VarTree::NKplain
;
1232 // examples of names:
1235 // <string<a,b<c>,7> >
1238 skipNestedAngles(p
);
1239 name
= QString::fromLatin1(s
, p
- s
);
1240 kind
= VarTree::NKtype
;
1244 // name, which might be "static"; allow dot for "_vtbl."
1247 TRACE(QString().sprintf("parse error: not a name %-20.20s", s
));
1251 if (len
== 6 && strncmp(s
, "static", 6) == 0) {
1252 kind
= VarTree::NKstatic
;
1254 // its a static variable, name comes now
1259 TRACE(QString().sprintf("parse error: not a name after static %-20.20s", s
));
1264 name
= QString::fromLatin1(s
, len
);
1266 // return the new position
1271 static bool parseValue(const char*& s
, ExprValue
* variable
)
1273 variable
->m_value
= "";
1277 // Sometimes we find the following output:
1278 // {<text variable, no debug info>} 0x40012000 <access>
1279 // {<data variable, no debug info>}
1280 // {<variable (not text or data), no debug info>}
1281 if (strncmp(s
, "{<text variable, ", 17) == 0 ||
1282 strncmp(s
, "{<data variable, ", 17) == 0 ||
1283 strncmp(s
, "{<variable (not text or data), ", 31) == 0)
1285 const char* start
= s
;
1286 skipNested(s
, '{', '}');
1287 variable
->m_value
= QString::fromLatin1(start
, s
-start
);
1288 variable
->m_value
+= ' '; // add only a single space
1295 if (!parseNested(s
, variable
)) {
1298 // must be the closing brace
1300 TRACE("parse error: missing } of " + variable
->m_name
);
1304 // final white space
1308 // Sometimes we find a warning; it ends at the next LF
1309 else if (strncmp(s
, "warning: ", 9) == 0) {
1310 const char* end
= strchr(s
, '\n');
1311 s
= end
? end
: s
+strlen(s
);
1312 // skip space at start of next line
1316 // examples of leaf values (cannot be the empty string):
1322 // (DwContentType&) @0x8123456: {...}
1326 // 0x823abc <Array<int> virtual table>
1327 // 0x40240f <globarstr> "test"
1328 // (void (*)()) 0x8048480 <f(E *, char)>
1331 // &parseP (HTMLClueV *, char *)
1332 // &virtual table offset 0, this adjustment 140737488346016
1333 // &virtual Dl::operator char const*() const
1334 // Variable "x" is not available.
1335 // The value of variable 'x' is distributed...
1336 // -nan(0xfffff081defa0)
1337 // @0x100400f08: <error reading variable>
1338 // (void (Templated<double>::*)(Templated<double> * const)) 0x400d74 <MostDerived::PrintV()>, this adjustment -16
1345 skipNested(p
, '(', ')');
1348 variable
->m_value
= QString::fromLatin1(s
, p
- s
);
1351 bool reference
= false;
1353 // skip reference marker
1357 const char* start
= p
;
1361 // some values consist of more than one token
1362 bool checkMultiPart
= false;
1364 if (p
[0] == '0' && p
[1] == 'x') {
1367 while (isxdigit(*p
))
1371 * Assume this is a pointer, but only if it's not a reference, since
1372 * references can't be expanded.
1375 variable
->m_varKind
= VarTree::VKpointer
;
1378 * References are followed by a colon, in which case we'll
1379 * find the value following the reference address.
1384 // Paranoia. (Can this happen, i.e. reference not followed by ':'?)
1388 checkMultiPart
= true;
1389 } else if (isdigit(*p
)) {
1390 // parse decimal number, possibly a float
1392 if (*p
== '.') { /* TODO: obey i18n? */
1393 // In long arrays an integer may be followed by '...'.
1394 // We test for this situation and don't gobble the '...'.
1395 if (p
[1] != '.' || p
[0] != '.') {
1401 if (*p
== 'e' || *p
== 'E') {
1404 if (*p
== '-' || *p
== '+')
1409 // for char variables there is the char, eg. 10 '\n'
1410 checkMultiPart
= true;
1411 } else if (*p
== '<') {
1412 // e.g. <optimized out>
1413 skipNestedAngles(p
);
1414 } else if (*p
== '"' || *p
== '\'') {
1415 // character may have multipart: '\000' <repeats 11 times>
1416 checkMultiPart
= *p
== '\'';
1419 } else if (*p
== 'L' && (p
[1] == '"' || p
[1] == '\'')) {
1420 // ditto for wchar_t strings
1421 checkMultiPart
= p
[1] == '\'';
1423 } else if (*p
== '&') {
1425 if (strncmp(p
, "virtual ", 8) == 0) {
1427 if (strncmp(p
, "table offset ", 13) == 0) {
1430 checkMultiPart
= true;
1432 skipFunctionName(p
);
1439 skipNested(p
, '(', ')');
1442 } else if (strncmp(p
, "Variable \"", 10) == 0) {
1443 // Variable "x" is not available.
1444 p
+= 10; // skip to "
1446 if (strncmp(p
, "\" is not available.", 19) == 0) {
1449 } else if (strncmp(p
, "The value of variable '", 23) == 0) {
1452 const char* e
= strchr(p
, '.');
1460 // must be an enumeration value
1462 // nan (floating point Not a Number) is followed by a number in ()
1463 // enum values can look like A::(anonymous namespace)::blue
1465 bool isAnonNS
= strncmp(p
+1, "anonymous namespace)", 20) == 0;
1466 skipNested(p
, '(', ')');
1471 variable
->m_value
+= QString::fromLatin1(start
, p
- start
);
1473 // remove line breaks from the value; this is ok since
1474 // string values never contain a literal line break
1475 variable
->m_value
.replace('\n', ' ');
1477 while (checkMultiPart
) {
1480 // may be followed by a string or <...>
1481 // if this was a pointer with a string,
1482 // reset that pointer flag since we have now a value
1484 checkMultiPart
= false;
1486 if (*p
== '"' || *p
== '\'') {
1488 variable
->m_varKind
= VarTree::VKsimple
;
1489 } else if (*p
== 'L' && (p
[1] == '"' || p
[1] == '\'')) {
1490 skipString(p
); // wchar_t string
1491 variable
->m_varKind
= VarTree::VKsimple
;
1492 } else if (*p
== '<') {
1493 // if this value is part of an array, it might be followed
1494 // by <repeats 15 times>, which we don't skip here
1495 if (strncmp(p
, "<repeats ", 9) == 0)
1497 // sometimes, a reference is followed by an error message:
1498 // @0x100400f08: <error reading variable>
1499 // in this case, we do not skip the text here, but leave it
1500 // for the subsequent parsing pass induced by the reference
1501 else if (reference
&& strncmp(p
, "<error reading", 14) == 0)
1504 skipNestedAngles(p
);
1505 checkMultiPart
= true;
1507 } else if (strncmp(p
, ", this adjustment ", 18) == 0) {
1508 // pointers-to-member are sometimes followed by
1509 // a "this adjustment" hint
1514 // we know that this is not a dereferencable pointer
1515 variable
->m_varKind
= VarTree::VKsimple
;
1516 ++start
; // skip ',', will be picked up below
1519 // there is always a blank before the string,
1520 // which we will include in the final string value
1521 variable
->m_value
+= QString::fromLatin1(start
-1, (p
- start
)+1);
1525 if (variable
->m_value
.length() == 0) {
1526 TRACE("parse error: no value for " + variable
->m_name
);
1530 // final white space
1535 * If this was a reference, the value follows. It might even be a
1536 * composite variable!
1546 static bool parseNested(const char*& s
, ExprValue
* variable
)
1548 // could be a structure or an array
1552 bool isStruct
= false;
1554 * If there is a name followed by an = or an < -- which starts a type
1555 * name -- or "static", it is a structure
1557 if (*p
== '<' || *p
== '}') {
1559 } else if (strncmp(p
, "static ", 7) == 0) {
1561 } else if (isalpha(*p
) || *p
== '_' || *p
== '$') {
1562 // look ahead for a comma after the name
1568 p
= s
; /* rescan the name */
1571 if (!parseVarSeq(p
, variable
)) {
1574 variable
->m_varKind
= VarTree::VKstruct
;
1576 if (!parseValueSeq(p
, variable
)) {
1579 variable
->m_varKind
= VarTree::VKarray
;
1585 static bool parseVarSeq(const char*& s
, ExprValue
* variable
)
1587 // parse a comma-separated sequence of variables
1588 ExprValue
* var
= variable
; /* var != 0 to indicate success if empty seq */
1592 if (strncmp(s
, "<No data fields>}", 17) == 0)
1594 // no member variables, so break out immediately
1595 s
+= 16; /* go to the closing brace */
1600 break; /* syntax error */
1601 variable
->appendChild(var
);
1604 // skip the comma and whitespace
1611 static bool parseValueSeq(const char*& s
, ExprValue
* variable
)
1613 // parse a comma-separated sequence of variables
1618 name
.sprintf("[%d]", index
);
1619 ExprValue
* var
= new ExprValue(name
, VarTree::NKplain
);
1620 good
= parseValue(s
, var
);
1625 // a value may be followed by "<repeats 45 times>"
1626 if (strncmp(s
, "<repeats ", 9) == 0) {
1629 int l
= strtol(s
, &end
, 10);
1630 if (end
== s
|| strncmp(end
, " times>", 7) != 0) {
1631 // should not happen
1635 TRACE(QString().sprintf("found <repeats %d times> in array", l
));
1636 // replace name and advance index
1637 name
.sprintf("[%d .. %d]", index
, index
+l
-1);
1640 // skip " times>" and space
1642 // possible final space
1647 variable
->appendChild(var
);
1648 // long arrays may be terminated by '...'
1649 if (strncmp(s
, "...", 3) == 0) {
1651 ExprValue
* var
= new ExprValue("...", VarTree::NKplain
);
1652 var
->m_value
= i18n("<additional entries of the array suppressed>");
1653 variable
->appendChild(var
);
1659 // skip the comma and whitespace
1662 // sometimes there is a closing brace after a comma
1670 * Parses a stack frame.
1672 static void parseFrameInfo(const char*& s
, QString
& func
,
1673 QString
& file
, int& lineNo
, DbgAddr
& address
)
1677 // next may be a hexadecimal address
1679 const char* start
= p
;
1683 while (isxdigit(*p
))
1685 address
= QString::fromLatin1(start
, p
-start
);
1686 if (strncmp(p
, " in ", 4) == 0)
1689 address
= DbgAddr();
1691 const char* start
= p
;
1692 // check for special signal handler frame
1693 if (strncmp(p
, "<signal handler called>", 23) == 0) {
1694 func
= QString::fromLatin1(start
, 23);
1704 * Skip the function name. It is terminated by a left parenthesis
1705 * which does not delimit "(anonymous namespace)" and which is
1706 * outside the angle brackets <> of template parameter lists
1707 * and is preceded by a space.
1712 // check for operator<< and operator<
1713 if (p
-start
>= 8 && strncmp(p
-8, "operator", 8) == 0)
1721 // skip template parameter list
1722 skipNestedAngles(p
);
1724 } else if (*p
== '(') {
1725 // this skips "(anonymous namespace)" as well as the formal
1726 // parameter list of the containing function if this is a member
1727 // of a nested class
1728 skipNestedWithString(p
, '(', ')');
1729 } else if (*p
== ' ') {
1732 break; // parameter list found
1746 * Skip parameters. But notice that for complicated conversion
1747 * functions (eg. "operator int(**)()()", ie. convert to pointer to
1748 * pointer to function) as well as operator()(...) we have to skip
1749 * additional pairs of parentheses. Furthermore, recent gdbs write the
1750 * demangled name followed by the arguments in a pair of parentheses,
1751 * where the demangled name can end in "const".
1754 skipNestedWithString(p
, '(', ')');
1757 if (strncmp(p
, "const", 5) == 0) {
1761 } while (*p
== '(');
1763 // check for file position
1764 if (strncmp(p
, "at ", 3) == 0) {
1766 const char* fileStart
= p
;
1767 // go for the end of the line
1768 while (*p
!= '\0' && *p
!= '\n')
1770 // search back for colon
1771 const char* colon
= p
;
1774 } while (*colon
!= ':');
1775 file
= QString::fromLatin1(fileStart
, colon
-fileStart
);
1776 lineNo
= atoi(colon
+1)-1;
1781 // check for "from shared lib"
1782 if (strncmp(p
, "from ", 5) == 0) {
1784 // go for the end of the line
1785 while (*p
!= '\0' && *p
!= '\n')
1794 // construct the function name (including file info)
1798 func
= QString::fromLatin1(start
, p
-start
-1); /* don't include \n */
1803 * Replace \n (and whitespace around it) in func by a blank. We cannot
1804 * use QString::simplified() for this because this would also
1805 * simplify space that belongs to a string arguments that gdb sometimes
1806 * prints in the argument lists of the function.
1808 ASSERT(!isspace(func
[0].toLatin1())); // there must be non-white before first \n
1810 while ((nl
= func
.indexOf('\n', nl
)) >= 0) {
1811 // search back to the beginning of the whitespace
1812 int startWhite
= nl
;
1815 } while (isspace(func
[startWhite
].toLatin1()));
1817 // search forward to the end of the whitespace
1820 } while (isspace(func
[nl
].toLatin1()));
1822 func
.replace(startWhite
, nl
-startWhite
, " ");
1823 /* continue searching for more \n's at this place: */
1830 * Parses a stack frame including its frame number
1832 static bool parseFrame(const char*& s
, int& frameNo
, QString
& func
,
1833 QString
& file
, int& lineNo
, DbgAddr
& address
)
1836 // #1 0x8048881 in Dl::Dl (this=0xbffff418, r=3214) at testfile.cpp:72
1837 // Breakpoint 3, Cl::f(int) const (this=0xbffff3c0, x=17) at testfile.cpp:155
1839 // must start with a hash mark followed by number
1840 // or with "Breakpoint " followed by number and comma
1844 s
++; /* skip the hash mark */
1845 } else if (strncmp(s
, "Breakpoint ", 11) == 0) {
1846 if (!isdigit(s
[11]))
1848 s
+= 11; /* skip "Breakpoint" */
1856 while (isspace(*s
) || *s
== ',')
1858 parseFrameInfo(s
, func
, file
, lineNo
, address
);
1862 void GdbDriver::parseBackTrace(const char* output
, std::list
<StackFrame
>& stack
)
1865 int lineNo
, frameNo
;
1868 while (::parseFrame(output
, frameNo
, func
, file
, lineNo
, address
)) {
1869 stack
.push_back(StackFrame());
1870 StackFrame
* frm
= &stack
.back();
1871 frm
->frameNo
= frameNo
;
1872 frm
->fileName
= file
;
1873 frm
->lineNo
= lineNo
;
1874 frm
->address
= address
;
1875 frm
->var
= new ExprValue(func
, VarTree::NKplain
);
1879 bool GdbDriver::parseFrameChange(const char* output
, int& frameNo
,
1880 QString
& file
, int& lineNo
, DbgAddr
& address
)
1883 return ::parseFrame(output
, frameNo
, func
, file
, lineNo
, address
);
1887 bool GdbDriver::parseBreakList(const char* output
, std::list
<Breakpoint
>& brks
)
1889 // skip first line, which is the headline
1890 const char* p
= strchr(output
, '\n');
1900 while (*p
!= '\0') {
1903 bp
.id
= strtol(p
, &dummy
, 10); /* don't care about overflows */
1905 // check for continued <MULTIPLE> breakpoint
1906 if (*p
== '.' && isdigit(p
[1]))
1908 // continuation: skip type and disposition
1914 if (strncmp(p
, "breakpoint", 10) == 0) {
1916 } else if (strncmp(p
, "hw watchpoint", 13) == 0) {
1917 bp
.type
= Breakpoint::watchpoint
;
1919 } else if (strncmp(p
, "watchpoint", 10) == 0) {
1920 bp
.type
= Breakpoint::watchpoint
;
1927 bp
.temporary
= *p
++ == 'd';
1929 while (*p
!= '\0' && !isspace(*p
)) /* "keep" or "del" */
1935 bp
.enabled
= *p
++ == 'y';
1936 while (*p
!= '\0' && !isspace(*p
)) /* "y" or "n" */
1941 // the address, if present
1942 if (bp
.type
== Breakpoint::breakpoint
&&
1943 strncmp(p
, "0x", 2) == 0)
1945 const char* start
= p
;
1946 while (*p
!= '\0' && !isspace(*p
))
1948 bp
.address
= QString::fromLatin1(start
, p
-start
);
1949 while (isspace(*p
) && *p
!= '\n')
1954 // remainder is location, hit and ignore count, condition
1955 end
= strchr(p
, '\n');
1958 p
+= bp
.location
.length();
1960 // location of a <MULTIPLE> filled in from subsequent breakpoints
1961 if (strncmp(p
, "<MULTIPLE>", 10) != 0)
1962 bp
.location
= QString::fromLatin1(p
, end
-p
).trimmed();
1963 p
= end
+1; /* skip over \n */
1966 // may be continued in next line
1967 while (isspace(*p
)) { /* p points to beginning of line */
1968 // skip white space at beginning of line
1972 end
= strchr(p
, '\n');
1976 if (strncmp(p
, "breakpoint already hit", 22) == 0) {
1977 // extract the hit count
1979 bp
.hitCount
= strtol(p
, &dummy
, 10);
1980 TRACE(QString("hit count %1").arg(bp
.hitCount
));
1981 } else if (strncmp(p
, "stop only if ", 13) == 0) {
1982 // extract condition
1984 bp
.condition
= QString::fromLatin1(p
, end
-p
).trimmed();
1985 TRACE("condition: "+bp
.condition
);
1986 } else if (strncmp(p
, "ignore next ", 12) == 0) {
1987 // extract ignore count
1989 bp
.ignoreCount
= strtol(p
, &dummy
, 10);
1990 TRACE(QString("ignore count %1").arg(bp
.ignoreCount
));
1992 // indeed a continuation
1993 bp
.location
+= " " + QString::fromLatin1(p
, end
-p
).trimmed();
1997 p
++; /* skip '\n' */
2000 if (brks
.empty() || brks
.back().id
!= bp
.id
) {
2003 // this is a continuation; fill in location if not yet set
2004 // otherwise, drop this breakpoint
2005 Breakpoint
& mbp
= brks
.back();
2006 if (mbp
.location
.isEmpty() && !bp
.location
.isEmpty()) {
2007 mbp
.location
= bp
.location
;
2008 mbp
.address
= bp
.address
;
2009 } else if (mbp
.address
.isEmpty() && !bp
.address
.isEmpty()) {
2010 mbp
.address
= bp
.address
;
2017 std::list
<ThreadInfo
> GdbDriver::parseThreadList(const char* output
)
2019 std::list
<ThreadInfo
> threads
;
2020 if (strcmp(output
, "\n") == 0 ||
2021 strncmp(output
, "No stack.", 9) == 0 ||
2022 strncmp(output
, "No threads.", 11) == 0) {
2027 bool newFormat
= false;
2028 const char* p
= output
;
2029 while (*p
!= '\0') {
2031 // seach look for thread id, watching out for the focus indicator
2032 thr
.hasFocus
= false;
2033 skipSpace(p
); /* may be \n from prev line: see "No stack" below */
2035 // recent GDBs write a header line; skip it
2036 if (threads
.empty() && strncmp(p
, "Id Target", 11) == 0) {
2037 p
= strchr(p
, '\n');
2041 continue; // next line please, '\n' is skipped above
2045 thr
.hasFocus
= true;
2047 // there follows only whitespace
2050 char *temp_end
= NULL
; /* we need a non-const 'end' for strtol to use...*/
2051 thr
.id
= strtol(p
, &temp_end
, 10);
2054 // syntax error: no number found; bail out
2062 * Now follows the thread's SYSTAG.
2065 // In the old format, it is terminated by two blanks.
2066 end
= strstr(p
, " ");
2068 // syntax error; bail out
2073 // In the new format lies crazyness: there is no definitive
2074 // end marker. At best we can guess when the SYSTAG ends.
2075 // A typical thread list on Linux looks like this:
2077 // Id Target Id Frame
2078 // 2 Thread 0x7ffff7854700 (LWP 10827) "thrserver" 0x00007ffff7928631 in clone () from /lib64/libc.so.6
2079 // * 1 Thread 0x7ffff7fcc700 (LWP 10808) "thrserver" main () at thrserver.c:84
2081 // Looking at GDB's code, the Target Id ends in tokens that
2082 // are bracketed by parentheses or quotes. Therefore,
2083 // we skip (at most) two tokens ('Thread' and the address),
2084 // and then all parts that are in parentheses or quotes.
2091 } else if (*end
== '(') {
2092 skipNested(end
, '(', ')');
2095 while (*end
&& !isspace(*end
))
2104 thr
.threadName
= QString::fromLatin1(p
, end
-p
).trimmed();
2108 * Now follows a standard stack frame. Sometimes, however, gdb
2109 * catches a thread at an instant where it doesn't have a stack.
2111 if (strncmp(p
, "[No stack.]", 11) != 0) {
2112 ::parseFrameInfo(p
, thr
.function
, thr
.fileName
, thr
.lineNo
, thr
.address
);
2114 thr
.function
= "[No stack]";
2116 p
+= 11; /* \n is skipped above */
2119 threads
.push_back(thr
);
2124 static bool parseNewBreakpoint(const char* o
, int& id
,
2125 QString
& file
, int& lineNo
, QString
& address
);
2126 static bool parseNewWatchpoint(const char* o
, int& id
,
2129 bool GdbDriver::parseBreakpoint(const char* output
, int& id
,
2130 QString
& file
, int& lineNo
, QString
& address
)
2132 // skip lines of that begin with "(Cannot find"
2133 while (strncmp(output
, "(Cannot find", 12) == 0 ||
2134 strncmp(output
, "Note: breakpoint", 16) == 0)
2136 output
= strchr(output
, '\n');
2139 output
++; /* skip newline */
2142 if (strncmp(output
, "Breakpoint ", 11) == 0) {
2143 output
+= 11; /* skip "Breakpoint " */
2144 return ::parseNewBreakpoint(output
, id
, file
, lineNo
, address
);
2145 } else if (strncmp(output
, "Temporary breakpoint ", 21) == 0) {
2147 return ::parseNewBreakpoint(output
, id
, file
, lineNo
, address
);
2148 } else if (strncmp(output
, "Hardware watchpoint ", 20) == 0) {
2150 return ::parseNewWatchpoint(output
, id
, address
);
2151 } else if (strncmp(output
, "Watchpoint ", 11) == 0) {
2153 return ::parseNewWatchpoint(output
, id
, address
);
2158 static bool parseNewBreakpoint(const char* o
, int& id
,
2159 QString
& file
, int& lineNo
, QString
& address
)
2163 id
= strtoul(o
, &p
, 10);
2167 // check for the address
2168 if (strncmp(p
, " at 0x", 6) == 0) {
2169 char* start
= p
+4; /* skip " at ", but not 0x */
2171 while (isxdigit(*p
))
2173 address
= QString::fromLatin1(start
, p
-start
);
2177 * Mostly, GDB responds with this syntax:
2179 * Breakpoint 1 at 0x400b94: file multibrkpt.cpp, line 9. (2 locations)
2181 * but sometimes it uses this syntax:
2183 * Breakpoint 4 at 0x804f158: lotto739.cpp:95. (3 locations)
2185 const char* fileEnd
, *numStart
= 0;
2186 const char* fileStart
= strstr(p
, "file ");
2190 fileEnd
= strstr(fileStart
, ", line ");
2192 numStart
= fileEnd
+ 7;
2194 if (numStart
== 0 && p
[0] == ':' && p
[1] == ' ')
2197 skipSpace(fileStart
);
2198 fileEnd
= strchr(fileStart
, ':');
2200 numStart
= fileEnd
+ 1;
2203 return !address
.isEmpty(); /* parse error only if there's no address */
2205 QString fileName
= QString::fromLatin1(fileStart
, fileEnd
-fileStart
);
2206 int line
= strtoul(numStart
, &p
, 10);
2211 lineNo
= line
-1; /* zero-based! */
2215 static bool parseNewWatchpoint(const char* o
, int& id
,
2220 id
= strtoul(o
, &p
, 10);
2224 if (strncmp(p
, ": ", 2) != 0)
2228 // all the rest on the line is the expression
2229 expr
= QString::fromLatin1(p
, strlen(p
)).trimmed();
2233 void GdbDriver::parseLocals(const char* output
, std::list
<ExprValue
*>& newVars
)
2235 // check for possible error conditions
2236 if (strncmp(output
, "No symbol table", 15) == 0)
2241 while (*output
!= '\0') {
2243 if (*output
== '\0')
2245 // skip occurrences of "No locals" and "No args"
2246 if (strncmp(output
, "No locals", 9) == 0 ||
2247 strncmp(output
, "No arguments", 12) == 0)
2249 output
= strchr(output
, '\n');
2256 ExprValue
* variable
= parseVar(output
);
2257 if (variable
== 0) {
2260 // do not add duplicates
2261 for (std::list
<ExprValue
*>::iterator o
= newVars
.begin(); o
!= newVars
.end(); ++o
) {
2262 if ((*o
)->m_name
== variable
->m_name
) {
2267 newVars
.push_back(variable
);
2272 ExprValue
* GdbDriver::parsePrintExpr(const char* output
, bool wantErrorValue
)
2275 // check for error conditions
2276 if (!parseErrorMessage(output
, var
, wantErrorValue
))
2278 // parse the variable
2279 var
= parseVar(output
);
2284 bool GdbDriver::parseChangeWD(const char* output
, QString
& message
)
2286 bool isGood
= false;
2287 message
= QString(output
).simplified();
2288 if (message
.isEmpty()) {
2289 message
= i18n("New working directory: ") + m_programWD
;
2295 bool GdbDriver::parseChangeExecutable(const char* output
, QString
& message
)
2300 * Lines starting with the following do not indicate errors:
2301 * Using host libthread_db
2302 * (no debugging symbols found)
2303 * Reading symbols from
2305 while (strncmp(output
, "Reading symbols from", 20) == 0 ||
2306 strncmp(output
, "done.", 5) == 0 ||
2307 strncmp(output
, "Missing separate debuginfo", 26) == 0 ||
2308 strncmp(output
, "Try: ", 5) == 0 ||
2309 strncmp(output
, "Using host libthread_db", 23) == 0 ||
2310 strncmp(output
, "(no debugging symbols found)", 28) == 0)
2312 // this line is good, go to the next one
2313 const char* end
= strchr(output
, '\n');
2315 output
+= strlen(output
);
2321 * If we've parsed all lines, there was no error.
2323 return output
[0] == '\0';
2326 bool GdbDriver::parseCoreFile(const char* output
)
2328 // if command succeeded, gdb emits a line starting with "#0 "
2329 return strstr(output
, "\n#0 ") != 0;
2332 uint
GdbDriver::parseProgramStopped(const char* output
, bool haveCoreFile
,
2335 // optionally: "program changed, rereading symbols",
2337 // "Program exited normally"
2338 // "Program terminated with wignal SIGSEGV"
2339 // "Program received signal SIGINT" or other signal
2341 // GDB since 7.3 prints
2342 // "[Inferior 1 (process 13400) exited normally]"
2343 // "[Inferior 1 (process 14698) exited with code 01]"
2345 // go through the output, line by line, checking what we have
2346 const char* start
= output
- 1;
2347 uint flags
= SFprogramActive
;
2348 message
= QString();
2350 start
++; /* skip '\n' */
2352 if (strncmp(start
, "Program ", 8) == 0 ||
2353 strncmp(start
, "ptrace: ", 8) == 0) {
2355 * When we receive a signal, the program remains active.
2357 * Special: If we "stopped" in a corefile, the string "Program
2358 * terminated with signal"... is displayed. (Normally, we see
2359 * "Program received signal"... when a signal happens.)
2361 if (strncmp(start
, "Program exited", 14) == 0 ||
2362 (strncmp(start
, "Program terminated", 18) == 0 && !haveCoreFile
) ||
2363 strncmp(start
, "ptrace: ", 8) == 0)
2365 flags
&= ~SFprogramActive
;
2369 const char* endOfMessage
= strchr(start
, '\n');
2370 if (endOfMessage
== 0)
2371 endOfMessage
= start
+ strlen(start
);
2372 message
= QString::fromLatin1(start
, endOfMessage
-start
);
2373 } else if (strncmp(start
, "[Inferior ", 10) == 0) {
2374 const char* p
= start
+ 10;
2375 // skip number and space
2376 while (*p
&& !isspace(*p
))
2380 skipNested(p
, '(', ')');
2381 if (strncmp(p
, " exited ", 8) == 0) {
2382 flags
&= ~SFprogramActive
;
2385 const char* end
= strchr(p
, '\n');
2387 end
= p
+ strlen(p
);
2388 // strip [] from the message
2389 message
= QString::fromLatin1(start
+1, end
-start
-2);
2392 } else if (strncmp(start
, "Breakpoint ", 11) == 0) {
2394 * We stopped at a (permanent) breakpoint (gdb doesn't tell us
2395 * that it stopped at a temporary breakpoint).
2397 flags
|= SFrefreshBreak
;
2398 } else if (strstr(start
, "re-reading symbols.") != 0) {
2399 flags
|= SFrefreshSource
;
2402 // next line, please
2403 start
= strchr(start
, '\n');
2404 } while (start
!= 0);
2407 * Gdb only notices when new threads have appeared, but not when a
2408 * thread finishes. So we always have to assume that the list of
2409 * threads has changed.
2411 flags
|= SFrefreshThreads
;
2416 QStringList
GdbDriver::parseSharedLibs(const char* output
)
2419 if (strncmp(output
, "No shared libraries loaded", 26) == 0)
2422 // parse the table of shared libraries
2424 // strip off head line
2425 output
= strchr(output
, '\n');
2428 output
++; /* skip '\n' */
2430 while (*output
!= '\0') {
2431 // format of a line is
2432 // 0x404c5000 0x40580d90 Yes /lib/libc.so.5
2433 // 3 blocks of non-space followed by space
2434 for (int i
= 0; *output
!= '\0' && i
< 3; i
++) {
2435 while (*output
!= '\0' && !isspace(*output
)) { /* non-space */
2438 skipSpace(output
); /* space */
2440 if (*output
== '\0')
2442 const char* start
= output
;
2443 output
= strchr(output
, '\n');
2445 output
= start
+ strlen(start
);
2446 shlibName
= QString::fromLatin1(start
, output
-start
);
2447 if (*output
!= '\0')
2449 shlibs
.append(shlibName
);
2450 TRACE("found shared lib " + shlibName
);
2455 bool GdbDriver::parseFindType(const char* output
, QString
& type
)
2457 if (strncmp(output
, "type = ", 7) != 0)
2461 * Everything else is the type. We strip off any leading "const" and any
2462 * trailing "&" on the grounds that neither affects the decoding of the
2463 * object. We also strip off all white-space from the type.
2466 if (strncmp(output
, "const ", 6) == 0)
2469 type
.replace(QRegExp("\\s+"), "");
2470 if (type
.endsWith("&"))
2471 type
.truncate(type
.length() - 1);
2475 std::list
<RegisterInfo
> GdbDriver::parseRegisters(const char* output
)
2477 std::list
<RegisterInfo
> regs
;
2478 if (strncmp(output
, "The program has no registers now", 32) == 0) {
2482 // parse register values
2483 while (*output
!= '\0')
2486 // skip space at the start of the line
2490 const char* start
= output
;
2491 while (*output
!= '\0' && !isspace(*output
))
2493 if (*output
== '\0')
2495 reg
.regName
= QString::fromLatin1(start
, output
-start
);
2502 * If we find a brace now, this is a vector register. We look for
2503 * the closing brace and treat the result as cooked value.
2508 skipNested(output
, '{', '}');
2509 value
= QString::fromLatin1(start
, output
-start
).simplified();
2510 // skip space, but not the end of line
2511 while (isspace(*output
) && *output
!= '\n')
2513 // get rid of the braces at the begining and the end
2515 if (value
[value
.length()-1] == '}') {
2516 value
= value
.left(value
.length()-1);
2518 // gdb 5.3 doesn't print a separate set of raw values
2519 if (*output
== '{') {
2520 // another set of vector follows
2521 // what we have so far is the raw value
2522 reg
.rawValue
= value
;
2525 skipNested(output
, '{', '}');
2526 value
= QString::fromLatin1(start
, output
-start
).simplified();
2529 // find first type that does not have an array, this is the RAW value
2530 const char* end
=start
;
2532 const char* cur
=start
;
2534 while (*cur
!= '=' && cur
<end
)
2537 while (isspace(*cur
) && cur
<end
)
2539 if (isNumberish(*cur
)) {
2541 while (*end
&& (*end
!='}') && (*end
!=',') && (*end
!='\n'))
2543 QString rawValue
= QString::fromLatin1(cur
, end
-cur
).simplified();
2544 reg
.rawValue
= rawValue
;
2546 if (rawValue
.left(2)=="0x") {
2547 // ok we have a raw value, now get it's type
2549 while (isspace(*end
) || *end
=='=') end
--;
2552 while (*cur
!='{' && *cur
!=' ')
2555 reg
.type
= QString::fromLatin1(cur
, end
-cur
);
2562 // skip to the end of line
2563 while (*output
!= '\0' && *output
!= '\n')
2565 // get rid of the braces at the begining and the end
2567 if (value
[value
.length()-1] == '}') {
2568 value
.truncate(value
.length()-1);
2571 reg
.cookedValue
= value
;
2576 // the rest of the line is the register value
2578 output
= strchr(output
,'\n');
2580 output
= start
+ strlen(start
);
2581 value
+= QString::fromLatin1(start
, output
-start
).simplified();
2584 * Look ahead: if the subsequent line is indented, it continues
2585 * the current register value.
2587 if (output
!= 0 && isspace(output
[1]))
2595 * We split the raw from the cooked values.
2596 * Some modern gdbs explicitly say: "0.1234 (raw 0x3e4567...)".
2597 * Here, the cooked value comes first, and the raw value is in
2600 int pos
= value
.indexOf(" (raw ");
2603 reg
.cookedValue
= value
.left(pos
);
2604 reg
.rawValue
= value
.mid(pos
+6);
2605 if (reg
.rawValue
.right(1) == ")") // remove closing bracket
2606 reg
.rawValue
.truncate(reg
.rawValue
.length()-1);
2611 * In other cases we split off the first token (separated by
2612 * whitespace). It is the raw value. The remainder of the line
2613 * is the cooked value.
2615 int pos
= value
.indexOf(' ');
2617 reg
.rawValue
= value
;
2618 reg
.cookedValue
= QString();
2620 reg
.rawValue
= value
.left(pos
);
2621 reg
.cookedValue
= value
.mid(pos
+1);
2625 if (*output
!= '\0')
2626 output
++; /* skip '\n' */
2628 regs
.push_back(reg
);
2633 bool GdbDriver::parseInfoLine(const char* output
, QString
& addrFrom
, QString
& addrTo
)
2635 // "is at address" or "starts at address"
2636 const char* start
= strstr(output
, "s at address ");
2641 const char* p
= start
;
2642 while (*p
!= '\0' && !isspace(*p
))
2644 addrFrom
= QString::fromLatin1(start
, p
-start
);
2646 start
= strstr(p
, "and ends at ");
2654 while (*p
!= '\0' && !isspace(*p
))
2656 addrTo
= QString::fromLatin1(start
, p
-start
);
2661 std::list
<DisassembledCode
> GdbDriver::parseDisassemble(const char* output
)
2663 std::list
<DisassembledCode
> code
;
2665 if (strncmp(output
, "Dump of assembler", 17) != 0) {
2673 // remove first line
2674 const char* p
= strchr(output
, '\n');
2676 return code
; /* not a regular output */
2681 const char* end
= strstr(output
, "End of assembler");
2683 end
= p
+ strlen(p
);
2685 // remove function offsets from the lines
2689 // skip initial space or PC pointer ("=>", since gdb 7.1)
2693 else if (p
[0] == '=' && p
[1] == '>')
2698 const char* start
= p
;
2700 while (p
!= end
&& !isspace(*p
))
2702 c
.address
= QString::fromLatin1(start
, p
-start
);
2704 // function name (enclosed in '<>', followed by ':')
2705 while (p
!= end
&& *p
!= '<')
2708 skipNestedAngles(p
);
2713 while (p
!= end
&& isspace(*p
))
2716 // code until end of line
2718 while (p
!= end
&& *p
!= '\n')
2720 if (p
!= end
) /* include '\n' */
2723 c
.code
= QString::fromLatin1(start
, p
-start
);
2729 QString
GdbDriver::parseMemoryDump(const char* output
, std::list
<MemoryDump
>& memdump
)
2731 if (isErrorExpr(output
)) {
2732 // error; strip space
2733 QString msg
= output
;
2734 return msg
.trimmed();
2737 const char* p
= output
; /* save typing */
2743 const char* start
= p
;
2744 while (*p
!= '\0' && *p
!= ':' && !isspace(*p
))
2746 md
.address
= QString::fromLatin1(start
, p
-start
);
2748 // parse function offset
2751 while (*p
!= '\0' && !(*p
== ':' && isspace(p
[1])))
2753 md
.address
.fnoffs
= QString::fromLatin1(start
, p
-start
);
2757 // skip space; this may skip a new-line char!
2759 // everything to the end of the line is the memory dump
2760 const char* end
= strchr(p
, '\n');
2762 md
.dump
= QString::fromLatin1(p
, end
-p
);
2765 md
.dump
= QString::fromLatin1(p
, strlen(p
));
2768 memdump
.push_back(md
);
2774 QString
GdbDriver::editableValue(VarTree
* value
)
2776 QByteArray ba
= value
->value().toLatin1();
2777 const char* s
= ba
.constData();
2779 // if the variable is a pointer value that contains a cast,
2782 skipNested(s
, '(', ')');
2788 const char* start
= s
;
2790 if (strncmp(s
, "0x", 2) == 0)
2793 while (isxdigit(*s
))
2797 * What we saw so far might have been a reference. If so, edit the
2798 * referenced value. Otherwise, edit the pointer.
2806 // if it's a pointer to a string, remove the string
2807 const char* end
= s
;
2811 return QString::fromLatin1(start
, end
-start
);
2814 return QString::fromLatin1(start
, strlen(start
));
2818 // else leave it unchanged (or stripped of the reference preamble)
2822 QString
GdbDriver::parseSetVariable(const char* output
)
2824 // if there is any output, it is an error message
2825 QString msg
= output
;
2826 return msg
.trimmed();
2830 #include "gdbdriver.moc"