3 // Copyright by Johannes Sixt
4 // This file is under GPL, the GNU General Public Licence
10 #include <klocale.h> /* i18n */
15 #include <stdlib.h> /* strtol, atoi */
16 #include <string.h> /* strcpy */
24 static void skipString(const char*& p
);
25 static void skipNested(const char*& s
, char opening
, char closing
);
26 static VarTree
* parseVar(const char*& s
);
27 static bool parseName(const char*& s
, QString
& name
, VarTree::NameKind
& kind
);
28 static bool parseValue(const char*& s
, VarTree
* variable
);
29 static bool parseNested(const char*& s
, VarTree
* variable
);
30 static bool parseVarSeq(const char*& s
, VarTree
* variable
);
31 static bool parseValueSeq(const char*& s
, VarTree
* variable
);
33 #define PROMPT "(kdbg)"
35 #define PROMPT_LAST_CHAR ')' /* needed when searching for prompt string */
38 // TODO: make this cmd info stuff non-static to allow multiple
39 // simultaneous gdbs to run!
43 const char* fmt
; /* format string */
45 argNone
, argString
, argNum
,
46 argStringNum
, argNumString
,
51 static const char printQStringStructFmt
[] =
52 // if the string data is junk, fail early
53 "print ($qstrunicode=($qstrdata=(%s))->unicode)?"
54 // print an array of shorts
55 "(*(unsigned short*)$qstrunicode)@"
57 "(($qstrlen=(unsigned int)($qstrdata->len))>100?100:$qstrlen)"
58 // if unicode data is 0, check if it is QString::null
59 ":($qstrdata==QString::null.d)\n";
61 // However, gdb can't always find QString::null (I don't know why)
62 // which results in an error; we autodetect this situation in
63 // parseQt2QStrings and revert to a safe expression.
64 // Same as above except for last line:
65 static const char printQStringStructNoNullFmt
[] =
66 "print ($qstrunicode=($qstrdata=(%s))->unicode)?"
67 "(*(unsigned short*)$qstrunicode)@"
68 "(($qstrlen=(unsigned int)($qstrdata->len))>100?100:$qstrlen)"
72 * The following array of commands must be sorted by the DC* values,
73 * because they are used as indices.
75 static GdbCmdInfo cmds
[] = {
76 { DCinitialize
, "", GdbCmdInfo::argNone
},
77 { DCtty
, "tty %s\n", GdbCmdInfo::argString
},
78 { DCexecutable
, "file \"%s\"\n", GdbCmdInfo::argString
},
79 { DCtargetremote
, "target remote %s\n", GdbCmdInfo::argString
},
80 { DCcorefile
, "core-file %s\n", GdbCmdInfo::argString
},
81 { DCattach
, "attach %s\n", GdbCmdInfo::argString
},
82 { DCinfolinemain
, "info line main\n", GdbCmdInfo::argNone
},
83 { DCinfolocals
, "kdbg__alllocals\n", GdbCmdInfo::argNone
},
84 { DCinforegisters
, "info all-registers\n", GdbCmdInfo::argNone
},
85 { DCsetargs
, "set args %s\n", GdbCmdInfo::argString
},
86 { DCsetenv
, "set env %s %s\n", GdbCmdInfo::argString2
},
87 { DCunsetenv
, "unset env %s\n", GdbCmdInfo::argString
},
88 { DCcd
, "cd %s\n", GdbCmdInfo::argString
},
89 { DCbt
, "bt\n", GdbCmdInfo::argNone
},
90 { DCrun
, "run\n", GdbCmdInfo::argNone
},
91 { DCcont
, "cont\n", GdbCmdInfo::argNone
},
92 { DCstep
, "step\n", GdbCmdInfo::argNone
},
93 { DCnext
, "next\n", GdbCmdInfo::argNone
},
94 { DCfinish
, "finish\n", GdbCmdInfo::argNone
},
95 { DCuntil
, "until %s:%d\n", GdbCmdInfo::argStringNum
},
96 { DCkill
, "kill\n", GdbCmdInfo::argNone
},
97 { DCbreaktext
, "break %s\n", GdbCmdInfo::argString
},
98 { DCbreakline
, "break %s:%d\n", GdbCmdInfo::argStringNum
},
99 { DCtbreakline
, "tbreak %s:%d\n", GdbCmdInfo::argStringNum
},
100 { DCdelete
, "delete %d\n", GdbCmdInfo::argNum
},
101 { DCenable
, "enable %d\n", GdbCmdInfo::argNum
},
102 { DCdisable
, "disable %d\n", GdbCmdInfo::argNum
},
103 { DCprint
, "print %s\n", GdbCmdInfo::argString
},
104 { DCprintStruct
, "print %s\n", GdbCmdInfo::argString
},
105 { DCprintQStringStruct
, printQStringStructFmt
, GdbCmdInfo::argString
},
106 { DCframe
, "frame %d\n", GdbCmdInfo::argNum
},
107 { DCfindType
, "whatis %s\n", GdbCmdInfo::argString
},
108 { DCinfosharedlib
, "info sharedlibrary\n", GdbCmdInfo::argNone
},
109 { DCinfobreak
, "info breakpoints\n", GdbCmdInfo::argNone
},
110 { DCcondition
, "condition %d %s\n", GdbCmdInfo::argNumString
},
111 { DCignore
, "ignore %d %d\n", GdbCmdInfo::argNum2
},
114 #define NUM_CMDS (int(sizeof(cmds)/sizeof(cmds[0])))
115 #define MAX_FMTLEN 200
117 GdbDriver::GdbDriver() :
119 m_gdbMajor(4), m_gdbMinor(16)
121 strcpy(m_prompt
, PROMPT
);
122 m_promptLen
= PROMPT_LEN
;
123 m_promptLastChar
= PROMPT_LAST_CHAR
;
126 // check command info array
128 for (int i
= 0; i
< NUM_CMDS
; i
++) {
129 // must be indexable by DbgCommand values, i.e. sorted by DbgCommand values
130 assert(i
== cmds
[i
].cmd
);
131 // a format string must be associated
132 assert(cmds
[i
].fmt
!= 0);
133 assert(strlen(cmds
[i
].fmt
) <= MAX_FMTLEN
);
134 // format string must match arg specification
135 switch (cmds
[i
].argsNeeded
) {
136 case GdbCmdInfo::argNone
:
137 assert(strchr(cmds
[i
].fmt
, '%') == 0);
139 case GdbCmdInfo::argString
:
140 perc
= strchr(cmds
[i
].fmt
, '%');
141 assert(perc
!= 0 && perc
[1] == 's');
142 assert(strchr(perc
+2, '%') == 0);
144 case GdbCmdInfo::argNum
:
145 perc
= strchr(cmds
[i
].fmt
, '%');
146 assert(perc
!= 0 && perc
[1] == 'd');
147 assert(strchr(perc
+2, '%') == 0);
149 case GdbCmdInfo::argStringNum
:
150 perc
= strchr(cmds
[i
].fmt
, '%');
151 assert(perc
!= 0 && perc
[1] == 's');
152 perc
= strchr(perc
+2, '%');
153 assert(perc
!= 0 && perc
[1] == 'd');
154 assert(strchr(perc
+2, '%') == 0);
156 case GdbCmdInfo::argNumString
:
157 perc
= strchr(cmds
[i
].fmt
, '%');
158 assert(perc
!= 0 && perc
[1] == 'd');
159 perc
= strchr(perc
+2, '%');
160 assert(perc
!= 0 && perc
[1] == 's');
161 assert(strchr(perc
+2, '%') == 0);
163 case GdbCmdInfo::argString2
:
164 perc
= strchr(cmds
[i
].fmt
, '%');
165 assert(perc
!= 0 && perc
[1] == 's');
166 perc
= strchr(perc
+2, '%');
167 assert(perc
!= 0 && perc
[1] == 's');
168 assert(strchr(perc
+2, '%') == 0);
170 case GdbCmdInfo::argNum2
:
171 perc
= strchr(cmds
[i
].fmt
, '%');
172 assert(perc
!= 0 && perc
[1] == 'd');
173 perc
= strchr(perc
+2, '%');
174 assert(perc
!= 0 && perc
[1] == 'd');
175 assert(strchr(perc
+2, '%') == 0);
179 assert(strlen(printQStringStructFmt
) <= MAX_FMTLEN
);
180 assert(strlen(printQStringStructNoNullFmt
) <= MAX_FMTLEN
);
184 GdbDriver::~GdbDriver()
189 QString
GdbDriver::driverName() const
194 QString
GdbDriver::defaultGdb()
198 " --fullname" /* to get standard file names each time the prog stops */
199 " --nx"; /* do not execute initialization files */
202 QString
GdbDriver::defaultInvocation() const
207 bool GdbDriver::startup(QString cmdStr
)
209 if (!DebuggerDriver::startup(cmdStr
))
212 static const char gdbInitialize
[] =
214 * Work around buggy gdbs that do command line editing even if they
215 * are not on a tty. The readline library echos every command back
216 * in this case, which is confusing for us.
220 "set print static-members off\n"
222 * Write a short macro that prints all locals: local variables and
223 * function arguments.
225 "define kdbg__alllocals\n"
226 "info locals\n" /* local vars supersede args with same name */
227 "info args\n" /* therefore, arguments must come last */
229 // change prompt string and synchronize with gdb
230 "set prompt " PROMPT
"\n"
233 executeCmdString(DCinitialize
, gdbInitialize
, false);
235 // assume that QString::null is ok
236 cmds
[DCprintQStringStruct
].fmt
= printQStringStructFmt
;
241 void GdbDriver::commandFinished(CmdQueueItem
* cmd
)
243 // command string must be committed
244 if (!cmd
->m_committed
) {
246 TRACE("calling " + (__PRETTY_FUNCTION__
+ (" with uncommited command:\n\t" +
251 switch (cmd
->m_cmd
) {
253 // get version number from preamble
256 QRegExp
GDBVersion("\\nGDB [0-9]+\\.[0-9]+");
257 int offset
= GDBVersion
.match(m_output
, 0, &len
);
259 char* start
= m_output
+ offset
+ 5; // skip "\nGDB "
261 m_gdbMajor
= strtol(start
, &end
, 10);
262 m_gdbMinor
= strtol(end
+ 1, 0, 10); // skip "."
264 // nothing was parsed
269 // assume some default version (what would make sense?)
273 // use a feasible core-file command
274 if (m_gdbMajor
> 4 || (m_gdbMajor
== 4 && m_gdbMinor
>= 16)) {
275 cmds
[DCcorefile
].fmt
= "target core %s\n";
277 cmds
[DCcorefile
].fmt
= "core-file %s\n";
284 /* ok, the command is ready */
285 emit
commandReceived(cmd
, m_output
);
287 switch (cmd
->m_cmd
) {
304 * The --fullname option makes gdb send a special normalized sequence print
305 * each time the program stops and at some other points. The sequence has
306 * the form "\032\032filename:lineno:charoffset:(beg|middle):address".
308 void GdbDriver::parseMarker()
310 char* startMarker
= strstr(m_output
, "\032\032");
311 if (startMarker
== 0)
314 // extract the marker
316 TRACE(QString("found marker: ") + startMarker
);
317 char* endMarker
= strchr(startMarker
, '\n');
323 // extract filename and line number
324 static QRegExp
MarkerRE(":[0-9]+:[0-9]+:[begmidl]+:0x");
326 int lineNoStart
= MarkerRE
.match(startMarker
);
327 if (lineNoStart
>= 0) {
328 int lineNo
= atoi(startMarker
+ lineNoStart
+1);
330 // now show the window
331 startMarker
[lineNoStart
] = '\0'; /* split off file name */
332 emit
activateFileLine(startMarker
, lineNo
-1);
338 #define LATIN1(str) ((str).isNull() ? "" : (str).data())
340 #define LATIN1(str) (str).latin1()
343 QString
GdbDriver::makeCmdString(DbgCommand cmd
, QString strArg
)
345 assert(cmd
>= 0 && cmd
< NUM_CMDS
);
346 assert(cmds
[cmd
].argsNeeded
== GdbCmdInfo::argString
);
349 // need the working directory when parsing the output
350 m_programWD
= strArg
;
351 } else if (cmd
== DCsetargs
) {
352 // attach saved redirection
356 strArg
+= m_redirect
;
359 SIZED_QString(cmdString
, MAX_FMTLEN
+strArg
.length());
360 cmdString
.sprintf(cmds
[cmd
].fmt
, LATIN1(strArg
));
364 QString
GdbDriver::makeCmdString(DbgCommand cmd
, int intArg
)
366 assert(cmd
>= 0 && cmd
< NUM_CMDS
);
367 assert(cmds
[cmd
].argsNeeded
== GdbCmdInfo::argNum
);
369 SIZED_QString(cmdString
, MAX_FMTLEN
+30);
371 cmdString
.sprintf(cmds
[cmd
].fmt
, intArg
);
375 QString
GdbDriver::makeCmdString(DbgCommand cmd
, QString strArg
, int intArg
)
377 assert(cmd
>= 0 && cmd
< NUM_CMDS
);
378 assert(cmds
[cmd
].argsNeeded
== GdbCmdInfo::argStringNum
||
379 cmds
[cmd
].argsNeeded
== GdbCmdInfo::argNumString
||
382 SIZED_QString(cmdString
, MAX_FMTLEN
+30+strArg
.length());
387 * intArg specifies which channels should be redirected to
388 * /dev/null. It is a value or'ed together from RDNstdin,
389 * RDNstdout, RDNstderr. We store the value for a later DCsetargs
392 * Note: We rely on that after the DCtty a DCsetargs will follow,
393 * which will ultimately apply the redirection.
395 static const char* const runRedir
[8] = {
399 " </dev/null >/dev/null",
401 " </dev/null 2>/dev/null",
403 " </dev/null >/dev/null 2>&1"
405 if (strArg
.isEmpty())
406 intArg
= 7; /* failsafe if no tty */
407 m_redirect
= runRedir
[intArg
& 7];
409 return makeCmdString(DCtty
, strArg
); /* note: no problem if strArg empty */
412 if (cmds
[cmd
].argsNeeded
== GdbCmdInfo::argStringNum
)
414 // line numbers are zero-based
415 if (cmd
== DCuntil
|| cmd
== DCbreakline
|| cmd
== DCtbreakline
)
417 cmdString
.sprintf(cmds
[cmd
].fmt
, LATIN1(strArg
), intArg
);
421 cmdString
.sprintf(cmds
[cmd
].fmt
, intArg
, LATIN1(strArg
));
426 QString
GdbDriver::makeCmdString(DbgCommand cmd
, QString strArg1
, QString strArg2
)
428 assert(cmd
>= 0 && cmd
< NUM_CMDS
);
429 assert(cmds
[cmd
].argsNeeded
== GdbCmdInfo::argString2
);
431 SIZED_QString(cmdString
, MAX_FMTLEN
+strArg1
.length()+strArg2
.length());
432 cmdString
.sprintf(cmds
[cmd
].fmt
, LATIN1(strArg1
), LATIN1(strArg2
));
436 QString
GdbDriver::makeCmdString(DbgCommand cmd
, int intArg1
, int intArg2
)
438 assert(cmd
>= 0 && cmd
< NUM_CMDS
);
439 assert(cmds
[cmd
].argsNeeded
== GdbCmdInfo::argNum2
);
441 SIZED_QString(cmdString
, MAX_FMTLEN
+60);
442 cmdString
.sprintf(cmds
[cmd
].fmt
, intArg1
, intArg2
);
446 CmdQueueItem
* GdbDriver::executeCmd(DbgCommand cmd
, bool clearLow
)
448 assert(cmd
>= 0 && cmd
< NUM_CMDS
);
449 assert(cmds
[cmd
].argsNeeded
== GdbCmdInfo::argNone
);
452 m_haveCoreFile
= false;
455 return executeCmdString(cmd
, cmds
[cmd
].fmt
, clearLow
);
458 CmdQueueItem
* GdbDriver::executeCmd(DbgCommand cmd
, QString strArg
,
461 return executeCmdString(cmd
, makeCmdString(cmd
, strArg
), clearLow
);
464 CmdQueueItem
* GdbDriver::executeCmd(DbgCommand cmd
, int intArg
,
468 return executeCmdString(cmd
, makeCmdString(cmd
, intArg
), clearLow
);
471 CmdQueueItem
* GdbDriver::executeCmd(DbgCommand cmd
, QString strArg
, int intArg
,
474 return executeCmdString(cmd
, makeCmdString(cmd
, strArg
, intArg
), clearLow
);
477 CmdQueueItem
* GdbDriver::executeCmd(DbgCommand cmd
, QString strArg1
, QString strArg2
,
480 return executeCmdString(cmd
, makeCmdString(cmd
, strArg1
, strArg2
), clearLow
);
483 CmdQueueItem
* GdbDriver::executeCmd(DbgCommand cmd
, int intArg1
, int intArg2
,
486 return executeCmdString(cmd
, makeCmdString(cmd
, intArg1
, intArg2
), clearLow
);
489 CmdQueueItem
* GdbDriver::queueCmd(DbgCommand cmd
, QueueMode mode
)
491 return queueCmdString(cmd
, cmds
[cmd
].fmt
, mode
);
494 CmdQueueItem
* GdbDriver::queueCmd(DbgCommand cmd
, QString strArg
,
497 return queueCmdString(cmd
, makeCmdString(cmd
, strArg
), mode
);
500 CmdQueueItem
* GdbDriver::queueCmd(DbgCommand cmd
, int intArg
,
503 return queueCmdString(cmd
, makeCmdString(cmd
, intArg
), mode
);
506 CmdQueueItem
* GdbDriver::queueCmd(DbgCommand cmd
, QString strArg
, int intArg
,
509 return queueCmdString(cmd
, makeCmdString(cmd
, strArg
, intArg
), mode
);
512 void GdbDriver::terminate()
518 void GdbDriver::interruptInferior()
521 // remove accidentally queued commands
525 static bool isErrorExpr(const char* output
)
528 strncmp(output
, "Cannot access memory at", 23) == 0 ||
529 strncmp(output
, "Attempt to dereference a generic pointer", 40) == 0 ||
530 strncmp(output
, "Attempt to take contents of ", 28) == 0 ||
531 strncmp(output
, "Attempt to use a type name as an expression", 43) == 0 ||
532 strncmp(output
, "There is no member or method named", 34) == 0 ||
533 strncmp(output
, "No symbol \"", 11) == 0 ||
534 strncmp(output
, "Internal error: ", 16) == 0;
538 * Returns true if the output is an error message. If wantErrorValue is
539 * true, a new VarTree object is created and filled with the error message.
541 static bool parseErrorMessage(const char* output
,
542 VarTree
*& variable
, bool wantErrorValue
)
544 if (isErrorExpr(output
))
546 if (wantErrorValue
) {
547 // put the error message as value in the variable
548 variable
= new VarTree(QString(), VarTree::NKplain
);
549 const char* endMsg
= strchr(output
, '\n');
551 endMsg
= output
+ strlen(output
);
552 variable
->m_value
= FROM_LATIN1(output
, endMsg
-output
);
563 // this is the XChar2b on X11
566 static QString
toQString(QChar
* unicode
, int len
);
567 QChar() : row(0), cell(0) { }
568 QChar(char c
) : row(0), cell(c
) { }
569 operator char() const { return row
? 0 : cell
; }
572 QString
QChar::toQString(QChar
* unicode
, int len
)
574 QString
result(len
+1);
575 char* data
= result
.data();
578 data
[len
] = unicode
[len
].cell
;
585 VarTree
* GdbDriver::parseQCharArray(const char* output
, bool wantErrorValue
)
587 VarTree
* variable
= 0;
590 * Parse off white space. gdb sometimes prints white space first if the
591 * printed array leaded to an error.
593 const char* p
= output
;
597 // check if this is an error indicating that gdb does not know about QString::null
598 if (cmds
[DCprintQStringStruct
].fmt
== printQStringStructFmt
&&
599 strncmp(p
, "Internal error: could not find static variable null", 51) == 0)
601 /* QString::null doesn't work, use an alternate expression */
602 cmds
[DCprintQStringStruct
].fmt
= printQStringStructNoNullFmt
;
603 // continue and let parseOffErrorExpr catch the error
606 // special case: empty string (0 repetitions)
607 if (strncmp(p
, "Invalid number 0 of repetitions", 31) == 0)
609 variable
= new VarTree(QString(), VarTree::NKplain
);
610 variable
->m_value
= "\"\"";
614 // check for error conditions
615 if (parseErrorMessage(p
, variable
, wantErrorValue
))
628 } while (isspace(*p
));
632 // this is the real data
638 enum { wasNothing
, wasChar
, wasRepeat
} lastThing
= wasNothing
;
640 * A matrix for separators between the individual "things"
641 * that are added to the string. The first index is a bool,
642 * the second index is from the enum above.
644 static const char* separator
[2][3] = {
645 { "\"", 0, ", \"" }, /* normal char is added */
646 { "'", "\", '", ", '" } /* repeated char is added */
649 while (isdigit(*p
)) {
652 unsigned short value
= (unsigned short) strtoul(p
, &end
, 0);
654 goto error
; /* huh? no valid digits */
655 // skip separator and search for a repeat count
657 while (isspace(*p
) || *p
== ',')
659 bool repeats
= strncmp(p
, "<repeats ", 9) == 0;
661 const char* start
= p
;
662 p
= strchr(p
+9, '>'); /* search end and advance */
666 repeatCount
= FROM_LATIN1(start
, p
-start
);
667 while (isspace(*p
) || *p
== ',')
670 // p is now at the next char (or the end)
672 // interpret the value as a QChar
673 // TODO: make cross-architecture compatible
675 (unsigned short&)ch
= value
;
677 // escape a few frequently used characters
678 char escapeCode
= '\0';
680 case '\n': escapeCode
= 'n'; break;
681 case '\r': escapeCode
= 'r'; break;
682 case '\t': escapeCode
= 't'; break;
683 case '\b': escapeCode
= 'b'; break;
684 case '\"': escapeCode
= '\"'; break;
685 case '\\': escapeCode
= '\\'; break;
687 // since we only deal with ascii values must always escape '\0'
688 case '\0': escapeCode
= '0'; break;
690 case '\0': if (value
== 0) { escapeCode
= '0'; } break;
695 result
+= separator
[repeats
][lastThing
];
697 if (escapeCode
!= '\0') {
703 // fixup repeat count and lastThing
706 result
+= repeatCount
;
707 lastThing
= wasRepeat
;
716 if (lastThing
== wasChar
)
720 variable
= new VarTree(QString(), VarTree::NKplain
);
721 variable
->m_value
= result
;
723 else if (strncmp(p
, "true", 4) == 0)
725 variable
= new VarTree(QString(), VarTree::NKplain
);
726 variable
->m_value
= "QString::null";
728 else if (strncmp(p
, "false", 5) == 0)
730 variable
= new VarTree(QString(), VarTree::NKplain
);
731 variable
->m_value
= "(null)";
738 if (wantErrorValue
) {
739 variable
= new VarTree(QString(), VarTree::NKplain
);
740 variable
->m_value
= "internal parse error";
745 static VarTree
* parseVar(const char*& s
)
754 VarTree::NameKind kind
;
755 if (!parseName(p
, name
, kind
)) {
763 TRACE(QString().sprintf("parse error: = not found after %s", (const char*)name
));
766 // skip the '=' and more whitespace
771 VarTree
* variable
= new VarTree(name
, kind
);
772 variable
->setDeleteChildren(true);
774 if (!parseValue(p
, variable
)) {
782 static void skipNested(const char*& s
, char opening
, char closing
)
786 // parse a nested type
790 * Search for next matching `closing' char, skipping nested pairs of
791 * `opening' and `closing'.
793 while (*p
&& nest
> 0) {
796 } else if (*p
== closing
) {
802 TRACE(QString().sprintf("parse error: mismatching %c%c at %-20.20s", opening
, closing
, s
));
807 void skipString(const char*& p
)
812 while (*p
!= quote
) {
814 // skip escaped character
815 // no special treatment for octal values necessary
818 // simply return if no more characters
826 * Strings can consist of several parts, some of which contain repeated
830 // look ahaead for <repeats 123 times>
834 if (strncmp(q
, "<repeats ", 9) == 0) {
836 while (*p
!= '\0' && *p
!= '>')
839 p
++; /* skip the '>' */
843 // is the string continued?
845 // look ahead for another quote
849 if (*q
== '"' || *q
== '\'') {
855 /* very long strings are followed by `...' */
856 if (*p
== '.' && p
[1] == '.' && p
[2] == '.') {
861 static void skipNestedWithString(const char*& s
, char opening
, char closing
)
865 // parse a nested expression
869 * Search for next matching `closing' char, skipping nested pairs of
870 * `opening' and `closing' as well as strings.
872 while (*p
&& nest
> 0) {
875 } else if (*p
== closing
) {
877 } else if (*p
== '\'' || *p
== '\"') {
884 TRACE(QString().sprintf("parse error: mismatching %c%c at %-20.20s", opening
, closing
, s
));
889 inline void skipName(const char*& p
)
891 // allow : (for enumeration values) and $ and . (for _vtbl.)
892 while (isalnum(*p
) || *p
== '_' || *p
== ':' || *p
== '$' || *p
== '.')
896 static bool parseName(const char*& s
, QString
& name
, VarTree::NameKind
& kind
)
898 kind
= VarTree::NKplain
;
901 // examples of names:
904 // <string<a,b<c>,7> >
907 skipNested(p
, '<', '>');
908 name
= FROM_LATIN1(s
, p
- s
);
909 kind
= VarTree::NKtype
;
913 // name, which might be "static"; allow dot for "_vtbl."
916 TRACE(QString().sprintf("parse error: not a name %-20.20s", s
));
920 if (len
== 6 && strncmp(s
, "static", 6) == 0) {
921 kind
= VarTree::NKstatic
;
923 // its a static variable, name comes now
929 TRACE(QString().sprintf("parse error: not a name after static %-20.20s", s
));
934 name
= FROM_LATIN1(s
, len
);
936 // return the new position
941 static bool parseValue(const char*& s
, VarTree
* variable
)
943 variable
->m_value
= "";
948 if (!parseNested(s
, variable
)) {
951 // must be the closing brace
953 TRACE("parse error: missing } of " + variable
->getText());
961 // examples of leaf values (cannot be the empty string):
967 // (DwContentType&) @0x8123456: {...}
971 // 0x823abc <Array<int> virtual table>
972 // (void (*)()) 0x8048480 <f(E *, char)>
975 // &parseP (HTMLClueV *, char *)
982 skipNested(p
, '(', ')');
986 variable
->m_value
= FROM_LATIN1(s
, p
- s
);
989 bool reference
= false;
991 // skip reference marker
995 const char* start
= p
;
999 // some values consist of more than one token
1000 bool checkMultiPart
= false;
1002 if (p
[0] == '0' && p
[1] == 'x') {
1005 while (isxdigit(*p
))
1009 * Assume this is a pointer, but only if it's not a reference, since
1010 * references can't be expanded.
1013 variable
->m_varKind
= VarTree::VKpointer
;
1016 * References are followed by a colon, in which case we'll
1017 * find the value following the reference address.
1022 // Paranoia. (Can this happen, i.e. reference not followed by ':'?)
1026 checkMultiPart
= true;
1027 } else if (isdigit(*p
)) {
1028 // parse decimal number, possibly a float
1031 if (*p
== '.') { /* TODO: obey i18n? */
1037 if (*p
== 'e' || *p
== 'E') {
1040 if (*p
== '-' || *p
== '+')
1046 // for char variables there is the char, eg. 10 '\n'
1047 checkMultiPart
= true;
1048 } else if (*p
== '<') {
1049 // e.g. <optimized out>
1050 skipNested(p
, '<', '>');
1051 } else if (*p
== '"' || *p
== '\'') {
1052 // character may have multipart: '\000' <repeats 11 times>
1053 checkMultiPart
= *p
== '\'';
1056 } else if (*p
== '&') {
1060 while (isspace(*p
)) {
1064 skipNested(p
, '(', ')');
1067 // must be an enumeration value
1070 variable
->m_value
+= FROM_LATIN1(start
, p
- start
);
1072 if (checkMultiPart
) {
1076 // may be followed by a string or <...>
1079 if (*p
== '"' || *p
== '\'') {
1081 } else if (*p
== '<') {
1082 skipNested(p
, '<', '>');
1085 // there is always a blank before the string,
1086 // which we will include in the final string value
1087 variable
->m_value
+= FROM_LATIN1(start
-1, (p
- start
)+1);
1088 // if this was a pointer, reset that flag since we
1089 // now got the value
1090 variable
->m_varKind
= VarTree::VKsimple
;
1094 if (variable
->m_value
.length() == 0) {
1095 TRACE("parse error: no value for " + variable
->getText());
1099 // final white space
1105 * If this was a reference, the value follows. It might even be a
1106 * composite variable!
1112 if (variable
->m_varKind
== VarTree::VKpointer
) {
1113 variable
->setDelayedExpanding(true);
1120 static bool parseNested(const char*& s
, VarTree
* variable
)
1122 // could be a structure or an array
1127 bool isStruct
= false;
1129 * If there is a name followed by an = or an < -- which starts a type
1130 * name -- or "static", it is a structure
1132 if (*p
== '<' || *p
== '}') {
1134 } else if (strncmp(p
, "static ", 7) == 0) {
1136 } else if (isalpha(*p
) || *p
== '_' || *p
== '$') {
1137 // look ahead for a comma after the name
1144 p
= s
; /* rescan the name */
1147 if (!parseVarSeq(p
, variable
)) {
1150 variable
->m_varKind
= VarTree::VKstruct
;
1152 if (!parseValueSeq(p
, variable
)) {
1155 variable
->m_varKind
= VarTree::VKarray
;
1161 static bool parseVarSeq(const char*& s
, VarTree
* variable
)
1163 // parse a comma-separated sequence of variables
1164 VarTree
* var
= variable
; /* var != 0 to indicate success if empty seq */
1168 if (strncmp(s
, "<No data fields>}", 17) == 0)
1170 // no member variables, so break out immediately
1171 s
+= 16; /* go to the closing brace */
1176 break; /* syntax error */
1177 variable
->appendChild(var
);
1180 // skip the comma and whitespace
1188 static bool parseValueSeq(const char*& s
, VarTree
* variable
)
1190 // parse a comma-separated sequence of variables
1195 name
.sprintf("[%d]", index
);
1197 VarTree
* var
= new VarTree(name
, VarTree::NKplain
);
1198 var
->setDeleteChildren(true);
1199 good
= parseValue(s
, var
);
1204 variable
->appendChild(var
);
1208 // skip the command and whitespace
1212 // sometimes there is a closing brace after a comma
1219 #if QT_VERSION < 200
1220 #define ISSPACE(c) isspace((c))
1223 #define ISSPACE(c) (c).isSpace()
1226 static bool parseFrame(const char*& s
, int& frameNo
, QString
& func
, QString
& file
, int& lineNo
)
1229 // #1 0x8048881 in Dl::Dl (this=0xbffff418, r=3214) at testfile.cpp:72
1231 // must start with a hash mark followed by number
1232 if (s
[0] != '#' || !isdigit(s
[1]))
1236 p
++; /* skip the hash mark */
1244 // next may be a hexadecimal address
1249 while (isxdigit(*p
))
1251 if (strncmp(p
, " in ", 4) == 0)
1254 const char* start
= p
;
1255 // search opening parenthesis
1256 while (*p
!= '\0' && *p
!= '(')
1266 * Skip parameters. But notice that for complicated conversion
1267 * functions (eg. "operator int(**)()()", ie. convert to pointer to
1268 * pointer to function) as well as operator()(...) we have to skip
1269 * additional pairs of parentheses.
1272 skipNestedWithString(p
, '(', ')');
1275 } while (*p
== '(');
1277 // check for file position
1278 if (strncmp(p
, "at ", 3) == 0) {
1280 const char* fileStart
= p
;
1281 // go for the end of the line
1282 while (*p
!= '\0' && *p
!= '\n')
1284 // search back for colon
1285 const char* colon
= p
;
1288 } while (*colon
!= ':');
1289 file
= FROM_LATIN1(fileStart
, colon
-fileStart
);
1290 lineNo
= atoi(colon
+1)-1;
1295 // check for "from shared lib"
1296 if (strncmp(p
, "from ", 5) == 0) {
1298 // go for the end of the line
1299 while (*p
!= '\0' && *p
!= '\n')
1308 // construct the function name (including file info)
1312 func
= FROM_LATIN1(start
, p
-start
-1); /* don't include \n */
1316 // replace \n (and whitespace around it) in func by a blank
1317 ASSERT(!ISSPACE(func
[0])); /* there must be non-white before first \n */
1319 while ((nl
= func
.find('\n', nl
)) >= 0) {
1320 // search back to the beginning of the whitespace
1321 int startWhite
= nl
;
1324 } while (ISSPACE(func
[startWhite
]));
1326 // search forward to the end of the whitespace
1329 } while (ISSPACE(func
[nl
]));
1331 func
.replace(startWhite
, nl
-startWhite
, " ");
1332 /* continue searching for more \n's at this place: */
1340 void GdbDriver::parseBackTrace(const char* output
, QList
<StackFrame
>& stack
)
1343 int lineNo
, frameNo
;
1345 while (::parseFrame(output
, frameNo
, func
, file
, lineNo
)) {
1346 StackFrame
* frm
= new StackFrame
;
1347 frm
->frameNo
= frameNo
;
1348 frm
->fileName
= file
;
1349 frm
->lineNo
= lineNo
;
1350 frm
->var
= new VarTree(func
, VarTree::NKplain
);
1355 bool GdbDriver::parseFrameChange(const char* output
,
1356 int& frameNo
, QString
& file
, int& lineNo
)
1359 return ::parseFrame(output
, frameNo
, func
, file
, lineNo
);
1363 bool GdbDriver::parseBreakList(const char* output
, QList
<Breakpoint
>& brks
)
1365 // skip first line, which is the headline
1366 const char* p
= strchr(output
, '\n');
1376 uint ignoreCount
= 0;
1380 while (*p
!= '\0') {
1382 long bpNum
= strtol(p
, &dummy
, 10); /* don't care about overflows */
1387 while (*p
!= '\0' && !isspace(*p
)) /* "breakpoint" */
1395 while (*p
!= '\0' && !isspace(*p
)) /* "keep" or "del" */
1403 while (*p
!= '\0' && !isspace(*p
)) /* "y" or "n" */
1409 // remainder is location, hit and ignore count, condition
1412 condition
= QString();
1413 end
= strchr(p
, '\n');
1416 p
+= location
.length();
1418 location
= FROM_LATIN1(p
, end
-p
).stripWhiteSpace();
1419 p
= end
+1; /* skip over \n */
1422 // may be continued in next line
1423 while (isspace(*p
)) { /* p points to beginning of line */
1424 // skip white space at beginning of line
1429 end
= strchr(p
, '\n');
1433 if (strncmp(p
, "breakpoint already hit", 22) == 0) {
1434 // extract the hit count
1436 hits
= strtol(p
, &dummy
, 10);
1437 TRACE(QString().sprintf("hit count %d", hits
));
1438 } else if (strncmp(p
, "stop only if ", 13) == 0) {
1439 // extract condition
1441 condition
= FROM_LATIN1(p
, end
-p
).stripWhiteSpace();
1442 TRACE("condition: "+condition
);
1443 } else if (strncmp(p
, "ignore next ", 12) == 0) {
1444 // extract ignore count
1446 ignoreCount
= strtol(p
, &dummy
, 10);
1447 TRACE(QString().sprintf("ignore count %d", ignoreCount
));
1449 // indeed a continuation
1450 location
+= " " + FROM_LATIN1(p
, end
-p
).stripWhiteSpace();
1454 p
++; /* skip '\n' */
1456 Breakpoint
* bp
= new Breakpoint
;
1458 bp
->temporary
= disp
== 'd';
1459 bp
->enabled
= enable
== 'y';
1460 bp
->location
= location
;
1461 bp
->hitCount
= hits
;
1462 bp
->ignoreCount
= ignoreCount
;
1463 bp
->condition
= condition
;
1469 bool GdbDriver::parseBreakpoint(const char* output
, int& id
,
1470 QString
& file
, int& lineNo
)
1472 const char* o
= output
;
1473 // skip lines of that begin with "(Cannot find"
1474 while (strncmp(o
, "(Cannot find", 12) == 0) {
1475 o
= strchr(o
, '\n');
1478 o
++; /* skip newline */
1481 if (strncmp(o
, "Breakpoint ", 11) != 0)
1485 output
+= 11; /* skip "Breakpoint " */
1487 int num
= strtoul(output
, &p
, 10);
1492 char* fileStart
= strstr(p
, "file ");
1498 char* numStart
= strstr(fileStart
, ", line ");
1499 QString fileName
= FROM_LATIN1(fileStart
, numStart
-fileStart
);
1501 int line
= strtoul(numStart
, &p
, 10);
1507 lineNo
= line
-1; /* zero-based! */
1511 void GdbDriver::parseLocals(const char* output
, QList
<VarTree
>& newVars
)
1513 // check for possible error conditions
1514 if (strncmp(output
, "No symbol table", 15) == 0)
1519 while (*output
!= '\0') {
1520 while (isspace(*output
))
1522 if (*output
== '\0')
1524 // skip occurrences of "No locals" and "No args"
1525 if (strncmp(output
, "No locals", 9) == 0 ||
1526 strncmp(output
, "No arguments", 12) == 0)
1528 output
= strchr(output
, '\n');
1535 VarTree
* variable
= parseVar(output
);
1536 if (variable
== 0) {
1539 // do not add duplicates
1540 for (VarTree
* o
= newVars
.first(); o
!= 0; o
= newVars
.next()) {
1541 if (o
->getText() == variable
->getText()) {
1546 newVars
.append(variable
);
1551 bool GdbDriver::parsePrintExpr(const char* output
, bool wantErrorValue
, VarTree
*& var
)
1553 // check for error conditions
1554 if (parseErrorMessage(output
, var
, wantErrorValue
))
1558 // parse the variable
1559 var
= parseVar(output
);
1564 bool GdbDriver::parseChangeWD(const char* output
, QString
& message
)
1566 bool isGood
= false;
1567 message
= QString(output
).simplifyWhiteSpace();
1568 if (message
.isEmpty()) {
1569 message
= i18n("New working directory: ") + m_programWD
;
1575 bool GdbDriver::parseChangeExecutable(const char* output
, QString
& message
)
1579 m_haveCoreFile
= false;
1582 * The command is successful if there is no output or the single
1583 * message (no debugging symbols found)...
1586 output
[0] == '\0' ||
1587 strcmp(output
, "(no debugging symbols found)...") == 0;
1590 bool GdbDriver::parseCoreFile(const char* output
)
1592 // if command succeeded, gdb emits a line starting with "#0 "
1593 m_haveCoreFile
= strstr(output
, "\n#0 ") != 0;
1594 return m_haveCoreFile
;
1597 uint
GdbDriver::parseProgramStopped(const char* output
, QString
& message
)
1599 // optionally: "program changed, rereading symbols",
1601 // "Program exited normally"
1602 // "Program terminated with wignal SIGSEGV"
1603 // "Program received signal SIGINT" or other signal
1606 // go through the output, line by line, checking what we have
1607 const char* start
= output
- 1;
1608 uint flags
= SFprogramActive
;
1609 message
= QString();
1611 start
++; /* skip '\n' */
1613 if (strncmp(start
, "Program ", 8) == 0 ||
1614 strncmp(start
, "ptrace: ", 8) == 0) {
1616 * When we receive a signal, the program remains active.
1618 * Special: If we "stopped" in a corefile, the string "Program
1619 * terminated with signal"... is displayed. (Normally, we see
1620 * "Program received signal"... when a signal happens.)
1622 if (strncmp(start
, "Program exited", 14) == 0 ||
1623 (strncmp(start
, "Program terminated", 18) == 0 && !m_haveCoreFile
) ||
1624 strncmp(start
, "ptrace: ", 8) == 0)
1626 flags
&= ~SFprogramActive
;
1630 const char* endOfMessage
= strchr(start
, '\n');
1631 if (endOfMessage
== 0)
1632 endOfMessage
= start
+ strlen(start
);
1633 message
= FROM_LATIN1(start
, endOfMessage
-start
);
1634 } else if (strncmp(start
, "Breakpoint ", 11) == 0) {
1636 * We stopped at a (permanent) breakpoint (gdb doesn't tell us
1637 * that it stopped at a temporary breakpoint).
1639 flags
|= SFrefreshBreak
;
1640 } else if (strstr(start
, "re-reading symbols.") != 0) {
1641 flags
|= SFrefreshSource
;
1644 // next line, please
1645 start
= strchr(start
, '\n');
1646 } while (start
!= 0);
1651 void GdbDriver::parseSharedLibs(const char* output
, QStrList
& shlibs
)
1653 if (strncmp(output
, "No shared libraries loaded", 26) == 0)
1656 // parse the table of shared libraries
1658 // strip off head line
1659 output
= strchr(output
, '\n');
1662 output
++; /* skip '\n' */
1664 while (*output
!= '\0') {
1665 // format of a line is
1666 // 0x404c5000 0x40580d90 Yes /lib/libc.so.5
1667 // 3 blocks of non-space followed by space
1668 for (int i
= 0; *output
!= '\0' && i
< 3; i
++) {
1669 while (*output
!= '\0' && !isspace(*output
)) { /* non-space */
1672 while (isspace(*output
)) { /* space */
1676 if (*output
== '\0')
1678 const char* start
= output
;
1679 output
= strchr(output
, '\n');
1681 output
= start
+ strlen(start
);
1682 shlibName
= FROM_LATIN1(start
, output
-start
);
1683 if (*output
!= '\0')
1685 shlibs
.append(shlibName
);
1686 TRACE("found shared lib " + shlibName
);
1690 bool GdbDriver::parseFindType(const char* output
, QString
& type
)
1692 if (strncmp(output
, "type = ", 7) != 0)
1696 * Everything else is the type. We strip off all white-space from the
1701 type
.replace(QRegExp("\\s+"), "");
1705 void GdbDriver::parseRegisters(const char* output
, QList
<RegisterInfo
>& regs
)
1707 if (strncmp(output
, "The program has no registers now", 32) == 0) {
1714 // parse register values
1715 while (*output
!= '\0')
1717 // skip space at the start of the line
1718 while (isspace(*output
))
1722 const char* start
= output
;
1723 while (*output
!= '\0' && !isspace(*output
))
1725 if (*output
== '\0')
1727 regName
= FROM_LATIN1(start
, output
-start
);
1730 while (isspace(*output
))
1732 // the rest of the line is the register value
1734 output
= strchr(output
,'\n');
1736 output
= start
+ strlen(start
);
1737 value
= FROM_LATIN1(start
, output
-start
).simplifyWhiteSpace();
1739 if (*output
!= '\0')
1740 output
++; /* skip '\n' */
1742 RegisterInfo
* reg
= new RegisterInfo
;
1743 reg
->regName
= regName
;
1746 * We split the raw from the cooked values. For this purpose, we
1747 * split off the first token (separated by whitespace). It is the
1748 * raw value. The remainder of the line is the cooked value.
1750 int pos
= value
.find(' ');
1752 reg
->rawValue
= value
;
1753 reg
->cookedValue
= QString();
1755 reg
->rawValue
= value
.left(pos
);
1756 reg
->cookedValue
= value
.mid(pos
+1,value
.length());
1758 * Some modern gdbs explicitly say: "0.1234 (raw 0x3e4567...)".
1759 * Here the raw value is actually in the second part.
1761 if (reg
->cookedValue
.left(5) == "(raw ") {
1762 QString raw
= reg
->cookedValue
.right(reg
->cookedValue
.length()-5);
1763 if (raw
[raw
.length()-1] == ')') /* remove closing bracket */
1764 raw
= raw
.left(raw
.length()-1);
1765 reg
->cookedValue
= reg
->rawValue
;
1766 reg
->rawValue
= raw
;
1775 #include "gdbdriver.moc"