gdbengine.cpp 163 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
**
con's avatar
con committed
9
** No Commercial Usage
10
**
con's avatar
con committed
11
12
13
14
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
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
**
con's avatar
con committed
25
26
27
28
29
30
** In addition, as a special exception, Nokia gives you certain additional
** rights.  These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
con's avatar
con committed
31
**
32
**************************************************************************/
con's avatar
con committed
33

34
35
#define QT_NO_CAST_FROM_ASCII

con's avatar
con committed
36
#include "gdbengine.h"
37

38
39
#include "attachgdbadapter.h"
#include "coregdbadapter.h"
ck's avatar
ck committed
40
#include "localplaingdbadapter.h"
41
#include "termgdbadapter.h"
ck's avatar
ck committed
42
43
#include "remotegdbserveradapter.h"
#include "remoteplaingdbadapter.h"
44
#include "trkgdbadapter.h"
45
#include "tcftrkgdbadapter.h"
con's avatar
con committed
46

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

#include "breakhandler.h"
#include "moduleshandler.h"
#include "registerhandler.h"
63
#include "snapshothandler.h"
64
#include "sourcefileshandler.h"
con's avatar
con committed
65
#include "stackhandler.h"
hjk's avatar
hjk committed
66
#include "threadshandler.h"
con's avatar
con committed
67
#include "watchhandler.h"
68

69
#include "logwindow.h"
con's avatar
con committed
70

71
#include <coreplugin/icore.h>
72
73
74
#include <projectexplorer/toolchain.h>
#include <texteditor/itexteditor.h>
#include <utils/qtcassert.h>
hjk's avatar
hjk committed
75

76
#include <QtCore/QCoreApplication>
con's avatar
con committed
77
78
79
#include <QtCore/QDebug>
#include <QtCore/QDir>
#include <QtCore/QFileInfo>
80
#include <QtCore/QMetaObject>
con's avatar
con committed
81
82
#include <QtCore/QTime>
#include <QtCore/QTimer>
83
#include <QtCore/QTemporaryFile>
84
#include <QtCore/QTextStream>
con's avatar
con committed
85
86

#include <QtGui/QAction>
87
#include <QtGui/QDialogButtonBox>
con's avatar
con committed
88
89
90
#include <QtGui/QLabel>
#include <QtGui/QMainWindow>
#include <QtGui/QMessageBox>
91
#include <QtGui/QPushButton>
con's avatar
con committed
92

Oswald Buddenhagen's avatar
Oswald Buddenhagen committed
93
#ifdef Q_OS_UNIX
con's avatar
con committed
94
95
96
#include <unistd.h>
#include <dlfcn.h>
#endif
hjk's avatar
hjk committed
97
#include <ctype.h>
con's avatar
con committed
98

99

100
101
namespace Debugger {
namespace Internal {
con's avatar
con committed
102
103
104

//#define DEBUG_PENDING  1

105
106
static const char winPythonVersionC[] = "python2.5";

con's avatar
con committed
107
108
109
#if DEBUG_PENDING
#   define PENDING_DEBUG(s) qDebug() << s
#else
Roberto Raggi's avatar
Roberto Raggi committed
110
#   define PENDING_DEBUG(s)
con's avatar
con committed
111
#endif
112
#define PENDING_DEBUGX(s) qDebug() << s
con's avatar
con committed
113

114
115
#define CB(callback) &GdbEngine::callback, STRINGIFY(callback)

116
QByteArray GdbEngine::tooltipIName(const QString &exp)
117
{
118
    return "tooltip." + exp.toLatin1().toHex();
119
120
}

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

con's avatar
con committed
152
153
154
155
156
157
static int &currentToken()
{
    static int token = 0;
    return token;
}

hjk's avatar
hjk committed
158
static QByteArray parsePlainConsoleStream(const GdbResponse &response)
159
{
hjk's avatar
hjk committed
160
    GdbMi output = response.data.findChild("consolestreamoutput");
161
162
163
164
165
166
167
168
169
170
    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
171
172
173
174
175
176
///////////////////////////////////////////////////////////////////////
//
// GdbEngine
//
///////////////////////////////////////////////////////////////////////

177
178
GdbEngine::GdbEngine(const DebuggerStartParameters &startParameters)
  : DebuggerEngine(startParameters)
con's avatar
con committed
179
{
Friedemann Kleint's avatar
Friedemann Kleint committed
180
    setObjectName(QLatin1String("GdbEngine"));
181
182
    qRegisterMetaType<WatchData>("WatchData");

183
    m_busy = false;
184
185
186
187
188
189
190
191
192
193
194
195
196
197
    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;
198
    m_stackNeeded = false;
199
200
    invalidateSourcesList();

ck's avatar
ck committed
201
    m_gdbAdapter = createAdapter();
202

203
204
205
    m_commandTimer.setSingleShot(true);
    connect(&m_commandTimer, SIGNAL(timeout()), SLOT(commandTimeout()));

hjk's avatar
hjk committed
206
    connect(debuggerCore()->action(AutoDerefPointers), SIGNAL(valueChanged(QVariant)),
207
            SLOT(reloadLocals()));
hjk's avatar
hjk committed
208
    connect(debuggerCore()->action(SortStructMembers), SIGNAL(valueChanged(QVariant)),
209
            SLOT(reloadLocals()));
hjk's avatar
hjk committed
210
    connect(debuggerCore()->action(CreateFullBacktrace), SIGNAL(triggered()),
211
            SLOT(createFullBacktrace()));
212
}
213

214
215
DebuggerStartMode GdbEngine::startMode() const
{
216
    return startParameters().startMode;
con's avatar
con committed
217
218
}

ck's avatar
ck committed
219
220
221
222
223
AbstractGdbProcess *GdbEngine::gdbProc() const
{
    return m_gdbAdapter->gdbProc();
}

con's avatar
con committed
224
225
GdbEngine::~GdbEngine()
{
226
    // Prevent sending error messages afterwards.
ck's avatar
ck committed
227
228
    if (m_gdbAdapter)
        disconnect(gdbProc(), 0, this, 0);
229
    delete m_gdbAdapter;
230
    m_gdbAdapter = 0;
hjk's avatar
hjk committed
231
232
}

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

#if 0
static void dump(const char *first, const char *middle, const QString & to)
{
    QByteArray ba(first, middle - first);
264
    Q_UNUSED(to)
con's avatar
con committed
265
266
267
268
269
270
271
272
273
274
275
    // 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

276
277
void GdbEngine::readDebugeeOutput(const QByteArray &data)
{
278
279
280
    QString msg = m_outputCodec->toUnicode(data.constData(), data.length(),
        &m_outputCodecState);
    showMessage(msg, AppStuff);
281
282
}

283
void GdbEngine::handleResponse(const QByteArray &buff)
con's avatar
con committed
284
{
285
    showMessage(QString::fromLocal8Bit(buff, buff.length()), LogOutput);
con's avatar
con committed
286
287

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

301
302
303
    const char *from = buff.constData();
    const char *to = from + buff.size();
    const char *inner;
con's avatar
con committed
304

305
306
307
308
    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
309
            break;
310
311
312
    if (from != inner) {
        token = QByteArray(from, inner - from).toInt();
        from = inner;
313
        //qDebug() << "found token" << token;
314
    }
con's avatar
con committed
315

hjk's avatar
hjk committed
316
    // next char decides kind of response
317
318
319
320
321
322
323
324
325
326
327
328
329
330
    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
331

hjk's avatar
hjk committed
332
            GdbMi result;
333
334
            while (from != to) {
                GdbMi data;
hjk's avatar
hjk committed
335
                if (*from != ',') {
336
337
                    // happens on archer where we get
                    // 23^running <NL> *running,thread-id="all" <NL> (gdb)
hjk's avatar
hjk committed
338
                    result.m_type = GdbMi::Tuple;
hjk's avatar
hjk committed
339
340
341
342
343
                    break;
                }
                ++from; // skip ','
                data.parseResultOrValue(from, to);
                if (data.isValid()) {
hjk's avatar
hjk committed
344
345
346
                    //qDebug() << "parsed result:" << data.toString();
                    result.m_children += data;
                    result.m_type = GdbMi::Tuple;
con's avatar
con committed
347
348
                }
            }
349
            if (asyncClass == "stopped") {
350
                handleStopResponse(result);
351
352
                m_pendingLogStreamOutput.clear();
                m_pendingConsoleStreamOutput.clear();
353
354
            } else if (asyncClass == "running") {
                // Archer has 'thread-id="all"' here
355
356
357
358
            } 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",
359
                // symbols-loaded="0"
hjk's avatar
hjk committed
360
                QByteArray id = result.findChild("id").data();
361
                if (!id.isEmpty())
362
                    showStatusMessage(tr("Library %1 loaded").arg(_(id)), 1000);
363
                progressPing();
364
                invalidateSourcesList();
hjk's avatar
hjk committed
365
366
367
368
            } 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
369
                QByteArray id = result.findChild("id").data();
370
                progressPing();
371
                showStatusMessage(tr("Library %1 unloaded").arg(_(id)), 1000);
372
                invalidateSourcesList();
373
374
            } else if (asyncClass == "thread-group-added") {
                // 7.1-symbianelf has "{id="i1"}"
375
376
377
            } 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
378
379
                // *-started seems to be standard in 7.1, but in early
                // 7.0.x, there was a *-created instead.
380
                progressPing();
ck's avatar
ck committed
381
                // 7.1.50 has thread-group-started,id="i1",pid="3529"
hjk's avatar
hjk committed
382
                QByteArray id = result.findChild("id").data();
383
                showStatusMessage(tr("Thread group %1 created").arg(_(id)), 1000);
ck's avatar
ck committed
384
385
386
387
388
389
390
                int pid = id.toInt();
                if (!pid) {
                    id = result.findChild("pid").data();
                    pid = id.toInt();
                }
                if (pid)
                    notifyInferiorPid(pid);
391
            } else if (asyncClass == "thread-created") {
392
                //"{id="1",group-id="28902"}"
hjk's avatar
hjk committed
393
                QByteArray id = result.findChild("id").data();
394
                showStatusMessage(tr("Thread %1 created").arg(_(id)), 1000);
395
            } else if (asyncClass == "thread-group-exited") {
396
                // Archer has "{id="28902"}"
hjk's avatar
hjk committed
397
                QByteArray id = result.findChild("id").data();
398
                showStatusMessage(tr("Thread group %1 exited").arg(_(id)), 1000);
399
            } else if (asyncClass == "thread-exited") {
400
                //"{id="1",group-id="28902"}"
hjk's avatar
hjk committed
401
402
                QByteArray id = result.findChild("id").data();
                QByteArray groupid = result.findChild("group-id").data();
403
                showStatusMessage(tr("Thread %1 in group %2 exited")
hjk's avatar
hjk committed
404
                    .arg(_(id)).arg(_(groupid)), 1000);
hjk's avatar
hjk committed
405
            } else if (asyncClass == "thread-selected") {
hjk's avatar
hjk committed
406
                QByteArray id = result.findChild("id").data();
407
                showStatusMessage(tr("Thread %1 selected").arg(_(id)), 1000);
408
                //"{id="2"}"
409
410
            } else if (m_isMacGdb && asyncClass == "shlibs-updated") {
                // Apple's gdb announces updated libs.
411
                invalidateSourcesList();
412
413
            } else if (m_isMacGdb && asyncClass == "shlibs-added") {
                // Apple's gdb announces added libs.
414
415
416
417
418
                // {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=""}}
419
                invalidateSourcesList();
420
421
422
423
424
            } 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",
425
                // line="1584",shlib="/../libFoo_debug.dylib",times="0"}
426
427
                const GdbMi bkpt = result.findChild("bkpt");
                const int number = bkpt.findChild("number").data().toInt();
hjk's avatar
hjk committed
428
                BreakpointId id = breakHandler()->findBreakpointByNumber(number);
429
                updateBreakpointDataFromOutput(id, bkpt);
430
            } else {
431
                qDebug() << "IGNORED ASYNC OUTPUT"
hjk's avatar
hjk committed
432
                    << asyncClass << result.toString();
433
            }
434
435
            break;
        }
436

437
        case '~': {
438
439
            QByteArray data = GdbMi::parseCString(from, to);
            m_pendingConsoleStreamOutput += data;
440
441

            // Parse pid from noise.
442
            if (!inferiorPid()) {
443
444
445
446
                // 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
447
448
449
                // Mac: [Switching to process 9294 local thread 0x2e03] or
                // [Switching to process 31773]
                static QRegExp re3(_("Switching to process ([0-9]+)"));
450
451
452
453
454
                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));
455
456
                else if (re3.indexIn(_(data)) != -1)
                    maybeHandleInferiorPidChanged(re3.cap(1));
457
            }
458
459

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

473
        case '@': {
474
            readDebugeeOutput(GdbMi::parseCString(from, to));
475
            break;
con's avatar
con committed
476
477
        }

478
479
480
481
482
483
        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:"))
484
                showMessage(_(data.mid(9)), AppStuff); // Cut "warning: "
con's avatar
con committed
485
486
487
            break;
        }

488
        case '^': {
hjk's avatar
hjk committed
489
            GdbResponse response;
con's avatar
con committed
490

hjk's avatar
hjk committed
491
            response.token = token;
con's avatar
con committed
492

493
494
495
            for (inner = from; inner != to; ++inner)
                if (*inner < 'a' || *inner > 'z')
                    break;
con's avatar
con committed
496

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

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

            //qDebug() << "\nLOG STREAM:" + m_pendingLogStreamOutput;
            //qDebug() << "\nCONSOLE STREAM:" + m_pendingConsoleStreamOutput;
hjk's avatar
hjk committed
528
            response.data.setStreamOutput("logstreamoutput",
529
                m_pendingLogStreamOutput);
hjk's avatar
hjk committed
530
            response.data.setStreamOutput("consolestreamoutput",
531
532
533
534
                m_pendingConsoleStreamOutput);
            m_pendingLogStreamOutput.clear();
            m_pendingConsoleStreamOutput.clear();

535
            handleResultRecord(&response);
536
537
538
539
540
            break;
        }
        default: {
            qDebug() << "UNKNOWN RESPONSE TYPE" << c;
            break;
con's avatar
con committed
541
542
543
544
545
546
        }
    }
}

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

void GdbEngine::readGdbStandardOutput()
{
558
    m_commandTimer.start(); // Restart timer.
559

560
561
    int newstart = 0;
    int scan = m_inbuffer.size();
con's avatar
con committed
562

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

565
    // This can trigger when a dialog starts a nested event loop.
566
567
568
    if (m_busy)
        return;

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

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

602
603
void GdbEngine::interruptInferiorTemporarily()
{
604
    foreach (const GdbCommand &cmd, m_commandsToRunOnTemporaryBreak) {
605
        if (cmd.flags & LosesChild) {
hjk's avatar
hjk committed
606
            notifyInferiorIll();
607
            return;
608
        }
609
    }
610
    requestInterruptInferior();
611
612
}

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

623
624
    showMessage(_("FOUND PID %1").arg(pid));
    notifyInferiorPid(pid);
con's avatar
con committed
625
626
}

627
void GdbEngine::postCommand(const QByteArray &command, AdapterCallback callback,
hjk's avatar
hjk committed
628
                            const char *callbackName, const QVariant &cookie)
629
630
631
632
{
    postCommand(command, NoFlags, callback, callbackName, cookie);
}

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

646
void GdbEngine::postCommand(const QByteArray &command, GdbCommandCallback callback,
647
648
                            const char *callbackName, const QVariant &cookie)
{
649
    postCommand(command, NoFlags, callback, callbackName, cookie);
650
651
}

652
void GdbEngine::postCommand(const QByteArray &command, GdbCommandFlags flags,
653
654
                            GdbCommandCallback callback, const char *callbackName,
                            const QVariant &cookie)
hjk's avatar
hjk committed
655
656
657
658
659
660
661
662
663
664
665
{
    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
666
{
hjk's avatar
hjk committed
667
    if (!stateAcceptsGdbCommands(state())) {
668
        PENDING_DEBUG(_("NO GDB PROCESS RUNNING, CMD IGNORED: " + cmd.command));
669
        showMessage(_("NO GDB PROCESS RUNNING, CMD IGNORED: %1 %2")
670
            .arg(_(cmd.command)).arg(state()));
con's avatar
con committed
671
672
673
        return;
    }

674
675
    if (cmd.flags & RebuildWatchModel) {
        ++m_pendingWatchRequests;
676
        PENDING_DEBUG("   WATCH MODEL:" << cmd.command << "=>" << cmd.callbackName
677
                      << "INCREMENTS PENDING TO" << m_pendingWatchRequests);
678
679
680
681
    } 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
682
    } else {
683
        PENDING_DEBUG("   OTHER (IN):" << cmd.command << "=>" << cmd.callbackName
684
685
                      << "LEAVES PENDING WATCH AT" << m_pendingWatchRequests
                      << "LEAVES PENDING BREAKPOINT AT" << m_pendingBreakpointRequests);
con's avatar
con committed
686
687
    }

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

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

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

742
    QTC_ASSERT(gdbProc()->state() == QProcess::Running, return;)
743

744
    ++currentToken();
745
    GdbCommand cmd = cmd0;
746
    cmd.postTime = QTime::currentTime();
747
    m_cookieForToken[currentToken()] = cmd;
748
749
    if (cmd.flags & ConsoleCommand)
        cmd.command = "-interpreter-exec console \"" + cmd.command + '"';
750
    cmd.command = QByteArray::number(currentToken()) + cmd.command;
751
    showMessage(_(cmd.command), LogInput);
752

753
    m_gdbAdapter->write(cmd.command + "\r\n");
754

755
    // Start Watchdog.
756
757
    if (m_commandTimer.interval() <= 20000)
        m_commandTimer.setInterval(commandTimeoutTime());
758
759
760
761
    // 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.
762
    if (!cmd.command.endsWith("-gdb-exit"))
763
        m_commandTimer.start();
764

hjk's avatar
hjk committed
765
    //if (cmd.flags & LosesChild)
hjk's avatar
hjk committed
766
    //    notifyInferiorIll();
767
768
}

769
770
int GdbEngine::commandTimeoutTime() const
{
hjk's avatar
hjk committed
771
    int time = debuggerCore()->action(GdbWatchdogTimeout)->value().toInt();
772
773
774
    return 1000 * qMax(20, time);
}

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

816
void GdbEngine::handleResultRecord(GdbResponse *response)
con's avatar
con committed
817
{
hjk's avatar
hjk committed
818
    //qDebug() << "TOKEN:" << response.token
819
    //    << " ACCEPTABLE:" << m_oldestAcceptableToken;
hjk's avatar
hjk committed
820
    //qDebug() << "\nRESULT" << response.token << response.toString();
con's avatar
con committed
821

822
    int token = response->token;
con's avatar
con committed
823
824
825
    if (token == -1)
        return;

826
    if (!m_cookieForToken.contains(token)) {
827
828
829
830
        // 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.
831
        showMessage(_("COOKIE FOR TOKEN %1 ALREADY EATEN. "