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;
700 * Returns true if the output is an error message. If wantErrorValue is
701 * true, a new ExprValue object is created and filled with the error message.
702 * If there are warnings, they are skipped and output points past the warnings
703 * on return (even if there \e are errors).
705 static bool parseErrorMessage(const char*& output
,
706 ExprValue
*& variable
, bool wantErrorValue
)
708 while (isspace(*output
))
712 while (strncmp(output
, "warning:", 8) == 0)
714 const char* end
= strchr(output
+8, '\n');
716 output
+= strlen(output
);
719 while (isspace(*output
))
723 if (isErrorExpr(output
))
725 if (wantErrorValue
) {
726 // put the error message as value in the variable
727 variable
= new ExprValue(QString(), VarTree::NKplain
);
728 const char* endMsg
= strchr(output
, '\n');
730 endMsg
= output
+ strlen(output
);
731 variable
->m_value
= QString::fromLatin1(output
, endMsg
-output
);
740 #if QT_VERSION >= 300
750 void GdbDriver::setPrintQStringDataCmd(const char* cmd
)
752 // don't accept the command if it is empty
753 if (cmd
== 0 || *cmd
== '\0')
755 assert(strlen(cmd
) <= MAX_FMTLEN
);
756 cmds
[DCprintQStringStruct
].fmt
= cmd
;
759 ExprValue
* GdbDriver::parseQCharArray(const char* output
, bool wantErrorValue
, bool qt3like
)
761 ExprValue
* variable
= 0;
764 * Parse off white space. gdb sometimes prints white space first if the
765 * printed array leaded to an error.
767 while (isspace(*output
))
770 // special case: empty string (0 repetitions)
771 if (strncmp(output
, "Invalid number 0 of repetitions", 31) == 0)
773 variable
= new ExprValue(QString(), VarTree::NKplain
);
774 variable
->m_value
= "\"\"";
778 // check for error conditions
779 if (parseErrorMessage(output
, variable
, wantErrorValue
))
785 const char* p
= output
;
793 } while (isspace(*p
));
797 // this is the real data
803 enum { wasNothing
, wasChar
, wasRepeat
} lastThing
= wasNothing
;
805 * A matrix for separators between the individual "things"
806 * that are added to the string. The first index is a bool,
807 * the second index is from the enum above.
809 static const char* separator
[2][3] = {
810 { "\"", 0, ", \"" }, /* normal char is added */
811 { "'", "\", '", ", '" } /* repeated char is added */
814 while (isdigit(*p
)) {
817 unsigned short value
= (unsigned short) strtoul(p
, &end
, 0);
819 goto error
; /* huh? no valid digits */
820 // skip separator and search for a repeat count
822 while (isspace(*p
) || *p
== ',')
824 bool repeats
= strncmp(p
, "<repeats ", 9) == 0;
826 const char* start
= p
;
827 p
= strchr(p
+9, '>'); /* search end and advance */
831 repeatCount
= QString::fromLatin1(start
, p
-start
);
832 while (isspace(*p
) || *p
== ',')
835 // p is now at the next char (or the end)
837 // interpret the value as a QChar
838 // TODO: make cross-architecture compatible
844 (unsigned short&)ch
= value
;
848 ch
.setRow(c
.qch
.row
);
849 ch
.setCell(c
.qch
.cell
);
853 // escape a few frequently used characters
854 char escapeCode
= '\0';
855 switch (ch
.toLatin1()) {
856 case '\n': escapeCode
= 'n'; break;
857 case '\r': escapeCode
= 'r'; break;
858 case '\t': escapeCode
= 't'; break;
859 case '\b': escapeCode
= 'b'; break;
860 case '\"': escapeCode
= '\"'; break;
861 case '\\': escapeCode
= '\\'; break;
862 case '\0': if (value
== 0) { escapeCode
= '0'; } break;
866 result
+= separator
[repeats
][lastThing
];
868 if (escapeCode
!= '\0') {
874 // fixup repeat count and lastThing
877 result
+= repeatCount
;
878 lastThing
= wasRepeat
;
887 if (lastThing
== wasChar
)
891 variable
= new ExprValue(QString(), VarTree::NKplain
);
892 variable
->m_value
= result
;
894 else if (strncmp(p
, "true", 4) == 0)
896 variable
= new ExprValue(QString(), VarTree::NKplain
);
897 variable
->m_value
= "QString::null";
899 else if (strncmp(p
, "false", 5) == 0)
901 variable
= new ExprValue(QString(), VarTree::NKplain
);
902 variable
->m_value
= "(null)";
909 if (wantErrorValue
) {
910 variable
= new ExprValue(QString(), VarTree::NKplain
);
911 variable
->m_value
= "internal parse error";
916 static ExprValue
* parseVar(const char*& s
)
925 VarTree::NameKind kind
;
927 * Detect anonymouse struct values: The 'name =' part is missing:
928 * s = { a = 1, { b = 2 }}
929 * Note that this detection works only inside structs when the anonymous
930 * struct is not the first member:
931 * s = {{ a = 1 }, b = 2}
932 * This is misparsed (by parseNested()) because it is mistakenly
933 * interprets the second opening brace as the first element of an array
938 name
= i18n("<anonymous struct or union>");
939 kind
= VarTree::NKanonymous
;
943 if (!parseName(p
, name
, kind
)) {
951 TRACE("parse error: = not found after " + name
);
954 // skip the '=' and more whitespace
960 ExprValue
* variable
= new ExprValue(name
, kind
);
962 if (!parseValue(p
, variable
)) {
970 static void skipNested(const char*& s
, char opening
, char closing
)
974 // parse a nested type
978 * Search for next matching `closing' char, skipping nested pairs of
979 * `opening' and `closing'.
981 while (*p
&& nest
> 0) {
984 } else if (*p
== closing
) {
990 TRACE(QString().sprintf("parse error: mismatching %c%c at %-20.20s", opening
, closing
, s
));
996 * This function skips text that is delimited by nested angle bracktes, '<>'.
997 * A complication arises because the delimited text can contain the names of
998 * operator<<, operator>>, operator<, and operator>, which have to be treated
999 * specially so that they do not count towards the nesting of '<>'.
1000 * This function assumes that the delimited text does not contain strings.
1002 static void skipNestedAngles(const char*& s
)
1007 p
++; // skip the initial '<'
1008 while (*p
&& nest
> 0)
1010 // Below we can check for p-s >= 9 instead of 8 because
1011 // *s is '<' and cannot be part of "operator".
1014 if (p
-s
>= 9 && strncmp(p
-8, "operator", 8) == 0) {
1023 if (p
-s
>= 9 && strncmp(p
-8, "operator", 8) == 0) {
1033 TRACE(QString().sprintf("parse error: mismatching <> at %-20.20s", s
));
1039 * Find the end of line that is not inside braces
1041 static void findEnd(const char*& s
)
1044 while (*p
&& *p
!='\n') {
1045 while (*p
&& *p
!='\n' && *p
!='{')
1049 skipNested(p
, '{', '}'); p
--;
1055 static bool isNumberish(const char ch
)
1057 return (ch
>='0' && ch
<='9') || ch
=='.' || ch
=='x';
1060 void skipString(const char*& p
)
1062 // wchar_t strings begin with L
1069 while (*p
!= quote
) {
1071 // skip escaped character
1072 // no special treatment for octal values necessary
1075 // simply return if no more characters
1083 * Strings can consist of several parts, some of which contain repeated
1086 if (quote
== '\'') {
1087 // look ahaead for <repeats 123 times>
1088 const char* q
= p
+1;
1091 if (strncmp(q
, "<repeats ", 9) == 0) {
1093 while (*p
!= '\0' && *p
!= '>')
1096 p
++; /* skip the '>' */
1100 // Is the string continued? If so, there is no L in wchar_t strings
1103 // look ahead for another quote
1104 const char* q
= p
+1;
1107 if (*q
== '"' || *q
== '\'') {
1113 // some strings can end in <incomplete sequence ...>
1114 if (strncmp(q
, "<incomplete sequence", 20) == 0)
1117 while (*p
!= '\0' && *p
!= '>')
1120 p
++; /* skip the '>' */
1125 * There's a bug in gdb where it prints the beginning of the string
1126 * continuation and the comma-blank in the wrong order if the new string
1127 * begins with an incomplete multi-byte character. For now, let's check
1128 * for this in a very narrow condition, particularly, where the next
1129 * character is given in octal notation. Example:
1130 * 'a' <repeats 20 times>"\240, b"
1132 if (*p
== '"' && p
[1] == '\\' && isdigit(p
[2])) {
1134 while (isdigit(p
[i
]))
1136 if (p
[i
] == ',' && p
[i
+1] == ' ') {
1137 // just treat everything beginning at the dquote as string
1141 /* very long strings are followed by `...' */
1142 if (*p
== '.' && p
[1] == '.' && p
[2] == '.') {
1147 static void skipNestedWithString(const char*& s
, char opening
, char closing
)
1151 // parse a nested expression
1155 * Search for next matching `closing' char, skipping nested pairs of
1156 * `opening' and `closing' as well as strings.
1158 while (*p
&& nest
> 0) {
1159 if (*p
== opening
) {
1161 } else if (*p
== closing
) {
1163 } else if (*p
== '\'' || *p
== '\"') {
1170 TRACE(QString().sprintf("parse error: mismatching %c%c at %-20.20s", opening
, closing
, s
));
1175 inline void skipName(const char*& p
)
1177 // allow : (for enumeration values) and $ and . (for _vtbl.)
1178 while (isalnum(*p
) || *p
== '_' || *p
== ':' || *p
== '$' || *p
== '.')
1182 static bool parseName(const char*& s
, QString
& name
, VarTree::NameKind
& kind
)
1184 kind
= VarTree::NKplain
;
1187 // examples of names:
1190 // <string<a,b<c>,7> >
1193 skipNestedAngles(p
);
1194 name
= QString::fromLatin1(s
, p
- s
);
1195 kind
= VarTree::NKtype
;
1199 // name, which might be "static"; allow dot for "_vtbl."
1202 TRACE(QString().sprintf("parse error: not a name %-20.20s", s
));
1206 if (len
== 6 && strncmp(s
, "static", 6) == 0) {
1207 kind
= VarTree::NKstatic
;
1209 // its a static variable, name comes now
1215 TRACE(QString().sprintf("parse error: not a name after static %-20.20s", s
));
1220 name
= QString::fromLatin1(s
, len
);
1222 // return the new position
1227 static bool parseValue(const char*& s
, ExprValue
* variable
)
1229 variable
->m_value
= "";
1233 // Sometimes we find the following output:
1234 // {<text variable, no debug info>} 0x40012000 <access>
1235 // {<data variable, no debug info>}
1236 // {<variable (not text or data), no debug info>}
1237 if (strncmp(s
, "{<text variable, ", 17) == 0 ||
1238 strncmp(s
, "{<data variable, ", 17) == 0 ||
1239 strncmp(s
, "{<variable (not text or data), ", 31) == 0)
1241 const char* start
= s
;
1242 skipNested(s
, '{', '}');
1243 variable
->m_value
= QString::fromLatin1(start
, s
-start
);
1244 variable
->m_value
+= ' '; // add only a single space
1252 if (!parseNested(s
, variable
)) {
1255 // must be the closing brace
1257 TRACE("parse error: missing } of " + variable
->m_name
);
1261 // final white space
1266 // Sometimes we find a warning; it ends at the next LF
1267 else if (strncmp(s
, "warning: ", 9) == 0) {
1268 const char* end
= strchr(s
, '\n');
1269 s
= end
? end
: s
+strlen(s
);
1270 // skip space at start of next line
1275 // examples of leaf values (cannot be the empty string):
1281 // (DwContentType&) @0x8123456: {...}
1285 // 0x823abc <Array<int> virtual table>
1286 // 0x40240f <globarstr> "test"
1287 // (void (*)()) 0x8048480 <f(E *, char)>
1290 // &parseP (HTMLClueV *, char *)
1291 // Variable "x" is not available.
1292 // The value of variable 'x' is distributed...
1293 // -nan(0xfffff081defa0)
1300 skipNested(p
, '(', ')');
1304 variable
->m_value
= QString::fromLatin1(s
, p
- s
);
1307 bool reference
= false;
1309 // skip reference marker
1313 const char* start
= p
;
1317 // some values consist of more than one token
1318 bool checkMultiPart
= false;
1320 if (p
[0] == '0' && p
[1] == 'x') {
1323 while (isxdigit(*p
))
1327 * Assume this is a pointer, but only if it's not a reference, since
1328 * references can't be expanded.
1331 variable
->m_varKind
= VarTree::VKpointer
;
1334 * References are followed by a colon, in which case we'll
1335 * find the value following the reference address.
1340 // Paranoia. (Can this happen, i.e. reference not followed by ':'?)
1344 checkMultiPart
= true;
1345 } else if (isdigit(*p
)) {
1346 // parse decimal number, possibly a float
1349 if (*p
== '.') { /* TODO: obey i18n? */
1350 // In long arrays an integer may be followed by '...'.
1351 // We test for this situation and don't gobble the '...'.
1352 if (p
[1] != '.' || p
[0] != '.') {
1359 if (*p
== 'e' || *p
== 'E') {
1362 if (*p
== '-' || *p
== '+')
1368 // for char variables there is the char, eg. 10 '\n'
1369 checkMultiPart
= true;
1370 } else if (*p
== '<') {
1371 // e.g. <optimized out>
1372 skipNestedAngles(p
);
1373 } else if (*p
== '"' || *p
== '\'') {
1374 // character may have multipart: '\000' <repeats 11 times>
1375 checkMultiPart
= *p
== '\'';
1378 } else if (*p
== 'L' && (p
[1] == '"' || p
[1] == '\'')) {
1379 // ditto for wchar_t strings
1380 checkMultiPart
= p
[1] == '\'';
1382 } else if (*p
== '&') {
1386 while (isspace(*p
)) {
1390 skipNested(p
, '(', ')');
1392 } else if (strncmp(p
, "Variable \"", 10) == 0) {
1393 // Variable "x" is not available.
1394 p
+= 10; // skip to "
1396 if (strncmp(p
, "\" is not available.", 19) == 0) {
1399 } else if (strncmp(p
, "The value of variable '", 23) == 0) {
1402 const char* e
= strchr(p
, '.');
1410 // must be an enumeration value
1412 // nan (floating point Not a Number) is followed by a number in ()
1413 // enum values can look like A::(anonymous namespace)::blue
1415 bool isAnonNS
= strncmp(p
+1, "anonymous namespace)", 20) == 0;
1416 skipNested(p
, '(', ')');
1421 variable
->m_value
+= QString::fromLatin1(start
, p
- start
);
1423 // remove line breaks from the value; this is ok since
1424 // string values never contain a literal line break
1425 variable
->m_value
.replace('\n', ' ');
1427 while (checkMultiPart
) {
1431 // may be followed by a string or <...>
1432 // if this was a pointer with a string,
1433 // reset that pointer flag since we have now a value
1435 checkMultiPart
= false;
1437 if (*p
== '"' || *p
== '\'') {
1439 variable
->m_varKind
= VarTree::VKsimple
;
1440 } else if (*p
== 'L' && (p
[1] == '"' || p
[1] == '\'')) {
1441 skipString(p
); // wchar_t string
1442 variable
->m_varKind
= VarTree::VKsimple
;
1443 } else if (*p
== '<') {
1444 // if this value is part of an array, it might be followed
1445 // by <repeats 15 times>, which we don't skip here
1446 if (strncmp(p
, "<repeats ", 9) != 0) {
1447 skipNestedAngles(p
);
1448 checkMultiPart
= true;
1452 // there is always a blank before the string,
1453 // which we will include in the final string value
1454 variable
->m_value
+= QString::fromLatin1(start
-1, (p
- start
)+1);
1458 if (variable
->m_value
.length() == 0) {
1459 TRACE("parse error: no value for " + variable
->m_name
);
1463 // final white space
1469 * If this was a reference, the value follows. It might even be a
1470 * composite variable!
1480 static bool parseNested(const char*& s
, ExprValue
* variable
)
1482 // could be a structure or an array
1487 bool isStruct
= false;
1489 * If there is a name followed by an = or an < -- which starts a type
1490 * name -- or "static", it is a structure
1492 if (*p
== '<' || *p
== '}') {
1494 } else if (strncmp(p
, "static ", 7) == 0) {
1496 } else if (isalpha(*p
) || *p
== '_' || *p
== '$') {
1497 // look ahead for a comma after the name
1504 p
= s
; /* rescan the name */
1507 if (!parseVarSeq(p
, variable
)) {
1510 variable
->m_varKind
= VarTree::VKstruct
;
1512 if (!parseValueSeq(p
, variable
)) {
1515 variable
->m_varKind
= VarTree::VKarray
;
1521 static bool parseVarSeq(const char*& s
, ExprValue
* variable
)
1523 // parse a comma-separated sequence of variables
1524 ExprValue
* var
= variable
; /* var != 0 to indicate success if empty seq */
1528 if (strncmp(s
, "<No data fields>}", 17) == 0)
1530 // no member variables, so break out immediately
1531 s
+= 16; /* go to the closing brace */
1536 break; /* syntax error */
1537 variable
->appendChild(var
);
1540 // skip the comma and whitespace
1548 static bool parseValueSeq(const char*& s
, ExprValue
* variable
)
1550 // parse a comma-separated sequence of variables
1555 name
.sprintf("[%d]", index
);
1556 ExprValue
* var
= new ExprValue(name
, VarTree::NKplain
);
1557 good
= parseValue(s
, var
);
1562 // a value may be followed by "<repeats 45 times>"
1563 if (strncmp(s
, "<repeats ", 9) == 0) {
1566 int l
= strtol(s
, &end
, 10);
1567 if (end
== s
|| strncmp(end
, " times>", 7) != 0) {
1568 // should not happen
1572 TRACE(QString().sprintf("found <repeats %d times> in array", l
));
1573 // replace name and advance index
1574 name
.sprintf("[%d .. %d]", index
, index
+l
-1);
1577 // skip " times>" and space
1579 // possible final space
1585 variable
->appendChild(var
);
1586 // long arrays may be terminated by '...'
1587 if (strncmp(s
, "...", 3) == 0) {
1589 ExprValue
* var
= new ExprValue("...", VarTree::NKplain
);
1590 var
->m_value
= i18n("<additional entries of the array suppressed>");
1591 variable
->appendChild(var
);
1597 // skip the comma and whitespace
1601 // sometimes there is a closing brace after a comma
1609 * Parses a stack frame.
1611 static void parseFrameInfo(const char*& s
, QString
& func
,
1612 QString
& file
, int& lineNo
, DbgAddr
& address
)
1616 // next may be a hexadecimal address
1618 const char* start
= p
;
1622 while (isxdigit(*p
))
1624 address
= QString::fromLatin1(start
, p
-start
);
1625 if (strncmp(p
, " in ", 4) == 0)
1628 address
= DbgAddr();
1630 const char* start
= p
;
1631 // check for special signal handler frame
1632 if (strncmp(p
, "<signal handler called>", 23) == 0) {
1633 func
= QString::fromLatin1(start
, 23);
1643 * Skip the function name. It is terminated by a left parenthesis
1644 * which does not delimit "(anonymous namespace)" and which is
1645 * outside the angle brackets <> of template parameter lists
1646 * and is preceded by a space.
1651 // check for operator<< and operator<
1652 if (p
-start
>= 8 && strncmp(p
-8, "operator", 8) == 0)
1660 // skip template parameter list
1661 skipNestedAngles(p
);
1663 } else if (*p
== '(') {
1664 // this skips "(anonymous namespace)" as well as the formal
1665 // parameter list of the containing function if this is a member
1666 // of a nested class
1667 skipNestedWithString(p
, '(', ')');
1668 } else if (*p
== ' ') {
1671 break; // parameter list found
1685 * Skip parameters. But notice that for complicated conversion
1686 * functions (eg. "operator int(**)()()", ie. convert to pointer to
1687 * pointer to function) as well as operator()(...) we have to skip
1688 * additional pairs of parentheses. Furthermore, recent gdbs write the
1689 * demangled name followed by the arguments in a pair of parentheses,
1690 * where the demangled name can end in "const".
1693 skipNestedWithString(p
, '(', ')');
1697 if (strncmp(p
, "const", 5) == 0) {
1702 } while (*p
== '(');
1704 // check for file position
1705 if (strncmp(p
, "at ", 3) == 0) {
1707 const char* fileStart
= p
;
1708 // go for the end of the line
1709 while (*p
!= '\0' && *p
!= '\n')
1711 // search back for colon
1712 const char* colon
= p
;
1715 } while (*colon
!= ':');
1716 file
= QString::fromLatin1(fileStart
, colon
-fileStart
);
1717 lineNo
= atoi(colon
+1)-1;
1722 // check for "from shared lib"
1723 if (strncmp(p
, "from ", 5) == 0) {
1725 // go for the end of the line
1726 while (*p
!= '\0' && *p
!= '\n')
1735 // construct the function name (including file info)
1739 func
= QString::fromLatin1(start
, p
-start
-1); /* don't include \n */
1744 * Replace \n (and whitespace around it) in func by a blank. We cannot
1745 * use QString::simplified() for this because this would also
1746 * simplify space that belongs to a string arguments that gdb sometimes
1747 * prints in the argument lists of the function.
1749 ASSERT(!isspace(func
[0].toLatin1())); // there must be non-white before first \n
1751 while ((nl
= func
.indexOf('\n', nl
)) >= 0) {
1752 // search back to the beginning of the whitespace
1753 int startWhite
= nl
;
1756 } while (isspace(func
[startWhite
].toLatin1()));
1758 // search forward to the end of the whitespace
1761 } while (isspace(func
[nl
].toLatin1()));
1763 func
.replace(startWhite
, nl
-startWhite
, " ");
1764 /* continue searching for more \n's at this place: */
1771 * Parses a stack frame including its frame number
1773 static bool parseFrame(const char*& s
, int& frameNo
, QString
& func
,
1774 QString
& file
, int& lineNo
, DbgAddr
& address
)
1777 // #1 0x8048881 in Dl::Dl (this=0xbffff418, r=3214) at testfile.cpp:72
1778 // Breakpoint 3, Cl::f(int) const (this=0xbffff3c0, x=17) at testfile.cpp:155
1780 // must start with a hash mark followed by number
1781 // or with "Breakpoint " followed by number and comma
1785 s
++; /* skip the hash mark */
1786 } else if (strncmp(s
, "Breakpoint ", 11) == 0) {
1787 if (!isdigit(s
[11]))
1789 s
+= 11; /* skip "Breakpoint" */
1798 while (isspace(*s
) || *s
== ',')
1800 parseFrameInfo(s
, func
, file
, lineNo
, address
);
1804 void GdbDriver::parseBackTrace(const char* output
, std::list
<StackFrame
>& stack
)
1807 int lineNo
, frameNo
;
1810 while (::parseFrame(output
, frameNo
, func
, file
, lineNo
, address
)) {
1811 stack
.push_back(StackFrame());
1812 StackFrame
* frm
= &stack
.back();
1813 frm
->frameNo
= frameNo
;
1814 frm
->fileName
= file
;
1815 frm
->lineNo
= lineNo
;
1816 frm
->address
= address
;
1817 frm
->var
= new ExprValue(func
, VarTree::NKplain
);
1821 bool GdbDriver::parseFrameChange(const char* output
, int& frameNo
,
1822 QString
& file
, int& lineNo
, DbgAddr
& address
)
1825 return ::parseFrame(output
, frameNo
, func
, file
, lineNo
, address
);
1829 bool GdbDriver::parseBreakList(const char* output
, std::list
<Breakpoint
>& brks
)
1831 // skip first line, which is the headline
1832 const char* p
= strchr(output
, '\n');
1842 while (*p
!= '\0') {
1845 bp
.id
= strtol(p
, &dummy
, 10); /* don't care about overflows */
1847 // check for continued <MULTIPLE> breakpoint
1848 if (*p
== '.' && isdigit(p
[1]))
1850 // continuation: skip type and disposition
1857 if (strncmp(p
, "breakpoint", 10) == 0) {
1859 } else if (strncmp(p
, "hw watchpoint", 13) == 0) {
1860 bp
.type
= Breakpoint::watchpoint
;
1862 } else if (strncmp(p
, "watchpoint", 10) == 0) {
1863 bp
.type
= Breakpoint::watchpoint
;
1871 bp
.temporary
= *p
++ == 'd';
1873 while (*p
!= '\0' && !isspace(*p
)) /* "keep" or "del" */
1880 bp
.enabled
= *p
++ == 'y';
1881 while (*p
!= '\0' && !isspace(*p
)) /* "y" or "n" */
1887 // the address, if present
1888 if (bp
.type
== Breakpoint::breakpoint
&&
1889 strncmp(p
, "0x", 2) == 0)
1891 const char* start
= p
;
1892 while (*p
!= '\0' && !isspace(*p
))
1894 bp
.address
= QString::fromLatin1(start
, p
-start
);
1895 while (isspace(*p
) && *p
!= '\n')
1900 // remainder is location, hit and ignore count, condition
1901 end
= strchr(p
, '\n');
1904 p
+= bp
.location
.length();
1906 // location of a <MULTIPLE> filled in from subsequent breakpoints
1907 if (strncmp(p
, "<MULTIPLE>", 10) != 0)
1908 bp
.location
= QString::fromLatin1(p
, end
-p
).trimmed();
1909 p
= end
+1; /* skip over \n */
1912 // may be continued in next line
1913 while (isspace(*p
)) { /* p points to beginning of line */
1914 // skip white space at beginning of line
1919 end
= strchr(p
, '\n');
1923 if (strncmp(p
, "breakpoint already hit", 22) == 0) {
1924 // extract the hit count
1926 bp
.hitCount
= strtol(p
, &dummy
, 10);
1927 TRACE(QString("hit count %1").arg(bp
.hitCount
));
1928 } else if (strncmp(p
, "stop only if ", 13) == 0) {
1929 // extract condition
1931 bp
.condition
= QString::fromLatin1(p
, end
-p
).trimmed();
1932 TRACE("condition: "+bp
.condition
);
1933 } else if (strncmp(p
, "ignore next ", 12) == 0) {
1934 // extract ignore count
1936 bp
.ignoreCount
= strtol(p
, &dummy
, 10);
1937 TRACE(QString("ignore count %1").arg(bp
.ignoreCount
));
1939 // indeed a continuation
1940 bp
.location
+= " " + QString::fromLatin1(p
, end
-p
).trimmed();
1944 p
++; /* skip '\n' */
1947 if (brks
.empty() || brks
.back().id
!= bp
.id
) {
1950 // this is a continuation; fill in location if not yet set
1951 // otherwise, drop this breakpoint
1952 Breakpoint
& mbp
= brks
.back();
1953 if (mbp
.location
.isEmpty() && !bp
.location
.isEmpty()) {
1954 mbp
.location
= bp
.location
;
1955 mbp
.address
= bp
.address
;
1956 } else if (mbp
.address
.isEmpty() && !bp
.address
.isEmpty()) {
1957 mbp
.address
= bp
.address
;
1964 std::list
<ThreadInfo
> GdbDriver::parseThreadList(const char* output
)
1966 std::list
<ThreadInfo
> threads
;
1967 if (strcmp(output
, "\n") == 0 ||
1968 strncmp(output
, "No stack.", 9) == 0 ||
1969 strncmp(output
, "No threads.", 11) == 0) {
1974 bool newFormat
= false;
1975 const char* p
= output
;
1976 while (*p
!= '\0') {
1978 // seach look for thread id, watching out for the focus indicator
1979 thr
.hasFocus
= false;
1980 while (isspace(*p
)) /* may be \n from prev line: see "No stack" below */
1983 // recent GDBs write a header line; skip it
1984 if (threads
.empty() && strncmp(p
, "Id Target", 11) == 0) {
1985 p
= strchr(p
, '\n');
1989 continue; // next line please, '\n' is skipped above
1993 thr
.hasFocus
= true;
1995 // there follows only whitespace
1998 char *temp_end
= NULL
; /* we need a non-const 'end' for strtol to use...*/
1999 thr
.id
= strtol(p
, &temp_end
, 10);
2002 // syntax error: no number found; bail out
2012 * Now follows the thread's SYSTAG.
2015 // In the old format, it is terminated by two blanks.
2016 end
= strstr(p
, " ");
2018 // syntax error; bail out
2023 // In the new format lies crazyness: there is no definitive
2024 // end marker. At best we can guess when the SYSTAG ends.
2025 // A typical thread list on Linux looks like this:
2027 // Id Target Id Frame
2028 // 2 Thread 0x7ffff7854700 (LWP 10827) "thrserver" 0x00007ffff7928631 in clone () from /lib64/libc.so.6
2029 // * 1 Thread 0x7ffff7fcc700 (LWP 10808) "thrserver" main () at thrserver.c:84
2031 // Looking at GDB's code, the Target Id ends in tokens that
2032 // are bracketed by parentheses or quotes. Therefore,
2033 // we skip (at most) two tokens ('Thread' and the address),
2034 // and then all parts that are in parentheses or quotes.
2041 } else if (*end
== '(') {
2042 skipNested(end
, '(', ')');
2045 while (*end
&& !isspace(*end
))
2051 while (isspace(*end
))
2055 thr
.threadName
= QString::fromLatin1(p
, end
-p
).trimmed();
2059 * Now follows a standard stack frame. Sometimes, however, gdb
2060 * catches a thread at an instant where it doesn't have a stack.
2062 if (strncmp(p
, "[No stack.]", 11) != 0) {
2063 ::parseFrameInfo(p
, thr
.function
, thr
.fileName
, thr
.lineNo
, thr
.address
);
2065 thr
.function
= "[No stack]";
2067 p
+= 11; /* \n is skipped above */
2070 threads
.push_back(thr
);
2075 static bool parseNewBreakpoint(const char* o
, int& id
,
2076 QString
& file
, int& lineNo
, QString
& address
);
2077 static bool parseNewWatchpoint(const char* o
, int& id
,
2080 bool GdbDriver::parseBreakpoint(const char* output
, int& id
,
2081 QString
& file
, int& lineNo
, QString
& address
)
2083 // skip lines of that begin with "(Cannot find"
2084 while (strncmp(output
, "(Cannot find", 12) == 0 ||
2085 strncmp(output
, "Note: breakpoint", 16) == 0)
2087 output
= strchr(output
, '\n');
2090 output
++; /* skip newline */
2093 if (strncmp(output
, "Breakpoint ", 11) == 0) {
2094 output
+= 11; /* skip "Breakpoint " */
2095 return ::parseNewBreakpoint(output
, id
, file
, lineNo
, address
);
2096 } else if (strncmp(output
, "Temporary breakpoint ", 21) == 0) {
2098 return ::parseNewBreakpoint(output
, id
, file
, lineNo
, address
);
2099 } else if (strncmp(output
, "Hardware watchpoint ", 20) == 0) {
2101 return ::parseNewWatchpoint(output
, id
, address
);
2102 } else if (strncmp(output
, "Watchpoint ", 11) == 0) {
2104 return ::parseNewWatchpoint(output
, id
, address
);
2109 static bool parseNewBreakpoint(const char* o
, int& id
,
2110 QString
& file
, int& lineNo
, QString
& address
)
2114 id
= strtoul(o
, &p
, 10);
2118 // check for the address
2119 if (strncmp(p
, " at 0x", 6) == 0) {
2120 char* start
= p
+4; /* skip " at ", but not 0x */
2122 while (isxdigit(*p
))
2124 address
= QString::fromLatin1(start
, p
-start
);
2128 * Mostly, GDB responds with this syntax:
2130 * Breakpoint 1 at 0x400b94: file multibrkpt.cpp, line 9. (2 locations)
2132 * but sometimes it uses this syntax:
2134 * Breakpoint 4 at 0x804f158: lotto739.cpp:95. (3 locations)
2136 char* fileEnd
, *numStart
= 0;
2137 char* fileStart
= strstr(p
, "file ");
2141 fileEnd
= strstr(fileStart
, ", line ");
2143 numStart
= fileEnd
+ 7;
2145 if (numStart
== 0 && p
[0] == ':' && p
[1] == ' ')
2148 while (isspace(*fileStart
))
2150 fileEnd
= strchr(fileStart
, ':');
2152 numStart
= fileEnd
+ 1;
2155 return !address
.isEmpty(); /* parse error only if there's no address */
2157 QString fileName
= QString::fromLatin1(fileStart
, fileEnd
-fileStart
);
2158 int line
= strtoul(numStart
, &p
, 10);
2163 lineNo
= line
-1; /* zero-based! */
2167 static bool parseNewWatchpoint(const char* o
, int& id
,
2172 id
= strtoul(o
, &p
, 10);
2176 if (strncmp(p
, ": ", 2) != 0)
2180 // all the rest on the line is the expression
2181 expr
= QString::fromLatin1(p
, strlen(p
)).trimmed();
2185 void GdbDriver::parseLocals(const char* output
, std::list
<ExprValue
*>& newVars
)
2187 // check for possible error conditions
2188 if (strncmp(output
, "No symbol table", 15) == 0)
2193 while (*output
!= '\0') {
2194 while (isspace(*output
))
2196 if (*output
== '\0')
2198 // skip occurrences of "No locals" and "No args"
2199 if (strncmp(output
, "No locals", 9) == 0 ||
2200 strncmp(output
, "No arguments", 12) == 0)
2202 output
= strchr(output
, '\n');
2209 ExprValue
* variable
= parseVar(output
);
2210 if (variable
== 0) {
2213 // do not add duplicates
2214 for (std::list
<ExprValue
*>::iterator o
= newVars
.begin(); o
!= newVars
.end(); ++o
) {
2215 if ((*o
)->m_name
== variable
->m_name
) {
2220 newVars
.push_back(variable
);
2225 ExprValue
* GdbDriver::parsePrintExpr(const char* output
, bool wantErrorValue
)
2228 // check for error conditions
2229 if (!parseErrorMessage(output
, var
, wantErrorValue
))
2231 // parse the variable
2232 var
= parseVar(output
);
2237 bool GdbDriver::parseChangeWD(const char* output
, QString
& message
)
2239 bool isGood
= false;
2240 message
= QString(output
).simplified();
2241 if (message
.isEmpty()) {
2242 message
= i18n("New working directory: ") + m_programWD
;
2248 bool GdbDriver::parseChangeExecutable(const char* output
, QString
& message
)
2252 m_haveCoreFile
= false;
2255 * Lines starting with the following do not indicate errors:
2256 * Using host libthread_db
2257 * (no debugging symbols found)
2258 * Reading symbols from
2260 while (strncmp(output
, "Reading symbols from", 20) == 0 ||
2261 strncmp(output
, "done.", 5) == 0 ||
2262 strncmp(output
, "Missing separate debuginfo", 26) == 0 ||
2263 strncmp(output
, "Try: ", 5) == 0 ||
2264 strncmp(output
, "Using host libthread_db", 23) == 0 ||
2265 strncmp(output
, "(no debugging symbols found)", 28) == 0)
2267 // this line is good, go to the next one
2268 const char* end
= strchr(output
, '\n');
2270 output
+= strlen(output
);
2276 * If we've parsed all lines, there was no error.
2278 return output
[0] == '\0';
2281 bool GdbDriver::parseCoreFile(const char* output
)
2283 // if command succeeded, gdb emits a line starting with "#0 "
2284 m_haveCoreFile
= strstr(output
, "\n#0 ") != 0;
2285 return m_haveCoreFile
;
2288 uint
GdbDriver::parseProgramStopped(const char* output
, QString
& message
)
2290 // optionally: "program changed, rereading symbols",
2292 // "Program exited normally"
2293 // "Program terminated with wignal SIGSEGV"
2294 // "Program received signal SIGINT" or other signal
2296 // GDB since 7.3 prints
2297 // "[Inferior 1 (process 13400) exited normally]"
2298 // "[Inferior 1 (process 14698) exited with code 01]"
2300 // go through the output, line by line, checking what we have
2301 const char* start
= output
- 1;
2302 uint flags
= SFprogramActive
;
2303 message
= QString();
2305 start
++; /* skip '\n' */
2307 if (strncmp(start
, "Program ", 8) == 0 ||
2308 strncmp(start
, "ptrace: ", 8) == 0) {
2310 * When we receive a signal, the program remains active.
2312 * Special: If we "stopped" in a corefile, the string "Program
2313 * terminated with signal"... is displayed. (Normally, we see
2314 * "Program received signal"... when a signal happens.)
2316 if (strncmp(start
, "Program exited", 14) == 0 ||
2317 (strncmp(start
, "Program terminated", 18) == 0 && !m_haveCoreFile
) ||
2318 strncmp(start
, "ptrace: ", 8) == 0)
2320 flags
&= ~SFprogramActive
;
2324 const char* endOfMessage
= strchr(start
, '\n');
2325 if (endOfMessage
== 0)
2326 endOfMessage
= start
+ strlen(start
);
2327 message
= QString::fromLatin1(start
, endOfMessage
-start
);
2328 } else if (strncmp(start
, "[Inferior ", 10) == 0) {
2329 const char* p
= start
+ 10;
2330 // skip number and space
2331 while (*p
&& !isspace(*p
))
2336 skipNested(p
, '(', ')');
2337 if (strncmp(p
, " exited ", 8) == 0) {
2338 flags
&= ~SFprogramActive
;
2341 const char* end
= strchr(p
, '\n');
2343 end
= p
+ strlen(p
);
2344 // strip [] from the message
2345 message
= QString::fromLatin1(start
+1, end
-start
-2);
2348 } else if (strncmp(start
, "Breakpoint ", 11) == 0) {
2350 * We stopped at a (permanent) breakpoint (gdb doesn't tell us
2351 * that it stopped at a temporary breakpoint).
2353 flags
|= SFrefreshBreak
;
2354 } else if (strstr(start
, "re-reading symbols.") != 0) {
2355 flags
|= SFrefreshSource
;
2358 // next line, please
2359 start
= strchr(start
, '\n');
2360 } while (start
!= 0);
2363 * Gdb only notices when new threads have appeared, but not when a
2364 * thread finishes. So we always have to assume that the list of
2365 * threads has changed.
2367 flags
|= SFrefreshThreads
;
2372 QStringList
GdbDriver::parseSharedLibs(const char* output
)
2375 if (strncmp(output
, "No shared libraries loaded", 26) == 0)
2378 // parse the table of shared libraries
2380 // strip off head line
2381 output
= strchr(output
, '\n');
2384 output
++; /* skip '\n' */
2386 while (*output
!= '\0') {
2387 // format of a line is
2388 // 0x404c5000 0x40580d90 Yes /lib/libc.so.5
2389 // 3 blocks of non-space followed by space
2390 for (int i
= 0; *output
!= '\0' && i
< 3; i
++) {
2391 while (*output
!= '\0' && !isspace(*output
)) { /* non-space */
2394 while (isspace(*output
)) { /* space */
2398 if (*output
== '\0')
2400 const char* start
= output
;
2401 output
= strchr(output
, '\n');
2403 output
= start
+ strlen(start
);
2404 shlibName
= QString::fromLatin1(start
, output
-start
);
2405 if (*output
!= '\0')
2407 shlibs
.append(shlibName
);
2408 TRACE("found shared lib " + shlibName
);
2413 bool GdbDriver::parseFindType(const char* output
, QString
& type
)
2415 if (strncmp(output
, "type = ", 7) != 0)
2419 * Everything else is the type. We strip off any leading "const" and any
2420 * trailing "&" on the grounds that neither affects the decoding of the
2421 * object. We also strip off all white-space from the type.
2424 if (strncmp(output
, "const ", 6) == 0)
2427 type
.replace(QRegExp("\\s+"), "");
2428 if (type
.endsWith("&"))
2429 type
.truncate(type
.length() - 1);
2433 std::list
<RegisterInfo
> GdbDriver::parseRegisters(const char* output
)
2435 std::list
<RegisterInfo
> regs
;
2436 if (strncmp(output
, "The program has no registers now", 32) == 0) {
2440 // parse register values
2441 while (*output
!= '\0')
2444 // skip space at the start of the line
2445 while (isspace(*output
))
2449 const char* start
= output
;
2450 while (*output
!= '\0' && !isspace(*output
))
2452 if (*output
== '\0')
2454 reg
.regName
= QString::fromLatin1(start
, output
-start
);
2457 while (isspace(*output
))
2463 * If we find a brace now, this is a vector register. We look for
2464 * the closing brace and treat the result as cooked value.
2469 skipNested(output
, '{', '}');
2470 value
= QString::fromLatin1(start
, output
-start
).simplified();
2471 // skip space, but not the end of line
2472 while (isspace(*output
) && *output
!= '\n')
2474 // get rid of the braces at the begining and the end
2476 if (value
[value
.length()-1] == '}') {
2477 value
= value
.left(value
.length()-1);
2479 // gdb 5.3 doesn't print a separate set of raw values
2480 if (*output
== '{') {
2481 // another set of vector follows
2482 // what we have so far is the raw value
2483 reg
.rawValue
= value
;
2486 skipNested(output
, '{', '}');
2487 value
= QString::fromLatin1(start
, output
-start
).simplified();
2490 // find first type that does not have an array, this is the RAW value
2491 const char* end
=start
;
2493 const char* cur
=start
;
2495 while (*cur
!= '=' && cur
<end
)
2498 while (isspace(*cur
) && cur
<end
)
2500 if (isNumberish(*cur
)) {
2502 while (*end
&& (*end
!='}') && (*end
!=',') && (*end
!='\n'))
2504 QString rawValue
= QString::fromLatin1(cur
, end
-cur
).simplified();
2505 reg
.rawValue
= rawValue
;
2507 if (rawValue
.left(2)=="0x") {
2508 // ok we have a raw value, now get it's type
2510 while (isspace(*end
) || *end
=='=') end
--;
2513 while (*cur
!='{' && *cur
!=' ')
2516 reg
.type
= QString::fromLatin1(cur
, end
-cur
);
2523 // skip to the end of line
2524 while (*output
!= '\0' && *output
!= '\n')
2526 // get rid of the braces at the begining and the end
2528 if (value
[value
.length()-1] == '}') {
2529 value
.truncate(value
.length()-1);
2532 reg
.cookedValue
= value
;
2537 // the rest of the line is the register value
2539 output
= strchr(output
,'\n');
2541 output
= start
+ strlen(start
);
2542 value
+= QString::fromLatin1(start
, output
-start
).simplified();
2545 * Look ahead: if the subsequent line is indented, it continues
2546 * the current register value.
2548 if (output
!= 0 && isspace(output
[1]))
2556 * We split the raw from the cooked values.
2557 * Some modern gdbs explicitly say: "0.1234 (raw 0x3e4567...)".
2558 * Here, the cooked value comes first, and the raw value is in
2561 int pos
= value
.indexOf(" (raw ");
2564 reg
.cookedValue
= value
.left(pos
);
2565 reg
.rawValue
= value
.mid(pos
+6);
2566 if (reg
.rawValue
.right(1) == ")") // remove closing bracket
2567 reg
.rawValue
.truncate(reg
.rawValue
.length()-1);
2572 * In other cases we split off the first token (separated by
2573 * whitespace). It is the raw value. The remainder of the line
2574 * is the cooked value.
2576 int pos
= value
.indexOf(' ');
2578 reg
.rawValue
= value
;
2579 reg
.cookedValue
= QString();
2581 reg
.rawValue
= value
.left(pos
);
2582 reg
.cookedValue
= value
.mid(pos
+1);
2586 if (*output
!= '\0')
2587 output
++; /* skip '\n' */
2589 regs
.push_back(reg
);
2594 bool GdbDriver::parseInfoLine(const char* output
, QString
& addrFrom
, QString
& addrTo
)
2596 // "is at address" or "starts at address"
2597 const char* start
= strstr(output
, "s at address ");
2602 const char* p
= start
;
2603 while (*p
!= '\0' && !isspace(*p
))
2605 addrFrom
= QString::fromLatin1(start
, p
-start
);
2607 start
= strstr(p
, "and ends at ");
2615 while (*p
!= '\0' && !isspace(*p
))
2617 addrTo
= QString::fromLatin1(start
, p
-start
);
2622 std::list
<DisassembledCode
> GdbDriver::parseDisassemble(const char* output
)
2624 std::list
<DisassembledCode
> code
;
2626 if (strncmp(output
, "Dump of assembler", 17) != 0) {
2634 // remove first line
2635 const char* p
= strchr(output
, '\n');
2637 return code
; /* not a regular output */
2642 const char* end
= strstr(output
, "End of assembler");
2644 end
= p
+ strlen(p
);
2646 // remove function offsets from the lines
2650 // skip initial space or PC pointer ("=>", since gdb 7.1)
2654 else if (p
[0] == '=' && p
[1] == '>')
2659 const char* start
= p
;
2661 while (p
!= end
&& !isspace(*p
))
2663 c
.address
= QString::fromLatin1(start
, p
-start
);
2665 // function name (enclosed in '<>', followed by ':')
2666 while (p
!= end
&& *p
!= '<')
2669 skipNestedAngles(p
);
2674 while (p
!= end
&& isspace(*p
))
2677 // code until end of line
2679 while (p
!= end
&& *p
!= '\n')
2681 if (p
!= end
) /* include '\n' */
2684 c
.code
= QString::fromLatin1(start
, p
-start
);
2690 QString
GdbDriver::parseMemoryDump(const char* output
, std::list
<MemoryDump
>& memdump
)
2692 if (isErrorExpr(output
)) {
2693 // error; strip space
2694 QString msg
= output
;
2695 return msg
.trimmed();
2698 const char* p
= output
; /* save typing */
2704 const char* start
= p
;
2705 while (*p
!= '\0' && *p
!= ':' && !isspace(*p
))
2707 md
.address
= QString::fromLatin1(start
, p
-start
);
2709 // parse function offset
2713 while (*p
!= '\0' && !(*p
== ':' && isspace(p
[1])))
2715 md
.address
.fnoffs
= QString::fromLatin1(start
, p
-start
);
2719 // skip space; this may skip a new-line char!
2722 // everything to the end of the line is the memory dump
2723 const char* end
= strchr(p
, '\n');
2725 md
.dump
= QString::fromLatin1(p
, end
-p
);
2728 md
.dump
= QString::fromLatin1(p
, strlen(p
));
2731 memdump
.push_back(md
);
2737 QString
GdbDriver::editableValue(VarTree
* value
)
2739 QByteArray ba
= value
->value().toLatin1();
2740 const char* s
= ba
.constData();
2742 // if the variable is a pointer value that contains a cast,
2745 skipNested(s
, '(', ')');
2752 const char* start
= s
;
2754 if (strncmp(s
, "0x", 2) == 0)
2757 while (isxdigit(*s
))
2761 * What we saw so far might have been a reference. If so, edit the
2762 * referenced value. Otherwise, edit the pointer.
2770 // if it's a pointer to a string, remove the string
2771 const char* end
= s
;
2776 return QString::fromLatin1(start
, end
-start
);
2779 return QString::fromLatin1(start
, strlen(start
));
2783 // else leave it unchanged (or stripped of the reference preamble)
2787 QString
GdbDriver::parseSetVariable(const char* output
)
2789 // if there is any output, it is an error message
2790 QString msg
= output
;
2791 return msg
.trimmed();
2795 #include "gdbdriver.moc"