gdbengine.cpp 160 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
#include "gdboptionspage.h"
35
#include "debuggercore.h"
36
#include "debuggerplugin.h"
37
#include "debuggerrunner.h"
38

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

48
#include "watchutils.h"
49
#include "debuggeractions.h"
50
#include "debuggeragents.h"
con's avatar
con committed
51
#include "debuggerconstants.h"
52
#include "debuggertooltip.h"
53
#include "debuggerstringutils.h"
con's avatar
con committed
54 55 56 57 58
#include "gdbmi.h"

#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 "sourcefileswindow.h"
con's avatar
con committed
66

67
#include "debuggerdialogs.h"
68
#include "logwindow.h"
con's avatar
con committed
69

hjk's avatar
hjk committed
70
#include <utils/qtcassert.h>
71
#include <utils/fancymainwindow.h>
72
#include <texteditor/itexteditor.h>
73
#include <projectexplorer/toolchain.h>
74
#include <coreplugin/icore.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 198 199
    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
200
    m_gdbAdapter = createAdapter();
201

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

774 775 776 777
void GdbEngine::commandTimeout()
{
    QList<int> keys = m_cookieForToken.keys();
    qSort(keys);
778
    bool killIt = false;
779
    foreach (int key, keys) {
780 781 782
        const GdbCommand &cmd = m_cookieForToken.value(key);
        if (!(cmd.flags & NonCriticalResponse))
            killIt = true;
783 784
        QByteArray msg = QByteArray::number(key);
        msg += ": " + cmd.command + " => ";
785
        msg += cmd.callbackName ? cmd.callbackName : "<unnamed callback>";
786
        showMessage(_(msg));