cdbengine.cpp 69 KB
Newer Older
1 2 3 4 5 6 7 8
/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation (qt-info@nokia.com)
**
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 17 18 19 20 21 22 23 24
**
** GNU Lesser General Public License Usage
**
** 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.
**
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.
31 32 33
**
**************************************************************************/

34
#include "cdbengine.h"
Friedemann Kleint's avatar
Friedemann Kleint committed
35 36
#include "debuggerstartparameters.h"
#include "disassemblerlines.h"
37 38
#include "cdboptions.h"
#include "cdboptionspage.h"
39 40 41 42 43 44 45
#include "bytearrayinputstream.h"
#include "breakpoint.h"
#include "breakhandler.h"
#include "stackframe.h"
#include "stackhandler.h"
#include "watchhandler.h"
#include "threadshandler.h"
Friedemann Kleint's avatar
Friedemann Kleint committed
46
#include "moduleshandler.h"
47 48 49
#include "debuggeractions.h"
#include "debuggercore.h"
#include "registerhandler.h"
50 51
#include "disassembleragent.h"
#include "memoryagent.h"
52
#include "debuggerrunner.h"
53
#include "debuggertooltip.h"
54 55 56
#include "cdbparsehelpers.h"
#include "watchutils.h"
#include "gdb/gdbmi.h"
57 58 59
#include "shared/cdbsymbolpathlisteditor.h"

#include <coreplugin/icore.h>
60
#include <texteditor/itexteditor.h>
61
#include <projectexplorer/toolchain.h>
62

63
#include <utils/synchronousprocess.h>
64 65 66 67 68 69 70 71 72 73
#include <utils/winutils.h>
#include <utils/qtcassert.h>
#include <utils/savedaction.h>

#include <QtCore/QCoreApplication>
#include <QtCore/QFileInfo>
#include <QtCore/QDir>
#include <QtCore/QDebug>
#include <QtCore/QTextStream>
#include <QtCore/QDateTime>
74
#include <QtGui/QToolTip>
75 76 77 78 79 80 81 82

#ifdef Q_OS_WIN
#    include <utils/winutils.h>
#    include "dbgwinutils.h"
#endif

#include <cctype>

83 84
Q_DECLARE_METATYPE(Debugger::Internal::DisassemblerAgent*)
Q_DECLARE_METATYPE(Debugger::Internal::MemoryAgent*)
85 86

enum { debug = 0 };
87
enum { debugLocals = 0 };
88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118
enum { debugBreakpoints = 0 };

#if 0
#  define STATE_DEBUG(func, line, notifyFunc) qDebug("%s at %s:%d", notifyFunc, func, line);
#else
#  define STATE_DEBUG(func, line, notifyFunc)
#endif

/* CdbEngine version 2: Run the CDB process on pipes and parse its output.
 * The engine relies on a CDB extension Qt Creator provides as an extension
 * library (32/64bit). It serves to:
 * - Notify the engine about the state of the debugging session:
 *   + idle: (hooked with .idle_cmd) debuggee stopped
 *   + accessible: Debuggee stopped, cdb.exe accepts commands
 *   + inaccessible: Debuggee runs, no way to post commands
 *   + session active/inactive: Lost debuggee, terminating.
 * - Hook up with output/event callbacks and produce formatted output
 * - Provide some extension commands that produce output in a standardized (GDBMI)
 *   format that ends up in handleExtensionMessage().
 *   + pid     Return debuggee pid for interrupting.
 *   + locals  Print locals from SymbolGroup
 *   + expandLocals Expand locals in symbol group
 *   + registers, modules, threads
 * Commands can be posted:
 * postCommand: Does not expect a reply
 * postBuiltinCommand: Run a builtin-command producing free-format, multiline output
 * that is captured by enclosing it in special tokens using the 'echo' command and
 * then invokes a callback with a CdbBuiltinCommand structure.
 * postExtensionCommand: Run a command provided by the extension producing
 * one-line output and invoke a callback with a CdbExtensionCommand structure. */

119 120 121
using namespace ProjectExplorer;
using namespace Debugger::Internal;

122
namespace Debugger {
123
namespace Internal {
124

125 126
static const char localsPrefixC[] = "local.";

127
struct MemoryViewCookie {
128
    explicit MemoryViewCookie(MemoryAgent *a = 0, QObject *e = 0,
129 130 131
                              quint64 addr = 0, quint64 l = 0) :
        agent(a), editorToken(e), address(addr), length(l) {}

132
    MemoryAgent *agent;
133 134 135 136 137 138 139 140 141 142 143 144 145
    QObject *editorToken;
    quint64 address;
    quint64 length;
};

struct SourceLocationCookie {
    explicit SourceLocationCookie(const QString &f = QString(), int l = 0) :
             fileName(f), lineNumber(l) {}

    QString fileName;
    int lineNumber;
};

146
} // namespace Internal
147 148
} // namespace Debugger

149 150
Q_DECLARE_METATYPE(Debugger::Internal::MemoryViewCookie)
Q_DECLARE_METATYPE(Debugger::Internal::SourceLocationCookie)
151 152

namespace Debugger {
153
namespace Internal {
154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256

// Base data structure for command queue entries with callback
struct CdbCommandBase
{
    typedef CdbEngine::BuiltinCommandHandler CommandHandler;

    CdbCommandBase();
    CdbCommandBase(const QByteArray  &cmd, int token, unsigned flags,
                   unsigned nc, const QVariant &cookie);

    int token;
    unsigned flags;
    QByteArray command;
    QVariant cookie;
    // Continue with another commands as specified in CommandSequenceFlags
    unsigned commandSequence;
};

CdbCommandBase::CdbCommandBase() :
    token(0), flags(0), commandSequence(0)
{
}

CdbCommandBase::CdbCommandBase(const QByteArray  &cmd, int t, unsigned f,
                               unsigned nc, const QVariant &c) :
    token(t), flags(f), command(cmd), cookie(c), commandSequence(nc)
{
}

// Queue entry for builtin commands producing free-format
// line-by-line output.
struct CdbBuiltinCommand : public CdbCommandBase
{
    typedef CdbEngine::BuiltinCommandHandler CommandHandler;

    CdbBuiltinCommand() {}
    CdbBuiltinCommand(const QByteArray  &cmd, int token, unsigned flags,
                      CommandHandler h,
                      unsigned nc, const QVariant &cookie) :
        CdbCommandBase(cmd, token, flags, nc, cookie), handler(h) {}


    QByteArray joinedReply() const;

    CommandHandler handler;
    QList<QByteArray> reply;
};

QByteArray CdbBuiltinCommand::joinedReply() const
{
    if (reply.isEmpty())
        return QByteArray();
    QByteArray answer;
    answer.reserve(120  * reply.size());
    foreach (const QByteArray &l, reply) {
        answer += l;
        answer += '\n';
    }
    return answer;
}

// Queue entry for Qt Creator extension commands producing one-line
// output with success flag and error message.
struct CdbExtensionCommand : public CdbCommandBase
{
    typedef CdbEngine::ExtensionCommandHandler CommandHandler;

    CdbExtensionCommand() : success(false) {}
    CdbExtensionCommand(const QByteArray  &cmd, int token, unsigned flags,
                      CommandHandler h,
                      unsigned nc, const QVariant &cookie) :
        CdbCommandBase(cmd, token, flags, nc, cookie), handler(h),success(false) {}

    CommandHandler handler;
    QByteArray reply;
    QByteArray errorMessage;
    bool success;
};

template <class CommandPtrType>
int indexOfCommand(const QList<CommandPtrType> &l, int token)
{
    const int count = l.size();
    for (int i = 0; i < count; i++)
        if (l.at(i)->token == token)
            return i;
    return -1;
}

static inline bool validMode(DebuggerStartMode sm)
{
    switch (sm) {
    case NoStartMode:
    case AttachTcf:
    case AttachCore:
    case StartRemoteGdb:
        return false;
    default:
        break;
    }
    return true;
}

257
static inline QString msgCdbDisabled(ToolChainType tc)
258 259
{
    return CdbEngine::tr("The CDB debug engine required for %1 is currently disabled.").
260
                      arg(ToolChain::toolChainName(tc));
261 262
}

263 264 265 266 267
// Accessed by RunControlFactory
DebuggerEngine *createCdbEngine(const DebuggerStartParameters &sp, QString *errorMessage)
{
#ifdef Q_OS_WIN
    CdbOptionsPage *op = CdbOptionsPage::instance();
268
    if (!op || !op->options()->isValid()) {
269
        *errorMessage = msgCdbDisabled(sp.toolChainType);
270 271 272 273 274 275 276
        return 0;
    }
    if (!validMode(sp.startMode)) {
        *errorMessage = CdbEngine::tr("The CDB debug engine does not support start mode %1.").arg(sp.startMode);
        return 0;
    }
    return new CdbEngine(sp, op->options());
277 278 279 280 281 282 283 284 285 286
#else
    Q_UNUSED(sp)
#endif
    *errorMessage = QString::fromLatin1("Unsuppported debug mode");
    return 0;
}

bool isCdbEngineEnabled()
{
#ifdef Q_OS_WIN
287
    return CdbOptionsPage::instance() && CdbOptionsPage::instance()->options()->isValid();
288 289 290 291 292
#else
    return false;
#endif
}

293
ConfigurationCheck checkCdbConfiguration(ToolChainType toolChain)
294
{
295
    ConfigurationCheck check;
296
    switch (toolChain) {
297 298 299 300 301 302
    case ToolChain_MinGW: // Do our best
    case ToolChain_MSVC:
    case ToolChain_WINCE:
    case ToolChain_OTHER:
    case ToolChain_UNKNOWN:
    case ToolChain_INVALID:
303
        if (!isCdbEngineEnabled()) {
304 305
            check.errorMessage = msgCdbDisabled(toolChain);
            check.settingsPage = CdbOptionsPage::settingsId();
306 307 308 309
        }
        break;
    default:
        //: %1 is something like "GCCE" or "Intel C++ Compiler (Linux)" (see ToolChain context)
310 311 312
        check.errorMessage = CdbEngine::tr("The CDB debug engine does not support the %1 toolchain.").
                    arg(ToolChain::toolChainName(toolChain));
        check.settingsPage = CdbOptionsPage::settingsId();
313
    }
314
    return check;
315 316
}

317 318 319 320 321 322 323 324 325
void addCdb2OptionPages(QList<Core::IOptionsPage *> *opts)
{
    opts->push_back(new CdbOptionsPage);
}

#define QT_CREATOR_CDB_EXT "qtcreatorcdbext"

static inline Utils::SavedAction *theAssemblerAction()
{
326
    return debuggerCore()->action(OperateByInstruction);
327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344
}

CdbEngine::CdbEngine(const DebuggerStartParameters &sp, const OptionsPtr &options) :
    DebuggerEngine(sp),
    m_creatorExtPrefix("<qtcreatorcdbext>|"),
    m_tokenPrefix("<token>"),
    m_options(options),
    m_inferiorPid(0),
    m_accessible(false),
    m_specialStopMode(NoSpecialStop),
    m_nextCommandToken(0),
    m_nextBreakpointNumber(1),
    m_currentBuiltinCommandIndex(-1),
    m_extensionCommandPrefixBA("!"QT_CREATOR_CDB_EXT"."),
    m_operateByInstructionPending(true),
    m_operateByInstruction(true), // Default CDB setting
    m_notifyEngineShutdownOnTermination(false),
    m_hasDebuggee(false),
345 346
    m_elapsedLogTime(0),
    m_sourceStepInto(false)
347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364
{
    Utils::SavedAction *assemblerAction = theAssemblerAction();
    m_operateByInstructionPending = assemblerAction->isChecked();
    connect(assemblerAction, SIGNAL(triggered(bool)), this, SLOT(operateByInstructionTriggered(bool)));

    setObjectName(QLatin1String("CdbEngine"));
    connect(&m_process, SIGNAL(finished(int)), this, SLOT(processFinished()));
    connect(&m_process, SIGNAL(error(QProcess::ProcessError)), this, SLOT(processError()));
    connect(&m_process, SIGNAL(readyReadStandardOutput()), this, SLOT(readyReadStandardOut()));
    connect(&m_process, SIGNAL(readyReadStandardError()), this, SLOT(readyReadStandardOut()));
}

CdbEngine::~CdbEngine()
{
}

void CdbEngine::operateByInstructionTriggered(bool operateByInstruction)
{
365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380
    if (state() == InferiorStopOk) {
        syncOperateByInstruction(operateByInstruction);
    } else {
        // To be set next time session becomes accessible
        m_operateByInstructionPending = operateByInstruction;
    }
}

void CdbEngine::syncOperateByInstruction(bool operateByInstruction)
{
    if (m_operateByInstruction == operateByInstruction)
        return;
    QTC_ASSERT(m_accessible, return; )
    m_operateByInstruction = operateByInstruction;
    postCommand(m_operateByInstruction ? QByteArray("l-t") : QByteArray("l+t"), 0);
    postCommand(m_operateByInstruction ? QByteArray("l-s") : QByteArray("l+s"), 0);
381 382 383 384
}

void CdbEngine::setToolTipExpression(const QPoint &mousePos, TextEditor::ITextEditor *editor, int cursorPos)
{
385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400
    if (debug)
        qDebug() << Q_FUNC_INFO;
    // Need a stopped debuggee and a cpp file in a valid frame
    if (state() != InferiorStopOk || !isCppEditor(editor) || stackHandler()->currentIndex() < 0)
        return;
    // Determine expression and function
    int line;
    int column;
    QString function;
    const QString exp = cppExpressionAt(editor, cursorPos, &line, &column, &function);
    // Are we in the current stack frame
    if (function.isEmpty() || exp.isEmpty() || function != stackHandler()->currentFrame().function)
        return;
    // No numerical or any other expressions [yet]
    if (!(exp.at(0).isLetter() || exp.at(0) == QLatin1Char('_')))
        return;
401 402 403 404 405
    const QByteArray iname = QByteArray(localsPrefixC) + exp.toAscii();
    if (const WatchData *data = watchHandler()->findItem(iname)) {
        QToolTip::hideText();
        QToolTip::showText(mousePos, data->toToolTip());
    }
406 407 408 409
}

void CdbEngine::setupEngine()
{
410
    // Nag to add symbol server
411 412
    if (CdbSymbolPathListEditor::promptToAddSymbolServer(CdbOptions::settingsGroup(),
                                                         &(m_options->symbolPaths)))
413 414
        m_options->toSettings(Core::ICore::instance()->settings());

415 416 417 418 419 420 421 422
    QString errorMessage;
    if (!doSetupEngine(&errorMessage)) { // Start engine which will run until initial breakpoint
        showMessage(errorMessage, LogError);
        notifyEngineSetupFailed();
    }
}

// Determine full path to the CDB extension library.
423
QString CdbEngine::extensionLibraryName(bool is64Bit)
424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475
{
    // Determine extension lib name and path to use
    QString rc;
    QTextStream(&rc) << QFileInfo(QCoreApplication::applicationDirPath()).path()
                     << "/lib/" << (is64Bit ? QT_CREATOR_CDB_EXT"64" : QT_CREATOR_CDB_EXT"32")
                     << '/' << QT_CREATOR_CDB_EXT << ".dll";
    return rc;
}

// Determine environment for CDB.exe, start out with run config and
// add CDB extension path merged with system value should there be one.
static QStringList mergeEnvironment(QStringList runConfigEnvironment,
                                    QString cdbExtensionPath)
{
    // Determine CDB extension path from Qt Creator
    static const char cdbExtensionPathVariableC[] = "_NT_DEBUGGER_EXTENSION_PATH";
    const QByteArray oldCdbExtensionPath = qgetenv(cdbExtensionPathVariableC);
    if (!oldCdbExtensionPath.isEmpty()) {
        cdbExtensionPath.append(QLatin1Char(';'));
        cdbExtensionPath.append(QString::fromLocal8Bit(oldCdbExtensionPath));
    }
    // We do not assume someone sets _NT_DEBUGGER_EXTENSION_PATH in the run
    // config, just to make sure, delete any existing entries
    const QString cdbExtensionPathVariableAssign =
            QLatin1String(cdbExtensionPathVariableC) + QLatin1Char('=');
    for (QStringList::iterator it = runConfigEnvironment.begin(); it != runConfigEnvironment.end() ; ) {
        if (it->startsWith(cdbExtensionPathVariableAssign)) {
            it = runConfigEnvironment.erase(it);
            break;
        } else {
            ++it;
        }
    }
    runConfigEnvironment.append(cdbExtensionPathVariableAssign +
                                QDir::toNativeSeparators(cdbExtensionPath));
    return runConfigEnvironment;
}

int CdbEngine::elapsedLogTime() const
{
    const int elapsed = m_logTime.elapsed();
    const int delta = elapsed - m_elapsedLogTime;
    m_elapsedLogTime = elapsed;
    return delta;
}

bool CdbEngine::doSetupEngine(QString *errorMessage)
{
    m_logTime.start();
    // Determine extension lib name and path to use
    // The extension is passed as relative name with the path variable set
    //(does not work with absolute path names)
476
    const QFileInfo extensionFi(CdbEngine::extensionLibraryName(m_options->is64bit));
477 478 479 480 481
    if (!extensionFi.isFile()) {
        *errorMessage = QString::fromLatin1("Internal error: The extension %1 cannot be found.").
                arg(QDir::toNativeSeparators(extensionFi.absoluteFilePath()));
        return false;
    }
482
    const QString extensionFileName = extensionFi.fileName();
483 484 485
    // Prepare arguments
    const DebuggerStartParameters &sp = startParameters();
    QStringList arguments;
486 487 488 489 490 491
    const bool isRemote = sp.startMode == AttachToRemote;
    if (isRemote) { // Must be first
        arguments << QLatin1String("-remote") << sp.remoteChannel;
    } else {
        arguments << (QLatin1String("-a") + extensionFileName);
    }
492 493 494 495 496 497 498 499 500 501 502 503 504 505
    // Source line info/No terminal breakpoint / Pull extension
    arguments << QLatin1String("-lines") << QLatin1String("-G")
    // register idle (debuggee stop) notification
              << QLatin1String("-c")
              << QString::fromAscii(".idle_cmd " + m_extensionCommandPrefixBA + "idle");
    if (sp.useTerminal) // Separate console
        arguments << QLatin1String("-2");
    if (!m_options->symbolPaths.isEmpty())
        arguments << QLatin1String("-y") << m_options->symbolPaths.join(QString(QLatin1Char(';')));
    if (!m_options->sourcePaths.isEmpty())
        arguments << QLatin1String("-srcpath") << m_options->sourcePaths.join(QString(QLatin1Char(';')));
    switch (sp.startMode) {
    case StartInternal:
    case StartExternal:
506
        arguments << QDir::toNativeSeparators(sp.executable);
507
        break;
508 509
    case AttachToRemote:
        break;
510
    case AttachExternal:
511
    case AttachCrashedExternal:
512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529
        arguments << QLatin1String("-p") << QString::number(sp.attachPID);
        if (sp.startMode == AttachCrashedExternal)
            arguments << QLatin1String("-e") << sp.crashParameter << QLatin1String("-g");
        break;
    default:
        *errorMessage = QString::fromLatin1("Internal error: Unsupported start mode %1.").arg(sp.startMode);
        return false;
    }
    const QString executable = m_options->executable;
    const QString msg = QString::fromLatin1("Launching %1 %2\nusing %3 of %4.").
            arg(QDir::toNativeSeparators(executable),
                arguments.join(QString(QLatin1Char(' '))),
                QDir::toNativeSeparators(extensionFi.absoluteFilePath()),
                extensionFi.lastModified().toString(Qt::SystemLocaleShortDate));
    showMessage(msg, LogMisc);

    m_outputBuffer.clear();
    m_process.setEnvironment(mergeEnvironment(sp.environment.toStringList(), extensionFi.absolutePath()));
530 531 532 533
#ifdef Q_OS_WIN
    if (!sp.processArgs.isEmpty()) // Appends
        m_process.setNativeArguments(sp.processArgs);
#endif
534 535 536 537 538 539 540 541 542 543 544 545 546 547
    m_process.start(executable, arguments);
    if (!m_process.waitForStarted()) {
        *errorMessage = QString::fromLatin1("Internal error: Cannot start process %1: %2").
                arg(QDir::toNativeSeparators(executable), m_process.errorString());
        return false;
    }
#ifdef Q_OS_WIN
    const unsigned long pid = Utils::winQPidToPid(m_process.pid());
#else
    const unsigned long pid = 0;
#endif
    showMessage(QString::fromLatin1("%1 running as %2").
                arg(QDir::toNativeSeparators(executable)).arg(pid), LogMisc);
    m_hasDebuggee = true;
548 549 550 551 552 553 554
    if (isRemote) { // We do not get an 'idle' in a remote session, but are accessible
        m_accessible = true;
        const QByteArray loadCommand = QByteArray(".load ")
                + extensionFileName.toLocal8Bit();
        postCommand(loadCommand, 0);
        notifyEngineSetupOk();
    }
555 556 557 558 559
    return true;
}

void CdbEngine::setupInferior()
{
560 561
    if (debug)
        qDebug("setupInferior");
562 563 564 565 566 567
    attemptBreakpointSynchronization();
    postExtensionCommand("pid", QByteArray(), 0, &CdbEngine::handlePid);
}

void CdbEngine::runEngine()
{
568 569
    if (debug)
        qDebug("runEngine");
570 571
    foreach (const QString &breakEvent, m_options->breakEvents)
            postCommand(QByteArray("sxe ") + breakEvent.toAscii(), 0);
572 573 574
    postCommand("g", 0);
}

575 576 577 578 579
bool CdbEngine::commandsPending() const
{
    return !m_builtinCommandQueue.isEmpty() || !m_extensionCommandQueue.isEmpty();
}

580 581 582 583 584 585 586 587 588 589 590 591
void CdbEngine::shutdownInferior()
{
    if (debug)
        qDebug("CdbEngine::shutdownInferior in state '%s', process running %d", stateName(state()),
               isCdbProcessRunning());

    if (!isCdbProcessRunning()) { // Direct launch: Terminated with process.
        if (debug)
            qDebug("notifyInferiorShutdownOk");
        notifyInferiorShutdownOk();
        return;
    }
592
    if (!canInterruptInferior() || commandsPending()) {
593 594 595 596
        notifyInferiorShutdownFailed();
        return;
    }

597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618
    if (m_accessible) {
        if (startParameters().startMode == AttachExternal || startParameters().startMode == AttachCrashedExternal)
            detachDebugger();
        if (debug)
            qDebug("notifyInferiorShutdownOk");
        notifyInferiorShutdownOk();
    } else {
        interruptInferior(); // Calls us again
    }
}

/* shutdownEngine/processFinished:
 * Note that in the case of launching a process by the debugger, the debugger
 * automatically quits a short time after reporting the session becoming
 * inaccessible without debuggee (notifyInferiorExited). In that case,
 * processFinished() must not report any arbitrarily notifyEngineShutdownOk()
 * as not to confuse the state engine.
 */

void CdbEngine::shutdownEngine()
{
    if (debug)
619 620 621 622
        qDebug("CdbEngine::shutdownEngine in state '%s', process running %d,"
               "accessible=%d,commands pending=%d",
               stateName(state()), isCdbProcessRunning(), m_accessible,
               commandsPending());
623 624 625 626 627 628 629 630

    if (!isCdbProcessRunning()) { // Direct launch: Terminated with process.
        if (debug)
            qDebug("notifyEngineShutdownOk");
        notifyEngineShutdownOk();
        return;
    }

631 632 633 634 635 636
    // No longer trigger anything from messages
    disconnect(&m_process, SIGNAL(readyReadStandardOutput()), this, 0);
    disconnect(&m_process, SIGNAL(readyReadStandardError()), this, 0);
    // Go for kill if there are commands pending.
    if (m_accessible && !commandsPending()) {
        // detach: Wait for debugger to finish.
637 638
        if (startParameters().startMode == AttachExternal)
            detachDebugger();
639 640 641 642 643 644 645 646 647 648 649
        // Remote requires a bit more force to quit.
        if (startParameters().startMode == AttachToRemote) {
            postCommand(m_extensionCommandPrefixBA + "shutdownex", 0);
            postCommand("qq", 0);
        } else {
            postCommand("q", 0);
        }
        m_notifyEngineShutdownOnTermination = true;
        return;
    } else {
        // Remote process. No can do, currently
650
        m_notifyEngineShutdownOnTermination = true;
651
        Utils::SynchronousProcess::stopProcess(m_process);
652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697
        return;
    }
    // Lost debuggee, debugger should quit anytime now
    if (!m_hasDebuggee) {
        m_notifyEngineShutdownOnTermination = true;
        return;
    }
    interruptInferior();
}

void CdbEngine::processFinished()
{
    if (debug)
        qDebug("CdbEngine::processFinished %dms '%s' notify=%d (exit state=%d, ex=%d)",
               elapsedLogTime(), stateName(state()), m_notifyEngineShutdownOnTermination,
               m_process.exitStatus(), m_process.exitCode());

    const bool crashed = m_process.exitStatus() == QProcess::CrashExit;
    if (crashed) {
        showMessage(tr("CDB crashed"), LogError); // not in your life.
    } else {
        showMessage(tr("CDB exited (%1)").arg(m_process.exitCode()), LogMisc);
    }

    if (m_notifyEngineShutdownOnTermination) {
        if (crashed) {
            if (debug)
                qDebug("notifyEngineIll");
            notifyEngineIll();
        } else {
            if (debug)
                qDebug("notifyEngineShutdownOk");
            notifyEngineShutdownOk();
        }
    } else {
        if (debug)
            qDebug("notifyEngineSpontaneousShutdown");
        notifyEngineSpontaneousShutdown();
    }
}

void CdbEngine::detachDebugger()
{
    postCommand(".detach", 0);
}

698 699
void CdbEngine::updateWatchData(const WatchData &dataIn,
                                const WatchUpdateFlags & flags)
700 701 702 703 704 705 706 707
{
    if (debug)
        qDebug("CdbEngine::updateWatchData() %dms %s incr=%d: %s",
               elapsedLogTime(), stateName(state()),
               flags.tryIncremental,
               qPrintable(dataIn.toString()));

    if (!dataIn.hasChildren) {
708
        WatchData data = dataIn;
709 710 711 712 713 714 715
        data.setAllUnneeded();
        watchHandler()->insertData(data);
        return;
    }
    updateLocalVariable(dataIn.iname);
}

716 717
void CdbEngine::addLocalsOptions(ByteArrayInputStream &str) const
{
718 719
    if (debuggerCore()->boolSetting(VerboseLog))
        str << blankSeparator << "-v";
720 721 722 723 724 725 726 727 728 729
    if (debuggerCore()->boolSetting(UseDebuggingHelpers))
        str << blankSeparator << "-c";
    const QByteArray typeFormats = watchHandler()->typeFormatRequests();
    if (!typeFormats.isEmpty())
        str << blankSeparator << "-T " << typeFormats;
    const QByteArray individualFormats = watchHandler()->individualFormatRequests();
    if (!individualFormats.isEmpty())
        str << blankSeparator << "-I " << individualFormats;
}

730 731 732 733 734 735
void CdbEngine::updateLocalVariable(const QByteArray &iname)
{
    const int stackFrame = stackHandler()->currentIndex();
    if (stackFrame >= 0) {
        QByteArray localsArguments;
        ByteArrayInputStream str(localsArguments);
736 737
        addLocalsOptions(str);
        str << blankSeparator << stackFrame <<  ' ' << iname;
738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753
        postExtensionCommand("locals", localsArguments, 0, &CdbEngine::handleLocals);
    } else {
        qWarning("Internal error; no stack frame in updateLocalVariable");
    }
}

unsigned CdbEngine::debuggerCapabilities() const
{
    return DisassemblerCapability | RegisterCapability | ShowMemoryCapability
           |WatchpointCapability|JumpToLineCapability
           |BreakOnThrowAndCatchCapability; // Sort-of: Can break on throw().
}

void CdbEngine::executeStep()
{
    postCommand(QByteArray("t"), 0); // Step into-> t (trace)
754 755
    if (!m_operateByInstruction)
        m_sourceStepInto = true; // See explanation at handleStackTrace().
756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791
    notifyInferiorRunRequested();
}

void CdbEngine::executeStepOut()
{
    postCommand(QByteArray("gu"), 0); // Step out-> gu (go up)
    notifyInferiorRunRequested();
}

void CdbEngine::executeNext()
{
    postCommand(QByteArray("p"), 0); // Step over -> p
    notifyInferiorRunRequested();
}

void CdbEngine::executeStepI()
{
    executeStep();
}

void CdbEngine::executeNextI()
{
    executeNext();
}

void CdbEngine::continueInferior()
{
    notifyInferiorRunRequested();
    doContinueInferior();
}

void CdbEngine::doContinueInferior()
{
    postCommand(QByteArray("g"), 0);
}

792 793 794 795 796
bool CdbEngine::canInterruptInferior() const
{
    return startParameters().startMode != AttachToRemote;
}

797 798
void CdbEngine::interruptInferior()
{
799 800 801 802 803 804 805 806
    if (canInterruptInferior()) {
        doInterruptInferior(NoSpecialStop);
    } else {
        showMessage(tr("Interrupting is not possible in remote sessions."), LogError);
        notifyInferiorStopOk();
        notifyInferiorRunRequested();
        notifyInferiorRunOk();
    }
807 808 809 810 811 812 813 814
}

void CdbEngine::doInterruptInferior(SpecialStopMode sm)
{
#ifdef Q_OS_WIN
    const SpecialStopMode oldSpecialMode = m_specialStopMode;
    m_specialStopMode = sm;
    QString errorMessage;
815
    if (!winDebugBreakProcess(m_inferiorPid, &errorMessage)) {
816 817 818 819 820 821 822 823 824 825 826
        m_specialStopMode = oldSpecialMode;
        showMessage(errorMessage, LogError);
    }
#else
    Q_UNUSED(sm)
#endif
}

void CdbEngine::executeRunToLine(const QString &fileName, int lineNumber)
{
    // Add one-shot breakpoint
827
    BreakpointParameters bp(BreakpointByFileAndLine);
828 829 830 831 832 833 834 835 836
    bp.fileName = fileName;
    bp.lineNumber = lineNumber;
    postCommand(cdbAddBreakpointCommand(bp, true), 0);
    continueInferior();
}

void CdbEngine::executeRunToFunction(const QString &functionName)
{
    // Add one-shot breakpoint
837
    BreakpointParameters bp(BreakpointByFunction);
838 839 840 841 842 843 844 845
    bp.functionName = functionName;

    postCommand(cdbAddBreakpointCommand(bp, true), 0);
    continueInferior();
}

void CdbEngine::setRegisterValue(int regnr, const QString &value)
{
846
    const Registers registers = registerHandler()->registers();
847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881
    QTC_ASSERT(regnr < registers.size(), return)
    // Value is decimal or 0x-hex-prefixed
    QByteArray cmd;
    ByteArrayInputStream str(cmd);
    str << "r " << registers.at(regnr).name << '=' << value;
    postCommand(cmd, 0);
    reloadRegisters();
}

void CdbEngine::executeJumpToLine(const QString & fileName, int lineNumber)
{
    QByteArray cmd;
    ByteArrayInputStream str(cmd);
    // Resolve source line address and go to that location
    str << "? `" << QDir::toNativeSeparators(fileName) << ':' << lineNumber << '`';
    const QVariant cookie = qVariantFromValue(SourceLocationCookie(fileName, lineNumber));
    postBuiltinCommand(cmd, 0, &CdbEngine::handleJumpToLineAddressResolution, 0, cookie);
}

void CdbEngine::handleJumpToLineAddressResolution(const CdbBuiltinCommandPtr &cmd)
{
    if (cmd->reply.isEmpty())
        return;
    // Evaluate expression: 5365511549 = 00000001`3fcf357d
    // Set register 'rip' to hex address and goto lcoation
    QByteArray answer = cmd->reply.front();
    const int equalPos = answer.indexOf(" = ");
    if (equalPos == -1)
        return;
    answer.remove(0, equalPos + 3);
    QTC_ASSERT(qVariantCanConvert<SourceLocationCookie>(cmd->cookie), return ; )
    const SourceLocationCookie cookie = qvariant_cast<SourceLocationCookie>(cmd->cookie);

    QByteArray registerCmd;
    ByteArrayInputStream str(registerCmd);
882 883
    // PC-register depending on 64/32bit.
    str << "r " << (m_options->is64bit ? "rip" : "eip") << "=0x" << answer;
884
    postCommand(registerCmd, 0);
885
    gotoLocation(Location(cookie.fileName, cookie.lineNumber));
886 887
}

888
void CdbEngine::assignValueInDebugger(const WatchData *w, const QString &expr, const QVariant &value)
889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909
{
    if (debug)
        qDebug() << "CdbEngine::assignValueInDebugger" << w->iname << expr << value;

    if (state() != InferiorStopOk || stackHandler()->currentIndex() < 0) {
        qWarning("Internal error: assignValueInDebugger: Invalid state or no stack frame.");
        return;
    }

    QByteArray cmd;
    ByteArrayInputStream str(cmd);
    str << m_extensionCommandPrefixBA << "assign " << w->iname << '=' << value.toString();
    postCommand(cmd, 0);
    updateLocalVariable(w->iname);
}

void CdbEngine::handleThreads(const CdbExtensionCommandPtr &reply)
{
    if (debug)
        qDebug("CdbEngine::handleThreads success=%d", reply->success);
    if (reply->success) {
910
        GdbMi data;
911 912
        data.fromString(reply->reply);
        int currentThreadId;
913
        Threads threads = ThreadsHandler::parseGdbmiThreads(data, &currentThreadId);
914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999
        threadsHandler()->setThreads(threads);
        threadsHandler()->setCurrentThreadId(currentThreadId);
        // Continue sequence
        postCommandSequence(reply->commandSequence);
    } else {
        showMessage(QString::fromLatin1(reply->errorMessage), LogError);
    }
}

void CdbEngine::executeDebuggerCommand(const QString &command)
{
    postCommand(command.toLocal8Bit(), QuietCommand);
}

// Post command without callback
void CdbEngine::postCommand(const QByteArray &cmd, unsigned flags)
{
    if (debug)
        qDebug("CdbEngine::postCommand %dms '%s' %u %s\n",
               elapsedLogTime(), cmd.constData(), flags, stateName(state()));
    if (!(flags & QuietCommand))
        showMessage(QString::fromLocal8Bit(cmd), LogInput);
    m_process.write(cmd + '\n');
}

// Post a built-in-command producing free-format output with a callback.
// In order to catch the output, it is enclosed in 'echo' commands
// printing a specially formatted token to be identifiable in the output.
void CdbEngine::postBuiltinCommand(const QByteArray &cmd, unsigned flags,
                                   BuiltinCommandHandler handler,
                                   unsigned nextCommandFlag,
                                   const QVariant &cookie)
{
    if (!m_accessible) {
        const QString msg = QString::fromLatin1("Attempt to issue builtin command '%1' to non-accessible session (%2)")
                .arg(QString::fromLocal8Bit(cmd), QString::fromAscii(stateName(state())));
        showMessage(msg, LogError);
        return;
    }
    if (!flags & QuietCommand)
        showMessage(QString::fromLocal8Bit(cmd), LogInput);

    const int token = m_nextCommandToken++;
    CdbBuiltinCommandPtr pendingCommand(new CdbBuiltinCommand(cmd, token, flags, handler, nextCommandFlag, cookie));

    m_builtinCommandQueue.push_back(pendingCommand);
    // Enclose command in echo-commands for token
    QByteArray fullCmd;
    ByteArrayInputStream str(fullCmd);
    str << ".echo \"" << m_tokenPrefix << token << "<\"\n"
            << cmd << "\n.echo \"" << m_tokenPrefix << token << ">\"\n";
    if (debug)
        qDebug("CdbEngine::postBuiltinCommand %dms '%s' flags=%u token=%d %s next=%u, cookie='%s', pending=%d, sequence=0x%x",
               elapsedLogTime(), cmd.constData(), flags, token, stateName(state()), nextCommandFlag, qPrintable(cookie.toString()),
               m_builtinCommandQueue.size(), nextCommandFlag);
    if (debug > 1)
        qDebug("CdbEngine::postBuiltinCommand: resulting command '%s'\n",
               fullCmd.constData());
    m_process.write(fullCmd);
}

// Post an extension command producing one-line output with a callback,
// pass along token for identification in queue.
void CdbEngine::postExtensionCommand(const QByteArray &cmd,
                                     const QByteArray &arguments,
                                     unsigned flags,
                                     ExtensionCommandHandler handler,
                                     unsigned nextCommandFlag,
                                     const QVariant &cookie)
{
    if (!m_accessible) {
        const QString msg = QString::fromLatin1("Attempt to issue extension command '%1' to non-accessible session (%2)")
                .arg(QString::fromLocal8Bit(cmd), QString::fromAscii(stateName(state())));
        showMessage(msg, LogError);
        return;
    }

    const int token = m_nextCommandToken++;

    // Format full command with token to be recognizeable in the output
    QByteArray fullCmd;
    ByteArrayInputStream str(fullCmd);
    str << m_extensionCommandPrefixBA << cmd << " -t " << token;
    if (!arguments.isEmpty())
        str <<  ' ' << arguments;

1000 1001 1002
    if (!flags & QuietCommand)
        showMessage(QString::fromLocal8Bit(fullCmd), LogInput);

1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018
    CdbExtensionCommandPtr pendingCommand(new CdbExtensionCommand(fullCmd, token, flags, handler, nextCommandFlag, cookie));

    m_extensionCommandQueue.push_back(pendingCommand);
    // Enclose command in echo-commands for token
    if (debug)
        qDebug("CdbEngine::postExtensionCommand %dms '%s' flags=%u token=%d %s next=%u, cookie='%s', pending=%d, sequence=0x%x",
               elapsedLogTime(), fullCmd.constData(), flags, token, stateName(state()), nextCommandFlag, qPrintable(cookie.toString()),
               m_extensionCommandQueue.size(), nextCommandFlag);
    m_process.write(fullCmd + '\n');
}

void CdbEngine::activateFrame(int index)
{
    // TODO: assembler,etc
    if (index < 0)
        return;
1019
    const StackFrames &frames = stackHandler()->frames();
1020 1021
    QTC_ASSERT(index < frames.size(), return; )

1022 1023
    const StackFrame frame = frames.at(index);
    if (debug || debugLocals)
1024
        qDebug("activateFrame idx=%d '%s' %d", index,
1025
               qPrintable(frame.file), frame.line);
1026 1027 1028 1029 1030 1031 1032
    stackHandler()->setCurrentIndex(index);
    const bool showAssembler = !frames.at(index).isUsable();
    if (showAssembler) { // Assembly code: Clean out model and force instruction mode.
        watchHandler()->beginCycle();
        watchHandler()->endCycle();
        QAction *assemblerAction = theAssemblerAction();
        if (assemblerAction->isChecked()) {
1033
            gotoLocation(frame);
1034 1035 1036 1037 1038
        } else {
            assemblerAction->trigger(); // Seems to trigger update
        }
        return;
    }
1039
    gotoLocation(frame);
1040 1041 1042 1043
    // Watchers: Initial expand, get uninitialized and query
    QByteArray arguments;
    ByteArrayInputStream str(arguments);
    // Pre-expand
1044 1045
    const QSet<QByteArray> expanded = watchHandler()->expandedINames();
    if (!expanded.isEmpty()) {
1046
        str << blankSeparator << "-e ";
1047 1048 1049
        int i = 0;
        foreach(const QByteArray &e, expanded) {
            if (i++)
1050 1051
                str << ',';
            str << e;
1052 1053
        }
    }
1054
    addLocalsOptions(str);
1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071
    // Uninitialized variables if desired
    if (debuggerCore()->boolSetting(UseCodeModel)) {
        QStringList uninitializedVariables;
        getUninitializedVariables(debuggerCore()->cppCodeModelSnapshot(),
                                  frame.function, frame.file, frame.line, &uninitializedVariables);
        if (!uninitializedVariables.isEmpty()) {
            str << blankSeparator << "-u ";
            int i = 0;
            foreach(const QString &u, uninitializedVariables) {
                if (i++)
                    str << ',';
                str << localsPrefixC << u;
            }
        }
    }
    // Required arguments: frame
    str << blankSeparator << index;
1072
    watchHandler()->beginCycle();
1073
    postExtensionCommand("locals", arguments, 0, &CdbEngine::handleLocals);
1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088
}

void CdbEngine::selectThread(int index)
{
    if (index < 0 || index == threadsHandler()->currentThread())
        return;

    resetLocation();
    const int newThreadId = threadsHandler()->threads().at(index).id;
    threadsHandler()->setCurrentThread(index);

    const QByteArray cmd = "~" + QByteArray::number(newThreadId) + " s";
    postBuiltinCommand(cmd, 0, &CdbEngine::dummyHandler, CommandListStack);
}

1089
void CdbEngine::fetchDisassembler(DisassemblerAgent *agent)
1090 1091 1092 1093 1094
{
    QTC_ASSERT(m_accessible, return;)
    QByteArray cmd;
    ByteArrayInputStream str(cmd);
    str <<  "u " << hex << hexPrefixOn << agent->address() << " L40";
1095
    const QVariant cookie = qVariantFromValue<DisassemblerAgent*>(agent);
1096 1097 1098 1099 1100 1101
    postBuiltinCommand(cmd, 0, &CdbEngine::handleDisassembler, 0, cookie);
}

// Parse: "00000000`77606060 cc              int     3"
void CdbEngine::handleDisassembler(const CdbBuiltinCommandPtr &command)
{
1102 1103
    QTC_ASSERT(qVariantCanConvert<DisassemblerAgent*>(command->cookie), return;)
    DisassemblerAgent *agent = qvariant_cast<DisassemblerAgent*>(command->cookie);
1104 1105 1106 1107
    DisassemblerLines disassemblerLines;
    foreach(const QByteArray &line, command->reply)
        disassemblerLines.appendLine(DisassemblerLine(QString::fromLatin1(line)));
    agent->setContents(disassemblerLines);
1108 1109
}

1110
void CdbEngine::fetchMemory(MemoryAgent *agent, QObject *editor, quint64 addr, quint64 length)
1111
{
1112 1113 1114 1115
    if (!m_accessible) {
        qWarning("Internal error: Attempt to read memory from inaccessible session: %s", Q_FUNC_INFO);
        return;
    }
1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187
    if (debug)
        qDebug("CdbEngine::fetchMemory %llu bytes from 0x%llx", length, addr);

    QByteArray args;
    ByteArrayInputStream str(args);
    str << addr << ' ' << length;
    const QVariant cookie = qVariantFromValue<MemoryViewCookie>(MemoryViewCookie(agent, editor, addr, length));
    postExtensionCommand("memory", args, 0, &CdbEngine::handleMemory, 0, cookie);
}

void CdbEngine::handleMemory(const CdbExtensionCommandPtr &command)
{
    QTC_ASSERT(qVariantCanConvert<MemoryViewCookie>(command->cookie), return;)
    const MemoryViewCookie memViewCookie = qvariant_cast<MemoryViewCookie>(command->cookie);
    if (command->success) {
        const QByteArray data = QByteArray::fromBase64(command->reply);
        if (unsigned(data.size()) == memViewCookie.length)
            memViewCookie.agent->addLazyData(memViewCookie.editorToken,
                                             memViewCookie.address, data);
    } else {
        showMessage(QString::fromLocal8Bit(command->errorMessage), LogError);
    }
}

void CdbEngine::reloadModules()
{
    postCommandSequence(CommandListModules);
}

void CdbEngine::loadSymbols(const QString & /* moduleName */)
{
}

void CdbEngine::loadAllSymbols()
{
}

void CdbEngine::requestModuleSymbols(const QString &moduleName)
{
    Q_UNUSED(moduleName)
}

void CdbEngine::reloadRegisters()
{
    postCommandSequence(CommandListRegisters);
}

void CdbEngine::reloadSourceFiles()
{
}

void CdbEngine::reloadFullStack()
{
    if (debug)
        qDebug("%s", Q_FUNC_INFO);
    postCommandSequence(CommandListStack);
}

void CdbEngine::handlePid(const CdbExtensionCommandPtr &reply)
{
    if (reply->success) {
        m_inferiorPid = reply->reply.toUInt();
        showMessage(QString::fromLatin1("Inferior pid: %1."), LogMisc);
        notifyInferiorSetupOk();
    }  else {
        showMessage(QString::fromLatin1("Failed to determine inferior pid: %1").
                    arg(QLatin1String(reply->errorMessage)), LogError);
        notifyInferiorSetupFailed();
    }
}

// Parse CDB gdbmi register syntax
1188
static inline Register parseRegister(const GdbMi &gdbmiReg)
1189
{
1190
    Register reg;
1191
    reg.name = gdbmiReg.findChild("name").data();
1192 1193
    const GdbMi description = gdbmiReg.findChild("description");
    if (description.type() != GdbMi::Invalid) {
1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204
        reg.name += " (";
        reg.name += description.data();
        reg.name += ')';
    }
    reg.value = QString::fromAscii(gdbmiReg.findChild("value").data());
    return reg;
}

void CdbEngine::handleModules(const CdbExtensionCommandPtr &reply)
{
    if (reply->success) {
1205
        GdbMi value;
1206
        value.fromString(reply->reply);
1207 1208
        if (value.type() == GdbMi::List) {
            Modules modules;
1209
            modules.reserve(value.childCount());
1210 1211
            foreach (const GdbMi &gdbmiModule, value.children()) {
                Module module;
1212 1213
                module.moduleName = QString::fromAscii(gdbmiModule.findChild("name").data());
                module.modulePath = QString::fromAscii(gdbmiModule.findChild("image").data());
1214 1215
                module.startAddress = gdbmiModule.findChild("start").data().toULongLong(0, 0);
                module.endAddress = gdbmiModule.findChild("end").data().toULongLong(0, 0);
1216 1217
                if (gdbmiModule.findChild("deferred").type() == GdbMi::Invalid)
                    module.symbolsRead = Module::ReadOk;
1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235
                modules.push_back(module);
            }
            modulesHandler()->setModules(modules);
        } else {
            showMessage(QString::fromLatin1("Parse error in modules response."), LogError);
            qWarning("Parse error in modules response:\n%s", reply->reply.constData());
        }
    }  else {
        showMessage(QString::fromLatin1("Failed to determine modules: %1").
                    arg(QLatin1String(reply->errorMessage)), LogError);
    }
    postCommandSequence(reply->commandSequence);

}

void CdbEngine::handleRegisters(const CdbExtensionCommandPtr &reply)
{
    if (reply->success) {
1236
        GdbMi value;
1237
        value.fromString(reply->reply);
1238 1239
        if (value.type() == GdbMi::List) {
            Registers registers;
1240
            registers.reserve(value.childCount());
1241
            foreach (const GdbMi &gdbmiReg, value.children())
1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257
                registers.push_back(parseRegister(gdbmiReg));
            registerHandler()->setRegisters(registers);
        } else {
            showMessage(QString::fromLatin1("Parse error in registers response."), LogError);
            qWarning("Parse error in registers response:\n%s", reply->reply.constData());
        }
    }  else {
        showMessage(QString::fromLatin1("Failed to determine registers: %1").
                    arg(QLatin1String(reply->errorMessage)), LogError);
    }
    postCommandSequence(reply->commandSequence);
}

void CdbEngine::handleLocals(const CdbExtensionCommandPtr &reply)
{
    if (reply->success) {
1258
        QList<WatchData> watchData;
1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276
        GdbMi root;
        root.fromString(reply->reply);
        QTC_ASSERT(root.isList(), return ; )
        if (debugLocals) {
            qDebug() << root.toString(true, 4);
        }
        // Courtesy of GDB engine
        foreach (const GdbMi &child, root.children()) {
            WatchData dummy;
            dummy.iname = child.findChild("iname").data();
            dummy.name = QLatin1String(child.findChild("name").data());
            parseWatchData(watchHandler()->expandedINames(), dummy, child, &watchData);
        }
        watchHandler()->insertBulkData(watchData);
        watchHandler()->endCycle();
        if (debugLocals) {
            QDebug nsp = qDebug().nospace();
            nsp << "Obtained " << watchData.size() << " items:\n";
1277
            foreach (const WatchData &wd, watchData)
1278
                nsp << wd.toString() <<'\n';
1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347
        }
    } else {
        showMessage(QString::fromLatin1(reply->errorMessage), LogError);
    }
}

void CdbEngine::handleExpandLocals(const CdbExtensionCommandPtr &reply)
{
    if (!reply->success)
        showMessage(QString::fromLatin1(reply->errorMessage), LogError);
}

enum CdbExecutionStatus {
CDB_STATUS_NO_CHANGE=0, CDB_STATUS_GO = 1, CDB_STATUS_GO_HANDLED = 2,
CDB_STATUS_GO_NOT_HANDLED = 3, CDB_STATUS_STEP_OVER = 4,
CDB_STATUS_STEP_INTO = 5, CDB_STATUS_BREAK = 6, CDB_STATUS_NO_DEBUGGEE = 7,
CDB_STATUS_STEP_BRANCH = 8, CDB_STATUS_IGNORE_EVENT = 9,
CDB_STATUS_RESTART_REQUESTED = 10, CDB_STATUS_REVERSE_GO = 11,
CDB_STATUS_REVERSE_STEP_BRANCH = 12, CDB_STATUS_REVERSE_STEP_OVER = 13,
CDB_STATUS_REVERSE_STEP_INTO = 14 };

static const char *cdbStatusName(unsigned long s)
{
    switch (s) {
    case CDB_STATUS_NO_CHANGE:
        return "No change";
    case CDB_STATUS_GO:
        return "go";
    case CDB_STATUS_GO_HANDLED:
        return "go_handled";
    case CDB_STATUS_GO_NOT_HANDLED:
        return "go_not_handled";
    case CDB_STATUS_STEP_OVER:
        return "step_over";
    case CDB_STATUS_STEP_INTO:
        return "step_into";
    case CDB_STATUS_BREAK:
        return "break";
    case CDB_STATUS_NO_DEBUGGEE:
        return "no_debuggee";
    case CDB_STATUS_STEP_BRANCH:
        return "step_branch";
    case CDB_STATUS_IGNORE_EVENT:
        return "ignore_event";
    case CDB_STATUS_RESTART_REQUESTED:
        return "restart_requested";
    case CDB_STATUS_REVERSE_GO:
        return "reverse_go";
    case CDB_STATUS_REVERSE_STEP_BRANCH:
        return "reverse_step_branch";
    case CDB_STATUS_REVERSE_STEP_OVER:
        return "reverse_step_over";
    case CDB_STATUS_REVERSE_STEP_INTO:
        return "reverse_step_into";
    }
    return "unknown";
}

void CdbEngine::handleSessionIdle(const QByteArray &message)
{
    if (!m_hasDebuggee)
        return;

    if (debug)
        qDebug("CdbEngine::handleSessionIdle %dms '%s' in state '%s', special mode %d",
               elapsedLogTime(), message.constData(),
               stateName(state()), m_specialStopMode);

    // Switch source level debugging
1348
    syncOperateByInstruction(m_operateByInstructionPending);
1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389

    const SpecialStopMode specialStopMode =  m_specialStopMode;
    m_specialStopMode = NoSpecialStop;

    switch(specialStopMode) {
    case SpecialStopSynchronizeBreakpoints:
        if (debug)
            qDebug("attemptBreakpointSynchronization in special stop");
        attemptBreakpointSynchronization();
        doContinueInferior();
        return;
    case NoSpecialStop:
        break;
    }
    switch(state()) { // Temporary stop at beginning
    case EngineSetupRequested:
        if (debug)
            qDebug("notifyEngineSetupOk");
        notifyEngineSetupOk();
        return;
    case InferiorSetupRequested:
        return;
    case InferiorStopRequested:
    case InferiorRunOk:
        break; // Proper stop of inferior handled below.

    default:
        qWarning("WARNING: CdbEngine::handleSessionAccessible called in state %s", stateName(state()));
        return;
    }
    // Handle stop.
    if (state() == InferiorStopRequested) {
        if (debug)
            qDebug("notifyInferiorStopOk");
        notifyInferiorStopOk();
    } else {
        if (debug)
            qDebug("notifyInferiorSpontaneousStop");
        notifyInferiorSpontaneousStop();
    }
    // Start sequence to get all relevant data. Hack: Avoid module reload?
1390
    unsigned sequence = CommandListStack|CommandListThreads;
1391 1392 1393
    if (debuggerCore()->isDockVisible(QLatin1String(Constants::DOCKWIDGET_REGISTER)))
        sequence |= CommandListRegisters;
    if (debuggerCore()->isDockVisible(QLatin1String(Constants::DOCKWIDGET_MODULES)))
1394 1395 1396
        sequence |= CommandListModules;
    postCommandSequence(sequence);
    // Report stop reason (GDBMI)
1397
    GdbMi stopReason;
1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409
    stopReason.fromString(message);
    if (debug)
        qDebug("%s", stopReason.toString(true, 4).constData());
    const QByteArray reason = stopReason.findChild("reason").data();
    if (reason.isEmpty()) {
        showStatusMessage(tr("Malformed stop response received."), LogError);
        return;
    }
    const int threadId = stopReason.findChild("threadId").data().toInt();
    if (reason == "breakpoint") {
        const int number = stopReason.findChild("breakpointId").data().toInt();
        const BreakpointId id = breakHandler()->findBreakpointByNumber(number);
1410
        if (id && breakHandler()->type(id) == Watchpoint) {
1411 1412 1413 1414 1415 1416 1417 1418 1419 1420
            showStatusMessage(msgWatchpointTriggered(id, number, breakHandler()->address(id), QString::number(threadId)));
        } else {
            showStatusMessage(msgBreakpointTriggered(id, number, QString::number(threadId)));
        }
        return;
    }
    if (reason == "exception") {
        WinException exception;
        exception.fromGdbMI(stopReason);
#ifdef Q_OS_WIN
1421 1422 1423 1424
        // It is possible to hit on a startup trap while stepping (if something
        // pulls DLLs. Avoid showing a 'stopped' Message box.
        if (exception.exceptionCode == winExceptionStartupCompleteTrap)
            return;
1425
        if (isDebuggerWinException(exception.exceptionCode)) {
1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517
            showStatusMessage(msgInterrupted());
            return;
        }
#endif
        const QString description = exception.toString();
        showStatusMessage(msgStoppedByException(description, QString::number(threadId)));
        showStoppedByExceptionMessageBox(description);
        return;
    }
    showStatusMessage(msgStopped(QLatin1String(reason)));
}

void CdbEngine::handleSessionAccessible(unsigned long cdbExState)
{
    const DebuggerState s = state();
    if (!m_hasDebuggee || s == InferiorRunOk) // suppress reports
        return;

    if (debug)
        qDebug("CdbEngine::handleSessionAccessible %dms in state '%s'/'%s', special mode %d",
               elapsedLogTime(), cdbStatusName(cdbExState), stateName(state()), m_specialStopMode);

    switch(s) {
    case EngineShutdownRequested:
        shutdownEngine();
        break;
    case InferiorShutdownRequested:
        shutdownInferior();
        break;
    default:
        break;
    }
}

void CdbEngine::handleSessionInaccessible(unsigned long cdbExState)
{
    const DebuggerState s = state();

    // suppress reports
    if (!m_hasDebuggee || (s == InferiorRunOk && cdbExState != CDB_STATUS_NO_DEBUGGEE))
        return;

    if (debug)
        qDebug("CdbEngine::handleSessionInaccessible %dms in state '%s', '%s', special mode %d",
               elapsedLogTime(), cdbStatusName(cdbExState), stateName(state()), m_specialStopMode);

    switch (state()) {
    case EngineSetupRequested:
        break;
    case EngineRunRequested:
        if (debug)
            qDebug("notifyEngineRunAndInferiorRunOk");
        notifyEngineRunAndInferiorRunOk();
        break;
    case InferiorRunOk:
    case InferiorStopOk:
        // Inaccessible without debuggee (exit breakpoint)
        // We go for spontaneous engine shutdown instead.
        if (cdbExState == CDB_STATUS_NO_DEBUGGEE) {
            if (debug)
                qDebug("Lost debuggeee");
            m_hasDebuggee = false;
        }
        break;
    case InferiorRunRequested:
        if (debug)
            qDebug("notifyInferiorRunOk");
        notifyInferiorRunOk();
        resetLocation();
        break;
    case EngineShutdownRequested:
        break;
    default:
        break;
    }
}

void CdbEngine::handleExtensionMessage(char t, int token, const QByteArray &what, const QByteArray &message)
{
    if (debug > 1) {
        QDebug nospace = qDebug().nospace();
        nospace << "handleExtensionMessage " << t << ' ' << token << ' ' << what
                << ' ' << stateName(state());
        if (t == 'N' || debug > 1) {
            nospace << ' ' << message;
        } else {
            nospace << ' ' << message.size() << " bytes";
        }
    }

    // Is there a reply expected, some command queued?
    if (t == 'R' || t == 'N') {
1518 1519 1520 1521
        if (token == -1) { // Default token, user typed in extension command
            showMessage(QString::fromLatin1(message), LogMisc);
            return;
        }
1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 <