cdbengine.cpp 89.4 KB
Newer Older
1 2 3 4
/**************************************************************************
**
** This file is part of Qt Creator
**
con's avatar
con committed
5
** Copyright (c) 2011 Nokia Corporation and/or its subsidiary(-ies).
6 7 8
**
** 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
#include <utils/winutils.h>
#include <utils/qtcassert.h>
#include <utils/savedaction.h>
67
#include <utils/consoleprocess.h>
68 69 70 71 72 73 74

#include <QtCore/QCoreApplication>
#include <QtCore/QFileInfo>
#include <QtCore/QDir>
#include <QtCore/QDebug>
#include <QtCore/QTextStream>
#include <QtCore/QDateTime>
75
#include <QtGui/QToolTip>
76 77
#include <QtGui/QMainWindow>
#include <QtGui/QMessageBox>
78 79 80 81 82 83 84 85

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

#include <cctype>

86 87
Q_DECLARE_METATYPE(Debugger::Internal::DisassemblerAgent*)
Q_DECLARE_METATYPE(Debugger::Internal::MemoryAgent*)
88 89

enum { debug = 0 };
90
enum { debugLocals = 0 };
91
enum { debugWatches = 0 };
92 93 94
enum { debugBreakpoints = 0 };

#if 0
95
#  define STATE_DEBUG(state, func, line, notifyFunc) qDebug("%s in %s at %s:%d", notifyFunc, stateName(state), func, line);
96
#else
97
#  define STATE_DEBUG(state, func, line, notifyFunc)
98 99
#endif

100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153
/*!
    \class Debugger::Internal::CdbEngine

    Cdb engine 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), which is loaded into cdb.exe. It serves to:

    \list
    \o Notify the engine about the state of the debugging session:
        \list
        \o idle: (hooked up with .idle_cmd) debuggee stopped
        \o accessible: Debuggee stopped, cdb.exe accepts commands
        \o inaccessible: Debuggee runs, no way to post commands
        \o session active/inactive: Lost debuggee, terminating.
        \endlist
    \o Hook up with output/event callbacks and produce formatted output to be able
       to catch application output and exceptions.
    \o Provide some extension commands that produce output in a standardized (GDBMI)
      format that ends up in handleExtensionMessage(), for example:
      \list
      \o pid     Return debuggee pid for interrupting.
      \o locals  Print locals from SymbolGroup
      \o expandLocals Expand locals in symbol group
      \o registers, modules, threads
      \endlist
   \endlist

   Debugger commands can be posted by calling:

   \list

    \o postCommand(): Does not expect a reply
    \o 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.
    \o postExtensionCommand(): Run a command provided by the extension producing
       one-line output and invoke a callback with a CdbExtensionCommand structure
       (output is potentially split up in chunks).
    \endlist


    Startup sequence:
    [Console: The console stub launches the process. On process startup,
              launchCDB() is called with AttachExternal].
    setupEngine() calls launchCDB() with the startparameters. The debuggee
    runs into the initial breakpoint (session idle). EngineSetupOk is
    notified (inferior still stopped). setupInferior() is then called
    which does breakpoint synchronization and issues the extension 'pid'
    command to obtain the inferior pid (which also hooks up the output callbacks).
     handlePid() notifies notifyInferiorSetupOk.
    runEngine() is then called which issues 'g' to continue the inferior.
    Shutdown mostly uses notifyEngineSpontaneousShutdown() as cdb just quits
    when the inferior exits (except attach modes).
*/
154

155 156
using namespace ProjectExplorer;

157
namespace Debugger {
158
namespace Internal {
159

160 161
static const char localsPrefixC[] = "local.";

hjk's avatar
hjk committed
162 163
struct MemoryViewCookie
{
164
    explicit MemoryViewCookie(MemoryAgent *a = 0, QObject *e = 0,
165
                              quint64 addr = 0, quint64 l = 0) :
hjk's avatar
hjk committed
166 167
        agent(a), editorToken(e), address(addr), length(l)
    {}
168

169
    MemoryAgent *agent;
170 171 172 173 174
    QObject *editorToken;
    quint64 address;
    quint64 length;
};

hjk's avatar
hjk committed
175 176
struct SourceLocationCookie
{
177 178 179 180 181 182 183
    explicit SourceLocationCookie(const QString &f = QString(), int l = 0) :
             fileName(f), lineNumber(l) {}

    QString fileName;
    int lineNumber;
};

184
} // namespace Internal
185 186
} // namespace Debugger

187 188
Q_DECLARE_METATYPE(Debugger::Internal::MemoryViewCookie)
Q_DECLARE_METATYPE(Debugger::Internal::SourceLocationCookie)
189 190

namespace Debugger {
191
namespace Internal {
192

193
static inline bool isConsole(const DebuggerStartParameters &sp)
hjk's avatar
hjk committed
194 195 196 197
{
    return (sp.startMode == StartInternal || sp.startMode == StartExternal)
        && sp.useTerminal;
}
198

hjk's avatar
hjk committed
199 200
static QMessageBox *
nonModalMessageBox(QMessageBox::Icon icon, const QString &title, const QString &text)
201 202 203 204 205 206 207 208
{
    QMessageBox *mb = new QMessageBox(icon, title, text, QMessageBox::Ok,
                                      debuggerCore()->mainWindow());
    mb->setAttribute(Qt::WA_DeleteOnClose);
    mb->show();
    return mb;
}

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
// 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) :
hjk's avatar
hjk committed
247 248
        CdbCommandBase(cmd, token, flags, nc, cookie), handler(h)
    {}
249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311


    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;
}

312
static inline QString msgCdbDisabled(ToolChainType tc)
313 314
{
    return CdbEngine::tr("The CDB debug engine required for %1 is currently disabled.").
315
                      arg(ToolChain::toolChainName(tc));
316 317
}

318
// Accessed by RunControlFactory
319 320
DebuggerEngine *createCdbEngine(const DebuggerStartParameters &sp,
    DebuggerEngine *masterEngine, QString *errorMessage)
321 322 323
{
#ifdef Q_OS_WIN
    CdbOptionsPage *op = CdbOptionsPage::instance();
324
    if (!op || !op->options()->isValid()) {
325
        *errorMessage = msgCdbDisabled(sp.toolChainType);
326 327 328 329 330 331
        return 0;
    }
    if (!validMode(sp.startMode)) {
        *errorMessage = CdbEngine::tr("The CDB debug engine does not support start mode %1.").arg(sp.startMode);
        return 0;
    }
332
    return new CdbEngine(sp, masterEngine, op->options());
333
#else
334
    Q_UNUSED(masterEngine)
335 336
    Q_UNUSED(sp)
#endif
337
    *errorMessage = QString::fromLatin1("Unsupported debug mode");
338 339 340 341 342 343
    return 0;
}

bool isCdbEngineEnabled()
{
#ifdef Q_OS_WIN
344
    return CdbOptionsPage::instance() && CdbOptionsPage::instance()->options()->isValid();
345 346 347 348 349
#else
    return false;
#endif
}

350
ConfigurationCheck checkCdbConfiguration(ToolChainType toolChain)
351
{
352
    ConfigurationCheck check;
353
    switch (toolChain) {
354 355 356 357 358 359
    case ToolChain_MinGW: // Do our best
    case ToolChain_MSVC:
    case ToolChain_WINCE:
    case ToolChain_OTHER:
    case ToolChain_UNKNOWN:
    case ToolChain_INVALID:
360
        if (!isCdbEngineEnabled()) {
361 362
            check.errorMessage = msgCdbDisabled(toolChain);
            check.settingsPage = CdbOptionsPage::settingsId();
363 364 365 366
        }
        break;
    default:
        //: %1 is something like "GCCE" or "Intel C++ Compiler (Linux)" (see ToolChain context)
367 368 369
        check.errorMessage = CdbEngine::tr("The CDB debug engine does not support the %1 toolchain.").
                    arg(ToolChain::toolChainName(toolChain));
        check.settingsPage = CdbOptionsPage::settingsId();
370
    }
371
    return check;
372 373
}

374
void addCdbOptionPages(QList<Core::IOptionsPage *> *opts)
375
{
376
#ifdef Q_OS_WIN
377
    opts->push_back(new CdbOptionsPage);
378 379 380
#else
    Q_UNUSED(opts);
#endif
381 382 383 384 385 386
}

#define QT_CREATOR_CDB_EXT "qtcreatorcdbext"

static inline Utils::SavedAction *theAssemblerAction()
{
387
    return debuggerCore()->action(OperateByInstruction);
388 389
}

390 391 392
CdbEngine::CdbEngine(const DebuggerStartParameters &sp,
        DebuggerEngine *masterEngine, const OptionsPtr &options) :
    DebuggerEngine(sp, masterEngine),
393 394 395
    m_creatorExtPrefix("<qtcreatorcdbext>|"),
    m_tokenPrefix("<token>"),
    m_options(options),
396
    m_effectiveStartMode(NoStartMode),
397 398 399 400 401 402 403 404 405 406
    m_inferiorPid(0),
    m_accessible(false),
    m_specialStopMode(NoSpecialStop),
    m_nextCommandToken(0),
    m_currentBuiltinCommandIndex(-1),
    m_extensionCommandPrefixBA("!"QT_CREATOR_CDB_EXT"."),
    m_operateByInstructionPending(true),
    m_operateByInstruction(true), // Default CDB setting
    m_notifyEngineShutdownOnTermination(false),
    m_hasDebuggee(false),
407
    m_elapsedLogTime(0),
408
    m_sourceStepInto(false),
409 410 411
    m_wX86BreakpointCount(0),
    m_watchPointX(0),
    m_watchPointY(0)
412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429
{
    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)
{
430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445
    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);
446 447 448 449
}

void CdbEngine::setToolTipExpression(const QPoint &mousePos, TextEditor::ITextEditor *editor, int cursorPos)
{
450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465
    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;
466
    const QByteArray iname = QByteArray(localsPrefixC) + exp.toAscii();
467 468 469 470 471
    const QModelIndex index = watchHandler()->itemIndex(iname);
    if (index.isValid()) {
        showDebuggerToolTip(mousePos, watchHandler()->modelForIName(iname), index.row());
    } else {
        hideDebuggerToolTip();
472
    }
473 474 475
}

// Determine full path to the CDB extension library.
476
QString CdbEngine::extensionLibraryName(bool is64Bit)
477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522
{
    // 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;
}

523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545
// Start the console stub with the sub process. Continue in consoleStubProcessStarted.
bool CdbEngine::startConsole(const DebuggerStartParameters &sp, QString *errorMessage)
{
    if (debug)
        qDebug("startConsole %s", qPrintable(sp.executable));
    m_consoleStub.reset(new Utils::ConsoleProcess);
    m_consoleStub->setMode(Utils::ConsoleProcess::Suspend);
    connect(m_consoleStub.data(), SIGNAL(processMessage(QString, bool)),
            SLOT(consoleStubMessage(QString, bool)));
    connect(m_consoleStub.data(), SIGNAL(processStarted()),
            SLOT(consoleStubProcessStarted()));
    connect(m_consoleStub.data(), SIGNAL(wrapperStopped()),
            SLOT(consoleStubExited()));
    m_consoleStub->setWorkingDirectory(sp.workingDirectory);
    m_consoleStub->setEnvironment(sp.environment);
    if (!m_consoleStub->start(sp.executable, sp.processArgs)) {
        *errorMessage = tr("The console process '%1' could not be started.").arg(sp.executable);
        return false;
    }
    return true;
}

void CdbEngine::consoleStubMessage(const QString &msg, bool isError)
546
{
547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594
    if (debug)
        qDebug("consoleStubProcessMessage() in %s error=%d %s", stateName(state()), isError, qPrintable(msg));
    if (isError) {
        if (state() == EngineSetupRequested) {
            STATE_DEBUG(state(), Q_FUNC_INFO, __LINE__, "notifyEngineSetupFailed")
            notifyEngineSetupFailed();
        } else {
            STATE_DEBUG(state(), Q_FUNC_INFO, __LINE__, "notifyEngineIll")
            notifyEngineIll();
        }
        nonModalMessageBox(QMessageBox::Critical, tr("Debugger Error"), msg);
    } else {
        showMessage(msg, AppOutput);
    }
}

void CdbEngine::consoleStubProcessStarted()
{
    if (debug)
        qDebug("consoleStubProcessStarted() PID=%lld", m_consoleStub->applicationPID());
    // Attach to console process.
    DebuggerStartParameters attachParameters = startParameters();
    attachParameters.executable.clear();
    attachParameters.processArgs.clear();
    attachParameters.attachPID = m_consoleStub->applicationPID();
    attachParameters.startMode = AttachExternal;
    showMessage(QString::fromLatin1("Attaching to %1...").arg(attachParameters.attachPID), LogMisc);
    QString errorMessage;
    if (!launchCDB(attachParameters, &errorMessage)) {
        showMessage(errorMessage, LogError);
        STATE_DEBUG(state(), Q_FUNC_INFO, __LINE__, "notifyEngineSetupFailed")
        notifyEngineSetupFailed();
    }
}

void CdbEngine::consoleStubExited()
{
}

void CdbEngine::setupEngine()
{
    if (debug)
        qDebug(">setupEngine");
    // Nag to add symbol server
    if (CdbSymbolPathListEditor::promptToAddSymbolServer(CdbOptions::settingsGroup(),
                                                         &(m_options->symbolPaths)))
        m_options->toSettings(Core::ICore::instance()->settings());

595
    m_logTime.start();
596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619
    QString errorMessage;
    // Console: Launch the stub with the suspended application and attach to it
    // CDB in theory has a command line option '-2' that launches a
    // console, too, but that immediately closes when the debuggee quits.
    // Use the Creator stub instead.
    const DebuggerStartParameters &sp = startParameters();
    const bool launchConsole = isConsole(sp);
    m_effectiveStartMode = launchConsole ? AttachExternal : sp.startMode;
    const bool ok = launchConsole ?
                startConsole(startParameters(), &errorMessage) :
                launchCDB(startParameters(), &errorMessage);
    if (debug)
        qDebug("<setupEngine ok=%d", ok);
    if (!ok) {
        showMessage(errorMessage, LogError);
        STATE_DEBUG(state(), Q_FUNC_INFO, __LINE__, "notifyEngineSetupFailed")
        notifyEngineSetupFailed();
    }
}

bool CdbEngine::launchCDB(const DebuggerStartParameters &sp, QString *errorMessage)
{
    if (debug)
        qDebug("launchCDB startMode=%d", sp.startMode);
620
    const QChar blank(QLatin1Char(' '));
621
    // Start engine which will run until initial breakpoint:
622 623 624
    // 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)
625
    const QFileInfo extensionFi(CdbEngine::extensionLibraryName(m_options->is64bit));
626 627 628 629 630
    if (!extensionFi.isFile()) {
        *errorMessage = QString::fromLatin1("Internal error: The extension %1 cannot be found.").
                arg(QDir::toNativeSeparators(extensionFi.absoluteFilePath()));
        return false;
    }
631
    const QString extensionFileName = extensionFi.fileName();
632 633
    // Prepare arguments
    QStringList arguments;
634 635 636 637 638 639
    const bool isRemote = sp.startMode == AttachToRemote;
    if (isRemote) { // Must be first
        arguments << QLatin1String("-remote") << sp.remoteChannel;
    } else {
        arguments << (QLatin1String("-a") + extensionFileName);
    }
640 641 642 643 644 645 646 647 648 649 650
    // 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(';')));
651 652
    // Compile argument string preserving quotes
    QString nativeArguments = m_options->additionalArguments;
653 654 655
    switch (sp.startMode) {
    case StartInternal:
    case StartExternal:
656 657 658
        if (!nativeArguments.isEmpty())
            nativeArguments.push_back(blank);
        nativeArguments += QDir::toNativeSeparators(sp.executable);
659
        break;
660 661
    case AttachToRemote:
        break;
662
    case AttachExternal:
663
    case AttachCrashedExternal:
664 665 666 667 668 669 670 671
        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;
    }
672 673 674 675 676 677
    if (!sp.processArgs.isEmpty()) { // Complete native argument string.
        if (!nativeArguments.isEmpty())
            nativeArguments.push_back(blank);
        nativeArguments += sp.processArgs;
    }

678 679 680
    const QString executable = m_options->executable;
    const QString msg = QString::fromLatin1("Launching %1 %2\nusing %3 of %4.").
            arg(QDir::toNativeSeparators(executable),
681
                arguments.join(QString(blank)) + blank + nativeArguments,
682 683 684 685 686 687
                QDir::toNativeSeparators(extensionFi.absoluteFilePath()),
                extensionFi.lastModified().toString(Qt::SystemLocaleShortDate));
    showMessage(msg, LogMisc);

    m_outputBuffer.clear();
    m_process.setEnvironment(mergeEnvironment(sp.environment.toStringList(), extensionFi.absolutePath()));
688 689
    if (!sp.workingDirectory.isEmpty())
        m_process.setWorkingDirectory(sp.workingDirectory);
690

691
#ifdef Q_OS_WIN
692 693
    if (!nativeArguments.isEmpty()) // Appends
        m_process.setNativeArguments(nativeArguments);
694
#endif
695 696 697 698 699 700 701 702 703 704 705 706 707 708
    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;
709 710 711 712 713
    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);
714
        STATE_DEBUG(state(), Q_FUNC_INFO, __LINE__, "notifyEngineSetupOk")
715 716
        notifyEngineSetupOk();
    }
717 718 719 720 721
    return true;
}

void CdbEngine::setupInferior()
{
722 723
    if (debug)
        qDebug("setupInferior");
724 725 726 727 728 729
    attemptBreakpointSynchronization();
    postExtensionCommand("pid", QByteArray(), 0, &CdbEngine::handlePid);
}

void CdbEngine::runEngine()
{
730 731
    if (debug)
        qDebug("runEngine");
732 733 734
    // Resume the threads frozen by the console stub.
    if (isConsole(startParameters()))
        postCommand("~* m", 0);
735 736
    foreach (const QString &breakEvent, m_options->breakEvents)
            postCommand(QByteArray("sxe ") + breakEvent.toAscii(), 0);
737 738 739
    postCommand("g", 0);
}

740 741 742 743 744
bool CdbEngine::commandsPending() const
{
    return !m_builtinCommandQueue.isEmpty() || !m_extensionCommandQueue.isEmpty();
}

745 746 747 748 749 750 751 752 753
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");
754
        STATE_DEBUG(state(), Q_FUNC_INFO, __LINE__, "notifyInferiorShutdownOk")
755 756 757
        notifyInferiorShutdownOk();
        return;
    }
758
    if (!canInterruptInferior() || commandsPending()) {
759
        STATE_DEBUG(state(), Q_FUNC_INFO, __LINE__, "notifyInferiorShutdownFailed")
760 761 762 763
        notifyInferiorShutdownFailed();
        return;
    }

764
    if (m_accessible) {
765
        if (m_effectiveStartMode == AttachExternal || m_effectiveStartMode == AttachCrashedExternal)
766
            detachDebugger();
767
        STATE_DEBUG(state(), Q_FUNC_INFO, __LINE__, "notifyInferiorShutdownOk")
768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784
        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)
785 786 787 788
        qDebug("CdbEngine::shutdownEngine in state '%s', process running %d,"
               "accessible=%d,commands pending=%d",
               stateName(state()), isCdbProcessRunning(), m_accessible,
               commandsPending());
789 790

    if (!isCdbProcessRunning()) { // Direct launch: Terminated with process.
791
        STATE_DEBUG(state(), Q_FUNC_INFO, __LINE__, "notifyEngineShutdownOk")
792 793 794 795
        notifyEngineShutdownOk();
        return;
    }

796 797 798 799 800 801
    // 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.
802
        if (m_effectiveStartMode == AttachExternal)
803
            detachDebugger();
804
        // Remote requires a bit more force to quit.
805
        if (m_effectiveStartMode == AttachToRemote) {
806 807 808 809 810 811 812 813 814
            postCommand(m_extensionCommandPrefixBA + "shutdownex", 0);
            postCommand("qq", 0);
        } else {
            postCommand("q", 0);
        }
        m_notifyEngineShutdownOnTermination = true;
        return;
    } else {
        // Remote process. No can do, currently
815
        m_notifyEngineShutdownOnTermination = true;
816
        Utils::SynchronousProcess::stopProcess(m_process);
817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844
        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");
845
            STATE_DEBUG(state(), Q_FUNC_INFO, __LINE__, "notifyEngineIll")
846 847
            notifyEngineIll();
        } else {
848
            STATE_DEBUG(state(), Q_FUNC_INFO, __LINE__, "notifyEngineShutdownOk")
849 850 851
            notifyEngineShutdownOk();
        }
    } else {
852
        STATE_DEBUG(state(), Q_FUNC_INFO, __LINE__, "notifyEngineSpontaneousShutdown")
853 854 855 856 857 858 859 860 861
        notifyEngineSpontaneousShutdown();
    }
}

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

862 863 864 865 866
static inline bool isWatchIName(const QByteArray &iname)
{
    return iname.startsWith("watch");
}

867 868
void CdbEngine::updateWatchData(const WatchData &dataIn,
                                const WatchUpdateFlags & flags)
869
{
870 871 872
    if (debug || debugLocals || debugWatches)
        qDebug("CdbEngine::updateWatchData() %dms accessible=%d %s incr=%d: %s",
               elapsedLogTime(), m_accessible, stateName(state()),
873 874 875
               flags.tryIncremental,
               qPrintable(dataIn.toString()));

876 877 878 879 880 881 882 883 884 885 886 887 888 889 890
    if (!m_accessible) // Add watch data while running?
        return;

    // New watch item?
    if (isWatchIName(dataIn.iname) && dataIn.isValueNeeded()) {
        QByteArray args;
        ByteArrayInputStream str(args);
        str << dataIn.iname << " \"" << dataIn.exp << '"';
        postExtensionCommand("addwatch", args, 0,
                             &CdbEngine::handleAddWatch, 0,
                             qVariantFromValue(dataIn));
        return;
    }

    if (!dataIn.hasChildren && !dataIn.isValueNeeded()) {
891
        WatchData data = dataIn;
892 893 894 895 896 897 898
        data.setAllUnneeded();
        watchHandler()->insertData(data);
        return;
    }
    updateLocalVariable(dataIn.iname);
}

899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914
void CdbEngine::handleAddWatch(const CdbExtensionCommandPtr &reply)
{
    WatchData item = qvariant_cast<WatchData>(reply->cookie);
    if (debugWatches)
        qDebug() << "handleAddWatch ok="  << reply->success << item.iname;
    if (reply->success) {
        updateLocalVariable(item.iname);
    } else {
        item.setError(tr("Unable to add expression"));
        watchHandler()->insertData(item);
        showMessage(QString::fromLatin1("Unable to add watch item '%1'/'%2': %3").
                    arg(QString::fromAscii(item.iname), QString::fromAscii(item.exp),
                        reply->errorMessage), LogError);
    }
}

915 916
void CdbEngine::addLocalsOptions(ByteArrayInputStream &str) const
{
917 918
    if (debuggerCore()->boolSetting(VerboseLog))
        str << blankSeparator << "-v";
919 920 921 922 923 924 925 926 927 928
    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;
}

929 930
void CdbEngine::updateLocalVariable(const QByteArray &iname)
{
931 932 933 934 935 936 937 938 939 940 941 942 943
    const bool isWatch = isWatchIName(iname);
    if (debugWatches)
        qDebug() << "updateLocalVariable watch=" << isWatch << iname;
    QByteArray localsArguments;
    ByteArrayInputStream str(localsArguments);
    addLocalsOptions(str);
    if (!isWatch) {
        const int stackFrame = stackHandler()->currentIndex();
        if (stackFrame < 0) {
            qWarning("Internal error; no stack frame in updateLocalVariable");
            return;
        }
        str << blankSeparator << stackFrame;
944
    }
945 946
    str << blankSeparator << iname;
    postExtensionCommand(isWatch ? "watches" : "locals", localsArguments, 0, &CdbEngine::handleLocals);
947 948 949 950 951
}

unsigned CdbEngine::debuggerCapabilities() const
{
    return DisassemblerCapability | RegisterCapability | ShowMemoryCapability
952
           |WatchpointCapability|JumpToLineCapability|AddWatcherCapability
953 954
           |BreakOnThrowAndCatchCapability // Sort-of: Can break on throw().
           |BreakModuleCapability;
955 956 957 958
}

void CdbEngine::executeStep()
{
959 960
    if (!m_operateByInstruction)
        m_sourceStepInto = true; // See explanation at handleStackTrace().
961
    postCommand(QByteArray("t"), 0); // Step into-> t (trace)
962
    STATE_DEBUG(state(), Q_FUNC_INFO, __LINE__, "notifyInferiorRunRequested")
963 964 965 966 967 968
    notifyInferiorRunRequested();
}

void CdbEngine::executeStepOut()
{
    postCommand(QByteArray("gu"), 0); // Step out-> gu (go up)
969
    STATE_DEBUG(state(), Q_FUNC_INFO, __LINE__, "notifyInferiorRunRequested")
970 971 972 973 974 975
    notifyInferiorRunRequested();
}

void CdbEngine::executeNext()
{
    postCommand(QByteArray("p"), 0); // Step over -> p
976
    STATE_DEBUG(state(), Q_FUNC_INFO, __LINE__, "notifyInferiorRunRequested")
977 978 979 980 981 982 983 984 985 986 987 988 989 990 991
    notifyInferiorRunRequested();
}

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

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

void CdbEngine::continueInferior()
{
992
    STATE_DEBUG(state(), Q_FUNC_INFO, __LINE__, "notifyInferiorRunRequested")
993 994 995 996 997 998 999 1000 1001
    notifyInferiorRunRequested();
    doContinueInferior();
}

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

1002 1003
bool CdbEngine::canInterruptInferior() const
{
1004
    return m_effectiveStartMode != AttachToRemote;
1005 1006
}

1007 1008
void CdbEngine::interruptInferior()
{
1009 1010 1011 1012
    if (canInterruptInferior()) {
        doInterruptInferior(NoSpecialStop);
    } else {
        showMessage(tr("Interrupting is not possible in remote sessions."), LogError);
1013
        STATE_DEBUG(state(), Q_FUNC_INFO, __LINE__, "notifyInferiorStopOk")
1014
        notifyInferiorStopOk();
1015
        STATE_DEBUG(state(), Q_FUNC_INFO, __LINE__, "notifyInferiorRunRequested")
1016
        notifyInferiorRunRequested();
1017
        STATE_DEBUG(state(), Q_FUNC_INFO, __LINE__, "notifyInferiorRunOk")
1018 1019
        notifyInferiorRunOk();
    }
1020 1021 1022 1023 1024 1025 1026 1027
}

void CdbEngine::doInterruptInferior(SpecialStopMode sm)
{
#ifdef Q_OS_WIN
    const SpecialStopMode oldSpecialMode = m_specialStopMode;
    m_specialStopMode = sm;
    QString errorMessage;
1028
    if (!winDebugBreakProcess(m_inferiorPid, &errorMessage)) {
1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039
        m_specialStopMode = oldSpecialMode;
        showMessage(errorMessage, LogError);
    }
#else
    Q_UNUSED(sm)
#endif
}

void CdbEngine::executeRunToLine(const QString &fileName, int lineNumber)
{
    // Add one-shot breakpoint
1040
    BreakpointParameters bp(BreakpointByFileAndLine);
1041 1042
    bp.fileName = fileName;
    bp.lineNumber = lineNumber;
1043
    postCommand(cdbAddBreakpointCommand(bp, BreakpointId(-1), true), 0);
1044 1045 1046 1047 1048 1049
    continueInferior();
}

void CdbEngine::executeRunToFunction(const QString &functionName)
{
    // Add one-shot breakpoint
1050
    BreakpointParameters bp(BreakpointByFunction);
1051 1052
    bp.functionName = functionName;

1053
    postCommand(cdbAddBreakpointCommand(bp, BreakpointId(-1), true), 0);
1054 1055 1056 1057 1058
    continueInferior();
}

void CdbEngine::setRegisterValue(int regnr, const QString &value)
{
1059
    const Registers registers = registerHandler()->registers();
1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094
    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);
1095 1096
    // PC-register depending on 64/32bit.
    str << "r " << (m_options->is64bit ? "rip" : "eip") << "=0x" << answer;
1097
    postCommand(registerCmd, 0);
1098
    gotoLocation(Location(cookie.fileName, cookie.lineNumber));
1099 1100
}

1101
void CdbEngine::assignValueInDebugger(const WatchData *w, const QString &expr, const QVariant &value)
1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114
{
    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);
1115 1116 1117
    // Update all locals in case we change a union or something pointed to
    // that affects other variables, too.
    updateLocals();
1118 1119
}

1120 1121 1122 1123 1124 1125 1126 1127 1128
void CdbEngine::parseThreads(const GdbMi &data, int forceCurrentThreadId /* = -1 */)
{
    int currentThreadId;
    Threads threads = ThreadsHandler::parseGdbmiThreads(data, &currentThreadId);
    threadsHandler()->setThreads(threads);
    threadsHandler()->setCurrentThreadId(forceCurrentThreadId >= 0 ?
                                         forceCurrentThreadId : currentThreadId);
}

1129 1130 1131 1132 1133
void CdbEngine::handleThreads(const CdbExtensionCommandPtr &reply)
{
    if (debug)
        qDebug("CdbEngine::handleThreads success=%d", reply->success);
    if (reply->success) {
1134
        GdbMi data;
1135
        data.fromString(reply->reply);
1136
        parseThreads(data);
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 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220
        // 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 <<