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
.toLatin1().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
.toLatin1().constData(), intArg
);
548 cmdString
.sprintf(cmds
[cmd
].fmt
, intArg
, strArg
.toLatin1().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
.toLatin1().constData(),
564 strArg2
.toLatin1().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 // (void (*)()) 0x8048480 <f(E *, char)>
1273 // &parseP (HTMLClueV *, char *)
1274 // Variable "x" is not available.
1275 // The value of variable 'x' is distributed...
1276 // -nan(0xfffff081defa0)
1283 skipNested(p
, '(', ')');
1287 variable
->m_value
= QString::fromLatin1(s
, p
- s
);
1290 bool reference
= false;
1292 // skip reference marker
1296 const char* start
= p
;
1300 // some values consist of more than one token
1301 bool checkMultiPart
= false;
1303 if (p
[0] == '0' && p
[1] == 'x') {
1306 while (isxdigit(*p
))
1310 * Assume this is a pointer, but only if it's not a reference, since
1311 * references can't be expanded.
1314 variable
->m_varKind
= VarTree::VKpointer
;
1317 * References are followed by a colon, in which case we'll
1318 * find the value following the reference address.
1323 // Paranoia. (Can this happen, i.e. reference not followed by ':'?)
1327 checkMultiPart
= true;
1328 } else if (isdigit(*p
)) {
1329 // parse decimal number, possibly a float
1332 if (*p
== '.') { /* TODO: obey i18n? */
1333 // In long arrays an integer may be followed by '...'.
1334 // We test for this situation and don't gobble the '...'.
1335 if (p
[1] != '.' || p
[0] != '.') {
1342 if (*p
== 'e' || *p
== 'E') {
1345 if (*p
== '-' || *p
== '+')
1351 // for char variables there is the char, eg. 10 '\n'
1352 checkMultiPart
= true;
1353 } else if (*p
== '<') {
1354 // e.g. <optimized out>
1355 skipNestedAngles(p
);
1356 } else if (*p
== '"' || *p
== '\'') {
1357 // character may have multipart: '\000' <repeats 11 times>
1358 checkMultiPart
= *p
== '\'';
1361 } else if (*p
== 'L' && (p
[1] == '"' || p
[1] == '\'')) {
1362 // ditto for wchar_t strings
1363 checkMultiPart
= p
[1] == '\'';
1365 } else if (*p
== '&') {
1369 while (isspace(*p
)) {
1373 skipNested(p
, '(', ')');
1375 } else if (strncmp(p
, "Variable \"", 10) == 0) {
1376 // Variable "x" is not available.
1377 p
+= 10; // skip to "
1379 if (strncmp(p
, "\" is not available.", 19) == 0) {
1382 } else if (strncmp(p
, "The value of variable '", 23) == 0) {
1385 const char* e
= strchr(p
, '.');
1393 // must be an enumeration value
1395 // nan (floating point Not a Number) is followed by a number in ()
1396 // enum values can look like A::(anonymous namespace)::blue
1398 bool isAnonNS
= strncmp(p
+1, "anonymous namespace)", 20) == 0;
1399 skipNested(p
, '(', ')');
1404 variable
->m_value
+= QString::fromLatin1(start
, p
- start
);
1406 // remove line breaks from the value; this is ok since
1407 // string values never contain a literal line break
1408 variable
->m_value
.replace('\n', ' ');
1410 if (checkMultiPart
) {
1414 // may be followed by a string or <...>
1417 if (*p
== '"' || *p
== '\'') {
1419 } else if (*p
== 'L' && (p
[1] == '"' || p
[1] == '\'')) {
1420 skipString(p
); // wchar_t string
1421 } else if (*p
== '<') {
1422 // if this value is part of an array, it might be followed
1423 // by <repeats 15 times>, which we don't skip here
1424 if (strncmp(p
, "<repeats ", 9) != 0)
1425 skipNestedAngles(p
);
1428 // there is always a blank before the string,
1429 // which we will include in the final string value
1430 variable
->m_value
+= QString::fromLatin1(start
-1, (p
- start
)+1);
1431 // if this was a pointer, reset that flag since we
1432 // now got the value
1433 variable
->m_varKind
= VarTree::VKsimple
;
1437 if (variable
->m_value
.length() == 0) {
1438 TRACE("parse error: no value for " + variable
->m_name
);
1442 // final white space
1448 * If this was a reference, the value follows. It might even be a
1449 * composite variable!
1459 static bool parseNested(const char*& s
, ExprValue
* variable
)
1461 // could be a structure or an array
1466 bool isStruct
= false;
1468 * If there is a name followed by an = or an < -- which starts a type
1469 * name -- or "static", it is a structure
1471 if (*p
== '<' || *p
== '}') {
1473 } else if (strncmp(p
, "static ", 7) == 0) {
1475 } else if (isalpha(*p
) || *p
== '_' || *p
== '$') {
1476 // look ahead for a comma after the name
1483 p
= s
; /* rescan the name */
1486 if (!parseVarSeq(p
, variable
)) {
1489 variable
->m_varKind
= VarTree::VKstruct
;
1491 if (!parseValueSeq(p
, variable
)) {
1494 variable
->m_varKind
= VarTree::VKarray
;
1500 static bool parseVarSeq(const char*& s
, ExprValue
* variable
)
1502 // parse a comma-separated sequence of variables
1503 ExprValue
* var
= variable
; /* var != 0 to indicate success if empty seq */
1507 if (strncmp(s
, "<No data fields>}", 17) == 0)
1509 // no member variables, so break out immediately
1510 s
+= 16; /* go to the closing brace */
1515 break; /* syntax error */
1516 variable
->appendChild(var
);
1519 // skip the comma and whitespace
1527 static bool parseValueSeq(const char*& s
, ExprValue
* variable
)
1529 // parse a comma-separated sequence of variables
1534 name
.sprintf("[%d]", index
);
1535 ExprValue
* var
= new ExprValue(name
, VarTree::NKplain
);
1536 good
= parseValue(s
, var
);
1541 // a value may be followed by "<repeats 45 times>"
1542 if (strncmp(s
, "<repeats ", 9) == 0) {
1545 int l
= strtol(s
, &end
, 10);
1546 if (end
== s
|| strncmp(end
, " times>", 7) != 0) {
1547 // should not happen
1551 TRACE(QString().sprintf("found <repeats %d times> in array", l
));
1552 // replace name and advance index
1553 name
.sprintf("[%d .. %d]", index
, index
+l
-1);
1556 // skip " times>" and space
1558 // possible final space
1564 variable
->appendChild(var
);
1565 // long arrays may be terminated by '...'
1566 if (strncmp(s
, "...", 3) == 0) {
1568 ExprValue
* var
= new ExprValue("...", VarTree::NKplain
);
1569 var
->m_value
= i18n("<additional entries of the array suppressed>");
1570 variable
->appendChild(var
);
1576 // skip the comma and whitespace
1580 // sometimes there is a closing brace after a comma
1588 * Parses a stack frame.
1590 static void parseFrameInfo(const char*& s
, QString
& func
,
1591 QString
& file
, int& lineNo
, DbgAddr
& address
)
1595 // next may be a hexadecimal address
1597 const char* start
= p
;
1601 while (isxdigit(*p
))
1603 address
= QString::fromLatin1(start
, p
-start
);
1604 if (strncmp(p
, " in ", 4) == 0)
1607 address
= DbgAddr();
1609 const char* start
= p
;
1610 // check for special signal handler frame
1611 if (strncmp(p
, "<signal handler called>", 23) == 0) {
1612 func
= QString::fromLatin1(start
, 23);
1622 * Skip the function name. It is terminated by a left parenthesis
1623 * which does not delimit "(anonymous namespace)" and which is
1624 * outside the angle brackets <> of template parameter lists
1625 * and is preceded by a space.
1630 // check for operator<< and operator<
1631 if (p
-start
>= 8 && strncmp(p
-8, "operator", 8) == 0)
1639 // skip template parameter list
1640 skipNestedAngles(p
);
1642 } else if (*p
== '(') {
1643 // this skips "(anonymous namespace)" as well as the formal
1644 // parameter list of the containing function if this is a member
1645 // of a nested class
1646 skipNestedWithString(p
, '(', ')');
1647 } else if (*p
== ' ') {
1650 break; // parameter list found
1664 * Skip parameters. But notice that for complicated conversion
1665 * functions (eg. "operator int(**)()()", ie. convert to pointer to
1666 * pointer to function) as well as operator()(...) we have to skip
1667 * additional pairs of parentheses. Furthermore, recent gdbs write the
1668 * demangled name followed by the arguments in a pair of parentheses,
1669 * where the demangled name can end in "const".
1672 skipNestedWithString(p
, '(', ')');
1676 if (strncmp(p
, "const", 5) == 0) {
1681 } while (*p
== '(');
1683 // check for file position
1684 if (strncmp(p
, "at ", 3) == 0) {
1686 const char* fileStart
= p
;
1687 // go for the end of the line
1688 while (*p
!= '\0' && *p
!= '\n')
1690 // search back for colon
1691 const char* colon
= p
;
1694 } while (*colon
!= ':');
1695 file
= QString::fromLatin1(fileStart
, colon
-fileStart
);
1696 lineNo
= atoi(colon
+1)-1;
1701 // check for "from shared lib"
1702 if (strncmp(p
, "from ", 5) == 0) {
1704 // go for the end of the line
1705 while (*p
!= '\0' && *p
!= '\n')
1714 // construct the function name (including file info)
1718 func
= QString::fromLatin1(start
, p
-start
-1); /* don't include \n */
1723 * Replace \n (and whitespace around it) in func by a blank. We cannot
1724 * use QString::simplified() for this because this would also
1725 * simplify space that belongs to a string arguments that gdb sometimes
1726 * prints in the argument lists of the function.
1728 ASSERT(!isspace(func
[0].toLatin1())); // there must be non-white before first \n
1730 while ((nl
= func
.indexOf('\n', nl
)) >= 0) {
1731 // search back to the beginning of the whitespace
1732 int startWhite
= nl
;
1735 } while (isspace(func
[startWhite
].toLatin1()));
1737 // search forward to the end of the whitespace
1740 } while (isspace(func
[nl
].toLatin1()));
1742 func
.replace(startWhite
, nl
-startWhite
, " ");
1743 /* continue searching for more \n's at this place: */
1750 * Parses a stack frame including its frame number
1752 static bool parseFrame(const char*& s
, int& frameNo
, QString
& func
,
1753 QString
& file
, int& lineNo
, DbgAddr
& address
)
1756 // #1 0x8048881 in Dl::Dl (this=0xbffff418, r=3214) at testfile.cpp:72
1757 // Breakpoint 3, Cl::f(int) const (this=0xbffff3c0, x=17) at testfile.cpp:155
1759 // must start with a hash mark followed by number
1760 // or with "Breakpoint " followed by number and comma
1764 s
++; /* skip the hash mark */
1765 } else if (strncmp(s
, "Breakpoint ", 11) == 0) {
1766 if (!isdigit(s
[11]))
1768 s
+= 11; /* skip "Breakpoint" */
1777 while (isspace(*s
) || *s
== ',')
1779 parseFrameInfo(s
, func
, file
, lineNo
, address
);
1783 void GdbDriver::parseBackTrace(const char* output
, std::list
<StackFrame
>& stack
)
1786 int lineNo
, frameNo
;
1789 while (::parseFrame(output
, frameNo
, func
, file
, lineNo
, address
)) {
1790 stack
.push_back(StackFrame());
1791 StackFrame
* frm
= &stack
.back();
1792 frm
->frameNo
= frameNo
;
1793 frm
->fileName
= file
;
1794 frm
->lineNo
= lineNo
;
1795 frm
->address
= address
;
1796 frm
->var
= new ExprValue(func
, VarTree::NKplain
);
1800 bool GdbDriver::parseFrameChange(const char* output
, int& frameNo
,
1801 QString
& file
, int& lineNo
, DbgAddr
& address
)
1804 return ::parseFrame(output
, frameNo
, func
, file
, lineNo
, address
);
1808 bool GdbDriver::parseBreakList(const char* output
, std::list
<Breakpoint
>& brks
)
1810 // skip first line, which is the headline
1811 const char* p
= strchr(output
, '\n');
1821 while (*p
!= '\0') {
1824 bp
.id
= strtol(p
, &dummy
, 10); /* don't care about overflows */
1829 if (strncmp(p
, "breakpoint", 10) == 0) {
1831 } else if (strncmp(p
, "hw watchpoint", 13) == 0) {
1832 bp
.type
= Breakpoint::watchpoint
;
1834 } else if (strncmp(p
, "watchpoint", 10) == 0) {
1835 bp
.type
= Breakpoint::watchpoint
;
1843 bp
.temporary
= *p
++ == 'd';
1844 while (*p
!= '\0' && !isspace(*p
)) /* "keep" or "del" */
1851 bp
.enabled
= *p
++ == 'y';
1852 while (*p
!= '\0' && !isspace(*p
)) /* "y" or "n" */
1858 // the address, if present
1859 if (bp
.type
== Breakpoint::breakpoint
&&
1860 strncmp(p
, "0x", 2) == 0)
1862 const char* start
= p
;
1863 while (*p
!= '\0' && !isspace(*p
))
1865 bp
.address
= QString::fromLatin1(start
, p
-start
);
1866 while (isspace(*p
) && *p
!= '\n')
1871 // remainder is location, hit and ignore count, condition
1872 end
= strchr(p
, '\n');
1875 p
+= bp
.location
.length();
1877 bp
.location
= QString::fromLatin1(p
, end
-p
).trimmed();
1878 p
= end
+1; /* skip over \n */
1881 // may be continued in next line
1882 while (isspace(*p
)) { /* p points to beginning of line */
1883 // skip white space at beginning of line
1888 end
= strchr(p
, '\n');
1892 if (strncmp(p
, "breakpoint already hit", 22) == 0) {
1893 // extract the hit count
1895 bp
.hitCount
= strtol(p
, &dummy
, 10);
1896 TRACE(QString("hit count %1").arg(bp
.hitCount
));
1897 } else if (strncmp(p
, "stop only if ", 13) == 0) {
1898 // extract condition
1900 bp
.condition
= QString::fromLatin1(p
, end
-p
).trimmed();
1901 TRACE("condition: "+bp
.condition
);
1902 } else if (strncmp(p
, "ignore next ", 12) == 0) {
1903 // extract ignore count
1905 bp
.ignoreCount
= strtol(p
, &dummy
, 10);
1906 TRACE(QString("ignore count %1").arg(bp
.ignoreCount
));
1908 // indeed a continuation
1909 bp
.location
+= " " + QString::fromLatin1(p
, end
-p
).trimmed();
1913 p
++; /* skip '\n' */
1920 std::list
<ThreadInfo
> GdbDriver::parseThreadList(const char* output
)
1922 std::list
<ThreadInfo
> threads
;
1923 if (strcmp(output
, "\n") == 0 ||
1924 strncmp(output
, "No stack.", 9) == 0 ||
1925 strncmp(output
, "No threads.", 11) == 0) {
1930 bool newFormat
= false;
1931 const char* p
= output
;
1932 while (*p
!= '\0') {
1934 // seach look for thread id, watching out for the focus indicator
1935 thr
.hasFocus
= false;
1936 while (isspace(*p
)) /* may be \n from prev line: see "No stack" below */
1939 // recent GDBs write a header line; skip it
1940 if (threads
.empty() && strncmp(p
, "Id Target", 11) == 0) {
1941 p
= strchr(p
, '\n');
1945 continue; // next line please, '\n' is skipped above
1949 thr
.hasFocus
= true;
1951 // there follows only whitespace
1954 char *temp_end
= NULL
; /* we need a non-const 'end' for strtol to use...*/
1955 thr
.id
= strtol(p
, &temp_end
, 10);
1958 // syntax error: no number found; bail out
1968 * Now follows the thread's SYSTAG.
1971 // In the old format, it is terminated by two blanks.
1972 end
= strstr(p
, " ");
1974 // syntax error; bail out
1979 // In the new format lies crazyness: there is no definitive
1980 // end marker. At best we can guess when the SYSTAG ends.
1981 // A typical thread list on Linux looks like this:
1983 // Id Target Id Frame
1984 // 2 Thread 0x7ffff7854700 (LWP 10827) "thrserver" 0x00007ffff7928631 in clone () from /lib64/libc.so.6
1985 // * 1 Thread 0x7ffff7fcc700 (LWP 10808) "thrserver" main () at thrserver.c:84
1987 // Looking at GDB's code, the Target Id ends in tokens that
1988 // are bracketed by parentheses or quotes. Therefore,
1989 // we skip (at most) two tokens ('Thread' and the address),
1990 // and then all parts that are in parentheses or quotes.
1997 } else if (*end
== '(') {
1998 skipNested(end
, '(', ')');
2001 while (*end
&& !isspace(*end
))
2007 while (isspace(*end
))
2011 thr
.threadName
= QString::fromLatin1(p
, end
-p
).trimmed();
2015 * Now follows a standard stack frame. Sometimes, however, gdb
2016 * catches a thread at an instant where it doesn't have a stack.
2018 if (strncmp(p
, "[No stack.]", 11) != 0) {
2019 ::parseFrameInfo(p
, thr
.function
, thr
.fileName
, thr
.lineNo
, thr
.address
);
2021 thr
.function
= "[No stack]";
2023 p
+= 11; /* \n is skipped above */
2026 threads
.push_back(thr
);
2031 static bool parseNewBreakpoint(const char* o
, int& id
,
2032 QString
& file
, int& lineNo
, QString
& address
);
2033 static bool parseNewWatchpoint(const char* o
, int& id
,
2036 bool GdbDriver::parseBreakpoint(const char* output
, int& id
,
2037 QString
& file
, int& lineNo
, QString
& address
)
2039 const char* o
= output
;
2040 // skip lines of that begin with "(Cannot find"
2041 while (strncmp(o
, "(Cannot find", 12) == 0) {
2042 o
= strchr(o
, '\n');
2045 o
++; /* skip newline */
2048 if (strncmp(o
, "Breakpoint ", 11) == 0) {
2049 output
+= 11; /* skip "Breakpoint " */
2050 return ::parseNewBreakpoint(output
, id
, file
, lineNo
, address
);
2051 } else if (strncmp(o
, "Temporary breakpoint ", 21) == 0) {
2053 return ::parseNewBreakpoint(output
, id
, file
, lineNo
, address
);
2054 } else if (strncmp(o
, "Hardware watchpoint ", 20) == 0) {
2056 return ::parseNewWatchpoint(output
, id
, address
);
2057 } else if (strncmp(o
, "Watchpoint ", 11) == 0) {
2059 return ::parseNewWatchpoint(output
, id
, address
);
2064 static bool parseNewBreakpoint(const char* o
, int& id
,
2065 QString
& file
, int& lineNo
, QString
& address
)
2069 id
= strtoul(o
, &p
, 10);
2073 // check for the address
2074 if (strncmp(p
, " at 0x", 6) == 0) {
2075 char* start
= p
+4; /* skip " at ", but not 0x */
2077 while (isxdigit(*p
))
2079 address
= QString::fromLatin1(start
, p
-start
);
2083 char* fileStart
= strstr(p
, "file ");
2085 return !address
.isEmpty(); /* parse error only if there's no address */
2089 char* numStart
= strstr(fileStart
, ", line ");
2090 QString fileName
= QString::fromLatin1(fileStart
, numStart
-fileStart
);
2092 int line
= strtoul(numStart
, &p
, 10);
2097 lineNo
= line
-1; /* zero-based! */
2101 static bool parseNewWatchpoint(const char* o
, int& id
,
2106 id
= strtoul(o
, &p
, 10);
2110 if (strncmp(p
, ": ", 2) != 0)
2114 // all the rest on the line is the expression
2115 expr
= QString::fromLatin1(p
, strlen(p
)).trimmed();
2119 void GdbDriver::parseLocals(const char* output
, std::list
<ExprValue
*>& newVars
)
2121 // check for possible error conditions
2122 if (strncmp(output
, "No symbol table", 15) == 0)
2127 while (*output
!= '\0') {
2128 while (isspace(*output
))
2130 if (*output
== '\0')
2132 // skip occurrences of "No locals" and "No args"
2133 if (strncmp(output
, "No locals", 9) == 0 ||
2134 strncmp(output
, "No arguments", 12) == 0)
2136 output
= strchr(output
, '\n');
2143 ExprValue
* variable
= parseVar(output
);
2144 if (variable
== 0) {
2147 // do not add duplicates
2148 for (std::list
<ExprValue
*>::iterator o
= newVars
.begin(); o
!= newVars
.end(); ++o
) {
2149 if ((*o
)->m_name
== variable
->m_name
) {
2154 newVars
.push_back(variable
);
2159 ExprValue
* GdbDriver::parsePrintExpr(const char* output
, bool wantErrorValue
)
2162 // check for error conditions
2163 if (!parseErrorMessage(output
, var
, wantErrorValue
))
2165 // parse the variable
2166 var
= parseVar(output
);
2171 bool GdbDriver::parseChangeWD(const char* output
, QString
& message
)
2173 bool isGood
= false;
2174 message
= QString(output
).simplified();
2175 if (message
.isEmpty()) {
2176 message
= i18n("New working directory: ") + m_programWD
;
2182 bool GdbDriver::parseChangeExecutable(const char* output
, QString
& message
)
2186 m_haveCoreFile
= false;
2189 * Lines starting with the following do not indicate errors:
2190 * Using host libthread_db
2191 * (no debugging symbols found)
2192 * Reading symbols from
2194 while (strncmp(output
, "Reading symbols from", 20) == 0 ||
2195 strncmp(output
, "Using host libthread_db", 23) == 0 ||
2196 strncmp(output
, "(no debugging symbols found)", 28) == 0)
2198 // this line is good, go to the next one
2199 const char* end
= strchr(output
, '\n');
2201 output
+= strlen(output
);
2207 * If we've parsed all lines, there was no error.
2209 return output
[0] == '\0';
2212 bool GdbDriver::parseCoreFile(const char* output
)
2214 // if command succeeded, gdb emits a line starting with "#0 "
2215 m_haveCoreFile
= strstr(output
, "\n#0 ") != 0;
2216 return m_haveCoreFile
;
2219 uint
GdbDriver::parseProgramStopped(const char* output
, QString
& message
)
2221 // optionally: "program changed, rereading symbols",
2223 // "Program exited normally"
2224 // "Program terminated with wignal SIGSEGV"
2225 // "Program received signal SIGINT" or other signal
2227 // GDB since 7.3 prints
2228 // "[Inferior 1 (process 13400) exited normally]"
2229 // "[Inferior 1 (process 14698) exited with code 01]"
2231 // go through the output, line by line, checking what we have
2232 const char* start
= output
- 1;
2233 uint flags
= SFprogramActive
;
2234 message
= QString();
2236 start
++; /* skip '\n' */
2238 if (strncmp(start
, "Program ", 8) == 0 ||
2239 strncmp(start
, "ptrace: ", 8) == 0) {
2241 * When we receive a signal, the program remains active.
2243 * Special: If we "stopped" in a corefile, the string "Program
2244 * terminated with signal"... is displayed. (Normally, we see
2245 * "Program received signal"... when a signal happens.)
2247 if (strncmp(start
, "Program exited", 14) == 0 ||
2248 (strncmp(start
, "Program terminated", 18) == 0 && !m_haveCoreFile
) ||
2249 strncmp(start
, "ptrace: ", 8) == 0)
2251 flags
&= ~SFprogramActive
;
2255 const char* endOfMessage
= strchr(start
, '\n');
2256 if (endOfMessage
== 0)
2257 endOfMessage
= start
+ strlen(start
);
2258 message
= QString::fromLatin1(start
, endOfMessage
-start
);
2259 } else if (strncmp(start
, "[Inferior ", 10) == 0) {
2260 const char* p
= start
+ 10;
2261 // skip number and space
2262 while (*p
&& !isspace(*p
))
2267 skipNested(p
, '(', ')');
2268 if (strncmp(p
, " exited ", 8) == 0) {
2269 flags
&= ~SFprogramActive
;
2272 const char* end
= strchr(p
, '\n');
2274 end
= p
+ strlen(p
);
2275 // strip [] from the message
2276 message
= QString::fromLatin1(start
+1, end
-start
-2);
2279 } else if (strncmp(start
, "Breakpoint ", 11) == 0) {
2281 * We stopped at a (permanent) breakpoint (gdb doesn't tell us
2282 * that it stopped at a temporary breakpoint).
2284 flags
|= SFrefreshBreak
;
2285 } else if (strstr(start
, "re-reading symbols.") != 0) {
2286 flags
|= SFrefreshSource
;
2289 // next line, please
2290 start
= strchr(start
, '\n');
2291 } while (start
!= 0);
2294 * Gdb only notices when new threads have appeared, but not when a
2295 * thread finishes. So we always have to assume that the list of
2296 * threads has changed.
2298 flags
|= SFrefreshThreads
;
2303 QStringList
GdbDriver::parseSharedLibs(const char* output
)
2306 if (strncmp(output
, "No shared libraries loaded", 26) == 0)
2309 // parse the table of shared libraries
2311 // strip off head line
2312 output
= strchr(output
, '\n');
2315 output
++; /* skip '\n' */
2317 while (*output
!= '\0') {
2318 // format of a line is
2319 // 0x404c5000 0x40580d90 Yes /lib/libc.so.5
2320 // 3 blocks of non-space followed by space
2321 for (int i
= 0; *output
!= '\0' && i
< 3; i
++) {
2322 while (*output
!= '\0' && !isspace(*output
)) { /* non-space */
2325 while (isspace(*output
)) { /* space */
2329 if (*output
== '\0')
2331 const char* start
= output
;
2332 output
= strchr(output
, '\n');
2334 output
= start
+ strlen(start
);
2335 shlibName
= QString::fromLatin1(start
, output
-start
);
2336 if (*output
!= '\0')
2338 shlibs
.append(shlibName
);
2339 TRACE("found shared lib " + shlibName
);
2344 bool GdbDriver::parseFindType(const char* output
, QString
& type
)
2346 if (strncmp(output
, "type = ", 7) != 0)
2350 * Everything else is the type. We strip off any leading "const" and any
2351 * trailing "&" on the grounds that neither affects the decoding of the
2352 * object. We also strip off all white-space from the type.
2355 if (strncmp(output
, "const ", 6) == 0)
2358 type
.replace(QRegExp("\\s+"), "");
2359 if (type
.endsWith("&"))
2360 type
.truncate(type
.length() - 1);
2364 std::list
<RegisterInfo
> GdbDriver::parseRegisters(const char* output
)
2366 std::list
<RegisterInfo
> regs
;
2367 if (strncmp(output
, "The program has no registers now", 32) == 0) {
2371 // parse register values
2372 while (*output
!= '\0')
2375 // skip space at the start of the line
2376 while (isspace(*output
))
2380 const char* start
= output
;
2381 while (*output
!= '\0' && !isspace(*output
))
2383 if (*output
== '\0')
2385 reg
.regName
= QString::fromLatin1(start
, output
-start
);
2388 while (isspace(*output
))
2394 * If we find a brace now, this is a vector register. We look for
2395 * the closing brace and treat the result as cooked value.
2400 skipNested(output
, '{', '}');
2401 value
= QString::fromLatin1(start
, output
-start
).simplified();
2402 // skip space, but not the end of line
2403 while (isspace(*output
) && *output
!= '\n')
2405 // get rid of the braces at the begining and the end
2407 if (value
[value
.length()-1] == '}') {
2408 value
= value
.left(value
.length()-1);
2410 // gdb 5.3 doesn't print a separate set of raw values
2411 if (*output
== '{') {
2412 // another set of vector follows
2413 // what we have so far is the raw value
2414 reg
.rawValue
= value
;
2417 skipNested(output
, '{', '}');
2418 value
= QString::fromLatin1(start
, output
-start
).simplified();
2421 // find first type that does not have an array, this is the RAW value
2422 const char* end
=start
;
2424 const char* cur
=start
;
2426 while (*cur
!= '=' && cur
<end
)
2429 while (isspace(*cur
) && cur
<end
)
2431 if (isNumberish(*cur
)) {
2433 while (*end
&& (*end
!='}') && (*end
!=',') && (*end
!='\n'))
2435 QString rawValue
= QString::fromLatin1(cur
, end
-cur
).simplified();
2436 reg
.rawValue
= rawValue
;
2438 if (rawValue
.left(2)=="0x") {
2439 // ok we have a raw value, now get it's type
2441 while (isspace(*end
) || *end
=='=') end
--;
2444 while (*cur
!='{' && *cur
!=' ')
2447 reg
.type
= QString::fromLatin1(cur
, end
-cur
);
2454 // skip to the end of line
2455 while (*output
!= '\0' && *output
!= '\n')
2457 // get rid of the braces at the begining and the end
2459 if (value
[value
.length()-1] == '}') {
2460 value
.truncate(value
.length()-1);
2463 reg
.cookedValue
= value
;
2468 // the rest of the line is the register value
2470 output
= strchr(output
,'\n');
2472 output
= start
+ strlen(start
);
2473 value
+= QString::fromLatin1(start
, output
-start
).simplified();
2476 * Look ahead: if the subsequent line is indented, it continues
2477 * the current register value.
2479 if (output
!= 0 && isspace(output
[1]))
2487 * We split the raw from the cooked values.
2488 * Some modern gdbs explicitly say: "0.1234 (raw 0x3e4567...)".
2489 * Here, the cooked value comes first, and the raw value is in
2492 int pos
= value
.indexOf(" (raw ");
2495 reg
.cookedValue
= value
.left(pos
);
2496 reg
.rawValue
= value
.mid(pos
+6);
2497 if (reg
.rawValue
.right(1) == ")") // remove closing bracket
2498 reg
.rawValue
.truncate(reg
.rawValue
.length()-1);
2503 * In other cases we split off the first token (separated by
2504 * whitespace). It is the raw value. The remainder of the line
2505 * is the cooked value.
2507 int pos
= value
.indexOf(' ');
2509 reg
.rawValue
= value
;
2510 reg
.cookedValue
= QString();
2512 reg
.rawValue
= value
.left(pos
);
2513 reg
.cookedValue
= value
.mid(pos
+1);
2517 if (*output
!= '\0')
2518 output
++; /* skip '\n' */
2520 regs
.push_back(reg
);
2525 bool GdbDriver::parseInfoLine(const char* output
, QString
& addrFrom
, QString
& addrTo
)
2527 // "is at address" or "starts at address"
2528 const char* start
= strstr(output
, "s at address ");
2533 const char* p
= start
;
2534 while (*p
!= '\0' && !isspace(*p
))
2536 addrFrom
= QString::fromLatin1(start
, p
-start
);
2538 start
= strstr(p
, "and ends at ");
2546 while (*p
!= '\0' && !isspace(*p
))
2548 addrTo
= QString::fromLatin1(start
, p
-start
);
2553 std::list
<DisassembledCode
> GdbDriver::parseDisassemble(const char* output
)
2555 std::list
<DisassembledCode
> code
;
2557 if (strncmp(output
, "Dump of assembler", 17) != 0) {
2565 // remove first line
2566 const char* p
= strchr(output
, '\n');
2568 return code
; /* not a regular output */
2573 const char* end
= strstr(output
, "End of assembler");
2575 end
= p
+ strlen(p
);
2577 // remove function offsets from the lines
2581 // skip initial space or PC pointer ("=>", since gdb 7.1)
2585 else if (p
[0] == '=' && p
[1] == '>')
2590 const char* start
= p
;
2592 while (p
!= end
&& !isspace(*p
))
2594 c
.address
= QString::fromLatin1(start
, p
-start
);
2596 // function name (enclosed in '<>', followed by ':')
2597 while (p
!= end
&& *p
!= '<')
2600 skipNestedAngles(p
);
2605 while (p
!= end
&& isspace(*p
))
2608 // code until end of line
2610 while (p
!= end
&& *p
!= '\n')
2612 if (p
!= end
) /* include '\n' */
2615 c
.code
= QString::fromLatin1(start
, p
-start
);
2621 QString
GdbDriver::parseMemoryDump(const char* output
, std::list
<MemoryDump
>& memdump
)
2623 if (isErrorExpr(output
)) {
2624 // error; strip space
2625 QString msg
= output
;
2626 return msg
.trimmed();
2629 const char* p
= output
; /* save typing */
2635 const char* start
= p
;
2636 while (*p
!= '\0' && *p
!= ':' && !isspace(*p
))
2638 md
.address
= QString::fromLatin1(start
, p
-start
);
2640 // parse function offset
2644 while (*p
!= '\0' && !(*p
== ':' && isspace(p
[1])))
2646 md
.address
.fnoffs
= QString::fromLatin1(start
, p
-start
);
2650 // skip space; this may skip a new-line char!
2653 // everything to the end of the line is the memory dump
2654 const char* end
= strchr(p
, '\n');
2656 md
.dump
= QString::fromLatin1(p
, end
-p
);
2659 md
.dump
= QString::fromLatin1(p
, strlen(p
));
2662 memdump
.push_back(md
);
2668 QString
GdbDriver::editableValue(VarTree
* value
)
2670 QByteArray ba
= value
->value().toLatin1();
2671 const char* s
= ba
.constData();
2673 // if the variable is a pointer value that contains a cast,
2676 skipNested(s
, '(', ')');
2683 const char* start
= s
;
2685 if (strncmp(s
, "0x", 2) == 0)
2688 while (isxdigit(*s
))
2692 * What we saw so far might have been a reference. If so, edit the
2693 * referenced value. Otherwise, edit the pointer.
2701 // if it's a pointer to a string, remove the string
2702 const char* end
= s
;
2707 return QString::fromLatin1(start
, end
-start
);
2710 return QString::fromLatin1(start
, strlen(start
));
2714 // else leave it unchanged (or stripped of the reference preamble)
2718 QString
GdbDriver::parseSetVariable(const char* output
)
2720 // if there is any output, it is an error message
2721 QString msg
= output
;
2722 return msg
.trimmed();
2726 #include "gdbdriver.moc"