2 * Copyright Johannes Sixt
3 * This file is licensed under the GNU General Public License Version 2.
4 * See the file COPYING in the toplevel directory of the source directory.
11 #include <QStringList>
12 #include <klocale.h> /* i18n */
15 #include <stdlib.h> /* strtol, atoi */
16 #include <string.h> /* strcpy */
21 static void skipString(const char*& p
);
22 static void skipNested(const char*& s
, char opening
, char closing
);
23 static ExprValue
* parseVar(const char*& s
);
24 static bool parseName(const char*& s
, QString
& name
, VarTree::NameKind
& kind
);
25 static bool parseValue(const char*& s
, ExprValue
* variable
);
26 static bool parseNested(const char*& s
, ExprValue
* variable
);
27 static bool parseVarSeq(const char*& s
, ExprValue
* variable
);
28 static bool parseValueSeq(const char*& s
, ExprValue
* variable
);
30 #define PROMPT "(kdbg)"
33 // TODO: make this cmd info stuff non-static to allow multiple
34 // simultaneous gdbs to run!
38 const char* fmt
; /* format string */
40 argNone
, argString
, argNum
,
41 argStringNum
, argNumString
,
47 // This is how the QString data print statement generally looks like.
48 // It is set by KDebugger via setPrintQStringDataCmd().
50 static const char printQStringStructFmt
[] =
51 // if the string data is junk, fail early
52 "print ($qstrunicode=($qstrdata=(%s))->unicode)?"
53 // print an array of shorts
54 "(*(unsigned short*)$qstrunicode)@"
56 "(($qstrlen=(unsigned int)($qstrdata->len))>100?100:$qstrlen)"
57 // if unicode data is 0, report a special value
60 static const char printQStringStructFmt
[] = "print (0?\"%s\":$kdbgundef)\n";
63 * The following array of commands must be sorted by the DC* values,
64 * because they are used as indices.
66 static GdbCmdInfo cmds
[] = {
67 { DCinitialize
, "", GdbCmdInfo::argNone
},
68 { DCtty
, "tty %s\n", GdbCmdInfo::argString
},
69 { DCexecutable
, "file \"%s\"\n", GdbCmdInfo::argString
},
70 { DCtargetremote
, "target remote %s\n", GdbCmdInfo::argString
},
72 { DCcorefile
, "target FreeBSD-core %s\n", GdbCmdInfo::argString
},
74 { DCcorefile
, "target core %s\n", GdbCmdInfo::argString
},
76 { DCattach
, "attach %s\n", GdbCmdInfo::argString
},
77 { DCinfolinemain
, "kdbg_infolinemain\n", GdbCmdInfo::argNone
},
78 { DCinfolocals
, "kdbg__alllocals\n", GdbCmdInfo::argNone
},
79 { DCinforegisters
, "info all-registers\n", GdbCmdInfo::argNone
},
80 { DCexamine
, "x %s %s\n", GdbCmdInfo::argString2
},
81 { DCinfoline
, "info line %s:%d\n", GdbCmdInfo::argStringNum
},
82 { DCdisassemble
, "disassemble %s %s\n", GdbCmdInfo::argString2
},
83 { DCsetargs
, "set args %s\n", GdbCmdInfo::argString
},
84 { DCsetenv
, "set env %s %s\n", GdbCmdInfo::argString2
},
85 { DCunsetenv
, "unset env %s\n", GdbCmdInfo::argString
},
86 { DCsetoption
, "setoption %s %d\n", GdbCmdInfo::argStringNum
},
87 { DCcd
, "cd %s\n", GdbCmdInfo::argString
},
88 { DCbt
, "bt\n", GdbCmdInfo::argNone
},
89 { DCrun
, "run\n", GdbCmdInfo::argNone
},
90 { DCcont
, "cont\n", GdbCmdInfo::argNone
},
91 { DCstep
, "step\n", GdbCmdInfo::argNone
},
92 { DCstepi
, "stepi\n", GdbCmdInfo::argNone
},
93 { DCnext
, "next\n", GdbCmdInfo::argNone
},
94 { DCnexti
, "nexti\n", GdbCmdInfo::argNone
},
95 { DCfinish
, "finish\n", GdbCmdInfo::argNone
},
96 { DCuntil
, "until %s:%d\n", GdbCmdInfo::argStringNum
},
97 { DCkill
, "kill\n", GdbCmdInfo::argNone
},
98 { DCbreaktext
, "break %s\n", GdbCmdInfo::argString
},
99 { DCbreakline
, "break %s:%d\n", GdbCmdInfo::argStringNum
},
100 { DCtbreakline
, "tbreak %s:%d\n", GdbCmdInfo::argStringNum
},
101 { DCbreakaddr
, "break *%s\n", GdbCmdInfo::argString
},
102 { DCtbreakaddr
, "tbreak *%s\n", GdbCmdInfo::argString
},
103 { DCwatchpoint
, "watch %s\n", GdbCmdInfo::argString
},
104 { DCdelete
, "delete %d\n", GdbCmdInfo::argNum
},
105 { DCenable
, "enable %d\n", GdbCmdInfo::argNum
},
106 { DCdisable
, "disable %d\n", GdbCmdInfo::argNum
},
107 { DCprint
, "print %s\n", GdbCmdInfo::argString
},
108 { DCprintDeref
, "print *(%s)\n", GdbCmdInfo::argString
},
109 { DCprintStruct
, "print %s\n", GdbCmdInfo::argString
},
110 { DCprintQStringStruct
, printQStringStructFmt
, GdbCmdInfo::argString
},
111 { DCprintPopup
, "print %s\n", GdbCmdInfo::argString
},
112 { DCframe
, "frame %d\n", GdbCmdInfo::argNum
},
113 { DCfindType
, "whatis %s\n", GdbCmdInfo::argString
},
114 { DCinfosharedlib
, "info sharedlibrary\n", GdbCmdInfo::argNone
},
115 { DCthread
, "thread %d\n", GdbCmdInfo::argNum
},
116 { DCinfothreads
, "info threads\n", GdbCmdInfo::argNone
},
117 { DCinfobreak
, "info breakpoints\n", GdbCmdInfo::argNone
},
118 { DCcondition
, "condition %d %s\n", GdbCmdInfo::argNumString
},
119 { DCsetpc
, "set variable $pc=%s\n", GdbCmdInfo::argString
},
120 { DCignore
, "ignore %d %d\n", GdbCmdInfo::argNum2
},
121 { DCprintWChar
, "print ($s=%s)?*$s@wcslen($s):0x0\n", GdbCmdInfo::argString
},
122 { DCsetvariable
, "set variable %s=%s\n", GdbCmdInfo::argString2
},
125 #define NUM_CMDS (int(sizeof(cmds)/sizeof(cmds[0])))
126 #define MAX_FMTLEN 200
128 GdbDriver::GdbDriver() :
132 // check command info array
134 for (int i
= 0; i
< NUM_CMDS
; i
++) {
135 // must be indexable by DbgCommand values, i.e. sorted by DbgCommand values
136 assert(i
== cmds
[i
].cmd
);
137 // a format string must be associated
138 assert(cmds
[i
].fmt
!= 0);
139 assert(strlen(cmds
[i
].fmt
) <= MAX_FMTLEN
);
140 // format string must match arg specification
141 switch (cmds
[i
].argsNeeded
) {
142 case GdbCmdInfo::argNone
:
143 assert(strchr(cmds
[i
].fmt
, '%') == 0);
145 case GdbCmdInfo::argString
:
146 perc
= strchr(cmds
[i
].fmt
, '%');
147 assert(perc
!= 0 && perc
[1] == 's');
148 assert(strchr(perc
+2, '%') == 0);
150 case GdbCmdInfo::argNum
:
151 perc
= strchr(cmds
[i
].fmt
, '%');
152 assert(perc
!= 0 && perc
[1] == 'd');
153 assert(strchr(perc
+2, '%') == 0);
155 case GdbCmdInfo::argStringNum
:
156 perc
= strchr(cmds
[i
].fmt
, '%');
157 assert(perc
!= 0 && perc
[1] == 's');
158 perc
= strchr(perc
+2, '%');
159 assert(perc
!= 0 && perc
[1] == 'd');
160 assert(strchr(perc
+2, '%') == 0);
162 case GdbCmdInfo::argNumString
:
163 perc
= strchr(cmds
[i
].fmt
, '%');
164 assert(perc
!= 0 && perc
[1] == 'd');
165 perc
= strchr(perc
+2, '%');
166 assert(perc
!= 0 && perc
[1] == 's');
167 assert(strchr(perc
+2, '%') == 0);
169 case GdbCmdInfo::argString2
:
170 perc
= strchr(cmds
[i
].fmt
, '%');
171 assert(perc
!= 0 && perc
[1] == 's');
172 perc
= strchr(perc
+2, '%');
173 assert(perc
!= 0 && perc
[1] == 's');
174 assert(strchr(perc
+2, '%') == 0);
176 case GdbCmdInfo::argNum2
:
177 perc
= strchr(cmds
[i
].fmt
, '%');
178 assert(perc
!= 0 && perc
[1] == 'd');
179 perc
= strchr(perc
+2, '%');
180 assert(perc
!= 0 && perc
[1] == 'd');
181 assert(strchr(perc
+2, '%') == 0);
185 assert(strlen(printQStringStructFmt
) <= MAX_FMTLEN
);
189 GdbDriver::~GdbDriver()
194 QString
GdbDriver::driverName() const
199 QString
GdbDriver::defaultGdb()
203 " --fullname" /* to get standard file names each time the prog stops */
204 " --nx"; /* do not execute initialization files */
207 QString
GdbDriver::defaultInvocation() const
209 if (m_defaultCmd
.isEmpty()) {
216 QStringList
GdbDriver::boolOptionList() const
219 return QStringList();
222 bool GdbDriver::startup(QString cmdStr
)
224 if (!DebuggerDriver::startup(cmdStr
))
227 static const char gdbInitialize
[] =
229 * Work around buggy gdbs that do command line editing even if they
230 * are not on a tty. The readline library echos every command back
231 * in this case, which is confusing for us.
235 "set print static-members off\n"
236 "set print asm-demangle on\n"
238 * Sometimes, gdb prints [New Thread ...] during 'info threads';
239 * we will not look at thread events anyway, so turn them off.
241 "set print thread-events off\n"
243 * Don't assume that program functions invoked from a watch expression
246 "set unwindonsignal on\n"
248 * Write a short macro that prints all locals: local variables and
249 * function arguments.
251 "define kdbg__alllocals\n"
252 "info locals\n" /* local vars supersede args with same name */
253 "info args\n" /* therefore, arguments must come last */
256 * Work around a bug in gdb-6.3: "info line main" crashes gdb.
258 "define kdbg_infolinemain\n"
262 // change prompt string and synchronize with gdb
263 "set prompt " PROMPT
"\n"
266 executeCmdString(DCinitialize
, gdbInitialize
, false);
268 // assume that QString::null is ok
269 cmds
[DCprintQStringStruct
].fmt
= printQStringStructFmt
;
274 void GdbDriver::commandFinished(CmdQueueItem
* cmd
)
276 // command string must be committed
277 if (!cmd
->m_committed
) {
279 TRACE("calling " + (__PRETTY_FUNCTION__
+ (" with uncommited command:\n\t" +
284 switch (cmd
->m_cmd
) {
288 * Check for GDB 7.1 or later; the syntax for the disassemble
289 * command has changed.
290 * This RE picks the last version number in the first line,
291 * because at least OpenSUSE writes its own version number
292 * in the first line (but before GDB's version number).
295 " " // must be preceded by space
296 "[(]?" // SLES 10 embeds in parentheses
297 "(\\d+)\\.(\\d+)" // major, minor
298 "[^ ]*\\n" // no space until end of line
300 int pos
= re
.indexIn(m_output
);
301 const char* disass
= "disassemble %s %s\n";
303 int major
= re
.cap(1).toInt();
304 int minor
= re
.cap(2).toInt();
305 if (major
> 7 || (major
== 7 && minor
>= 1))
307 disass
= "disassemble %s, %s\n";
310 cmds
[DCdisassemble
].fmt
= disass
;
316 /* ok, the command is ready */
317 emit
commandReceived(cmd
, m_output
.constData());
319 switch (cmd
->m_cmd
) {
338 int GdbDriver::findPrompt(const QByteArray
& output
) const
341 * If there's a prompt string in the collected output, it must be at
344 * Note: It could nevertheless happen that a character sequence that is
345 * equal to the prompt string appears at the end of the output,
346 * although it is very, very unlikely (namely as part of a string that
347 * lingered in gdb's output buffer due to some timing/heavy load
348 * conditions for a very long time such that that buffer overflowed
349 * exactly at the end of the prompt string look-a-like).
351 int len
= output
.length();
352 if (len
>= PROMPT_LEN
&&
353 strncmp(output
.data()+len
-PROMPT_LEN
, PROMPT
, PROMPT_LEN
) == 0)
355 return len
-PROMPT_LEN
;
361 * The --fullname option makes gdb send a special normalized sequence print
362 * each time the program stops and at some other points. The sequence has
363 * the form "\032\032filename:lineno:charoffset:(beg|middle):address".
365 void GdbDriver::parseMarker(CmdQueueItem
* cmd
)
367 char* startMarker
= strstr(m_output
.data(), "\032\032");
368 if (startMarker
== 0)
371 // extract the marker
373 TRACE(QString("found marker: ") + startMarker
);
374 char* endMarker
= strchr(startMarker
, '\n');
380 // extract filename and line number
381 static QRegExp
MarkerRE(":(\\d+):\\d+:[begmidl]+:0x");
383 int lineNoStart
= MarkerRE
.indexIn(startMarker
);
384 if (lineNoStart
>= 0) {
385 int lineNo
= MarkerRE
.cap(1).toInt();
387 // get address unless there is one in cmd
388 DbgAddr address
= cmd
->m_addr
;
389 if (address
.isEmpty()) {
390 const char* addrStart
= startMarker
+ lineNoStart
+
391 MarkerRE
.matchedLength() - 2;
392 address
= QString(addrStart
).trimmed();
395 // now show the window
396 startMarker
[lineNoStart
] = '\0'; /* split off file name */
397 emit
activateFileLine(startMarker
, lineNo
-1, address
);
403 * Escapes characters that might lead to problems when they appear on gdb's
406 static void normalizeStringArg(QString
& arg
)
409 * Remove trailing backslashes. This approach is a little simplistic,
410 * but we know that there is at the moment no case where a trailing
411 * backslash would make sense.
413 while (!arg
.isEmpty() && arg
[arg
.length()-1] == '\\') {
414 arg
= arg
.left(arg
.length()-1);
419 QString
GdbDriver::makeCmdString(DbgCommand cmd
, QString strArg
)
421 assert(cmd
>= 0 && cmd
< NUM_CMDS
);
422 assert(cmds
[cmd
].argsNeeded
== GdbCmdInfo::argString
);
424 normalizeStringArg(strArg
);
427 // need the working directory when parsing the output
428 m_programWD
= strArg
;
429 } else if (cmd
== DCsetargs
&& !m_redirect
.isEmpty()) {
431 * Use saved redirection. We prepend it in front of the user's
432 * arguments so that the user can override the redirections.
434 strArg
= m_redirect
+ " " + strArg
;
438 cmdString
.sprintf(cmds
[cmd
].fmt
, strArg
.toUtf8().constData());
442 QString
GdbDriver::makeCmdString(DbgCommand cmd
, int intArg
)
444 assert(cmd
>= 0 && cmd
< NUM_CMDS
);
445 assert(cmds
[cmd
].argsNeeded
== GdbCmdInfo::argNum
);
448 cmdString
.sprintf(cmds
[cmd
].fmt
, intArg
);
452 QString
GdbDriver::makeCmdString(DbgCommand cmd
, QString strArg
, int intArg
)
454 assert(cmd
>= 0 && cmd
< NUM_CMDS
);
455 assert(cmds
[cmd
].argsNeeded
== GdbCmdInfo::argStringNum
||
456 cmds
[cmd
].argsNeeded
== GdbCmdInfo::argNumString
||
460 normalizeStringArg(strArg
);
467 * intArg specifies which channels should be redirected to
468 * /dev/null. It is a value or'ed together from RDNstdin,
469 * RDNstdout, RDNstderr. We store the value for a later DCsetargs
472 * Note: We rely on that after the DCtty a DCsetargs will follow,
473 * which will ultimately apply the redirection.
475 static const char* const runRedir
[8] = {
479 "</dev/null >/dev/null",
481 "</dev/null 2>/dev/null",
483 "</dev/null >/dev/null 2>&1"
485 if (strArg
.isEmpty())
486 intArg
= 7; /* failsafe if no tty */
487 m_redirect
= runRedir
[intArg
& 7];
489 return makeCmdString(DCtty
, strArg
); /* note: no problem if strArg empty */
492 if (cmd
== DCexamine
) {
493 // make a format specifier from the intArg
494 static const char size
[16] = {
495 '\0', 'b', 'h', 'w', 'g'
497 static const char format
[16] = {
498 '\0', 'x', 'd', 'u', 'o', 't',
499 'a', 'c', 'f', 's', 'i'
501 assert(MDTsizemask
== 0xf); /* lowest 4 bits */
502 assert(MDTformatmask
== 0xf0); /* next 4 bits */
503 int count
= 16; /* number of entities to print */
504 char sizeSpec
= size
[intArg
& MDTsizemask
];
505 char formatSpec
= format
[(intArg
& MDTformatmask
) >> 4];
506 assert(sizeSpec
!= '\0');
507 assert(formatSpec
!= '\0');
508 // adjust count such that 16 lines are printed
509 switch (intArg
& MDTformatmask
) {
510 case MDTstring
: case MDTinsn
:
511 break; /* no modification needed */
513 // all cases drop through:
514 switch (intArg
& MDTsizemask
) {
526 spec
.sprintf("/%d%c%c", count
, sizeSpec
, formatSpec
);
528 return makeCmdString(DCexamine
, spec
, strArg
);
531 if (cmds
[cmd
].argsNeeded
== GdbCmdInfo::argStringNum
)
533 // line numbers are zero-based
534 if (cmd
== DCuntil
|| cmd
== DCbreakline
||
535 cmd
== DCtbreakline
|| cmd
== DCinfoline
)
539 if (cmd
== DCinfoline
)
541 // must split off file name part
542 strArg
= QFileInfo(strArg
).fileName();
544 cmdString
.sprintf(cmds
[cmd
].fmt
, strArg
.toUtf8().constData(), intArg
);
548 cmdString
.sprintf(cmds
[cmd
].fmt
, intArg
, strArg
.toUtf8().constData());
553 QString
GdbDriver::makeCmdString(DbgCommand cmd
, QString strArg1
, QString strArg2
)
555 assert(cmd
>= 0 && cmd
< NUM_CMDS
);
556 assert(cmds
[cmd
].argsNeeded
== GdbCmdInfo::argString2
);
558 normalizeStringArg(strArg1
);
559 normalizeStringArg(strArg2
);
562 cmdString
.sprintf(cmds
[cmd
].fmt
,
563 strArg1
.toUtf8().constData(),
564 strArg2
.toUtf8().constData());
568 QString
GdbDriver::makeCmdString(DbgCommand cmd
, int intArg1
, int intArg2
)
570 assert(cmd
>= 0 && cmd
< NUM_CMDS
);
571 assert(cmds
[cmd
].argsNeeded
== GdbCmdInfo::argNum2
);
574 cmdString
.sprintf(cmds
[cmd
].fmt
, intArg1
, intArg2
);
578 CmdQueueItem
* GdbDriver::executeCmd(DbgCommand cmd
, bool clearLow
)
580 assert(cmd
>= 0 && cmd
< NUM_CMDS
);
581 assert(cmds
[cmd
].argsNeeded
== GdbCmdInfo::argNone
);
584 m_haveCoreFile
= false;
587 return executeCmdString(cmd
, cmds
[cmd
].fmt
, clearLow
);
590 CmdQueueItem
* GdbDriver::executeCmd(DbgCommand cmd
, QString strArg
,
593 return executeCmdString(cmd
, makeCmdString(cmd
, strArg
), clearLow
);
596 CmdQueueItem
* GdbDriver::executeCmd(DbgCommand cmd
, int intArg
,
600 return executeCmdString(cmd
, makeCmdString(cmd
, intArg
), clearLow
);
603 CmdQueueItem
* GdbDriver::executeCmd(DbgCommand cmd
, QString strArg
, int intArg
,
606 return executeCmdString(cmd
, makeCmdString(cmd
, strArg
, intArg
), clearLow
);
609 CmdQueueItem
* GdbDriver::executeCmd(DbgCommand cmd
, QString strArg1
, QString strArg2
,
612 return executeCmdString(cmd
, makeCmdString(cmd
, strArg1
, strArg2
), clearLow
);
615 CmdQueueItem
* GdbDriver::executeCmd(DbgCommand cmd
, int intArg1
, int intArg2
,
618 return executeCmdString(cmd
, makeCmdString(cmd
, intArg1
, intArg2
), clearLow
);
621 CmdQueueItem
* GdbDriver::queueCmd(DbgCommand cmd
, QueueMode mode
)
623 return queueCmdString(cmd
, cmds
[cmd
].fmt
, mode
);
626 CmdQueueItem
* GdbDriver::queueCmd(DbgCommand cmd
, QString strArg
,
629 return queueCmdString(cmd
, makeCmdString(cmd
, strArg
), mode
);
632 CmdQueueItem
* GdbDriver::queueCmd(DbgCommand cmd
, int intArg
,
635 return queueCmdString(cmd
, makeCmdString(cmd
, intArg
), mode
);
638 CmdQueueItem
* GdbDriver::queueCmd(DbgCommand cmd
, QString strArg
, int intArg
,
641 return queueCmdString(cmd
, makeCmdString(cmd
, strArg
, intArg
), mode
);
644 CmdQueueItem
* GdbDriver::queueCmd(DbgCommand cmd
, QString strArg1
, QString strArg2
,
647 return queueCmdString(cmd
, makeCmdString(cmd
, strArg1
, strArg2
), mode
);
650 void GdbDriver::terminate()
652 ::kill(pid(), SIGTERM
);
656 void GdbDriver::detachAndTerminate()
658 ::kill(pid(), SIGINT
);
660 executeCmdString(DCinitialize
, "detach\nquit\n", true);
663 void GdbDriver::interruptInferior()
665 ::kill(pid(), SIGINT
);
666 // remove accidentally queued commands
670 static bool isErrorExpr(const char* output
)
673 strncmp(output
, "Cannot access memory at", 23) == 0 ||
674 strncmp(output
, "Attempt to dereference a generic pointer", 40) == 0 ||
675 strncmp(output
, "Attempt to take contents of ", 28) == 0 ||
676 strncmp(output
, "Attempt to use a type name as an expression", 43) == 0 ||
677 strncmp(output
, "There is no member or method named", 34) == 0 ||
678 strncmp(output
, "A parse error in expression", 27) == 0 ||
679 strncmp(output
, "No symbol \"", 11) == 0 ||
680 strncmp(output
, "Internal error: ", 16) == 0;
684 * Returns true if the output is an error message. If wantErrorValue is
685 * true, a new ExprValue object is created and filled with the error message.
686 * If there are warnings, they are skipped and output points past the warnings
687 * on return (even if there \e are errors).
689 static bool parseErrorMessage(const char*& output
,
690 ExprValue
*& variable
, bool wantErrorValue
)
692 while (isspace(*output
))
696 while (strncmp(output
, "warning:", 8) == 0)
698 const char* end
= strchr(output
+8, '\n');
700 output
+= strlen(output
);
703 while (isspace(*output
))
707 if (isErrorExpr(output
))
709 if (wantErrorValue
) {
710 // put the error message as value in the variable
711 variable
= new ExprValue(QString(), VarTree::NKplain
);
712 const char* endMsg
= strchr(output
, '\n');
714 endMsg
= output
+ strlen(output
);
715 variable
->m_value
= QString::fromLatin1(output
, endMsg
-output
);
724 #if QT_VERSION >= 300
734 void GdbDriver::setPrintQStringDataCmd(const char* cmd
)
736 // don't accept the command if it is empty
737 if (cmd
== 0 || *cmd
== '\0')
739 assert(strlen(cmd
) <= MAX_FMTLEN
);
740 cmds
[DCprintQStringStruct
].fmt
= cmd
;
743 ExprValue
* GdbDriver::parseQCharArray(const char* output
, bool wantErrorValue
, bool qt3like
)
745 ExprValue
* variable
= 0;
748 * Parse off white space. gdb sometimes prints white space first if the
749 * printed array leaded to an error.
751 while (isspace(*output
))
754 // special case: empty string (0 repetitions)
755 if (strncmp(output
, "Invalid number 0 of repetitions", 31) == 0)
757 variable
= new ExprValue(QString(), VarTree::NKplain
);
758 variable
->m_value
= "\"\"";
762 // check for error conditions
763 if (parseErrorMessage(output
, variable
, wantErrorValue
))
769 const char* p
= output
;
777 } while (isspace(*p
));
781 // this is the real data
787 enum { wasNothing
, wasChar
, wasRepeat
} lastThing
= wasNothing
;
789 * A matrix for separators between the individual "things"
790 * that are added to the string. The first index is a bool,
791 * the second index is from the enum above.
793 static const char* separator
[2][3] = {
794 { "\"", 0, ", \"" }, /* normal char is added */
795 { "'", "\", '", ", '" } /* repeated char is added */
798 while (isdigit(*p
)) {
801 unsigned short value
= (unsigned short) strtoul(p
, &end
, 0);
803 goto error
; /* huh? no valid digits */
804 // skip separator and search for a repeat count
806 while (isspace(*p
) || *p
== ',')
808 bool repeats
= strncmp(p
, "<repeats ", 9) == 0;
810 const char* start
= p
;
811 p
= strchr(p
+9, '>'); /* search end and advance */
815 repeatCount
= QString::fromLatin1(start
, p
-start
);
816 while (isspace(*p
) || *p
== ',')
819 // p is now at the next char (or the end)
821 // interpret the value as a QChar
822 // TODO: make cross-architecture compatible
828 (unsigned short&)ch
= value
;
832 ch
.setRow(c
.qch
.row
);
833 ch
.setCell(c
.qch
.cell
);
837 // escape a few frequently used characters
838 char escapeCode
= '\0';
839 switch (ch
.toLatin1()) {
840 case '\n': escapeCode
= 'n'; break;
841 case '\r': escapeCode
= 'r'; break;
842 case '\t': escapeCode
= 't'; break;
843 case '\b': escapeCode
= 'b'; break;
844 case '\"': escapeCode
= '\"'; break;
845 case '\\': escapeCode
= '\\'; break;
846 case '\0': if (value
== 0) { escapeCode
= '0'; } break;
850 result
+= separator
[repeats
][lastThing
];
852 if (escapeCode
!= '\0') {
858 // fixup repeat count and lastThing
861 result
+= repeatCount
;
862 lastThing
= wasRepeat
;
871 if (lastThing
== wasChar
)
875 variable
= new ExprValue(QString(), VarTree::NKplain
);
876 variable
->m_value
= result
;
878 else if (strncmp(p
, "true", 4) == 0)
880 variable
= new ExprValue(QString(), VarTree::NKplain
);
881 variable
->m_value
= "QString::null";
883 else if (strncmp(p
, "false", 5) == 0)
885 variable
= new ExprValue(QString(), VarTree::NKplain
);
886 variable
->m_value
= "(null)";
893 if (wantErrorValue
) {
894 variable
= new ExprValue(QString(), VarTree::NKplain
);
895 variable
->m_value
= "internal parse error";
900 static ExprValue
* parseVar(const char*& s
)
909 VarTree::NameKind kind
;
911 * Detect anonymouse struct values: The 'name =' part is missing:
912 * s = { a = 1, { b = 2 }}
913 * Note that this detection works only inside structs when the anonymous
914 * struct is not the first member:
915 * s = {{ a = 1 }, b = 2}
916 * This is misparsed (by parseNested()) because it is mistakenly
917 * interprets the second opening brace as the first element of an array
922 name
= i18n("<anonymous struct or union>");
923 kind
= VarTree::NKanonymous
;
927 if (!parseName(p
, name
, kind
)) {
935 TRACE("parse error: = not found after " + name
);
938 // skip the '=' and more whitespace
944 ExprValue
* variable
= new ExprValue(name
, kind
);
946 if (!parseValue(p
, variable
)) {
954 static void skipNested(const char*& s
, char opening
, char closing
)
958 // parse a nested type
962 * Search for next matching `closing' char, skipping nested pairs of
963 * `opening' and `closing'.
965 while (*p
&& nest
> 0) {
968 } else if (*p
== closing
) {
974 TRACE(QString().sprintf("parse error: mismatching %c%c at %-20.20s", opening
, closing
, s
));
980 * This function skips text that is delimited by nested angle bracktes, '<>'.
981 * A complication arises because the delimited text can contain the names of
982 * operator<<, operator>>, operator<, and operator>, which have to be treated
983 * specially so that they do not count towards the nesting of '<>'.
984 * This function assumes that the delimited text does not contain strings.
986 static void skipNestedAngles(const char*& s
)
991 p
++; // skip the initial '<'
992 while (*p
&& nest
> 0)
994 // Below we can check for p-s >= 9 instead of 8 because
995 // *s is '<' and cannot be part of "operator".
998 if (p
-s
>= 9 && strncmp(p
-8, "operator", 8) == 0) {
1007 if (p
-s
>= 9 && strncmp(p
-8, "operator", 8) == 0) {
1017 TRACE(QString().sprintf("parse error: mismatching <> at %-20.20s", s
));
1023 * Find the end of line that is not inside braces
1025 static void findEnd(const char*& s
)
1028 while (*p
&& *p
!='\n') {
1029 while (*p
&& *p
!='\n' && *p
!='{')
1033 skipNested(p
, '{', '}'); p
--;
1039 static bool isNumberish(const char ch
)
1041 return (ch
>='0' && ch
<='9') || ch
=='.' || ch
=='x';
1044 void skipString(const char*& p
)
1046 // wchar_t strings begin with L
1053 while (*p
!= quote
) {
1055 // skip escaped character
1056 // no special treatment for octal values necessary
1059 // simply return if no more characters
1067 * Strings can consist of several parts, some of which contain repeated
1070 if (quote
== '\'') {
1071 // look ahaead for <repeats 123 times>
1072 const char* q
= p
+1;
1075 if (strncmp(q
, "<repeats ", 9) == 0) {
1077 while (*p
!= '\0' && *p
!= '>')
1080 p
++; /* skip the '>' */
1084 // Is the string continued? If so, there is no L in wchar_t strings
1087 // look ahead for another quote
1088 const char* q
= p
+1;
1091 if (*q
== '"' || *q
== '\'') {
1097 // some strings can end in <incomplete sequence ...>
1098 if (strncmp(q
, "<incomplete sequence", 20) == 0)
1101 while (*p
!= '\0' && *p
!= '>')
1104 p
++; /* skip the '>' */
1109 * There's a bug in gdb where it prints the beginning of the string
1110 * continuation and the comma-blank in the wrong order if the new string
1111 * begins with an incomplete multi-byte character. For now, let's check
1112 * for this in a very narrow condition, particularly, where the next
1113 * character is given in octal notation. Example:
1114 * 'a' <repeats 20 times>"\240, b"
1116 if (*p
== '"' && p
[1] == '\\' && isdigit(p
[2])) {
1118 while (isdigit(p
[i
]))
1120 if (p
[i
] == ',' && p
[i
+1] == ' ') {
1121 // just treat everything beginning at the dquote as string
1125 /* very long strings are followed by `...' */
1126 if (*p
== '.' && p
[1] == '.' && p
[2] == '.') {
1131 static void skipNestedWithString(const char*& s
, char opening
, char closing
)
1135 // parse a nested expression
1139 * Search for next matching `closing' char, skipping nested pairs of
1140 * `opening' and `closing' as well as strings.
1142 while (*p
&& nest
> 0) {
1143 if (*p
== opening
) {
1145 } else if (*p
== closing
) {
1147 } else if (*p
== '\'' || *p
== '\"') {
1154 TRACE(QString().sprintf("parse error: mismatching %c%c at %-20.20s", opening
, closing
, s
));
1159 inline void skipName(const char*& p
)
1161 // allow : (for enumeration values) and $ and . (for _vtbl.)
1162 while (isalnum(*p
) || *p
== '_' || *p
== ':' || *p
== '$' || *p
== '.')
1166 static bool parseName(const char*& s
, QString
& name
, VarTree::NameKind
& kind
)
1168 kind
= VarTree::NKplain
;
1171 // examples of names:
1174 // <string<a,b<c>,7> >
1177 skipNestedAngles(p
);
1178 name
= QString::fromLatin1(s
, p
- s
);
1179 kind
= VarTree::NKtype
;
1183 // name, which might be "static"; allow dot for "_vtbl."
1186 TRACE(QString().sprintf("parse error: not a name %-20.20s", s
));
1190 if (len
== 6 && strncmp(s
, "static", 6) == 0) {
1191 kind
= VarTree::NKstatic
;
1193 // its a static variable, name comes now
1199 TRACE(QString().sprintf("parse error: not a name after static %-20.20s", s
));
1204 name
= QString::fromLatin1(s
, len
);
1206 // return the new position
1211 static bool parseValue(const char*& s
, ExprValue
* variable
)
1213 variable
->m_value
= "";
1217 // Sometimes we find the following output:
1218 // {<text variable, no debug info>} 0x40012000 <access>
1219 // {<data variable, no debug info>}
1220 // {<variable (not text or data), no debug info>}
1221 if (strncmp(s
, "{<text variable, ", 17) == 0 ||
1222 strncmp(s
, "{<data variable, ", 17) == 0 ||
1223 strncmp(s
, "{<variable (not text or data), ", 31) == 0)
1225 const char* start
= s
;
1226 skipNested(s
, '{', '}');
1227 variable
->m_value
= QString::fromLatin1(start
, s
-start
);
1228 variable
->m_value
+= ' '; // add only a single space
1236 if (!parseNested(s
, variable
)) {
1239 // must be the closing brace
1241 TRACE("parse error: missing } of " + variable
->m_name
);
1245 // final white space
1250 // Sometimes we find a warning; it ends at the next LF
1251 else if (strncmp(s
, "warning: ", 9) == 0) {
1252 const char* end
= strchr(s
, '\n');
1253 s
= end
? end
: s
+strlen(s
);
1254 // skip space at start of next line
1259 // examples of leaf values (cannot be the empty string):
1265 // (DwContentType&) @0x8123456: {...}
1269 // 0x823abc <Array<int> virtual table>
1270 // 0x40240f <globarstr> "test"
1271 // (void (*)()) 0x8048480 <f(E *, char)>
1274 // &parseP (HTMLClueV *, char *)
1275 // Variable "x" is not available.
1276 // The value of variable 'x' is distributed...
1277 // -nan(0xfffff081defa0)
1284 skipNested(p
, '(', ')');
1288 variable
->m_value
= QString::fromLatin1(s
, p
- s
);
1291 bool reference
= false;
1293 // skip reference marker
1297 const char* start
= p
;
1301 // some values consist of more than one token
1302 bool checkMultiPart
= false;
1304 if (p
[0] == '0' && p
[1] == 'x') {
1307 while (isxdigit(*p
))
1311 * Assume this is a pointer, but only if it's not a reference, since
1312 * references can't be expanded.
1315 variable
->m_varKind
= VarTree::VKpointer
;
1318 * References are followed by a colon, in which case we'll
1319 * find the value following the reference address.
1324 // Paranoia. (Can this happen, i.e. reference not followed by ':'?)
1328 checkMultiPart
= true;
1329 } else if (isdigit(*p
)) {
1330 // parse decimal number, possibly a float
1333 if (*p
== '.') { /* TODO: obey i18n? */
1334 // In long arrays an integer may be followed by '...'.
1335 // We test for this situation and don't gobble the '...'.
1336 if (p
[1] != '.' || p
[0] != '.') {
1343 if (*p
== 'e' || *p
== 'E') {
1346 if (*p
== '-' || *p
== '+')
1352 // for char variables there is the char, eg. 10 '\n'
1353 checkMultiPart
= true;
1354 } else if (*p
== '<') {
1355 // e.g. <optimized out>
1356 skipNestedAngles(p
);
1357 } else if (*p
== '"' || *p
== '\'') {
1358 // character may have multipart: '\000' <repeats 11 times>
1359 checkMultiPart
= *p
== '\'';
1362 } else if (*p
== 'L' && (p
[1] == '"' || p
[1] == '\'')) {
1363 // ditto for wchar_t strings
1364 checkMultiPart
= p
[1] == '\'';
1366 } else if (*p
== '&') {
1370 while (isspace(*p
)) {
1374 skipNested(p
, '(', ')');
1376 } else if (strncmp(p
, "Variable \"", 10) == 0) {
1377 // Variable "x" is not available.
1378 p
+= 10; // skip to "
1380 if (strncmp(p
, "\" is not available.", 19) == 0) {
1383 } else if (strncmp(p
, "The value of variable '", 23) == 0) {
1386 const char* e
= strchr(p
, '.');
1394 // must be an enumeration value
1396 // nan (floating point Not a Number) is followed by a number in ()
1397 // enum values can look like A::(anonymous namespace)::blue
1399 bool isAnonNS
= strncmp(p
+1, "anonymous namespace)", 20) == 0;
1400 skipNested(p
, '(', ')');
1405 variable
->m_value
+= QString::fromLatin1(start
, p
- start
);
1407 // remove line breaks from the value; this is ok since
1408 // string values never contain a literal line break
1409 variable
->m_value
.replace('\n', ' ');
1411 while (checkMultiPart
) {
1415 // may be followed by a string or <...>
1416 // if this was a pointer with a string,
1417 // reset that pointer flag since we have now a value
1419 checkMultiPart
= false;
1421 if (*p
== '"' || *p
== '\'') {
1423 variable
->m_varKind
= VarTree::VKsimple
;
1424 } else if (*p
== 'L' && (p
[1] == '"' || p
[1] == '\'')) {
1425 skipString(p
); // wchar_t string
1426 variable
->m_varKind
= VarTree::VKsimple
;
1427 } else if (*p
== '<') {
1428 // if this value is part of an array, it might be followed
1429 // by <repeats 15 times>, which we don't skip here
1430 if (strncmp(p
, "<repeats ", 9) != 0) {
1431 skipNestedAngles(p
);
1432 checkMultiPart
= true;
1436 // there is always a blank before the string,
1437 // which we will include in the final string value
1438 variable
->m_value
+= QString::fromLatin1(start
-1, (p
- start
)+1);
1442 if (variable
->m_value
.length() == 0) {
1443 TRACE("parse error: no value for " + variable
->m_name
);
1447 // final white space
1453 * If this was a reference, the value follows. It might even be a
1454 * composite variable!
1464 static bool parseNested(const char*& s
, ExprValue
* variable
)
1466 // could be a structure or an array
1471 bool isStruct
= false;
1473 * If there is a name followed by an = or an < -- which starts a type
1474 * name -- or "static", it is a structure
1476 if (*p
== '<' || *p
== '}') {
1478 } else if (strncmp(p
, "static ", 7) == 0) {
1480 } else if (isalpha(*p
) || *p
== '_' || *p
== '$') {
1481 // look ahead for a comma after the name
1488 p
= s
; /* rescan the name */
1491 if (!parseVarSeq(p
, variable
)) {
1494 variable
->m_varKind
= VarTree::VKstruct
;
1496 if (!parseValueSeq(p
, variable
)) {
1499 variable
->m_varKind
= VarTree::VKarray
;
1505 static bool parseVarSeq(const char*& s
, ExprValue
* variable
)
1507 // parse a comma-separated sequence of variables
1508 ExprValue
* var
= variable
; /* var != 0 to indicate success if empty seq */
1512 if (strncmp(s
, "<No data fields>}", 17) == 0)
1514 // no member variables, so break out immediately
1515 s
+= 16; /* go to the closing brace */
1520 break; /* syntax error */
1521 variable
->appendChild(var
);
1524 // skip the comma and whitespace
1532 static bool parseValueSeq(const char*& s
, ExprValue
* variable
)
1534 // parse a comma-separated sequence of variables
1539 name
.sprintf("[%d]", index
);
1540 ExprValue
* var
= new ExprValue(name
, VarTree::NKplain
);
1541 good
= parseValue(s
, var
);
1546 // a value may be followed by "<repeats 45 times>"
1547 if (strncmp(s
, "<repeats ", 9) == 0) {
1550 int l
= strtol(s
, &end
, 10);
1551 if (end
== s
|| strncmp(end
, " times>", 7) != 0) {
1552 // should not happen
1556 TRACE(QString().sprintf("found <repeats %d times> in array", l
));
1557 // replace name and advance index
1558 name
.sprintf("[%d .. %d]", index
, index
+l
-1);
1561 // skip " times>" and space
1563 // possible final space
1569 variable
->appendChild(var
);
1570 // long arrays may be terminated by '...'
1571 if (strncmp(s
, "...", 3) == 0) {
1573 ExprValue
* var
= new ExprValue("...", VarTree::NKplain
);
1574 var
->m_value
= i18n("<additional entries of the array suppressed>");
1575 variable
->appendChild(var
);
1581 // skip the comma and whitespace
1585 // sometimes there is a closing brace after a comma
1593 * Parses a stack frame.
1595 static void parseFrameInfo(const char*& s
, QString
& func
,
1596 QString
& file
, int& lineNo
, DbgAddr
& address
)
1600 // next may be a hexadecimal address
1602 const char* start
= p
;
1606 while (isxdigit(*p
))
1608 address
= QString::fromLatin1(start
, p
-start
);
1609 if (strncmp(p
, " in ", 4) == 0)
1612 address
= DbgAddr();
1614 const char* start
= p
;
1615 // check for special signal handler frame
1616 if (strncmp(p
, "<signal handler called>", 23) == 0) {
1617 func
= QString::fromLatin1(start
, 23);
1627 * Skip the function name. It is terminated by a left parenthesis
1628 * which does not delimit "(anonymous namespace)" and which is
1629 * outside the angle brackets <> of template parameter lists
1630 * and is preceded by a space.
1635 // check for operator<< and operator<
1636 if (p
-start
>= 8 && strncmp(p
-8, "operator", 8) == 0)
1644 // skip template parameter list
1645 skipNestedAngles(p
);
1647 } else if (*p
== '(') {
1648 // this skips "(anonymous namespace)" as well as the formal
1649 // parameter list of the containing function if this is a member
1650 // of a nested class
1651 skipNestedWithString(p
, '(', ')');
1652 } else if (*p
== ' ') {
1655 break; // parameter list found
1669 * Skip parameters. But notice that for complicated conversion
1670 * functions (eg. "operator int(**)()()", ie. convert to pointer to
1671 * pointer to function) as well as operator()(...) we have to skip
1672 * additional pairs of parentheses. Furthermore, recent gdbs write the
1673 * demangled name followed by the arguments in a pair of parentheses,
1674 * where the demangled name can end in "const".
1677 skipNestedWithString(p
, '(', ')');
1681 if (strncmp(p
, "const", 5) == 0) {
1686 } while (*p
== '(');
1688 // check for file position
1689 if (strncmp(p
, "at ", 3) == 0) {
1691 const char* fileStart
= p
;
1692 // go for the end of the line
1693 while (*p
!= '\0' && *p
!= '\n')
1695 // search back for colon
1696 const char* colon
= p
;
1699 } while (*colon
!= ':');
1700 file
= QString::fromLatin1(fileStart
, colon
-fileStart
);
1701 lineNo
= atoi(colon
+1)-1;
1706 // check for "from shared lib"
1707 if (strncmp(p
, "from ", 5) == 0) {
1709 // go for the end of the line
1710 while (*p
!= '\0' && *p
!= '\n')
1719 // construct the function name (including file info)
1723 func
= QString::fromLatin1(start
, p
-start
-1); /* don't include \n */
1728 * Replace \n (and whitespace around it) in func by a blank. We cannot
1729 * use QString::simplified() for this because this would also
1730 * simplify space that belongs to a string arguments that gdb sometimes
1731 * prints in the argument lists of the function.
1733 ASSERT(!isspace(func
[0].toLatin1())); // there must be non-white before first \n
1735 while ((nl
= func
.indexOf('\n', nl
)) >= 0) {
1736 // search back to the beginning of the whitespace
1737 int startWhite
= nl
;
1740 } while (isspace(func
[startWhite
].toLatin1()));
1742 // search forward to the end of the whitespace
1745 } while (isspace(func
[nl
].toLatin1()));
1747 func
.replace(startWhite
, nl
-startWhite
, " ");
1748 /* continue searching for more \n's at this place: */
1755 * Parses a stack frame including its frame number
1757 static bool parseFrame(const char*& s
, int& frameNo
, QString
& func
,
1758 QString
& file
, int& lineNo
, DbgAddr
& address
)
1761 // #1 0x8048881 in Dl::Dl (this=0xbffff418, r=3214) at testfile.cpp:72
1762 // Breakpoint 3, Cl::f(int) const (this=0xbffff3c0, x=17) at testfile.cpp:155
1764 // must start with a hash mark followed by number
1765 // or with "Breakpoint " followed by number and comma
1769 s
++; /* skip the hash mark */
1770 } else if (strncmp(s
, "Breakpoint ", 11) == 0) {
1771 if (!isdigit(s
[11]))
1773 s
+= 11; /* skip "Breakpoint" */
1782 while (isspace(*s
) || *s
== ',')
1784 parseFrameInfo(s
, func
, file
, lineNo
, address
);
1788 void GdbDriver::parseBackTrace(const char* output
, std::list
<StackFrame
>& stack
)
1791 int lineNo
, frameNo
;
1794 while (::parseFrame(output
, frameNo
, func
, file
, lineNo
, address
)) {
1795 stack
.push_back(StackFrame());
1796 StackFrame
* frm
= &stack
.back();
1797 frm
->frameNo
= frameNo
;
1798 frm
->fileName
= file
;
1799 frm
->lineNo
= lineNo
;
1800 frm
->address
= address
;
1801 frm
->var
= new ExprValue(func
, VarTree::NKplain
);
1805 bool GdbDriver::parseFrameChange(const char* output
, int& frameNo
,
1806 QString
& file
, int& lineNo
, DbgAddr
& address
)
1809 return ::parseFrame(output
, frameNo
, func
, file
, lineNo
, address
);
1813 bool GdbDriver::parseBreakList(const char* output
, std::list
<Breakpoint
>& brks
)
1815 // skip first line, which is the headline
1816 const char* p
= strchr(output
, '\n');
1826 while (*p
!= '\0') {
1829 bp
.id
= strtol(p
, &dummy
, 10); /* don't care about overflows */
1831 // check for continued <MULTIPLE> breakpoint
1832 if (*p
== '.' && isdigit(p
[1]))
1834 // continuation: skip type and disposition
1841 if (strncmp(p
, "breakpoint", 10) == 0) {
1843 } else if (strncmp(p
, "hw watchpoint", 13) == 0) {
1844 bp
.type
= Breakpoint::watchpoint
;
1846 } else if (strncmp(p
, "watchpoint", 10) == 0) {
1847 bp
.type
= Breakpoint::watchpoint
;
1855 bp
.temporary
= *p
++ == 'd';
1857 while (*p
!= '\0' && !isspace(*p
)) /* "keep" or "del" */
1864 bp
.enabled
= *p
++ == 'y';
1865 while (*p
!= '\0' && !isspace(*p
)) /* "y" or "n" */
1871 // the address, if present
1872 if (bp
.type
== Breakpoint::breakpoint
&&
1873 strncmp(p
, "0x", 2) == 0)
1875 const char* start
= p
;
1876 while (*p
!= '\0' && !isspace(*p
))
1878 bp
.address
= QString::fromLatin1(start
, p
-start
);
1879 while (isspace(*p
) && *p
!= '\n')
1884 // remainder is location, hit and ignore count, condition
1885 end
= strchr(p
, '\n');
1888 p
+= bp
.location
.length();
1890 // location of a <MULTIPLE> filled in from subsequent breakpoints
1891 if (strncmp(p
, "<MULTIPLE>", 10) != 0)
1892 bp
.location
= QString::fromLatin1(p
, end
-p
).trimmed();
1893 p
= end
+1; /* skip over \n */
1896 // may be continued in next line
1897 while (isspace(*p
)) { /* p points to beginning of line */
1898 // skip white space at beginning of line
1903 end
= strchr(p
, '\n');
1907 if (strncmp(p
, "breakpoint already hit", 22) == 0) {
1908 // extract the hit count
1910 bp
.hitCount
= strtol(p
, &dummy
, 10);
1911 TRACE(QString("hit count %1").arg(bp
.hitCount
));
1912 } else if (strncmp(p
, "stop only if ", 13) == 0) {
1913 // extract condition
1915 bp
.condition
= QString::fromLatin1(p
, end
-p
).trimmed();
1916 TRACE("condition: "+bp
.condition
);
1917 } else if (strncmp(p
, "ignore next ", 12) == 0) {
1918 // extract ignore count
1920 bp
.ignoreCount
= strtol(p
, &dummy
, 10);
1921 TRACE(QString("ignore count %1").arg(bp
.ignoreCount
));
1923 // indeed a continuation
1924 bp
.location
+= " " + QString::fromLatin1(p
, end
-p
).trimmed();
1928 p
++; /* skip '\n' */
1931 if (brks
.empty() || brks
.back().id
!= bp
.id
) {
1934 // this is a continuation; fill in location if not yet set
1935 // otherwise, drop this breakpoint
1936 Breakpoint
& mbp
= brks
.back();
1937 if (mbp
.location
.isEmpty() && !bp
.location
.isEmpty()) {
1938 mbp
.location
= bp
.location
;
1939 mbp
.address
= bp
.address
;
1940 } else if (mbp
.address
.isEmpty() && !bp
.address
.isEmpty()) {
1941 mbp
.address
= bp
.address
;
1948 std::list
<ThreadInfo
> GdbDriver::parseThreadList(const char* output
)
1950 std::list
<ThreadInfo
> threads
;
1951 if (strcmp(output
, "\n") == 0 ||
1952 strncmp(output
, "No stack.", 9) == 0 ||
1953 strncmp(output
, "No threads.", 11) == 0) {
1958 bool newFormat
= false;
1959 const char* p
= output
;
1960 while (*p
!= '\0') {
1962 // seach look for thread id, watching out for the focus indicator
1963 thr
.hasFocus
= false;
1964 while (isspace(*p
)) /* may be \n from prev line: see "No stack" below */
1967 // recent GDBs write a header line; skip it
1968 if (threads
.empty() && strncmp(p
, "Id Target", 11) == 0) {
1969 p
= strchr(p
, '\n');
1973 continue; // next line please, '\n' is skipped above
1977 thr
.hasFocus
= true;
1979 // there follows only whitespace
1982 char *temp_end
= NULL
; /* we need a non-const 'end' for strtol to use...*/
1983 thr
.id
= strtol(p
, &temp_end
, 10);
1986 // syntax error: no number found; bail out
1996 * Now follows the thread's SYSTAG.
1999 // In the old format, it is terminated by two blanks.
2000 end
= strstr(p
, " ");
2002 // syntax error; bail out
2007 // In the new format lies crazyness: there is no definitive
2008 // end marker. At best we can guess when the SYSTAG ends.
2009 // A typical thread list on Linux looks like this:
2011 // Id Target Id Frame
2012 // 2 Thread 0x7ffff7854700 (LWP 10827) "thrserver" 0x00007ffff7928631 in clone () from /lib64/libc.so.6
2013 // * 1 Thread 0x7ffff7fcc700 (LWP 10808) "thrserver" main () at thrserver.c:84
2015 // Looking at GDB's code, the Target Id ends in tokens that
2016 // are bracketed by parentheses or quotes. Therefore,
2017 // we skip (at most) two tokens ('Thread' and the address),
2018 // and then all parts that are in parentheses or quotes.
2025 } else if (*end
== '(') {
2026 skipNested(end
, '(', ')');
2029 while (*end
&& !isspace(*end
))
2035 while (isspace(*end
))
2039 thr
.threadName
= QString::fromLatin1(p
, end
-p
).trimmed();
2043 * Now follows a standard stack frame. Sometimes, however, gdb
2044 * catches a thread at an instant where it doesn't have a stack.
2046 if (strncmp(p
, "[No stack.]", 11) != 0) {
2047 ::parseFrameInfo(p
, thr
.function
, thr
.fileName
, thr
.lineNo
, thr
.address
);
2049 thr
.function
= "[No stack]";
2051 p
+= 11; /* \n is skipped above */
2054 threads
.push_back(thr
);
2059 static bool parseNewBreakpoint(const char* o
, int& id
,
2060 QString
& file
, int& lineNo
, QString
& address
);
2061 static bool parseNewWatchpoint(const char* o
, int& id
,
2064 bool GdbDriver::parseBreakpoint(const char* output
, int& id
,
2065 QString
& file
, int& lineNo
, QString
& address
)
2067 // skip lines of that begin with "(Cannot find"
2068 while (strncmp(output
, "(Cannot find", 12) == 0 ||
2069 strncmp(output
, "Note: breakpoint", 16) == 0)
2071 output
= strchr(output
, '\n');
2074 output
++; /* skip newline */
2077 if (strncmp(output
, "Breakpoint ", 11) == 0) {
2078 output
+= 11; /* skip "Breakpoint " */
2079 return ::parseNewBreakpoint(output
, id
, file
, lineNo
, address
);
2080 } else if (strncmp(output
, "Temporary breakpoint ", 21) == 0) {
2082 return ::parseNewBreakpoint(output
, id
, file
, lineNo
, address
);
2083 } else if (strncmp(output
, "Hardware watchpoint ", 20) == 0) {
2085 return ::parseNewWatchpoint(output
, id
, address
);
2086 } else if (strncmp(output
, "Watchpoint ", 11) == 0) {
2088 return ::parseNewWatchpoint(output
, id
, address
);
2093 static bool parseNewBreakpoint(const char* o
, int& id
,
2094 QString
& file
, int& lineNo
, QString
& address
)
2098 id
= strtoul(o
, &p
, 10);
2102 // check for the address
2103 if (strncmp(p
, " at 0x", 6) == 0) {
2104 char* start
= p
+4; /* skip " at ", but not 0x */
2106 while (isxdigit(*p
))
2108 address
= QString::fromLatin1(start
, p
-start
);
2112 * Mostly, GDB responds with this syntax:
2114 * Breakpoint 1 at 0x400b94: file multibrkpt.cpp, line 9. (2 locations)
2116 * but sometimes it uses this syntax:
2118 * Breakpoint 4 at 0x804f158: lotto739.cpp:95. (3 locations)
2120 char* fileEnd
, *numStart
= 0;
2121 char* fileStart
= strstr(p
, "file ");
2125 fileEnd
= strstr(fileStart
, ", line ");
2127 numStart
= fileEnd
+ 7;
2129 if (numStart
== 0 && p
[0] == ':' && p
[1] == ' ')
2132 while (isspace(*fileStart
))
2134 fileEnd
= strchr(fileStart
, ':');
2136 numStart
= fileEnd
+ 1;
2139 return !address
.isEmpty(); /* parse error only if there's no address */
2141 QString fileName
= QString::fromLatin1(fileStart
, fileEnd
-fileStart
);
2142 int line
= strtoul(numStart
, &p
, 10);
2147 lineNo
= line
-1; /* zero-based! */
2151 static bool parseNewWatchpoint(const char* o
, int& id
,
2156 id
= strtoul(o
, &p
, 10);
2160 if (strncmp(p
, ": ", 2) != 0)
2164 // all the rest on the line is the expression
2165 expr
= QString::fromLatin1(p
, strlen(p
)).trimmed();
2169 void GdbDriver::parseLocals(const char* output
, std::list
<ExprValue
*>& newVars
)
2171 // check for possible error conditions
2172 if (strncmp(output
, "No symbol table", 15) == 0)
2177 while (*output
!= '\0') {
2178 while (isspace(*output
))
2180 if (*output
== '\0')
2182 // skip occurrences of "No locals" and "No args"
2183 if (strncmp(output
, "No locals", 9) == 0 ||
2184 strncmp(output
, "No arguments", 12) == 0)
2186 output
= strchr(output
, '\n');
2193 ExprValue
* variable
= parseVar(output
);
2194 if (variable
== 0) {
2197 // do not add duplicates
2198 for (std::list
<ExprValue
*>::iterator o
= newVars
.begin(); o
!= newVars
.end(); ++o
) {
2199 if ((*o
)->m_name
== variable
->m_name
) {
2204 newVars
.push_back(variable
);
2209 ExprValue
* GdbDriver::parsePrintExpr(const char* output
, bool wantErrorValue
)
2212 // check for error conditions
2213 if (!parseErrorMessage(output
, var
, wantErrorValue
))
2215 // parse the variable
2216 var
= parseVar(output
);
2221 bool GdbDriver::parseChangeWD(const char* output
, QString
& message
)
2223 bool isGood
= false;
2224 message
= QString(output
).simplified();
2225 if (message
.isEmpty()) {
2226 message
= i18n("New working directory: ") + m_programWD
;
2232 bool GdbDriver::parseChangeExecutable(const char* output
, QString
& message
)
2236 m_haveCoreFile
= false;
2239 * Lines starting with the following do not indicate errors:
2240 * Using host libthread_db
2241 * (no debugging symbols found)
2242 * Reading symbols from
2244 while (strncmp(output
, "Reading symbols from", 20) == 0 ||
2245 strncmp(output
, "done.", 5) == 0 ||
2246 strncmp(output
, "Missing separate debuginfo", 26) == 0 ||
2247 strncmp(output
, "Try: ", 5) == 0 ||
2248 strncmp(output
, "Using host libthread_db", 23) == 0 ||
2249 strncmp(output
, "(no debugging symbols found)", 28) == 0)
2251 // this line is good, go to the next one
2252 const char* end
= strchr(output
, '\n');
2254 output
+= strlen(output
);
2260 * If we've parsed all lines, there was no error.
2262 return output
[0] == '\0';
2265 bool GdbDriver::parseCoreFile(const char* output
)
2267 // if command succeeded, gdb emits a line starting with "#0 "
2268 m_haveCoreFile
= strstr(output
, "\n#0 ") != 0;
2269 return m_haveCoreFile
;
2272 uint
GdbDriver::parseProgramStopped(const char* output
, QString
& message
)
2274 // optionally: "program changed, rereading symbols",
2276 // "Program exited normally"
2277 // "Program terminated with wignal SIGSEGV"
2278 // "Program received signal SIGINT" or other signal
2280 // GDB since 7.3 prints
2281 // "[Inferior 1 (process 13400) exited normally]"
2282 // "[Inferior 1 (process 14698) exited with code 01]"
2284 // go through the output, line by line, checking what we have
2285 const char* start
= output
- 1;
2286 uint flags
= SFprogramActive
;
2287 message
= QString();
2289 start
++; /* skip '\n' */
2291 if (strncmp(start
, "Program ", 8) == 0 ||
2292 strncmp(start
, "ptrace: ", 8) == 0) {
2294 * When we receive a signal, the program remains active.
2296 * Special: If we "stopped" in a corefile, the string "Program
2297 * terminated with signal"... is displayed. (Normally, we see
2298 * "Program received signal"... when a signal happens.)
2300 if (strncmp(start
, "Program exited", 14) == 0 ||
2301 (strncmp(start
, "Program terminated", 18) == 0 && !m_haveCoreFile
) ||
2302 strncmp(start
, "ptrace: ", 8) == 0)
2304 flags
&= ~SFprogramActive
;
2308 const char* endOfMessage
= strchr(start
, '\n');
2309 if (endOfMessage
== 0)
2310 endOfMessage
= start
+ strlen(start
);
2311 message
= QString::fromLatin1(start
, endOfMessage
-start
);
2312 } else if (strncmp(start
, "[Inferior ", 10) == 0) {
2313 const char* p
= start
+ 10;
2314 // skip number and space
2315 while (*p
&& !isspace(*p
))
2320 skipNested(p
, '(', ')');
2321 if (strncmp(p
, " exited ", 8) == 0) {
2322 flags
&= ~SFprogramActive
;
2325 const char* end
= strchr(p
, '\n');
2327 end
= p
+ strlen(p
);
2328 // strip [] from the message
2329 message
= QString::fromLatin1(start
+1, end
-start
-2);
2332 } else if (strncmp(start
, "Breakpoint ", 11) == 0) {
2334 * We stopped at a (permanent) breakpoint (gdb doesn't tell us
2335 * that it stopped at a temporary breakpoint).
2337 flags
|= SFrefreshBreak
;
2338 } else if (strstr(start
, "re-reading symbols.") != 0) {
2339 flags
|= SFrefreshSource
;
2342 // next line, please
2343 start
= strchr(start
, '\n');
2344 } while (start
!= 0);
2347 * Gdb only notices when new threads have appeared, but not when a
2348 * thread finishes. So we always have to assume that the list of
2349 * threads has changed.
2351 flags
|= SFrefreshThreads
;
2356 QStringList
GdbDriver::parseSharedLibs(const char* output
)
2359 if (strncmp(output
, "No shared libraries loaded", 26) == 0)
2362 // parse the table of shared libraries
2364 // strip off head line
2365 output
= strchr(output
, '\n');
2368 output
++; /* skip '\n' */
2370 while (*output
!= '\0') {
2371 // format of a line is
2372 // 0x404c5000 0x40580d90 Yes /lib/libc.so.5
2373 // 3 blocks of non-space followed by space
2374 for (int i
= 0; *output
!= '\0' && i
< 3; i
++) {
2375 while (*output
!= '\0' && !isspace(*output
)) { /* non-space */
2378 while (isspace(*output
)) { /* space */
2382 if (*output
== '\0')
2384 const char* start
= output
;
2385 output
= strchr(output
, '\n');
2387 output
= start
+ strlen(start
);
2388 shlibName
= QString::fromLatin1(start
, output
-start
);
2389 if (*output
!= '\0')
2391 shlibs
.append(shlibName
);
2392 TRACE("found shared lib " + shlibName
);
2397 bool GdbDriver::parseFindType(const char* output
, QString
& type
)
2399 if (strncmp(output
, "type = ", 7) != 0)
2403 * Everything else is the type. We strip off any leading "const" and any
2404 * trailing "&" on the grounds that neither affects the decoding of the
2405 * object. We also strip off all white-space from the type.
2408 if (strncmp(output
, "const ", 6) == 0)
2411 type
.replace(QRegExp("\\s+"), "");
2412 if (type
.endsWith("&"))
2413 type
.truncate(type
.length() - 1);
2417 std::list
<RegisterInfo
> GdbDriver::parseRegisters(const char* output
)
2419 std::list
<RegisterInfo
> regs
;
2420 if (strncmp(output
, "The program has no registers now", 32) == 0) {
2424 // parse register values
2425 while (*output
!= '\0')
2428 // skip space at the start of the line
2429 while (isspace(*output
))
2433 const char* start
= output
;
2434 while (*output
!= '\0' && !isspace(*output
))
2436 if (*output
== '\0')
2438 reg
.regName
= QString::fromLatin1(start
, output
-start
);
2441 while (isspace(*output
))
2447 * If we find a brace now, this is a vector register. We look for
2448 * the closing brace and treat the result as cooked value.
2453 skipNested(output
, '{', '}');
2454 value
= QString::fromLatin1(start
, output
-start
).simplified();
2455 // skip space, but not the end of line
2456 while (isspace(*output
) && *output
!= '\n')
2458 // get rid of the braces at the begining and the end
2460 if (value
[value
.length()-1] == '}') {
2461 value
= value
.left(value
.length()-1);
2463 // gdb 5.3 doesn't print a separate set of raw values
2464 if (*output
== '{') {
2465 // another set of vector follows
2466 // what we have so far is the raw value
2467 reg
.rawValue
= value
;
2470 skipNested(output
, '{', '}');
2471 value
= QString::fromLatin1(start
, output
-start
).simplified();
2474 // find first type that does not have an array, this is the RAW value
2475 const char* end
=start
;
2477 const char* cur
=start
;
2479 while (*cur
!= '=' && cur
<end
)
2482 while (isspace(*cur
) && cur
<end
)
2484 if (isNumberish(*cur
)) {
2486 while (*end
&& (*end
!='}') && (*end
!=',') && (*end
!='\n'))
2488 QString rawValue
= QString::fromLatin1(cur
, end
-cur
).simplified();
2489 reg
.rawValue
= rawValue
;
2491 if (rawValue
.left(2)=="0x") {
2492 // ok we have a raw value, now get it's type
2494 while (isspace(*end
) || *end
=='=') end
--;
2497 while (*cur
!='{' && *cur
!=' ')
2500 reg
.type
= QString::fromLatin1(cur
, end
-cur
);
2507 // skip to the end of line
2508 while (*output
!= '\0' && *output
!= '\n')
2510 // get rid of the braces at the begining and the end
2512 if (value
[value
.length()-1] == '}') {
2513 value
.truncate(value
.length()-1);
2516 reg
.cookedValue
= value
;
2521 // the rest of the line is the register value
2523 output
= strchr(output
,'\n');
2525 output
= start
+ strlen(start
);
2526 value
+= QString::fromLatin1(start
, output
-start
).simplified();
2529 * Look ahead: if the subsequent line is indented, it continues
2530 * the current register value.
2532 if (output
!= 0 && isspace(output
[1]))
2540 * We split the raw from the cooked values.
2541 * Some modern gdbs explicitly say: "0.1234 (raw 0x3e4567...)".
2542 * Here, the cooked value comes first, and the raw value is in
2545 int pos
= value
.indexOf(" (raw ");
2548 reg
.cookedValue
= value
.left(pos
);
2549 reg
.rawValue
= value
.mid(pos
+6);
2550 if (reg
.rawValue
.right(1) == ")") // remove closing bracket
2551 reg
.rawValue
.truncate(reg
.rawValue
.length()-1);
2556 * In other cases we split off the first token (separated by
2557 * whitespace). It is the raw value. The remainder of the line
2558 * is the cooked value.
2560 int pos
= value
.indexOf(' ');
2562 reg
.rawValue
= value
;
2563 reg
.cookedValue
= QString();
2565 reg
.rawValue
= value
.left(pos
);
2566 reg
.cookedValue
= value
.mid(pos
+1);
2570 if (*output
!= '\0')
2571 output
++; /* skip '\n' */
2573 regs
.push_back(reg
);
2578 bool GdbDriver::parseInfoLine(const char* output
, QString
& addrFrom
, QString
& addrTo
)
2580 // "is at address" or "starts at address"
2581 const char* start
= strstr(output
, "s at address ");
2586 const char* p
= start
;
2587 while (*p
!= '\0' && !isspace(*p
))
2589 addrFrom
= QString::fromLatin1(start
, p
-start
);
2591 start
= strstr(p
, "and ends at ");
2599 while (*p
!= '\0' && !isspace(*p
))
2601 addrTo
= QString::fromLatin1(start
, p
-start
);
2606 std::list
<DisassembledCode
> GdbDriver::parseDisassemble(const char* output
)
2608 std::list
<DisassembledCode
> code
;
2610 if (strncmp(output
, "Dump of assembler", 17) != 0) {
2618 // remove first line
2619 const char* p
= strchr(output
, '\n');
2621 return code
; /* not a regular output */
2626 const char* end
= strstr(output
, "End of assembler");
2628 end
= p
+ strlen(p
);
2630 // remove function offsets from the lines
2634 // skip initial space or PC pointer ("=>", since gdb 7.1)
2638 else if (p
[0] == '=' && p
[1] == '>')
2643 const char* start
= p
;
2645 while (p
!= end
&& !isspace(*p
))
2647 c
.address
= QString::fromLatin1(start
, p
-start
);
2649 // function name (enclosed in '<>', followed by ':')
2650 while (p
!= end
&& *p
!= '<')
2653 skipNestedAngles(p
);
2658 while (p
!= end
&& isspace(*p
))
2661 // code until end of line
2663 while (p
!= end
&& *p
!= '\n')
2665 if (p
!= end
) /* include '\n' */
2668 c
.code
= QString::fromLatin1(start
, p
-start
);
2674 QString
GdbDriver::parseMemoryDump(const char* output
, std::list
<MemoryDump
>& memdump
)
2676 if (isErrorExpr(output
)) {
2677 // error; strip space
2678 QString msg
= output
;
2679 return msg
.trimmed();
2682 const char* p
= output
; /* save typing */
2688 const char* start
= p
;
2689 while (*p
!= '\0' && *p
!= ':' && !isspace(*p
))
2691 md
.address
= QString::fromLatin1(start
, p
-start
);
2693 // parse function offset
2697 while (*p
!= '\0' && !(*p
== ':' && isspace(p
[1])))
2699 md
.address
.fnoffs
= QString::fromLatin1(start
, p
-start
);
2703 // skip space; this may skip a new-line char!
2706 // everything to the end of the line is the memory dump
2707 const char* end
= strchr(p
, '\n');
2709 md
.dump
= QString::fromLatin1(p
, end
-p
);
2712 md
.dump
= QString::fromLatin1(p
, strlen(p
));
2715 memdump
.push_back(md
);
2721 QString
GdbDriver::editableValue(VarTree
* value
)
2723 QByteArray ba
= value
->value().toLatin1();
2724 const char* s
= ba
.constData();
2726 // if the variable is a pointer value that contains a cast,
2729 skipNested(s
, '(', ')');
2736 const char* start
= s
;
2738 if (strncmp(s
, "0x", 2) == 0)
2741 while (isxdigit(*s
))
2745 * What we saw so far might have been a reference. If so, edit the
2746 * referenced value. Otherwise, edit the pointer.
2754 // if it's a pointer to a string, remove the string
2755 const char* end
= s
;
2760 return QString::fromLatin1(start
, end
-start
);
2763 return QString::fromLatin1(start
, strlen(start
));
2767 // else leave it unchanged (or stripped of the reference preamble)
2771 QString
GdbDriver::parseSetVariable(const char* output
)
2773 // if there is any output, it is an error message
2774 QString msg
= output
;
2775 return msg
.trimmed();
2779 #include "gdbdriver.moc"