gdbengine.cpp 161 KB
Newer Older
1
/**************************************************************************
con's avatar
con committed
2
3
4
**
** This file is part of Qt Creator
**
hjk's avatar
hjk committed
5
** Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
con's avatar
con committed
6
**
7
** Contact: Nokia Corporation (qt-info@nokia.com)
con's avatar
con committed
8
**
9
** Commercial Usage
10
**
11
12
13
14
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
15
**
16
** GNU Lesser General Public License Usage
17
**
18
19
20
21
22
23
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
24
**
25
** If you are unsure which license is appropriate for your use, please
hjk's avatar
hjk committed
26
** contact the sales department at http://qt.nokia.com/contact.
con's avatar
con committed
27
**
28
**************************************************************************/
con's avatar
con committed
29

30
31
#define QT_NO_CAST_FROM_ASCII

con's avatar
con committed
32
#include "gdbengine.h"
33

34
35
#include "attachgdbadapter.h"
#include "coregdbadapter.h"
ck's avatar
ck committed
36
#include "localplaingdbadapter.h"
37
#include "termgdbadapter.h"
ck's avatar
ck committed
38
39
#include "remotegdbserveradapter.h"
#include "remoteplaingdbadapter.h"
40
#include "trkgdbadapter.h"
41
#include "tcftrkgdbadapter.h"
con's avatar
con committed
42

43
#include "debuggeractions.h"
con's avatar
con committed
44
#include "debuggerconstants.h"
45
46
47
#include "debuggercore.h"
#include "debuggerplugin.h"
#include "debuggerrunner.h"
48
#include "debuggerstringutils.h"
49
50
#include "debuggertooltip.h"
#include "disassembleragent.h"
con's avatar
con committed
51
#include "gdbmi.h"
52
53
54
#include "gdboptionspage.h"
#include "memoryagent.h"
#include "watchutils.h"
con's avatar
con committed
55
56
57
58

#include "breakhandler.h"
#include "moduleshandler.h"
#include "registerhandler.h"
59
#include "snapshothandler.h"
60
#include "sourcefileshandler.h"
con's avatar
con committed
61
#include "stackhandler.h"
hjk's avatar
hjk committed
62
#include "threadshandler.h"
con's avatar
con committed
63
#include "watchhandler.h"
64

65
#include "logwindow.h"
con's avatar
con committed
66

67
#include <coreplugin/icore.h>
68
69
70
#include <projectexplorer/toolchain.h>
#include <texteditor/itexteditor.h>
#include <utils/qtcassert.h>
hjk's avatar
hjk committed
71

72
#include <QtCore/QCoreApplication>
con's avatar
con committed
73
74
75
#include <QtCore/QDebug>
#include <QtCore/QDir>
#include <QtCore/QFileInfo>
76
#include <QtCore/QMetaObject>
con's avatar
con committed
77
78
#include <QtCore/QTime>
#include <QtCore/QTimer>
79
#include <QtCore/QTemporaryFile>
80
#include <QtCore/QTextStream>
con's avatar
con committed
81
82

#include <QtGui/QAction>
83
#include <QtGui/QDialogButtonBox>
con's avatar
con committed
84
85
86
#include <QtGui/QLabel>
#include <QtGui/QMainWindow>
#include <QtGui/QMessageBox>
87
#include <QtGui/QPushButton>
con's avatar
con committed
88

Oswald Buddenhagen's avatar
Oswald Buddenhagen committed
89
#ifdef Q_OS_UNIX
con's avatar
con committed
90
91
92
#include <unistd.h>
#include <dlfcn.h>
#endif
hjk's avatar
hjk committed
93
#include <ctype.h>
con's avatar
con committed
94

95

96
97
namespace Debugger {
namespace Internal {
con's avatar
con committed
98
99
100

//#define DEBUG_PENDING  1

101
102
static const char winPythonVersionC[] = "python2.5";

con's avatar
con committed
103
104
105
#if DEBUG_PENDING
#   define PENDING_DEBUG(s) qDebug() << s
#else
Roberto Raggi's avatar
Roberto Raggi committed
106
#   define PENDING_DEBUG(s)
con's avatar
con committed
107
#endif
108
#define PENDING_DEBUGX(s) qDebug() << s
con's avatar
con committed
109

110
111
#define CB(callback) &GdbEngine::callback, STRINGIFY(callback)

112
QByteArray GdbEngine::tooltipIName(const QString &exp)
113
{
114
    return "tooltip." + exp.toLatin1().toHex();
115
116
}

hjk's avatar
hjk committed
117
static bool stateAcceptsGdbCommands(DebuggerState state)
hjk's avatar
hjk committed
118
{
Oswald Buddenhagen's avatar
Oswald Buddenhagen committed
119
    switch (state) {
hjk's avatar
hjk committed
120
    case EngineSetupRequested:
121
122
    case EngineSetupOk:
    case EngineSetupFailed:
Oswald Buddenhagen's avatar
Oswald Buddenhagen committed
123
    case InferiorUnrunnable:
hjk's avatar
hjk committed
124
    case InferiorSetupRequested:
hjk's avatar
hjk committed
125
    case InferiorSetupFailed:
hjk's avatar
hjk committed
126
127
128
129
130
131
132
133
    case EngineRunRequested:
    case InferiorRunRequested:
    case InferiorRunOk:
    case InferiorStopRequested:
    case InferiorStopOk:
    case InferiorShutdownRequested:
    case EngineShutdownRequested:
    case InferiorShutdownOk:
Oswald Buddenhagen's avatar
Oswald Buddenhagen committed
134
135
136
137
    case InferiorShutdownFailed:
        return true;
    case DebuggerNotReady:
    case InferiorStopFailed:
hjk's avatar
hjk committed
138
139
140
141
142
    case EngineRunFailed:
    case InferiorRunFailed:
    case EngineShutdownOk:
    case EngineShutdownFailed:
    case DebuggerFinished:
143
        return false;
Oswald Buddenhagen's avatar
Oswald Buddenhagen committed
144
145
146
    }
    return false;
}
hjk's avatar
hjk committed
147

con's avatar
con committed
148
149
150
151
152
153
static int &currentToken()
{
    static int token = 0;
    return token;
}

hjk's avatar
hjk committed
154
static QByteArray parsePlainConsoleStream(const GdbResponse &response)
155
{
hjk's avatar
hjk committed
156
    GdbMi output = response.data.findChild("consolestreamoutput");
157
158
159
160
161
162
163
164
165
166
    QByteArray out = output.data();
    // FIXME: proper decoding needed
    if (out.endsWith("\\n"))
        out.chop(2);
    while (out.endsWith('\n') || out.endsWith(' '))
        out.chop(1);
    int pos = out.indexOf(" = ");
    return out.mid(pos + 3);
}

con's avatar
con committed
167
168
169
170
171
172
///////////////////////////////////////////////////////////////////////
//
// GdbEngine
//
///////////////////////////////////////////////////////////////////////

173
174
GdbEngine::GdbEngine(const DebuggerStartParameters &startParameters)
  : DebuggerEngine(startParameters)
con's avatar
con committed
175
{
Friedemann Kleint's avatar
Friedemann Kleint committed
176
    setObjectName(QLatin1String("GdbEngine"));
177
178
    qRegisterMetaType<WatchData>("WatchData");

179
    m_busy = false;
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
    m_gdbAdapter = 0;
    m_debuggingHelperState = DebuggingHelperUninitialized;
    m_gdbVersion = 100;
    m_gdbBuildVersion = -1;
    m_isMacGdb = false;
    m_hasPython = false;
    m_registerNamesListed = false;
    m_hasInferiorThreadList = false;
    m_sourcesListUpdating = false;
    m_oldestAcceptableToken = -1;
    m_outputCodec = QTextCodec::codecForLocale();
    m_pendingWatchRequests = 0;
    m_pendingBreakpointRequests = 0;
    m_commandsDoneCallback = 0;
    invalidateSourcesList();

ck's avatar
ck committed
196
    m_gdbAdapter = createAdapter();
197

198
199
200
    m_commandTimer.setSingleShot(true);
    connect(&m_commandTimer, SIGNAL(timeout()), SLOT(commandTimeout()));

hjk's avatar
hjk committed
201
    connect(debuggerCore()->action(AutoDerefPointers), SIGNAL(valueChanged(QVariant)),
202
            SLOT(reloadLocals()));
hjk's avatar
hjk committed
203
    connect(debuggerCore()->action(SortStructMembers), SIGNAL(valueChanged(QVariant)),
204
            SLOT(reloadLocals()));
hjk's avatar
hjk committed
205
    connect(debuggerCore()->action(CreateFullBacktrace), SIGNAL(triggered()),
206
            SLOT(createFullBacktrace()));
207
}
208

209
210
DebuggerStartMode GdbEngine::startMode() const
{
211
    return startParameters().startMode;
con's avatar
con committed
212
213
}

ck's avatar
ck committed
214
215
216
217
218
AbstractGdbProcess *GdbEngine::gdbProc() const
{
    return m_gdbAdapter->gdbProc();
}

con's avatar
con committed
219
220
GdbEngine::~GdbEngine()
{
221
    // Prevent sending error messages afterwards.
ck's avatar
ck committed
222
223
    if (m_gdbAdapter)
        disconnect(gdbProc(), 0, this, 0);
224
    delete m_gdbAdapter;
225
    m_gdbAdapter = 0;
hjk's avatar
hjk committed
226
227
}

228
QString GdbEngine::errorMessage(QProcess::ProcessError error)
con's avatar
con committed
229
230
231
{
    switch (error) {
        case QProcess::FailedToStart:
232
            return tr("The Gdb process failed to start. Either the "
con's avatar
con committed
233
                "invoked program '%1' is missing, or you may have insufficient "
234
235
                "permissions to invoke the program.\n%2")
                .arg(m_gdb, gdbProc()->errorString());
con's avatar
con committed
236
        case QProcess::Crashed:
237
            return tr("The Gdb process crashed some time after starting "
con's avatar
con committed
238
239
                "successfully.");
        case QProcess::Timedout:
240
            return tr("The last waitFor...() function timed out. "
con's avatar
con committed
241
242
243
                "The state of QProcess is unchanged, and you can try calling "
                "waitFor...() again.");
        case QProcess::WriteError:
244
            return tr("An error occurred when attempting to write "
con's avatar
con committed
245
246
247
                "to the Gdb process. For example, the process may not be running, "
                "or it may have closed its input channel.");
        case QProcess::ReadError:
248
            return tr("An error occurred when attempting to read from "
con's avatar
con committed
249
250
                "the Gdb process. For example, the process may not be running.");
        default:
251
            return tr("An unknown error in the Gdb process occurred. ");
con's avatar
con committed
252
253
254
255
256
257
258
    }
}

#if 0
static void dump(const char *first, const char *middle, const QString & to)
{
    QByteArray ba(first, middle - first);
259
    Q_UNUSED(to)
con's avatar
con committed
260
261
262
263
264
265
266
267
268
269
270
    // note that qDebug cuts off output after a certain size... (bug?)
    qDebug("\n>>>>> %s\n%s\n====\n%s\n<<<<<\n",
        qPrintable(currentTime()),
        qPrintable(QString(ba).trimmed()),
        qPrintable(to.trimmed()));
    //qDebug() << "";
    //qDebug() << qPrintable(currentTime())
    //    << " Reading response:  " << QString(ba).trimmed() << "\n";
}
#endif

271
272
void GdbEngine::readDebugeeOutput(const QByteArray &data)
{
273
274
275
    QString msg = m_outputCodec->toUnicode(data.constData(), data.length(),
        &m_outputCodecState);
    showMessage(msg, AppStuff);
276
277
}

278
void GdbEngine::handleResponse(const QByteArray &buff)
con's avatar
con committed
279
{
280
    showMessage(QString::fromLocal8Bit(buff, buff.length()), LogOutput);
con's avatar
con committed
281
282

#if 0
283
    static QTime lastTime;
con's avatar
con committed
284
285
    qDebug() // << "#### start response handling #### "
        << lastTime.msecsTo(QTime::currentTime()) << "ms,"
286
287
        << "buf:" << buff.left(1500) << "..."
        //<< "buf:" << buff
288
        << "size:" << buff.size();
289
    lastTime = QTime::currentTime();
con's avatar
con committed
290
#else
291
    //qDebug() << "buf:" << buff;
con's avatar
con committed
292
#endif
293
294
    if (buff.isEmpty() || buff == "(gdb) ")
        return;
con's avatar
con committed
295

296
297
298
    const char *from = buff.constData();
    const char *to = from + buff.size();
    const char *inner;
con's avatar
con committed
299

300
301
302
303
    int token = -1;
    // token is a sequence of numbers
    for (inner = from; inner != to; ++inner)
        if (*inner < '0' || *inner > '9')
con's avatar
con committed
304
            break;
305
306
307
    if (from != inner) {
        token = QByteArray(from, inner - from).toInt();
        from = inner;
308
        //qDebug() << "found token" << token;
309
    }
con's avatar
con committed
310

hjk's avatar
hjk committed
311
    // next char decides kind of response
312
313
314
315
316
317
318
319
320
321
322
323
324
325
    const char c = *from++;
    //qDebug() << "CODE:" << c;
    switch (c) {
        case '*':
        case '+':
        case '=': {
            QByteArray asyncClass;
            for (; from != to; ++from) {
                const char c = *from;
                if (!isNameChar(c))
                    break;
                asyncClass += *from;
            }
            //qDebug() << "ASYNCCLASS" << asyncClass;
con's avatar
con committed
326

hjk's avatar
hjk committed
327
            GdbMi result;
328
329
            while (from != to) {
                GdbMi data;
hjk's avatar
hjk committed
330
                if (*from != ',') {
331
332
                    // happens on archer where we get
                    // 23^running <NL> *running,thread-id="all" <NL> (gdb)
hjk's avatar
hjk committed
333
                    result.m_type = GdbMi::Tuple;
hjk's avatar
hjk committed
334
335
336
337
338
                    break;
                }
                ++from; // skip ','
                data.parseResultOrValue(from, to);
                if (data.isValid()) {
hjk's avatar
hjk committed
339
340
341
                    //qDebug() << "parsed result:" << data.toString();
                    result.m_children += data;
                    result.m_type = GdbMi::Tuple;
con's avatar
con committed
342
343
                }
            }
344
            if (asyncClass == "stopped") {
345
                handleStopResponse(result);
346
347
                m_pendingLogStreamOutput.clear();
                m_pendingConsoleStreamOutput.clear();
348
349
            } else if (asyncClass == "running") {
                // Archer has 'thread-id="all"' here
350
351
352
353
            } else if (asyncClass == "library-loaded") {
                // Archer has 'id="/usr/lib/libdrm.so.2",
                // target-name="/usr/lib/libdrm.so.2",
                // host-name="/usr/lib/libdrm.so.2",
354
                // symbols-loaded="0"
hjk's avatar
hjk committed
355
                QByteArray id = result.findChild("id").data();
356
                if (!id.isEmpty())
357
                    showStatusMessage(tr("Library %1 loaded").arg(_(id)), 1000);
358
                progressPing();
359
                invalidateSourcesList();
hjk's avatar
hjk committed
360
361
362
363
            } else if (asyncClass == "library-unloaded") {
                // Archer has 'id="/usr/lib/libdrm.so.2",
                // target-name="/usr/lib/libdrm.so.2",
                // host-name="/usr/lib/libdrm.so.2"
hjk's avatar
hjk committed
364
                QByteArray id = result.findChild("id").data();
365
                progressPing();
366
                showStatusMessage(tr("Library %1 unloaded").arg(_(id)), 1000);
367
                invalidateSourcesList();
368
369
            } else if (asyncClass == "thread-group-added") {
                // 7.1-symbianelf has "{id="i1"}"
370
371
372
            } else if (asyncClass == "thread-group-created"
                    || asyncClass == "thread-group-started") {
                // Archer had only "{id="28902"}" at some point of 6.8.x.
hjk's avatar
hjk committed
373
374
                // *-started seems to be standard in 7.1, but in early
                // 7.0.x, there was a *-created instead.
375
                progressPing();
ck's avatar
ck committed
376
                // 7.1.50 has thread-group-started,id="i1",pid="3529"
hjk's avatar
hjk committed
377
                QByteArray id = result.findChild("id").data();
378
                showStatusMessage(tr("Thread group %1 created").arg(_(id)), 1000);
ck's avatar
ck committed
379
380
381
382
383
384
385
                int pid = id.toInt();
                if (!pid) {
                    id = result.findChild("pid").data();
                    pid = id.toInt();
                }
                if (pid)
                    notifyInferiorPid(pid);
386
            } else if (asyncClass == "thread-created") {
387
                //"{id="1",group-id="28902"}"
hjk's avatar
hjk committed
388
                QByteArray id = result.findChild("id").data();
389
                showStatusMessage(tr("Thread %1 created").arg(_(id)), 1000);
390
            } else if (asyncClass == "thread-group-exited") {
391
                // Archer has "{id="28902"}"
hjk's avatar
hjk committed
392
                QByteArray id = result.findChild("id").data();
393
                showStatusMessage(tr("Thread group %1 exited").arg(_(id)), 1000);
394
            } else if (asyncClass == "thread-exited") {
395
                //"{id="1",group-id="28902"}"
hjk's avatar
hjk committed
396
397
                QByteArray id = result.findChild("id").data();
                QByteArray groupid = result.findChild("group-id").data();
398
                showStatusMessage(tr("Thread %1 in group %2 exited")
hjk's avatar
hjk committed
399
                    .arg(_(id)).arg(_(groupid)), 1000);
hjk's avatar
hjk committed
400
            } else if (asyncClass == "thread-selected") {
hjk's avatar
hjk committed
401
                QByteArray id = result.findChild("id").data();
402
                showStatusMessage(tr("Thread %1 selected").arg(_(id)), 1000);
403
                //"{id="2"}"
404
405
            } else if (m_isMacGdb && asyncClass == "shlibs-updated") {
                // Apple's gdb announces updated libs.
406
                invalidateSourcesList();
407
408
            } else if (m_isMacGdb && asyncClass == "shlibs-added") {
                // Apple's gdb announces added libs.
409
410
411
412
413
                // {shlib-info={num="2", name="libmathCommon.A_debug.dylib",
                // kind="-", dyld-addr="0x7f000", reason="dyld", requested-state="Y",
                // state="Y", path="/usr/lib/system/libmathCommon.A_debug.dylib",
                // description="/usr/lib/system/libmathCommon.A_debug.dylib",
                // loaded_addr="0x7f000", slide="0x7f000", prefix=""}}
414
                invalidateSourcesList();
415
416
417
418
419
            } else if (m_isMacGdb && asyncClass == "resolve-pending-breakpoint") {
                // Apple's gdb announces resolved breakpoints.
                // new_bp="1",pended_bp="1",new_expr="\"gdbengine.cpp\":1584",
                // bkpt={number="1",type="breakpoint",disp="keep",enabled="y",
                // addr="0x0000000115cc3ddf",func="foo()",file="../foo.cpp",
420
                // line="1584",shlib="/../libFoo_debug.dylib",times="0"}
421
422
                const GdbMi bkpt = result.findChild("bkpt");
                const int number = bkpt.findChild("number").data().toInt();
hjk's avatar
hjk committed
423
                BreakpointId id = breakHandler()->findBreakpointByNumber(number);
424
                updateBreakpointDataFromOutput(id, bkpt);
425
            } else {
426
                qDebug() << "IGNORED ASYNC OUTPUT"
hjk's avatar
hjk committed
427
                    << asyncClass << result.toString();
428
            }
429
430
            break;
        }
431

432
        case '~': {
433
434
            QByteArray data = GdbMi::parseCString(from, to);
            m_pendingConsoleStreamOutput += data;
435
436

            // Parse pid from noise.
437
            if (!inferiorPid()) {
438
439
440
441
                // Linux/Mac gdb: [New [Tt]hread 0x545 (LWP 4554)]
                static QRegExp re1(_("New .hread 0x[0-9a-f]+ \\(LWP ([0-9]*)\\)"));
                // MinGW 6.8: [New thread 2437.0x435345]
                static QRegExp re2(_("New .hread ([0-9]+)\\.0x[0-9a-f]*"));
hjk's avatar
hjk committed
442
443
444
                // Mac: [Switching to process 9294 local thread 0x2e03] or
                // [Switching to process 31773]
                static QRegExp re3(_("Switching to process ([0-9]+)"));
445
446
447
448
449
                QTC_ASSERT(re1.isValid() && re2.isValid(), return);
                if (re1.indexIn(_(data)) != -1)
                    maybeHandleInferiorPidChanged(re1.cap(1));
                else if (re2.indexIn(_(data)) != -1)
                    maybeHandleInferiorPidChanged(re2.cap(1));
450
451
                else if (re3.indexIn(_(data)) != -1)
                    maybeHandleInferiorPidChanged(re3.cap(1));
452
            }
453
454

            // Show some messages to give the impression something happens.
455
            if (data.startsWith("Reading symbols from ")) {
456
                showStatusMessage(tr("Reading %1...").arg(_(data.mid(21))), 1000);
457
                progressPing();
458
                invalidateSourcesList();
459
460
461
            } else if (data.startsWith("[New ") || data.startsWith("[Thread ")) {
                if (data.endsWith('\n'))
                    data.chop(1);
462
                progressPing();
463
                showStatusMessage(_(data), 1000);
464
            }
465
466
            break;
        }
467

468
        case '@': {
469
            readDebugeeOutput(GdbMi::parseCString(from, to));
470
            break;
con's avatar
con committed
471
472
        }

473
474
475
476
477
478
        case '&': {
            QByteArray data = GdbMi::parseCString(from, to);
            m_pendingLogStreamOutput += data;
            // On Windows, the contents seem to depend on the debugger
            // version and/or OS version used.
            if (data.startsWith("warning:"))
479
                showMessage(_(data.mid(9)), AppStuff); // Cut "warning: "
con's avatar
con committed
480
481
482
            break;
        }

483
        case '^': {
hjk's avatar
hjk committed
484
            GdbResponse response;
con's avatar
con committed
485

hjk's avatar
hjk committed
486
            response.token = token;
con's avatar
con committed
487

488
489
490
            for (inner = from; inner != to; ++inner)
                if (*inner < 'a' || *inner > 'z')
                    break;
con's avatar
con committed
491

Oswald Buddenhagen's avatar
Oswald Buddenhagen committed
492
            QByteArray resultClass = QByteArray::fromRawData(from, inner - from);
493
            if (resultClass == "done") {
hjk's avatar
hjk committed
494
                response.resultClass = GdbResultDone;
495
            } else if (resultClass == "running") {
hjk's avatar
hjk committed
496
                response.resultClass = GdbResultRunning;
497
            } else if (resultClass == "connected") {
hjk's avatar
hjk committed
498
                response.resultClass = GdbResultConnected;
499
            } else if (resultClass == "error") {
hjk's avatar
hjk committed
500
                response.resultClass = GdbResultError;
501
            } else if (resultClass == "exit") {
hjk's avatar
hjk committed
502
                response.resultClass = GdbResultExit;
503
            } else {
hjk's avatar
hjk committed
504
                response.resultClass = GdbResultUnknown;
505
            }
con's avatar
con committed
506

507
508
            from = inner;
            if (from != to) {
hjk's avatar
hjk committed
509
510
                if (*from == ',') {
                    ++from;
hjk's avatar
hjk committed
511
512
513
                    response.data.parseTuple_helper(from, to);
                    response.data.m_type = GdbMi::Tuple;
                    response.data.m_name = "data";
hjk's avatar
hjk committed
514
                } else {
515
                    // Archer has this.
hjk's avatar
hjk committed
516
517
                    response.data.m_type = GdbMi::Tuple;
                    response.data.m_name = "data";
con's avatar
con committed
518
519
                }
            }
520
521
522

            //qDebug() << "\nLOG STREAM:" + m_pendingLogStreamOutput;
            //qDebug() << "\nCONSOLE STREAM:" + m_pendingConsoleStreamOutput;
hjk's avatar
hjk committed
523
            response.data.setStreamOutput("logstreamoutput",
524
                m_pendingLogStreamOutput);
hjk's avatar
hjk committed
525
            response.data.setStreamOutput("consolestreamoutput",
526
527
528
529
                m_pendingConsoleStreamOutput);
            m_pendingLogStreamOutput.clear();
            m_pendingConsoleStreamOutput.clear();

530
            handleResultRecord(&response);
531
532
533
534
535
            break;
        }
        default: {
            qDebug() << "UNKNOWN RESPONSE TYPE" << c;
            break;
con's avatar
con committed
536
537
538
539
540
541
        }
    }
}

void GdbEngine::readGdbStandardError()
{
ck's avatar
ck committed
542
    QByteArray err = gdbProc()->readAllStandardError();
543
    showMessage(_("UNEXPECTED GDB STDERR: " + err));
544
545
    if (err == "Undefined command: \"bb\".  Try \"help\".\n")
        return;
546
547
    if (err.startsWith("BFD: reopening"))
        return;
548
    qWarning() << "Unexpected gdb stderr:" << err;
con's avatar
con committed
549
550
551
552
}

void GdbEngine::readGdbStandardOutput()
{
553
    m_commandTimer.start(); // Restart timer.
554

555
556
    int newstart = 0;
    int scan = m_inbuffer.size();
con's avatar
con committed
557

ck's avatar
ck committed
558
    m_inbuffer.append(gdbProc()->readAllStandardOutput());
con's avatar
con committed
559

560
    // This can trigger when a dialog starts a nested event loop.
561
562
563
    if (m_busy)
        return;

564
565
    while (newstart < m_inbuffer.size()) {
        int start = newstart;
566
        int end = m_inbuffer.indexOf('\n', scan);
567
568
569
570
571
        if (end < 0) {
            m_inbuffer.remove(0, start);
            return;
        }
        newstart = end + 1;
572
        scan = newstart;
573
574
        if (end == start)
            continue;
Tobias Hunger's avatar
Tobias Hunger committed
575
#        if defined(Q_OS_WIN)
576
577
578
579
580
        if (m_inbuffer.at(end - 1) == '\r') {
            --end;
            if (end == start)
                continue;
        }
Tobias Hunger's avatar
Tobias Hunger committed
581
#        endif
582
        m_busy = true;
583
        handleResponse(QByteArray::fromRawData(m_inbuffer.constData() + start, end - start));
584
        m_busy = false;
con's avatar
con committed
585
    }
586
    m_inbuffer.clear();
con's avatar
con committed
587
588
589
590
}

void GdbEngine::interruptInferior()
{
hjk's avatar
hjk committed
591
    QTC_ASSERT(state() == InferiorStopRequested, qDebug() << state(); return);
hjk's avatar
hjk committed
592
    showStatusMessage(tr("Stop requested..."), 5000);
593
    showMessage(_("TRYING TO INTERRUPT INFERIOR"));
hjk's avatar
hjk committed
594
    m_gdbAdapter->interruptInferior();
con's avatar
con committed
595
596
}

597
598
void GdbEngine::interruptInferiorTemporarily()
{
599
    foreach (const GdbCommand &cmd, m_commandsToRunOnTemporaryBreak) {
600
        if (cmd.flags & LosesChild) {
hjk's avatar
hjk committed
601
            notifyInferiorIll();
602
            return;
603
        }
604
    }
605
    requestInterruptInferior();
606
607
}

con's avatar
con committed
608
609
void GdbEngine::maybeHandleInferiorPidChanged(const QString &pid0)
{
610
    const qint64 pid = pid0.toLongLong();
con's avatar
con committed
611
    if (pid == 0) {
612
        showMessage(_("Cannot parse PID from %1").arg(pid0));
con's avatar
con committed
613
614
        return;
    }
615
    if (pid == inferiorPid())
con's avatar
con committed
616
        return;
617

618
619
    showMessage(_("FOUND PID %1").arg(pid));
    notifyInferiorPid(pid);
con's avatar
con committed
620
621
}

622
void GdbEngine::postCommand(const QByteArray &command, AdapterCallback callback,
hjk's avatar
hjk committed
623
                            const char *callbackName, const QVariant &cookie)
624
625
626
627
{
    postCommand(command, NoFlags, callback, callbackName, cookie);
}

628
void GdbEngine::postCommand(const QByteArray &command, GdbCommandFlags flags,
629
630
                            AdapterCallback callback,
                            const char *callbackName, const QVariant &cookie)
hjk's avatar
hjk committed
631
632
633
{
    GdbCommand cmd;
    cmd.command = command;
634
    cmd.flags = flags;
hjk's avatar
hjk committed
635
636
637
638
639
640
    cmd.adapterCallback = callback;
    cmd.callbackName = callbackName;
    cmd.cookie = cookie;
    postCommandHelper(cmd);
}

641
void GdbEngine::postCommand(const QByteArray &command, GdbCommandCallback callback,
642
643
                            const char *callbackName, const QVariant &cookie)
{
644
    postCommand(command, NoFlags, callback, callbackName, cookie);
645
646
}

647
void GdbEngine::postCommand(const QByteArray &command, GdbCommandFlags flags,
648
649
                            GdbCommandCallback callback, const char *callbackName,
                            const QVariant &cookie)
hjk's avatar
hjk committed
650
651
652
653
654
655
656
657
658
659
660
{
    GdbCommand cmd;
    cmd.command = command;
    cmd.flags = flags;
    cmd.callback = callback;
    cmd.callbackName = callbackName;
    cmd.cookie = cookie;
    postCommandHelper(cmd);
}

void GdbEngine::postCommandHelper(const GdbCommand &cmd)
con's avatar
con committed
661
{
hjk's avatar
hjk committed
662
    if (!stateAcceptsGdbCommands(state())) {
663
        PENDING_DEBUG(_("NO GDB PROCESS RUNNING, CMD IGNORED: " + cmd.command));
664
        showMessage(_("NO GDB PROCESS RUNNING, CMD IGNORED: %1 %2")
665
            .arg(_(cmd.command)).arg(state()));
con's avatar
con committed
666
667
668
        return;
    }

669
670
    if (cmd.flags & RebuildWatchModel) {
        ++m_pendingWatchRequests;
671
        PENDING_DEBUG("   WATCH MODEL:" << cmd.command << "=>" << cmd.callbackName
672
                      << "INCREMENTS PENDING TO" << m_pendingWatchRequests);
673
674
675
676
    } else if (cmd.flags & RebuildBreakpointModel) {
        ++m_pendingBreakpointRequests;
        PENDING_DEBUG("   BRWAKPOINT MODEL:" << cmd.command << "=>" << cmd.callbackName
                      << "INCREMENTS PENDING TO" << m_pendingBreakpointRequests);
con's avatar
con committed
677
    } else {
678
        PENDING_DEBUG("   OTHER (IN):" << cmd.command << "=>" << cmd.callbackName
679
680
                      << "LEAVES PENDING WATCH AT" << m_pendingWatchRequests
                      << "LEAVES PENDING BREAKPOINT AT" << m_pendingBreakpointRequests);
con's avatar
con committed
681
682
    }

683
684
685
686
687
688
    // FIXME: clean up logic below
    if (cmd.flags & Immediate) {
        // This should always be sent.
        flushCommand(cmd);
    } else if ((cmd.flags & NeedsStop)
            || !m_commandsToRunOnTemporaryBreak.isEmpty()) {
hjk's avatar
hjk committed
689
690
691
        if (state() == InferiorStopOk || state() == InferiorUnrunnable
            || state() == InferiorSetupRequested || state() == EngineSetupOk
            || state() == InferiorShutdownRequested) {
hjk's avatar
hjk committed
692
693
694
695
            // Can be safely sent now.
            flushCommand(cmd);
        } else {
            // Queue the commands that we cannot send at once.
696
            showMessage(_("QUEUING COMMAND " + cmd.command));
hjk's avatar
hjk committed
697
            m_commandsToRunOnTemporaryBreak.append(cmd);
hjk's avatar
hjk committed
698
699
700
701
            if (state() == InferiorStopRequested) {
                if (cmd.flags & LosesChild) {
                    notifyInferiorIll();
                }
702
                showMessage(_("CHILD ALREADY BEING INTERRUPTED. STILL HOPING."));
703
704
                // Calling shutdown() here breaks all situations where two
                // NeedsStop commands are issued in quick succession.
hjk's avatar
hjk committed
705
            } else if (state() == InferiorRunOk) {
706
                showStatusMessage(tr("Stopping temporarily"), 1000);
707
                interruptInferiorTemporarily();
708
            } else {
hjk's avatar
hjk committed
709
710
                qDebug() << "ATTEMPTING TO QUEUE COMMAND "
                    << cmd.command << "IN INAPPROPRIATE STATE" << state();
711
            }
hjk's avatar
hjk committed
712
        }
hjk's avatar
hjk committed
713
    } else if (!cmd.command.isEmpty()) {
714
        flushCommand(cmd);
con's avatar
con committed
715
716
717
    }
}

718
719
void GdbEngine::flushQueuedCommands()
{
720
    showStatusMessage(tr("Processing queued commands"), 1000);
721
722
    while (!m_commandsToRunOnTemporaryBreak.isEmpty()) {
        GdbCommand cmd = m_commandsToRunOnTemporaryBreak.takeFirst();
723
        showMessage(_("RUNNING QUEUED COMMAND " + cmd.command + ' '
724
            + cmd.callbackName));
725
726
727
728
        flushCommand(cmd);
    }
}

hjk's avatar
hjk committed
729
void GdbEngine::flushCommand(const GdbCommand &cmd0)
730
{
731
732
733
    if (!stateAcceptsGdbCommands(state())) {
        showMessage(_(cmd0.command), LogInput);
        showMessage(_("GDB PROCESS ACCEPTS NO CMD IN STATE %1 ").arg(state()));
734
735
736
        return;
    }

737
    QTC_ASSERT(gdbProc()->state() == QProcess::Running, return;)
738

739
    ++currentToken();
740
    GdbCommand cmd = cmd0;
741
    cmd.postTime = QTime::currentTime();
742
    m_cookieForToken[currentToken()] = cmd;
743
744
    if (cmd.flags & ConsoleCommand)
        cmd.command = "-interpreter-exec console \"" + cmd.command + '"';
745
    cmd.command = QByteArray::number(currentToken()) + cmd.command;
746
    showMessage(_(cmd.command), LogInput);
747

748
    m_gdbAdapter->write(cmd.command + "\r\n");
749

750
    // Start Watchdog.
751
752
    if (m_commandTimer.interval() <= 20000)
        m_commandTimer.setInterval(commandTimeoutTime());
753
754
755
756
    // The process can die for external reason between the "-gdb-exit" was
    // sent and a response could be retrieved. We don't want the watchdog
    // to bark in that case since the only possible outcome is a dead
    // process anyway.
757
    if (!cmd.command.endsWith("-gdb-exit"))
758
        m_commandTimer.start();
759

hjk's avatar
hjk committed
760
    //if (cmd.flags & LosesChild)
hjk's avatar
hjk committed
761
    //    notifyInferiorIll();
762
763
}

764
765
int GdbEngine::commandTimeoutTime() const
{
hjk's avatar
hjk committed
766
    int time = debuggerCore()->action(GdbWatchdogTimeout)->value().toInt();
767
768
769
    return 1000 * qMax(20, time);
}

770
771
772
773
void GdbEngine::commandTimeout()
{
    QList<int> keys = m_cookieForToken.keys();
    qSort(keys);
774
    bool killIt = false;
775
    foreach (int key, keys) {
776
777
778
        const GdbCommand &cmd = m_cookieForToken.value(key);
        if (!(cmd.flags & NonCriticalResponse))
            killIt = true;
779
780
        QByteArray msg = QByteArray::number(key);
        msg += ": " + cmd.command + " => ";
781
        msg += cmd.callbackName ? cmd.callbackName : "<unnamed callback>";
782
        showMessage(_(msg));
783
    }
784
    if (killIt) {
785
        showMessage(_("TIMED OUT WAITING FOR GDB REPLY. COMMANDS STILL IN PROGRESS:"));
786
787
        int timeOut = m_commandTimer.interval();
        //m_commandTimer.stop();
788
        const QString msg = tr("The gdb process has not responded "
con's avatar
con committed
789
            "to a command within %1 seconds. This could mean it is stuck "
790
            "in an endless loop or taking longer than expected to perform "
791
            "the operation.\nYou can choose between waiting "
hjk's avatar
hjk committed
792
            "longer or abort debugging.").arg(timeOut / 1000);
793
        QMessageBox *mb = showMessageBox(QMessageBox::Critical,
794
            tr("Gdb not responding"), msg,
795
796
797
798
            QMessageBox::Ok | QMessageBox::Cancel);
        mb->button(QMessageBox::Cancel)->setText(tr("Give gdb more time"));
        mb->button(QMessageBox::Ok)->setText(tr("Stop debugging"));
        if (mb->exec() == QMessageBox::Ok) {
799
            showMessage(_("KILLING DEBUGGER AS REQUESTED BY USER"));
800
            // This is an undefined state, so we just pull the emergency brake.
801
            watchHandler()->endCycle();
ck's avatar
ck committed
802
            gdbProc()->kill();
803
        } else {
804
            showMessage(_("CONTINUE DEBUGGER AS REQUESTED BY USER"));
805
        }
806
    } else {
807
        showMessage(_("\nNON-CRITICAL TIMEOUT\n"));
808
    }
809
810
}

811
void GdbEngine::handleResultRecord(GdbResponse *response)
con's avatar
con committed
812
{
hjk's avatar
hjk committed
813
    //qDebug() << "TOKEN:" << response.token
814
    //    << " ACCEPTABLE:" << m_oldestAcceptableToken;
hjk's avatar
hjk committed
815
    //qDebug() << "\nRESULT" << response.token << response.toString();
con's avatar
con committed
816

817
    int token = response->token;
con's avatar
con committed
818
819
820
    if (token == -1)
        return;

821
    if (!m_cookieForToken.contains(token)) {
822
823
824
825
        // In theory this should not happen (rather the error should be
        // reported in the "first" response to the command) in practice it
        // does. We try to handle a few situations we are aware of gracefully.
        // Ideally, this code should not be present at all.
826
        showMessage(_("COOKIE FOR TOKEN %1 ALREADY EATEN. "
827
            "TWO RESPONSES FOR ONE COMMAND?").arg(token));
828
829
        if (response->resultClass == GdbResultError) {
            QByteArray msg = respon