Skip to content
Snippets Groups Projects
debuggermanager.cpp 46.3 KiB
Newer Older
/**************************************************************************
con's avatar
con committed
**
** This file is part of Qt Creator
**
** Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
con's avatar
con committed
**
** Contact: Nokia Corporation (qt-info@nokia.com)
con's avatar
con committed
**
** Commercial Usage
** 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.
** 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.
** If you are unsure which license is appropriate for your use, please
hjk's avatar
hjk committed
** contact the sales department at http://qt.nokia.com/contact.
con's avatar
con committed
**
**************************************************************************/
con's avatar
con committed

#include "debuggermanager.h"

#include "debuggeractions.h"
#include "debuggerrunner.h"
con's avatar
con committed
#include "debuggerconstants.h"
#include "idebuggerengine.h"

#include "breakwindow.h"
#include "debuggeroutputwindow.h"
#include "moduleswindow.h"
#include "registerwindow.h"
#include "stackwindow.h"
#include "sourcefileswindow.h"
con's avatar
con committed
#include "threadswindow.h"
#include "watchwindow.h"

#include "breakhandler.h"
#include "moduleshandler.h"
#include "registerhandler.h"
#include "stackhandler.h"
#include "stackframe.h"
con's avatar
con committed
#include "watchhandler.h"

#include "debuggerdialogs.h"
Friedemann Kleint's avatar
Friedemann Kleint committed
#ifdef Q_OS_WIN
#  include "shared/peutils.h"
Friedemann Kleint's avatar
Friedemann Kleint committed
#endif
#include <coreplugin/icore.h>
#include <utils/qtcassert.h>
#include <utils/fancymainwindow.h>
#include <projectexplorer/toolchain.h>
con's avatar
con committed
#include <QtCore/QDebug>
#include <QtCore/QDir>
#include <QtCore/QFileInfo>
#include <QtCore/QTextStream>
con's avatar
con committed
#include <QtCore/QTime>
con's avatar
con committed

#include <QtGui/QApplication>
con's avatar
con committed
#include <QtGui/QAction>
#include <QtGui/QComboBox>
#include <QtGui/QDockWidget>
#include <QtGui/QErrorMessage>
#include <QtGui/QFileDialog>
#include <QtGui/QLabel>
#include <QtGui/QMessageBox>
#include <QtGui/QPlainTextEdit>
#include <QtGui/QPushButton>
con's avatar
con committed
#include <QtGui/QStatusBar>
#include <QtGui/QTextBlock>
#include <QtGui/QTextCursor>
#include <QtGui/QToolButton>
#include <QtGui/QToolTip>

namespace Debugger {
namespace Internal {
IDebuggerEngine *createGdbEngine(DebuggerManager *parent);
IDebuggerEngine *createScriptEngine(DebuggerManager *parent);
IDebuggerEngine *createTcfEngine(DebuggerManager *parent);

// The createWinEngine function takes a list of options pages it can add to.
// This allows for having a "enabled" toggle on the page independently
// of the engine. That's good for not enabling the related ActiveX control
// unnecessarily.

IDebuggerEngine *createWinEngine(DebuggerManager *, bool /* cmdLineEnabled */, QList<Core::IOptionsPage*> *)
#ifdef CDB_ENABLED
;
#else
{ return 0; }
#endif
QDebug operator<<(QDebug str, const DebuggerStartParameters &p)
{
    QDebug nospace = str.nospace();
    const QString sep = QString(QLatin1Char(','));
    nospace << "executable=" << p.executable << " coreFile=" << p.coreFile
            << " processArgs=" << p.processArgs.join(sep)
            << " environment=<" << p.environment.size() << " variables>"
            << " workingDir=" << p.workingDir << " buildDir=" << p.buildDir
            << " attachPID=" << p.attachPID << " useTerminal=" << p.useTerminal
            << " remoteChannel=" << p.remoteChannel
            << " remoteArchitecture=" << p.remoteArchitecture
            << " serverStartScript=" << p.serverStartScript
            << " toolchain=" << p.toolChainType << '\n';
using namespace Constants;
con's avatar
con committed

static const QString tooltipIName = "tooltip";

static const char *stateName(int s)
{
    switch (s) {
    case DebuggerProcessNotReady:
        return "DebuggerProcessNotReady";
    case DebuggerProcessStartingUp:
        return "DebuggerProcessStartingUp";
    case DebuggerInferiorRunningRequested:
        return "DebuggerInferiorRunningRequested";
    case DebuggerInferiorRunning:
        return "DebuggerInferiorRunning";
    case DebuggerInferiorStopRequested:
        return "DebuggerInferiorStopRequested";
    case DebuggerInferiorStopped:
        return "DebuggerInferiorStopped";
    }
    return "<unknown>";
}

con's avatar
con committed

///////////////////////////////////////////////////////////////////////
//
// DebuggerStartParameters
con's avatar
con committed
//
///////////////////////////////////////////////////////////////////////

DebuggerStartParameters::DebuggerStartParameters()
  : attachPID(-1),
hjk's avatar
hjk committed
    toolChainType(ProjectExplorer::ToolChain::UNKNOWN),
    startMode(NoStartMode)

void DebuggerStartParameters::clear()
{
    executable.clear();
    coreFile.clear();
    processArgs.clear();
    environment.clear();
    workingDir.clear();
    buildDir.clear();
    attachPID = -1;
    useTerminal = false;
    remoteChannel.clear();
    remoteArchitecture.clear();
    serverStartScript.clear();
    toolChainType = ProjectExplorer::ToolChain::UNKNOWN;
hjk's avatar
hjk committed
    startMode = NoStartMode;

///////////////////////////////////////////////////////////////////////
//
// DebuggerManager
//
///////////////////////////////////////////////////////////////////////

static IDebuggerEngine *gdbEngine = 0;
static IDebuggerEngine *scriptEngine = 0;
static IDebuggerEngine *tcfEngine = 0;
hjk's avatar
hjk committed
static IDebuggerEngine *winEngine = 0;

DebuggerManager::DebuggerManager()
  : m_startParameters(new DebuggerStartParameters),
con's avatar
con committed
{
con's avatar
con committed
}

DebuggerManager::~DebuggerManager()
{
    #define doDelete(ptr) delete ptr; ptr = 0
    doDelete(gdbEngine);
    doDelete(scriptEngine);
    doDelete(tcfEngine);
hjk's avatar
hjk committed
    doDelete(winEngine);
con's avatar
con committed
}

con's avatar
con committed
{
    m_status = -1;
    m_busy = false;

    m_modulesHandler = 0;
    m_registerHandler = 0;

    m_statusLabel = new QLabel;
    m_statusLabel->setMinimumSize(QSize(30, 10));

con's avatar
con committed
    m_breakWindow = new BreakWindow;
    m_modulesWindow = new ModulesWindow(this);
con's avatar
con committed
    m_outputWindow = new DebuggerOutputWindow;
    m_registerWindow = new RegisterWindow(this);
    m_stackWindow = new StackWindow(this);
    m_sourceFilesWindow = new SourceFilesWindow;
con's avatar
con committed
    m_threadsWindow = new ThreadsWindow;
    m_localsWindow = new WatchWindow(WatchWindow::LocalsType, this);
    m_watchersWindow = new WatchWindow(WatchWindow::WatchersType, this);
    //m_tooltipWindow = new WatchWindow(WatchWindow::TooltipType, this);
    m_statusTimer = new QTimer(this);
con's avatar
con committed

    m_mainWindow = new Core::Utils::FancyMainWindow;
con's avatar
con committed
    m_mainWindow->setTabPosition(Qt::AllDockWidgetAreas, QTabWidget::North);
    m_mainWindow->setDocumentMode(true);

    // Stack
    m_stackHandler = new StackHandler;
    QAbstractItemView *stackView =
        qobject_cast<QAbstractItemView *>(m_stackWindow);
    stackView->setModel(m_stackHandler->stackModel());
    connect(stackView, SIGNAL(frameActivated(int)),
        this, SLOT(activateFrame(int)));
    connect(theDebuggerAction(ExpandStack), SIGNAL(triggered()),
        this, SLOT(reloadFullStack()));
    connect(theDebuggerAction(MaximalStackDepth), SIGNAL(triggered()),
        this, SLOT(reloadFullStack()));
con's avatar
con committed

    // Threads
    m_threadsHandler = new ThreadsHandler;
    QAbstractItemView *threadsView =
        qobject_cast<QAbstractItemView *>(m_threadsWindow);
    threadsView->setModel(m_threadsHandler->threadsModel());
    connect(threadsView, SIGNAL(threadSelected(int)),
        this, SLOT(selectThread(int)));

    // Breakpoints
    m_breakHandler = new BreakHandler(this);
con's avatar
con committed
    QAbstractItemView *breakView =
        qobject_cast<QAbstractItemView *>(m_breakWindow);
    breakView->setModel(m_breakHandler->model());
    connect(breakView, SIGNAL(breakpointActivated(int)),
        m_breakHandler, SLOT(activateBreakpoint(int)));
    connect(breakView, SIGNAL(breakpointDeleted(int)),
con's avatar
con committed
        m_breakHandler, SLOT(removeBreakpoint(int)));
    connect(breakView, SIGNAL(breakpointSynchronizationRequested()),
        this, SLOT(attemptBreakpointSynchronization()));
    connect(breakView, SIGNAL(breakByFunctionRequested(QString)),
        this, SLOT(breakByFunction(QString)), Qt::QueuedConnection);
    connect(breakView, SIGNAL(breakByFunctionMainRequested()),
        this, SLOT(breakByFunctionMain()), Qt::QueuedConnection);
con's avatar
con committed

    // Modules
    QAbstractItemView *modulesView =
        qobject_cast<QAbstractItemView *>(m_modulesWindow);
    m_modulesHandler = new ModulesHandler;
    modulesView->setModel(m_modulesHandler->model());
    connect(modulesView, SIGNAL(reloadModulesRequested()),
        this, SLOT(reloadModules()));
    connect(modulesView, SIGNAL(loadSymbolsRequested(QString)),
        this, SLOT(loadSymbols(QString)));
    connect(modulesView, SIGNAL(loadAllSymbolsRequested()),
        this, SLOT(loadAllSymbols()));
    connect(modulesView, SIGNAL(fileOpenRequested(QString)),
        this, SLOT(fileOpen(QString)));
    connect(modulesView, SIGNAL(newDockRequested(QWidget*)),
        this, SLOT(createNewDock(QWidget*)));
con's avatar
con committed

    // Source Files
    //m_sourceFilesHandler = new SourceFilesHandler;
    QAbstractItemView *sourceFilesView =
        qobject_cast<QAbstractItemView *>(m_sourceFilesWindow);
    //sourceFileView->setModel(m_stackHandler->stackModel());
    connect(sourceFilesView, SIGNAL(reloadSourceFilesRequested()),
        this, SLOT(reloadSourceFiles()));
    connect(sourceFilesView, SIGNAL(fileOpenRequested(QString)),
        this, SLOT(fileOpen(QString)));
con's avatar
con committed

con's avatar
con committed
    QAbstractItemView *registerView =
        qobject_cast<QAbstractItemView *>(m_registerWindow);
    m_registerHandler = new RegisterHandler;
    registerView->setModel(m_registerHandler->model());

    // Locals
    m_watchHandler = new WatchHandler;
    QTreeView *localsView = qobject_cast<QTreeView *>(m_localsWindow);
    localsView->setModel(m_watchHandler->model(LocalsWatch));

    // Watchers
    QTreeView *watchersView = qobject_cast<QTreeView *>(m_watchersWindow);
    watchersView->setModel(m_watchHandler->model(WatchersWatch));
    connect(m_watchHandler, SIGNAL(sessionValueRequested(QString,QVariant*)),
        this, SIGNAL(sessionValueRequested(QString,QVariant*)));
    connect(m_watchHandler, SIGNAL(setSessionValueRequested(QString,QVariant)),
        this, SIGNAL(setSessionValueRequested(QString,QVariant)));
    connect(theDebuggerAction(AssignValue), SIGNAL(triggered()),
        this, SLOT(assignValueInDebugger()), Qt::QueuedConnection);
con's avatar
con committed

    // Tooltip
    //QTreeView *tooltipView = qobject_cast<QTreeView *>(m_tooltipWindow);
    //tooltipView->setModel(m_watchHandler->model(TooltipsWatch));
    //qRegisterMetaType<WatchData>("Debugger::Internal::WatchData");
    qRegisterMetaType<WatchData>("WatchData");
hjk's avatar
hjk committed
    connect(m_watchHandler, SIGNAL(watchDataUpdateNeeded(WatchData)),
        this, SLOT(updateWatchData(WatchData)));
con's avatar
con committed
    m_continueAction = new QAction(this);
    m_continueAction->setText(tr("Continue"));
    m_continueAction->setIcon(QIcon(":/debugger/images/debugger_continue_small.png"));
con's avatar
con committed

    m_stopAction = new QAction(this);
    m_stopAction->setText(tr("Interrupt"));
    m_stopAction->setIcon(QIcon(":/debugger/images/debugger_interrupt_small.png"));
con's avatar
con committed

    m_resetAction = new QAction(this);
    m_resetAction->setText(tr("Reset Debugger"));

    m_nextAction = new QAction(this);
    m_nextAction->setText(tr("Step Over"));
    //m_nextAction->setShortcut(QKeySequence(tr("F6")));
    m_nextAction->setIcon(QIcon(":/debugger/images/debugger_stepover_small.png"));
con's avatar
con committed

    m_stepAction = new QAction(this);
    m_stepAction->setText(tr("Step Into"));
    //m_stepAction->setShortcut(QKeySequence(tr("F7")));
    m_stepAction->setIcon(QIcon(":/debugger/images/debugger_stepinto_small.png"));
con's avatar
con committed

    m_stepOutAction = new QAction(this);
    m_stepOutAction->setText(tr("Step Out"));
    //m_stepOutAction->setShortcut(QKeySequence(tr("Shift+F7")));
    m_stepOutAction->setIcon(QIcon(":/debugger/images/debugger_stepout_small.png"));
con's avatar
con committed

    m_runToLineAction = new QAction(this);
    m_runToLineAction->setText(tr("Run to Line"));

    m_runToFunctionAction = new QAction(this);
    m_runToFunctionAction->setText(tr("Run to Outermost Function"));

    m_jumpToLineAction = new QAction(this);
    m_jumpToLineAction->setText(tr("Jump to Line"));

    m_breakAction = new QAction(this);
    m_breakAction->setText(tr("Toggle Breakpoint"));

    m_watchAction = new QAction(this);
    m_watchAction->setText(tr("Add to Watch Window"));

    m_reverseDirectionAction = new QAction(this);
    m_reverseDirectionAction->setText(tr("Reverse Direction"));
    m_reverseDirectionAction->setCheckable(true);
    m_reverseDirectionAction->setChecked(false);
    //m_reverseDirectionAction->setIcon(QIcon(":/debugger/images/debugger_stepoverproc_small.png"));

con's avatar
con committed
    connect(m_continueAction, SIGNAL(triggered()),
        this, SLOT(continueExec()));
    connect(m_stopAction, SIGNAL(triggered()),
        this, SLOT(interruptDebuggingRequest()));
    connect(m_resetAction, SIGNAL(triggered()),
        this, SLOT(exitDebugger()));
    connect(m_nextAction, SIGNAL(triggered()),
        this, SLOT(nextExec()));
    connect(m_stepAction, SIGNAL(triggered()),
        this, SLOT(stepExec()));
    connect(m_stepOutAction, SIGNAL(triggered()),
        this, SLOT(stepOutExec()));
    connect(m_runToLineAction, SIGNAL(triggered()),
        this, SLOT(runToLineExec()));
    connect(m_runToFunctionAction, SIGNAL(triggered()),
        this, SLOT(runToFunctionExec()));
    connect(m_jumpToLineAction, SIGNAL(triggered()),
        this, SLOT(jumpToLineExec()));
    connect(m_watchAction, SIGNAL(triggered()),
        this, SLOT(addToWatchWindow()));
    connect(m_breakAction, SIGNAL(triggered()),
        this, SLOT(toggleBreakpoint()));

    connect(m_statusTimer, SIGNAL(timeout()),
        this, SLOT(clearStatusMessage()));
con's avatar
con committed

    connect(theDebuggerAction(ExecuteCommand), SIGNAL(triggered()),
        this, SLOT(executeDebuggerCommand()));
    connect(theDebuggerAction(WatchPoint), SIGNAL(triggered()),
        this, SLOT(watchPoint()));
con's avatar
con committed

    connect(theDebuggerAction(StepByInstruction), SIGNAL(triggered()),
        this, SLOT(stepByInstructionTriggered()));


    m_breakDock = m_mainWindow->addDockForWidget(m_breakWindow);
con's avatar
con committed

    m_modulesDock = m_mainWindow->addDockForWidget(m_modulesWindow);
con's avatar
con committed
    connect(m_modulesDock->toggleViewAction(), SIGNAL(toggled(bool)),
        this, SLOT(reloadModules()), Qt::QueuedConnection);

    m_registerDock = m_mainWindow->addDockForWidget(m_registerWindow);
con's avatar
con committed
    connect(m_registerDock->toggleViewAction(), SIGNAL(toggled(bool)),
        this, SLOT(reloadRegisters()), Qt::QueuedConnection);

    m_outputDock = m_mainWindow->addDockForWidget(m_outputWindow);
con's avatar
con committed

    m_stackDock = m_mainWindow->addDockForWidget(m_stackWindow);
con's avatar
con committed

    m_sourceFilesDock = m_mainWindow->addDockForWidget(m_sourceFilesWindow);
    connect(m_sourceFilesDock->toggleViewAction(), SIGNAL(toggled(bool)),
        this, SLOT(reloadSourceFiles()), Qt::QueuedConnection);

    m_threadsDock = m_mainWindow->addDockForWidget(m_threadsWindow);
con's avatar
con committed

    QSplitter *localsAndWatchers = new QSplitter(Qt::Vertical, 0);
    localsAndWatchers->setWindowTitle(m_localsWindow->windowTitle());
    localsAndWatchers->addWidget(m_localsWindow);
    localsAndWatchers->addWidget(m_watchersWindow);
    //localsAndWatchers->addWidget(m_tooltipWindow);
    localsAndWatchers->setStretchFactor(0, 3);
    localsAndWatchers->setStretchFactor(1, 1);
    localsAndWatchers->setStretchFactor(2, 1);
    m_watchDock = m_mainWindow->addDockForWidget(localsAndWatchers);
con's avatar
con committed
    setStatus(DebuggerProcessNotReady);
QList<Core::IOptionsPage*> DebuggerManager::initializeEngines(unsigned enabledTypeFlags)
    if (enabledTypeFlags & GdbEngineType) {
        gdbEngine = createGdbEngine(this);
        gdbEngine->addOptionPages(&rc);
    }
    winEngine = createWinEngine(this, (enabledTypeFlags & CdbEngineType), &rc);

    if (enabledTypeFlags & ScriptEngineType) {
        scriptEngine = createScriptEngine(this);
        scriptEngine->addOptionPages(&rc);
    }

    if (enabledTypeFlags & TcfEngineType) {
        tcfEngine = createTcfEngine(this);
        tcfEngine->addOptionPages(&rc);
    }

Friedemann Kleint's avatar
Friedemann Kleint committed
    if (Debugger::Constants::Internal::debug)
        qDebug() << Q_FUNC_INFO << gdbEngine << winEngine << scriptEngine << rc.size();
    return rc;
con's avatar
con committed
}

IDebuggerEngine *DebuggerManager::engine()
{
    return m_engine;
}

IDebuggerManagerAccessForEngines *DebuggerManager::engineInterface()
{
dt's avatar
dt committed
    return this;
con's avatar
con committed
}

void DebuggerManager::createNewDock(QWidget *widget)
{
    QDockWidget *dockWidget = new QDockWidget(widget->windowTitle(), m_mainWindow);
    dockWidget->setObjectName(widget->windowTitle());
    dockWidget->setFeatures(QDockWidget::DockWidgetClosable);
    dockWidget->setWidget(widget);
    m_mainWindow->addDockWidget(Qt::TopDockWidgetArea, dockWidget);
    dockWidget->show();
}

con's avatar
con committed
void DebuggerManager::setSimpleDockWidgetArrangement()
{
    m_mainWindow->setTrackingEnabled(false);
    QList<QDockWidget *> dockWidgets = m_mainWindow->dockWidgets();
    foreach (QDockWidget *dockWidget, dockWidgets) {
        dockWidget->setFloating(false);
con's avatar
con committed
        m_mainWindow->removeDockWidget(dockWidget);
con's avatar
con committed

    foreach (QDockWidget *dockWidget, dockWidgets) {
con's avatar
con committed
        m_mainWindow->addDockWidget(Qt::BottomDockWidgetArea, dockWidget);
        dockWidget->show();
    }

    m_mainWindow->tabifyDockWidget(m_watchDock, m_breakDock);
    m_mainWindow->tabifyDockWidget(m_watchDock, m_modulesDock);
    m_mainWindow->tabifyDockWidget(m_watchDock, m_outputDock);
    m_mainWindow->tabifyDockWidget(m_watchDock, m_registerDock);
    m_mainWindow->tabifyDockWidget(m_watchDock, m_threadsDock);
    m_mainWindow->tabifyDockWidget(m_watchDock, m_sourceFilesDock);
con's avatar
con committed

    // They following views are rarely used in ordinary debugging. Hiding them
    // saves cycles since the corresponding information won't be retrieved.
    m_sourceFilesDock->hide();
con's avatar
con committed
    m_registerDock->hide();
    m_modulesDock->hide();
    m_outputDock->hide();
    m_mainWindow->setTrackingEnabled(true);
con's avatar
con committed
}

QAbstractItemModel *DebuggerManager::threadsModel()
{
    return qobject_cast<ThreadsWindow*>(m_threadsWindow)->model();
}

void DebuggerManager::clearStatusMessage()
{
    m_statusLabel->setText(m_lastPermanentStatusMessage);
}

con's avatar
con committed
void DebuggerManager::showStatusMessage(const QString &msg, int timeout)
{
    Q_UNUSED(timeout)
Friedemann Kleint's avatar
Friedemann Kleint committed
    if (Debugger::Constants::Internal::debug)
        qDebug() << "STATUS MSG: " << msg;
    showDebuggerOutput(LogStatus, msg);
hjk's avatar
hjk committed
    m_statusLabel->setText(QLatin1String("   ") + msg);
    if (timeout > 0) {
        m_statusTimer->setSingleShot(true);
        m_statusTimer->start(timeout);
    } else {
        m_lastPermanentStatusMessage = msg;
        m_statusTimer->stop();
    }
con's avatar
con committed
}

void DebuggerManager::notifyInferiorStopRequested()
{
    setStatus(DebuggerInferiorStopRequested);
    showStatusMessage(tr("Stop requested..."), 5000);
}

con's avatar
con committed
void DebuggerManager::notifyInferiorStopped()
{
    resetLocation();
    setStatus(DebuggerInferiorStopped);
    showStatusMessage(tr("Stopped."), 5000);
}

void DebuggerManager::notifyInferiorRunningRequested()
{
    setStatus(DebuggerInferiorRunningRequested);
    showStatusMessage(tr("Running requested..."), 5000);
con's avatar
con committed
}

void DebuggerManager::notifyInferiorRunning()
{
    setStatus(DebuggerInferiorRunning);
    showStatusMessage(tr("Running..."), 5000);
}

void DebuggerManager::notifyInferiorExited()
{
    setStatus(DebuggerProcessNotReady);
    showStatusMessage(tr("Exited."), 5000);
con's avatar
con committed
}

void DebuggerManager::notifyInferiorPidChanged(qint64 pid)
con's avatar
con committed
{
Friedemann Kleint's avatar
Friedemann Kleint committed
    if (Debugger::Constants::Internal::debug)
        qDebug() << Q_FUNC_INFO << m_inferiorPid << pid;

    if (m_inferiorPid != pid) {
        m_inferiorPid = pid;
        emit inferiorPidChanged(pid);
    }
con's avatar
con committed
}

void DebuggerManager::showApplicationOutput(const QString &str)
con's avatar
con committed
{
     emit applicationOutputAvailable(str);
con's avatar
con committed
}

void DebuggerManager::shutdown()
{
Friedemann Kleint's avatar
Friedemann Kleint committed
    if (Debugger::Constants::Internal::debug)
        qDebug() << Q_FUNC_INFO << m_engine;

    if (m_engine)
        m_engine->shutdown();
    m_engine = 0;

    #define doDelete(ptr) delete ptr; ptr = 0
    doDelete(scriptEngine);
    doDelete(gdbEngine);
    doDelete(winEngine);
    doDelete(tcfEngine);
con's avatar
con committed
    // Delete these manually before deleting the manager
    // (who will delete the models for most views)
    doDelete(m_breakWindow);
    doDelete(m_modulesWindow);
    doDelete(m_outputWindow);
    doDelete(m_registerWindow);
    doDelete(m_stackWindow);
    doDelete(m_sourceFilesWindow);
    doDelete(m_threadsWindow);
    //doDelete(m_tooltipWindow);
    doDelete(m_watchersWindow);
    doDelete(m_localsWindow);

    doDelete(m_breakHandler);
    doDelete(m_threadsHandler);
    doDelete(m_modulesHandler);
    doDelete(m_registerHandler);
    doDelete(m_stackHandler);
    doDelete(m_watchHandler);
    #undef doDelete
con's avatar
con committed
}

BreakpointData *DebuggerManager::findBreakpoint(const QString &fileName, int lineNumber)
{
    if (!m_breakHandler)
        return 0;
    int index = m_breakHandler->findBreakpoint(fileName, lineNumber);
    return index == -1 ? 0 : m_breakHandler->at(index);
}

con's avatar
con committed
void DebuggerManager::toggleBreakpoint()
{
    QString fileName;
    int lineNumber = -1;
    queryCurrentTextEditor(&fileName, &lineNumber, 0);
    if (lineNumber == -1)
        return;
    toggleBreakpoint(fileName, lineNumber);
}

void DebuggerManager::toggleBreakpoint(const QString &fileName, int lineNumber)
{
Friedemann Kleint's avatar
Friedemann Kleint committed
    if (Debugger::Constants::Internal::debug)
        qDebug() << Q_FUNC_INFO << fileName << lineNumber;

    QTC_ASSERT(m_breakHandler, return);
    if (status() != DebuggerInferiorRunning
         && status() != DebuggerInferiorStopped
         && status() != DebuggerProcessNotReady) {
        showStatusMessage(tr("Changing breakpoint state requires either a "
            "fully running or fully stopped application."));
        return;
    }

    int index = m_breakHandler->findBreakpoint(fileName, lineNumber);
con's avatar
con committed
    if (index == -1)
        m_breakHandler->setBreakpoint(fileName, lineNumber);
con's avatar
con committed
    else
        m_breakHandler->removeBreakpoint(index);
    attemptBreakpointSynchronization();
con's avatar
con committed
}

void DebuggerManager::toggleBreakpointEnabled(const QString &fileName, int lineNumber)
{
    if (Debugger::Constants::Internal::debug)
        qDebug() << Q_FUNC_INFO << fileName << lineNumber;

    QTC_ASSERT(m_breakHandler, return);
    if (status() != DebuggerInferiorRunning
         && status() != DebuggerInferiorStopped
         && status() != DebuggerProcessNotReady) {
        showStatusMessage(tr("Changing breakpoint state requires either a "
            "fully running or fully stopped application."));
        return;
    }

    m_breakHandler->toggleBreakpointEnabled(fileName, lineNumber);

    attemptBreakpointSynchronization();
void DebuggerManager::attemptBreakpointSynchronization()
{
    if (m_engine)
        m_engine->attemptBreakpointSynchronization();
void DebuggerManager::setToolTipExpression(const QPoint &mousePos, TextEditor::ITextEditor *editor, int cursorPos)
con's avatar
con committed
{
    if (m_engine)
        m_engine->setToolTipExpression(mousePos, editor, cursorPos);
con's avatar
con committed
}

void DebuggerManager::updateWatchData(const WatchData &data)
{
    if (m_engine)
        m_engine->updateWatchData(data);
}

hjk's avatar
hjk committed
static QString msgEngineNotAvailable(const char *engine)
hjk's avatar
hjk committed
    return DebuggerManager::tr("The application requires the debugger engine '%1', "
        "which is disabled.").arg(QLatin1String(engine));
}

static IDebuggerEngine *debuggerEngineForToolChain(ProjectExplorer::ToolChain::ToolChainType tc)
{
    IDebuggerEngine *rc = 0;
    switch (tc) {
    case ProjectExplorer::ToolChain::LinuxICC:
    case ProjectExplorer::ToolChain::MinGW:
    case ProjectExplorer::ToolChain::GCC:
        rc = gdbEngine;
        break;
    case ProjectExplorer::ToolChain::MSVC:
    case ProjectExplorer::ToolChain::WINCE:
        rc = winEngine;
        break;
    case ProjectExplorer::ToolChain::OTHER:
    case ProjectExplorer::ToolChain::UNKNOWN:
    case ProjectExplorer::ToolChain::INVALID:
        break;
    }
    if (Debugger::Constants::Internal::debug)
        qDebug()  << "Toolchain" << tc << rc;
    return rc;
}

// Figure out the debugger type of an executable. Analyze executable
// unless the toolchain provides a hint.
static IDebuggerEngine *determineDebuggerEngine(const QString &executable,
                                                int toolChainType,
                                                QString *errorMessage,
                                                QString *settingsIdHint)
Friedemann Kleint's avatar
Friedemann Kleint committed
{
    if (executable.endsWith(_(".js"))) {
        if (!scriptEngine) {
            *errorMessage = msgEngineNotAvailable("Script Engine");
            return 0;
        }
hjk's avatar
hjk committed
    if (executable.endsWith(_(".sym"))) {
        if (!gdbEngine) {
            *errorMessage = msgEngineNotAvailable("Gdb Engine");
hjk's avatar
hjk committed
            return 0;
        }
        return gdbEngine;
hjk's avatar
hjk committed

    if (IDebuggerEngine *tce = debuggerEngineForToolChain(
            static_cast<ProjectExplorer::ToolChain::ToolChainType>(toolChainType)))
#ifndef Q_OS_WIN
    if (!gdbEngine) {
        *errorMessage = msgEngineNotAvailable("Gdb Engine");
        return 0;
    }

Friedemann Kleint's avatar
Friedemann Kleint committed
#else
    // A remote executable?
    if (!executable.endsWith(_(".exe")))
        return gdbEngine;
Friedemann Kleint's avatar
Friedemann Kleint committed
    // If a file has PDB files, it has been compiled by VS.
    QStringList pdbFiles;
    if (!getPDBFiles(executable, &pdbFiles, errorMessage))
Friedemann Kleint's avatar
Friedemann Kleint committed
    // We need the CDB debugger in order to be able to debug VS
    // executables
    if (!winEngine) {
        *errorMessage = DebuggerManager::tr("Debugging VS executables is currently not enabled.");
        *settingsIdHint = QLatin1String("Cdb");
Friedemann Kleint's avatar
Friedemann Kleint committed
    }
Friedemann Kleint's avatar
Friedemann Kleint committed
#endif
}

// Figure out the debugger type of a PID
static IDebuggerEngine *determineDebuggerEngine(int  /* pid */,
                                                int toolChainType,
                                                QString *errorMessage)
hjk's avatar
hjk committed
    if (IDebuggerEngine *tce = debuggerEngineForToolChain(
            static_cast<ProjectExplorer::ToolChain::ToolChainType>(toolChainType)))
#ifdef Q_OS_WIN
    // Preferably Windows debugger
    if (winEngine)
        return winEngine;
    if (gdbEngine)
        return gdbEngine;
    *errorMessage = msgEngineNotAvailable("Gdb Engine");
    return 0;
#else
    if (!gdbEngine) {
        *errorMessage = msgEngineNotAvailable("Gdb Engine");
        return 0;
    }

hjk's avatar
hjk committed
void DebuggerManager::startNewDebugger(const DebuggerStartParametersPtr &sp)
con's avatar
con committed
{
hjk's avatar
hjk committed
    m_startParameters = sp;
Friedemann Kleint's avatar
Friedemann Kleint committed
    if (Debugger::Constants::Internal::debug)
hjk's avatar
hjk committed
        qDebug() << Q_FUNC_INFO << '\n' << *m_startParameters;
hjk's avatar
hjk committed
    m_inferiorPid = m_startParameters->attachPID > 0
        ? m_startParameters->attachPID : 0;
    const QString toolChainName = ProjectExplorer::ToolChain::toolChainName(static_cast<ProjectExplorer::ToolChain::ToolChainType>(m_startParameters->toolChainType));
con's avatar
con committed

    emit debugModeRequested();
    showDebuggerOutput(LogStatus,
        tr("Starting debugger for tool chain '%1'...").arg(toolChainName));
    showDebuggerOutput(LogDebug, DebuggerSettings::instance()->dump());
con's avatar
con committed

Friedemann Kleint's avatar
Friedemann Kleint committed
    QString errorMessage;
hjk's avatar
hjk committed
    switch (m_startParameters->startMode) {
    case AttachCrashedExternal:
hjk's avatar
hjk committed
        m_engine = determineDebuggerEngine(m_startParameters->attachPID,
            m_startParameters->toolChainType, &errorMessage);
hjk's avatar
hjk committed
        m_engine = determineDebuggerEngine(m_startParameters->executable, 
            m_startParameters->toolChainType, &errorMessage, &settingsIdHint);
        // Create Message box with possibility to go to settings
        QAbstractButton *settingsButton = 0;
        QMessageBox msgBox(QMessageBox::Warning, tr("Warning"),
            tr("Cannot debug '%1' (tool chain: '%2'): %3").
            arg(m_startParameters->executable, toolChainName, errorMessage),
            QMessageBox::Ok);
        if (!settingsIdHint.isEmpty())
            settingsButton = msgBox.addButton(tr("Settings..."), QMessageBox::AcceptRole);
        msgBox.exec();
        if (msgBox.clickedButton() == settingsButton)
hjk's avatar
hjk committed
            Core::ICore::instance()->showOptionsDialog(
                _(Debugger::Constants::DEBUGGER_SETTINGS_CATEGORY), settingsIdHint);
Friedemann Kleint's avatar
Friedemann Kleint committed
    }
Friedemann Kleint's avatar
Friedemann Kleint committed
    if (Debugger::Constants::Internal::debug)
        qDebug() << m_startParameters->executable << m_engine;
con's avatar
con committed

    setStatus(DebuggerProcessStartingUp);
hjk's avatar
hjk committed
    connect(m_engine, SIGNAL(startFailed()), this, SLOT(startFailed()));
    m_engine->startDebugger(m_startParameters);
}

void DebuggerManager::startFailed()
{
    disconnect(m_engine, SIGNAL(startFailed()), this, SLOT(startFailed()));
    setStatus(DebuggerProcessNotReady);
    debuggingFinished();
con's avatar
con committed
}

void DebuggerManager::cleanupViews()
{
    resetLocation();
    breakHandler()->setAllPending();
    stackHandler()->removeAll();
    threadsHandler()->removeAll();
    modulesHandler()->removeAll();
    watchHandler()->cleanup();
    registerHandler()->removeAll();
    m_sourceFilesWindow->removeAll();
con's avatar
con committed
}

void DebuggerManager::exitDebugger()
{
Friedemann Kleint's avatar
Friedemann Kleint committed
    if (Debugger::Constants::Internal::debug)
        qDebug() << Q_FUNC_INFO;

hjk's avatar
hjk committed
    if (m_engine)
        m_engine->exitDebugger();
con's avatar
con committed
    cleanupViews();
    setStatus(DebuggerProcessNotReady);
    setBusyCursor(false);
    emit debuggingFinished();
}

hjk's avatar
hjk committed
DebuggerStartParametersPtr DebuggerManager::startParameters() const
{
    return m_startParameters;
}

qint64 DebuggerManager::inferiorPid() const
{
    return m_inferiorPid;
}

void DebuggerManager::assignValueInDebugger()
{
    if (QAction *action = qobject_cast<QAction *>(sender())) {
        QString str = action->data().toString();
        int i = str.indexOf('=');
        if (i != -1)
            assignValueInDebugger(str.left(i), str.mid(i + 1));
con's avatar
con committed
void DebuggerManager::assignValueInDebugger(const QString &expr, const QString &value)
{
    QTC_ASSERT(m_engine, return);
    m_engine->assignValueInDebugger(expr, value);
con's avatar
con committed
}

void DebuggerManager::activateFrame(int index)
{
    QTC_ASSERT(m_engine, return);
    m_engine->activateFrame(index);
con's avatar
con committed
}

void DebuggerManager::selectThread(int index)
{
    QTC_ASSERT(m_engine, return);
    m_engine->selectThread(index);
con's avatar
con committed
}

void DebuggerManager::loadAllSymbols()
{
    QTC_ASSERT(m_engine, return);
    m_engine->loadAllSymbols();
con's avatar
con committed
}

void DebuggerManager::loadSymbols(const QString &module)
{
    QTC_ASSERT(m_engine, return);
    m_engine->loadSymbols(module);
con's avatar
con committed
}

QList<Symbol> DebuggerManager::moduleSymbols(const QString &moduleName)
{
    QTC_ASSERT(m_engine, return QList<Symbol>());
    return m_engine->moduleSymbols(moduleName);
}

con's avatar
con committed
void DebuggerManager::stepExec()
{
    QTC_ASSERT(m_engine, return);
con's avatar
con committed
    resetLocation();
    if (theDebuggerBoolSetting(StepByInstruction))
        m_engine->stepIExec();
    else
        m_engine->stepExec();
con's avatar
con committed

void DebuggerManager::stepOutExec()
{
    QTC_ASSERT(m_engine, return);
con's avatar
con committed
    resetLocation();
    m_engine->stepOutExec();
con's avatar
con committed
}

void DebuggerManager::nextExec()
{
    QTC_ASSERT(m_engine, return);
con's avatar
con committed
    resetLocation();
    if (theDebuggerBoolSetting(StepByInstruction))
        m_engine->nextIExec();
    else
        m_engine->nextExec();
con's avatar
con committed
}

void DebuggerManager::watchPoint()
{
    if (QAction *action = qobject_cast<QAction *>(sender()))
        if (m_engine)
            m_engine->watchPoint(action->data().toPoint());
}

void DebuggerManager::executeDebuggerCommand()
{