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

hjk's avatar
hjk committed
30
#include "cdbdebugengine.h"
31
#include "cdbdebugengine_p.h"
32
#include "cdbstacktracecontext.h"
33 34
#include "cdbstackframecontext.h"
#include "cdbsymbolgroupcontext.h"
Friedemann Kleint's avatar
Friedemann Kleint committed
35
#include "cdbbreakpoint.h"
36 37
#include "cdbmodules.h"
#include "cdbassembler.h"
38 39
#include "cdboptionspage.h"
#include "cdboptions.h"
Banana Joe's avatar
Banana Joe committed
40

41
#include "debuggeractions.h"
Banana Joe's avatar
Banana Joe committed
42 43 44
#include "debuggermanager.h"
#include "breakhandler.h"
#include "stackhandler.h"
45
#include "watchhandler.h"
46 47
#include "registerhandler.h"
#include "moduleshandler.h"
48
#include "disassemblerhandler.h"
49
#include "watchutils.h"
Banana Joe's avatar
Banana Joe committed
50

51
#include <coreplugin/icore.h>
52
#include <utils/qtcassert.h>
Friedemann Kleint's avatar
Friedemann Kleint committed
53
#include <utils/winutils.h>
54
#include <utils/consoleprocess.h>
55
#include <texteditor/itexteditor.h>
56

Friedemann Kleint's avatar
Friedemann Kleint committed
57
#include <QtCore/QDebug>
58
#include <QtCore/QTimer>
Friedemann Kleint's avatar
Friedemann Kleint committed
59 60 61
#include <QtCore/QTimerEvent>
#include <QtCore/QFileInfo>
#include <QtCore/QDir>
Friedemann Kleint's avatar
Friedemann Kleint committed
62
#include <QtCore/QLibrary>
63
#include <QtCore/QCoreApplication>
64 65
#include <QtGui/QMessageBox>
#include <QtGui/QMainWindow>
66
#include <QtGui/QApplication>
67
#include <QtGui/QToolTip>
Banana Joe's avatar
Banana Joe committed
68 69

#define DBGHELP_TRANSLATE_TCHAR
70
#include <inc/Dbghelp.h>
Banana Joe's avatar
Banana Joe committed
71

72
static const char *dbgHelpDllC = "dbghelp";
Friedemann Kleint's avatar
Friedemann Kleint committed
73 74
static const char *dbgEngineDllC = "dbgeng";
static const char *debugCreateFuncC = "DebugCreate";
Banana Joe's avatar
Banana Joe committed
75

76 77 78 79 80
static const char *localSymbolRootC = "local";

namespace Debugger {
namespace Internal {

Friedemann Kleint's avatar
Friedemann Kleint committed
81 82
typedef QList<WatchData> WatchList;

83 84
// ----- Message helpers

85
QString msgDebugEngineComResult(HRESULT hr)
Friedemann Kleint's avatar
Friedemann Kleint committed
86 87
{
    switch (hr) {
88 89 90 91
        case S_OK:
        return QLatin1String("S_OK");
        case S_FALSE:
        return QLatin1String("S_FALSE");
Friedemann Kleint's avatar
Friedemann Kleint committed
92 93 94 95 96 97 98 99 100 101 102
        case E_FAIL:
        break;
        case E_INVALIDARG:
        return QLatin1String("E_INVALIDARG");
        case E_NOINTERFACE:
        return QLatin1String("E_NOINTERFACE");
        case E_OUTOFMEMORY:
        return QLatin1String("E_OUTOFMEMORY");
        case E_UNEXPECTED:
        return QLatin1String("E_UNEXPECTED");
        case E_NOTIMPL:
103
        return QLatin1String("E_NOTIMPL");
Friedemann Kleint's avatar
Friedemann Kleint committed
104 105 106 107 108
    }
    if (hr == HRESULT_FROM_WIN32(ERROR_ACCESS_DENIED))
        return QLatin1String("ERROR_ACCESS_DENIED");;
    if (hr == HRESULT_FROM_NT(STATUS_CONTROL_C_EXIT))
        return QLatin1String("STATUS_CONTROL_C_EXIT");
109
    return QLatin1String("E_FAIL ") + Core::Utils::winErrorMessage(HRESULT_CODE(hr));
Friedemann Kleint's avatar
Friedemann Kleint committed
110 111
}

112 113 114 115 116
static QString msgStackIndexOutOfRange(int idx, int size)
{
    return QString::fromLatin1("Frame index %1 out of range (%2).").arg(idx).arg(size);
}

117
QString msgComFailed(const char *func, HRESULT hr)
118 119 120 121
{
    return QString::fromLatin1("%1 failed: %2").arg(QLatin1String(func), msgDebugEngineComResult(hr));
}

122
static const char *msgNoStackTraceC = "Internal error: no stack trace present.";
Friedemann Kleint's avatar
Friedemann Kleint committed
123

124 125 126 127 128 129
static inline QString msgLibLoadFailed(const QString &lib, const QString &why)
{
    return CdbDebugEngine::tr("Unable to load the debugger engine library '%1': %2").
            arg(lib, why);
}

130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145
// Format function failure message. Pass in Q_FUNC_INFO
static QString msgFunctionFailed(const char *func, const QString &why)
{
    // Strip a "cdecl_ int namespace1::class::foo(int bar)" as
    // returned by Q_FUNC_INFO down to "foo"
    QString function = QLatin1String(func);
    const int firstParentPos = function.indexOf(QLatin1Char('('));
    if (firstParentPos != -1)
        function.truncate(firstParentPos);
    const int classSepPos = function.lastIndexOf(QLatin1String("::"));
    if (classSepPos != -1)
        function.remove(0, classSepPos + 2);
   //: Function call failed
   return CdbDebugEngine::tr("The function \"%1()\" failed: %2").arg(function, why);
}

146 147
// ----- Engine helpers

148
static inline ULONG getInterruptTimeOutSecs(CIDebugControl *ctl)
149 150 151 152 153 154
{
    ULONG rc = 0;
    ctl->GetInterruptTimeout(&rc);
    return rc;
}

155 156 157
bool getExecutionStatus(CIDebugControl *ctl,
                        ULONG *executionStatus,
                        QString *errorMessage /* = 0 */)
158 159 160
{
    const HRESULT hr = ctl->GetExecutionStatus(executionStatus);
    if (FAILED(hr)) {
161 162
        if (errorMessage)
            *errorMessage = msgComFailed("GetExecutionStatus", hr);
163 164 165 166 167
        return false;
    }
    return true;
}

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
const char *executionStatusString(ULONG executionStatus)
{
    switch (executionStatus) {
    case DEBUG_STATUS_NO_CHANGE:
        return "DEBUG_STATUS_NO_CHANGE";
    case DEBUG_STATUS_GO:
        return "DEBUG_STATUS_GO";
    case DEBUG_STATUS_GO_HANDLED:
        return "DEBUG_STATUS_GO_HANDLED";
    case DEBUG_STATUS_GO_NOT_HANDLED:
        return "DEBUG_STATUS_GO_NOT_HANDLED";
    case DEBUG_STATUS_STEP_OVER:
        return "DEBUG_STATUS_STEP_OVER";
    case DEBUG_STATUS_STEP_INTO:
        return "DEBUG_STATUS_STEP_INTO";
    case DEBUG_STATUS_BREAK:
        return "DEBUG_STATUS_BREAK";
    case DEBUG_STATUS_NO_DEBUGGEE:
        return "DEBUG_STATUS_NO_DEBUGGEE";
    case DEBUG_STATUS_STEP_BRANCH:
        return "DEBUG_STATUS_STEP_BRANCH";
    case DEBUG_STATUS_IGNORE_EVENT:
        return "DEBUG_STATUS_IGNORE_EVENT";
    case DEBUG_STATUS_RESTART_REQUESTED:
        return "DEBUG_STATUS_RESTART_REQUESTED";
    case DEBUG_STATUS_REVERSE_GO:
        return "DEBUG_STATUS_REVERSE_GO";
          case DEBUG_STATUS_REVERSE_STEP_BRANCH:
        return "DEBUG_STATUS_REVERSE_STEP_BRANCH";
    case DEBUG_STATUS_REVERSE_STEP_OVER:
        return "DEBUG_STATUS_REVERSE_STEP_OVER";
    case DEBUG_STATUS_REVERSE_STEP_INTO:
        return "DEBUG_STATUS_REVERSE_STEP_INTO";
        default:
        break;
    }
    return "<Unknown execution status>";
}

// Debug convenience
const char *executionStatusString(CIDebugControl *ctl)
{
    ULONG executionStatus;
    if (getExecutionStatus(ctl, &executionStatus))
        return executionStatusString(executionStatus);
    return "<failed>";
}

216
// --------- DebuggerEngineLibrary
Friedemann Kleint's avatar
Friedemann Kleint committed
217 218 219 220 221
DebuggerEngineLibrary::DebuggerEngineLibrary() :
    m_debugCreate(0)
{
}

222 223
// Build a lib name as "Path\x.dll"
static inline QString libPath(const QString &libName, const QString &path = QString())
Friedemann Kleint's avatar
Friedemann Kleint committed
224
{
225 226 227 228 229 230 231
    QString rc = path;
    if (!rc.isEmpty())
        rc += QDir::separator();
    rc += libName;
    rc += QLatin1String(".dll");
    return rc;
}
Friedemann Kleint's avatar
Friedemann Kleint committed
232

233 234 235 236 237 238 239 240 241 242 243 244
bool DebuggerEngineLibrary::init(const QString &path, QString *errorMessage)
{
    // Load the dependent help lib first
    const QString helpLibPath = libPath(QLatin1String(dbgHelpDllC), path);
    QLibrary helpLib(helpLibPath, 0);
    if (!helpLib.isLoaded() && !helpLib.load()) {
        *errorMessage = msgLibLoadFailed(helpLibPath, helpLib.errorString());
        return false;
    }
    // Load dbgeng lib
    const QString engineLibPath = libPath(QLatin1String(dbgEngineDllC), path);
    QLibrary lib(engineLibPath, 0);
Friedemann Kleint's avatar
Friedemann Kleint committed
245
    if (!lib.isLoaded() && !lib.load()) {
246
        *errorMessage = msgLibLoadFailed(engineLibPath, lib.errorString());
Friedemann Kleint's avatar
Friedemann Kleint committed
247 248 249 250 251 252 253 254 255 256 257 258 259
        return false;
    }
    // Locate symbols
    void *createFunc = lib.resolve(debugCreateFuncC);
    if (!createFunc) {
        *errorMessage = CdbDebugEngine::tr("Unable to resolve '%1' in the debugger engine library '%2'").
                        arg(QLatin1String(debugCreateFuncC), QLatin1String(dbgEngineDllC));
        return false;
    }
    m_debugCreate = static_cast<DebugCreateFunction>(createFunc);
    return true;
}

260
// ----- SyntaxSetter
261
SyntaxSetter::SyntaxSetter(CIDebugControl *ctl, ULONG desiredSyntax) :
Friedemann Kleint's avatar
Friedemann Kleint committed
262 263 264 265 266 267 268 269 270 271 272 273 274 275
    m_desiredSyntax(desiredSyntax),
    m_ctl(ctl)
{
    m_ctl->GetExpressionSyntax(&m_oldSyntax);
    if (m_oldSyntax != m_desiredSyntax)
        m_ctl->SetExpressionSyntax(m_desiredSyntax);
}

SyntaxSetter::~SyntaxSetter()
{
    if (m_oldSyntax != m_desiredSyntax)
        m_ctl->SetExpressionSyntax(m_oldSyntax);
}

276 277 278 279 280 281 282 283 284 285 286
// CdbComInterfaces
CdbComInterfaces::CdbComInterfaces() :
    debugClient(0),
    debugControl(0),
    debugSystemObjects(0),
    debugSymbols(0),
    debugRegisters(0),
    debugDataSpaces(0)
{
}

Friedemann Kleint's avatar
Friedemann Kleint committed
287 288
// --- CdbDebugEnginePrivate

289 290 291 292
CdbDebugEnginePrivate::CdbDebugEnginePrivate(DebuggerManager *parent,
                                             const QSharedPointer<CdbOptions> &options,
                                             CdbDebugEngine* engine) :
    m_options(options),
Banana Joe's avatar
Banana Joe committed
293 294
    m_hDebuggeeProcess(0),
    m_hDebuggeeThread(0),
295
    m_breakEventMode(BreakEventHandle),
296
    m_dumper(new CdbDumperHelper(parent, &m_cif)),
Banana Joe's avatar
Banana Joe committed
297
    m_watchTimer(-1),
298
    m_debugEventCallBack(engine),
Friedemann Kleint's avatar
Friedemann Kleint committed
299 300
    m_engine(engine),
    m_debuggerManager(parent),
301
    m_debuggerManagerAccess(parent->engineInterface()),
302
    m_currentStackTrace(0),
303
    m_firstActivatedFrame(true),
304
    m_mode(AttachCore)
305
{
306 307 308
}

bool CdbDebugEnginePrivate::init(QString *errorMessage)
Banana Joe's avatar
Banana Joe committed
309
{
310 311
    // Load the DLL
    DebuggerEngineLibrary lib;
312
    if (!lib.init(m_options->path, errorMessage))
313 314 315
        return false;

    // Initialize the COM interfaces
Banana Joe's avatar
Banana Joe committed
316
    HRESULT hr;
317
    hr = lib.debugCreate( __uuidof(IDebugClient5), reinterpret_cast<void**>(&m_cif.debugClient));
Friedemann Kleint's avatar
Friedemann Kleint committed
318
    if (FAILED(hr)) {
319 320
        *errorMessage = QString::fromLatin1("Creation of IDebugClient5 failed: %1").arg(msgDebugEngineComResult(hr));
        return false;
Friedemann Kleint's avatar
Friedemann Kleint committed
321 322
    }

323 324
    m_cif.debugClient->SetOutputCallbacksWide(&m_debugOutputCallBack);
    m_cif.debugClient->SetEventCallbacksWide(&m_debugEventCallBack);
325

326
    hr = lib.debugCreate( __uuidof(IDebugControl4), reinterpret_cast<void**>(&m_cif.debugControl));
Friedemann Kleint's avatar
Friedemann Kleint committed
327
    if (FAILED(hr)) {
328 329
        *errorMessage = QString::fromLatin1("Creation of IDebugControl4 failed: %1").arg(msgDebugEngineComResult(hr));
        return false;
Friedemann Kleint's avatar
Friedemann Kleint committed
330 331
    }

332
    m_cif.debugControl->SetCodeLevel(DEBUG_LEVEL_SOURCE);
333

334
    hr = lib.debugCreate( __uuidof(IDebugSystemObjects4), reinterpret_cast<void**>(&m_cif.debugSystemObjects));
335 336 337 338
    if (FAILED(hr)) {
        *errorMessage = QString::fromLatin1("Creation of IDebugSystemObjects4 failed: %1").arg(msgDebugEngineComResult(hr));
        return false;
    }
Friedemann Kleint's avatar
Friedemann Kleint committed
339

340
    hr = lib.debugCreate( __uuidof(IDebugSymbols3), reinterpret_cast<void**>(&m_cif.debugSymbols));
341 342 343 344
    if (FAILED(hr)) {
        *errorMessage = QString::fromLatin1("Creation of IDebugSymbols3 failed: %1").arg(msgDebugEngineComResult(hr));
        return false;
    }
Friedemann Kleint's avatar
Friedemann Kleint committed
345

346
    hr = lib.debugCreate( __uuidof(IDebugRegisters2), reinterpret_cast<void**>(&m_cif.debugRegisters));
347 348
    if (FAILED(hr)) {
        *errorMessage = QString::fromLatin1("Creation of IDebugRegisters2 failed: %1").arg(msgDebugEngineComResult(hr));
349
        return false;
350
    }
351 352 353 354 355 356 357

    hr = lib.debugCreate( __uuidof(IDebugDataSpaces4), reinterpret_cast<void**>(&m_cif.debugDataSpaces));
    if (FAILED(hr)) {
        *errorMessage = QString::fromLatin1("Creation of IDebugDataSpaces4 failed: %1").arg(msgDebugEngineComResult(hr));
        return false;
    }

358
    if (debugCDB)
359
        qDebug() << QString::fromLatin1("CDB Initialization succeeded, interrupt time out %1s.").arg(getInterruptTimeOutSecs(m_cif.debugControl));
360
    return true;
Friedemann Kleint's avatar
Friedemann Kleint committed
361
}
Banana Joe's avatar
Banana Joe committed
362

363 364 365
IDebuggerEngine *CdbDebugEngine::create(DebuggerManager *parent,
                                        const QSharedPointer<CdbOptions> &options,
                                        QString *errorMessage)
Friedemann Kleint's avatar
Friedemann Kleint committed
366
{
367
    CdbDebugEngine *rc = new CdbDebugEngine(parent, options);
368 369
    if (rc->m_d->init(errorMessage)) {
        rc->syncDebuggerPaths();
370
        return rc;
371
    }
372 373
    delete rc;
    return 0;
Banana Joe's avatar
Banana Joe committed
374 375
}

376
CdbDebugEnginePrivate::~CdbDebugEnginePrivate()
Banana Joe's avatar
Banana Joe committed
377
{
378
    cleanStackTrace();
379 380 381 382 383 384 385 386 387 388 389 390
    if (m_cif.debugClient)
        m_cif.debugClient->Release();
    if (m_cif.debugControl)
        m_cif.debugControl->Release();
    if (m_cif.debugSystemObjects)
        m_cif.debugSystemObjects->Release();
    if (m_cif.debugSymbols)
        m_cif.debugSymbols->Release();
    if (m_cif.debugRegisters)
        m_cif.debugRegisters->Release();
    if (m_cif.debugDataSpaces)
        m_cif.debugDataSpaces->Release();
Banana Joe's avatar
Banana Joe committed
391 392
}

393
void CdbDebugEnginePrivate::clearForRun()
394 395 396 397
{
    if (debugCDB)
        qDebug() << Q_FUNC_INFO;

398 399 400
    m_breakEventMode = BreakEventHandle;
    m_firstActivatedFrame = false;
    cleanStackTrace();
401
    m_editorToolTipCache.clear();
402 403 404
}

void CdbDebugEnginePrivate::cleanStackTrace()
405
{
406 407 408 409 410 411
    if (m_currentStackTrace) {
        delete m_currentStackTrace;
        m_currentStackTrace = 0;
    }
}

412
CdbDebugEngine::CdbDebugEngine(DebuggerManager *parent, const QSharedPointer<CdbOptions> &options) :
Friedemann Kleint's avatar
Friedemann Kleint committed
413
    IDebuggerEngine(parent),
414
    m_d(new CdbDebugEnginePrivate(parent, options, this))
415
{
416
    m_d->m_consoleStubProc.setMode(Core::Utils::ConsoleProcess::Suspend);
417 418 419
    connect(&m_d->m_consoleStubProc, SIGNAL(processError(QString)), this, SLOT(slotConsoleStubError(QString)));
    connect(&m_d->m_consoleStubProc, SIGNAL(processStarted()), this, SLOT(slotConsoleStubStarted()));
    connect(&m_d->m_consoleStubProc, SIGNAL(wrapperStopped()), this, SLOT(slotConsoleStubTerminated()));
420 421 422 423
    connect(&m_d->m_debugOutputCallBack, SIGNAL(debuggerOutput(QString,QString)),
            m_d->m_debuggerManager, SLOT(showDebuggerOutput(QString,QString)));
    connect(&m_d->m_debugOutputCallBack, SIGNAL(debuggerInputPrompt(QString,QString)),
            m_d->m_debuggerManager, SLOT(showDebuggerInput(QString,QString)));
424 425 426 427
    connect(&m_d->m_debugOutputCallBack, SIGNAL(debuggeeOutput(QString)),
            m_d->m_debuggerManager, SLOT(showApplicationOutput(QString)));
    connect(&m_d->m_debugOutputCallBack, SIGNAL(debuggeeInputPrompt(QString)),
            m_d->m_debuggerManager, SLOT(showApplicationOutput(QString)));
428 429 430 431 432 433 434
}

CdbDebugEngine::~CdbDebugEngine()
{
    delete m_d;
}

hjk's avatar
hjk committed
435
void CdbDebugEngine::startWatchTimer()
Banana Joe's avatar
Banana Joe committed
436
{
437 438 439
    if (debugCDB)
        qDebug() << Q_FUNC_INFO;

440 441
    if (m_d->m_watchTimer == -1)
        m_d->m_watchTimer = startTimer(0);
Banana Joe's avatar
Banana Joe committed
442 443
}

hjk's avatar
hjk committed
444
void CdbDebugEngine::killWatchTimer()
Banana Joe's avatar
Banana Joe committed
445
{
446 447 448
    if (debugCDB)
        qDebug() << Q_FUNC_INFO;

449 450 451
    if (m_d->m_watchTimer != -1) {
        killTimer(m_d->m_watchTimer);
        m_d->m_watchTimer = -1;
Banana Joe's avatar
Banana Joe committed
452 453 454
    }
}

hjk's avatar
hjk committed
455
void CdbDebugEngine::shutdown()
Banana Joe's avatar
Banana Joe committed
456 457 458 459
{
    exitDebugger();
}

460
QString CdbDebugEngine::editorToolTip(const QString &exp, const QString &function)
Banana Joe's avatar
Banana Joe committed
461
{
462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486
    // Figure the editor tooltip. Ask the frame context of the
    // function if it is a local variable it knows. If that is not
    // the case, try to evaluate via debugger
    QString errorMessage;
    QString rc;
    // Find the frame of the function if there is any
    CdbStackFrameContext *frame = 0;
    if (m_d->m_currentStackTrace &&  !function.isEmpty()) {
        const int frameIndex = m_d->m_currentStackTrace->indexOf(function);
        if (frameIndex != -1)
            frame = m_d->m_currentStackTrace->frameContextAt(frameIndex, &errorMessage);
    }
    if (frame && frame->editorToolTip(QLatin1String("local.") + exp, &rc, &errorMessage))
        return rc;
    // No function/symbol context found, try to evaluate in current context.
    // Do not append type as this will mostly be 'long long' for integers, etc.
    QString type;
    if (!evaluateExpression(exp, &rc, &type, &errorMessage))
        return QString();
    return rc;
}

void CdbDebugEngine::setToolTipExpression(const QPoint &mousePos, TextEditor::ITextEditor *editor, int cursorPos)
{
    typedef CdbDebugEnginePrivate::EditorToolTipCache EditorToolTipCache;
487
    if (debugCDB)
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
        qDebug() << Q_FUNC_INFO << '\n' << cursorPos;
    // Need a stopped debuggee and a cpp file
    if (!m_d->m_hDebuggeeProcess || m_d->isDebuggeeRunning())
        return;
    if (!isCppEditor(editor))
        return;
    // Determine expression and function
    QString toolTip;
    do {
        int line;
        int column;
        QString function;
        const QString exp = cppExpressionAt(editor, cursorPos, &line, &column, &function);
        if (function.isEmpty() || exp.isEmpty())
            break;
        // Check cache (key containing function) or try to figure out expression
        QString cacheKey = function;
        cacheKey += QLatin1Char('@');
        cacheKey += exp;
        const EditorToolTipCache::const_iterator cit = m_d->m_editorToolTipCache.constFind(cacheKey);
        if (cit != m_d->m_editorToolTipCache.constEnd()) {
            toolTip = cit.value();
        } else {
            toolTip = editorToolTip(exp, function);
            if (!toolTip.isEmpty())
                m_d->m_editorToolTipCache.insert(cacheKey, toolTip);
        }
    } while (false);
    // Display
    QToolTip::hideText();
    if (!toolTip.isEmpty())
        QToolTip::showText(mousePos, toolTip);
Banana Joe's avatar
Banana Joe committed
520 521
}

522 523 524 525 526 527 528
void CdbDebugEnginePrivate::clearDisplay()
{
    m_debuggerManagerAccess->threadsHandler()->removeAll();
    m_debuggerManagerAccess->modulesHandler()->removeAll();
    m_debuggerManagerAccess->registerHandler()->removeAll();
}

529
bool CdbDebugEngine::startDebugger(const QSharedPointer<DebuggerStartParameters> &sp)
530
{
531 532 533 534
    if (m_d->m_hDebuggeeProcess) {
        warning(QLatin1String("Internal error: Attempt to start debugger while another process is being debugged."));
        return false;
    }
535
    m_d->clearDisplay();
536

537
    const DebuggerStartMode mode = m_d->m_debuggerManager->startMode();
538
    // Figure out dumper. @TODO: same in gdb...
539
    const QString dumperLibName = QDir::toNativeSeparators(m_d->m_debuggerManagerAccess->qtDumperLibraryName());
540 541 542
    bool dumperEnabled = mode != AttachCore
                         && mode != AttachCrashedExternal
                         && !dumperLibName.isEmpty()
543
                         && m_d->m_debuggerManagerAccess->qtDumperLibraryEnabled();
544 545 546 547
    if (dumperEnabled) {
        const QFileInfo fi(dumperLibName);
        if (!fi.isFile()) {
            const QString msg = tr("The dumper library '%1' does not exist.").arg(dumperLibName);
548
            m_d->m_debuggerManagerAccess->showQtDumperLibraryWarning(msg);
549 550 551
            dumperEnabled = false;
        }
    }
552
    m_d->m_dumper->reset(dumperLibName, dumperEnabled);
Friedemann Kleint's avatar
Friedemann Kleint committed
553
    m_d->m_debuggerManager->showStatusMessage("Starting Debugger", -1);
Friedemann Kleint's avatar
Friedemann Kleint committed
554 555
    QString errorMessage;
    bool rc = false;
556
    bool needWatchTimer = false;
557
    m_d->clearForRun();
558
    switch (mode) {
Friedemann Kleint's avatar
Friedemann Kleint committed
559
    case AttachExternal:
560 561 562
    case AttachCrashedExternal:
        rc = startAttachDebugger(sp->attachPID, mode, &errorMessage);
        needWatchTimer = true; // Fetch away module load, etc. even if crashed
Friedemann Kleint's avatar
Friedemann Kleint committed
563 564 565
        break;
    case StartInternal:
    case StartExternal:
566
        if (sp->useTerminal) {
567 568
            // Launch console stub and wait for its startup
            m_d->m_consoleStubProc.stop(); // We leave the console open, so recycle it now.
569 570 571
            m_d->m_consoleStubProc.setWorkingDirectory(sp->workingDir);
            m_d->m_consoleStubProc.setEnvironment(sp->environment);
            rc = m_d->m_consoleStubProc.start(sp->executable, sp->processArgs);
572
            if (!rc)
573
                errorMessage = tr("The console stub process was unable to start '%1'.").arg(sp->executable);
574
            // continues in slotConsoleStubStarted()...
575
        } else {
576
            needWatchTimer = true;
577 578
            rc = startDebuggerWithExecutable(mode, &errorMessage);
        }
Friedemann Kleint's avatar
Friedemann Kleint committed
579 580
        break;
    case AttachCore:
581
        errorMessage = tr("Attaching to core files is not supported!");
Friedemann Kleint's avatar
Friedemann Kleint committed
582 583 584
        break;
    }
    if (rc) {
585
        m_d->m_debuggerManager->showStatusMessage(tr("Debugger running"), -1);
586 587
        if (needWatchTimer)
            startWatchTimer();
Friedemann Kleint's avatar
Friedemann Kleint committed
588
    } else {
589
        warning(errorMessage);
Friedemann Kleint's avatar
Friedemann Kleint committed
590 591 592
    }
    return rc;
}
Banana Joe's avatar
Banana Joe committed
593

594
bool CdbDebugEngine::startAttachDebugger(qint64 pid, DebuggerStartMode sm, QString *errorMessage)
Friedemann Kleint's avatar
Friedemann Kleint committed
595
{
596
    // Need to attrach invasively, otherwise, no notification signals
597
    // for for CreateProcess/ExitProcess occur.
598 599
    const ULONG flags = DEBUG_ATTACH_INVASIVE_RESUME_PROCESS;
    const HRESULT hr = m_d->m_cif.debugClient->AttachProcess(NULL, pid, flags);
Friedemann Kleint's avatar
Friedemann Kleint committed
600
    if (debugCDB)
601
        qDebug() << "Attaching to " << pid << " returns " << hr << executionStatusString(m_d->m_cif.debugControl);
Friedemann Kleint's avatar
Friedemann Kleint committed
602
    if (FAILED(hr)) {
603
        *errorMessage = tr("Attaching to a process failed for process id %1: %2").arg(pid).arg(msgDebugEngineComResult(hr));
Friedemann Kleint's avatar
Friedemann Kleint committed
604
        return false;
605
    } else {
606
        m_d->m_mode = sm;
Friedemann Kleint's avatar
Friedemann Kleint committed
607 608 609 610
    }
    return true;
}

611
bool CdbDebugEngine::startDebuggerWithExecutable(DebuggerStartMode sm, QString *errorMessage)
Friedemann Kleint's avatar
Friedemann Kleint committed
612 613
{
    m_d->m_debuggerManager->showStatusMessage("Starting Debugger", -1);
Banana Joe's avatar
Banana Joe committed
614 615 616 617 618

    DEBUG_CREATE_PROCESS_OPTIONS dbgopts;
    memset(&dbgopts, 0, sizeof(dbgopts));
    dbgopts.CreateFlags = DEBUG_PROCESS | DEBUG_ONLY_THIS_PROCESS;

619 620
    const QSharedPointer<DebuggerStartParameters> sp = m_d->m_debuggerManager->startParameters();
    const QString filename(sp->executable);
Friedemann Kleint's avatar
Friedemann Kleint committed
621 622
    if (debugCDB)
        qDebug() << Q_FUNC_INFO <<filename;
Banana Joe's avatar
Banana Joe committed
623

Friedemann Kleint's avatar
Friedemann Kleint committed
624
    const QFileInfo fi(filename);
625
    m_d->m_cif.debugSymbols->AppendImagePathWide(reinterpret_cast<PCWSTR>(QDir::toNativeSeparators(fi.absolutePath()).utf16()));
626 627 628
    //m_cif.debugSymbols->SetSymbolOptions(SYMOPT_CASE_INSENSITIVE | SYMOPT_UNDNAME | SYMOPT_DEBUG | SYMOPT_LOAD_LINES | SYMOPT_OMAP_FIND_NEAREST | SYMOPT_AUTO_PUBLICS);
    m_d->m_cif.debugSymbols->SetSymbolOptions(SYMOPT_CASE_INSENSITIVE | SYMOPT_UNDNAME | SYMOPT_LOAD_LINES | SYMOPT_OMAP_FIND_NEAREST | SYMOPT_AUTO_PUBLICS);
    //m_cif.debugSymbols->AddSymbolOptions(SYMOPT_CASE_INSENSITIVE | SYMOPT_UNDNAME | SYMOPT_DEFERRED_LOADS | SYMOPT_DEBUG | SYMOPT_LOAD_LINES | SYMOPT_OMAP_FIND_NEAREST | SYMOPT_AUTO_PUBLICS | SYMOPT_NO_IMAGE_SEARCH);
Banana Joe's avatar
Banana Joe committed
629

Friedemann Kleint's avatar
Friedemann Kleint committed
630
    // TODO console
631
    const QString cmd = Core::Utils::AbstractProcess::createWinCommandline(filename, sp->processArgs);
Friedemann Kleint's avatar
Friedemann Kleint committed
632 633 634 635
    if (debugCDB)
        qDebug() << "Starting " << cmd;
    PCWSTR env = 0;
    QByteArray envData;
636 637
    if (!sp->environment.empty()) {
        envData = Core::Utils::AbstractProcess::createWinEnvironment(Core::Utils::AbstractProcess::fixWinEnvironment(sp->environment));
Friedemann Kleint's avatar
Friedemann Kleint committed
638 639
        env = reinterpret_cast<PCWSTR>(envData.data());
    }
640
    const HRESULT hr = m_d->m_cif.debugClient->CreateProcess2Wide(NULL,
641
                                                               reinterpret_cast<PWSTR>(const_cast<ushort *>(cmd.utf16())),
Friedemann Kleint's avatar
Friedemann Kleint committed
642 643
                                                               &dbgopts,
                                                               sizeof(dbgopts),
644
                                                               reinterpret_cast<PCWSTR>(sp->workingDir.utf16()),
Friedemann Kleint's avatar
Friedemann Kleint committed
645 646
                                                               env);
    if (FAILED(hr)) {
647
        *errorMessage = tr("Unable to create a process '%1': %2").arg(cmd, msgDebugEngineComResult(hr));
Friedemann Kleint's avatar
Friedemann Kleint committed
648
        m_d->m_debuggerManagerAccess->notifyInferiorExited();
Friedemann Kleint's avatar
Friedemann Kleint committed
649
        return false;
650 651
    } else {
        m_d->m_mode = sm;
Banana Joe's avatar
Banana Joe committed
652
    }
Friedemann Kleint's avatar
Friedemann Kleint committed
653
    m_d->m_debuggerManagerAccess->notifyInferiorRunning();
Banana Joe's avatar
Banana Joe committed
654 655 656
    return true;
}

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
// check for a breakpoint at 'main()'
static inline bool hasBreakPointAtMain(const BreakHandler *bp)
{
    if (const int count = bp->size()) {
        // check all variations, resolved or not
        const QString main = QLatin1String("main");
        const QString qMain = QLatin1String("qMain");
        const QString moduleMainPattern = QLatin1String("!main");
        for (int i = 0; i < count ; i++) {
            const QString &function = bp->at(i)->funcName;
            if (function == main || function == qMain || function.endsWith(moduleMainPattern))
                return true;
        }
    }
    return false;
}

void CdbDebugEnginePrivate::processCreatedAttached(ULONG64 processHandle, ULONG64 initialThreadHandle)
{
    setDebuggeeHandles(reinterpret_cast<HANDLE>(processHandle), reinterpret_cast<HANDLE>(initialThreadHandle));
    m_debuggerManagerAccess->notifyInferiorRunning();
    ULONG currentThreadId;
    if (SUCCEEDED(m_cif.debugSystemObjects->GetThreadIdByHandle(initialThreadHandle, &currentThreadId))) {
        m_currentThreadId = currentThreadId;
    } else {
        m_currentThreadId = 0;
    }
684 685
    // Clear any saved breakpoints and set initial breakpoints
    m_engine->executeDebuggerCommand(QLatin1String("bc"));
686
    if (m_debuggerManagerAccess->breakHandler()->hasPendingBreakpoints())
687
        m_engine->attemptBreakpointSynchronization();
688 689 690 691 692 693 694 695 696 697 698
    // Attaching to crashed: This handshake (signalling an event) is required for
    // the exception to be delivered to the debugger
    if (m_mode == AttachCrashedExternal) {
        const QString crashParameter = m_debuggerManager->startParameters()->crashParameter;
        if (!crashParameter.isEmpty()) {
            ULONG64 evtNr = crashParameter.toULongLong();
            const HRESULT hr = m_cif.debugControl->SetNotifyEventHandle(evtNr);
            if (FAILED(hr))
                m_engine->warning(QString::fromLatin1("Handshake failed on event #%1: %2").arg(evtNr).arg(msgComFailed("SetNotifyEventHandle", hr)));
        }
    }
699 700
    if (debugCDB)
        qDebug() << Q_FUNC_INFO << '\n' << executionStatusString(m_cif.debugControl);
701 702
}

703 704 705 706 707
void CdbDebugEngine::processTerminated(unsigned long exitCode)
{
    if (debugCDB)
        qDebug() << Q_FUNC_INFO << exitCode;

708
    m_d->clearForRun();
709 710 711 712 713
    m_d->setDebuggeeHandles(0, 0);
    m_d->m_debuggerManagerAccess->notifyInferiorExited();
    m_d->m_debuggerManager->exitDebugger();
}

Friedemann Kleint's avatar
Friedemann Kleint committed
714 715
// End debugging using
void CdbDebugEnginePrivate::endDebugging(EndDebuggingMode em)
Banana Joe's avatar
Banana Joe committed
716
{
Friedemann Kleint's avatar
Friedemann Kleint committed
717
    enum Action { Detach, Terminate };
Friedemann Kleint's avatar
Friedemann Kleint committed
718
    if (debugCDB)
Friedemann Kleint's avatar
Friedemann Kleint committed
719 720 721 722 723 724 725 726
        qDebug() << Q_FUNC_INFO << em;

    if (m_mode == AttachCore || !m_hDebuggeeProcess)
        return;
    // Figure out action
    Action action;
    switch (em) {
    case EndDebuggingAuto:
727 728
        action = (m_mode == AttachExternal || m_mode == AttachCrashedExternal) ?
                 Detach : Terminate;
Friedemann Kleint's avatar
Friedemann Kleint committed
729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744
        break;
    case EndDebuggingDetach:
        action = Detach;
        break;
    case EndDebuggingTerminate:
        action = Terminate;
        break;
    }
    if (debugCDB)
        qDebug() << Q_FUNC_INFO << action;
    // Need a stopped debuggee to act
    QString errorMessage;
    const bool wasRunning = isDebuggeeRunning();
    if (wasRunning) { // Process must be stopped in order to terminate
        interruptInterferiorProcess(&errorMessage);
        QCoreApplication::processEvents(QEventLoop::ExcludeUserInputEvents);
745
    }
Friedemann Kleint's avatar
Friedemann Kleint committed
746 747 748 749 750 751 752 753 754 755 756 757 758
    HRESULT hr;
    switch (action) {
    case Detach:
        hr = m_cif.debugClient->DetachCurrentProcess();
        if (FAILED(hr))
            errorMessage += msgComFailed("DetachCurrentProcess", hr);
        break;
    case Terminate:
        hr = m_cif.debugClient->TerminateCurrentProcess();
        if (FAILED(hr))
            errorMessage += msgComFailed("TerminateCurrentProcess", hr);
        if (!wasRunning) {
            hr = m_cif.debugClient->TerminateProcesses();
759
            if (FAILED(hr))
Friedemann Kleint's avatar
Friedemann Kleint committed
760
                errorMessage += msgComFailed("TerminateProcesses", hr);
761
        }
Friedemann Kleint's avatar
Friedemann Kleint committed
762 763 764 765 766
        QCoreApplication::processEvents(QEventLoop::ExcludeUserInputEvents);
        break;
    }
    setDebuggeeHandles(0, 0);
    m_engine->killWatchTimer();
767 768 769 770 771 772

    // Clean up resources (open files, etc.)
    hr = m_cif.debugClient->EndSession(DEBUG_END_PASSIVE);
    if (FAILED(hr))
        errorMessage += msgComFailed("EndSession", hr);

Friedemann Kleint's avatar
Friedemann Kleint committed
773 774 775
    if (!errorMessage.isEmpty()) {
        errorMessage = QString::fromLatin1("There were errors trying to end debugging: %1").arg(errorMessage);
        m_debuggerManagerAccess->showDebuggerOutput(QLatin1String("error"), errorMessage);
776
        m_engine->warning(errorMessage);
777
    }
Friedemann Kleint's avatar
Friedemann Kleint committed
778 779 780 781 782 783 784 785 786 787
}

void CdbDebugEngine::exitDebugger()
{
    m_d->endDebugging();
}

void CdbDebugEngine::detachDebugger()
{
    m_d->endDebugging(CdbDebugEnginePrivate::EndDebuggingDetach);
Banana Joe's avatar
Banana Joe committed
788 789
}

790
CdbStackFrameContext *CdbDebugEnginePrivate::getStackFrameContext(int frameIndex, QString *errorMessage) const
791
{
792 793 794 795
    if (!m_currentStackTrace) {
        *errorMessage = QLatin1String(msgNoStackTraceC);
        return 0;
    }
796
    if (CdbStackFrameContext *sg = m_currentStackTrace->frameContextAt(frameIndex, errorMessage))
797 798
        return sg;
    return 0;
799 800
}

Friedemann Kleint's avatar
Friedemann Kleint committed
801 802 803 804 805 806 807 808 809 810 811 812 813 814 815
static inline QString formatWatchList(const WatchList &wl)
{
    const int count = wl.size();
    QString rc;
    for (int i = 0; i < count; i++) {
        if (i)
            rc += QLatin1String(", ");
        rc += wl.at(i).iname;
        rc += QLatin1String(" (");
        rc += wl.at(i).exp;
        rc += QLatin1Char(')');
    }
    return rc;
}

816 817 818 819
bool CdbDebugEnginePrivate::updateLocals(int frameIndex,
                                         WatchHandler *wh,
                                         QString *errorMessage)
{
Friedemann Kleint's avatar
Friedemann Kleint committed
820 821 822
    wh->reinitializeWatchers();

    QList<WatchData> incompletes = wh->takeCurrentIncompletes();
823
    if (debugCDB)
Friedemann Kleint's avatar
Friedemann Kleint committed
824 825 826
        qDebug() << Q_FUNC_INFO << "\n    " << frameIndex << formatWatchList(incompletes);

    m_engine->filterEvaluateWatchers(&incompletes, wh);
827
    if (!incompletes.empty()) {
Friedemann Kleint's avatar
Friedemann Kleint committed
828
        const QString msg = QLatin1String("Warning: Locals left in incomplete list: ") + formatWatchList(incompletes);
829
        m_engine->warning(msg);
Friedemann Kleint's avatar
Friedemann Kleint committed
830
    }
831

832
    bool success = false;
833 834
    if (CdbStackFrameContext *sgc = getStackFrameContext(frameIndex, errorMessage))
        success = sgc->populateModelInitially(wh, errorMessage);
835

836
    wh->rebuildModel();
837 838 839
    return success;
}

Friedemann Kleint's avatar
Friedemann Kleint committed
840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863
void CdbDebugEngine::evaluateWatcher(WatchData *wd)
{
    if (debugCDB > 1)
        qDebug() << Q_FUNC_INFO << wd->exp;
    QString errorMessage;
    QString value;
    QString type;
    if (evaluateExpression(wd->exp, &value, &type, &errorMessage)) {
        wd->setValue(value);
        wd->setType(type);
    } else {
        wd->setValue(errorMessage);
        wd->setTypeUnneeded();
    }
    wd->setChildCount(0);
}

void CdbDebugEngine::filterEvaluateWatchers(QList<WatchData> *wd, WatchHandler *wh)
{
    typedef QList<WatchData> WatchList;
    if (wd->empty())
        return;

    // Filter out actual watchers. Ignore the "<Edit>" top level place holders
864
    SyntaxSetter syntaxSetter(m_d->m_cif.debugControl, DEBUG_EXPR_CPLUSPLUS);
Friedemann Kleint's avatar
Friedemann Kleint committed
865 866 867 868 869 870
    const QString watcherPrefix = QLatin1String("watch.");
    const QChar lessThan = QLatin1Char('<');
    const QChar greaterThan = QLatin1Char('>');
    bool placeHolderSeen = false;
    for (WatchList::iterator it = wd->begin(); it != wd->end(); ) {
        if (it->iname.startsWith(watcherPrefix)) {
871
            const bool isPlaceHolder = it->exp.startsWith(lessThan) && it->exp.endsWith(greaterThan);
Friedemann Kleint's avatar
Friedemann Kleint committed
872 873 874 875 876 877 878 879 880 881
            if (isPlaceHolder) {
                if (!placeHolderSeen) { // Max one place holder
                    it->setChildCount(0);
                    it->setAllUnneeded();
                    wh->insertData(*it);
                    placeHolderSeen = true;
                }
            } else {
                evaluateWatcher(&(*it));
                wh->insertData(*it);
882
            }
Friedemann Kleint's avatar
Friedemann Kleint committed
883 884 885 886 887 888 889
            it = wd->erase(it);
        } else {
            ++it;
        }
    }
}

hjk's avatar
hjk committed
890
void CdbDebugEngine::updateWatchModel()
Banana Joe's avatar
Banana Joe committed
891
{
Friedemann Kleint's avatar
Friedemann Kleint committed
892 893 894 895 896 897 898
    // Stack trace exists and evaluation funcs can only be called
    // when running
    if (m_d->isDebuggeeRunning()) {
        qWarning("updateWatchModel() called while debuggee is running.");
        return;
    }

899
    const int frameIndex = m_d->m_debuggerManagerAccess->stackHandler()->currentIndex();
Friedemann Kleint's avatar
Friedemann Kleint committed
900 901 902 903 904

    WatchHandler *watchHandler = m_d->m_debuggerManagerAccess->watchHandler();
    WatchList incomplete = watchHandler->takeCurrentIncompletes();
    if (incomplete.empty())
        return;
905
    if (debugCDB)
Friedemann Kleint's avatar
Friedemann Kleint committed
906
        qDebug() << Q_FUNC_INFO << "\n    fi=" << frameIndex << formatWatchList(incomplete);
907 908

    bool success = false;
Friedemann Kleint's avatar
Friedemann Kleint committed
909 910 911 912 913 914
    QString errorMessage;
    do {
        // Filter out actual watchers
        filterEvaluateWatchers(&incomplete, watchHandler);
        // Do locals. We might get called while running when someone enters watchers
        if (!incomplete.empty()) {
915 916
            CdbStackFrameContext *sg = m_d->m_currentStackTrace->frameContextAt(frameIndex, &errorMessage);
            if (!sg || !sg->completeModel(incomplete, watchHandler, &errorMessage))
Friedemann Kleint's avatar
Friedemann Kleint committed
917 918 919 920 921
                break;
        }
        watchHandler->rebuildModel();
        success = true;
    } while (false);
922
    if (!success)
923
        warning(msgFunctionFailed(Q_FUNC_INFO, errorMessage));
Banana Joe's avatar
Banana Joe committed
924 925
}

hjk's avatar
hjk committed
926
void CdbDebugEngine::stepExec()
Banana Joe's avatar
Banana Joe committed
927
{
Friedemann Kleint's avatar
Friedemann Kleint committed
928 929 930
    if (debugCDB)
        qDebug() << Q_FUNC_INFO;

931
    m_d->clearForRun();
932
    const HRESULT hr = m_d->m_cif.debugControl->SetExecutionStatus(DEBUG_STATUS_STEP_INTO);
933
    if (FAILED(hr))
934
        warning(msgFunctionFailed(Q_FUNC_INFO, msgComFailed("SetExecutionStatus", hr)));
935 936

    m_d->m_breakEventMode = CdbDebugEnginePrivate::BreakEventIgnoreOnce;
Banana Joe's avatar
Banana Joe committed
937 938 939
    startWatchTimer();
}

hjk's avatar
hjk committed
940
void CdbDebugEngine::stepOutExec()
Banana Joe's avatar
Banana Joe committed
941
{
Friedemann Kleint's avatar
Friedemann Kleint committed
942 943 944 945
    if (debugCDB)
        qDebug() << Q_FUNC_INFO;

    StackHandler* sh = m_d->m_debuggerManagerAccess->stackHandler();
Banana Joe's avatar
Banana Joe committed
946 947 948
    const int idx = sh->currentIndex() + 1;
    QList<StackFrame> stackframes = sh->frames();
    if (idx < 0 || idx >= stackframes.size()) {
949
        warning(QString::fromLatin1("cannot step out"));
Banana Joe's avatar
Banana Joe committed
950 951 952
        return;
    }

953
    // Set a temporary breakpoint and continue
Banana Joe's avatar
Banana Joe committed
954
    const StackFrame& frame = stackframes.at(idx);
955 956 957 958 959 960 961 962
    bool success = false;
    QString errorMessage;
    do {
        const ULONG64 address = frame.address.toULongLong(&success, 16);
        if (!success) {
            errorMessage = QLatin1String("Cannot obtain address from stack frame");
            break;
        }
Banana Joe's avatar
Banana Joe committed
963

964
        IDebugBreakpoint2* pBP;
965
        HRESULT hr = m_d->m_cif.debugControl->AddBreakpoint2(DEBUG_BREAKPOINT_CODE, DEBUG_ANY_ID, &pBP);
966 967 968 969
        if (FAILED(hr) || !pBP) {
            errorMessage = QString::fromLatin1("Cannot create temporary breakpoint: %1").arg(msgDebugEngineComResult(hr));
            break;
        }
Banana Joe's avatar
Banana Joe committed
970

971 972 973 974 975 976 977 978
        pBP->SetOffset(address);
        pBP->AddFlags(DEBUG_BREAKPOINT_ENABLED);
        pBP->AddFlags(DEBUG_BREAKPOINT_ONE_SHOT);
        if (!m_d->continueInferior(&errorMessage))
            break;
        success = true;
    } while (false);
    if (!success)
979
        warning(msgFunctionFailed(Q_FUNC_INFO, errorMessage));
Banana Joe's avatar
Banana Joe committed
980 981
}

hjk's avatar
hjk committed
982
void CdbDebugEngine::nextExec()
Banana Joe's avatar
Banana Joe committed
983
{
Friedemann Kleint's avatar
Friedemann Kleint committed
984 985 986
    if (debugCDB)
        qDebug() << Q_FUNC_INFO;

987
    m_d->clearForRun();
988
    const HRESULT hr = m_d->m_cif.debugControl->SetExecutionStatus(DEBUG_STATUS_STEP_OVER);
989 990 991
    if (SUCCEEDED(hr)) {
        startWatchTimer();
    } else {
992
        warning(msgFunctionFailed(Q_FUNC_INFO, msgComFailed("SetExecutionStatus", hr)));
993
    }
Banana Joe's avatar
Banana Joe committed
994 995
}

hjk's avatar
hjk committed
996
void CdbDebugEngine::stepIExec()
Banana Joe's avatar
Banana Joe committed
997
{
998
    warning(QString::fromLatin1("CdbDebugEngine::stepIExec() not implemented"));
Banana Joe's avatar
Banana Joe committed
999 1000
}

hjk's avatar
hjk committed
1001
void CdbDebugEngine::nextIExec()
Banana Joe's avatar
Banana Joe committed
1002
{
Friedemann Kleint's avatar
Friedemann Kleint committed
1003 1004 1005
    if (debugCDB)
        qDebug() << Q_FUNC_INFO;

1006
    m_d->clearForRun();
1007
    const HRESULT hr = m_d->m_cif.debugControl->Execute(DEBUG_OUTCTL_THIS_CLIENT, "p", 0);
1008 1009 1010
    if (SUCCEEDED(hr)) {
        startWatchTimer();
    } else {
1011
       warning(msgFunctionFailed(Q_FUNC_INFO, msgDebugEngineComResult(hr)));
1012
    }
Banana Joe's avatar
Banana Joe committed
1013 1014
}

hjk's avatar
hjk committed
1015
void CdbDebugEngine::continueInferior()
1016 1017 1018
{
    QString errorMessage;
    if  (!m_d->continueInferior(&errorMessage))
1019
        warning(msgFunctionFailed(Q_FUNC_INFO, errorMessage));
1020 1021 1022
}

// Continue process without notifications
1023
bool CdbDebugEnginePrivate::continueInferiorProcess(QString *errorMessagePtr /* = 0 */)
Banana Joe's avatar
Banana Joe committed
1024
{
Friedemann Kleint's avatar
Friedemann Kleint committed
1025 1026
    if (debugCDB)
        qDebug() << Q_FUNC_INFO;
1027
    const HRESULT hr = m_cif.debugControl->SetExecutionStatus(DEBUG_STATUS_GO);
1028
    if (FAILED(hr)) {
1029 1030 1031 1032
        const QString errorMessage = msgComFailed("SetExecutionStatus", hr);
        if (errorMessagePtr) {
            *errorMessagePtr = errorMessage;
        } else {
1033
            m_engine->warning(msgFunctionFailed(Q_FUNC_INFO, errorMessage));
1034
        }
1035 1036 1037 1038
        return false;
    }
    return  true;
}
Friedemann Kleint's avatar
Friedemann Kleint committed
1039

1040 1041
// Continue process with notifications
bool CdbDebugEnginePrivate::continueInferior(QString *errorMessage)
1042
{
Banana Joe's avatar
Banana Joe committed
1043
    ULONG executionStatus;
1044
    if (!getExecutionStatus(m_cif.debugControl, &executionStatus, errorMessage))
1045 1046 1047 1048 1049 1050
        return false;

    if (debugCDB)
        qDebug() << Q_FUNC_INFO << "\n    ex=" << executionStatus;

    if (executionStatus == DEBUG_STATUS_GO) {
1051
        m_engine->warning(QLatin1String("continueInferior() called while debuggee is running."));
1052
        return true;
1053
    }
1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065

    clearForRun();
    m_engine->killWatchTimer();
    m_debuggerManager->resetLocation();
    m_debuggerManagerAccess->notifyInferiorRunningRequested();

    if (!continueInferiorProcess(errorMessage))
        return false;

    m_engine->startWatchTimer();
    m_debuggerManagerAccess->notifyInferiorRunning();
    return true;
Banana Joe's avatar
Banana Joe committed
1066 1067
}

1068
bool CdbDebugEnginePrivate::interruptInterferiorProcess(QString *errorMessage)
Banana Joe's avatar
Banana Joe committed
1069
{
1070 1071 1072
    // Interrupt the interferior process without notifications
    if (debugCDB) {
        ULONG executionStatus;
1073
        getExecutionStatus(m_cif.debugControl, &executionStatus, errorMessage);
1074 1075 1076 1077 1078 1079 1080
        qDebug() << Q_FUNC_INFO << "\n    ex=" << executionStatus;
    }

    if (!DebugBreakProcess(m_hDebuggeeProcess)) {
        *errorMessage = QString::fromLatin1("DebugBreakProcess failed: %1").arg(Core::Utils::winErrorMessage(GetLastError()));
        return false;
    }
1081
#if 0
1082
    const HRESULT hr = m_cif.debugControl->SetInterrupt(DEBUG_INTERRUPT_ACTIVE|DEBUG_INTERRUPT_EXIT);
1083 1084
    if (FAILED(hr)) {
        *errorMessage = QString::fromLatin1("Unable to interrupt debuggee after %1s: %2").
1085
                        arg(getInterruptTimeOutSecs(m_cif.debugControl)).arg(msgComFailed("SetInterrupt", hr));
1086 1087 1088 1089 1090
        return false;
    }
#endif
    return true;
}
Friedemann Kleint's avatar
Friedemann Kleint committed
1091

1092 1093 1094
void CdbDebugEngine::interruptInferior()
{
    if (!m_d->m_hDebuggeeProcess || !m_d->isDebuggeeRunning())
Banana Joe's avatar
Banana Joe committed
1095
        return;
1096 1097 1098

    QString errorMessage;
    if (m_d->interruptInterferiorProcess(&errorMessage)) {
1099 1100
        m_d->m_debuggerManagerAccess->notifyInferiorStopped();
    } else {
1101
        warning(msgFunctionFailed(Q_FUNC_INFO, errorMessage));
Banana Joe's avatar
Banana Joe committed
1102 1103 1104
    }
}