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
, bool clearLow
)
591 assert(cmd
>= 0 && cmd
< NUM_CMDS
);
592 assert(cmds
[cmd
].argsNeeded
== GdbCmdInfo::argNone
);
595 m_haveCoreFile
= false;
598 return executeCmdString(cmd
, cmds
[cmd
].fmt
, clearLow
);
601 CmdQueueItem
* GdbDriver::executeCmd(DbgCommand cmd
, QString strArg
,
604 return executeCmdString(cmd
, makeCmdString(cmd
, strArg
), clearLow
);
607 CmdQueueItem
* GdbDriver::executeCmd(DbgCommand cmd
, int intArg
,
611 return executeCmdString(cmd
, makeCmdString(cmd
, intArg
), clearLow
);
614 CmdQueueItem
* GdbDriver::executeCmd(DbgCommand cmd
, QString strArg
, int intArg
,
617 return executeCmdString(cmd
, makeCmdString(cmd
, strArg
, intArg
), clearLow
);
620 CmdQueueItem
* GdbDriver::executeCmd(DbgCommand cmd
, QString strArg1
, QString strArg2
,
623 return executeCmdString(cmd
, makeCmdString(cmd
, strArg1
, strArg2
), clearLow
);
626 CmdQueueItem
* GdbDriver::executeCmd(DbgCommand cmd
, int intArg1
, int intArg2
,
629 return executeCmdString(cmd
, makeCmdString(cmd
, intArg1
, intArg2
), clearLow
);
632 CmdQueueItem
* GdbDriver::queueCmd(DbgCommand cmd
, QueueMode mode
)
634 return queueCmdString(cmd
, cmds
[cmd
].fmt
, mode
);
637 CmdQueueItem
* GdbDriver::queueCmd(DbgCommand cmd
, QString strArg
,
640 return queueCmdString(cmd
, makeCmdString(cmd
, strArg
), mode
);
643 CmdQueueItem
* GdbDriver::queueCmd(DbgCommand cmd
, int intArg
,
646 return queueCmdString(cmd
, makeCmdString(cmd
, intArg
), mode
);
649 CmdQueueItem
* GdbDriver::queueCmd(DbgCommand cmd
, QString strArg
, int intArg
,
652 return queueCmdString(cmd
, makeCmdString(cmd
, strArg
, intArg
), mode
);
655 CmdQueueItem
* GdbDriver::queueCmd(DbgCommand cmd
, QString strArg1
, QString strArg2
,
658 return queueCmdString(cmd
, makeCmdString(cmd
, strArg1
, strArg2
), mode
);
661 void GdbDriver::terminate()
663 if (m_state
!= DSidle
)
665 ::kill(pid(), SIGINT
);
666 m_state
= DSinterrupted
;
672 void GdbDriver::detachAndTerminate()
674 ::kill(pid(), SIGINT
);
676 executeCmdString(DCinitialize
, "detach\nquit\n", true);
679 void GdbDriver::interruptInferior()
681 ::kill(pid(), SIGINT
);
682 // remove accidentally queued commands
686 static bool isErrorExpr(const char* output
)
689 strncmp(output
, "Cannot access memory at", 23) == 0 ||
690 strncmp(output
, "Attempt to dereference a generic pointer", 40) == 0 ||
691 strncmp(output
, "Attempt to take contents of ", 28) == 0 ||
692 strncmp(output
, "Attempt to use a type name as an expression", 43) == 0 ||
693 strncmp(output
, "There is no member or method named", 34) == 0 ||
694 strncmp(output
, "A parse error in expression", 27) == 0 ||
695 strncmp(output
, "No symbol \"", 11) == 0 ||
696 strncmp(output
, "Internal error: ", 16) == 0;
699 static void skipSpace(const char*& p
)
705 static void skipDecimal(const char*& p
)
712 * Returns true if the output is an error message. If wantErrorValue is
713 * true, a new ExprValue object is created and filled with the error message.
714 * If there are warnings, they are skipped and output points past the warnings
715 * on return (even if there \e are errors).
717 static bool parseErrorMessage(const char*& output
,
718 ExprValue
*& variable
, bool wantErrorValue
)
723 while (strncmp(output
, "warning:", 8) == 0)
725 const char* end
= strchr(output
+8, '\n');
727 output
+= strlen(output
);
733 if (isErrorExpr(output
))
735 if (wantErrorValue
) {
736 // put the error message as value in the variable
737 variable
= new ExprValue(QString(), VarTree::NKplain
);
738 const char* endMsg
= strchr(output
, '\n');
740 endMsg
= output
+ strlen(output
);
741 variable
->m_value
= QString::fromLatin1(output
, endMsg
-output
);
750 #if QT_VERSION >= 300
760 void GdbDriver::setPrintQStringDataCmd(const char* cmd
)
762 // don't accept the command if it is empty
763 if (cmd
== 0 || *cmd
== '\0')
765 assert(strlen(cmd
) <= MAX_FMTLEN
);
766 cmds
[DCprintQStringStruct
].fmt
= cmd
;
769 ExprValue
* GdbDriver::parseQCharArray(const char* output
, bool wantErrorValue
, bool qt3like
)
771 ExprValue
* variable
= 0;
774 * Parse off white space. gdb sometimes prints white space first if the
775 * printed array leaded to an error.
779 // special case: empty string (0 repetitions)
780 if (strncmp(output
, "Invalid number 0 of repetitions", 31) == 0)
782 variable
= new ExprValue(QString(), VarTree::NKplain
);
783 variable
->m_value
= "\"\"";
787 // check for error conditions
788 if (parseErrorMessage(output
, variable
, wantErrorValue
))
794 const char* p
= output
;
804 // this is the real data
810 enum { wasNothing
, wasChar
, wasRepeat
} lastThing
= wasNothing
;
812 * A matrix for separators between the individual "things"
813 * that are added to the string. The first index is a bool,
814 * the second index is from the enum above.
816 static const char* separator
[2][3] = {
817 { "\"", 0, ", \"" }, /* normal char is added */
818 { "'", "\", '", ", '" } /* repeated char is added */
821 while (isdigit(*p
)) {
824 unsigned short value
= (unsigned short) strtoul(p
, &end
, 0);
826 goto error
; /* huh? no valid digits */
827 // skip separator and search for a repeat count
829 while (isspace(*p
) || *p
== ',')
831 bool repeats
= strncmp(p
, "<repeats ", 9) == 0;
833 const char* start
= p
;
834 p
= strchr(p
+9, '>'); /* search end and advance */
838 repeatCount
= QString::fromLatin1(start
, p
-start
);
839 while (isspace(*p
) || *p
== ',')
842 // p is now at the next char (or the end)
844 // interpret the value as a QChar
845 // TODO: make cross-architecture compatible
851 (unsigned short&)ch
= value
;
855 ch
.setRow(c
.qch
.row
);
856 ch
.setCell(c
.qch
.cell
);
860 // escape a few frequently used characters
861 char escapeCode
= '\0';
862 switch (ch
.toLatin1()) {
863 case '\n': escapeCode
= 'n'; break;
864 case '\r': escapeCode
= 'r'; break;
865 case '\t': escapeCode
= 't'; break;
866 case '\b': escapeCode
= 'b'; break;
867 case '\"': escapeCode
= '\"'; break;
868 case '\\': escapeCode
= '\\'; break;
869 case '\0': if (value
== 0) { escapeCode
= '0'; } break;
873 result
+= separator
[repeats
][lastThing
];
875 if (escapeCode
!= '\0') {
881 // fixup repeat count and lastThing
884 result
+= repeatCount
;
885 lastThing
= wasRepeat
;
894 if (lastThing
== wasChar
)
898 variable
= new ExprValue(QString(), VarTree::NKplain
);
899 variable
->m_value
= result
;
901 else if (strncmp(p
, "true", 4) == 0)
903 variable
= new ExprValue(QString(), VarTree::NKplain
);
904 variable
->m_value
= "QString::null";
906 else if (strncmp(p
, "false", 5) == 0)
908 variable
= new ExprValue(QString(), VarTree::NKplain
);
909 variable
->m_value
= "(null)";
916 if (wantErrorValue
) {
917 variable
= new ExprValue(QString(), VarTree::NKplain
);
918 variable
->m_value
= "internal parse error";
923 static ExprValue
* parseVar(const char*& s
)
930 VarTree::NameKind kind
;
932 * Detect anonymouse struct values: The 'name =' part is missing:
933 * s = { a = 1, { b = 2 }}
934 * Note that this detection works only inside structs when the anonymous
935 * struct is not the first member:
936 * s = {{ a = 1 }, b = 2}
937 * This is misparsed (by parseNested()) because it is mistakenly
938 * interprets the second opening brace as the first element of an array
943 name
= i18n("<anonymous struct or union>");
944 kind
= VarTree::NKanonymous
;
948 if (!parseName(p
, name
, kind
)) {
955 TRACE("parse error: = not found after " + name
);
958 // skip the '=' and more whitespace
963 ExprValue
* variable
= new ExprValue(name
, kind
);
965 if (!parseValue(p
, variable
)) {
973 static void skipNested(const char*& s
, char opening
, char closing
)
977 // parse a nested type
981 * Search for next matching `closing' char, skipping nested pairs of
982 * `opening' and `closing'.
984 while (*p
&& nest
> 0) {
987 } else if (*p
== closing
) {
993 TRACE(QString().sprintf("parse error: mismatching %c%c at %-20.20s", opening
, closing
, s
));
999 * This function skips text that is delimited by nested angle bracktes, '<>'.
1000 * A complication arises because the delimited text can contain the names of
1001 * operator<<, operator>>, operator<, and operator>, which have to be treated
1002 * specially so that they do not count towards the nesting of '<>'.
1003 * This function assumes that the delimited text does not contain strings.
1005 static void skipNestedAngles(const char*& s
)
1010 p
++; // skip the initial '<'
1011 while (*p
&& nest
> 0)
1013 // Below we can check for p-s >= 9 instead of 8 because
1014 // *s is '<' and cannot be part of "operator".
1017 if (p
-s
>= 9 && strncmp(p
-8, "operator", 8) == 0) {
1026 if (p
-s
>= 9 && strncmp(p
-8, "operator", 8) == 0) {
1036 TRACE(QString().sprintf("parse error: mismatching <> at %-20.20s", s
));
1042 * Find the end of line that is not inside braces
1044 static void findEnd(const char*& s
)
1047 while (*p
&& *p
!='\n') {
1048 while (*p
&& *p
!='\n' && *p
!='{')
1052 skipNested(p
, '{', '}'); p
--;
1058 static bool isNumberish(const char ch
)
1060 return (ch
>='0' && ch
<='9') || ch
=='.' || ch
=='x';
1063 void skipString(const char*& p
)
1065 // wchar_t strings begin with L
1072 while (*p
!= quote
) {
1074 // skip escaped character
1075 // no special treatment for octal values necessary
1078 // simply return if no more characters
1086 * Strings can consist of several parts, some of which contain repeated
1089 if (quote
== '\'') {
1090 // look ahaead for <repeats 123 times>
1091 const char* q
= p
+1;
1093 if (strncmp(q
, "<repeats ", 9) == 0) {
1095 while (*p
!= '\0' && *p
!= '>')
1098 p
++; /* skip the '>' */
1102 // Is the string continued? If so, there is no L in wchar_t strings
1105 // look ahead for another quote
1106 const char* q
= p
+1;
1108 if (*q
== '"' || *q
== '\'') {
1114 // some strings can end in <incomplete sequence ...>
1115 if (strncmp(q
, "<incomplete sequence", 20) == 0)
1118 while (*p
!= '\0' && *p
!= '>')
1121 p
++; /* skip the '>' */
1126 * There's a bug in gdb where it prints the beginning of the string
1127 * continuation and the comma-blank in the wrong order if the new string
1128 * begins with an incomplete multi-byte character. For now, let's check
1129 * for this in a very narrow condition, particularly, where the next
1130 * character is given in octal notation. Example:
1131 * 'a' <repeats 20 times>"\240, b"
1133 if (*p
== '"' && p
[1] == '\\' && isdigit(p
[2])) {
1135 while (isdigit(p
[i
]))
1137 if (p
[i
] == ',' && p
[i
+1] == ' ') {
1138 // just treat everything beginning at the dquote as string
1142 /* very long strings are followed by `...' */
1143 if (*p
== '.' && p
[1] == '.' && p
[2] == '.') {
1148 static void skipNestedWithString(const char*& s
, char opening
, char closing
)
1152 // parse a nested expression
1156 * Search for next matching `closing' char, skipping nested pairs of
1157 * `opening' and `closing' as well as strings.
1159 while (*p
&& nest
> 0) {
1160 if (*p
== opening
) {
1162 } else if (*p
== closing
) {
1164 } else if (*p
== '\'' || *p
== '\"') {
1171 TRACE(QString().sprintf("parse error: mismatching %c%c at %-20.20s", opening
, closing
, s
));
1176 static void skipName(const char*& p
)
1178 // allow : (for enumeration values) and $ and . (for _vtbl.)
1179 while (isalnum(*p
) || *p
== '_' || *p
== ':' || *p
== '$' || *p
== '.')
1183 static void skipFunctionName(const char*& p
)
1188 // skip template parameter list
1189 skipNestedAngles(p
);
1190 } else if (*p
== '(') {
1191 // this skips "(anonymous namespace)" as well as the formal
1192 // parameter list of the containing function if this is a member
1193 // of a nested class
1194 skipNestedWithString(p
, '(', ')');
1195 } else if (isalnum(*p
) || *p
== '_' || *p
== ':') {
1196 const char* start
= p
;
1198 // check for operator
1200 strncmp(p
-8, "operator", 8) == 0 &&
1201 // do not mistake this as the tail of some identifier
1202 (p
-start
== 8 || !(isalnum(p
[-9]) || p
[-9] == '_')))
1204 // skip forward until we find the opening parenthesis
1205 // this catches both operator()(...) as well as
1206 // type conversion operators, e.g.
1207 // operator char const*() const
1208 // operator void(*)()
1209 while (*p
&& *p
!= '(')
1212 } else if (strncmp(p
, " const", 6) == 0 &&
1213 // must not mistake "const" as the beginning of
1214 // a subequent identifier
1215 !isalnum(p
[6]) && p
[6] != '_') {
1223 static bool parseName(const char*& s
, QString
& name
, VarTree::NameKind
& kind
)
1225 kind
= VarTree::NKplain
;
1228 // examples of names:
1231 // <string<a,b<c>,7> >
1234 skipNestedAngles(p
);
1235 name
= QString::fromLatin1(s
, p
- s
);
1236 kind
= VarTree::NKtype
;
1240 // name, which might be "static"; allow dot for "_vtbl."
1243 TRACE(QString().sprintf("parse error: not a name %-20.20s", s
));
1247 if (len
== 6 && strncmp(s
, "static", 6) == 0) {
1248 kind
= VarTree::NKstatic
;
1250 // its a static variable, name comes now
1255 TRACE(QString().sprintf("parse error: not a name after static %-20.20s", s
));
1260 name
= QString::fromLatin1(s
, len
);
1262 // return the new position
1267 static bool parseValue(const char*& s
, ExprValue
* variable
)
1269 variable
->m_value
= "";
1273 // Sometimes we find the following output:
1274 // {<text variable, no debug info>} 0x40012000 <access>
1275 // {<data variable, no debug info>}
1276 // {<variable (not text or data), no debug info>}
1277 if (strncmp(s
, "{<text variable, ", 17) == 0 ||
1278 strncmp(s
, "{<data variable, ", 17) == 0 ||
1279 strncmp(s
, "{<variable (not text or data), ", 31) == 0)
1281 const char* start
= s
;
1282 skipNested(s
, '{', '}');
1283 variable
->m_value
= QString::fromLatin1(start
, s
-start
);
1284 variable
->m_value
+= ' '; // add only a single space
1291 if (!parseNested(s
, variable
)) {
1294 // must be the closing brace
1296 TRACE("parse error: missing } of " + variable
->m_name
);
1300 // final white space
1304 // Sometimes we find a warning; it ends at the next LF
1305 else if (strncmp(s
, "warning: ", 9) == 0) {
1306 const char* end
= strchr(s
, '\n');
1307 s
= end
? end
: s
+strlen(s
);
1308 // skip space at start of next line
1312 // examples of leaf values (cannot be the empty string):
1318 // (DwContentType&) @0x8123456: {...}
1322 // 0x823abc <Array<int> virtual table>
1323 // 0x40240f <globarstr> "test"
1324 // (void (*)()) 0x8048480 <f(E *, char)>
1327 // &parseP (HTMLClueV *, char *)
1328 // &virtual table offset 0, this adjustment 140737488346016
1329 // &virtual Dl::operator char const*() const
1330 // Variable "x" is not available.
1331 // The value of variable 'x' is distributed...
1332 // -nan(0xfffff081defa0)
1333 // @0x100400f08: <error reading variable>
1334 // (void (Templated<double>::*)(Templated<double> * const)) 0x400d74 <MostDerived::PrintV()>, this adjustment -16
1341 skipNested(p
, '(', ')');
1344 variable
->m_value
= QString::fromLatin1(s
, p
- s
);
1347 bool reference
= false;
1349 // skip reference marker
1353 const char* start
= p
;
1357 // some values consist of more than one token
1358 bool checkMultiPart
= false;
1360 if (p
[0] == '0' && p
[1] == 'x') {
1363 while (isxdigit(*p
))
1367 * Assume this is a pointer, but only if it's not a reference, since
1368 * references can't be expanded.
1371 variable
->m_varKind
= VarTree::VKpointer
;
1374 * References are followed by a colon, in which case we'll
1375 * find the value following the reference address.
1380 // Paranoia. (Can this happen, i.e. reference not followed by ':'?)
1384 checkMultiPart
= true;
1385 } else if (isdigit(*p
)) {
1386 // parse decimal number, possibly a float
1388 if (*p
== '.') { /* TODO: obey i18n? */
1389 // In long arrays an integer may be followed by '...'.
1390 // We test for this situation and don't gobble the '...'.
1391 if (p
[1] != '.' || p
[0] != '.') {
1397 if (*p
== 'e' || *p
== 'E') {
1400 if (*p
== '-' || *p
== '+')
1405 // for char variables there is the char, eg. 10 '\n'
1406 checkMultiPart
= true;
1407 } else if (*p
== '<') {
1408 // e.g. <optimized out>
1409 skipNestedAngles(p
);
1410 } else if (*p
== '"' || *p
== '\'') {
1411 // character may have multipart: '\000' <repeats 11 times>
1412 checkMultiPart
= *p
== '\'';
1415 } else if (*p
== 'L' && (p
[1] == '"' || p
[1] == '\'')) {
1416 // ditto for wchar_t strings
1417 checkMultiPart
= p
[1] == '\'';
1419 } else if (*p
== '&') {
1421 if (strncmp(p
, "virtual ", 8) == 0) {
1423 if (strncmp(p
, "table offset ", 13) == 0) {
1426 checkMultiPart
= true;
1428 skipFunctionName(p
);
1435 skipNested(p
, '(', ')');
1438 } else if (strncmp(p
, "Variable \"", 10) == 0) {
1439 // Variable "x" is not available.
1440 p
+= 10; // skip to "
1442 if (strncmp(p
, "\" is not available.", 19) == 0) {
1445 } else if (strncmp(p
, "The value of variable '", 23) == 0) {
1448 const char* e
= strchr(p
, '.');
1456 // must be an enumeration value
1458 // nan (floating point Not a Number) is followed by a number in ()
1459 // enum values can look like A::(anonymous namespace)::blue
1461 bool isAnonNS
= strncmp(p
+1, "anonymous namespace)", 20) == 0;
1462 skipNested(p
, '(', ')');
1467 variable
->m_value
+= QString::fromLatin1(start
, p
- start
);
1469 // remove line breaks from the value; this is ok since
1470 // string values never contain a literal line break
1471 variable
->m_value
.replace('\n', ' ');
1473 while (checkMultiPart
) {
1476 // may be followed by a string or <...>
1477 // if this was a pointer with a string,
1478 // reset that pointer flag since we have now a value
1480 checkMultiPart
= false;
1482 if (*p
== '"' || *p
== '\'') {
1484 variable
->m_varKind
= VarTree::VKsimple
;
1485 } else if (*p
== 'L' && (p
[1] == '"' || p
[1] == '\'')) {
1486 skipString(p
); // wchar_t string
1487 variable
->m_varKind
= VarTree::VKsimple
;
1488 } else if (*p
== '<') {
1489 // if this value is part of an array, it might be followed
1490 // by <repeats 15 times>, which we don't skip here
1491 if (strncmp(p
, "<repeats ", 9) == 0)
1493 // sometimes, a reference is followed by an error message:
1494 // @0x100400f08: <error reading variable>
1495 // in this case, we do not skip the text here, but leave it
1496 // for the subsequent parsing pass induced by the reference
1497 else if (reference
&& strncmp(p
, "<error reading", 14) == 0)
1500 skipNestedAngles(p
);
1501 checkMultiPart
= true;
1503 } else if (strncmp(p
, ", this adjustment ", 18) == 0) {
1504 // pointers-to-member are sometimes followed by
1505 // a "this adjustment" hint
1510 // we know that this is not a dereferencable pointer
1511 variable
->m_varKind
= VarTree::VKsimple
;
1512 ++start
; // skip ',', will be picked up below
1515 // there is always a blank before the string,
1516 // which we will include in the final string value
1517 variable
->m_value
+= QString::fromLatin1(start
-1, (p
- start
)+1);
1521 if (variable
->m_value
.length() == 0) {
1522 TRACE("parse error: no value for " + variable
->m_name
);
1526 // final white space
1531 * If this was a reference, the value follows. It might even be a
1532 * composite variable!
1542 static bool parseNested(const char*& s
, ExprValue
* variable
)
1544 // could be a structure or an array
1548 bool isStruct
= false;
1550 * If there is a name followed by an = or an < -- which starts a type
1551 * name -- or "static", it is a structure
1553 if (*p
== '<' || *p
== '}') {
1555 } else if (strncmp(p
, "static ", 7) == 0) {
1557 } else if (isalpha(*p
) || *p
== '_' || *p
== '$') {
1558 // look ahead for a comma after the name
1564 p
= s
; /* rescan the name */
1567 if (!parseVarSeq(p
, variable
)) {
1570 variable
->m_varKind
= VarTree::VKstruct
;
1572 if (!parseValueSeq(p
, variable
)) {
1575 variable
->m_varKind
= VarTree::VKarray
;
1581 static bool parseVarSeq(const char*& s
, ExprValue
* variable
)
1583 // parse a comma-separated sequence of variables
1584 ExprValue
* var
= variable
; /* var != 0 to indicate success if empty seq */
1588 if (strncmp(s
, "<No data fields>}", 17) == 0)
1590 // no member variables, so break out immediately
1591 s
+= 16; /* go to the closing brace */
1596 break; /* syntax error */
1597 variable
->appendChild(var
);
1600 // skip the comma and whitespace
1607 static bool parseValueSeq(const char*& s
, ExprValue
* variable
)
1609 // parse a comma-separated sequence of variables
1614 name
.sprintf("[%d]", index
);
1615 ExprValue
* var
= new ExprValue(name
, VarTree::NKplain
);
1616 good
= parseValue(s
, var
);
1621 // a value may be followed by "<repeats 45 times>"
1622 if (strncmp(s
, "<repeats ", 9) == 0) {
1625 int l
= strtol(s
, &end
, 10);
1626 if (end
== s
|| strncmp(end
, " times>", 7) != 0) {
1627 // should not happen
1631 TRACE(QString().sprintf("found <repeats %d times> in array", l
));
1632 // replace name and advance index
1633 name
.sprintf("[%d .. %d]", index
, index
+l
-1);
1636 // skip " times>" and space
1638 // possible final space
1643 variable
->appendChild(var
);
1644 // long arrays may be terminated by '...'
1645 if (strncmp(s
, "...", 3) == 0) {
1647 ExprValue
* var
= new ExprValue("...", VarTree::NKplain
);
1648 var
->m_value
= i18n("<additional entries of the array suppressed>");
1649 variable
->appendChild(var
);
1655 // skip the comma and whitespace
1658 // sometimes there is a closing brace after a comma
1666 * Parses a stack frame.
1668 static void parseFrameInfo(const char*& s
, QString
& func
,
1669 QString
& file
, int& lineNo
, DbgAddr
& address
)
1673 // next may be a hexadecimal address
1675 const char* start
= p
;
1679 while (isxdigit(*p
))
1681 address
= QString::fromLatin1(start
, p
-start
);
1682 if (strncmp(p
, " in ", 4) == 0)
1685 address
= DbgAddr();
1687 const char* start
= p
;
1688 // check for special signal handler frame
1689 if (strncmp(p
, "<signal handler called>", 23) == 0) {
1690 func
= QString::fromLatin1(start
, 23);
1700 * Skip the function name. It is terminated by a left parenthesis
1701 * which does not delimit "(anonymous namespace)" and which is
1702 * outside the angle brackets <> of template parameter lists
1703 * and is preceded by a space.
1708 // check for operator<< and operator<
1709 if (p
-start
>= 8 && strncmp(p
-8, "operator", 8) == 0)
1717 // skip template parameter list
1718 skipNestedAngles(p
);
1720 } else if (*p
== '(') {
1721 // this skips "(anonymous namespace)" as well as the formal
1722 // parameter list of the containing function if this is a member
1723 // of a nested class
1724 skipNestedWithString(p
, '(', ')');
1725 } else if (*p
== ' ') {
1728 break; // parameter list found
1742 * Skip parameters. But notice that for complicated conversion
1743 * functions (eg. "operator int(**)()()", ie. convert to pointer to
1744 * pointer to function) as well as operator()(...) we have to skip
1745 * additional pairs of parentheses. Furthermore, recent gdbs write the
1746 * demangled name followed by the arguments in a pair of parentheses,
1747 * where the demangled name can end in "const".
1750 skipNestedWithString(p
, '(', ')');
1753 if (strncmp(p
, "const", 5) == 0) {
1757 } while (*p
== '(');
1759 // check for file position
1760 if (strncmp(p
, "at ", 3) == 0) {
1762 const char* fileStart
= p
;
1763 // go for the end of the line
1764 while (*p
!= '\0' && *p
!= '\n')
1766 // search back for colon
1767 const char* colon
= p
;
1770 } while (*colon
!= ':');
1771 file
= QString::fromLatin1(fileStart
, colon
-fileStart
);
1772 lineNo
= atoi(colon
+1)-1;
1777 // check for "from shared lib"
1778 if (strncmp(p
, "from ", 5) == 0) {
1780 // go for the end of the line
1781 while (*p
!= '\0' && *p
!= '\n')
1790 // construct the function name (including file info)
1794 func
= QString::fromLatin1(start
, p
-start
-1); /* don't include \n */
1799 * Replace \n (and whitespace around it) in func by a blank. We cannot
1800 * use QString::simplified() for this because this would also
1801 * simplify space that belongs to a string arguments that gdb sometimes
1802 * prints in the argument lists of the function.
1804 ASSERT(!isspace(func
[0].toLatin1())); // there must be non-white before first \n
1806 while ((nl
= func
.indexOf('\n', nl
)) >= 0) {
1807 // search back to the beginning of the whitespace
1808 int startWhite
= nl
;
1811 } while (isspace(func
[startWhite
].toLatin1()));
1813 // search forward to the end of the whitespace
1816 } while (isspace(func
[nl
].toLatin1()));
1818 func
.replace(startWhite
, nl
-startWhite
, " ");
1819 /* continue searching for more \n's at this place: */
1826 * Parses a stack frame including its frame number
1828 static bool parseFrame(const char*& s
, int& frameNo
, QString
& func
,
1829 QString
& file
, int& lineNo
, DbgAddr
& address
)
1832 // #1 0x8048881 in Dl::Dl (this=0xbffff418, r=3214) at testfile.cpp:72
1833 // Breakpoint 3, Cl::f(int) const (this=0xbffff3c0, x=17) at testfile.cpp:155
1835 // must start with a hash mark followed by number
1836 // or with "Breakpoint " followed by number and comma
1840 s
++; /* skip the hash mark */
1841 } else if (strncmp(s
, "Breakpoint ", 11) == 0) {
1842 if (!isdigit(s
[11]))
1844 s
+= 11; /* skip "Breakpoint" */
1852 while (isspace(*s
) || *s
== ',')
1854 parseFrameInfo(s
, func
, file
, lineNo
, address
);
1858 void GdbDriver::parseBackTrace(const char* output
, std::list
<StackFrame
>& stack
)
1861 int lineNo
, frameNo
;
1864 while (::parseFrame(output
, frameNo
, func
, file
, lineNo
, address
)) {
1865 stack
.push_back(StackFrame());
1866 StackFrame
* frm
= &stack
.back();
1867 frm
->frameNo
= frameNo
;
1868 frm
->fileName
= file
;
1869 frm
->lineNo
= lineNo
;
1870 frm
->address
= address
;
1871 frm
->var
= new ExprValue(func
, VarTree::NKplain
);
1875 bool GdbDriver::parseFrameChange(const char* output
, int& frameNo
,
1876 QString
& file
, int& lineNo
, DbgAddr
& address
)
1879 return ::parseFrame(output
, frameNo
, func
, file
, lineNo
, address
);
1883 bool GdbDriver::parseBreakList(const char* output
, std::list
<Breakpoint
>& brks
)
1885 // skip first line, which is the headline
1886 const char* p
= strchr(output
, '\n');
1896 while (*p
!= '\0') {
1899 bp
.id
= strtol(p
, &dummy
, 10); /* don't care about overflows */
1901 // check for continued <MULTIPLE> breakpoint
1902 if (*p
== '.' && isdigit(p
[1]))
1904 // continuation: skip type and disposition
1910 if (strncmp(p
, "breakpoint", 10) == 0) {
1912 } else if (strncmp(p
, "hw watchpoint", 13) == 0) {
1913 bp
.type
= Breakpoint::watchpoint
;
1915 } else if (strncmp(p
, "watchpoint", 10) == 0) {
1916 bp
.type
= Breakpoint::watchpoint
;
1923 bp
.temporary
= *p
++ == 'd';
1925 while (*p
!= '\0' && !isspace(*p
)) /* "keep" or "del" */
1931 bp
.enabled
= *p
++ == 'y';
1932 while (*p
!= '\0' && !isspace(*p
)) /* "y" or "n" */
1937 // the address, if present
1938 if (bp
.type
== Breakpoint::breakpoint
&&
1939 strncmp(p
, "0x", 2) == 0)
1941 const char* start
= p
;
1942 while (*p
!= '\0' && !isspace(*p
))
1944 bp
.address
= QString::fromLatin1(start
, p
-start
);
1945 while (isspace(*p
) && *p
!= '\n')
1950 // remainder is location, hit and ignore count, condition
1951 end
= strchr(p
, '\n');
1954 p
+= bp
.location
.length();
1956 // location of a <MULTIPLE> filled in from subsequent breakpoints
1957 if (strncmp(p
, "<MULTIPLE>", 10) != 0)
1958 bp
.location
= QString::fromLatin1(p
, end
-p
).trimmed();
1959 p
= end
+1; /* skip over \n */
1962 // may be continued in next line
1963 while (isspace(*p
)) { /* p points to beginning of line */
1964 // skip white space at beginning of line
1968 end
= strchr(p
, '\n');
1972 if (strncmp(p
, "breakpoint already hit", 22) == 0) {
1973 // extract the hit count
1975 bp
.hitCount
= strtol(p
, &dummy
, 10);
1976 TRACE(QString("hit count %1").arg(bp
.hitCount
));
1977 } else if (strncmp(p
, "stop only if ", 13) == 0) {
1978 // extract condition
1980 bp
.condition
= QString::fromLatin1(p
, end
-p
).trimmed();
1981 TRACE("condition: "+bp
.condition
);
1982 } else if (strncmp(p
, "ignore next ", 12) == 0) {
1983 // extract ignore count
1985 bp
.ignoreCount
= strtol(p
, &dummy
, 10);
1986 TRACE(QString("ignore count %1").arg(bp
.ignoreCount
));
1988 // indeed a continuation
1989 bp
.location
+= " " + QString::fromLatin1(p
, end
-p
).trimmed();
1993 p
++; /* skip '\n' */
1996 if (brks
.empty() || brks
.back().id
!= bp
.id
) {
1999 // this is a continuation; fill in location if not yet set
2000 // otherwise, drop this breakpoint
2001 Breakpoint
& mbp
= brks
.back();
2002 if (mbp
.location
.isEmpty() && !bp
.location
.isEmpty()) {
2003 mbp
.location
= bp
.location
;
2004 mbp
.address
= bp
.address
;
2005 } else if (mbp
.address
.isEmpty() && !bp
.address
.isEmpty()) {
2006 mbp
.address
= bp
.address
;
2013 std::list
<ThreadInfo
> GdbDriver::parseThreadList(const char* output
)
2015 std::list
<ThreadInfo
> threads
;
2016 if (strcmp(output
, "\n") == 0 ||
2017 strncmp(output
, "No stack.", 9) == 0 ||
2018 strncmp(output
, "No threads.", 11) == 0) {
2023 bool newFormat
= false;
2024 const char* p
= output
;
2025 while (*p
!= '\0') {
2027 // seach look for thread id, watching out for the focus indicator
2028 thr
.hasFocus
= false;
2029 skipSpace(p
); /* may be \n from prev line: see "No stack" below */
2031 // recent GDBs write a header line; skip it
2032 if (threads
.empty() && strncmp(p
, "Id Target", 11) == 0) {
2033 p
= strchr(p
, '\n');
2037 continue; // next line please, '\n' is skipped above
2041 thr
.hasFocus
= true;
2043 // there follows only whitespace
2046 char *temp_end
= NULL
; /* we need a non-const 'end' for strtol to use...*/
2047 thr
.id
= strtol(p
, &temp_end
, 10);
2050 // syntax error: no number found; bail out
2058 * Now follows the thread's SYSTAG.
2061 // In the old format, it is terminated by two blanks.
2062 end
= strstr(p
, " ");
2064 // syntax error; bail out
2069 // In the new format lies crazyness: there is no definitive
2070 // end marker. At best we can guess when the SYSTAG ends.
2071 // A typical thread list on Linux looks like this:
2073 // Id Target Id Frame
2074 // 2 Thread 0x7ffff7854700 (LWP 10827) "thrserver" 0x00007ffff7928631 in clone () from /lib64/libc.so.6
2075 // * 1 Thread 0x7ffff7fcc700 (LWP 10808) "thrserver" main () at thrserver.c:84
2077 // Looking at GDB's code, the Target Id ends in tokens that
2078 // are bracketed by parentheses or quotes. Therefore,
2079 // we skip (at most) two tokens ('Thread' and the address),
2080 // and then all parts that are in parentheses or quotes.
2087 } else if (*end
== '(') {
2088 skipNested(end
, '(', ')');
2091 while (*end
&& !isspace(*end
))
2100 thr
.threadName
= QString::fromLatin1(p
, end
-p
).trimmed();
2104 * Now follows a standard stack frame. Sometimes, however, gdb
2105 * catches a thread at an instant where it doesn't have a stack.
2107 if (strncmp(p
, "[No stack.]", 11) != 0) {
2108 ::parseFrameInfo(p
, thr
.function
, thr
.fileName
, thr
.lineNo
, thr
.address
);
2110 thr
.function
= "[No stack]";
2112 p
+= 11; /* \n is skipped above */
2115 threads
.push_back(thr
);
2120 static bool parseNewBreakpoint(const char* o
, int& id
,
2121 QString
& file
, int& lineNo
, QString
& address
);
2122 static bool parseNewWatchpoint(const char* o
, int& id
,
2125 bool GdbDriver::parseBreakpoint(const char* output
, int& id
,
2126 QString
& file
, int& lineNo
, QString
& address
)
2128 // skip lines of that begin with "(Cannot find"
2129 while (strncmp(output
, "(Cannot find", 12) == 0 ||
2130 strncmp(output
, "Note: breakpoint", 16) == 0)
2132 output
= strchr(output
, '\n');
2135 output
++; /* skip newline */
2138 if (strncmp(output
, "Breakpoint ", 11) == 0) {
2139 output
+= 11; /* skip "Breakpoint " */
2140 return ::parseNewBreakpoint(output
, id
, file
, lineNo
, address
);
2141 } else if (strncmp(output
, "Temporary breakpoint ", 21) == 0) {
2143 return ::parseNewBreakpoint(output
, id
, file
, lineNo
, address
);
2144 } else if (strncmp(output
, "Hardware watchpoint ", 20) == 0) {
2146 return ::parseNewWatchpoint(output
, id
, address
);
2147 } else if (strncmp(output
, "Watchpoint ", 11) == 0) {
2149 return ::parseNewWatchpoint(output
, id
, address
);
2154 static bool parseNewBreakpoint(const char* o
, int& id
,
2155 QString
& file
, int& lineNo
, QString
& address
)
2159 id
= strtoul(o
, &p
, 10);
2163 // check for the address
2164 if (strncmp(p
, " at 0x", 6) == 0) {
2165 char* start
= p
+4; /* skip " at ", but not 0x */
2167 while (isxdigit(*p
))
2169 address
= QString::fromLatin1(start
, p
-start
);
2173 * Mostly, GDB responds with this syntax:
2175 * Breakpoint 1 at 0x400b94: file multibrkpt.cpp, line 9. (2 locations)
2177 * but sometimes it uses this syntax:
2179 * Breakpoint 4 at 0x804f158: lotto739.cpp:95. (3 locations)
2181 const char* fileEnd
, *numStart
= 0;
2182 const char* fileStart
= strstr(p
, "file ");
2186 fileEnd
= strstr(fileStart
, ", line ");
2188 numStart
= fileEnd
+ 7;
2190 if (numStart
== 0 && p
[0] == ':' && p
[1] == ' ')
2193 skipSpace(fileStart
);
2194 fileEnd
= strchr(fileStart
, ':');
2196 numStart
= fileEnd
+ 1;
2199 return !address
.isEmpty(); /* parse error only if there's no address */
2201 QString fileName
= QString::fromLatin1(fileStart
, fileEnd
-fileStart
);
2202 int line
= strtoul(numStart
, &p
, 10);
2207 lineNo
= line
-1; /* zero-based! */
2211 static bool parseNewWatchpoint(const char* o
, int& id
,
2216 id
= strtoul(o
, &p
, 10);
2220 if (strncmp(p
, ": ", 2) != 0)
2224 // all the rest on the line is the expression
2225 expr
= QString::fromLatin1(p
, strlen(p
)).trimmed();
2229 void GdbDriver::parseLocals(const char* output
, std::list
<ExprValue
*>& newVars
)
2231 // check for possible error conditions
2232 if (strncmp(output
, "No symbol table", 15) == 0)
2237 while (*output
!= '\0') {
2239 if (*output
== '\0')
2241 // skip occurrences of "No locals" and "No args"
2242 if (strncmp(output
, "No locals", 9) == 0 ||
2243 strncmp(output
, "No arguments", 12) == 0)
2245 output
= strchr(output
, '\n');
2252 ExprValue
* variable
= parseVar(output
);
2253 if (variable
== 0) {
2256 // do not add duplicates
2257 for (std::list
<ExprValue
*>::iterator o
= newVars
.begin(); o
!= newVars
.end(); ++o
) {
2258 if ((*o
)->m_name
== variable
->m_name
) {
2263 newVars
.push_back(variable
);
2268 ExprValue
* GdbDriver::parsePrintExpr(const char* output
, bool wantErrorValue
)
2271 // check for error conditions
2272 if (!parseErrorMessage(output
, var
, wantErrorValue
))
2274 // parse the variable
2275 var
= parseVar(output
);
2280 bool GdbDriver::parseChangeWD(const char* output
, QString
& message
)
2282 bool isGood
= false;
2283 message
= QString(output
).simplified();
2284 if (message
.isEmpty()) {
2285 message
= i18n("New working directory: ") + m_programWD
;
2291 bool GdbDriver::parseChangeExecutable(const char* output
, QString
& message
)
2295 m_haveCoreFile
= false;
2298 * Lines starting with the following do not indicate errors:
2299 * Using host libthread_db
2300 * (no debugging symbols found)
2301 * Reading symbols from
2303 while (strncmp(output
, "Reading symbols from", 20) == 0 ||
2304 strncmp(output
, "done.", 5) == 0 ||
2305 strncmp(output
, "Missing separate debuginfo", 26) == 0 ||
2306 strncmp(output
, "Try: ", 5) == 0 ||
2307 strncmp(output
, "Using host libthread_db", 23) == 0 ||
2308 strncmp(output
, "(no debugging symbols found)", 28) == 0)
2310 // this line is good, go to the next one
2311 const char* end
= strchr(output
, '\n');
2313 output
+= strlen(output
);
2319 * If we've parsed all lines, there was no error.
2321 return output
[0] == '\0';
2324 bool GdbDriver::parseCoreFile(const char* output
)
2326 // if command succeeded, gdb emits a line starting with "#0 "
2327 m_haveCoreFile
= strstr(output
, "\n#0 ") != 0;
2328 return m_haveCoreFile
;
2331 uint
GdbDriver::parseProgramStopped(const char* output
, QString
& message
)
2333 // optionally: "program changed, rereading symbols",
2335 // "Program exited normally"
2336 // "Program terminated with wignal SIGSEGV"
2337 // "Program received signal SIGINT" or other signal
2339 // GDB since 7.3 prints
2340 // "[Inferior 1 (process 13400) exited normally]"
2341 // "[Inferior 1 (process 14698) exited with code 01]"
2343 // go through the output, line by line, checking what we have
2344 const char* start
= output
- 1;
2345 uint flags
= SFprogramActive
;
2346 message
= QString();
2348 start
++; /* skip '\n' */
2350 if (strncmp(start
, "Program ", 8) == 0 ||
2351 strncmp(start
, "ptrace: ", 8) == 0) {
2353 * When we receive a signal, the program remains active.
2355 * Special: If we "stopped" in a corefile, the string "Program
2356 * terminated with signal"... is displayed. (Normally, we see
2357 * "Program received signal"... when a signal happens.)
2359 if (strncmp(start
, "Program exited", 14) == 0 ||
2360 (strncmp(start
, "Program terminated", 18) == 0 && !m_haveCoreFile
) ||
2361 strncmp(start
, "ptrace: ", 8) == 0)
2363 flags
&= ~SFprogramActive
;
2367 const char* endOfMessage
= strchr(start
, '\n');
2368 if (endOfMessage
== 0)
2369 endOfMessage
= start
+ strlen(start
);
2370 message
= QString::fromLatin1(start
, endOfMessage
-start
);
2371 } else if (strncmp(start
, "[Inferior ", 10) == 0) {
2372 const char* p
= start
+ 10;
2373 // skip number and space
2374 while (*p
&& !isspace(*p
))
2378 skipNested(p
, '(', ')');
2379 if (strncmp(p
, " exited ", 8) == 0) {
2380 flags
&= ~SFprogramActive
;
2383 const char* end
= strchr(p
, '\n');
2385 end
= p
+ strlen(p
);
2386 // strip [] from the message
2387 message
= QString::fromLatin1(start
+1, end
-start
-2);
2390 } else if (strncmp(start
, "Breakpoint ", 11) == 0) {
2392 * We stopped at a (permanent) breakpoint (gdb doesn't tell us
2393 * that it stopped at a temporary breakpoint).
2395 flags
|= SFrefreshBreak
;
2396 } else if (strstr(start
, "re-reading symbols.") != 0) {
2397 flags
|= SFrefreshSource
;
2400 // next line, please
2401 start
= strchr(start
, '\n');
2402 } while (start
!= 0);
2405 * Gdb only notices when new threads have appeared, but not when a
2406 * thread finishes. So we always have to assume that the list of
2407 * threads has changed.
2409 flags
|= SFrefreshThreads
;
2414 QStringList
GdbDriver::parseSharedLibs(const char* output
)
2417 if (strncmp(output
, "No shared libraries loaded", 26) == 0)
2420 // parse the table of shared libraries
2422 // strip off head line
2423 output
= strchr(output
, '\n');
2426 output
++; /* skip '\n' */
2428 while (*output
!= '\0') {
2429 // format of a line is
2430 // 0x404c5000 0x40580d90 Yes /lib/libc.so.5
2431 // 3 blocks of non-space followed by space
2432 for (int i
= 0; *output
!= '\0' && i
< 3; i
++) {
2433 while (*output
!= '\0' && !isspace(*output
)) { /* non-space */
2436 skipSpace(output
); /* space */
2438 if (*output
== '\0')
2440 const char* start
= output
;
2441 output
= strchr(output
, '\n');
2443 output
= start
+ strlen(start
);
2444 shlibName
= QString::fromLatin1(start
, output
-start
);
2445 if (*output
!= '\0')
2447 shlibs
.append(shlibName
);
2448 TRACE("found shared lib " + shlibName
);
2453 bool GdbDriver::parseFindType(const char* output
, QString
& type
)
2455 if (strncmp(output
, "type = ", 7) != 0)
2459 * Everything else is the type. We strip off any leading "const" and any
2460 * trailing "&" on the grounds that neither affects the decoding of the
2461 * object. We also strip off all white-space from the type.
2464 if (strncmp(output
, "const ", 6) == 0)
2467 type
.replace(QRegExp("\\s+"), "");
2468 if (type
.endsWith("&"))
2469 type
.truncate(type
.length() - 1);
2473 std::list
<RegisterInfo
> GdbDriver::parseRegisters(const char* output
)
2475 std::list
<RegisterInfo
> regs
;
2476 if (strncmp(output
, "The program has no registers now", 32) == 0) {
2480 // parse register values
2481 while (*output
!= '\0')
2484 // skip space at the start of the line
2488 const char* start
= output
;
2489 while (*output
!= '\0' && !isspace(*output
))
2491 if (*output
== '\0')
2493 reg
.regName
= QString::fromLatin1(start
, output
-start
);
2500 * If we find a brace now, this is a vector register. We look for
2501 * the closing brace and treat the result as cooked value.
2506 skipNested(output
, '{', '}');
2507 value
= QString::fromLatin1(start
, output
-start
).simplified();
2508 // skip space, but not the end of line
2509 while (isspace(*output
) && *output
!= '\n')
2511 // get rid of the braces at the begining and the end
2513 if (value
[value
.length()-1] == '}') {
2514 value
= value
.left(value
.length()-1);
2516 // gdb 5.3 doesn't print a separate set of raw values
2517 if (*output
== '{') {
2518 // another set of vector follows
2519 // what we have so far is the raw value
2520 reg
.rawValue
= value
;
2523 skipNested(output
, '{', '}');
2524 value
= QString::fromLatin1(start
, output
-start
).simplified();
2527 // find first type that does not have an array, this is the RAW value
2528 const char* end
=start
;
2530 const char* cur
=start
;
2532 while (*cur
!= '=' && cur
<end
)
2535 while (isspace(*cur
) && cur
<end
)
2537 if (isNumberish(*cur
)) {
2539 while (*end
&& (*end
!='}') && (*end
!=',') && (*end
!='\n'))
2541 QString rawValue
= QString::fromLatin1(cur
, end
-cur
).simplified();
2542 reg
.rawValue
= rawValue
;
2544 if (rawValue
.left(2)=="0x") {
2545 // ok we have a raw value, now get it's type
2547 while (isspace(*end
) || *end
=='=') end
--;
2550 while (*cur
!='{' && *cur
!=' ')
2553 reg
.type
= QString::fromLatin1(cur
, end
-cur
);
2560 // skip to the end of line
2561 while (*output
!= '\0' && *output
!= '\n')
2563 // get rid of the braces at the begining and the end
2565 if (value
[value
.length()-1] == '}') {
2566 value
.truncate(value
.length()-1);
2569 reg
.cookedValue
= value
;
2574 // the rest of the line is the register value
2576 output
= strchr(output
,'\n');
2578 output
= start
+ strlen(start
);
2579 value
+= QString::fromLatin1(start
, output
-start
).simplified();
2582 * Look ahead: if the subsequent line is indented, it continues
2583 * the current register value.
2585 if (output
!= 0 && isspace(output
[1]))
2593 * We split the raw from the cooked values.
2594 * Some modern gdbs explicitly say: "0.1234 (raw 0x3e4567...)".
2595 * Here, the cooked value comes first, and the raw value is in
2598 int pos
= value
.indexOf(" (raw ");
2601 reg
.cookedValue
= value
.left(pos
);
2602 reg
.rawValue
= value
.mid(pos
+6);
2603 if (reg
.rawValue
.right(1) == ")") // remove closing bracket
2604 reg
.rawValue
.truncate(reg
.rawValue
.length()-1);
2609 * In other cases we split off the first token (separated by
2610 * whitespace). It is the raw value. The remainder of the line
2611 * is the cooked value.
2613 int pos
= value
.indexOf(' ');
2615 reg
.rawValue
= value
;
2616 reg
.cookedValue
= QString();
2618 reg
.rawValue
= value
.left(pos
);
2619 reg
.cookedValue
= value
.mid(pos
+1);
2623 if (*output
!= '\0')
2624 output
++; /* skip '\n' */
2626 regs
.push_back(reg
);
2631 bool GdbDriver::parseInfoLine(const char* output
, QString
& addrFrom
, QString
& addrTo
)
2633 // "is at address" or "starts at address"
2634 const char* start
= strstr(output
, "s at address ");
2639 const char* p
= start
;
2640 while (*p
!= '\0' && !isspace(*p
))
2642 addrFrom
= QString::fromLatin1(start
, p
-start
);
2644 start
= strstr(p
, "and ends at ");
2652 while (*p
!= '\0' && !isspace(*p
))
2654 addrTo
= QString::fromLatin1(start
, p
-start
);
2659 std::list
<DisassembledCode
> GdbDriver::parseDisassemble(const char* output
)
2661 std::list
<DisassembledCode
> code
;
2663 if (strncmp(output
, "Dump of assembler", 17) != 0) {
2671 // remove first line
2672 const char* p
= strchr(output
, '\n');
2674 return code
; /* not a regular output */
2679 const char* end
= strstr(output
, "End of assembler");
2681 end
= p
+ strlen(p
);
2683 // remove function offsets from the lines
2687 // skip initial space or PC pointer ("=>", since gdb 7.1)
2691 else if (p
[0] == '=' && p
[1] == '>')
2696 const char* start
= p
;
2698 while (p
!= end
&& !isspace(*p
))
2700 c
.address
= QString::fromLatin1(start
, p
-start
);
2702 // function name (enclosed in '<>', followed by ':')
2703 while (p
!= end
&& *p
!= '<')
2706 skipNestedAngles(p
);
2711 while (p
!= end
&& isspace(*p
))
2714 // code until end of line
2716 while (p
!= end
&& *p
!= '\n')
2718 if (p
!= end
) /* include '\n' */
2721 c
.code
= QString::fromLatin1(start
, p
-start
);
2727 QString
GdbDriver::parseMemoryDump(const char* output
, std::list
<MemoryDump
>& memdump
)
2729 if (isErrorExpr(output
)) {
2730 // error; strip space
2731 QString msg
= output
;
2732 return msg
.trimmed();
2735 const char* p
= output
; /* save typing */
2741 const char* start
= p
;
2742 while (*p
!= '\0' && *p
!= ':' && !isspace(*p
))
2744 md
.address
= QString::fromLatin1(start
, p
-start
);
2746 // parse function offset
2749 while (*p
!= '\0' && !(*p
== ':' && isspace(p
[1])))
2751 md
.address
.fnoffs
= QString::fromLatin1(start
, p
-start
);
2755 // skip space; this may skip a new-line char!
2757 // everything to the end of the line is the memory dump
2758 const char* end
= strchr(p
, '\n');
2760 md
.dump
= QString::fromLatin1(p
, end
-p
);
2763 md
.dump
= QString::fromLatin1(p
, strlen(p
));
2766 memdump
.push_back(md
);
2772 QString
GdbDriver::editableValue(VarTree
* value
)
2774 QByteArray ba
= value
->value().toLatin1();
2775 const char* s
= ba
.constData();
2777 // if the variable is a pointer value that contains a cast,
2780 skipNested(s
, '(', ')');
2786 const char* start
= s
;
2788 if (strncmp(s
, "0x", 2) == 0)
2791 while (isxdigit(*s
))
2795 * What we saw so far might have been a reference. If so, edit the
2796 * referenced value. Otherwise, edit the pointer.
2804 // if it's a pointer to a string, remove the string
2805 const char* end
= s
;
2809 return QString::fromLatin1(start
, end
-start
);
2812 return QString::fromLatin1(start
, strlen(start
));
2816 // else leave it unchanged (or stripped of the reference preamble)
2820 QString
GdbDriver::parseSetVariable(const char* output
)
2822 // if there is any output, it is an error message
2823 QString msg
= output
;
2824 return msg
.trimmed();
2828 #include "gdbdriver.moc"